Java Code Examples for org.apache.wss4j.dom.handler.RequestData#setWsDocInfo()

The following examples show how to use org.apache.wss4j.dom.handler.RequestData#setWsDocInfo() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BinarySecurityTokenInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
private List<WSSecurityEngineResult> processToken(Element tokenElement, final SoapMessage message)
    throws WSSecurityException {
    RequestData data = new CXFRequestData();
    Object o = SecurityUtils.getSecurityPropertyValue(SecurityConstants.CALLBACK_HANDLER, message);
    try {
        data.setCallbackHandler(SecurityUtils.getCallbackHandler(o));
    } catch (Exception ex) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ex);
    }
    data.setMsgContext(message);
    data.setWssConfig(WSSConfig.getNewInstance());

    WSDocInfo wsDocInfo = new WSDocInfo(tokenElement.getOwnerDocument());
    data.setWsDocInfo(wsDocInfo);

    BinarySecurityTokenProcessor p = new BinarySecurityTokenProcessor();
    return p.handleToken(tokenElement, data);
}
 
Example 2
Source File: SamlTokenInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
private List<WSSecurityEngineResult> processToken(Element tokenElement, final SoapMessage message)
    throws WSSecurityException {

    RequestData data = new CXFRequestData();
    Object o = SecurityUtils.getSecurityPropertyValue(SecurityConstants.CALLBACK_HANDLER, message);
    try {
        data.setCallbackHandler(SecurityUtils.getCallbackHandler(o));
    } catch (Exception ex) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ex);
    }
    data.setMsgContext(message);
    data.setWssConfig(WSSConfig.getNewInstance());

    data.setSigVerCrypto(getCrypto(SecurityConstants.SIGNATURE_CRYPTO,
                                 SecurityConstants.SIGNATURE_PROPERTIES, message));

    WSDocInfo wsDocInfo = new WSDocInfo(tokenElement.getOwnerDocument());
    data.setWsDocInfo(wsDocInfo);

    SAMLTokenProcessor p = new SAMLTokenProcessor();
    return p.handleToken(tokenElement, data);
}
 
Example 3
Source File: STSUnitTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private List<WSSecurityEngineResult> processToken(SecurityToken token) throws Exception {
    RequestData requestData = new RequestData();
    CallbackHandler callbackHandler = new CommonCallbackHandler();
    requestData.setCallbackHandler(callbackHandler);
    Crypto crypto = CryptoFactory.getInstance("clientKeystore.properties",
                                              this.getClass().getClassLoader());
    requestData.setSigVerCrypto(crypto);
    requestData.setWsDocInfo(new WSDocInfo(token.getToken().getOwnerDocument()));

    Processor processor = new SAMLTokenProcessor();
    return processor.handleToken(token.getToken(), requestData);
}
 
Example 4
Source File: IssueUnitTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private List<WSSecurityEngineResult> processToken(SecurityToken token) throws Exception {
    RequestData requestData = new RequestData();
    requestData.setDisableBSPEnforcement(true);
    CallbackHandler callbackHandler = new org.apache.cxf.systest.sts.common.CommonCallbackHandler();
    requestData.setCallbackHandler(callbackHandler);
    Crypto crypto = CryptoFactory.getInstance("serviceKeystore.properties");
    requestData.setDecCrypto(crypto);
    requestData.setSigVerCrypto(crypto);
    requestData.setWsDocInfo(new WSDocInfo(token.getToken().getOwnerDocument()));

    Processor processor = new SAMLTokenProcessor();
    return processor.handleToken(token.getToken(), requestData);
}
 
Example 5
Source File: STSRESTTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private static List<WSSecurityEngineResult> processToken(Element assertionElement)
        throws Exception {
        RequestData requestData = new RequestData();
//        requestData.setDisableBSPEnforcement(true);
        requestData.setCallbackHandler(new org.apache.cxf.systest.sts.common.CommonCallbackHandler());
        requestData.setDecCrypto(serviceCrypto);
//        requestData.setSigVerCrypto(serviceCrypto);
        requestData.setWsDocInfo(new WSDocInfo(assertionElement.getOwnerDocument()));

        return new SAMLTokenProcessor().handleToken(assertionElement, requestData);
    }
 
Example 6
Source File: CustomParameterTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private List<WSSecurityEngineResult> processToken(Element assertionElement)
    throws Exception {
    RequestData requestData = new RequestData();
    requestData.setDisableBSPEnforcement(true);
    CallbackHandler callbackHandler = new org.apache.cxf.systest.sts.common.CommonCallbackHandler();
    requestData.setCallbackHandler(callbackHandler);
    Crypto crypto = CryptoFactory.getInstance("serviceKeystore.properties");
    requestData.setDecCrypto(crypto);
    requestData.setSigVerCrypto(crypto);
    requestData.setWsDocInfo(new WSDocInfo(assertionElement.getOwnerDocument()));

    Processor processor = new SAMLTokenProcessor();
    return processor.handleToken(assertionElement, requestData);
}
 
Example 7
Source File: SimpleBatchSTSClient.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected byte[] decryptKey(Element child) throws TrustException, WSSecurityException {
    String encryptionAlgorithm = X509Util.getEncAlgo(child);
    // For the SPNEGO case just return the decoded cipher value and decrypt it later
    if (encryptionAlgorithm != null && encryptionAlgorithm.endsWith("spnego#GSS_Wrap")) {
        // Get the CipherValue
        Element tmpE =
            XMLUtils.getDirectChildElement(child, "CipherData", WSS4JConstants.ENC_NS);
        byte[] cipherValue = null;
        if (tmpE != null) {
            tmpE =
                XMLUtils.getDirectChildElement(tmpE, "CipherValue", WSS4JConstants.ENC_NS);
            if (tmpE != null) {
                String content = DOMUtils.getContent(tmpE);
                cipherValue = Base64.getMimeDecoder().decode(content);
            }
        }
        if (cipherValue == null) {
            throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY, "noCipher");
        }
        return cipherValue;
    }
    try {
        EncryptedKeyProcessor proc = new EncryptedKeyProcessor();
        RequestData data = new RequestData();
        data.setWssConfig(WSSConfig.getNewInstance());
        data.setDecCrypto(createCrypto(true));
        data.setCallbackHandler(createHandler());

        WSDocInfo docInfo = new WSDocInfo(child.getOwnerDocument());
        data.setWsDocInfo(docInfo);

        List<WSSecurityEngineResult> result = proc.handleToken(child, data);
        return
            (byte[])result.get(0).get(
                WSSecurityEngineResult.TAG_SECRET
            );
    } catch (IOException e) {
        throw new TrustException("ENCRYPTED_KEY_ERROR", e, LOG);
    }
}
 
Example 8
Source File: AbstractSTSClient.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected byte[] decryptKey(Element child) throws TrustException, WSSecurityException, Base64DecodingException {
    String encryptionAlgorithm = X509Util.getEncAlgo(child);
    // For the SPNEGO case just return the decoded cipher value and decrypt it later
    if (encryptionAlgorithm != null && encryptionAlgorithm.endsWith("spnego#GSS_Wrap")) {
        // Get the CipherValue
        Element tmpE =
            XMLUtils.getDirectChildElement(child, "CipherData", WSS4JConstants.ENC_NS);
        byte[] cipherValue = null;
        if (tmpE != null) {
            tmpE =
                XMLUtils.getDirectChildElement(tmpE, "CipherValue", WSS4JConstants.ENC_NS);
            if (tmpE != null) {
                String content = DOMUtils.getContent(tmpE);
                cipherValue = org.apache.xml.security.utils.XMLUtils.decode(content);
            }
        }
        if (cipherValue == null) {
            throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY, "noCipher");
        }
        return cipherValue;
    }
    try {
        EncryptedKeyProcessor proc = new EncryptedKeyProcessor();
        WSDocInfo docInfo = new WSDocInfo(child.getOwnerDocument());
        RequestData data = new RequestData();
        data.setWssConfig(WSSConfig.getNewInstance());
        data.setDecCrypto(createCrypto(true));
        data.setCallbackHandler(createHandler());
        data.setWsDocInfo(docInfo);
        List<WSSecurityEngineResult> result = proc.handleToken(child, data);
        return
            (byte[])result.get(0).get(
                WSSecurityEngineResult.TAG_SECRET
            );
    } catch (IOException e) {
        throw new TrustException("ENCRYPTED_KEY_ERROR", e, LOG);
    }
}
 
Example 9
Source File: SAMLTokenRenewer.java    From cxf with Apache License 2.0 4 votes vote down vote up
private void validateAssertion(
    SamlAssertionWrapper assertion,
    ReceivedToken tokenToRenew,
    SecurityToken token,
    TokenRenewerParameters tokenParameters
) throws WSSecurityException {
    // Check the cached renewal properties
    Map<String, Object> props = token.getProperties();
    if (props == null) {
        LOG.log(Level.WARNING, "Error in getting properties from cached token");
        throw new STSException(
            "Error in getting properties from cached token", STSException.REQUEST_FAILED
        );
    }
    String isAllowRenewal = (String)props.get(STSConstants.TOKEN_RENEWING_ALLOW);
    String isAllowRenewalAfterExpiry =
        (String)props.get(STSConstants.TOKEN_RENEWING_ALLOW_AFTER_EXPIRY);

    if (isAllowRenewal == null || !Boolean.valueOf(isAllowRenewal)) {
        LOG.log(Level.WARNING, "The token is not allowed to be renewed");
        throw new STSException("The token is not allowed to be renewed", STSException.REQUEST_FAILED);
    }

    // Check to see whether the token has expired greater than the configured max expiry time
    if (tokenToRenew.getState() == STATE.EXPIRED) {
        if (!allowRenewalAfterExpiry || isAllowRenewalAfterExpiry == null
            || !Boolean.valueOf(isAllowRenewalAfterExpiry)) {
            LOG.log(Level.WARNING, "Renewal after expiry is not allowed");
            throw new STSException(
                "Renewal after expiry is not allowed", STSException.REQUEST_FAILED
            );
        }
        DateTime expiryDate = getExpiryDate(assertion);
        DateTime currentDate = new DateTime();
        if ((currentDate.getMillis() - expiryDate.getMillis()) > (maxExpiry * 1000L)) {
            LOG.log(Level.WARNING, "The token expired too long ago to be renewed");
            throw new STSException(
                "The token expired too long ago to be renewed", STSException.REQUEST_FAILED
            );
        }
    }

    // Verify Proof of Possession
    ProofOfPossessionValidator popValidator = new ProofOfPossessionValidator();
    if (verifyProofOfPossession) {
        STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();
        Crypto sigCrypto = stsProperties.getSignatureCrypto();
        CallbackHandler callbackHandler = stsProperties.getCallbackHandler();
        RequestData requestData = new RequestData();
        requestData.setSigVerCrypto(sigCrypto);
        WSSConfig wssConfig = WSSConfig.getNewInstance();
        requestData.setWssConfig(wssConfig);

        WSDocInfo docInfo = new WSDocInfo(((Element)tokenToRenew.getToken()).getOwnerDocument());
        requestData.setWsDocInfo(docInfo);
        // Parse the HOK subject if it exists

        assertion.parseSubject(
            new WSSSAMLKeyInfoProcessor(requestData), sigCrypto, callbackHandler
        );

        SAMLKeyInfo keyInfo = assertion.getSubjectKeyInfo();
        if (keyInfo == null) {
            keyInfo = new SAMLKeyInfo((byte[])null);
        }
        if (!popValidator.checkProofOfPossession(tokenParameters, keyInfo)) {
            throw new STSException(
                "Failed to verify the proof of possession of the key associated with the "
                + "saml token. No matching key found in the request.",
                STSException.INVALID_REQUEST
            );
        }
    }

    // Check the AppliesTo address
    String appliesToAddress = tokenParameters.getAppliesToAddress();
    if (appliesToAddress != null) {
        if (assertion.getSaml1() != null) {
            List<AudienceRestrictionCondition> restrConditions =
                assertion.getSaml1().getConditions().getAudienceRestrictionConditions();
            if (!matchSaml1AudienceRestriction(appliesToAddress, restrConditions)) {
                LOG.log(Level.WARNING, "The AppliesTo address does not match the Audience Restriction");
                throw new STSException(
                    "The AppliesTo address does not match the Audience Restriction",
                    STSException.INVALID_REQUEST
                );
            }
        } else {
            List<AudienceRestriction> audienceRestrs =
                assertion.getSaml2().getConditions().getAudienceRestrictions();
            if (!matchSaml2AudienceRestriction(appliesToAddress, audienceRestrs)) {
                LOG.log(Level.WARNING, "The AppliesTo address does not match the Audience Restriction");
                throw new STSException(
                    "The AppliesTo address does not match the Audience Restriction",
                    STSException.INVALID_REQUEST
                );
            }
        }
    }

}
 
Example 10
Source File: SAMLProtocolResponseValidator.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Validate the response signature
 */
private void validateResponseSignature(
    Signature signature,
    Document doc,
    Crypto sigCrypto,
    CallbackHandler callbackHandler
) throws WSSecurityException {
    RequestData requestData = new RequestData();
    requestData.setSigVerCrypto(sigCrypto);
    WSSConfig wssConfig = WSSConfig.getNewInstance();
    requestData.setWssConfig(wssConfig);
    requestData.setCallbackHandler(callbackHandler);
    requestData.setWsDocInfo(new WSDocInfo(doc));

    SAMLKeyInfo samlKeyInfo = null;

    KeyInfo keyInfo = signature.getKeyInfo();
    if (keyInfo != null) {
        try {
            samlKeyInfo =
                SAMLUtil.getCredentialFromKeyInfo(
                    keyInfo.getDOM(), new WSSSAMLKeyInfoProcessor(requestData), sigCrypto
                );
        } catch (WSSecurityException ex) {
            LOG.log(Level.FINE, "Error in getting KeyInfo from SAML Response: " + ex.getMessage(), ex);
            throw ex;
        }
    } else if (!keyInfoMustBeAvailable) {
        samlKeyInfo = createKeyInfoFromDefaultAlias(sigCrypto);
    }
    if (samlKeyInfo == null) {
        LOG.warning("No KeyInfo supplied in the SAMLResponse signature");
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    // Validate Signature against profiles
    validateSignatureAgainstProfiles(signature, samlKeyInfo);

    // Now verify trust on the signature
    Credential trustCredential = new Credential();
    trustCredential.setPublicKey(samlKeyInfo.getPublicKey());
    trustCredential.setCertificates(samlKeyInfo.getCerts());

    try {
        signatureValidator.validate(trustCredential, requestData);
    } catch (WSSecurityException e) {
        LOG.log(Level.FINE, "Error in validating signature on SAML Response: " + e.getMessage(), e);
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }
}
 
Example 11
Source File: SAMLProtocolResponseValidator.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Validate an internal Assertion
 */
private void validateAssertion(
    SamlAssertionWrapper assertion,
    Crypto sigCrypto,
    CallbackHandler callbackHandler,
    Document doc,
    boolean signedResponse
) throws WSSecurityException {
    Credential credential = new Credential();
    credential.setSamlAssertion(assertion);

    RequestData requestData = new RequestData();
    requestData.setSigVerCrypto(sigCrypto);
    WSSConfig wssConfig = WSSConfig.getNewInstance();
    requestData.setWssConfig(wssConfig);
    requestData.setCallbackHandler(callbackHandler);

    if (assertion.isSigned()) {
        if (assertion.getSaml1() != null) {
            assertion.getSaml1().getDOM().setIdAttributeNS(null, "AssertionID", true);
        } else {
            assertion.getSaml2().getDOM().setIdAttributeNS(null, "ID", true);
        }

        // Verify the signature
        try {
            Signature sig = assertion.getSignature();
            WSDocInfo docInfo = new WSDocInfo(sig.getDOM().getOwnerDocument());
            requestData.setWsDocInfo(docInfo);

            SAMLKeyInfo samlKeyInfo = null;

            KeyInfo keyInfo = sig.getKeyInfo();
            if (keyInfo != null) {
                samlKeyInfo = SAMLUtil.getCredentialFromKeyInfo(
                    keyInfo.getDOM(), new WSSSAMLKeyInfoProcessor(requestData), sigCrypto
                );
            } else if (!keyInfoMustBeAvailable) {
                samlKeyInfo = createKeyInfoFromDefaultAlias(sigCrypto);
            }

            if (samlKeyInfo == null) {
                LOG.warning("No KeyInfo supplied in the SAMLResponse assertion signature");
                throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
            }

            assertion.verifySignature(samlKeyInfo);

            assertion.parseSubject(
                new WSSSAMLKeyInfoProcessor(requestData),
                requestData.getSigVerCrypto(),
                requestData.getCallbackHandler()
            );
        } catch (WSSecurityException e) {
            LOG.log(Level.FINE, "Assertion failed signature validation", e);
            throw e;
        }
    }

    // Validate the Assertion & verify trust in the signature
    try {
        SamlSSOAssertionValidator assertionValidator = new SamlSSOAssertionValidator(signedResponse);
        assertionValidator.validate(credential, requestData);
    } catch (WSSecurityException ex) {
        LOG.log(Level.FINE, "Assertion validation failed: " + ex.getMessage(), ex);
        throw ex;
    }
}
 
Example 12
Source File: AuthnRequestParser.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
/**
 * Validate the AuthnRequest or LogoutRequest signature
 */
private void validateRequestSignature(
    Signature signature,
    Crypto sigCrypto
) throws WSSecurityException {
    RequestData requestData = new RequestData();
    requestData.setSigVerCrypto(sigCrypto);
    WSSConfig wssConfig = WSSConfig.getNewInstance();
    requestData.setWssConfig(wssConfig);
    // requestData.setCallbackHandler(callbackHandler);

    SAMLKeyInfo samlKeyInfo = null;

    KeyInfo keyInfo = signature.getKeyInfo();
    if (keyInfo != null) {
        try {
            Document doc = signature.getDOM().getOwnerDocument();
            requestData.setWsDocInfo(new WSDocInfo(doc));
            samlKeyInfo =
                SAMLUtil.getCredentialFromKeyInfo(
                    keyInfo.getDOM(), new WSSSAMLKeyInfoProcessor(requestData), sigCrypto
                );
        } catch (WSSecurityException ex) {
            LOG.debug("Error in getting KeyInfo from SAML AuthnRequest: {}", ex.getMessage(), ex);
            throw ex;
        }
    }

    if (samlKeyInfo == null) {
        LOG.debug("No KeyInfo supplied in the AuthnRequest signature");
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    // Validate Signature against profiles
    validateSignatureAgainstProfiles(signature, samlKeyInfo);

    // Now verify trust on the signature
    Credential trustCredential = new Credential();
    trustCredential.setPublicKey(samlKeyInfo.getPublicKey());
    trustCredential.setCertificates(samlKeyInfo.getCerts());

    try {
        Validator signatureValidator = new SignatureTrustValidator();
        signatureValidator.validate(trustCredential, requestData);
    } catch (WSSecurityException e) {
        LOG.debug("Error in validating signature on SAML AuthnRequest: {}", e.getMessage(), e);
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }
}
 
Example 13
Source File: FederationProcessorImpl.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
private Element decryptEncryptedRST(Element encryptedRST, FedizContext config) throws ProcessingException {

        KeyManager decryptionKeyManager = config.getDecryptionKey();
        if (decryptionKeyManager == null || decryptionKeyManager.getCrypto() == null) {
            LOG.debug("We must have a decryption Crypto instance configured to decrypt encrypted tokens");
            throw new ProcessingException(TYPE.BAD_REQUEST);
        }
        String keyPassword = decryptionKeyManager.getKeyPassword();
        if (keyPassword == null) {
            LOG.debug("We must have a decryption key password to decrypt encrypted tokens");
            throw new ProcessingException(TYPE.BAD_REQUEST);
        }

        EncryptedDataProcessor proc = new EncryptedDataProcessor();
        WSDocInfo docInfo = new WSDocInfo(encryptedRST.getOwnerDocument());
        RequestData data = new RequestData();
        data.setWsDocInfo(docInfo);

        // Disable WSS4J processing of the (decrypted) SAML Token
        WSSConfig wssConfig = WSSConfig.getNewInstance();
        wssConfig.setProcessor(WSConstants.SAML_TOKEN, new NOOpProcessor());
        wssConfig.setProcessor(WSConstants.SAML2_TOKEN, new NOOpProcessor());
        data.setWssConfig(wssConfig);

        data.setDecCrypto(decryptionKeyManager.getCrypto());
        data.setCallbackHandler(new DecryptionCallbackHandler(keyPassword));
        try {
            List<WSSecurityEngineResult> result = proc.handleToken(encryptedRST, data);
            if (!result.isEmpty()) {
                @SuppressWarnings("unchecked")
                List<WSDataRef> dataRefs = (List<WSDataRef>)result.get(result.size() - 1)
                    .get(WSSecurityEngineResult.TAG_DATA_REF_URIS);
                if (dataRefs != null && !dataRefs.isEmpty()) {
                    return dataRefs.get(0).getProtectedElement();
                }
            }
        } catch (WSSecurityException e) {
            LOG.debug(e.getMessage(), e);
            throw new ProcessingException(TYPE.TOKEN_INVALID);
        }
        return null;
    }