Search in sources :

Example 1 with DOMValidateContext

use of javax.xml.crypto.dsig.dom.DOMValidateContext in project OpenAttestation by OpenAttestation.

the class SamlUtil method verifySAMLSignature.

/**
    Seeks out the signature element in the given tree, and validates it.
    Searches the configured keystore (asking it to function also as a
    truststore) for a certificate with a matching fingerprint.
    * 
    * Certificates trusted for SAML-signing must be marked with the
    * tag "(saml)" or "(SAML)" in their alias
    * 
    
    @return true if the signature validates and we know the signer; 
            false otherwise
    */
public boolean verifySAMLSignature(Element target, X509Certificate[] trustedSigners) throws MarshalException, XMLSignatureException, KeyStoreException {
    // Validate the signature -- i.e. SAML object is pristine:
    NodeList nl = target.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
    if (nl.getLength() == 0) {
        throw new IllegalArgumentException("Cannot find Signature element");
    }
    DOMValidateContext context = new DOMValidateContext(new KeyValueKeySelector(), nl.item(0));
    // MarshalException
    XMLSignature signature = factory.unmarshalXMLSignature(context);
    log.debug("signature.validate(context): " + signature.validate(context));
    for (Object keyInfoItem : signature.getKeyInfo().getContent()) {
        if (keyInfoItem instanceof X509Data) {
            for (Object X509Item : ((X509Data) keyInfoItem).getContent()) {
                if (X509Item instanceof X509Certificate) {
                    X509Certificate theirCert = (X509Certificate) X509Item;
                    log.debug("Found X509 certificate in XML: {}", theirCert.getSubjectX500Principal().getName());
                    //theirCert.get
                    for (X509Certificate ourCert : trustedSigners) {
                        if (ourCert.equals(theirCert)) {
                            log.debug("Bingo!! match for cert: " + ourCert.getSubjectX500Principal().getName());
                            return true;
                        } else {
                            log.info("No match for cert: " + ourCert.getSubjectX500Principal().getName());
                        }
                    }
                }
            }
        }
    }
    if (!signature.validate(context)) {
        // XMLSignatureException
        log.warn("XML signature is not valid");
        return false;
    }
    // Find a trusted cert -- i.e. the signer is actually someone we trust:
    for (Object keyInfoItem : signature.getKeyInfo().getContent()) {
        if (keyInfoItem instanceof X509Data) {
            for (Object X509Item : ((X509Data) keyInfoItem).getContent()) {
                if (X509Item instanceof X509Certificate) {
                    X509Certificate theirCert = (X509Certificate) X509Item;
                    log.debug("Found X509 certificate in XML: {}", theirCert.getSubjectX500Principal().getName());
                    for (X509Certificate ourCert : trustedSigners) {
                        if (ourCert.equals(theirCert)) {
                            return true;
                        }
                    }
                }
            }
        }
    }
    log.warn("Signature was valid, but signer was not known.");
    return false;
}
Also used : XMLSignature(javax.xml.crypto.dsig.XMLSignature) NodeList(org.w3c.dom.NodeList) DOMValidateContext(javax.xml.crypto.dsig.dom.DOMValidateContext) X509Data(javax.xml.crypto.dsig.keyinfo.X509Data) X509Certificate(java.security.cert.X509Certificate)

Example 2 with DOMValidateContext

use of javax.xml.crypto.dsig.dom.DOMValidateContext in project jdk8u_jdk by JetBrains.

the class GenerationTests method test_create_signature.

static void test_create_signature() throws Exception {
    System.out.println("* Generating signature.xml");
    // create references
    List<Reference> refs = new ArrayList<Reference>();
    // Reference 1
    refs.add(fac.newReference(STYLESHEET, sha1));
    // Reference 2
    refs.add(fac.newReference(STYLESHEET_B64, sha1, Collections.singletonList(fac.newTransform(Transform.BASE64, (TransformParameterSpec) null)), null, null));
    // Reference 3
    refs.add(fac.newReference("#object-1", sha1, Collections.singletonList(fac.newTransform(Transform.XPATH, new XPathFilterParameterSpec("self::text()"))), XMLObject.TYPE, null));
    // Reference 4
    String expr = "\n" + " ancestor-or-self::dsig:SignedInfo                  " + "\n" + "  and                                               " + "\n" + " count(ancestor-or-self::dsig:Reference |           " + "\n" + "      here()/ancestor::dsig:Reference[1]) >         " + "\n" + " count(ancestor-or-self::dsig:Reference)            " + "\n" + "  or                                                " + "\n" + " count(ancestor-or-self::node() |                   " + "\n" + "      id('notaries')) =                             " + "\n" + " count(ancestor-or-self::node())                    " + "\n";
    XPathFilterParameterSpec xfp = new XPathFilterParameterSpec(expr, Collections.singletonMap("dsig", XMLSignature.XMLNS));
    refs.add(fac.newReference("", sha1, Collections.singletonList(fac.newTransform(Transform.XPATH, xfp)), XMLObject.TYPE, null));
    // Reference 5
    refs.add(fac.newReference("#object-2", sha1, Collections.singletonList(fac.newTransform(Transform.BASE64, (TransformParameterSpec) null)), XMLObject.TYPE, null));
    // Reference 6
    refs.add(fac.newReference("#manifest-1", sha1, null, Manifest.TYPE, null));
    // Reference 7
    refs.add(fac.newReference("#signature-properties-1", sha1, null, SignatureProperties.TYPE, null));
    // Reference 8
    List<Transform> transforms = new ArrayList<Transform>();
    transforms.add(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
    refs.add(fac.newReference("", sha1, transforms, null, null));
    // Reference 9
    transforms.add(fac.newTransform(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (TransformParameterSpec) null));
    refs.add(fac.newReference("", sha1, transforms, null, null));
    // Reference 10
    Transform env = fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null);
    refs.add(fac.newReference("#xpointer(/)", sha1, Collections.singletonList(env), null, null));
    // Reference 11
    transforms.clear();
    transforms.add(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
    transforms.add(fac.newTransform(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (TransformParameterSpec) null));
    refs.add(fac.newReference("#xpointer(/)", sha1, transforms, null, null));
    // Reference 12
    refs.add(fac.newReference("#object-3", sha1, null, XMLObject.TYPE, null));
    // Reference 13
    Transform withComments = fac.newTransform(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (TransformParameterSpec) null);
    refs.add(fac.newReference("#object-3", sha1, Collections.singletonList(withComments), XMLObject.TYPE, null));
    // Reference 14
    refs.add(fac.newReference("#xpointer(id('object-3'))", sha1, null, XMLObject.TYPE, null));
    // Reference 15
    withComments = fac.newTransform(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (TransformParameterSpec) null);
    refs.add(fac.newReference("#xpointer(id('object-3'))", sha1, Collections.singletonList(withComments), XMLObject.TYPE, null));
    // Reference 16
    refs.add(fac.newReference("#reference-2", sha1));
    // Reference 17
    refs.add(fac.newReference("#manifest-reference-1", sha1, null, null, "reference-1"));
    // Reference 18
    refs.add(fac.newReference("#reference-1", sha1, null, null, "reference-2"));
    // create SignedInfo
    SignedInfo si = fac.newSignedInfo(withoutComments, dsaSha1, refs);
    // create keyinfo
    XPathFilterParameterSpec xpf = new XPathFilterParameterSpec("ancestor-or-self::dsig:X509Data", Collections.singletonMap("dsig", XMLSignature.XMLNS));
    RetrievalMethod rm = kifac.newRetrievalMethod("#object-4", X509Data.TYPE, Collections.singletonList(fac.newTransform(Transform.XPATH, xpf)));
    KeyInfo ki = kifac.newKeyInfo(Collections.singletonList(rm), null);
    Document doc = db.newDocument();
    // create objects
    List<XMLStructure> objs = new ArrayList<XMLStructure>();
    // Object 1
    objs.add(fac.newXMLObject(Collections.singletonList(new DOMStructure(doc.createTextNode("I am the text."))), "object-1", "text/plain", null));
    // Object 2
    objs.add(fac.newXMLObject(Collections.singletonList(new DOMStructure(doc.createTextNode("SSBhbSB0aGUgdGV4dC4="))), "object-2", "text/plain", Transform.BASE64));
    // Object 3
    Element nc = doc.createElementNS(null, "NonCommentandus");
    nc.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "");
    nc.appendChild(doc.createComment(" Commentandum "));
    objs.add(fac.newXMLObject(Collections.singletonList(new DOMStructure(nc)), "object-3", null, null));
    // Manifest
    List<Reference> manRefs = new ArrayList<Reference>();
    // Manifest Reference 1
    manRefs.add(fac.newReference(STYLESHEET, sha1, null, null, "manifest-reference-1"));
    // Manifest Reference 2
    manRefs.add(fac.newReference("#reference-1", sha1));
    // Manifest Reference 3
    List<Transform> manTrans = new ArrayList<Transform>();
    Document docxslt = db.parse(new ByteArrayInputStream(xslt.getBytes()));
    Node xslElem = docxslt.getDocumentElement();
    manTrans.add(fac.newTransform(Transform.XSLT, new XSLTTransformParameterSpec(new DOMStructure(xslElem))));
    manTrans.add(fac.newTransform(CanonicalizationMethod.INCLUSIVE, (TransformParameterSpec) null));
    manRefs.add(fac.newReference("#notaries", sha1, manTrans, null, null));
    objs.add(fac.newXMLObject(Collections.singletonList(fac.newManifest(manRefs, "manifest-1")), null, null, null));
    // SignatureProperties
    Element sa = doc.createElementNS("urn:demo", "SignerAddress");
    sa.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "urn:demo");
    Element ip = doc.createElementNS("urn:demo", "IP");
    ip.appendChild(doc.createTextNode("192.168.21.138"));
    sa.appendChild(ip);
    SignatureProperty sp = fac.newSignatureProperty(Collections.singletonList(new DOMStructure(sa)), "#signature", null);
    SignatureProperties sps = fac.newSignatureProperties(Collections.singletonList(sp), "signature-properties-1");
    objs.add(fac.newXMLObject(Collections.singletonList(sps), null, null, null));
    // Object 4
    List<Object> xds = new ArrayList<Object>();
    xds.add("CN=User");
    xds.add(kifac.newX509IssuerSerial("CN=User", new BigInteger("45ef2729", 16)));
    xds.add(signingCert);
    objs.add(fac.newXMLObject(Collections.singletonList(kifac.newX509Data(xds)), "object-4", null, null));
    // create XMLSignature
    XMLSignature sig = fac.newXMLSignature(si, ki, objs, "signature", null);
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(false);
    Document envDoc = dbf.newDocumentBuilder().parse(new FileInputStream(ENVELOPE));
    Element ys = (Element) envDoc.getElementsByTagName("YoursSincerely").item(0);
    DOMSignContext dsc = new DOMSignContext(signingKey, ys);
    dsc.setURIDereferencer(httpUd);
    sig.sign(dsc);
    //      StringWriter sw = new StringWriter();
    //        dumpDocument(envDoc, sw);
    NodeList nl = envDoc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
    if (nl.getLength() == 0) {
        throw new Exception("Couldn't find signature Element");
    }
    Element sigElement = (Element) nl.item(0);
    DOMValidateContext dvc = new DOMValidateContext(new X509KeySelector(ks), sigElement);
    dvc.setURIDereferencer(httpUd);
    File f = new File(System.getProperty("dir.test.vector.baltimore") + System.getProperty("file.separator") + "merlin-xmldsig-twenty-three" + System.getProperty("file.separator"));
    dvc.setBaseURI(f.toURI().toString());
    XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);
    if (sig.equals(sig2) == false) {
        throw new Exception("Unmarshalled signature is not equal to generated signature");
    }
    if (sig2.validate(dvc) == false) {
        throw new Exception("Validation of generated signature failed");
    }
    System.out.println();
}
Also used : XMLStructure(javax.xml.crypto.XMLStructure) DOMValidateContext(javax.xml.crypto.dsig.dom.DOMValidateContext) URIReference(javax.xml.crypto.URIReference) URIReferenceException(javax.xml.crypto.URIReferenceException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext) BigInteger(java.math.BigInteger)

Example 3 with DOMValidateContext

use of javax.xml.crypto.dsig.dom.DOMValidateContext in project jdk8u_jdk by JetBrains.

the class GenerationTests method test_create_detached_signature.

static boolean test_create_detached_signature(String canonicalizationMethod, String signatureMethod, String digestMethod, String transform, KeyInfoType keyInfo, Content contentType, int port) throws Exception {
    System.out.print("Sign ...");
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(false);
    // Create SignedInfo
    DigestMethod dm = fac.newDigestMethod(digestMethod, null);
    List transformList = null;
    if (transform != null) {
        TransformParameterSpec params = null;
        switch(transform) {
            case Transform.XPATH:
                params = new XPathFilterParameterSpec("//.");
                break;
            case Transform.XPATH2:
                params = new XPathFilter2ParameterSpec(Collections.singletonList(new XPathType("//.", XPathType.Filter.INTERSECT)));
                break;
            case Transform.XSLT:
                Element element = dbf.newDocumentBuilder().parse(new ByteArrayInputStream(xslt.getBytes())).getDocumentElement();
                DOMStructure stylesheet = new DOMStructure(element);
                params = new XSLTTransformParameterSpec(stylesheet);
                break;
        }
        transformList = Collections.singletonList(fac.newTransform(transform, params));
    }
    String url = String.format("http://localhost:%d/%s", port, contentType);
    List refs = Collections.singletonList(fac.newReference(url, dm, transformList, null, null));
    CanonicalizationMethod cm = fac.newCanonicalizationMethod(canonicalizationMethod, (C14NMethodParameterSpec) null);
    SignatureMethod sm = fac.newSignatureMethod(signatureMethod, null);
    Key signingKey;
    Key validationKey;
    switch(signatureMethod) {
        case SignatureMethod.DSA_SHA1:
        case SignatureMethod.RSA_SHA1:
            KeyPair kp = generateKeyPair(sm);
            validationKey = kp.getPublic();
            signingKey = kp.getPrivate();
            break;
        case SignatureMethod.HMAC_SHA1:
            KeyGenerator kg = KeyGenerator.getInstance("HmacSHA1");
            signingKey = kg.generateKey();
            validationKey = signingKey;
            break;
        default:
            throw new RuntimeException("Unsupported signature algorithm");
    }
    SignedInfo si = fac.newSignedInfo(cm, sm, refs, null);
    // Create KeyInfo
    KeyInfoFactory kif = fac.getKeyInfoFactory();
    List list = null;
    if (keyInfo == KeyInfoType.KeyValue) {
        if (validationKey instanceof PublicKey) {
            KeyValue kv = kif.newKeyValue((PublicKey) validationKey);
            list = Collections.singletonList(kv);
        }
    } else if (keyInfo == KeyInfoType.x509data) {
        list = Collections.singletonList(kif.newX509Data(Collections.singletonList("cn=Test")));
    } else if (keyInfo == KeyInfoType.KeyName) {
        list = Collections.singletonList(kif.newKeyName("Test"));
    } else {
        throw new RuntimeException("Unexpected KeyInfo: " + keyInfo);
    }
    KeyInfo ki = list != null ? kif.newKeyInfo(list) : null;
    // Create an empty doc for detached signature
    Document doc = dbf.newDocumentBuilder().newDocument();
    DOMSignContext xsc = new DOMSignContext(signingKey, doc);
    // Generate signature
    XMLSignature signature = fac.newXMLSignature(si, ki);
    signature.sign(xsc);
    // Save signature
    String signatureString;
    try (StringWriter writer = new StringWriter()) {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer trans = tf.newTransformer();
        Node parent = xsc.getParent();
        trans.transform(new DOMSource(parent), new StreamResult(writer));
        signatureString = writer.toString();
    }
    System.out.print("Validate ... ");
    try (ByteArrayInputStream bis = new ByteArrayInputStream(signatureString.getBytes())) {
        doc = dbf.newDocumentBuilder().parse(bis);
    }
    NodeList nodeLst = doc.getElementsByTagName("Signature");
    Node node = nodeLst.item(0);
    if (node == null) {
        throw new RuntimeException("Couldn't find Signature element");
    }
    if (!(node instanceof Element)) {
        throw new RuntimeException("Unexpected node type");
    }
    Element sig = (Element) node;
    // Validate signature
    DOMValidateContext vc = new DOMValidateContext(validationKey, sig);
    vc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);
    signature = fac.unmarshalXMLSignature(vc);
    boolean success = signature.validate(vc);
    if (!success) {
        System.out.println("Core signature validation failed");
        return false;
    }
    success = signature.getSignatureValue().validate(vc);
    if (!success) {
        System.out.println("Cryptographic validation of signature failed");
        return false;
    }
    return true;
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) DOMValidateContext(javax.xml.crypto.dsig.dom.DOMValidateContext) KeyGenerator(javax.crypto.KeyGenerator) KeyPair(java.security.KeyPair) StreamResult(javax.xml.transform.stream.StreamResult) PublicKey(java.security.PublicKey) DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext) PublicKey(java.security.PublicKey) Key(java.security.Key) PrivateKey(java.security.PrivateKey) SecretKey(javax.crypto.SecretKey)

Example 4 with DOMValidateContext

use of javax.xml.crypto.dsig.dom.DOMValidateContext in project jdk8u_jdk by JetBrains.

the class GenerationTests method test_create_signature_enveloped_dsa.

static void test_create_signature_enveloped_dsa(int size) throws Exception {
    System.out.println("* Generating signature-enveloped-dsa-" + size + ".xml");
    SignatureMethod sm = null;
    KeyInfo ki = null;
    Key privKey;
    if (size == 1024) {
        sm = dsaSha1;
        ki = dsa1024;
        privKey = signingKey;
    } else if (size == 2048) {
        sm = dsaSha256;
        ki = dsa2048;
        privKey = getPrivateKey("DSA", 2048);
    } else
        throw new RuntimeException("unsupported keysize:" + size);
    // create SignedInfo
    SignedInfo si = fac.newSignedInfo(withoutComments, sm, Collections.singletonList(fac.newReference("", sha1, Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null)));
    // create XMLSignature
    XMLSignature sig = fac.newXMLSignature(si, ki);
    Document doc = db.newDocument();
    Element envelope = doc.createElementNS("http://example.org/envelope", "Envelope");
    envelope.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns", "http://example.org/envelope");
    doc.appendChild(envelope);
    DOMSignContext dsc = new DOMSignContext(privKey, envelope);
    sig.sign(dsc);
    //        StringWriter sw = new StringWriter();
    //        dumpDocument(doc, sw);
    //        System.out.println(sw.toString());
    DOMValidateContext dvc = new DOMValidateContext(kvks, envelope.getFirstChild());
    XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);
    if (sig.equals(sig2) == false) {
        throw new Exception("Unmarshalled signature is not equal to generated signature");
    }
    if (sig2.validate(dvc) == false) {
        throw new Exception("Validation of generated signature failed");
    }
    System.out.println();
}
Also used : DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext) DOMValidateContext(javax.xml.crypto.dsig.dom.DOMValidateContext) PublicKey(java.security.PublicKey) Key(java.security.Key) PrivateKey(java.security.PrivateKey) SecretKey(javax.crypto.SecretKey) URIReferenceException(javax.xml.crypto.URIReferenceException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 5 with DOMValidateContext

use of javax.xml.crypto.dsig.dom.DOMValidateContext in project jdk8u_jdk by JetBrains.

the class GenerationTests method test_create_signature_with_attr_in_no_namespace.

static void test_create_signature_with_attr_in_no_namespace() throws Exception {
    System.out.println("* Generating signature-with-attr-in-no-namespace.xml");
    // create references
    List<Reference> refs = Collections.singletonList(fac.newReference("#unknown", sha1));
    // create SignedInfo
    SignedInfo si = fac.newSignedInfo(withoutComments, rsaSha1, refs);
    // create object-1
    Document doc = db.newDocument();
    Element nc = doc.createElementNS(null, "NonCommentandus");
    // add attribute with no namespace
    nc.setAttribute("Id", "unknown");
    XMLObject obj = fac.newXMLObject(Collections.singletonList(new DOMStructure(nc)), "object-1", null, null);
    // create XMLSignature
    XMLSignature sig = fac.newXMLSignature(si, rsa, Collections.singletonList(obj), "signature", null);
    DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA", 512), doc);
    dsc.setIdAttributeNS(nc, null, "Id");
    sig.sign(dsc);
    //      dumpDocument(doc, new PrintWriter(System.out));
    DOMValidateContext dvc = new DOMValidateContext(kvks, doc.getDocumentElement());
    dvc.setIdAttributeNS(nc, null, "Id");
    XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);
    if (sig.equals(sig2) == false) {
        throw new Exception("Unmarshalled signature is not equal to generated signature");
    }
    if (sig2.validate(dvc) == false) {
        throw new Exception("Validation of generated signature failed");
    }
    System.out.println();
}
Also used : URIReference(javax.xml.crypto.URIReference) DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext) DOMValidateContext(javax.xml.crypto.dsig.dom.DOMValidateContext) URIReferenceException(javax.xml.crypto.URIReferenceException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Aggregations

DOMValidateContext (javax.xml.crypto.dsig.dom.DOMValidateContext)15 DOMSignContext (javax.xml.crypto.dsig.dom.DOMSignContext)9 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)8 URIReferenceException (javax.xml.crypto.URIReferenceException)8 URIReference (javax.xml.crypto.URIReference)7 XMLStructure (javax.xml.crypto.XMLStructure)4 XMLSignature (javax.xml.crypto.dsig.XMLSignature)4 NodeList (org.w3c.dom.NodeList)4 XMLSignatureFactory (javax.xml.crypto.dsig.XMLSignatureFactory)3 Key (java.security.Key)2 PrivateKey (java.security.PrivateKey)2 PublicKey (java.security.PublicKey)2 X509Certificate (java.security.cert.X509Certificate)2 SecretKey (javax.crypto.SecretKey)2 KeySelector (javax.xml.crypto.KeySelector)2 Document (org.w3c.dom.Document)2 Element (org.w3c.dom.Element)2 IOException (java.io.IOException)1 BigInteger (java.math.BigInteger)1 KeyPair (java.security.KeyPair)1