List of usage examples for org.apache.hadoop.security UserGroupInformation getLoginUser
@InterfaceAudience.Public @InterfaceStability.Evolving public static UserGroupInformation getLoginUser() throws IOException
From source file:azkaban.utils.AuthenticationUtils.java
License:Apache License
public static HttpURLConnection loginAuthenticatedURL(final URL url, final String keytabPrincipal, final String keytabPath) throws Exception { logger.info("Logging in URL: " + url.toString() + " using Principal: " + keytabPrincipal + ", Keytab: " + keytabPath);// w w w . ja v a 2 s . com UserGroupInformation loginUser = UserGroupInformation.getLoginUser(); if (loginUser == null) { UserGroupInformation.loginUserFromKeytab(keytabPrincipal, keytabPath); loginUser = UserGroupInformation.getLoginUser(); logger.info("Logged in with user " + loginUser); } else { logger.info("Login user (" + loginUser + ") already created, refreshing tgt."); loginUser.checkTGTAndReloginFromKeytab(); } final HttpURLConnection connection = loginUser.doAs((PrivilegedExceptionAction<HttpURLConnection>) () -> { final Token token = new Token(); return new AuthenticatedURL().openConnection(url, token); }); return connection; }
From source file:co.cask.cdap.common.kerberos.SecurityUtil.java
License:Apache License
public static void loginForMasterService(CConfiguration cConf) throws IOException, LoginException { String principal = SecurityUtil .expandPrincipal(cConf.get(Constants.Security.CFG_CDAP_MASTER_KRB_PRINCIPAL)); String keytabPath = cConf.get(Constants.Security.CFG_CDAP_MASTER_KRB_KEYTAB_PATH); if (UserGroupInformation.isSecurityEnabled()) { LOG.info("Logging in as: principal={}, keytab={}", principal, keytabPath); UserGroupInformation.loginUserFromKeytab(principal, keytabPath); long delaySec = cConf.getLong(Constants.Security.KERBEROS_KEYTAB_RELOGIN_INTERVAL); Executors.newSingleThreadScheduledExecutor(Threads.createDaemonThreadFactory("Kerberos keytab renewal")) .scheduleWithFixedDelay(new Runnable() { @Override/*from w w w . j a va 2s . com*/ public void run() { try { UserGroupInformation.getLoginUser().checkTGTAndReloginFromKeytab(); } catch (IOException e) { LOG.error("Failed to relogin from keytab", e); } } }, delaySec, delaySec, TimeUnit.SECONDS); } }
From source file:com.blackberry.bdp.kaboom.Authenticator.java
License:Apache License
private boolean authenticate(String proxyUserName) { UserGroupInformation proxyTicket;//from w w w .j av 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.blackberry.bdp.kaboom.Authenticator.java
License:Apache License
/** * Static synchronized method for static Kerberos login. <br/> * Static synchronized due to a thundering herd problem when multiple Sinks * attempt to log in using the same principal at the same time with the * intention of impersonating different users (or even the same user). If this * is not controlled, MIT Kerberos v5 believes it is seeing a replay attach * and it returns: <blockquote>Request is a replay (34) - * PROCESS_TGS</blockquote> In addition, since the underlying Hadoop APIs we * are using for impersonation are static, we define this method as static as * well.//from ww w .j a va 2s.c om * * @param principal * Fully-qualified principal to use for authentication. * @param keytab * Location of keytab file containing credentials for principal. * @return Logged-in user * @throws IOException * if login fails. */ private synchronized UserGroupInformation kerberosLogin(Authenticator authenticator, String principal, String keytab) throws IOException { // if we are the 2nd user thru the lock, the login should already be // available statically if login was successful UserGroupInformation curUser = null; try { curUser = UserGroupInformation.getLoginUser(); } catch (IOException e) { // not a big deal but this shouldn't typically happen because it will // generally fall back to the UNIX user LOG.debug("Unable to get login user before Kerberos auth attempt.", e); } // we already have logged in successfully if (curUser != null && curUser.getUserName().equals(principal)) { LOG.debug("{}: Using existing principal ({}): {}", new Object[] { authenticator, principal, curUser }); // no principal found } else { LOG.info("{}: Attempting kerberos login as principal ({}) from keytab " + "file ({})", new Object[] { authenticator, principal, keytab }); // attempt static kerberos login UserGroupInformation.loginUserFromKeytab(principal, keytab); curUser = UserGroupInformation.getLoginUser(); } return curUser; }
From source file:com.cloudera.beeswax.BeeswaxServiceImpl.java
License:Apache License
private <T> T doWithState(RunningQueryState state, PrivilegedExceptionAction<T> action) throws BeeswaxException { try {/*ww w .j av a2 s. c o m*/ UserGroupInformation ugi; if (UserGroupInformation.isSecurityEnabled()) ugi = UserGroupInformation.createProxyUser(state.query.hadoop_user, UserGroupInformation.getLoginUser()); else { ugi = UserGroupInformation.createRemoteUser(state.query.hadoop_user); } return ugi.doAs(action); } catch (UndeclaredThrowableException e) { if (e.getUndeclaredThrowable() instanceof PrivilegedActionException) { Throwable bwe = e.getUndeclaredThrowable().getCause(); if (bwe instanceof BeeswaxException) { LOG.error("Caught BeeswaxException", (BeeswaxException) bwe); throw (BeeswaxException) bwe; } } LOG.error("Caught unexpected exception.", e); throw new BeeswaxException(e.getMessage(), state.handle.log_context, state.handle); } catch (IOException e) { LOG.error("Caught IOException", e); throw new BeeswaxException(e.getMessage(), state.handle.log_context, state.handle); } catch (InterruptedException e) { LOG.error("Caught InterruptedException", e); throw new BeeswaxException(e.getMessage(), state.handle.log_context, state.handle); } }
From source file:com.cloudera.beeswax.Server.java
License:Apache License
/** * Authenticate using kerberos if configured *///from w ww. j av a 2 s .c om private static void doKerberosAuth() throws IllegalArgumentException { if (keytabFile == null || keytabFile.isEmpty()) { throw new IllegalArgumentException("No keytab specified"); } if (principalConf == null || principalConf.isEmpty()) { throw new IllegalArgumentException("No principal specified"); } // Login from the keytab try { kerberosName = SecurityUtil.getServerPrincipal(principalConf, "0.0.0.0"); UserGroupInformation.loginUserFromKeytab(kerberosName, keytabFile); LOG.info("Logged in using Kerberos ticket for '" + kerberosName + "' from " + keytabFile); bwUgi = UserGroupInformation.getCurrentUser(); // Start a thread to periodically refresh kerberos ticket Thread t = new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(refreshInterval); } catch (InterruptedException e) { return; } try { LOG.info("Refreshed Kerberos ticket for '" + kerberosName + "' from " + keytabFile); UserGroupInformation.getLoginUser().reloginFromKeytab(); } catch (IOException eIO) { LOG.error("Error refreshing Kerberos ticket", eIO); } } } }, "KerberosRefresher"); t.start(); } catch (IOException e) { throw new IllegalArgumentException("Couldn't setup Kerberos authentication", e); } }
From source file:com.cloudera.hoop.client.fs.HoopPseudoAuthenticator.java
License:Open Source License
/** * Return the client user name./*from w ww. j a va 2s . c o m*/ * * @return the client user name. */ @Override protected String getUserName() { try { return UserGroupInformation.getLoginUser().getUserName(); } catch (IOException ex) { throw new SecurityException("Could not obtain current user, " + ex.getMessage(), ex); } }
From source file:com.cloudera.lib.service.hadoop.HadoopService.java
License:Open Source License
protected UserGroupInformation getUGI(String user) throws IOException { return UserGroupInformation.createProxyUser(user, UserGroupInformation.getLoginUser()); }
From source file:com.cloudera.llama.am.yarn.YarnRMConnector.java
License:Apache License
private UserGroupInformation createUGIForApp() throws Exception { String userName = getConf().get(HADOOP_USER_NAME_KEY, HADOOP_USER_NAME_DEFAULT); UserGroupInformation llamaUGI = UserGroupInformation.getLoginUser(); return UserGroupInformation.createProxyUser(userName, llamaUGI); }
From source file:com.datatorrent.stram.cli.ApexCli.java
License:Apache License
public static void main(final String[] args) throws Exception { final ApexCli shell = new ApexCli(); shell.preImpersonationInit(args);//www.j a v a2 s . c om String hadoopUserName = System.getenv("HADOOP_USER_NAME"); if (UserGroupInformation.isSecurityEnabled() && StringUtils.isNotBlank(hadoopUserName) && !hadoopUserName.equals(UserGroupInformation.getLoginUser().getUserName())) { LOG.info("You ({}) are running as user {}", UserGroupInformation.getLoginUser().getUserName(), hadoopUserName); UserGroupInformation ugi = UserGroupInformation.createProxyUser(hadoopUserName, UserGroupInformation.getLoginUser()); ugi.doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { shell.mainHelper(); return null; } }); } else { shell.mainHelper(); } }