Search in sources :

Example 31 with HandlerResult

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

the class WssPKIHandlerTest method testGetNormalizedTokenSuccessNoCrlPki.

/**
     * This test ensures the proper functionality of WssHandler's method,
     * getNormalizedToken(), when given a valid HTTPServletRequest.
     */
@Test
public void testGetNormalizedTokenSuccessNoCrlPki() throws java.security.cert.CertificateException, ServletException {
    WssPKIHandler handler = getWssHandlerWithMockedCrl("signature.properties", true);
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);
    FilterChain chain = mock(FilterChain.class);
    when(request.getAttribute(("javax.servlet.request.X509Certificate"))).thenReturn(getTestCerts());
    /**
         * Note that the getNormalizedToken() method for PKI handlers do not
         * use the resolve tag.
         */
    HandlerResult result = null;
    result = handler.getNormalizedToken(request, response, chain, true);
    assertThat(result, is(notNullValue()));
    assertThat(result.getStatus(), equalTo(HandlerResult.Status.COMPLETED));
    verify(handler.crlChecker).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 32 with HandlerResult

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

the class SAMLAssertionHandler method getNormalizedToken.

@Override
public HandlerResult getNormalizedToken(ServletRequest request, ServletResponse response, FilterChain chain, boolean resolve) {
    HandlerResult handlerResult = new HandlerResult();
    String realm = (String) request.getAttribute(ContextPolicy.ACTIVE_REALM);
    SecurityToken securityToken;
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    String authHeader = ((HttpServletRequest) request).getHeader(SecurityConstants.SAML_HEADER_NAME);
    // check for full SAML assertions coming in (federated requests, etc.)
    if (authHeader != null) {
        String[] tokenizedAuthHeader = authHeader.split(" ");
        if (tokenizedAuthHeader.length == 2 && tokenizedAuthHeader[0].equals("SAML")) {
            String encodedSamlAssertion = tokenizedAuthHeader[1];
            LOGGER.trace("Header retrieved");
            try {
                String tokenString = RestSecurity.inflateBase64(encodedSamlAssertion);
                LOGGER.trace("Header value: {}", tokenString);
                securityToken = new SecurityToken();
                Element thisToken = null;
                if (tokenString.contains(SAML_NAMESPACE)) {
                    try {
                        thisToken = StaxUtils.read(new StringReader(tokenString)).getDocumentElement();
                    } catch (XMLStreamException e) {
                        LOGGER.info("Unexpected error converting XML string to element - proceeding without SAML token.", e);
                    }
                } else {
                    thisToken = parseAssertionWithoutNamespace(tokenString);
                }
                securityToken.setToken(thisToken);
                SAMLAuthenticationToken samlToken = new SAMLAuthenticationToken(null, securityToken, realm);
                handlerResult.setToken(samlToken);
                handlerResult.setStatus(HandlerResult.Status.COMPLETED);
            } catch (IOException e) {
                LOGGER.info("Unexpected error converting header value to string", e);
            }
            return handlerResult;
        }
    }
    // Check for legacy SAML cookie
    Map<String, Cookie> cookies = HttpUtils.getCookieMap(httpRequest);
    Cookie samlCookie = cookies.get(SecurityConstants.SAML_COOKIE_NAME);
    if (samlCookie != null) {
        String cookieValue = samlCookie.getValue();
        LOGGER.trace("Cookie retrieved");
        try {
            String tokenString = RestSecurity.inflateBase64(cookieValue);
            LOGGER.trace("Cookie value: {}", tokenString);
            securityToken = new SecurityToken();
            Element thisToken = StaxUtils.read(new StringReader(tokenString)).getDocumentElement();
            securityToken.setToken(thisToken);
            SAMLAuthenticationToken samlToken = new SAMLAuthenticationToken(null, securityToken, realm);
            handlerResult.setToken(samlToken);
            handlerResult.setStatus(HandlerResult.Status.COMPLETED);
        } catch (IOException e) {
            LOGGER.info("Unexpected error converting cookie value to string - proceeding without SAML token.", e);
        } catch (XMLStreamException e) {
            LOGGER.info("Unexpected error converting XML string to element - proceeding without SAML token.", e);
        }
        return handlerResult;
    }
    HttpSession session = httpRequest.getSession(false);
    if (session == null && httpRequest.getRequestedSessionId() != null) {
        session = sessionFactory.getOrCreateSession(httpRequest);
    }
    if (session != null) {
        //Check if there is a SAML Assertion in the session
        //If so, create a SAMLAuthenticationToken using the sessionId
        SecurityTokenHolder savedToken = (SecurityTokenHolder) session.getAttribute(SecurityConstants.SAML_ASSERTION);
        if (savedToken != null && savedToken.getSecurityToken(realm) != null) {
            SecurityAssertionImpl assertion = new SecurityAssertionImpl(savedToken.getSecurityToken(realm));
            if (assertion.isPresentlyValid()) {
                LOGGER.trace("Creating SAML authentication token with session.");
                SAMLAuthenticationToken samlToken = new SAMLAuthenticationToken(null, session.getId(), realm);
                handlerResult.setToken(samlToken);
                handlerResult.setStatus(HandlerResult.Status.COMPLETED);
                return handlerResult;
            } else {
                LOGGER.trace("SAML token in session has expired - removing from session and returning with no results");
                savedToken.remove(realm);
            }
        } else {
            LOGGER.trace("No SAML token located in session - returning with no results");
        }
    } else {
        LOGGER.trace("No HTTP Session - returning with no results");
    }
    return handlerResult;
}
Also used : Cookie(javax.servlet.http.Cookie) HttpSession(javax.servlet.http.HttpSession) Element(org.w3c.dom.Element) HandlerResult(org.codice.ddf.security.handler.api.HandlerResult) IOException(java.io.IOException) SAMLAuthenticationToken(org.codice.ddf.security.handler.api.SAMLAuthenticationToken) SecurityAssertionImpl(ddf.security.assertion.impl.SecurityAssertionImpl) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) HttpServletRequest(javax.servlet.http.HttpServletRequest) SecurityTokenHolder(ddf.security.common.SecurityTokenHolder) XMLStreamException(javax.xml.stream.XMLStreamException) StringReader(java.io.StringReader)

Example 33 with HandlerResult

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

the class IdpHandler method doPaosRequest.

private HandlerResult doPaosRequest(ServletRequest request, ServletResponse response) {
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;
    HandlerResult handlerResult = new HandlerResult(HandlerResult.Status.REDIRECTED, null);
    handlerResult.setSource("idp-" + SOURCE);
    String paosHeader = ((HttpServletRequest) request).getHeader(PAOS);
    //some of these options aren't currently used, leaving these here as a marker for what
    //isn't implemented
    boolean wantChannelBind = paosHeader.contains("urn:oasis:names:tc:SAML:protocol:ext:channel-binding");
    boolean wantHok = paosHeader.contains("urn:oasis:names:tc:SAML:2.0:cm:holder-of-key");
    boolean wantSigned = paosHeader.contains("urn:oasis:names:tc:SAML:2.0:profiles:SSO:ecp:2.0:WantAuthnRequestsSigned");
    boolean wantDelegation = paosHeader.contains("urn:oasis:names:tc:SAML:2.0:conditions:delegation");
    LOGGER.trace("ECP Client requested: channel bind {}, holder of key {}, signatures {}, delegation {}", wantChannelBind, wantHok, wantSigned, wantDelegation);
    LOGGER.trace("Configuring SAML Response for POST.");
    Document doc = DOMUtils.createDocument();
    doc.appendChild(doc.createElement("root"));
    LOGGER.trace("Signing SAML POST Response.");
    String authnRequest;
    String paosRequest;
    String ecpRequest;
    String ecpRelayState;
    try {
        IDPSSODescriptor idpssoDescriptor = idpMetadata.getDescriptor();
        if (idpssoDescriptor == null) {
            throw new ServletException("IdP metadata is missing. No IDPSSODescriptor present.");
        }
        authnRequest = createAndSignAuthnRequest(true, wantSigned && idpssoDescriptor.getWantAuthnRequestsSigned());
        paosRequest = createPaosRequest((HttpServletRequest) request);
        ecpRequest = createEcpRequest();
        ecpRelayState = createEcpRelayState((HttpServletRequest) request);
    } catch (ServletException | WSSecurityException e) {
        LOGGER.debug("Unable to create and sign AuthnRequest.", e);
        httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        try {
            httpServletResponse.flushBuffer();
        } catch (IOException e1) {
            LOGGER.debug("Failed to send error response: {}", e1);
        }
        return handlerResult;
    }
    LOGGER.trace("Converting SAML Response to DOM");
    String soapMessage = soapMessageTemplate.replace("{{" + PAOS_REQUEST + "}}", paosRequest);
    soapMessage = soapMessage.replace("{{" + ECP_REQUEST + "}}", ecpRequest);
    soapMessage = soapMessage.replace("{{" + SAML_REQUEST + "}}", authnRequest);
    soapMessage = soapMessage.replace("{{" + ECP_RELAY_STATE + "}}", ecpRelayState);
    soapMessage = soapMessage.replace("{{" + PAOS_RESPONSE + "}}", "");
    try {
        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        httpServletResponse.setContentType("application/vnd.paos+xml");
        httpServletResponse.getOutputStream().print(soapMessage);
        httpServletResponse.flushBuffer();
    } catch (IOException ioe) {
        LOGGER.debug("Failed to send auth response: {}", ioe);
    }
    return handlerResult;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) IDPSSODescriptor(org.opensaml.saml.saml2.metadata.IDPSSODescriptor) HttpServletResponse(javax.servlet.http.HttpServletResponse) HandlerResult(org.codice.ddf.security.handler.api.HandlerResult) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) IOException(java.io.IOException) Document(org.w3c.dom.Document)

Example 34 with HandlerResult

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

the class AbstractPKIHandler method handleError.

@Override
public HandlerResult handleError(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws ServletException {
    String realm = (String) servletRequest.getAttribute(ContextPolicy.ACTIVE_REALM);
    HandlerResult result = new HandlerResult(HandlerResult.Status.NO_ACTION, null);
    result.setSource(realm + "-" + SOURCE);
    LOGGER.debug("In error handler for pki - no action taken.");
    return result;
}
Also used : HandlerResult(org.codice.ddf.security.handler.api.HandlerResult)

Example 35 with HandlerResult

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

the class AbstractPKIHandler method getNormalizedToken.

/**
     * Handler implementing PKI authentication. Returns the {@link org.codice.ddf.security.handler.api.HandlerResult} containing
     * a BinarySecurityToken if the operation was successful.
     *
     * @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 result of handling this request - status and optional tokens
     * @throws ServletException
     */
@Override
public HandlerResult getNormalizedToken(ServletRequest request, ServletResponse response, FilterChain chain, boolean resolve) throws ServletException {
    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("Doing PKI authentication and authorization for path {}", path);
    //doesn't matter what the resolve flag is set to, we do the same action
    BaseAuthenticationToken token = extractAuthenticationInfo(realm, (X509Certificate[]) httpRequest.getAttribute("javax.servlet.request.X509Certificate"));
    X509Certificate[] certs = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");
    HttpServletResponse httpResponse = response instanceof HttpServletResponse ? (HttpServletResponse) response : null;
    // The httpResponse was null, return no action and try to process with other handlers
    if (httpResponse == null && resolve) {
        LOGGER.debug("HTTP Response was null for request {}", path);
        return handlerResult;
    }
    // No auth info was extracted, return NO_ACTION
    if (token == null) {
        return handlerResult;
    }
    // CRL was specified, check against CRL and return the result or throw a ServletException to the WebSSOFilter
    if (crlChecker.passesCrlCheck(certs)) {
        handlerResult.setToken(token);
        handlerResult.setStatus(HandlerResult.Status.COMPLETED);
    } else {
        String errorMsg = "The certificate used to complete the request has been revoked.";
        LOGGER.info(errorMsg);
        throw new ServletException(errorMsg);
    }
    return handlerResult;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) BaseAuthenticationToken(org.codice.ddf.security.handler.api.BaseAuthenticationToken) HttpServletResponse(javax.servlet.http.HttpServletResponse) HandlerResult(org.codice.ddf.security.handler.api.HandlerResult) X509Certificate(java.security.cert.X509Certificate)

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