You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@tomcat.apache.org by cr...@locus.apache.org on 2000/01/29 23:56:43 UTC
cvs commit: jakarta-tomcat/proposals/catalina/src/share/org/apache/tomcat/security SecurityValve.java LocalStrings.properties SecurityInterceptor.java
craigmcc 00/01/29 14:56:43
Modified: proposals/catalina/src/share/org/apache/tomcat/security
LocalStrings.properties
Added: proposals/catalina/src/share/org/apache/tomcat/security
SecurityValve.java
Removed: proposals/catalina/src/share/org/apache/tomcat/security
SecurityInterceptor.java
Log:
Replace "Interceptor" implementation of security with a "Valve"
implementation instead.
Revision Changes Path
1.3 +8 -0 jakarta-tomcat/proposals/catalina/src/share/org/apache/tomcat/security/LocalStrings.properties
Index: LocalStrings.properties
===================================================================
RCS file: /home/cvs/jakarta-tomcat/proposals/catalina/src/share/org/apache/tomcat/security/LocalStrings.properties,v
retrieving revision 1.2
retrieving revision 1.3
diff -u -r1.2 -r1.3
--- LocalStrings.properties 2000/01/29 03:47:30 1.2
+++ LocalStrings.properties 2000/01/29 22:56:43 1.3
@@ -5,3 +5,11 @@
securityInterceptor.notStarted=Security Interceptor has not yet been started
securityInterceptor.unknownMethod=Unknown authentication method $0 configured for this application
securityInterceptor.userDataConstraint=This request violates a User Data constraint for this application
+securityValve.alreadyStarted=Security Interceptor has already been started
+securityValve.forbidden=Access to the requested resource has been denied
+securityValve.missingMethod=No authentication method configured for this application
+securityValve.noNext=Configuration error: No 'next' Valve in this pipeline
+securityValve.notContext=Configuration error: Must be attached to a Context
+securityValve.notStarted=Security Interceptor has not yet been started
+securityValve.unknownMethod=Unknown authentication method $0 configured for this application
+securityValve.userDataConstraint=This request violates a User Data constraint for this application
1.1 jakarta-tomcat/proposals/catalina/src/share/org/apache/tomcat/security/SecurityValve.java
Index: SecurityValve.java
===================================================================
/*
* $Header: /home/cvs/jakarta-tomcat/proposals/catalina/src/share/org/apache/tomcat/security/SecurityValve.java,v 1.1 2000/01/29 22:56:43 craigmcc Exp $
* $Revision: 1.1 $
* $Date: 2000/01/29 22:56:43 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.tomcat.security;
import java.io.IOException;
import java.security.Principal;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import org.apache.tomcat.Container;
import org.apache.tomcat.Context;
import org.apache.tomcat.Lifecycle;
import org.apache.tomcat.LifecycleException;
import org.apache.tomcat.Realm;
import org.apache.tomcat.Request;
import org.apache.tomcat.Response;
import org.apache.tomcat.Valve;
import org.apache.tomcat.core.ValveBase;
import org.apache.tomcat.deployment.AuthorizationConstraint;
import org.apache.tomcat.deployment.LoginConfiguration;
import org.apache.tomcat.deployment.SecurityConstraint;
import org.apache.tomcat.deployment.SecurityRole;
import org.apache.tomcat.deployment.SecurityRoleReference;
import org.apache.tomcat.deployment.ServletDescriptor;
import org.apache.tomcat.deployment.UserDataConstraint;
import org.apache.tomcat.deployment.WebApplicationDescriptor;
import org.apache.tomcat.deployment.WebResourceCollection;
import org.apache.tomcat.util.StringManager;
/**
* Implementation of the <b>Valve</b> interface that enforces the
* <code><security-constraint></code> elements in the web application
* deployment descriptor. This functionality is implemented as an
* Interceptor so that it can be omitted in environments that do not require
* these features.
* <p>
* <b>USAGE CONSTRAINT</b>: When this class is utilized, the Context to
* which it is attached (or a parent Container in a hierarchy) must have an
* associated Realm that can be used for authenticating users and enumerating
* the roles to which they have been assigned.
* <p>
* XXX - Unimplemented Features:
* <ul>
* <li>Role mapping for per-servlet <code><security-role-ref></code>
* elements in the deployment descriptor.
* <li>HTTP Digest Authentication support.
* <li>HTTPS Client Authentication support.
* <li>Form Based Authentication support.
* </ul>
*
* @author Craig R. McClanahan
* @version $Revision: 1.1 $ $Date: 2000/01/29 22:56:43 $
*/
public final class SecurityValve
extends ValveBase
implements Lifecycle {
// ----------------------------------------------------- Instance Variables
/**
* The Context to which this Interceptor is attached.
*/
private Context context = null;
/**
* Descriptive information about this implementation.
*/
private static final String info =
"org.apache.tomcat.security.SecurityValve/1.0";
/**
* The string manager for this package.
*/
private StringManager sm =
StringManager.getManager(Constants.Package);
/**
* Has this component been started?
*/
private boolean started = false;
// ------------------------------------------------------------- Properties
/**
* Return the Container to which this Interceptor is attached.
*/
public Container getContainer() {
return (this.context);
}
/**
* Set the Container to which this Interceptor is attached.
*
* @param container The container to which we are attached
*/
public void setContainer(Container container) {
if (!(container instanceof Context))
throw new IllegalArgumentException
(sm.getString("securityValve.notContext"));
this.context = (Context) container;
}
/**
* Return descriptive information about this Interceptor implementation.
*/
public String getInfo() {
return (this.info);
}
// --------------------------------------------------------- Public Methods
/**
* Enforce the security restrictions in the web application deployment
* descriptor of our associated Context.
*
* @param request Request to be processed
* @param response Response to be processed
*
* @exception IOException if an input/output error occurs
* @exception ServletException if thrown by a processing element
*/
public void invoke(Request request, Response response)
throws IOException, ServletException {
// Acquire the WebApplicationDescriptor for this Context
WebApplicationDescriptor descriptor = context.getDescriptor();
if (descriptor == null) {
invokeNext(request, response);
return;
}
// Is this request URI subject to a security constraint?
SecurityConstraint constraint = findConstraint(request, descriptor);
if (constraint == null) {
invokeNext(request, response);
return;
}
// Enforce any user data constraint for this security constraint
if (!checkUserData(request, response,
constraint.getUserDataConstraint())) {
return;
}
// Authenticate based upon the specified login configuration
if (!authenticate(request, response,
descriptor.getLoginConfiguration())) {
return;
}
// Perform access control based on the specified role(s)
if (!accessControl(request, response,
constraint.getAuthorizationConstraint())) {
return;
}
// Any and all specified constraints have been satisfied
invokeNext(request, response);
}
/**
* Invoke the next valve in our pipeline, if any.
*
* @param request Request to be processed
* @param response Response to be processed
* @param throwable Exception thrown by subordinate Interceptor or
* Container, if any
*/
private void invokeNext(Request request, Response response)
throws IOException, ServletException {
if (getNext() == null)
throw new IllegalStateException
(sm.getString("securityValve.noNext"));
getNext().invoke(request, response);
}
// -------------------------------------------------------- Private Methods
/**
* Perform access control based on the specified authorization constraint.
* Return <code>true</code> if this constraint is satisfied and processing
* should continue, or <code>false</code> otherwise.
*
* @param request Request we are processing
* @param response Response we are creating
* @param auth Authorization constraint we are enforcing
*
* @exception IOException if an input/output error occurs
*/
private boolean accessControl(Request request, Response response,
AuthorizationConstraint auth)
throws IOException {
// Which user principal have we already authenticated?
Principal principal = request.getRequest().getUserPrincipal();
if (principal == null) {
response.getResponse().sendError
(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
sm.getString("securityValve.missingMethod"));
return (false);
}
// Check each role included in this constraint
Realm realm = context.getRealm();
Enumeration roles = auth.getSecurityRoles();
while (roles.hasMoreElements()) {
SecurityRole role = (SecurityRole) roles.nextElement();
if (realm.hasRole(principal, role.getName()))
return (true);
}
// Return a "Forbidden" message denying access to this resource
response.getResponse().sendError
(HttpServletResponse.SC_FORBIDDEN,
sm.getString("securityValve.forbidden"));
return (false);
}
/**
* Authenticate the user making this request, based on the specified
* login configuration. Return <code>true</code> if any specified
* constraint has been satisfied, or <code>false</code> if we have
* created a response challenge already.
*
* @param request Request we are processing
* @param response Response we are creating
* @param login LoginConfiguration describing how authentication
* should be performed
*
* @exception IOException if an input/output error occurs
*/
private boolean authenticate(Request request, Response response,
LoginConfiguration config)
throws IOException {
// Has a login configuration element been specified?
if (config == null)
return (true);
// Identify the requested (or default) login mechanism
String method = config.getAuthenticationMethod();
if (method == null)
method = Constants.BASIC_METHOD; // XXX - Is this default correct?
// Apply the requested login mechanism
if (method.equals(Constants.BASIC_METHOD))
return (HttpBasicAuth.authenticate(request, response,
config, context.getRealm()));
/*
else if (method.equals(Constants.CERT_METHOD))
return (ClientCertAuth.authenticate(request, response,
config, context.getRealm()));
else if (method.equals(Constants.DIGEST_METHOD))
return (ClientCertAuth.authenticate(request, response,
config, context.getRealm()));
else if (method.equals(Constants.FORM_METHOD))
return (LoginFormAuth.authenticate(request, response,
config, context.getRealm()));
*/
else {
response.getResponse().sendError
(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
sm.getString("securityValve.unknownMethod", method));
return (false);
}
}
/**
* Enforce any user data constraint required by the security constraint
* guarding this request URI. Return <code>true</code> if this constraint
* was not violated and processing should continue, or <code>false</code>
* if we have created a response already.
*
* @param request Request we are processing
* @param response Response we are creating
* @param user UserDataConstraint we are enforcing
*
* @exception IOException if an input/output error occurs
*/
private boolean checkUserData(Request request, Response response,
UserDataConstraint user)
throws IOException {
if (user == null)
return (true);
String guarantee = user.getTransportGuarantee();
if (guarantee == null)
return (true);
if (guarantee.equals(UserDataConstraint.NONE_TRANSPORT))
return (true);
if (!request.getRequest().isSecure()) {
response.getResponse().sendError
(HttpServletResponse.SC_BAD_REQUEST,
sm.getString("securityValve.userDataConstraint"));
return (false);
}
return (true);
}
/**
* Return the SecurityConstraint 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 descriptor WebApplicationDescriptor within which we are operating
*/
private SecurityConstraint findConstraint(Request request,
WebApplicationDescriptor descriptor) {
// Are there any defined security constraints?
if (descriptor == null)
return (null);
Enumeration constraints = descriptor.getSecurityConstraints();
if (constraints == null)
return (null);
// Check each defined security constraint
while (constraints.hasMoreElements()) {
SecurityConstraint constraint =
(SecurityConstraint) constraints.nextElement();
Enumeration collections = constraint.getWebResourceCollections();
while (collections.hasMoreElements()) {
WebResourceCollection collection =
(WebResourceCollection) collections.nextElement();
if (matchCollection(request, collection))
return (constraint);
}
}
// No applicable security constraint was found
return (null);
}
/**
* Do the characteristics of this request match the protection patterns
* of the specified web resource collection? Matching is done based on
* both the URL pattern and HTTP method (if any) restrictions.
*
* @param request Request we are processing
* @param collection WebResourceCollection to test against
*/
private boolean matchCollection(Request request,
WebResourceCollection collection) {
// Test against the HTTP method(s) listed in the collection
String method = request.getRequest().getMethod();
int n = 0;
boolean match = false;
Enumeration methods = collection.getHttpMethods();
while (methods.hasMoreElements()) {
n++;
if (method.equals((String) methods.nextElement())) {
match = true;
break;
}
}
if ((!match) && (n > 0))
return (false);
// Test against the URL pattern(s) listed in the collection
// XXX - Should this do a "longest match" comparison?
String path = request.getRequest().getServletPath();
if (path == null)
path = "";
if (request.getRequest().getPathInfo() != null)
path += request.getRequest().getPathInfo();
Enumeration patterns = collection.getUrlPatterns();
while (patterns.hasMoreElements()) {
String pattern = (String) patterns.nextElement();
if (matchPattern(path, pattern))
return (true);
}
return (false);
}
/**
* Does the specified request path match the specified URL pattern?
*
* XXX - Shouldn't this be a shared utility method someplace?
*
* @param path Context-relative request path to be checked
* (must start with '/')
* @param pattern URL pattern to be compared against
*/
private boolean matchPattern(String path, String pattern) {
// Normalize the argument strings
if ((path == null) || (path.length() == 0))
path = "/";
if ((pattern == null) || (pattern.length() == 0))
pattern = "/";
// Check for exact match
if (path.equals(pattern))
return (true);
// Check for universal mapping
if (pattern.equals("/"))
return (true);
// Check for path prefix matching
if (pattern.startsWith("/") && pattern.endsWith("/*")) {
pattern = pattern.substring(0, pattern.length() - 2);
if (pattern.length() == 0)
return (true); // "/*" is the same as "/"
if (path.endsWith("/"))
path = path.substring(0, path.length() - 1);
while (true) {
if (pattern.equals(path))
return (true);
int slash = path.lastIndexOf('/');
if (slash <= 0)
break;
path = path.substring(0, slash);
}
return (false);
}
// Check for suffix matching
else if (pattern.startsWith("*.")) {
int slash = path.lastIndexOf('/');
int period = path.lastIndexOf('.');
if ((slash >= 0) && (period > slash) &&
path.endsWith(pattern.substring(1))) {
return (true);
}
}
return (false);
}
// ------------------------------------------------------ Lifecycle Methods
/**
* Prepare for the beginning of active use of the public methods of this
* component. This method should be called after <code>configure()</code>,
* and before any of the public methods of the component are utilized.
*
* @exception IllegalStateException if this component has already been
* started
* @exception LifecycleException if this component detects a fatal error
* that prevents this component from being used
*/
public void start() throws LifecycleException {
// Validate and update our current component state
if (started)
throw new LifecycleException
(sm.getString("securityValve.alreadyStarted"));
started = true;
}
/**
* Gracefully terminate the active use of the public methods of this
* component. This method should be the last one called on a given
* instance of this component.
*
* @exception IllegalStateException if this component has not been started
* @exception LifecycleException if this component detects a fatal error
* that needs to be reported
*/
public void stop() throws LifecycleException {
// Validate and update our current component state
if (!started)
throw new LifecycleException
(sm.getString("securityValve.notStarted"));
started = false;
}
}