source: java/net/deterlab/abac/Context.java @ 6b31de6

abac0-leakabac0-meimei-idmei-rt0-nmei_rt0tvf-new-xml
Last change on this file since 6b31de6 was aaadefd, checked in by Ted Faber <faber@…>, 11 years ago

Add newCredential to the Context

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