Search in sources :

Example 1 with XMLSignature

use of org.apache.xml.security.signature.XMLSignature in project OpenAM by OpenRock.

the class AMSignatureProvider method verifyXMLSignature.

/**
     * Verify the signature of a DOM Document
     * @param doc a DOM Document
     * @param idAttrName Attribute name for the id attribute 
     * @param certAlias certAlias alias for Signer's certificate, this is used
                        to search signer's public certificate if it is not
                        presented in ds:KeyInfo
     * @return true if the xml signature is verified, false otherwise
     * @throws XMLSignatureException if problem occurs during verification
     */
public boolean verifyXMLSignature(Document doc, java.lang.String idAttrName, java.lang.String certAlias) throws XMLSignatureException {
    try {
        Element nscontext = org.apache.xml.security.utils.XMLUtils.createDSctx(doc, "ds", Constants.SignatureSpecNS);
        Element sigElement = (Element) XPathAPI.selectSingleNode(doc, "//ds:Signature[1]", nscontext);
        Element refElement;
        try {
            refElement = (Element) XPathAPI.selectSingleNode(sigElement, "//ds:Reference[1]", nscontext);
        } catch (TransformerException te) {
            throw new XMLSignatureException(te);
        }
        String refUri = refElement.getAttribute("URI");
        String signedId = ((Element) sigElement.getParentNode()).getAttribute(idAttrName);
        if (refUri == null || signedId == null || !refUri.substring(1).equals(signedId)) {
            SAMLUtilsCommon.debug.error("Signature reference ID does not match with element ID");
            throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("uriNoMatchWithId"));
        }
        XMLSignature signature = new XMLSignature(sigElement, "");
        signature.addResourceResolver(new com.sun.identity.saml.xmlsig.OfflineResolver());
        doc.getDocumentElement().setIdAttribute(idAttrName, true);
        KeyInfo ki = signature.getKeyInfo();
        PublicKey pk = this.getX509PublicKey(doc, ki);
        if (pk != null) {
            // verify using public key
            if (signature.checkSignatureValue(pk)) {
                return true;
            } else {
                return false;
            }
        } else {
            if (certAlias == null || certAlias.length() == 0) {
                return false;
            }
            if (SAMLUtilsCommon.debug.messageEnabled()) {
                SAMLUtilsCommon.debug.message("Could not find a KeyInfo, " + "try to use certAlias");
            }
            X509Certificate newcert = keystore.getX509Certificate(certAlias);
            if (newcert != null) {
                if (signature.checkSignatureValue(newcert)) {
                    return true;
                } else {
                    return false;
                }
            } else {
                PublicKey key = keystore.getPublicKey(certAlias);
                if (key != null) {
                    if (signature.checkSignatureValue(key)) {
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    SAMLUtilsCommon.debug.error("Could not find " + "public key based on certAlias to verify" + " signature");
                    return false;
                }
            }
        }
    } catch (Exception ex) {
        SAMLUtilsCommon.debug.error("verifyXMLSignature Exception: ", ex);
        throw new XMLSignatureException(ex.getMessage());
    }
}
Also used : TransformerException(javax.xml.transform.TransformerException) KeyInfo(org.apache.xml.security.keys.KeyInfo) XMLSignature(org.apache.xml.security.signature.XMLSignature) TransformerException(javax.xml.transform.TransformerException)

Example 2 with XMLSignature

use of org.apache.xml.security.signature.XMLSignature in project OpenAM by OpenRock.

the class AMSignatureProvider method signWithWSSSAMLTokenProfile.

/**
     * Sign part of the xml document referered by the supplied a list
     * of id attributes of nodes
     * @param doc XML dom object
     * @param cert Signer's certificate
     * @param assertionID assertion ID
     * @param algorithm XML signature algorithm
     * @param ids list of id attribute values of nodes to be signed
     * @param wsfVersion the web services version.
     * @return SAML Security Token  signature
     * @throws XMLSignatureException if the document could not be signed
     */
public Element signWithWSSSAMLTokenProfile(Document doc, java.security.cert.Certificate cert, String assertionID, String algorithm, List ids, String wsfVersion) throws XMLSignatureException {
    if (doc == null) {
        SAMLUtilsCommon.debug.error("signXML: doc is null.");
        throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("nullInput"));
    }
    if (cert == null) {
        SAMLUtilsCommon.debug.error("signWithWSSSAMLTokenProfile: " + "Certificate is null");
        throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("nullInput"));
    }
    if (assertionID == null) {
        SAMLUtilsCommon.debug.error("signWithWSSSAMLTokenProfile: " + "AssertionID is null");
        throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("nullInput"));
    }
    this.wsfVersion = wsfVersion;
    String wsseNS = SAMLConstants.NS_WSSE;
    String wsuNS = SAMLConstants.NS_WSU;
    if ((wsfVersion != null) && (wsfVersion.equals(SOAPBindingConstants.WSF_11_VERSION))) {
        wsseNS = WSSEConstants.NS_WSSE_WSF11;
        wsuNS = WSSEConstants.NS_WSU_WSF11;
    }
    Element root = (Element) doc.getDocumentElement().getElementsByTagNameNS(wsseNS, SAMLConstants.TAG_SECURITY).item(0);
    XMLSignature signature = null;
    try {
        ElementProxy.setDefaultPrefix(Constants.SignatureSpecNS, SAMLConstants.PREFIX_DS);
        Element wsucontext = org.apache.xml.security.utils.XMLUtils.createDSctx(doc, "wsu", wsuNS);
        NodeList wsuNodes = (NodeList) XPathAPI.selectNodeList(doc, "//*[@wsu:Id]", wsucontext);
        if (wsuNodes != null && wsuNodes.getLength() != 0) {
            for (int i = 0; i < wsuNodes.getLength(); i++) {
                Element elem = (Element) wsuNodes.item(i);
                String id = elem.getAttributeNS(wsuNS, "Id");
                if (id != null && id.length() != 0) {
                    elem.setIdAttributeNS(wsuNS, "Id", true);
                }
            }
        }
        String certAlias = keystore.getCertificateAlias(cert);
        PrivateKey privateKey = (PrivateKey) keystore.getPrivateKey(certAlias);
        if (privateKey == null) {
            SAMLUtilsCommon.debug.error("private key is null");
            throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("nullprivatekey"));
        }
        if (algorithm == null || algorithm.length() == 0) {
            algorithm = getKeyAlgorithm(privateKey);
        }
        if (!isValidAlgorithm(algorithm)) {
            throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("invalidalgorithm"));
        }
        signature = new XMLSignature(doc, "", algorithm, Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
        root.appendChild(signature.getElement());
        int size = ids.size();
        for (int i = 0; i < size; ++i) {
            Transforms transforms = new Transforms(doc);
            transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
            String id = (String) ids.get(i);
            if (SAMLUtilsCommon.debug.messageEnabled()) {
                SAMLUtilsCommon.debug.message("id = " + id);
            }
            signature.addDocument("#" + id, transforms, Constants.ALGO_ID_DIGEST_SHA1);
        }
        KeyInfo keyInfo = signature.getKeyInfo();
        Element securityTokenRef = doc.createElementNS(wsseNS, SAMLConstants.TAG_SECURITYTOKENREFERENCE);
        keyInfo.addUnknownElement(securityTokenRef);
        securityTokenRef.setAttributeNS(SAMLConstants.NS_XMLNS, SAMLConstants.TAG_XMLNS, wsseNS);
        securityTokenRef.setAttributeNS(SAMLConstants.NS_XMLNS, SAMLConstants.TAG_XMLNS_SEC, SAMLConstants.NS_SEC);
        securityTokenRef.setAttributeNS(null, SAMLConstants.TAG_USAGE, SAMLConstants.TAG_SEC_MESSAGEAUTHENTICATION);
        Element reference = doc.createElementNS(wsseNS, SAMLConstants.TAG_REFERENCE);
        reference.setAttributeNS(null, SAMLConstants.TAG_URI, "#" + assertionID);
        securityTokenRef.appendChild(reference);
        signature.sign(privateKey);
    } catch (Exception e) {
        SAMLUtilsCommon.debug.error("signWithWSSX509TokenProfile " + "Exception: ", e);
        throw new XMLSignatureException(e.getMessage());
    }
    if (SAMLUtilsCommon.debug.messageEnabled()) {
        SAMLUtilsCommon.debug.message("SAML Signed doc = " + XMLUtils.print(doc.getDocumentElement()));
    }
    return signature.getElement();
}
Also used : KeyInfo(org.apache.xml.security.keys.KeyInfo) XMLSignature(org.apache.xml.security.signature.XMLSignature) Transforms(org.apache.xml.security.transforms.Transforms) TransformerException(javax.xml.transform.TransformerException)

Example 3 with XMLSignature

use of org.apache.xml.security.signature.XMLSignature in project OpenAM by OpenRock.

the class WSFederationMetaSecurityUtils method verifySignature.

/**
     * Verifies signatures in entity descriptor represented by the 
     * <code>Document</code>.
     * @param doc The document.
     * @throws WSFederationMetaException if unable to verify the entity 
     * descriptor. 
     */
public static void verifySignature(Document doc) throws WSFederationMetaException {
    String classMethod = "WSFederationMetaSecurityUtils.verifySignature: ";
    NodeList sigElements = null;
    try {
        Element nscontext = org.apache.xml.security.utils.XMLUtils.createDSctx(doc, "ds", Constants.SignatureSpecNS);
        sigElements = XPathAPI.selectNodeList(doc, "//ds:Signature", nscontext);
    } catch (Exception ex) {
        debug.error(classMethod, ex);
        throw new WSFederationMetaException(ex);
    }
    int numSigs = sigElements.getLength();
    if (debug.messageEnabled()) {
        debug.message(classMethod + "# of signatures = " + numSigs);
    }
    if (numSigs == 0) {
        return;
    }
    initializeKeyStore();
    for (int i = 0; i < numSigs; i++) {
        Element sigElement = (Element) sigElements.item(i);
        String sigParentName = sigElement.getParentNode().getLocalName();
        Object[] objs = { sigParentName };
        if (debug.messageEnabled()) {
            debug.message(classMethod + "verifying signature under " + sigParentName);
        }
        try {
            XMLSignature signature = new XMLSignature(sigElement, "");
            signature.addResourceResolver(new com.sun.identity.saml.xmlsig.OfflineResolver());
            KeyInfo ki = signature.getKeyInfo();
            X509Certificate x509cert = null;
            if (ki != null && ki.containsX509Data()) {
                if (keyStore != null) {
                    StorageResolver sr = new StorageResolver(new KeyStoreResolver(keyStore));
                    ki.addStorageResolver(sr);
                }
                x509cert = ki.getX509Certificate();
            }
            if (x509cert == null) {
                if (debug.messageEnabled()) {
                    debug.message(classMethod + "" + "try to find cert in KeyDescriptor");
                }
                String xpath = "following-sibling::*[local-name()=\"" + TAG_KEY_DESCRIPTOR + "\" and namespace-uri()=\"" + NS_META + "\"]";
                Node node = XPathAPI.selectSingleNode(sigElement, xpath);
                if (node != null) {
                    Element kd = (Element) node;
                    String use = kd.getAttributeNS(null, ATTR_USE);
                    if (use.equals("signing")) {
                        NodeList nl = kd.getChildNodes();
                        for (int j = 0; j < nl.getLength(); j++) {
                            Node child = nl.item(j);
                            if (child.getNodeType() == Node.ELEMENT_NODE) {
                                String localName = child.getLocalName();
                                String ns = child.getNamespaceURI();
                                if (TAG_KEY_INFO.equals(localName) && NS_XMLSIG.equals(ns)) {
                                    ki = new KeyInfo((Element) child, "");
                                    if (ki.containsX509Data()) {
                                        if (keyStore != null) {
                                            KeyStoreResolver ksr = new KeyStoreResolver(keyStore);
                                            StorageResolver sr = new StorageResolver(ksr);
                                            ki.addStorageResolver(sr);
                                        }
                                        x509cert = ki.getX509Certificate();
                                    }
                                }
                                break;
                            }
                        }
                    }
                }
            }
            if (x509cert == null) {
                throw new WSFederationMetaException("verify_no_cert", objs);
            }
            if (checkCert && ((keyProvider == null) || (keyProvider.getCertificateAlias(x509cert) == null))) {
                throw new WSFederationMetaException("untrusted_cert", objs);
            }
            PublicKey pk = x509cert.getPublicKey();
            if (!signature.checkSignatureValue(pk)) {
                throw new WSFederationMetaException("verify_fail", objs);
            }
        } catch (WSFederationMetaException sme) {
            throw sme;
        } catch (Exception ex) {
            debug.error(classMethod, ex);
            throw new WSFederationMetaException(Locale.getString(WSFederationMetaUtils.bundle, "verify_fail", objs) + "\n" + ex.getMessage());
        }
    }
}
Also used : StorageResolver(org.apache.xml.security.keys.storage.StorageResolver) PublicKey(java.security.PublicKey) NodeList(org.w3c.dom.NodeList) IDPSSOConfigElement(com.sun.identity.wsfederation.jaxb.entityconfig.IDPSSOConfigElement) FederationConfigElement(com.sun.identity.wsfederation.jaxb.entityconfig.FederationConfigElement) FederationElement(com.sun.identity.wsfederation.jaxb.wsfederation.FederationElement) SPSSOConfigElement(com.sun.identity.wsfederation.jaxb.entityconfig.SPSSOConfigElement) Element(org.w3c.dom.Element) TokenSigningKeyInfoElement(com.sun.identity.wsfederation.jaxb.wsfederation.TokenSigningKeyInfoElement) Node(org.w3c.dom.Node) JAXBException(javax.xml.bind.JAXBException) X509Certificate(java.security.cert.X509Certificate) KeyStoreResolver(org.apache.xml.security.keys.storage.implementations.KeyStoreResolver) KeyInfo(org.apache.xml.security.keys.KeyInfo) XMLSignature(org.apache.xml.security.signature.XMLSignature)

Example 4 with XMLSignature

use of org.apache.xml.security.signature.XMLSignature in project OpenAM by OpenRock.

the class FMSigProvider method verify.

public boolean verify(String xmlString, String idValue, Set<X509Certificate> verificationCerts) throws SAML2Exception {
    String classMethod = "FMSigProvider.verify: ";
    if (xmlString == null || xmlString.length() == 0 || idValue == null || idValue.length() == 0) {
        SAML2SDKUtils.debug.error(classMethod + "Either input xmlString or idValue is null.");
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("nullInput"));
    }
    Document doc = XMLUtils.toDOMDocument(xmlString, SAML2SDKUtils.debug);
    if (doc == null) {
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("errorObtainingElement"));
    }
    Element nscontext = org.apache.xml.security.utils.XMLUtils.createDSctx(doc, "ds", Constants.SignatureSpecNS);
    Element sigElement = null;
    try {
        sigElement = (Element) org.apache.xpath.XPathAPI.selectSingleNode(doc, "//ds:Signature[1]", nscontext);
    } catch (TransformerException te) {
        throw new SAML2Exception(te);
    }
    Element refElement;
    try {
        refElement = (Element) XPathAPI.selectSingleNode(doc, "//ds:Reference[1]", nscontext);
    } catch (TransformerException te) {
        throw new SAML2Exception(te);
    }
    String refUri = refElement.getAttribute("URI");
    String signedId = ((Element) sigElement.getParentNode()).getAttribute(SAML2Constants.ID);
    if (refUri == null || signedId == null || !refUri.substring(1).equals(signedId)) {
        SAML2SDKUtils.debug.error(classMethod + "Signature reference ID does " + "not match with element ID");
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("uriNoMatchWithId"));
    }
    doc.getDocumentElement().setIdAttribute(SAML2Constants.ID, true);
    XMLSignature signature = null;
    try {
        signature = new XMLSignature((Element) sigElement, "");
    } catch (XMLSignatureException sige) {
        throw new SAML2Exception(sige);
    } catch (XMLSecurityException xse) {
        throw new SAML2Exception(xse);
    }
    signature.addResourceResolver(new com.sun.identity.saml.xmlsig.OfflineResolver());
    KeyInfo ki = signature.getKeyInfo();
    X509Certificate certToUse = null;
    if (ki != null && ki.containsX509Data()) {
        try {
            certToUse = ki.getX509Certificate();
        } catch (KeyResolverException kre) {
            SAML2SDKUtils.debug.error(classMethod + "Could not obtain a certificate " + "from inside the document.");
            certToUse = null;
        }
        if (certToUse != null && checkCert) {
            if (!verificationCerts.contains(certToUse)) {
                SAML2SDKUtils.debug.error(classMethod + "The cert contained in the document is NOT trusted");
                throw new SAML2Exception(SAML2SDKUtils.bundle.getString("invalidCertificate"));
            }
            if (SAML2SDKUtils.debug.messageEnabled()) {
                SAML2SDKUtils.debug.message(classMethod + "The cert contained in the document is trusted");
            }
        }
    }
    if (certToUse != null) {
        verificationCerts = Collections.singleton(certToUse);
    }
    if (!isValidSignature(signature, verificationCerts)) {
        SAML2SDKUtils.debug.error(classMethod + "Signature verification failed.");
        return false;
    }
    if (SAML2SDKUtils.debug.messageEnabled()) {
        SAML2SDKUtils.debug.message(classMethod + "Signature verification successful.");
    }
    return true;
}
Also used : Element(org.w3c.dom.Element) KeyResolverException(org.apache.xml.security.keys.keyresolver.KeyResolverException) Document(org.w3c.dom.Document) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException) X509Certificate(java.security.cert.X509Certificate) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) KeyInfo(org.apache.xml.security.keys.KeyInfo) XMLSignature(org.apache.xml.security.signature.XMLSignature) XMLSignatureException(org.apache.xml.security.signature.XMLSignatureException) TransformerException(javax.xml.transform.TransformerException)

Example 5 with XMLSignature

use of org.apache.xml.security.signature.XMLSignature in project xades4j by luisgoncalves.

the class KeyInfoBuilderTest method testIncludeCertAndKey.

@Test
public void testIncludeCertAndKey() throws Exception {
    System.out.println("includeCertAndKey");
    KeyInfoBuilder keyInfoBuilder = new KeyInfoBuilder(new TestBasicSignatureOptionsProvider(true, true, false), new TestAlgorithmsProvider(), new TestAlgorithmsParametersMarshallingProvider());
    XMLSignature xmlSignature = getTestSignature();
    keyInfoBuilder.buildKeyInfo(testCertificate, xmlSignature);
    Assert.assertEquals(0, xmlSignature.getSignedInfo().getLength());
    KeyValue kv = xmlSignature.getKeyInfo().itemKeyValue(0);
    Assert.assertTrue(kv.getPublicKey().getAlgorithm().startsWith("RSA"));
    XMLX509Certificate x509Certificate = xmlSignature.getKeyInfo().itemX509Data(0).itemCertificate(0);
    Assert.assertEquals(testCertificate, x509Certificate.getX509Certificate());
}
Also used : XMLX509Certificate(org.apache.xml.security.keys.content.x509.XMLX509Certificate) KeyValue(org.apache.xml.security.keys.content.KeyValue) XMLSignature(org.apache.xml.security.signature.XMLSignature) Test(org.junit.Test)

Aggregations

XMLSignature (org.apache.xml.security.signature.XMLSignature)132 Document (org.w3c.dom.Document)91 Element (org.w3c.dom.Element)69 X509Certificate (java.security.cert.X509Certificate)60 Test (org.junit.Test)55 DocumentBuilder (javax.xml.parsers.DocumentBuilder)52 InputStream (java.io.InputStream)51 ByteArrayInputStream (java.io.ByteArrayInputStream)50 ByteArrayOutputStream (java.io.ByteArrayOutputStream)49 KeyStore (java.security.KeyStore)48 ArrayList (java.util.ArrayList)48 XMLStreamReader (javax.xml.stream.XMLStreamReader)43 Key (java.security.Key)42 DOMSource (javax.xml.transform.dom.DOMSource)42 StreamResult (javax.xml.transform.stream.StreamResult)42 Transforms (org.apache.xml.security.transforms.Transforms)29 SecretKey (javax.crypto.SecretKey)28 XPath (javax.xml.xpath.XPath)23 KeyInfo (org.apache.xml.security.keys.KeyInfo)22 XPathFactory (javax.xml.xpath.XPathFactory)19