source: java/net/deterlab/abac/Context.java @ f31432f

abac0-leakabac0-meicompt_changesgec13mei-idmei-rt0-nmei_rt0tvf-new-xml
Last change on this file since f31432f was d5317fd, checked in by Ted Faber <faber@…>, 14 years ago

Doc error

  • Property mode set to 100644
File size: 33.1 KB
RevLine 
[418b586]1package net.deterlab.abac;
2
3import edu.uci.ics.jung.graph.*;
4import edu.uci.ics.jung.graph.util.*;
5
6import java.io.*;
7import java.util.*;
[ad24705]8import java.util.regex.*;
[418b586]9import java.util.zip.*;
10import java.security.*;
11import java.security.cert.*;
12
[0595372]13import org.bouncycastle.asn1.*;
14import org.bouncycastle.asn1.x509.*;
[418b586]15import org.bouncycastle.x509.*;
16import org.bouncycastle.openssl.*;
[238717d]17import org.bouncycastle.jce.provider.BouncyCastleProvider;
[418b586]18
19/**
20 * Represents a global graph of credentials in the form of principals and
[e36ea1d]21 * attributes.  Contains the identities and credentials that can be used in a
22 * proof.
23 * @author <a href="http://abac.deterlab.net">ISI ABAC team</a>
24 * @version 1.3
[418b586]25 */
26public class Context {
[e36ea1d]27    /** Certificate imported successfully */
28    public static final int ABAC_CERT_SUCCESS = 0;
29    /** Certificate import failed, invalid certificate */
30    public static final int ABAC_CERT_INVALID = -1;
31    /** Certificate import failed, signature filed */
32    public static final int ABAC_CERT_BAD_SIG = -2;
33    /** Certificate import failed, unknown issuer */
34    public static final int ABAC_CERT_MISSING_ISSUER = -3;
35
36    /** Internal graph representation */
[418b586]37    protected Graph<Role,Credential> g;
[e36ea1d]38    /** Set of edges in the graph that were added by the logic.  */
[418b586]39    protected Set<Credential> derived_edges;
[e36ea1d]40    /** Internal persistent query object */
[418b586]41    protected Query pq;
[e36ea1d]42    /** True when the graph has been changed since the last set of implied
43     * edges were calculated. */
[418b586]44    protected boolean dirty;
[e36ea1d]45    /** Set of identities known to this Context. */
[388a3d7]46    protected Set<Identity> m_identities;
[418b586]47
[e36ea1d]48    /** Translation from issuer CN to issuer pubkey identifier */
[418b586]49    protected Map<String, String> nicknames;
[e36ea1d]50    /** Translation from issuer pubkey identifier to issuer CN */
[418b586]51    protected Map<String, String> keys;
52
[238717d]53    /** True once BouncyCastle has been loaded. */
54    static boolean providerLoaded = false;
55
56    /**
57     * Load the BouncyCastle provider, necessary for ABAC crypto (shouldn't
58     * need to be called directly).  This is called from the Context static
59     * constructor and static constructors in other ABAC classes that use
60     * BouncyCastle crypto (which loads a Context, which calls it as well) to
61     * make sure crypto is available. 
62     */
63    static void loadBouncyCastle() {
64        if ( !providerLoaded ) {
65            AccessController.doPrivileged(new PrivilegedAction<Object>() {
66                public Object run() {
67                    Security.addProvider(new BouncyCastleProvider());
68                    return null;
69                }
70            });
71            providerLoaded = true;
72        }
73    }
74
75    /** Load the BouncyCastle provider. */
76    static { loadBouncyCastle(); };
77
[e36ea1d]78    /**
79     * The result of a query on this context.  The credentials form a partial
80     * or total proof, and success indicates whether the proof succeeded.
81     * @author <a href="http://abac.deterlab.net">ISI ABAC team</a>
82     * @version 1.3
83     */
[1a80501]84    public class QueryResult {
[e36ea1d]85        /** Credentials returned */
[1a80501]86        protected Collection<Credential> creds;
[e36ea1d]87        /** True if the proof succeeded. */
[1a80501]88        protected boolean success;
89
[e36ea1d]90        /**
91         * Construct a result from components.
92         * @param c the collection of credentials in the proof
93         * @param s a boolean, true if the query succeeded.
94         */
95        QueryResult(Collection<Credential> c, boolean s) {
[1a80501]96            creds = c;
97            success = s;
98        }
99
[e36ea1d]100        /**
101         * Empty constructor
102         */
[1a80501]103        public QueryResult() { 
104            creds = new TreeSet<Credential>();
105            success = false;
106        }
107
[e36ea1d]108        /**
109         * Return the credentials in the proof.
110         * @return the collection of credentials
111         */
[1a80501]112        public Collection<Credential> getCredentials() { return creds; }
[e36ea1d]113        /**
114         * Return the success in the proof.
115         * @return the boolean, true on success
116         */
[1a80501]117        public boolean getSuccess() { return success; }
118    }
119
120
[e36ea1d]121    /**
122     * Create an empty Context.
123     */
[418b586]124    public Context() {
125        /* create the graph */
126        g = Graphs.<Role,Credential>synchronizedDirectedGraph(
127                new DirectedSparseGraph<Role,Credential>());
128        derived_edges = new HashSet<Credential>();
129        pq = new Query(g);
130        dirty = false;
[388a3d7]131        m_identities = new TreeSet<Identity>();
[418b586]132        nicknames = new TreeMap<String, String>();
133        keys = new TreeMap<String, String>();
134    }
135
[e36ea1d]136    /**
137     * Create a context from another context.
138     * @param c the Context to copy
139     */
[418b586]140    public Context(Context c) {
141        this();
[388a3d7]142        for (Identity i: c.m_identities) 
[6432e35]143            load_id_chunk(i);
[418b586]144        for (Credential cr: c.credentials()) 
[6432e35]145            load_attribute_chunk(cr);
[418b586]146        derive_implied_edges();
147    }
148
[83cdf0f]149    /**
150     * Create a Context from a collection of Credentials.  A jabac extension.
151     * @param creds the collection of credentials
152     */
153    public Context(Collection<Credential> creds) {
154        this();
155        for (Credential c: creds) {
156            Identity i = c.issuer();
157
158            if (i != null ) load_id_chunk(i);
159            load_attribute_chunk(c);
160        }
161    }
162
[e36ea1d]163    /**
164     * Load an Identity from a file.
165     * @param fn a String containing the file name.
166     * @return one of the static int return codes.
167     */
[6432e35]168    public int load_id_file(String fn) { return load_id_chunk(new File(fn)); }
[e36ea1d]169    /**
170     * Load an Identity from a file.
171     * @param fn a File containing the file name.
172     * @return one of the static int return codes.
173     */
[6432e35]174    public int load_id_file(File fn) { return load_id_chunk(fn); }
[e36ea1d]175    /**
176     * Load an Identity from an object.  Supported objects are an Identity, a
177     * String, a File, or a java.security.cert.X509Certificate.  A string
178     * creates an new identity, and the others are derived from the contents of
179     * the data or file.
180     * @param c an object convertable to an identity as above.
181     * @return one of the static int return codes.
182     */
[6432e35]183    public int load_id_chunk(Object c) {
[418b586]184        try {
185            if (c instanceof Identity)
186                addIdentity((Identity) c);
187            else if (c instanceof String) 
188                addIdentity(new Identity((String) c));
189            else if (c instanceof File) 
190                addIdentity(new Identity((File) c));
191            else if (c instanceof X509Certificate) 
192                addIdentity(new Identity((X509Certificate) c));
193            else 
194                return ABAC_CERT_INVALID;
195        }
196        catch (SignatureException sig) {
197            return ABAC_CERT_BAD_SIG;
198        }
199        catch (Exception e) {
200            return ABAC_CERT_INVALID;
201        }
202        return ABAC_CERT_SUCCESS;
203    }
204
[e36ea1d]205    /**
206     * Load an attribute certificate from a file.
207     * @param fn a String containing the file name.
208     * @return one of the static int return codes.
209     */
[6432e35]210    public int load_attribute_file(String fn) { 
211        return load_attribute_chunk(new File(fn));
[418b586]212    }
213
[e36ea1d]214    /**
215     * Load an attribute certificate from a file.
216     * @param fn a File containing the file name.
217     * @return one of the static int return codes.
218     */
[6432e35]219    public int load_attribute_file(File fn) { return load_attribute_chunk(fn); }
[418b586]220
[e36ea1d]221    /**
222     * Load an Identity from an object.  Supported objects are a Credential, a
223     * String, a File, or an org.bouncycastle.x509.X509V2AttributeCertificate.
224     * A string creates an new Credential, and the others are derived from the
225     * contents of the data or file.
226     * @param c an object convertable to a Credential as above.
227     * @return one of the static int return codes.
228     */
[6432e35]229    public int load_attribute_chunk(Object c) {
[418b586]230        try {
231            if (c instanceof Credential)
232                add_credential((Credential) c);
233            else if (c instanceof String) 
[388a3d7]234                add_credential(new Credential((String) c, m_identities));
[418b586]235            else if (c instanceof File) 
[388a3d7]236                add_credential(new Credential((File) c, m_identities));
[418b586]237            else if ( c instanceof X509V2AttributeCertificate) 
238                add_credential(new Credential((X509V2AttributeCertificate)c,
[388a3d7]239                            m_identities));
[418b586]240            else 
241                return ABAC_CERT_INVALID;
242        }
[388a3d7]243        catch (InvalidKeyException sig) {
244            return ABAC_CERT_MISSING_ISSUER ;
245        }
[418b586]246        catch (SignatureException sig) {
247            return ABAC_CERT_BAD_SIG;
248        }
249        catch (Exception e) {
250            return ABAC_CERT_INVALID;
251        }
252        return ABAC_CERT_SUCCESS;
253    }
254
[e36ea1d]255    /**
256     * Determine if prinicpal possesses role in the current context.  If so,
257     * return a proof of that, otherwise return a partial proof of it.
258     * @param role a String encoding the role to check for.
259     * @param principal a String with the principal ID in it.
260     * @return a Context.QueryResult containing the result.
261     */
[1a80501]262    public QueryResult query(String role, String principal) {
[418b586]263        derive_implied_edges();
264
265        Query q = new Query(g);
266        Graph<Role, Credential> rg = q.run(role, principal);
[1a80501]267
268        return new QueryResult(rg.getEdges(), q.successful());
[418b586]269    }
270
271    /**
[e36ea1d]272     * Return a collection of the credentials in the graph.s
273     * @return a collection of the credentials in the graph.
[418b586]274     */
275    public Collection<Credential> credentials() {
276        Collection<Credential> creds = new HashSet<Credential>();
277
[ad24705]278        // only non-derived edges
[418b586]279        for (Credential cred : g.getEdges())
[ad24705]280            if (!derived_edges.contains(cred))
[418b586]281                creds.add(cred);
282
283        return creds;
284    }
285
[388a3d7]286    /**
287     * Return all the Identities known in this context.  A jabac extension.
288     * @return all the Identities known in this context.
289     */
290    public Collection<Identity> identities() {
291        return m_identities;
292    }
293
[e36ea1d]294    /**
295     * Returns true if the given Identity is known in this Context.  A jabac
296     * extension.
297     * @param i the Identity to look for
298     * @return a boolean, true if the Identity is known.
299     */
[238717d]300    public boolean knowsIdentity(Identity i) { return m_identities.contains(i);}
[e36ea1d]301    /**
302     * Returns true if an Identity with the given string representation is
303     * known in this Context.  A jabac extension.
304     * @param k the string representing the Identity to look for
305     * @return a boolean, true if the Identity is known.
306     */
[53f5c27]307    public boolean knowsKeyID(String k) {
308        boolean known = false;
[388a3d7]309        for (Identity i: m_identities)
[53f5c27]310            if (k.equals(i.getKeyID())) return true;
311        return false;
[418b586]312    }
313
[53f5c27]314
[418b586]315    /**
316     * Add a credential to the graph.
[e36ea1d]317     * @param cred the Credential to add
[418b586]318     */
[56ec930]319    protected void add_credential(Credential cred) {
[418b586]320        Role tail = cred.tail();
321        Role head = cred.head();
322
[f25a7ff]323        // explicitly add the vertices, to avoid a null pointer exception
[418b586]324        if ( !g.containsVertex(head)) 
325            g.addVertex(head);
326        if ( !g.containsVertex(tail)) 
327            g.addVertex(tail);
328
329        if (!g.containsEdge(cred))
330            g.addEdge(cred, tail, head);
331
332        // add the prereqs of an intersection to the graph
333        if (tail.is_intersection())
334            for (Role prereq : tail.prereqs())
335                g.addVertex(prereq);
336
337        dirty = true;
338    }
339
340    /**
341     * Remove a credential from the graph.
[e36ea1d]342     * @param cred the Credential to remove
[418b586]343     */
[56ec930]344    protected void remove_credential(Credential cred) {
[418b586]345        if (g.containsEdge(cred))
346            g.removeEdge(cred);
347        dirty = true;
348    }
349
350    /**
351     * Add a role w/o an edge
[e36ea1d]352     * @param v the Role to add
[418b586]353     */
[56ec930]354    protected void add_vertex(Role v) {
[418b586]355        if (!g.containsVertex(v)) {
356            g.addVertex(v);
357            dirty = true;
358        }
359    }
360
[e36ea1d]361    /**
362     * Remove a role and connected edges.
363     * @param v the Role to remove
364     */
[56ec930]365    protected void remove_vertex(Role v) {
[418b586]366        if (g.containsVertex(v)) {
367            g.removeVertex(v);
368            dirty = true;
369        }
370    }
371
372    /**
373     * Derive the implied edges in the graph, according to RT0 derivation rules.
374     * They are added to this graph. See "Distributed Credential Chain Discovery
375     * in Trust Management" by Ninghui Li et al. for details. Note that a
376     * derived linking edge can imply a new intersection edge and vice versa.
377     * Therefore we iteratively derive edges, giving up when an iteration
378     * produces 0 new edges.
379     */
380    protected synchronized void derive_implied_edges() {
381        // nothing to do on a clean graph
382        if (!dirty)
383            return;
384
385        clear_old_edges();
386
387        // iteratively derive links. continue as long as new links are added
388        while (derive_links_iter() > 0)
389            ;
390        dirty = false;
391    }
392
393    /**
394     * Single iteration of deriving implied edges. Returns the number of new
395     * links added.
[e36ea1d]396     * @return the number of new links added.
[418b586]397     */
398    protected int derive_links_iter() {
399        int count = 0;
400
401        /* for every node in the graph.. */
402        for (Role vertex : g.getVertices()) {
403            if (vertex.is_intersection()) {
404                // for each prereq edge:
405                //     find set of principals that have the prereq
[f25a7ff]406                // find the intersection of all sets (i.e., principals
407                //     that satisfy all prereqs)
[418b586]408                // for each principal in intersection:
409                //     add derived edge
410
411                Set<Role> principals = null;
412
413                for (Role prereq : vertex.prereqs()) {
414                    Set<Role> cur_principals = pq.find_principals(prereq);
415
416                    if (principals == null)
417                        principals = cur_principals;
418                    else
419                        // no, they couldn't just call it "intersection"
420                        principals.retainAll(cur_principals);
421
422                    if (principals.size() == 0)
423                        break;
424                }
425
426                // add em
427                for (Role principal : principals)
428                    if (add_derived_edge(vertex, principal))
429                        ++count;
430            }
431
432            else if (vertex.is_linking()) {
433                // make the rest of the code a bit clearer
434                Role A_r1_r2 = vertex;
435
436                Role A_r1 = new Role(A_r1_r2.A_r1());
437                String r2 = A_r1_r2.r2();
438
439                /* locate the node A.r1 */
[f25a7ff]440                if (!g.containsVertex(A_r1)) continue; 
[418b586]441
442                /* for each B that satisfies A_r1 */
443                for (Role principal : pq.find_principals(A_r1)) {
444                    Role B_r2 = new Role(principal + "." + r2);
445                    if (!g.containsVertex(B_r2)) continue;
446
447                    if (add_derived_edge(A_r1_r2, B_r2))
448                        ++count;
449                }
450            }
451        }
452
453        return count;
454    }
455
456    /**
457     * Add a derived edge in the graph. Returns true only if the edge does not
458     * exist.
[e36ea1d]459     * @return a boolean, true if an edge has been added
[418b586]460     */
461    protected boolean add_derived_edge(Role head, Role tail) {
462        // edge exists: return false
463        if (g.findEdge(tail, head) != null)
464            return false;
465
466        // add the new edge
467        Credential derived_edge = new Credential(head, tail);
468        derived_edges.add(derived_edge);
469        g.addEdge(derived_edge, tail, head);
470
471        return true;
472    }
473
474    /**
475     * Clear the derived edges that currently exist in the graph. This is done
476     * before the edges are rederived. The derived edges in filtered graphs are
477     * also cleared.
478     */
479    protected void clear_old_edges() { 
480        for (Credential i: derived_edges) 
481            g.removeEdge(i);
482        derived_edges = new HashSet<Credential>();
483    }
484    /**
485     * Put the Identity into the set of ids used to validate certificates.
486     * Also put the keyID and name into the translation mappings used by Roles
487     * to pretty print.  In the role mapping, if multiple ids use the same
488     * common name they are disambiguated.  Only one entry for keyid is
489     * allowed.
[6432e35]490     * @param id the Identity to add
[418b586]491     */
492    protected void addIdentity(Identity id) { 
[388a3d7]493        m_identities.add(id);
[418b586]494        if (id.getName() != null && id.getKeyID() != null) {
495            if ( !keys.containsKey(id.getKeyID()) ) {
496                String name = id.getName();
497                int n= 1;
498
499                while (nicknames.containsKey(name)) {
500                    name = id.getName() + n++;
501                }
502                nicknames.put(name, id.getKeyID());
503                keys.put(id.getKeyID(), name);
504            }
505        }
506    }
507    /**
508     * Translate either keys to nicknames or vice versa.  Break the string into
509     * space separated tokens and then each of them into period separated
510     * strings.  If any of the smallest strings is in the map, replace it with
511     * the value.
[e36ea1d]512     * @param is the string to manipulate
513     * @param m the Map containing translations
514     * @return the string after modification
[418b586]515     */
516    protected String replace(String is, Map<String, String> m) {
517        String rv = "";
518        for (String tok: is.split(" ")) {
519            String term = "";
520            for (String s: tok.split("\\.")) {
521                String next = m.containsKey(s) ? m.get(s) : s;
522
523                if (term.isEmpty()) term = next;
524                else term += "." + next;
525            }
526            if (rv.isEmpty()) rv = term;
527            else rv += " " + term;
528        }
529        return rv;
530    }
531
[e36ea1d]532    /**
533     * Expand menmonic names in a Role string, e.g. the CN of the issuer
534     * certificate, into the full key ID.  Used internally by Roles to provide
535     * transparent use of mnemonics
536     * @param s the string to expand
537     * @return the String after expansion.
538     */
539    String expandKeyID(String s) { return replace(s, nicknames); }
540    /**
541     * Convert key IDs to  menmonic names in a Role string.  The inverse of
542     * expandKeyID.
543     * @param s the string to expand
544     * @return the String after expansion.
545     */
546    String expandNickname(String s) { return replace(s, keys); }
[418b586]547
[39526ce]548    /**
549     * Read the current ZipEntry's bytes from z.  Tedious because there's no
550     * way to reliably tell how big the entry is, so we have to rely on a
551     * simple expanding array read of the bytes.
552     */
553    protected byte[] readCurrentZipEntry(ZipInputStream z) throws IOException {
554        final int bsize = 4096;
555        byte[] buf = new byte[bsize];
556        byte[] rv = new byte[0];
557        int r = 0;
558
559        // z.read returns -1 at the end of entry
560        while ((r = z.read(buf, 0, bsize)) != -1 ) {
561            byte[] b = new byte[rv.length + r];
562
563            System.arraycopy(rv, 0, b, 0, rv.length);
564            System.arraycopy(buf, 0, b, rv.length, r);
565            rv = b;
566        }
567        return rv;
568    }
569
[418b586]570    /**
571     * Import a zip file.  First import all the identities
572     * (pem), then the credentials (der) into the credential graph then any
573     * alias files into the two maps.  If keys is not null, any key pairs in
574     * PEM files are put in there.  If errors is not null, errors reading files
[6432e35]575     * are added indexed by filename.  This is a jabac extension.
[39526ce]576     * @param s the InputStream to read
[e36ea1d]577     * @param keys a Collection into which to insert unmatched keys
578     * @param errors a Map from entry name to generated exception
579     * @throws IOException if the file is unreadable.  Per entry exceptions are
580     *                     returned in the errors parameter.
[418b586]581     */
[39526ce]582    public void load_zip(InputStream s, Collection<KeyPair> keys, 
[418b586]583            Map<String, Exception> errors) throws IOException {
[39526ce]584        Map<String, byte[]> derEntries = new HashMap<String, byte[]>();
[418b586]585        Map<String, Identity> ids = new TreeMap<String, Identity>();
586        Map<String, KeyPair> kps = new TreeMap<String, KeyPair>();
[39526ce]587        int entries = 0;
[418b586]588
[39526ce]589        ZipInputStream z = new ZipInputStream(s);
[418b586]590
[39526ce]591        for (ZipEntry ze = z.getNextEntry(); ze != null; ze = z.getNextEntry()){
[418b586]592            try {
[39526ce]593                entries++;
594                byte[] buf = readCurrentZipEntry(z);
[418b586]595                PEMReader r = new PEMReader(
[39526ce]596                        new InputStreamReader(new ByteArrayInputStream(buf)));
[418b586]597                Object o = readPEM(r);
598
599                if ( o != null ) {
600                    if (o instanceof Identity) {
601                        Identity i = (Identity) o;
602                        String kid = i.getKeyID();
603
604                        if (kps.containsKey(kid) ) {
605                            i.setKeyPair(kps.get(kid));
606                            kps.remove(kid);
607                        }
608                        else if (i.getKeyPair() == null ) 
609                            ids.put(i.getKeyID(), i);
610
[6432e35]611                        load_id_chunk(i);
[418b586]612                    }
613                    else if (o instanceof KeyPair ) {
614                        KeyPair kp = (KeyPair) o;
[0595372]615                        String kid = extractKeyID(kp.getPublic());
[418b586]616
617                        if (ids.containsKey(kid)) {
618                            Identity i = ids.get(kid);
619
620                            i.setKeyPair(kp);
621                            ids.remove(kid);
622                        }
623                        else {
624                            kps.put(kid, kp);
625                        }
626                    }
627                }
628                else {
629                    // Not a PEM file
[39526ce]630                    derEntries.put(ze.getName(),buf);
[418b586]631                    continue;
632                }
633            }
634            catch (Exception e ) {
[39526ce]635                if (errors != null ) errors.put(ze.getName(), e);
[418b586]636            }
637        }
638
[39526ce]639        for ( String k: derEntries.keySet() ) {
[418b586]640            try {
[39526ce]641                add_credential(new Credential(
642                            new ByteArrayInputStream(derEntries.get(k)),
[388a3d7]643                            m_identities));
[418b586]644            }
645            catch (Exception e ) {
[39526ce]646                if (errors != null ) errors.put(k, e);
[418b586]647            }
648        }
[39526ce]649
650        if (entries == 0) 
651            throw new IOException("Not a ZIP file (or empty ZIP file)");
652    }
653    /**
654     * Equivalent to load_zip(s, null, null).
655     * @param s the InputStream to read
656     * @throws IOException if the file is unreadable. To see per-entry
657     *                      exceptions use a signature with the errors parameter
658     */
659    public void load_zip(InputStream s) 
660            throws IOException {
661        load_zip(s, null, null);
662    }
663    /**
664     * Equivalent to load_zip(s, null, errors).
665     * @param s the InputStream to read
666     * @param errors a Map from entry name to generated exception
667     * @throws IOException if the file is unreadable.  Per entry exceptions are
668     *                     returned in the errors parameter.
669     */
670    public void load_zip(InputStream s, 
671            Map<String, Exception> errors) throws IOException {
672        load_zip(s, null, errors);
[418b586]673    }
[e36ea1d]674    /**
[39526ce]675     * Equivalent to load_zip(s, keys, null).
676     * @param s the InputStream to read
677     * @param keys a Collection into which to insert unmatched keys
678     * @throws IOException if the file is unreadable. To see per-entry
679     *                      exceptions use a signature with the errors parameter
680     */
681    public void load_zip(InputStream s, 
682            Collection<KeyPair> keys) throws IOException {
683        load_zip(s, keys, null);
684    }
685
686    /**
687     * Loads a zip file.  Equivalent to
688     * load_zip(new FileInputStream(zf), keys, errors).
689     * @param zf the File to read
690     * @param keys a Collection into which to insert unmatched keys
691     * @param errors a Map from entry name to generated exception
692     * @throws IOException if the file is unreadable.  Per entry exceptions are
693     *                     returned in the errors parameter.
694     */
695    public void load_zip(File zf, Collection<KeyPair> keys, 
696            Map<String, Exception> errors) throws IOException {
697        load_zip(new FileInputStream(zf), keys, errors);
698    }
699    /**
700     * Equivalent to load_zip(d, null, null).
[e36ea1d]701     * @param d the File to read
702     * @throws IOException if the file is unreadable. To see per-entry
703     *                      exceptions use a signature with the errors parameter
704     */
[39526ce]705    public void load_zip(File d) 
[418b586]706            throws IOException {
[39526ce]707        load_zip(d, null, null);
[418b586]708    }
[e36ea1d]709    /**
[39526ce]710     * Equivalent to load_zip(d, null, errors).
[e36ea1d]711     * @param d the File to read
712     * @param errors a Map from entry name to generated exception
713     * @throws IOException if the file is unreadable.  Per entry exceptions are
714     *                     returned in the errors parameter.
715     */
[39526ce]716    public void load_zip(File d, 
[418b586]717            Map<String, Exception> errors) throws IOException {
[39526ce]718        load_zip(d, null, errors);
[418b586]719    }
[e36ea1d]720    /**
[39526ce]721     * Equivalent to load_zip(d, keys, null).
[e36ea1d]722     * @param d the File to read
723     * @param keys a Collection into which to insert unmatched keys
724     * @throws IOException if the file is unreadable. To see per-entry
725     *                      exceptions use a signature with the errors parameter
726     */
[39526ce]727    public void load_zip(File d, 
[418b586]728            Collection<KeyPair> keys) throws IOException {
[39526ce]729        load_zip(d, keys, null);
[418b586]730    }
731
[e36ea1d]732    /**
733     * Read a PEM file that contains an X509 Certificate, a key pair, or both.
734     * If a cert is present it is converted into an Identity.  A key pair is
735     * returned as a java.security.KeyPair and both are returned as an Identity
736     * with an associated key pair.
737     * @param r a PEMReader from which to read
738     * @return an object encoding the contents (as above)
739     * @throws IOException for an unreadable or badly formated input
740     */
[418b586]741    protected Object readPEM(PEMReader r) throws IOException {
742        Identity i = null;
743        KeyPair keys = null;
744        Object o = null;
745
746        while ( (o = r.readObject()) != null ) {
747            if (o instanceof X509Certificate) {
748                if ( i == null ) {
749                    try {
750                        i = new Identity((X509Certificate)o);
751                    }
752                    catch (Exception e) {
753                        // Translate Idenitiy exceptions to IOException
754                        throw new IOException(e);
755                    }
756                    if (keys != null ) {
757                        i.setKeyPair(keys);
758                        keys = null;
759                    }
760                }
761                else throw new IOException("Two certificates");
762            }
763            else if (o instanceof KeyPair ) {
764                if ( i != null ) i.setKeyPair((KeyPair) o);
765                else keys = (KeyPair) o;
766            }
767            else {
768                throw new IOException("Unexpected PEM object: " + 
769                        o.getClass().getName());
770            }
771        }
772
773        if ( i != null ) return i;
774        else if ( keys != null) return keys;
775        else return null;
776    }
777
778    /**
779     * Import a directory full of files.  First import all the identities
780     * (pem), then the credentials (der) into the credential graph then any
781     * alias files into the two maps.  If keys is not null, any key pairs in
782     * PEM files are put in there.  If errors is not null, errors reading files
[6432e35]783     * are added indexed by filename.  This behaves slightly differently from
784     * the load_directory description in the general libabac documentation.
[e36ea1d]785     * @param d the File to read.  If it is a directory its contents are read
786     * @param keys a Collection into which to insert unmatched keys
787     * @param errors a Map from entry name to generated exception
788     * @throws IOException if the file is unreadable.  Per file exceptions are
789     *                     returned in the errors parameter.
[418b586]790     */
[6432e35]791    public void load_directory(File d, Collection<KeyPair> keys, 
[418b586]792            Map<String, Exception> errors) {
793        Vector<File> derFiles = new Vector<File>();
794        Collection<File> files = new Vector<File>();
795        Map<String, Identity> ids = new TreeMap<String, Identity>();
796        Map<String, KeyPair> kps = new TreeMap<String, KeyPair>();
797
798        if (d.isDirectory() ) 
799            for (File f : d.listFiles()) 
800                files.add(f);
801        else files.add(d);
802
803        for (File f: files ) {
804            try {
805                PEMReader r = new PEMReader(new FileReader(f));
806                Object o = readPEM(r);
807
808                if ( o != null ) {
809                    if (o instanceof Identity) {
810                        Identity i = (Identity) o;
811                        String kid = i.getKeyID();
812
813                        if (kps.containsKey(kid) ) {
814                            i.setKeyPair(kps.get(kid));
815                            kps.remove(kid);
816                        }
817                        else if (i.getKeyPair() == null ) 
818                            ids.put(i.getKeyID(), i);
819
[6432e35]820                        load_id_chunk(i);
[418b586]821                    }
822                    else if (o instanceof KeyPair ) {
823                        KeyPair kp = (KeyPair) o;
[0595372]824                        String kid = extractKeyID(kp.getPublic());
[418b586]825
826                        if (ids.containsKey(kid)) {
827                            Identity i = ids.get(kid);
828
829                            i.setKeyPair(kp);
830                            ids.remove(kid);
831                        }
832                        else {
833                            kps.put(kid, kp);
834                        }
835                    }
836                }
837                else {
838                    // Not a PEM file
839                    derFiles.add(f);
840                    continue;
841                }
842            }
843            catch (Exception e ) {
844                if (errors != null ) errors.put(f.getName(), e);
845            }
846        }
847
848        for ( File f : derFiles ) {
849            try {
[388a3d7]850                add_credential(new Credential(f, m_identities));
[418b586]851            }
852            catch (Exception e ) {
853                if (errors != null ) errors.put(f.getName(), e);
854            }
855        }
856    }
[e36ea1d]857    /**
[6432e35]858     * Equivalent to load_directory(d, null, null).
[e36ea1d]859     * @param d the File to read.  If it is a directory its contents are read
860     * @throws IOException if the file is unreadable.  To see per-file
861     *                     exceptions use a signature with the errors parameter.
862     */
[6432e35]863    public void load_directory(File d) {
864        load_directory(d, null, null);
[418b586]865    }
[e36ea1d]866    /**
[6432e35]867     * Equivalent to load_directory(d, null, null).
[e36ea1d]868     * @param d the File to read.  If it is a directory its contents are read
869     * @param errors a Map from entry name to generated exception
870     * @throws IOException if the file is unreadable.  Per file exceptions are
871     *                     returned in the errors parameter.
872     */
[6432e35]873    public void load_directory(File d, Map<String, Exception> errors) {
874        load_directory(d, null, errors);
[418b586]875    }
[e36ea1d]876    /**
[6432e35]877     * Equivalent to load_directory(d, null, null).
[e36ea1d]878     * @param d the File to read.  If it is a directory its contents are read
879     * @param keys a Collection into which to insert unmatched keys
880     * @throws IOException if the file is unreadable.  To see per-file
881     *                     exceptions use a signature with the errors parameter.
882     */
[6432e35]883    public void load_directory(File d, Collection<KeyPair> keys) {
884        load_directory(d, keys, null);
[418b586]885    }
886
[ad24705]887    /**
888     * Load from a simple rt0 text format.  A jabac extension.  The format is
889     * <br/>
890     * # comments<br/>
891     * role &lt;- role<br/>
892     * <br/>
893     *
894     * Spaces are not significant around the arrow and the tail can be as long
895     * as needed.
[39526ce]896     * @param s the InputStream to load
897     * @throws IOException if there is an error getting the file open or in
898     * format
[ad24705]899     */
[39526ce]900    public void load_rt0(InputStream s) 
[ad24705]901            throws IOException {
902        Pattern comment = Pattern.compile("(^\\s*#|^\\s*$)");
[39526ce]903        Pattern rule = Pattern.compile("([\\w\\.]+)\\s*<-+\\s*(.+)");
904        LineNumberReader r = new LineNumberReader(new InputStreamReader(s));
[ad24705]905        String line = null;
906
907        while ((line = r.readLine()) != null) {
908            Matcher cm = comment.matcher(line);
909            Matcher rm = rule.matcher(line);
910
911            if (cm.find()) continue;
912            if (rm.find()) 
913                add_credential(new Credential(new Role(rm.group(1)), 
914                            new Role(rm.group(2))));
[39526ce]915            else 
916                throw new RuntimeException("Unexpected format: line " + 
917                        r.getLineNumber());
[ad24705]918        }
919    }
920    /**
[39526ce]921     * Equivalent to load_rt0(new FileInputStream(f)
[ad24705]922     * @param f the File to load
923     * @throws IOException if there is an error getting the file open
924     */
[39526ce]925    public void load_rt0(File f) throws IOException {
926        load_rt0(new FileInputStream(f));
[ad24705]927    }
928       
929
[e36ea1d]930    /**
931     * Write the certificates that make up the context as a zip file, with an
[3d13073]932     * entry for each credential or identity.  The files are all zipped in a
933     * directory derived from the filename.
[39526ce]934     * @param s the OutputStream to write
[e36ea1d]935     * @param allIDs a boolean, if true write certificates for all Identities,
936     * whether used in signing a credential or not.
937     * @param withPrivateKeys a boolean, if true write the Identities as PEM
938     * file containing both the certificate and the private keys.
[3d13073]939     * @throws IOException if there is a problem writing the file.
[e36ea1d]940     */
[39526ce]941    public void write_zip(OutputStream s, boolean allIDs, 
942            boolean withPrivateKeys) throws IOException {
943        ZipOutputStream z = new ZipOutputStream(s);
[388a3d7]944        Set<Identity> ids = allIDs ?  m_identities : new TreeSet<Identity>();
[39526ce]945        String baseDir = "creds";
[b6e7c18]946        int idx = baseDir.indexOf('.');
947
948
949        if (idx != -1) 
950            baseDir = baseDir.substring(0, idx);
[418b586]951
952        int n = 0;
953        for (Credential c: credentials()) {
[b6e7c18]954            z.putNextEntry(new ZipEntry(baseDir + File.separator + 
955                        "attr" + n++  + ".der"));
[418b586]956            c.write(z);
957            z.closeEntry();
[d69593c]958            if ( c.issuer() != null && !allIDs) ids.add(c.issuer());
[418b586]959        }
960        for (Identity i: ids) {
[b6e7c18]961            z.putNextEntry(new ZipEntry(baseDir + File.separator + 
962                        i.getName() + ".pem"));
[418b586]963            i.write(z);
964            if (withPrivateKeys)
965                i.writePrivateKey(z);
966            z.closeEntry();
967        }
968        z.close();
969    }
[39526ce]970    /**
971     * Equivalent to
972     * write_zip(new FileOutputStream(f), allIDs, withPrivateKeys).
973     * @param f the File to write
974     * @param allIDs a boolean, if true write certificates for all Identities,
975     * whether used in signing a credential or not.
976     * @param withPrivateKeys a boolean, if true write the Identities as PEM
977     * file containing both the certificate and the private keys.
978     * @throws IOException if there is a problem writing the file.
979     */
980    public void write_zip(File f, boolean allIDs, boolean withPrivateKeys) 
981            throws IOException {
982        write_zip(new FileOutputStream(f), allIDs, withPrivateKeys);
983    }
[418b586]984
[ad24705]985    /**
986     * Write to a simple rt0 text format.  A jabac extension.
987     * The format is
988     * <br/>
989     * role &lt;- role<br/>
990     * <br/>
991     *
992     * @param w a Writer to print on
993     * @param useKeyIDs a boolean, true to print key IDs not mnemonics
994     */
995    public void write_rt0(Writer w, boolean useKeyIDs) {
996        PrintWriter pw = w instanceof PrintWriter ? 
997            (PrintWriter) w : new PrintWriter(w);
998
999        for (Credential c: credentials()) 
1000            pw.println(useKeyIDs ? c.toString() : c.simpleString(this));
1001        pw.flush();
1002    }
1003
1004    /**
1005     * Call write_rt0 on a FileWriter derived from f.
1006     * @param f the File to write to
1007     * @param useKeyIDs a boolean, true to print key IDs not mnemonics
1008     * @throws IOException if there is a problem writing the file.
1009     */
1010    public void write_rt0(File f, boolean useKeyIDs) throws IOException {
1011        write_rt0(new FileWriter(f), useKeyIDs);
1012    }
1013
1014    /**
1015     * Equivalent to write_rt0(w, false);
1016     * @param w a Writer to print on
1017     */
1018    public void write_rt0(Writer w) { write_rt0(w, false); }
1019
1020    /**
1021     * Equivalent to write_rt0(f, false);
1022     * @param f the File to write to
1023     * @throws IOException if there is a problem writing the file.
1024     */
1025    public void write_rt0(File f) throws IOException {
1026        write_rt0(new FileWriter(f), false);
1027    }
1028
[0595372]1029    /**
[e36ea1d]1030     * Get to the SHA1 hash of the key.  Used by Roles and Identities to get a
1031     * key ID.
1032     * @param k the PublicKey to get the ID from.
1033     * @return a String with the key identifier
[0595372]1034     */
[e36ea1d]1035    static String extractKeyID(PublicKey k) {
[0595372]1036        SubjectPublicKeyInfo ki = extractSubjectPublicKeyInfo(k);
1037        SubjectKeyIdentifier id = 
1038            SubjectKeyIdentifier.createSHA1KeyIdentifier(ki);
1039
1040        // Now format it into a string for keeps
1041        Formatter fmt = new Formatter(new StringWriter());
1042        for (byte b: id.getKeyIdentifier())
1043            fmt.format("%02x", b);
1044        return fmt.out().toString();
1045    }
1046
1047    /**
1048     * Extratct the SubjectPublicKeyInfo.  Useful for some other encryptions,
1049     * notably Certificate.make_cert().
[e36ea1d]1050     * @param k the PublicKey to get the ID from.
1051     * @return a String with the key identifier
[0595372]1052     */
[e36ea1d]1053    static SubjectPublicKeyInfo extractSubjectPublicKeyInfo(
[0595372]1054            PublicKey k) {
1055        ASN1Sequence seq = null;
1056        try {
1057            seq = (ASN1Sequence) new ASN1InputStream(
1058                    k.getEncoded()).readObject();
1059        }
1060        catch (IOException ie) {
1061            // Badly formatted key??
1062            return null;
1063        }
1064        return new SubjectPublicKeyInfo(seq);
1065    }
1066
1067
[418b586]1068}
Note: See TracBrowser for help on using the repository browser.