Search in sources :

Example 46 with HandlerResult

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

the class AbstractBasicAuthenticationHandler method getNormalizedToken.

/**
     * Processes the incoming request to retrieve the username/password tokens. Handles responding
     * to the client that authentication is needed if they are not present in the request.
     * Returns the {@link org.codice.ddf.security.handler.api.HandlerResult} for the HTTP Request.
     *
     * @param request  http request to obtain attributes from and to pass into any local filter chains required
     * @param response http response to return http responses or redirects
     * @param chain    original filter chain (should not be called from your handler)
     * @param resolve  flag with true implying that credentials should be obtained, false implying return if no credentials are found.
     * @return
     */
@Override
public HandlerResult getNormalizedToken(ServletRequest request, ServletResponse response, FilterChain chain, boolean resolve) {
    String realm = (String) request.getAttribute(ContextPolicy.ACTIVE_REALM);
    HandlerResult handlerResult = new HandlerResult(HandlerResult.Status.NO_ACTION, null);
    handlerResult.setSource(realm + "-" + SOURCE);
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    String path = httpRequest.getServletPath();
    LOGGER.debug("Handling request for path {}", path);
    LOGGER.debug("Doing authentication and authorization for path {}", path);
    BaseAuthenticationToken token = extractAuthenticationInfo(httpRequest);
    // we found credentials, attach to result and return with completed status
    if (token != null) {
        handlerResult.setToken(token);
        handlerResult.setStatus(HandlerResult.Status.COMPLETED);
        return handlerResult;
    }
    // we didn't find the credentials, see if we are to do anything or not
    if (resolve) {
        doAuthPrompt(realm, (HttpServletResponse) response);
        handlerResult.setStatus(HandlerResult.Status.REDIRECTED);
    }
    return handlerResult;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) BaseAuthenticationToken(org.codice.ddf.security.handler.api.BaseAuthenticationToken) HandlerResult(org.codice.ddf.security.handler.api.HandlerResult)

Example 47 with HandlerResult

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

the class GuestHandler method handleError.

@Override
public HandlerResult handleError(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws ServletException {
    HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
    String realm = (String) servletRequest.getAttribute(ContextPolicy.ACTIVE_REALM);
    httpResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    try {
        httpResponse.getWriter().write(INVALID_MESSAGE);
        httpResponse.flushBuffer();
    } catch (IOException e) {
        LOGGER.debug("Failed to send auth response: {}", e);
    }
    HandlerResult result = new HandlerResult();
    result.setSource(realm + "-GuestHandler");
    LOGGER.debug("In error handler for guest - returning action completed.");
    result.setStatus(HandlerResult.Status.REDIRECTED);
    return result;
}
Also used : HttpServletResponse(javax.servlet.http.HttpServletResponse) HandlerResult(org.codice.ddf.security.handler.api.HandlerResult) IOException(java.io.IOException)

Example 48 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 49 with HandlerResult

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

the class LoginFilter method validateRequest.

private Subject validateRequest(final HttpServletRequest httpRequest) throws IOException, ServletException {
    Subject subject = null;
    Object ddfAuthToken = httpRequest.getAttribute(DDF_AUTHENTICATION_TOKEN);
    if (ddfAuthToken instanceof HandlerResult) {
        HandlerResult result = (HandlerResult) ddfAuthToken;
        BaseAuthenticationToken thisToken = result.getToken();
        /*
             * If the user has already authenticated they will have a valid SAML token. Validate
             * that here and create the subject from the token.
             */
        if (thisToken instanceof SAMLAuthenticationToken) {
            subject = handleAuthenticationToken(httpRequest, (SAMLAuthenticationToken) thisToken);
        } else if (thisToken != null) {
            subject = handleAuthenticationToken(httpRequest, thisToken);
        }
    }
    return subject;
}
Also used : BaseAuthenticationToken(org.codice.ddf.security.handler.api.BaseAuthenticationToken) HandlerResult(org.codice.ddf.security.handler.api.HandlerResult) SAMLAuthenticationToken(org.codice.ddf.security.handler.api.SAMLAuthenticationToken) Subject(ddf.security.Subject)

Example 50 with HandlerResult

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

the class LoginFilterTest method testBadSigSamlCookie.

@Test(expected = ServletException.class)
public void testBadSigSamlCookie() throws IOException, XMLStreamException, ServletException, ParserConfigurationException, SAXException, SecurityServiceException {
    FilterConfig filterConfig = mock(FilterConfig.class);
    LoginFilter loginFilter = new LoginFilter();
    loginFilter.setSessionFactory(sessionFactory);
    ddf.security.service.SecurityManager securityManager = mock(SecurityManager.class);
    loginFilter.setSecurityManager(securityManager);
    loginFilter.setSignaturePropertiesFile("signature.properties");
    try {
        loginFilter.init(filterConfig);
    } catch (ServletException e) {
        fail(e.getMessage());
    }
    HttpServletRequest servletRequest = new TestHttpServletRequest();
    HttpServletResponse servletResponse = mock(HttpServletResponse.class);
    FilterChain filterChain = mock(FilterChain.class);
    SecurityToken securityToken = new SecurityToken();
    Element thisToken = readDocument("/bad_saml.xml").getDocumentElement();
    securityToken.setToken(thisToken);
    SAMLAuthenticationToken samlToken = new SAMLAuthenticationToken(null, securityToken, "karaf");
    HandlerResult result = new HandlerResult(HandlerResult.Status.COMPLETED, samlToken);
    servletRequest.setAttribute("ddf.security.token", result);
    loginFilter.doFilter(servletRequest, servletResponse, filterChain);
}
Also used : FilterChain(javax.servlet.FilterChain) Element(org.w3c.dom.Element) HttpServletResponse(javax.servlet.http.HttpServletResponse) HandlerResult(org.codice.ddf.security.handler.api.HandlerResult) SAMLAuthenticationToken(org.codice.ddf.security.handler.api.SAMLAuthenticationToken) ServletException(javax.servlet.ServletException) HttpServletRequest(javax.servlet.http.HttpServletRequest) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) FilterConfig(javax.servlet.FilterConfig) SecurityManager(ddf.security.service.SecurityManager) Test(org.junit.Test)

Aggregations

HandlerResult (org.codice.ddf.security.handler.api.HandlerResult)74 HttpServletRequest (javax.servlet.http.HttpServletRequest)44 Test (org.junit.Test)44 HttpServletResponse (javax.servlet.http.HttpServletResponse)40 HandlerResultImpl (org.codice.ddf.security.handler.HandlerResultImpl)17 SecurityFilterChain (org.codice.ddf.platform.filter.SecurityFilterChain)15 FilterChain (javax.servlet.FilterChain)13 IOException (java.io.IOException)11 ServletException (javax.servlet.ServletException)8 SecurityToken (org.apache.cxf.ws.security.tokenstore.SecurityToken)8 HttpSession (javax.servlet.http.HttpSession)7 AuthenticationHandler (org.codice.ddf.security.handler.api.AuthenticationHandler)7 Element (org.w3c.dom.Element)7 ServletRequest (javax.servlet.ServletRequest)6 ServletResponse (javax.servlet.ServletResponse)6 ContextPolicyManager (org.codice.ddf.security.policy.context.ContextPolicyManager)6 AuthenticationException (org.codice.ddf.platform.filter.AuthenticationException)5 BaseAuthenticationToken (org.codice.ddf.security.handler.api.BaseAuthenticationToken)5 SAMLAuthenticationToken (org.codice.ddf.security.handler.api.SAMLAuthenticationToken)5 ProxyFilterChain (org.codice.ddf.security.handler.cas.filter.ProxyFilterChain)5