Search in sources :

Example 16 with SAMLKeyInfo

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

the class AbstractSamlInHandler method validateToken.

protected void validateToken(Message message, SamlAssertionWrapper assertion) {
    try {
        RequestData data = new RequestData();
        data.setMsgContext(message);
        // Add Audience Restrictions for SAML
        configureAudienceRestriction(message, data);
        if (assertion.isSigned()) {
            WSSConfig cfg = WSSConfig.getNewInstance();
            data.setWssConfig(cfg);
            data.setCallbackHandler(RSSecurityUtils.getCallbackHandler(message, this.getClass()));
            try {
                data.setSigVerCrypto(new CryptoLoader().getCrypto(message, SecurityConstants.SIGNATURE_CRYPTO, SecurityConstants.SIGNATURE_PROPERTIES));
            } catch (IOException ex) {
                throwFault("Crypto can not be loaded", ex);
            }
            boolean enableRevocation = false;
            String enableRevocationStr = (String) org.apache.cxf.rt.security.utils.SecurityUtils.getSecurityPropertyValue(SecurityConstants.ENABLE_REVOCATION, message);
            if (enableRevocationStr != null) {
                enableRevocation = Boolean.parseBoolean(enableRevocationStr);
            }
            data.setEnableRevocation(enableRevocation);
            Signature sig = assertion.getSignature();
            WSDocInfo docInfo = new WSDocInfo(sig.getDOM().getOwnerDocument());
            data.setWsDocInfo(docInfo);
            SAMLKeyInfo samlKeyInfo = null;
            KeyInfo keyInfo = sig.getKeyInfo();
            if (keyInfo != null) {
                samlKeyInfo = SAMLUtil.getCredentialFromKeyInfo(keyInfo.getDOM(), new WSSSAMLKeyInfoProcessor(data), data.getSigVerCrypto());
            } else if (!keyInfoMustBeAvailable) {
                samlKeyInfo = createKeyInfoFromDefaultAlias(data.getSigVerCrypto());
            }
            assertion.verifySignature(samlKeyInfo);
            assertion.parseSubject(new WSSSAMLKeyInfoProcessor(data), data.getSigVerCrypto(), data.getCallbackHandler());
        } else if (getTLSCertificates(message) == null) {
            throwFault("Assertion must be signed", null);
        }
        if (samlValidator != null) {
            Credential credential = new Credential();
            credential.setSamlAssertion(assertion);
            samlValidator.validate(credential, data);
        }
        checkSubjectConfirmationData(message, assertion);
        setSecurityContext(message, assertion);
    } catch (Exception ex) {
        throwFault("Assertion can not be validated", ex);
    }
}
Also used : WSDocInfo(org.apache.wss4j.dom.WSDocInfo) Credential(org.apache.wss4j.dom.validate.Credential) CryptoLoader(org.apache.cxf.rs.security.common.CryptoLoader) IOException(java.io.IOException) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) IOException(java.io.IOException) SAMLKeyInfo(org.apache.wss4j.common.saml.SAMLKeyInfo) WSSConfig(org.apache.wss4j.dom.engine.WSSConfig) KeyInfo(org.opensaml.xmlsec.signature.KeyInfo) SAMLKeyInfo(org.apache.wss4j.common.saml.SAMLKeyInfo) RequestData(org.apache.wss4j.dom.handler.RequestData) Signature(org.opensaml.xmlsec.signature.Signature) WSSSAMLKeyInfoProcessor(org.apache.wss4j.dom.saml.WSSSAMLKeyInfoProcessor)

Example 17 with SAMLKeyInfo

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

the class SAMLTokenRenewer method validateAssertion.

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);
            }
        }
    }
}
Also used : WSDocInfo(org.apache.wss4j.dom.WSDocInfo) CallbackHandler(javax.security.auth.callback.CallbackHandler) STSException(org.apache.cxf.ws.security.sts.provider.STSException) DateTime(org.joda.time.DateTime) Crypto(org.apache.wss4j.common.crypto.Crypto) AudienceRestriction(org.opensaml.saml.saml2.core.AudienceRestriction) SAMLKeyInfo(org.apache.wss4j.common.saml.SAMLKeyInfo) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) WSSConfig(org.apache.wss4j.dom.engine.WSSConfig) RequestData(org.apache.wss4j.dom.handler.RequestData) AudienceRestrictionCondition(org.opensaml.saml.saml1.core.AudienceRestrictionCondition) WSSSAMLKeyInfoProcessor(org.apache.wss4j.dom.saml.WSSSAMLKeyInfoProcessor)

Example 18 with SAMLKeyInfo

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

the class IssueSamlUnitTest method testIssueSaml2SymmetricKeyTokenEncryptedKey.

/**
 * Test to successfully issue a Saml2 SymmetricKey token. Rather than using a Nonce as the Entropy,
 * a secret key is supplied by the client instead in an EncryptedKey structure.
 */
@org.junit.Test
public void testIssueSaml2SymmetricKeyTokenEncryptedKey() throws Exception {
    TokenIssueOperation issueOperation = new TokenIssueOperation();
    // Add Token Provider
    issueOperation.setTokenProviders(Collections.singletonList(new SAMLTokenProvider()));
    // Add Service
    ServiceMBean service = new StaticService();
    service.setEndpoints(Collections.singletonList("http://dummy-service.com/dummy"));
    issueOperation.setServices(Collections.singletonList(service));
    // Add STSProperties object
    STSPropertiesMBean stsProperties = new StaticSTSProperties();
    Crypto crypto = CryptoFactory.getInstance(getEncryptionProperties());
    stsProperties.setEncryptionCrypto(crypto);
    stsProperties.setSignatureCrypto(crypto);
    stsProperties.setEncryptionUsername("myservicekey");
    stsProperties.setSignatureUsername("mystskey");
    stsProperties.setCallbackHandler(new PasswordCallbackHandler());
    stsProperties.setIssuer("STS");
    issueOperation.setStsProperties(stsProperties);
    // Mock up a request
    RequestSecurityTokenType request = new RequestSecurityTokenType();
    JAXBElement<String> tokenType = new JAXBElement<String>(QNameConstants.TOKEN_TYPE, String.class, WSS4JConstants.WSS_SAML2_TOKEN_TYPE);
    request.getAny().add(tokenType);
    JAXBElement<String> keyType = new JAXBElement<String>(QNameConstants.KEY_TYPE, String.class, STSConstants.SYMMETRIC_KEY_KEYTYPE);
    request.getAny().add(keyType);
    request.getAny().add(createAppliesToElement("http://dummy-service.com/dummy"));
    // Mock up message context
    MessageImpl msg = new MessageImpl();
    WrappedMessageContext msgCtx = new WrappedMessageContext(msg);
    Principal principal = new CustomTokenPrincipal("alice");
    msgCtx.put(SecurityContext.class.getName(), createSecurityContext(principal));
    // Now add Entropy
    Document doc = DOMUtils.createDocument();
    WSSecEncryptedKey builder = new WSSecEncryptedKey(doc);
    builder.setUserInfo("mystskey");
    builder.setKeyIdentifierType(WSConstants.ISSUER_SERIAL);
    builder.setKeyEncAlgo(WSS4JConstants.KEYTRANSPORT_RSAOAEP);
    KeyGenerator keyGen = KeyUtils.getKeyGenerator(WSConstants.AES_128);
    SecretKey symmetricKey = keyGen.generateKey();
    builder.prepare(stsProperties.getSignatureCrypto(), symmetricKey);
    Element encryptedKeyElement = builder.getEncryptedKeyElement();
    byte[] secret = symmetricKey.getEncoded();
    EntropyType entropyType = new EntropyType();
    entropyType.getAny().add(encryptedKeyElement);
    JAXBElement<EntropyType> entropyJaxbType = new JAXBElement<>(QNameConstants.ENTROPY, EntropyType.class, entropyType);
    request.getAny().add(entropyJaxbType);
    RequestSecurityTokenResponseCollectionType response = issueOperation.issue(request, principal, msgCtx);
    List<RequestSecurityTokenResponseType> securityTokenResponse = response.getRequestSecurityTokenResponse();
    assertFalse(securityTokenResponse.isEmpty());
    // Test the generated token.
    Element assertion = null;
    for (Object tokenObject : securityTokenResponse.get(0).getAny()) {
        if (tokenObject instanceof JAXBElement<?> && REQUESTED_SECURITY_TOKEN.equals(((JAXBElement<?>) tokenObject).getName())) {
            RequestedSecurityTokenType rstType = (RequestedSecurityTokenType) ((JAXBElement<?>) tokenObject).getValue();
            assertion = (Element) rstType.getAny();
        }
    }
    assertNotNull(assertion);
    String tokenString = DOM2Writer.nodeToString(assertion);
    assertTrue(tokenString.contains("AttributeStatement"));
    assertTrue(tokenString.contains("alice"));
    assertFalse(tokenString.contains(SAML2Constants.CONF_BEARER));
    assertTrue(tokenString.contains(SAML2Constants.CONF_HOLDER_KEY));
    // Test that the (encrypted) secret sent in Entropy was used in the SAML Subject KeyInfo
    SamlAssertionWrapper assertionWrapper = new SamlAssertionWrapper(assertion);
    RequestData data = new RequestData();
    Properties properties = new Properties();
    properties.put("org.apache.wss4j.crypto.provider", "org.apache.wss4j.common.crypto.Merlin");
    properties.put("org.apache.wss4j.crypto.merlin.keystore.password", "sspass");
    properties.put("org.apache.wss4j.crypto.merlin.keystore.file", "keys/servicestore.jks");
    data.setDecCrypto(CryptoFactory.getInstance(properties));
    data.setCallbackHandler(new PasswordCallbackHandler());
    data.setWssConfig(WSSConfig.getNewInstance());
    data.setWsDocInfo(new WSDocInfo(assertion.getOwnerDocument()));
    assertionWrapper.parseSubject(new WSSSAMLKeyInfoProcessor(data), data.getSigVerCrypto(), data.getCallbackHandler());
    SAMLKeyInfo samlKeyInfo = assertionWrapper.getSubjectKeyInfo();
    assertArrayEquals(secret, samlKeyInfo.getSecret());
}
Also used : WSSecEncryptedKey(org.apache.wss4j.dom.message.WSSecEncryptedKey) ServiceMBean(org.apache.cxf.sts.service.ServiceMBean) RequestSecurityTokenType(org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenType) JAXBElement(javax.xml.bind.JAXBElement) Element(org.w3c.dom.Element) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) RequestSecurityTokenResponseType(org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenResponseType) StaticSTSProperties(org.apache.cxf.sts.StaticSTSProperties) RequestedSecurityTokenType(org.apache.cxf.ws.security.sts.provider.model.RequestedSecurityTokenType) StaticService(org.apache.cxf.sts.service.StaticService) Document(org.w3c.dom.Document) RequestSecurityTokenResponseCollectionType(org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenResponseCollectionType) EncryptionProperties(org.apache.cxf.sts.service.EncryptionProperties) SignatureProperties(org.apache.cxf.sts.SignatureProperties) StaticSTSProperties(org.apache.cxf.sts.StaticSTSProperties) Properties(java.util.Properties) CustomTokenPrincipal(org.apache.wss4j.common.principal.CustomTokenPrincipal) SAMLKeyInfo(org.apache.wss4j.common.saml.SAMLKeyInfo) EntropyType(org.apache.cxf.ws.security.sts.provider.model.EntropyType) RequestData(org.apache.wss4j.dom.handler.RequestData) PasswordCallbackHandler(org.apache.cxf.sts.common.PasswordCallbackHandler) KeyGenerator(javax.crypto.KeyGenerator) WSDocInfo(org.apache.wss4j.dom.WSDocInfo) JAXBElement(javax.xml.bind.JAXBElement) Crypto(org.apache.wss4j.common.crypto.Crypto) SecretKey(javax.crypto.SecretKey) SAMLTokenProvider(org.apache.cxf.sts.token.provider.SAMLTokenProvider) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) WrappedMessageContext(org.apache.cxf.jaxws.context.WrappedMessageContext) SecurityContext(org.apache.cxf.security.SecurityContext) MessageImpl(org.apache.cxf.message.MessageImpl) WSSSAMLKeyInfoProcessor(org.apache.wss4j.dom.saml.WSSSAMLKeyInfoProcessor) CustomTokenPrincipal(org.apache.wss4j.common.principal.CustomTokenPrincipal) Principal(java.security.Principal)

Example 19 with SAMLKeyInfo

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

the class STSRESTTest method testIssuePublicKeySAML2TokenShortKeyType.

@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());
}
Also used : SAMLKeyInfo(org.apache.wss4j.common.saml.SAMLKeyInfo) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) Document(org.w3c.dom.Document) WebClient(org.apache.cxf.jaxrs.client.WebClient)

Example 20 with SAMLKeyInfo

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

the class STSRESTTest method testIssuePublicKeySAML2Token.

@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());
}
Also used : SAMLKeyInfo(org.apache.wss4j.common.saml.SAMLKeyInfo) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) Document(org.w3c.dom.Document) WebClient(org.apache.cxf.jaxrs.client.WebClient)

Aggregations

SAMLKeyInfo (org.apache.wss4j.common.saml.SAMLKeyInfo)23 SamlAssertionWrapper (org.apache.wss4j.common.saml.SamlAssertionWrapper)12 WSSSAMLKeyInfoProcessor (org.apache.wss4j.dom.saml.WSSSAMLKeyInfoProcessor)10 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)9 WSDocInfo (org.apache.wss4j.dom.WSDocInfo)9 RequestData (org.apache.wss4j.dom.handler.RequestData)9 WSSConfig (org.apache.wss4j.dom.engine.WSSConfig)8 Credential (org.apache.wss4j.dom.validate.Credential)8 X509Certificate (java.security.cert.X509Certificate)7 KeyInfo (org.opensaml.xmlsec.signature.KeyInfo)7 WSSecurityEngineResult (org.apache.wss4j.dom.engine.WSSecurityEngineResult)5 Document (org.w3c.dom.Document)5 WebClient (org.apache.cxf.jaxrs.client.WebClient)4 SecurityToken (org.apache.cxf.ws.security.tokenstore.SecurityToken)4 BasicX509Credential (org.opensaml.security.x509.BasicX509Credential)4 Signature (org.opensaml.xmlsec.signature.Signature)4 IOException (java.io.IOException)3 PublicKey (java.security.PublicKey)3 STSPropertiesMBean (org.apache.cxf.sts.STSPropertiesMBean)3 Crypto (org.apache.wss4j.common.crypto.Crypto)3