Search in sources :

Example 1 with TokenValidatorResponse

use of org.apache.cxf.sts.token.validator.TokenValidatorResponse in project ddf by codice.

the class PKITokenValidator method validateToken.

/**
     * Validate a Token using the given TokenValidatorParameters.
     *
     * @param tokenParameters
     * @return TokenValidatorResponse
     */
public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
    LOGGER.trace("Validating PKI Token");
    STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();
    Crypto sigCrypto = stsProperties.getSignatureCrypto();
    CallbackHandler callbackHandler = stsProperties.getCallbackHandler();
    RequestData requestData = new RequestData();
    requestData.setSigVerCrypto(sigCrypto);
    requestData.setWssConfig(WSSConfig.getNewInstance());
    requestData.setCallbackHandler(callbackHandler);
    TokenValidatorResponse response = new TokenValidatorResponse();
    ReceivedToken validateTarget = tokenParameters.getToken();
    validateTarget.setState(STATE.INVALID);
    response.setToken(validateTarget);
    PKIAuthenticationToken pkiToken = getPKITokenFromTarget(validateTarget);
    if (pkiToken == null) {
        return response;
    }
    BinarySecurityTokenType binarySecurityType = pkiToken.createBinarySecurityTokenType(pkiToken.getCredentials());
    // Test the encoding type
    String encodingType = binarySecurityType.getEncodingType();
    if (!PKIAuthenticationToken.BASE64_ENCODING.equals(encodingType)) {
        LOGGER.trace("Bad encoding type attribute specified: {}", encodingType);
        return response;
    }
    //
    // Turn the received JAXB object into a DOM element
    //
    Document doc = DOMUtils.createDocument();
    BinarySecurity binarySecurity = new X509Security(doc);
    binarySecurity.setEncodingType(encodingType);
    binarySecurity.setValueType(binarySecurityType.getValueType());
    String data = binarySecurityType.getValue();
    Node textNode = doc.createTextNode(data);
    binarySecurity.getElement().appendChild(textNode);
    //
    try {
        Credential credential = new Credential();
        credential.setBinarySecurityToken(binarySecurity);
        if (merlin != null) {
            byte[] token = binarySecurity.getToken();
            if (token != null) {
                X509Certificate[] certificates = merlin.getCertificatesFromBytes(token);
                if (certificates != null) {
                    if (doPathValidation) {
                        credential.setCertificates(certificates);
                    } else {
                        credential.setCertificates(new X509Certificate[] { certificates[0] });
                    }
                }
            } else {
                LOGGER.debug("Binary Security Token bytes were null.");
            }
        }
        Credential returnedCredential = validator.validate(credential, requestData);
        X500Principal subjectX500Principal = returnedCredential.getCertificates()[0].getSubjectX500Principal();
        response.setPrincipal(subjectX500Principal);
        if (response.getAdditionalProperties() == null) {
            response.setAdditionalProperties(new HashMap<>());
        }
        try {
            String emailAddress = SubjectUtils.getEmailAddress(subjectX500Principal);
            if (emailAddress != null) {
                response.getAdditionalProperties().put(SubjectUtils.EMAIL_ADDRESS_CLAIM_URI, emailAddress);
            }
            String country = SubjectUtils.getCountry(subjectX500Principal);
            if (country != null) {
                response.getAdditionalProperties().put(SubjectUtils.COUNTRY_CLAIM_URI, country);
            }
        } catch (Exception e) {
            LOGGER.debug("Unable to set email address or country from certificate.", e);
        }
        validateTarget.setPrincipal(subjectX500Principal);
        validateTarget.setState(STATE.VALID);
    } catch (WSSecurityException ex) {
        LOGGER.info("Unable to validate credentials.", ex);
    }
    return response;
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) Credential(org.apache.wss4j.dom.validate.Credential) BinarySecurity(org.apache.wss4j.common.token.BinarySecurity) Node(org.w3c.dom.Node) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) Document(org.w3c.dom.Document) X509Certificate(java.security.cert.X509Certificate) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) IOException(java.io.IOException) PKIAuthenticationToken(org.codice.ddf.security.handler.api.PKIAuthenticationToken) Crypto(org.apache.wss4j.common.crypto.Crypto) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) BinarySecurityTokenType(org.apache.cxf.ws.security.sts.provider.model.secext.BinarySecurityTokenType) RequestData(org.apache.wss4j.dom.handler.RequestData) X500Principal(javax.security.auth.x500.X500Principal) TokenValidatorResponse(org.apache.cxf.sts.token.validator.TokenValidatorResponse) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken) X509Security(org.apache.wss4j.common.token.X509Security)

Example 2 with TokenValidatorResponse

use of org.apache.cxf.sts.token.validator.TokenValidatorResponse in project ddf by codice.

the class TestPKITokenValidator method testValidateAnyRealmToken.

@Test
public void testValidateAnyRealmToken() {
    BinarySecurityTokenType binarySecurityTokenType = new BinarySecurityTokenType();
    binarySecurityTokenType.setEncodingType(WSConstants.SOAPMESSAGE_NS + "#Base64Binary");
    binarySecurityTokenType.setValueType(PKIAuthenticationToken.PKI_TOKEN_VALUE_TYPE);
    PKIAuthenticationTokenFactory pkiAuthenticationTokenFactory = new PKIAuthenticationTokenFactory();
    pkiAuthenticationTokenFactory.setSignaturePropertiesPath(TestPKITokenValidator.class.getResource("/signature.properties").getPath());
    pkiAuthenticationTokenFactory.init();
    PKIAuthenticationToken pkiAuthenticationToken = pkiAuthenticationTokenFactory.getTokenFromCerts(certificates, "*");
    binarySecurityTokenType.setValue(pkiAuthenticationToken.getEncodedCredentials());
    ReceivedToken receivedToken = mock(ReceivedToken.class);
    when(receivedToken.getToken()).thenReturn(binarySecurityTokenType);
    TokenValidatorParameters tokenValidatorParameters = mock(TokenValidatorParameters.class);
    STSPropertiesMBean stsPropertiesMBean = mock(STSPropertiesMBean.class);
    when(stsPropertiesMBean.getSignatureCrypto()).thenReturn(merlin);
    when(tokenValidatorParameters.getStsProperties()).thenReturn(stsPropertiesMBean);
    when(tokenValidatorParameters.getToken()).thenReturn(receivedToken);
    doCallRealMethod().when(receivedToken).setState(any(ReceivedToken.STATE.class));
    doCallRealMethod().when(receivedToken).getState();
    TokenValidatorResponse tokenValidatorResponse = pkiTokenValidator.validateToken(tokenValidatorParameters);
    assertEquals(ReceivedToken.STATE.VALID, tokenValidatorResponse.getToken().getState());
    assertEquals("US", tokenValidatorResponse.getAdditionalProperties().get(SubjectUtils.COUNTRY_CLAIM_URI));
    assertEquals("localhost@example.org", tokenValidatorResponse.getAdditionalProperties().get(SubjectUtils.EMAIL_ADDRESS_CLAIM_URI));
}
Also used : TokenValidatorParameters(org.apache.cxf.sts.token.validator.TokenValidatorParameters) PKIAuthenticationToken(org.codice.ddf.security.handler.api.PKIAuthenticationToken) BinarySecurityTokenType(org.apache.cxf.ws.security.sts.provider.model.secext.BinarySecurityTokenType) PKIAuthenticationTokenFactory(org.codice.ddf.security.handler.api.PKIAuthenticationTokenFactory) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) TokenValidatorResponse(org.apache.cxf.sts.token.validator.TokenValidatorResponse) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken) Test(org.junit.Test)

Example 3 with TokenValidatorResponse

use of org.apache.cxf.sts.token.validator.TokenValidatorResponse in project ddf by codice.

the class UPBSTValidator method validateToken.

/**
     * Validate a Token using the given TokenValidatorParameters.
     *
     * @param tokenParameters
     * @return TokenValidatorResponse
     */
public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
    LOGGER.trace("Validating UPBST Token");
    if (parser == null) {
        throw new IllegalStateException("XMLParser must be configured.");
    }
    if (failedLoginDelayer == null) {
        throw new IllegalStateException("Failed Login Delayer must be configured");
    }
    STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();
    Crypto sigCrypto = stsProperties.getSignatureCrypto();
    CallbackHandler callbackHandler = stsProperties.getCallbackHandler();
    RequestData requestData = new RequestData();
    requestData.setSigVerCrypto(sigCrypto);
    requestData.setWssConfig(WSSConfig.getNewInstance());
    requestData.setCallbackHandler(callbackHandler);
    TokenValidatorResponse response = new TokenValidatorResponse();
    ReceivedToken validateTarget = tokenParameters.getToken();
    validateTarget.setState(STATE.INVALID);
    response.setToken(validateTarget);
    if (!validateTarget.isBinarySecurityToken()) {
        return response;
    }
    BinarySecurityTokenType binarySecurityType = (BinarySecurityTokenType) validateTarget.getToken();
    // Test the encoding type
    String encodingType = binarySecurityType.getEncodingType();
    if (!UPAuthenticationToken.BASE64_ENCODING.equals(encodingType)) {
        LOGGER.trace("Bad encoding type attribute specified: {}", encodingType);
        return response;
    }
    UPAuthenticationToken usernameToken = getUsernameTokenFromTarget(validateTarget);
    if (usernameToken == null) {
        return response;
    }
    UsernameTokenType usernameTokenType = getUsernameTokenType(usernameToken);
    // Marshall the received JAXB object into a DOM Element
    Element usernameTokenElement = null;
    JAXBElement<UsernameTokenType> tokenType = new JAXBElement<>(QNameConstants.USERNAME_TOKEN, UsernameTokenType.class, usernameTokenType);
    Document doc = DOMUtils.createDocument();
    Element rootElement = doc.createElement("root-element");
    List<String> ctxPath = new ArrayList<>(1);
    ctxPath.add(UsernameTokenType.class.getPackage().getName());
    ParserConfigurator configurator = parser.configureParser(ctxPath, UPBSTValidator.class.getClassLoader());
    try {
        parser.marshal(configurator, tokenType, rootElement);
    } catch (ParserException ex) {
        LOGGER.info("Unable to parse username token", ex);
        return response;
    }
    usernameTokenElement = (Element) rootElement.getFirstChild();
    //
    // Validate the token
    //
    WSSConfig wssConfig = WSSConfig.getNewInstance();
    try {
        boolean allowNamespaceQualifiedPasswordTypes = requestData.isAllowNamespaceQualifiedPasswordTypes();
        UsernameToken ut = new UsernameToken(usernameTokenElement, allowNamespaceQualifiedPasswordTypes, new BSPEnforcer());
        // The parsed principal is set independent whether validation is successful or not
        response.setPrincipal(new CustomTokenPrincipal(ut.getName()));
        if (ut.getPassword() == null) {
            return response;
        }
        String tokenId = String.format("%s:%s:%s", usernameToken.getUsername(), usernameToken.getPassword(), usernameToken.getRealm());
        // See if the UsernameToken is stored in the cache
        int hash = tokenId.hashCode();
        SecurityToken secToken = null;
        if (tokenParameters.getTokenStore() != null) {
            secToken = tokenParameters.getTokenStore().getToken(Integer.toString(hash));
            if (secToken != null && secToken.getTokenHash() != hash) {
                secToken = null;
            } else if (secToken != null) {
                validateTarget.setState(STATE.VALID);
            }
        }
        if (secToken == null) {
            Credential credential = new Credential();
            credential.setUsernametoken(ut);
            if (usernameToken.getRealm() != null && !"*".equals(usernameToken.getRealm())) {
                Validator validator = validators.get(usernameToken.getRealm());
                if (validator != null) {
                    try {
                        validator.validate(credential, requestData);
                        validateTarget.setState(STATE.VALID);
                        LOGGER.debug("Validated user against realm {}", usernameToken.getRealm());
                    } catch (WSSecurityException ex) {
                        LOGGER.debug("Not able to validate user against realm {}", usernameToken.getRealm());
                    }
                }
            } else {
                Set<Map.Entry<String, Validator>> entries = validators.entrySet();
                for (Map.Entry<String, Validator> entry : entries) {
                    try {
                        entry.getValue().validate(credential, requestData);
                        validateTarget.setState(STATE.VALID);
                        LOGGER.debug("Validated user against realm {}", entry.getKey());
                        break;
                    } catch (WSSecurityException ex) {
                        LOGGER.debug("Not able to validate user against realm {}", entry.getKey());
                    }
                }
            }
        }
        Principal principal = createPrincipal(ut.getName(), ut.getPassword(), ut.getPasswordType(), ut.getNonce(), ut.getCreated());
        // Store the successfully validated token in the cache
        if (tokenParameters.getTokenStore() != null && secToken == null && STATE.VALID.equals(validateTarget.getState())) {
            secToken = new SecurityToken(ut.getID());
            secToken.setToken(ut.getElement());
            int hashCode = tokenId.hashCode();
            String identifier = Integer.toString(hashCode);
            secToken.setTokenHash(hashCode);
            tokenParameters.getTokenStore().add(identifier, secToken);
        }
        response.setPrincipal(principal);
        response.setTokenRealm(null);
        validateTarget.setPrincipal(principal);
    } catch (WSSecurityException ex) {
        LOGGER.debug("Unable to validate token.", ex);
    }
    if (response.getToken().getState() != STATE.VALID) {
        failedLoginDelayer.delay(response.getToken().getPrincipal().getName());
    }
    return response;
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) JAXBElement(javax.xml.bind.JAXBElement) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) UsernameToken(org.apache.wss4j.dom.message.token.UsernameToken) AttributedString(org.apache.cxf.ws.security.sts.provider.model.secext.AttributedString) PasswordString(org.apache.cxf.ws.security.sts.provider.model.secext.PasswordString) Document(org.w3c.dom.Document) CustomTokenPrincipal(org.apache.wss4j.common.principal.CustomTokenPrincipal) BinarySecurityTokenType(org.apache.cxf.ws.security.sts.provider.model.secext.BinarySecurityTokenType) WSSConfig(org.apache.wss4j.dom.engine.WSSConfig) RequestData(org.apache.wss4j.dom.handler.RequestData) UPAuthenticationToken(org.codice.ddf.security.handler.api.UPAuthenticationToken) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken) ParserException(org.codice.ddf.parser.ParserException) Credential(org.apache.wss4j.dom.validate.Credential) UsernameTokenType(org.apache.cxf.ws.security.sts.provider.model.secext.UsernameTokenType) BSPEnforcer(org.apache.wss4j.common.bsp.BSPEnforcer) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) JAXBElement(javax.xml.bind.JAXBElement) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) ParserConfigurator(org.codice.ddf.parser.ParserConfigurator) Crypto(org.apache.wss4j.common.crypto.Crypto) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) TokenValidatorResponse(org.apache.cxf.sts.token.validator.TokenValidatorResponse) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Validator(org.apache.wss4j.dom.validate.Validator) JAASUsernameTokenValidator(org.apache.wss4j.dom.validate.JAASUsernameTokenValidator) TokenValidator(org.apache.cxf.sts.token.validator.TokenValidator) CustomTokenPrincipal(org.apache.wss4j.common.principal.CustomTokenPrincipal) Principal(java.security.Principal)

Example 4 with TokenValidatorResponse

use of org.apache.cxf.sts.token.validator.TokenValidatorResponse in project ddf by codice.

the class TestPKITokenValidator method testNoValidateToken.

@Test
public void testNoValidateToken() {
    BinarySecurityTokenType binarySecurityTokenType = new BinarySecurityTokenType();
    binarySecurityTokenType.setEncodingType(WSConstants.SOAPMESSAGE_NS + "#Base64Binary");
    binarySecurityTokenType.setValueType(PKIAuthenticationToken.PKI_TOKEN_VALUE_TYPE);
    PKIAuthenticationTokenFactory pkiAuthenticationTokenFactory = new PKIAuthenticationTokenFactory();
    pkiAuthenticationTokenFactory.setSignaturePropertiesPath(TestPKITokenValidator.class.getResource("/badSignature.properties").getPath());
    pkiAuthenticationTokenFactory.init();
    PKIAuthenticationToken pkiAuthenticationToken = pkiAuthenticationTokenFactory.getTokenFromCerts(badCertificates, "karaf");
    binarySecurityTokenType.setValue(pkiAuthenticationToken.getEncodedCredentials());
    ReceivedToken receivedToken = mock(ReceivedToken.class);
    when(receivedToken.getToken()).thenReturn(binarySecurityTokenType);
    TokenValidatorParameters tokenValidatorParameters = mock(TokenValidatorParameters.class);
    STSPropertiesMBean stsPropertiesMBean = mock(STSPropertiesMBean.class);
    when(stsPropertiesMBean.getSignatureCrypto()).thenReturn(merlin);
    when(tokenValidatorParameters.getStsProperties()).thenReturn(stsPropertiesMBean);
    when(tokenValidatorParameters.getToken()).thenReturn(receivedToken);
    doCallRealMethod().when(receivedToken).setState(any(ReceivedToken.STATE.class));
    doCallRealMethod().when(receivedToken).getState();
    TokenValidatorResponse tokenValidatorResponse = pkiTokenValidator.validateToken(tokenValidatorParameters);
    assertEquals(ReceivedToken.STATE.INVALID, tokenValidatorResponse.getToken().getState());
}
Also used : TokenValidatorParameters(org.apache.cxf.sts.token.validator.TokenValidatorParameters) PKIAuthenticationToken(org.codice.ddf.security.handler.api.PKIAuthenticationToken) BinarySecurityTokenType(org.apache.cxf.ws.security.sts.provider.model.secext.BinarySecurityTokenType) PKIAuthenticationTokenFactory(org.codice.ddf.security.handler.api.PKIAuthenticationTokenFactory) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) TokenValidatorResponse(org.apache.cxf.sts.token.validator.TokenValidatorResponse) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken) Test(org.junit.Test)

Example 5 with TokenValidatorResponse

use of org.apache.cxf.sts.token.validator.TokenValidatorResponse in project ddf by codice.

the class UPBSTValidatorTest method testValidateBadTokenCache.

@Test
public void testValidateBadTokenCache() {
    UPBSTValidator upbstValidator = getUpbstValidator(new XmlParser(), meanValidator);
    upbstValidator.addRealm(null);
    TokenValidatorParameters tokenParameters = new TokenValidatorParameters();
    tokenParameters.setTokenStore(new TokenStore() {

        @Override
        public void add(SecurityToken token) {
        }

        @Override
        public void add(String identifier, SecurityToken token) {
        }

        @Override
        public void remove(String identifier) {
        }

        @Override
        public Collection<String> getTokenIdentifiers() {
            return null;
        }

        @Override
        public SecurityToken getToken(String identifier) {
            SecurityToken securityToken = new SecurityToken();
            securityToken.setTokenHash(-1432225336);
            return securityToken;
        }
    });
    ReceivedToken validateTarget = new ReceivedToken(upbstToken);
    tokenParameters.setToken(validateTarget);
    tokenParameters.setStsProperties(stsPropertiesMBean);
    TokenValidatorResponse response = upbstValidator.validateToken(tokenParameters);
    Assert.assertEquals(ReceivedToken.STATE.INVALID, response.getToken().getState());
    verify(failedLoginDelayer, times(1)).delay(anyString());
}
Also used : TokenValidatorParameters(org.apache.cxf.sts.token.validator.TokenValidatorParameters) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) XmlParser(org.codice.ddf.parser.xml.XmlParser) Collection(java.util.Collection) TokenValidatorResponse(org.apache.cxf.sts.token.validator.TokenValidatorResponse) Matchers.anyString(org.mockito.Matchers.anyString) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken) TokenStore(org.apache.cxf.ws.security.tokenstore.TokenStore) Test(org.junit.Test)

Aggregations

TokenValidatorResponse (org.apache.cxf.sts.token.validator.TokenValidatorResponse)28 ReceivedToken (org.apache.cxf.sts.request.ReceivedToken)23 Test (org.junit.Test)19 TokenValidatorParameters (org.apache.cxf.sts.token.validator.TokenValidatorParameters)18 STSPropertiesMBean (org.apache.cxf.sts.STSPropertiesMBean)16 Crypto (org.apache.wss4j.common.crypto.Crypto)13 BinarySecurityTokenType (org.apache.cxf.ws.security.sts.provider.model.secext.BinarySecurityTokenType)12 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)10 RequestData (org.apache.wss4j.dom.handler.RequestData)10 Credential (org.apache.wss4j.dom.validate.Credential)9 X509Certificate (java.security.cert.X509Certificate)7 XmlParser (org.codice.ddf.parser.xml.XmlParser)7 X500Principal (javax.security.auth.x500.X500Principal)6 CallbackHandler (javax.security.auth.callback.CallbackHandler)5 JAASUsernameTokenValidator (org.apache.wss4j.dom.validate.JAASUsernameTokenValidator)5 PKIAuthenticationToken (org.codice.ddf.security.handler.api.PKIAuthenticationToken)4 Principal (java.security.Principal)3 HashSet (java.util.HashSet)3 JAXBContext (javax.xml.bind.JAXBContext)3 JAXBException (javax.xml.bind.JAXBException)3