Search in sources :

Example 71 with WSSecurityException

use of org.apache.wss4j.common.ext.WSSecurityException in project cxf by apache.

the class SecuredPartsPolicyValidator method validatePolicies.

/**
 * Validate policies.
 */
public void validatePolicies(PolicyValidatorParameters parameters, Collection<AssertionInfo> ais) {
    // 
    if (isTransportBinding(parameters.getAssertionInfoMap(), parameters.getMessage())) {
        return;
    }
    Message msg = parameters.getMessage();
    Element soapBody = parameters.getSoapBody();
    Element header = parameters.getSoapHeader();
    soapBody = (Element) DOMUtils.getDomElement(soapBody);
    header = (Element) DOMUtils.getDomElement(header);
    Collection<WSDataRef> dataRefs = parameters.getEncrypted();
    if (coverageType == CoverageType.SIGNED) {
        dataRefs = parameters.getSigned();
    }
    for (AssertionInfo ai : ais) {
        if (ai.isAsserted()) {
            // they are a child of a SupportingToken
            continue;
        }
        AbstractSecuredParts p = (AbstractSecuredParts) ai.getAssertion();
        ai.setAsserted(true);
        if (p.isBody()) {
            try {
                if (coverageType == CoverageType.SIGNED) {
                    CryptoCoverageUtil.checkBodyCoverage(soapBody, dataRefs, CoverageType.SIGNED, CoverageScope.ELEMENT);
                } else {
                    CryptoCoverageUtil.checkBodyCoverage(soapBody, dataRefs, CoverageType.ENCRYPTED, CoverageScope.CONTENT);
                }
            } catch (WSSecurityException e) {
                ai.setNotAsserted("Soap Body is not " + coverageType);
                continue;
            }
        }
        for (Header h : p.getHeaders()) {
            if (header == null) {
                ai.setNotAsserted(h.getNamespace() + ":" + h.getName() + " not + " + coverageType);
            } else {
                try {
                    CryptoCoverageUtil.checkHeaderCoverage(header, dataRefs, h.getNamespace(), h.getName(), coverageType, CoverageScope.ELEMENT);
                } catch (WSSecurityException e) {
                    ai.setNotAsserted(h.getNamespace() + ":" + h.getName() + " not + " + coverageType);
                }
            }
        }
        Attachments attachments = p.getAttachments();
        if (attachments != null) {
            try {
                CoverageScope scope = CoverageScope.ELEMENT;
                if (attachments.isContentSignatureTransform()) {
                    scope = CoverageScope.CONTENT;
                }
                CryptoCoverageUtil.checkAttachmentsCoverage(msg.getAttachments(), dataRefs, coverageType, scope);
            } catch (WSSecurityException e) {
                ai.setNotAsserted("An attachment was not signed/encrypted");
            }
        }
    }
}
Also used : CoverageScope(org.apache.cxf.ws.security.wss4j.CryptoCoverageUtil.CoverageScope) AssertionInfo(org.apache.cxf.ws.policy.AssertionInfo) Message(org.apache.cxf.message.Message) Header(org.apache.wss4j.policy.model.Header) AbstractSecuredParts(org.apache.wss4j.policy.model.AbstractSecuredParts) Element(org.w3c.dom.Element) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) WSDataRef(org.apache.wss4j.dom.WSDataRef) Attachments(org.apache.wss4j.policy.model.Attachments)

Example 72 with WSSecurityException

use of org.apache.wss4j.common.ext.WSSecurityException in project cxf by apache.

the class SecuredElementsPolicyValidator method validatePolicies.

/**
 * Validate policies.
 */
public void validatePolicies(PolicyValidatorParameters parameters, Collection<AssertionInfo> ais) {
    // XPathFactory and XPath are not thread-safe so we must recreate them
    // each request.
    final XPathFactory factory = XPathFactory.newInstance();
    try {
        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
    } catch (javax.xml.xpath.XPathFactoryConfigurationException ex) {
    // ignore
    }
    final XPath xpath = factory.newXPath();
    Element soapEnvelope = parameters.getSoapHeader() != null ? parameters.getSoapHeader().getOwnerDocument().getDocumentElement() : null;
    Collection<WSDataRef> dataRefs = parameters.getEncrypted();
    if (coverageType == CoverageType.SIGNED) {
        dataRefs = parameters.getSigned();
    }
    for (AssertionInfo ai : ais) {
        RequiredElements elements = (RequiredElements) ai.getAssertion();
        ai.setAsserted(true);
        if (elements != null && elements.getXPaths() != null && !elements.getXPaths().isEmpty()) {
            List<String> expressions = new ArrayList<>();
            MapNamespaceContext namespaceContext = new MapNamespaceContext();
            for (org.apache.wss4j.policy.model.XPath xPath : elements.getXPaths()) {
                expressions.add(xPath.getXPath());
                Map<String, String> namespaceMap = xPath.getPrefixNamespaceMap();
                if (namespaceMap != null) {
                    namespaceContext.addNamespaces(namespaceMap);
                }
            }
            if (parameters.getSoapHeader() == null) {
                ai.setNotAsserted("No " + coverageType + " element found matching one of the XPaths " + Arrays.toString(expressions.toArray()));
            } else {
                xpath.setNamespaceContext(namespaceContext);
                try {
                    CryptoCoverageUtil.checkCoverage(soapEnvelope, dataRefs, xpath, expressions, coverageType, coverageScope);
                } catch (WSSecurityException e) {
                    ai.setNotAsserted("No " + coverageType + " element found matching one of the XPaths " + Arrays.toString(expressions.toArray()));
                }
            }
        }
    }
}
Also used : XPath(javax.xml.xpath.XPath) RequiredElements(org.apache.wss4j.policy.model.RequiredElements) AssertionInfo(org.apache.cxf.ws.policy.AssertionInfo) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) MapNamespaceContext(org.apache.cxf.helpers.MapNamespaceContext) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) WSDataRef(org.apache.wss4j.dom.WSDataRef) XPathFactory(javax.xml.xpath.XPathFactory)

Example 73 with WSSecurityException

use of org.apache.wss4j.common.ext.WSSecurityException in project cxf by apache.

the class CustomAttributeProvider method getStatement.

/**
 * Get an AttributeStatementBean using the given parameters.
 */
public AttributeStatementBean getStatement(TokenProviderParameters providerParameters) {
    List<AttributeBean> attributeList = new ArrayList<>();
    TokenRequirements tokenRequirements = providerParameters.getTokenRequirements();
    String tokenType = tokenRequirements.getTokenType();
    // Handle Claims
    ProcessedClaimCollection retrievedClaims = ClaimsUtils.processClaims(providerParameters);
    AttributeStatementBean attrBean = new AttributeStatementBean();
    Iterator<ProcessedClaim> claimIterator = retrievedClaims.iterator();
    if (!claimIterator.hasNext()) {
        // If no Claims have been processed then create a default attribute
        AttributeBean attributeBean = createDefaultAttribute(tokenType);
        attributeList.add(attributeBean);
    }
    while (claimIterator.hasNext()) {
        ProcessedClaim claim = claimIterator.next();
        AttributeBean attributeBean = createAttributeFromClaim(claim, tokenType);
        attributeList.add(attributeBean);
    }
    ReceivedToken onBehalfOf = tokenRequirements.getOnBehalfOf();
    ReceivedToken actAs = tokenRequirements.getActAs();
    try {
        if (onBehalfOf != null) {
            AttributeBean parameterBean = handleAdditionalParameters(false, onBehalfOf.getToken(), tokenType);
            if (!parameterBean.getAttributeValues().isEmpty()) {
                attributeList.add(parameterBean);
            }
        }
        if (actAs != null) {
            AttributeBean parameterBean = handleAdditionalParameters(true, actAs.getToken(), tokenType);
            if (!parameterBean.getAttributeValues().isEmpty()) {
                attributeList.add(parameterBean);
            }
        }
    } catch (WSSecurityException ex) {
        throw new STSException(ex.getMessage(), ex);
    }
    attrBean.setSamlAttributes(attributeList);
    return attrBean;
}
Also used : AttributeStatementBean(org.apache.wss4j.common.saml.bean.AttributeStatementBean) ProcessedClaimCollection(org.apache.cxf.sts.claims.ProcessedClaimCollection) TokenRequirements(org.apache.cxf.sts.request.TokenRequirements) ProcessedClaim(org.apache.cxf.sts.claims.ProcessedClaim) ArrayList(java.util.ArrayList) STSException(org.apache.cxf.ws.security.sts.provider.STSException) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) AttributeBean(org.apache.wss4j.common.saml.bean.AttributeBean) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken)

Example 74 with WSSecurityException

use of org.apache.wss4j.common.ext.WSSecurityException in project cxf by apache.

the class SymmetricKeyHandler method createSymmetricKey.

/**
 * Create the Symmetric Key
 */
public void createSymmetricKey() {
    computedKey = false;
    boolean generateEntropy = true;
    if (clientEntropy != null) {
        BinarySecret binarySecret = clientEntropy.getBinarySecret();
        if (binarySecret != null && (STSConstants.SYMMETRIC_KEY_TYPE.equals(binarySecret.getBinarySecretType()) || binarySecret.getBinarySecretType() == null)) {
            secret = binarySecret.getBinarySecretValue();
            generateEntropy = false;
        } else if (clientEntropy.getDecryptedKey() != null) {
            secret = clientEntropy.getDecryptedKey();
            generateEntropy = false;
        }
    }
    if (generateEntropy) {
        try {
            entropyBytes = WSSecurityUtil.generateNonce(keySize / 8);
            secret = entropyBytes;
        } catch (WSSecurityException ex) {
            LOG.log(Level.WARNING, "", ex);
            throw new STSException("Error in creating symmetric key", ex, STSException.INVALID_REQUEST);
        }
        if (clientEntropy != null && clientEntropy.getBinarySecret() != null) {
            byte[] nonce = clientEntropy.getBinarySecret().getBinarySecretValue();
            try {
                P_SHA1 psha1 = new P_SHA1();
                secret = psha1.createKey(nonce, entropyBytes, 0, keySize / 8);
                computedKey = true;
            } catch (WSSecurityException ex) {
                LOG.log(Level.WARNING, "", ex);
                throw new STSException("Error in creating symmetric key", STSException.INVALID_REQUEST);
            }
        }
    }
}
Also used : P_SHA1(org.apache.wss4j.common.derivedKey.P_SHA1) STSException(org.apache.cxf.ws.security.sts.provider.STSException) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) BinarySecret(org.apache.cxf.sts.request.BinarySecret)

Example 75 with WSSecurityException

use of org.apache.wss4j.common.ext.WSSecurityException in project cxf by apache.

the class DefaultSubjectProvider method createKeyInfo.

/**
 * Create and return the KeyInfoBean to be inserted into the SubjectBean
 */
protected KeyInfoBean createKeyInfo(SubjectProviderParameters subjectProviderParameters) {
    TokenProviderParameters providerParameters = subjectProviderParameters.getProviderParameters();
    KeyRequirements keyRequirements = providerParameters.getKeyRequirements();
    STSPropertiesMBean stsProperties = providerParameters.getStsProperties();
    String keyType = keyRequirements.getKeyType();
    if (STSConstants.SYMMETRIC_KEY_KEYTYPE.equals(keyType)) {
        Crypto crypto = stsProperties.getEncryptionCrypto();
        EncryptionProperties encryptionProperties = providerParameters.getEncryptionProperties();
        String encryptionName = encryptionProperties.getEncryptionName();
        if (encryptionName == null) {
            // Fall back on the STS encryption name
            encryptionName = stsProperties.getEncryptionUsername();
        }
        if (encryptionName == null) {
            LOG.fine("No encryption Name is configured for Symmetric KeyType");
            throw new STSException("No Encryption Name is configured", STSException.REQUEST_FAILED);
        }
        final CryptoType cryptoType;
        // Check for using of service endpoint (AppliesTo) as certificate identifier
        if (STSConstants.USE_ENDPOINT_AS_CERT_ALIAS.equals(encryptionName)) {
            if (providerParameters.getAppliesToAddress() == null) {
                throw new STSException("AppliesTo is not initilaized for encryption name " + STSConstants.USE_ENDPOINT_AS_CERT_ALIAS);
            }
            cryptoType = new CryptoType(CryptoType.TYPE.ENDPOINT);
            cryptoType.setEndpoint(providerParameters.getAppliesToAddress());
        } else {
            cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
            cryptoType.setAlias(encryptionName);
        }
        try {
            X509Certificate[] certs = crypto.getX509Certificates(cryptoType);
            if ((certs == null) || (certs.length == 0)) {
                throw new STSException("Encryption certificate is not found for alias: " + encryptionName);
            }
            Document doc = subjectProviderParameters.getDoc();
            byte[] secret = subjectProviderParameters.getSecret();
            return createEncryptedKeyKeyInfo(certs[0], secret, doc, encryptionProperties, crypto);
        } catch (WSSecurityException ex) {
            LOG.log(Level.WARNING, "", ex);
            throw new STSException(ex.getMessage(), ex);
        }
    } else if (STSConstants.PUBLIC_KEY_KEYTYPE.equals(keyType)) {
        ReceivedCredential receivedCredential = keyRequirements.getReceivedCredential();
        // Validate UseKey trust
        if (stsProperties.isValidateUseKey() && stsProperties.getSignatureCrypto() != null) {
            if (receivedCredential.getX509Cert() != null) {
                try {
                    Collection<Pattern> constraints = Collections.emptyList();
                    stsProperties.getSignatureCrypto().verifyTrust(new X509Certificate[] { receivedCredential.getX509Cert() }, false, constraints, null);
                } catch (WSSecurityException e) {
                    LOG.log(Level.FINE, "Error in trust validation of UseKey: ", e);
                    throw new STSException("Error in trust validation of UseKey", STSException.REQUEST_FAILED);
                }
            }
            if (receivedCredential.getPublicKey() != null) {
                try {
                    stsProperties.getSignatureCrypto().verifyTrust(receivedCredential.getPublicKey());
                } catch (WSSecurityException e) {
                    LOG.log(Level.FINE, "Error in trust validation of UseKey: ", e);
                    throw new STSException("Error in trust validation of UseKey", STSException.REQUEST_FAILED);
                }
            }
        }
        return createPublicKeyKeyInfo(receivedCredential.getX509Cert(), receivedCredential.getPublicKey());
    }
    return null;
}
Also used : STSException(org.apache.cxf.ws.security.sts.provider.STSException) EncryptionProperties(org.apache.cxf.sts.service.EncryptionProperties) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) CryptoType(org.apache.wss4j.common.crypto.CryptoType) Document(org.w3c.dom.Document) X509Certificate(java.security.cert.X509Certificate) ReceivedCredential(org.apache.cxf.sts.request.ReceivedCredential) Crypto(org.apache.wss4j.common.crypto.Crypto) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) Collection(java.util.Collection) KeyRequirements(org.apache.cxf.sts.request.KeyRequirements)

Aggregations

WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)241 Element (org.w3c.dom.Element)72 Document (org.w3c.dom.Document)53 IOException (java.io.IOException)51 Crypto (org.apache.wss4j.common.crypto.Crypto)50 SamlAssertionWrapper (org.apache.wss4j.common.saml.SamlAssertionWrapper)39 Credential (org.apache.wss4j.dom.validate.Credential)37 RequestData (org.apache.wss4j.dom.handler.RequestData)36 X509Certificate (java.security.cert.X509Certificate)31 Response (org.opensaml.saml.saml2.core.Response)31 SAMLCallback (org.apache.wss4j.common.saml.SAMLCallback)25 DateTime (org.joda.time.DateTime)22 XMLObject (org.opensaml.core.xml.XMLObject)22 XMLStreamException (javax.xml.stream.XMLStreamException)21 SecurityToken (org.apache.cxf.ws.security.tokenstore.SecurityToken)21 Fault (org.apache.cxf.interceptor.Fault)20 SOAPException (javax.xml.soap.SOAPException)19 CallbackHandler (javax.security.auth.callback.CallbackHandler)18 ReceivedToken (org.apache.cxf.sts.request.ReceivedToken)17 InputStream (java.io.InputStream)16