Search in sources :

Example 1 with UsernameToken

use of org.apache.wss4j.dom.message.token.UsernameToken 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 2 with UsernameToken

use of org.apache.wss4j.dom.message.token.UsernameToken in project ddf by codice.

the class UsernameTokenValidator method validateToken.

/**
     * Validate a Token using the given TokenValidatorParameters.
     */
public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
    LOGGER.debug("Validating UsernameToken");
    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);
    WSSConfig wssConfig = WSSConfig.getNewInstance();
    requestData.setWssConfig(wssConfig);
    requestData.setCallbackHandler(callbackHandler);
    TokenValidatorResponse response = new TokenValidatorResponse();
    ReceivedToken validateTarget = tokenParameters.getToken();
    validateTarget.setState(ReceivedToken.STATE.INVALID);
    response.setToken(validateTarget);
    if (!validateTarget.isUsernameToken()) {
        return response;
    }
    //
    // Turn the JAXB UsernameTokenType into a DOM Element for validation
    //
    UsernameTokenType usernameTokenType = (UsernameTokenType) validateTarget.getToken();
    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());
    Element usernameTokenElement = null;
    ParserConfigurator configurator = parser.configureParser(ctxPath, UsernameTokenValidator.class.getClassLoader());
    try {
        parser.marshal(configurator, tokenType, rootElement);
        usernameTokenElement = (Element) rootElement.getFirstChild();
    } catch (ParserException ex) {
        LOGGER.info("Unable to parse username token", ex);
        return response;
    }
    //
    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) {
            failedLoginDelayer.delay(ut.getName());
            return response;
        }
        Credential credential = new Credential();
        credential.setUsernametoken(ut);
        //Only this section is new, the rest is copied from the apache class
        Set<Map.Entry<String, Validator>> entries = validators.entrySet();
        for (Map.Entry<String, Validator> entry : entries) {
            try {
                entry.getValue().validate(credential, requestData);
                validateTarget.setState(ReceivedToken.STATE.VALID);
                break;
            } catch (WSSecurityException ex) {
                LOGGER.debug("Unable to validate user against {}" + entry.getKey(), ex);
            }
        }
        if (ReceivedToken.STATE.INVALID.equals(validateTarget.getState())) {
            failedLoginDelayer.delay(ut.getName());
            return response;
        }
        //end new section
        Principal principal = createPrincipal(ut.getName(), ut.getPassword(), ut.getPasswordType(), ut.getNonce(), ut.getCreated());
        response.setPrincipal(principal);
        response.setTokenRealm(null);
        validateTarget.setState(ReceivedToken.STATE.VALID);
        validateTarget.setPrincipal(principal);
    } catch (WSSecurityException ex) {
        LOGGER.debug("Unable to validate token.", ex);
    }
    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) Document(org.w3c.dom.Document) CustomTokenPrincipal(org.apache.wss4j.common.principal.CustomTokenPrincipal) WSSConfig(org.apache.wss4j.dom.engine.WSSConfig) JAASUsernameTokenValidator(org.apache.wss4j.dom.validate.JAASUsernameTokenValidator) RequestData(org.apache.wss4j.dom.handler.RequestData) 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) 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 3 with UsernameToken

use of org.apache.wss4j.dom.message.token.UsernameToken in project tesb-rt-se by Talend.

the class UsernameTokenProvider method createToken.

public TokenProviderResponse createToken(TokenProviderParameters tokenParameters) {
    try {
        Document doc = DOMUtils.createDocument();
        Principal principal = tokenParameters.getPrincipal();
        String user = principal.getName();
        // Get the password
        WSPasswordCallback[] cb = { new WSPasswordCallback(user, WSPasswordCallback.USERNAME_TOKEN) };
        STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();
        stsProperties.getCallbackHandler().handle(cb);
        String password = cb[0].getPassword();
        if (password == null || "".equals(password)) {
            throw new STSException("No password available", STSException.REQUEST_FAILED);
        }
        UsernameToken ut = new UsernameToken(true, doc, WSConstants.PASSWORD_TEXT);
        ut.setName(user);
        ut.setPassword(password);
        WSSConfig config = WSSConfig.getNewInstance();
        ut.setID(config.getIdAllocator().createId("UsernameToken-", ut));
        TokenProviderResponse response = new TokenProviderResponse();
        response.setToken(ut.getElement());
        response.setTokenId(ut.getID());
        return response;
    } catch (Exception e) {
        e.printStackTrace();
        throw new STSException("Error creating UsernameToken", e, STSException.REQUEST_FAILED);
    }
}
Also used : STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) WSSConfig(org.apache.wss4j.dom.engine.WSSConfig) UsernameToken(org.apache.wss4j.dom.message.token.UsernameToken) STSException(org.apache.cxf.ws.security.sts.provider.STSException) TokenProviderResponse(org.apache.cxf.sts.token.provider.TokenProviderResponse) Document(org.w3c.dom.Document) WSPasswordCallback(org.apache.wss4j.common.ext.WSPasswordCallback) Principal(java.security.Principal) STSException(org.apache.cxf.ws.security.sts.provider.STSException)

Example 4 with UsernameToken

use of org.apache.wss4j.dom.message.token.UsernameToken in project tesb-rt-se by Talend.

the class PropertyFileCallbackHandler method validate.

@Override
public Credential validate(Credential credential, RequestData data) throws WSSecurityException {
    if (credential == null || credential.getUsernametoken() == null) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "noCredential");
    }
    String user = null;
    String password = null;
    UsernameToken usernameToken = credential.getUsernametoken();
    user = usernameToken.getName();
    String pwType = usernameToken.getPasswordType();
    if (log.isDebugEnabled()) {
        log.debug("UsernameToken user " + usernameToken.getName());
        log.debug("UsernameToken password type " + pwType);
    }
    if (usernameToken.isHashed()) {
        log.warn("Authentication failed as hashed username token not supported");
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
    }
    password = usernameToken.getPassword();
    if (!WSConstants.PASSWORD_TEXT.equals(pwType)) {
        log.warn("Password type " + pwType + " not supported");
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
    }
    if (!(user != null && user.length() > 0 && password != null && password.length() > 0)) {
        log.warn("User or password empty");
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
    }
    try {
        InputStream stream = PropertyFileCallbackHandler.class.getClassLoader().getResourceAsStream("user.properties");
        Properties properties = new Properties();
        properties.load(stream);
        String propertyPwd = (String) properties.get(user);
        if (propertyPwd == null || !propertyPwd.equalsIgnoreCase(password)) {
            log.info("Authentication failed");
            throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
        }
    } catch (Exception ex) {
        log.info("Authentication failed", ex);
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
    }
    return credential;
}
Also used : InputStream(java.io.InputStream) UsernameToken(org.apache.wss4j.dom.message.token.UsernameToken) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) Properties(java.util.Properties) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException)

Example 5 with UsernameToken

use of org.apache.wss4j.dom.message.token.UsernameToken in project tesb-rt-se by Talend.

the class PropertyFileCallbackHandlerTest method testPropertyFileCallbackHandlerEmptyPassword.

@Test
public void testPropertyFileCallbackHandlerEmptyPassword() throws Exception {
    PropertyFileCallbackHandler handler = new PropertyFileCallbackHandler();
    Document doc = getDocument();
    UsernameToken ut = new UsernameToken(true, doc, WSS4JConstants.PASSWORD_TEXT);
    ut.setName("tadmin");
    ut.setPassword("");
    Credential credential = new Credential();
    credential.setUsernametoken(ut);
    RequestData data = new RequestData();
    try {
        handler.validate(credential, data);
    } catch (WSSecurityException ex) {
        return;
    }
    Assert.fail("Expected WSSecurityException is not thrown ");
}
Also used : Credential(org.apache.wss4j.dom.validate.Credential) RequestData(org.apache.wss4j.dom.handler.RequestData) UsernameToken(org.apache.wss4j.dom.message.token.UsernameToken) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) Document(org.w3c.dom.Document) Test(org.junit.Test)

Aggregations

UsernameToken (org.apache.wss4j.dom.message.token.UsernameToken)46 Document (org.w3c.dom.Document)32 Credential (org.apache.wss4j.dom.validate.Credential)16 RequestData (org.apache.wss4j.dom.handler.RequestData)15 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)12 Element (org.w3c.dom.Element)10 Principal (java.security.Principal)9 WSUsernameTokenPrincipalImpl (org.apache.wss4j.common.principal.WSUsernameTokenPrincipalImpl)5 Test (org.junit.Test)5 UnsupportedCallbackException (javax.security.auth.callback.UnsupportedCallbackException)4 JAXBElement (javax.xml.bind.JAXBElement)4 AuthorizationPolicy (org.apache.cxf.configuration.security.AuthorizationPolicy)4 Message (org.apache.cxf.message.Message)4 ReceivedToken (org.apache.cxf.sts.request.ReceivedToken)4 UsernameTokenType (org.apache.cxf.ws.security.sts.provider.model.secext.UsernameTokenType)4 SecurityToken (org.apache.cxf.ws.security.tokenstore.SecurityToken)4 CustomTokenPrincipal (org.apache.wss4j.common.principal.CustomTokenPrincipal)4 CallbackHandler (javax.security.auth.callback.CallbackHandler)3 Fault (org.apache.cxf.interceptor.Fault)3 STSPropertiesMBean (org.apache.cxf.sts.STSPropertiesMBean)3