Search in sources :

Example 26 with STSException

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

the class CancelSCTUnitTest method testCancelSCT.

/**
 * Test to successfully cancel a SecurityContextToken
 */
@org.junit.Test
public void testCancelSCT() throws Exception {
    TokenCancelOperation cancelOperation = new TokenCancelOperation();
    cancelOperation.setTokenStore(tokenStore);
    // Add Token Canceller
    TokenCanceller sctCanceller = new SCTCanceller();
    sctCanceller.setVerifyProofOfPossession(false);
    cancelOperation.setTokenCancellers(Collections.singletonList(sctCanceller));
    // Add STSProperties object
    STSPropertiesMBean stsProperties = new StaticSTSProperties();
    Crypto crypto = CryptoFactory.getInstance(getEncryptionProperties());
    stsProperties.setEncryptionCrypto(crypto);
    stsProperties.setSignatureCrypto(crypto);
    stsProperties.setEncryptionUsername("myservicekey");
    stsProperties.setSignatureUsername("mystskey");
    stsProperties.setCallbackHandler(new PasswordCallbackHandler());
    stsProperties.setIssuer("STS");
    cancelOperation.setStsProperties(stsProperties);
    // Get a SecurityContextToken via the SCTProvider
    TokenProviderResponse providerResponse = createSCT();
    Element sct = (Element) providerResponse.getToken();
    CancelTargetType cancelTarget = new CancelTargetType();
    cancelTarget.setAny(sct);
    // Mock up a request
    JAXBElement<CancelTargetType> cancelTargetType = new JAXBElement<CancelTargetType>(QNameConstants.CANCEL_TARGET, CancelTargetType.class, cancelTarget);
    RequestSecurityTokenType request = new RequestSecurityTokenType();
    request.getAny().add(cancelTargetType);
    // Mock up message context
    MessageImpl msg = new MessageImpl();
    WrappedMessageContext msgCtx = new WrappedMessageContext(msg);
    Principal principal = new CustomTokenPrincipal("alice");
    msgCtx.put(SecurityContext.class.getName(), createSecurityContext(principal));
    // Cancel a token
    RequestSecurityTokenResponseType response = cancelOperation.cancel(request, principal, msgCtx);
    assertTrue(validateResponse(response));
    // Now try to cancel again
    try {
        cancelOperation.cancel(request, principal, msgCtx);
    } catch (STSException ex) {
    // expected
    }
}
Also used : JAXBElement(javax.xml.bind.JAXBElement) Element(org.w3c.dom.Element) RequestSecurityTokenType(org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenType) CancelTargetType(org.apache.cxf.ws.security.sts.provider.model.CancelTargetType) STSException(org.apache.cxf.ws.security.sts.provider.STSException) RequestSecurityTokenResponseType(org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenResponseType) StaticSTSProperties(org.apache.cxf.sts.StaticSTSProperties) JAXBElement(javax.xml.bind.JAXBElement) CustomTokenPrincipal(org.apache.wss4j.common.principal.CustomTokenPrincipal) Crypto(org.apache.wss4j.common.crypto.Crypto) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) WrappedMessageContext(org.apache.cxf.jaxws.context.WrappedMessageContext) SecurityContext(org.apache.cxf.security.SecurityContext) PasswordCallbackHandler(org.apache.cxf.sts.common.PasswordCallbackHandler) TokenProviderResponse(org.apache.cxf.sts.token.provider.TokenProviderResponse) SCTCanceller(org.apache.cxf.sts.token.canceller.SCTCanceller) MessageImpl(org.apache.cxf.message.MessageImpl) CustomTokenPrincipal(org.apache.wss4j.common.principal.CustomTokenPrincipal) Principal(java.security.Principal) TokenCanceller(org.apache.cxf.sts.token.canceller.TokenCanceller)

Example 27 with STSException

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

the class DefaultConditionsProvider method getConditions.

/**
 * Get a ConditionsBean object.
 */
@Override
public ConditionsBean getConditions(TokenProviderParameters providerParameters) {
    ConditionsBean conditions = new ConditionsBean();
    Lifetime tokenLifetime = providerParameters.getTokenRequirements().getLifetime();
    if (lifetime > 0) {
        if (acceptClientLifetime && tokenLifetime != null && (tokenLifetime.getCreated() != null || tokenLifetime.getExpires() != null)) {
            Instant creationTime = parsedInstantOrDefault(tokenLifetime.getCreated(), Instant.now());
            Instant expirationTime = parsedInstantOrDefault(tokenLifetime.getExpires(), creationTime.plusSeconds(lifetime));
            // Check to see if the created time is in the future
            Instant validCreation = Instant.now();
            if (futureTimeToLive > 0) {
                validCreation = validCreation.plusSeconds(futureTimeToLive);
            }
            if (creationTime.isAfter(validCreation)) {
                LOG.fine("The Created Time is too far in the future");
                throw new STSException("The Created Time is too far in the future", STSException.INVALID_TIME);
            }
            long requestedLifetime = Duration.between(creationTime, expirationTime).getSeconds();
            if (requestedLifetime > getMaxLifetime()) {
                StringBuilder sb = new StringBuilder();
                sb.append("Requested lifetime [").append(requestedLifetime);
                sb.append(" sec] exceed configured maximum lifetime [").append(getMaxLifetime());
                sb.append(" sec]");
                LOG.warning(sb.toString());
                if (isFailLifetimeExceedance()) {
                    throw new STSException("Requested lifetime exceeds maximum lifetime", STSException.INVALID_TIME);
                }
                expirationTime = creationTime.plusSeconds(getMaxLifetime());
            }
            conditions.setNotAfter(expirationTime);
            conditions.setNotBefore(creationTime);
        } else {
            conditions.setTokenPeriodSeconds(lifetime);
        }
    } else {
        conditions.setTokenPeriodMinutes(5);
    }
    List<AudienceRestrictionBean> audienceRestrictions = createAudienceRestrictions(providerParameters);
    if (audienceRestrictions != null && !audienceRestrictions.isEmpty()) {
        conditions.setAudienceRestrictions(audienceRestrictions);
    }
    return conditions;
}
Also used : Lifetime(org.apache.cxf.sts.request.Lifetime) AudienceRestrictionBean(org.apache.wss4j.common.saml.bean.AudienceRestrictionBean) Instant(java.time.Instant) ConditionsBean(org.apache.wss4j.common.saml.bean.ConditionsBean) STSException(org.apache.cxf.ws.security.sts.provider.STSException)

Example 28 with STSException

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

the class SAMLTokenProvider method testKeyType.

/**
 * Do some tests on the KeyType parameter.
 */
private void testKeyType(TokenProviderParameters tokenParameters) {
    KeyRequirements keyRequirements = tokenParameters.getKeyRequirements();
    String keyType = keyRequirements.getKeyType();
    if (STSConstants.PUBLIC_KEY_KEYTYPE.equals(keyType)) {
        if (keyRequirements.getReceivedCredential() == null || (keyRequirements.getReceivedCredential().getX509Cert() == null && keyRequirements.getReceivedCredential().getPublicKey() == null)) {
            LOG.log(Level.WARNING, "A PublicKey Keytype is requested, but no certificate is provided");
            throw new STSException("No client certificate for PublicKey KeyType", STSException.INVALID_REQUEST);
        }
    } else if (!STSConstants.SYMMETRIC_KEY_KEYTYPE.equals(keyType) && !STSConstants.BEARER_KEY_KEYTYPE.equals(keyType) && keyType != null) {
        LOG.log(Level.WARNING, "An unknown KeyType was requested: " + keyType);
        throw new STSException("Unknown KeyType", STSException.INVALID_REQUEST);
    }
}
Also used : STSException(org.apache.cxf.ws.security.sts.provider.STSException) KeyRequirements(org.apache.cxf.sts.request.KeyRequirements)

Example 29 with STSException

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

the class SAMLTokenProvider method createToken.

/**
 * Create a token given a TokenProviderParameters
 */
public TokenProviderResponse createToken(TokenProviderParameters tokenParameters) {
    testKeyType(tokenParameters);
    KeyRequirements keyRequirements = tokenParameters.getKeyRequirements();
    TokenRequirements tokenRequirements = tokenParameters.getTokenRequirements();
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("Handling token of type: " + tokenRequirements.getTokenType());
    }
    byte[] secret = null;
    byte[] entropyBytes = null;
    long keySize = 0;
    boolean computedKey = false;
    if (STSConstants.SYMMETRIC_KEY_KEYTYPE.equals(keyRequirements.getKeyType())) {
        SymmetricKeyHandler keyHandler = new SymmetricKeyHandler(tokenParameters);
        keyHandler.createSymmetricKey();
        secret = keyHandler.getSecret();
        entropyBytes = keyHandler.getEntropyBytes();
        keySize = keyHandler.getKeySize();
        computedKey = keyHandler.isComputedKey();
    }
    try {
        Document doc = DOMUtils.createDocument();
        SamlAssertionWrapper assertion = createSamlToken(tokenParameters, secret, doc);
        Element token = assertion.toDOM(doc);
        // set the token in cache (only if the token is signed)
        byte[] signatureValue = assertion.getSignatureValue();
        if (tokenParameters.getTokenStore() != null && signatureValue != null && signatureValue.length > 0) {
            SecurityToken securityToken = CacheUtils.createSecurityTokenForStorage(token, assertion.getId(), assertion.getNotOnOrAfter(), tokenParameters.getPrincipal(), tokenParameters.getRealm(), tokenParameters.getTokenRequirements().getRenewing());
            CacheUtils.storeTokenInCache(securityToken, tokenParameters.getTokenStore(), signatureValue);
        }
        TokenProviderResponse response = new TokenProviderResponse();
        String tokenType = tokenRequirements.getTokenType();
        if (WSS4JConstants.WSS_SAML2_TOKEN_TYPE.equals(tokenType) || WSS4JConstants.SAML2_NS.equals(tokenType)) {
            response.setTokenId(token.getAttributeNS(null, "ID"));
        } else {
            response.setTokenId(token.getAttributeNS(null, "AssertionID"));
        }
        if (tokenParameters.isEncryptToken()) {
            token = TokenProviderUtils.encryptToken(token, response.getTokenId(), tokenParameters.getStsProperties(), tokenParameters.getEncryptionProperties(), keyRequirements, tokenParameters.getMessageContext());
        }
        response.setToken(token);
        final DateTime validFrom;
        final DateTime validTill;
        if (assertion.getSamlVersion().equals(SAMLVersion.VERSION_20)) {
            validFrom = assertion.getSaml2().getConditions().getNotBefore();
            validTill = assertion.getSaml2().getConditions().getNotOnOrAfter();
        } else {
            validFrom = assertion.getSaml1().getConditions().getNotBefore();
            validTill = assertion.getSaml1().getConditions().getNotOnOrAfter();
        }
        response.setCreated(validFrom.toDate().toInstant());
        response.setExpires(validTill.toDate().toInstant());
        response.setEntropy(entropyBytes);
        if (keySize > 0) {
            response.setKeySize(keySize);
        }
        response.setComputedKey(computedKey);
        LOG.fine("SAML Token successfully created");
        if (secret != null) {
            Arrays.fill(secret, (byte) 0);
        }
        return response;
    } catch (Exception e) {
        LOG.log(Level.WARNING, "", e);
        throw new STSException("Can't serialize SAML assertion", e, STSException.REQUEST_FAILED);
    }
}
Also used : Element(org.w3c.dom.Element) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) STSException(org.apache.cxf.ws.security.sts.provider.STSException) Document(org.w3c.dom.Document) DateTime(org.joda.time.DateTime) STSException(org.apache.cxf.ws.security.sts.provider.STSException) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) TokenRequirements(org.apache.cxf.sts.request.TokenRequirements) KeyRequirements(org.apache.cxf.sts.request.KeyRequirements)

Example 30 with STSException

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

the class SymmetricKeyHandler method createSymmetricKey.

/**
 * Create the Symmetric Key
 */
public void createSymmetricKey() {
    computedKey = false;
    boolean generateEntropy = true;
    if (clientEntropy != null) {
        BinarySecret binarySecret = clientEntropy.getBinarySecret();
        if (binarySecret != null && (STSConstants.SYMMETRIC_KEY_TYPE.equals(binarySecret.getBinarySecretType()) || binarySecret.getBinarySecretType() == null)) {
            secret = binarySecret.getBinarySecretValue();
            generateEntropy = false;
        } else if (clientEntropy.getDecryptedKey() != null) {
            secret = clientEntropy.getDecryptedKey();
            generateEntropy = false;
        }
    }
    if (generateEntropy) {
        try {
            entropyBytes = WSSecurityUtil.generateNonce(keySize / 8);
            secret = entropyBytes;
        } catch (WSSecurityException ex) {
            LOG.log(Level.WARNING, "", ex);
            throw new STSException("Error in creating symmetric key", ex, STSException.INVALID_REQUEST);
        }
        if (clientEntropy != null && clientEntropy.getBinarySecret() != null) {
            byte[] nonce = clientEntropy.getBinarySecret().getBinarySecretValue();
            try {
                P_SHA1 psha1 = new P_SHA1();
                secret = psha1.createKey(nonce, entropyBytes, 0, keySize / 8);
                computedKey = true;
            } catch (WSSecurityException ex) {
                LOG.log(Level.WARNING, "", ex);
                throw new STSException("Error in creating symmetric key", STSException.INVALID_REQUEST);
            }
        }
    }
}
Also used : P_SHA1(org.apache.wss4j.common.derivedKey.P_SHA1) STSException(org.apache.cxf.ws.security.sts.provider.STSException) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) BinarySecret(org.apache.cxf.sts.request.BinarySecret)

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