Search in sources :

Example 6 with STSPropertiesMBean

use of org.apache.cxf.sts.STSPropertiesMBean 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 7 with STSPropertiesMBean

use of org.apache.cxf.sts.STSPropertiesMBean in project ddf by codice.

the class TestUsernameTokenValidator method testValidateBadTokenNoTokenStore.

@Test
public void testValidateBadTokenNoTokenStore() {
    UsernameTokenValidator usernameTokenValidator = getUsernameTokenValidator(new XmlParser(), meanValidator);
    usernameTokenValidator.addRealm(null);
    TokenValidatorParameters tokenValidatorParameters = mock(TokenValidatorParameters.class);
    STSPropertiesMBean stsPropertiesMBean = mock(STSPropertiesMBean.class);
    when(stsPropertiesMBean.getSignatureCrypto()).thenReturn(mock(Crypto.class));
    when(tokenValidatorParameters.getStsProperties()).thenReturn(stsPropertiesMBean);
    ReceivedToken receivedToken = mock(ReceivedToken.class);
    doCallRealMethod().when(receivedToken).setState(any(ReceivedToken.STATE.class));
    doCallRealMethod().when(receivedToken).getState();
    when(receivedToken.isUsernameToken()).thenReturn(true);
    when(tokenValidatorParameters.getToken()).thenReturn(receivedToken);
    Set<Class<?>> classes = new HashSet<>();
    classes.add(ObjectFactory.class);
    classes.add(org.apache.cxf.ws.security.sts.provider.model.wstrust14.ObjectFactory.class);
    JAXBContextCache.CachedContextAndSchemas cache = null;
    try {
        cache = JAXBContextCache.getCachedContextAndSchemas(classes, null, null, null, false);
    } catch (JAXBException e) {
        fail(e.getMessage());
    }
    JAXBContext jaxbContext = cache.getContext();
    Unmarshaller unmarshaller = null;
    try {
        if (jaxbContext != null) {
            unmarshaller = jaxbContext.createUnmarshaller();
        }
    } catch (JAXBException e) {
        fail(e.getMessage());
    }
    JAXBElement<?> token = null;
    if (unmarshaller != null) {
        try {
            token = (JAXBElement<?>) unmarshaller.unmarshal(this.getClass().getResourceAsStream("/user-no-password.xml"));
        } catch (JAXBException e) {
            fail(e.getMessage());
        }
    }
    when(receivedToken.getToken()).thenReturn(token.getValue());
    TokenValidatorResponse tokenValidatorResponse = usernameTokenValidator.validateToken(tokenValidatorParameters);
    assertEquals(ReceivedToken.STATE.INVALID, tokenValidatorResponse.getToken().getState());
    verify(failedLoginDelayer, times(1)).delay(anyString());
}
Also used : XmlParser(org.codice.ddf.parser.xml.XmlParser) JAXBContextCache(org.apache.cxf.common.jaxb.JAXBContextCache) JAXBException(javax.xml.bind.JAXBException) JAXBContext(javax.xml.bind.JAXBContext) TokenValidatorParameters(org.apache.cxf.sts.token.validator.TokenValidatorParameters) Crypto(org.apache.wss4j.common.crypto.Crypto) JAASUsernameTokenValidator(org.apache.wss4j.dom.validate.JAASUsernameTokenValidator) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) TokenValidatorResponse(org.apache.cxf.sts.token.validator.TokenValidatorResponse) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken) Unmarshaller(javax.xml.bind.Unmarshaller) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 8 with STSPropertiesMBean

use of org.apache.cxf.sts.STSPropertiesMBean in project ddf by codice.

the class TestUsernameTokenValidator method testValidateBadToken.

@Test
public void testValidateBadToken() {
    UsernameTokenValidator usernameTokenValidator = getUsernameTokenValidator(new XmlParser(), meanValidator);
    usernameTokenValidator.addRealm(null);
    TokenValidatorParameters tokenValidatorParameters = mock(TokenValidatorParameters.class);
    STSPropertiesMBean stsPropertiesMBean = mock(STSPropertiesMBean.class);
    when(stsPropertiesMBean.getSignatureCrypto()).thenReturn(mock(Crypto.class));
    when(tokenValidatorParameters.getStsProperties()).thenReturn(stsPropertiesMBean);
    ReceivedToken receivedToken = mock(ReceivedToken.class);
    doCallRealMethod().when(receivedToken).setState(any(ReceivedToken.STATE.class));
    doCallRealMethod().when(receivedToken).getState();
    when(receivedToken.isUsernameToken()).thenReturn(true);
    when(tokenValidatorParameters.getToken()).thenReturn(receivedToken);
    Set<Class<?>> classes = new HashSet<>();
    classes.add(ObjectFactory.class);
    classes.add(org.apache.cxf.ws.security.sts.provider.model.wstrust14.ObjectFactory.class);
    JAXBContextCache.CachedContextAndSchemas cache = null;
    try {
        cache = JAXBContextCache.getCachedContextAndSchemas(classes, null, null, null, false);
    } catch (JAXBException e) {
        fail(e.getMessage());
    }
    JAXBContext jaxbContext = cache.getContext();
    Unmarshaller unmarshaller = null;
    try {
        if (jaxbContext != null) {
            unmarshaller = jaxbContext.createUnmarshaller();
        }
    } catch (JAXBException e) {
        fail(e.getMessage());
    }
    JAXBElement<?> token = null;
    if (unmarshaller != null) {
        try {
            token = (JAXBElement<?>) unmarshaller.unmarshal(this.getClass().getResourceAsStream("/user.xml"));
        } catch (JAXBException e) {
            fail(e.getMessage());
        }
    }
    when(receivedToken.getToken()).thenReturn(token.getValue());
    TokenValidatorResponse tokenValidatorResponse = usernameTokenValidator.validateToken(tokenValidatorParameters);
    assertEquals(ReceivedToken.STATE.INVALID, tokenValidatorResponse.getToken().getState());
    verify(failedLoginDelayer, times(1)).delay(anyString());
}
Also used : XmlParser(org.codice.ddf.parser.xml.XmlParser) JAXBContextCache(org.apache.cxf.common.jaxb.JAXBContextCache) JAXBException(javax.xml.bind.JAXBException) JAXBContext(javax.xml.bind.JAXBContext) TokenValidatorParameters(org.apache.cxf.sts.token.validator.TokenValidatorParameters) Crypto(org.apache.wss4j.common.crypto.Crypto) JAASUsernameTokenValidator(org.apache.wss4j.dom.validate.JAASUsernameTokenValidator) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) TokenValidatorResponse(org.apache.cxf.sts.token.validator.TokenValidatorResponse) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken) Unmarshaller(javax.xml.bind.Unmarshaller) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 9 with STSPropertiesMBean

use of org.apache.cxf.sts.STSPropertiesMBean in project ddf by codice.

the class TestUsernameTokenValidator method testNoFailedDelayer.

@Test(expected = IllegalStateException.class)
public void testNoFailedDelayer() {
    UsernameTokenValidator usernameTokenValidator = new UsernameTokenValidator(new XmlParser(), null) {

        public void addRealm(ServiceReference<JaasRealm> serviceReference) {
            validators.put("myrealm", meanValidator);
        }
    };
    usernameTokenValidator.addRealm(null);
    TokenValidatorParameters tokenValidatorParameters = mock(TokenValidatorParameters.class);
    STSPropertiesMBean stsPropertiesMBean = mock(STSPropertiesMBean.class);
    when(stsPropertiesMBean.getSignatureCrypto()).thenReturn(mock(Crypto.class));
    when(tokenValidatorParameters.getStsProperties()).thenReturn(stsPropertiesMBean);
    ReceivedToken receivedToken = mock(ReceivedToken.class);
    doCallRealMethod().when(receivedToken).setState(any(ReceivedToken.STATE.class));
    doCallRealMethod().when(receivedToken).getState();
    when(receivedToken.isUsernameToken()).thenReturn(true);
    when(tokenValidatorParameters.getToken()).thenReturn(receivedToken);
    Set<Class<?>> classes = new HashSet<>();
    classes.add(ObjectFactory.class);
    classes.add(org.apache.cxf.ws.security.sts.provider.model.wstrust14.ObjectFactory.class);
    JAXBContextCache.CachedContextAndSchemas cache = null;
    try {
        cache = JAXBContextCache.getCachedContextAndSchemas(classes, null, null, null, false);
    } catch (JAXBException e) {
        fail(e.getMessage());
    }
    JAXBContext jaxbContext = cache.getContext();
    Unmarshaller unmarshaller = null;
    try {
        if (jaxbContext != null) {
            unmarshaller = jaxbContext.createUnmarshaller();
        }
    } catch (JAXBException e) {
        fail(e.getMessage());
    }
    JAXBElement<?> token = null;
    if (unmarshaller != null) {
        try {
            token = (JAXBElement<?>) unmarshaller.unmarshal(this.getClass().getResourceAsStream("/user-no-password.xml"));
        } catch (JAXBException e) {
            fail(e.getMessage());
        }
    }
    when(receivedToken.getToken()).thenReturn(token.getValue());
    usernameTokenValidator.validateToken(tokenValidatorParameters);
}
Also used : XmlParser(org.codice.ddf.parser.xml.XmlParser) JAXBContextCache(org.apache.cxf.common.jaxb.JAXBContextCache) JAXBException(javax.xml.bind.JAXBException) JAXBContext(javax.xml.bind.JAXBContext) ServiceReference(org.osgi.framework.ServiceReference) TokenValidatorParameters(org.apache.cxf.sts.token.validator.TokenValidatorParameters) Crypto(org.apache.wss4j.common.crypto.Crypto) JAASUsernameTokenValidator(org.apache.wss4j.dom.validate.JAASUsernameTokenValidator) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken) Unmarshaller(javax.xml.bind.Unmarshaller) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 10 with STSPropertiesMBean

use of org.apache.cxf.sts.STSPropertiesMBean in project cxf by apache.

the class DefaultSubjectProvider method createKeyInfo.

/**
 * Create and return the KeyInfoBean to be inserted into the SubjectBean
 */
protected KeyInfoBean createKeyInfo(SubjectProviderParameters subjectProviderParameters) {
    TokenProviderParameters providerParameters = subjectProviderParameters.getProviderParameters();
    KeyRequirements keyRequirements = providerParameters.getKeyRequirements();
    STSPropertiesMBean stsProperties = providerParameters.getStsProperties();
    String keyType = keyRequirements.getKeyType();
    if (STSConstants.SYMMETRIC_KEY_KEYTYPE.equals(keyType)) {
        Crypto crypto = stsProperties.getEncryptionCrypto();
        EncryptionProperties encryptionProperties = providerParameters.getEncryptionProperties();
        String encryptionName = encryptionProperties.getEncryptionName();
        if (encryptionName == null) {
            // Fall back on the STS encryption name
            encryptionName = stsProperties.getEncryptionUsername();
        }
        if (encryptionName == null) {
            LOG.fine("No encryption Name is configured for Symmetric KeyType");
            throw new STSException("No Encryption Name is configured", STSException.REQUEST_FAILED);
        }
        CryptoType cryptoType = null;
        // Check for using of service endpoint (AppliesTo) as certificate identifier
        if (STSConstants.USE_ENDPOINT_AS_CERT_ALIAS.equals(encryptionName)) {
            if (providerParameters.getAppliesToAddress() == null) {
                throw new STSException("AppliesTo is not initilaized for encryption name " + STSConstants.USE_ENDPOINT_AS_CERT_ALIAS);
            }
            cryptoType = new CryptoType(CryptoType.TYPE.ENDPOINT);
            cryptoType.setEndpoint(providerParameters.getAppliesToAddress());
        } else {
            cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
            cryptoType.setAlias(encryptionName);
        }
        try {
            X509Certificate[] certs = crypto.getX509Certificates(cryptoType);
            if ((certs == null) || (certs.length == 0)) {
                throw new STSException("Encryption certificate is not found for alias: " + encryptionName);
            }
            Document doc = subjectProviderParameters.getDoc();
            byte[] secret = subjectProviderParameters.getSecret();
            return createEncryptedKeyKeyInfo(certs[0], secret, doc, encryptionProperties, crypto);
        } catch (WSSecurityException ex) {
            LOG.log(Level.WARNING, "", ex);
            throw new STSException(ex.getMessage(), ex);
        }
    } else if (STSConstants.PUBLIC_KEY_KEYTYPE.equals(keyType)) {
        ReceivedKey receivedKey = keyRequirements.getReceivedKey();
        // Validate UseKey trust
        if (stsProperties.isValidateUseKey() && stsProperties.getSignatureCrypto() != null) {
            if (receivedKey.getX509Cert() != null) {
                try {
                    Collection<Pattern> constraints = Collections.emptyList();
                    stsProperties.getSignatureCrypto().verifyTrust(new X509Certificate[] { receivedKey.getX509Cert() }, false, constraints, null);
                } catch (WSSecurityException e) {
                    LOG.log(Level.FINE, "Error in trust validation of UseKey: ", e);
                    throw new STSException("Error in trust validation of UseKey", STSException.REQUEST_FAILED);
                }
            }
            if (receivedKey.getPublicKey() != null) {
                try {
                    stsProperties.getSignatureCrypto().verifyTrust(receivedKey.getPublicKey());
                } catch (WSSecurityException e) {
                    LOG.log(Level.FINE, "Error in trust validation of UseKey: ", e);
                    throw new STSException("Error in trust validation of UseKey", STSException.REQUEST_FAILED);
                }
            }
        }
        return createPublicKeyKeyInfo(receivedKey.getX509Cert(), receivedKey.getPublicKey());
    }
    return null;
}
Also used : STSException(org.apache.cxf.ws.security.sts.provider.STSException) EncryptionProperties(org.apache.cxf.sts.service.EncryptionProperties) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) CryptoType(org.apache.wss4j.common.crypto.CryptoType) Document(org.w3c.dom.Document) X509Certificate(java.security.cert.X509Certificate) ReceivedKey(org.apache.cxf.sts.request.ReceivedKey) Crypto(org.apache.wss4j.common.crypto.Crypto) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) Collection(java.util.Collection) KeyRequirements(org.apache.cxf.sts.request.KeyRequirements)

Aggregations

STSPropertiesMBean (org.apache.cxf.sts.STSPropertiesMBean)122 Crypto (org.apache.wss4j.common.crypto.Crypto)93 ArrayList (java.util.ArrayList)86 JAXBElement (javax.xml.bind.JAXBElement)86 WrappedMessageContext (org.apache.cxf.jaxws.context.WrappedMessageContext)83 MessageImpl (org.apache.cxf.message.MessageImpl)83 StaticSTSProperties (org.apache.cxf.sts.StaticSTSProperties)83 RequestSecurityTokenType (org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenType)83 RequestSecurityTokenResponseType (org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenResponseType)79 PasswordCallbackHandler (org.apache.cxf.sts.common.PasswordCallbackHandler)75 Element (org.w3c.dom.Element)70 TokenProvider (org.apache.cxf.sts.token.provider.TokenProvider)65 Principal (java.security.Principal)56 ServiceMBean (org.apache.cxf.sts.service.ServiceMBean)54 StaticService (org.apache.cxf.sts.service.StaticService)54 CustomTokenPrincipal (org.apache.wss4j.common.principal.CustomTokenPrincipal)54 SecurityContext (org.apache.cxf.security.SecurityContext)49 SAMLTokenProvider (org.apache.cxf.sts.token.provider.SAMLTokenProvider)49 RequestSecurityTokenResponseCollectionType (org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenResponseCollectionType)49 RequestedSecurityTokenType (org.apache.cxf.ws.security.sts.provider.model.RequestedSecurityTokenType)49