source: java/net/deterlab/abac/Identity.java @ ebf0ae2

tvf-new-xml
Last change on this file since ebf0ae2 was fbdd2d1, checked in by Ted Faber <faber@…>, 12 years ago

Remove the not-self-signed exception

  • Property mode set to 100644
File size: 13.4 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.4
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.
126     * @param cn a String containing the menomnic name
127     * @param validity a long containing the validity period (in seconds)
128     * @throws CertInvalidException if the stream is unparsable
129     * @throws MissingIssuerException if none of the Identities can validate the
130     *                              certificate
131     * @throws BadSignatureException if the signature check fails
132     * @throws ABACException if an uncategorized error occurs
133     */
134    public Identity(String cn, long validity) throws ABACException {
135        X509V1CertificateGenerator gen = new X509V1CertificateGenerator();
136        try {
137            kp = KeyPairGenerator.getInstance("RSA").genKeyPair();
138        }
139        catch (NoSuchAlgorithmException e) {
140            throw new ABACException(e.getMessage(), e);
141        }
142        X509Certificate a = null;
143
144        gen.setIssuerDN(new X500Principal("CN=" + cn));
145        gen.setSubjectDN(new X500Principal("CN=" + cn));
146        gen.setNotAfter(new Date(System.currentTimeMillis() +
147                1000L * validity));
148        gen.setNotBefore(new Date(System.currentTimeMillis()));
149        gen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
150        gen.setPublicKey(kp.getPublic());
151        gen.setSignatureAlgorithm("SHA256WithRSAEncryption");
152        try {
153            a = (X509Certificate) gen.generate(kp.getPrivate(), "BC");
154        }
155        catch (CertificateEncodingException e) {
156            throw new CertInvalidException(e.getMessage(), e);
157        }
158        catch (GeneralSecurityException e) {
159            throw new ABACException(e.getMessage(), e);
160        }
161
162        init(a);
163    }
164
165    /**
166     * Construct from a string, used as a CN.  Keys are generated.
167     * @param cn a String containing the menomnic name
168     * @throws CertInvalidException if the stream is unparsable
169     * @throws MissingIssuerException if none of the Identities can validate the
170     *                              certificate
171     * @throws BadSignatureException if the signature check fails
172     * @throws ABACException if an uncategorized error occurs
173     */
174    public Identity(String cn) throws ABACException { 
175        this(cn, defaultValidity);
176    }
177
178    /**
179     * Construct from a file containing a self-signed PEM certificate.
180     * @param file the File to read
181     * @throws CertInvalidException if the stream is unparsable
182     * @throws MissingIssuerException if none of the Identities can validate the
183     *                              certificate
184     * @throws BadSignatureException if the signature check fails
185     * @throws ABACException if an uncategorized error occurs
186     * @throws FileNotFoundException if the file is invalid
187     */
188    public Identity(File file) throws ABACException, FileNotFoundException { 
189        kp = null;
190        init(new FileReader(file));
191    }
192
193    /**
194     * Construct from a reader containing a self-signed PEM certificate.
195     * @param r the Reader containing the certificate
196     * @throws CertInvalidException if the stream is unparsable
197     * @throws MissingIssuerException if none of the Identities can validate the
198     *                              certificate
199     * @throws BadSignatureException if the signature check fails
200     * @throws ABACException if an uncategorized error occurs
201     */
202    public Identity(Reader r) throws ABACException {
203        kp = null;
204        init(r);
205    }
206
207    /**
208     * Construct from an InputStream containing a self-signed PEM certificate.
209     * @param s the InputStream containing the certificate
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     */
216    public Identity(InputStream s) throws ABACException {
217        kp = null;
218        init(new InputStreamReader(s));
219    }
220
221    /**
222     * Construct from an X509Certificate
223     * @param cert an X509Certificate to init from
224     * @throws CertInvalidException if the stream is unparsable
225     * @throws MissingIssuerException if none of the Identities can validate the
226     *                              certificate
227     * @throws BadSignatureException if the signature check fails
228     * @throws ABACException if an uncategorized error occurs
229     */
230    public Identity(X509Certificate cert) throws ABACException {
231        kp = null;
232        init(cert);
233    }
234
235    /**
236     * Write the PEM key to the given writer.
237     * @param w the Writer
238     * @return true if the Identity had a keypair and wrote the key
239     * @throws IOException if writing fails
240     */
241    public boolean writePrivateKey(Writer w) throws IOException {
242        if (kp != null ) {
243            PEMWriter pw = new PEMWriter(w);
244
245            pw.writeObject(kp.getPrivate());
246            pw.flush();
247            return true;
248        }
249        else return false;
250    }
251
252    /**
253     * Write the PEM key to a file with the given name.
254     */
255    public boolean writePrivateKey(String fn) 
256            throws IOException, FileNotFoundException {
257        return writePrivateKey(new FileWriter(fn));
258    }
259
260    /**
261     * Write the PEM key to the given file.
262     * @param fn a String with the output file name
263     * @return true if the Identity had a keypair and wrote the key
264     * @throws IOException if writing fails
265     */
266    public boolean writePrivateKey(File fn) 
267            throws IOException, FileNotFoundException {
268        return writePrivateKey(new FileWriter(fn));
269    }
270
271    /**
272     * Write the PEM key to the given OutputStream.
273     * @param s an OutputStream to write on
274     * @return true if the Identity had a keypair and wrote the key
275     * @throws IOException if writing fails
276     */
277    public boolean writePrivateKey(OutputStream s) 
278            throws IOException, FileNotFoundException {
279        return writePrivateKey(new OutputStreamWriter(s));
280    }
281
282
283    /**
284     * Write the PEM cert to the given writer.
285     * @param w a Writer to write on
286     * @throws IOException if writing fails
287     */
288    public void write(Writer w) throws IOException {
289        PEMWriter pw = new PEMWriter(w);
290
291        pw.writeObject(cert);
292        pw.flush();
293    }
294
295    /**
296     * Write the PEM cert to a file with the given name.
297     */
298    public void write(String fn) throws IOException, FileNotFoundException {
299        write(new FileWriter(fn));
300    }
301
302    /**
303     * Write the PEM cert to the given file.
304     * @param fn a String with the output file name
305     * @throws IOException if writing fails
306     */
307    public void write(File fn) throws IOException, FileNotFoundException {
308        write(new FileWriter(fn));
309    }
310
311    /**
312     * Write the PEM cert to the given OutputStream.
313     * @param s an OutputStream to write on
314     * @throws IOException if writing fails
315     */
316    public void write(OutputStream s) 
317        throws IOException, FileNotFoundException {
318        write(new OutputStreamWriter(s));
319    }
320
321
322    /**
323     * Return the Identity's KeyID
324     * @return the Identity's KeyID
325     */
326    public String getKeyID() { return keyid; }
327    /**
328     * Return the Identity's mnemonic name
329     * @return the Identity's mnemonic name
330     */
331    public String getName() { return cn; }
332    /**
333     * Return the Identity's X509 Certificate
334     * @return the Identity's X509 Certificate
335     */
336    public X509Certificate getCertificate() { return cert; }
337
338    /**
339     * Return the expiration time of the Identity
340     * @return a Date the expiration time of the Identity
341     */
342    public Date getExpiration(){ return expiration; }
343
344    /**
345     * Return a simple string rep of the Identity.
346     * @return a simple string rep of the Identity.
347     */
348    public String toString() { 
349        String s = keyid + " (" + cn ;
350
351        if (getKeyPair() != null ) s += " [keyed]";
352        s += ")";
353        return s;
354    }
355    /**
356     * Associate a keypair with this Identity.  If the ID has a certificate,
357     * make sure that the keypair matches it.  If not throw an
358     * IllegalArgumentException.
359     * @param k the KeyPair to connect
360     * @throws IllegalArgumentException if the keypair does not
361     *                              match the pubkey in the X509 certificate
362     */
363    public void setKeyPair(KeyPair k) {
364        if (keyid != null) {
365            String kid = Context.extractKeyID(k.getPublic());
366
367            if ( kid != null && kid.equals(keyid)) kp = k;
368            else 
369                throw new IllegalArgumentException(
370                        "Keypair does not match certificate");
371        }
372        else kp = k;
373    }
374
375    /**
376     * Return the keypair associated with this Identity (if any)
377     * @return the keypair associated with this Identity (if any)
378     */
379    public KeyPair getKeyPair() { return kp; }
380
381    /**
382     * Return true if the two identites refer to teh same key.  Two Identities
383     * are equal if their key ID's match.
384     * @return true if the two key ID's are equal.
385     */
386    public boolean equals(Object o) { 
387        if ( o == null ) return false;
388        else if ( ! (o instanceof Identity) ) return false;
389        else return getKeyID().equals(((Identity)o).getKeyID());
390    }
391
392    /**
393     * Return a hash code for the Identity - the hash of its KeyID()
394     * @return an int, the hashCode
395     */
396    public int hashCode() {
397        if (keyid == null) return super.hashCode();
398        return keyid.hashCode();
399    }
400
401
402    /**
403     * Order 2 identities for sorting.  They are ordered by their key ID's.
404     * @param o an Object to compare
405     * @return -1 if this Identity is before, 0 if they are the same, and 1
406     *              if this Identity is after the given object.
407     */
408    public int compareTo(Object o) { 
409        if ( ! (o instanceof Identity) ) return 1;
410        else return getKeyID().compareTo(((Identity)o).getKeyID());
411    }
412
413};
Note: See TracBrowser for help on using the repository browser.