Search in sources :

Example 21 with SecurityConstraint

use of org.apache.tomcat.util.descriptor.web.SecurityConstraint in project tomcat by apache.

the class TestRealmBase method testHttpConstraint.

/*
     * This test case covers the special case in section 13.4.1 of the Servlet
     * 3.1 specification for {@link javax.servlet.annotation.HttpConstraint}.
     */
@Test
public void testHttpConstraint() throws IOException {
    // Get the annotation from the test case
    Class<TesterServletSecurity01> clazz = TesterServletSecurity01.class;
    ServletSecurity servletSecurity = clazz.getAnnotation(ServletSecurity.class);
    // Convert the annotation into constraints
    ServletSecurityElement servletSecurityElement = new ServletSecurityElement(servletSecurity);
    SecurityConstraint[] constraints = SecurityConstraint.createConstraints(servletSecurityElement, "/*");
    // Create a separate constraint that covers DELETE
    SecurityConstraint deleteConstraint = new SecurityConstraint();
    deleteConstraint.addAuthRole(ROLE1);
    SecurityCollection deleteCollection = new SecurityCollection();
    deleteCollection.addMethod("DELETE");
    deleteCollection.addPatternDecoded("/*");
    deleteConstraint.addCollection(deleteCollection);
    TesterMapRealm mapRealm = new TesterMapRealm();
    // Set up the mock request and response
    TesterRequest request = new TesterRequest();
    Response response = new TesterResponse();
    Context context = request.getContext();
    context.addSecurityRole(ROLE1);
    context.addSecurityRole(ROLE2);
    request.getMappingData().context = context;
    // Create the principals
    List<String> userRoles1 = new ArrayList<>();
    userRoles1.add(ROLE1);
    GenericPrincipal gp1 = new GenericPrincipal(USER1, PWD, userRoles1);
    List<String> userRoles2 = new ArrayList<>();
    userRoles2.add(ROLE2);
    GenericPrincipal gp2 = new GenericPrincipal(USER2, PWD, userRoles2);
    List<String> userRoles99 = new ArrayList<>();
    GenericPrincipal gp99 = new GenericPrincipal(USER99, PWD, userRoles99);
    // Add the constraints to the context
    for (SecurityConstraint constraint : constraints) {
        context.addConstraint(constraint);
    }
    context.addConstraint(deleteConstraint);
    // All users should be able to perform a GET
    request.setMethod("GET");
    SecurityConstraint[] constraintsGet = mapRealm.findSecurityConstraints(request, context);
    request.setUserPrincipal(null);
    Assert.assertTrue(mapRealm.hasResourcePermission(request, response, constraintsGet, null));
    request.setUserPrincipal(gp1);
    Assert.assertTrue(mapRealm.hasResourcePermission(request, response, constraintsGet, null));
    request.setUserPrincipal(gp2);
    Assert.assertTrue(mapRealm.hasResourcePermission(request, response, constraintsGet, null));
    request.setUserPrincipal(gp99);
    Assert.assertTrue(mapRealm.hasResourcePermission(request, response, constraintsGet, null));
    // Only user1 should be able to perform a POST as only that user has
    // role1.
    request.setMethod("POST");
    SecurityConstraint[] constraintsPost = mapRealm.findSecurityConstraints(request, context);
    request.setUserPrincipal(null);
    Assert.assertFalse(mapRealm.hasResourcePermission(request, response, constraintsPost, null));
    request.setUserPrincipal(gp1);
    Assert.assertTrue(mapRealm.hasResourcePermission(request, response, constraintsPost, null));
    request.setUserPrincipal(gp2);
    Assert.assertFalse(mapRealm.hasResourcePermission(request, response, constraintsPost, null));
    request.setUserPrincipal(gp99);
    Assert.assertFalse(mapRealm.hasResourcePermission(request, response, constraintsPost, null));
    // Only users with application roles (role1 or role2 so user1 or user2)
    // should be able to perform a PUT.
    request.setMethod("PUT");
    SecurityConstraint[] constraintsPut = mapRealm.findSecurityConstraints(request, context);
    request.setUserPrincipal(null);
    Assert.assertFalse(mapRealm.hasResourcePermission(request, response, constraintsPut, null));
    request.setUserPrincipal(gp1);
    Assert.assertTrue(mapRealm.hasResourcePermission(request, response, constraintsPut, null));
    request.setUserPrincipal(gp2);
    Assert.assertTrue(mapRealm.hasResourcePermission(request, response, constraintsPut, null));
    request.setUserPrincipal(gp99);
    Assert.assertFalse(mapRealm.hasResourcePermission(request, response, constraintsPut, null));
    // Any authenticated user should be able to perform a TRACE.
    request.setMethod("TRACE");
    SecurityConstraint[] constraintsTrace = mapRealm.findSecurityConstraints(request, context);
    request.setUserPrincipal(null);
    Assert.assertFalse(mapRealm.hasResourcePermission(request, response, constraintsTrace, null));
    request.setUserPrincipal(gp1);
    Assert.assertTrue(mapRealm.hasResourcePermission(request, response, constraintsTrace, null));
    request.setUserPrincipal(gp2);
    Assert.assertTrue(mapRealm.hasResourcePermission(request, response, constraintsTrace, null));
    request.setUserPrincipal(gp99);
    Assert.assertTrue(mapRealm.hasResourcePermission(request, response, constraintsTrace, null));
    // Only user1 should be able to perform a DELETE as only that user has
    // role1.
    request.setMethod("DELETE");
    SecurityConstraint[] constraintsDelete = mapRealm.findSecurityConstraints(request, context);
    request.setUserPrincipal(null);
    Assert.assertFalse(mapRealm.hasResourcePermission(request, response, constraintsDelete, null));
    request.setUserPrincipal(gp1);
    Assert.assertTrue(mapRealm.hasResourcePermission(request, response, constraintsDelete, null));
    request.setUserPrincipal(gp2);
    Assert.assertFalse(mapRealm.hasResourcePermission(request, response, constraintsDelete, null));
    request.setUserPrincipal(gp99);
    Assert.assertFalse(mapRealm.hasResourcePermission(request, response, constraintsDelete, null));
}
Also used : Context(org.apache.catalina.Context) TesterContext(org.apache.tomcat.unittest.TesterContext) ServletSecurity(javax.servlet.annotation.ServletSecurity) ArrayList(java.util.ArrayList) TesterResponse(org.apache.tomcat.unittest.TesterResponse) ServletSecurityElement(javax.servlet.ServletSecurityElement) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) TesterResponse(org.apache.tomcat.unittest.TesterResponse) Response(org.apache.catalina.connector.Response) TesterMapRealm(org.apache.catalina.startup.TesterMapRealm) TesterRequest(org.apache.tomcat.unittest.TesterRequest) SecurityCollection(org.apache.tomcat.util.descriptor.web.SecurityCollection) Test(org.junit.Test)

Example 22 with SecurityConstraint

use of org.apache.tomcat.util.descriptor.web.SecurityConstraint in project tomcat by apache.

the class TestRealmBase method doRoleTest.

private void doRoleTest(List<String> userRoles, List<String> constraintOneRoles, List<String> constraintTwoRoles, List<String> applicationRoles, boolean expected) throws IOException {
    TesterMapRealm mapRealm = new TesterMapRealm();
    // Configure the security constraints for the resource
    SecurityConstraint constraintOne = new SecurityConstraint();
    if (constraintOneRoles != null) {
        constraintOne.setAuthConstraint(true);
        for (String constraintRole : constraintOneRoles) {
            constraintOne.addAuthRole(constraintRole);
            if (applicationRoles.contains(SecurityConstraint.ROLE_ALL_AUTHENTICATED_USERS)) {
                constraintOne.treatAllAuthenticatedUsersAsApplicationRole();
            }
        }
    }
    SecurityConstraint constraintTwo = new SecurityConstraint();
    if (constraintTwoRoles != null) {
        constraintTwo.setAuthConstraint(true);
        for (String constraintRole : constraintTwoRoles) {
            constraintTwo.addAuthRole(constraintRole);
            if (applicationRoles.contains(SecurityConstraint.ROLE_ALL_AUTHENTICATED_USERS)) {
                constraintTwo.treatAllAuthenticatedUsersAsApplicationRole();
            }
        }
    }
    SecurityConstraint[] constraints = new SecurityConstraint[] { constraintOne, constraintTwo };
    // Set up the mock request and response
    Request request = new Request(null);
    Response response = new TesterResponse();
    Context context = new TesterContext();
    for (String applicationRole : applicationRoles) {
        context.addSecurityRole(applicationRole);
    }
    request.getMappingData().context = context;
    // Configure the users in the Realm
    if (userRoles != null) {
        GenericPrincipal gp = new GenericPrincipal(USER1, PWD, userRoles);
        request.setUserPrincipal(gp);
    }
    // Check if user meets constraints
    boolean result = mapRealm.hasResourcePermission(request, response, constraints, null);
    Assert.assertEquals(Boolean.valueOf(expected), Boolean.valueOf(result));
}
Also used : TesterResponse(org.apache.tomcat.unittest.TesterResponse) Response(org.apache.catalina.connector.Response) Context(org.apache.catalina.Context) TesterContext(org.apache.tomcat.unittest.TesterContext) TesterMapRealm(org.apache.catalina.startup.TesterMapRealm) Request(org.apache.catalina.connector.Request) TesterRequest(org.apache.tomcat.unittest.TesterRequest) TesterResponse(org.apache.tomcat.unittest.TesterResponse) TesterContext(org.apache.tomcat.unittest.TesterContext) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint)

Example 23 with SecurityConstraint

use of org.apache.tomcat.util.descriptor.web.SecurityConstraint in project tomcat by apache.

the class TestRestCsrfPreventionFilter2 method setUpApplication.

private void setUpApplication() throws Exception {
    context = tomcat.addContext(CONTEXT_PATH_LOGIN, System.getProperty("java.io.tmpdir"));
    context.setSessionTimeout(SHORT_SESSION_TIMEOUT_MINS);
    Tomcat.addServlet(context, SERVLET_NAME, new TesterServlet());
    context.addServletMappingDecoded(URI_PROTECTED, SERVLET_NAME);
    FilterDef filterDef = new FilterDef();
    filterDef.setFilterName(FILTER_NAME);
    filterDef.setFilterClass(RestCsrfPreventionFilter.class.getCanonicalName());
    filterDef.addInitParameter(FILTER_INIT_PARAM, REMOVE_CUSTOMER + "," + ADD_CUSTOMER);
    context.addFilterDef(filterDef);
    FilterMap filterMap = new FilterMap();
    filterMap.setFilterName(FILTER_NAME);
    filterMap.addURLPatternDecoded(URI_CSRF_PROTECTED);
    context.addFilterMap(filterMap);
    SecurityCollection collection = new SecurityCollection();
    collection.addPatternDecoded(URI_PROTECTED);
    SecurityConstraint sc = new SecurityConstraint();
    sc.addAuthRole(ROLE);
    sc.addCollection(collection);
    context.addConstraint(sc);
    LoginConfig lc = new LoginConfig();
    lc.setAuthMethod(METHOD);
    context.setLoginConfig(lc);
    AuthenticatorBase basicAuthenticator = new BasicAuthenticator();
    context.getPipeline().addValve(basicAuthenticator);
}
Also used : AuthenticatorBase(org.apache.catalina.authenticator.AuthenticatorBase) FilterDef(org.apache.tomcat.util.descriptor.web.FilterDef) BasicAuthenticator(org.apache.catalina.authenticator.BasicAuthenticator) LoginConfig(org.apache.tomcat.util.descriptor.web.LoginConfig) FilterMap(org.apache.tomcat.util.descriptor.web.FilterMap) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) SecurityCollection(org.apache.tomcat.util.descriptor.web.SecurityCollection)

Example 24 with SecurityConstraint

use of org.apache.tomcat.util.descriptor.web.SecurityConstraint in project tomcat by apache.

the class StandardContext method addServletSecurity.

@Override
public Set<String> addServletSecurity(ServletRegistration.Dynamic registration, ServletSecurityElement servletSecurityElement) {
    Set<String> conflicts = new HashSet<>();
    Collection<String> urlPatterns = registration.getMappings();
    for (String urlPattern : urlPatterns) {
        boolean foundConflict = false;
        SecurityConstraint[] securityConstraints = findConstraints();
        for (SecurityConstraint securityConstraint : securityConstraints) {
            SecurityCollection[] collections = securityConstraint.findCollections();
            for (SecurityCollection collection : collections) {
                if (collection.findPattern(urlPattern)) {
                    // not. It is not permitted to have a mixture
                    if (collection.isFromDescriptor()) {
                        // Skip this pattern
                        foundConflict = true;
                        conflicts.add(urlPattern);
                        break;
                    } else {
                        // Need to overwrite constraint for this pattern
                        collection.removePattern(urlPattern);
                        // If the collection is now empty, remove it
                        if (collection.findPatterns().length == 0) {
                            securityConstraint.removeCollection(collection);
                        }
                    }
                }
            }
            // If the constraint now has no collections - remove it
            if (securityConstraint.findCollections().length == 0) {
                removeConstraint(securityConstraint);
            }
            // once a conflict has been found
            if (foundConflict) {
                break;
            }
        }
        // If the pattern did not conflict, add the new constraint(s).
        if (!foundConflict) {
            SecurityConstraint[] newSecurityConstraints = SecurityConstraint.createConstraints(servletSecurityElement, urlPattern);
            for (SecurityConstraint securityConstraint : newSecurityConstraints) {
                addConstraint(securityConstraint);
            }
            checkConstraintsForUncoveredMethods(newSecurityConstraints);
        }
    }
    return conflicts;
}
Also used : SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) HashSet(java.util.HashSet) SecurityCollection(org.apache.tomcat.util.descriptor.web.SecurityCollection)

Example 25 with SecurityConstraint

use of org.apache.tomcat.util.descriptor.web.SecurityConstraint in project tomcat by apache.

the class StandardContext method addConstraint.

/**
     * Add a security constraint to the set for this web application.
     *
     * @param constraint the new security constraint
     */
@Override
public void addConstraint(SecurityConstraint constraint) {
    // Validate the proposed constraint
    SecurityCollection[] collections = constraint.findCollections();
    for (int i = 0; i < collections.length; i++) {
        String[] patterns = collections[i].findPatterns();
        for (int j = 0; j < patterns.length; j++) {
            patterns[j] = adjustURLPattern(patterns[j]);
            if (!validateURLPattern(patterns[j]))
                throw new IllegalArgumentException(sm.getString("standardContext.securityConstraint.pattern", patterns[j]));
        }
        if (collections[i].findMethods().length > 0 && collections[i].findOmittedMethods().length > 0) {
            throw new IllegalArgumentException(sm.getString("standardContext.securityConstraint.mixHttpMethod"));
        }
    }
    // Add this constraint to the set for our web application
    synchronized (constraintsLock) {
        SecurityConstraint[] results = new SecurityConstraint[constraints.length + 1];
        for (int i = 0; i < constraints.length; i++) results[i] = constraints[i];
        results[constraints.length] = constraint;
        constraints = results;
    }
}
Also used : SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) SecurityCollection(org.apache.tomcat.util.descriptor.web.SecurityCollection)

Aggregations

SecurityConstraint (org.apache.tomcat.util.descriptor.web.SecurityConstraint)32 SecurityCollection (org.apache.tomcat.util.descriptor.web.SecurityCollection)21 LoginConfig (org.apache.tomcat.util.descriptor.web.LoginConfig)13 Context (org.apache.catalina.Context)12 TesterServlet (org.apache.catalina.startup.TesterServlet)5 TesterMapRealm (org.apache.catalina.startup.TesterMapRealm)4 Tomcat (org.apache.catalina.startup.Tomcat)4 Test (org.junit.Test)4 ArrayList (java.util.ArrayList)3 Wrapper (org.apache.catalina.Wrapper)3 BasicAuthenticator (org.apache.catalina.authenticator.BasicAuthenticator)3 SSLAuthenticator (org.apache.catalina.authenticator.SSLAuthenticator)3 StandardContext (org.apache.catalina.core.StandardContext)3 Principal (java.security.Principal)2 Container (org.apache.catalina.Container)2 DigestAuthenticator (org.apache.catalina.authenticator.DigestAuthenticator)2 NonLoginAuthenticator (org.apache.catalina.authenticator.NonLoginAuthenticator)2 Request (org.apache.catalina.connector.Request)2 Response (org.apache.catalina.connector.Response)2 TesterServletEncodeUrl (org.apache.catalina.startup.TesterServletEncodeUrl)2