Search in sources :

Example 11 with SecurityCollection

use of org.apache.catalina.deploy.SecurityCollection in project tomcat70 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.addPattern("/*");
    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.setContext(context);
    // Create the principals
    List<String> userRoles1 = new ArrayList<String>();
    userRoles1.add(ROLE1);
    GenericPrincipal gp1 = new GenericPrincipal(USER1, PWD, userRoles1);
    List<String> userRoles2 = new ArrayList<String>();
    userRoles2.add(ROLE2);
    GenericPrincipal gp2 = new GenericPrincipal(USER2, PWD, userRoles2);
    List<String> userRoles99 = new ArrayList<String>();
    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));
    // 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.catalina.deploy.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.catalina.deploy.SecurityCollection) Test(org.junit.Test)

Example 12 with SecurityCollection

use of org.apache.catalina.deploy.SecurityCollection in project tomcat70 by apache.

the class StandardContext method addConstraint.

/**
 * Add a security constraint to the set for this web application.
 */
@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.catalina.deploy.SecurityConstraint) SecurityConstraint(org.apache.catalina.deploy.SecurityConstraint) SecurityCollection(org.apache.catalina.deploy.SecurityCollection)

Example 13 with SecurityCollection

use of org.apache.catalina.deploy.SecurityCollection in project tomcat70 by apache.

the class StandardContext method addServletSecurity.

@Override
public Set<String> addServletSecurity(ApplicationServletRegistration registration, ServletSecurityElement servletSecurityElement) {
    Set<String> conflicts = new HashSet<String>();
    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);
                    } else {
                        // Need to overwrite constraint for this pattern
                        // so remove every pattern found
                        // TODO spec 13.4.2 appears to say only the
                        // conflicting pattern is overwritten, not the
                        // entire security constraint.
                        removeConstraint(securityConstraint);
                    }
                }
                if (foundConflict) {
                    break;
                }
            }
            if (foundConflict) {
                break;
            }
        }
        // code can add url patterns after calling setSecurity.
        if (!foundConflict) {
            SecurityConstraint[] newSecurityConstraints = SecurityConstraint.createConstraints(servletSecurityElement, urlPattern);
            for (SecurityConstraint securityConstraint : newSecurityConstraints) {
                addConstraint(securityConstraint);
            }
        }
    }
    return conflicts;
}
Also used : SecurityConstraint(org.apache.catalina.deploy.SecurityConstraint) HashSet(java.util.HashSet) SecurityCollection(org.apache.catalina.deploy.SecurityCollection)

Example 14 with SecurityCollection

use of org.apache.catalina.deploy.SecurityCollection in project tomcat70 by apache.

the class RealmBase method findSecurityConstraints.

/**
 * Return the SecurityConstraints configured to guard the request URI for
 * this request, or <code>null</code> if there is no such constraint.
 *
 * @param request Request we are processing
 * @param context Context the Request is mapped to
 */
@Override
public SecurityConstraint[] findSecurityConstraints(Request request, Context context) {
    ArrayList<SecurityConstraint> results = null;
    // Are there any defined security constraints?
    SecurityConstraint[] constraints = context.findConstraints();
    if ((constraints == null) || (constraints.length == 0)) {
        if (log.isDebugEnabled())
            log.debug("  No applicable constraints defined");
        return (null);
    }
    // Check each defined security constraint
    String uri = request.getRequestPathMB().toString();
    // Mapper treats as '/' do the same to prevent NPE
    if (uri == null || uri.length() == 0) {
        uri = "/";
    }
    String method = request.getMethod();
    int i;
    boolean found = false;
    for (i = 0; i < constraints.length; i++) {
        SecurityCollection[] collection = constraints[i].findCollections();
        // See Bugzilla 30624
        if (collection == null) {
            continue;
        }
        if (log.isDebugEnabled()) {
            log.debug("  Checking constraint '" + constraints[i] + "' against " + method + " " + uri + " --> " + constraints[i].included(uri, method));
        }
        for (int j = 0; j < collection.length; j++) {
            String[] patterns = collection[j].findPatterns();
            // See Bugzilla 30624
            if (patterns == null) {
                continue;
            }
            for (int k = 0; k < patterns.length; k++) {
                // Exact match including special case for the context root.
                if (uri.equals(patterns[k]) || patterns[k].length() == 0 && uri.equals("/")) {
                    found = true;
                    if (collection[j].findMethod(method)) {
                        if (results == null) {
                            results = new ArrayList<SecurityConstraint>();
                        }
                        results.add(constraints[i]);
                    }
                }
            }
        }
    }
    if (found) {
        return resultsToArray(results);
    }
    int longest = -1;
    for (i = 0; i < constraints.length; i++) {
        SecurityCollection[] collection = constraints[i].findCollections();
        // See Bugzilla 30624
        if (collection == null) {
            continue;
        }
        if (log.isDebugEnabled()) {
            log.debug("  Checking constraint '" + constraints[i] + "' against " + method + " " + uri + " --> " + constraints[i].included(uri, method));
        }
        for (int j = 0; j < collection.length; j++) {
            String[] patterns = collection[j].findPatterns();
            // See Bugzilla 30624
            if (patterns == null) {
                continue;
            }
            boolean matched = false;
            int length = -1;
            for (int k = 0; k < patterns.length; k++) {
                String pattern = patterns[k];
                if (pattern.startsWith("/") && pattern.endsWith("/*") && pattern.length() >= longest) {
                    if (pattern.length() == 2) {
                        matched = true;
                        length = pattern.length();
                    } else if (pattern.regionMatches(0, uri, 0, pattern.length() - 1) || (pattern.length() - 2 == uri.length() && pattern.regionMatches(0, uri, 0, pattern.length() - 2))) {
                        matched = true;
                        length = pattern.length();
                    }
                }
            }
            if (matched) {
                if (length > longest) {
                    found = false;
                    if (results != null) {
                        results.clear();
                    }
                    longest = length;
                }
                if (collection[j].findMethod(method)) {
                    found = true;
                    if (results == null) {
                        results = new ArrayList<SecurityConstraint>();
                    }
                    results.add(constraints[i]);
                }
            }
        }
    }
    if (found) {
        return resultsToArray(results);
    }
    for (i = 0; i < constraints.length; i++) {
        SecurityCollection[] collection = constraints[i].findCollections();
        // See Bugzilla 30624
        if (collection == null) {
            continue;
        }
        if (log.isDebugEnabled()) {
            log.debug("  Checking constraint '" + constraints[i] + "' against " + method + " " + uri + " --> " + constraints[i].included(uri, method));
        }
        boolean matched = false;
        int pos = -1;
        for (int j = 0; j < collection.length; j++) {
            String[] patterns = collection[j].findPatterns();
            // See Bugzilla 30624
            if (patterns == null) {
                continue;
            }
            for (int k = 0; k < patterns.length && !matched; k++) {
                String pattern = patterns[k];
                if (pattern.startsWith("*.")) {
                    int slash = uri.lastIndexOf('/');
                    int dot = uri.lastIndexOf('.');
                    if (slash >= 0 && dot > slash && dot != uri.length() - 1 && uri.length() - dot == pattern.length() - 1) {
                        if (pattern.regionMatches(1, uri, dot, uri.length() - dot)) {
                            matched = true;
                            pos = j;
                        }
                    }
                }
            }
        }
        if (matched) {
            found = true;
            if (collection[pos].findMethod(method)) {
                if (results == null) {
                    results = new ArrayList<SecurityConstraint>();
                }
                results.add(constraints[i]);
            }
        }
    }
    if (found) {
        return resultsToArray(results);
    }
    for (i = 0; i < constraints.length; i++) {
        SecurityCollection[] collection = constraints[i].findCollections();
        // See Bugzilla 30624
        if (collection == null) {
            continue;
        }
        if (log.isDebugEnabled()) {
            log.debug("  Checking constraint '" + constraints[i] + "' against " + method + " " + uri + " --> " + constraints[i].included(uri, method));
        }
        for (int j = 0; j < collection.length; j++) {
            String[] patterns = collection[j].findPatterns();
            // See Bugzilla 30624
            if (patterns == null) {
                continue;
            }
            boolean matched = false;
            for (int k = 0; k < patterns.length && !matched; k++) {
                String pattern = patterns[k];
                if (pattern.equals("/")) {
                    matched = true;
                }
            }
            if (matched) {
                if (results == null) {
                    results = new ArrayList<SecurityConstraint>();
                }
                results.add(constraints[i]);
            }
        }
    }
    if (results == null) {
        // No applicable security constraint was found
        if (log.isDebugEnabled())
            log.debug("  No applicable constraint located");
    }
    return resultsToArray(results);
}
Also used : SecurityConstraint(org.apache.catalina.deploy.SecurityConstraint) SecurityConstraint(org.apache.catalina.deploy.SecurityConstraint) SecurityCollection(org.apache.catalina.deploy.SecurityCollection)

Example 15 with SecurityCollection

use of org.apache.catalina.deploy.SecurityCollection in project tomcat70 by apache.

the class TesterSupport method configureClientCertContext.

protected static void configureClientCertContext(Tomcat tomcat) {
    TesterSupport.initSsl(tomcat);
    // Need a web application with a protected and unprotected URL
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    Tomcat.addServlet(ctx, "simple", new SimpleServlet());
    ctx.addServletMapping("/unprotected", "simple");
    ctx.addServletMapping("/protected", "simple");
    // Security constraints
    SecurityCollection collection = new SecurityCollection();
    collection.addPattern("/protected");
    SecurityConstraint sc = new SecurityConstraint();
    sc.addAuthRole(ROLE);
    sc.addCollection(collection);
    ctx.addConstraint(sc);
    // Configure the Realm
    MapRealm realm = new MapRealm();
    String cn = "NOTFOUND";
    try {
        KeyStore ks = getKeyStore(CLIENT_JKS);
        X509Certificate cert = (X509Certificate) ks.getCertificate(CLIENT_ALIAS);
        cn = cert.getSubjectDN().getName();
    } catch (Exception ex) {
    // Ignore
    }
    realm.addUser(cn, "not used");
    realm.addUserRole(cn, ROLE);
    ctx.setRealm(realm);
    // Configure the authenticator
    LoginConfig lc = new LoginConfig();
    lc.setAuthMethod("CLIENT-CERT");
    ctx.setLoginConfig(lc);
    ctx.getPipeline().addValve(new SSLAuthenticator());
}
Also used : SSLContext(javax.net.ssl.SSLContext) Context(org.apache.catalina.Context) SSLAuthenticator(org.apache.catalina.authenticator.SSLAuthenticator) LoginConfig(org.apache.catalina.deploy.LoginConfig) MapRealm(org.apache.catalina.startup.TestTomcat.MapRealm) KeyStore(java.security.KeyStore) SecurityConstraint(org.apache.catalina.deploy.SecurityConstraint) X509Certificate(java.security.cert.X509Certificate) ServletException(javax.servlet.ServletException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) UnknownHostException(java.net.UnknownHostException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SecurityCollection(org.apache.catalina.deploy.SecurityCollection)

Aggregations

SecurityCollection (org.apache.catalina.deploy.SecurityCollection)19 SecurityConstraint (org.apache.catalina.deploy.SecurityConstraint)19 LoginConfig (org.apache.catalina.deploy.LoginConfig)11 Context (org.apache.catalina.Context)9 TesterServlet (org.apache.catalina.startup.TesterServlet)5 Tomcat (org.apache.catalina.startup.Tomcat)5 Test (org.junit.Test)4 AuthenticatorBase (org.apache.catalina.authenticator.AuthenticatorBase)3 ClientEndpointConfig (javax.websocket.ClientEndpointConfig)2 DefaultServlet (org.apache.catalina.servlets.DefaultServlet)2 MapRealm (org.apache.catalina.startup.TestTomcat.MapRealm)2 TesterServletEncodeUrl (org.apache.catalina.startup.TesterServletEncodeUrl)2 TesterContext (org.apache.tomcat.unittest.TesterContext)2 File (java.io.File)1 IOException (java.io.IOException)1 URISyntaxException (java.net.URISyntaxException)1 UnknownHostException (java.net.UnknownHostException)1 KeyManagementException (java.security.KeyManagementException)1 KeyStore (java.security.KeyStore)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1