List of usage examples for org.apache.hadoop.security UserGroupInformation getAuthenticationMethod
public synchronized AuthenticationMethod getAuthenticationMethod()
From source file:azkaban.jobtype.JavaJobRunnerMain.java
License:Apache License
private void runMethodAsProxyUser(Properties props, final Object obj, final String runMethod) throws IOException, InterruptedException { UserGroupInformation ugi = SecurityUtils.getProxiedUser(props, _logger, new Configuration()); _logger.info("user " + ugi + " authenticationMethod " + ugi.getAuthenticationMethod()); _logger.info("user " + ugi + " hasKerberosCredentials " + ugi.hasKerberosCredentials()); SecurityUtils.getProxiedUser(props, _logger, new Configuration()) .doAs(new PrivilegedExceptionAction<Void>() { @Override//from ww w.j a va 2s .co m public Void run() throws Exception { runMethod(obj, runMethod); return null; } }); }
From source file:co.cask.cdap.security.impersonation.UGIProviderTest.java
License:Apache License
@Test public void testDefaultUGIProvider() throws IOException { System.setProperty("sun.security.krb5.debug", "true"); DefaultUGIProvider provider = new DefaultUGIProvider(cConf, locationFactory); // Try with local keytab file ImpersonationInfo aliceInfo = new ImpersonationInfo(getPrincipal("alice"), keytabFile.getAbsolutePath()); UserGroupInformation aliceUGI = provider.getConfiguredUGI(aliceInfo); Assert.assertEquals(UserGroupInformation.AuthenticationMethod.KERBEROS, aliceUGI.getAuthenticationMethod()); Assert.assertTrue(aliceUGI.hasKerberosCredentials()); // Fetch it again, it is should return the same UGI since there is caching Assert.assertSame(aliceUGI, provider.getConfiguredUGI(aliceInfo)); // Put the keytab on HDFS Location remoteKeytab = locationFactory.create("keytab").getTempFile(".tmp"); Files.copy(keytabFile, Locations.newOutputSupplier(remoteKeytab)); // Login with remote keytab file ImpersonationInfo bobInfo = new ImpersonationInfo(getPrincipal("bob"), remoteKeytab.toURI().toString()); UserGroupInformation bobUGI = provider.getConfiguredUGI(bobInfo); Assert.assertEquals(UserGroupInformation.AuthenticationMethod.KERBEROS, bobUGI.getAuthenticationMethod()); Assert.assertTrue(bobUGI.hasKerberosCredentials()); // Delete the keytab on HDFS remoteKeytab.delete();// ww w . j ava 2 s .c o m // Fetch the bob UGI again, it should still return the valid one Assert.assertSame(bobUGI, provider.getConfiguredUGI(bobInfo)); // Invalid the cache, getting of Alice UGI should pass, while getting of Bob should fails provider.invalidCache(); Assert.assertNotSame(aliceUGI, provider.getConfiguredUGI(aliceInfo)); try { provider.getConfiguredUGI(bobInfo); Assert.fail("Expected IOException when getting UGI for " + bobInfo); } catch (IOException e) { // Expected } }
From source file:com.blackberry.bdp.kaboom.Authenticator.java
License:Apache License
private boolean authenticate(String proxyUserName) { UserGroupInformation proxyTicket;/*from w ww . jav a 2 s . c o m*/ // logic for kerberos login boolean useSecurity = UserGroupInformation.isSecurityEnabled(); LOG.info("Hadoop Security enabled: " + useSecurity); if (useSecurity) { // sanity checking if (kerbConfPrincipal.isEmpty()) { LOG.error("Hadoop running in secure mode, but Flume config doesn't " + "specify a principal to use for Kerberos auth."); return false; } if (kerbKeytab.isEmpty()) { LOG.error("Hadoop running in secure mode, but Flume config doesn't " + "specify a keytab to use for Kerberos auth."); return false; } String principal; try { // resolves _HOST pattern using standard Hadoop search/replace // via DNS lookup when 2nd argument is empty principal = SecurityUtil.getServerPrincipal(kerbConfPrincipal, ""); } catch (IOException e) { LOG.error("Host lookup error resolving kerberos principal (" + kerbConfPrincipal + "). Exception follows.", e); return false; } Preconditions.checkNotNull(principal, "Principal must not be null"); KerberosUser prevUser = staticLogin.get(); KerberosUser newUser = new KerberosUser(principal, kerbKeytab); // be cruel and unusual when user tries to login as multiple principals // this isn't really valid with a reconfigure but this should be rare // enough to warrant a restart of the agent JVM // TODO: find a way to interrogate the entire current config state, // since we don't have to be unnecessarily protective if they switch all // HDFS sinks to use a different principal all at once. Preconditions.checkState(prevUser == null || prevUser.equals(newUser), "Cannot use multiple kerberos principals in the same agent. " + " Must restart agent to use new principal or keytab. " + "Previous = %s, New = %s", prevUser, newUser); // attempt to use cached credential if the user is the same // this is polite and should avoid flooding the KDC with auth requests UserGroupInformation curUser = null; if (prevUser != null && prevUser.equals(newUser)) { try { LOG.info("Attempting login as {} with cached credentials", prevUser.getPrincipal()); curUser = UserGroupInformation.getLoginUser(); } catch (IOException e) { LOG.warn("User unexpectedly had no active login. Continuing with " + "authentication", e); } } if (curUser == null || !curUser.getUserName().equals(principal)) { try { // static login curUser = kerberosLogin(this, principal, kerbKeytab); LOG.info("Current user obtained from Kerberos login {}", curUser.getUserName()); } catch (IOException e) { LOG.error("Authentication or file read error while attempting to " + "login as kerberos principal (" + principal + ") using " + "keytab (" + kerbKeytab + "). Exception follows.", e); return false; } } else { LOG.debug("{}: Using existing principal login: {}", this, curUser); } try { if (UserGroupInformation.getLoginUser().isFromKeytab() == false) { LOG.warn("Using a keytab for authentication is {}", UserGroupInformation.getLoginUser().isFromKeytab()); LOG.warn("curUser.isFromKeytab(): {}", curUser.isFromKeytab()); LOG.warn("UserGroupInformation.getCurrentUser().isLoginKeytabBased(): {}", UserGroupInformation.getCurrentUser().isLoginKeytabBased()); LOG.warn("UserGroupInformation.isLoginKeytabBased(): {}", UserGroupInformation.isLoginKeytabBased()); LOG.warn("curUser.getAuthenticationMethod(): {}", curUser.getAuthenticationMethod()); //System.exit(1); } } catch (IOException e) { LOG.error("Failed to get login user.", e); System.exit(1); } // we supposedly got through this unscathed... so store the static user staticLogin.set(newUser); } // hadoop impersonation works with or without kerberos security proxyTicket = null; if (!proxyUserName.isEmpty()) { try { proxyTicket = UserGroupInformation.createProxyUser(proxyUserName, UserGroupInformation.getLoginUser()); } catch (IOException e) { LOG.error("Unable to login as proxy user. Exception follows.", e); return false; } } UserGroupInformation ugi = null; if (proxyTicket != null) { ugi = proxyTicket; } else if (useSecurity) { try { ugi = UserGroupInformation.getLoginUser(); } catch (IOException e) { LOG.error("Unexpected error: Unable to get authenticated user after " + "apparent successful login! Exception follows.", e); return false; } } if (ugi != null) { // dump login information AuthenticationMethod authMethod = ugi.getAuthenticationMethod(); LOG.info("Auth method: {}", authMethod); LOG.info(" User name: {}", ugi.getUserName()); LOG.info(" Using keytab: {}", ugi.isFromKeytab()); if (authMethod == AuthenticationMethod.PROXY) { UserGroupInformation superUser; try { superUser = UserGroupInformation.getLoginUser(); LOG.info(" Superuser auth: {}", superUser.getAuthenticationMethod()); LOG.info(" Superuser name: {}", superUser.getUserName()); LOG.info(" Superuser using keytab: {}", superUser.isFromKeytab()); } catch (IOException e) { LOG.error("Unexpected error: unknown superuser impersonating proxy.", e); return false; } } LOG.info("Logged in as user {}", ugi.getUserName()); UGIState state = new UGIState(); state.ugi = proxyTicket; state.lastAuthenticated = System.currentTimeMillis(); proxyUserMap.put(proxyUserName, state); return true; } return true; }
From source file:com.huayu.metis.flume.sink.hdfs.HDFSEventSink.java
License:Apache License
private boolean authenticate() { // logic for kerberos login boolean useSecurity = UserGroupInformation.isSecurityEnabled(); LOG.info("Hadoop Security enabled: " + useSecurity); if (useSecurity) { // sanity checking if (kerbConfPrincipal.isEmpty()) { LOG.error("Hadoop running in secure mode, but Flume config doesn't " + "specify a principal to use for Kerberos auth."); return false; }//from w w w . ja v a 2s . c o m if (kerbKeytab.isEmpty()) { LOG.error("Hadoop running in secure mode, but Flume config doesn't " + "specify a keytab to use for Kerberos auth."); return false; } else { //If keytab is specified, user should want it take effect. //HDFSEventSink will halt when keytab file is non-exist or unreadable File kfile = new File(kerbKeytab); if (!(kfile.isFile() && kfile.canRead())) { throw new IllegalArgumentException( "The keyTab file: " + kerbKeytab + " is nonexistent or can't read. " + "Please specify a readable keytab file for Kerberos auth."); } } String principal; try { // resolves _HOST pattern using standard Hadoop search/replace // via DNS lookup when 2nd argument is empty principal = SecurityUtil.getServerPrincipal(kerbConfPrincipal, ""); } catch (IOException e) { LOG.error("Host lookup error resolving kerberos principal (" + kerbConfPrincipal + "). Exception follows.", e); return false; } Preconditions.checkNotNull(principal, "Principal must not be null"); KerberosUser prevUser = staticLogin.get(); KerberosUser newUser = new KerberosUser(principal, kerbKeytab); // be cruel and unusual when user tries to login as multiple principals // this isn't really valid with a reconfigure but this should be rare // enough to warrant a restart of the agent JVM // TODO: find a way to interrogate the entire current config state, // since we don't have to be unnecessarily protective if they switch all // HDFS sinks to use a different principal all at once. Preconditions.checkState(prevUser == null || prevUser.equals(newUser), "Cannot use multiple kerberos principals in the same agent. " + " Must restart agent to use new principal or keytab. " + "Previous = %s, New = %s", prevUser, newUser); // attempt to use cached credential if the user is the same // this is polite and should avoid flooding the KDC with auth requests UserGroupInformation curUser = null; if (prevUser != null && prevUser.equals(newUser)) { try { curUser = UserGroupInformation.getLoginUser(); } catch (IOException e) { LOG.warn("User unexpectedly had no active login. Continuing with " + "authentication", e); } } if (curUser == null || !curUser.getUserName().equals(principal)) { try { // static login kerberosLogin(this, principal, kerbKeytab); } catch (IOException e) { LOG.error("Authentication or file read error while attempting to " + "login as kerberos principal (" + principal + ") using " + "keytab (" + kerbKeytab + "). Exception follows.", e); return false; } } else { LOG.debug("{}: Using existing principal login: {}", this, curUser); } // we supposedly got through this unscathed... so store the static user staticLogin.set(newUser); } // hadoop impersonation works with or without kerberos security proxyTicket = null; if (!proxyUserName.isEmpty()) { try { proxyTicket = UserGroupInformation.createProxyUser(proxyUserName, UserGroupInformation.getLoginUser()); } catch (IOException e) { LOG.error("Unable to login as proxy user. Exception follows.", e); return false; } } UserGroupInformation ugi = null; if (proxyTicket != null) { ugi = proxyTicket; } else if (useSecurity) { try { ugi = UserGroupInformation.getLoginUser(); } catch (IOException e) { LOG.error("Unexpected error: Unable to get authenticated user after " + "apparent successful login! Exception follows.", e); return false; } } if (ugi != null) { // dump login information AuthenticationMethod authMethod = ugi.getAuthenticationMethod(); LOG.info("Auth method: {}", authMethod); LOG.info(" User name: {}", ugi.getUserName()); LOG.info(" Using keytab: {}", ugi.isFromKeytab()); if (authMethod == AuthenticationMethod.PROXY) { UserGroupInformation superUser; try { superUser = UserGroupInformation.getLoginUser(); LOG.info(" Superuser auth: {}", superUser.getAuthenticationMethod()); LOG.info(" Superuser name: {}", superUser.getUserName()); LOG.info(" Superuser using keytab: {}", superUser.isFromKeytab()); } catch (IOException e) { LOG.error("Unexpected error: unknown superuser impersonating proxy.", e); return false; } } LOG.info("Logged in as user {}", ugi.getUserName()); return true; } return true; }
From source file:com.rim.logdriver.sawmill.Authenticator.java
License:Apache License
private boolean authenticate(String proxyUserName) { UserGroupInformation proxyTicket;/*from www.j a v a 2 s. c o m*/ // logic for kerberos login boolean useSecurity = UserGroupInformation.isSecurityEnabled(); LOG.info("Hadoop Security enabled: " + useSecurity); if (useSecurity) { // sanity checking if (kerbConfPrincipal.isEmpty()) { LOG.error("Hadoop running in secure mode, but Flume config doesn't " + "specify a principal to use for Kerberos auth."); return false; } if (kerbKeytab.isEmpty()) { LOG.error("Hadoop running in secure mode, but Flume config doesn't " + "specify a keytab to use for Kerberos auth."); return false; } String principal; try { // resolves _HOST pattern using standard Hadoop search/replace // via DNS lookup when 2nd argument is empty principal = SecurityUtil.getServerPrincipal(kerbConfPrincipal, ""); } catch (IOException e) { LOG.error("Host lookup error resolving kerberos principal (" + kerbConfPrincipal + "). Exception follows.", e); return false; } Preconditions.checkNotNull(principal, "Principal must not be null"); KerberosUser prevUser = staticLogin.get(); KerberosUser newUser = new KerberosUser(principal, kerbKeytab); // be cruel and unusual when user tries to login as multiple principals // this isn't really valid with a reconfigure but this should be rare // enough to warrant a restart of the agent JVM // TODO: find a way to interrogate the entire current config state, // since we don't have to be unnecessarily protective if they switch all // HDFS sinks to use a different principal all at once. Preconditions.checkState(prevUser == null || prevUser.equals(newUser), "Cannot use multiple kerberos principals in the same agent. " + " Must restart agent to use new principal or keytab. " + "Previous = %s, New = %s", prevUser, newUser); // attempt to use cached credential if the user is the same // this is polite and should avoid flooding the KDC with auth requests UserGroupInformation curUser = null; if (prevUser != null && prevUser.equals(newUser)) { try { curUser = UserGroupInformation.getLoginUser(); } catch (IOException e) { LOG.warn("User unexpectedly had no active login. Continuing with " + "authentication", e); } } if (curUser == null || !curUser.getUserName().equals(principal)) { try { // static login kerberosLogin(this, principal, kerbKeytab); } catch (IOException e) { LOG.error("Authentication or file read error while attempting to " + "login as kerberos principal (" + principal + ") using " + "keytab (" + kerbKeytab + "). Exception follows.", e); return false; } } else { LOG.debug("{}: Using existing principal login: {}", this, curUser); } try { if (UserGroupInformation.getLoginUser().isFromKeytab() == false) { LOG.error("Not using a keytab for authentication. Shutting down."); System.exit(1); } } catch (IOException e) { LOG.error("Failed to get login user.", e); System.exit(1); } // we supposedly got through this unscathed... so store the static user staticLogin.set(newUser); } // hadoop impersonation works with or without kerberos security proxyTicket = null; if (!proxyUserName.isEmpty()) { try { proxyTicket = UserGroupInformation.createProxyUser(proxyUserName, UserGroupInformation.getLoginUser()); } catch (IOException e) { LOG.error("Unable to login as proxy user. Exception follows.", e); return false; } } UserGroupInformation ugi = null; if (proxyTicket != null) { ugi = proxyTicket; } else if (useSecurity) { try { ugi = UserGroupInformation.getLoginUser(); } catch (IOException e) { LOG.error("Unexpected error: Unable to get authenticated user after " + "apparent successful login! Exception follows.", e); return false; } } if (ugi != null) { // dump login information AuthenticationMethod authMethod = ugi.getAuthenticationMethod(); LOG.info("Auth method: {}", authMethod); LOG.info(" User name: {}", ugi.getUserName()); LOG.info(" Using keytab: {}", ugi.isFromKeytab()); if (authMethod == AuthenticationMethod.PROXY) { UserGroupInformation superUser; try { superUser = UserGroupInformation.getLoginUser(); LOG.info(" Superuser auth: {}", superUser.getAuthenticationMethod()); LOG.info(" Superuser name: {}", superUser.getUserName()); LOG.info(" Superuser using keytab: {}", superUser.isFromKeytab()); } catch (IOException e) { LOG.error("Unexpected error: unknown superuser impersonating proxy.", e); return false; } } LOG.info("Logged in as user {}", ugi.getUserName()); UGIState state = new UGIState(); state.ugi = proxyTicket; state.lastAuthenticated = System.currentTimeMillis(); proxyUserMap.put(proxyUserName, state); return true; } return true; }
From source file:org.apache.accumulo.core.security.AuthenticationTokenIdentifierTest.java
License:Apache License
@Test public void testUgi() { String principal = "user"; AuthenticationTokenIdentifier token = new AuthenticationTokenIdentifier(principal); UserGroupInformation actual = token.getUser(), expected = UserGroupInformation.createRemoteUser(principal); assertEquals(expected.getAuthenticationMethod(), actual.getAuthenticationMethod()); assertEquals(expected.getUserName(), expected.getUserName()); }
From source file:org.apache.accumulo.test.security.KerberosClientOptsTest.java
License:Apache License
@Test public void testParseArgsPerformsLogin() throws Exception { String user = testName.getMethodName(); File userKeytab = new File(kdc.getKeytabDir(), user + ".keytab"); if (userKeytab.exists() && !userKeytab.delete()) { log.warn("Unable to delete {}", userKeytab); }//from ww w .java 2 s . c o m kdc.createPrincipal(userKeytab, user); user = kdc.qualifyUser(user); ClientOpts opts = new ClientOpts(); String[] args = new String[] { "--sasl", "--keytab", userKeytab.getAbsolutePath(), "-u", user }; opts.parseArgs(testName.getMethodName(), args); UserGroupInformation ugi = UserGroupInformation.getCurrentUser(); assertEquals(user, ugi.getUserName()); assertEquals(AuthenticationMethod.KERBEROS, ugi.getAuthenticationMethod()); }
From source file:org.apache.atlas.security.SecureClientUtils.java
License:Apache License
public static URLConnectionClientHandler getClientConnectionHandler(DefaultClientConfig config, org.apache.commons.configuration.Configuration clientConfig, String doAsUser, final UserGroupInformation ugi) { config.getProperties().put(URLConnectionClientHandler.PROPERTY_HTTP_URL_CONNECTION_SET_METHOD_WORKAROUND, true);/*from ww w. ja v a2 s. c o m*/ Configuration conf = new Configuration(); conf.addResource(conf.get(SSLFactory.SSL_CLIENT_CONF_KEY, SecurityProperties.SSL_CLIENT_PROPERTIES)); UserGroupInformation.setConfiguration(conf); final ConnectionConfigurator connConfigurator = newConnConfigurator(conf); String authType = "simple"; if (clientConfig != null) { authType = clientConfig.getString("atlas.http.authentication.type", "simple"); } Authenticator authenticator = new PseudoDelegationTokenAuthenticator(); if (!authType.equals("simple")) { authenticator = new KerberosDelegationTokenAuthenticator(); } authenticator.setConnectionConfigurator(connConfigurator); final DelegationTokenAuthenticator finalAuthenticator = (DelegationTokenAuthenticator) authenticator; final DelegationTokenAuthenticatedURL.Token token = new DelegationTokenAuthenticatedURL.Token(); HttpURLConnectionFactory httpURLConnectionFactory = null; try { UserGroupInformation ugiToUse = ugi != null ? ugi : UserGroupInformation.getCurrentUser(); final UserGroupInformation actualUgi = (ugiToUse .getAuthenticationMethod() == UserGroupInformation.AuthenticationMethod.PROXY) ? ugiToUse.getRealUser() : ugiToUse; LOG.info("Real User: {}, is from ticket cache? {}", actualUgi, actualUgi.isLoginTicketBased()); if (StringUtils.isEmpty(doAsUser)) { doAsUser = actualUgi.getShortUserName(); } LOG.info("doAsUser: {}", doAsUser); final String finalDoAsUser = doAsUser; httpURLConnectionFactory = new HttpURLConnectionFactory() { @Override public HttpURLConnection getHttpURLConnection(final URL url) throws IOException { try { return actualUgi.doAs(new PrivilegedExceptionAction<HttpURLConnection>() { @Override public HttpURLConnection run() throws Exception { try { return new DelegationTokenAuthenticatedURL(finalAuthenticator, connConfigurator) .openConnection(url, token, finalDoAsUser); } catch (Exception e) { throw new IOException(e); } } }); } catch (Exception e) { if (e instanceof IOException) { throw (IOException) e; } else { throw new IOException(e); } } } }; } catch (IOException e) { LOG.warn("Error obtaining user", e); } return new URLConnectionClientHandler(httpURLConnectionFactory); }
From source file:org.apache.drill.exec.rpc.BitConnectionConfig.java
License:Apache License
public Map<String, ?> getSaslClientProperties(final DrillbitEndpoint remoteEndpoint) throws IOException { final DrillProperties properties = DrillProperties.createEmpty(); final UserGroupInformation loginUser = UserGroupInformation.getLoginUser(); if (loginUser.getAuthenticationMethod() == UserGroupInformation.AuthenticationMethod.KERBEROS) { final HadoopKerberosName loginPrincipal = new HadoopKerberosName(loginUser.getUserName()); if (!useLoginPrincipal) { properties.setProperty(DrillProperties.SERVICE_PRINCIPAL, KerberosUtil.getPrincipalFromParts( loginPrincipal.getShortName(), remoteEndpoint.getAddress(), loginPrincipal.getRealm())); } else {/* ww w.ja va 2s.co m*/ properties.setProperty(DrillProperties.SERVICE_PRINCIPAL, loginPrincipal.toString()); } } return properties.stringPropertiesAsMap(); }
From source file:org.apache.falcon.security.AuthenticationInitializationServiceTest.java
License:Apache License
@Test public void testInitForSimpleAuthenticationMethod() { try {// w w w . ja va2s. co m StartupProperties.get().setProperty(SecurityUtil.AUTHENTICATION_TYPE, PseudoAuthenticationHandler.TYPE); authenticationService.init(); UserGroupInformation loginUser = UserGroupInformation.getLoginUser(); Assert.assertFalse(loginUser.isFromKeytab()); Assert.assertEquals(loginUser.getAuthenticationMethod().name().toLowerCase(), PseudoAuthenticationHandler.TYPE); Assert.assertEquals(System.getProperty("user.name"), loginUser.getUserName()); } catch (Exception e) { Assert.fail("AuthenticationInitializationService init failed.", e); } }