source: java/net/deterlab/abac/Context.java @ 7f614c1

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

Add expirations to all credentials

  • Property mode set to 100644
File size: 34.8 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        if (m_identities.contains(id)) {
518            //XXX keep more recent
519            return;
520        }
521        m_identities.add(id);
522        if (id.getName() != null && id.getKeyID() != null) {
523            if ( !keys.containsKey(id.getKeyID()) ) {
524                String name = id.getName();
525                int n= 1;
526
527                while (nicknames.containsKey(name)) {
528                    name = id.getName() + n++;
529                }
530                nicknames.put(name, id.getKeyID());
531                keys.put(id.getKeyID(), name);
532            }
533        }
534    }
535    /**
536     * Translate either keys to nicknames or vice versa.  Break the string into
537     * space separated tokens and then each of them into period separated
538     * strings.  If any of the smallest strings is in the map, replace it with
539     * the value.
540     * @param is the string to manipulate
541     * @param m the Map containing translations
542     * @return the string after modification
543     */
544    protected String replace(String is, Map<String, String> m) {
545        String rv = "";
546        for (String tok: is.split(" ")) {
547            String term = "";
548            for (String s: tok.split("\\.")) {
549                String next = m.containsKey(s) ? m.get(s) : s;
550
551                if (term.isEmpty()) term = next;
552                else term += "." + next;
553            }
554            if (rv.isEmpty()) rv = term;
555            else rv += " " + term;
556        }
557        return rv;
558    }
559
560    /**
561     * Expand menmonic names in a Role string, e.g. the CN of the issuer
562     * certificate, into the full key ID.  Used internally by Roles to provide
563     * transparent use of mnemonics
564     * @param s the string to expand
565     * @return the String after expansion.
566     */
567    String expandKeyID(String s) { return replace(s, nicknames); }
568    /**
569     * Convert key IDs to  menmonic names in a Role string.  The inverse of
570     * expandKeyID.
571     * @param s the string to expand
572     * @return the String after expansion.
573     */
574    String expandNickname(String s) { return replace(s, keys); }
575
576    /**
577     * Read the current ZipEntry's bytes from z.  Tedious because there's no
578     * way to reliably tell how big the entry is, so we have to rely on a
579     * simple expanding array read of the bytes.
580     */
581    protected byte[] readCurrentZipEntry(ZipInputStream z) throws IOException {
582        final int bsize = 4096;
583        byte[] buf = new byte[bsize];
584        byte[] rv = new byte[0];
585        int r = 0;
586
587        // z.read returns -1 at the end of entry
588        while ((r = z.read(buf, 0, bsize)) != -1 ) {
589            byte[] b = new byte[rv.length + r];
590
591            System.arraycopy(rv, 0, b, 0, rv.length);
592            System.arraycopy(buf, 0, b, rv.length, r);
593            rv = b;
594        }
595        return rv;
596    }
597
598    /**
599     * Import a zip file.  First import all the identities
600     * (pem), then the credentials (der) into the credential graph then any
601     * alias files into the two maps.  If keys is not null, any key pairs in
602     * PEM files are put in there.  If errors is not null, errors reading files
603     * are added indexed by filename.  This is a jabac extension.
604     * @param s the InputStream to read
605     * @param keys a Collection into which to insert unmatched keys
606     * @param errors a Map from entry name to generated exception
607     * @throws IOException if the file is unreadable.  Per entry exceptions are
608     *                     returned in the errors parameter.
609     */
610    public void load_zip(InputStream s, Collection<KeyPair> keys, 
611            Map<String, Exception> errors) throws IOException {
612        Map<String, byte[]> derEntries = new HashMap<String, byte[]>();
613        Map<String, Identity> ids = new TreeMap<String, Identity>();
614        Map<String, KeyPair> kps = new TreeMap<String, KeyPair>();
615        int entries = 0;
616
617        ZipInputStream z = new ZipInputStream(s);
618
619        for (ZipEntry ze = z.getNextEntry(); ze != null; ze = z.getNextEntry()){
620            try {
621                entries++;
622                byte[] buf = readCurrentZipEntry(z);
623                PEMReader r = new PEMReader(
624                        new InputStreamReader(new ByteArrayInputStream(buf)));
625                Object o = readPEM(r);
626
627                if ( o != null ) {
628                    if (o instanceof Identity) {
629                        Identity i = (Identity) o;
630                        String kid = i.getKeyID();
631
632                        if (kps.containsKey(kid) ) {
633                            i.setKeyPair(kps.get(kid));
634                            kps.remove(kid);
635                        }
636                        else if (i.getKeyPair() == null ) 
637                            ids.put(i.getKeyID(), i);
638
639                        load_id_chunk(i);
640                    }
641                    else if (o instanceof KeyPair ) {
642                        KeyPair kp = (KeyPair) o;
643                        String kid = extractKeyID(kp.getPublic());
644
645                        if (ids.containsKey(kid)) {
646                            Identity i = ids.get(kid);
647
648                            i.setKeyPair(kp);
649                            ids.remove(kid);
650                        }
651                        else {
652                            kps.put(kid, kp);
653                        }
654                    }
655                }
656                else {
657                    // Not a PEM file
658                    derEntries.put(ze.getName(),buf);
659                    continue;
660                }
661            }
662            catch (Exception e ) {
663                if (errors != null ) errors.put(ze.getName(), e);
664            }
665        }
666
667        for ( String k: derEntries.keySet() ) {
668            try {
669                Credential[] creds = credentialFactory.parseCredential(
670                            new ByteArrayInputStream(derEntries.get(k)),
671                            m_identities);
672                for (Credential c: creds) 
673                    add_credential(c);
674            }
675            catch (Exception e ) {
676                if (errors != null ) errors.put(k, e);
677            }
678        }
679
680        if (entries == 0) 
681            throw new IOException("Not a ZIP file (or empty ZIP file)");
682    }
683    /**
684     * Equivalent to load_zip(s, null, null).
685     * @param s the InputStream to read
686     * @throws IOException if the file is unreadable. To see per-entry
687     *                      exceptions use a signature with the errors parameter
688     */
689    public void load_zip(InputStream s) 
690            throws IOException {
691        load_zip(s, null, null);
692    }
693    /**
694     * Equivalent to load_zip(s, null, errors).
695     * @param s the InputStream to read
696     * @param errors a Map from entry name to generated exception
697     * @throws IOException if the file is unreadable.  Per entry exceptions are
698     *                     returned in the errors parameter.
699     */
700    public void load_zip(InputStream s, 
701            Map<String, Exception> errors) throws IOException {
702        load_zip(s, null, errors);
703    }
704    /**
705     * Equivalent to load_zip(s, keys, null).
706     * @param s the InputStream to read
707     * @param keys a Collection into which to insert unmatched keys
708     * @throws IOException if the file is unreadable. To see per-entry
709     *                      exceptions use a signature with the errors parameter
710     */
711    public void load_zip(InputStream s, 
712            Collection<KeyPair> keys) throws IOException {
713        load_zip(s, keys, null);
714    }
715
716    /**
717     * Loads a zip file.  Equivalent to
718     * load_zip(new FileInputStream(zf), keys, errors).
719     * @param zf the File to read
720     * @param keys a Collection into which to insert unmatched keys
721     * @param errors a Map from entry name to generated exception
722     * @throws IOException if the file is unreadable.  Per entry exceptions are
723     *                     returned in the errors parameter.
724     */
725    public void load_zip(File zf, Collection<KeyPair> keys, 
726            Map<String, Exception> errors) throws IOException {
727        load_zip(new FileInputStream(zf), keys, errors);
728    }
729    /**
730     * Equivalent to load_zip(d, null, null).
731     * @param d the File to read
732     * @throws IOException if the file is unreadable. To see per-entry
733     *                      exceptions use a signature with the errors parameter
734     */
735    public void load_zip(File d) 
736            throws IOException {
737        load_zip(d, null, null);
738    }
739    /**
740     * Equivalent to load_zip(d, null, errors).
741     * @param d the File to read
742     * @param errors a Map from entry name to generated exception
743     * @throws IOException if the file is unreadable.  Per entry exceptions are
744     *                     returned in the errors parameter.
745     */
746    public void load_zip(File d, 
747            Map<String, Exception> errors) throws IOException {
748        load_zip(d, null, errors);
749    }
750    /**
751     * Equivalent to load_zip(d, keys, null).
752     * @param d the File to read
753     * @param keys a Collection into which to insert unmatched keys
754     * @throws IOException if the file is unreadable. To see per-entry
755     *                      exceptions use a signature with the errors parameter
756     */
757    public void load_zip(File d, 
758            Collection<KeyPair> keys) throws IOException {
759        load_zip(d, keys, null);
760    }
761
762    /**
763     * Read a PEM file that contains an X509 Certificate, a key pair, or both.
764     * If a cert is present it is converted into an Identity.  A key pair is
765     * returned as a java.security.KeyPair and both are returned as an Identity
766     * with an associated key pair.
767     * @param r a PEMReader from which to read
768     * @return an object encoding the contents (as above)
769     * @throws IOException for an unreadable or badly formated input
770     */
771    protected Object readPEM(PEMReader r) throws IOException {
772        Identity i = null;
773        KeyPair keys = null;
774        Object o = null;
775
776        while ( (o = r.readObject()) != null ) {
777            if (o instanceof X509Certificate) {
778                if ( i == null ) {
779                    try {
780                        i = new Identity((X509Certificate)o);
781                    }
782                    catch (Exception e) {
783                        // Translate Idenitiy exceptions to IOException
784                        throw new IOException(e);
785                    }
786                    if (keys != null ) {
787                        i.setKeyPair(keys);
788                        keys = null;
789                    }
790                }
791                else throw new IOException("Two certificates");
792            }
793            else if (o instanceof KeyPair ) {
794                if ( i != null ) i.setKeyPair((KeyPair) o);
795                else keys = (KeyPair) o;
796            }
797            else {
798                throw new IOException("Unexpected PEM object: " + 
799                        o.getClass().getName());
800            }
801        }
802
803        if ( i != null ) return i;
804        else if ( keys != null) return keys;
805        else return null;
806    }
807
808    /**
809     * Import a directory full of files.  First import all the identities
810     * (pem), then the credentials (der) into the credential graph then any
811     * alias files into the two maps.  If keys is not null, any key pairs in
812     * PEM files are put in there.  If errors is not null, errors reading files
813     * are added indexed by filename.  This behaves slightly differently from
814     * the load_directory description in the general libabac documentation.
815     * @param d the File to read.  If it is a directory its contents are read
816     * @param keys a Collection into which to insert unmatched keys
817     * @param errors a Map from entry name to generated exception
818     * @throws IOException if the file is unreadable.  Per file exceptions are
819     *                     returned in the errors parameter.
820     */
821    public void load_directory(File d, Collection<KeyPair> keys, 
822            Map<String, Exception> errors) {
823        Vector<File> derFiles = new Vector<File>();
824        Collection<File> files = new Vector<File>();
825        Map<String, Identity> ids = new TreeMap<String, Identity>();
826        Map<String, KeyPair> kps = new TreeMap<String, KeyPair>();
827
828        if (d.isDirectory() ) 
829            for (File f : d.listFiles()) 
830                files.add(f);
831        else files.add(d);
832
833        for (File f: files ) {
834            try {
835                PEMReader r = new PEMReader(new FileReader(f));
836                Object o = readPEM(r);
837
838                if ( o != null ) {
839                    if (o instanceof Identity) {
840                        Identity i = (Identity) o;
841                        String kid = i.getKeyID();
842
843                        if (kps.containsKey(kid) ) {
844                            i.setKeyPair(kps.get(kid));
845                            kps.remove(kid);
846                        }
847                        else if (i.getKeyPair() == null ) 
848                            ids.put(i.getKeyID(), i);
849
850                        load_id_chunk(i);
851                    }
852                    else if (o instanceof KeyPair ) {
853                        KeyPair kp = (KeyPair) o;
854                        String kid = extractKeyID(kp.getPublic());
855
856                        if (ids.containsKey(kid)) {
857                            Identity i = ids.get(kid);
858
859                            i.setKeyPair(kp);
860                            ids.remove(kid);
861                        }
862                        else {
863                            kps.put(kid, kp);
864                        }
865                    }
866                }
867                else {
868                    // Not a PEM file
869                    derFiles.add(f);
870                    continue;
871                }
872            }
873            catch (Exception e ) {
874                if (errors != null ) errors.put(f.getName(), e);
875            }
876        }
877
878        for ( File f : derFiles ) {
879            try {
880                Credential[] creds = credentialFactory.parseCredential(f, 
881                        m_identities);
882                for (Credential c: creds) 
883                    add_credential(c);
884            }
885            catch (Exception e ) {
886                if (errors != null ) errors.put(f.getName(), e);
887            }
888        }
889    }
890    /**
891     * Equivalent to load_directory(d, null, null).
892     * @param d the File to read.  If it is a directory its contents are read
893     * @throws IOException if the file is unreadable.  To see per-file
894     *                     exceptions use a signature with the errors parameter.
895     */
896    public void load_directory(File d) {
897        load_directory(d, null, null);
898    }
899    /**
900     * Equivalent to load_directory(d, null, null).
901     * @param d the File to read.  If it is a directory its contents are read
902     * @param errors a Map from entry name to generated exception
903     * @throws IOException if the file is unreadable.  Per file exceptions are
904     *                     returned in the errors parameter.
905     */
906    public void load_directory(File d, Map<String, Exception> errors) {
907        load_directory(d, null, errors);
908    }
909    /**
910     * Equivalent to load_directory(d, null, null).
911     * @param d the File to read.  If it is a directory its contents are read
912     * @param keys a Collection into which to insert unmatched keys
913     * @throws IOException if the file is unreadable.  To see per-file
914     *                     exceptions use a signature with the errors parameter.
915     */
916    public void load_directory(File d, Collection<KeyPair> keys) {
917        load_directory(d, keys, null);
918    }
919
920    /**
921     * Load from a simple rt0 text format.  A jabac extension.  The format is
922     * <br/>
923     * # comments<br/>
924     * role &lt;- role<br/>
925     * <br/>
926     *
927     * Spaces are not significant around the arrow and the tail can be as long
928     * as needed.
929     * @param s the InputStream to load
930     * @throws IOException if there is an error getting the file open or in
931     * format
932     */
933    public void load_rt0(InputStream s) 
934            throws IOException {
935        Pattern comment = Pattern.compile("(^\\s*#|^\\s*$)");
936        Pattern rule = Pattern.compile("([\\w\\.]+)\\s*<-+\\s*(.+)");
937        LineNumberReader r = new LineNumberReader(new InputStreamReader(s));
938        String line = null;
939
940        while ((line = r.readLine()) != null) {
941            Matcher cm = comment.matcher(line);
942            Matcher rm = rule.matcher(line);
943
944            if (cm.find()) continue;
945            if (rm.find()) 
946                add_credential(new InternalCredential(new Role(rm.group(1)), 
947                            new Role(rm.group(2))));
948            else 
949                throw new RuntimeException("Unexpected format: line " + 
950                        r.getLineNumber());
951        }
952    }
953    /**
954     * Equivalent to load_rt0(new FileInputStream(f)
955     * @param f the File to load
956     * @throws IOException if there is an error getting the file open
957     */
958    public void load_rt0(File f) throws IOException {
959        load_rt0(new FileInputStream(f));
960    }
961       
962
963    /**
964     * Write the certificates that make up the context as a zip file, with an
965     * entry for each credential or identity.  The files are all zipped in a
966     * directory derived from the filename.
967     * @param s the OutputStream to write
968     * @param allIDs a boolean, if true write certificates for all Identities,
969     * whether used in signing a credential or not.
970     * @param withPrivateKeys a boolean, if true write the Identities as PEM
971     * file containing both the certificate and the private keys.
972     * @throws IOException if there is a problem writing the file.
973     */
974    public void write_zip(OutputStream s, boolean allIDs, 
975            boolean withPrivateKeys) throws IOException {
976        ZipOutputStream z = new ZipOutputStream(s);
977        Set<Identity> ids = allIDs ?  m_identities : new TreeSet<Identity>();
978        String baseDir = "creds";
979        int idx = baseDir.indexOf('.');
980
981
982        if (idx != -1) 
983            baseDir = baseDir.substring(0, idx);
984
985        int n = 0;
986        for (Credential c: credentials()) {
987            z.putNextEntry(new ZipEntry(baseDir + File.separator + 
988                        "attr" + n++  + ".der"));
989            c.write(z);
990            z.closeEntry();
991            if ( c.issuer() != null && !allIDs) ids.add(c.issuer());
992        }
993        for (Identity i: ids) {
994            z.putNextEntry(new ZipEntry(baseDir + File.separator + 
995                        i.getName() + ".pem"));
996            i.write(z);
997            if (withPrivateKeys)
998                i.writePrivateKey(z);
999            z.closeEntry();
1000        }
1001        z.close();
1002    }
1003    /**
1004     * Equivalent to
1005     * write_zip(new FileOutputStream(f), allIDs, withPrivateKeys).
1006     * @param f the File to write
1007     * @param allIDs a boolean, if true write certificates for all Identities,
1008     * whether used in signing a credential or not.
1009     * @param withPrivateKeys a boolean, if true write the Identities as PEM
1010     * file containing both the certificate and the private keys.
1011     * @throws IOException if there is a problem writing the file.
1012     */
1013    public void write_zip(File f, boolean allIDs, boolean withPrivateKeys) 
1014            throws IOException {
1015        write_zip(new FileOutputStream(f), allIDs, withPrivateKeys);
1016    }
1017
1018    /**
1019     * Write to a simple rt0 text format.  A jabac extension.
1020     * The format is
1021     * <br/>
1022     * role &lt;- role<br/>
1023     * <br/>
1024     *
1025     * @param w a Writer to print on
1026     * @param useKeyIDs a boolean, true to print key IDs not mnemonics
1027     */
1028    public void write_rt0(Writer w, boolean useKeyIDs) {
1029        PrintWriter pw = w instanceof PrintWriter ? 
1030            (PrintWriter) w : new PrintWriter(w);
1031
1032        for (Credential c: credentials()) 
1033            pw.println(useKeyIDs ? c.toString() : c.simpleString(this));
1034        pw.flush();
1035    }
1036
1037    /**
1038     * Call write_rt0 on a FileWriter derived from f.
1039     * @param f the File to write to
1040     * @param useKeyIDs a boolean, true to print key IDs not mnemonics
1041     * @throws IOException if there is a problem writing the file.
1042     */
1043    public void write_rt0(File f, boolean useKeyIDs) throws IOException {
1044        write_rt0(new FileWriter(f), useKeyIDs);
1045    }
1046
1047    /**
1048     * Equivalent to write_rt0(w, false);
1049     * @param w a Writer to print on
1050     */
1051    public void write_rt0(Writer w) { write_rt0(w, false); }
1052
1053    /**
1054     * Equivalent to write_rt0(f, false);
1055     * @param f the File to write to
1056     * @throws IOException if there is a problem writing the file.
1057     */
1058    public void write_rt0(File f) throws IOException {
1059        write_rt0(new FileWriter(f), false);
1060    }
1061
1062    /**
1063     * Return this Context's CredentialFactory.
1064     * @return this Context's CredentialFactory.
1065     */
1066    public CredentialFactory getCredentialFactory() {
1067        return credentialFactory;
1068    }
1069
1070    /**
1071     * Set this Context's CredentialFactory.
1072     * @param cf the new CredentialFactoty
1073     */
1074    public void setCredentialFactory(CredentialFactory cf) { 
1075        credentialFactory = cf;
1076    }
1077
1078    /**
1079     * Return a new credential supported by this Context.  It is not inserted
1080     * in the Context.
1081     * @param head a Role, the head of the encoded ABAC statement
1082     * @param tail a Role, the tail of the decoded ABAC statement
1083     * @return a Credential encoding that ABAC statement
1084     */
1085    public Credential newCredential(Role head, Role tail) {
1086        return credentialFactory.generateCredential(head, tail);
1087    }
1088
1089    /**
1090     * Get to the SHA1 hash of the key.  Used by Roles and Identities to get a
1091     * key ID.
1092     * @param k the PublicKey to get the ID from.
1093     * @return a String with the key identifier
1094     */
1095    static String extractKeyID(PublicKey k) {
1096        SubjectPublicKeyInfo ki = extractSubjectPublicKeyInfo(k);
1097        SubjectKeyIdentifier id = 
1098            SubjectKeyIdentifier.createSHA1KeyIdentifier(ki);
1099
1100        // Now format it into a string for keeps
1101        Formatter fmt = new Formatter(new StringWriter());
1102        for (byte b: id.getKeyIdentifier())
1103            fmt.format("%02x", b);
1104        return fmt.out().toString();
1105    }
1106
1107    /**
1108     * Extratct the SubjectPublicKeyInfo.  Useful for some other encryptions,
1109     * notably Certificate.make_cert().
1110     * @param k the PublicKey to get the ID from.
1111     * @return a String with the key identifier
1112     */
1113    static SubjectPublicKeyInfo extractSubjectPublicKeyInfo(
1114            PublicKey k) {
1115        ASN1Sequence seq = null;
1116        try {
1117            seq = (ASN1Sequence) new ASN1InputStream(
1118                    k.getEncoded()).readObject();
1119        }
1120        catch (IOException ie) {
1121            // Badly formatted key??
1122            return null;
1123        }
1124        return new SubjectPublicKeyInfo(seq);
1125    }
1126
1127}
Note: See TracBrowser for help on using the repository browser.