source: java/net/deterlab/abac/Context.java @ 0100d7b

abac0-leakabac0-meimei-idmei-rt0-nmei_rt0tvf-new-xml
Last change on this file since 0100d7b was 8fdbdac, checked in by Ted Faber <faber@…>, 12 years ago

Missed a couple cases (ant didn't rebuild)

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