Search in sources :

Example 86 with SamlAssertionWrapper

use of org.apache.wss4j.common.saml.SamlAssertionWrapper in project cxf by apache.

the class AbstractBindingBuilder method addSamlToken.

protected SamlAssertionWrapper addSamlToken(SamlToken token) throws WSSecurityException {
    assertToken(token);
    if (!isTokenRequired(token.getIncludeTokenType())) {
        return null;
    }
    // 
    // Get the SAML CallbackHandler
    // 
    Object o = SecurityUtils.getSecurityPropertyValue(SecurityConstants.SAML_CALLBACK_HANDLER, message);
    if (o == null) {
        SecurityToken securityToken = getSecurityToken();
        if (securityToken != null) {
            Element tokenElement = securityToken.getToken();
            String namespace = tokenElement.getNamespaceURI();
            String localname = tokenElement.getLocalName();
            SamlTokenType tokenType = token.getSamlTokenType();
            if ((tokenType == SamlTokenType.WssSamlV11Token10 || tokenType == SamlTokenType.WssSamlV11Token11) && WSS4JConstants.SAML_NS.equals(namespace) && "Assertion".equals(localname)) {
                return new SamlAssertionWrapper(tokenElement);
            } else if (tokenType == SamlTokenType.WssSamlV20Token11 && WSS4JConstants.SAML2_NS.equals(namespace) && "Assertion".equals(localname)) {
                return new SamlAssertionWrapper(tokenElement);
            }
        }
    }
    SAMLCallback samlCallback = new SAMLCallback();
    SamlTokenType tokenType = token.getSamlTokenType();
    if (tokenType == SamlTokenType.WssSamlV11Token10 || tokenType == SamlTokenType.WssSamlV11Token11) {
        samlCallback.setSamlVersion(Version.SAML_11);
    } else if (tokenType == SamlTokenType.WssSamlV20Token11) {
        samlCallback.setSamlVersion(Version.SAML_20);
    }
    try {
        CallbackHandler handler = SecurityUtils.getCallbackHandler(o);
        if (handler == null) {
            unassertPolicy(token, "No SAML CallbackHandler available");
            return null;
        }
        SAMLUtil.doSAMLCallback(handler, samlCallback);
    } catch (Exception ex) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ex);
    }
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);
    if (samlCallback.isSignAssertion()) {
        String issuerName = samlCallback.getIssuerKeyName();
        if (issuerName == null) {
            String userNameKey = SecurityConstants.SIGNATURE_USERNAME;
            issuerName = (String) SecurityUtils.getSecurityPropertyValue(userNameKey, message);
        }
        String password = samlCallback.getIssuerKeyPassword();
        if (password == null) {
            password = getPassword(issuerName, token, WSPasswordCallback.SIGNATURE);
        }
        Crypto crypto = samlCallback.getIssuerCrypto();
        if (crypto == null) {
            crypto = getSignatureCrypto();
        }
        assertion.signAssertion(issuerName, password, crypto, samlCallback.isSendKeyValue(), samlCallback.getCanonicalizationAlgorithm(), samlCallback.getSignatureAlgorithm(), samlCallback.getSignatureDigestAlgorithm());
    }
    return assertion;
}
Also used : SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) SamlTokenType(org.apache.wss4j.policy.model.SamlToken.SamlTokenType) CallbackHandler(javax.security.auth.callback.CallbackHandler) AttachmentCallbackHandler(org.apache.cxf.ws.security.wss4j.AttachmentCallbackHandler) Crypto(org.apache.wss4j.common.crypto.Crypto) Element(org.w3c.dom.Element) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) SAMLCallback(org.apache.wss4j.common.saml.SAMLCallback) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) SOAPException(javax.xml.soap.SOAPException) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) XMLStreamException(javax.xml.stream.XMLStreamException) XPathExpressionException(javax.xml.xpath.XPathExpressionException)

Example 87 with SamlAssertionWrapper

use of org.apache.wss4j.common.saml.SamlAssertionWrapper in project cxf by apache.

the class AbstractBindingBuilder method handleSupportingTokens.

protected List<SupportingToken> handleSupportingTokens(SupportingTokens suppTokens, boolean endorse, List<SupportingToken> ret) throws WSSecurityException, SOAPException {
    if (suppTokens == null) {
        return ret;
    }
    for (AbstractToken token : suppTokens.getTokens()) {
        assertToken(token);
        if (!isTokenRequired(token.getIncludeTokenType())) {
            // Check for any SignedParts so as *not* to sign them
            getSignedParts(suppTokens);
            continue;
        }
        if (token instanceof UsernameToken) {
            handleUsernameTokenSupportingToken((UsernameToken) token, endorse, suppTokens.isEncryptedToken(), ret);
        } else if (token instanceof IssuedToken || token instanceof SecureConversationToken || token instanceof SecurityContextToken || token instanceof KerberosToken || token instanceof SpnegoContextToken) {
            // ws-trust/ws-sc stuff.......
            SecurityToken secToken = getSecurityToken();
            if (secToken == null) {
                unassertPolicy(token, "Could not find IssuedToken");
            }
            Element clone = cloneElement(secToken.getToken());
            secToken.setToken(clone);
            addSupportingElement(clone);
            String id = XMLUtils.getIDFromReference(secToken.getId());
            if (suppTokens.isEncryptedToken()) {
                WSEncryptionPart part = new WSEncryptionPart(id, "Element");
                part.setElement(clone);
                encryptedTokensList.add(part);
            }
            if (secToken.getX509Certificate() == null) {
                ret.add(new SupportingToken(token, new WSSecurityTokenHolder(secToken, secHeader), getSignedParts(suppTokens)));
            } else {
                ret.add(signSupportingToken(secToken, id, token, suppTokens));
            }
        } else if (token instanceof X509Token) {
            // We have to use a cert. Prepare X509 signature
            WSSecSignature sig = getSignatureBuilder(token, false, endorse);
            assertPolicy(suppTokens);
            Element bstElem = sig.getBinarySecurityTokenElement();
            if (bstElem != null) {
                if (lastEncryptedKeyElement != null) {
                    if (lastEncryptedKeyElement.getNextSibling() != null) {
                        secHeader.getSecurityHeaderElement().insertBefore(bstElem, lastEncryptedKeyElement.getNextSibling());
                    } else {
                        secHeader.getSecurityHeaderElement().appendChild(bstElem);
                    }
                } else {
                    sig.prependBSTElementToHeader();
                }
                if (suppTokens.isEncryptedToken()) {
                    WSEncryptionPart part = new WSEncryptionPart(sig.getBSTTokenId(), "Element");
                    part.setElement(bstElem);
                    encryptedTokensList.add(part);
                }
            }
            ret.add(new SupportingToken(token, sig, getSignedParts(suppTokens)));
        } else if (token instanceof KeyValueToken) {
            WSSecSignature sig = getSignatureBuilder(token, false, endorse);
            assertPolicy(suppTokens);
            if (suppTokens.isEncryptedToken()) {
                WSEncryptionPart part = new WSEncryptionPart(sig.getBSTTokenId(), "Element");
                encryptedTokensList.add(part);
            }
            ret.add(new SupportingToken(token, sig, getSignedParts(suppTokens)));
        } else if (token instanceof SamlToken) {
            SamlAssertionWrapper assertionWrapper = addSamlToken((SamlToken) token);
            if (assertionWrapper != null) {
                Element envelope = saaj.getSOAPPart().getEnvelope();
                envelope = (Element) DOMUtils.getDomElement(envelope);
                Element assertionElement = assertionWrapper.toDOM(envelope.getOwnerDocument());
                addSupportingElement(assertionElement);
                ret.add(new SupportingToken(token, assertionWrapper, getSignedParts(suppTokens)));
                if (suppTokens.isEncryptedToken()) {
                    WSEncryptionPart part = new WSEncryptionPart(assertionWrapper.getId(), "Element");
                    part.setElement(assertionElement);
                    encryptedTokensList.add(part);
                }
            }
        }
    }
    return ret;
}
Also used : WSEncryptionPart(org.apache.wss4j.common.WSEncryptionPart) SamlToken(org.apache.wss4j.policy.model.SamlToken) KerberosToken(org.apache.wss4j.policy.model.KerberosToken) IssuedToken(org.apache.wss4j.policy.model.IssuedToken) Element(org.w3c.dom.Element) WSSecSignature(org.apache.wss4j.dom.message.WSSecSignature) WSSecUsernameToken(org.apache.wss4j.dom.message.WSSecUsernameToken) UsernameToken(org.apache.wss4j.policy.model.UsernameToken) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) SecureConversationToken(org.apache.wss4j.policy.model.SecureConversationToken) SpnegoContextToken(org.apache.wss4j.policy.model.SpnegoContextToken) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) AbstractToken(org.apache.wss4j.policy.model.AbstractToken) X509Token(org.apache.wss4j.policy.model.X509Token) SecurityContextToken(org.apache.wss4j.policy.model.SecurityContextToken) KeyValueToken(org.apache.wss4j.policy.model.KeyValueToken)

Example 88 with SamlAssertionWrapper

use of org.apache.wss4j.common.saml.SamlAssertionWrapper in project cxf by apache.

the class AsymmetricBindingHandler method doEncryptBeforeSign.

private void doEncryptBeforeSign() {
    AbstractTokenWrapper wrapper = getEncryptBeforeSignWrapper();
    AbstractToken encryptionToken = null;
    if (wrapper != null) {
        encryptionToken = wrapper.getToken();
        assertToken(encryptionToken);
    }
    AbstractTokenWrapper initiatorWrapper = abinding.getInitiatorSignatureToken();
    if (initiatorWrapper == null) {
        initiatorWrapper = abinding.getInitiatorToken();
    }
    assertTokenWrapper(initiatorWrapper);
    boolean attached = false;
    if (initiatorWrapper != null) {
        AbstractToken initiatorToken = initiatorWrapper.getToken();
        if (initiatorToken instanceof IssuedToken) {
            SecurityToken secToken = getSecurityToken();
            if (secToken == null) {
                unassertPolicy(initiatorToken, "Security token is not found or expired");
                return;
            } else if (isTokenRequired(initiatorToken.getIncludeTokenType())) {
                Element el = secToken.getToken();
                this.addEncryptedKeyElement(cloneElement(el));
                attached = true;
            }
        } else if (initiatorToken instanceof SamlToken && isRequestor()) {
            try {
                SamlAssertionWrapper assertionWrapper = addSamlToken((SamlToken) initiatorToken);
                if (assertionWrapper != null && isTokenRequired(initiatorToken.getIncludeTokenType())) {
                    Element envelope = saaj.getSOAPPart().getEnvelope();
                    envelope = (Element) DOMUtils.getDomElement(envelope);
                    addSupportingElement(assertionWrapper.toDOM(envelope.getOwnerDocument()));
                    storeAssertionAsSecurityToken(assertionWrapper);
                }
            } catch (Exception e) {
                String reason = e.getMessage();
                LOG.log(Level.WARNING, "Encrypt before sign failed due to : " + reason);
                LOG.log(Level.FINE, e.getMessage(), e);
                throw new Fault(e);
            }
        } else if (initiatorToken instanceof SamlToken) {
            String tokenId = getSAMLToken();
            if (tokenId == null) {
                unassertPolicy(initiatorToken, "Security token is not found or expired");
                return;
            }
        }
    }
    List<WSEncryptionPart> sigParts = new ArrayList<>();
    if (timestampEl != null) {
        WSEncryptionPart timestampPart = convertToEncryptionPart(timestampEl.getElement());
        sigParts.add(timestampPart);
    }
    try {
        addSupportingTokens(sigParts);
    } catch (WSSecurityException ex) {
        LOG.log(Level.FINE, ex.getMessage(), ex);
        unassertPolicy(encryptionToken, ex);
    }
    List<WSEncryptionPart> encrParts = null;
    try {
        encrParts = getEncryptedParts();
        // Signed parts are determined before encryption because encrypted signed headers
        // will not be included otherwise
        sigParts.addAll(this.getSignedParts(null));
    } catch (SOAPException ex) {
        LOG.log(Level.FINE, ex.getMessage(), ex);
        throw new Fault(ex);
    }
    WSSecBase encrBase = null;
    if (encryptionToken != null && !encrParts.isEmpty()) {
        encrBase = doEncryption(wrapper, encrParts, true);
        handleEncryptedSignedHeaders(encrParts, sigParts);
    }
    if (!isRequestor()) {
        addSignatureConfirmation(sigParts);
    }
    try {
        if (!sigParts.isEmpty()) {
            if (initiatorWrapper != null && isRequestor()) {
                doSignature(initiatorWrapper, sigParts, attached);
            } else if (!isRequestor()) {
                AbstractTokenWrapper recipientSignatureToken = abinding.getRecipientSignatureToken();
                if (recipientSignatureToken == null) {
                    recipientSignatureToken = abinding.getRecipientToken();
                }
                if (recipientSignatureToken != null) {
                    assertTokenWrapper(recipientSignatureToken);
                    assertToken(recipientSignatureToken.getToken());
                    doSignature(recipientSignatureToken, sigParts, attached);
                }
            }
        }
    } catch (WSSecurityException ex) {
        LOG.log(Level.FINE, ex.getMessage(), ex);
        throw new Fault(ex);
    } catch (SOAPException ex) {
        LOG.log(Level.FINE, ex.getMessage(), ex);
        throw new Fault(ex);
    }
    if (isRequestor()) {
        doEndorse();
    }
    if (encrBase != null) {
        encryptTokensInSecurityHeader(encryptionToken, encrBase);
    }
}
Also used : WSEncryptionPart(org.apache.wss4j.common.WSEncryptionPart) SamlToken(org.apache.wss4j.policy.model.SamlToken) IssuedToken(org.apache.wss4j.policy.model.IssuedToken) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) Fault(org.apache.cxf.interceptor.Fault) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) SOAPException(javax.xml.soap.SOAPException) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) WSSecBase(org.apache.wss4j.dom.message.WSSecBase) AbstractToken(org.apache.wss4j.policy.model.AbstractToken) SOAPException(javax.xml.soap.SOAPException) AbstractTokenWrapper(org.apache.wss4j.policy.model.AbstractTokenWrapper)

Example 89 with SamlAssertionWrapper

use of org.apache.wss4j.common.saml.SamlAssertionWrapper in project cxf by apache.

the class AsymmetricBindingHandler method getSAMLToken.

private String getSAMLToken() {
    List<WSHandlerResult> results = CastUtils.cast((List<?>) message.getExchange().getInMessage().get(WSHandlerConstants.RECV_RESULTS));
    for (WSHandlerResult rResult : results) {
        List<WSSecurityEngineResult> wsSecEngineResults = rResult.getResults();
        for (WSSecurityEngineResult wser : wsSecEngineResults) {
            Integer actInt = (Integer) wser.get(WSSecurityEngineResult.TAG_ACTION);
            if (actInt.intValue() == WSConstants.ST_SIGNED || actInt.intValue() == WSConstants.ST_UNSIGNED) {
                Instant created = Instant.now();
                Instant expires = created.plusSeconds(WSS4JUtils.getSecurityTokenLifetime(message) / 1000L);
                String id = (String) wser.get(WSSecurityEngineResult.TAG_ID);
                SecurityToken tempTok = new SecurityToken(id, created, expires);
                tempTok.setSecret((byte[]) wser.get(WSSecurityEngineResult.TAG_SECRET));
                tempTok.setX509Certificate((X509Certificate) wser.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE), null);
                SamlAssertionWrapper samlAssertion = (SamlAssertionWrapper) wser.get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
                if (samlAssertion.getSamlVersion() == SAMLVersion.VERSION_20) {
                    tempTok.setTokenType(WSS4JConstants.WSS_SAML2_TOKEN_TYPE);
                } else {
                    tempTok.setTokenType(WSS4JConstants.WSS_SAML_TOKEN_TYPE);
                }
                message.put(SecurityConstants.TOKEN, tempTok);
                return id;
            }
        }
    }
    return null;
}
Also used : SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) Instant(java.time.Instant) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) WSHandlerResult(org.apache.wss4j.dom.handler.WSHandlerResult) WSSecurityEngineResult(org.apache.wss4j.dom.engine.WSSecurityEngineResult)

Example 90 with SamlAssertionWrapper

use of org.apache.wss4j.common.saml.SamlAssertionWrapper in project cxf by apache.

the class TokenIssueOperation method issueSingle.

public RequestSecurityTokenResponseType issueSingle(RequestSecurityTokenType request, Principal principal, Map<String, Object> messageContext) {
    long start = System.currentTimeMillis();
    TokenProviderParameters providerParameters = new TokenProviderParameters();
    try {
        RequestRequirements requestRequirements = parseRequest(request, messageContext);
        providerParameters = createTokenProviderParameters(requestRequirements, principal, messageContext);
        providerParameters.setClaimsManager(claimsManager);
        String realm = providerParameters.getRealm();
        TokenRequirements tokenRequirements = requestRequirements.getTokenRequirements();
        String tokenType = tokenRequirements.getTokenType();
        if (stsProperties.getSamlRealmCodec() != null) {
            SamlAssertionWrapper assertion = fetchSAMLAssertionFromWSSecuritySAMLToken(messageContext);
            if (assertion != null) {
                String wssecRealm = stsProperties.getSamlRealmCodec().getRealmFromToken(assertion);
                SAMLTokenPrincipal samlPrincipal = new SAMLTokenPrincipalImpl(assertion);
                if (LOG.isLoggable(Level.FINE)) {
                    LOG.fine("SAML token realm of user '" + samlPrincipal.getName() + "' is " + wssecRealm);
                }
                ReceivedToken wssecToken = new ReceivedToken(assertion.getElement());
                wssecToken.setState(STATE.VALID);
                TokenValidatorResponse tokenResponse = new TokenValidatorResponse();
                tokenResponse.setPrincipal(samlPrincipal);
                tokenResponse.setToken(wssecToken);
                tokenResponse.setTokenRealm(wssecRealm);
                tokenResponse.setAdditionalProperties(new HashMap<String, Object>());
                processValidToken(providerParameters, wssecToken, tokenResponse);
                providerParameters.setPrincipal(wssecToken.getPrincipal());
            }
        }
        // Validate OnBehalfOf token if present
        if (providerParameters.getTokenRequirements().getOnBehalfOf() != null) {
            ReceivedToken validateTarget = providerParameters.getTokenRequirements().getOnBehalfOf();
            handleDelegationToken(validateTarget, providerParameters, principal, messageContext, realm, requestRequirements);
        }
        // See whether ActAs is allowed or not
        if (providerParameters.getTokenRequirements().getActAs() != null) {
            ReceivedToken validateTarget = providerParameters.getTokenRequirements().getActAs();
            handleDelegationToken(validateTarget, providerParameters, principal, messageContext, realm, requestRequirements);
        }
        // create token
        TokenProviderResponse tokenResponse = null;
        for (TokenProvider tokenProvider : tokenProviders) {
            boolean canHandle = false;
            if (realm == null) {
                canHandle = tokenProvider.canHandleToken(tokenType);
            } else {
                canHandle = tokenProvider.canHandleToken(tokenType, realm);
            }
            if (canHandle) {
                try {
                    tokenResponse = tokenProvider.createToken(providerParameters);
                } catch (STSException ex) {
                    LOG.log(Level.WARNING, "", ex);
                    throw ex;
                } catch (RuntimeException ex) {
                    LOG.log(Level.WARNING, "", ex);
                    throw new STSException("Error in providing a token", ex, STSException.REQUEST_FAILED);
                }
                break;
            }
        }
        if (tokenResponse == null || tokenResponse.getToken() == null) {
            LOG.log(Level.WARNING, "No token provider found for requested token type: " + tokenType);
            throw new STSException("No token provider found for requested token type: " + tokenType, STSException.REQUEST_FAILED);
        }
        // prepare response
        try {
            KeyRequirements keyRequirements = requestRequirements.getKeyRequirements();
            EncryptionProperties encryptionProperties = providerParameters.getEncryptionProperties();
            RequestSecurityTokenResponseType response = createResponse(encryptionProperties, tokenResponse, tokenRequirements, keyRequirements);
            STSIssueSuccessEvent event = new STSIssueSuccessEvent(providerParameters, System.currentTimeMillis() - start);
            publishEvent(event);
            return response;
        } catch (Throwable ex) {
            LOG.log(Level.WARNING, "", ex);
            throw new STSException("Error in creating the response", ex, STSException.REQUEST_FAILED);
        }
    } catch (RuntimeException ex) {
        LOG.log(Level.SEVERE, "Cannot issue token: " + ex.getMessage(), ex);
        STSIssueFailureEvent event = new STSIssueFailureEvent(providerParameters, System.currentTimeMillis() - start, ex);
        publishEvent(event);
        throw ex;
    }
}
Also used : SAMLTokenPrincipal(org.apache.wss4j.common.principal.SAMLTokenPrincipal) RequestRequirements(org.apache.cxf.sts.request.RequestRequirements) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) STSException(org.apache.cxf.ws.security.sts.provider.STSException) EncryptionProperties(org.apache.cxf.sts.service.EncryptionProperties) RequestSecurityTokenResponseType(org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenResponseType) TokenProviderParameters(org.apache.cxf.sts.token.provider.TokenProviderParameters) TokenProvider(org.apache.cxf.sts.token.provider.TokenProvider) TokenRequirements(org.apache.cxf.sts.request.TokenRequirements) TokenValidatorResponse(org.apache.cxf.sts.token.validator.TokenValidatorResponse) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken) TokenProviderResponse(org.apache.cxf.sts.token.provider.TokenProviderResponse) KeyRequirements(org.apache.cxf.sts.request.KeyRequirements) SAMLTokenPrincipalImpl(org.apache.wss4j.common.principal.SAMLTokenPrincipalImpl) STSIssueSuccessEvent(org.apache.cxf.sts.event.STSIssueSuccessEvent) STSIssueFailureEvent(org.apache.cxf.sts.event.STSIssueFailureEvent)

Aggregations

SamlAssertionWrapper (org.apache.wss4j.common.saml.SamlAssertionWrapper)141 Element (org.w3c.dom.Element)68 Document (org.w3c.dom.Document)55 WSSecurityEngineResult (org.apache.wss4j.dom.engine.WSSecurityEngineResult)44 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)40 SAMLCallback (org.apache.wss4j.common.saml.SAMLCallback)35 SecurityToken (org.apache.cxf.ws.security.tokenstore.SecurityToken)27 Crypto (org.apache.wss4j.common.crypto.Crypto)26 Response (org.opensaml.saml.saml2.core.Response)23 URL (java.net.URL)22 Bus (org.apache.cxf.Bus)20 SpringBusFactory (org.apache.cxf.bus.spring.SpringBusFactory)19 ArrayList (java.util.ArrayList)18 WebClient (org.apache.cxf.jaxrs.client.WebClient)18 Status (org.opensaml.saml.saml2.core.Status)18 HashMap (java.util.HashMap)16 Test (org.junit.Test)16 Principal (java.security.Principal)15 WSHandlerResult (org.apache.wss4j.dom.handler.WSHandlerResult)14 Response (javax.ws.rs.core.Response)13