Search in sources :

Example 76 with Subject

use of ddf.security.Subject in project ddf by codice.

the class AuthorizationFilterTest method testBadSubject.

@Test
public void testBadSubject() {
    FilterConfig filterConfig = mock(FilterConfig.class);
    ContextPolicyManager contextPolicyManager = new TestPolicyManager();
    contextPolicyManager.setContextPolicy(PATH, getMockContextPolicy());
    AuthorizationFilter loginFilter = new AuthorizationFilter(contextPolicyManager);
    try {
        loginFilter.init(filterConfig);
    } catch (ServletException e) {
        fail(e.getMessage());
    }
    HttpServletRequest servletRequest = getMockServletRequest();
    servletRequest.setAttribute(SecurityConstants.SECURITY_SUBJECT, mock(Subject.class));
    HttpServletResponse servletResponse = mock(HttpServletResponse.class);
    FilterChain filterChain = (request, response) -> fail("Should not have called doFilter without a valid Subject");
    try {
        loginFilter.doFilter(servletRequest, servletResponse, filterChain);
    } catch (IOException | ServletException e) {
        fail(e.getMessage());
    }
}
Also used : ServletException(javax.servlet.ServletException) HttpServletRequest(javax.servlet.http.HttpServletRequest) FilterChain(javax.servlet.FilterChain) ServletException(javax.servlet.ServletException) ContextPolicy(org.codice.ddf.security.policy.context.ContextPolicy) CollectionPermission(ddf.security.permission.CollectionPermission) Collection(java.util.Collection) KeyValuePermission(ddf.security.permission.KeyValuePermission) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) HashMap(java.util.HashMap) Test(org.junit.Test) Subject(ddf.security.Subject) Mockito.when(org.mockito.Mockito.when) Matchers.anyString(org.mockito.Matchers.anyString) Matchers.any(org.mockito.Matchers.any) HttpServletRequest(javax.servlet.http.HttpServletRequest) ThreadContext(org.apache.shiro.util.ThreadContext) Map(java.util.Map) FilterConfig(javax.servlet.FilterConfig) SecurityConstants(ddf.security.SecurityConstants) Assert.fail(org.junit.Assert.fail) Collections(java.util.Collections) ContextPolicyManager(org.codice.ddf.security.policy.context.ContextPolicyManager) Mockito.mock(org.mockito.Mockito.mock) Before(org.junit.Before) FilterChain(javax.servlet.FilterChain) HttpServletResponse(javax.servlet.http.HttpServletResponse) FilterConfig(javax.servlet.FilterConfig) IOException(java.io.IOException) Subject(ddf.security.Subject) ContextPolicyManager(org.codice.ddf.security.policy.context.ContextPolicyManager) Test(org.junit.Test)

Example 77 with Subject

use of ddf.security.Subject in project ddf by codice.

the class LoginFilter method handleAuthenticationToken.

private Subject handleAuthenticationToken(HttpServletRequest httpRequest, SAMLAuthenticationToken token) throws ServletException {
    Subject subject;
    try {
        LOGGER.debug("Validating received SAML assertion.");
        boolean wasReference = false;
        boolean firstLogin = true;
        if (token.isReference()) {
            wasReference = true;
            LOGGER.trace("Converting SAML reference to assertion");
            Object sessionToken = httpRequest.getSession(false).getAttribute(SecurityConstants.SAML_ASSERTION);
            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("Http Session assertion - class: {}  loader: {}", sessionToken.getClass().getName(), sessionToken.getClass().getClassLoader());
                LOGGER.trace("SecurityToken class: {}  loader: {}", SecurityToken.class.getName(), SecurityToken.class.getClassLoader());
            }
            SecurityToken savedToken = null;
            try {
                savedToken = ((SecurityTokenHolder) sessionToken).getSecurityToken(token.getRealm());
            } catch (ClassCastException e) {
                httpRequest.getSession(false).invalidate();
            }
            if (savedToken != null) {
                firstLogin = false;
                token.replaceReferenece(savedToken);
            }
            if (token.isReference()) {
                String msg = "Missing or invalid SAML assertion for provided reference.";
                LOGGER.debug(msg);
                throw new InvalidSAMLReceivedException(msg);
            }
        }
        SAMLAuthenticationToken newToken = renewSecurityToken(httpRequest.getSession(false), token);
        SecurityToken securityToken;
        if (newToken != null) {
            firstLogin = false;
            securityToken = (SecurityToken) newToken.getCredentials();
        } else {
            securityToken = (SecurityToken) token.getCredentials();
        }
        if (!wasReference) {
            // wrap the token
            SamlAssertionWrapper assertion = new SamlAssertionWrapper(securityToken.getToken());
            // get the crypto junk
            Crypto crypto = getSignatureCrypto();
            Response samlResponse = createSamlResponse(httpRequest.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.setSigVerCrypto(crypto);
            WSSConfig wssConfig = WSSConfig.getNewInstance();
            requestData.setWssConfig(wssConfig);
            X509Certificate[] x509Certs = (X509Certificate[]) httpRequest.getAttribute("javax.servlet.request.X509Certificate");
            requestData.setTlsCerts(x509Certs);
            validateHolderOfKeyConfirmation(assertion, x509Certs);
            if (assertion.isSigned()) {
                // Verify the signature
                WSSSAMLKeyInfoProcessor wsssamlKeyInfoProcessor = new WSSSAMLKeyInfoProcessor(requestData, new WSDocInfo(samlResponse.getDOM().getOwnerDocument()));
                assertion.verifySignature(wsssamlKeyInfoProcessor, crypto);
                assertion.parseSubject(new WSSSAMLKeyInfoProcessor(requestData, new WSDocInfo(samlResponse.getDOM().getOwnerDocument())), requestData.getSigVerCrypto(), requestData.getCallbackHandler());
            }
            // Validate the Assertion & verify trust in the signature
            assertionValidator.validate(credential, requestData);
        }
        // if it is all good, then we'll create our subject
        subject = securityManager.getSubject(securityToken);
        if (firstLogin) {
            boolean hasSecurityAuditRole = Arrays.stream(System.getProperty("security.audit.roles").split(",")).filter(subject::hasRole).findFirst().isPresent();
            if (hasSecurityAuditRole) {
                SecurityLogger.audit("Subject has logged in with admin privileges", subject);
            }
        }
        if (!wasReference && firstLogin) {
            addSamlToSession(httpRequest, token.getRealm(), securityToken);
        }
    } catch (SecurityServiceException e) {
        LOGGER.debug("Unable to get subject from SAML request.", e);
        throw new ServletException(e);
    } catch (WSSecurityException e) {
        LOGGER.debug("Unable to read/validate security token from request.", e);
        throw new ServletException(e);
    }
    return subject;
}
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) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) InvalidSAMLReceivedException(org.codice.ddf.security.handler.api.InvalidSAMLReceivedException) Document(org.w3c.dom.Document) SAMLAuthenticationToken(org.codice.ddf.security.handler.api.SAMLAuthenticationToken) Subject(ddf.security.Subject) X509Certificate(java.security.cert.X509Certificate) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) Response(org.opensaml.saml.saml2.core.Response) ServletResponse(javax.servlet.ServletResponse) ServletException(javax.servlet.ServletException) 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 78 with Subject

use of ddf.security.Subject in project ddf by codice.

the class LoginFilter method renewSecurityToken.

private SAMLAuthenticationToken renewSecurityToken(HttpSession session, SAMLAuthenticationToken savedToken) throws ServletException, WSSecurityException {
    if (session != null) {
        SecurityAssertion savedAssertion = new SecurityAssertionImpl(((SecurityToken) savedToken.getCredentials()));
        if (savedAssertion.getIssuer() != null && !savedAssertion.getIssuer().equals(SystemBaseUrl.getHost())) {
            return null;
        }
        if (savedAssertion.getNotOnOrAfter() == null) {
            return null;
        }
        long afterMil = savedAssertion.getNotOnOrAfter().getTime();
        long timeoutMillis = (afterMil - System.currentTimeMillis());
        if (timeoutMillis <= 0) {
            throw new InvalidSAMLReceivedException("SAML assertion has expired.");
        }
        if (timeoutMillis <= 60000) {
            // within 60 seconds
            try {
                LOGGER.debug("Attempting to refresh user's SAML assertion.");
                Subject subject = securityManager.getSubject(savedToken);
                LOGGER.debug("Refresh of user assertion successful");
                for (Object principal : subject.getPrincipals()) {
                    if (principal instanceof SecurityAssertion) {
                        SecurityToken token = ((SecurityAssertion) principal).getSecurityToken();
                        SAMLAuthenticationToken samlAuthenticationToken = new SAMLAuthenticationToken((java.security.Principal) savedToken.getPrincipal(), token, savedToken.getRealm());
                        if (LOGGER.isTraceEnabled()) {
                            LOGGER.trace("Setting session token - class: {}  classloader: {}", token.getClass().getName(), token.getClass().getClassLoader());
                        }
                        ((SecurityTokenHolder) session.getAttribute(SecurityConstants.SAML_ASSERTION)).addSecurityToken(savedToken.getRealm(), token);
                        LOGGER.debug("Saved new user assertion to session.");
                        return samlAuthenticationToken;
                    }
                }
            } catch (SecurityServiceException e) {
                LOGGER.debug("Unable to refresh user's SAML assertion. User will log out prematurely.", e);
                session.invalidate();
            } catch (Exception e) {
                LOGGER.info("Unhandled exception occurred.", e);
                session.invalidate();
            }
        }
    }
    return null;
}
Also used : SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) SecurityTokenHolder(ddf.security.common.SecurityTokenHolder) SecurityServiceException(ddf.security.service.SecurityServiceException) InvalidSAMLReceivedException(org.codice.ddf.security.handler.api.InvalidSAMLReceivedException) SecurityAssertion(ddf.security.assertion.SecurityAssertion) SAMLAuthenticationToken(org.codice.ddf.security.handler.api.SAMLAuthenticationToken) Subject(ddf.security.Subject) ServletException(javax.servlet.ServletException) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) SignatureException(java.security.SignatureException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) SecurityServiceException(ddf.security.service.SecurityServiceException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) InvalidSAMLReceivedException(org.codice.ddf.security.handler.api.InvalidSAMLReceivedException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) NoSuchProviderException(java.security.NoSuchProviderException) SecurityAssertionImpl(ddf.security.assertion.impl.SecurityAssertionImpl)

Example 79 with Subject

use of ddf.security.Subject in project ddf by codice.

the class LoginFilter method handleAuthenticationToken.

private Subject handleAuthenticationToken(HttpServletRequest httpRequest, BaseAuthenticationToken token) throws ServletException {
    Subject subject;
    HttpSession session = sessionFactory.getOrCreateSession(httpRequest);
    //if we already have an assertion inside the session and it has not expired, then use that instead
    SecurityToken sessionToken = getSecurityToken(session, token.getRealm());
    if (sessionToken == null) {
        /*
             * The user didn't have a SAML token from a previous authentication, but they do have the
             * credentials to log in - perform that action here.
             */
        try {
            // login with the specified authentication credentials (AuthenticationToken)
            subject = securityManager.getSubject(token);
            for (Object principal : subject.getPrincipals().asList()) {
                if (principal instanceof SecurityAssertion) {
                    if (LOGGER.isTraceEnabled()) {
                        Element samlToken = ((SecurityAssertion) principal).getSecurityToken().getToken();
                        LOGGER.trace("SAML Assertion returned: {}", XMLUtils.prettyFormat(samlToken));
                    }
                    SecurityToken securityToken = ((SecurityAssertion) principal).getSecurityToken();
                    addSamlToSession(httpRequest, token.getRealm(), securityToken);
                }
            }
        } catch (SecurityServiceException e) {
            LOGGER.debug("Unable to get subject from auth request.", e);
            throw new ServletException(e);
        }
    } else {
        LOGGER.trace("Creating SAML authentication token with session.");
        SAMLAuthenticationToken samlToken = new SAMLAuthenticationToken(null, session.getId(), token.getRealm());
        return handleAuthenticationToken(httpRequest, samlToken);
    }
    return subject;
}
Also used : SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) ServletException(javax.servlet.ServletException) SecurityServiceException(ddf.security.service.SecurityServiceException) HttpSession(javax.servlet.http.HttpSession) Element(org.w3c.dom.Element) SecurityAssertion(ddf.security.assertion.SecurityAssertion) SAMLAuthenticationToken(org.codice.ddf.security.handler.api.SAMLAuthenticationToken) Subject(ddf.security.Subject)

Example 80 with Subject

use of ddf.security.Subject 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)

Aggregations

Subject (ddf.security.Subject)94 Test (org.junit.Test)47 SecurityAssertion (ddf.security.assertion.SecurityAssertion)23 SecurityToken (org.apache.cxf.ws.security.tokenstore.SecurityToken)23 HashMap (java.util.HashMap)20 Metacard (ddf.catalog.data.Metacard)18 SecurityManager (ddf.security.service.SecurityManager)14 IOException (java.io.IOException)14 Serializable (java.io.Serializable)14 CollectionPermission (ddf.security.permission.CollectionPermission)13 ArrayList (java.util.ArrayList)12 Map (java.util.Map)12 CreateRequest (ddf.catalog.operation.CreateRequest)11 CreateRequestImpl (ddf.catalog.operation.impl.CreateRequestImpl)11 UnsupportedQueryException (ddf.catalog.source.UnsupportedQueryException)10 SecurityServiceException (ddf.security.service.SecurityServiceException)10 HashSet (java.util.HashSet)10 PrincipalCollection (org.apache.shiro.subject.PrincipalCollection)9 Before (org.junit.Before)9 HttpServletRequest (javax.servlet.http.HttpServletRequest)8