source: java/net/deterlab/abac/Identity.java @ 2e87ebb

abac0-leakabac0-mei
Last change on this file since 2e87ebb was a1a9a47, checked in by Ted Faber <faber@…>, 11 years ago

Bump version

  • Property mode set to 100644
File size: 14.7 KB
Line 
1package net.deterlab.abac;
2
3import java.io.*;
4
5import java.util.*;
6import java.security.*;
7import java.security.cert.*;
8import javax.security.auth.x500.*;
9
10import java.math.BigInteger;
11
12import org.bouncycastle.asn1.*;
13import org.bouncycastle.asn1.util.*;
14import org.bouncycastle.asn1.x509.*;
15import org.bouncycastle.x509.*;
16import org.bouncycastle.openssl.*;
17
18
19/**
20 * An ABAC identity.  An X509 Certificate-encoded public key.  The key
21 * identifier is used as the name of the Identity.  This whole class is
22 * something of a jabac extension.
23 * @author <a href="http://abac.deterlab.net">ISI ABAC team</a>
24 * @version 1.5
25 */
26public class Identity implements Comparable {
27    /** Default validity period (in seconds) */
28    static public long defaultValidity = 3600L * 24L * 365L;
29    /** The underlying X509 certificate. */
30    protected X509Certificate cert;
31    /** The public key id used as this principal's name */
32    protected String keyid;
33    /** The common name in the certificate, used as a mnemonic */
34    protected String cn;
35    /** The keypair, if any, used to sign for this Identity */
36    protected KeyPair kp;
37    /** The expiration for this Identity */
38    protected Date expiration;
39
40    /** Make sure BouncyCastle is loaded */
41    static { Context.loadBouncyCastle(); } 
42
43    /**
44     * Initialize from PEM cert in a reader.  Use a PEMReader to get
45     * the certificate, and call init(cert) on it.
46     * @param r a Reader containing the certificate
47     * @throws CertInvalidException if the stream is unparsable
48     * @throws MissingIssuerException if none of the Identities can validate the
49     *                              certificate
50     * @throws BadSignatureException if the signature check fails
51     * @throws ABACException if an uncategorized error occurs
52     */
53    protected void init(Reader r) throws ABACException {
54        PEMReader pr = new PEMReader(r);
55        Object c = null;
56
57        try {
58            while ( ( c= pr.readObject()) != null ){
59
60                if (c instanceof X509Certificate) {
61                    if ( cn == null ) 
62                        init((X509Certificate)c);
63                    else
64                        throw new CertInvalidException("Two certs in one");
65                }
66                else if (c instanceof KeyPair) setKeyPair((KeyPair)c);
67                else 
68                    throw new CertInvalidException(
69                            "Not an identity certificate");
70            }
71        }
72        catch (IOException e) {
73            throw new CertInvalidException(e.getMessage(), e);
74        }
75        // If there's nothing for the PEM reader to parse, the cert is invalid.
76        if (cn == null) 
77            throw new CertInvalidException("Not an identity certificate");
78    }
79
80    /**
81     * Initialize internals from cert.  Confirm it is self signed,  and then
82     * the keyid and common name.  There's some work to get this stuff, but
83     * it's all an incantation of getting the right classes to get the right
84     * data.  Looks more complex than it is.
85     * @param c an X509Certificate to init from
86     * @throws CertInvalidException if the stream is unparsable
87     * @throws MissingIssuerException if none of the Identities can validate the
88     *                              certificate
89     * @throws BadSignatureException if the signature check fails
90     * @throws ABACException if an uncategorized error occurs
91     */
92    protected void init(X509Certificate c) throws ABACException {
93        cert = (X509Certificate) c;
94        try {
95            cert.verify(cert.getPublicKey());
96        }
97        catch (SignatureException e) {
98            // XXX: the cert is not signed by the key we provided.  Right now
99            // we check each cert as if it were self-signed. Other signing
100            // strategies are allowed here by default.  We expect outside
101            // sources to validate ID certs if they expect different chains of
102        }
103        catch (CertificateException e) {
104            throw new CertInvalidException(e.getMessage(), e);
105        }
106        catch (InvalidKeyException e) {
107            // XXX: the cert is not signed by the key we provided.  Right now
108            // we check each cert as if it were self-signed. Other signing
109            // strategies are allowed here by default.  We expect outside
110            // sources to validate ID certs if they expect different chains of
111            // trust.
112        }
113        catch (GeneralSecurityException e) {
114            throw new ABACException(e.getMessage(), e);
115        }
116        // Cert is valid, fill in the CN and keyid
117        keyid = Context.extractKeyID(cert.getPublicKey());
118        cn = cert.getSubjectDN().getName();
119        expiration = cert.getNotAfter();
120        /// XXX: better parse
121        if (cn.startsWith("CN=")) cn = cn.substring(3);
122    }
123
124    /**
125     * Construct from a string, used as a CN.  Keys are generated.  If signer
126     * and signingKey are given, sign the certificate with them.  If neither is
127     * given, self sign it.  If one is given and not the other, throw an
128     * ABACException.
129     * @param cn a String containing the menomnic name
130     * @param validity a long containing the validity period (in seconds)
131     * @param signer an X509Certificate that is signing the Identity
132     * @param signingKey the key with which to sign
133     * @throws CertInvalidException if the stream is unparsable
134     * @throws MissingIssuerException if none of the Identities can validate the
135     *                              certificate
136     * @throws BadSignatureException if the signature check fails
137     * @throws ABACException if an uncategorized error occurs
138     */
139    public Identity(String cn, long validity, X509Certificate signer, 
140            PrivateKey signingKey) 
141            throws ABACException {
142
143        if ( (signer != null && signingKey == null) || 
144                (signer == null && signingKey != null) )
145            throw new ABACException("Both signer and signingKey must be "+ 
146                    "given or neither");
147
148        X509V1CertificateGenerator gen = new X509V1CertificateGenerator();
149        try {
150            kp = KeyPairGenerator.getInstance("RSA").genKeyPair();
151        }
152        catch (NoSuchAlgorithmException e) {
153            throw new ABACException(e.getMessage(), e);
154        }
155        X509Certificate a = null;
156        X500Principal sp = (signer != null ) ?
157            signer.getSubjectX500Principal() : new X500Principal("CN=" + cn);
158        PrivateKey sk = (signingKey != null ) ? signingKey : kp.getPrivate();
159
160        gen.setIssuerDN(sp);
161        gen.setSubjectDN(new X500Principal("CN=" + cn));
162        gen.setNotAfter(new Date(System.currentTimeMillis() +
163                1000L * validity));
164        gen.setNotBefore(new Date(System.currentTimeMillis()));
165        gen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
166        gen.setPublicKey(kp.getPublic());
167        gen.setSignatureAlgorithm("SHA256WithRSAEncryption");
168        try {
169            a = (X509Certificate) gen.generate(sk, "BC");
170        }
171        catch (CertificateEncodingException e) {
172            throw new CertInvalidException(e.getMessage(), e);
173        }
174        catch (GeneralSecurityException e) {
175            throw new ABACException(e.getMessage(), e);
176        }
177
178        init(a);
179    }
180    /**
181     * Construct from a string, used as a CN.  Keys are generated.
182     * @param cn a String containing the menomnic name
183     * @param validity a long containing the validity period (in seconds)
184     * @throws CertInvalidException if the stream is unparsable
185     * @throws MissingIssuerException if none of the Identities can validate the
186     *                              certificate
187     * @throws BadSignatureException if the signature check fails
188     * @throws ABACException if an uncategorized error occurs
189     */
190    public Identity(String cn, long validity) throws ABACException {
191        this(cn, validity, null, null);
192    }
193
194    /**
195     * Construct from a string, used as a CN.  Keys are generated.
196     * @param cn a String containing the menomnic name
197     * @throws CertInvalidException if the stream is unparsable
198     * @throws MissingIssuerException if none of the Identities can validate the
199     *                              certificate
200     * @throws BadSignatureException if the signature check fails
201     * @throws ABACException if an uncategorized error occurs
202     */
203    public Identity(String cn) throws ABACException { 
204        this(cn, defaultValidity);
205    }
206
207    /**
208     * Construct from a file containing a self-signed PEM certificate.
209     * @param file the File to read
210     * @throws CertInvalidException if the stream is unparsable
211     * @throws MissingIssuerException if none of the Identities can validate the
212     *                              certificate
213     * @throws BadSignatureException if the signature check fails
214     * @throws ABACException if an uncategorized error occurs
215     * @throws FileNotFoundException if the file is invalid
216     */
217    public Identity(File file) throws ABACException, FileNotFoundException { 
218        kp = null;
219        init(new FileReader(file));
220    }
221
222    /**
223     * Construct from a reader containing a self-signed PEM certificate.
224     * @param r the Reader containing the certificate
225     * @throws CertInvalidException if the stream is unparsable
226     * @throws MissingIssuerException if none of the Identities can validate the
227     *                              certificate
228     * @throws BadSignatureException if the signature check fails
229     * @throws ABACException if an uncategorized error occurs
230     */
231    public Identity(Reader r) throws ABACException {
232        kp = null;
233        init(r);
234    }
235
236    /**
237     * Construct from an InputStream containing a self-signed PEM certificate.
238     * @param s the InputStream containing the certificate
239     * @throws CertInvalidException if the stream is unparsable
240     * @throws MissingIssuerException if none of the Identities can validate the
241     *                              certificate
242     * @throws BadSignatureException if the signature check fails
243     * @throws ABACException if an uncategorized error occurs
244     */
245    public Identity(InputStream s) throws ABACException {
246        kp = null;
247        init(new InputStreamReader(s));
248    }
249
250    /**
251     * Construct from an X509Certificate
252     * @param cert an X509Certificate to init from
253     * @throws CertInvalidException if the stream is unparsable
254     * @throws MissingIssuerException if none of the Identities can validate the
255     *                              certificate
256     * @throws BadSignatureException if the signature check fails
257     * @throws ABACException if an uncategorized error occurs
258     */
259    public Identity(X509Certificate cert) throws ABACException {
260        kp = null;
261        init(cert);
262    }
263
264    /**
265     * Write the PEM key to the given writer.
266     * @param w the Writer
267     * @return true if the Identity had a keypair and wrote the key
268     * @throws IOException if writing fails
269     */
270    public boolean writePrivateKey(Writer w) throws IOException {
271        if (kp != null ) {
272            PEMWriter pw = new PEMWriter(w);
273
274            pw.writeObject(kp.getPrivate());
275            pw.flush();
276            return true;
277        }
278        else return false;
279    }
280
281    /**
282     * Write the PEM key to a file with the given name.
283     */
284    public boolean writePrivateKey(String fn) 
285            throws IOException, FileNotFoundException {
286        return writePrivateKey(new FileWriter(fn));
287    }
288
289    /**
290     * Write the PEM key to the given file.
291     * @param fn a String with the output file name
292     * @return true if the Identity had a keypair and wrote the key
293     * @throws IOException if writing fails
294     */
295    public boolean writePrivateKey(File fn) 
296            throws IOException, FileNotFoundException {
297        return writePrivateKey(new FileWriter(fn));
298    }
299
300    /**
301     * Write the PEM key to the given OutputStream.
302     * @param s an OutputStream to write on
303     * @return true if the Identity had a keypair and wrote the key
304     * @throws IOException if writing fails
305     */
306    public boolean writePrivateKey(OutputStream s) 
307            throws IOException, FileNotFoundException {
308        return writePrivateKey(new OutputStreamWriter(s));
309    }
310
311
312    /**
313     * Write the PEM cert to the given writer.
314     * @param w a Writer to write on
315     * @throws IOException if writing fails
316     */
317    public void write(Writer w) throws IOException {
318        PEMWriter pw = new PEMWriter(w);
319
320        pw.writeObject(cert);
321        pw.flush();
322    }
323
324    /**
325     * Write the PEM cert to a file with the given name.
326     */
327    public void write(String fn) throws IOException, FileNotFoundException {
328        write(new FileWriter(fn));
329    }
330
331    /**
332     * Write the PEM cert to the given file.
333     * @param fn a String with the output file name
334     * @throws IOException if writing fails
335     */
336    public void write(File fn) throws IOException, FileNotFoundException {
337        write(new FileWriter(fn));
338    }
339
340    /**
341     * Write the PEM cert to the given OutputStream.
342     * @param s an OutputStream to write on
343     * @throws IOException if writing fails
344     */
345    public void write(OutputStream s) 
346        throws IOException, FileNotFoundException {
347        write(new OutputStreamWriter(s));
348    }
349
350
351    /**
352     * Return the Identity's KeyID
353     * @return the Identity's KeyID
354     */
355    public String getKeyID() { return keyid; }
356    /**
357     * Return the Identity's mnemonic name
358     * @return the Identity's mnemonic name
359     */
360    public String getName() { return cn; }
361    /**
362     * Return the Identity's X509 Certificate
363     * @return the Identity's X509 Certificate
364     */
365    public X509Certificate getCertificate() { return cert; }
366
367    /**
368     * Return the expiration time of the Identity
369     * @return a Date the expiration time of the Identity
370     */
371    public Date getExpiration(){ return expiration; }
372
373    /**
374     * Return a simple string rep of the Identity.
375     * @return a simple string rep of the Identity.
376     */
377    public String toString() { 
378        String s = keyid + " (" + cn ;
379
380        if (getKeyPair() != null ) s += " [keyed]";
381        s += ")";
382        return s;
383    }
384    /**
385     * Associate a keypair with this Identity.  If the ID has a certificate,
386     * make sure that the keypair matches it.  If not throw an
387     * IllegalArgumentException.
388     * @param k the KeyPair to connect
389     * @throws IllegalArgumentException if the keypair does not
390     *                              match the pubkey in the X509 certificate
391     */
392    public void setKeyPair(KeyPair k) {
393        if (keyid != null) {
394            String kid = Context.extractKeyID(k.getPublic());
395
396            if ( kid != null && kid.equals(keyid)) kp = k;
397            else 
398                throw new IllegalArgumentException(
399                        "Keypair does not match certificate");
400        }
401        else kp = k;
402    }
403
404    /**
405     * Return the keypair associated with this Identity (if any)
406     * @return the keypair associated with this Identity (if any)
407     */
408    public KeyPair getKeyPair() { return kp; }
409
410    /**
411     * Return true if the two identites refer to teh same key.  Two Identities
412     * are equal if their key ID's match.
413     * @return true if the two key ID's are equal.
414     */
415    public boolean equals(Object o) { 
416        if ( o == null ) return false;
417        else if ( ! (o instanceof Identity) ) return false;
418        else return getKeyID().equals(((Identity)o).getKeyID());
419    }
420
421    /**
422     * Return a hash code for the Identity - the hash of its KeyID()
423     * @return an int, the hashCode
424     */
425    public int hashCode() {
426        if (keyid == null) return super.hashCode();
427        return keyid.hashCode();
428    }
429
430
431    /**
432     * Order 2 identities for sorting.  They are ordered by their key ID's.
433     * @param o an Object to compare
434     * @return -1 if this Identity is before, 0 if they are the same, and 1
435     *              if this Identity is after the given object.
436     */
437    public int compareTo(Object o) { 
438        if ( ! (o instanceof Identity) ) return 1;
439        else return getKeyID().compareTo(((Identity)o).getKeyID());
440    }
441
442};
Note: See TracBrowser for help on using the repository browser.