Search in sources :

Example 51 with SamlAssertionWrapper

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

the class SamlTokenInterceptor method processToken.

protected void processToken(SoapMessage message) {
    Header h = findSecurityHeader(message, false);
    if (h == null) {
        return;
    }
    Element el = (Element) h.getObject();
    Element child = DOMUtils.getFirstElement(el);
    while (child != null) {
        if ("Assertion".equals(child.getLocalName()) && (WSS4JConstants.SAML_NS.equals(child.getNamespaceURI()) || WSS4JConstants.SAML2_NS.equals(child.getNamespaceURI()))) {
            try {
                List<WSSecurityEngineResult> samlResults = processToken(child, message);
                if (samlResults != null) {
                    List<WSHandlerResult> results = CastUtils.cast((List<?>) message.get(WSHandlerConstants.RECV_RESULTS));
                    if (results == null) {
                        results = new ArrayList<>();
                        message.put(WSHandlerConstants.RECV_RESULTS, results);
                    }
                    boolean signed = false;
                    for (WSSecurityEngineResult result : samlResults) {
                        SamlAssertionWrapper wrapper = (SamlAssertionWrapper) result.get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
                        if (wrapper.isSigned()) {
                            signed = true;
                            break;
                        }
                    }
                    assertTokens(message, SPConstants.SAML_TOKEN, signed);
                    Integer key = WSConstants.ST_UNSIGNED;
                    if (signed) {
                        key = WSConstants.ST_SIGNED;
                    }
                    WSHandlerResult rResult = new WSHandlerResult(null, samlResults, Collections.singletonMap(key, samlResults));
                    results.add(0, rResult);
                    // Check version against policy
                    AssertionInfoMap aim = message.get(AssertionInfoMap.class);
                    for (AssertionInfo ai : PolicyUtils.getAllAssertionsByLocalname(aim, SPConstants.SAML_TOKEN)) {
                        SamlToken samlToken = (SamlToken) ai.getAssertion();
                        for (WSSecurityEngineResult result : samlResults) {
                            SamlAssertionWrapper assertionWrapper = (SamlAssertionWrapper) result.get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
                            if (!checkVersion(aim, samlToken, assertionWrapper)) {
                                ai.setNotAsserted("Wrong SAML Version");
                            }
                            TLSSessionInfo tlsInfo = message.get(TLSSessionInfo.class);
                            Certificate[] tlsCerts = null;
                            if (tlsInfo != null) {
                                tlsCerts = tlsInfo.getPeerCertificates();
                            }
                            if (!DOMSAMLUtil.checkHolderOfKey(assertionWrapper, null, tlsCerts)) {
                                ai.setNotAsserted("Assertion fails holder-of-key requirements");
                                continue;
                            }
                            if (!DOMSAMLUtil.checkSenderVouches(assertionWrapper, tlsCerts, null, null)) {
                                ai.setNotAsserted("Assertion fails sender-vouches requirements");
                                continue;
                            }
                        }
                    }
                    if (signed) {
                        Principal principal = (Principal) samlResults.get(0).get(WSSecurityEngineResult.TAG_PRINCIPAL);
                        SecurityContext sc = message.get(SecurityContext.class);
                        if (sc == null || sc.getUserPrincipal() == null) {
                            message.put(SecurityContext.class, new DefaultSecurityContext(principal, null));
                        }
                    }
                }
            } catch (WSSecurityException ex) {
                throw WSS4JUtils.createSoapFault(message, message.getVersion(), ex);
            }
        }
        child = DOMUtils.getNextElement(child);
    }
}
Also used : DefaultSecurityContext(org.apache.cxf.interceptor.security.DefaultSecurityContext) AssertionInfo(org.apache.cxf.ws.policy.AssertionInfo) SamlToken(org.apache.wss4j.policy.model.SamlToken) Element(org.w3c.dom.Element) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) WSSecurityEngineResult(org.apache.wss4j.dom.engine.WSSecurityEngineResult) WSHandlerResult(org.apache.wss4j.dom.handler.WSHandlerResult) AssertionInfoMap(org.apache.cxf.ws.policy.AssertionInfoMap) Header(org.apache.cxf.headers.Header) DefaultSecurityContext(org.apache.cxf.interceptor.security.DefaultSecurityContext) SecurityContext(org.apache.cxf.security.SecurityContext) TLSSessionInfo(org.apache.cxf.security.transport.TLSSessionInfo) Principal(java.security.Principal) Certificate(java.security.cert.Certificate)

Example 52 with SamlAssertionWrapper

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

the class AbstractBindingBuilder method addSignatureParts.

protected void addSignatureParts(List<SupportingToken> tokenList, List<WSEncryptionPart> sigParts) {
    boolean useSTRTransform = MessageUtils.getContextualBoolean(message, SecurityConstants.USE_STR_TRANSFORM, true);
    for (SupportingToken supportingToken : tokenList) {
        Object tempTok = supportingToken.getTokenImplementation();
        WSEncryptionPart part = null;
        if (tempTok instanceof WSSecSignature) {
            WSSecSignature tempSig = (WSSecSignature) tempTok;
            SecurityTokenReference secRef = tempSig.getSecurityTokenReference();
            if (WSS4JConstants.WSS_SAML_KI_VALUE_TYPE.equals(secRef.getKeyIdentifierValueType()) || WSS4JConstants.WSS_SAML2_KI_VALUE_TYPE.equals(secRef.getKeyIdentifierValueType())) {
                Element secRefElement = cloneElement(secRef.getElement());
                addSupportingElement(secRefElement);
                part = new WSEncryptionPart("STRTransform", null, "Element");
                part.setId(tempSig.getSecurityTokenReferenceURI());
                part.setElement(secRefElement);
            } else {
                if (tempSig.getBSTTokenId() != null) {
                    part = new WSEncryptionPart(tempSig.getBSTTokenId());
                    part.setElement(tempSig.getBinarySecurityTokenElement());
                }
            }
        } else if (tempTok instanceof WSSecUsernameToken) {
            WSSecUsernameToken unt = (WSSecUsernameToken) tempTok;
            part = new WSEncryptionPart(unt.getId());
            part.setElement(unt.getUsernameTokenElement());
        } else if (tempTok instanceof BinarySecurity) {
            BinarySecurity bst = (BinarySecurity) tempTok;
            part = new WSEncryptionPart(bst.getID());
            part.setElement(bst.getElement());
        } else if (tempTok instanceof SamlAssertionWrapper) {
            SamlAssertionWrapper assertionWrapper = (SamlAssertionWrapper) tempTok;
            Document doc = assertionWrapper.getElement().getOwnerDocument();
            boolean saml1 = assertionWrapper.getSaml1() != null;
            if (useSTRTransform) {
                // TODO We only support using a KeyIdentifier for the moment
                SecurityTokenReference secRef = createSTRForSamlAssertion(doc, assertionWrapper.getId(), saml1, false);
                Element clone = cloneElement(secRef.getElement());
                addSupportingElement(clone);
                part = new WSEncryptionPart("STRTransform", null, "Element");
                part.setId(secRef.getID());
                part.setElement(clone);
            } else {
                part = new WSEncryptionPart(assertionWrapper.getId());
                part.setElement(assertionWrapper.getElement());
            }
        } else if (tempTok instanceof WSSecurityTokenHolder) {
            SecurityToken token = ((WSSecurityTokenHolder) tempTok).getToken();
            String tokenType = token.getTokenType();
            if (WSS4JConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType) || WSS4JConstants.SAML_NS.equals(tokenType) || WSS4JConstants.WSS_SAML2_TOKEN_TYPE.equals(tokenType) || WSS4JConstants.SAML2_NS.equals(tokenType)) {
                Document doc = token.getToken().getOwnerDocument();
                boolean saml1 = WSS4JConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType) || WSS4JConstants.SAML_NS.equals(tokenType);
                String id = token.getId();
                if (id == null || "".equals(id)) {
                    if (saml1) {
                        id = token.getToken().getAttributeNS(null, "AssertionID");
                    } else {
                        id = token.getToken().getAttributeNS(null, "ID");
                    }
                }
                if (useSTRTransform) {
                    SecurityTokenReference secRef = createSTRForSamlAssertion(doc, id, saml1, false);
                    Element clone = cloneElement(secRef.getElement());
                    addSupportingElement(clone);
                    part = new WSEncryptionPart("STRTransform", null, "Element");
                    part.setId(secRef.getID());
                    part.setElement(clone);
                } else {
                    part = new WSEncryptionPart(id);
                    part.setElement(token.getToken());
                }
            } else {
                String id = XMLUtils.getIDFromReference(token.getId());
                part = new WSEncryptionPart(id);
                part.setElement(token.getToken());
            }
        } else {
            unassertPolicy(supportingToken.getToken(), "UnsupportedTokenInSupportingToken: " + tempTok);
        }
        if (part != null) {
            sigParts.add(part);
        }
    }
}
Also used : WSEncryptionPart(org.apache.wss4j.common.WSEncryptionPart) BinarySecurity(org.apache.wss4j.common.token.BinarySecurity) WSSecSignature(org.apache.wss4j.dom.message.WSSecSignature) Element(org.w3c.dom.Element) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) Document(org.w3c.dom.Document) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) SecurityTokenReference(org.apache.wss4j.common.token.SecurityTokenReference) WSSecUsernameToken(org.apache.wss4j.dom.message.WSSecUsernameToken)

Example 53 with SamlAssertionWrapper

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

the class AsymmetricBindingHandler method doSignBeforeEncrypt.

private void doSignBeforeEncrypt() {
    try {
        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()) {
                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);
                }
            } else if (initiatorToken instanceof SamlToken) {
                String tokenId = getSAMLToken();
                if (tokenId == null) {
                    unassertPolicy(initiatorToken, "Security token is not found or expired");
                    return;
                }
            }
            assertToken(initiatorToken);
        }
        // Add timestamp
        List<WSEncryptionPart> sigs = new ArrayList<>();
        if (timestampEl != null) {
            WSEncryptionPart timestampPart = convertToEncryptionPart(timestampEl.getElement());
            sigs.add(timestampPart);
        }
        addSupportingTokens(sigs);
        sigs.addAll(this.getSignedParts(null));
        if (isRequestor() && initiatorWrapper != null) {
            doSignature(initiatorWrapper, sigs, attached);
            doEndorse();
        } else if (!isRequestor()) {
            // confirm sig
            addSignatureConfirmation(sigs);
            AbstractTokenWrapper recipientSignatureToken = abinding.getRecipientSignatureToken();
            if (recipientSignatureToken == null) {
                recipientSignatureToken = abinding.getRecipientToken();
            }
            if (recipientSignatureToken != null) {
                assertTokenWrapper(recipientSignatureToken);
                assertToken(recipientSignatureToken.getToken());
                doSignature(recipientSignatureToken, sigs, attached);
            }
        }
        List<WSEncryptionPart> enc = getEncryptedParts();
        // Check for signature protection
        if (abinding.isEncryptSignature()) {
            if (mainSigId != null) {
                WSEncryptionPart sigPart = new WSEncryptionPart(mainSigId, "Element");
                sigPart.setElement(bottomUpElement);
                enc.add(sigPart);
            }
            if (sigConfList != null && !sigConfList.isEmpty()) {
                enc.addAll(sigConfList);
            }
            assertPolicy(new QName(abinding.getName().getNamespaceURI(), SPConstants.ENCRYPT_SIGNATURE));
        }
        // Do encryption
        AbstractTokenWrapper encToken;
        if (isRequestor()) {
            enc.addAll(encryptedTokensList);
            encToken = abinding.getRecipientEncryptionToken();
            if (encToken == null) {
                encToken = abinding.getRecipientToken();
            }
        } else {
            encToken = abinding.getInitiatorEncryptionToken();
            if (encToken == null) {
                encToken = abinding.getInitiatorToken();
            }
        }
        doEncryption(encToken, enc, false);
        if (encToken != null) {
            assertTokenWrapper(encToken);
            assertToken(encToken.getToken());
        }
    } catch (Exception e) {
        String reason = e.getMessage();
        LOG.log(Level.WARNING, "Sign before encryption failed due to : " + reason);
        LOG.log(Level.FINE, e.getMessage(), e);
        throw new Fault(e);
    }
}
Also used : WSEncryptionPart(org.apache.wss4j.common.WSEncryptionPart) SamlToken(org.apache.wss4j.policy.model.SamlToken) QName(javax.xml.namespace.QName) 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) SOAPException(javax.xml.soap.SOAPException) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) AbstractToken(org.apache.wss4j.policy.model.AbstractToken) AbstractTokenWrapper(org.apache.wss4j.policy.model.AbstractTokenWrapper)

Example 54 with SamlAssertionWrapper

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

the class STSLoginModule method getRoles.

private Set<Principal> getRoles(Message msg, Credential credential) {
    SamlAssertionWrapper samlAssertion = credential.getTransformedToken();
    if (samlAssertion == null) {
        samlAssertion = credential.getSamlAssertion();
    }
    if (samlAssertion != null) {
        String roleAttributeName = null;
        if (msg != null) {
            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);
        return SAMLUtils.parseRolesFromClaims(claims, roleAttributeName, null);
    }
    return Collections.emptySet();
}
Also used : SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) ClaimCollection(org.apache.cxf.rt.security.claims.ClaimCollection)

Example 55 with SamlAssertionWrapper

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

the class STSStaxTokenValidator method validate.

@SuppressWarnings("unchecked")
@Override
public <T extends SamlSecurityToken & InboundSecurityToken> T validate(final SamlAssertionWrapper samlAssertionWrapper, final InboundSecurityToken subjectSecurityToken, final TokenContext tokenContext) throws WSSecurityException {
    // Check conditions
    checkConditions(samlAssertionWrapper);
    // Check OneTimeUse Condition
    checkOneTimeUse(samlAssertionWrapper, tokenContext.getWssSecurityProperties().getSamlOneTimeUseReplayCache());
    // Validate the assertion against schemas/profiles
    validateAssertion(samlAssertionWrapper);
    Crypto sigVerCrypto = null;
    if (samlAssertionWrapper.isSigned()) {
        sigVerCrypto = tokenContext.getWssSecurityProperties().getSignatureVerificationCrypto();
    }
    final SoapMessage message = (SoapMessage) tokenContext.getWssSecurityProperties().getMsgContext();
    // Validate to STS if required
    boolean valid = false;
    if (alwaysValidateToSts) {
        Element tokenElement = samlAssertionWrapper.getElement();
        validateTokenToSTS(tokenElement, message);
        valid = true;
    }
    final boolean stsValidated = valid;
    SamlSecurityTokenImpl securityToken = new SamlSecurityTokenImpl(samlAssertionWrapper, subjectSecurityToken, tokenContext.getWsSecurityContext(), sigVerCrypto, WSSecurityTokenConstants.KeyIdentifier_NoKeyInfo, tokenContext.getWssSecurityProperties()) {

        @Override
        public void verify() throws XMLSecurityException {
            if (stsValidated) {
                // Already validated
                return;
            }
            try {
                super.verify();
            } catch (XMLSecurityException ex) {
                SamlAssertionWrapper assertion = super.getSamlAssertionWrapper();
                Element tokenElement = assertion.getElement();
                validateTokenToSTS(tokenElement, message);
            }
        }
    };
    securityToken.setElementPath(tokenContext.getElementPath());
    securityToken.setXMLSecEvent(tokenContext.getFirstXMLSecEvent());
    return (T) securityToken;
}
Also used : Crypto(org.apache.wss4j.common.crypto.Crypto) Element(org.w3c.dom.Element) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) SamlSecurityTokenImpl(org.apache.wss4j.stax.impl.securityToken.SamlSecurityTokenImpl) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException) SoapMessage(org.apache.cxf.binding.soap.SoapMessage)

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