Search in sources :

Example 1 with KeyInfo

use of org.apache.xml.security.keys.KeyInfo 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 KeyInfo

use of org.apache.xml.security.keys.KeyInfo 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 KeyInfo

use of org.apache.xml.security.keys.KeyInfo 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 KeyInfo

use of org.apache.xml.security.keys.KeyInfo 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 KeyInfo

use of org.apache.xml.security.keys.KeyInfo in project OpenAM by OpenRock.

the class KeyInfoFactoryImpl method generatePublicKeyInfo.

/*
    This method modeled after the example here:
    https://svn.apache.org/repos/asf/santuario/xml-security-java/trunk/samples/org/apache/xml/security/samples/keys/CreateKeyInfo.java
     */
@Override
public Element generatePublicKeyInfo(X509Certificate recipientCert) throws ParserConfigurationException, XMLSecurityException {
    Document sharedDocument = xmlUtilities.newSafeDocument(XMLUtils.isValidating());
    KeyInfo keyInfo = new KeyInfo(sharedDocument);
    sharedDocument.appendChild(keyInfo.getElement());
    X509Data x509Data = new X509Data(sharedDocument);
    keyInfo.add(x509Data);
    x509Data.addCertificate(recipientCert);
    return keyInfo.getElement();
}
Also used : KeyInfo(org.apache.xml.security.keys.KeyInfo) Document(org.w3c.dom.Document) X509Data(org.apache.xml.security.keys.content.X509Data)

Aggregations

KeyInfo (org.apache.xml.security.keys.KeyInfo)10 XMLSignature (org.apache.xml.security.signature.XMLSignature)7 TransformerException (javax.xml.transform.TransformerException)5 Element (org.w3c.dom.Element)4 PublicKey (java.security.PublicKey)3 X509Certificate (java.security.cert.X509Certificate)3 Document (org.w3c.dom.Document)3 Node (org.w3c.dom.Node)3 JAXBException (javax.xml.bind.JAXBException)2 EncryptedData (org.apache.xml.security.encryption.EncryptedData)2 EncryptedKey (org.apache.xml.security.encryption.EncryptedKey)2 X509Data (org.apache.xml.security.keys.content.X509Data)2 StorageResolver (org.apache.xml.security.keys.storage.StorageResolver)2 KeyStoreResolver (org.apache.xml.security.keys.storage.implementations.KeyStoreResolver)2 Transforms (org.apache.xml.security.transforms.Transforms)2 NodeList (org.w3c.dom.NodeList)2 XMLSignatureException (com.sun.identity.saml.xmlsig.XMLSignatureException)1 SAML2Exception (com.sun.identity.saml2.common.SAML2Exception)1 EntityConfigElement (com.sun.identity.saml2.jaxb.entityconfig.EntityConfigElement)1 IDPSSOConfigElement (com.sun.identity.saml2.jaxb.entityconfig.IDPSSOConfigElement)1