Search in sources :

Example 1 with SAMLTokenPrincipalImpl

use of org.apache.wss4j.common.principal.SAMLTokenPrincipalImpl in project cxf by apache.

the class ActAsAttributeStatementProvider method handleAdditionalParameters.

/**
 * Handle an ActAs element.
 */
private AttributeBean handleAdditionalParameters(Object parameter, String tokenType) throws WSSecurityException {
    AttributeBean parameterBean = new AttributeBean();
    String claimType = "ActAs";
    if (WSS4JConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType) || WSS4JConstants.SAML_NS.equals(tokenType)) {
        parameterBean.setSimpleName(claimType);
        parameterBean.setQualifiedName("http://cxf.apache.org/sts");
    } else {
        parameterBean.setQualifiedName(claimType);
        parameterBean.setNameFormat("http://cxf.apache.org/sts");
    }
    if (parameter instanceof UsernameTokenType) {
        parameterBean.addAttributeValue(((UsernameTokenType) parameter).getUsername().getValue());
    } else if (parameter instanceof Element) {
        SamlAssertionWrapper wrapper = new SamlAssertionWrapper((Element) parameter);
        SAMLTokenPrincipal principal = new SAMLTokenPrincipalImpl(wrapper);
        parameterBean.addAttributeValue(principal.getName());
        // Check for other ActAs attributes here + add them in
        if (wrapper.getSaml2() != null) {
            for (org.opensaml.saml.saml2.core.AttributeStatement attributeStatement : wrapper.getSaml2().getAttributeStatements()) {
                for (org.opensaml.saml.saml2.core.Attribute attribute : attributeStatement.getAttributes()) {
                    if ("ActAs".equals(attribute.getName())) {
                        for (XMLObject attributeValue : attribute.getAttributeValues()) {
                            Element attributeValueElement = attributeValue.getDOM();
                            String text = attributeValueElement.getTextContent();
                            parameterBean.addAttributeValue(text);
                        }
                    }
                }
            }
        } else if (wrapper.getSaml1() != null) {
            for (org.opensaml.saml.saml1.core.AttributeStatement attributeStatement : wrapper.getSaml1().getAttributeStatements()) {
                for (org.opensaml.saml.saml1.core.Attribute attribute : attributeStatement.getAttributes()) {
                    if ("ActAs".equals(attribute.getAttributeName())) {
                        for (XMLObject attributeValue : attribute.getAttributeValues()) {
                            Element attributeValueElement = attributeValue.getDOM();
                            String text = attributeValueElement.getTextContent();
                            parameterBean.addAttributeValue(text);
                        }
                    }
                }
            }
        }
    }
    return parameterBean;
}
Also used : SAMLTokenPrincipal(org.apache.wss4j.common.principal.SAMLTokenPrincipal) UsernameTokenType(org.apache.cxf.ws.security.sts.provider.model.secext.UsernameTokenType) Element(org.w3c.dom.Element) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) XMLObject(org.opensaml.core.xml.XMLObject) AttributeBean(org.apache.wss4j.common.saml.bean.AttributeBean) SAMLTokenPrincipalImpl(org.apache.wss4j.common.principal.SAMLTokenPrincipalImpl)

Example 2 with SAMLTokenPrincipalImpl

use of org.apache.wss4j.common.principal.SAMLTokenPrincipalImpl 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 3 with SAMLTokenPrincipalImpl

use of org.apache.wss4j.common.principal.SAMLTokenPrincipalImpl in project cxf by apache.

the class CustomAttributeProvider method handleAdditionalParameters.

/**
 * Handle ActAs or OnBehalfOf elements.
 */
private AttributeBean handleAdditionalParameters(boolean actAs, Object parameter, String tokenType) throws WSSecurityException {
    AttributeBean parameterBean = new AttributeBean();
    String claimType = actAs ? "CustomActAs" : "CustomOnBehalfOf";
    if (WSS4JConstants.WSS_SAML2_TOKEN_TYPE.equals(tokenType) || WSS4JConstants.SAML2_NS.equals(tokenType)) {
        parameterBean.setQualifiedName(claimType);
        parameterBean.setNameFormat("http://cxf.apache.org/sts/custom/" + claimType);
    } else {
        parameterBean.setSimpleName(claimType);
        parameterBean.setQualifiedName("http://cxf.apache.org/sts/custom/" + claimType);
    }
    if (parameter instanceof UsernameTokenType) {
        parameterBean.addAttributeValue(((UsernameTokenType) parameter).getUsername().getValue());
    } else if (parameter instanceof Element) {
        SamlAssertionWrapper wrapper = new SamlAssertionWrapper((Element) parameter);
        SAMLTokenPrincipal principal = new SAMLTokenPrincipalImpl(wrapper);
        parameterBean.addAttributeValue(principal.getName());
    }
    return parameterBean;
}
Also used : SAMLTokenPrincipal(org.apache.wss4j.common.principal.SAMLTokenPrincipal) UsernameTokenType(org.apache.cxf.ws.security.sts.provider.model.secext.UsernameTokenType) Element(org.w3c.dom.Element) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) AttributeBean(org.apache.wss4j.common.saml.bean.AttributeBean) SAMLTokenPrincipalImpl(org.apache.wss4j.common.principal.SAMLTokenPrincipalImpl)

Example 4 with SAMLTokenPrincipalImpl

use of org.apache.wss4j.common.principal.SAMLTokenPrincipalImpl in project cxf by apache.

the class STSTokenValidator method validateWithSTS.

public Credential validateWithSTS(Credential credential, Message message) throws WSSecurityException {
    try {
        SecurityToken token = new SecurityToken();
        Element tokenElement = null;
        int hash = 0;
        if (credential.getSamlAssertion() != null) {
            SamlAssertionWrapper assertion = credential.getSamlAssertion();
            byte[] signatureValue = assertion.getSignatureValue();
            if (signatureValue != null && signatureValue.length > 0) {
                hash = Arrays.hashCode(signatureValue);
            }
            tokenElement = credential.getSamlAssertion().getElement();
        } else if (credential.getUsernametoken() != null) {
            tokenElement = credential.getUsernametoken().getElement();
            hash = credential.getUsernametoken().hashCode();
        } else if (credential.getBinarySecurityToken() != null) {
            tokenElement = credential.getBinarySecurityToken().getElement();
            hash = credential.getBinarySecurityToken().hashCode();
        } else if (credential.getSecurityContextToken() != null) {
            tokenElement = credential.getSecurityContextToken().getElement();
            hash = credential.getSecurityContextToken().hashCode();
        }
        token.setToken(tokenElement);
        TokenStore ts = null;
        if (!disableCaching) {
            ts = getTokenStore(message);
            if (ts == null) {
                ts = tokenStore;
            }
            if (ts != null && hash != 0) {
                SecurityToken transformedToken = getTransformedToken(ts, hash);
                if (transformedToken != null && !transformedToken.isExpired()) {
                    SamlAssertionWrapper assertion = new SamlAssertionWrapper(transformedToken.getToken());
                    credential.setPrincipal(new SAMLTokenPrincipalImpl(assertion));
                    credential.setTransformedToken(assertion);
                    return credential;
                }
            }
        }
        token.setTokenHash(hash);
        STSClient c = stsClient;
        if (c == null) {
            c = STSUtils.getClient(message, "sts");
        }
        synchronized (c) {
            System.setProperty("noprint", "true");
            SecurityToken returnedToken = null;
            if (useIssueBinding && useOnBehalfOf) {
                ElementCallbackHandler callbackHandler = new ElementCallbackHandler(tokenElement);
                c.setOnBehalfOf(callbackHandler);
                returnedToken = c.requestSecurityToken();
                c.setOnBehalfOf(null);
            } else if (useIssueBinding && !useOnBehalfOf && credential.getUsernametoken() != null) {
                c.getProperties().put(SecurityConstants.USERNAME, credential.getUsernametoken().getName());
                c.getProperties().put(SecurityConstants.PASSWORD, credential.getUsernametoken().getPassword());
                returnedToken = c.requestSecurityToken();
                c.getProperties().remove(SecurityConstants.USERNAME);
                c.getProperties().remove(SecurityConstants.PASSWORD);
            } else {
                List<SecurityToken> tokens = c.validateSecurityToken(token);
                returnedToken = tokens.get(0);
            }
            if (returnedToken != token) {
                SamlAssertionWrapper assertion = new SamlAssertionWrapper(returnedToken.getToken());
                credential.setTransformedToken(assertion);
                credential.setPrincipal(new SAMLTokenPrincipalImpl(assertion));
                if (!disableCaching && hash != 0 && ts != null) {
                    ts.add(returnedToken);
                    token.setTransformedTokenIdentifier(returnedToken.getId());
                    ts.add(Integer.toString(hash), token);
                }
            }
            return credential;
        }
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, e, "invalidSAMLsecurity");
    }
}
Also used : Element(org.w3c.dom.Element) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) IOException(java.io.IOException) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) List(java.util.List) TokenStore(org.apache.cxf.ws.security.tokenstore.TokenStore) SAMLTokenPrincipalImpl(org.apache.wss4j.common.principal.SAMLTokenPrincipalImpl)

Example 5 with SAMLTokenPrincipalImpl

use of org.apache.wss4j.common.principal.SAMLTokenPrincipalImpl in project cxf by apache.

the class UsernameTokenInterceptor method createSecurityContext.

private SecurityContext createSecurityContext(Message msg, SamlAssertionWrapper samlAssertion) {
    String roleAttributeName = (String) SecurityUtils.getSecurityPropertyValue(SecurityConstants.SAML_ROLE_ATTRIBUTENAME, msg);
    if (roleAttributeName == null || roleAttributeName.length() == 0) {
        roleAttributeName = WSS4JInInterceptor.SAML_ROLE_ATTRIBUTENAME_DEFAULT;
    }
    ClaimCollection claims = SAMLUtils.getClaims(samlAssertion);
    Set<Principal> roles = SAMLUtils.parseRolesFromClaims(claims, roleAttributeName, null);
    SAMLSecurityContext context = new SAMLSecurityContext(new SAMLTokenPrincipalImpl(samlAssertion), roles, claims);
    context.setIssuer(SAMLUtils.getIssuer(samlAssertion));
    context.setAssertionElement(SAMLUtils.getAssertionElement(samlAssertion));
    return context;
}
Also used : SAMLSecurityContext(org.apache.cxf.rt.security.saml.claims.SAMLSecurityContext) ClaimCollection(org.apache.cxf.rt.security.claims.ClaimCollection) SAMLTokenPrincipalImpl(org.apache.wss4j.common.principal.SAMLTokenPrincipalImpl) Principal(java.security.Principal) UsernameTokenPrincipal(org.apache.wss4j.common.principal.UsernameTokenPrincipal)

Aggregations

SAMLTokenPrincipalImpl (org.apache.wss4j.common.principal.SAMLTokenPrincipalImpl)6 SamlAssertionWrapper (org.apache.wss4j.common.saml.SamlAssertionWrapper)5 Element (org.w3c.dom.Element)4 SAMLTokenPrincipal (org.apache.wss4j.common.principal.SAMLTokenPrincipal)3 Principal (java.security.Principal)2 ReceivedToken (org.apache.cxf.sts.request.ReceivedToken)2 UsernameTokenType (org.apache.cxf.ws.security.sts.provider.model.secext.UsernameTokenType)2 SecurityToken (org.apache.cxf.ws.security.tokenstore.SecurityToken)2 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)2 AttributeBean (org.apache.wss4j.common.saml.bean.AttributeBean)2 IOException (java.io.IOException)1 X509Certificate (java.security.cert.X509Certificate)1 HashMap (java.util.HashMap)1 List (java.util.List)1 CallbackHandler (javax.security.auth.callback.CallbackHandler)1 UnsupportedCallbackException (javax.security.auth.callback.UnsupportedCallbackException)1 ClaimCollection (org.apache.cxf.rt.security.claims.ClaimCollection)1 SAMLSecurityContext (org.apache.cxf.rt.security.saml.claims.SAMLSecurityContext)1 STSPropertiesMBean (org.apache.cxf.sts.STSPropertiesMBean)1 STSIssueFailureEvent (org.apache.cxf.sts.event.STSIssueFailureEvent)1