Search in sources :

Example 6 with ContextPolicy

use of org.codice.ddf.security.policy.context.ContextPolicy in project ddf by codice.

the class AuthenticationEndpointTest method testMultiRealm.

@Test
public void testMultiRealm() throws SecurityServiceException {
    HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.isSecure()).thenReturn(true);
    ContextPolicy policy = mock(ContextPolicy.class);
    ContextPolicy anotherPolicy = mock(ContextPolicy.class);
    when(policy.getRealm()).thenReturn(REALM);
    when(anotherPolicy.getRealm()).thenReturn("ANOTHER_REALM");
    when(policyManager.getContextPolicy(PATH)).thenReturn(policy);
    when(policyManager.getContextPolicy("/anotherPath")).thenReturn(anotherPolicy);
    mockUser("another", "another", "ANOTHER_REALM");
    authEndpoint.login(request, USER_NAME, PASSWORD, PATH);
    authEndpoint.login(request, "another", "another", "/anotherPath");
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ContextPolicy(org.codice.ddf.security.policy.context.ContextPolicy) Test(org.junit.Test)

Example 7 with ContextPolicy

use of org.codice.ddf.security.policy.context.ContextPolicy in project ddf by codice.

the class WebSSOFilterTest method testDoFilterWhiteListed.

@Test
public void testDoFilterWhiteListed() throws IOException, AuthenticationException {
    ContextPolicy testPolicy = mock(ContextPolicy.class);
    ContextPolicyManager policyManager = mock(ContextPolicyManager.class);
    when(policyManager.getContextPolicy(anyString())).thenReturn(testPolicy);
    when(policyManager.isWhiteListed(anyString())).thenReturn(true);
    when(policyManager.getSessionAccess()).thenReturn(false);
    WebSSOFilter filter = new WebSSOFilter();
    // set handlers
    AuthenticationHandler handler1 = mock(AuthenticationHandler.class);
    HandlerResult noActionResult = mock(HandlerResult.class);
    when(noActionResult.getStatus()).thenReturn(Status.NO_ACTION);
    HandlerResult completedResult = mock(HandlerResult.class);
    when(completedResult.getStatus()).thenReturn(Status.COMPLETED);
    when(completedResult.getToken()).thenReturn(null);
    when(handler1.getNormalizedToken(any(ServletRequest.class), any(ServletResponse.class), any(SecurityFilterChain.class), eq(true))).thenReturn(completedResult);
    when(handler1.getNormalizedToken(any(ServletRequest.class), any(ServletResponse.class), any(SecurityFilterChain.class), eq(false))).thenReturn(noActionResult);
    filter.setHandlerList(Collections.singletonList(handler1));
    filter.setContextPolicyManager(policyManager);
    SecurityFilterChain filterChain = mock(SecurityFilterChain.class);
    HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getRequestURI()).thenReturn(MOCK_CONTEXT);
    HttpServletResponse response = mock(HttpServletResponse.class);
    filter.doFilter(request, response, filterChain);
    verify(request, times(1)).setAttribute(ContextPolicy.NO_AUTH_POLICY, true);
    verify(filterChain).doFilter(request, response);
    verify(handler1, never()).getNormalizedToken(any(HttpServletRequest.class), any(HttpServletResponse.class), any(SecurityFilterChain.class), anyBoolean());
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletResponse(javax.servlet.ServletResponse) SecurityFilterChain(org.codice.ddf.platform.filter.SecurityFilterChain) HttpServletResponse(javax.servlet.http.HttpServletResponse) AuthenticationHandler(org.codice.ddf.security.handler.api.AuthenticationHandler) HandlerResult(org.codice.ddf.security.handler.api.HandlerResult) ContextPolicy(org.codice.ddf.security.policy.context.ContextPolicy) ContextPolicyManager(org.codice.ddf.security.policy.context.ContextPolicyManager) Test(org.junit.Test)

Example 8 with ContextPolicy

use of org.codice.ddf.security.policy.context.ContextPolicy in project ddf by codice.

the class WebSSOFilterTest method testDoFilterSessionStorageDisabled.

@Test
public void testDoFilterSessionStorageDisabled() throws Exception {
    PrincipalCollection principalCollectionMock = mock(PrincipalCollection.class);
    PrincipalHolder principalHolderMock = mock(PrincipalHolder.class);
    when(principalHolderMock.getPrincipals()).thenReturn(principalCollectionMock);
    HttpSession sessionMock = mock(HttpSession.class);
    when(sessionMock.getAttribute(SECURITY_TOKEN_KEY)).thenReturn(principalHolderMock);
    HttpServletRequest requestMock = mock(HttpServletRequest.class);
    when(requestMock.getSession(any(Boolean.class))).thenReturn(sessionMock);
    when(requestMock.getRequestURI()).thenReturn(MOCK_CONTEXT);
    HttpServletResponse responseMock = mock(HttpServletResponse.class);
    ContextPolicyManager policyManager = mock(ContextPolicyManager.class);
    when(policyManager.getSessionAccess()).thenReturn(false);
    when(policyManager.isWhiteListed(MOCK_CONTEXT)).thenReturn(false);
    ContextPolicy testPolicy = mock(ContextPolicy.class);
    when(testPolicy.getAuthenticationMethods()).thenReturn(Collections.singletonList("basic"));
    when(policyManager.getContextPolicy(MOCK_CONTEXT)).thenReturn(testPolicy);
    AuthenticationHandler handlerMock = mock(AuthenticationHandler.class);
    when(handlerMock.getAuthenticationType()).thenReturn("basic");
    HandlerResult completedResult = mock(HandlerResult.class);
    when(completedResult.getStatus()).thenReturn(Status.COMPLETED);
    when(completedResult.getToken()).thenReturn(mock(BaseAuthenticationToken.class));
    when(handlerMock.getNormalizedToken(any(ServletRequest.class), any(ServletResponse.class), any(SecurityFilterChain.class), anyBoolean())).thenReturn(completedResult);
    SecurityFilterChain filterChain = mock(SecurityFilterChain.class);
    WebSSOFilter filter = new WebSSOFilter();
    filter.setContextPolicyManager(policyManager);
    filter.setHandlerList(Collections.singletonList(handlerMock));
    filter.doFilter(requestMock, responseMock, filterChain);
    verify(sessionMock, times(0)).getAttribute(SECURITY_TOKEN_KEY);
    verify(handlerMock, times(1)).getNormalizedToken(any(), any(), any(), anyBoolean());
    verify(requestMock, times(1)).setAttribute(eq(AUTHENTICATION_TOKEN_KEY), any());
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletResponse(javax.servlet.ServletResponse) HttpSession(javax.servlet.http.HttpSession) PrincipalCollection(org.apache.shiro.subject.PrincipalCollection) HttpServletResponse(javax.servlet.http.HttpServletResponse) HandlerResult(org.codice.ddf.security.handler.api.HandlerResult) ContextPolicy(org.codice.ddf.security.policy.context.ContextPolicy) ContextPolicyManager(org.codice.ddf.security.policy.context.ContextPolicyManager) HttpServletRequest(javax.servlet.http.HttpServletRequest) SecurityFilterChain(org.codice.ddf.platform.filter.SecurityFilterChain) BaseAuthenticationToken(org.codice.ddf.security.handler.BaseAuthenticationToken) AuthenticationHandler(org.codice.ddf.security.handler.api.AuthenticationHandler) Mockito.anyBoolean(org.mockito.Mockito.anyBoolean) PrincipalHolder(ddf.security.common.PrincipalHolder) Test(org.junit.Test)

Example 9 with ContextPolicy

use of org.codice.ddf.security.policy.context.ContextPolicy in project ddf by codice.

the class AuthorizationFilter method doFilter.

@SuppressWarnings("PackageAccessibility")
@Override
public void doFilter(ServletRequest request, ServletResponse response, SecurityFilterChain chain) throws IOException, AuthenticationException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    Subject subject = null;
    if (request.getAttribute(ContextPolicy.NO_AUTH_POLICY) != null) {
        LOGGER.debug("NO_AUTH_POLICY header was found, skipping authorization filter.");
        chain.doFilter(request, response);
    } else {
        try {
            subject = SecurityUtils.getSubject();
        } catch (Exception e) {
            LOGGER.debug("Unable to retrieve user from request.", e);
        }
        boolean permitted = true;
        final String path = httpRequest.getRequestURI();
        ContextPolicy policy = contextPolicyManager.getContextPolicy(path);
        CollectionPermission permissions = null;
        if (policy != null && subject != null) {
            permissions = policy.getAllowedAttributePermissions();
            if (!permissions.isEmpty()) {
                permitted = subject.isPermitted(permissions);
            }
        } else {
            LOGGER.warn("Unable to determine policy for path {}. User is not permitted to continue. Check policy configuration!", LogSanitizer.sanitize(path));
            permitted = false;
        }
        if (!permitted) {
            securityLogger.audit("Subject not authorized to view resource {}", path);
            LOGGER.debug("Subject not authorized.");
            returnNotAuthorized(httpResponse);
        } else {
            if (!permissions.isEmpty()) {
                securityLogger.audit("Subject is authorized to view resource {}", path);
            }
            LOGGER.debug("Subject is authorized!");
            chain.doFilter(request, response);
        }
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) CollectionPermission(ddf.security.permission.CollectionPermission) Subject(org.apache.shiro.subject.Subject) IOException(java.io.IOException) AuthenticationException(org.codice.ddf.platform.filter.AuthenticationException) ContextPolicy(org.codice.ddf.security.policy.context.ContextPolicy)

Example 10 with ContextPolicy

use of org.codice.ddf.security.policy.context.ContextPolicy in project ddf by codice.

the class PolicyManager method setPolicies.

/**
 * Initializes the policy store. This method will be called every time the policy attributes
 * change. This will happen after the component has been initialized (see {@link #configure()} and
 * when an update is made to the {@code org.codice.ddf.security.policy.context.impl.PolicyManager}
 * configuration pid. <br>
 * See https://osgi.org/javadoc/r6/cmpn/org/osgi/service/cm/ManagedService.html for more details
 * on how and when this method may be called.
 *
 * @param properties map of properties to use to initialize the policy store. Since there is no
 *     configuration file bound to these properties by default, this map may be {@code null}.
 */
public void setPolicies(Map<String, Object> properties) {
    if (properties == null) {
        LOGGER.debug("setPolicies() called with null properties map. " + "Policy store should have already been initialized so ignoring.");
        LOGGER.debug("Policy Store already contains {} items", policyStore.size());
        return;
    }
    LOGGER.debug("setPolicies called: {}", properties);
    Map<String, ContextPolicy> originalPolicyStore = getPolicyStore();
    setGuestAccess((boolean) properties.get(GUEST_ACCESS));
    setSessionAccess((boolean) properties.get(SESSION_ACCESS));
    String webAuthTypes = (String) properties.get(WEB_AUTH_TYPES);
    String endpointAuthTypes = (String) properties.get(ENDPOINT_AUTH_TYPES);
    String[] attrContexts = (String[]) properties.get(REQ_ATTRS);
    String[] whiteList = (String[]) properties.get(WHITE_LIST);
    if (whiteList != null) {
        setWhiteListContexts(Arrays.asList(whiteList));
    }
    if (webAuthTypes != null && endpointAuthTypes != null && attrContexts != null) {
        Map<String, List<ContextAttributeMapping>> contextToAttr = new HashMap<>();
        List<String> attrContextList = new ArrayList<>();
        Collections.addAll(attrContextList, attrContexts);
        for (String attr : attrContextList) {
            int index = attr.indexOf('=');
            if (index < 1) {
                throw new IllegalArgumentException("Invalid attribute context: " + attr);
            }
            String context = attr.substring(0, index);
            String value = attr.substring(index + 1);
            if (StringUtils.isNotEmpty(context) && value != null) {
                if (value.startsWith("{") && value.endsWith("}")) {
                    if (value.length() == 2) {
                        value = "";
                    } else {
                        value = value.substring(1, value.length() - 1);
                    }
                }
                String[] attributes = value.split(";");
                List<ContextAttributeMapping> attrMaps = new ArrayList<>();
                for (String attribute : attributes) {
                    String[] parts = attribute.split("=");
                    if (parts.length == 2) {
                        attrMaps.add(new DefaultContextAttributeMapping(context, parts[0], parts[1]));
                    }
                }
                contextToAttr.put(context, attrMaps);
            }
        }
        this.contextToAttr = contextToAttr;
        if (contextToAuthFile == null) {
            Map<String, List<String>> contextToAuthMap = new HashMap<>();
            contextToAuthMap.put(ROOT_CONTEXT, Arrays.asList(webAuthTypes.split("\\|")));
            contextToAuthMap.put(SERVICES_CONTEXT, Arrays.asList(endpointAuthTypes.split("\\|")));
            contextToAuthConfig = contextToAuthMap;
            setPolicyStore(contextToAuthMap, contextToAttr);
        } else {
            setPolicyStore(contextToAuthFile, contextToAttr);
        }
    }
    LOGGER.debug("Policy store initialized, now contains {} entries", policyStore.size());
    securityLogger.audit("Policy store changed from:\n{} \nto:\n{}", originalPolicyStore, getPolicyStore());
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) DefaultContextAttributeMapping(org.codice.ddf.security.policy.context.attributes.DefaultContextAttributeMapping) ContextPolicy(org.codice.ddf.security.policy.context.ContextPolicy) ArrayList(java.util.ArrayList) List(java.util.List) ContextAttributeMapping(org.codice.ddf.security.policy.context.attributes.ContextAttributeMapping) DefaultContextAttributeMapping(org.codice.ddf.security.policy.context.attributes.DefaultContextAttributeMapping)

Aggregations

ContextPolicy (org.codice.ddf.security.policy.context.ContextPolicy)29 Test (org.junit.Test)12 HttpServletRequest (javax.servlet.http.HttpServletRequest)11 ContextPolicyManager (org.codice.ddf.security.policy.context.ContextPolicyManager)10 ArrayList (java.util.ArrayList)8 HttpServletResponse (javax.servlet.http.HttpServletResponse)8 AuthenticationHandler (org.codice.ddf.security.handler.api.AuthenticationHandler)6 ServletRequest (javax.servlet.ServletRequest)5 ServletResponse (javax.servlet.ServletResponse)5 SecurityFilterChain (org.codice.ddf.platform.filter.SecurityFilterChain)5 HandlerResult (org.codice.ddf.security.handler.api.HandlerResult)5 CollectionPermission (ddf.security.permission.CollectionPermission)4 HashMap (java.util.HashMap)4 List (java.util.List)4 ContextAttributeMapping (org.codice.ddf.security.policy.context.attributes.ContextAttributeMapping)4 DefaultContextAttributeMapping (org.codice.ddf.security.policy.context.attributes.DefaultContextAttributeMapping)4 Map (java.util.Map)3 HttpSession (javax.servlet.http.HttpSession)3 AuthenticationException (org.codice.ddf.platform.filter.AuthenticationException)3 ImmutableMap (com.google.common.collect.ImmutableMap)2