Search in sources :

Example 1 with UPAuthenticationToken

use of org.codice.ddf.security.handler.api.UPAuthenticationToken in project ddf by codice.

the class BasicAuthenticationHandlerTest method testIllegalStateException.

@Test(expected = IllegalStateException.class)
public void testIllegalStateException() {
    BasicAuthenticationHandler handler = new BasicAuthenticationHandler();
    UPAuthenticationToken result = (UPAuthenticationToken) handler.extractAuthInfo("Basic " + Base64.getEncoder().encodeToString(CREDENTIALS.getBytes()), "TestRealm");
    assertNotNull(result);
    assertEquals("admin", result.getUsername());
    assertEquals("password", result.getPassword());
    assertEquals("TestRealm", result.getRealm());
    WssBasicAuthenticationHandler wssHandler = new WssBasicAuthenticationHandler(null);
    BaseAuthenticationToken wssResult = wssHandler.extractAuthInfo("Basic " + Base64.getEncoder().encodeToString(CREDENTIALS.getBytes()), "TestRealm");
}
Also used : BaseAuthenticationToken(org.codice.ddf.security.handler.api.BaseAuthenticationToken) UPAuthenticationToken(org.codice.ddf.security.handler.api.UPAuthenticationToken) Test(org.junit.Test)

Example 2 with UPAuthenticationToken

use of org.codice.ddf.security.handler.api.UPAuthenticationToken in project ddf by codice.

the class IdpEndpoint method handleLogin.

protected org.opensaml.saml.saml2.core.Response handleLogin(AuthnRequest authnRequest, String authMethod, HttpServletRequest request, AuthObj authObj, boolean passive, boolean hasCookie) throws SecurityServiceException, WSSecurityException, SimpleSign.SignatureException, ConstraintViolationException {
    LOGGER.debug("Performing login for user. passive: {}, cookie: {}", passive, hasCookie);
    BaseAuthenticationToken token = null;
    request.setAttribute(ContextPolicy.ACTIVE_REALM, BaseAuthenticationToken.ALL_REALM);
    if (PKI.equals(authMethod)) {
        LOGGER.debug("Logging user in via PKI.");
        PKIHandler pkiHandler = new PKIHandler();
        pkiHandler.setTokenFactory(tokenFactory);
        try {
            HandlerResult handlerResult = pkiHandler.getNormalizedToken(request, null, null, false);
            if (handlerResult.getStatus().equals(HandlerResult.Status.COMPLETED)) {
                token = handlerResult.getToken();
            }
        } catch (ServletException e) {
            LOGGER.info("Encountered an exception while checking for PKI auth info.", e);
        }
    } else if (USER_PASS.equals(authMethod)) {
        LOGGER.debug("Logging user in via BASIC auth.");
        if (authObj != null && authObj.username != null && authObj.password != null) {
            token = new UPAuthenticationToken(authObj.username, authObj.password, BaseAuthenticationToken.ALL_REALM);
        } else {
            BasicAuthenticationHandler basicAuthenticationHandler = new BasicAuthenticationHandler();
            HandlerResult handlerResult = basicAuthenticationHandler.getNormalizedToken(request, null, null, false);
            if (handlerResult.getStatus().equals(HandlerResult.Status.COMPLETED)) {
                token = handlerResult.getToken();
            }
        }
    } else if (SAML.equals(authMethod)) {
        LOGGER.debug("Logging user in via SAML assertion.");
        token = new SAMLAuthenticationToken(null, authObj.assertion, BaseAuthenticationToken.ALL_REALM);
    } else if (GUEST.equals(authMethod) && guestAccess) {
        LOGGER.debug("Logging user in as Guest.");
        token = new GuestAuthenticationToken(BaseAuthenticationToken.ALL_REALM, request.getRemoteAddr());
    } else {
        throw new IllegalArgumentException("Auth method is not supported.");
    }
    org.w3c.dom.Element samlToken = null;
    String statusCode;
    if (hasCookie) {
        samlToken = getSamlAssertion(request);
        statusCode = StatusCode.SUCCESS;
    } else {
        try {
            statusCode = StatusCode.AUTHN_FAILED;
            Subject subject = securityManager.getSubject(token);
            for (Object principal : subject.getPrincipals().asList()) {
                if (principal instanceof SecurityAssertion) {
                    SecurityToken securityToken = ((SecurityAssertion) principal).getSecurityToken();
                    samlToken = securityToken.getToken();
                }
            }
            if (samlToken != null) {
                statusCode = StatusCode.SUCCESS;
            }
        } catch (SecurityServiceException e) {
            if (!passive) {
                throw e;
            } else {
                statusCode = StatusCode.AUTHN_FAILED;
            }
        }
    }
    LOGGER.debug("User log in successful.");
    return SamlProtocol.createResponse(SamlProtocol.createIssuer(SystemBaseUrl.constructUrl("/idp/login", true)), SamlProtocol.createStatus(statusCode), authnRequest.getID(), samlToken);
}
Also used : SecurityServiceException(ddf.security.service.SecurityServiceException) GuestAuthenticationToken(org.codice.ddf.security.handler.api.GuestAuthenticationToken) PKIHandler(org.codice.ddf.security.handler.pki.PKIHandler) HandlerResult(org.codice.ddf.security.handler.api.HandlerResult) SecurityAssertion(ddf.security.assertion.SecurityAssertion) SAMLAuthenticationToken(org.codice.ddf.security.handler.api.SAMLAuthenticationToken) Subject(ddf.security.Subject) ServletException(javax.servlet.ServletException) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) Element(org.w3c.dom.Element) BaseAuthenticationToken(org.codice.ddf.security.handler.api.BaseAuthenticationToken) UPAuthenticationToken(org.codice.ddf.security.handler.api.UPAuthenticationToken) BasicAuthenticationHandler(org.codice.ddf.security.handler.basic.BasicAuthenticationHandler) SignableSAMLObject(org.opensaml.saml.common.SignableSAMLObject) SignableXMLObject(org.opensaml.xmlsec.signature.SignableXMLObject) XMLObject(org.opensaml.core.xml.XMLObject)

Example 3 with UPAuthenticationToken

use of org.codice.ddf.security.handler.api.UPAuthenticationToken in project ddf by codice.

the class UPBSTValidator method canHandleToken.

/**
     * Return true if this TokenValidator implementation is capable of validating the
     * ReceivedToken argument. The realm is ignored in this token Validator.
     *
     * @param validateTarget
     * @param cxfRealm
     * @return true if the token can be handled
     */
public boolean canHandleToken(ReceivedToken validateTarget, String cxfRealm) {
    boolean canHandle = false;
    UPAuthenticationToken usernameToken = getUsernameTokenFromTarget(validateTarget);
    if (usernameToken != null) {
        // This generic instance just looks for the default realms (DDF and Karaf)
        if (usernameToken.getRealm() == null) {
            LOGGER.trace("No realm specified in request");
            canHandle = (validators != null);
        } else if (validators != null && validators.containsKey(usernameToken.getRealm())) {
            LOGGER.trace("Realm '{}' recognized - canHandleToken = true", usernameToken.getRealm());
            canHandle = true;
        } else if (validators != null && "*".equals(usernameToken.getRealm())) {
            LOGGER.trace("Realm '*' recognized - canHandleToken = true");
            canHandle = true;
        }
        if (!canHandle) {
            LOGGER.trace("Realm '{}' unrecognized - canHandleToken = false", usernameToken.getRealm());
        }
    }
    LOGGER.debug("Returning canHandle: {}", canHandle);
    return canHandle;
}
Also used : UPAuthenticationToken(org.codice.ddf.security.handler.api.UPAuthenticationToken)

Example 4 with UPAuthenticationToken

use of org.codice.ddf.security.handler.api.UPAuthenticationToken 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 5 with UPAuthenticationToken

use of org.codice.ddf.security.handler.api.UPAuthenticationToken in project ddf by codice.

the class Security method getSubject.

/**
     * Gets the {@link Subject} given a user name and password.
     *
     * @param username username
     * @param password password
     * @return {@link Subject} associated with the user name and password provided
     */
public Subject getSubject(String username, String password) {
    UPAuthenticationToken token = new UPAuthenticationToken(username, password);
    SecurityManager securityManager = getSecurityManager();
    if (securityManager != null) {
        try {
            return securityManager.getSubject(token);
        } catch (SecurityServiceException | RuntimeException e) {
            LOGGER.info("Unable to request subject for {} user.", username, e);
        }
    }
    return null;
}
Also used : SecurityServiceException(ddf.security.service.SecurityServiceException) SecurityManager(ddf.security.service.SecurityManager) UPAuthenticationToken(org.codice.ddf.security.handler.api.UPAuthenticationToken)

Aggregations

UPAuthenticationToken (org.codice.ddf.security.handler.api.UPAuthenticationToken)11 Subject (ddf.security.Subject)5 SecurityToken (org.apache.cxf.ws.security.tokenstore.SecurityToken)5 SecurityAssertion (ddf.security.assertion.SecurityAssertion)4 SecurityServiceException (ddf.security.service.SecurityServiceException)4 BinarySecurityTokenType (org.apache.cxf.ws.security.sts.provider.model.secext.BinarySecurityTokenType)3 BaseAuthenticationToken (org.codice.ddf.security.handler.api.BaseAuthenticationToken)3 SecurityTokenHolder (ddf.security.common.SecurityTokenHolder)2 SecurityManager (ddf.security.service.SecurityManager)2 HttpSession (javax.servlet.http.HttpSession)2 STSPropertiesMBean (org.apache.cxf.sts.STSPropertiesMBean)2 AttributedString (org.apache.cxf.ws.security.sts.provider.model.secext.AttributedString)2 PasswordString (org.apache.cxf.ws.security.sts.provider.model.secext.PasswordString)2 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)2 HandlerResult (org.codice.ddf.security.handler.api.HandlerResult)2 Element (org.w3c.dom.Element)2 FtpUser (ddf.catalog.ftp.user.FtpUser)1 URI (java.net.URI)1 Principal (java.security.Principal)1 ArrayList (java.util.ArrayList)1