Search in sources :

Example 1 with BaseAuthenticationToken

use of org.codice.ddf.security.handler.BaseAuthenticationToken in project ddf by codice.

the class LoginFilter method doFilter.

/**
 * Gets token, resolves token references, and calls the security manager to get a Subject
 *
 * @param request
 * @param response
 * @param chain
 * @throws IOException
 * @throws ServletException
 */
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final SecurityFilterChain chain) throws IOException, AuthenticationException {
    LOGGER.debug("Performing doFilter() on LoginFilter");
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    // Skip filter if no authentication policy
    if (request.getAttribute(ContextPolicy.NO_AUTH_POLICY) != null) {
        LOGGER.debug("NO_AUTH_POLICY header was found, skipping login filter.");
        chain.doFilter(request, response);
        return;
    }
    // grab token from httpRequest
    BaseAuthenticationToken token;
    Object ddfAuthToken = httpRequest.getAttribute(AUTHENTICATION_TOKEN_KEY);
    if (ddfAuthToken instanceof HandlerResult && ((HandlerResult) ddfAuthToken).getToken() instanceof BaseAuthenticationToken) {
        token = (BaseAuthenticationToken) ((HandlerResult) ddfAuthToken).getToken();
    } else {
        LOGGER.debug("Could not attach subject to http request.");
        return;
    }
    token.setX509Certs((X509Certificate[]) httpRequest.getAttribute("javax.servlet.request.X509Certificate"));
    token.setRequestURI(httpRequest.getRequestURI());
    if (securityManager == null) {
        throw new AuthenticationException("Unable to authenticate user, system is not available.");
    }
    // get subject from the token
    Subject subject;
    try {
        subject = securityManager.getSubject(token);
    } catch (SecurityServiceException e) {
        LOGGER.debug("Error getting subject from a Shiro realm", e);
        return;
    }
    // check that security manager was able to resolve a subject
    if (subject == null) {
        LOGGER.debug("Could not attach subject to http request.");
        return;
    }
    // subject is now resolved, perform request as that subject
    httpRequest.setAttribute(SecurityConstants.SECURITY_SUBJECT, subject);
    LOGGER.debug("Now performing request as user {} for {}", subject.getPrincipal(), StringUtils.isNotBlank(httpRequest.getContextPath()) ? httpRequest.getContextPath() : httpRequest.getServletPath());
    subject.execute(() -> {
        // attach subject to the http session
        if (contextPolicyManager.getSessionAccess()) {
            addToSession(httpRequest, subject);
        }
        PrivilegedExceptionAction<Void> action = () -> {
            chain.doFilter(request, response);
            return null;
        };
        Collection<SecurityAssertion> securityAssertions = subject.getPrincipals().byType(SecurityAssertion.class);
        if (!securityAssertions.isEmpty()) {
            HashSet<?> emptySet = new HashSet<>();
            javax.security.auth.Subject javaSubject = new javax.security.auth.Subject(true, securityAssertions.stream().map(SecurityAssertion::getPrincipals).flatMap(Collection::stream).collect(Collectors.toSet()), emptySet, emptySet);
            httpRequest.setAttribute(SecurityConstants.SECURITY_JAVA_SUBJECT, javaSubject);
            if (contextPolicyManager.getSessionAccess()) {
                addToSession(httpRequest, javaSubject);
            }
            javax.security.auth.Subject.doAs(javaSubject, action);
        } else {
            LOGGER.debug("Subject had no security assertion.");
        }
        return null;
    });
}
Also used : SecurityServiceException(ddf.security.service.SecurityServiceException) AuthenticationException(org.codice.ddf.platform.filter.AuthenticationException) HandlerResult(org.codice.ddf.security.handler.api.HandlerResult) SecurityAssertion(ddf.security.assertion.SecurityAssertion) X509Certificate(java.security.cert.X509Certificate) Subject(ddf.security.Subject) HttpServletRequest(javax.servlet.http.HttpServletRequest) BaseAuthenticationToken(org.codice.ddf.security.handler.BaseAuthenticationToken) PrincipalCollection(org.apache.shiro.subject.PrincipalCollection) Collection(java.util.Collection) HashSet(java.util.HashSet)

Example 2 with BaseAuthenticationToken

use of org.codice.ddf.security.handler.BaseAuthenticationToken in project ddf by codice.

the class WebSSOFilter method handleResultStatus.

private void handleResultStatus(HttpServletRequest httpRequest, HttpServletResponse httpResponse, HandlerResult result, String path, String ipAddress) throws AuthenticationChallengeException, AuthenticationFailureException {
    if (result != null) {
        switch(result.getStatus()) {
            case REDIRECTED:
                // handler handled the response - it is redirecting or whatever
                // necessary to get their tokens
                LOGGER.debug("Stopping filter chain - handled by plugins");
                throw new AuthenticationChallengeException("Stopping filter chain - handled by plugins");
            case NO_ACTION:
                if (!contextPolicyManager.getGuestAccess()) {
                    LOGGER.warn("No handlers were able to determine required credentials, returning bad request to {}. Check policy configuration for path: {}", ipAddress, path);
                    returnSimpleResponse(HttpServletResponse.SC_BAD_REQUEST, httpResponse);
                    throw new AuthenticationFailureException("No handlers were able to determine required credentials");
                }
                result = new HandlerResultImpl(Status.COMPLETED, new GuestAuthenticationToken(ipAddress, securityLogger));
                result.setSource("default");
            // fall through
            case COMPLETED:
                if (result.getToken() == null) {
                    LOGGER.warn("Completed without credentials for {} - check context policy configuration for path: {}", ipAddress, path);
                    returnSimpleResponse(HttpServletResponse.SC_BAD_REQUEST, httpResponse);
                    throw new AuthenticationFailureException("Completed without credentials");
                }
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Attaching result handler to the http request - token is instance of {} from classloader {}", result.getToken().getClass().getName(), result.getToken().getClass().getClassLoader());
                }
                if (result.getToken() instanceof BaseAuthenticationToken) {
                    ((BaseAuthenticationToken) result.getToken()).setAllowGuest(contextPolicyManager.getGuestAccess());
                }
                httpRequest.setAttribute(AUTHENTICATION_TOKEN_KEY, result);
                break;
            default:
                LOGGER.warn("Unexpected response from handler - ignoring. Remote IP: {}, Path: {}", ipAddress, path);
                throw new AuthenticationFailureException("Unexpected response from handler");
        }
    } else {
        LOGGER.warn("Expected login credentials from {} - didn't find any. Returning a bad request for path: {}", ipAddress, path);
        returnSimpleResponse(HttpServletResponse.SC_BAD_REQUEST, httpResponse);
        throw new AuthenticationFailureException("Didn't find any login credentials");
    }
}
Also used : AuthenticationChallengeException(org.codice.ddf.platform.filter.AuthenticationChallengeException) GuestAuthenticationToken(org.codice.ddf.security.handler.GuestAuthenticationToken) HandlerResultImpl(org.codice.ddf.security.handler.HandlerResultImpl) BaseAuthenticationToken(org.codice.ddf.security.handler.BaseAuthenticationToken) AuthenticationFailureException(org.codice.ddf.platform.filter.AuthenticationFailureException)

Example 3 with BaseAuthenticationToken

use of org.codice.ddf.security.handler.BaseAuthenticationToken in project ddf by codice.

the class PKIRealmTest method testSupportsBad.

@Test
public void testSupportsBad() {
    BaseAuthenticationToken authenticationToken = mock(BaseAuthenticationToken.class);
    boolean supports = pkiRealm.supports(authenticationToken);
    assertFalse(supports);
    when(authenticationToken.getCredentials()).thenReturn(new Object());
    when(authenticationToken.getPrincipal()).thenReturn(new Object());
    supports = pkiRealm.supports(authenticationToken);
    assertFalse(supports);
    when(authenticationToken.getType()).thenReturn(AuthenticationTokenType.SAML);
    supports = pkiRealm.supports(authenticationToken);
    assertFalse(supports);
    when(authenticationToken.getCredentials()).thenReturn(new X509Certificate[1]);
    when(authenticationToken.getType()).thenReturn(AuthenticationTokenType.PKI);
    supports = pkiRealm.supports(authenticationToken);
    assertFalse(supports);
    when(authenticationToken.getCredentials()).thenReturn(new Object());
    when(authenticationToken.getPrincipal()).thenReturn(new X500Principal("cn=test"));
    supports = pkiRealm.supports(authenticationToken);
    assertFalse(supports);
}
Also used : BaseAuthenticationToken(org.codice.ddf.security.handler.BaseAuthenticationToken) X500Principal(javax.security.auth.x500.X500Principal) Test(org.junit.Test)

Example 4 with BaseAuthenticationToken

use of org.codice.ddf.security.handler.BaseAuthenticationToken in project ddf by codice.

the class PKIRealmTest method testDoGetAuthenticationInfo.

@Test
public void testDoGetAuthenticationInfo() {
    BaseAuthenticationToken authenticationToken = mock(BaseAuthenticationToken.class);
    X509Certificate[] certificates = new X509Certificate[1];
    certificates[0] = mock(X509Certificate.class);
    X500Principal x500Principal = new X500Principal("cn=myxman,ou=someunit,o=someorg");
    when(authenticationToken.getCredentials()).thenReturn(certificates);
    when(authenticationToken.getPrincipal()).thenReturn(x500Principal);
    when(authenticationToken.getType()).thenReturn(AuthenticationTokenType.PKI);
    AuthenticationInfo authenticationInfo = pkiRealm.doGetAuthenticationInfo(authenticationToken);
    assertThat(authenticationInfo.getCredentials(), is(certificates));
    SecurityAssertion assertion = authenticationInfo.getPrincipals().oneByType(SecurityAssertion.class);
    assertNotNull(assertion);
    assertThat(assertion.getPrincipal(), is(x500Principal));
    AttributeStatement attributeStatement = assertion.getAttributeStatements().get(0);
    assertNotNull(attributeStatement);
    assertThat(attributeStatement.getAttributes().size(), greaterThan(0));
    Attribute attribute = attributeStatement.getAttributes().get(0);
    assertThat(attribute.getName(), is("email"));
    assertThat(attribute.getValues().size(), is(2));
    assertThat(attribute.getValues(), contains("tester@example.com", "test@example.com"));
}
Also used : Attribute(ddf.security.assertion.Attribute) AttributeStatement(ddf.security.assertion.AttributeStatement) BaseAuthenticationToken(org.codice.ddf.security.handler.BaseAuthenticationToken) X500Principal(javax.security.auth.x500.X500Principal) SecurityAssertion(ddf.security.assertion.SecurityAssertion) X509Certificate(java.security.cert.X509Certificate) AuthenticationInfo(org.apache.shiro.authc.AuthenticationInfo) Test(org.junit.Test)

Example 5 with BaseAuthenticationToken

use of org.codice.ddf.security.handler.BaseAuthenticationToken in project ddf by codice.

the class SamlRealmTest method testDoGetAuthenticationInfoBase.

@Ignore
@Test
public void testDoGetAuthenticationInfoBase() {
    SamlRealm realm = new SamlRealm();
    BaseAuthenticationToken authenticationToken = mock(BaseAuthenticationToken.class);
    when(authenticationToken.getCredentialsAsString()).thenReturn("creds");
    AuthenticationInfo authenticationInfo = realm.doGetAuthenticationInfo(authenticationToken);
    assertNotNull(authenticationInfo.getCredentials());
    assertNotNull(authenticationInfo.getPrincipals());
}
Also used : BaseAuthenticationToken(org.codice.ddf.security.handler.BaseAuthenticationToken) AuthenticationInfo(org.apache.shiro.authc.AuthenticationInfo) Ignore(org.junit.Ignore) Test(org.junit.Test)

Aggregations

BaseAuthenticationToken (org.codice.ddf.security.handler.BaseAuthenticationToken)17 Test (org.junit.Test)9 X509Certificate (java.security.cert.X509Certificate)4 X500Principal (javax.security.auth.x500.X500Principal)4 SecurityAssertion (ddf.security.assertion.SecurityAssertion)3 SecurityServiceException (ddf.security.service.SecurityServiceException)3 AuthenticationInfo (org.apache.shiro.authc.AuthenticationInfo)3 AuthenticationToken (org.apache.shiro.authc.AuthenticationToken)3 GuestAuthenticationToken (org.codice.ddf.security.handler.GuestAuthenticationToken)3 Attribute (ddf.security.assertion.Attribute)2 SecurityManager (ddf.security.service.SecurityManager)2 PrincipalCollection (org.apache.shiro.subject.PrincipalCollection)2 SimplePrincipalCollection (org.apache.shiro.subject.SimplePrincipalCollection)2 AuthenticationException (org.codice.ddf.platform.filter.AuthenticationException)2 AuthenticationTokenFactory (org.codice.ddf.security.handler.AuthenticationTokenFactory)2 HandlerResultImpl (org.codice.ddf.security.handler.HandlerResultImpl)2 HandlerResult (org.codice.ddf.security.handler.api.HandlerResult)2 Subject (ddf.security.Subject)1 AttributeStatement (ddf.security.assertion.AttributeStatement)1 SecurityAssertionSaml (ddf.security.assertion.saml.impl.SecurityAssertionSaml)1