Search in sources :

Example 1 with SaslServer

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

use of javax.security.sasl.SaslServer in project herddb by diennea.

the class SaslNettyServer method createSaslServer.

private SaslServer createSaslServer(final String mech, final Subject subject) throws SaslException, IOException {
    if (subject == null) {
        SaslDigestCallbackHandler ch = new SaslNettyServer.SaslDigestCallbackHandler();
        return Sasl.createSaslServer(mech, null, SaslUtils.DEFAULT_REALM, SaslUtils.getSaslProps(), ch);
    } else {
        SaslServerCallbackHandler callbackHandler = new SaslServerCallbackHandler(Configuration.getConfiguration());
        // server is using a JAAS-authenticated subject: determine service principal name and hostname from zk server's subject.
        if (subject.getPrincipals().size() > 0) {
            try {
                final Object[] principals = subject.getPrincipals().toArray();
                final Principal servicePrincipal = (Principal) principals[0];
                final String servicePrincipalNameAndHostname = servicePrincipal.getName();
                int indexOf = servicePrincipalNameAndHostname.indexOf("/");
                final String serviceHostnameAndKerbDomain = servicePrincipalNameAndHostname.substring(indexOf + 1, servicePrincipalNameAndHostname.length());
                int indexOfAt = serviceHostnameAndKerbDomain.indexOf("@");
                final String servicePrincipalName, serviceHostname;
                if (indexOf > 0) {
                    // e.g. servicePrincipalName := "zookeeper"
                    servicePrincipalName = servicePrincipalNameAndHostname.substring(0, indexOf);
                    // e.g. serviceHostname := "myhost.foo.com"
                    serviceHostname = serviceHostnameAndKerbDomain.substring(0, indexOfAt);
                } else {
                    servicePrincipalName = servicePrincipalNameAndHostname.substring(0, indexOfAt);
                    serviceHostname = null;
                }
                // TODO: should depend on zoo.cfg specified mechs, but if subject is non-null, it can be assumed to be GSSAPI.
                final String _mech = "GSSAPI";
                LOG.log(Level.INFO, "serviceHostname is ''{0}'', servicePrincipalName is ''{1}'', SASL mechanism(mech) is ''" + _mech + "'', Subject is ''{2}''", new Object[] { serviceHostname, servicePrincipalName, subject });
                try {
                    return Subject.doAs(subject, new PrivilegedExceptionAction<SaslServer>() {

                        public SaslServer run() {
                            try {
                                SaslServer saslServer;
                                saslServer = Sasl.createSaslServer(_mech, servicePrincipalName, serviceHostname, null, callbackHandler);
                                return saslServer;
                            } catch (SaslException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    });
                } catch (PrivilegedActionException e) {
                    // TODO: exit server at this point(?)
                    e.printStackTrace();
                }
            } catch (IndexOutOfBoundsException e) {
                throw new RuntimeException(e);
            }
        } else {
            try {
                SaslServer saslServer = Sasl.createSaslServer("DIGEST-MD5", "herddb", "herddb", null, callbackHandler);
                return saslServer;
            } catch (SaslException e) {
                e.printStackTrace();
            }
        }
    }
    LOG.severe("failed to create saslServer object.");
    return null;
}
Also used : PrivilegedActionException(java.security.PrivilegedActionException) SaslServer(javax.security.sasl.SaslServer) SaslException(javax.security.sasl.SaslException) Principal(java.security.Principal)

Example 3 with SaslServer

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

the class DefaultKafkaPrincipalBuilderTest method testPrincipalBuilderGssapi.

@Test
public void testPrincipalBuilderGssapi() throws Exception {
    SaslServer server = mock(SaslServer.class);
    KerberosShortNamer kerberosShortNamer = mock(KerberosShortNamer.class);
    EasyMock.expect(server.getMechanismName()).andReturn(SaslConfigs.GSSAPI_MECHANISM);
    EasyMock.expect(server.getAuthorizationID()).andReturn("foo/host@REALM.COM");
    EasyMock.expect(kerberosShortNamer.shortName(EasyMock.anyObject(KerberosName.class))).andReturn("foo");
    replayAll();
    DefaultKafkaPrincipalBuilder builder = new DefaultKafkaPrincipalBuilder(kerberosShortNamer);
    KafkaPrincipal principal = builder.build(new SaslAuthenticationContext(server, SecurityProtocol.SASL_PLAINTEXT, InetAddress.getLocalHost()));
    assertEquals(KafkaPrincipal.USER_TYPE, principal.getPrincipalType());
    assertEquals("foo", principal.getName());
    verifyAll();
}
Also used : KerberosShortNamer(org.apache.kafka.common.security.kerberos.KerberosShortNamer) DefaultKafkaPrincipalBuilder(org.apache.kafka.common.security.authenticator.DefaultKafkaPrincipalBuilder) SaslServer(javax.security.sasl.SaslServer) KerberosName(org.apache.kafka.common.security.kerberos.KerberosName) Test(org.junit.Test)

Example 4 with SaslServer

use of javax.security.sasl.SaslServer in project drill by axbaretto.

the class KerberosFactory method createSaslServer.

@Override
public SaslServer createSaslServer(final UserGroupInformation ugi, final Map<String, ?> properties) throws SaslException {
    final String qopValue = properties.containsKey(Sasl.QOP) ? properties.get(Sasl.QOP).toString() : "auth";
    try {
        final String primaryName = ugi.getShortUserName();
        final String instanceName = new HadoopKerberosName(ugi.getUserName()).getHostName();
        final SaslServer saslServer = ugi.doAs(new PrivilegedExceptionAction<SaslServer>() {

            @Override
            public SaslServer run() throws Exception {
                return FastSaslServerFactory.getInstance().createSaslServer(KerberosUtil.KERBEROS_SASL_NAME, primaryName, instanceName, properties, new KerberosServerCallbackHandler());
            }
        });
        logger.trace("GSSAPI SaslServer created with QOP {}.", qopValue);
        return saslServer;
    } catch (final UndeclaredThrowableException e) {
        final Throwable cause = e.getCause();
        logger.debug("Authentication failed.", cause);
        if (cause instanceof SaslException) {
            throw (SaslException) cause;
        } else {
            throw new SaslException(String.format("Unexpected failure trying to authenticate using Kerberos with QOP %s", qopValue), cause);
        }
    } catch (final IOException | InterruptedException e) {
        logger.debug("Authentication failed.", e);
        throw new SaslException(String.format("Unexpected failure trying to authenticate using Kerberos with QOP %s", qopValue), e);
    }
}
Also used : HadoopKerberosName(org.apache.hadoop.security.HadoopKerberosName) SaslServer(javax.security.sasl.SaslServer) IOException(java.io.IOException) SaslException(javax.security.sasl.SaslException) LoginException(javax.security.auth.login.LoginException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) SaslException(javax.security.sasl.SaslException) IOException(java.io.IOException) UndeclaredThrowableException(java.lang.reflect.UndeclaredThrowableException) InvocationTargetException(java.lang.reflect.InvocationTargetException) UndeclaredThrowableException(java.lang.reflect.UndeclaredThrowableException)

Example 5 with SaslServer

use of javax.security.sasl.SaslServer in project drill by apache.

the class KerberosFactory method createSaslServer.

@Override
public SaslServer createSaslServer(final UserGroupInformation ugi, final Map<String, ?> properties) throws SaslException {
    final String qopValue = properties.containsKey(Sasl.QOP) ? properties.get(Sasl.QOP).toString() : "auth";
    try {
        final String primaryName = ugi.getShortUserName();
        final String instanceName = new HadoopKerberosName(ugi.getUserName()).getHostName();
        final SaslServer saslServer = ugi.doAs(new PrivilegedExceptionAction<SaslServer>() {

            @Override
            public SaslServer run() throws Exception {
                return FastSaslServerFactory.getInstance().createSaslServer(KerberosUtil.KERBEROS_SASL_NAME, primaryName, instanceName, properties, new KerberosServerCallbackHandler());
            }
        });
        logger.trace("GSSAPI SaslServer created with QOP {}.", qopValue);
        return saslServer;
    } catch (final UndeclaredThrowableException e) {
        final Throwable cause = e.getCause();
        logger.debug("Authentication failed.", cause);
        if (cause instanceof SaslException) {
            throw (SaslException) cause;
        } else {
            throw new SaslException(String.format("Unexpected failure trying to authenticate using Kerberos with QOP %s", qopValue), cause);
        }
    } catch (final IOException | InterruptedException e) {
        logger.debug("Authentication failed.", e);
        throw new SaslException(String.format("Unexpected failure trying to authenticate using Kerberos with QOP %s", qopValue), e);
    }
}
Also used : HadoopKerberosName(org.apache.hadoop.security.HadoopKerberosName) SaslServer(javax.security.sasl.SaslServer) IOException(java.io.IOException) SaslException(javax.security.sasl.SaslException) LoginException(javax.security.auth.login.LoginException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) SaslException(javax.security.sasl.SaslException) IOException(java.io.IOException) UndeclaredThrowableException(java.lang.reflect.UndeclaredThrowableException) InvocationTargetException(java.lang.reflect.InvocationTargetException) UndeclaredThrowableException(java.lang.reflect.UndeclaredThrowableException)

Aggregations

SaslServer (javax.security.sasl.SaslServer)27 SaslException (javax.security.sasl.SaslException)12 IOException (java.io.IOException)8 PrivilegedActionException (java.security.PrivilegedActionException)7 UnsupportedCallbackException (javax.security.auth.callback.UnsupportedCallbackException)6 Principal (java.security.Principal)5 DefaultKafkaPrincipalBuilder (org.apache.kafka.common.security.authenticator.DefaultKafkaPrincipalBuilder)5 KerberosName (org.apache.kafka.common.security.kerberos.KerberosName)4 TSaslServerTransport (org.apache.thrift.transport.TSaslServerTransport)4 InetSocketAddress (java.net.InetSocketAddress)3 HashMap (java.util.HashMap)3 Callback (javax.security.auth.callback.Callback)3 LoginException (javax.security.auth.login.LoginException)3 AuthorizeCallback (javax.security.sasl.AuthorizeCallback)3 KerberosShortNamer (org.apache.kafka.common.security.kerberos.KerberosShortNamer)3 GSSCredential (org.ietf.jgss.GSSCredential)3 GSSException (org.ietf.jgss.GSSException)3 GSSManager (org.ietf.jgss.GSSManager)3 GSSName (org.ietf.jgss.GSSName)3 Oid (org.ietf.jgss.Oid)3