Search in sources :

Example 1 with XMLSecurityException

use of org.apache.xml.security.exceptions.XMLSecurityException 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 2 with XMLSecurityException

use of org.apache.xml.security.exceptions.XMLSecurityException in project OpenAM by OpenRock.

the class FMSigProvider method sign.

/**
     * Sign the xml document node whose identifying attribute value
     * is as supplied, using enveloped signatures and use exclusive xml
     * canonicalization. The resulting signature is inserted after the
     * first child node (normally Issuer element for SAML2) of the node
     * to be signed.
     * @param xmlString String representing an XML document to be signed
     * @param idValue id attribute value of the root node to be signed
     * @param privateKey Signing key
     * @param cert Certificate which contain the public key correlated to
     *             the signing key; It if is not null, then the signature
     *             will include the certificate; Otherwise, the signature
     *             will not include any certificate
     * @return Element representing the signature element
     * @throws SAML2Exception if the document could not be signed
     */
public Element sign(String xmlString, String idValue, PrivateKey privateKey, X509Certificate cert) throws SAML2Exception {
    String classMethod = "FMSigProvider.sign: ";
    if (xmlString == null || xmlString.length() == 0 || idValue == null || idValue.length() == 0 || privateKey == null) {
        SAML2SDKUtils.debug.error(classMethod + "Either input xml string or id value or " + "private key 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 root = doc.getDocumentElement();
    XMLSignature sig = null;
    try {
        ElementProxy.setDefaultPrefix(Constants.SignatureSpecNS, SAMLConstants.PREFIX_DS);
    } catch (XMLSecurityException xse1) {
        throw new SAML2Exception(xse1);
    }
    root.setIdAttribute(SAML2Constants.ID, true);
    try {
        if ((sigAlg == null) || (sigAlg.trim().length() == 0)) {
            if (privateKey.getAlgorithm().equalsIgnoreCase(SAML2Constants.DSA)) {
                sigAlg = XMLSignature.ALGO_ID_SIGNATURE_DSA;
            } else {
                if (privateKey.getAlgorithm().equalsIgnoreCase(SAML2Constants.RSA)) {
                    sigAlg = XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1;
                }
            }
        }
        sig = new XMLSignature(doc, "", sigAlg, c14nMethod);
    } catch (XMLSecurityException xse2) {
        throw new SAML2Exception(xse2);
    }
    Node firstChild = root.getFirstChild();
    while (firstChild != null && (firstChild.getLocalName() == null || !firstChild.getLocalName().equals("Issuer"))) {
        firstChild = firstChild.getNextSibling();
    }
    Node nextSibling = null;
    if (firstChild != null) {
        nextSibling = firstChild.getNextSibling();
    }
    if (nextSibling == null) {
        root.appendChild(sig.getElement());
    } else {
        root.insertBefore(sig.getElement(), nextSibling);
    }
    sig.getSignedInfo().addResourceResolver(new com.sun.identity.saml.xmlsig.OfflineResolver());
    Transforms transforms = new Transforms(doc);
    try {
        transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
    } catch (TransformationException te1) {
        throw new SAML2Exception(te1);
    }
    try {
        transforms.addTransform(transformAlg);
    } catch (TransformationException te2) {
        throw new SAML2Exception(te2);
    }
    String ref = "#" + idValue;
    try {
        sig.addDocument(ref, transforms, Constants.ALGO_ID_DIGEST_SHA1);
    } catch (XMLSignatureException sige1) {
        throw new SAML2Exception(sige1);
    }
    if (cert != null) {
        try {
            sig.addKeyInfo(cert);
        } catch (XMLSecurityException xse3) {
            throw new SAML2Exception(xse3);
        }
    }
    try {
        sig.sign(privateKey);
    } catch (XMLSignatureException sige2) {
        throw new SAML2Exception(sige2);
    }
    if (SAML2SDKUtils.debug.messageEnabled()) {
        SAML2SDKUtils.debug.message(classMethod + "Signing is successful.");
    }
    return sig.getElement();
}
Also used : TransformationException(org.apache.xml.security.transforms.TransformationException) Element(org.w3c.dom.Element) Node(org.w3c.dom.Node) Transforms(org.apache.xml.security.transforms.Transforms) Document(org.w3c.dom.Document) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) XMLSignature(org.apache.xml.security.signature.XMLSignature) XMLSignatureException(org.apache.xml.security.signature.XMLSignatureException)

Example 3 with XMLSecurityException

use of org.apache.xml.security.exceptions.XMLSecurityException in project OpenAM by OpenRock.

the class SecurityUtils method getPublicKey.

/**
     * Returns the <code>PublicKey</code>.
     */
private static PublicKey getPublicKey(Element reference) throws XMLSignatureException {
    PublicKey pubKey = null;
    Document doc = reference.getOwnerDocument();
    Element dsaKey = (Element) reference.getElementsByTagNameNS(Constants.SignatureSpecNS, SAMLConstants.TAG_DSAKEYVALUE).item(0);
    if (dsaKey != null) {
        // It's DSAKey
        NodeList nodes = dsaKey.getChildNodes();
        int nodeCount = nodes.getLength();
        if (nodeCount > 0) {
            BigInteger p = null, q = null, g = null, y = null;
            for (int i = 0; i < nodeCount; i++) {
                Node currentNode = nodes.item(i);
                if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
                    String tagName = currentNode.getLocalName();
                    Node sub = currentNode.getChildNodes().item(0);
                    String value = sub.getNodeValue();
                    value = SAMLUtils.removeNewLineChars(value);
                    BigInteger v = new BigInteger(Base64.decode(value));
                    if (tagName.equals("P")) {
                        p = v;
                    } else if (tagName.equals("Q")) {
                        q = v;
                    } else if (tagName.equals("G")) {
                        g = v;
                    } else if (tagName.equals("Y")) {
                        y = v;
                    } else {
                        SAMLUtils.debug.error("Wrong tag name in DSA key.");
                        throw new XMLSignatureException(SAMLUtils.bundle.getString("errorObtainPK"));
                    }
                }
            }
            DSAKeyValue dsaKeyValue = new DSAKeyValue(doc, p, q, g, y);
            try {
                pubKey = dsaKeyValue.getPublicKey();
            } catch (XMLSecurityException xse) {
                SAMLUtils.debug.error("Could not get Public Key from" + " DSA key value.");
                throw new XMLSignatureException(SAMLUtils.bundle.getString("errorObtainPK"));
            }
        }
    } else {
        Element rsaKey = (Element) reference.getElementsByTagNameNS(Constants.SignatureSpecNS, SAMLConstants.TAG_RSAKEYVALUE).item(0);
        if (rsaKey != null) {
            // It's RSAKey
            NodeList nodes = rsaKey.getChildNodes();
            int nodeCount = nodes.getLength();
            BigInteger m = null, e = null;
            if (nodeCount > 0) {
                for (int i = 0; i < nodeCount; i++) {
                    Node currentNode = nodes.item(i);
                    if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
                        String tagName = currentNode.getLocalName();
                        Node sub = currentNode.getChildNodes().item(0);
                        String value = sub.getNodeValue();
                        value = SAMLUtils.removeNewLineChars(value);
                        BigInteger v = new BigInteger(Base64.decode(value));
                        if (tagName.equals("Exponent")) {
                            e = v;
                        } else if (tagName.equals("Modulus")) {
                            m = v;
                        } else {
                            SAMLUtils.debug.error("Wrong tag name from " + "RSA key element.");
                            throw new XMLSignatureException(SAMLUtils.bundle.getString("errorObtainPK"));
                        }
                    }
                }
            }
            RSAKeyValue rsaKeyValue = new RSAKeyValue(doc, m, e);
            try {
                pubKey = rsaKeyValue.getPublicKey();
            } catch (XMLSecurityException ex) {
                SAMLUtils.debug.error("Could not get Public Key from" + " RSA key value.");
                throw new XMLSignatureException(SAMLUtils.bundle.getString("errorObtainPK"));
            }
        }
    }
    return pubKey;
}
Also used : RSAKeyValue(org.apache.xml.security.keys.content.keyvalues.RSAKeyValue) DSAKeyValue(org.apache.xml.security.keys.content.keyvalues.DSAKeyValue) PublicKey(java.security.PublicKey) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) BigInteger(java.math.BigInteger) Document(org.w3c.dom.Document) XMLSignatureException(com.sun.identity.saml.xmlsig.XMLSignatureException) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException)

Example 4 with XMLSecurityException

use of org.apache.xml.security.exceptions.XMLSecurityException in project OpenAM by OpenRock.

the class DefaultSubjectProvider method getHoKSubjectConfirmationData.

private SubjectConfirmationData getHoKSubjectConfirmationData(X509Certificate certificate) throws TokenCreationException {
    Element keyInfoElement;
    try {
        keyInfoElement = keyInfoFactory.generatePublicKeyInfo(certificate);
    } catch (ParserConfigurationException e) {
        throw new TokenCreationException(ResourceException.INTERNAL_ERROR, "Exception caught generating KeyInfo for HoK SubjectConfirmation DefaultSubjectProvider: " + e, e);
    } catch (XMLSecurityException e) {
        throw new TokenCreationException(ResourceException.INTERNAL_ERROR, "Exception caught generating KeyInfo for HoK SubjectConfirmation DefaultSubjectProvider: " + e, e);
    }
    try {
        final List<Element> elementList = new ArrayList<Element>();
        elementList.add(keyInfoElement);
        final SubjectConfirmationData subjectConfirmationData = AssertionFactory.getInstance().createSubjectConfirmationData();
        subjectConfirmationData.setContentType(KEY_INFO_CONFIRMATION_DATA_TYPE);
        subjectConfirmationData.setContent(elementList);
        return subjectConfirmationData;
    } catch (SAML2Exception e) {
        throw new TokenCreationException(ResourceException.INTERNAL_ERROR, "Exception caught generating SubjectConfirmationData with HoK KeyInfo element in DefaultSubjectProvider: " + e, e);
    }
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SubjectConfirmationData(com.sun.identity.saml2.assertion.SubjectConfirmationData) TokenCreationException(org.forgerock.openam.sts.TokenCreationException) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException)

Example 5 with XMLSecurityException

use of org.apache.xml.security.exceptions.XMLSecurityException in project ddf by codice.

the class X509PathTokenValidator method validateToken.

/**
     * Validate a Token using the given TokenValidatorParameters.
     *
     * @param tokenParameters
     * @return TokenValidatorResponse
     */
public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
    LOGGER.trace("Validating X.509 Token");
    STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();
    Crypto sigCrypto = stsProperties.getSignatureCrypto();
    CallbackHandler callbackHandler = stsProperties.getCallbackHandler();
    RequestData requestData = new RequestData();
    requestData.setSigVerCrypto(sigCrypto);
    requestData.setWssConfig(WSSConfig.getNewInstance());
    requestData.setCallbackHandler(callbackHandler);
    requestData.setMsgContext(tokenParameters.getMessageContext());
    requestData.setSubjectCertConstraints(certConstraints.getCompiledSubjectContraints());
    TokenValidatorResponse response = new TokenValidatorResponse();
    ReceivedToken validateTarget = tokenParameters.getToken();
    validateTarget.setState(STATE.INVALID);
    response.setToken(validateTarget);
    BinarySecurity binarySecurity = null;
    BinarySecurityTokenType binarySecurityType = null;
    if (validateTarget.isBinarySecurityToken()) {
        binarySecurityType = (BinarySecurityTokenType) validateTarget.getToken();
        // Test the encoding type
        String encodingType = binarySecurityType.getEncodingType();
        if (!BASE64_ENCODING.equals(encodingType)) {
            LOGGER.trace("Bad encoding type attribute specified: {}", encodingType);
            return response;
        }
        //
        // Turn the received JAXB object into a DOM element
        //
        Document doc = DOMUtils.createDocument();
        binarySecurity = new X509Security(doc);
        binarySecurity.setEncodingType(encodingType);
        binarySecurity.setValueType(binarySecurityType.getValueType());
        String data = binarySecurityType.getValue();
        Node textNode = doc.createTextNode(data);
        binarySecurity.getElement().appendChild(textNode);
    } else if (validateTarget.isDOMElement()) {
        try {
            Document doc = DOMUtils.createDocument();
            binarySecurity = new X509Security(doc);
            binarySecurity.setEncodingType(BASE64_ENCODING);
            X509Data x509Data = new X509Data((Element) validateTarget.getToken(), "");
            if (x509Data.containsCertificate()) {
                XMLX509Certificate xmlx509Certificate = x509Data.itemCertificate(0);
                if (xmlx509Certificate == null) {
                    throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY_TOKEN);
                }
                X509Certificate cert = xmlx509Certificate.getX509Certificate();
                ((X509Security) binarySecurity).setX509Certificate(cert);
            }
        } catch (WSSecurityException ex) {
            LOGGER.debug("Unable to set certificate", ex);
            return response;
        } catch (XMLSecurityException ex) {
            LOGGER.debug("Unable to get certificates", ex);
            return response;
        }
    } else {
        return response;
    }
    //
    try {
        Credential credential = new Credential();
        credential.setBinarySecurityToken(binarySecurity);
        if (merlin != null) {
            byte[] token = binarySecurity.getToken();
            if (token != null) {
                if (binarySecurityType != null) {
                    if (binarySecurityType.getValueType().equals(X509_PKI_PATH)) {
                        X509Certificate[] certificates = merlin.getCertificatesFromBytes(token);
                        if (certificates != null) {
                            credential.setCertificates(certificates);
                        }
                    } else {
                        X509Certificate singleCert = merlin.loadCertificate(new ByteArrayInputStream(token));
                        credential.setCertificates(new X509Certificate[] { singleCert });
                    }
                }
            } else {
                LOGGER.debug("Binary Security Token bytes were null.");
            }
        }
        Credential returnedCredential = validator.validate(credential, requestData);
        X500Principal subjectX500Principal = returnedCredential.getCertificates()[0].getSubjectX500Principal();
        response.setPrincipal(subjectX500Principal);
        if (response.getAdditionalProperties() == null) {
            response.setAdditionalProperties(new HashMap<>());
        }
        try {
            String emailAddress = SubjectUtils.getEmailAddress(subjectX500Principal);
            if (emailAddress != null) {
                response.getAdditionalProperties().put(SubjectUtils.EMAIL_ADDRESS_CLAIM_URI, emailAddress);
            }
            String country = SubjectUtils.getCountry(subjectX500Principal);
            if (country != null) {
                response.getAdditionalProperties().put(SubjectUtils.COUNTRY_CLAIM_URI, country);
            }
        } catch (Exception e) {
            LOGGER.debug("Unable to set email address or country from certificate.", e);
        }
        validateTarget.setState(STATE.VALID);
        validateTarget.setPrincipal(subjectX500Principal);
    } catch (WSSecurityException ex) {
        LOGGER.debug("Unable to validate credentials.", ex);
    }
    return response;
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) Document(org.w3c.dom.Document) X509Data(org.apache.xml.security.keys.content.X509Data) BinarySecurityTokenType(org.apache.cxf.ws.security.sts.provider.model.secext.BinarySecurityTokenType) RequestData(org.apache.wss4j.dom.handler.RequestData) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken) X509Security(org.apache.wss4j.common.token.X509Security) Credential(org.apache.wss4j.dom.validate.Credential) BinarySecurity(org.apache.wss4j.common.token.BinarySecurity) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) X509Certificate(java.security.cert.X509Certificate) XMLX509Certificate(org.apache.xml.security.keys.content.x509.XMLX509Certificate) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) IOException(java.io.IOException) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException) XMLX509Certificate(org.apache.xml.security.keys.content.x509.XMLX509Certificate) Crypto(org.apache.wss4j.common.crypto.Crypto) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) ByteArrayInputStream(java.io.ByteArrayInputStream) X500Principal(javax.security.auth.x500.X500Principal) TokenValidatorResponse(org.apache.cxf.sts.token.validator.TokenValidatorResponse)

Aggregations

XMLSecurityException (org.apache.xml.security.exceptions.XMLSecurityException)5 Element (org.w3c.dom.Element)5 Document (org.w3c.dom.Document)4 SAML2Exception (com.sun.identity.saml2.common.SAML2Exception)3 Node (org.w3c.dom.Node)3 X509Certificate (java.security.cert.X509Certificate)2 XMLSignature (org.apache.xml.security.signature.XMLSignature)2 XMLSignatureException (org.apache.xml.security.signature.XMLSignatureException)2 XMLSignatureException (com.sun.identity.saml.xmlsig.XMLSignatureException)1 SubjectConfirmationData (com.sun.identity.saml2.assertion.SubjectConfirmationData)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 IOException (java.io.IOException)1 BigInteger (java.math.BigInteger)1 PublicKey (java.security.PublicKey)1 ArrayList (java.util.ArrayList)1 CallbackHandler (javax.security.auth.callback.CallbackHandler)1 X500Principal (javax.security.auth.x500.X500Principal)1 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)1 TransformerException (javax.xml.transform.TransformerException)1 STSPropertiesMBean (org.apache.cxf.sts.STSPropertiesMBean)1