Search in sources :

Example 1 with SamlAssertionWrapper

use of org.apache.wss4j.common.saml.SamlAssertionWrapper in project ddf by codice.

the class SAMLAssertionHandlerTest method testGetNormalizedTokenSuccessWithHeader.

/**
     * This test ensures the proper functionality of SAMLAssertionHandler's
     * method, getNormalizedToken(), when given a valid HttpServletRequest.
     */
@Test
public void testGetNormalizedTokenSuccessWithHeader() throws Exception {
    SAMLAssertionHandler handler = new SAMLAssertionHandler();
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);
    FilterChain chain = mock(FilterChain.class);
    Element assertion = readDocument("/saml.xml").getDocumentElement();
    String assertionId = assertion.getAttributeNodeNS(null, "ID").getNodeValue();
    SecurityToken samlToken = new SecurityToken(assertionId, assertion, null);
    SamlAssertionWrapper wrappedAssertion = new SamlAssertionWrapper(samlToken.getToken());
    String saml = wrappedAssertion.assertionToString();
    doReturn("SAML " + RestSecurity.deflateAndBase64Encode(saml)).when(request).getHeader(SecurityConstants.SAML_HEADER_NAME);
    HandlerResult result = handler.getNormalizedToken(request, response, chain, true);
    assertNotNull(result);
    assertEquals(HandlerResult.Status.COMPLETED, result.getStatus());
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) FilterChain(javax.servlet.FilterChain) Element(org.w3c.dom.Element) HttpServletResponse(javax.servlet.http.HttpServletResponse) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) HandlerResult(org.codice.ddf.security.handler.api.HandlerResult) Test(org.junit.Test)

Example 2 with SamlAssertionWrapper

use of org.apache.wss4j.common.saml.SamlAssertionWrapper in project ddf by codice.

the class SAMLAssertionHandlerTest method testGetNormalizedTokenSuccessWithCookie.

/**
     * This test ensures the proper functionality of SAMLAssertionHandler's
     * method, getNormalizedToken(), when given a valid HttpServletRequest.
     * Uses legacy SAML cookie
     */
@Test
public void testGetNormalizedTokenSuccessWithCookie() throws Exception {
    SAMLAssertionHandler handler = new SAMLAssertionHandler();
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);
    FilterChain chain = mock(FilterChain.class);
    Element assertion = readDocument("/saml.xml").getDocumentElement();
    String assertionId = assertion.getAttributeNodeNS(null, "ID").getNodeValue();
    SecurityToken samlToken = new SecurityToken(assertionId, assertion, null);
    SamlAssertionWrapper wrappedAssertion = new SamlAssertionWrapper(samlToken.getToken());
    String saml = wrappedAssertion.assertionToString();
    Cookie cookie = new Cookie(SecurityConstants.SAML_COOKIE_NAME, RestSecurity.deflateAndBase64Encode(saml));
    when(request.getCookies()).thenReturn(new Cookie[] { cookie });
    HandlerResult result = handler.getNormalizedToken(request, response, chain, true);
    assertNotNull(result);
    assertEquals(HandlerResult.Status.COMPLETED, result.getStatus());
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) Cookie(javax.servlet.http.Cookie) FilterChain(javax.servlet.FilterChain) Element(org.w3c.dom.Element) HttpServletResponse(javax.servlet.http.HttpServletResponse) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) HandlerResult(org.codice.ddf.security.handler.api.HandlerResult) Test(org.junit.Test)

Example 3 with SamlAssertionWrapper

use of org.apache.wss4j.common.saml.SamlAssertionWrapper in project ddf by codice.

the class SecurityAssertionStore method getSecurityAssertion.

/**
     * Return the SecurityAssertion wrapper associated with the provided message
     *
     * @param message Message
     * @return SecurityAssertion
     */
public static SecurityAssertion getSecurityAssertion(Message message) {
    if (message != null) {
        TokenStore tokenStore = getTokenStore(message);
        Principal principal = null;
        SecurityContext context = message.get(SecurityContext.class);
        if (context != null) {
            principal = context.getUserPrincipal();
        }
        if (!(principal instanceof SAMLTokenPrincipal)) {
            // Try to find the SAMLTokenPrincipal if it exists
            List<?> wsResults = List.class.cast(message.get(WSHandlerConstants.RECV_RESULTS));
            if (wsResults != null) {
                for (Object wsResult : wsResults) {
                    if (wsResult instanceof WSHandlerResult) {
                        List<WSSecurityEngineResult> wsseResults = ((WSHandlerResult) wsResult).getResults();
                        for (WSSecurityEngineResult wsseResult : wsseResults) {
                            Object principalResult = wsseResult.get(WSSecurityEngineResult.TAG_PRINCIPAL);
                            if (principalResult instanceof SAMLTokenPrincipal) {
                                principal = (SAMLTokenPrincipal) principalResult;
                                break;
                            }
                        }
                    }
                }
            }
        }
        if (tokenStore != null && principal != null && principal instanceof SAMLTokenPrincipal) {
            String id = ((SAMLTokenPrincipal) principal).getId();
            SamlAssertionWrapper samlAssertionWrapper = ((SAMLTokenPrincipal) principal).getToken();
            SecurityToken token = tokenStore.getToken(id);
            if (token == null) {
                if (samlAssertionWrapper.getSaml2().getIssueInstant() != null && samlAssertionWrapper.getSaml2().getConditions() != null && samlAssertionWrapper.getSaml2().getConditions().getNotOnOrAfter() != null) {
                    token = new SecurityToken(id, samlAssertionWrapper.getElement(), samlAssertionWrapper.getSaml2().getIssueInstant().toDate(), samlAssertionWrapper.getSaml2().getConditions().getNotOnOrAfter().toDate());
                } else {
                    // we don't know how long this should last or when it was created, so just
                    // set it to 1 minute
                    // This shouldn't happen unless someone sets up a third party STS with weird
                    // settings.
                    Date date = new Date();
                    token = new SecurityToken(id, samlAssertionWrapper.getElement(), date, new Date(date.getTime() + TimeUnit.MINUTES.toMillis(1)));
                }
                tokenStore.add(token);
            }
            return new SecurityAssertionImpl(token);
        }
    }
    return new SecurityAssertionImpl();
}
Also used : SAMLTokenPrincipal(org.apache.wss4j.common.principal.SAMLTokenPrincipal) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) WSHandlerResult(org.apache.wss4j.dom.handler.WSHandlerResult) WSSecurityEngineResult(org.apache.wss4j.dom.engine.WSSecurityEngineResult) Date(java.util.Date) SecurityAssertionImpl(ddf.security.assertion.impl.SecurityAssertionImpl) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) SecurityContext(org.apache.cxf.security.SecurityContext) TokenStore(org.apache.cxf.ws.security.tokenstore.TokenStore) SAMLTokenPrincipal(org.apache.wss4j.common.principal.SAMLTokenPrincipal) Principal(java.security.Principal)

Example 4 with SamlAssertionWrapper

use of org.apache.wss4j.common.saml.SamlAssertionWrapper 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 5 with SamlAssertionWrapper

use of org.apache.wss4j.common.saml.SamlAssertionWrapper in project ddf by codice.

the class SamlProtocol method createResponse.

public static Response createResponse(Issuer issuer, Status status, String requestId, Element samlAssertion) throws WSSecurityException {
    Response response = responseSAMLObjectBuilder.buildObject();
    response.setIssuer(issuer);
    response.setStatus(status);
    response.setID("_" + UUID.randomUUID().toString());
    response.setIssueInstant(new DateTime());
    response.setInResponseTo(requestId);
    response.setVersion(SAMLVersion.VERSION_20);
    if (samlAssertion != null) {
        SamlAssertionWrapper samlAssertionWrapper = new SamlAssertionWrapper(samlAssertion);
        response.getAssertions().add(samlAssertionWrapper.getSaml2());
    }
    return response;
}
Also used : Response(org.opensaml.saml.saml2.core.Response) LogoutResponse(org.opensaml.saml.saml2.core.LogoutResponse) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) DateTime(org.joda.time.DateTime)

Aggregations

SamlAssertionWrapper (org.apache.wss4j.common.saml.SamlAssertionWrapper)7 SecurityToken (org.apache.cxf.ws.security.tokenstore.SecurityToken)5 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)3 Element (org.w3c.dom.Element)3 FilterChain (javax.servlet.FilterChain)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 WSSecurityEngineResult (org.apache.wss4j.dom.engine.WSSecurityEngineResult)2 HandlerResult (org.codice.ddf.security.handler.api.HandlerResult)2 Test (org.junit.Test)2 Response (org.opensaml.saml.saml2.core.Response)2 Subject (ddf.security.Subject)1 SecurityAssertion (ddf.security.assertion.SecurityAssertion)1 SecurityAssertionImpl (ddf.security.assertion.impl.SecurityAssertionImpl)1 SecurityServiceException (ddf.security.service.SecurityServiceException)1 IOException (java.io.IOException)1 Principal (java.security.Principal)1 X509Certificate (java.security.cert.X509Certificate)1 Date (java.util.Date)1 ServletException (javax.servlet.ServletException)1