Search in sources :

Example 21 with WSSConfig

use of org.apache.wss4j.dom.engine.WSSConfig in project cxf by apache.

the class AbstractSamlInHandler method validateToken.

protected void validateToken(Message message, SamlAssertionWrapper assertion) {
    try {
        RequestData data = new RequestData();
        data.setMsgContext(message);
        // Add Audience Restrictions for SAML
        configureAudienceRestriction(message, data);
        if (assertion.isSigned()) {
            WSSConfig cfg = WSSConfig.getNewInstance();
            data.setWssConfig(cfg);
            data.setCallbackHandler(RSSecurityUtils.getCallbackHandler(message, this.getClass()));
            try {
                data.setSigVerCrypto(new CryptoLoader().getCrypto(message, SecurityConstants.SIGNATURE_CRYPTO, SecurityConstants.SIGNATURE_PROPERTIES));
            } catch (IOException ex) {
                throwFault("Crypto can not be loaded", ex);
            }
            boolean enableRevocation = false;
            String enableRevocationStr = (String) org.apache.cxf.rt.security.utils.SecurityUtils.getSecurityPropertyValue(SecurityConstants.ENABLE_REVOCATION, message);
            if (enableRevocationStr != null) {
                enableRevocation = Boolean.parseBoolean(enableRevocationStr);
            }
            data.setEnableRevocation(enableRevocation);
            Signature sig = assertion.getSignature();
            WSDocInfo docInfo = new WSDocInfo(sig.getDOM().getOwnerDocument());
            data.setWsDocInfo(docInfo);
            SAMLKeyInfo samlKeyInfo = null;
            KeyInfo keyInfo = sig.getKeyInfo();
            if (keyInfo != null) {
                samlKeyInfo = SAMLUtil.getCredentialFromKeyInfo(keyInfo.getDOM(), new WSSSAMLKeyInfoProcessor(data), data.getSigVerCrypto());
            } else if (!keyInfoMustBeAvailable) {
                samlKeyInfo = createKeyInfoFromDefaultAlias(data.getSigVerCrypto());
            }
            assertion.verifySignature(samlKeyInfo);
            assertion.parseSubject(new WSSSAMLKeyInfoProcessor(data), data.getSigVerCrypto(), data.getCallbackHandler());
        } else if (getTLSCertificates(message) == null) {
            throwFault("Assertion must be signed", null);
        }
        if (samlValidator != null) {
            Credential credential = new Credential();
            credential.setSamlAssertion(assertion);
            samlValidator.validate(credential, data);
        }
        checkSubjectConfirmationData(message, assertion);
        setSecurityContext(message, assertion);
    } catch (Exception ex) {
        throwFault("Assertion can not be validated", ex);
    }
}
Also used : WSDocInfo(org.apache.wss4j.dom.WSDocInfo) Credential(org.apache.wss4j.dom.validate.Credential) CryptoLoader(org.apache.cxf.rs.security.common.CryptoLoader) IOException(java.io.IOException) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) IOException(java.io.IOException) SAMLKeyInfo(org.apache.wss4j.common.saml.SAMLKeyInfo) WSSConfig(org.apache.wss4j.dom.engine.WSSConfig) KeyInfo(org.opensaml.xmlsec.signature.KeyInfo) SAMLKeyInfo(org.apache.wss4j.common.saml.SAMLKeyInfo) RequestData(org.apache.wss4j.dom.handler.RequestData) Signature(org.opensaml.xmlsec.signature.Signature) WSSSAMLKeyInfoProcessor(org.apache.wss4j.dom.saml.WSSSAMLKeyInfoProcessor)

Example 22 with WSSConfig

use of org.apache.wss4j.dom.engine.WSSConfig in project cxf by apache.

the class SCTProvider method createToken.

/**
 * Create a token given a TokenProviderParameters
 */
public TokenProviderResponse createToken(TokenProviderParameters tokenParameters) {
    TokenRequirements tokenRequirements = tokenParameters.getTokenRequirements();
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("Handling token of type: " + tokenRequirements.getTokenType());
    }
    if (tokenParameters.getTokenStore() == null) {
        LOG.log(Level.FINE, "A cache must be configured to use the SCTProvider");
        throw new STSException("Can't serialize SCT", STSException.REQUEST_FAILED);
    }
    SymmetricKeyHandler keyHandler = new SymmetricKeyHandler(tokenParameters);
    keyHandler.createSymmetricKey();
    try {
        Document doc = DOMUtils.getEmptyDocument();
        SecurityContextToken sct = new SecurityContextToken(getWSCVersion(tokenRequirements.getTokenType()), doc);
        WSSConfig wssConfig = WSSConfig.getNewInstance();
        sct.setID(wssConfig.getIdAllocator().createId("sctId-", sct));
        TokenProviderResponse response = new TokenProviderResponse();
        response.setTokenId(sct.getIdentifier());
        if (returnEntropy) {
            response.setEntropy(keyHandler.getEntropyBytes());
        }
        long keySize = keyHandler.getKeySize();
        response.setKeySize(keySize);
        response.setComputedKey(keyHandler.isComputedKey());
        // putting the secret key into the cache
        Instant created = Instant.now();
        response.setCreated(created);
        Instant expires = null;
        if (lifetime > 0) {
            expires = created.plusSeconds(lifetime);
            response.setExpires(expires);
        }
        SecurityToken token = new SecurityToken(sct.getIdentifier(), created, expires);
        token.setSecret(keyHandler.getSecret());
        token.setPrincipal(tokenParameters.getPrincipal());
        Map<String, Object> props = token.getProperties();
        if (props == null) {
            props = new HashMap<>();
        }
        token.setProperties(props);
        if (tokenParameters.getRealm() != null) {
            props.put(STSConstants.TOKEN_REALM, tokenParameters.getRealm());
        }
        // Handle Renewing logic
        Renewing renewing = tokenParameters.getTokenRequirements().getRenewing();
        if (renewing != null) {
            props.put(STSConstants.TOKEN_RENEWING_ALLOW, String.valueOf(renewing.isAllowRenewing()));
            props.put(STSConstants.TOKEN_RENEWING_ALLOW_AFTER_EXPIRY, String.valueOf(renewing.isAllowRenewingAfterExpiry()));
        } else {
            props.put(STSConstants.TOKEN_RENEWING_ALLOW, "true");
            props.put(STSConstants.TOKEN_RENEWING_ALLOW_AFTER_EXPIRY, "false");
        }
        tokenParameters.getTokenStore().add(token);
        if (tokenParameters.isEncryptToken()) {
            Element el = TokenProviderUtils.encryptToken(sct.getElement(), response.getTokenId(), tokenParameters.getStsProperties(), tokenParameters.getEncryptionProperties(), tokenParameters.getKeyRequirements(), tokenParameters.getMessageContext());
            response.setToken(el);
        } else {
            response.setToken(sct.getElement());
        }
        // Create the references
        TokenReference attachedReference = new TokenReference();
        attachedReference.setIdentifier(sct.getID());
        attachedReference.setUseDirectReference(true);
        attachedReference.setWsseValueType(tokenRequirements.getTokenType());
        response.setAttachedReference(attachedReference);
        TokenReference unAttachedReference = new TokenReference();
        unAttachedReference.setIdentifier(sct.getIdentifier());
        unAttachedReference.setUseDirectReference(true);
        unAttachedReference.setWsseValueType(tokenRequirements.getTokenType());
        response.setUnattachedReference(unAttachedReference);
        LOG.fine("SecurityContextToken successfully created");
        return response;
    } catch (Exception e) {
        LOG.log(Level.WARNING, "", e);
        throw new STSException("Can't serialize SCT", e, STSException.REQUEST_FAILED);
    }
}
Also used : Renewing(org.apache.cxf.sts.request.Renewing) Instant(java.time.Instant) Element(org.w3c.dom.Element) STSException(org.apache.cxf.ws.security.sts.provider.STSException) Document(org.w3c.dom.Document) STSException(org.apache.cxf.ws.security.sts.provider.STSException) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) TokenRequirements(org.apache.cxf.sts.request.TokenRequirements) SecurityContextToken(org.apache.wss4j.dom.message.token.SecurityContextToken) WSSConfig(org.apache.wss4j.dom.engine.WSSConfig)

Example 23 with WSSConfig

use of org.apache.wss4j.dom.engine.WSSConfig in project cxf by apache.

the class UsernameTokenValidator method validateToken.

/**
 * Validate a Token using the given TokenValidatorParameters.
 */
public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
    LOG.fine("Validating UsernameToken");
    STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();
    Crypto sigCrypto = stsProperties.getSignatureCrypto();
    CallbackHandler callbackHandler = stsProperties.getCallbackHandler();
    RequestData requestData = new RequestData();
    requestData.setSigVerCrypto(sigCrypto);
    WSSConfig wssConfig = WSSConfig.getNewInstance();
    requestData.setWssConfig(wssConfig);
    requestData.setCallbackHandler(callbackHandler);
    requestData.setMsgContext(tokenParameters.getMessageContext());
    TokenValidatorResponse response = new TokenValidatorResponse();
    ReceivedToken validateTarget = tokenParameters.getToken();
    validateTarget.setState(STATE.INVALID);
    response.setToken(validateTarget);
    if (!validateTarget.isUsernameToken()) {
        return response;
    }
    // 
    // Turn the JAXB UsernameTokenType into a DOM Element for validation
    // 
    UsernameTokenType usernameTokenType = (UsernameTokenType) validateTarget.getToken();
    // Marshall the received JAXB object into a DOM Element
    final Element usernameTokenElement;
    try {
        Set<Class<?>> classes = new HashSet<>();
        classes.add(ObjectFactory.class);
        classes.add(org.apache.cxf.ws.security.sts.provider.model.wstrust14.ObjectFactory.class);
        CachedContextAndSchemas cache = JAXBContextCache.getCachedContextAndSchemas(classes, null, null, null, false);
        JAXBContext jaxbContext = cache.getContext();
        Marshaller marshaller = jaxbContext.createMarshaller();
        Document doc = DOMUtils.getEmptyDocument();
        Element rootElement = doc.createElement("root-element");
        JAXBElement<UsernameTokenType> tokenType = new JAXBElement<UsernameTokenType>(QNameConstants.USERNAME_TOKEN, UsernameTokenType.class, usernameTokenType);
        marshaller.marshal(tokenType, rootElement);
        usernameTokenElement = (Element) rootElement.getFirstChild();
    } catch (JAXBException ex) {
        LOG.log(Level.WARNING, "", ex);
        return response;
    }
    // 
    try {
        boolean allowNamespaceQualifiedPasswordTypes = requestData.isAllowNamespaceQualifiedPasswordTypes();
        UsernameToken ut = new UsernameToken(usernameTokenElement, allowNamespaceQualifiedPasswordTypes, new BSPEnforcer());
        // The parsed principal is set independent whether validation is successful or not
        response.setPrincipal(new CustomTokenPrincipal(ut.getName()));
        if (ut.getPassword() == null) {
            return response;
        }
        // See if the UsernameToken is stored in the cache
        int hash = ut.hashCode();
        SecurityToken secToken = null;
        if (tokenParameters.getTokenStore() != null) {
            secToken = tokenParameters.getTokenStore().getToken(Integer.toString(hash));
            if (secToken != null && (secToken.getTokenHash() != hash || secToken.isExpired())) {
                secToken = null;
            }
        }
        Principal principal = null;
        if (secToken == null) {
            Credential credential = new Credential();
            credential.setUsernametoken(ut);
            credential = validator.validate(credential, requestData);
            principal = credential.getPrincipal();
            if (credential.getSubject() != null && roleParser != null) {
                // Parse roles from the validated token
                Set<Principal> roles = roleParser.parseRolesFromSubject(principal, credential.getSubject());
                response.setRoles(roles);
            }
        }
        if (principal == null) {
            principal = createPrincipal(ut.getName(), ut.getPassword(), ut.getPasswordType(), ut.getNonce(), ut.getCreated());
        }
        // Get the realm of the UsernameToken
        String tokenRealm = null;
        if (usernameTokenRealmCodec != null) {
            tokenRealm = usernameTokenRealmCodec.getRealmFromToken(ut);
            // verify the realm against the cached token
            if (secToken != null) {
                Map<String, Object> props = secToken.getProperties();
                if (props != null) {
                    String cachedRealm = (String) props.get(STSConstants.TOKEN_REALM);
                    if (!tokenRealm.equals(cachedRealm)) {
                        return response;
                    }
                }
            }
        }
        // Store the successfully validated token in the cache
        if (tokenParameters.getTokenStore() != null && secToken == null) {
            secToken = new SecurityToken(ut.getID());
            secToken.setToken(ut.getElement());
            int hashCode = ut.hashCode();
            String identifier = Integer.toString(hashCode);
            secToken.setTokenHash(hashCode);
            tokenParameters.getTokenStore().add(identifier, secToken);
        }
        response.setPrincipal(principal);
        response.setTokenRealm(tokenRealm);
        validateTarget.setState(STATE.VALID);
        LOG.fine("Username Token successfully validated");
    } catch (WSSecurityException ex) {
        LOG.log(Level.WARNING, "", ex);
    }
    return response;
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) JAXBElement(javax.xml.bind.JAXBElement) Element(org.w3c.dom.Element) UsernameToken(org.apache.wss4j.dom.message.token.UsernameToken) JAXBContext(javax.xml.bind.JAXBContext) Document(org.w3c.dom.Document) CustomTokenPrincipal(org.apache.wss4j.common.principal.CustomTokenPrincipal) WSSConfig(org.apache.wss4j.dom.engine.WSSConfig) RequestData(org.apache.wss4j.dom.handler.RequestData) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken) CachedContextAndSchemas(org.apache.cxf.common.jaxb.JAXBContextCache.CachedContextAndSchemas) HashSet(java.util.HashSet) Marshaller(javax.xml.bind.Marshaller) Credential(org.apache.wss4j.dom.validate.Credential) UsernameTokenType(org.apache.cxf.ws.security.sts.provider.model.secext.UsernameTokenType) JAXBException(javax.xml.bind.JAXBException) BSPEnforcer(org.apache.wss4j.common.bsp.BSPEnforcer) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) JAXBElement(javax.xml.bind.JAXBElement) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) Crypto(org.apache.wss4j.common.crypto.Crypto) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) CustomTokenPrincipal(org.apache.wss4j.common.principal.CustomTokenPrincipal) Principal(java.security.Principal)

Example 24 with WSSConfig

use of org.apache.wss4j.dom.engine.WSSConfig in project cxf by apache.

the class SAMLTokenRenewer method validateAssertion.

private void validateAssertion(SamlAssertionWrapper assertion, ReceivedToken tokenToRenew, SecurityToken token, TokenRenewerParameters tokenParameters) throws WSSecurityException {
    // Check the cached renewal properties
    Map<String, Object> props = token.getProperties();
    if (props == null) {
        LOG.log(Level.WARNING, "Error in getting properties from cached token");
        throw new STSException("Error in getting properties from cached token", STSException.REQUEST_FAILED);
    }
    String isAllowRenewal = (String) props.get(STSConstants.TOKEN_RENEWING_ALLOW);
    String isAllowRenewalAfterExpiry = (String) props.get(STSConstants.TOKEN_RENEWING_ALLOW_AFTER_EXPIRY);
    if (isAllowRenewal == null || !Boolean.valueOf(isAllowRenewal)) {
        LOG.log(Level.WARNING, "The token is not allowed to be renewed");
        throw new STSException("The token is not allowed to be renewed", STSException.REQUEST_FAILED);
    }
    // Check to see whether the token has expired greater than the configured max expiry time
    if (tokenToRenew.getState() == STATE.EXPIRED) {
        if (!allowRenewalAfterExpiry || isAllowRenewalAfterExpiry == null || !Boolean.valueOf(isAllowRenewalAfterExpiry)) {
            LOG.log(Level.WARNING, "Renewal after expiry is not allowed");
            throw new STSException("Renewal after expiry is not allowed", STSException.REQUEST_FAILED);
        }
        DateTime expiryDate = getExpiryDate(assertion);
        DateTime currentDate = new DateTime();
        if ((currentDate.getMillis() - expiryDate.getMillis()) > (maxExpiry * 1000L)) {
            LOG.log(Level.WARNING, "The token expired too long ago to be renewed");
            throw new STSException("The token expired too long ago to be renewed", STSException.REQUEST_FAILED);
        }
    }
    // Verify Proof of Possession
    ProofOfPossessionValidator popValidator = new ProofOfPossessionValidator();
    if (verifyProofOfPossession) {
        STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();
        Crypto sigCrypto = stsProperties.getSignatureCrypto();
        CallbackHandler callbackHandler = stsProperties.getCallbackHandler();
        RequestData requestData = new RequestData();
        requestData.setSigVerCrypto(sigCrypto);
        WSSConfig wssConfig = WSSConfig.getNewInstance();
        requestData.setWssConfig(wssConfig);
        WSDocInfo docInfo = new WSDocInfo(((Element) tokenToRenew.getToken()).getOwnerDocument());
        requestData.setWsDocInfo(docInfo);
        // Parse the HOK subject if it exists
        assertion.parseSubject(new WSSSAMLKeyInfoProcessor(requestData), sigCrypto, callbackHandler);
        SAMLKeyInfo keyInfo = assertion.getSubjectKeyInfo();
        if (keyInfo == null) {
            keyInfo = new SAMLKeyInfo((byte[]) null);
        }
        if (!popValidator.checkProofOfPossession(tokenParameters, keyInfo)) {
            throw new STSException("Failed to verify the proof of possession of the key associated with the " + "saml token. No matching key found in the request.", STSException.INVALID_REQUEST);
        }
    }
    // Check the AppliesTo address
    String appliesToAddress = tokenParameters.getAppliesToAddress();
    if (appliesToAddress != null) {
        if (assertion.getSaml1() != null) {
            List<AudienceRestrictionCondition> restrConditions = assertion.getSaml1().getConditions().getAudienceRestrictionConditions();
            if (!matchSaml1AudienceRestriction(appliesToAddress, restrConditions)) {
                LOG.log(Level.WARNING, "The AppliesTo address does not match the Audience Restriction");
                throw new STSException("The AppliesTo address does not match the Audience Restriction", STSException.INVALID_REQUEST);
            }
        } else {
            List<AudienceRestriction> audienceRestrs = assertion.getSaml2().getConditions().getAudienceRestrictions();
            if (!matchSaml2AudienceRestriction(appliesToAddress, audienceRestrs)) {
                LOG.log(Level.WARNING, "The AppliesTo address does not match the Audience Restriction");
                throw new STSException("The AppliesTo address does not match the Audience Restriction", STSException.INVALID_REQUEST);
            }
        }
    }
}
Also used : WSDocInfo(org.apache.wss4j.dom.WSDocInfo) CallbackHandler(javax.security.auth.callback.CallbackHandler) STSException(org.apache.cxf.ws.security.sts.provider.STSException) DateTime(org.joda.time.DateTime) Crypto(org.apache.wss4j.common.crypto.Crypto) AudienceRestriction(org.opensaml.saml.saml2.core.AudienceRestriction) SAMLKeyInfo(org.apache.wss4j.common.saml.SAMLKeyInfo) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) WSSConfig(org.apache.wss4j.dom.engine.WSSConfig) RequestData(org.apache.wss4j.dom.handler.RequestData) AudienceRestrictionCondition(org.opensaml.saml.saml1.core.AudienceRestrictionCondition) WSSSAMLKeyInfoProcessor(org.apache.wss4j.dom.saml.WSSSAMLKeyInfoProcessor)

Aggregations

WSSConfig (org.apache.wss4j.dom.engine.WSSConfig)24 RequestData (org.apache.wss4j.dom.handler.RequestData)16 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)15 Credential (org.apache.wss4j.dom.validate.Credential)12 WSDocInfo (org.apache.wss4j.dom.WSDocInfo)11 WSSSAMLKeyInfoProcessor (org.apache.wss4j.dom.saml.WSSSAMLKeyInfoProcessor)10 Crypto (org.apache.wss4j.common.crypto.Crypto)9 SAMLKeyInfo (org.apache.wss4j.common.saml.SAMLKeyInfo)8 Element (org.w3c.dom.Element)8 STSPropertiesMBean (org.apache.cxf.sts.STSPropertiesMBean)7 KeyInfo (org.opensaml.xmlsec.signature.KeyInfo)7 Document (org.w3c.dom.Document)7 CallbackHandler (javax.security.auth.callback.CallbackHandler)6 Principal (java.security.Principal)5 ReceivedToken (org.apache.cxf.sts.request.ReceivedToken)5 SecurityToken (org.apache.cxf.ws.security.tokenstore.SecurityToken)5 Validator (org.apache.wss4j.dom.validate.Validator)4 BasicX509Credential (org.opensaml.security.x509.BasicX509Credential)4 X509Certificate (java.security.cert.X509Certificate)3 Map (java.util.Map)3