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

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

Introduction

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

Prototype

public static UserGroupInformation loginUserFromKeytabAndReturnUGI(String user, String path)
        throws IOException 

Source Link

Document

Log a user in from a keytab file.

Usage

From source file:org.apache.drill.exec.rpc.security.kerberos.KerberosFactory.java

License:Apache License

@Override
public UserGroupInformation createAndLoginUser(final Map<String, ?> properties) throws IOException {
    final Configuration conf = new Configuration();
    conf.set(CommonConfigurationKeys.HADOOP_SECURITY_AUTHENTICATION,
            UserGroupInformation.AuthenticationMethod.KERBEROS.toString());
    UserGroupInformation.setConfiguration(conf);

    final String keytab = (String) properties.get(DrillProperties.KEYTAB);
    final boolean assumeSubject = properties.containsKey(DrillProperties.KERBEROS_FROM_SUBJECT)
            && Boolean.parseBoolean((String) properties.get(DrillProperties.KERBEROS_FROM_SUBJECT));
    try {//from   w  w w  .  ja va  2 s . c o  m
        final UserGroupInformation ugi;
        if (assumeSubject) {
            ugi = UserGroupInformation.getUGIFromSubject(Subject.getSubject(AccessController.getContext()));
            logger.debug("Assuming subject for {}.", ugi.getShortUserName());
        } else {
            if (keytab != null) {
                ugi = UserGroupInformation
                        .loginUserFromKeytabAndReturnUGI((String) properties.get(DrillProperties.USER), keytab);
                logger.debug("Logged in {} using keytab.", ugi.getShortUserName());
            } else {
                // includes Kerberos ticket login
                ugi = UserGroupInformation.getCurrentUser();
                logger.debug("Logged in {} using ticket.", ugi.getShortUserName());
            }
        }
        return ugi;
    } catch (final IOException e) {
        logger.debug("Login failed.", e);
        final Throwable cause = e.getCause();
        if (cause instanceof LoginException) {
            throw new SaslException("Failed to login.", cause);
        }
        throw new SaslException("Unexpected failure trying to login.", cause);
    }
}

From source file:org.apache.drill.exec.server.rest.auth.SpnegoConfig.java

License:Apache License

private UserGroupInformation loginAndReturnUgi() throws DrillException {

    validateSpnegoConfig();/*ww w.  jav  a 2  s  .  co m*/

    UserGroupInformation ugi;
    try {
        // Check if security is not enabled and try to set the security parameter to login the principal.
        // After the login is performed reset the static UGI state.
        if (!UserGroupInformation.isSecurityEnabled()) {
            final Configuration newConfig = new Configuration();
            newConfig.set(CommonConfigurationKeys.HADOOP_SECURITY_AUTHENTICATION,
                    UserGroupInformation.AuthenticationMethod.KERBEROS.toString());

            if (clientNameMapping != null) {
                newConfig.set(CommonConfigurationKeys.HADOOP_SECURITY_AUTH_TO_LOCAL, clientNameMapping);
            }

            UserGroupInformation.setConfiguration(newConfig);
            ugi = UserGroupInformation.loginUserFromKeytabAndReturnUGI(principal, keytab);

            // Reset the original configuration for static UGI
            UserGroupInformation.setConfiguration(new Configuration());
        } else {
            // Let's not overwrite the rules here since it might be possible that CUSTOM security is configured for
            // JDBC/ODBC with default rules. If Kerberos was enabled then the correct rules must already be set
            ugi = UserGroupInformation.loginUserFromKeytabAndReturnUGI(principal, keytab);
        }
    } catch (Exception e) {
        throw new DrillException(String.format("Login failed for %s with given keytab", principal), e);
    }
    return ugi;
}

From source file:org.apache.falcon.regression.core.util.KerberosHelper.java

License:Apache License

public static UserGroupInformation getUGI(String user) throws IOException {
    // if unsecure cluster create a remote user object
    if (!MerlinConstants.IS_SECURE) {
        return UserGroupInformation.createRemoteUser(user);
    }//from   ww w  .  j a v  a  2  s .c  o  m
    // if secure create a ugi object from keytab
    return UserGroupInformation.loginUserFromKeytabAndReturnUGI(getPrincipal(user), getKeyTab(user));
}

From source file:org.apache.hive.service.auth.HiveAuthFactory.java

License:Apache License

public static UserGroupInformation loginFromSpnegoKeytabAndReturnUGI(HiveConf hiveConf) throws IOException {
    String principal = hiveConf.getVar(ConfVars.HIVE_SERVER2_SPNEGO_PRINCIPAL);
    String keyTabFile = hiveConf.getVar(ConfVars.HIVE_SERVER2_SPNEGO_KEYTAB);
    if (principal.isEmpty() || keyTabFile.isEmpty()) {
        throw new IOException("HiveServer2 SPNEGO principal or keytab is not correctly configured");
    } else {/*w  ww  .  j  ava2s  .co m*/
        return UserGroupInformation.loginUserFromKeytabAndReturnUGI(
                SecurityUtil.getServerPrincipal(principal, "0.0.0.0"), keyTabFile);
    }
}

From source file:org.apache.phoenix.end2end.HttpParamImpersonationQueryServerIT.java

License:Apache License

private static void startQueryServer() throws Exception {
    PQS = new QueryServer(new String[0], UTIL.getConfiguration());
    // Get the SPNEGO ident for PQS to use
    final UserGroupInformation ugi = UserGroupInformation.loginUserFromKeytabAndReturnUGI(SPNEGO_PRINCIPAL,
            KEYTAB.getAbsolutePath());//  ww w. ja  v  a 2  s .  c o  m
    PQS_EXECUTOR = Executors.newSingleThreadExecutor();
    // Launch PQS, doing in the Kerberos login instead of letting PQS do it itself (which would
    // break the HBase/HDFS logins also running in the same test case).
    PQS_EXECUTOR.submit(new Runnable() {
        @Override
        public void run() {
            ugi.doAs(new PrivilegedAction<Void>() {
                @Override
                public Void run() {
                    PQS.run();
                    return null;
                }
            });
        }
    });
    PQS.awaitRunning();
    PQS_PORT = PQS.getPort();
    PQS_URL = ThinClientUtil.getConnectionUrl("localhost", PQS_PORT) + ";authentication=SPNEGO";
}

From source file:org.apache.phoenix.end2end.HttpParamImpersonationQueryServerIT.java

License:Apache License

@Test
public void testSuccessfulImpersonation() throws Exception {
    final Entry<String, File> user1 = getUser(1);
    final Entry<String, File> user2 = getUser(2);
    // Build the JDBC URL by hand with the doAs
    final String doAsUrlTemplate = Driver.CONNECT_STRING_PREFIX + "url=http://localhost:" + PQS_PORT + "?"
            + QueryServicesOptions.DEFAULT_QUERY_SERVER_REMOTEUSEREXTRACTOR_PARAM
            + "=%s;authentication=SPNEGO;serialization=PROTOBUF";
    final String tableName = "POSITIVE_IMPERSONATION";
    final int numRows = 5;
    final UserGroupInformation serviceUgi = UserGroupInformation
            .loginUserFromKeytabAndReturnUGI(SERVICE_PRINCIPAL, KEYTAB.getAbsolutePath());
    serviceUgi.doAs(new PrivilegedExceptionAction<Void>() {
        @Override//w  w  w.  j a  v a 2s.  co m
        public Void run() throws Exception {
            createTable(tableName, numRows);
            grantUsersToPhoenixSystemTables(Arrays.asList(user1.getKey(), user2.getKey()));
            return null;
        }
    });
    UserGroupInformation user1Ugi = UserGroupInformation.loginUserFromKeytabAndReturnUGI(user1.getKey(),
            user1.getValue().getAbsolutePath());
    user1Ugi.doAs(new PrivilegedExceptionAction<Void>() {
        @Override
        public Void run() throws Exception {
            // This user should not be able to read the table
            readAndExpectPermissionError(PQS_URL, tableName, numRows);
            // Run the same query with the same credentials, but with a doAs. We should be permitted since the user we're impersonating can run the query
            final String doAsUrl = String.format(doAsUrlTemplate, serviceUgi.getShortUserName());
            try (Connection conn = DriverManager.getConnection(doAsUrl);
                    Statement stmt = conn.createStatement()) {
                conn.setAutoCommit(true);
                readRows(stmt, tableName, numRows);
            }
            return null;
        }
    });
}

From source file:org.apache.phoenix.end2end.HttpParamImpersonationQueryServerIT.java

License:Apache License

@Test
public void testDisallowedImpersonation() throws Exception {
    final Entry<String, File> user2 = getUser(2);
    // Build the JDBC URL by hand with the doAs
    final String doAsUrlTemplate = Driver.CONNECT_STRING_PREFIX + "url=http://localhost:" + PQS_PORT + "?"
            + QueryServicesOptions.DEFAULT_QUERY_SERVER_REMOTEUSEREXTRACTOR_PARAM
            + "=%s;authentication=SPNEGO;serialization=PROTOBUF";
    final String tableName = "DISALLOWED_IMPERSONATION";
    final int numRows = 5;
    final UserGroupInformation serviceUgi = UserGroupInformation
            .loginUserFromKeytabAndReturnUGI(SERVICE_PRINCIPAL, KEYTAB.getAbsolutePath());
    serviceUgi.doAs(new PrivilegedExceptionAction<Void>() {
        @Override/*from  w w  w.  j  a  v a  2  s  .c  o  m*/
        public Void run() throws Exception {
            createTable(tableName, numRows);
            grantUsersToPhoenixSystemTables(Arrays.asList(user2.getKey()));
            return null;
        }
    });
    UserGroupInformation user2Ugi = UserGroupInformation.loginUserFromKeytabAndReturnUGI(user2.getKey(),
            user2.getValue().getAbsolutePath());
    user2Ugi.doAs(new PrivilegedExceptionAction<Void>() {
        @Override
        public Void run() throws Exception {
            // This user is disallowed to read this table
            readAndExpectPermissionError(PQS_URL, tableName, numRows);
            // This user is also not allowed to impersonate
            final String doAsUrl = String.format(doAsUrlTemplate, serviceUgi.getShortUserName());
            try (Connection conn = DriverManager.getConnection(doAsUrl);
                    Statement stmt = conn.createStatement()) {
                conn.setAutoCommit(true);
                readRows(stmt, tableName, numRows);
                fail("user2 should not be allowed to impersonate the service user");
            } catch (Exception e) {
                LOG.info("Caught expected exception", e);
            }
            return null;
        }
    });
}

From source file:org.apache.phoenix.end2end.SecureQueryServerIT.java

License:Apache License

@Test
public void testBasicReadWrite() throws Exception {
    final Entry<String, File> user1 = getUser(1);
    UserGroupInformation user1Ugi = UserGroupInformation.loginUserFromKeytabAndReturnUGI(user1.getKey(),
            user1.getValue().getAbsolutePath());
    user1Ugi.doAs(new PrivilegedExceptionAction<Void>() {
        @Override//from www  .  ja v a 2  s  .co m
        public Void run() throws Exception {
            // Phoenix
            final String tableName = "phx_table1";
            try (java.sql.Connection conn = DriverManager.getConnection(PQS_URL);
                    Statement stmt = conn.createStatement()) {
                conn.setAutoCommit(true);
                assertFalse(stmt.execute("CREATE TABLE " + tableName + "(pk integer not null primary key)"));
                final int numRows = 5;
                for (int i = 0; i < numRows; i++) {
                    assertEquals(1, stmt.executeUpdate("UPSERT INTO " + tableName + " values(" + i + ")"));
                }

                try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) {
                    for (int i = 0; i < numRows; i++) {
                        assertTrue(rs.next());
                        assertEquals(i, rs.getInt(1));
                    }
                    assertFalse(rs.next());
                }
            }
            return null;
        }
    });
}

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

License:Apache License

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

    UserGroupInformation ugi = UserGroupInformation.loginUserFromKeytabAndReturnUGI(princ1, keytab1.getPath());

    PrivilegedExceptionAction<Void> callable = new PrivilegedExceptionAction<Void>() {
        public Void run() throws Exception {
            String url = joinUserAuthentication(BASE_URL, princ1, keytab1);
            connections.add(ConnectionInfo.create(url).normalize(ReadOnlyProps.EMPTY_PROPS, EMPTY_PROPERTIES));
            return null;
        }//from   ww w  .  j  ava 2 s  .  c  om
    };

    // Using the same UGI should result in two equivalent ConnectionInfo objects
    ugi.doAs(callable);
    assertEquals(1, connections.size());
    verifyAllConnectionsAreKerberosBased(connections);

    ugi.doAs(callable);
    assertEquals(1, connections.size());
    verifyAllConnectionsAreKerberosBased(connections);
}

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

License:Apache License

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

    UserGroupInformation ugi = UserGroupInformation.loginUserFromKeytabAndReturnUGI(princ1, keytab1.getPath());

    PrivilegedExceptionAction<Void> callable = new PrivilegedExceptionAction<Void>() {
        public Void run() throws Exception {
            String url = joinUserAuthentication(BASE_URL, princ1, keytab1);
            connections.add(ConnectionInfo.create(url).normalize(ReadOnlyProps.EMPTY_PROPS, EMPTY_PROPERTIES));
            return null;
        }//  ww  w . j  av  a 2  s.  c  om
    };

    ugi.doAs(callable);
    assertEquals(1, connections.size());
    verifyAllConnectionsAreKerberosBased(connections);

    // A second, but equivalent, call from the same "real" user but a different UGI instance
    // is expected functionality (programmer error).
    UserGroupInformation ugiCopy = UserGroupInformation.loginUserFromKeytabAndReturnUGI(princ1,
            keytab1.getPath());
    ugiCopy.doAs(callable);
    assertEquals(2, connections.size());
    verifyAllConnectionsAreKerberosBased(connections);
}