Search in sources :

Example 6 with AuthenticationFailureException

use of org.codice.ddf.platform.filter.AuthenticationFailureException in project ddf by codice.

the class SamlRealm method doGetAuthenticationInfo.

/**
 * Perform authentication based on the supplied token.
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {
    Object credential = null;
    // perform validation
    if (token instanceof SAMLAuthenticationToken) {
        try {
            samlAssertionValidator.validate((SAMLAuthenticationToken) token);
            credential = token.getCredentials();
        } catch (AuthenticationFailureException e) {
            String msg = "Unable to validate request's authentication.";
            LOGGER.info(msg);
            throw new AuthenticationException(msg, e);
        }
    }
    if (credential == null) {
        String msg = "Unable to authenticate credential.  A NULL credential was provided in the supplied authentication token. This may be due to an error with the SSO server that created the token.";
        LOGGER.info(msg);
        throw new AuthenticationException(msg);
    }
    LOGGER.debug("Received credentials.");
    LOGGER.debug("Creating token authentication information with SAML.");
    SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo();
    Element securityToken = checkForSecurityToken(credential);
    SimplePrincipalCollection principals = createPrincipalFromToken(securityToken);
    simpleAuthenticationInfo.setPrincipals(principals);
    simpleAuthenticationInfo.setCredentials(credential);
    return simpleAuthenticationInfo;
}
Also used : SimpleAuthenticationInfo(org.apache.shiro.authc.SimpleAuthenticationInfo) AuthenticationException(org.apache.shiro.authc.AuthenticationException) Element(org.w3c.dom.Element) SimplePrincipalCollection(org.apache.shiro.subject.SimplePrincipalCollection) AuthenticationFailureException(org.codice.ddf.platform.filter.AuthenticationFailureException) SAMLAuthenticationToken(org.codice.ddf.security.handler.SAMLAuthenticationToken)

Example 7 with AuthenticationFailureException

use of org.codice.ddf.platform.filter.AuthenticationFailureException in project ddf by codice.

the class SamlAssertionValidatorImpl method validate.

/**
 * Validates a SAMLAuthenticationToken by checking it's signature against the configured system
 * certs.
 *
 * @param token token to validate
 * @throws AuthenticationFailureException thrown when the cert fails to validate
 */
@Override
public void validate(SAMLAuthenticationToken token) throws AuthenticationFailureException {
    try {
        LOGGER.debug("Validation received SAML Assertion");
        PrincipalCollection principalCollection = (PrincipalCollection) token.getCredentials();
        Collection<SecurityAssertion> securityAssertions = principalCollection.byType(SecurityAssertion.class);
        SecurityAssertion securityAssertion = null;
        for (SecurityAssertion assertion : securityAssertions) {
            if (SecurityAssertionSaml.SAML2_TOKEN_TYPE.equals(assertion.getTokenType())) {
                securityAssertion = assertion;
                break;
            }
        }
        if (securityAssertion == null) {
            throw new AuthenticationFailureException("Unable to validate SAML token. Token is not SAML.");
        }
        SamlAssertionWrapper assertion = new SamlAssertionWrapper((Element) securityAssertion.getToken());
        // get the crypto junk
        Crypto crypto = getSignatureCrypto();
        Response samlResponse = createSamlResponse(token.getRequestURI(), assertion.getIssuerString(), createStatus(SAMLProtocolResponseValidator.SAML2_STATUSCODE_SUCCESS, null));
        BUILDER.get().reset();
        Document doc = BUILDER.get().newDocument();
        Element policyElement = OpenSAMLUtil.toDom(samlResponse, doc);
        doc.appendChild(policyElement);
        Credential credential = new Credential();
        credential.setSamlAssertion(assertion);
        RequestData requestData = new RequestData();
        requestData.setWsDocInfo(new WSDocInfo(samlResponse.getDOM().getOwnerDocument()));
        requestData.setSigVerCrypto(crypto);
        WSSConfig wssConfig = WSSConfig.getNewInstance();
        requestData.setWssConfig(wssConfig);
        X509Certificate[] x509Certs = token.getX509Certs();
        requestData.setTlsCerts(x509Certs);
        validateHolderOfKeyConfirmation(assertion, x509Certs);
        if (assertion.isSigned()) {
            // Verify the signature
            WSSSAMLKeyInfoProcessor wsssamlKeyInfoProcessor = new WSSSAMLKeyInfoProcessor(requestData);
            assertion.verifySignature(wsssamlKeyInfoProcessor, crypto);
            assertion.parseSubject(new WSSSAMLKeyInfoProcessor(requestData), requestData.getSigVerCrypto(), requestData.getCallbackHandler());
        }
        assertionValidator.validate(credential, requestData);
    } catch (SecurityServiceException e) {
        LOGGER.debug("Unable to get subject from SAML request.", e);
        throw new AuthenticationFailureException(e);
    } catch (WSSecurityException e) {
        LOGGER.debug("Unable to read/validate security token from request.", e);
        throw new AuthenticationFailureException(e);
    }
}
Also used : WSDocInfo(org.apache.wss4j.dom.WSDocInfo) Credential(org.apache.wss4j.dom.validate.Credential) SecurityServiceException(ddf.security.service.SecurityServiceException) Element(org.w3c.dom.Element) PrincipalCollection(org.apache.shiro.subject.PrincipalCollection) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) AuthenticationFailureException(org.codice.ddf.platform.filter.AuthenticationFailureException) SecurityAssertion(ddf.security.assertion.SecurityAssertion) Document(org.w3c.dom.Document) X509Certificate(java.security.cert.X509Certificate) Response(org.opensaml.saml.saml2.core.Response) Crypto(org.apache.wss4j.common.crypto.Crypto) WSSConfig(org.apache.wss4j.dom.engine.WSSConfig) RequestData(org.apache.wss4j.dom.handler.RequestData) WSSSAMLKeyInfoProcessor(org.apache.wss4j.dom.saml.WSSSAMLKeyInfoProcessor)

Example 8 with AuthenticationFailureException

use of org.codice.ddf.platform.filter.AuthenticationFailureException in project ddf by codice.

the class CsrfFilter method doFilter.

/**
 * Checks that the origin or referer header of the request matches a system trusted authority when
 * attempting to access certain contexts. Also checks for the existence of an anti-CSRF header
 * "X-Requested-With". A 403 is returned and the request is stopped if one or more of these
 * conditions are met: - Neither the Origin nor Referer header is present on the request. -
 * Neither the Origin nor Referer header match a trusted authority. - The "X-Requested-With"
 * header is not present on the request.
 *
 * @param request incoming http request
 * @param response response stream for returning the response
 * @param chain chain of filters to be invoked following this filter
 * @throws IOException
 * @throws AuthenticationException
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, SecurityFilterChain chain) throws IOException, AuthenticationException {
    if (shouldFilter) {
        LOGGER.debug("Performing doFilter() on CsrfFilter");
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        String targetContextPath = httpRequest.getRequestURI();
        String requestMethod = httpRequest.getMethod();
        String userAgentHeader = httpRequest.getHeader(HttpHeaders.USER_AGENT);
        // Begin CSRF checks if request is accessing a Cross-Site protected context
        if (protectedContexts.stream().anyMatch(targetContextPath::startsWith) && doBrowserProtectionFilter(httpRequest, httpResponse, targetContextPath, requestMethod)) {
            throw new AuthenticationFailureException();
        }
        // Execute CSRF check if user is accessing /services
        if (targetContextPath.startsWith(SERVICE_CONTEXT) && doSystemProtectionFilter(httpRequest, httpResponse, targetContextPath, requestMethod, userAgentHeader)) {
            throw new AuthenticationFailureException();
        }
    }
    // All checks passed
    chain.doFilter(request, response);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) AuthenticationFailureException(org.codice.ddf.platform.filter.AuthenticationFailureException)

Example 9 with AuthenticationFailureException

use of org.codice.ddf.platform.filter.AuthenticationFailureException in project ddf by codice.

the class WebSSOFilter method doFilter.

/**
 * Provides filtering for every registered http context. Checks for an existing session. If it
 * doesn't exist, it then looks up the current context and determines the proper handlers to
 * include in the chain. Each handler is given the opportunity to locate their specific tokens if
 * they exist or to go off and obtain them. Once a token has been received that we know how to
 * process , we attach them to the request and continue down the chain.
 *
 * @param servletRequest incoming http request
 * @param servletResponse response stream for returning the response
 * @param filterChain chain of filters to be invoked following this filter
 * @throws IOException
 * @throws AuthenticationException
 */
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, SecurityFilterChain filterChain) throws IOException, AuthenticationException {
    LOGGER.debug("Performing doFilter() on WebSSOFilter");
    HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
    HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
    final String path = httpRequest.getRequestURI();
    LOGGER.debug("Handling request for path {}", path);
    boolean isWhiteListed = false;
    if (contextPolicyManager != null) {
        isWhiteListed = contextPolicyManager.isWhiteListed(path);
    }
    if (isWhiteListed) {
        LOGGER.debug("Context of {} has been whitelisted, adding a NO_AUTH_POLICY attribute to the header.", path);
        servletRequest.setAttribute(ContextPolicy.NO_AUTH_POLICY, true);
        filterChain.doFilter(httpRequest, httpResponse);
    } else {
        // make sure request didn't come in with NO_AUTH_POLICY set
        servletRequest.setAttribute(ContextPolicy.NO_AUTH_POLICY, null);
        // now handle the request and set the authentication token
        LOGGER.debug("Handling request for {}.", path);
        try {
            handleRequest(httpRequest, httpResponse, filterChain, getHandlerList(path));
        } catch (AuthenticationFailureException e) {
            String message = (e.getRootCause() != null) ? e.getRootCause().getMessage() : e.getMessage();
            securityLogger.audit("Authentication failed. Error message: '{}'", message);
            throw e;
        }
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) AuthenticationFailureException(org.codice.ddf.platform.filter.AuthenticationFailureException)

Example 10 with AuthenticationFailureException

use of org.codice.ddf.platform.filter.AuthenticationFailureException in project ddf by codice.

the class IdpHandler method doPaosRequest.

private HandlerResult doPaosRequest(ServletRequest request, ServletResponse response) {
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;
    HandlerResult handlerResult = new HandlerResultImpl(HandlerResult.Status.REDIRECTED, null);
    handlerResult.setSource(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 AuthenticationFailureException(IDP_METADATA_MISSING);
        }
        authnRequest = createAndSignAuthnRequest(true, wantSigned && idpssoDescriptor.getWantAuthnRequestsSigned());
        paosRequest = createPaosRequest((HttpServletRequest) request);
        ecpRequest = createEcpRequest();
        ecpRelayState = createEcpRelayState((HttpServletRequest) request);
    } catch (WSSecurityException | AuthenticationFailureException 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(PAOS_MIME);
        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) IDPSSODescriptor(org.opensaml.saml.saml2.metadata.IDPSSODescriptor) HandlerResultImpl(org.codice.ddf.security.handler.HandlerResultImpl) HttpServletResponse(javax.servlet.http.HttpServletResponse) HandlerResult(org.codice.ddf.security.handler.api.HandlerResult) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) AuthenticationFailureException(org.codice.ddf.platform.filter.AuthenticationFailureException) IOException(java.io.IOException) Document(org.w3c.dom.Document)

Aggregations

AuthenticationFailureException (org.codice.ddf.platform.filter.AuthenticationFailureException)11 IOException (java.io.IOException)5 HttpServletRequest (javax.servlet.http.HttpServletRequest)4 HttpServletResponse (javax.servlet.http.HttpServletResponse)4 HandlerResultImpl (org.codice.ddf.security.handler.HandlerResultImpl)4 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)3 HandlerResult (org.codice.ddf.security.handler.api.HandlerResult)3 IDPSSODescriptor (org.opensaml.saml.saml2.metadata.IDPSSODescriptor)3 Document (org.w3c.dom.Document)3 Element (org.w3c.dom.Element)3 SignatureException (ddf.security.samlp.SignatureException)2 AuthenticationChallengeException (org.codice.ddf.platform.filter.AuthenticationChallengeException)2 SecurityAssertion (ddf.security.assertion.SecurityAssertion)1 SecurityServiceException (ddf.security.service.SecurityServiceException)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 URI (java.net.URI)1 URISyntaxException (java.net.URISyntaxException)1 X509Certificate (java.security.cert.X509Certificate)1 UriBuilder (javax.ws.rs.core.UriBuilder)1 UriBuilderImpl (org.apache.cxf.jaxrs.impl.UriBuilderImpl)1