Search in sources :

Example 1 with WSEncryptionPart

use of org.apache.wss4j.common.WSEncryptionPart in project cxf by apache.

the class TokenProviderUtils method encryptToken.

/**
 * Encrypt a Token element using the given arguments.
 */
public static Element encryptToken(Element element, String id, STSPropertiesMBean stsProperties, EncryptionProperties encryptionProperties, KeyRequirements keyRequirements, Map<String, Object> messageContext) throws WSSecurityException {
    String name = encryptionProperties.getEncryptionName();
    if (name == null) {
        name = stsProperties.getEncryptionUsername();
    }
    if (name == null) {
        LOG.fine("No encryption alias is configured");
        return element;
    }
    // Get the encryption algorithm to use
    String encryptionAlgorithm = keyRequirements.getEncryptionAlgorithm();
    if (encryptionAlgorithm == null) {
        // If none then default to what is configured
        encryptionAlgorithm = encryptionProperties.getEncryptionAlgorithm();
    } else {
        List<String> supportedAlgorithms = encryptionProperties.getAcceptedEncryptionAlgorithms();
        if (!supportedAlgorithms.contains(encryptionAlgorithm)) {
            encryptionAlgorithm = encryptionProperties.getEncryptionAlgorithm();
            if (LOG.isLoggable(Level.FINE)) {
                LOG.fine("EncryptionAlgorithm not supported, defaulting to: " + encryptionAlgorithm);
            }
        }
    }
    // Get the key-wrap algorithm to use
    String keyWrapAlgorithm = keyRequirements.getKeywrapAlgorithm();
    if (keyWrapAlgorithm == null) {
        // If none then default to what is configured
        keyWrapAlgorithm = encryptionProperties.getKeyWrapAlgorithm();
    } else {
        List<String> supportedAlgorithms = encryptionProperties.getAcceptedKeyWrapAlgorithms();
        if (!supportedAlgorithms.contains(keyWrapAlgorithm)) {
            keyWrapAlgorithm = encryptionProperties.getKeyWrapAlgorithm();
            if (LOG.isLoggable(Level.FINE)) {
                LOG.fine("KeyWrapAlgorithm not supported, defaulting to: " + keyWrapAlgorithm);
            }
        }
    }
    Document doc = element.getOwnerDocument();
    DocumentFragment frag = doc.createDocumentFragment();
    frag.appendChild(element);
    WSSecEncrypt builder = new WSSecEncrypt(doc);
    if (ConfigurationConstants.USE_REQ_SIG_CERT.equals(name)) {
        X509Certificate cert = getReqSigCert(messageContext);
        builder.setUseThisCert(cert);
    } else {
        builder.setUserInfo(name);
    }
    builder.setKeyIdentifierType(encryptionProperties.getKeyIdentifierType());
    builder.setSymmetricEncAlgorithm(encryptionAlgorithm);
    builder.setKeyEncAlgo(keyWrapAlgorithm);
    builder.setEmbedEncryptedKey(true);
    WSEncryptionPart encryptionPart = new WSEncryptionPart(id, "Element");
    encryptionPart.setElement(element);
    builder.prepare(stsProperties.getEncryptionCrypto());
    builder.encryptForRef(null, Collections.singletonList(encryptionPart));
    return (Element) frag.getFirstChild();
}
Also used : WSEncryptionPart(org.apache.wss4j.common.WSEncryptionPart) WSSecEncrypt(org.apache.wss4j.dom.message.WSSecEncrypt) JAXBElement(javax.xml.bind.JAXBElement) Element(org.w3c.dom.Element) Document(org.w3c.dom.Document) DocumentFragment(org.w3c.dom.DocumentFragment) X509Certificate(java.security.cert.X509Certificate)

Example 2 with WSEncryptionPart

use of org.apache.wss4j.common.WSEncryptionPart in project cxf by apache.

the class AbstractBindingBuilder method getParts.

/**
 * Identifies the portions of the message to be signed/encrypted.
 *
 * @param sign
 *            whether the matches are to be signed or encrypted
 * @param includeBody
 *            if the body should be included in the signature/encryption
 * @param parts
 *            any {@code WSEncryptionPart}s to match for signature or
 *            encryption as specified by WS-SP signed parts or encrypted
 *            parts. Parts without a name match all elements with the
 *            provided namespace.
 * @param found
 *            a list of elements that have previously been tagged for
 *            signing/encryption. Populated with additional matches found by
 *            this method and used to prevent including the same element
 *            twice under the same operation.
 * @return a configured list of {@code WSEncryptionPart}s suitable for
 *         processing by WSS4J
 * @throws SOAPException
 *             if there is an error extracting SOAP content from the SAAJ
 *             model
 */
protected List<WSEncryptionPart> getParts(boolean sign, boolean includeBody, List<WSEncryptionPart> parts, List<Element> found) throws SOAPException {
    List<WSEncryptionPart> result = new ArrayList<>();
    Element soapBody = SAAJUtils.getBody(this.saaj);
    soapBody = (Element) DOMUtils.getDomElement(soapBody);
    if (includeBody && !found.contains(soapBody)) {
        found.add(soapBody);
        final String id = this.addWsuIdToElement(soapBody);
        if (sign) {
            WSEncryptionPart bodyPart = new WSEncryptionPart(id, "Element");
            bodyPart.setElement(soapBody);
            result.add(bodyPart);
        } else {
            WSEncryptionPart bodyPart = new WSEncryptionPart(id, "Content");
            bodyPart.setElement(soapBody);
            result.add(bodyPart);
        }
    }
    final SOAPHeader header = SAAJUtils.getHeader(saaj);
    // Handle sign/enc parts
    for (WSEncryptionPart part : parts) {
        if (part.getId() != null && part.getId().startsWith("cid:")) {
            // Attachments are handled inside WSS4J via a CallbackHandler
            result.add(part);
            continue;
        }
        final List<Element> elements;
        if (StringUtils.isEmpty(part.getName())) {
            // An entire namespace
            elements = DOMUtils.getChildrenWithNamespace(header, part.getNamespace());
        } else {
            // All elements with a given name and namespace
            elements = DOMUtils.getChildrenWithName(header, part.getNamespace(), part.getName());
        }
        for (Element el : elements) {
            if (!found.contains(el)) {
                found.add(el);
                // Generate an ID for the element and use this ID or else
                // WSS4J will only ever sign/encrypt the first matching
                // element with the same name and namespace as that in the
                // WSEncryptionPart
                final String id = this.addWsuIdToElement(el);
                WSEncryptionPart elPart = new WSEncryptionPart(id, part.getEncModifier());
                elPart.setElement(el);
                result.add(elPart);
            }
        }
    }
    return result;
}
Also used : WSEncryptionPart(org.apache.wss4j.common.WSEncryptionPart) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) SOAPHeader(javax.xml.soap.SOAPHeader)

Example 3 with WSEncryptionPart

use of org.apache.wss4j.common.WSEncryptionPart in project cxf by apache.

the class AbstractBindingBuilder method convertToEncryptionPart.

/**
 * Convert a DOM Element into a WSEncryptionPart, adding a (wsu:)Id if there is not
 * one already.
 * @param element The DOM Element to convert
 * @return The WSEncryptionPart representing the DOM Element argument
 */
public WSEncryptionPart convertToEncryptionPart(Element element) {
    String id = addWsuIdToElement(element);
    WSEncryptionPart part = new WSEncryptionPart(id);
    part.setElement(element);
    return part;
}
Also used : WSEncryptionPart(org.apache.wss4j.common.WSEncryptionPart)

Example 4 with WSEncryptionPart

use of org.apache.wss4j.common.WSEncryptionPart in project cxf by apache.

the class AbstractBindingBuilder method doEndorsedSignatures.

protected void doEndorsedSignatures(List<SupportingToken> tokenList, boolean isTokenProtection, boolean isSigProtect) {
    for (SupportingToken supportingToken : tokenList) {
        Object tempTok = supportingToken.getTokenImplementation();
        List<WSEncryptionPart> sigParts = new ArrayList<>();
        WSEncryptionPart sigPart = new WSEncryptionPart(mainSigId);
        sigPart.setElement(bottomUpElement);
        sigParts.add(sigPart);
        if (supportingToken.getSignedParts() != null) {
            for (WSEncryptionPart signedPart : supportingToken.getSignedParts()) {
                sigParts.add(signedPart);
            }
        }
        if (tempTok instanceof WSSecSignature) {
            WSSecSignature sig = (WSSecSignature) tempTok;
            if (isTokenProtection && sig.getBSTTokenId() != null) {
                WSEncryptionPart bstPart = new WSEncryptionPart(sig.getBSTTokenId());
                bstPart.setElement(sig.getBinarySecurityTokenElement());
                sigParts.add(bstPart);
            }
            try {
                List<Reference> referenceList = sig.addReferencesToSign(sigParts);
                sig.computeSignature(referenceList, false, null);
                addSig(sig.getSignatureValue());
                if (isSigProtect) {
                    WSEncryptionPart part = new WSEncryptionPart(sig.getId(), "Element");
                    encryptedTokensList.add(part);
                }
            } catch (WSSecurityException e) {
                unassertPolicy(supportingToken.getToken(), e);
            }
        } else if (tempTok instanceof WSSecurityTokenHolder) {
            SecurityToken token = ((WSSecurityTokenHolder) tempTok).getToken();
            if (isTokenProtection) {
                sigParts.add(new WSEncryptionPart(token.getId()));
            }
            try {
                if (supportingToken.getToken().getDerivedKeys() == DerivedKeys.RequireDerivedKeys) {
                    doSymmSignatureDerived(supportingToken.getToken(), token, sigParts, isTokenProtection, isSigProtect);
                } else {
                    doSymmSignature(supportingToken.getToken(), token, sigParts, isTokenProtection, isSigProtect);
                }
            } catch (Exception e) {
                LOG.log(Level.FINE, e.getMessage(), e);
            }
        } else if (tempTok instanceof WSSecUsernameToken) {
            WSSecUsernameToken utBuilder = (WSSecUsernameToken) tempTok;
            String id = utBuilder.getId();
            Instant created = Instant.now();
            Instant expires = created.plusSeconds(WSS4JUtils.getSecurityTokenLifetime(message) / 1000L);
            SecurityToken secToken = new SecurityToken(id, utBuilder.getUsernameTokenElement(), created, expires);
            if (isTokenProtection) {
                sigParts.add(new WSEncryptionPart(secToken.getId()));
            }
            try {
                byte[] secret = utBuilder.getDerivedKey();
                secToken.setSecret(secret);
                if (supportingToken.getToken().getDerivedKeys() == DerivedKeys.RequireDerivedKeys) {
                    doSymmSignatureDerived(supportingToken.getToken(), secToken, sigParts, isTokenProtection, isSigProtect);
                } else {
                    doSymmSignature(supportingToken.getToken(), secToken, sigParts, isTokenProtection, isSigProtect);
                }
            } catch (Exception e) {
                LOG.log(Level.FINE, e.getMessage(), e);
            }
        }
    }
}
Also used : WSEncryptionPart(org.apache.wss4j.common.WSEncryptionPart) Reference(javax.xml.crypto.dsig.Reference) SecurityTokenReference(org.apache.wss4j.common.token.SecurityTokenReference) WSSecSignature(org.apache.wss4j.dom.message.WSSecSignature) Instant(java.time.Instant) ArrayList(java.util.ArrayList) 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) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) WSSecUsernameToken(org.apache.wss4j.dom.message.WSSecUsernameToken)

Example 5 with WSEncryptionPart

use of org.apache.wss4j.common.WSEncryptionPart in project cxf by apache.

the class AbstractBindingBuilder method getSignedParts.

public List<WSEncryptionPart> getSignedParts(SupportingTokens supportingToken) throws SOAPException {
    boolean isSignBody = false;
    SignedParts parts = null;
    SignedElements elements = null;
    if (supportingToken != null && supportingToken.isEndorsing()) {
        parts = supportingToken.getSignedParts();
        elements = supportingToken.getSignedElements();
        // Store them so that the main Signature doesn't sign them
        if (parts != null) {
            suppTokenParts.add(parts);
            this.assertPolicy(parts.getName());
        }
        if (elements != null) {
            suppTokenParts.add(elements);
            this.assertPolicy(elements.getName());
        }
    } else {
        Collection<AssertionInfo> ais = getAllAssertionsByLocalname(SPConstants.SIGNED_PARTS);
        if (!ais.isEmpty()) {
            for (AssertionInfo ai : ais) {
                SignedParts signedParts = (SignedParts) ai.getAssertion();
                ai.setAsserted(true);
                if (!suppTokenParts.contains(signedParts)) {
                    parts = signedParts;
                }
            }
        }
        ais = getAllAssertionsByLocalname(SPConstants.SIGNED_ELEMENTS);
        if (!ais.isEmpty()) {
            for (AssertionInfo ai : ais) {
                SignedElements signedElements = (SignedElements) ai.getAssertion();
                ai.setAsserted(true);
                if (!suppTokenParts.contains(signedElements)) {
                    elements = signedElements;
                }
            }
        }
    }
    if (parts == null && elements == null) {
        return new ArrayList<>();
    }
    List<WSEncryptionPart> signedParts = new ArrayList<>();
    if (parts != null) {
        isSignBody = parts.isBody();
        for (Header head : parts.getHeaders()) {
            WSEncryptionPart wep = new WSEncryptionPart(head.getName(), head.getNamespace(), "Header");
            signedParts.add(wep);
        }
        Attachments attachments = parts.getAttachments();
        if (attachments != null) {
            String modifier = "Element";
            if (attachments.isContentSignatureTransform()) {
                modifier = "Content";
            }
            WSEncryptionPart wep = new WSEncryptionPart("cid:Attachments", modifier);
            signedParts.add(wep);
        }
    }
    return getPartsAndElements(true, isSignBody, signedParts, elements == null ? null : elements.getXPaths(), null);
}
Also used : AssertionInfo(org.apache.cxf.ws.policy.AssertionInfo) WSEncryptionPart(org.apache.wss4j.common.WSEncryptionPart) SOAPHeader(javax.xml.soap.SOAPHeader) Header(org.apache.wss4j.policy.model.Header) WSSecHeader(org.apache.wss4j.dom.message.WSSecHeader) SignedElements(org.apache.wss4j.policy.model.SignedElements) ArrayList(java.util.ArrayList) SignedParts(org.apache.wss4j.policy.model.SignedParts) Attachments(org.apache.wss4j.policy.model.Attachments)

Aggregations

WSEncryptionPart (org.apache.wss4j.common.WSEncryptionPart)25 Element (org.w3c.dom.Element)17 ArrayList (java.util.ArrayList)13 WSSecUsernameToken (org.apache.wss4j.dom.message.WSSecUsernameToken)10 QName (javax.xml.namespace.QName)8 SecurityToken (org.apache.cxf.ws.security.tokenstore.SecurityToken)8 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)8 SecurityTokenReference (org.apache.wss4j.common.token.SecurityTokenReference)8 Reference (javax.xml.crypto.dsig.Reference)7 SOAPException (javax.xml.soap.SOAPException)7 WSSecSignature (org.apache.wss4j.dom.message.WSSecSignature)7 UsernameToken (org.apache.wss4j.policy.model.UsernameToken)7 Fault (org.apache.cxf.interceptor.Fault)6 AbstractToken (org.apache.wss4j.policy.model.AbstractToken)6 AlgorithmSuiteType (org.apache.wss4j.policy.model.AlgorithmSuite.AlgorithmSuiteType)6 IssuedToken (org.apache.wss4j.policy.model.IssuedToken)6 AttachmentCallbackHandler (org.apache.cxf.ws.security.wss4j.AttachmentCallbackHandler)5 KerberosToken (org.apache.wss4j.policy.model.KerberosToken)5 SecureConversationToken (org.apache.wss4j.policy.model.SecureConversationToken)5 SecurityContextToken (org.apache.wss4j.policy.model.SecurityContextToken)5