Search in sources :

Example 1 with CryptoLoader

use of org.apache.cxf.rs.security.common.CryptoLoader in project cxf by apache.

the class XmlEncOutInterceptor method encryptDocument.

protected Document encryptDocument(Message message, Document payloadDoc) throws Exception {
    String symEncAlgo = encProps.getEncryptionSymmetricKeyAlgo() == null ? XMLCipher.AES_256 : encProps.getEncryptionSymmetricKeyAlgo();
    byte[] secretKey = getSymmetricKey(symEncAlgo);
    Document encryptedDataDoc = DOMUtils.createDocument();
    Element encryptedDataElement = createEncryptedDataElement(encryptedDataDoc, symEncAlgo);
    if (encryptSymmetricKey) {
        X509Certificate receiverCert;
        String userName = (String) SecurityUtils.getSecurityPropertyValue(SecurityConstants.ENCRYPT_USERNAME, message);
        if (RSSecurityUtils.USE_REQUEST_SIGNATURE_CERT.equals(userName) && !MessageUtils.isRequestor(message)) {
            receiverCert = (X509Certificate) message.getExchange().getInMessage().get(AbstractXmlSecInHandler.SIGNING_CERT);
            if (receiverCert == null) {
                receiverCert = (X509Certificate) message.getExchange().getInMessage().get(SecurityConstants.ENCRYPT_CERT);
            }
        } else {
            CryptoLoader loader = new CryptoLoader();
            Crypto crypto = loader.getCrypto(message, SecurityConstants.ENCRYPT_CRYPTO, SecurityConstants.ENCRYPT_PROPERTIES);
            userName = RSSecurityUtils.getUserName(crypto, userName);
            if (StringUtils.isEmpty(userName)) {
                throw new Exception("User name is not available");
            }
            receiverCert = getReceiverCertificateFromCrypto(crypto, userName);
        }
        if (receiverCert == null) {
            throw new Exception("Receiver certificate is not available");
        }
        String keyEncAlgo = encProps.getEncryptionKeyTransportAlgo() == null ? XMLCipher.RSA_OAEP : encProps.getEncryptionKeyTransportAlgo();
        String digestAlgo = encProps.getEncryptionDigestAlgo();
        byte[] encryptedSecretKey = encryptSymmetricKey(secretKey, receiverCert, keyEncAlgo, digestAlgo);
        addEncryptedKeyElement(encryptedDataElement, receiverCert, encryptedSecretKey, keyEncAlgo, digestAlgo);
    }
    // encrypt payloadDoc
    XMLCipher xmlCipher = EncryptionUtils.initXMLCipher(symEncAlgo, XMLCipher.ENCRYPT_MODE, symmetricKey);
    Document result = xmlCipher.doFinal(payloadDoc, payloadDoc.getDocumentElement(), false);
    NodeList list = result.getElementsByTagNameNS(ENC_NS, "CipherValue");
    if (list.getLength() != 1) {
        throw new Exception("Payload CipherData is missing");
    }
    String cipherText = ((Element) list.item(0)).getTextContent().trim();
    Element cipherValue = createCipherValue(encryptedDataDoc, encryptedDataDoc.getDocumentElement());
    cipherValue.appendChild(encryptedDataDoc.createTextNode(cipherText));
    // StaxUtils.copy(new DOMSource(encryptedDataDoc), System.out);
    return encryptedDataDoc;
}
Also used : Crypto(org.apache.wss4j.common.crypto.Crypto) Element(org.w3c.dom.Element) CryptoLoader(org.apache.cxf.rs.security.common.CryptoLoader) NodeList(org.w3c.dom.NodeList) XMLCipher(org.apache.xml.security.encryption.XMLCipher) Document(org.w3c.dom.Document) X509Certificate(java.security.cert.X509Certificate) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) BadPaddingException(javax.crypto.BadPaddingException) CertificateEncodingException(java.security.cert.CertificateEncodingException)

Example 2 with CryptoLoader

use of org.apache.cxf.rs.security.common.CryptoLoader in project cxf by apache.

the class XmlSecOutInterceptor method configureEncryption.

private void configureEncryption(Message message, XMLSecurityProperties properties) throws Exception {
    String symEncAlgo = encryptionProperties.getEncryptionSymmetricKeyAlgo() == null ? XMLCipher.AES_256 : encryptionProperties.getEncryptionSymmetricKeyAlgo();
    properties.setEncryptionSymAlgorithm(symEncAlgo);
    properties.setEncryptionKey(getSymmetricKey(symEncAlgo));
    if (encryptSymmetricKey) {
        X509Certificate sendingCert;
        String userName = (String) SecurityUtils.getSecurityPropertyValue(SecurityConstants.ENCRYPT_USERNAME, message);
        if (RSSecurityUtils.USE_REQUEST_SIGNATURE_CERT.equals(userName) && !MessageUtils.isRequestor(message)) {
            sendingCert = message.getExchange().getInMessage().getContent(X509Certificate.class);
            if (sendingCert == null) {
                @SuppressWarnings("unchecked") final List<SecurityEvent> incomingSecurityEventList = (List<SecurityEvent>) message.getExchange().get(SecurityEvent.class.getName() + ".in");
                sendingCert = getUseReqSigCert(incomingSecurityEventList);
            }
        } else {
            CryptoLoader loader = new CryptoLoader();
            Crypto crypto = loader.getCrypto(message, SecurityConstants.ENCRYPT_CRYPTO, SecurityConstants.ENCRYPT_PROPERTIES);
            userName = RSSecurityUtils.getUserName(crypto, userName);
            if (StringUtils.isEmpty(userName)) {
                throw new Exception("User name is not available");
            }
            sendingCert = getCertificateFromCrypto(crypto, userName);
        }
        if (sendingCert == null) {
            throw new Exception("Sending certificate is not available");
        }
        properties.setEncryptionUseThisCertificate(sendingCert);
        properties.setEncryptionKeyIdentifier(convertKeyIdentifier(encryptionProperties.getEncryptionKeyIdType()));
        properties.setEncryptionKeyName(encryptionProperties.getEncryptionKeyName());
        if (encryptionProperties.getEncryptionKeyTransportAlgo() != null) {
            properties.setEncryptionKeyTransportAlgorithm(encryptionProperties.getEncryptionKeyTransportAlgo());
        }
        if (encryptionProperties.getEncryptionDigestAlgo() != null) {
            properties.setEncryptionKeyTransportDigestAlgorithm(encryptionProperties.getEncryptionDigestAlgo());
        }
    }
    properties.addAction(XMLSecurityConstants.ENCRYPTION);
    if (elementsToEncrypt == null || elementsToEncrypt.isEmpty()) {
        LOG.fine("No Elements to encrypt are specified, so the entire request is encrypt");
        SecurePart securePart = new SecurePart((QName) null, SecurePart.Modifier.Element);
        securePart.setSecureEntireRequest(true);
        properties.addEncryptionPart(securePart);
    } else {
        for (QName element : elementsToEncrypt) {
            SecurePart securePart = new SecurePart(element, SecurePart.Modifier.Element);
            properties.addEncryptionPart(securePart);
        }
    }
}
Also used : SecurePart(org.apache.xml.security.stax.ext.SecurePart) TokenSecurityEvent(org.apache.xml.security.stax.securityEvent.TokenSecurityEvent) SecurityEvent(org.apache.xml.security.stax.securityEvent.SecurityEvent) Crypto(org.apache.wss4j.common.crypto.Crypto) QName(javax.xml.namespace.QName) CryptoLoader(org.apache.cxf.rs.security.common.CryptoLoader) ArrayList(java.util.ArrayList) List(java.util.List) X509Certificate(java.security.cert.X509Certificate) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) XMLStreamException(javax.xml.stream.XMLStreamException) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException)

Example 3 with CryptoLoader

use of org.apache.cxf.rs.security.common.CryptoLoader in project cxf by apache.

the class XmlSecInInterceptor method getSignatureCrypto.

private Crypto getSignatureCrypto(Message message) {
    final String cryptoKey;
    final String propKey;
    if (RSSecurityUtils.isSignedAndEncryptedTwoWay(message)) {
        cryptoKey = SecurityConstants.ENCRYPT_CRYPTO;
        propKey = SecurityConstants.ENCRYPT_PROPERTIES;
    } else {
        cryptoKey = SecurityConstants.SIGNATURE_CRYPTO;
        propKey = SecurityConstants.SIGNATURE_PROPERTIES;
    }
    try {
        return new CryptoLoader().getCrypto(message, cryptoKey, propKey);
    } catch (Exception ex) {
        throwFault("Crypto can not be loaded", ex);
        return null;
    }
}
Also used : CryptoLoader(org.apache.cxf.rs.security.common.CryptoLoader) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) XMLStreamException(javax.xml.stream.XMLStreamException) PatternSyntaxException(java.util.regex.PatternSyntaxException) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException) WebApplicationException(javax.ws.rs.WebApplicationException) IOException(java.io.IOException)

Example 4 with CryptoLoader

use of org.apache.cxf.rs.security.common.CryptoLoader in project cxf by apache.

the class AbstractXmlSigInHandler method checkSignature.

protected void checkSignature(Message message) {
    Document doc = getDocument(message);
    if (doc == null) {
        return;
    }
    Element root = doc.getDocumentElement();
    Element signatureElement = getSignatureElement(root);
    if (signatureElement == null) {
        throwFault("XML Signature is not available", null);
    }
    final String cryptoKey;
    final String propKey;
    if (RSSecurityUtils.isSignedAndEncryptedTwoWay(message)) {
        cryptoKey = SecurityConstants.ENCRYPT_CRYPTO;
        propKey = SecurityConstants.ENCRYPT_PROPERTIES;
    } else {
        cryptoKey = SecurityConstants.SIGNATURE_CRYPTO;
        propKey = SecurityConstants.SIGNATURE_PROPERTIES;
    }
    Crypto crypto = null;
    try {
        CryptoLoader loader = new CryptoLoader();
        crypto = loader.getCrypto(message, cryptoKey, propKey);
    } catch (Exception ex) {
        throwFault("Crypto can not be loaded", ex);
    }
    boolean valid = false;
    Reference ref = null;
    try {
        XMLSignature signature = new XMLSignature(signatureElement, "", true);
        if (sigProps != null) {
            SignedInfo sInfo = signature.getSignedInfo();
            if (sigProps.getSignatureAlgo() != null && !sigProps.getSignatureAlgo().equals(sInfo.getSignatureMethodURI())) {
                throwFault("Signature Algorithm is not supported", null);
            }
            if (sigProps.getSignatureC14nMethod() != null && !sigProps.getSignatureC14nMethod().equals(sInfo.getCanonicalizationMethodURI())) {
                throwFault("Signature C14n Algorithm is not supported", null);
            }
        }
        ref = getReference(signature);
        Element signedElement = validateReference(root, ref);
        if (signedElement.hasAttributeNS(null, "ID")) {
            signedElement.setIdAttributeNS(null, "ID", true);
        }
        if (signedElement.hasAttributeNS(null, "Id")) {
            signedElement.setIdAttributeNS(null, "Id", true);
        }
        X509Certificate cert = null;
        PublicKey publicKey = null;
        // See also WSS4J SAMLUtil.getCredentialFromKeyInfo
        KeyInfo keyInfo = signature.getKeyInfo();
        if (keyInfo != null) {
            cert = keyInfo.getX509Certificate();
            if (cert != null) {
                valid = signature.checkSignatureValue(cert);
            } else {
                publicKey = keyInfo.getPublicKey();
                if (publicKey != null) {
                    valid = signature.checkSignatureValue(publicKey);
                }
            }
        } else if (!keyInfoMustBeAvailable) {
            String user = getUserName(crypto, message);
            cert = RSSecurityUtils.getCertificates(crypto, user)[0];
            publicKey = cert.getPublicKey();
            valid = signature.checkSignatureValue(cert);
        }
        // validate trust
        new TrustValidator().validateTrust(crypto, cert, publicKey, getSubjectContraints(message));
        if (valid && persistSignature) {
            if (signature.getKeyInfo() != null) {
                message.put(SIGNING_CERT, signature.getKeyInfo().getX509Certificate());
            }
            if (signature.getKeyInfo() != null) {
                message.put(SIGNING_PUBLIC_KEY, signature.getKeyInfo().getPublicKey());
            }
            message.setContent(Element.class, signedElement);
        }
    } catch (Exception ex) {
        throwFault("Signature validation failed", ex);
    }
    if (!valid) {
        throwFault("Signature validation failed", null);
    }
    if (removeSignature) {
        if (!isEnveloping(root)) {
            Element signedEl = getSignedElement(root, ref);
            signedEl.removeAttribute("ID");
            root.removeChild(signatureElement);
        } else {
            Element actualBody = getActualBody(root);
            Document newDoc = DOMUtils.createDocument();
            newDoc.adoptNode(actualBody);
            root = actualBody;
        }
    }
    message.setContent(XMLStreamReader.class, new W3CDOMStreamReader(root));
    message.setContent(InputStream.class, null);
}
Also used : TrustValidator(org.apache.cxf.rs.security.common.TrustValidator) Reference(org.apache.xml.security.signature.Reference) PublicKey(java.security.PublicKey) Element(org.w3c.dom.Element) CryptoLoader(org.apache.cxf.rs.security.common.CryptoLoader) Document(org.w3c.dom.Document) PatternSyntaxException(java.util.regex.PatternSyntaxException) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException) X509Certificate(java.security.cert.X509Certificate) SignedInfo(org.apache.xml.security.signature.SignedInfo) Crypto(org.apache.wss4j.common.crypto.Crypto) KeyInfo(org.apache.xml.security.keys.KeyInfo) W3CDOMStreamReader(org.apache.cxf.staxutils.W3CDOMStreamReader) XMLSignature(org.apache.xml.security.signature.XMLSignature)

Example 5 with CryptoLoader

use of org.apache.cxf.rs.security.common.CryptoLoader in project cxf by apache.

the class JAXRSOAuth2Test method testSAML2BearerGrant.

@Test
public void testSAML2BearerGrant() throws Exception {
    String address = "https://localhost:" + port + "/oauth2/token";
    WebClient wc = createWebClient(address);
    Crypto crypto = new CryptoLoader().loadCrypto(CRYPTO_RESOURCE_PROPERTIES);
    SelfSignInfo signInfo = new SelfSignInfo(crypto, "alice", "password");
    SamlCallbackHandler samlCallbackHandler = new SamlCallbackHandler(false);
    String audienceURI = "https://localhost:" + port + "/oauth2/token";
    samlCallbackHandler.setAudience(audienceURI);
    SamlAssertionWrapper assertionWrapper = SAMLUtils.createAssertion(samlCallbackHandler, signInfo);
    Document doc = DOMUtils.newDocument();
    Element assertionElement = assertionWrapper.toDOM(doc);
    String assertion = DOM2Writer.nodeToString(assertionElement);
    Saml2BearerGrant grant = new Saml2BearerGrant(assertion);
    ClientAccessToken at = OAuthClientUtils.getAccessToken(wc, new Consumer("alice", "alice"), grant, false);
    assertNotNull(at.getTokenKey());
}
Also used : SelfSignInfo(org.apache.cxf.rs.security.saml.SAMLUtils.SelfSignInfo) SamlCallbackHandler(org.apache.cxf.systest.jaxrs.security.oauth2.common.SamlCallbackHandler) Crypto(org.apache.wss4j.common.crypto.Crypto) Saml2BearerGrant(org.apache.cxf.rs.security.oauth2.grants.saml.Saml2BearerGrant) Consumer(org.apache.cxf.rs.security.oauth2.client.Consumer) CryptoLoader(org.apache.cxf.rs.security.common.CryptoLoader) Element(org.w3c.dom.Element) ClientAccessToken(org.apache.cxf.rs.security.oauth2.common.ClientAccessToken) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) Document(org.w3c.dom.Document) WebClient(org.apache.cxf.jaxrs.client.WebClient) Test(org.junit.Test)

Aggregations

CryptoLoader (org.apache.cxf.rs.security.common.CryptoLoader)14 Crypto (org.apache.wss4j.common.crypto.Crypto)11 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)8 X509Certificate (java.security.cert.X509Certificate)7 IOException (java.io.IOException)5 XMLSecurityException (org.apache.xml.security.exceptions.XMLSecurityException)5 Element (org.w3c.dom.Element)5 XMLStreamException (javax.xml.stream.XMLStreamException)4 PatternSyntaxException (java.util.regex.PatternSyntaxException)3 UnsupportedCallbackException (javax.security.auth.callback.UnsupportedCallbackException)3 SamlAssertionWrapper (org.apache.wss4j.common.saml.SamlAssertionWrapper)3 Document (org.w3c.dom.Document)3 PrivateKey (java.security.PrivateKey)2 PublicKey (java.security.PublicKey)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 DestroyFailedException (javax.security.auth.DestroyFailedException)2 WebApplicationException (javax.ws.rs.WebApplicationException)2 QName (javax.xml.namespace.QName)2 Base64Exception (org.apache.cxf.common.util.Base64Exception)2