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

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

Allow users to set validity periods.

  • Property mode set to 100644
File size: 21.8 KB
Line 
1package net.deterlab.abac;
2
3import java.io.*;
4import java.math.*;
5import java.text.*;
6
7import java.util.*;
8
9import java.security.*;
10import java.security.cert.*;
11
12import javax.xml.parsers.*;
13import javax.xml.transform.*;
14import javax.xml.transform.dom.*;
15import javax.xml.transform.stream.*;
16
17import javax.xml.crypto.*;
18import javax.xml.crypto.dsig.*;
19import javax.xml.crypto.dsig.dom.*;
20import javax.xml.crypto.dsig.keyinfo.*;
21import javax.xml.crypto.dsig.spec.*;
22
23import org.xml.sax.*;
24import org.w3c.dom.*;
25
26/**
27 * An ABAC credential formatted as an abac-type GENI credential.
28 * @author <a href="http://abac.deterlab.net">ISI ABAC team</a>
29 * @version 1.4
30 */
31public class GENICredential extends Credential implements Comparable {
32    /** The signed XML representing this credential */
33    protected Document doc;
34
35    /**
36     * X509KeySelector implementation from
37     * http://www.outsourcingi.com/art-271-Programming-With-the-Java-XML-Digital-Signature-API.html
38     * .
39     *
40     * Straight ahead extraction of a key from an X509 cert, but it is their
41     * code and hard to improve on.
42     */
43    static protected class X509KeySelector extends KeySelector {
44        public KeySelectorResult select(KeyInfo keyInfo,
45                                        KeySelector.Purpose purpose,
46                                        AlgorithmMethod method,
47                                        XMLCryptoContext context)
48            throws KeySelectorException {
49            Iterator ki = keyInfo.getContent().iterator();
50            while (ki.hasNext()) {
51                XMLStructure info = (XMLStructure) ki.next();
52                if (!(info instanceof X509Data))
53                    continue;
54                X509Data x509Data = (X509Data) info;
55                Iterator xi = x509Data.getContent().iterator();
56                while (xi.hasNext()) {
57                    Object o = xi.next();
58                    if (!(o instanceof X509Certificate))
59                        continue;
60                    final PublicKey key = ((X509Certificate)o).getPublicKey();
61                    // Make sure the algorithm is compatible
62                    // with the method.
63                    if (algEquals(method.getAlgorithm(), key.getAlgorithm())) {
64                        return new KeySelectorResult() {
65                            public Key getKey() { return key; }
66                        };
67                    }
68                }
69            }
70            throw new KeySelectorException("No key found!");
71        }
72
73        boolean algEquals(String algURI, String algName) {
74            if ((algName.equalsIgnoreCase("DSA") &&
75                algURI.equalsIgnoreCase(SignatureMethod.DSA_SHA1)) ||
76                (algName.equalsIgnoreCase("RSA") &&
77
78                algURI.equalsIgnoreCase(SignatureMethod.RSA_SHA1))) {
79                return true;
80            } else {
81                return false;
82            }
83        }
84    }
85
86    /**
87     * Create an empty Credential.
88     */
89    public GENICredential() {
90        super();
91        doc = null;
92    }
93    /**
94     * Create a credential from a head and tail role.  This credential has no
95     * underlying certificate, and cannot be exported or used in real proofs.
96     * make_cert can create a certificate for a credential initialized this
97     * way.
98     * @param head the Role at the head of the credential
99     * @param tail the Role at the tail of the credential
100     */
101    public GENICredential(Role head, Role tail) {
102        super(head, tail);
103        doc = null; 
104    }
105
106    /**
107     * Do the credential extraction from an input stream.  This parses the
108     * certificate from the input stream and saves it. The contents must be
109     * validated and parsed later.
110     * @param stream the InputStream to read the certificate from.
111     * @return the parsed XML document
112     * @throws IOException if the stream is unparsable
113     */
114    static protected Document read_certificate(InputStream stream) 
115            throws IOException {
116        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
117        DocumentBuilder db = null;
118        Document ldoc = null;
119
120        if ( dbf == null ) 
121            throw new IOException("Cannot get DocumentBuilderFactory!?");
122        try {
123            /* Note this setting is required to find the properly
124             * namespace-scoped signature block in the credential.
125             */
126            dbf.setNamespaceAware(true);
127            if ( (db = dbf.newDocumentBuilder()) == null ) 
128                throw new IOException("Cannot get DocumentBuilder!?");
129            ldoc = db.parse(stream);
130            ldoc.normalizeDocument();
131            return ldoc;
132        }
133        catch (IllegalArgumentException ie) {
134            throw new IOException("null stream", ie);
135        }
136        catch (SAXException se) {
137            throw new IOException(se.getMessage(), se);
138        }
139        catch (Exception e) {
140            throw new IOException(e.getMessage(), e);
141        }
142
143    }
144
145    /**
146     * Walk the document and set all instances of an xml:id attribute to be ID
147     * attributes in terms of the java libraries.  This is needed for the
148     * signature code to find signed subsections.  The "xml:id" is treated as
149     * both a namespace free ID with a colon and as an "id" identifier in the
150     * "xml" namespace so we don't miss it.
151     * @param n the root of the document to mark
152     */
153    static protected void setIDAttrs(Node n) {
154        if ( n.getNodeType() == Node.ELEMENT_NODE) {
155            Element e = (Element) n;
156            String id = e.getAttribute("xml:id");
157
158            if ( id != null && id.length() > 0 )
159                e.setIdAttribute("xml:id", true);
160
161            id = e.getAttributeNS("xml", "id");
162            if ( id != null && id.length() > 0 )
163                e.setIdAttributeNS("xml", "id", true);
164        }
165
166        for (Node nn = n.getFirstChild(); nn != null; nn = nn.getNextSibling())
167            setIDAttrs(nn);
168    }
169
170    /**
171     * Return the child of Node n  that has the given name, if there is one.
172     * @param n a Node to search
173     * @param name the name to search for
174     * @return a Node with the name, may be null
175     */
176    static protected Node getChildByName(Node n, String name) {
177        if (name == null ) return null;
178
179        for (Node nn = n.getFirstChild(); nn != null; nn = nn.getNextSibling())
180            if ( nn.getNodeType() == Node.ELEMENT_NODE && 
181                    name.equals(nn.getNodeName())) return nn;
182        return null;
183    }
184
185    /**
186     * Find the X509Certificate in the Signature element and convert it to an
187     * ABAC identity.  This assumes a KeyInfo in that section holding an
188     * X509Data section containing the certificate in an X509Certificate
189     * section.  Any of that not being found will cause a failure.  If the
190     * Identity cannot be created a Gignature exception is thrown.
191     * @param n a Node pointing to a Signature section
192     * @return an Identity constructed frm the X509 Certificate
193     * @throws MissingIssuerException if the Identity cannot be created from the
194     * certificate.
195     */
196    static protected Identity getIdentity(Node n) 
197        throws MissingIssuerException {
198        Identity rv = null;
199        Node nn = getChildByName(n, "KeyInfo");
200        String certStr = null;
201
202        if ( nn == null ) return null;
203        if ( ( nn = getChildByName(nn, "X509Data")) == null ) return null;
204        if ( ( nn = getChildByName(nn, "X509Certificate")) == null ) return null;
205        if ( ( certStr = nn.getTextContent()) == null ) return null;
206        try {
207            certStr = "-----BEGIN CERTIFICATE-----\n" + 
208                certStr + 
209                "\n-----END CERTIFICATE-----";
210            return new Identity(new StringReader(certStr));
211        } 
212        catch (Exception e) {
213            throw new MissingIssuerException(e.getMessage(), e);
214        }
215    }
216
217    static protected Date getTime(Document d, String field) 
218            throws ABACException {
219        Node root = null;
220        Node n = null;
221        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz");
222        Date date = null;
223        String dstr = null;
224
225        if ( (root = getChildByName(d, "signed-credential")) == null)
226            throw new CertInvalidException("No signed-credential element");
227        if ( (n = getChildByName(root, "credential")) == null )
228            throw new CertInvalidException("No credential element");
229        if ( (n = getChildByName(n, field)) == null )
230            throw new CertInvalidException("No " + field + " element");
231
232        if ( ( dstr = n.getTextContent()) == null ) 
233            throw new CertInvalidException("No expires content");
234
235        dstr = dstr.replace("Z", "GMT");
236        if ((date = df.parse(dstr, new ParsePosition(0))) == null)
237            throw new CertInvalidException("Cannot parse date: "+
238                    n.getTextContent());
239
240        return date;
241    }
242
243    /**
244     * Initialize a credential from parsed certificate.  Validiate it against
245     * the given identities and parse out the roles.  Note that catching
246     * java.security.GeneralSecurityException catches most of the exceptions
247     * this throws.
248     * @param ids a Collection of Identities to use in validating the cert
249     * @throws CertInvalidException if the stream is unparsable
250     * @throws MissingIssuerException if none of the Identities can validate the
251     *                              certificate
252     * @throws BadSignatureException if the signature check fails
253     */
254    protected void init(Collection<Identity> ids) 
255            throws ABACException {
256
257        XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
258        NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS, 
259                "Signature");
260        DOMValidateContext valContext = null;
261        XMLSignature signature = null;
262
263        try {
264
265            if (nl.getLength() == 0) 
266                throw new CertInvalidException("Cannot find Signature element");
267
268            setIDAttrs(doc);
269            valContext = new DOMValidateContext(new X509KeySelector(),
270                    nl.item(0));
271            if ( valContext == null )
272                throw new ABACException("No validation context!?");
273
274            signature = fac.unmarshalXMLSignature(valContext);
275            if (signature == null) 
276                throw new BadSignatureException("Cannot unmarshal signature");
277
278            if (!signature.validate(valContext))
279                throw new BadSignatureException("bad signature");
280
281            m_expiration = getTime(doc, "expires");
282
283            if ( m_expiration.before(new Date()))
284                throw new CertInvalidException("Certificate Expired " + 
285                        m_expiration);
286
287            load_roles();
288
289            id = getIdentity(nl.item(0));
290
291            if ( !ids.contains(id) ) ids.add(id);
292
293            if (!id.getKeyID().equals(m_head.principal()))
294                throw new MissingIssuerException("Issuer ID and left hand " +
295                        "side principal disagree");
296        }
297        catch (ABACException ae) {
298            throw ae;
299        }
300        catch (Exception e) {
301            throw new BadSignatureException(e.getMessage(), e);
302        }
303    }
304
305    /**
306     * Parse a credential from an InputStream and initialize the role from it.
307     * Combine read_credential(stream) and init(ids).  Note that catching
308     * java.security.GeneralSecurityException catches most of the exceptions
309     * this throws.
310     * @param stream the InputStream to read the certificate from.
311     * @param ids a Collection of Identities to use in validating the cert
312     * @throws CertInvalidException if the stream is unparsable
313     * @throws MissingIssuerException if none of the Identities can validate the
314     *                              certificate
315     * @throws BadSignatureException if the signature check fails
316     */
317    protected void init(InputStream stream, Collection<Identity> ids) 
318            throws ABACException {
319         try {
320            doc = read_certificate(stream);
321         }
322         catch (IOException e) {
323             throw new CertInvalidException("Cannot parse cert", e);
324         }
325        if (doc == null) throw new CertInvalidException("Unknown Format");
326        init(ids);
327    }
328
329    /**
330     * Create a credential from an attribute cert in a file. Throws an
331     * exception if the cert file can't be opened or if there's a format
332     * problem with the cert.  Note that catching
333     * java.security.GeneralSecurityException catches most of the exceptions
334     * this throws.
335     * @param filename a String containing the filename to read
336     * @param ids a Collection of Identities to use in validating the cert
337     * @throws CertInvalidException if the stream is unparsable
338     * @throws MissingIssuerException if none of the Identities can validate the
339     *                              certificate
340     * @throws BadSignatureException if the signature check fails
341     */
342    GENICredential(String filename, Collection<Identity> ids) 
343        throws ABACException { 
344        try {
345            init(new FileInputStream(filename), ids);
346        }
347        catch (FileNotFoundException e) {
348            throw new CertInvalidException("Bad filename", e);
349        }
350    }
351
352    /**
353     * Create a credential from an attribute cert in a file. Throws an
354     * exception if the cert file can't be opened or if there's a format
355     * problem with the cert.  Note that catching
356     * java.security.GeneralSecurityException catches most of the exceptions
357     * this throws.
358     * @param file the File to read
359     * @param ids a Collection of Identities to use in validating the cert
360     * @throws CertInvalidException if the stream is unparsable
361     * @throws MissingIssuerException if none of the Identities can validate the
362     *                              certificate
363     * @throws BadSignatureException if the signature check fails
364     */
365    GENICredential(File file, Collection<Identity> ids) 
366            throws ABACException {
367        try {
368            init(new FileInputStream(file), ids);
369        }
370        catch (FileNotFoundException e) {
371            throw new CertInvalidException("Bad filename", e);
372        }
373    }
374
375    /**
376     * Create a credential from an InputStream.  Throws an exception if the
377     * stream can't be parsed or if there's a format problem with the cert.
378     * Note that catching java.security.GeneralSecurityException catches most
379     * of the exceptions this throws.
380     * @param s the InputStream to read
381     * @param ids a Collection of Identities to use in validating the cert
382     * @throws CertInvalidException if the stream is unparsable
383     * @throws MissingIssuerException if none of the Identities can validate the
384     *                              certificate
385     * @throws BadSignatureException if the signature check fails
386     */
387    GENICredential(InputStream s, Collection<Identity> ids) 
388            throws ABACException { init(s, ids); }
389
390    /**
391     * Encode the abac credential's XML and set the validity.  This is straight
392     * line code that directly builds the credential.
393     * @param validity a long holding the number of seconds that the credential
394     * is valid for.
395     * @return a Node, the place to attach signatures
396     * @throws ABACException if any of the XML construction fails
397     */
398    protected Node make_rt0_content(long validity) throws ABACException {
399        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
400        DocumentBuilder db = null;
401        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
402        StringBuffer expBuf = new StringBuffer();
403
404        /* This is a weirdness to cope with the GENI format.  They have a naked
405         * xml:id specifier without any namespace declarations in the
406         * credential.  Notice that this is the opposite of the setting used in
407         * init to read a credential. */
408        dbf.setNamespaceAware(false);
409
410        if ( dbf == null ) 
411            throw new ABACException("Cannot get DocumentBuilderFactory!?");
412
413        try {
414            db = dbf.newDocumentBuilder();
415        }
416        catch (ParserConfigurationException pe) {
417            throw new ABACException("Cannot get DocumentBuilder!?" + 
418                    pe.getMessage(), pe);
419        }
420
421        doc = db.newDocument();
422        if ( doc == null ) 
423            throw new ABACException("No Document");
424
425        Element root = doc.createElement("signed-credential"); 
426        Element cred = doc.createElement("credential");
427        Element sig = doc.createElement("signatures");
428        Element e = doc.createElement("type");
429        Node text = doc.createTextNode("abac");
430
431        doc.appendChild(root);
432
433        cred.setAttribute("xml:id", "ref0");
434        /* So that the signing code can find the section to sign */
435        cred.setIdAttribute("xml:id", true);
436
437        root.appendChild(cred);
438        e.appendChild(text);
439        cred.appendChild(e);
440
441        m_expiration = new Date(System.currentTimeMillis() + 
442                (1000L * validity ));
443        df.setTimeZone(new SimpleTimeZone(0, "Z"));
444        df.format(m_expiration, expBuf, new FieldPosition(0));
445        e = doc.createElement("expires");
446        text = doc.createTextNode(expBuf.toString());
447        e.appendChild(text);
448        cred.appendChild(e);
449
450        e = doc.createElement("version");
451        text = doc.createTextNode("1.0");
452        e.appendChild(text);
453        cred.appendChild(e);
454
455        e = doc.createElement("rt0");
456        text = doc.createTextNode(m_head + "<-" + m_tail);
457        e.appendChild(text);
458        cred.appendChild(e);
459
460        root.appendChild(sig);
461        return sig;
462    }
463
464    /**
465     * Create a certificate from this credential issued by the given identity
466     * valid for the given time (in seconds).  This is the signed XML ABAC
467     * credential.
468     * @param i the Identity that will issue the certificate
469     * @param validity a long holding the number of seconds that the credential
470     * is valid for.
471     * @throws ABACException if xml creation fails
472     * @throws MissingIssuerException if the issuer is bad
473     * @throws BadSignatureException if the signature creation fails
474     */
475    public void make_cert(Identity i, long validity) 
476            throws ABACException {
477        X509Certificate cert = i.getCertificate();
478        KeyPair kp = i.getKeyPair();
479        PublicKey pubKey = null;
480        PrivateKey privKey = null;
481        if ( cert == null ) 
482            throw new MissingIssuerException("No credential in identity?");
483        if ( kp == null ) 
484            throw new MissingIssuerException("No keypair in identity?");
485
486        pubKey = kp.getPublic();
487        if ((privKey = kp.getPrivate()) == null ) 
488            throw new MissingIssuerException("No private ket in identity");
489
490        XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
491        Reference ref = null;
492        SignedInfo si = null;
493        KeyInfoFactory kif = fac.getKeyInfoFactory();
494
495        /* The <Object> doesn't say much, but shuts the compiler up about
496         * unchecked references.  The lists are polymorphyc and the signature
497         * libs expect that, so <Object> is the best we can do.
498         */
499        List<Object> x509Content = new ArrayList<Object>();
500        List<Object> keyInfo = new ArrayList<Object>();
501        x509Content.add(cert.getSubjectX500Principal().getName());
502        x509Content.add(cert);
503        X509Data xd = kif.newX509Data(x509Content);
504        KeyValue kv = null;
505
506        try {
507            kv = kif.newKeyValue(pubKey);
508        } 
509        catch (KeyException ke) {
510            throw new ABACException("Unsupported key format " + 
511                    ke.getMessage(), ke);
512        }
513
514        Collections.addAll(keyInfo, kv, xd);
515
516        KeyInfo ki = kif.newKeyInfo(keyInfo);
517        Node sig = make_rt0_content(validity);
518
519        try {
520            ref = fac.newReference("#ref0", 
521                    fac.newDigestMethod(DigestMethod.SHA1, null),
522                    Collections.singletonList(
523                        fac.newTransform(Transform.ENVELOPED, 
524                            (TransformParameterSpec) null)),
525                    null, null);
526
527            si = fac.newSignedInfo(
528                    fac.newCanonicalizationMethod(
529                        CanonicalizationMethod.INCLUSIVE,
530                        (C14NMethodParameterSpec) null),
531                    fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null),
532                    Collections.singletonList(ref));
533
534            DOMSignContext dsc = new DOMSignContext(privKey, sig);
535            XMLSignature signature = fac.newXMLSignature(si, ki);
536            signature.sign(dsc);
537        }
538        catch (Exception me) {
539            throw new BadSignatureException(me.getMessage(), me);
540        }
541
542    }
543
544    /**
545     * Create a certificate from this credential issued by the given identity
546     * valid for the default validity period.  This is the signed XML ABAC
547     * credential.
548     * @param i the Identity that will issue the certificate
549     * @throws ABACException if xml creation fails
550     * @throws MissingIssuerException if the issuer is bad
551     * @throws BadSignatureException if the signature creation fails
552     */
553    public void make_cert(Identity i) 
554            throws ABACException {
555        make_cert(i, defaultValidity);
556    }
557
558    /**
559     * Load the roles off the attribute cert.
560     * @throws CertInvalidException if the certificate is badly formatted
561     */
562    private void load_roles() throws CertInvalidException {
563        if ( doc == null ) 
564            throw new CertInvalidException("No credential");
565
566        NodeList nodes = doc.getElementsByTagName("type");
567        Node node = null;
568        String roles = null;
569
570        if (nodes == null || nodes.getLength() != 1) 
571            throw new CertInvalidException("More than one type element?");
572
573        node = nodes.item(0);
574        if ( node == null ) 
575            throw new CertInvalidException("bad rt0 element?");
576
577        if ( !"abac".equals(node.getTextContent()) ) 
578            throw new CertInvalidException("Not an abac type credential");
579
580        nodes = doc.getElementsByTagName("rt0");
581        if (nodes == null || nodes.getLength() != 1) 
582            throw new CertInvalidException("More than one rt0 element?");
583
584        node = nodes.item(0);
585
586        if ( node == null ) 
587            throw new CertInvalidException("bad rt0 element?");
588
589        if ( (roles = node.getTextContent()) == null ) 
590            throw new CertInvalidException("bad rt0 element (no text)?");
591
592        String[] parts = roles.split("\\s*<--?\\s*");
593        if (parts.length != 2)
594            throw new CertInvalidException("Invalid attribute: " + roles);
595
596        m_head = new Role(parts[0]);
597        m_tail = new Role(parts[1]);
598    }
599
600    /**
601     * Output the signed GENI ABAC certificate associated with this
602     * Credential to the OutputStream.
603     * @param s the OutputStream on which to write
604     * @throws IOException if there is an error writing.
605     */
606    public void write(OutputStream s) throws IOException {
607        if ( doc == null ) 
608            return;
609        try {
610            TransformerFactory tf = TransformerFactory.newInstance();
611            Transformer t = tf.newTransformer();
612            DOMSource source = new DOMSource(doc);
613            StreamResult result = new StreamResult(s);
614
615            t.transform(source, result);
616            s.flush();
617        } 
618        catch (Exception e) {
619            throw new IOException(e.getMessage(), e);
620        }
621    }
622    /**
623     * Output the signed GENI ABAC certificate associated with this
624     * Credential to the OutputStream.
625     * @param fn a String, the file name on which to write
626     * @throws IOException if there is an error writing.
627     * @throws FileNotFoundExeption if the file path is bogus
628     */
629    public void write(String fn) throws IOException, FileNotFoundException {
630        write(new FileOutputStream(fn));
631    }
632
633    /**
634     * Return true if this Credential has a certificate associated.  A jabac
635     * extension.
636     * @return true if this Credential has a certificate associated.
637     */
638    public boolean hasCertificate() { return doc != null; }
639
640    /**
641     * Return a CredentialCredentialFactorySpecialization for GENICredentials.
642     * Used by the CredentialFactory to parse and generate these kind of
643     * credentials.  It basically wraps constuctor calls.
644     * @return a CredentialFactorySpecialization for this kind of credential.
645     */
646    static public CredentialFactorySpecialization
647            getCredentialFactorySpecialization() {
648        return new CredentialFactorySpecialization() {
649            public Credential[] parseCredential(InputStream is, 
650                    Collection<Identity> ids) throws ABACException {
651                return new Credential[] { new GENICredential(is, ids) }; 
652            }
653            public Credential generateCredential(Role head, Role tail) {
654                return new GENICredential(head, tail);
655            }
656        };
657    }
658}
Note: See TracBrowser for help on using the repository browser.