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

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

Add expirations to all credentials

  • Property mode set to 100644
File size: 21.0 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.  This is straight line code that
392     * directly builds the credential.
393     * @return a Node, the place to attach signatures
394     * @throws ABACException if any of the XML construction fails
395     */
396    protected Node make_rt0_content() throws ABACException {
397        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
398        DocumentBuilder db = null;
399        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
400        StringBuffer expBuf = new StringBuffer();
401
402        /* This is a weirdness to cope with the GENI format.  They have a naked
403         * xml:id specifier without any namespace declarations in the
404         * credential.  Notice that this is the opposite of the setting used in
405         * init to read a credential. */
406        dbf.setNamespaceAware(false);
407
408        if ( dbf == null ) 
409            throw new ABACException("Cannot get DocumentBuilderFactory!?");
410
411        try {
412            db = dbf.newDocumentBuilder();
413        }
414        catch (ParserConfigurationException pe) {
415            throw new ABACException("Cannot get DocumentBuilder!?" + 
416                    pe.getMessage(), pe);
417        }
418
419        doc = db.newDocument();
420        if ( doc == null ) 
421            throw new ABACException("No Document");
422
423        Element root = doc.createElement("signed-credential"); 
424        Element cred = doc.createElement("credential");
425        Element sig = doc.createElement("signatures");
426        Element e = doc.createElement("type");
427        Node text = doc.createTextNode("abac");
428
429        doc.appendChild(root);
430
431        cred.setAttribute("xml:id", "ref0");
432        /* So that the signing code can find the section to sign */
433        cred.setIdAttribute("xml:id", true);
434
435        root.appendChild(cred);
436        e.appendChild(text);
437        cred.appendChild(e);
438
439        /* XXX: pass in valid time */
440        df.setTimeZone(new SimpleTimeZone(0, "Z"));
441        df.format(new Date(System.currentTimeMillis() + 
442                    (3600L * 1000L * 24L * 365L)),
443                expBuf, new FieldPosition(0));
444        e = doc.createElement("expires");
445        text = doc.createTextNode(expBuf.toString());
446        e.appendChild(text);
447        cred.appendChild(e);
448
449        e = doc.createElement("version");
450        text = doc.createTextNode("1.0");
451        e.appendChild(text);
452        cred.appendChild(e);
453
454        e = doc.createElement("rt0");
455        text = doc.createTextNode(m_head + "<-" + m_tail);
456        e.appendChild(text);
457        cred.appendChild(e);
458
459        root.appendChild(sig);
460        return sig;
461    }
462
463    /**
464     * Create a certificate from this credential issued by the given identity.
465     * This is the signed XML ABAC credential.
466     * @param i the Identity that will issue the certificate
467     * @throws ABACException if xml creation fails
468     * @throws MissingIssuerException if the issuer is bad
469     * @throws BadSignatureException if the signature creation fails
470     */
471    public void make_cert(Identity i) 
472            throws ABACException {
473        X509Certificate cert = i.getCertificate();
474        KeyPair kp = i.getKeyPair();
475        PublicKey pubKey = null;
476        PrivateKey privKey = null;
477        if ( cert == null ) 
478            throw new MissingIssuerException("No credential in identity?");
479        if ( kp == null ) 
480            throw new MissingIssuerException("No keypair in identity?");
481
482        pubKey = kp.getPublic();
483        if ((privKey = kp.getPrivate()) == null ) 
484            throw new MissingIssuerException("No private ket in identity");
485
486        XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
487        Reference ref = null;
488        SignedInfo si = null;
489        KeyInfoFactory kif = fac.getKeyInfoFactory();
490
491        /* The <Object> doesn't say much, but shuts the compiler up about
492         * unchecked references.  The lists are polymorphyc and the signature
493         * libs expect that, so <Object> is the best we can do.
494         */
495        List<Object> x509Content = new ArrayList<Object>();
496        List<Object> keyInfo = new ArrayList<Object>();
497        x509Content.add(cert.getSubjectX500Principal().getName());
498        x509Content.add(cert);
499        X509Data xd = kif.newX509Data(x509Content);
500        KeyValue kv = null;
501
502        try {
503            kv = kif.newKeyValue(pubKey);
504        } 
505        catch (KeyException ke) {
506            throw new ABACException("Unsupported key format " + 
507                    ke.getMessage(), ke);
508        }
509
510        Collections.addAll(keyInfo, kv, xd);
511
512        KeyInfo ki = kif.newKeyInfo(keyInfo);
513        Node sig = make_rt0_content();
514
515        try {
516            ref = fac.newReference("#ref0", 
517                    fac.newDigestMethod(DigestMethod.SHA1, null),
518                    Collections.singletonList(
519                        fac.newTransform(Transform.ENVELOPED, 
520                            (TransformParameterSpec) null)),
521                    null, null);
522
523            si = fac.newSignedInfo(
524                    fac.newCanonicalizationMethod(
525                        CanonicalizationMethod.INCLUSIVE,
526                        (C14NMethodParameterSpec) null),
527                    fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null),
528                    Collections.singletonList(ref));
529
530            DOMSignContext dsc = new DOMSignContext(privKey, sig);
531            XMLSignature signature = fac.newXMLSignature(si, ki);
532            signature.sign(dsc);
533        }
534        catch (Exception me) {
535            throw new BadSignatureException(me.getMessage(), me);
536        }
537
538    }
539
540    /**
541     * Load the roles off the attribute cert.
542     * @throws CertInvalidException if the certificate is badly formatted
543     */
544    private void load_roles() throws CertInvalidException {
545        if ( doc == null ) 
546            throw new CertInvalidException("No credential");
547
548        NodeList nodes = doc.getElementsByTagName("type");
549        Node node = null;
550        String roles = null;
551
552        if (nodes == null || nodes.getLength() != 1) 
553            throw new CertInvalidException("More than one type element?");
554
555        node = nodes.item(0);
556        if ( node == null ) 
557            throw new CertInvalidException("bad rt0 element?");
558
559        if ( !"abac".equals(node.getTextContent()) ) 
560            throw new CertInvalidException("Not an abac type credential");
561
562        nodes = doc.getElementsByTagName("rt0");
563        if (nodes == null || nodes.getLength() != 1) 
564            throw new CertInvalidException("More than one rt0 element?");
565
566        node = nodes.item(0);
567
568        if ( node == null ) 
569            throw new CertInvalidException("bad rt0 element?");
570
571        if ( (roles = node.getTextContent()) == null ) 
572            throw new CertInvalidException("bad rt0 element (no text)?");
573
574        String[] parts = roles.split("\\s*<--?\\s*");
575        if (parts.length != 2)
576            throw new CertInvalidException("Invalid attribute: " + roles);
577
578        m_head = new Role(parts[0]);
579        m_tail = new Role(parts[1]);
580    }
581
582    /**
583     * Output the signed GENI ABAC certificate associated with this
584     * Credential to the OutputStream.
585     * @param s the OutputStream on which to write
586     * @throws IOException if there is an error writing.
587     */
588    public void write(OutputStream s) throws IOException {
589        if ( doc == null ) 
590            return;
591        try {
592            TransformerFactory tf = TransformerFactory.newInstance();
593            Transformer t = tf.newTransformer();
594            DOMSource source = new DOMSource(doc);
595            StreamResult result = new StreamResult(s);
596
597            t.transform(source, result);
598            s.flush();
599        } 
600        catch (Exception e) {
601            throw new IOException(e.getMessage(), e);
602        }
603    }
604    /**
605     * Output the signed GENI ABAC certificate associated with this
606     * Credential to the OutputStream.
607     * @param fn a String, the file name on which to write
608     * @throws IOException if there is an error writing.
609     * @throws FileNotFoundExeption if the file path is bogus
610     */
611    public void write(String fn) throws IOException, FileNotFoundException {
612        write(new FileOutputStream(fn));
613    }
614
615    /**
616     * Return true if this Credential has a certificate associated.  A jabac
617     * extension.
618     * @return true if this Credential has a certificate associated.
619     */
620    public boolean hasCertificate() { return doc != null; }
621
622    /**
623     * Return a CredentialCredentialFactorySpecialization for GENICredentials.
624     * Used by the CredentialFactory to parse and generate these kind of
625     * credentials.  It basically wraps constuctor calls.
626     * @return a CredentialFactorySpecialization for this kind of credential.
627     */
628    static public CredentialFactorySpecialization
629            getCredentialFactorySpecialization() {
630        return new CredentialFactorySpecialization() {
631            public Credential[] parseCredential(InputStream is, 
632                    Collection<Identity> ids) throws ABACException {
633                return new Credential[] { new GENICredential(is, ids) }; 
634            }
635            public Credential generateCredential(Role head, Role tail) {
636                return new GENICredential(head, tail);
637            }
638        };
639    }
640}
Note: See TracBrowser for help on using the repository browser.