Search in sources :

Example 6 with CryptoLoader

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

the class JAXRSOAuth2Test method testSAML2BearerAuthenticationDirect.

@Test
public void testSAML2BearerAuthenticationDirect() throws Exception {
    String address = "https://localhost:" + PORT + "/oauth2-auth/token";
    WebClient wc = createWebClient(address);
    Crypto crypto = new CryptoLoader().loadCrypto(CRYPTO_RESOURCE_PROPERTIES);
    SelfSignInfo signInfo = new SelfSignInfo(crypto, "alice", "password");
    SamlCallbackHandler samlCallbackHandler = new SamlCallbackHandler(true);
    samlCallbackHandler.setIssuer("alice");
    String audienceURI = "https://localhost:" + PORT + "/oauth2-auth/token";
    samlCallbackHandler.setAudience(audienceURI);
    SamlAssertionWrapper assertionWrapper = SAMLUtils.createAssertion(samlCallbackHandler, signInfo);
    Document doc = DOMUtils.newDocument();
    Element assertionElement = assertionWrapper.toDOM(doc);
    String assertion = DOM2Writer.nodeToString(assertionElement);
    String encodedAssertion = Base64UrlUtility.encode(assertion);
    Map<String, String> extraParams = new HashMap<>();
    extraParams.put(Constants.CLIENT_AUTH_ASSERTION_TYPE, Constants.CLIENT_AUTH_SAML2_BEARER);
    extraParams.put(Constants.CLIENT_AUTH_ASSERTION_PARAM, encodedAssertion);
    ClientAccessToken at = OAuthClientUtils.getAccessToken(wc, new CustomGrant(), extraParams);
    assertNotNull(at.getTokenKey());
}
Also used : SelfSignInfo(org.apache.cxf.rs.security.saml.SAMLUtils.SelfSignInfo) HashMap(java.util.HashMap) 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) SamlCallbackHandler(org.apache.cxf.systest.jaxrs.security.oauth2.common.SamlCallbackHandler) Crypto(org.apache.wss4j.common.crypto.Crypto) Test(org.junit.Test)

Example 7 with CryptoLoader

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

the class AbstractXmlEncInHandler method getSymmetricKeyBytes.

// Subclasses can overwrite it and return the bytes, assuming they know the actual key
protected byte[] getSymmetricKeyBytes(Message message, Element encDataElement) {
    String cryptoKey = null;
    String propKey = null;
    if (RSSecurityUtils.isSignedAndEncryptedTwoWay(message)) {
        cryptoKey = SecurityConstants.SIGNATURE_CRYPTO;
        propKey = SecurityConstants.SIGNATURE_PROPERTIES;
    } else {
        cryptoKey = SecurityConstants.ENCRYPT_CRYPTO;
        propKey = SecurityConstants.ENCRYPT_PROPERTIES;
    }
    Crypto crypto = null;
    try {
        crypto = new CryptoLoader().getCrypto(message, cryptoKey, propKey);
    } catch (Exception ex) {
        throwFault("Crypto can not be loaded", ex);
    }
    Element encKeyElement = getNode(encDataElement, ENC_NS, "EncryptedKey", 0);
    if (encKeyElement == null) {
        // TODO: support EncryptedData/ds:KeyInfo - the encrypted key is passed out of band
        throwFault("EncryptedKey element is not available", null);
    }
    X509Certificate cert = loadCertificate(crypto, encKeyElement);
    try {
        new TrustValidator().validateTrust(crypto, cert, null);
    } catch (Exception ex) {
        throwFault(ex.getMessage(), ex);
    }
    // now start decrypting
    String keyEncAlgo = getEncodingMethodAlgorithm(encKeyElement);
    String digestAlgo = getDigestMethodAlgorithm(encKeyElement);
    if (encProps != null) {
        if (encProps.getEncryptionKeyTransportAlgo() != null && !encProps.getEncryptionKeyTransportAlgo().equals(keyEncAlgo)) {
            throwFault("Key Transport Algorithm is not supported", null);
        }
        if (encProps.getEncryptionDigestAlgo() != null && (digestAlgo == null || !encProps.getEncryptionDigestAlgo().equals(digestAlgo))) {
            throwFault("Digest Algorithm is not supported", null);
        }
    } else if (!XMLCipher.RSA_OAEP.equals(keyEncAlgo)) {
        // RSA OAEP is the required default Key Transport Algorithm
        throwFault("Key Transport Algorithm is not supported", null);
    }
    Element cipherValue = getNode(encKeyElement, ENC_NS, "CipherValue", 0);
    if (cipherValue == null) {
        throwFault("CipherValue element is not available", null);
    }
    try {
        return decryptSymmetricKey(cipherValue.getTextContent().trim(), cert, crypto, keyEncAlgo, digestAlgo, message);
    } catch (Exception ex) {
        throwFault(ex.getMessage(), ex);
    }
    return null;
}
Also used : Crypto(org.apache.wss4j.common.crypto.Crypto) TrustValidator(org.apache.cxf.rs.security.common.TrustValidator) CryptoLoader(org.apache.cxf.rs.security.common.CryptoLoader) Element(org.w3c.dom.Element) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) XMLEncryptionException(org.apache.xml.security.encryption.XMLEncryptionException) Base64Exception(org.apache.cxf.common.util.Base64Exception) X509Certificate(java.security.cert.X509Certificate)

Example 8 with CryptoLoader

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

the class XmlSecInInterceptor method configureDecryptionKeys.

private void configureDecryptionKeys(Message message, XMLSecurityProperties properties) throws IOException, UnsupportedCallbackException, WSSecurityException {
    String cryptoKey = null;
    String propKey = null;
    if (RSSecurityUtils.isSignedAndEncryptedTwoWay(message)) {
        cryptoKey = SecurityConstants.SIGNATURE_CRYPTO;
        propKey = SecurityConstants.SIGNATURE_PROPERTIES;
    } else {
        cryptoKey = SecurityConstants.ENCRYPT_CRYPTO;
        propKey = SecurityConstants.ENCRYPT_PROPERTIES;
    }
    Crypto crypto = null;
    try {
        crypto = new CryptoLoader().getCrypto(message, cryptoKey, propKey);
    } catch (Exception ex) {
        throwFault("Crypto can not be loaded", ex);
    }
    if (crypto != null) {
        String alias = decryptionAlias;
        if (alias == null) {
            alias = crypto.getDefaultX509Identifier();
        }
        if (alias != null) {
            CallbackHandler callback = RSSecurityUtils.getCallbackHandler(message, this.getClass());
            WSPasswordCallback passwordCallback = new WSPasswordCallback(alias, WSPasswordCallback.DECRYPT);
            callback.handle(new Callback[] { passwordCallback });
            Key privateKey = crypto.getPrivateKey(alias, passwordCallback.getPassword());
            properties.setDecryptionKey(privateKey);
        }
    }
}
Also used : Crypto(org.apache.wss4j.common.crypto.Crypto) CallbackHandler(javax.security.auth.callback.CallbackHandler) CryptoLoader(org.apache.cxf.rs.security.common.CryptoLoader) WSPasswordCallback(org.apache.wss4j.common.ext.WSPasswordCallback) 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) Key(java.security.Key) PublicKey(java.security.PublicKey)

Example 9 with CryptoLoader

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

the class XmlSecOutInterceptor method configureSignature.

private void configureSignature(Message message, XMLSecurityProperties properties) throws Exception {
    String userNameKey = SecurityConstants.SIGNATURE_USERNAME;
    CryptoLoader loader = new CryptoLoader();
    Crypto crypto = loader.getCrypto(message, SecurityConstants.SIGNATURE_CRYPTO, SecurityConstants.SIGNATURE_PROPERTIES);
    String user = RSSecurityUtils.getUserName(message, crypto, userNameKey);
    if (StringUtils.isEmpty(user) || RSSecurityUtils.USE_REQUEST_SIGNATURE_CERT.equals(user)) {
        throw new Exception("User name is not available");
    }
    String password = RSSecurityUtils.getPassword(message, user, WSPasswordCallback.SIGNATURE, this.getClass());
    X509Certificate[] issuerCerts = RSSecurityUtils.getCertificates(crypto, user);
    properties.setSignatureCerts(issuerCerts);
    String sigAlgo = sigProps.getSignatureAlgo() == null ? SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1 : sigProps.getSignatureAlgo();
    String pubKeyAlgo = issuerCerts[0].getPublicKey().getAlgorithm();
    if (pubKeyAlgo.equalsIgnoreCase("DSA")) {
        sigAlgo = SignatureConstants.ALGO_ID_SIGNATURE_DSA_SHA1;
    }
    properties.setSignatureAlgorithm(sigAlgo);
    PrivateKey privateKey = null;
    try {
        privateKey = crypto.getPrivateKey(user, password);
    } catch (Exception ex) {
        String errorMessage = "Private key can not be loaded, user:" + user;
        LOG.severe(errorMessage);
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ex);
    }
    properties.setSignatureKey(privateKey);
    String digestAlgo = sigProps.getSignatureDigestAlgo() == null ? Constants.ALGO_ID_DIGEST_SHA1 : sigProps.getSignatureDigestAlgo();
    properties.setSignatureDigestAlgorithm(digestAlgo);
    if (this.keyInfoMustBeAvailable) {
        properties.setSignatureKeyIdentifier(convertKeyIdentifier(sigProps.getSignatureKeyIdType()));
        properties.setSignatureKeyName(sigProps.getSignatureKeyName());
    } else {
        properties.setSignatureKeyIdentifier(SecurityTokenConstants.KeyIdentifier_NoKeyInfo);
    }
    String c14nMethod = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315";
    if (sigProps.getSignatureC14nMethod() != null) {
        c14nMethod = sigProps.getSignatureC14nMethod();
    }
    properties.setSignatureCanonicalizationAlgorithm(c14nMethod);
    properties.addAction(XMLSecurityConstants.SIGNATURE);
    // Only enveloped supported for the moment.
    String transform = "http://www.w3.org/2001/10/xml-exc-c14n#";
    if (sigProps.getSignatureC14nTransform() != null) {
        transform = sigProps.getSignatureC14nTransform();
    }
    if (sigProps.getSignatureLocation() != null) {
        properties.setSignaturePosition(sigProps.getSignatureLocation());
    }
    if (sigProps.getSignatureGenerateIdAttributes() != null) {
        properties.setSignatureGenerateIds(sigProps.getSignatureGenerateIdAttributes());
    }
    if (Boolean.TRUE.equals(sigProps.getSignatureOmitC14nTransform())) {
        properties.setSignatureIncludeDigestTransform(false);
    }
    if (elementsToSign == null || elementsToSign.isEmpty()) {
        LOG.fine("No Elements to sign are specified, so the entire request is signed");
        SecurePart securePart = new SecurePart(null, SecurePart.Modifier.Element, new String[] { "http://www.w3.org/2000/09/xmldsig#enveloped-signature", transform }, digestAlgo);
        securePart.setSecureEntireRequest(true);
        properties.addSignaturePart(securePart);
    } else {
        for (QName element : elementsToSign) {
            SecurePart securePart = new SecurePart(element, SecurePart.Modifier.Element, new String[] { "http://www.w3.org/2000/09/xmldsig#enveloped-signature", transform }, digestAlgo);
            properties.addSignaturePart(securePart);
        }
    }
}
Also used : SecurePart(org.apache.xml.security.stax.ext.SecurePart) Crypto(org.apache.wss4j.common.crypto.Crypto) PrivateKey(java.security.PrivateKey) QName(javax.xml.namespace.QName) CryptoLoader(org.apache.cxf.rs.security.common.CryptoLoader) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) XMLStreamException(javax.xml.stream.XMLStreamException) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException) X509Certificate(java.security.cert.X509Certificate)

Example 10 with CryptoLoader

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

the class XmlSigOutInterceptor method createSignature.

// enveloping & detached sigs will be supported too
private Document createSignature(Message message, Document doc) throws Exception {
    String userNameKey = SecurityConstants.SIGNATURE_USERNAME;
    CryptoLoader loader = new CryptoLoader();
    Crypto crypto = loader.getCrypto(message, SecurityConstants.SIGNATURE_CRYPTO, SecurityConstants.SIGNATURE_PROPERTIES);
    String user = RSSecurityUtils.getUserName(message, crypto, userNameKey);
    if (StringUtils.isEmpty(user) || RSSecurityUtils.USE_REQUEST_SIGNATURE_CERT.equals(user)) {
        throw new Exception("User name is not available");
    }
    String password = RSSecurityUtils.getPassword(message, user, WSPasswordCallback.SIGNATURE, this.getClass());
    X509Certificate[] issuerCerts = RSSecurityUtils.getCertificates(crypto, user);
    String sigAlgo = sigProps.getSignatureAlgo() == null ? SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1 : sigProps.getSignatureAlgo();
    String pubKeyAlgo = issuerCerts[0].getPublicKey().getAlgorithm();
    if (pubKeyAlgo.equalsIgnoreCase("DSA")) {
        sigAlgo = XMLSignature.ALGO_ID_SIGNATURE_DSA;
    }
    PrivateKey privateKey = null;
    try {
        privateKey = crypto.getPrivateKey(user, password);
    } catch (Exception ex) {
        String errorMessage = "Private key can not be loaded, user:" + user;
        LOG.severe(errorMessage);
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ex);
    }
    String id = UUID.randomUUID().toString();
    String referenceId = "#" + id;
    String digestAlgo = sigProps.getSignatureDigestAlgo() == null ? Constants.ALGO_ID_DIGEST_SHA1 : sigProps.getSignatureDigestAlgo();
    XMLSignature sig = null;
    if (ENVELOPING_SIG.equals(sigStyle)) {
        sig = prepareEnvelopingSignature(doc, id, referenceId, sigAlgo, digestAlgo);
    } else if (DETACHED_SIG.equals(sigStyle)) {
        sig = prepareDetachedSignature(doc, id, referenceId, sigAlgo, digestAlgo);
    } else {
        sig = prepareEnvelopedSignature(doc, id, referenceId, sigAlgo, digestAlgo);
    }
    if (this.keyInfoMustBeAvailable) {
        sig.addKeyInfo(issuerCerts[0]);
        sig.addKeyInfo(issuerCerts[0].getPublicKey());
    }
    sig.sign(privateKey);
    return sig.getElement().getOwnerDocument();
}
Also used : Crypto(org.apache.wss4j.common.crypto.Crypto) PrivateKey(java.security.PrivateKey) XMLSignature(org.apache.xml.security.signature.XMLSignature) CryptoLoader(org.apache.cxf.rs.security.common.CryptoLoader) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) X509Certificate(java.security.cert.X509Certificate)

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 WebApplicationException (javax.ws.rs.WebApplicationException)2 QName (javax.xml.namespace.QName)2 Base64Exception (org.apache.cxf.common.util.Base64Exception)2 WebClient (org.apache.cxf.jaxrs.client.WebClient)2