Example usage for org.apache.hadoop.security UserGroupInformation loginUserFromKeytab

List of usage examples for org.apache.hadoop.security UserGroupInformation loginUserFromKeytab

Introduction

In this page you can find the example usage for org.apache.hadoop.security UserGroupInformation loginUserFromKeytab.

Prototype

@InterfaceAudience.Public
@InterfaceStability.Evolving
public static void loginUserFromKeytab(String user, String path) throws IOException 

Source Link

Document

Log a user in from a keytab file.

Usage

From source file:org.apache.phoenix.jdbc.SecureUserConnectionsIT.java

License:Apache License

@Test
public void testAlternatingDestructiveLogins() throws Exception {
    final HashSet<ConnectionInfo> connections = new HashSet<>();
    final String princ1 = getUserPrincipal(1);
    final File keytab1 = getUserKeytabFile(1);
    final String princ2 = getUserPrincipal(2);
    final File keytab2 = getUserKeytabFile(2);
    final String url1 = joinUserAuthentication(BASE_URL, princ1, keytab1);
    final String url2 = joinUserAuthentication(BASE_URL, princ2, keytab2);

    UserGroupInformation.loginUserFromKeytab(princ1, keytab1.getPath());
    // Using the same UGI should result in two equivalent ConnectionInfo objects
    connections.add(ConnectionInfo.create(url1).normalize(ReadOnlyProps.EMPTY_PROPS, EMPTY_PROPERTIES));
    assertEquals(1, connections.size());
    // Sanity check
    verifyAllConnectionsAreKerberosBased(connections);

    UserGroupInformation.loginUserFromKeytab(princ2, keytab2.getPath());
    connections.add(ConnectionInfo.create(url2).normalize(ReadOnlyProps.EMPTY_PROPS, EMPTY_PROPERTIES));
    assertEquals(2, connections.size());
    verifyAllConnectionsAreKerberosBased(connections);

    // Because the UGI instances are unique, so are the connections
    UserGroupInformation.loginUserFromKeytab(princ1, keytab1.getPath());
    connections.add(ConnectionInfo.create(url1).normalize(ReadOnlyProps.EMPTY_PROPS, EMPTY_PROPERTIES));
    assertEquals(3, connections.size());
    verifyAllConnectionsAreKerberosBased(connections);
}

From source file:org.apache.phoenix.jdbc.SecureUserConnectionsIT.java

License:Apache License

@Test
public void testMultipleConnectionsAsSameUser() throws Exception {
    final HashSet<ConnectionInfo> connections = new HashSet<>();
    final String princ1 = getUserPrincipal(1);
    final File keytab1 = getUserKeytabFile(1);
    final String url = joinUserAuthentication(BASE_URL, princ1, keytab1);

    UserGroupInformation.loginUserFromKeytab(princ1, keytab1.getPath());
    // Using the same UGI should result in two equivalent ConnectionInfo objects
    connections.add(ConnectionInfo.create(url).normalize(ReadOnlyProps.EMPTY_PROPS, EMPTY_PROPERTIES));
    assertEquals(1, connections.size());
    // Sanity check
    verifyAllConnectionsAreKerberosBased(connections);

    // Because the UGI instances are unique, so are the connections
    connections.add(ConnectionInfo.create(url).normalize(ReadOnlyProps.EMPTY_PROPS, EMPTY_PROPERTIES));
    assertEquals(1, connections.size());
}

From source file:org.apache.phoenix.mapreduce.index.automation.PhoenixMRJobSubmitter.java

License:Apache License

private void enableKeyTabSecurity() throws IOException {

    final String PRINCIPAL = "principal";
    final String KEYTAB = "keyTab";
    // Login with the credentials from the keytab to retrieve the TGT . The
    // renewal of the TGT happens in a Zookeeper thread
    String principal = null;//from   w  w  w  .j a v  a2 s  . c o m
    String keyTabPath = null;
    AppConfigurationEntry entries[] = javax.security.auth.login.Configuration.getConfiguration()
            .getAppConfigurationEntry("Client");
    LOG.info("Security - Fetched App Login Configuration Entries");
    if (entries != null) {
        for (AppConfigurationEntry entry : entries) {
            if (entry.getOptions().get(PRINCIPAL) != null) {
                principal = (String) entry.getOptions().get(PRINCIPAL);
            }
            if (entry.getOptions().get(KEYTAB) != null) {
                keyTabPath = (String) entry.getOptions().get(KEYTAB);
            }
        }
        LOG.info("Security - Got Principal = " + principal + "");
        if (principal != null && keyTabPath != null) {
            LOG.info("Security - Retreiving the TGT with principal:" + principal + " and keytab:" + keyTabPath);
            UserGroupInformation.loginUserFromKeytab(principal, keyTabPath);
            LOG.info("Security - Retrieved TGT with principal:" + principal + " and keytab:" + keyTabPath);
        }
    }
}

From source file:org.apache.pig.backend.hadoop.HKerberos.java

License:Apache License

public static void tryKerberosKeytabLogin(Configuration conf) {
    // Before we can actually connect we may need to login using the provided credentials.
    if (UserGroupInformation.isSecurityEnabled()) {
        UserGroupInformation loginUser;//from w w w .  j  a  v  a2 s .  c  om
        try {
            loginUser = UserGroupInformation.getLoginUser();
        } catch (IOException e) {
            LOG.error("Unable to start attempt to login using Kerberos keytab: " + e.getMessage());
            return;
        }

        // If we are logged in into Kerberos with a keytab we can skip this to avoid needless logins
        if (!loginUser.hasKerberosCredentials() && !loginUser.isFromKeytab()) {
            String krb5Conf = conf.get("java.security.krb5.conf");
            String krb5Principal = conf.get("hadoop.security.krb5.principal");
            String krb5Keytab = conf.get("hadoop.security.krb5.keytab");

            // Only attempt login if we have all the required settings.
            if (krb5Conf != null && krb5Principal != null && krb5Keytab != null) {
                LOG.info("Trying login using Kerberos Keytab");
                LOG.info("krb5: Conf      = " + krb5Conf);
                LOG.info("krb5: Principal = " + krb5Principal);
                LOG.info("krb5: Keytab    = " + krb5Keytab);
                System.setProperty("java.security.krb5.conf", krb5Conf);
                try {
                    UserGroupInformation.loginUserFromKeytab(krb5Principal, krb5Keytab);
                } catch (IOException e) {
                    LOG.error("Unable to perform keytab based kerberos authentication: " + e.getMessage());
                }
            }
        }
    }
}

From source file:org.apache.sentry.api.service.thrift.SentryWebServer.java

License:Apache License

private static void validateConf(Configuration conf) {
    String authHandlerName = conf.get(ServerConfig.SENTRY_WEB_SECURITY_TYPE);
    Preconditions.checkNotNull(authHandlerName, "Web authHandler should not be null.");
    String allowUsers = conf.get(ServerConfig.SENTRY_WEB_SECURITY_ALLOW_CONNECT_USERS);
    Preconditions.checkNotNull(allowUsers, "Allow connect user(s) should not be null.");
    if (ServerConfig.SENTRY_WEB_SECURITY_TYPE_KERBEROS.equalsIgnoreCase(authHandlerName)) {
        String principal = conf.get(ServerConfig.SENTRY_WEB_SECURITY_PRINCIPAL);
        Preconditions.checkNotNull(principal, "Kerberos principal should not be null.");
        Preconditions.checkArgument(principal.length() != 0, "Kerberos principal is not right.");
        String keytabFile = conf.get(ServerConfig.SENTRY_WEB_SECURITY_KEYTAB);
        Preconditions.checkNotNull(keytabFile, "Keytab File should not be null.");
        Preconditions.checkArgument(keytabFile.length() != 0, "Keytab File is not right.");
        try {/*www. j  a v  a  2s .  c om*/
            UserGroupInformation.setConfiguration(conf);
            String hostPrincipal = SecurityUtil.getServerPrincipal(principal, ServerConfig.RPC_ADDRESS_DEFAULT);
            UserGroupInformation.loginUserFromKeytab(hostPrincipal, keytabFile);
        } catch (IOException ex) {
            throw new IllegalArgumentException("Can't use Kerberos authentication, principal [" + principal
                    + "] keytab [" + keytabFile + "]", ex);
        }
        LOGGER.info("Using Kerberos authentication, principal [{}] keytab [{}]", principal, keytabFile);
    }
}

From source file:org.apache.sentry.binding.hbaseindexer.authz.HBaseIndexerAuthzBinding.java

License:Apache License

/**
 * Initialize kerberos via UserGroupInformation.  Will only attempt to login
 * during the first request, subsequent calls will have no effect.
 * @param keytabFile path to keytab file
 * @param principal principal used for authentication
 * @throws IllegalArgumentException//from   w  ww .  ja v  a 2  s.  c  om
 */
private void initKerberos(String keytabFile, String principal) {
    if (keytabFile == null || keytabFile.length() == 0) {
        throw new IllegalArgumentException(String.format(
                "Setting keytab file path required when kerberos is enabled. Use %s configuration entry to define keytab file.",
                HBASE_REGIONSERVER_KEYTAB_FILE));
    }
    if (principal == null || principal.length() == 0) {
        throw new IllegalArgumentException(String.format(
                "Setting kerberos principal is required when kerberos is enabled. Use %s configuration entry to define principal.",
                HBASE_REGIONSERVER_KERBEROS_PRINCIPAL));
    }
    if (kerberosInit.compareAndSet(false, true)) { // init kerberos if kerberosInit is false, then set it to true
        // let's avoid modifying the supplied configuration, just to be conservative
        final Configuration ugiConf = new Configuration(authzConf);
        UserGroupInformation.setConfiguration(ugiConf);
        LOG.info(
                "Attempting to acquire kerberos ticket for HBase Indexer binding with keytab: {}, principal: {} ",
                keytabFile, principal);
        try {
            UserGroupInformation.loginUserFromKeytab(principal, keytabFile);
        } catch (IOException ioe) {
            kerberosInit.set(false);
            throw new RuntimeException(ioe);
        }
        LOG.info("Got Kerberos ticket for HBase Indexer binding");
    }

}

From source file:org.apache.sentry.binding.solr.authz.SentrySolrPluginImpl.java

License:Apache License

/**
 * Initialize kerberos via UserGroupInformation.  Will only attempt to login
 * during the first request, subsequent calls will have no effect.
 *//*from w  ww  .  ja v a 2s. com*/
private void initKerberos(SolrAuthzConf authzConf, String keytabFile, String principal) {
    synchronized (SentrySolrPluginImpl.class) {
        UserGroupInformation.setConfiguration(authzConf);
        LOG.info("Attempting to acquire kerberos ticket with keytab: {}, principal: {} ", keytabFile,
                principal);
        try {
            UserGroupInformation.loginUserFromKeytab(principal, keytabFile);
        } catch (IOException ioe) {
            throw new SolrException(ErrorCode.SERVER_ERROR, ioe);
        }
        LOG.info("Got Kerberos ticket");
    }
}

From source file:org.apache.sentry.hdfs.SentryHdfsServiceIntegrationBase.java

License:Apache License

@Before
public void before() throws Exception {
    conf.set("hadoop.security.authentication", "kerberos");
    UserGroupInformation.setConfiguration(conf);
    UserGroupInformation.loginUserFromKeytab(CLIENT_PRINCIPAL, clientKeytab.getPath());

    connectToHdfsSyncService();//from  ww w . j a  va 2 s  . co m
}

From source file:org.apache.sentry.kafka.binding.KafkaAuthBinding.java

License:Apache License

/**
 * Initialize kerberos via UserGroupInformation.  Will only attempt to login
 * during the first request, subsequent calls will have no effect.
 *//*from   ww w .ja va  2  s  . c o m*/
private void initKerberos(String keytabFile, String principal) {
    if (keytabFile == null || keytabFile.length() == 0) {
        throw new IllegalArgumentException("keytabFile required because kerberos is enabled");
    }
    if (principal == null || principal.length() == 0) {
        throw new IllegalArgumentException("principal required because kerberos is enabled");
    }
    synchronized (KafkaAuthBinding.class) {
        if (kerberosInit == null) {
            kerberosInit = Boolean.TRUE;
            // let's avoid modifying the supplied configuration, just to be conservative
            final Configuration ugiConf = new Configuration();
            ugiConf.set(HADOOP_SECURITY_AUTHENTICATION, ServiceConstants.ServerConfig.SECURITY_MODE_KERBEROS);
            UserGroupInformation.setConfiguration(ugiConf);
            LOG.info("Attempting to acquire kerberos ticket with keytab: {}, principal: {} ", keytabFile,
                    principal);
            try {
                UserGroupInformation.loginUserFromKeytab(principal, keytabFile);
            } catch (IOException ioe) {
                throw new RuntimeException(
                        "Failed to login user with Principal: " + principal + " and Keytab file: " + keytabFile,
                        ioe);
            }
            LOG.info("Got Kerberos ticket");
        }
    }
}

From source file:org.apache.sentry.service.thrift.SentryServiceIntegrationBase.java

License:Apache License

public static void setupConf() throws Exception {
    if (kerberos) {
        setupKdc();/*  w w  w . ja v  a 2  s  .c  om*/
        kdc = SentryMiniKdcTestcase.getKdc();
        kdcWorkDir = SentryMiniKdcTestcase.getWorkDir();
        serverKeytab = new File(kdcWorkDir, "server.keytab");
        clientKeytab = new File(kdcWorkDir, "client.keytab");
        kdc.createPrincipal(serverKeytab, SERVER_PRINCIPAL);
        kdc.createPrincipal(clientKeytab, CLIENT_PRINCIPAL);
        conf.set(ServerConfig.PRINCIPAL, getServerKerberosName());
        conf.set(ServerConfig.KEY_TAB, serverKeytab.getPath());
        conf.set(ServerConfig.ALLOW_CONNECT, CLIENT_KERBEROS_SHORT_NAME);
        conf.set(ServerConfig.SERVER_HA_ZOOKEEPER_CLIENT_PRINCIPAL, getServerKerberosName());
        conf.set(ServerConfig.SERVER_HA_ZOOKEEPER_CLIENT_KEYTAB, serverKeytab.getPath());

        conf.set(ServerConfig.SECURITY_USE_UGI_TRANSPORT, "true");
        conf.set("hadoop.security.authentication", "kerberos");
        UserGroupInformation.setConfiguration(conf);
        UserGroupInformation.loginUserFromKeytab(CLIENT_PRINCIPAL, clientKeytab.getPath());
        clientUgi = UserGroupInformation.getLoginUser();
    } else {
        LOGGER.info("Stopped KDC");
        conf.set(ServerConfig.SECURITY_MODE, ServerConfig.SECURITY_MODE_NONE);
    }

    if (webServerEnabled) {
        conf.set(ServerConfig.SENTRY_WEB_ENABLE, "true");
        conf.set(ServerConfig.SENTRY_WEB_PORT, String.valueOf(webServerPort));
        conf.set(ServerConfig.SENTRY_WEB_PUBSUB_SERVLET_ENABLED, "true");
        if (webSecurity) {
            httpKeytab = new File(kdcWorkDir, "http.keytab");
            kdc.createPrincipal(httpKeytab, HTTP_PRINCIPAL);
            conf.set(ServerConfig.SENTRY_WEB_SECURITY_TYPE, ServerConfig.SENTRY_WEB_SECURITY_TYPE_KERBEROS);
            conf.set(ServerConfig.SENTRY_WEB_SECURITY_PRINCIPAL, HTTP_PRINCIPAL);
            conf.set(ServerConfig.SENTRY_WEB_SECURITY_KEYTAB, httpKeytab.getPath());
            conf.set(ServerConfig.SENTRY_WEB_SECURITY_ALLOW_CONNECT_USERS, allowedUsers);
        } else {
            conf.set(ServerConfig.SENTRY_WEB_SECURITY_TYPE, ServerConfig.SENTRY_WEB_SECURITY_TYPE_NONE);
        }
    } else {
        conf.set(ServerConfig.SENTRY_WEB_ENABLE, "false");
    }
    if (pooled) {
        conf.set(ApiConstants.ClientConfig.SENTRY_POOL_ENABLED, "true");
    }
    if (useSSL) {
        String keystorePath = Resources.getResource("keystore.jks").getPath();
        conf.set(ServerConfig.SENTRY_WEB_USE_SSL, "true");
        conf.set(ServerConfig.SENTRY_WEB_SSL_KEYSTORE_PATH, keystorePath);
        conf.set(ServerConfig.SENTRY_WEB_SSL_KEYSTORE_PASSWORD, "password");

        LOGGER.debug("{} is at {}", ServerConfig.SENTRY_WEB_SSL_KEYSTORE_PATH, keystorePath);
    }
    conf.set(ServerConfig.SENTRY_VERIFY_SCHEM_VERSION, "false");
    conf.set(ServerConfig.ADMIN_GROUPS, ADMIN_GROUP);
    conf.set(ServerConfig.RPC_ADDRESS, SERVER_HOST);
    conf.set(ServerConfig.RPC_PORT, String.valueOf(0));
    dbDir = new File(Files.createTempDir(), "sentry_policy_db");
    conf.set(ServerConfig.SENTRY_STORE_JDBC_URL,
            "jdbc:derby:;databaseName=" + dbDir.getPath() + ";create=true");
    conf.set(ServerConfig.SENTRY_STORE_JDBC_PASS, "dummy");
    server = SentryServiceFactory.create(conf);
    conf.set(ApiConstants.ClientConfig.SERVER_RPC_ADDRESS, server.getAddress().getHostName());
    conf.set(ApiConstants.ClientConfig.SERVER_RPC_PORT, String.valueOf(server.getAddress().getPort()));
    conf.set(ServerConfig.SENTRY_STORE_GROUP_MAPPING, ServerConfig.SENTRY_STORE_LOCAL_GROUP_MAPPING);
}