Search in sources :

Example 36 with Subject

use of javax.security.auth.Subject in project elasticsearch by elastic.

the class HdfsBlobStoreContainerTests method createContext.

@SuppressForbidden(reason = "lesser of two evils (the other being a bunch of JNI/classloader nightmares)")
private FileContext createContext(URI uri) {
    // mirrors HdfsRepository.java behaviour
    Configuration cfg = new Configuration(true);
    cfg.setClassLoader(HdfsRepository.class.getClassLoader());
    cfg.reloadConfiguration();
    Constructor<?> ctor;
    Subject subject;
    try {
        Class<?> clazz = Class.forName("org.apache.hadoop.security.User");
        ctor = clazz.getConstructor(String.class);
        ctor.setAccessible(true);
    } catch (ClassNotFoundException | NoSuchMethodException e) {
        throw new RuntimeException(e);
    }
    try {
        Principal principal = (Principal) ctor.newInstance(System.getProperty("user.name"));
        subject = new Subject(false, Collections.singleton(principal), Collections.emptySet(), Collections.emptySet());
    } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
        throw new RuntimeException(e);
    }
    // disable file system cache
    cfg.setBoolean("fs.hdfs.impl.disable.cache", true);
    // set file system to TestingFs to avoid a bunch of security
    // checks, similar to what is done in HdfsTests.java
    cfg.set("fs.AbstractFileSystem." + uri.getScheme() + ".impl", TestingFs.class.getName());
    // create the FileContext with our user
    return Subject.doAs(subject, (PrivilegedAction<FileContext>) () -> {
        try {
            TestingFs fs = (TestingFs) AbstractFileSystem.get(uri, cfg);
            return FileContext.getFileContext(fs, cfg);
        } catch (UnsupportedFileSystemException e) {
            throw new RuntimeException(e);
        }
    });
}
Also used : Configuration(org.apache.hadoop.conf.Configuration) Subject(javax.security.auth.Subject) InvocationTargetException(java.lang.reflect.InvocationTargetException) UnsupportedFileSystemException(org.apache.hadoop.fs.UnsupportedFileSystemException) Principal(java.security.Principal) FileContext(org.apache.hadoop.fs.FileContext) SuppressForbidden(org.elasticsearch.common.SuppressForbidden)

Example 37 with Subject

use of javax.security.auth.Subject in project jetty.project by eclipse.

the class JaspiAuthenticator method validateRequest.

public Authentication validateRequest(JaspiMessageInfo messageInfo) throws ServerAuthException {
    try {
        String authContextId = _authConfig.getAuthContextID(messageInfo);
        ServerAuthContext authContext = _authConfig.getAuthContext(authContextId, _serviceSubject, _authProperties);
        Subject clientSubject = new Subject();
        AuthStatus authStatus = authContext.validateRequest(messageInfo, clientSubject, _serviceSubject);
        if (authStatus == AuthStatus.SEND_CONTINUE)
            return Authentication.SEND_CONTINUE;
        if (authStatus == AuthStatus.SEND_FAILURE)
            return Authentication.SEND_FAILURE;
        if (authStatus == AuthStatus.SUCCESS) {
            Set<UserIdentity> ids = clientSubject.getPrivateCredentials(UserIdentity.class);
            UserIdentity userIdentity;
            if (ids.size() > 0) {
                userIdentity = ids.iterator().next();
            } else {
                CallerPrincipalCallback principalCallback = _callbackHandler.getThreadCallerPrincipalCallback();
                if (principalCallback == null) {
                    return Authentication.UNAUTHENTICATED;
                }
                Principal principal = principalCallback.getPrincipal();
                if (principal == null) {
                    String principalName = principalCallback.getName();
                    Set<Principal> principals = principalCallback.getSubject().getPrincipals();
                    for (Principal p : principals) {
                        if (p.getName().equals(principalName)) {
                            principal = p;
                            break;
                        }
                    }
                    if (principal == null) {
                        return Authentication.UNAUTHENTICATED;
                    }
                }
                GroupPrincipalCallback groupPrincipalCallback = _callbackHandler.getThreadGroupPrincipalCallback();
                String[] groups = groupPrincipalCallback == null ? null : groupPrincipalCallback.getGroups();
                userIdentity = _identityService.newUserIdentity(clientSubject, principal, groups);
            }
            HttpSession session = ((HttpServletRequest) messageInfo.getRequestMessage()).getSession(false);
            Authentication cached = (session == null ? null : (SessionAuthentication) session.getAttribute(SessionAuthentication.__J_AUTHENTICATED));
            if (cached != null)
                return cached;
            return new UserAuthentication(getAuthMethod(), userIdentity);
        }
        if (authStatus == AuthStatus.SEND_SUCCESS) {
            // we are processing a message in a secureResponse dialog.
            return Authentication.SEND_SUCCESS;
        }
        if (authStatus == AuthStatus.FAILURE) {
            HttpServletResponse response = (HttpServletResponse) messageInfo.getResponseMessage();
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return Authentication.SEND_FAILURE;
        }
        // should not happen
        throw new IllegalStateException("No AuthStatus returned");
    } catch (IOException | AuthException e) {
        throw new ServerAuthException(e);
    }
}
Also used : HttpSession(javax.servlet.http.HttpSession) UserIdentity(org.eclipse.jetty.server.UserIdentity) HttpServletResponse(javax.servlet.http.HttpServletResponse) AuthException(javax.security.auth.message.AuthException) ServerAuthException(org.eclipse.jetty.security.ServerAuthException) SessionAuthentication(org.eclipse.jetty.security.authentication.SessionAuthentication) IOException(java.io.IOException) ServerAuthException(org.eclipse.jetty.security.ServerAuthException) UserAuthentication(org.eclipse.jetty.security.UserAuthentication) Subject(javax.security.auth.Subject) ServerAuthContext(javax.security.auth.message.config.ServerAuthContext) HttpServletRequest(javax.servlet.http.HttpServletRequest) CallerPrincipalCallback(javax.security.auth.message.callback.CallerPrincipalCallback) GroupPrincipalCallback(javax.security.auth.message.callback.GroupPrincipalCallback) AuthStatus(javax.security.auth.message.AuthStatus) DeferredAuthentication(org.eclipse.jetty.security.authentication.DeferredAuthentication) SessionAuthentication(org.eclipse.jetty.security.authentication.SessionAuthentication) UserAuthentication(org.eclipse.jetty.security.UserAuthentication) Authentication(org.eclipse.jetty.server.Authentication) Principal(java.security.Principal)

Example 38 with Subject

use of javax.security.auth.Subject in project jetty.project by eclipse.

the class JaspiAuthenticatorFactory method getAuthenticator.

/* ------------------------------------------------------------ */
public Authenticator getAuthenticator(Server server, ServletContext context, AuthConfiguration configuration, IdentityService identityService, LoginService loginService) {
    Authenticator authenticator = null;
    try {
        AuthConfigFactory authConfigFactory = AuthConfigFactory.getFactory();
        RegistrationListener listener = new RegistrationListener() {

            public void notify(String layer, String appContext) {
            }
        };
        Subject serviceSubject = findServiceSubject(server);
        String serverName = findServerName(server, serviceSubject);
        String contextPath = context.getContextPath();
        if (contextPath == null || contextPath.length() == 0)
            contextPath = "/";
        String appContext = serverName + " " + context.getContextPath();
        AuthConfigProvider authConfigProvider = authConfigFactory.getConfigProvider(MESSAGE_LAYER, appContext, listener);
        if (authConfigProvider != null) {
            ServletCallbackHandler servletCallbackHandler = new ServletCallbackHandler(loginService);
            ServerAuthConfig serverAuthConfig = authConfigProvider.getServerAuthConfig(MESSAGE_LAYER, appContext, servletCallbackHandler);
            if (serverAuthConfig != null) {
                Map map = new HashMap();
                for (String key : configuration.getInitParameterNames()) map.put(key, configuration.getInitParameter(key));
                authenticator = new JaspiAuthenticator(serverAuthConfig, map, servletCallbackHandler, serviceSubject, true, identityService);
            }
        }
    } catch (AuthException e) {
        LOG.warn(e);
    }
    return authenticator;
}
Also used : RegistrationListener(javax.security.auth.message.config.RegistrationListener) AuthConfigProvider(javax.security.auth.message.config.AuthConfigProvider) HashMap(java.util.HashMap) AuthConfigFactory(javax.security.auth.message.config.AuthConfigFactory) AuthException(javax.security.auth.message.AuthException) HashMap(java.util.HashMap) Map(java.util.Map) Authenticator(org.eclipse.jetty.security.Authenticator) Subject(javax.security.auth.Subject) ServerAuthConfig(javax.security.auth.message.config.ServerAuthConfig)

Example 39 with Subject

use of javax.security.auth.Subject in project jetty.project by eclipse.

the class ServletCallbackHandler method handle.

public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
    for (Callback callback : callbacks) {
        // jaspi to server communication
        if (callback instanceof CallerPrincipalCallback) {
            _callerPrincipals.set((CallerPrincipalCallback) callback);
        } else if (callback instanceof GroupPrincipalCallback) {
            _groupPrincipals.set((GroupPrincipalCallback) callback);
        } else if (callback instanceof PasswordValidationCallback) {
            PasswordValidationCallback passwordValidationCallback = (PasswordValidationCallback) callback;
            Subject subject = passwordValidationCallback.getSubject();
            UserIdentity user = _loginService.login(passwordValidationCallback.getUsername(), passwordValidationCallback.getPassword(), null);
            if (user != null) {
                passwordValidationCallback.setResult(true);
                passwordValidationCallback.getSubject().getPrincipals().addAll(user.getSubject().getPrincipals());
                passwordValidationCallback.getSubject().getPrivateCredentials().add(user);
            }
        } else if (callback instanceof CredentialValidationCallback) {
            CredentialValidationCallback credentialValidationCallback = (CredentialValidationCallback) callback;
            Subject subject = credentialValidationCallback.getSubject();
            LoginCallback loginCallback = new LoginCallbackImpl(subject, credentialValidationCallback.getUsername(), credentialValidationCallback.getCredential());
            UserIdentity user = _loginService.login(credentialValidationCallback.getUsername(), credentialValidationCallback.getCredential(), null);
            if (user != null) {
                loginCallback.setUserPrincipal(user.getUserPrincipal());
                credentialValidationCallback.getSubject().getPrivateCredentials().add(loginCallback);
                credentialValidationCallback.setResult(true);
                credentialValidationCallback.getSubject().getPrincipals().addAll(user.getSubject().getPrincipals());
                credentialValidationCallback.getSubject().getPrivateCredentials().add(user);
            }
        } else // TODO implement these
        if (callback instanceof CertStoreCallback) {
        } else if (callback instanceof PrivateKeyCallback) {
        } else if (callback instanceof SecretKeyCallback) {
        } else if (callback instanceof TrustStoreCallback) {
        } else {
            throw new UnsupportedCallbackException(callback);
        }
    }
}
Also used : LoginCallback(org.eclipse.jetty.security.authentication.LoginCallback) SecretKeyCallback(javax.security.auth.message.callback.SecretKeyCallback) TrustStoreCallback(javax.security.auth.message.callback.TrustStoreCallback) CertStoreCallback(javax.security.auth.message.callback.CertStoreCallback) UserIdentity(org.eclipse.jetty.server.UserIdentity) CredentialValidationCallback(org.eclipse.jetty.security.jaspi.callback.CredentialValidationCallback) Subject(javax.security.auth.Subject) CallerPrincipalCallback(javax.security.auth.message.callback.CallerPrincipalCallback) LoginCallbackImpl(org.eclipse.jetty.security.authentication.LoginCallbackImpl) GroupPrincipalCallback(javax.security.auth.message.callback.GroupPrincipalCallback) TrustStoreCallback(javax.security.auth.message.callback.TrustStoreCallback) LoginCallback(org.eclipse.jetty.security.authentication.LoginCallback) GroupPrincipalCallback(javax.security.auth.message.callback.GroupPrincipalCallback) PasswordValidationCallback(javax.security.auth.message.callback.PasswordValidationCallback) CredentialValidationCallback(org.eclipse.jetty.security.jaspi.callback.CredentialValidationCallback) CallerPrincipalCallback(javax.security.auth.message.callback.CallerPrincipalCallback) CertStoreCallback(javax.security.auth.message.callback.CertStoreCallback) PrivateKeyCallback(javax.security.auth.message.callback.PrivateKeyCallback) SecretKeyCallback(javax.security.auth.message.callback.SecretKeyCallback) Callback(javax.security.auth.callback.Callback) PasswordValidationCallback(javax.security.auth.message.callback.PasswordValidationCallback) PrivateKeyCallback(javax.security.auth.message.callback.PrivateKeyCallback) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException)

Example 40 with Subject

use of javax.security.auth.Subject in project jetty.project by eclipse.

the class AbstractLoginService method login.

/* ------------------------------------------------------------ */
/** 
     * @see org.eclipse.jetty.security.LoginService#login(java.lang.String, java.lang.Object, javax.servlet.ServletRequest)
     */
@Override
public UserIdentity login(String username, Object credentials, ServletRequest request) {
    if (username == null)
        return null;
    UserPrincipal userPrincipal = loadUserInfo(username);
    if (userPrincipal != null && userPrincipal.authenticate(credentials)) {
        //safe to load the roles
        String[] roles = loadRoleInfo(userPrincipal);
        Subject subject = new Subject();
        subject.getPrincipals().add(userPrincipal);
        subject.getPrivateCredentials().add(userPrincipal._credential);
        if (roles != null)
            for (String role : roles) subject.getPrincipals().add(new RolePrincipal(role));
        subject.setReadOnly();
        return _identityService.newUserIdentity(subject, userPrincipal, roles);
    }
    return null;
}
Also used : Subject(javax.security.auth.Subject)

Aggregations

Subject (javax.security.auth.Subject)669 Test (org.testng.annotations.Test)131 Test (org.junit.Test)122 HashMap (java.util.HashMap)120 Principal (java.security.Principal)114 HashSet (java.util.HashSet)109 Set (java.util.Set)82 EntitlementException (com.sun.identity.entitlement.EntitlementException)64 LoginContext (javax.security.auth.login.LoginContext)62 LoginException (javax.security.auth.login.LoginException)49 ConditionDecision (com.sun.identity.entitlement.ConditionDecision)47 ResourceResponse (org.forgerock.json.resource.ResourceResponse)47 RealmContext (org.forgerock.openam.rest.RealmContext)46 Context (org.forgerock.services.context.Context)41 SSOToken (com.iplanet.sso.SSOToken)40 IOException (java.io.IOException)40 ClientContext (org.forgerock.services.context.ClientContext)40 Map (java.util.Map)38 SSOTokenContext (org.forgerock.openam.rest.resource.SSOTokenContext)38 ResourceException (org.forgerock.json.resource.ResourceException)37