Search in sources :

Example 6 with SecurityToken

use of org.apache.cxf.ws.security.tokenstore.SecurityToken in project ddf by codice.

the class LoginFilterTest method testExpiredSamlCookie.

@Test(expected = ServletException.class)
public void testExpiredSamlCookie() 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(ddf.security.service.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("/good_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)

Example 7 with SecurityToken

use of org.apache.cxf.ws.security.tokenstore.SecurityToken in project ddf by codice.

the class LoginFilter method addSamlToSession.

/**
     * Adds SAML assertion to HTTP session.
     *
     * @param httpRequest   the http request object for this request
     * @param securityToken the SecurityToken object representing the SAML assertion
     */
private void addSamlToSession(HttpServletRequest httpRequest, String realm, SecurityToken securityToken) {
    if (securityToken == null) {
        LOGGER.debug("Cannot add null security token to session.");
        return;
    }
    HttpSession session = sessionFactory.getOrCreateSession(httpRequest);
    SecurityToken sessionToken = getSecurityToken(session, realm);
    if (sessionToken == null) {
        addSecurityToken(session, realm, securityToken);
    }
    SecurityAssertion securityAssertion = new SecurityAssertionImpl(securityToken);
    SecurityLogger.audit("Added SAML for user [{}] to session [{}]", securityAssertion.getPrincipal().getName(), session.getId());
    int minutes = getExpirationTime();
    //we just want to set this to some non-zero value if the configuration is messed up
    int seconds = 60;
    if (minutes > 0) {
        seconds = minutes * 60;
    }
    session.setMaxInactiveInterval(seconds);
}
Also used : SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) HttpSession(javax.servlet.http.HttpSession) SecurityAssertion(ddf.security.assertion.SecurityAssertion) SecurityAssertionImpl(ddf.security.assertion.impl.SecurityAssertionImpl)

Example 8 with SecurityToken

use of org.apache.cxf.ws.security.tokenstore.SecurityToken in project ddf by codice.

the class IdpEndpoint method determineAuthMethod.

private AuthObj determineAuthMethod(String bodyStr, AuthnRequest authnRequest) {
    XMLStreamReader xmlStreamReader = null;
    try {
        xmlStreamReader = xmlInputFactory.createXMLStreamReader(new StringReader(bodyStr));
    } catch (XMLStreamException e) {
        LOGGER.debug("Unable to parse SOAP message from client.", e);
    }
    SoapMessage soapMessage = new SoapMessage(Soap11.getInstance());
    SAAJInInterceptor.SAAJPreInInterceptor preInInterceptor = new SAAJInInterceptor.SAAJPreInInterceptor();
    soapMessage.setContent(XMLStreamReader.class, xmlStreamReader);
    preInInterceptor.handleMessage(soapMessage);
    SAAJInInterceptor inInterceptor = new SAAJInInterceptor();
    inInterceptor.handleMessage(soapMessage);
    SOAPPart soapMessageContent = (SOAPPart) soapMessage.getContent(Node.class);
    AuthObj authObj = new AuthObj();
    try {
        Iterator soapHeaderElements = soapMessageContent.getEnvelope().getHeader().examineAllHeaderElements();
        while (soapHeaderElements.hasNext()) {
            SOAPHeaderElement soapHeaderElement = (SOAPHeaderElement) soapHeaderElements.next();
            if (soapHeaderElement.getLocalName().equals("Security")) {
                Iterator childElements = soapHeaderElement.getChildElements();
                while (childElements.hasNext()) {
                    Object nextElement = childElements.next();
                    if (nextElement instanceof SOAPElement) {
                        SOAPElement element = (SOAPElement) nextElement;
                        if (element.getLocalName().equals("UsernameToken")) {
                            Iterator usernameTokenElements = element.getChildElements();
                            Object next;
                            while (usernameTokenElements.hasNext()) {
                                if ((next = usernameTokenElements.next()) instanceof Element) {
                                    Element nextEl = (Element) next;
                                    if (nextEl.getLocalName().equals("Username")) {
                                        authObj.username = nextEl.getTextContent();
                                    } else if (nextEl.getLocalName().equals("Password")) {
                                        authObj.password = nextEl.getTextContent();
                                    }
                                }
                            }
                            if (authObj.username != null && authObj.password != null) {
                                authObj.method = USER_PASS;
                                break;
                            }
                        } else if (element.getLocalName().equals("Assertion") && element.getNamespaceURI().equals("urn:oasis:names:tc:SAML:2.0:assertion")) {
                            authObj.assertion = new SecurityToken(element.getAttribute("ID"), element, null, null);
                            authObj.method = SAML;
                            break;
                        }
                    }
                }
            }
        }
    } catch (SOAPException e) {
        LOGGER.debug("Unable to parse SOAP message.", e);
    }
    RequestedAuthnContext requestedAuthnContext = authnRequest.getRequestedAuthnContext();
    boolean requestingPki = false;
    boolean requestingUp = false;
    if (requestedAuthnContext != null) {
        List<AuthnContextClassRef> authnContextClassRefs = requestedAuthnContext.getAuthnContextClassRefs();
        for (AuthnContextClassRef authnContextClassRef : authnContextClassRefs) {
            String authnContextClassRefStr = authnContextClassRef.getAuthnContextClassRef();
            if (SAML2Constants.AUTH_CONTEXT_CLASS_REF_X509.equals(authnContextClassRefStr) || SAML2Constants.AUTH_CONTEXT_CLASS_REF_SMARTCARD_PKI.equals(authnContextClassRefStr) || SAML2Constants.AUTH_CONTEXT_CLASS_REF_SOFTWARE_PKI.equals(authnContextClassRefStr) || SAML2Constants.AUTH_CONTEXT_CLASS_REF_SPKI.equals(authnContextClassRefStr) || SAML2Constants.AUTH_CONTEXT_CLASS_REF_TLS_CLIENT.equals(authnContextClassRefStr)) {
                requestingPki = true;
            } else if (SAML2Constants.AUTH_CONTEXT_CLASS_REF_PASSWORD.equals(authnContextClassRefStr) || SAML2Constants.AUTH_CONTEXT_CLASS_REF_PASSWORD_PROTECTED_TRANSPORT.equals(authnContextClassRefStr)) {
                requestingUp = true;
            }
        }
    } else {
        //The requested auth context isn't required so we don't know what they want... just set both to true
        requestingPki = true;
        requestingUp = true;
    }
    if (requestingUp && authObj.method != null && authObj.method.equals(USER_PASS)) {
        LOGGER.trace("Found UsernameToken and correct AuthnContextClassRef");
        return authObj;
    } else if (requestingPki && authObj.method == null) {
        LOGGER.trace("Found no token, but client requested PKI AuthnContextClassRef");
        authObj.method = PKI;
        return authObj;
    } else if (authObj.method == null) {
        LOGGER.debug("No authentication tokens found for the current request and the client did not request PKI authentication");
    }
    return authObj;
}
Also used : SOAPHeaderElement(javax.xml.soap.SOAPHeaderElement) XMLStreamReader(javax.xml.stream.XMLStreamReader) Node(org.w3c.dom.Node) SOAPElement(javax.xml.soap.SOAPElement) SOAPHeaderElement(javax.xml.soap.SOAPHeaderElement) Element(org.w3c.dom.Element) AuthnContextClassRef(org.opensaml.saml.saml2.core.AuthnContextClassRef) SoapMessage(org.apache.cxf.binding.soap.SoapMessage) SAAJInInterceptor(org.apache.cxf.binding.soap.saaj.SAAJInInterceptor) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) RequestedAuthnContext(org.opensaml.saml.saml2.core.RequestedAuthnContext) XMLStreamException(javax.xml.stream.XMLStreamException) SOAPException(javax.xml.soap.SOAPException) StringReader(java.io.StringReader) SOAPPart(javax.xml.soap.SOAPPart) Iterator(java.util.Iterator) SOAPElement(javax.xml.soap.SOAPElement) SignableSAMLObject(org.opensaml.saml.common.SignableSAMLObject) SignableXMLObject(org.opensaml.xmlsec.signature.SignableXMLObject) XMLObject(org.opensaml.core.xml.XMLObject)

Example 9 with SecurityToken

use of org.apache.cxf.ws.security.tokenstore.SecurityToken in project ddf by codice.

the class IdpEndpoint method handleLogin.

protected org.opensaml.saml.saml2.core.Response handleLogin(AuthnRequest authnRequest, String authMethod, HttpServletRequest request, AuthObj authObj, boolean passive, boolean hasCookie) throws SecurityServiceException, WSSecurityException, SimpleSign.SignatureException, ConstraintViolationException {
    LOGGER.debug("Performing login for user. passive: {}, cookie: {}", passive, hasCookie);
    BaseAuthenticationToken token = null;
    request.setAttribute(ContextPolicy.ACTIVE_REALM, BaseAuthenticationToken.ALL_REALM);
    if (PKI.equals(authMethod)) {
        LOGGER.debug("Logging user in via PKI.");
        PKIHandler pkiHandler = new PKIHandler();
        pkiHandler.setTokenFactory(tokenFactory);
        try {
            HandlerResult handlerResult = pkiHandler.getNormalizedToken(request, null, null, false);
            if (handlerResult.getStatus().equals(HandlerResult.Status.COMPLETED)) {
                token = handlerResult.getToken();
            }
        } catch (ServletException e) {
            LOGGER.info("Encountered an exception while checking for PKI auth info.", e);
        }
    } else if (USER_PASS.equals(authMethod)) {
        LOGGER.debug("Logging user in via BASIC auth.");
        if (authObj != null && authObj.username != null && authObj.password != null) {
            token = new UPAuthenticationToken(authObj.username, authObj.password, BaseAuthenticationToken.ALL_REALM);
        } else {
            BasicAuthenticationHandler basicAuthenticationHandler = new BasicAuthenticationHandler();
            HandlerResult handlerResult = basicAuthenticationHandler.getNormalizedToken(request, null, null, false);
            if (handlerResult.getStatus().equals(HandlerResult.Status.COMPLETED)) {
                token = handlerResult.getToken();
            }
        }
    } else if (SAML.equals(authMethod)) {
        LOGGER.debug("Logging user in via SAML assertion.");
        token = new SAMLAuthenticationToken(null, authObj.assertion, BaseAuthenticationToken.ALL_REALM);
    } else if (GUEST.equals(authMethod) && guestAccess) {
        LOGGER.debug("Logging user in as Guest.");
        token = new GuestAuthenticationToken(BaseAuthenticationToken.ALL_REALM, request.getRemoteAddr());
    } else {
        throw new IllegalArgumentException("Auth method is not supported.");
    }
    org.w3c.dom.Element samlToken = null;
    String statusCode;
    if (hasCookie) {
        samlToken = getSamlAssertion(request);
        statusCode = StatusCode.SUCCESS;
    } else {
        try {
            statusCode = StatusCode.AUTHN_FAILED;
            Subject subject = securityManager.getSubject(token);
            for (Object principal : subject.getPrincipals().asList()) {
                if (principal instanceof SecurityAssertion) {
                    SecurityToken securityToken = ((SecurityAssertion) principal).getSecurityToken();
                    samlToken = securityToken.getToken();
                }
            }
            if (samlToken != null) {
                statusCode = StatusCode.SUCCESS;
            }
        } catch (SecurityServiceException e) {
            if (!passive) {
                throw e;
            } else {
                statusCode = StatusCode.AUTHN_FAILED;
            }
        }
    }
    LOGGER.debug("User log in successful.");
    return SamlProtocol.createResponse(SamlProtocol.createIssuer(SystemBaseUrl.constructUrl("/idp/login", true)), SamlProtocol.createStatus(statusCode), authnRequest.getID(), samlToken);
}
Also used : SecurityServiceException(ddf.security.service.SecurityServiceException) GuestAuthenticationToken(org.codice.ddf.security.handler.api.GuestAuthenticationToken) PKIHandler(org.codice.ddf.security.handler.pki.PKIHandler) HandlerResult(org.codice.ddf.security.handler.api.HandlerResult) SecurityAssertion(ddf.security.assertion.SecurityAssertion) SAMLAuthenticationToken(org.codice.ddf.security.handler.api.SAMLAuthenticationToken) Subject(ddf.security.Subject) ServletException(javax.servlet.ServletException) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) Element(org.w3c.dom.Element) BaseAuthenticationToken(org.codice.ddf.security.handler.api.BaseAuthenticationToken) UPAuthenticationToken(org.codice.ddf.security.handler.api.UPAuthenticationToken) BasicAuthenticationHandler(org.codice.ddf.security.handler.basic.BasicAuthenticationHandler) SignableSAMLObject(org.opensaml.saml.common.SignableSAMLObject) SignableXMLObject(org.opensaml.xmlsec.signature.SignableXMLObject) XMLObject(org.opensaml.core.xml.XMLObject)

Example 10 with SecurityToken

use of org.apache.cxf.ws.security.tokenstore.SecurityToken in project ddf by codice.

the class IdpEndpointTest method setup.

@Before
public void setup() throws IOException, SecurityServiceException, ParserConfigurationException, SAXException {
    System.setProperty("org.codice.ddf.system.hostname", "localhost");
    System.setProperty("javax.net.ssl.keyStorePassword", "changeit");
    File jksFile = temporaryFolder.newFile("serverKeystore.jks");
    FileOutputStream jksOutStream = new FileOutputStream(jksFile);
    InputStream jksStream = IdpEndpointTest.class.getResourceAsStream("/serverKeystore.jks");
    IOUtils.copy(jksStream, jksOutStream);
    IOUtils.closeQuietly(jksStream);
    IOUtils.closeQuietly(jksOutStream);
    File signatureFile = temporaryFolder.newFile("signature.properties");
    FileOutputStream signatureOutStream = new FileOutputStream(signatureFile);
    InputStream signatureStream = IdpEndpointTest.class.getResourceAsStream("/signature.properties");
    IOUtils.copy(signatureStream, signatureOutStream);
    IOUtils.closeQuietly(signatureStream);
    IOUtils.closeQuietly(signatureOutStream);
    File encryptionFile = temporaryFolder.newFile("encryption.properties");
    FileOutputStream encryptionOutStream = new FileOutputStream(encryptionFile);
    InputStream encryptionStream = IdpEndpointTest.class.getResourceAsStream("/encryption.properties");
    IOUtils.copy(encryptionStream, encryptionOutStream);
    IOUtils.closeQuietly(encryptionStream);
    IOUtils.closeQuietly(encryptionOutStream);
    EncryptionService encryptionService = mock(EncryptionService.class);
    when(encryptionService.decrypt(anyString())).thenReturn("changeit");
    when(encryptionService.encrypt(anyString())).thenReturn("changeit");
    SecurityManager securityManager = mock(SecurityManager.class);
    Subject subject = mock(Subject.class);
    PrincipalCollection principalCollection = mock(PrincipalCollection.class);
    SecurityAssertion securityAssertion = mock(SecurityAssertion.class);
    SecurityToken securityToken = mock(SecurityToken.class);
    when(subject.getPrincipals()).thenReturn(principalCollection);
    when(principalCollection.asList()).thenReturn(Collections.singletonList(securityAssertion));
    when(securityAssertion.getSecurityToken()).thenReturn(securityToken);
    when(securityToken.getToken()).thenReturn(readDocument("/saml.xml").getDocumentElement());
    when(securityManager.getSubject(anyObject())).thenReturn(subject);
    System.setProperty("javax.net.ssl.keyStore", jksFile.getAbsolutePath());
    idpEndpoint = new IdpEndpoint(signatureFile.getAbsolutePath(), encryptionFile.getAbsolutePath(), encryptionService);
    idpEndpoint.setStrictSignature(true);
    idpEndpoint.init();
    idpEndpoint.setSpMetadata(Collections.singletonList(spMetadata));
    idpEndpoint.setSecurityManager(securityManager);
    PKIAuthenticationTokenFactory pkiAuthenticationTokenFactory = new PKIAuthenticationTokenFactory();
    pkiAuthenticationTokenFactory.setSignaturePropertiesPath(signatureFile.getAbsolutePath());
    pkiAuthenticationTokenFactory.init();
    idpEndpoint.setTokenFactory(pkiAuthenticationTokenFactory);
    idpEndpoint.cookieCache.cacheSamlAssertion("1", readDocument("/saml.xml").getDocumentElement());
    idpEndpoint.setExpirationTime(30);
    relayState = "ef95c04b-6c05-4d12-b65f-dd32fed8811e";
    requestCertificateAttributeName = "javax.servlet.request.X509Certificate";
    requestURL = new StringBuffer("https://www.example.com");
    samlConditionDateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
    signature = authNRequestGetSignature;
    signatureAlgorithm = "http://www.w3.org/2000/09/xmldsig#rsa-sha1";
    ssoSAMLResponse = "https://localhost:8993/services/saml/sso?SAMLResponse=";
}
Also used : SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) SecurityManager(ddf.security.service.SecurityManager) PKIAuthenticationTokenFactory(org.codice.ddf.security.handler.api.PKIAuthenticationTokenFactory) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) EncryptionService(ddf.security.encryption.EncryptionService) FileOutputStream(java.io.FileOutputStream) PrincipalCollection(org.apache.shiro.subject.PrincipalCollection) SecurityAssertion(ddf.security.assertion.SecurityAssertion) File(java.io.File) Subject(ddf.security.Subject) Before(org.junit.Before)

Aggregations

SecurityToken (org.apache.cxf.ws.security.tokenstore.SecurityToken)187 Element (org.w3c.dom.Element)57 Test (org.junit.Test)47 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)35 Subject (ddf.security.Subject)32 SamlAssertionWrapper (org.apache.wss4j.common.saml.SamlAssertionWrapper)28 SecurityAssertion (ddf.security.assertion.SecurityAssertion)27 QName (javax.xml.namespace.QName)26 Fault (org.apache.cxf.interceptor.Fault)23 SecurityManager (ddf.security.service.SecurityManager)22 TokenStoreException (org.apache.cxf.ws.security.tokenstore.TokenStoreException)18 TokenStore (org.apache.cxf.ws.security.tokenstore.TokenStore)17 SOAPException (javax.xml.soap.SOAPException)16 Message (org.apache.cxf.message.Message)16 WSSecurityEngineResult (org.apache.wss4j.dom.engine.WSSecurityEngineResult)16 IssuedToken (org.apache.wss4j.policy.model.IssuedToken)15 CollectionPermission (ddf.security.permission.CollectionPermission)14 Bus (org.apache.cxf.Bus)14 Document (org.w3c.dom.Document)14 ArrayList (java.util.ArrayList)13