Search in sources :

Example 1 with UnsupportedCallbackException

use of javax.security.auth.callback.UnsupportedCallbackException 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 2 with UnsupportedCallbackException

use of javax.security.auth.callback.UnsupportedCallbackException in project jetty.project by eclipse.

the class LdapLoginModule method login.

/**
     * since ldap uses a context bind for valid authentication checking, we override login()
     * <p>
     * if credentials are not available from the users context or if we are forcing the binding check
     * then we try a binding authentication check, otherwise if we have the users encoded password then
     * we can try authentication via that mechanic
     *
     * @return true if authenticated, false otherwise
     * @throws LoginException if unable to login
     */
public boolean login() throws LoginException {
    try {
        if (getCallbackHandler() == null) {
            throw new LoginException("No callback handler");
        }
        Callback[] callbacks = configureCallbacks();
        getCallbackHandler().handle(callbacks);
        String webUserName = ((NameCallback) callbacks[0]).getName();
        Object webCredential = ((ObjectCallback) callbacks[1]).getObject();
        if (webUserName == null || webCredential == null) {
            setAuthenticated(false);
            return isAuthenticated();
        }
        boolean authed = false;
        if (_forceBindingLogin) {
            authed = bindingLogin(webUserName, webCredential);
        } else {
            // This sets read and the credential
            UserInfo userInfo = getUserInfo(webUserName);
            if (userInfo == null) {
                setAuthenticated(false);
                return false;
            }
            setCurrentUser(new JAASUserInfo(userInfo));
            if (webCredential instanceof String)
                authed = credentialLogin(Credential.getCredential((String) webCredential));
            else
                authed = credentialLogin(webCredential);
        }
        //only fetch roles if authenticated
        if (authed)
            getCurrentUser().fetchRoles();
        return authed;
    } catch (UnsupportedCallbackException e) {
        throw new LoginException("Error obtaining callback information.");
    } catch (IOException e) {
        if (_debug) {
            e.printStackTrace();
        }
        throw new LoginException("IO Error performing login.");
    } catch (Exception e) {
        if (_debug) {
            e.printStackTrace();
        }
        throw new LoginException("Error obtaining user info.");
    }
}
Also used : ObjectCallback(org.eclipse.jetty.jaas.callback.ObjectCallback) IOException(java.io.IOException) LoginException(javax.security.auth.login.LoginException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) NamingException(javax.naming.NamingException) IOException(java.io.IOException) ObjectCallback(org.eclipse.jetty.jaas.callback.ObjectCallback) NameCallback(javax.security.auth.callback.NameCallback) Callback(javax.security.auth.callback.Callback) NameCallback(javax.security.auth.callback.NameCallback) LoginException(javax.security.auth.login.LoginException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException)

Example 3 with UnsupportedCallbackException

use of javax.security.auth.callback.UnsupportedCallbackException in project jetty.project by eclipse.

the class FormAuthModule method validateRequest.

@Override
public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject) throws AuthException {
    HttpServletRequest request = (HttpServletRequest) messageInfo.getRequestMessage();
    HttpServletResponse response = (HttpServletResponse) messageInfo.getResponseMessage();
    String uri = request.getRequestURI();
    if (uri == null)
        uri = URIUtil.SLASH;
    boolean mandatory = isMandatory(messageInfo);
    mandatory |= isJSecurityCheck(uri);
    HttpSession session = request.getSession(mandatory);
    // not mandatory or its the login or login error page don't authenticate
    if (!mandatory || isLoginOrErrorPage(URIUtil.addPaths(request.getServletPath(), request.getPathInfo())))
        // TODO return null for do nothing?
        return AuthStatus.SUCCESS;
    try {
        // Handle a request for authentication.
        if (isJSecurityCheck(uri)) {
            final String username = request.getParameter(__J_USERNAME);
            final String password = request.getParameter(__J_PASSWORD);
            boolean success = tryLogin(messageInfo, clientSubject, response, session, username, new Password(password));
            if (success) {
                // Redirect to original request                    
                String nuri = null;
                synchronized (session) {
                    nuri = (String) session.getAttribute(__J_URI);
                }
                if (nuri == null || nuri.length() == 0) {
                    nuri = request.getContextPath();
                    if (nuri.length() == 0)
                        nuri = URIUtil.SLASH;
                }
                response.setContentLength(0);
                response.sendRedirect(response.encodeRedirectURL(nuri));
                return AuthStatus.SEND_CONTINUE;
            }
            // not authenticated
            if (LOG.isDebugEnabled())
                LOG.debug("Form authentication FAILED for " + StringUtil.printable(username));
            if (_formErrorPage == null) {
                if (response != null)
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
            } else {
                response.setContentLength(0);
                response.sendRedirect(response.encodeRedirectURL(URIUtil.addPaths(request.getContextPath(), _formErrorPage)));
            }
            // that occur?
            return AuthStatus.SEND_FAILURE;
        }
        // Check if the session is already authenticated.
        SessionAuthentication sessionAuth = (SessionAuthentication) session.getAttribute(SessionAuthentication.__J_AUTHENTICATED);
        if (sessionAuth != null) {
            //to FormAuthModule
            if (sessionAuth.getUserIdentity().getSubject() == null)
                return AuthStatus.SEND_FAILURE;
            Set<Object> credentials = sessionAuth.getUserIdentity().getSubject().getPrivateCredentials();
            if (credentials == null || credentials.isEmpty())
                //if no private credentials, assume it cannot be authenticated
                return AuthStatus.SEND_FAILURE;
            clientSubject.getPrivateCredentials().addAll(credentials);
            clientSubject.getPrivateCredentials().add(sessionAuth.getUserIdentity());
            return AuthStatus.SUCCESS;
        }
        // if we can't send challenge
        if (DeferredAuthentication.isDeferred(response))
            return AuthStatus.SUCCESS;
        // redirect to login page  
        StringBuffer buf = request.getRequestURL();
        if (request.getQueryString() != null)
            buf.append("?").append(request.getQueryString());
        synchronized (session) {
            session.setAttribute(__J_URI, buf.toString());
        }
        response.setContentLength(0);
        response.sendRedirect(response.encodeRedirectURL(URIUtil.addPaths(request.getContextPath(), _formLoginPage)));
        return AuthStatus.SEND_CONTINUE;
    } catch (IOException e) {
        throw new AuthException(e.getMessage());
    } catch (UnsupportedCallbackException e) {
        throw new AuthException(e.getMessage());
    }
}
Also used : HttpSession(javax.servlet.http.HttpSession) HttpServletResponse(javax.servlet.http.HttpServletResponse) AuthException(javax.security.auth.message.AuthException) SessionAuthentication(org.eclipse.jetty.security.authentication.SessionAuthentication) IOException(java.io.IOException) HttpServletRequest(javax.servlet.http.HttpServletRequest) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) Password(org.eclipse.jetty.util.security.Password)

Example 4 with UnsupportedCallbackException

use of javax.security.auth.callback.UnsupportedCallbackException in project hbase by apache.

the class TestHBaseSaslRpcClient method testSaslClientCallbackHandlerWithException.

@Test
public void testSaslClientCallbackHandlerWithException() {
    final Token<? extends TokenIdentifier> token = createTokenMock();
    when(token.getIdentifier()).thenReturn(DEFAULT_USER_NAME.getBytes());
    when(token.getPassword()).thenReturn(DEFAULT_USER_PASSWORD.getBytes());
    final SaslClientCallbackHandler saslClCallbackHandler = new SaslClientCallbackHandler(token);
    try {
        saslClCallbackHandler.handle(new Callback[] { mock(TextOutputCallback.class) });
    } catch (UnsupportedCallbackException expEx) {
    //expected
    } catch (Exception ex) {
        fail("testSaslClientCallbackHandlerWithException error : " + ex.getMessage());
    }
}
Also used : TextOutputCallback(javax.security.auth.callback.TextOutputCallback) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) SaslClientCallbackHandler(org.apache.hadoop.hbase.security.AbstractHBaseSaslRpcClient.SaslClientCallbackHandler) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) ExpectedException(org.junit.rules.ExpectedException) IOException(java.io.IOException) Test(org.junit.Test)

Example 5 with UnsupportedCallbackException

use of javax.security.auth.callback.UnsupportedCallbackException in project hbase by apache.

the class ThriftServerRunner method setupServer.

/**
   * Setting up the thrift TServer
   */
private void setupServer() throws Exception {
    // Construct correct ProtocolFactory
    TProtocolFactory protocolFactory;
    if (conf.getBoolean(COMPACT_CONF_KEY, false)) {
        LOG.debug("Using compact protocol");
        protocolFactory = new TCompactProtocol.Factory();
    } else {
        LOG.debug("Using binary protocol");
        protocolFactory = new TBinaryProtocol.Factory();
    }
    final TProcessor p = new Hbase.Processor<>(handler);
    ImplType implType = ImplType.getServerImpl(conf);
    TProcessor processor = p;
    // Construct correct TransportFactory
    TTransportFactory transportFactory;
    if (conf.getBoolean(FRAMED_CONF_KEY, false) || implType.isAlwaysFramed) {
        if (qop != null) {
            throw new RuntimeException("Thrift server authentication" + " doesn't work with framed transport yet");
        }
        transportFactory = new TFramedTransport.Factory(conf.getInt(MAX_FRAME_SIZE_CONF_KEY, 2) * 1024 * 1024);
        LOG.debug("Using framed transport");
    } else if (qop == null) {
        transportFactory = new TTransportFactory();
    } else {
        // Extract the name from the principal
        String name = SecurityUtil.getUserFromPrincipal(conf.get("hbase.thrift.kerberos.principal"));
        Map<String, String> saslProperties = new HashMap<>();
        saslProperties.put(Sasl.QOP, qop);
        TSaslServerTransport.Factory saslFactory = new TSaslServerTransport.Factory();
        saslFactory.addServerDefinition("GSSAPI", name, host, saslProperties, new SaslGssCallbackHandler() {

            @Override
            public void handle(Callback[] callbacks) throws UnsupportedCallbackException {
                AuthorizeCallback ac = null;
                for (Callback callback : callbacks) {
                    if (callback instanceof AuthorizeCallback) {
                        ac = (AuthorizeCallback) callback;
                    } else {
                        throw new UnsupportedCallbackException(callback, "Unrecognized SASL GSSAPI Callback");
                    }
                }
                if (ac != null) {
                    String authid = ac.getAuthenticationID();
                    String authzid = ac.getAuthorizationID();
                    if (!authid.equals(authzid)) {
                        ac.setAuthorized(false);
                    } else {
                        ac.setAuthorized(true);
                        String userName = SecurityUtil.getUserFromPrincipal(authzid);
                        LOG.info("Effective user: " + userName);
                        ac.setAuthorizedID(userName);
                    }
                }
            }
        });
        transportFactory = saslFactory;
        // Create a processor wrapper, to get the caller
        processor = new TProcessor() {

            @Override
            public boolean process(TProtocol inProt, TProtocol outProt) throws TException {
                TSaslServerTransport saslServerTransport = (TSaslServerTransport) inProt.getTransport();
                SaslServer saslServer = saslServerTransport.getSaslServer();
                String principal = saslServer.getAuthorizationID();
                hbaseHandler.setEffectiveUser(principal);
                return p.process(inProt, outProt);
            }
        };
    }
    if (conf.get(BIND_CONF_KEY) != null && !implType.canSpecifyBindIP) {
        LOG.error("Server types " + Joiner.on(", ").join(ImplType.serversThatCannotSpecifyBindIP()) + " don't support IP " + "address binding at the moment. See " + "https://issues.apache.org/jira/browse/HBASE-2155 for details.");
        throw new RuntimeException("-" + BIND_CONF_KEY + " not supported with " + implType);
    }
    // Thrift's implementation uses '0' as a placeholder for 'use the default.'
    int backlog = conf.getInt(BACKLOG_CONF_KEY, 0);
    if (implType == ImplType.HS_HA || implType == ImplType.NONBLOCKING || implType == ImplType.THREADED_SELECTOR) {
        InetAddress listenAddress = getBindAddress(conf);
        TNonblockingServerTransport serverTransport = new TNonblockingServerSocket(new InetSocketAddress(listenAddress, listenPort));
        if (implType == ImplType.NONBLOCKING) {
            TNonblockingServer.Args serverArgs = new TNonblockingServer.Args(serverTransport);
            serverArgs.processor(processor).transportFactory(transportFactory).protocolFactory(protocolFactory);
            tserver = new TNonblockingServer(serverArgs);
        } else if (implType == ImplType.HS_HA) {
            THsHaServer.Args serverArgs = new THsHaServer.Args(serverTransport);
            CallQueue callQueue = new CallQueue(new LinkedBlockingQueue<>(), metrics);
            ExecutorService executorService = createExecutor(callQueue, serverArgs.getMaxWorkerThreads(), serverArgs.getMaxWorkerThreads());
            serverArgs.executorService(executorService).processor(processor).transportFactory(transportFactory).protocolFactory(protocolFactory);
            tserver = new THsHaServer(serverArgs);
        } else {
            // THREADED_SELECTOR
            TThreadedSelectorServer.Args serverArgs = new HThreadedSelectorServerArgs(serverTransport, conf);
            CallQueue callQueue = new CallQueue(new LinkedBlockingQueue<>(), metrics);
            ExecutorService executorService = createExecutor(callQueue, serverArgs.getWorkerThreads(), serverArgs.getWorkerThreads());
            serverArgs.executorService(executorService).processor(processor).transportFactory(transportFactory).protocolFactory(protocolFactory);
            tserver = new TThreadedSelectorServer(serverArgs);
        }
        LOG.info("starting HBase " + implType.simpleClassName() + " server on " + Integer.toString(listenPort));
    } else if (implType == ImplType.THREAD_POOL) {
        // Thread pool server. Get the IP address to bind to.
        InetAddress listenAddress = getBindAddress(conf);
        int readTimeout = conf.getInt(THRIFT_SERVER_SOCKET_READ_TIMEOUT_KEY, THRIFT_SERVER_SOCKET_READ_TIMEOUT_DEFAULT);
        TServerTransport serverTransport = new TServerSocket(new TServerSocket.ServerSocketTransportArgs().bindAddr(new InetSocketAddress(listenAddress, listenPort)).backlog(backlog).clientTimeout(readTimeout));
        TBoundedThreadPoolServer.Args serverArgs = new TBoundedThreadPoolServer.Args(serverTransport, conf);
        serverArgs.processor(processor).transportFactory(transportFactory).protocolFactory(protocolFactory);
        LOG.info("starting " + ImplType.THREAD_POOL.simpleClassName() + " on " + listenAddress + ":" + Integer.toString(listenPort) + " with readTimeout " + readTimeout + "ms; " + serverArgs);
        TBoundedThreadPoolServer tserver = new TBoundedThreadPoolServer(serverArgs, metrics);
        this.tserver = tserver;
    } else {
        throw new AssertionError("Unsupported Thrift server implementation: " + implType.simpleClassName());
    }
    // A sanity check that we instantiated the right type of server.
    if (tserver.getClass() != implType.serverClass) {
        throw new AssertionError("Expected to create Thrift server class " + implType.serverClass.getName() + " but got " + tserver.getClass().getName());
    }
    registerFilters(conf);
}
Also used : TProtocolFactory(org.apache.thrift.protocol.TProtocolFactory) TNonblockingServerTransport(org.apache.thrift.transport.TNonblockingServerTransport) TProcessor(org.apache.thrift.TProcessor) SaslServer(javax.security.sasl.SaslServer) InetSocketAddress(java.net.InetSocketAddress) TThreadedSelectorServer(org.apache.thrift.server.TThreadedSelectorServer) LogFactory(org.apache.commons.logging.LogFactory) TProtocolFactory(org.apache.thrift.protocol.TProtocolFactory) TTransportFactory(org.apache.thrift.transport.TTransportFactory) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) TCompactProtocol(org.apache.thrift.protocol.TCompactProtocol) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) AuthorizeCallback(javax.security.sasl.AuthorizeCallback) TServerSocket(org.apache.thrift.transport.TServerSocket) THsHaServer(org.apache.thrift.server.THsHaServer) TProcessor(org.apache.thrift.TProcessor) TProtocol(org.apache.thrift.protocol.TProtocol) TFramedTransport(org.apache.thrift.transport.TFramedTransport) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) TTransportFactory(org.apache.thrift.transport.TTransportFactory) TNonblockingServer(org.apache.thrift.server.TNonblockingServer) TServerTransport(org.apache.thrift.transport.TServerTransport) TSaslServerTransport(org.apache.thrift.transport.TSaslServerTransport) SaslGssCallbackHandler(org.apache.hadoop.security.SaslRpcServer.SaslGssCallbackHandler) Callback(javax.security.auth.callback.Callback) AuthorizeCallback(javax.security.sasl.AuthorizeCallback) TBinaryProtocol(org.apache.thrift.protocol.TBinaryProtocol) TNonblockingServerSocket(org.apache.thrift.transport.TNonblockingServerSocket) ExecutorService(java.util.concurrent.ExecutorService) Map(java.util.Map) TreeMap(java.util.TreeMap) HashMap(java.util.HashMap) InetAddress(java.net.InetAddress)

Aggregations

UnsupportedCallbackException (javax.security.auth.callback.UnsupportedCallbackException)323 Callback (javax.security.auth.callback.Callback)205 IOException (java.io.IOException)195 NameCallback (javax.security.auth.callback.NameCallback)175 PasswordCallback (javax.security.auth.callback.PasswordCallback)171 LoginException (javax.security.auth.login.LoginException)86 CallbackHandler (javax.security.auth.callback.CallbackHandler)61 FailedLoginException (javax.security.auth.login.FailedLoginException)44 LoginContext (javax.security.auth.login.LoginContext)41 Subject (javax.security.auth.Subject)35 Principal (java.security.Principal)31 RealmCallback (javax.security.sasl.RealmCallback)27 HttpServletRequest (javax.servlet.http.HttpServletRequest)27 AuthorizeCallback (javax.security.sasl.AuthorizeCallback)26 HashMap (java.util.HashMap)23 CallerPrincipalCallback (javax.security.auth.message.callback.CallerPrincipalCallback)23 Test (org.junit.Test)21 GroupPrincipalCallback (javax.security.auth.message.callback.GroupPrincipalCallback)20 AuthException (javax.security.auth.message.AuthException)18 SaslException (javax.security.sasl.SaslException)18