Search in sources :

Example 1 with Realm

use of org.apache.catalina.Realm in project tomcat by apache.

the class AuthenticatorBase method reauthenticateFromSSO.

/**
     * Attempts reauthentication to the <code>Realm</code> using the credentials
     * included in argument <code>entry</code>.
     *
     * @param ssoId
     *            identifier of SingleSignOn session with which the caller is
     *            associated
     * @param request
     *            the request that needs to be authenticated
     * @return <code>true</code> if the reauthentication from SSL occurred
     */
protected boolean reauthenticateFromSSO(String ssoId, Request request) {
    if (sso == null || ssoId == null) {
        return false;
    }
    boolean reauthenticated = false;
    Container parent = getContainer();
    if (parent != null) {
        Realm realm = parent.getRealm();
        if (realm != null) {
            reauthenticated = sso.reauthenticate(ssoId, realm, request);
        }
    }
    if (reauthenticated) {
        associate(ssoId, request.getSessionInternal(true));
        if (log.isDebugEnabled()) {
            log.debug(" Reauthenticated cached principal '" + request.getUserPrincipal().getName() + "' with auth type '" + request.getAuthType() + "'");
        }
    }
    return reauthenticated;
}
Also used : Container(org.apache.catalina.Container) Realm(org.apache.catalina.Realm)

Example 2 with Realm

use of org.apache.catalina.Realm in project tomcat by apache.

the class AuthenticatorBase method invoke.

// --------------------------------------------------------- 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
     */
@Override
public void invoke(Request request, Response response) throws IOException, ServletException {
    if (log.isDebugEnabled()) {
        log.debug("Security checking request " + request.getMethod() + " " + request.getRequestURI());
    }
    // Have we got a cached authenticated Principal to record?
    if (cache) {
        Principal principal = request.getUserPrincipal();
        if (principal == null) {
            Session session = request.getSessionInternal(false);
            if (session != null) {
                principal = session.getPrincipal();
                if (principal != null) {
                    if (log.isDebugEnabled()) {
                        log.debug("We have cached auth type " + session.getAuthType() + " for principal " + principal);
                    }
                    request.setAuthType(session.getAuthType());
                    request.setUserPrincipal(principal);
                }
            }
        }
    }
    boolean authRequired = isContinuationRequired(request);
    // The Servlet may specify security constraints through annotations.
    // Ensure that they have been processed before constraints are checked
    Wrapper wrapper = request.getWrapper();
    if (wrapper != null) {
        wrapper.servletSecurityAnnotationScan();
    }
    Realm realm = this.context.getRealm();
    // Is this request URI subject to a security constraint?
    SecurityConstraint[] constraints = realm.findSecurityConstraints(request, this.context);
    AuthConfigProvider jaspicProvider = getJaspicProvider();
    if (jaspicProvider != null) {
        authRequired = true;
    }
    if (constraints == null && !context.getPreemptiveAuthentication() && !authRequired) {
        if (log.isDebugEnabled()) {
            log.debug(" Not subject to any constraint");
        }
        getNext().invoke(request, response);
        return;
    }
    // or browsers as caching can provide a security hole
    if (constraints != null && disableProxyCaching && !"POST".equalsIgnoreCase(request.getMethod())) {
        if (securePagesWithPragma) {
            // Note: These can cause problems with downloading files with IE
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
        } else {
            response.setHeader("Cache-Control", "private");
        }
        response.setHeader("Expires", DATE_ONE);
    }
    if (constraints != null) {
        // Enforce any user data constraint for this security constraint
        if (log.isDebugEnabled()) {
            log.debug(" Calling hasUserDataPermission()");
        }
        if (!realm.hasUserDataPermission(request, response, constraints)) {
            if (log.isDebugEnabled()) {
                log.debug(" Failed hasUserDataPermission() test");
            }
            /*
                 * ASSERT: Authenticator already set the appropriate HTTP status
                 * code, so we do not have to do anything special
                 */
            return;
        }
    }
    // Since authenticate modifies the response on failure,
    // we have to check for allow-from-all first.
    boolean hasAuthConstraint = false;
    if (constraints != null) {
        hasAuthConstraint = true;
        for (int i = 0; i < constraints.length && hasAuthConstraint; i++) {
            if (!constraints[i].getAuthConstraint()) {
                hasAuthConstraint = false;
            } else if (!constraints[i].getAllRoles() && !constraints[i].getAuthenticatedUsers()) {
                String[] roles = constraints[i].findAuthRoles();
                if (roles == null || roles.length == 0) {
                    hasAuthConstraint = false;
                }
            }
        }
    }
    if (!authRequired && hasAuthConstraint) {
        authRequired = true;
    }
    if (!authRequired && context.getPreemptiveAuthentication()) {
        authRequired = request.getCoyoteRequest().getMimeHeaders().getValue("authorization") != null;
    }
    if (!authRequired && context.getPreemptiveAuthentication() && HttpServletRequest.CLIENT_CERT_AUTH.equals(getAuthMethod())) {
        X509Certificate[] certs = getRequestCertificates(request);
        authRequired = certs != null && certs.length > 0;
    }
    JaspicState jaspicState = null;
    if (authRequired) {
        if (log.isDebugEnabled()) {
            log.debug(" Calling authenticate()");
        }
        if (jaspicProvider != null) {
            jaspicState = getJaspicState(jaspicProvider, request, response, hasAuthConstraint);
            if (jaspicState == null) {
                return;
            }
        }
        if (jaspicProvider == null && !doAuthenticate(request, response) || jaspicProvider != null && !authenticateJaspic(request, response, jaspicState, false)) {
            if (log.isDebugEnabled()) {
                log.debug(" Failed authenticate() test");
            }
            /*
                 * ASSERT: Authenticator already set the appropriate HTTP status
                 * code, so we do not have to do anything special
                 */
            return;
        }
    }
    if (constraints != null) {
        if (log.isDebugEnabled()) {
            log.debug(" Calling accessControl()");
        }
        if (!realm.hasResourcePermission(request, response, constraints, this.context)) {
            if (log.isDebugEnabled()) {
                log.debug(" Failed accessControl() test");
            }
            /*
                 * ASSERT: AccessControl method has already set the appropriate
                 * HTTP status code, so we do not have to do anything special
                 */
            return;
        }
    }
    // Any and all specified constraints have been satisfied
    if (log.isDebugEnabled()) {
        log.debug(" Successfully passed all security constraints");
    }
    getNext().invoke(request, response);
    if (jaspicProvider != null) {
        secureResponseJspic(request, response, jaspicState);
    }
}
Also used : Wrapper(org.apache.catalina.Wrapper) AuthConfigProvider(javax.security.auth.message.config.AuthConfigProvider) Realm(org.apache.catalina.Realm) Principal(java.security.Principal) TomcatPrincipal(org.apache.catalina.TomcatPrincipal) GenericPrincipal(org.apache.catalina.realm.GenericPrincipal) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) X509Certificate(java.security.cert.X509Certificate) Session(org.apache.catalina.Session)

Example 3 with Realm

use of org.apache.catalina.Realm in project tomcat by apache.

the class CombinedRealm method authenticate.

/**
     * Return the Principal associated with the specified chain of X509
     * client certificates.  If there is none, return <code>null</code>.
     *
     * @param certs Array of client certificates, with the first one in
     *  the array being the certificate of the client itself.
     */
@Override
public Principal authenticate(X509Certificate[] certs) {
    Principal authenticatedUser = null;
    String username = null;
    if (certs != null && certs.length > 0) {
        username = certs[0].getSubjectDN().getName();
    }
    for (Realm realm : realms) {
        if (log.isDebugEnabled()) {
            log.debug(sm.getString("combinedRealm.authStart", username, realm.getClass().getName()));
        }
        authenticatedUser = realm.authenticate(certs);
        if (authenticatedUser == null) {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("combinedRealm.authFail", username, realm.getClass().getName()));
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("combinedRealm.authSuccess", username, realm.getClass().getName()));
            }
            break;
        }
    }
    return authenticatedUser;
}
Also used : Realm(org.apache.catalina.Realm) Principal(java.security.Principal)

Example 4 with Realm

use of org.apache.catalina.Realm in project tomcat by apache.

the class StandardContextSF method storeChildren.

/**
     * Store the specified context element children.
     *
     * @param aWriter Current output writer
     * @param indent Indentation level
     * @param aContext Context to store
     * @param parentDesc The element description
     * @throws Exception Configuration storing error
     */
@Override
public void storeChildren(PrintWriter aWriter, int indent, Object aContext, StoreDescription parentDesc) throws Exception {
    if (aContext instanceof StandardContext) {
        StandardContext context = (StandardContext) aContext;
        // Store nested <Listener> elements
        LifecycleListener[] listeners = context.findLifecycleListeners();
        ArrayList<LifecycleListener> listenersArray = new ArrayList<>();
        for (LifecycleListener listener : listeners) {
            if (!(listener instanceof ThreadLocalLeakPreventionListener)) {
                listenersArray.add(listener);
            }
        }
        storeElementArray(aWriter, indent, listenersArray.toArray());
        // Store nested <Valve> elements
        Valve[] valves = context.getPipeline().getValves();
        storeElementArray(aWriter, indent, valves);
        // Store nested <Loader> elements
        Loader loader = context.getLoader();
        storeElement(aWriter, indent, loader);
        // Store nested <Manager> elements
        if (context.getCluster() == null || !context.getDistributable()) {
            Manager manager = context.getManager();
            storeElement(aWriter, indent, manager);
        }
        // Store nested <Realm> element
        Realm realm = context.getRealm();
        if (realm != null) {
            Realm parentRealm = null;
            // @TODO is this case possible?
            if (context.getParent() != null) {
                parentRealm = context.getParent().getRealm();
            }
            if (realm != parentRealm) {
                storeElement(aWriter, indent, realm);
            }
        }
        // Store nested resources
        WebResourceRoot resources = context.getResources();
        storeElement(aWriter, indent, resources);
        // Store nested <WrapperListener> elements
        String[] wLifecycles = context.findWrapperLifecycles();
        getStoreAppender().printTagArray(aWriter, "WrapperListener", indent + 2, wLifecycles);
        // Store nested <WrapperLifecycle> elements
        String[] wListeners = context.findWrapperListeners();
        getStoreAppender().printTagArray(aWriter, "WrapperLifecycle", indent + 2, wListeners);
        // Store nested <Parameter> elements
        ApplicationParameter[] appParams = context.findApplicationParameters();
        storeElementArray(aWriter, indent, appParams);
        // Store nested naming resources elements (EJB,Resource,...)
        NamingResourcesImpl nresources = context.getNamingResources();
        storeElement(aWriter, indent, nresources);
        // Store nested watched resources <WatchedResource>
        String[] wresources = context.findWatchedResources();
        wresources = filterWatchedResources(context, wresources);
        getStoreAppender().printTagArray(aWriter, "WatchedResource", indent + 2, wresources);
        // Store nested <JarScanner> elements
        JarScanner jarScanner = context.getJarScanner();
        storeElement(aWriter, indent, jarScanner);
        // Store nested <CookieProcessor> elements
        CookieProcessor cookieProcessor = context.getCookieProcessor();
        storeElement(aWriter, indent, cookieProcessor);
    }
}
Also used : ApplicationParameter(org.apache.tomcat.util.descriptor.web.ApplicationParameter) ArrayList(java.util.ArrayList) Loader(org.apache.catalina.Loader) LifecycleListener(org.apache.catalina.LifecycleListener) Manager(org.apache.catalina.Manager) JarScanner(org.apache.tomcat.JarScanner) ThreadLocalLeakPreventionListener(org.apache.catalina.core.ThreadLocalLeakPreventionListener) CookieProcessor(org.apache.tomcat.util.http.CookieProcessor) StandardContext(org.apache.catalina.core.StandardContext) Valve(org.apache.catalina.Valve) NamingResourcesImpl(org.apache.catalina.deploy.NamingResourcesImpl) Realm(org.apache.catalina.Realm) WebResourceRoot(org.apache.catalina.WebResourceRoot)

Example 5 with Realm

use of org.apache.catalina.Realm in project tomcat by apache.

the class StandardHostSF method storeChildren.

/**
     * Store the specified Host properties and children
     * (Listener,Alias,Realm,Valve,Cluster, Context)
     *
     * @param aWriter
     *            PrintWriter to which we are storing
     * @param indent
     *            Number of spaces to indent this element
     * @param aHost
     *            Host whose properties are being stored
     *
     * @exception Exception
     *                if an exception occurs while storing
     */
@Override
public void storeChildren(PrintWriter aWriter, int indent, Object aHost, StoreDescription parentDesc) throws Exception {
    if (aHost instanceof StandardHost) {
        StandardHost host = (StandardHost) aHost;
        // Store nested <Listener> elements
        LifecycleListener[] listeners = ((Lifecycle) host).findLifecycleListeners();
        storeElementArray(aWriter, indent, listeners);
        // Store nested <Alias> elements
        String[] aliases = host.findAliases();
        getStoreAppender().printTagArray(aWriter, "Alias", indent + 2, aliases);
        // Store nested <Realm> element
        Realm realm = host.getRealm();
        if (realm != null) {
            Realm parentRealm = null;
            if (host.getParent() != null) {
                parentRealm = host.getParent().getRealm();
            }
            if (realm != parentRealm) {
                storeElement(aWriter, indent, realm);
            }
        }
        // Store nested <Valve> elements
        Valve[] valves = host.getPipeline().getValves();
        if (valves != null && valves.length > 0) {
            List<Valve> hostValves = new ArrayList<>();
            for (int i = 0; i < valves.length; i++) {
                if (!(valves[i] instanceof ClusterValve))
                    hostValves.add(valves[i]);
            }
            storeElementArray(aWriter, indent, hostValves.toArray());
        }
        // store all <Cluster> elements
        Cluster cluster = host.getCluster();
        if (cluster != null) {
            Cluster parentCluster = null;
            if (host.getParent() != null) {
                parentCluster = host.getParent().getCluster();
            }
            if (cluster != parentCluster) {
                storeElement(aWriter, indent, cluster);
            }
        }
        // store all <Context> elements
        Container[] children = host.findChildren();
        storeElementArray(aWriter, indent, children);
    }
}
Also used : Lifecycle(org.apache.catalina.Lifecycle) ArrayList(java.util.ArrayList) Cluster(org.apache.catalina.Cluster) LifecycleListener(org.apache.catalina.LifecycleListener) ClusterValve(org.apache.catalina.ha.ClusterValve) Container(org.apache.catalina.Container) StandardHost(org.apache.catalina.core.StandardHost) ClusterValve(org.apache.catalina.ha.ClusterValve) Valve(org.apache.catalina.Valve) Realm(org.apache.catalina.Realm)

Aggregations

Realm (org.apache.catalina.Realm)27 Lifecycle (org.apache.catalina.Lifecycle)11 LifecycleException (org.apache.catalina.LifecycleException)11 Container (org.apache.catalina.Container)9 ArrayList (java.util.ArrayList)7 IOException (java.io.IOException)6 Cluster (org.apache.catalina.Cluster)6 Principal (java.security.Principal)5 Valve (org.apache.catalina.Valve)5 NamingException (javax.naming.NamingException)4 LifecycleListener (org.apache.catalina.LifecycleListener)3 Loader (org.apache.catalina.Loader)3 Manager (org.apache.catalina.Manager)3 StandardContext (org.apache.catalina.core.StandardContext)3 InstanceManager (org.apache.tomcat.InstanceManager)3 MalformedURLException (java.net.MalformedURLException)2 HashMap (java.util.HashMap)2 HashSet (java.util.HashSet)2 Properties (java.util.Properties)2 Set (java.util.Set)2