Search in sources :

Example 1 with SecurityAssertion

use of ddf.security.assertion.SecurityAssertion 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 2 with SecurityAssertion

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

Example 3 with SecurityAssertion

use of ddf.security.assertion.SecurityAssertion in project ddf by codice.

the class IdpEndpointTest method testPassiveLoginPkiUnsupported.

@Test
public void testPassiveLoginPkiUnsupported() throws SecurityServiceException, WSSecurityException, CertificateEncodingException, IOException {
    String samlRequest = authNRequestPassivePkiGet;
    HttpServletRequest request = mock(HttpServletRequest.class);
    X509Certificate x509Certificate = mock(X509Certificate.class);
    Subject subject = mock(Subject.class);
    PrincipalCollection principalCollection = mock(PrincipalCollection.class);
    SecurityAssertion securityAssertion = mock(SecurityAssertion.class);
    SecurityToken securityToken = mock(SecurityToken.class);
    SecurityManager securityManager = mock(SecurityManager.class);
    when(subject.getPrincipals()).thenReturn(principalCollection);
    when(principalCollection.asList()).thenReturn(Collections.singletonList(securityAssertion));
    when(securityAssertion.getSecurityToken()).thenReturn(securityToken);
    //this mock element is what will cause the signature error
    when(securityToken.getToken()).thenReturn(mock(Element.class));
    when(securityManager.getSubject(anyObject())).thenReturn(subject);
    idpEndpoint.setSecurityManager(securityManager);
    idpEndpoint.setStrictSignature(false);
    when(request.isSecure()).thenReturn(true);
    when(request.getRequestURL()).thenReturn(requestURL);
    when(request.getAttribute(ContextPolicy.ACTIVE_REALM)).thenReturn("*");
    //dummy cert
    when((X509Certificate[]) request.getAttribute(requestCertificateAttributeName)).thenReturn(new X509Certificate[] { x509Certificate });
    when(x509Certificate.getEncoded()).thenReturn(new byte[48]);
    Response response = idpEndpoint.showGetLogin(samlRequest, relayState, signatureAlgorithm, signature, request);
    String responseStr = StringUtils.substringBetween(response.getEntity().toString(), "SAMLResponse=", "&RelayState");
    responseStr = URLDecoder.decode(responseStr, "UTF-8");
    responseStr = RestSecurity.inflateBase64(responseStr);
    //the only cookie that should exist is the "1" cookie so "2" should send us to the login webapp
    assertThat(responseStr, containsString("status:RequestUnsupported"));
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) Response(javax.ws.rs.core.Response) SecurityManager(ddf.security.service.SecurityManager) Element(org.w3c.dom.Element) PrincipalCollection(org.apache.shiro.subject.PrincipalCollection) Matchers.containsString(org.hamcrest.Matchers.containsString) Matchers.anyString(org.mockito.Matchers.anyString) SecurityAssertion(ddf.security.assertion.SecurityAssertion) X509Certificate(java.security.cert.X509Certificate) Subject(ddf.security.Subject) Test(org.junit.Test)

Example 4 with SecurityAssertion

use of ddf.security.assertion.SecurityAssertion in project ddf by codice.

the class SecurityTest method testTokenAboutToExpire.

@Test
public void testTokenAboutToExpire() throws Exception {
    Subject subject = mock(Subject.class);
    SecurityAssertion assertion = mock(SecurityAssertion.class);
    PrincipalCollection pc = mock(PrincipalCollection.class);
    SecurityToken st = mock(SecurityToken.class);
    when(st.isAboutToExpire(anyLong())).thenReturn(true);
    assertThat(security.tokenAboutToExpire(null), equalTo(true));
    assertThat(security.tokenAboutToExpire(subject), equalTo(true));
    when(subject.getPrincipals()).thenReturn(pc);
    assertThat(security.tokenAboutToExpire(subject), equalTo(true));
    when(pc.oneByType(any(Class.class))).thenReturn(assertion);
    when(assertion.getSecurityToken()).thenReturn(st);
    assertThat(security.tokenAboutToExpire(subject), equalTo(true));
    when(st.isAboutToExpire(anyLong())).thenReturn(false);
    assertThat(security.tokenAboutToExpire(subject), equalTo(false));
}
Also used : SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) PrincipalCollection(org.apache.shiro.subject.PrincipalCollection) SecurityAssertion(ddf.security.assertion.SecurityAssertion) Subject(ddf.security.Subject) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 5 with SecurityAssertion

use of ddf.security.assertion.SecurityAssertion in project ddf by codice.

the class RestSecurityTest method testSetSubjectOnClient.

@Test
public void testSetSubjectOnClient() throws Exception {
    Element samlToken = readDocument("/saml.xml").getDocumentElement();
    Subject subject = mock(Subject.class);
    SecurityAssertion assertion = mock(SecurityAssertion.class);
    SecurityToken token = new SecurityToken(UUID.randomUUID().toString(), samlToken, new Date(), new Date());
    when(assertion.getSecurityToken()).thenReturn(token);
    when(subject.getPrincipals()).thenReturn(new SimplePrincipalCollection(assertion, "sts"));
    WebClient client = WebClient.create("https://example.org");
    RestSecurity.setSubjectOnClient(subject, client);
    assertNotNull(client.getHeaders().get(RestSecurity.AUTH_HEADER));
    ArrayList headers = (ArrayList) client.getHeaders().get(RestSecurity.AUTH_HEADER);
    boolean containsSaml = false;
    for (Object header : headers) {
        if (StringUtils.contains(header.toString(), RestSecurity.SAML_HEADER_PREFIX)) {
            containsSaml = true;
        }
    }
    assertTrue(containsSaml);
}
Also used : SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) SimplePrincipalCollection(org.apache.shiro.subject.SimplePrincipalCollection) SecurityAssertion(ddf.security.assertion.SecurityAssertion) WebClient(org.apache.cxf.jaxrs.client.WebClient) Subject(ddf.security.Subject) Date(java.util.Date) Test(org.junit.Test)

Aggregations

SecurityAssertion (ddf.security.assertion.SecurityAssertion)35 Subject (ddf.security.Subject)23 SecurityToken (org.apache.cxf.ws.security.tokenstore.SecurityToken)23 Test (org.junit.Test)14 SecurityManager (ddf.security.service.SecurityManager)11 PrincipalCollection (org.apache.shiro.subject.PrincipalCollection)11 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)9 CollectionPermission (ddf.security.permission.CollectionPermission)8 Message (org.apache.cxf.message.Message)8 SecurityServiceException (ddf.security.service.SecurityServiceException)6 Exchange (org.apache.cxf.message.Exchange)6 BindingOperationInfo (org.apache.cxf.service.model.BindingOperationInfo)6 Element (org.w3c.dom.Element)6 SecurityAssertionImpl (ddf.security.assertion.impl.SecurityAssertionImpl)5 Principal (java.security.Principal)5 HttpSession (javax.servlet.http.HttpSession)5 SecurityTokenHolder (ddf.security.common.SecurityTokenHolder)4 HttpServletRequest (javax.servlet.http.HttpServletRequest)4 QName (javax.xml.namespace.QName)4 SimplePrincipalCollection (org.apache.shiro.subject.SimplePrincipalCollection)4