Search in sources :

Example 11 with STSPropertiesMBean

use of org.apache.cxf.sts.STSPropertiesMBean in project cxf by apache.

the class SamlCallbackHandler method handle.

public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
    for (Callback callback : callbacks) {
        if (callback instanceof SAMLCallback) {
            SAMLCallback samlCallback = (SAMLCallback) callback;
            // Set the Subject
            if (subjectBean != null) {
                samlCallback.setSubject(subjectBean);
            }
            // Set the token Type.
            TokenRequirements tokenRequirements = tokenParameters.getTokenRequirements();
            String tokenType = tokenRequirements.getTokenType();
            boolean saml1 = false;
            if (WSS4JConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType) || WSS4JConstants.SAML_NS.equals(tokenType)) {
                samlCallback.setSamlVersion(Version.SAML_11);
                saml1 = true;
                setSubjectOnBeans();
            } else {
                samlCallback.setSamlVersion(Version.SAML_20);
            }
            // Set the issuer
            if (issuer == null) {
                STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();
                samlCallback.setIssuer(stsProperties.getIssuer());
            } else {
                samlCallback.setIssuer(issuer);
            }
            // Set the statements
            boolean statementAdded = false;
            if (attributeBeans != null && !attributeBeans.isEmpty()) {
                samlCallback.setAttributeStatementData(attributeBeans);
                statementAdded = true;
            }
            if (authBeans != null && !authBeans.isEmpty()) {
                samlCallback.setAuthenticationStatementData(authBeans);
                statementAdded = true;
            }
            if (authDecisionBeans != null && !authDecisionBeans.isEmpty()) {
                samlCallback.setAuthDecisionStatementData(authDecisionBeans);
                statementAdded = true;
            }
            // If SAML 1.1 we *must* add a Statement
            if (saml1 && !statementAdded) {
                AttributeStatementBean defaultStatement = new DefaultAttributeStatementProvider().getStatement(tokenParameters);
                defaultStatement.setSubject(subjectBean);
                samlCallback.setAttributeStatementData(Collections.singletonList(defaultStatement));
            }
            // Set the conditions
            samlCallback.setConditions(conditionsBean);
        }
    }
}
Also used : AttributeStatementBean(org.apache.wss4j.common.saml.bean.AttributeStatementBean) SAMLCallback(org.apache.wss4j.common.saml.SAMLCallback) Callback(javax.security.auth.callback.Callback) TokenRequirements(org.apache.cxf.sts.request.TokenRequirements) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) SAMLCallback(org.apache.wss4j.common.saml.SAMLCallback)

Example 12 with STSPropertiesMBean

use of org.apache.cxf.sts.STSPropertiesMBean in project cxf by apache.

the class DefaultJWTClaimsProvider method getJwtClaims.

/**
 * Get a JwtClaims object.
 */
public JwtClaims getJwtClaims(JWTClaimsProviderParameters jwtClaimsProviderParameters) {
    JwtClaims claims = new JwtClaims();
    claims.setSubject(getSubjectName(jwtClaimsProviderParameters));
    claims.setTokenId(UUID.randomUUID().toString());
    // Set the Issuer
    String issuer = jwtClaimsProviderParameters.getIssuer();
    if (issuer == null) {
        STSPropertiesMBean stsProperties = jwtClaimsProviderParameters.getProviderParameters().getStsProperties();
        claims.setIssuer(stsProperties.getIssuer());
    } else {
        claims.setIssuer(issuer);
    }
    handleWSTrustClaims(jwtClaimsProviderParameters, claims);
    handleConditions(jwtClaimsProviderParameters, claims);
    handleAudienceRestriction(jwtClaimsProviderParameters, claims);
    handleActAs(jwtClaimsProviderParameters, claims);
    return claims;
}
Also used : JwtClaims(org.apache.cxf.rs.security.jose.jwt.JwtClaims) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean)

Example 13 with STSPropertiesMBean

use of org.apache.cxf.sts.STSPropertiesMBean in project cxf by apache.

the class SAMLTokenRenewer method signAssertion.

private void signAssertion(SamlAssertionWrapper assertion, TokenRenewerParameters tokenParameters) throws Exception {
    if (signToken) {
        STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();
        String realm = tokenParameters.getRealm();
        RealmProperties samlRealm = null;
        if (realm != null && realmMap.containsKey(realm)) {
            samlRealm = realmMap.get(realm);
        }
        signToken(assertion, samlRealm, stsProperties, tokenParameters.getKeyRequirements());
    } else {
        if (assertion.getSaml1().getSignature() != null) {
            assertion.getSaml1().setSignature(null);
        } else if (assertion.getSaml2().getSignature() != null) {
            assertion.getSaml2().setSignature(null);
        }
    }
}
Also used : STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) RealmProperties(org.apache.cxf.sts.token.realm.RealmProperties)

Example 14 with STSPropertiesMBean

use of org.apache.cxf.sts.STSPropertiesMBean in project cxf by apache.

the class SAMLTokenValidator method validateToken.

/**
 * Validate a Token using the given TokenValidatorParameters.
 */
public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
    LOG.fine("Validating SAML Token");
    STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();
    Crypto sigCrypto = stsProperties.getSignatureCrypto();
    CallbackHandler callbackHandler = stsProperties.getCallbackHandler();
    TokenValidatorResponse response = new TokenValidatorResponse();
    ReceivedToken validateTarget = tokenParameters.getToken();
    validateTarget.setState(STATE.INVALID);
    response.setToken(validateTarget);
    if (!validateTarget.isDOMElement()) {
        return response;
    }
    try {
        Element validateTargetElement = (Element) validateTarget.getToken();
        SamlAssertionWrapper assertion = new SamlAssertionWrapper(validateTargetElement);
        if (!assertion.isSigned()) {
            LOG.log(Level.WARNING, "The received assertion is not signed, and therefore not trusted");
            return response;
        }
        RequestData requestData = new RequestData();
        requestData.setSigVerCrypto(sigCrypto);
        WSSConfig wssConfig = WSSConfig.getNewInstance();
        requestData.setWssConfig(wssConfig);
        requestData.setCallbackHandler(callbackHandler);
        requestData.setMsgContext(tokenParameters.getMessageContext());
        requestData.setSubjectCertConstraints(certConstraints.getCompiledSubjectContraints());
        requestData.setWsDocInfo(new WSDocInfo(validateTargetElement.getOwnerDocument()));
        // Verify the signature
        Signature sig = assertion.getSignature();
        KeyInfo keyInfo = sig.getKeyInfo();
        SAMLKeyInfo samlKeyInfo = SAMLUtil.getCredentialFromKeyInfo(keyInfo.getDOM(), new WSSSAMLKeyInfoProcessor(requestData), sigCrypto);
        assertion.verifySignature(samlKeyInfo);
        SecurityToken secToken = null;
        byte[] signatureValue = assertion.getSignatureValue();
        if (tokenParameters.getTokenStore() != null && signatureValue != null && signatureValue.length > 0) {
            int hash = Arrays.hashCode(signatureValue);
            secToken = tokenParameters.getTokenStore().getToken(Integer.toString(hash));
            if (secToken != null && secToken.getTokenHash() != hash) {
                secToken = null;
            }
        }
        if (secToken != null && secToken.isExpired()) {
            if (LOG.isLoggable(Level.FINE)) {
                LOG.fine("Token: " + secToken.getId() + " is in the cache but expired - revalidating");
            }
            secToken = null;
        }
        Principal principal = null;
        if (secToken == null) {
            // Validate the assertion against schemas/profiles
            validateAssertion(assertion);
            // Now verify trust on the signature
            Credential trustCredential = new Credential();
            trustCredential.setPublicKey(samlKeyInfo.getPublicKey());
            trustCredential.setCertificates(samlKeyInfo.getCerts());
            trustCredential = validator.validate(trustCredential, requestData);
            principal = trustCredential.getPrincipal();
            // Finally check that subject DN of the signing certificate matches a known constraint
            X509Certificate cert = null;
            if (trustCredential.getCertificates() != null) {
                cert = trustCredential.getCertificates()[0];
            }
            if (!certConstraints.matches(cert)) {
                return response;
            }
        }
        if (principal == null) {
            principal = new SAMLTokenPrincipalImpl(assertion);
        }
        // Parse roles from the validated token
        if (samlRoleParser != null) {
            Set<Principal> roles = samlRoleParser.parseRolesFromAssertion(principal, null, assertion);
            response.setRoles(roles);
        }
        // Get the realm of the SAML token
        String tokenRealm = null;
        SAMLRealmCodec codec = samlRealmCodec;
        if (codec == null) {
            codec = stsProperties.getSamlRealmCodec();
        }
        if (codec != null) {
            tokenRealm = codec.getRealmFromToken(assertion);
            // 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 (cachedRealm != null && !tokenRealm.equals(cachedRealm)) {
                        return response;
                    }
                }
            }
        }
        response.setTokenRealm(tokenRealm);
        if (!validateConditions(assertion, validateTarget)) {
            return response;
        }
        // Store the successfully validated token in the cache
        if (secToken == null) {
            storeTokenInCache(tokenParameters.getTokenStore(), assertion, tokenParameters.getPrincipal(), tokenRealm);
        }
        // Add the SamlAssertionWrapper to the properties, as the claims are required to be transformed
        Map<String, Object> addProps = new HashMap<>(1);
        addProps.put(SamlAssertionWrapper.class.getName(), assertion);
        response.setAdditionalProperties(addProps);
        response.setPrincipal(principal);
        validateTarget.setState(STATE.VALID);
        LOG.fine("SAML Token successfully validated");
    } catch (WSSecurityException ex) {
        LOG.log(Level.WARNING, "", ex);
    }
    return response;
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) HashMap(java.util.HashMap) Element(org.w3c.dom.Element) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) SAMLRealmCodec(org.apache.cxf.sts.token.realm.SAMLRealmCodec) 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) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken) SAMLTokenPrincipalImpl(org.apache.wss4j.common.principal.SAMLTokenPrincipalImpl) WSDocInfo(org.apache.wss4j.dom.WSDocInfo) Credential(org.apache.wss4j.dom.validate.Credential) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) X509Certificate(java.security.cert.X509Certificate) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) Crypto(org.apache.wss4j.common.crypto.Crypto) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) Signature(org.opensaml.xmlsec.signature.Signature) WSSSAMLKeyInfoProcessor(org.apache.wss4j.dom.saml.WSSSAMLKeyInfoProcessor) Principal(java.security.Principal)

Example 15 with STSPropertiesMBean

use of org.apache.cxf.sts.STSPropertiesMBean in project cxf by apache.

the class X509TokenValidator method validateToken.

/**
 * Validate a Token using the given TokenValidatorParameters.
 */
public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
    LOG.fine("Validating X.509 Token");
    STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();
    CallbackHandler callbackHandler = stsProperties.getCallbackHandler();
    // See CXF-4028
    Crypto crypto = stsProperties.getEncryptionCrypto();
    if (crypto == null) {
        crypto = stsProperties.getSignatureCrypto();
    }
    RequestData requestData = new RequestData();
    requestData.setSigVerCrypto(crypto);
    requestData.setWssConfig(WSSConfig.getNewInstance());
    requestData.setCallbackHandler(callbackHandler);
    requestData.setMsgContext(tokenParameters.getMessageContext());
    requestData.setSubjectCertConstraints(certConstraints.getCompiledSubjectContraints());
    TokenValidatorResponse response = new TokenValidatorResponse();
    ReceivedToken validateTarget = tokenParameters.getToken();
    validateTarget.setState(STATE.INVALID);
    response.setToken(validateTarget);
    BinarySecurity binarySecurity = null;
    if (validateTarget.isBinarySecurityToken()) {
        BinarySecurityTokenType binarySecurityType = (BinarySecurityTokenType) validateTarget.getToken();
        // Test the encoding type
        String encodingType = binarySecurityType.getEncodingType();
        if (!BASE64_ENCODING.equals(encodingType)) {
            LOG.fine("Bad encoding type attribute specified: " + encodingType);
            return response;
        }
        // 
        // Turn the received JAXB object into a DOM element
        // 
        Document doc = DOMUtils.getEmptyDocument();
        binarySecurity = new X509Security(doc);
        binarySecurity.setEncodingType(encodingType);
        binarySecurity.setValueType(binarySecurityType.getValueType());
        String data = binarySecurityType.getValue();
        Node textNode = doc.createTextNode(data);
        binarySecurity.getElement().appendChild(textNode);
    } else if (validateTarget.isDOMElement()) {
        try {
            Document doc = DOMUtils.getEmptyDocument();
            binarySecurity = new X509Security(doc);
            binarySecurity.setEncodingType(BASE64_ENCODING);
            X509Data x509Data = new X509Data((Element) validateTarget.getToken(), "");
            if (x509Data.containsCertificate()) {
                X509Certificate cert = x509Data.itemCertificate(0).getX509Certificate();
                ((X509Security) binarySecurity).setX509Certificate(cert);
            }
        } catch (WSSecurityException ex) {
            LOG.log(Level.WARNING, "", ex);
            return response;
        } catch (XMLSecurityException ex) {
            LOG.log(Level.WARNING, "", ex);
            return response;
        }
    } else {
        return response;
    }
    // 
    try {
        Credential credential = new Credential();
        credential.setBinarySecurityToken(binarySecurity);
        if (crypto != null) {
            X509Certificate cert = ((X509Security) binarySecurity).getX509Certificate(crypto);
            credential.setCertificates(new X509Certificate[] { cert });
        }
        Credential returnedCredential = validator.validate(credential, requestData);
        Principal principal = returnedCredential.getPrincipal();
        if (principal == null) {
            principal = returnedCredential.getCertificates()[0].getSubjectX500Principal();
        }
        response.setPrincipal(principal);
        validateTarget.setState(STATE.VALID);
        LOG.fine("X.509 Token successfully validated");
    } catch (WSSecurityException ex) {
        LOG.log(Level.WARNING, "", ex);
    }
    return response;
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) Credential(org.apache.wss4j.dom.validate.Credential) BinarySecurity(org.apache.wss4j.common.token.BinarySecurity) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) Document(org.w3c.dom.Document) X509Data(org.apache.xml.security.keys.content.X509Data) X509Certificate(java.security.cert.X509Certificate) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException) Crypto(org.apache.wss4j.common.crypto.Crypto) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) BinarySecurityTokenType(org.apache.cxf.ws.security.sts.provider.model.secext.BinarySecurityTokenType) RequestData(org.apache.wss4j.dom.handler.RequestData) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken) X509Security(org.apache.wss4j.common.token.X509Security) Principal(java.security.Principal)

Aggregations

STSPropertiesMBean (org.apache.cxf.sts.STSPropertiesMBean)122 Crypto (org.apache.wss4j.common.crypto.Crypto)93 ArrayList (java.util.ArrayList)86 JAXBElement (javax.xml.bind.JAXBElement)86 WrappedMessageContext (org.apache.cxf.jaxws.context.WrappedMessageContext)83 MessageImpl (org.apache.cxf.message.MessageImpl)83 StaticSTSProperties (org.apache.cxf.sts.StaticSTSProperties)83 RequestSecurityTokenType (org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenType)83 RequestSecurityTokenResponseType (org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenResponseType)79 PasswordCallbackHandler (org.apache.cxf.sts.common.PasswordCallbackHandler)75 Element (org.w3c.dom.Element)70 TokenProvider (org.apache.cxf.sts.token.provider.TokenProvider)65 Principal (java.security.Principal)56 ServiceMBean (org.apache.cxf.sts.service.ServiceMBean)54 StaticService (org.apache.cxf.sts.service.StaticService)54 CustomTokenPrincipal (org.apache.wss4j.common.principal.CustomTokenPrincipal)54 SecurityContext (org.apache.cxf.security.SecurityContext)49 SAMLTokenProvider (org.apache.cxf.sts.token.provider.SAMLTokenProvider)49 RequestSecurityTokenResponseCollectionType (org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenResponseCollectionType)49 RequestedSecurityTokenType (org.apache.cxf.ws.security.sts.provider.model.RequestedSecurityTokenType)49