Search in sources :

Example 1 with AuthenticationHandler

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

the class WebSSOFilter method handleRequest.

private void handleRequest(HttpServletRequest httpRequest, HttpServletResponse httpResponse, SecurityFilterChain filterChain, List<AuthenticationHandler> handlers) throws AuthenticationException, IOException {
    HandlerResult result = null;
    // First pass, see if anyone can come up with proper security token from the get-go
    LOGGER.debug("Checking for existing tokens in request.");
    final String path = httpRequest.getRequestURI();
    String ipAddress = httpRequest.getHeader("X-FORWARDED-FOR");
    if (ipAddress == null) {
        ipAddress = httpRequest.getRemoteAddr();
    }
    if (contextPolicyManager.getSessionAccess()) {
        result = checkForPreviousResultOnSession(httpRequest, ipAddress);
    }
    // no result found on session, try and get result from handlers
    if (result == null) {
        if (!handlers.isEmpty()) {
            result = getResultFromHandlers(httpRequest, httpResponse, filterChain, handlers);
        } else {
            // no configured handlers
            if (contextPolicyManager.getGuestAccess()) {
                LOGGER.trace("No configured handlers found, but guest access is enabled. Continuing with an empty handler result for guest login.");
                result = new HandlerResultImpl(Status.NO_ACTION, null);
                result.setSource("default");
            } else {
                LOGGER.warn("No configured handler found and guest access is disabled. Returning status code 503, Service Unavailable. Check system configuration and bundle state.");
                returnSimpleResponse(HttpServletResponse.SC_SERVICE_UNAVAILABLE, httpResponse);
                return;
            }
        }
    }
    handleResultStatus(httpRequest, httpResponse, result, path, ipAddress);
    // If we got here, we've received our tokens to continue
    LOGGER.debug("Invoking the rest of the filter chain");
    try {
        filterChain.doFilter(httpRequest, httpResponse);
    } catch (Exception e) {
        LOGGER.debug("Exception in filter chain - passing off to handlers. Msg: {}", e.getMessage(), e);
        // First pass, see if anyone can come up with proper security token
        // from the git-go
        result = null;
        for (AuthenticationHandler auth : handlers) {
            result = auth.handleError(httpRequest, httpResponse, filterChain);
            if (result.getStatus() != HandlerResult.Status.NO_ACTION) {
                LOGGER.debug("Handler {} set the status to {}", auth.getAuthenticationType(), result.getStatus());
                break;
            }
        }
        if (result == null || result.getStatus() == HandlerResult.Status.NO_ACTION) {
            LOGGER.debug("Error during authentication - no error recovery attempted - returning bad request.");
            httpResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            httpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
            httpResponse.flushBuffer();
        }
        throw new AuthenticationFailureException(e);
    }
}
Also used : HandlerResultImpl(org.codice.ddf.security.handler.HandlerResultImpl) HandlerResult(org.codice.ddf.security.handler.api.HandlerResult) AuthenticationHandler(org.codice.ddf.security.handler.api.AuthenticationHandler) AuthenticationFailureException(org.codice.ddf.platform.filter.AuthenticationFailureException) AuthenticationChallengeException(org.codice.ddf.platform.filter.AuthenticationChallengeException) AuthenticationFailureException(org.codice.ddf.platform.filter.AuthenticationFailureException) SessionException(org.apache.shiro.session.SessionException) IOException(java.io.IOException) AuthenticationException(org.codice.ddf.platform.filter.AuthenticationException)

Example 2 with AuthenticationHandler

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

the class WebSSOFilterTest method testDoFilterWhiteListed.

@Test
public void testDoFilterWhiteListed() throws IOException, AuthenticationException {
    ContextPolicy testPolicy = mock(ContextPolicy.class);
    ContextPolicyManager policyManager = mock(ContextPolicyManager.class);
    when(policyManager.getContextPolicy(anyString())).thenReturn(testPolicy);
    when(policyManager.isWhiteListed(anyString())).thenReturn(true);
    when(policyManager.getSessionAccess()).thenReturn(false);
    WebSSOFilter filter = new WebSSOFilter();
    // set handlers
    AuthenticationHandler handler1 = mock(AuthenticationHandler.class);
    HandlerResult noActionResult = mock(HandlerResult.class);
    when(noActionResult.getStatus()).thenReturn(Status.NO_ACTION);
    HandlerResult completedResult = mock(HandlerResult.class);
    when(completedResult.getStatus()).thenReturn(Status.COMPLETED);
    when(completedResult.getToken()).thenReturn(null);
    when(handler1.getNormalizedToken(any(ServletRequest.class), any(ServletResponse.class), any(SecurityFilterChain.class), eq(true))).thenReturn(completedResult);
    when(handler1.getNormalizedToken(any(ServletRequest.class), any(ServletResponse.class), any(SecurityFilterChain.class), eq(false))).thenReturn(noActionResult);
    filter.setHandlerList(Collections.singletonList(handler1));
    filter.setContextPolicyManager(policyManager);
    SecurityFilterChain filterChain = mock(SecurityFilterChain.class);
    HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getRequestURI()).thenReturn(MOCK_CONTEXT);
    HttpServletResponse response = mock(HttpServletResponse.class);
    filter.doFilter(request, response, filterChain);
    verify(request, times(1)).setAttribute(ContextPolicy.NO_AUTH_POLICY, true);
    verify(filterChain).doFilter(request, response);
    verify(handler1, never()).getNormalizedToken(any(HttpServletRequest.class), any(HttpServletResponse.class), any(SecurityFilterChain.class), anyBoolean());
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletResponse(javax.servlet.ServletResponse) SecurityFilterChain(org.codice.ddf.platform.filter.SecurityFilterChain) HttpServletResponse(javax.servlet.http.HttpServletResponse) AuthenticationHandler(org.codice.ddf.security.handler.api.AuthenticationHandler) HandlerResult(org.codice.ddf.security.handler.api.HandlerResult) ContextPolicy(org.codice.ddf.security.policy.context.ContextPolicy) ContextPolicyManager(org.codice.ddf.security.policy.context.ContextPolicyManager) Test(org.junit.Test)

Example 3 with AuthenticationHandler

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

the class WebSSOFilterTest method testDoFilterSessionStorageDisabled.

@Test
public void testDoFilterSessionStorageDisabled() throws Exception {
    PrincipalCollection principalCollectionMock = mock(PrincipalCollection.class);
    PrincipalHolder principalHolderMock = mock(PrincipalHolder.class);
    when(principalHolderMock.getPrincipals()).thenReturn(principalCollectionMock);
    HttpSession sessionMock = mock(HttpSession.class);
    when(sessionMock.getAttribute(SECURITY_TOKEN_KEY)).thenReturn(principalHolderMock);
    HttpServletRequest requestMock = mock(HttpServletRequest.class);
    when(requestMock.getSession(any(Boolean.class))).thenReturn(sessionMock);
    when(requestMock.getRequestURI()).thenReturn(MOCK_CONTEXT);
    HttpServletResponse responseMock = mock(HttpServletResponse.class);
    ContextPolicyManager policyManager = mock(ContextPolicyManager.class);
    when(policyManager.getSessionAccess()).thenReturn(false);
    when(policyManager.isWhiteListed(MOCK_CONTEXT)).thenReturn(false);
    ContextPolicy testPolicy = mock(ContextPolicy.class);
    when(testPolicy.getAuthenticationMethods()).thenReturn(Collections.singletonList("basic"));
    when(policyManager.getContextPolicy(MOCK_CONTEXT)).thenReturn(testPolicy);
    AuthenticationHandler handlerMock = mock(AuthenticationHandler.class);
    when(handlerMock.getAuthenticationType()).thenReturn("basic");
    HandlerResult completedResult = mock(HandlerResult.class);
    when(completedResult.getStatus()).thenReturn(Status.COMPLETED);
    when(completedResult.getToken()).thenReturn(mock(BaseAuthenticationToken.class));
    when(handlerMock.getNormalizedToken(any(ServletRequest.class), any(ServletResponse.class), any(SecurityFilterChain.class), anyBoolean())).thenReturn(completedResult);
    SecurityFilterChain filterChain = mock(SecurityFilterChain.class);
    WebSSOFilter filter = new WebSSOFilter();
    filter.setContextPolicyManager(policyManager);
    filter.setHandlerList(Collections.singletonList(handlerMock));
    filter.doFilter(requestMock, responseMock, filterChain);
    verify(sessionMock, times(0)).getAttribute(SECURITY_TOKEN_KEY);
    verify(handlerMock, times(1)).getNormalizedToken(any(), any(), any(), anyBoolean());
    verify(requestMock, times(1)).setAttribute(eq(AUTHENTICATION_TOKEN_KEY), any());
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletResponse(javax.servlet.ServletResponse) HttpSession(javax.servlet.http.HttpSession) PrincipalCollection(org.apache.shiro.subject.PrincipalCollection) HttpServletResponse(javax.servlet.http.HttpServletResponse) HandlerResult(org.codice.ddf.security.handler.api.HandlerResult) ContextPolicy(org.codice.ddf.security.policy.context.ContextPolicy) ContextPolicyManager(org.codice.ddf.security.policy.context.ContextPolicyManager) HttpServletRequest(javax.servlet.http.HttpServletRequest) SecurityFilterChain(org.codice.ddf.platform.filter.SecurityFilterChain) BaseAuthenticationToken(org.codice.ddf.security.handler.BaseAuthenticationToken) AuthenticationHandler(org.codice.ddf.security.handler.api.AuthenticationHandler) Mockito.anyBoolean(org.mockito.Mockito.anyBoolean) PrincipalHolder(ddf.security.common.PrincipalHolder) Test(org.junit.Test)

Example 4 with AuthenticationHandler

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

the class WebSSOFilter method handleRequest.

private void handleRequest(HttpServletRequest httpRequest, HttpServletResponse httpResponse, FilterChain filterChain, List<AuthenticationHandler> handlers) throws IOException, ServletException {
    if (handlers.size() == 0) {
        LOGGER.warn("Handlers not ready. Returning status code 503, Service Unavailable. Check system configuration and bundle state.");
        returnSimpleResponse(HttpServletResponse.SC_SERVICE_UNAVAILABLE, httpResponse);
        return;
    }
    // First pass, see if anyone can come up with proper security token from the get-go
    HandlerResult result = null;
    LOGGER.debug("Checking for existing tokens in request.");
    for (AuthenticationHandler auth : handlers) {
        result = auth.getNormalizedToken(httpRequest, httpResponse, filterChain, false);
        if (result.getStatus() != HandlerResult.Status.NO_ACTION) {
            LOGGER.debug("Handler {} set the result status to {}", auth.getAuthenticationType(), result.getStatus());
            break;
        }
    }
    // If we haven't received usable credentials yet, go get some
    if (result == null || result.getStatus() == HandlerResult.Status.NO_ACTION) {
        LOGGER.debug("First pass with no tokens found - requesting tokens");
        // This pass, tell each handler to do whatever it takes to get a SecurityToken
        for (AuthenticationHandler auth : handlers) {
            result = auth.getNormalizedToken(httpRequest, httpResponse, filterChain, true);
            if (result.getStatus() != HandlerResult.Status.NO_ACTION) {
                LOGGER.debug("Handler {} set the result status to {}", auth.getAuthenticationType(), result.getStatus());
                break;
            }
        }
    }
    final String path = httpRequest.getRequestURI();
    String ipAddress = httpRequest.getHeader("X-FORWARDED-FOR");
    if (ipAddress == null) {
        ipAddress = httpRequest.getRemoteAddr();
    }
    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");
                return;
            case NO_ACTION:
                // should never occur - one of the handlers should have returned a token
                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);
                return;
            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);
                    return;
                }
                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());
                }
                httpRequest.setAttribute(DDF_AUTHENTICATION_TOKEN, result);
                break;
            default:
                LOGGER.warn("Unexpected response from handler - ignoring. Remote IP: {}, Path: {}", ipAddress, path);
                return;
        }
    } 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);
        return;
    }
    // If we got here, we've received our tokens to continue
    LOGGER.debug("Invoking the rest of the filter chain");
    try {
        filterChain.doFilter(httpRequest, httpResponse);
    } catch (InvalidSAMLReceivedException e) {
        // we tried to process an invalid or missing SAML assertion
        returnSimpleResponse(HttpServletResponse.SC_UNAUTHORIZED, httpResponse);
    } catch (Exception e) {
        LOGGER.debug("Exception in filter chain - passing off to handlers. Msg: {}", e.getMessage(), e);
        // First pass, see if anyone can come up with proper security token
        // from the git-go
        result = null;
        for (AuthenticationHandler auth : handlers) {
            result = auth.handleError(httpRequest, httpResponse, filterChain);
            if (result.getStatus() != HandlerResult.Status.NO_ACTION) {
                LOGGER.debug("Handler {} set the status to {}", auth.getAuthenticationType(), result.getStatus());
                break;
            }
        }
        if (result == null || result.getStatus() == HandlerResult.Status.NO_ACTION) {
            LOGGER.debug("Error during authentication - no error recovery attempted - returning bad request.");
            httpResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            httpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
            httpResponse.flushBuffer();
        }
    }
}
Also used : HandlerResult(org.codice.ddf.security.handler.api.HandlerResult) AuthenticationHandler(org.codice.ddf.security.handler.api.AuthenticationHandler) InvalidSAMLReceivedException(org.codice.ddf.security.handler.api.InvalidSAMLReceivedException) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) InvalidSAMLReceivedException(org.codice.ddf.security.handler.api.InvalidSAMLReceivedException)

Example 5 with AuthenticationHandler

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

the class WebSSOFilterTest method testDoFilterWithRedirected.

@Test
public void testDoFilterWithRedirected() throws AuthenticationException, IOException {
    ContextPolicy testPolicy = mock(ContextPolicy.class);
    ContextPolicyManager policyManager = mock(ContextPolicyManager.class);
    when(policyManager.getContextPolicy(MOCK_CONTEXT)).thenReturn(testPolicy);
    when(policyManager.isWhiteListed(MOCK_CONTEXT)).thenReturn(false);
    when(policyManager.getSessionAccess()).thenReturn(false);
    WebSSOFilter filter = new WebSSOFilter();
    // set handlers
    AuthenticationHandler handler1 = mock(AuthenticationHandler.class);
    HandlerResult noActionResult = mock(HandlerResult.class);
    when(noActionResult.getStatus()).thenReturn(Status.NO_ACTION);
    HandlerResult redirectedResult = mock(HandlerResult.class);
    when(redirectedResult.getStatus()).thenReturn(Status.REDIRECTED);
    when(redirectedResult.getToken()).thenReturn(null);
    when(handler1.getNormalizedToken(any(ServletRequest.class), any(ServletResponse.class), any(SecurityFilterChain.class), eq(false))).thenReturn(noActionResult);
    when(handler1.getNormalizedToken(any(ServletRequest.class), any(ServletResponse.class), any(SecurityFilterChain.class), eq(true))).thenReturn(redirectedResult);
    filter.setContextPolicyManager(policyManager);
    filter.setHandlerList(Collections.singletonList(handler1));
    SecurityFilterChain filterChain = mock(SecurityFilterChain.class);
    HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getRequestURI()).thenReturn(MOCK_CONTEXT);
    HttpServletResponse response = mock(HttpServletResponse.class);
    try {
        filter.doFilter(request, response, filterChain);
    } catch (AuthenticationException e) {
    }
    // the next filter should NOT be called
    verify(filterChain, never()).doFilter(request, response);
    verify(request, never()).setAttribute(eq(DDF_AUTHENTICATION_TOKEN), any(HandlerResult.class));
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletResponse(javax.servlet.ServletResponse) SecurityFilterChain(org.codice.ddf.platform.filter.SecurityFilterChain) AuthenticationException(org.codice.ddf.platform.filter.AuthenticationException) HttpServletResponse(javax.servlet.http.HttpServletResponse) AuthenticationHandler(org.codice.ddf.security.handler.api.AuthenticationHandler) HandlerResult(org.codice.ddf.security.handler.api.HandlerResult) ContextPolicy(org.codice.ddf.security.policy.context.ContextPolicy) ContextPolicyManager(org.codice.ddf.security.policy.context.ContextPolicyManager) Test(org.junit.Test)

Aggregations

AuthenticationHandler (org.codice.ddf.security.handler.api.AuthenticationHandler)9 HandlerResult (org.codice.ddf.security.handler.api.HandlerResult)7 ContextPolicy (org.codice.ddf.security.policy.context.ContextPolicy)6 ContextPolicyManager (org.codice.ddf.security.policy.context.ContextPolicyManager)6 Test (org.junit.Test)6 ServletRequest (javax.servlet.ServletRequest)5 ServletResponse (javax.servlet.ServletResponse)5 HttpServletRequest (javax.servlet.http.HttpServletRequest)5 HttpServletResponse (javax.servlet.http.HttpServletResponse)5 SecurityFilterChain (org.codice.ddf.platform.filter.SecurityFilterChain)5 AuthenticationException (org.codice.ddf.platform.filter.AuthenticationException)3 SecurityLogger (ddf.security.audit.SecurityLogger)2 PrincipalHolder (ddf.security.common.PrincipalHolder)2 IOException (java.io.IOException)2 HttpSession (javax.servlet.http.HttpSession)2 PrincipalCollection (org.apache.shiro.subject.PrincipalCollection)2 BaseAuthenticationToken (org.codice.ddf.security.handler.BaseAuthenticationToken)2 Mockito.anyBoolean (org.mockito.Mockito.anyBoolean)2 Logger (ch.qos.logback.classic.Logger)1 ArrayList (java.util.ArrayList)1