Search in sources :

Example 16 with Principal

use of java.security.Principal in project tomcat by apache.

the class SpnegoAuthenticator method doAuthenticate.

@Override
protected boolean doAuthenticate(Request request, HttpServletResponse response) throws IOException {
    if (checkForCachedAuthentication(request, response, true)) {
        return true;
    }
    MessageBytes authorization = request.getCoyoteRequest().getMimeHeaders().getValue("authorization");
    if (authorization == null) {
        if (log.isDebugEnabled()) {
            log.debug(sm.getString("authenticator.noAuthHeader"));
        }
        response.setHeader(AUTH_HEADER_NAME, AUTH_HEADER_VALUE_NEGOTIATE);
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return false;
    }
    authorization.toBytes();
    ByteChunk authorizationBC = authorization.getByteChunk();
    if (!authorizationBC.startsWithIgnoreCase("negotiate ", 0)) {
        if (log.isDebugEnabled()) {
            log.debug(sm.getString("spnegoAuthenticator.authHeaderNotNego"));
        }
        response.setHeader(AUTH_HEADER_NAME, AUTH_HEADER_VALUE_NEGOTIATE);
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return false;
    }
    authorizationBC.setOffset(authorizationBC.getOffset() + 10);
    byte[] decoded = Base64.decodeBase64(authorizationBC.getBuffer(), authorizationBC.getOffset(), authorizationBC.getLength());
    if (getApplyJava8u40Fix()) {
        SpnegoTokenFixer.fix(decoded);
    }
    if (decoded.length == 0) {
        if (log.isDebugEnabled()) {
            log.debug(sm.getString("spnegoAuthenticator.authHeaderNoToken"));
        }
        response.setHeader(AUTH_HEADER_NAME, AUTH_HEADER_VALUE_NEGOTIATE);
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return false;
    }
    LoginContext lc = null;
    GSSContext gssContext = null;
    byte[] outToken = null;
    Principal principal = null;
    try {
        try {
            lc = new LoginContext(getLoginConfigName());
            lc.login();
        } catch (LoginException e) {
            log.error(sm.getString("spnegoAuthenticator.serviceLoginFail"), e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return false;
        }
        Subject subject = lc.getSubject();
        // Assume the GSSContext is stateless
        // TODO: Confirm this assumption
        final GSSManager manager = GSSManager.getInstance();
        // IBM JDK only understands indefinite lifetime
        final int credentialLifetime;
        if (JreVendor.IS_IBM_JVM) {
            credentialLifetime = GSSCredential.INDEFINITE_LIFETIME;
        } else {
            credentialLifetime = GSSCredential.DEFAULT_LIFETIME;
        }
        final PrivilegedExceptionAction<GSSCredential> action = new PrivilegedExceptionAction<GSSCredential>() {

            @Override
            public GSSCredential run() throws GSSException {
                return manager.createCredential(null, credentialLifetime, new Oid("1.3.6.1.5.5.2"), GSSCredential.ACCEPT_ONLY);
            }
        };
        gssContext = manager.createContext(Subject.doAs(subject, action));
        outToken = Subject.doAs(lc.getSubject(), new AcceptAction(gssContext, decoded));
        if (outToken == null) {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("spnegoAuthenticator.ticketValidateFail"));
            }
            // Start again
            response.setHeader(AUTH_HEADER_NAME, AUTH_HEADER_VALUE_NEGOTIATE);
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        principal = Subject.doAs(subject, new AuthenticateAction(context.getRealm(), gssContext, storeDelegatedCredential));
    } catch (GSSException e) {
        if (log.isDebugEnabled()) {
            log.debug(sm.getString("spnegoAuthenticator.ticketValidateFail"), e);
        }
        response.setHeader(AUTH_HEADER_NAME, AUTH_HEADER_VALUE_NEGOTIATE);
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return false;
    } catch (PrivilegedActionException e) {
        Throwable cause = e.getCause();
        if (cause instanceof GSSException) {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("spnegoAuthenticator.serviceLoginFail"), e);
            }
        } else {
            log.error(sm.getString("spnegoAuthenticator.serviceLoginFail"), e);
        }
        response.setHeader(AUTH_HEADER_NAME, AUTH_HEADER_VALUE_NEGOTIATE);
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return false;
    } finally {
        if (gssContext != null) {
            try {
                gssContext.dispose();
            } catch (GSSException e) {
            // Ignore
            }
        }
        if (lc != null) {
            try {
                lc.logout();
            } catch (LoginException e) {
            // Ignore
            }
        }
    }
    // Send response token on success and failure
    response.setHeader(AUTH_HEADER_NAME, AUTH_HEADER_VALUE_NEGOTIATE + " " + Base64.encodeBase64String(outToken));
    if (principal != null) {
        register(request, response, principal, Constants.SPNEGO_METHOD, principal.getName(), null);
        Pattern p = noKeepAliveUserAgents;
        if (p != null) {
            MessageBytes ua = request.getCoyoteRequest().getMimeHeaders().getValue("user-agent");
            if (ua != null && p.matcher(ua.toString()).matches()) {
                response.setHeader("Connection", "close");
            }
        }
        return true;
    }
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    return false;
}
Also used : Pattern(java.util.regex.Pattern) ByteChunk(org.apache.tomcat.util.buf.ByteChunk) PrivilegedActionException(java.security.PrivilegedActionException) MessageBytes(org.apache.tomcat.util.buf.MessageBytes) PrivilegedExceptionAction(java.security.PrivilegedExceptionAction) Oid(org.ietf.jgss.Oid) Subject(javax.security.auth.Subject) LoginContext(javax.security.auth.login.LoginContext) GSSException(org.ietf.jgss.GSSException) GSSCredential(org.ietf.jgss.GSSCredential) GSSContext(org.ietf.jgss.GSSContext) GSSManager(org.ietf.jgss.GSSManager) LoginException(javax.security.auth.login.LoginException) Principal(java.security.Principal)

Example 17 with Principal

use of java.security.Principal in project tomcat by apache.

the class AuthenticatorBase method logout.

@Override
public void logout(Request request) {
    AuthConfigProvider provider = getJaspicProvider();
    if (provider != null) {
        MessageInfo messageInfo = new MessageInfoImpl(request, request.getResponse(), true);
        Subject client = (Subject) request.getNote(Constants.REQ_JASPIC_SUBJECT_NOTE);
        if (client == null) {
            return;
        }
        ServerAuthContext serverAuthContext;
        try {
            ServerAuthConfig serverAuthConfig = provider.getServerAuthConfig("HttpServlet", jaspicAppContextID, CallbackHandlerImpl.getInstance());
            String authContextID = serverAuthConfig.getAuthContextID(messageInfo);
            serverAuthContext = serverAuthConfig.getAuthContext(authContextID, null, null);
            serverAuthContext.cleanSubject(messageInfo, client);
        } catch (AuthException e) {
            log.debug(sm.getString("authenticator.jaspicCleanSubjectFail"), e);
        }
    }
    Principal p = request.getPrincipal();
    if (p instanceof TomcatPrincipal) {
        try {
            ((TomcatPrincipal) p).logout();
        } catch (Throwable t) {
            ExceptionUtils.handleThrowable(t);
            log.debug(sm.getString("authenticator.tomcatPrincipalLogoutFail"), t);
        }
    }
    register(request, request.getResponse(), null, null, null, null);
}
Also used : AuthConfigProvider(javax.security.auth.message.config.AuthConfigProvider) MessageInfoImpl(org.apache.catalina.authenticator.jaspic.MessageInfoImpl) AuthException(javax.security.auth.message.AuthException) Subject(javax.security.auth.Subject) ServerAuthConfig(javax.security.auth.message.config.ServerAuthConfig) Principal(java.security.Principal) TomcatPrincipal(org.apache.catalina.TomcatPrincipal) GenericPrincipal(org.apache.catalina.realm.GenericPrincipal) MessageInfo(javax.security.auth.message.MessageInfo) ServerAuthContext(javax.security.auth.message.config.ServerAuthContext) TomcatPrincipal(org.apache.catalina.TomcatPrincipal)

Example 18 with Principal

use of java.security.Principal 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 19 with Principal

use of java.security.Principal in project tomcat by apache.

the class AuthenticatorBase method login.

@Override
public void login(String username, String password, Request request) throws ServletException {
    Principal principal = doLogin(request, username, password);
    register(request, request.getResponse(), principal, getAuthMethod(), username, password);
}
Also used : Principal(java.security.Principal) TomcatPrincipal(org.apache.catalina.TomcatPrincipal) GenericPrincipal(org.apache.catalina.realm.GenericPrincipal)

Example 20 with Principal

use of java.security.Principal in project tomcat by apache.

the class DeltaRequest method execute.

public void execute(DeltaSession session, boolean notifyListeners) {
    if (!this.sessionId.equals(session.getId()))
        throw new java.lang.IllegalArgumentException(sm.getString("deltaRequest.ssid.mismatch"));
    session.access();
    for (int i = 0; i < actions.size(); i++) {
        AttributeInfo info = actions.get(i);
        switch(info.getType()) {
            case TYPE_ATTRIBUTE:
                if (info.getAction() == ACTION_SET) {
                    if (log.isTraceEnabled())
                        log.trace("Session.setAttribute('" + info.getName() + "', '" + info.getValue() + "')");
                    session.setAttribute(info.getName(), info.getValue(), notifyListeners, false);
                } else {
                    if (log.isTraceEnabled())
                        log.trace("Session.removeAttribute('" + info.getName() + "')");
                    session.removeAttribute(info.getName(), notifyListeners, false);
                }
                break;
            case TYPE_ISNEW:
                if (log.isTraceEnabled())
                    log.trace("Session.setNew('" + info.getValue() + "')");
                session.setNew(((Boolean) info.getValue()).booleanValue(), false);
                break;
            case TYPE_MAXINTERVAL:
                if (log.isTraceEnabled())
                    log.trace("Session.setMaxInactiveInterval('" + info.getValue() + "')");
                session.setMaxInactiveInterval(((Integer) info.getValue()).intValue(), false);
                break;
            case TYPE_PRINCIPAL:
                Principal p = null;
                if (info.getAction() == ACTION_SET) {
                    p = (Principal) info.getValue();
                }
                session.setPrincipal(p, false);
                break;
            case TYPE_AUTHTYPE:
                String authType = null;
                if (info.getAction() == ACTION_SET) {
                    authType = (String) info.getValue();
                }
                session.setAuthType(authType, false);
                break;
            case TYPE_LISTENER:
                SessionListener listener = (SessionListener) info.getValue();
                if (info.getAction() == ACTION_SET) {
                    session.addSessionListener(listener, false);
                } else {
                    session.removeSessionListener(listener, false);
                }
                break;
            default:
                throw new java.lang.IllegalArgumentException(sm.getString("deltaRequest.invalidAttributeInfoType", info));
        }
    //switch
    }
    //for
    session.endAccess();
    reset();
}
Also used : SessionListener(org.apache.catalina.SessionListener) Principal(java.security.Principal) GenericPrincipal(org.apache.catalina.realm.GenericPrincipal)

Aggregations

Principal (java.security.Principal)931 Test (org.junit.Test)243 Subject (javax.security.auth.Subject)114 EveryonePrincipal (org.apache.jackrabbit.oak.spi.security.principal.EveryonePrincipal)114 HashSet (java.util.HashSet)89 User (org.apache.jackrabbit.api.security.user.User)75 Group (org.apache.jackrabbit.api.security.user.Group)74 Authorizable (org.apache.jackrabbit.api.security.user.Authorizable)58 Privilege (javax.jcr.security.Privilege)57 RepositoryException (javax.jcr.RepositoryException)51 IOException (java.io.IOException)50 ArrayList (java.util.ArrayList)48 HttpServletRequest (javax.servlet.http.HttpServletRequest)47 TestPrincipal (org.apache.jackrabbit.core.security.TestPrincipal)45 AbstractSecurityTest (org.apache.jackrabbit.oak.AbstractSecurityTest)43 EveryonePrincipal (org.apache.jackrabbit.core.security.principal.EveryonePrincipal)42 PrincipalIterator (org.apache.jackrabbit.api.security.principal.PrincipalIterator)40 HashMap (java.util.HashMap)39 PrincipalImpl (org.apache.jackrabbit.oak.spi.security.principal.PrincipalImpl)39 X500Principal (javax.security.auth.x500.X500Principal)38