Search in sources :

Example 31 with STSException

use of org.apache.cxf.ws.security.sts.provider.STSException 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);
        }
        final CryptoType cryptoType;
        // 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)) {
        ReceivedCredential receivedCredential = keyRequirements.getReceivedCredential();
        // Validate UseKey trust
        if (stsProperties.isValidateUseKey() && stsProperties.getSignatureCrypto() != null) {
            if (receivedCredential.getX509Cert() != null) {
                try {
                    Collection<Pattern> constraints = Collections.emptyList();
                    stsProperties.getSignatureCrypto().verifyTrust(new X509Certificate[] { receivedCredential.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 (receivedCredential.getPublicKey() != null) {
                try {
                    stsProperties.getSignatureCrypto().verifyTrust(receivedCredential.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(receivedCredential.getX509Cert(), receivedCredential.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) ReceivedCredential(org.apache.cxf.sts.request.ReceivedCredential) 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 32 with STSException

use of org.apache.cxf.ws.security.sts.provider.STSException in project cxf by apache.

the class JWTTokenValidator method validateToken.

/**
 * Validate a Token using the given TokenValidatorParameters.
 */
public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
    LOG.fine("Validating JWT Token");
    STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();
    TokenValidatorResponse response = new TokenValidatorResponse();
    ReceivedToken validateTarget = tokenParameters.getToken();
    validateTarget.setState(STATE.INVALID);
    response.setToken(validateTarget);
    String token = ((Element) validateTarget.getToken()).getTextContent();
    if (token == null || "".equals(token)) {
        return response;
    }
    if (token.split("\\.").length != 3) {
        LOG.log(Level.WARNING, "JWT Token appears not to be signed. Validation has failed");
        return response;
    }
    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(token);
    JwtToken jwt = jwtConsumer.getJwtToken();
    // Verify the signature
    Properties verificationProperties = new Properties();
    Crypto signatureCrypto = stsProperties.getSignatureCrypto();
    String alias = stsProperties.getSignatureUsername();
    if (alias != null) {
        verificationProperties.put(JoseConstants.RSSEC_KEY_STORE_ALIAS, alias);
    }
    if (!(signatureCrypto instanceof Merlin)) {
        throw new STSException("Can't get the keystore", STSException.REQUEST_FAILED);
    }
    KeyStore keystore = ((Merlin) signatureCrypto).getKeyStore();
    verificationProperties.put(JoseConstants.RSSEC_KEY_STORE, keystore);
    JwsSignatureVerifier signatureVerifier = JwsUtils.loadSignatureVerifier(verificationProperties, jwt.getJwsHeaders());
    if (!jwtConsumer.verifySignatureWith(signatureVerifier)) {
        return response;
    }
    try {
        validateToken(jwt);
    } catch (RuntimeException ex) {
        LOG.log(Level.WARNING, "JWT token validation failed", ex);
        return response;
    }
    // Get the realm of the JWT Token
    if (realmCodec != null) {
        String tokenRealm = realmCodec.getRealmFromToken(jwt);
        response.setTokenRealm(tokenRealm);
    }
    if (isVerifiedWithAPublicKey(jwt)) {
        Principal principal = new SimplePrincipal(jwt.getClaims().getSubject());
        response.setPrincipal(principal);
        // Parse roles from the validated token
        if (roleParser != null) {
            Set<Principal> roles = roleParser.parseRolesFromToken(principal, null, jwt);
            response.setRoles(roles);
        }
    }
    validateTarget.setState(STATE.VALID);
    LOG.fine("JWT Token successfully validated");
    return response;
}
Also used : Element(org.w3c.dom.Element) STSException(org.apache.cxf.ws.security.sts.provider.STSException) Properties(java.util.Properties) KeyStore(java.security.KeyStore) JwtToken(org.apache.cxf.rs.security.jose.jwt.JwtToken) JwsSignatureVerifier(org.apache.cxf.rs.security.jose.jws.JwsSignatureVerifier) Crypto(org.apache.wss4j.common.crypto.Crypto) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) TokenValidatorResponse(org.apache.cxf.sts.token.validator.TokenValidatorResponse) JwsJwtCompactConsumer(org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken) Merlin(org.apache.wss4j.common.crypto.Merlin) SimplePrincipal(org.apache.cxf.common.security.SimplePrincipal) Principal(java.security.Principal) SimplePrincipal(org.apache.cxf.common.security.SimplePrincipal)

Example 33 with STSException

use of org.apache.cxf.ws.security.sts.provider.STSException in project cxf by apache.

the class SAMLTokenRenewer method renewToken.

/**
 * Renew a token given a TokenRenewerParameters
 */
public TokenRenewerResponse renewToken(TokenRenewerParameters tokenParameters) {
    TokenRenewerResponse response = new TokenRenewerResponse();
    ReceivedToken tokenToRenew = tokenParameters.getToken();
    if (tokenToRenew == null || tokenToRenew.getToken() == null || (tokenToRenew.getState() != STATE.EXPIRED && tokenToRenew.getState() != STATE.VALID)) {
        LOG.log(Level.WARNING, "The token to renew is null or invalid");
        throw new STSException("The token to renew is null or invalid", STSException.INVALID_REQUEST);
    }
    TokenStore tokenStore = tokenParameters.getTokenStore();
    if (tokenStore == null) {
        LOG.log(Level.FINE, "A cache must be configured to use the SAMLTokenRenewer");
        throw new STSException("Can't renew SAML assertion", STSException.REQUEST_FAILED);
    }
    try {
        SamlAssertionWrapper assertion = new SamlAssertionWrapper((Element) tokenToRenew.getToken());
        byte[] oldSignature = assertion.getSignatureValue();
        int hash = Arrays.hashCode(oldSignature);
        SecurityToken cachedToken = tokenStore.getToken(Integer.toString(hash));
        if (cachedToken == null) {
            LOG.log(Level.FINE, "The token to be renewed must be stored in the cache");
            throw new STSException("Can't renew SAML assertion", STSException.REQUEST_FAILED);
        }
        // Validate the Assertion
        validateAssertion(assertion, tokenToRenew, cachedToken, tokenParameters);
        SamlAssertionWrapper renewedAssertion = new SamlAssertionWrapper(assertion.getSamlObject());
        String oldId = createNewId(renewedAssertion);
        // Remove the previous token (now expired) from the cache
        tokenStore.remove(oldId);
        tokenStore.remove(Integer.toString(hash));
        // Create new Conditions & sign the Assertion
        createNewConditions(renewedAssertion, tokenParameters);
        signAssertion(renewedAssertion, tokenParameters);
        Document doc = DOMUtils.createDocument();
        Element token = renewedAssertion.toDOM(doc);
        if (renewedAssertion.getSaml1() != null) {
            token.setIdAttributeNS(null, "AssertionID", true);
        } else {
            token.setIdAttributeNS(null, "ID", true);
        }
        doc.appendChild(token);
        // Cache the token
        storeTokenInCache(tokenStore, renewedAssertion, tokenParameters.getPrincipal(), tokenParameters);
        response.setToken(token);
        response.setTokenId(renewedAssertion.getId());
        final DateTime validFrom;
        final DateTime validTill;
        if (renewedAssertion.getSamlVersion().equals(SAMLVersion.VERSION_20)) {
            validFrom = renewedAssertion.getSaml2().getConditions().getNotBefore();
            validTill = renewedAssertion.getSaml2().getConditions().getNotOnOrAfter();
        } else {
            validFrom = renewedAssertion.getSaml1().getConditions().getNotBefore();
            validTill = renewedAssertion.getSaml1().getConditions().getNotOnOrAfter();
        }
        response.setCreated(validFrom.toDate().toInstant());
        response.setExpires(validTill.toDate().toInstant());
        LOG.fine("SAML Token successfully renewed");
        return response;
    } catch (Exception ex) {
        LOG.log(Level.WARNING, "", ex);
        throw new STSException("Can't renew SAML assertion", ex, STSException.REQUEST_FAILED);
    }
}
Also used : Element(org.w3c.dom.Element) STSException(org.apache.cxf.ws.security.sts.provider.STSException) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) Document(org.w3c.dom.Document) DateTime(org.joda.time.DateTime) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) STSException(org.apache.cxf.ws.security.sts.provider.STSException) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken) TokenStore(org.apache.cxf.ws.security.tokenstore.TokenStore)

Example 34 with STSException

use of org.apache.cxf.ws.security.sts.provider.STSException in project cxf by apache.

the class SCTCanceller method cancelToken.

/**
 * Cancel a Token using the given TokenCancellerParameters.
 */
public TokenCancellerResponse cancelToken(TokenCancellerParameters tokenParameters) {
    LOG.fine("Trying to cancel a SecurityContextToken");
    TokenCancellerResponse response = new TokenCancellerResponse();
    ReceivedToken cancelTarget = tokenParameters.getToken();
    if (tokenParameters.getTokenStore() == null) {
        LOG.log(Level.FINE, "A cache must be configured to use the SCTCanceller");
        return response;
    }
    if (cancelTarget == null) {
        LOG.log(Level.FINE, "Cancel Target is null");
        return response;
    }
    cancelTarget.setState(STATE.NONE);
    response.setToken(cancelTarget);
    if (cancelTarget.isDOMElement()) {
        try {
            Element cancelTargetElement = (Element) cancelTarget.getToken();
            SecurityContextToken sct = new SecurityContextToken(cancelTargetElement);
            String identifier = sct.getIdentifier();
            SecurityToken token = tokenParameters.getTokenStore().getToken(identifier);
            if (token == null) {
                LOG.fine("Identifier: " + identifier + " is not found in the cache");
                return response;
            }
            if (verifyProofOfPossession && !matchKey(tokenParameters, token.getSecret())) {
                throw new STSException("Failed to verify the proof of possession of the key associated with the " + "security context. No matching key found in the request.", STSException.INVALID_REQUEST);
            }
            tokenParameters.getTokenStore().remove(token.getId());
            cancelTarget.setState(STATE.CANCELLED);
            LOG.fine("SecurityContextToken successfully cancelled");
        } catch (WSSecurityException ex) {
            LOG.log(Level.WARNING, "", ex);
        }
    }
    return response;
}
Also used : SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) SecurityContextToken(org.apache.wss4j.dom.message.token.SecurityContextToken) Element(org.w3c.dom.Element) STSException(org.apache.cxf.ws.security.sts.provider.STSException) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken)

Example 35 with STSException

use of org.apache.cxf.ws.security.sts.provider.STSException 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

STSException (org.apache.cxf.ws.security.sts.provider.STSException)87 Element (org.w3c.dom.Element)33 Crypto (org.apache.wss4j.common.crypto.Crypto)31 JAXBElement (javax.xml.bind.JAXBElement)30 StaticSTSProperties (org.apache.cxf.sts.StaticSTSProperties)26 RequestSecurityTokenResponseType (org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenResponseType)26 RequestSecurityTokenType (org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenType)26 WrappedMessageContext (org.apache.cxf.jaxws.context.WrappedMessageContext)25 MessageImpl (org.apache.cxf.message.MessageImpl)25 STSPropertiesMBean (org.apache.cxf.sts.STSPropertiesMBean)24 PasswordCallbackHandler (org.apache.cxf.sts.common.PasswordCallbackHandler)24 ServiceMBean (org.apache.cxf.sts.service.ServiceMBean)21 StaticService (org.apache.cxf.sts.service.StaticService)20 RequestSecurityTokenResponseCollectionType (org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenResponseCollectionType)18 Document (org.w3c.dom.Document)18 Principal (java.security.Principal)14 ReceivedToken (org.apache.cxf.sts.request.ReceivedToken)14 EncryptionProperties (org.apache.cxf.sts.service.EncryptionProperties)14 TokenRequirements (org.apache.cxf.sts.request.TokenRequirements)13 SAMLTokenProvider (org.apache.cxf.sts.token.provider.SAMLTokenProvider)13