Search in sources :

Example 1 with AuthorizeCallback

use of javax.security.sasl.AuthorizeCallback 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)

Example 2 with AuthorizeCallback

use of javax.security.sasl.AuthorizeCallback in project hbase by apache.

the class ThriftServer method getTTransportFactory.

private static TTransportFactory getTTransportFactory(SaslUtil.QualityOfProtection qop, String name, String host, boolean framed, int frameSize) {
    if (framed) {
        if (qop != null) {
            throw new RuntimeException("Thrift server authentication" + " doesn't work with framed transport yet");
        }
        log.debug("Using framed transport");
        return new TFramedTransport.Factory(frameSize);
    } else if (qop == null) {
        return new TTransportFactory();
    } else {
        Map<String, String> saslProperties = new HashMap<>();
        saslProperties.put(Sasl.QOP, qop.getSaslQop());
        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);
                    }
                }
            }
        });
        return saslFactory;
    }
}
Also used : TSaslServerTransport(org.apache.thrift.transport.TSaslServerTransport) SaslGssCallbackHandler(org.apache.hadoop.security.SaslRpcServer.SaslGssCallbackHandler) AuthorizeCallback(javax.security.sasl.AuthorizeCallback) Callback(javax.security.auth.callback.Callback) LogFactory(org.apache.commons.logging.LogFactory) TTransportFactory(org.apache.thrift.transport.TTransportFactory) TProtocolFactory(org.apache.thrift.protocol.TProtocolFactory) TTransportFactory(org.apache.thrift.transport.TTransportFactory) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) Map(java.util.Map) HashMap(java.util.HashMap) AuthorizeCallback(javax.security.sasl.AuthorizeCallback)

Example 3 with AuthorizeCallback

use of javax.security.sasl.AuthorizeCallback in project alluxio by Alluxio.

the class PlainSaslServer method evaluateResponse.

@Override
public byte[] evaluateResponse(byte[] response) throws SaslException {
    Preconditions.checkState(!mCompleted, "PLAIN authentication has completed");
    Preconditions.checkArgument(response != null, "Received null response");
    try {
        // parse the response
        // message = [authorizationId] UTF8NUL authenticationId UTF8NUL passwd'
        // authorizationId may be empty,then the authorizationId = authenticationId
        String payload;
        try {
            payload = new String(response, "UTF-8");
        } catch (Exception e) {
            throw new IllegalArgumentException("Received corrupt response", e);
        }
        String[] parts = payload.split("", 3);
        // validate response
        if (parts.length != 3) {
            throw new IllegalArgumentException("Invalid message format, parts must contain 3 items");
        }
        String authorizationId = parts[0];
        String authenticationId = parts[1];
        String passwd = parts[2];
        Preconditions.checkState(authenticationId != null && !authenticationId.isEmpty(), "No authentication identity provided");
        Preconditions.checkState(passwd != null && !passwd.isEmpty(), "No password provided");
        if (authorizationId == null || authorizationId.isEmpty()) {
            authorizationId = authenticationId;
        } else if (!authorizationId.equals(authenticationId)) {
            // TODO(dong): support impersonation
            throw new UnsupportedOperationException("Impersonation is not supported now.");
        }
        NameCallback nameCallback = new NameCallback("User");
        nameCallback.setName(authenticationId);
        PasswordCallback passwordCallback = new PasswordCallback("Password", false);
        passwordCallback.setPassword(passwd.toCharArray());
        AuthorizeCallback authCallback = new AuthorizeCallback(authenticationId, authorizationId);
        Callback[] cbList = { nameCallback, passwordCallback, authCallback };
        mHandler.handle(cbList);
        if (!authCallback.isAuthorized()) {
            throw new SaslException("AuthorizeCallback authorized failure");
        }
        mAuthorizationId = authCallback.getAuthorizedID();
    } catch (Exception e) {
        throw new SaslException("Plain authentication failed: " + e.getMessage(), e);
    }
    mCompleted = true;
    return null;
}
Also used : NameCallback(javax.security.auth.callback.NameCallback) PasswordCallback(javax.security.auth.callback.PasswordCallback) NameCallback(javax.security.auth.callback.NameCallback) AuthorizeCallback(javax.security.sasl.AuthorizeCallback) Callback(javax.security.auth.callback.Callback) PasswordCallback(javax.security.auth.callback.PasswordCallback) SaslException(javax.security.sasl.SaslException) SaslException(javax.security.sasl.SaslException) AuthorizeCallback(javax.security.sasl.AuthorizeCallback)

Example 4 with AuthorizeCallback

use of javax.security.sasl.AuthorizeCallback in project jdk8u_jdk by JetBrains.

the class PropertiesFileCallbackHandler method handle.

public void handle(Callback[] callbacks) throws UnsupportedCallbackException {
    NameCallback ncb = null;
    PasswordCallback pcb = null;
    AuthorizeCallback acb = null;
    RealmCallback rcb = null;
    for (int i = 0; i < callbacks.length; i++) {
        if (callbacks[i] instanceof NameCallback) {
            ncb = (NameCallback) callbacks[i];
        } else if (callbacks[i] instanceof PasswordCallback) {
            pcb = (PasswordCallback) callbacks[i];
        } else if (callbacks[i] instanceof AuthorizeCallback) {
            acb = (AuthorizeCallback) callbacks[i];
        } else if (callbacks[i] instanceof RealmCallback) {
            rcb = (RealmCallback) callbacks[i];
        } else {
            throw new UnsupportedCallbackException(callbacks[i]);
        }
    }
    if (pcb != null && ncb != null) {
        String username = ncb.getDefaultName();
        String pw = pwDb.getProperty(username);
        if (pw != null) {
            char[] pwchars = pw.toCharArray();
            pcb.setPassword(pwchars);
            // Clear pw
            for (int i = 0; i < pwchars.length; i++) {
                pwchars[i] = 0;
            }
            // Set canonicalized username if any
            String canonAuthid = (namesDb != null ? namesDb.getProperty(username) : null);
            if (canonAuthid != null) {
                ncb.setName(canonAuthid);
            }
        }
    }
    if (acb != null) {
        String authid = acb.getAuthenticationID();
        String authzid = acb.getAuthorizationID();
        if (authid.equals(authzid)) {
            // Self is always authorized
            acb.setAuthorized(true);
        } else {
            // Check db for allowed authzids
            String authzes = (proxyDb != null ? proxyDb.getProperty(authid) : null);
            if (authzes != null && authzes.indexOf(authzid) >= 0) {
                // XXX need to search for subtrings or use StringTokenizer
                // to avoid incorrectly matching subnames
                acb.setAuthorized(true);
            }
        }
        if (acb.isAuthorized()) {
            // Set canonicalized name
            String canonAuthzid = (namesDb != null ? namesDb.getProperty(authzid) : null);
            if (canonAuthzid != null) {
                acb.setAuthorizedID(canonAuthzid);
            }
        }
    }
}
Also used : AuthorizeCallback(javax.security.sasl.AuthorizeCallback) RealmCallback(javax.security.sasl.RealmCallback)

Example 5 with AuthorizeCallback

use of javax.security.sasl.AuthorizeCallback in project apache-kafka-on-k8s by banzaicloud.

the class SaslClientCallbackHandler method handle.

@Override
public void handle(Callback[] callbacks) throws UnsupportedCallbackException {
    for (Callback callback : callbacks) {
        if (callback instanceof NameCallback) {
            NameCallback nc = (NameCallback) callback;
            if (!isKerberos && subject != null && !subject.getPublicCredentials(String.class).isEmpty()) {
                nc.setName(subject.getPublicCredentials(String.class).iterator().next());
            } else
                nc.setName(nc.getDefaultName());
        } else if (callback instanceof PasswordCallback) {
            if (!isKerberos && subject != null && !subject.getPrivateCredentials(String.class).isEmpty()) {
                char[] password = subject.getPrivateCredentials(String.class).iterator().next().toCharArray();
                ((PasswordCallback) callback).setPassword(password);
            } else {
                String errorMessage = "Could not login: the client is being asked for a password, but the Kafka" + " client code does not currently support obtaining a password from the user.";
                if (isKerberos) {
                    errorMessage += " Make sure -Djava.security.auth.login.config property passed to JVM and" + " the client is configured to use a ticket cache (using" + " the JAAS configuration setting 'useTicketCache=true)'. Make sure you are using" + " FQDN of the Kafka broker you are trying to connect to.";
                }
                throw new UnsupportedCallbackException(callback, errorMessage);
            }
        } else if (callback instanceof RealmCallback) {
            RealmCallback rc = (RealmCallback) callback;
            rc.setText(rc.getDefaultText());
        } else if (callback instanceof AuthorizeCallback) {
            AuthorizeCallback ac = (AuthorizeCallback) callback;
            String authId = ac.getAuthenticationID();
            String authzId = ac.getAuthorizationID();
            ac.setAuthorized(authId.equals(authzId));
            if (ac.isAuthorized())
                ac.setAuthorizedID(authzId);
        } else if (callback instanceof ScramExtensionsCallback) {
            ScramExtensionsCallback sc = (ScramExtensionsCallback) callback;
            if (!isKerberos && subject != null && !subject.getPublicCredentials(Map.class).isEmpty()) {
                sc.extensions((Map<String, String>) subject.getPublicCredentials(Map.class).iterator().next());
            }
        } else {
            throw new UnsupportedCallbackException(callback, "Unrecognized SASL ClientCallback");
        }
    }
}
Also used : RealmCallback(javax.security.sasl.RealmCallback) PasswordCallback(javax.security.auth.callback.PasswordCallback) NameCallback(javax.security.auth.callback.NameCallback) ScramExtensionsCallback(org.apache.kafka.common.security.scram.ScramExtensionsCallback) AuthorizeCallback(javax.security.sasl.AuthorizeCallback) Callback(javax.security.auth.callback.Callback) NameCallback(javax.security.auth.callback.NameCallback) ScramExtensionsCallback(org.apache.kafka.common.security.scram.ScramExtensionsCallback) PasswordCallback(javax.security.auth.callback.PasswordCallback) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) Map(java.util.Map) AuthorizeCallback(javax.security.sasl.AuthorizeCallback) RealmCallback(javax.security.sasl.RealmCallback)

Aggregations

AuthorizeCallback (javax.security.sasl.AuthorizeCallback)36 Callback (javax.security.auth.callback.Callback)29 NameCallback (javax.security.auth.callback.NameCallback)28 PasswordCallback (javax.security.auth.callback.PasswordCallback)26 UnsupportedCallbackException (javax.security.auth.callback.UnsupportedCallbackException)26 RealmCallback (javax.security.sasl.RealmCallback)16 IOException (java.io.IOException)12 SaslException (javax.security.sasl.SaslException)9 HashMap (java.util.HashMap)5 Map (java.util.Map)5 SaslServer (javax.security.sasl.SaslServer)3 TProtocolFactory (org.apache.thrift.protocol.TProtocolFactory)3 TSaslServerTransport (org.apache.thrift.transport.TSaslServerTransport)3 TTransportFactory (org.apache.thrift.transport.TTransportFactory)3 InetAddress (java.net.InetAddress)2 InetSocketAddress (java.net.InetSocketAddress)2 ArrayDeque (java.util.ArrayDeque)2 List (java.util.List)2 ExecutorService (java.util.concurrent.ExecutorService)2 LinkedBlockingQueue (java.util.concurrent.LinkedBlockingQueue)2