Search in sources :

Example 26 with HandlerResult

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

the class PKIHandlerTest method testNoActionWhenHttpResponseIsNull.

/**
     * Tests that the certificate gets through when CRL checking is enabled but
     * the cert is not listed in the CRL
     *
     * @throws java.security.cert.CertificateException
     * @throws ServletException
     */
@Test
public void testNoActionWhenHttpResponseIsNull() throws java.security.cert.CertificateException, ServletException {
    PKIHandler handler = getPKIHandlerWithMockedCrl("signature.properties", true);
    HttpServletResponse httpResponse = null;
    HttpServletRequest httpRequest = mock(HttpServletRequest.class);
    FilterChain chain = mock(FilterChain.class);
    HandlerResult result = handler.getNormalizedToken(httpRequest, httpResponse, chain, true);
    assertThat(result.getStatus(), equalTo(HandlerResult.Status.NO_ACTION));
    verify(handler.crlChecker, never()).passesCrlCheck(getTestCerts());
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) FilterChain(javax.servlet.FilterChain) HttpServletResponse(javax.servlet.http.HttpServletResponse) HandlerResult(org.codice.ddf.security.handler.api.HandlerResult) Test(org.junit.Test)

Example 27 with HandlerResult

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

the class SAMLAssertionHandler method handleError.

/**
     * If an error occured during the processing of the request, this method will get called. Since
     * SAML handling is typically processed first, then we can assume that there was an error with
     * the presented SAML assertion - either it was invalid, or the reference didn't match a
     * cached assertion, etc. In order not to get stuck in a processing loop, we will return a 401
     * status code.
     *
     * @param servletRequest  http servlet request
     * @param servletResponse http servlet response
     * @param chain           rest of the request chain to be invoked after security handling
     * @return result containing the potential credentials and status
     * @throws ServletException
     */
@Override
public HandlerResult handleError(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws ServletException {
    HandlerResult result = new HandlerResult();
    HttpServletRequest httpRequest = servletRequest instanceof HttpServletRequest ? (HttpServletRequest) servletRequest : null;
    HttpServletResponse httpResponse = servletResponse instanceof HttpServletResponse ? (HttpServletResponse) servletResponse : null;
    if (httpRequest == null || httpResponse == null) {
        return result;
    }
    LOGGER.debug("In error handler for saml - setting status code to 401 and returning status REDIRECTED.");
    // we tried to process an invalid or missing SAML assertion
    try {
        httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        httpResponse.flushBuffer();
    } catch (IOException e) {
        LOGGER.debug("Failed to send auth response", e);
    }
    result.setStatus(HandlerResult.Status.REDIRECTED);
    return result;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) HandlerResult(org.codice.ddf.security.handler.api.HandlerResult) IOException(java.io.IOException)

Example 28 with HandlerResult

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

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

the class WebSSOFilterTest method testDoFilterWithRedirected.

@Test
public void testDoFilterWithRedirected() throws ServletException, IOException {
    ContextPolicy testPolicy = mock(ContextPolicy.class);
    when(testPolicy.getRealm()).thenReturn("TestRealm");
    ContextPolicyManager policyManager = mock(ContextPolicyManager.class);
    when(policyManager.getContextPolicy(anyString())).thenReturn(testPolicy);
    when(policyManager.isWhiteListed(anyString())).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(FilterChain.class), eq(false))).thenReturn(noActionResult);
    when(handler1.getNormalizedToken(any(ServletRequest.class), any(ServletResponse.class), any(FilterChain.class), eq(true))).thenReturn(redirectedResult);
    filter.setHandlerList(Collections.singletonList(handler1));
    FilterChain filterChain = mock(FilterChain.class);
    HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getContextPath()).thenReturn(MOCK_CONTEXT);
    HttpServletResponse response = mock(HttpServletResponse.class);
    filter.doFilter(request, response, filterChain);
    // 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) FilterChain(javax.servlet.FilterChain) 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 30 with HandlerResult

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

the class WebSSOFilterTest method testDoFilterResolvingOnSecondCall.

@Test
public void testDoFilterResolvingOnSecondCall() throws IOException, ServletException {
    ContextPolicy testPolicy = mock(ContextPolicy.class);
    when(testPolicy.getRealm()).thenReturn("TestRealm");
    ContextPolicyManager policyManager = mock(ContextPolicyManager.class);
    when(policyManager.getContextPolicy(anyString())).thenReturn(testPolicy);
    when(policyManager.isWhiteListed(anyString())).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(FilterChain.class), eq(true))).thenReturn(completedResult);
    when(handler1.getNormalizedToken(any(ServletRequest.class), any(ServletResponse.class), any(FilterChain.class), eq(false))).thenReturn(noActionResult);
    filter.setHandlerList(Collections.singletonList(handler1));
    FilterChain filterChain = mock(FilterChain.class);
    HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getContextPath()).thenReturn(MOCK_CONTEXT);
    HttpServletResponse response = mock(HttpServletResponse.class);
    filter.doFilter(request, response, filterChain);
    verify(handler1, times(2)).getNormalizedToken(any(HttpServletRequest.class), any(HttpServletResponse.class), any(FilterChain.class), anyBoolean());
    // 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) FilterChain(javax.servlet.FilterChain) 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

HandlerResult (org.codice.ddf.security.handler.api.HandlerResult)51 HttpServletRequest (javax.servlet.http.HttpServletRequest)33 HttpServletResponse (javax.servlet.http.HttpServletResponse)33 Test (org.junit.Test)33 FilterChain (javax.servlet.FilterChain)24 ServletException (javax.servlet.ServletException)10 IOException (java.io.IOException)8 SecurityToken (org.apache.cxf.ws.security.tokenstore.SecurityToken)8 ProxyFilterChain (org.codice.ddf.security.handler.cas.filter.ProxyFilterChain)6 Element (org.w3c.dom.Element)6 BaseAuthenticationToken (org.codice.ddf.security.handler.api.BaseAuthenticationToken)5 SAMLAuthenticationToken (org.codice.ddf.security.handler.api.SAMLAuthenticationToken)5 ServletRequest (javax.servlet.ServletRequest)4 ServletResponse (javax.servlet.ServletResponse)4 HttpSession (javax.servlet.http.HttpSession)4 AuthenticationHandler (org.codice.ddf.security.handler.api.AuthenticationHandler)4 Subject (ddf.security.Subject)3 SecurityTokenHolder (ddf.security.common.SecurityTokenHolder)3 SecurityManager (ddf.security.service.SecurityManager)3 FilterConfig (javax.servlet.FilterConfig)3