Search in sources :

Example 16 with Crypto

use of org.apache.wss4j.common.crypto.Crypto in project cxf by apache.

the class SAMLResponseValidatorTest method testResponseModifiedSignedAssertion.

@org.junit.Test
public void testResponseModifiedSignedAssertion() throws Exception {
    Document doc = DOMUtils.createDocument();
    Status status = SAML2PResponseComponentBuilder.createStatus(SAMLProtocolResponseValidator.SAML2_STATUSCODE_SUCCESS, null);
    Response response = SAML2PResponseComponentBuilder.createSAMLResponse("http://cxf.apache.org/saml", "http://cxf.apache.org/issuer", status);
    // Create an AuthenticationAssertion
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.AUTHN);
    callbackHandler.setIssuer("http://cxf.apache.org/issuer");
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_SENDER_VOUCHES);
    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);
    Crypto issuerCrypto = new Merlin();
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    ClassLoader loader = Loader.getClassLoader(SAMLResponseValidatorTest.class);
    InputStream input = Merlin.loadInputStream(loader, "alice.jks");
    keyStore.load(input, "password".toCharArray());
    ((Merlin) issuerCrypto).setKeyStore(keyStore);
    assertion.signAssertion("alice", "password", issuerCrypto, false);
    response.getAssertions().add(assertion.getSaml2());
    Element policyElement = OpenSAMLUtil.toDom(response, doc);
    doc.appendChild(policyElement);
    assertNotNull(policyElement);
    List<Element> assertions = DOMUtils.findAllElementsByTagNameNS(policyElement, SAMLConstants.SAML20_NS, "Assertion");
    assertNotNull(assertions);
    assertTrue(assertions.size() == 1);
    assertions.get(0).setAttributeNS(null, "newattr", "http://apache.org");
    Response marshalledResponse = (Response) OpenSAMLUtil.fromDom(policyElement);
    // Validate the Response
    SAMLProtocolResponseValidator validator = new SAMLProtocolResponseValidator();
    try {
        // Validate the Response
        validator.validateSamlResponse(marshalledResponse, issuerCrypto, new KeystorePasswordCallback());
        fail("Expected failure on a bad signature");
    } catch (WSSecurityException ex) {
    // expected
    }
}
Also used : Status(org.opensaml.saml.saml2.core.Status) InputStream(java.io.InputStream) Element(org.w3c.dom.Element) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) Document(org.w3c.dom.Document) KeyStore(java.security.KeyStore) Response(org.opensaml.saml.saml2.core.Response) Crypto(org.apache.wss4j.common.crypto.Crypto) SAMLCallback(org.apache.wss4j.common.saml.SAMLCallback) Merlin(org.apache.wss4j.common.crypto.Merlin)

Example 17 with Crypto

use of org.apache.wss4j.common.crypto.Crypto in project cxf by apache.

the class CryptoLoader method getCryptoCache.

public final Map<Object, Crypto> getCryptoCache(Message message) {
    Endpoint endpoint = message.getExchange().getEndpoint();
    if (endpoint != null) {
        EndpointInfo info = endpoint.getEndpointInfo();
        synchronized (info) {
            Map<Object, Crypto> o = CastUtils.cast((Map<?, ?>) info.getProperty(CRYPTO_CACHE));
            if (o == null) {
                o = new ConcurrentHashMap<>();
                info.setProperty(CRYPTO_CACHE, o);
            }
            return o;
        }
    }
    return null;
}
Also used : EndpointInfo(org.apache.cxf.service.model.EndpointInfo) Crypto(org.apache.wss4j.common.crypto.Crypto) Endpoint(org.apache.cxf.endpoint.Endpoint)

Example 18 with Crypto

use of org.apache.wss4j.common.crypto.Crypto in project cxf by apache.

the class AbstractSAMLTokenProvider method signToken.

protected void signToken(SamlAssertionWrapper assertion, RealmProperties samlRealm, STSPropertiesMBean stsProperties, KeyRequirements keyRequirements) throws Exception {
    // Initialise signature objects with defaults of STSPropertiesMBean
    Crypto signatureCrypto = stsProperties.getSignatureCrypto();
    CallbackHandler callbackHandler = stsProperties.getCallbackHandler();
    SignatureProperties signatureProperties = stsProperties.getSignatureProperties();
    String alias = stsProperties.getSignatureUsername();
    if (samlRealm != null) {
        // callbackhandler and alias of STSPropertiesMBean is ignored
        if (samlRealm.getSignatureCrypto() != null) {
            LOG.fine("SAMLRealm signature keystore used");
            signatureCrypto = samlRealm.getSignatureCrypto();
            callbackHandler = samlRealm.getCallbackHandler();
            alias = samlRealm.getSignatureAlias();
        }
        // SignatureProperties can be defined independently of SignatureCrypto
        if (samlRealm.getSignatureProperties() != null) {
            signatureProperties = samlRealm.getSignatureProperties();
        }
    }
    // Get the signature algorithm to use
    String signatureAlgorithm = keyRequirements.getSignatureAlgorithm();
    if (signatureAlgorithm == null) {
        // If none then default to what is configured
        signatureAlgorithm = signatureProperties.getSignatureAlgorithm();
    } else {
        List<String> supportedAlgorithms = signatureProperties.getAcceptedSignatureAlgorithms();
        if (!supportedAlgorithms.contains(signatureAlgorithm)) {
            signatureAlgorithm = signatureProperties.getSignatureAlgorithm();
            if (LOG.isLoggable(Level.FINE)) {
                LOG.fine("SignatureAlgorithm not supported, defaulting to: " + signatureAlgorithm);
            }
        }
    }
    // Get the c14n algorithm to use
    String c14nAlgorithm = keyRequirements.getC14nAlgorithm();
    if (c14nAlgorithm == null) {
        // If none then default to what is configured
        c14nAlgorithm = signatureProperties.getC14nAlgorithm();
    } else {
        List<String> supportedAlgorithms = signatureProperties.getAcceptedC14nAlgorithms();
        if (!supportedAlgorithms.contains(c14nAlgorithm)) {
            c14nAlgorithm = signatureProperties.getC14nAlgorithm();
            if (LOG.isLoggable(Level.FINE)) {
                LOG.fine("C14nAlgorithm not supported, defaulting to: " + c14nAlgorithm);
            }
        }
    }
    // If alias not defined, get the default of the SignatureCrypto
    if ((alias == null || "".equals(alias)) && (signatureCrypto != null)) {
        alias = signatureCrypto.getDefaultX509Identifier();
        if (LOG.isLoggable(Level.FINE)) {
            LOG.fine("Signature alias is null so using default alias: " + alias);
        }
    }
    // Get the password
    String password = null;
    if (callbackHandler != null) {
        WSPasswordCallback[] cb = { new WSPasswordCallback(alias, WSPasswordCallback.SIGNATURE) };
        LOG.fine("Creating SAML Token");
        callbackHandler.handle(cb);
        password = cb[0].getPassword();
    }
    LOG.fine("Signing SAML Token");
    boolean useKeyValue = signatureProperties.isUseKeyValue();
    assertion.signAssertion(alias, password, signatureCrypto, useKeyValue, c14nAlgorithm, signatureAlgorithm, signatureProperties.getDigestAlgorithm());
}
Also used : Crypto(org.apache.wss4j.common.crypto.Crypto) CallbackHandler(javax.security.auth.callback.CallbackHandler) SignatureProperties(org.apache.cxf.sts.SignatureProperties) WSPasswordCallback(org.apache.wss4j.common.ext.WSPasswordCallback)

Example 19 with Crypto

use of org.apache.wss4j.common.crypto.Crypto in project cxf by apache.

the class DefaultSubjectProvider method createKeyInfo.

/**
 * Create and return the KeyInfoBean to be inserted into the SubjectBean
 */
protected KeyInfoBean createKeyInfo(SubjectProviderParameters subjectProviderParameters) {
    TokenProviderParameters providerParameters = subjectProviderParameters.getProviderParameters();
    KeyRequirements keyRequirements = providerParameters.getKeyRequirements();
    STSPropertiesMBean stsProperties = providerParameters.getStsProperties();
    String keyType = keyRequirements.getKeyType();
    if (STSConstants.SYMMETRIC_KEY_KEYTYPE.equals(keyType)) {
        Crypto crypto = stsProperties.getEncryptionCrypto();
        EncryptionProperties encryptionProperties = providerParameters.getEncryptionProperties();
        String encryptionName = encryptionProperties.getEncryptionName();
        if (encryptionName == null) {
            // Fall back on the STS encryption name
            encryptionName = stsProperties.getEncryptionUsername();
        }
        if (encryptionName == null) {
            LOG.fine("No encryption Name is configured for Symmetric KeyType");
            throw new STSException("No Encryption Name is configured", STSException.REQUEST_FAILED);
        }
        CryptoType cryptoType = null;
        // Check for using of service endpoint (AppliesTo) as certificate identifier
        if (STSConstants.USE_ENDPOINT_AS_CERT_ALIAS.equals(encryptionName)) {
            if (providerParameters.getAppliesToAddress() == null) {
                throw new STSException("AppliesTo is not initilaized for encryption name " + STSConstants.USE_ENDPOINT_AS_CERT_ALIAS);
            }
            cryptoType = new CryptoType(CryptoType.TYPE.ENDPOINT);
            cryptoType.setEndpoint(providerParameters.getAppliesToAddress());
        } else {
            cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
            cryptoType.setAlias(encryptionName);
        }
        try {
            X509Certificate[] certs = crypto.getX509Certificates(cryptoType);
            if ((certs == null) || (certs.length == 0)) {
                throw new STSException("Encryption certificate is not found for alias: " + encryptionName);
            }
            Document doc = subjectProviderParameters.getDoc();
            byte[] secret = subjectProviderParameters.getSecret();
            return createEncryptedKeyKeyInfo(certs[0], secret, doc, encryptionProperties, crypto);
        } catch (WSSecurityException ex) {
            LOG.log(Level.WARNING, "", ex);
            throw new STSException(ex.getMessage(), ex);
        }
    } else if (STSConstants.PUBLIC_KEY_KEYTYPE.equals(keyType)) {
        ReceivedKey receivedKey = keyRequirements.getReceivedKey();
        // Validate UseKey trust
        if (stsProperties.isValidateUseKey() && stsProperties.getSignatureCrypto() != null) {
            if (receivedKey.getX509Cert() != null) {
                try {
                    Collection<Pattern> constraints = Collections.emptyList();
                    stsProperties.getSignatureCrypto().verifyTrust(new X509Certificate[] { receivedKey.getX509Cert() }, false, constraints, null);
                } catch (WSSecurityException e) {
                    LOG.log(Level.FINE, "Error in trust validation of UseKey: ", e);
                    throw new STSException("Error in trust validation of UseKey", STSException.REQUEST_FAILED);
                }
            }
            if (receivedKey.getPublicKey() != null) {
                try {
                    stsProperties.getSignatureCrypto().verifyTrust(receivedKey.getPublicKey());
                } catch (WSSecurityException e) {
                    LOG.log(Level.FINE, "Error in trust validation of UseKey: ", e);
                    throw new STSException("Error in trust validation of UseKey", STSException.REQUEST_FAILED);
                }
            }
        }
        return createPublicKeyKeyInfo(receivedKey.getX509Cert(), receivedKey.getPublicKey());
    }
    return null;
}
Also used : STSException(org.apache.cxf.ws.security.sts.provider.STSException) EncryptionProperties(org.apache.cxf.sts.service.EncryptionProperties) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) CryptoType(org.apache.wss4j.common.crypto.CryptoType) Document(org.w3c.dom.Document) X509Certificate(java.security.cert.X509Certificate) ReceivedKey(org.apache.cxf.sts.request.ReceivedKey) Crypto(org.apache.wss4j.common.crypto.Crypto) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) Collection(java.util.Collection) KeyRequirements(org.apache.cxf.sts.request.KeyRequirements)

Example 20 with Crypto

use of org.apache.wss4j.common.crypto.Crypto in project cxf by apache.

the class JWTTokenProvider method encryptToken.

private String encryptToken(String token, JweHeaders jweHeaders, STSPropertiesMBean stsProperties, EncryptionProperties encryptionProperties, KeyRequirements keyRequirements) throws Exception {
    Properties encProperties = new Properties();
    String name = encryptionProperties.getEncryptionName();
    if (name == null) {
        name = stsProperties.getEncryptionUsername();
    }
    if (name == null) {
        LOG.fine("No encryption alias is configured");
        return token;
    }
    encProperties.put(JoseConstants.RSSEC_KEY_STORE_ALIAS, name);
    // Get the encryption algorithm to use - for now we don't allow the client to ask
    // for a particular encryption algorithm, as with SAML
    String encryptionAlgorithm = encryptionProperties.getEncryptionAlgorithm();
    try {
        ContentAlgorithm.getAlgorithm(encryptionAlgorithm);
    } catch (IllegalArgumentException ex) {
        encryptionAlgorithm = ContentAlgorithm.A128GCM.name();
    }
    encProperties.put(JoseConstants.RSSEC_ENCRYPTION_CONTENT_ALGORITHM, encryptionAlgorithm);
    // Get the key-wrap algorithm to use - for now we don't allow the client to ask
    // for a particular encryption algorithm, as with SAML
    String keyWrapAlgorithm = encryptionProperties.getKeyWrapAlgorithm();
    try {
        KeyAlgorithm.getAlgorithm(keyWrapAlgorithm);
    } catch (IllegalArgumentException ex) {
        keyWrapAlgorithm = KeyAlgorithm.RSA_OAEP.name();
    }
    encProperties.put(JoseConstants.RSSEC_ENCRYPTION_KEY_ALGORITHM, keyWrapAlgorithm);
    // Initialise encryption objects with defaults of STSPropertiesMBean
    Crypto encryptionCrypto = stsProperties.getEncryptionCrypto();
    if (!(encryptionCrypto instanceof Merlin)) {
        throw new STSException("Can't get the keystore", STSException.REQUEST_FAILED);
    }
    KeyStore keystore = ((Merlin) encryptionCrypto).getKeyStore();
    encProperties.put(JoseConstants.RSSEC_KEY_STORE, keystore);
    JweEncryptionProvider encProvider = JweUtils.loadEncryptionProvider(encProperties, jweHeaders);
    return encProvider.encrypt(StringUtils.toBytesUTF8(token), null);
}
Also used : Crypto(org.apache.wss4j.common.crypto.Crypto) JweEncryptionProvider(org.apache.cxf.rs.security.jose.jwe.JweEncryptionProvider) STSException(org.apache.cxf.ws.security.sts.provider.STSException) EncryptionProperties(org.apache.cxf.sts.service.EncryptionProperties) SignatureProperties(org.apache.cxf.sts.SignatureProperties) Properties(java.util.Properties) RealmProperties(org.apache.cxf.sts.token.realm.RealmProperties) KeyStore(java.security.KeyStore) Merlin(org.apache.wss4j.common.crypto.Merlin)

Aggregations

Crypto (org.apache.wss4j.common.crypto.Crypto)266 PasswordCallbackHandler (org.apache.cxf.sts.common.PasswordCallbackHandler)148 Element (org.w3c.dom.Element)132 WrappedMessageContext (org.apache.cxf.jaxws.context.WrappedMessageContext)113 MessageImpl (org.apache.cxf.message.MessageImpl)113 StaticSTSProperties (org.apache.cxf.sts.StaticSTSProperties)111 CustomTokenPrincipal (org.apache.wss4j.common.principal.CustomTokenPrincipal)109 STSPropertiesMBean (org.apache.cxf.sts.STSPropertiesMBean)88 ArrayList (java.util.ArrayList)85 Document (org.w3c.dom.Document)83 CallbackHandler (javax.security.auth.callback.CallbackHandler)82 JAXBElement (javax.xml.bind.JAXBElement)82 RequestSecurityTokenType (org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenType)77 RequestSecurityTokenResponseType (org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenResponseType)74 TokenRequirements (org.apache.cxf.sts.request.TokenRequirements)67 TokenProvider (org.apache.cxf.sts.token.provider.TokenProvider)66 Principal (java.security.Principal)63 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)55 ReceivedToken (org.apache.cxf.sts.request.ReceivedToken)54 TokenValidator (org.apache.cxf.sts.token.validator.TokenValidator)54