Search in sources :

Example 26 with Subject

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

the class CommandJobTest method getCommandJob.

private CommandJob getCommandJob() {
    return new CommandJob() {

        @SuppressWarnings("unchecked")
        @Override
        public Subject getSystemSubject() {
            Subject subject = mock(Subject.class);
            when(subject.execute(Matchers.<Callable<Object>>any())).thenAnswer(invocation -> {
                Callable<Object> callable = (Callable<Object>) invocation.getArguments()[0];
                return callable.call();
            });
            return subject;
        }

        @Override
        protected SessionFactory getSessionFactory() {
            return sessionFactory;
        }
    };
}
Also used : Subject(ddf.security.Subject) Callable(java.util.concurrent.Callable)

Example 27 with Subject

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

the class WorkspaceService method getWorkspaces.

@SuppressWarnings("unchecked")
@Listener("/service/workspaces")
public void getWorkspaces(final ServerSession remote, Message message) {
    ServerMessage.Mutable reply = new ServerMessageImpl();
    Map<String, Object> data = message.getDataAsMap();
    Subject subject = (Subject) bayeux.getContext().getRequestAttribute(SecurityConstants.SECURITY_SUBJECT);
    String username = SubjectUtils.getName(subject);
    // No workspaces persisted for a guest user (whose username="")
    if (StringUtils.isNotBlank(username)) {
        if (data == null || data.isEmpty() || data.get("workspaces") == null) {
            List<Map<String, Object>> workspacesList = new ArrayList<Map<String, Object>>();
            try {
                workspacesList = persistentStore.get(PersistentStore.WORKSPACE_TYPE, "user = '" + username + "'");
                if (workspacesList.size() == 1) {
                    // Convert workspace's JSON representation back to nested maps of Map<String, Object>
                    Map<String, Object> workspaces = (Map<String, Object>) workspacesList.get(0);
                    JSONContext.Client jsonContext = new Jackson1JSONContextClient();
                    String json = (String) workspaces.get("workspaces_json_txt");
                    LOGGER.debug("workspaces extracted JSON text:\n {}", json);
                    Map<String, Object> workspacesMap;
                    try {
                        workspacesMap = jsonContext.getParser().parse(new StringReader(json), Map.class);
                        reply.putAll(workspacesMap);
                    } catch (ParseException e) {
                        LOGGER.info("ParseException while trying to convert persisted workspaces's for user {} from JSON", username, e);
                    }
                }
            } catch (PersistenceException e) {
                LOGGER.info("PersistenceException while trying to retrieve persisted workspaces for user {}", username, e);
            }
            reply.put(Search.SUCCESSFUL, true);
            remote.deliver(serverSession, "/service/workspaces", reply);
        } else {
            LOGGER.debug("Persisting workspaces for username = {}", username);
            // Use JSON serializer so that only "data" component is serialized, not entire Message
            JSONContext.Server jsonContext = new Jackson1JSONContextServer();
            String json = jsonContext.getGenerator().generate(data);
            LOGGER.debug("workspaces JSON text:\n {}", json);
            PersistentItem item = new PersistentItem();
            item.addIdProperty(username);
            item.addProperty("user", username);
            item.addProperty("workspaces_json", json);
            try {
                persistentStore.add(PersistentStore.WORKSPACE_TYPE, item);
            } catch (PersistenceException e) {
                LOGGER.info("PersistenceException while trying to persist workspaces for user {}", username, e);
            }
            reply.put(Search.SUCCESSFUL, true);
            remote.deliver(serverSession, "/service/workspaces", reply);
        }
    }
}
Also used : PersistentItem(org.codice.ddf.persistence.PersistentItem) ServerMessage(org.cometd.bayeux.server.ServerMessage) ArrayList(java.util.ArrayList) Subject(ddf.security.Subject) JSONContext(org.cometd.common.JSONContext) ServerMessageImpl(org.cometd.server.ServerMessageImpl) StringReader(java.io.StringReader) PersistenceException(org.codice.ddf.persistence.PersistenceException) ParseException(java.text.ParseException) Jackson1JSONContextServer(org.cometd.server.Jackson1JSONContextServer) Jackson1JSONContextClient(org.cometd.common.Jackson1JSONContextClient) Map(java.util.Map) Listener(org.cometd.annotation.Listener)

Example 28 with Subject

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

the class SearchService method processQuery.

/**
     * Service method called by Cometd when something arrives on the service channel
     *
     * @param remote
     *            - Client session
     * @param message
     *            - JSON message
     */
@Listener("/service/query")
public void processQuery(final ServerSession remote, Message message) {
    ServerMessage.Mutable reply = new ServerMessageImpl();
    Map<String, Object> queryMessage = message.getDataAsMap();
    if (queryMessage != null && queryMessage.containsKey(Search.ID)) {
        bayeux.createChannelIfAbsent("/" + queryMessage.get(Search.ID), new ConfigurableServerChannel.Initializer() {

            public void configureChannel(ConfigurableServerChannel channel) {
                channel.setPersistent(true);
            }
        });
        BayeuxContext context = bayeux.getContext();
        Subject subject = null;
        if (context != null) {
            subject = (Subject) context.getRequestAttribute(SecurityConstants.SECURITY_SUBJECT);
        }
        // kick off the query
        executeQuery(queryMessage, subject);
        reply.put(Search.SUCCESSFUL, true);
        remote.deliver(serverSession, reply);
    } else {
        reply.put(Search.SUCCESSFUL, false);
        reply.put("status", "ERROR: unable to return results, no id in query request");
        remote.deliver(serverSession, reply);
    }
}
Also used : ServerMessageImpl(org.cometd.server.ServerMessageImpl) ServerMessage(org.cometd.bayeux.server.ServerMessage) ConfigurableServerChannel(org.cometd.bayeux.server.ConfigurableServerChannel) BayeuxContext(org.cometd.bayeux.server.BayeuxContext) Subject(ddf.security.Subject) Listener(org.cometd.annotation.Listener)

Example 29 with Subject

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

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

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