Java Code Examples for org.apache.wss4j.common.saml.SamlAssertionWrapper#getSubjectKeyInfo()

The following examples show how to use org.apache.wss4j.common.saml.SamlAssertionWrapper#getSubjectKeyInfo() . 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: STSRESTTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testIssueSymmetricKeySaml1() throws Exception {
    WebClient client = webClient()
        .path("saml1.1")
        .query("keyType", STSConstants.SYMMETRIC_KEY_KEYTYPE)
        .accept(MediaType.APPLICATION_XML);

    Document assertionDoc = client.get(Document.class);

    SamlAssertionWrapper assertion = validateSAMLToken(assertionDoc);
    assertTrue(assertion.getSaml2() == null && assertion.getSaml1() != null);

    List<String> methods = assertion.getConfirmationMethods();
    String confirmMethod = null;
    if (methods != null && !methods.isEmpty()) {
        confirmMethod = methods.get(0);
    }
    assertTrue(OpenSAMLUtil.isMethodHolderOfKey(confirmMethod));
    SAMLKeyInfo subjectKeyInfo = assertion.getSubjectKeyInfo();
    assertNotNull(subjectKeyInfo.getSecret());
}
 
Example 2
Source File: STSRESTTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testIssueSymmetricKeySaml1ShortKeyType() throws Exception {
    WebClient client = webClient()
        .path("saml1.1")
        .query("keyType", "SymmetricKey")
        .accept(MediaType.APPLICATION_XML);

    Document assertionDoc = client.get(Document.class);

    SamlAssertionWrapper assertion = validateSAMLToken(assertionDoc);
    assertTrue(assertion.getSaml2() == null && assertion.getSaml1() != null);

    List<String> methods = assertion.getConfirmationMethods();
    String confirmMethod = null;
    if (methods != null && !methods.isEmpty()) {
        confirmMethod = methods.get(0);
    }
    assertTrue(OpenSAMLUtil.isMethodHolderOfKey(confirmMethod));
    SAMLKeyInfo subjectKeyInfo = assertion.getSubjectKeyInfo();
    assertNotNull(subjectKeyInfo.getSecret());
}
 
Example 3
Source File: STSRESTTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testIssuePublicKeySAML2Token() throws Exception {
    WebClient client = webClient()
        .path("saml2.0")
        .query("keyType", STSConstants.PUBLIC_KEY_KEYTYPE)
        .accept(MediaType.APPLICATION_XML);

    Document assertionDoc = client.get(Document.class);

    SamlAssertionWrapper assertion = validateSAMLToken(assertionDoc);
    assertTrue(assertion.getSaml2() != null && assertion.getSaml1() == null);

    List<String> methods = assertion.getConfirmationMethods();
    String confirmMethod = null;
    if (methods != null && !methods.isEmpty()) {
        confirmMethod = methods.get(0);
    }
    assertTrue(OpenSAMLUtil.isMethodHolderOfKey(confirmMethod));
    SAMLKeyInfo subjectKeyInfo = assertion.getSubjectKeyInfo();
    assertNotNull(subjectKeyInfo.getCerts());
}
 
Example 4
Source File: STSRESTTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testIssuePublicKeySAML2TokenShortKeyType() throws Exception {
    WebClient client = webClient()
        .path("saml2.0")
        .query("keyType", "PublicKey")
        .accept(MediaType.APPLICATION_XML);

    Document assertionDoc = client.get(Document.class);

    SamlAssertionWrapper assertion = validateSAMLToken(assertionDoc);
    assertTrue(assertion.getSaml2() != null && assertion.getSaml1() == null);

    List<String> methods = assertion.getConfirmationMethods();
    String confirmMethod = null;
    if (methods != null && !methods.isEmpty()) {
        confirmMethod = methods.get(0);
    }
    assertTrue(OpenSAMLUtil.isMethodHolderOfKey(confirmMethod));
    SAMLKeyInfo subjectKeyInfo = assertion.getSubjectKeyInfo();
    assertNotNull(subjectKeyInfo.getCerts());
}
 
Example 5
Source File: SCTTokenValidator.java    From cxf with Apache License 2.0 6 votes vote down vote up
public Credential validate(Credential credential, RequestData data) throws WSSecurityException {
    Credential validatedCredential = super.validate(credential, data);

    SamlAssertionWrapper transformedToken = validatedCredential.getTransformedToken();
    if (transformedToken == null || transformedToken.getSaml2() == null
        || !"DoubleItSTSIssuer".equals(transformedToken.getIssuerString())) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE);
    }

    transformedToken.parseSubject(
        new WSSSAMLKeyInfoProcessor(data), data.getSigVerCrypto(),
        data.getCallbackHandler()
    );
    SAMLKeyInfo keyInfo = transformedToken.getSubjectKeyInfo();
    byte[] secret = keyInfo.getSecret();
    validatedCredential.setSecretKey(secret);

    return validatedCredential;
}
 
Example 6
Source File: IssuedTokenPolicyValidator.java    From cxf with Apache License 2.0 6 votes vote down vote up
private SecurityToken createSecurityToken(
    SamlAssertionWrapper assertionWrapper
) {
    SecurityToken token = new SecurityToken(assertionWrapper.getId());

    SAMLKeyInfo subjectKeyInfo = assertionWrapper.getSubjectKeyInfo();
    if (subjectKeyInfo != null) {
        token.setSecret(subjectKeyInfo.getSecret());
        X509Certificate[] certs = subjectKeyInfo.getCerts();
        if (certs != null && certs.length > 0) {
            token.setX509Certificate(certs[0], null);
        }
        if (subjectKeyInfo.getPublicKey() != null) {
            token.setKey(subjectKeyInfo.getPublicKey());
        }
    }
    if (assertionWrapper.getSaml1() != null) {
        token.setTokenType(WSS4JConstants.WSS_SAML_TOKEN_TYPE);
    } else if (assertionWrapper.getSaml2() != null) {
        token.setTokenType(WSS4JConstants.WSS_SAML2_TOKEN_TYPE);
    }
    token.setToken(assertionWrapper.getElement());

    return token;
}
 
Example 7
Source File: SAMLUtil.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
/**
 * Check the holder-of-key requirements against the received assertion. The subject
 * credential of the SAML Assertion must match a client certificate credential when
 * 2-way TLS is used.
 * @param assertionWrapper the SAML Assertion wrapper object
 * @param tlsCerts The client certificates
 */
public static boolean checkHolderOfKey(
    SamlAssertionWrapper assertionWrapper,
    Certificate[] tlsCerts
) {
    List<String> confirmationMethods = assertionWrapper.getConfirmationMethods();
    for (String confirmationMethod : confirmationMethods) {
        if (OpenSAMLUtil.isMethodHolderOfKey(confirmationMethod)) {
            if (tlsCerts == null || tlsCerts.length == 0) {
                return false;
            }
            SAMLKeyInfo subjectKeyInfo = assertionWrapper.getSubjectKeyInfo();
            if (!compareCredentials(subjectKeyInfo, tlsCerts)) {
                return false;
            }
        }
    }
    return true;
}
 
Example 8
Source File: IssueUnitTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Test the Symmetric Key SAML1 case
 */
@org.junit.Test
public void testSymmetricKeySaml1() throws Exception {
    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = IssueUnitTest.class.getResource("cxf-client.xml");

    Bus bus = bf.createBus(busFile.toString());
    BusFactory.setDefaultBus(bus);
    BusFactory.setThreadDefaultBus(bus);

    // Get a token
    SecurityToken token =
        requestSecurityToken(SAML1_TOKEN_TYPE, SYMMETRIC_KEY_KEYTYPE, bus, DEFAULT_ADDRESS);
    assertTrue(token.getSecret() != null && token.getSecret().length > 0);
    assertEquals(SAML1_TOKEN_TYPE, token.getTokenType());
    assertNotNull(token.getToken());

    // Process the token
    List<WSSecurityEngineResult> results = processToken(token);

    assertTrue(results != null && results.size() == 1);
    SamlAssertionWrapper assertion =
        (SamlAssertionWrapper)results.get(0).get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
    assertNotNull(assertion);
    assertTrue(assertion.getSaml1() != null && assertion.getSaml2() == null);
    assertTrue(assertion.isSigned());

    List<String> methods = assertion.getConfirmationMethods();
    String confirmMethod = null;
    if (methods != null && !methods.isEmpty()) {
        confirmMethod = methods.get(0);
    }
    assertTrue(OpenSAMLUtil.isMethodHolderOfKey(confirmMethod));
    SAMLKeyInfo subjectKeyInfo = assertion.getSubjectKeyInfo();
    assertNotNull(subjectKeyInfo.getSecret());

    bus.shutdown(true);
}
 
Example 9
Source File: IssueUnitTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Test the Public Key SAML2 case
 */
@org.junit.Test
public void testPublicKeySaml2() throws Exception {
    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = IssueUnitTest.class.getResource("cxf-client.xml");

    Bus bus = bf.createBus(busFile.toString());
    BusFactory.setDefaultBus(bus);
    BusFactory.setThreadDefaultBus(bus);

    // Get a token
    SecurityToken token =
        requestSecurityToken(SAML2_TOKEN_TYPE, PUBLIC_KEY_KEYTYPE, bus, DEFAULT_ADDRESS);
    assertTrue(token.getSecret() == null && token.getX509Certificate() != null);
    assertEquals(SAML2_TOKEN_TYPE, token.getTokenType());
    assertNotNull(token.getToken());

    // Process the token
    List<WSSecurityEngineResult> results = processToken(token);
    assertTrue(results != null && results.size() == 1);
    SamlAssertionWrapper assertion =
        (SamlAssertionWrapper)results.get(0).get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
    assertNotNull(assertion);
    assertTrue(assertion.getSaml1() == null && assertion.getSaml2() != null);
    assertTrue(assertion.isSigned());

    List<String> methods = assertion.getConfirmationMethods();
    String confirmMethod = null;
    if (methods != null && !methods.isEmpty()) {
        confirmMethod = methods.get(0);
    }
    assertTrue(OpenSAMLUtil.isMethodHolderOfKey(confirmMethod));
    SAMLKeyInfo subjectKeyInfo = assertion.getSubjectKeyInfo();
    assertNotNull(subjectKeyInfo.getCerts());

    bus.shutdown(true);
}
 
Example 10
Source File: AbstractSamlInHandler.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected boolean checkHolderOfKey(Message message,
                                SamlAssertionWrapper assertionWrapper,
                                Certificate[] tlsCerts) {
    List<String> confirmationMethods = assertionWrapper.getConfirmationMethods();
    for (String confirmationMethod : confirmationMethods) {
        if (OpenSAMLUtil.isMethodHolderOfKey(confirmationMethod)) {
            SAMLKeyInfo subjectKeyInfo = assertionWrapper.getSubjectKeyInfo();
            if (!compareCredentials(subjectKeyInfo, message, tlsCerts)) {
                return false;
            }
        }
    }
    return true;
}
 
Example 11
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 12
Source File: AbstractBindingPolicyValidator.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Find the token corresponding to either the X509Certificate or PublicKey used to sign
 * the "signatureResult" argument.
 */
private WSSecurityEngineResult findCorrespondingToken(
    WSSecurityEngineResult signatureResult,
    List<WSSecurityEngineResult> results
) {
    // See what was used to sign this result
    X509Certificate cert =
        (X509Certificate)signatureResult.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);
    PublicKey publicKey =
        (PublicKey)signatureResult.get(WSSecurityEngineResult.TAG_PUBLIC_KEY);

    for (WSSecurityEngineResult token : results) {
        Integer actInt = (Integer)token.get(WSSecurityEngineResult.TAG_ACTION);
        if (actInt == WSConstants.SIGN) {
            continue;
        }

        BinarySecurity binarySecurity =
            (BinarySecurity)token.get(WSSecurityEngineResult.TAG_BINARY_SECURITY_TOKEN);
        PublicKey foundPublicKey =
            (PublicKey)token.get(WSSecurityEngineResult.TAG_PUBLIC_KEY);
        if (binarySecurity instanceof X509Security
            || binarySecurity instanceof PKIPathSecurity) {
            X509Certificate foundCert =
                (X509Certificate)token.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);
            if (foundCert.equals(cert)) {
                return token;
            }
        } else if (actInt.intValue() == WSConstants.ST_SIGNED
            || actInt.intValue() == WSConstants.ST_UNSIGNED) {
            SamlAssertionWrapper assertionWrapper =
                (SamlAssertionWrapper)token.get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
            SAMLKeyInfo samlKeyInfo = assertionWrapper.getSubjectKeyInfo();
            if (samlKeyInfo != null) {
                X509Certificate[] subjectCerts = samlKeyInfo.getCerts();
                PublicKey subjectPublicKey = samlKeyInfo.getPublicKey();
                if ((cert != null && subjectCerts != null
                    && cert.equals(subjectCerts[0]))
                    || (subjectPublicKey != null && subjectPublicKey.equals(publicKey))) {
                    return token;
                }
            }
        } else if (publicKey != null && publicKey.equals(foundPublicKey)) {
            return token;
        }
    }
    return null;
}
 
Example 13
Source File: AbstractSupportingTokenPolicyValidator.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Process SAML Tokens. Only signed results are supported.
 */
protected boolean processSAMLTokens(PolicyValidatorParameters parameters, boolean derived) {
    if (parameters.getSamlResults().isEmpty()) {
        return false;
    }

    List<WSSecurityEngineResult> tokenResults = new ArrayList<>();
    tokenResults.addAll(parameters.getSamlResults());


    if (isSigned() && !areTokensSigned(tokenResults, parameters.getSignedResults(),
                                       parameters.getEncryptedResults(),
                                       parameters.getMessage())) {
        return false;
    }
    if (isEncrypted() && !areTokensEncrypted(tokenResults,
                                             parameters.getEncryptedResults())) {
        return false;
    }

    if (derived && parameters.getResults().getActionResults().containsKey(WSConstants.DKT)) {
        List<WSSecurityEngineResult> dktResults = new ArrayList<>(tokenResults.size());
        for (WSSecurityEngineResult wser : tokenResults) {
            SamlAssertionWrapper assertion =
                (SamlAssertionWrapper)wser.get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
            if (assertion != null && assertion.getSubjectKeyInfo() != null
                && assertion.getSubjectKeyInfo().getSecret() != null) {
                WSSecurityEngineResult dktResult =
                    getMatchingDerivedKey(assertion.getSubjectKeyInfo().getSecret(), parameters.getResults());
                if (dktResult != null) {
                    dktResults.add(dktResult);
                }
            }
        }
        tokenResults.addAll(dktResults);
    }


    if (isEndorsing() && !checkEndorsed(tokenResults, parameters.getSignedResults(),
                                        parameters.getMessage(),
                                        parameters.getTimestampElement())) {
        return false;
    }

    return validateSignedEncryptedPolicies(tokenResults, parameters.getSignedResults(),
                                         parameters.getEncryptedResults(),
                                         parameters.getMessage());
}
 
Example 14
Source File: AbstractSupportingTokenPolicyValidator.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Check that a WSSecurityEngineResult corresponding to a signature or encryption uses the same
 * signing/encrypting credential as one of the tokens.
 * @param result a WSSecurityEngineResult corresponding to a signature or encryption
 * @param tokenResult A list of WSSecurityEngineResults corresponding to tokens
 * @return
 */
private boolean checkSignatureOrEncryptionResult(
    WSSecurityEngineResult result,
    List<WSSecurityEngineResult> tokenResult
) {
    // See what was used to sign/encrypt this result
    X509Certificate cert =
        (X509Certificate)result.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);
    byte[] secret = (byte[])result.get(WSSecurityEngineResult.TAG_SECRET);
    PublicKey publicKey =
        (PublicKey)result.get(WSSecurityEngineResult.TAG_PUBLIC_KEY);

    // Now see if the same credential exists in the tokenResult list
    for (WSSecurityEngineResult token : tokenResult) {
        Integer actInt = (Integer)token.get(WSSecurityEngineResult.TAG_ACTION);
        BinarySecurity binarySecurity =
            (BinarySecurity)token.get(WSSecurityEngineResult.TAG_BINARY_SECURITY_TOKEN);
        if (binarySecurity instanceof X509Security
            || binarySecurity instanceof PKIPathSecurity) {
            X509Certificate foundCert =
                (X509Certificate)token.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);
            if (foundCert.equals(cert)) {
                return true;
            }
        } else if (actInt.intValue() == WSConstants.ST_SIGNED
            || actInt.intValue() == WSConstants.ST_UNSIGNED) {
            SamlAssertionWrapper assertionWrapper =
                (SamlAssertionWrapper)token.get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
            SAMLKeyInfo samlKeyInfo = assertionWrapper.getSubjectKeyInfo();
            if (samlKeyInfo != null) {
                X509Certificate[] subjectCerts = samlKeyInfo.getCerts();
                byte[] subjectSecretKey = samlKeyInfo.getSecret();
                PublicKey subjectPublicKey = samlKeyInfo.getPublicKey();
                if ((cert != null && subjectCerts != null && cert.equals(subjectCerts[0]))
                    || (subjectSecretKey != null && Arrays.equals(subjectSecretKey, secret))
                    || (subjectPublicKey != null && subjectPublicKey.equals(publicKey))) {
                    return true;
                }
            }
        } else if (publicKey != null) {
            PublicKey foundPublicKey =
                (PublicKey)token.get(WSSecurityEngineResult.TAG_PUBLIC_KEY);
            if (publicKey.equals(foundPublicKey)) {
                return true;
            }
        } else {
            byte[] foundSecret = (byte[])token.get(WSSecurityEngineResult.TAG_SECRET);
            byte[] derivedKey =
                (byte[])token.get(WSSecurityEngineResult.TAG_ENCRYPTED_EPHEMERAL_KEY);
            if ((foundSecret != null && Arrays.equals(foundSecret, secret))
                || (derivedKey != null && Arrays.equals(derivedKey, secret))) {
                return true;
            }
        }
    }

    return false;
}
 
Example 15
Source File: LayoutPolicyValidator.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Find the index of the token corresponding to either the X509Certificate or PublicKey used
 * to sign the "signatureResult" argument.
 */
private int findCorrespondingTokenIndex(
    WSSecurityEngineResult signatureResult,
    List<WSSecurityEngineResult> results
) {
    // See what was used to sign this result
    X509Certificate cert =
        (X509Certificate)signatureResult.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);
    PublicKey publicKey =
        (PublicKey)signatureResult.get(WSSecurityEngineResult.TAG_PUBLIC_KEY);

    for (int i = 0; i < results.size(); i++) {
        WSSecurityEngineResult token = results.get(i);
        Integer actInt = (Integer)token.get(WSSecurityEngineResult.TAG_ACTION);
        if (actInt == WSConstants.SIGN) {
            continue;
        }

        BinarySecurity binarySecurity =
            (BinarySecurity)token.get(WSSecurityEngineResult.TAG_BINARY_SECURITY_TOKEN);
        PublicKey foundPublicKey =
            (PublicKey)token.get(WSSecurityEngineResult.TAG_PUBLIC_KEY);
        if (binarySecurity instanceof X509Security
            || binarySecurity instanceof PKIPathSecurity) {
            X509Certificate foundCert =
                (X509Certificate)token.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);
            if (foundCert.equals(cert)) {
                return i;
            }
        } else if (actInt.intValue() == WSConstants.ST_SIGNED
            || actInt.intValue() == WSConstants.ST_UNSIGNED) {
            SamlAssertionWrapper assertionWrapper =
                (SamlAssertionWrapper)token.get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
            SAMLKeyInfo samlKeyInfo = assertionWrapper.getSubjectKeyInfo();
            if (samlKeyInfo != null) {
                X509Certificate[] subjectCerts = samlKeyInfo.getCerts();
                PublicKey subjectPublicKey = samlKeyInfo.getPublicKey();
                if ((cert != null && subjectCerts != null
                    && cert.equals(subjectCerts[0]))
                    || (subjectPublicKey != null && subjectPublicKey.equals(publicKey))) {
                    return i;
                }
            }
        } else if (publicKey != null && publicKey.equals(foundPublicKey)) {
            return i;
        }
    }
    return -1;
}
 
Example 16
Source File: SamlSSOAssertionValidator.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Check the Subject Confirmation method requirements
 */
protected void verifySubjectConfirmationMethod(
    SamlAssertionWrapper samlAssertion
) throws WSSecurityException {

    List<String> methods = samlAssertion.getConfirmationMethods();
    if (methods == null || methods.isEmpty()) {
        if (super.getRequiredSubjectConfirmationMethod() != null) {
            LOG.warning("A required subject confirmation method was not present");
            throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE,
                                      "invalidSAMLsecurity");
        } else if (super.isRequireStandardSubjectConfirmationMethod()) {
            LOG.warning("A standard subject confirmation method was not present");
            throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE,
                                      "invalidSAMLsecurity");
        }
    }

    boolean signed = samlAssertion.isSigned();
    boolean requiredMethodFound = false;
    boolean standardMethodFound = false;
    for (String method : methods) {
        if (OpenSAMLUtil.isMethodHolderOfKey(method)) {
            if (samlAssertion.getSubjectKeyInfo() == null) {
                LOG.warning("There is no Subject KeyInfo to match the holder-of-key subject conf method");
                throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "noKeyInSAMLToken");
            }

            // The assertion must have been signed for HOK
            if (!signed) {
                LOG.warning("A holder-of-key assertion must be signed");
                throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
            }
            standardMethodFound = true;
        }

        if (method != null) {
            if (method.equals(super.getRequiredSubjectConfirmationMethod())) {
                requiredMethodFound = true;
            }
            if (SAML2Constants.CONF_BEARER.equals(method)
                || SAML1Constants.CONF_BEARER.equals(method)) {
                standardMethodFound = true;
                if (super.isRequireBearerSignature() && !signed && !signedResponse) {
                    LOG.warning("A Bearer Assertion was not signed");
                    throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE,
                                                  "invalidSAMLsecurity");
                }
            } else if (SAML2Constants.CONF_SENDER_VOUCHES.equals(method)
                || SAML1Constants.CONF_SENDER_VOUCHES.equals(method)) {
                standardMethodFound = true;
            }
        }
    }

    if (!requiredMethodFound && super.getRequiredSubjectConfirmationMethod() != null) {
        LOG.warning("A required subject confirmation method was not present");
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE,
                                      "invalidSAMLsecurity");
    }

    if (!standardMethodFound && super.isRequireStandardSubjectConfirmationMethod()) {
        LOG.warning("A standard subject confirmation method was not present");
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE,
                                  "invalidSAMLsecurity");
    }
}