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.accumulo.monitor.servlets.trace.Basic.java

License:Apache License

protected Entry<Scanner, UserGroupInformation> getScanner(final StringBuilder sb)
        throws AccumuloException, AccumuloSecurityException {
    AccumuloConfiguration conf = Monitor.getContext().getConfiguration();
    final boolean saslEnabled = conf.getBoolean(Property.INSTANCE_RPC_SASL_ENABLED);
    UserGroupInformation traceUgi = null;
    final String principal;
    final AuthenticationToken at;
    Map<String, String> loginMap = conf.getAllPropertiesWithPrefix(Property.TRACE_TOKEN_PROPERTY_PREFIX);
    // May be null
    String keytab = loginMap.get(Property.TRACE_TOKEN_PROPERTY_PREFIX.getKey() + "keytab");
    if (keytab == null || keytab.length() == 0) {
        keytab = conf.getPath(Property.GENERAL_KERBEROS_KEYTAB);
    }//from w  ww  . jav  a  2  s . c  om

    if (saslEnabled && null != keytab) {
        principal = SecurityUtil.getServerPrincipal(conf.get(Property.TRACE_USER));
        try {
            traceUgi = UserGroupInformation.loginUserFromKeytabAndReturnUGI(principal, keytab);
        } catch (IOException e) {
            throw new RuntimeException("Failed to login as trace user", e);
        }
    } else {
        principal = conf.get(Property.TRACE_USER);
    }

    if (!saslEnabled) {
        if (loginMap.isEmpty()) {
            Property p = Property.TRACE_PASSWORD;
            at = new PasswordToken(conf.get(p).getBytes(UTF_8));
        } else {
            Properties props = new Properties();
            int prefixLength = Property.TRACE_TOKEN_PROPERTY_PREFIX.getKey().length();
            for (Entry<String, String> entry : loginMap.entrySet()) {
                props.put(entry.getKey().substring(prefixLength), entry.getValue());
            }

            AuthenticationToken token = Property.createInstanceFromPropertyName(conf, Property.TRACE_TOKEN_TYPE,
                    AuthenticationToken.class, new PasswordToken());
            token.init(props);
            at = token;
        }
    } else {
        at = null;
    }

    final String table = conf.get(Property.TRACE_TABLE);
    Scanner scanner;
    if (null != traceUgi) {
        try {
            scanner = traceUgi.doAs(new PrivilegedExceptionAction<Scanner>() {

                @Override
                public Scanner run() throws Exception {
                    // Make the KerberosToken inside the doAs
                    AuthenticationToken token = at;
                    if (null == token) {
                        token = new KerberosToken();
                    }
                    return getScanner(table, principal, token, sb);
                }

            });
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException("Failed to obtain scanner", e);
        }
    } else {
        if (null == at) {
            throw new AssertionError("AuthenticationToken should not be null");
        }
        scanner = getScanner(table, principal, at, sb);
    }

    return new AbstractMap.SimpleEntry<>(scanner, traceUgi);
}

From source file:org.apache.accumulo.test.functional.KerberosIT.java

License:Apache License

@Test
public void testAdminUser() throws Exception {
    // Login as the client (provided to `accumulo init` as the "root" user)
    UserGroupInformation ugi = UserGroupInformation.loginUserFromKeytabAndReturnUGI(rootUser.getPrincipal(),
            rootUser.getKeytab().getAbsolutePath());
    ugi.doAs(new PrivilegedExceptionAction<Void>() {
        @Override//from  w  ww.  j a va 2  s. c  o m
        public Void run() throws Exception {
            final Connector conn = mac.getConnector(rootUser.getPrincipal(), new KerberosToken());

            // The "root" user should have all system permissions
            for (SystemPermission perm : SystemPermission.values()) {
                assertTrue("Expected user to have permission: " + perm,
                        conn.securityOperations().hasSystemPermission(conn.whoami(), perm));
            }

            // and the ability to modify the root and metadata tables
            for (String table : Arrays.asList(RootTable.NAME, MetadataTable.NAME)) {
                assertTrue(conn.securityOperations().hasTablePermission(conn.whoami(), table,
                        TablePermission.ALTER_TABLE));
            }
            return null;
        }
    });
}

From source file:org.apache.accumulo.test.functional.KerberosIT.java

License:Apache License

@Test
public void testNewUser() throws Exception {
    String newUser = testName.getMethodName();
    final File newUserKeytab = new File(kdc.getKeytabDir(), newUser + ".keytab");
    if (newUserKeytab.exists() && !newUserKeytab.delete()) {
        log.warn("Unable to delete {}", newUserKeytab);
    }//from www. j a va  2s .  c  om

    // Create a new user
    kdc.createPrincipal(newUserKeytab, newUser);

    final String newQualifiedUser = kdc.qualifyUser(newUser);
    final HashSet<String> users = Sets.newHashSet(rootUser.getPrincipal());

    // Login as the "root" user
    UserGroupInformation ugi = UserGroupInformation.loginUserFromKeytabAndReturnUGI(rootUser.getPrincipal(),
            rootUser.getKeytab().getAbsolutePath());
    log.info("Logged in as {}", rootUser.getPrincipal());

    ugi.doAs(new PrivilegedExceptionAction<Void>() {
        @Override
        public Void run() throws Exception {
            Connector conn = mac.getConnector(rootUser.getPrincipal(), new KerberosToken());
            log.info("Created connector as {}", rootUser.getPrincipal());
            assertEquals(rootUser.getPrincipal(), conn.whoami());

            // Make sure the system user doesn't exist -- this will force some RPC to happen server-side
            createTableWithDataAndCompact(conn);

            assertEquals(users, conn.securityOperations().listLocalUsers());

            return null;
        }
    });
    // Switch to a new user
    ugi = UserGroupInformation.loginUserFromKeytabAndReturnUGI(newQualifiedUser,
            newUserKeytab.getAbsolutePath());
    log.info("Logged in as {}", newQualifiedUser);
    ugi.doAs(new PrivilegedExceptionAction<Void>() {
        @Override
        public Void run() throws Exception {
            Connector conn = mac.getConnector(newQualifiedUser, new KerberosToken());
            log.info("Created connector as {}", newQualifiedUser);
            assertEquals(newQualifiedUser, conn.whoami());

            // The new user should have no system permissions
            for (SystemPermission perm : SystemPermission.values()) {
                assertFalse(conn.securityOperations().hasSystemPermission(newQualifiedUser, perm));
            }

            users.add(newQualifiedUser);

            // Same users as before, plus the new user we just created
            assertEquals(users, conn.securityOperations().listLocalUsers());
            return null;
        }

    });
}

From source file:org.apache.accumulo.test.functional.KerberosIT.java

License:Apache License

@Test
public void testUserPrivilegesThroughGrant() throws Exception {
    String user1 = testName.getMethodName();
    final File user1Keytab = new File(kdc.getKeytabDir(), user1 + ".keytab");
    if (user1Keytab.exists() && !user1Keytab.delete()) {
        log.warn("Unable to delete {}", user1Keytab);
    }//from   w  w  w  .  j ava  2  s  .co m

    // Create some new users
    kdc.createPrincipal(user1Keytab, user1);

    final String qualifiedUser1 = kdc.qualifyUser(user1);

    // Log in as user1
    UserGroupInformation ugi = UserGroupInformation.loginUserFromKeytabAndReturnUGI(user1,
            user1Keytab.getAbsolutePath());
    log.info("Logged in as {}", user1);
    ugi.doAs(new PrivilegedExceptionAction<Void>() {
        @Override
        public Void run() throws Exception {
            // Indirectly creates this user when we use it
            Connector conn = mac.getConnector(qualifiedUser1, new KerberosToken());
            log.info("Created connector as {}", qualifiedUser1);

            // The new user should have no system permissions
            for (SystemPermission perm : SystemPermission.values()) {
                assertFalse(conn.securityOperations().hasSystemPermission(qualifiedUser1, perm));
            }

            return null;
        }
    });

    ugi = UserGroupInformation.loginUserFromKeytabAndReturnUGI(rootUser.getPrincipal(),
            rootUser.getKeytab().getAbsolutePath());
    ugi.doAs(new PrivilegedExceptionAction<Void>() {
        @Override
        public Void run() throws Exception {
            Connector conn = mac.getConnector(rootUser.getPrincipal(), new KerberosToken());
            conn.securityOperations().grantSystemPermission(qualifiedUser1, SystemPermission.CREATE_TABLE);
            return null;
        }
    });

    // Switch back to the original user
    ugi = UserGroupInformation.loginUserFromKeytabAndReturnUGI(user1, user1Keytab.getAbsolutePath());
    ugi.doAs(new PrivilegedExceptionAction<Void>() {
        @Override
        public Void run() throws Exception {
            Connector conn = mac.getConnector(qualifiedUser1, new KerberosToken());

            // Shouldn't throw an exception since we granted the create table permission
            final String table = testName.getMethodName() + "_user_table";
            conn.tableOperations().create(table);

            // Make sure we can actually use the table we made
            BatchWriter bw = conn.createBatchWriter(table, new BatchWriterConfig());
            Mutation m = new Mutation("a");
            m.put("b", "c", "d");
            bw.addMutation(m);
            bw.close();

            conn.tableOperations().compact(table, new CompactionConfig().setWait(true).setFlush(true));
            return null;
        }
    });
}

From source file:org.apache.accumulo.test.functional.KerberosIT.java

License:Apache License

@Test
public void testUserPrivilegesForTable() throws Exception {
    String user1 = testName.getMethodName();
    final File user1Keytab = new File(kdc.getKeytabDir(), user1 + ".keytab");
    if (user1Keytab.exists() && !user1Keytab.delete()) {
        log.warn("Unable to delete {}", user1Keytab);
    }/*from   w w w .j a v  a 2  s.co  m*/

    // Create some new users -- cannot contain realm
    kdc.createPrincipal(user1Keytab, user1);

    final String qualifiedUser1 = kdc.qualifyUser(user1);

    // Log in as user1
    UserGroupInformation ugi = UserGroupInformation.loginUserFromKeytabAndReturnUGI(qualifiedUser1,
            user1Keytab.getAbsolutePath());
    log.info("Logged in as {}", user1);
    ugi.doAs(new PrivilegedExceptionAction<Void>() {
        @Override
        public Void run() throws Exception {
            // Indirectly creates this user when we use it
            Connector conn = mac.getConnector(qualifiedUser1, new KerberosToken());
            log.info("Created connector as {}", qualifiedUser1);

            // The new user should have no system permissions
            for (SystemPermission perm : SystemPermission.values()) {
                assertFalse(conn.securityOperations().hasSystemPermission(qualifiedUser1, perm));
            }
            return null;
        }

    });

    final String table = testName.getMethodName() + "_user_table";
    final String viz = "viz";

    ugi = UserGroupInformation.loginUserFromKeytabAndReturnUGI(rootUser.getPrincipal(),
            rootUser.getKeytab().getAbsolutePath());

    ugi.doAs(new PrivilegedExceptionAction<Void>() {
        @Override
        public Void run() throws Exception {
            Connector conn = mac.getConnector(rootUser.getPrincipal(), new KerberosToken());
            conn.tableOperations().create(table);
            // Give our unprivileged user permission on the table we made for them
            conn.securityOperations().grantTablePermission(qualifiedUser1, table, TablePermission.READ);
            conn.securityOperations().grantTablePermission(qualifiedUser1, table, TablePermission.WRITE);
            conn.securityOperations().grantTablePermission(qualifiedUser1, table, TablePermission.ALTER_TABLE);
            conn.securityOperations().grantTablePermission(qualifiedUser1, table, TablePermission.DROP_TABLE);
            conn.securityOperations().changeUserAuthorizations(qualifiedUser1, new Authorizations(viz));
            return null;
        }
    });

    // Switch back to the original user
    ugi = UserGroupInformation.loginUserFromKeytabAndReturnUGI(qualifiedUser1, user1Keytab.getAbsolutePath());
    ugi.doAs(new PrivilegedExceptionAction<Void>() {
        @Override
        public Void run() throws Exception {
            Connector conn = mac.getConnector(qualifiedUser1, new KerberosToken());

            // Make sure we can actually use the table we made

            // Write data
            final long ts = 1000l;
            BatchWriter bw = conn.createBatchWriter(table, new BatchWriterConfig());
            Mutation m = new Mutation("a");
            m.put("b", "c", new ColumnVisibility(viz.getBytes()), ts, "d");
            bw.addMutation(m);
            bw.close();

            // Compact
            conn.tableOperations().compact(table, new CompactionConfig().setWait(true).setFlush(true));

            // Alter
            conn.tableOperations().setProperty(table, Property.TABLE_BLOOM_ENABLED.getKey(), "true");

            // Read (and proper authorizations)
            Scanner s = conn.createScanner(table, new Authorizations(viz));
            Iterator<Entry<Key, Value>> iter = s.iterator();
            assertTrue("No results from iterator", iter.hasNext());
            Entry<Key, Value> entry = iter.next();
            assertEquals(new Key("a", "b", "c", viz, ts), entry.getKey());
            assertEquals(new Value("d".getBytes()), entry.getValue());
            assertFalse("Had more results from iterator", iter.hasNext());
            return null;
        }
    });
}

From source file:org.apache.accumulo.test.functional.KerberosIT.java

License:Apache License

@Test
public void testDelegationToken() throws Exception {
    final String tableName = getUniqueNames(1)[0];

    // Login as the "root" user
    UserGroupInformation root = UserGroupInformation.loginUserFromKeytabAndReturnUGI(rootUser.getPrincipal(),
            rootUser.getKeytab().getAbsolutePath());
    log.info("Logged in as {}", rootUser.getPrincipal());

    final int numRows = 100, numColumns = 10;

    // As the "root" user, open up the connection and get a delegation token
    final AuthenticationToken delegationToken = root.doAs(new PrivilegedExceptionAction<AuthenticationToken>() {
        @Override/*from  w  w w. j av a2 s  .co m*/
        public AuthenticationToken run() throws Exception {
            Connector conn = mac.getConnector(rootUser.getPrincipal(), new KerberosToken());
            log.info("Created connector as {}", rootUser.getPrincipal());
            assertEquals(rootUser.getPrincipal(), conn.whoami());

            conn.tableOperations().create(tableName);
            BatchWriter bw = conn.createBatchWriter(tableName, new BatchWriterConfig());
            for (int r = 0; r < numRows; r++) {
                Mutation m = new Mutation(Integer.toString(r));
                for (int c = 0; c < numColumns; c++) {
                    String col = Integer.toString(c);
                    m.put(col, col, col);
                }
                bw.addMutation(m);
            }
            bw.close();

            return conn.securityOperations().getDelegationToken(new DelegationTokenConfig());
        }
    });

    // The above login with keytab doesn't have a way to logout, so make a fake user that won't have krb credentials
    UserGroupInformation userWithoutPrivs = UserGroupInformation.createUserForTesting("fake_user",
            new String[0]);
    int recordsSeen = userWithoutPrivs.doAs(new PrivilegedExceptionAction<Integer>() {
        @Override
        public Integer run() throws Exception {
            Connector conn = mac.getConnector(rootUser.getPrincipal(), delegationToken);

            BatchScanner bs = conn.createBatchScanner(tableName, Authorizations.EMPTY, 2);
            bs.setRanges(Collections.singleton(new Range()));
            int recordsSeen = Iterables.size(bs);
            bs.close();
            return recordsSeen;
        }
    });

    assertEquals(numRows * numColumns, recordsSeen);
}

From source file:org.apache.accumulo.test.functional.KerberosIT.java

License:Apache License

@Test
public void testDelegationTokenAsDifferentUser() throws Exception {
    // Login as the "root" user
    UserGroupInformation ugi = UserGroupInformation.loginUserFromKeytabAndReturnUGI(rootUser.getPrincipal(),
            rootUser.getKeytab().getAbsolutePath());
    log.info("Logged in as {}", rootUser.getPrincipal());

    final AuthenticationToken delegationToken;
    try {/*from w w w. j  a  v  a2  s .  c o  m*/
        delegationToken = ugi.doAs(new PrivilegedExceptionAction<AuthenticationToken>() {
            @Override
            public AuthenticationToken run() throws Exception {
                // As the "root" user, open up the connection and get a delegation token
                Connector conn = mac.getConnector(rootUser.getPrincipal(), new KerberosToken());
                log.info("Created connector as {}", rootUser.getPrincipal());
                assertEquals(rootUser.getPrincipal(), conn.whoami());
                return conn.securityOperations().getDelegationToken(new DelegationTokenConfig());
            }
        });
    } catch (UndeclaredThrowableException ex) {
        throw ex;
    }

    // make a fake user that won't have krb credentials
    UserGroupInformation userWithoutPrivs = UserGroupInformation.createUserForTesting("fake_user",
            new String[0]);
    try {
        // Use the delegation token to try to log in as a different user
        userWithoutPrivs.doAs(new PrivilegedExceptionAction<Void>() {
            @Override
            public Void run() throws Exception {
                mac.getConnector("some_other_user", delegationToken);
                return null;
            }
        });
        fail("Using a delegation token as a different user should throw an exception");
    } catch (UndeclaredThrowableException e) {
        Throwable cause = e.getCause();
        assertNotNull(cause);
        // We should get an AccumuloSecurityException from trying to use a delegation token for the wrong user
        assertTrue("Expected cause to be AccumuloSecurityException, but was " + cause.getClass(),
                cause instanceof AccumuloSecurityException);
    }
}

From source file:org.apache.accumulo.test.functional.KerberosIT.java

License:Apache License

@Test
public void testGetDelegationTokenDenied() throws Exception {
    String newUser = testName.getMethodName();
    final File newUserKeytab = new File(kdc.getKeytabDir(), newUser + ".keytab");
    if (newUserKeytab.exists() && !newUserKeytab.delete()) {
        log.warn("Unable to delete {}", newUserKeytab);
    }//from   ww w.jav a 2s .  c  o  m

    // Create a new user
    kdc.createPrincipal(newUserKeytab, newUser);

    final String qualifiedNewUser = kdc.qualifyUser(newUser);

    // Login as a normal user
    UserGroupInformation ugi = UserGroupInformation.loginUserFromKeytabAndReturnUGI(qualifiedNewUser,
            newUserKeytab.getAbsolutePath());
    try {
        ugi.doAs(new PrivilegedExceptionAction<Void>() {
            @Override
            public Void run() throws Exception {
                // As the "root" user, open up the connection and get a delegation token
                Connector conn = mac.getConnector(qualifiedNewUser, new KerberosToken());
                log.info("Created connector as {}", qualifiedNewUser);
                assertEquals(qualifiedNewUser, conn.whoami());

                conn.securityOperations().getDelegationToken(new DelegationTokenConfig());
                return null;
            }
        });
    } catch (UndeclaredThrowableException ex) {
        assertTrue(ex.getCause() instanceof AccumuloSecurityException);
    }
}

From source file:org.apache.accumulo.test.functional.KerberosIT.java

License:Apache License

@Test
public void testRestartedMasterReusesSecretKey() throws Exception {
    // Login as the "root" user
    UserGroupInformation root = UserGroupInformation.loginUserFromKeytabAndReturnUGI(rootUser.getPrincipal(),
            rootUser.getKeytab().getAbsolutePath());
    log.info("Logged in as {}", rootUser.getPrincipal());

    // As the "root" user, open up the connection and get a delegation token
    final AuthenticationToken delegationToken1 = root
            .doAs(new PrivilegedExceptionAction<AuthenticationToken>() {
                @Override//ww  w. ja va2 s . c o m
                public AuthenticationToken run() throws Exception {
                    Connector conn = mac.getConnector(rootUser.getPrincipal(), new KerberosToken());
                    log.info("Created connector as {}", rootUser.getPrincipal());
                    assertEquals(rootUser.getPrincipal(), conn.whoami());

                    AuthenticationToken token = conn.securityOperations()
                            .getDelegationToken(new DelegationTokenConfig());

                    assertTrue("Could not get tables with delegation token", mac
                            .getConnector(rootUser.getPrincipal(), token).tableOperations().list().size() > 0);

                    return token;
                }
            });

    log.info("Stopping master");
    mac.getClusterControl().stop(ServerType.MASTER);
    Thread.sleep(5000);
    log.info("Restarting master");
    mac.getClusterControl().start(ServerType.MASTER);

    // Make sure our original token is still good
    root.doAs(new PrivilegedExceptionAction<Void>() {
        @Override
        public Void run() throws Exception {
            Connector conn = mac.getConnector(rootUser.getPrincipal(), delegationToken1);

            assertTrue("Could not get tables with delegation token", conn.tableOperations().list().size() > 0);

            return null;
        }
    });

    // Get a new token, so we can compare the keyId on the second to the first
    final AuthenticationToken delegationToken2 = root
            .doAs(new PrivilegedExceptionAction<AuthenticationToken>() {
                @Override
                public AuthenticationToken run() throws Exception {
                    Connector conn = mac.getConnector(rootUser.getPrincipal(), new KerberosToken());
                    log.info("Created connector as {}", rootUser.getPrincipal());
                    assertEquals(rootUser.getPrincipal(), conn.whoami());

                    AuthenticationToken token = conn.securityOperations()
                            .getDelegationToken(new DelegationTokenConfig());

                    assertTrue("Could not get tables with delegation token", mac
                            .getConnector(rootUser.getPrincipal(), token).tableOperations().list().size() > 0);

                    return token;
                }
            });

    // A restarted master should reuse the same secret key after a restart if the secret key hasn't expired (1day by default)
    DelegationTokenImpl dt1 = (DelegationTokenImpl) delegationToken1;
    DelegationTokenImpl dt2 = (DelegationTokenImpl) delegationToken2;
    assertEquals(dt1.getIdentifier().getKeyId(), dt2.getIdentifier().getKeyId());
}

From source file:org.apache.accumulo.test.functional.KerberosIT.java

License:Apache License

@Test(expected = AccumuloException.class)
public void testDelegationTokenWithInvalidLifetime() throws Throwable {
    // Login as the "root" user
    UserGroupInformation root = UserGroupInformation.loginUserFromKeytabAndReturnUGI(rootUser.getPrincipal(),
            rootUser.getKeytab().getAbsolutePath());
    log.info("Logged in as {}", rootUser.getPrincipal());

    // As the "root" user, open up the connection and get a delegation token
    try {/*from  w  w w .j  a v a  2 s  . c  o  m*/
        root.doAs(new PrivilegedExceptionAction<AuthenticationToken>() {
            @Override
            public AuthenticationToken run() throws Exception {
                Connector conn = mac.getConnector(rootUser.getPrincipal(), new KerberosToken());
                log.info("Created connector as {}", rootUser.getPrincipal());
                assertEquals(rootUser.getPrincipal(), conn.whoami());

                // Should fail
                return conn.securityOperations().getDelegationToken(
                        new DelegationTokenConfig().setTokenLifetime(Long.MAX_VALUE, TimeUnit.MILLISECONDS));
            }
        });
    } catch (UndeclaredThrowableException e) {
        Throwable cause = e.getCause();
        if (null != cause) {
            throw cause;
        } else {
            throw e;
        }
    }
}