001/** 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018package org.apache.hadoop.security; 019 020import static org.apache.hadoop.fs.CommonConfigurationKeys.HADOOP_USER_GROUP_METRICS_PERCENTILES_INTERVALS; 021import static org.apache.hadoop.util.PlatformName.IBM_JAVA; 022 023import java.io.File; 024import java.io.IOException; 025import java.lang.reflect.UndeclaredThrowableException; 026import java.security.AccessControlContext; 027import java.security.AccessController; 028import java.security.Principal; 029import java.security.PrivilegedAction; 030import java.security.PrivilegedActionException; 031import java.security.PrivilegedExceptionAction; 032import java.util.ArrayList; 033import java.util.Arrays; 034import java.util.Collection; 035import java.util.Collections; 036import java.util.HashMap; 037import java.util.Iterator; 038import java.util.LinkedHashSet; 039import java.util.List; 040import java.util.Map; 041import java.util.Set; 042 043import javax.security.auth.Subject; 044import javax.security.auth.callback.CallbackHandler; 045import javax.security.auth.kerberos.KerberosPrincipal; 046import javax.security.auth.kerberos.KerberosTicket; 047import javax.security.auth.kerberos.KeyTab; 048import javax.security.auth.login.AppConfigurationEntry; 049import javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag; 050import javax.security.auth.login.LoginContext; 051import javax.security.auth.login.LoginException; 052import javax.security.auth.spi.LoginModule; 053 054import org.apache.commons.logging.Log; 055import org.apache.commons.logging.LogFactory; 056import org.apache.hadoop.classification.InterfaceAudience; 057import org.apache.hadoop.classification.InterfaceStability; 058import org.apache.hadoop.conf.Configuration; 059import org.apache.hadoop.io.Text; 060import org.apache.hadoop.metrics2.annotation.Metric; 061import org.apache.hadoop.metrics2.annotation.Metrics; 062import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem; 063import org.apache.hadoop.metrics2.lib.MetricsRegistry; 064import org.apache.hadoop.metrics2.lib.MutableQuantiles; 065import org.apache.hadoop.metrics2.lib.MutableRate; 066import org.apache.hadoop.security.SaslRpcServer.AuthMethod; 067import org.apache.hadoop.security.authentication.util.KerberosUtil; 068import org.apache.hadoop.security.token.Token; 069import org.apache.hadoop.security.token.TokenIdentifier; 070import org.apache.hadoop.util.Shell; 071import org.apache.hadoop.util.Time; 072 073import com.google.common.annotations.VisibleForTesting; 074 075/** 076 * User and group information for Hadoop. 077 * This class wraps around a JAAS Subject and provides methods to determine the 078 * user's username and groups. It supports both the Windows, Unix and Kerberos 079 * login modules. 080 */ 081@InterfaceAudience.LimitedPrivate({"HDFS", "MapReduce", "HBase", "Hive", "Oozie"}) 082@InterfaceStability.Evolving 083public class UserGroupInformation { 084 private static final Log LOG = LogFactory.getLog(UserGroupInformation.class); 085 /** 086 * Percentage of the ticket window to use before we renew ticket. 087 */ 088 private static final float TICKET_RENEW_WINDOW = 0.80f; 089 private static boolean shouldRenewImmediatelyForTests = false; 090 static final String HADOOP_USER_NAME = "HADOOP_USER_NAME"; 091 static final String HADOOP_PROXY_USER = "HADOOP_PROXY_USER"; 092 093 /** 094 * For the purposes of unit tests, we want to test login 095 * from keytab and don't want to wait until the renew 096 * window (controlled by TICKET_RENEW_WINDOW). 097 * @param immediate true if we should login without waiting for ticket window 098 */ 099 @VisibleForTesting 100 static void setShouldRenewImmediatelyForTests(boolean immediate) { 101 shouldRenewImmediatelyForTests = immediate; 102 } 103 104 /** 105 * UgiMetrics maintains UGI activity statistics 106 * and publishes them through the metrics interfaces. 107 */ 108 @Metrics(about="User and group related metrics", context="ugi") 109 static class UgiMetrics { 110 final MetricsRegistry registry = new MetricsRegistry("UgiMetrics"); 111 112 @Metric("Rate of successful kerberos logins and latency (milliseconds)") 113 MutableRate loginSuccess; 114 @Metric("Rate of failed kerberos logins and latency (milliseconds)") 115 MutableRate loginFailure; 116 @Metric("GetGroups") MutableRate getGroups; 117 MutableQuantiles[] getGroupsQuantiles; 118 119 static UgiMetrics create() { 120 return DefaultMetricsSystem.instance().register(new UgiMetrics()); 121 } 122 123 void addGetGroups(long latency) { 124 getGroups.add(latency); 125 if (getGroupsQuantiles != null) { 126 for (MutableQuantiles q : getGroupsQuantiles) { 127 q.add(latency); 128 } 129 } 130 } 131 } 132 133 /** 134 * A login module that looks at the Kerberos, Unix, or Windows principal and 135 * adds the corresponding UserName. 136 */ 137 @InterfaceAudience.Private 138 public static class HadoopLoginModule implements LoginModule { 139 private Subject subject; 140 141 @Override 142 public boolean abort() throws LoginException { 143 return true; 144 } 145 146 private <T extends Principal> T getCanonicalUser(Class<T> cls) { 147 for(T user: subject.getPrincipals(cls)) { 148 return user; 149 } 150 return null; 151 } 152 153 @Override 154 public boolean commit() throws LoginException { 155 if (LOG.isDebugEnabled()) { 156 LOG.debug("hadoop login commit"); 157 } 158 // if we already have a user, we are done. 159 if (!subject.getPrincipals(User.class).isEmpty()) { 160 if (LOG.isDebugEnabled()) { 161 LOG.debug("using existing subject:"+subject.getPrincipals()); 162 } 163 return true; 164 } 165 Principal user = null; 166 // if we are using kerberos, try it out 167 if (isAuthenticationMethodEnabled(AuthenticationMethod.KERBEROS)) { 168 user = getCanonicalUser(KerberosPrincipal.class); 169 if (LOG.isDebugEnabled()) { 170 LOG.debug("using kerberos user:"+user); 171 } 172 } 173 //If we don't have a kerberos user and security is disabled, check 174 //if user is specified in the environment or properties 175 if (!isSecurityEnabled() && (user == null)) { 176 String envUser = System.getenv(HADOOP_USER_NAME); 177 if (envUser == null) { 178 envUser = System.getProperty(HADOOP_USER_NAME); 179 } 180 user = envUser == null ? null : new User(envUser); 181 } 182 // use the OS user 183 if (user == null) { 184 user = getCanonicalUser(OS_PRINCIPAL_CLASS); 185 if (LOG.isDebugEnabled()) { 186 LOG.debug("using local user:"+user); 187 } 188 } 189 // if we found the user, add our principal 190 if (user != null) { 191 if (LOG.isDebugEnabled()) { 192 LOG.debug("Using user: \"" + user + "\" with name " + user.getName()); 193 } 194 195 User userEntry = null; 196 try { 197 userEntry = new User(user.getName()); 198 } catch (Exception e) { 199 throw (LoginException)(new LoginException(e.toString()).initCause(e)); 200 } 201 if (LOG.isDebugEnabled()) { 202 LOG.debug("User entry: \"" + userEntry.toString() + "\"" ); 203 } 204 205 subject.getPrincipals().add(userEntry); 206 return true; 207 } 208 LOG.error("Can't find user in " + subject); 209 throw new LoginException("Can't find user name"); 210 } 211 212 @Override 213 public void initialize(Subject subject, CallbackHandler callbackHandler, 214 Map<String, ?> sharedState, Map<String, ?> options) { 215 this.subject = subject; 216 } 217 218 @Override 219 public boolean login() throws LoginException { 220 if (LOG.isDebugEnabled()) { 221 LOG.debug("hadoop login"); 222 } 223 return true; 224 } 225 226 @Override 227 public boolean logout() throws LoginException { 228 if (LOG.isDebugEnabled()) { 229 LOG.debug("hadoop logout"); 230 } 231 return true; 232 } 233 } 234 235 /** Metrics to track UGI activity */ 236 static UgiMetrics metrics = UgiMetrics.create(); 237 /** The auth method to use */ 238 private static AuthenticationMethod authenticationMethod; 239 /** Server-side groups fetching service */ 240 private static Groups groups; 241 /** The configuration to use */ 242 private static Configuration conf; 243 244 245 /** Leave 10 minutes between relogin attempts. */ 246 private static final long MIN_TIME_BEFORE_RELOGIN = 10 * 60 * 1000L; 247 248 /**Environment variable pointing to the token cache file*/ 249 public static final String HADOOP_TOKEN_FILE_LOCATION = 250 "HADOOP_TOKEN_FILE_LOCATION"; 251 252 /** 253 * A method to initialize the fields that depend on a configuration. 254 * Must be called before useKerberos or groups is used. 255 */ 256 private static void ensureInitialized() { 257 if (conf == null) { 258 synchronized(UserGroupInformation.class) { 259 if (conf == null) { // someone might have beat us 260 initialize(new Configuration(), false); 261 } 262 } 263 } 264 } 265 266 /** 267 * Initialize UGI and related classes. 268 * @param conf the configuration to use 269 */ 270 private static synchronized void initialize(Configuration conf, 271 boolean overrideNameRules) { 272 authenticationMethod = SecurityUtil.getAuthenticationMethod(conf); 273 if (overrideNameRules || !HadoopKerberosName.hasRulesBeenSet()) { 274 try { 275 HadoopKerberosName.setConfiguration(conf); 276 } catch (IOException ioe) { 277 throw new RuntimeException( 278 "Problem with Kerberos auth_to_local name configuration", ioe); 279 } 280 } 281 // If we haven't set up testing groups, use the configuration to find it 282 if (!(groups instanceof TestingGroups)) { 283 groups = Groups.getUserToGroupsMappingService(conf); 284 } 285 UserGroupInformation.conf = conf; 286 287 if (metrics.getGroupsQuantiles == null) { 288 int[] intervals = conf.getInts(HADOOP_USER_GROUP_METRICS_PERCENTILES_INTERVALS); 289 if (intervals != null && intervals.length > 0) { 290 final int length = intervals.length; 291 MutableQuantiles[] getGroupsQuantiles = new MutableQuantiles[length]; 292 for (int i = 0; i < length; i++) { 293 getGroupsQuantiles[i] = metrics.registry.newQuantiles( 294 "getGroups" + intervals[i] + "s", 295 "Get groups", "ops", "latency", intervals[i]); 296 } 297 metrics.getGroupsQuantiles = getGroupsQuantiles; 298 } 299 } 300 } 301 302 /** 303 * Set the static configuration for UGI. 304 * In particular, set the security authentication mechanism and the 305 * group look up service. 306 * @param conf the configuration to use 307 */ 308 @InterfaceAudience.Public 309 @InterfaceStability.Evolving 310 public static void setConfiguration(Configuration conf) { 311 initialize(conf, true); 312 } 313 314 @InterfaceAudience.Private 315 @VisibleForTesting 316 static void reset() { 317 authenticationMethod = null; 318 conf = null; 319 groups = null; 320 setLoginUser(null); 321 HadoopKerberosName.setRules(null); 322 } 323 324 /** 325 * Determine if UserGroupInformation is using Kerberos to determine 326 * user identities or is relying on simple authentication 327 * 328 * @return true if UGI is working in a secure environment 329 */ 330 public static boolean isSecurityEnabled() { 331 return !isAuthenticationMethodEnabled(AuthenticationMethod.SIMPLE); 332 } 333 334 @InterfaceAudience.Private 335 @InterfaceStability.Evolving 336 private static boolean isAuthenticationMethodEnabled(AuthenticationMethod method) { 337 ensureInitialized(); 338 return (authenticationMethod == method); 339 } 340 341 /** 342 * Information about the logged in user. 343 */ 344 private static UserGroupInformation loginUser = null; 345 private static String keytabPrincipal = null; 346 private static String keytabFile = null; 347 348 private final Subject subject; 349 // All non-static fields must be read-only caches that come from the subject. 350 private final User user; 351 private final boolean isKeytab; 352 private final boolean isKrbTkt; 353 354 private static String OS_LOGIN_MODULE_NAME; 355 private static Class<? extends Principal> OS_PRINCIPAL_CLASS; 356 357 private static final boolean windows = 358 System.getProperty("os.name").startsWith("Windows"); 359 private static final boolean is64Bit = 360 System.getProperty("os.arch").contains("64"); 361 private static final boolean aix = System.getProperty("os.name").equals("AIX"); 362 363 /* Return the OS login module class name */ 364 private static String getOSLoginModuleName() { 365 if (IBM_JAVA) { 366 if (windows) { 367 return is64Bit ? "com.ibm.security.auth.module.Win64LoginModule" 368 : "com.ibm.security.auth.module.NTLoginModule"; 369 } else if (aix) { 370 return is64Bit ? "com.ibm.security.auth.module.AIX64LoginModule" 371 : "com.ibm.security.auth.module.AIXLoginModule"; 372 } else { 373 return "com.ibm.security.auth.module.LinuxLoginModule"; 374 } 375 } else { 376 return windows ? "com.sun.security.auth.module.NTLoginModule" 377 : "com.sun.security.auth.module.UnixLoginModule"; 378 } 379 } 380 381 /* Return the OS principal class */ 382 @SuppressWarnings("unchecked") 383 private static Class<? extends Principal> getOsPrincipalClass() { 384 ClassLoader cl = ClassLoader.getSystemClassLoader(); 385 try { 386 String principalClass = null; 387 if (IBM_JAVA) { 388 if (is64Bit) { 389 principalClass = "com.ibm.security.auth.UsernamePrincipal"; 390 } else { 391 if (windows) { 392 principalClass = "com.ibm.security.auth.NTUserPrincipal"; 393 } else if (aix) { 394 principalClass = "com.ibm.security.auth.AIXPrincipal"; 395 } else { 396 principalClass = "com.ibm.security.auth.LinuxPrincipal"; 397 } 398 } 399 } else { 400 principalClass = windows ? "com.sun.security.auth.NTUserPrincipal" 401 : "com.sun.security.auth.UnixPrincipal"; 402 } 403 return (Class<? extends Principal>) cl.loadClass(principalClass); 404 } catch (ClassNotFoundException e) { 405 LOG.error("Unable to find JAAS classes:" + e.getMessage()); 406 } 407 return null; 408 } 409 static { 410 OS_LOGIN_MODULE_NAME = getOSLoginModuleName(); 411 OS_PRINCIPAL_CLASS = getOsPrincipalClass(); 412 } 413 414 private static class RealUser implements Principal { 415 private final UserGroupInformation realUser; 416 417 RealUser(UserGroupInformation realUser) { 418 this.realUser = realUser; 419 } 420 421 @Override 422 public String getName() { 423 return realUser.getUserName(); 424 } 425 426 public UserGroupInformation getRealUser() { 427 return realUser; 428 } 429 430 @Override 431 public boolean equals(Object o) { 432 if (this == o) { 433 return true; 434 } else if (o == null || getClass() != o.getClass()) { 435 return false; 436 } else { 437 return realUser.equals(((RealUser) o).realUser); 438 } 439 } 440 441 @Override 442 public int hashCode() { 443 return realUser.hashCode(); 444 } 445 446 @Override 447 public String toString() { 448 return realUser.toString(); 449 } 450 } 451 452 /** 453 * A JAAS configuration that defines the login modules that we want 454 * to use for login. 455 */ 456 private static class HadoopConfiguration 457 extends javax.security.auth.login.Configuration { 458 private static final String SIMPLE_CONFIG_NAME = "hadoop-simple"; 459 private static final String USER_KERBEROS_CONFIG_NAME = 460 "hadoop-user-kerberos"; 461 private static final String KEYTAB_KERBEROS_CONFIG_NAME = 462 "hadoop-keytab-kerberos"; 463 464 private static final Map<String, String> BASIC_JAAS_OPTIONS = 465 new HashMap<String,String>(); 466 static { 467 String jaasEnvVar = System.getenv("HADOOP_JAAS_DEBUG"); 468 if (jaasEnvVar != null && "true".equalsIgnoreCase(jaasEnvVar)) { 469 BASIC_JAAS_OPTIONS.put("debug", "true"); 470 } 471 } 472 473 private static final AppConfigurationEntry OS_SPECIFIC_LOGIN = 474 new AppConfigurationEntry(OS_LOGIN_MODULE_NAME, 475 LoginModuleControlFlag.REQUIRED, 476 BASIC_JAAS_OPTIONS); 477 private static final AppConfigurationEntry HADOOP_LOGIN = 478 new AppConfigurationEntry(HadoopLoginModule.class.getName(), 479 LoginModuleControlFlag.REQUIRED, 480 BASIC_JAAS_OPTIONS); 481 private static final Map<String,String> USER_KERBEROS_OPTIONS = 482 new HashMap<String,String>(); 483 static { 484 if (IBM_JAVA) { 485 USER_KERBEROS_OPTIONS.put("useDefaultCcache", "true"); 486 } else { 487 USER_KERBEROS_OPTIONS.put("doNotPrompt", "true"); 488 USER_KERBEROS_OPTIONS.put("useTicketCache", "true"); 489 } 490 String ticketCache = System.getenv("KRB5CCNAME"); 491 if (ticketCache != null) { 492 if (IBM_JAVA) { 493 // The first value searched when "useDefaultCcache" is used. 494 System.setProperty("KRB5CCNAME", ticketCache); 495 } else { 496 USER_KERBEROS_OPTIONS.put("ticketCache", ticketCache); 497 } 498 } 499 USER_KERBEROS_OPTIONS.put("renewTGT", "true"); 500 USER_KERBEROS_OPTIONS.putAll(BASIC_JAAS_OPTIONS); 501 } 502 private static final AppConfigurationEntry USER_KERBEROS_LOGIN = 503 new AppConfigurationEntry(KerberosUtil.getKrb5LoginModuleName(), 504 LoginModuleControlFlag.OPTIONAL, 505 USER_KERBEROS_OPTIONS); 506 private static final Map<String,String> KEYTAB_KERBEROS_OPTIONS = 507 new HashMap<String,String>(); 508 static { 509 if (IBM_JAVA) { 510 KEYTAB_KERBEROS_OPTIONS.put("credsType", "both"); 511 } else { 512 KEYTAB_KERBEROS_OPTIONS.put("doNotPrompt", "true"); 513 KEYTAB_KERBEROS_OPTIONS.put("useKeyTab", "true"); 514 KEYTAB_KERBEROS_OPTIONS.put("storeKey", "true"); 515 } 516 KEYTAB_KERBEROS_OPTIONS.put("refreshKrb5Config", "true"); 517 KEYTAB_KERBEROS_OPTIONS.putAll(BASIC_JAAS_OPTIONS); 518 } 519 private static final AppConfigurationEntry KEYTAB_KERBEROS_LOGIN = 520 new AppConfigurationEntry(KerberosUtil.getKrb5LoginModuleName(), 521 LoginModuleControlFlag.REQUIRED, 522 KEYTAB_KERBEROS_OPTIONS); 523 524 private static final AppConfigurationEntry[] SIMPLE_CONF = 525 new AppConfigurationEntry[]{OS_SPECIFIC_LOGIN, HADOOP_LOGIN}; 526 527 private static final AppConfigurationEntry[] USER_KERBEROS_CONF = 528 new AppConfigurationEntry[]{OS_SPECIFIC_LOGIN, USER_KERBEROS_LOGIN, 529 HADOOP_LOGIN}; 530 531 private static final AppConfigurationEntry[] KEYTAB_KERBEROS_CONF = 532 new AppConfigurationEntry[]{KEYTAB_KERBEROS_LOGIN, HADOOP_LOGIN}; 533 534 @Override 535 public AppConfigurationEntry[] getAppConfigurationEntry(String appName) { 536 if (SIMPLE_CONFIG_NAME.equals(appName)) { 537 return SIMPLE_CONF; 538 } else if (USER_KERBEROS_CONFIG_NAME.equals(appName)) { 539 return USER_KERBEROS_CONF; 540 } else if (KEYTAB_KERBEROS_CONFIG_NAME.equals(appName)) { 541 if (IBM_JAVA) { 542 KEYTAB_KERBEROS_OPTIONS.put("useKeytab", 543 prependFileAuthority(keytabFile)); 544 } else { 545 KEYTAB_KERBEROS_OPTIONS.put("keyTab", keytabFile); 546 } 547 KEYTAB_KERBEROS_OPTIONS.put("principal", keytabPrincipal); 548 return KEYTAB_KERBEROS_CONF; 549 } 550 return null; 551 } 552 } 553 554 private static String prependFileAuthority(String keytabPath) { 555 return keytabPath.startsWith("file://") ? keytabPath 556 : "file://" + keytabPath; 557 } 558 559 /** 560 * Represents a javax.security configuration that is created at runtime. 561 */ 562 private static class DynamicConfiguration 563 extends javax.security.auth.login.Configuration { 564 private AppConfigurationEntry[] ace; 565 566 DynamicConfiguration(AppConfigurationEntry[] ace) { 567 this.ace = ace; 568 } 569 570 @Override 571 public AppConfigurationEntry[] getAppConfigurationEntry(String appName) { 572 return ace; 573 } 574 } 575 576 private static LoginContext 577 newLoginContext(String appName, Subject subject, 578 javax.security.auth.login.Configuration loginConf) 579 throws LoginException { 580 // Temporarily switch the thread's ContextClassLoader to match this 581 // class's classloader, so that we can properly load HadoopLoginModule 582 // from the JAAS libraries. 583 Thread t = Thread.currentThread(); 584 ClassLoader oldCCL = t.getContextClassLoader(); 585 t.setContextClassLoader(HadoopLoginModule.class.getClassLoader()); 586 try { 587 return new LoginContext(appName, subject, null, loginConf); 588 } finally { 589 t.setContextClassLoader(oldCCL); 590 } 591 } 592 593 private LoginContext getLogin() { 594 return user.getLogin(); 595 } 596 597 private void setLogin(LoginContext login) { 598 user.setLogin(login); 599 } 600 601 /** 602 * Create a UserGroupInformation for the given subject. 603 * This does not change the subject or acquire new credentials. 604 * @param subject the user's subject 605 */ 606 UserGroupInformation(Subject subject) { 607 this.subject = subject; 608 this.user = subject.getPrincipals(User.class).iterator().next(); 609 this.isKeytab = !subject.getPrivateCredentials(KeyTab.class).isEmpty(); 610 this.isKrbTkt = !subject.getPrivateCredentials(KerberosTicket.class).isEmpty(); 611 } 612 613 /** 614 * checks if logged in using kerberos 615 * @return true if the subject logged via keytab or has a Kerberos TGT 616 */ 617 public boolean hasKerberosCredentials() { 618 return isKeytab || isKrbTkt; 619 } 620 621 /** 622 * Return the current user, including any doAs in the current stack. 623 * @return the current user 624 * @throws IOException if login fails 625 */ 626 @InterfaceAudience.Public 627 @InterfaceStability.Evolving 628 public synchronized 629 static UserGroupInformation getCurrentUser() throws IOException { 630 AccessControlContext context = AccessController.getContext(); 631 Subject subject = Subject.getSubject(context); 632 if (subject == null || subject.getPrincipals(User.class).isEmpty()) { 633 return getLoginUser(); 634 } else { 635 return new UserGroupInformation(subject); 636 } 637 } 638 639 /** 640 * Find the most appropriate UserGroupInformation to use 641 * 642 * @param ticketCachePath The Kerberos ticket cache path, or NULL 643 * if none is specfied 644 * @param user The user name, or NULL if none is specified. 645 * 646 * @return The most appropriate UserGroupInformation 647 */ 648 public static UserGroupInformation getBestUGI( 649 String ticketCachePath, String user) throws IOException { 650 if (ticketCachePath != null) { 651 return getUGIFromTicketCache(ticketCachePath, user); 652 } else if (user == null) { 653 return getCurrentUser(); 654 } else { 655 return createRemoteUser(user); 656 } 657 } 658 659 /** 660 * Create a UserGroupInformation from a Kerberos ticket cache. 661 * 662 * @param user The principal name to load from the ticket 663 * cache 664 * @param ticketCachePath the path to the ticket cache file 665 * 666 * @throws IOException if the kerberos login fails 667 */ 668 @InterfaceAudience.Public 669 @InterfaceStability.Evolving 670 public static UserGroupInformation getUGIFromTicketCache( 671 String ticketCache, String user) throws IOException { 672 if (!isAuthenticationMethodEnabled(AuthenticationMethod.KERBEROS)) { 673 return getBestUGI(null, user); 674 } 675 try { 676 Map<String,String> krbOptions = new HashMap<String,String>(); 677 if (IBM_JAVA) { 678 krbOptions.put("useDefaultCcache", "true"); 679 // The first value searched when "useDefaultCcache" is used. 680 System.setProperty("KRB5CCNAME", ticketCache); 681 } else { 682 krbOptions.put("doNotPrompt", "true"); 683 krbOptions.put("useTicketCache", "true"); 684 krbOptions.put("useKeyTab", "false"); 685 krbOptions.put("ticketCache", ticketCache); 686 } 687 krbOptions.put("renewTGT", "false"); 688 krbOptions.putAll(HadoopConfiguration.BASIC_JAAS_OPTIONS); 689 AppConfigurationEntry ace = new AppConfigurationEntry( 690 KerberosUtil.getKrb5LoginModuleName(), 691 LoginModuleControlFlag.REQUIRED, 692 krbOptions); 693 DynamicConfiguration dynConf = 694 new DynamicConfiguration(new AppConfigurationEntry[]{ ace }); 695 LoginContext login = newLoginContext( 696 HadoopConfiguration.USER_KERBEROS_CONFIG_NAME, null, dynConf); 697 login.login(); 698 699 Subject loginSubject = login.getSubject(); 700 Set<Principal> loginPrincipals = loginSubject.getPrincipals(); 701 if (loginPrincipals.isEmpty()) { 702 throw new RuntimeException("No login principals found!"); 703 } 704 if (loginPrincipals.size() != 1) { 705 LOG.warn("found more than one principal in the ticket cache file " + 706 ticketCache); 707 } 708 User ugiUser = new User(loginPrincipals.iterator().next().getName(), 709 AuthenticationMethod.KERBEROS, login); 710 loginSubject.getPrincipals().add(ugiUser); 711 UserGroupInformation ugi = new UserGroupInformation(loginSubject); 712 ugi.setLogin(login); 713 ugi.setAuthenticationMethod(AuthenticationMethod.KERBEROS); 714 return ugi; 715 } catch (LoginException le) { 716 throw new IOException("failure to login using ticket cache file " + 717 ticketCache, le); 718 } 719 } 720 721 /** 722 * Create a UserGroupInformation from a Subject with Kerberos principal. 723 * 724 * @param user The KerberosPrincipal to use in UGI 725 * 726 * @throws IOException if the kerberos login fails 727 */ 728 public static UserGroupInformation getUGIFromSubject(Subject subject) 729 throws IOException { 730 if (subject == null) { 731 throw new IOException("Subject must not be null"); 732 } 733 734 if (subject.getPrincipals(KerberosPrincipal.class).isEmpty()) { 735 throw new IOException("Provided Subject must contain a KerberosPrincipal"); 736 } 737 738 KerberosPrincipal principal = 739 subject.getPrincipals(KerberosPrincipal.class).iterator().next(); 740 741 User ugiUser = new User(principal.getName(), 742 AuthenticationMethod.KERBEROS, null); 743 subject.getPrincipals().add(ugiUser); 744 UserGroupInformation ugi = new UserGroupInformation(subject); 745 ugi.setLogin(null); 746 ugi.setAuthenticationMethod(AuthenticationMethod.KERBEROS); 747 return ugi; 748 } 749 750 /** 751 * Get the currently logged in user. 752 * @return the logged in user 753 * @throws IOException if login fails 754 */ 755 @InterfaceAudience.Public 756 @InterfaceStability.Evolving 757 public synchronized 758 static UserGroupInformation getLoginUser() throws IOException { 759 if (loginUser == null) { 760 loginUserFromSubject(null); 761 } 762 return loginUser; 763 } 764 765 /** 766 * remove the login method that is followed by a space from the username 767 * e.g. "jack (auth:SIMPLE)" -> "jack" 768 * 769 * @param userName 770 * @return userName without login method 771 */ 772 public static String trimLoginMethod(String userName) { 773 int spaceIndex = userName.indexOf(' '); 774 if (spaceIndex >= 0) { 775 userName = userName.substring(0, spaceIndex); 776 } 777 return userName; 778 } 779 780 /** 781 * Log in a user using the given subject 782 * @parma subject the subject to use when logging in a user, or null to 783 * create a new subject. 784 * @throws IOException if login fails 785 */ 786 @InterfaceAudience.Public 787 @InterfaceStability.Evolving 788 public synchronized 789 static void loginUserFromSubject(Subject subject) throws IOException { 790 ensureInitialized(); 791 try { 792 if (subject == null) { 793 subject = new Subject(); 794 } 795 LoginContext login = 796 newLoginContext(authenticationMethod.getLoginAppName(), 797 subject, new HadoopConfiguration()); 798 login.login(); 799 UserGroupInformation realUser = new UserGroupInformation(subject); 800 realUser.setLogin(login); 801 realUser.setAuthenticationMethod(authenticationMethod); 802 realUser = new UserGroupInformation(login.getSubject()); 803 // If the HADOOP_PROXY_USER environment variable or property 804 // is specified, create a proxy user as the logged in user. 805 String proxyUser = System.getenv(HADOOP_PROXY_USER); 806 if (proxyUser == null) { 807 proxyUser = System.getProperty(HADOOP_PROXY_USER); 808 } 809 loginUser = proxyUser == null ? realUser : createProxyUser(proxyUser, realUser); 810 811 String fileLocation = System.getenv(HADOOP_TOKEN_FILE_LOCATION); 812 if (fileLocation != null) { 813 // Load the token storage file and put all of the tokens into the 814 // user. Don't use the FileSystem API for reading since it has a lock 815 // cycle (HADOOP-9212). 816 Credentials cred = Credentials.readTokenStorageFile( 817 new File(fileLocation), conf); 818 loginUser.addCredentials(cred); 819 } 820 loginUser.spawnAutoRenewalThreadForUserCreds(); 821 } catch (LoginException le) { 822 LOG.debug("failure to login", le); 823 throw new IOException("failure to login", le); 824 } 825 if (LOG.isDebugEnabled()) { 826 LOG.debug("UGI loginUser:"+loginUser); 827 } 828 } 829 830 @InterfaceAudience.Private 831 @InterfaceStability.Unstable 832 @VisibleForTesting 833 public synchronized static void setLoginUser(UserGroupInformation ugi) { 834 // if this is to become stable, should probably logout the currently 835 // logged in ugi if it's different 836 loginUser = ugi; 837 } 838 839 /** 840 * Is this user logged in from a keytab file? 841 * @return true if the credentials are from a keytab file. 842 */ 843 public boolean isFromKeytab() { 844 return isKeytab; 845 } 846 847 /** 848 * Get the Kerberos TGT 849 * @return the user's TGT or null if none was found 850 */ 851 private synchronized KerberosTicket getTGT() { 852 Set<KerberosTicket> tickets = subject 853 .getPrivateCredentials(KerberosTicket.class); 854 for (KerberosTicket ticket : tickets) { 855 if (SecurityUtil.isOriginalTGT(ticket)) { 856 if (LOG.isDebugEnabled()) { 857 LOG.debug("Found tgt " + ticket); 858 } 859 return ticket; 860 } 861 } 862 return null; 863 } 864 865 private long getRefreshTime(KerberosTicket tgt) { 866 long start = tgt.getStartTime().getTime(); 867 long end = tgt.getEndTime().getTime(); 868 return start + (long) ((end - start) * TICKET_RENEW_WINDOW); 869 } 870 871 /**Spawn a thread to do periodic renewals of kerberos credentials*/ 872 private void spawnAutoRenewalThreadForUserCreds() { 873 if (isSecurityEnabled()) { 874 //spawn thread only if we have kerb credentials 875 if (user.getAuthenticationMethod() == AuthenticationMethod.KERBEROS && 876 !isKeytab) { 877 Thread t = new Thread(new Runnable() { 878 879 @Override 880 public void run() { 881 String cmd = conf.get("hadoop.kerberos.kinit.command", 882 "kinit"); 883 KerberosTicket tgt = getTGT(); 884 if (tgt == null) { 885 return; 886 } 887 long nextRefresh = getRefreshTime(tgt); 888 while (true) { 889 try { 890 long now = Time.now(); 891 if(LOG.isDebugEnabled()) { 892 LOG.debug("Current time is " + now); 893 LOG.debug("Next refresh is " + nextRefresh); 894 } 895 if (now < nextRefresh) { 896 Thread.sleep(nextRefresh - now); 897 } 898 Shell.execCommand(cmd, "-R"); 899 if(LOG.isDebugEnabled()) { 900 LOG.debug("renewed ticket"); 901 } 902 reloginFromTicketCache(); 903 tgt = getTGT(); 904 if (tgt == null) { 905 LOG.warn("No TGT after renewal. Aborting renew thread for " + 906 getUserName()); 907 return; 908 } 909 nextRefresh = Math.max(getRefreshTime(tgt), 910 now + MIN_TIME_BEFORE_RELOGIN); 911 } catch (InterruptedException ie) { 912 LOG.warn("Terminating renewal thread"); 913 return; 914 } catch (IOException ie) { 915 LOG.warn("Exception encountered while running the" + 916 " renewal command. Aborting renew thread. " + ie); 917 return; 918 } 919 } 920 } 921 }); 922 t.setDaemon(true); 923 t.setName("TGT Renewer for " + getUserName()); 924 t.start(); 925 } 926 } 927 } 928 /** 929 * Log a user in from a keytab file. Loads a user identity from a keytab 930 * file and logs them in. They become the currently logged-in user. 931 * @param user the principal name to load from the keytab 932 * @param path the path to the keytab file 933 * @throws IOException if the keytab file can't be read 934 */ 935 @InterfaceAudience.Public 936 @InterfaceStability.Evolving 937 public synchronized 938 static void loginUserFromKeytab(String user, 939 String path 940 ) throws IOException { 941 if (!isSecurityEnabled()) 942 return; 943 944 keytabFile = path; 945 keytabPrincipal = user; 946 Subject subject = new Subject(); 947 LoginContext login; 948 long start = 0; 949 try { 950 login = newLoginContext(HadoopConfiguration.KEYTAB_KERBEROS_CONFIG_NAME, 951 subject, new HadoopConfiguration()); 952 start = Time.now(); 953 login.login(); 954 metrics.loginSuccess.add(Time.now() - start); 955 loginUser = new UserGroupInformation(subject); 956 loginUser.setLogin(login); 957 loginUser.setAuthenticationMethod(AuthenticationMethod.KERBEROS); 958 } catch (LoginException le) { 959 if (start > 0) { 960 metrics.loginFailure.add(Time.now() - start); 961 } 962 throw new IOException("Login failure for " + user + " from keytab " + 963 path+ ": " + le, le); 964 } 965 LOG.info("Login successful for user " + keytabPrincipal 966 + " using keytab file " + keytabFile); 967 } 968 969 /** 970 * Log the current user out who previously logged in using keytab. 971 * This method assumes that the user logged in by calling 972 * {@link #loginUserFromKeytab(String, String)}. 973 * 974 * @throws IOException if a failure occurred in logout, or if the user did 975 * not log in by invoking loginUserFromKeyTab() before. 976 */ 977 @InterfaceAudience.Public 978 @InterfaceStability.Evolving 979 public void logoutUserFromKeytab() throws IOException { 980 if (!isSecurityEnabled() || 981 user.getAuthenticationMethod() != AuthenticationMethod.KERBEROS) { 982 return; 983 } 984 LoginContext login = getLogin(); 985 if (login == null || keytabFile == null) { 986 throw new IOException("loginUserFromKeytab must be done first"); 987 } 988 989 try { 990 if (LOG.isDebugEnabled()) { 991 LOG.debug("Initiating logout for " + getUserName()); 992 } 993 synchronized (UserGroupInformation.class) { 994 login.logout(); 995 } 996 } catch (LoginException le) { 997 throw new IOException("Logout failure for " + user + " from keytab " + 998 keytabFile, le); 999 } 1000 1001 LOG.info("Logout successful for user " + keytabPrincipal 1002 + " using keytab file " + keytabFile); 1003 } 1004 1005 /** 1006 * Re-login a user from keytab if TGT is expired or is close to expiry. 1007 * 1008 * @throws IOException 1009 */ 1010 public synchronized void checkTGTAndReloginFromKeytab() throws IOException { 1011 if (!isSecurityEnabled() 1012 || user.getAuthenticationMethod() != AuthenticationMethod.KERBEROS 1013 || !isKeytab) 1014 return; 1015 KerberosTicket tgt = getTGT(); 1016 if (tgt != null && !shouldRenewImmediatelyForTests && 1017 Time.now() < getRefreshTime(tgt)) { 1018 return; 1019 } 1020 reloginFromKeytab(); 1021 } 1022 1023 /** 1024 * Re-Login a user in from a keytab file. Loads a user identity from a keytab 1025 * file and logs them in. They become the currently logged-in user. This 1026 * method assumes that {@link #loginUserFromKeytab(String, String)} had 1027 * happened already. 1028 * The Subject field of this UserGroupInformation object is updated to have 1029 * the new credentials. 1030 * @throws IOException on a failure 1031 */ 1032 @InterfaceAudience.Public 1033 @InterfaceStability.Evolving 1034 public synchronized void reloginFromKeytab() 1035 throws IOException { 1036 if (!isSecurityEnabled() || 1037 user.getAuthenticationMethod() != AuthenticationMethod.KERBEROS || 1038 !isKeytab) 1039 return; 1040 1041 long now = Time.now(); 1042 if (!shouldRenewImmediatelyForTests && !hasSufficientTimeElapsed(now)) { 1043 return; 1044 } 1045 1046 KerberosTicket tgt = getTGT(); 1047 //Return if TGT is valid and is not going to expire soon. 1048 if (tgt != null && !shouldRenewImmediatelyForTests && 1049 now < getRefreshTime(tgt)) { 1050 return; 1051 } 1052 1053 LoginContext login = getLogin(); 1054 if (login == null || keytabFile == null) { 1055 throw new IOException("loginUserFromKeyTab must be done first"); 1056 } 1057 1058 long start = 0; 1059 // register most recent relogin attempt 1060 user.setLastLogin(now); 1061 try { 1062 if (LOG.isDebugEnabled()) { 1063 LOG.debug("Initiating logout for " + getUserName()); 1064 } 1065 synchronized (UserGroupInformation.class) { 1066 // clear up the kerberos state. But the tokens are not cleared! As per 1067 // the Java kerberos login module code, only the kerberos credentials 1068 // are cleared 1069 login.logout(); 1070 // login and also update the subject field of this instance to 1071 // have the new credentials (pass it to the LoginContext constructor) 1072 login = newLoginContext( 1073 HadoopConfiguration.KEYTAB_KERBEROS_CONFIG_NAME, getSubject(), 1074 new HadoopConfiguration()); 1075 if (LOG.isDebugEnabled()) { 1076 LOG.debug("Initiating re-login for " + keytabPrincipal); 1077 } 1078 start = Time.now(); 1079 login.login(); 1080 metrics.loginSuccess.add(Time.now() - start); 1081 setLogin(login); 1082 } 1083 } catch (LoginException le) { 1084 if (start > 0) { 1085 metrics.loginFailure.add(Time.now() - start); 1086 } 1087 throw new IOException("Login failure for " + keytabPrincipal + 1088 " from keytab " + keytabFile, le); 1089 } 1090 } 1091 1092 /** 1093 * Re-Login a user in from the ticket cache. This 1094 * method assumes that login had happened already. 1095 * The Subject field of this UserGroupInformation object is updated to have 1096 * the new credentials. 1097 * @throws IOException on a failure 1098 */ 1099 @InterfaceAudience.Public 1100 @InterfaceStability.Evolving 1101 public synchronized void reloginFromTicketCache() 1102 throws IOException { 1103 if (!isSecurityEnabled() || 1104 user.getAuthenticationMethod() != AuthenticationMethod.KERBEROS || 1105 !isKrbTkt) 1106 return; 1107 LoginContext login = getLogin(); 1108 if (login == null) { 1109 throw new IOException("login must be done first"); 1110 } 1111 long now = Time.now(); 1112 if (!hasSufficientTimeElapsed(now)) { 1113 return; 1114 } 1115 // register most recent relogin attempt 1116 user.setLastLogin(now); 1117 try { 1118 if (LOG.isDebugEnabled()) { 1119 LOG.debug("Initiating logout for " + getUserName()); 1120 } 1121 //clear up the kerberos state. But the tokens are not cleared! As per 1122 //the Java kerberos login module code, only the kerberos credentials 1123 //are cleared 1124 login.logout(); 1125 //login and also update the subject field of this instance to 1126 //have the new credentials (pass it to the LoginContext constructor) 1127 login = 1128 newLoginContext(HadoopConfiguration.USER_KERBEROS_CONFIG_NAME, 1129 getSubject(), new HadoopConfiguration()); 1130 if (LOG.isDebugEnabled()) { 1131 LOG.debug("Initiating re-login for " + getUserName()); 1132 } 1133 login.login(); 1134 setLogin(login); 1135 } catch (LoginException le) { 1136 throw new IOException("Login failure for " + getUserName(), le); 1137 } 1138 } 1139 1140 1141 /** 1142 * Log a user in from a keytab file. Loads a user identity from a keytab 1143 * file and login them in. This new user does not affect the currently 1144 * logged-in user. 1145 * @param user the principal name to load from the keytab 1146 * @param path the path to the keytab file 1147 * @throws IOException if the keytab file can't be read 1148 */ 1149 public synchronized 1150 static UserGroupInformation loginUserFromKeytabAndReturnUGI(String user, 1151 String path 1152 ) throws IOException { 1153 if (!isSecurityEnabled()) 1154 return UserGroupInformation.getCurrentUser(); 1155 String oldKeytabFile = null; 1156 String oldKeytabPrincipal = null; 1157 1158 long start = 0; 1159 try { 1160 oldKeytabFile = keytabFile; 1161 oldKeytabPrincipal = keytabPrincipal; 1162 keytabFile = path; 1163 keytabPrincipal = user; 1164 Subject subject = new Subject(); 1165 1166 LoginContext login = newLoginContext( 1167 HadoopConfiguration.KEYTAB_KERBEROS_CONFIG_NAME, subject, 1168 new HadoopConfiguration()); 1169 1170 start = Time.now(); 1171 login.login(); 1172 metrics.loginSuccess.add(Time.now() - start); 1173 UserGroupInformation newLoginUser = new UserGroupInformation(subject); 1174 newLoginUser.setLogin(login); 1175 newLoginUser.setAuthenticationMethod(AuthenticationMethod.KERBEROS); 1176 1177 return newLoginUser; 1178 } catch (LoginException le) { 1179 if (start > 0) { 1180 metrics.loginFailure.add(Time.now() - start); 1181 } 1182 throw new IOException("Login failure for " + user + " from keytab " + 1183 path, le); 1184 } finally { 1185 if(oldKeytabFile != null) keytabFile = oldKeytabFile; 1186 if(oldKeytabPrincipal != null) keytabPrincipal = oldKeytabPrincipal; 1187 } 1188 } 1189 1190 private boolean hasSufficientTimeElapsed(long now) { 1191 if (now - user.getLastLogin() < MIN_TIME_BEFORE_RELOGIN ) { 1192 LOG.warn("Not attempting to re-login since the last re-login was " + 1193 "attempted less than " + (MIN_TIME_BEFORE_RELOGIN/1000) + " seconds"+ 1194 " before."); 1195 return false; 1196 } 1197 return true; 1198 } 1199 1200 /** 1201 * Did the login happen via keytab 1202 * @return true or false 1203 */ 1204 @InterfaceAudience.Public 1205 @InterfaceStability.Evolving 1206 public synchronized static boolean isLoginKeytabBased() throws IOException { 1207 return getLoginUser().isKeytab; 1208 } 1209 1210 /** 1211 * Did the login happen via ticket cache 1212 * @return true or false 1213 */ 1214 public static boolean isLoginTicketBased() throws IOException { 1215 return getLoginUser().isKrbTkt; 1216 } 1217 1218 /** 1219 * Create a user from a login name. It is intended to be used for remote 1220 * users in RPC, since it won't have any credentials. 1221 * @param user the full user principal name, must not be empty or null 1222 * @return the UserGroupInformation for the remote user. 1223 */ 1224 @InterfaceAudience.Public 1225 @InterfaceStability.Evolving 1226 public static UserGroupInformation createRemoteUser(String user) { 1227 return createRemoteUser(user, AuthMethod.SIMPLE); 1228 } 1229 1230 /** 1231 * Create a user from a login name. It is intended to be used for remote 1232 * users in RPC, since it won't have any credentials. 1233 * @param user the full user principal name, must not be empty or null 1234 * @return the UserGroupInformation for the remote user. 1235 */ 1236 @InterfaceAudience.Public 1237 @InterfaceStability.Evolving 1238 public static UserGroupInformation createRemoteUser(String user, AuthMethod authMethod) { 1239 if (user == null || user.isEmpty()) { 1240 throw new IllegalArgumentException("Null user"); 1241 } 1242 Subject subject = new Subject(); 1243 subject.getPrincipals().add(new User(user)); 1244 UserGroupInformation result = new UserGroupInformation(subject); 1245 result.setAuthenticationMethod(authMethod); 1246 return result; 1247 } 1248 1249 /** 1250 * existing types of authentications' methods 1251 */ 1252 @InterfaceAudience.Public 1253 @InterfaceStability.Evolving 1254 public static enum AuthenticationMethod { 1255 // currently we support only one auth per method, but eventually a 1256 // subtype is needed to differentiate, ex. if digest is token or ldap 1257 SIMPLE(AuthMethod.SIMPLE, 1258 HadoopConfiguration.SIMPLE_CONFIG_NAME), 1259 KERBEROS(AuthMethod.KERBEROS, 1260 HadoopConfiguration.USER_KERBEROS_CONFIG_NAME), 1261 TOKEN(AuthMethod.TOKEN), 1262 CERTIFICATE(null), 1263 KERBEROS_SSL(null), 1264 PROXY(null); 1265 1266 private final AuthMethod authMethod; 1267 private final String loginAppName; 1268 1269 private AuthenticationMethod(AuthMethod authMethod) { 1270 this(authMethod, null); 1271 } 1272 private AuthenticationMethod(AuthMethod authMethod, String loginAppName) { 1273 this.authMethod = authMethod; 1274 this.loginAppName = loginAppName; 1275 } 1276 1277 public AuthMethod getAuthMethod() { 1278 return authMethod; 1279 } 1280 1281 String getLoginAppName() { 1282 if (loginAppName == null) { 1283 throw new UnsupportedOperationException( 1284 this + " login authentication is not supported"); 1285 } 1286 return loginAppName; 1287 } 1288 1289 public static AuthenticationMethod valueOf(AuthMethod authMethod) { 1290 for (AuthenticationMethod value : values()) { 1291 if (value.getAuthMethod() == authMethod) { 1292 return value; 1293 } 1294 } 1295 throw new IllegalArgumentException( 1296 "no authentication method for " + authMethod); 1297 } 1298 }; 1299 1300 /** 1301 * Create a proxy user using username of the effective user and the ugi of the 1302 * real user. 1303 * @param user 1304 * @param realUser 1305 * @return proxyUser ugi 1306 */ 1307 @InterfaceAudience.Public 1308 @InterfaceStability.Evolving 1309 public static UserGroupInformation createProxyUser(String user, 1310 UserGroupInformation realUser) { 1311 if (user == null || user.isEmpty()) { 1312 throw new IllegalArgumentException("Null user"); 1313 } 1314 if (realUser == null) { 1315 throw new IllegalArgumentException("Null real user"); 1316 } 1317 Subject subject = new Subject(); 1318 Set<Principal> principals = subject.getPrincipals(); 1319 principals.add(new User(user)); 1320 principals.add(new RealUser(realUser)); 1321 UserGroupInformation result =new UserGroupInformation(subject); 1322 result.setAuthenticationMethod(AuthenticationMethod.PROXY); 1323 return result; 1324 } 1325 1326 /** 1327 * get RealUser (vs. EffectiveUser) 1328 * @return realUser running over proxy user 1329 */ 1330 @InterfaceAudience.Public 1331 @InterfaceStability.Evolving 1332 public UserGroupInformation getRealUser() { 1333 for (RealUser p: subject.getPrincipals(RealUser.class)) { 1334 return p.getRealUser(); 1335 } 1336 return null; 1337 } 1338 1339 1340 1341 /** 1342 * This class is used for storing the groups for testing. It stores a local 1343 * map that has the translation of usernames to groups. 1344 */ 1345 private static class TestingGroups extends Groups { 1346 private final Map<String, List<String>> userToGroupsMapping = 1347 new HashMap<String,List<String>>(); 1348 private Groups underlyingImplementation; 1349 1350 private TestingGroups(Groups underlyingImplementation) { 1351 super(new org.apache.hadoop.conf.Configuration()); 1352 this.underlyingImplementation = underlyingImplementation; 1353 } 1354 1355 @Override 1356 public List<String> getGroups(String user) throws IOException { 1357 List<String> result = userToGroupsMapping.get(user); 1358 1359 if (result == null) { 1360 result = underlyingImplementation.getGroups(user); 1361 } 1362 1363 return result; 1364 } 1365 1366 private void setUserGroups(String user, String[] groups) { 1367 userToGroupsMapping.put(user, Arrays.asList(groups)); 1368 } 1369 } 1370 1371 /** 1372 * Create a UGI for testing HDFS and MapReduce 1373 * @param user the full user principal name 1374 * @param userGroups the names of the groups that the user belongs to 1375 * @return a fake user for running unit tests 1376 */ 1377 @InterfaceAudience.Public 1378 @InterfaceStability.Evolving 1379 public static UserGroupInformation createUserForTesting(String user, 1380 String[] userGroups) { 1381 ensureInitialized(); 1382 UserGroupInformation ugi = createRemoteUser(user); 1383 // make sure that the testing object is setup 1384 if (!(groups instanceof TestingGroups)) { 1385 groups = new TestingGroups(groups); 1386 } 1387 // add the user groups 1388 ((TestingGroups) groups).setUserGroups(ugi.getShortUserName(), userGroups); 1389 return ugi; 1390 } 1391 1392 1393 /** 1394 * Create a proxy user UGI for testing HDFS and MapReduce 1395 * 1396 * @param user 1397 * the full user principal name for effective user 1398 * @param realUser 1399 * UGI of the real user 1400 * @param userGroups 1401 * the names of the groups that the user belongs to 1402 * @return a fake user for running unit tests 1403 */ 1404 public static UserGroupInformation createProxyUserForTesting(String user, 1405 UserGroupInformation realUser, String[] userGroups) { 1406 ensureInitialized(); 1407 UserGroupInformation ugi = createProxyUser(user, realUser); 1408 // make sure that the testing object is setup 1409 if (!(groups instanceof TestingGroups)) { 1410 groups = new TestingGroups(groups); 1411 } 1412 // add the user groups 1413 ((TestingGroups) groups).setUserGroups(ugi.getShortUserName(), userGroups); 1414 return ugi; 1415 } 1416 1417 /** 1418 * Get the user's login name. 1419 * @return the user's name up to the first '/' or '@'. 1420 */ 1421 public String getShortUserName() { 1422 for (User p: subject.getPrincipals(User.class)) { 1423 return p.getShortName(); 1424 } 1425 return null; 1426 } 1427 1428 public String getPrimaryGroupName() throws IOException { 1429 String[] groups = getGroupNames(); 1430 if (groups.length == 0) { 1431 throw new IOException("There is no primary group for UGI " + this); 1432 } 1433 return groups[0]; 1434 } 1435 1436 /** 1437 * Get the user's full principal name. 1438 * @return the user's full principal name. 1439 */ 1440 @InterfaceAudience.Public 1441 @InterfaceStability.Evolving 1442 public String getUserName() { 1443 return user.getName(); 1444 } 1445 1446 /** 1447 * Add a TokenIdentifier to this UGI. The TokenIdentifier has typically been 1448 * authenticated by the RPC layer as belonging to the user represented by this 1449 * UGI. 1450 * 1451 * @param tokenId 1452 * tokenIdentifier to be added 1453 * @return true on successful add of new tokenIdentifier 1454 */ 1455 public synchronized boolean addTokenIdentifier(TokenIdentifier tokenId) { 1456 return subject.getPublicCredentials().add(tokenId); 1457 } 1458 1459 /** 1460 * Get the set of TokenIdentifiers belonging to this UGI 1461 * 1462 * @return the set of TokenIdentifiers belonging to this UGI 1463 */ 1464 public synchronized Set<TokenIdentifier> getTokenIdentifiers() { 1465 return subject.getPublicCredentials(TokenIdentifier.class); 1466 } 1467 1468 /** 1469 * Add a token to this UGI 1470 * 1471 * @param token Token to be added 1472 * @return true on successful add of new token 1473 */ 1474 public boolean addToken(Token<? extends TokenIdentifier> token) { 1475 return (token != null) ? addToken(token.getService(), token) : false; 1476 } 1477 1478 /** 1479 * Add a named token to this UGI 1480 * 1481 * @param alias Name of the token 1482 * @param token Token to be added 1483 * @return true on successful add of new token 1484 */ 1485 public boolean addToken(Text alias, Token<? extends TokenIdentifier> token) { 1486 synchronized (subject) { 1487 getCredentialsInternal().addToken(alias, token); 1488 return true; 1489 } 1490 } 1491 1492 /** 1493 * Obtain the collection of tokens associated with this user. 1494 * 1495 * @return an unmodifiable collection of tokens associated with user 1496 */ 1497 public Collection<Token<? extends TokenIdentifier>> getTokens() { 1498 synchronized (subject) { 1499 return Collections.unmodifiableCollection( 1500 new ArrayList<Token<?>>(getCredentialsInternal().getAllTokens())); 1501 } 1502 } 1503 1504 /** 1505 * Obtain the tokens in credentials form associated with this user. 1506 * 1507 * @return Credentials of tokens associated with this user 1508 */ 1509 public Credentials getCredentials() { 1510 synchronized (subject) { 1511 Credentials creds = new Credentials(getCredentialsInternal()); 1512 Iterator<Token<?>> iter = creds.getAllTokens().iterator(); 1513 while (iter.hasNext()) { 1514 if (iter.next() instanceof Token.PrivateToken) { 1515 iter.remove(); 1516 } 1517 } 1518 return creds; 1519 } 1520 } 1521 1522 /** 1523 * Add the given Credentials to this user. 1524 * @param credentials of tokens and secrets 1525 */ 1526 public void addCredentials(Credentials credentials) { 1527 synchronized (subject) { 1528 getCredentialsInternal().addAll(credentials); 1529 } 1530 } 1531 1532 private synchronized Credentials getCredentialsInternal() { 1533 final Credentials credentials; 1534 final Set<Credentials> credentialsSet = 1535 subject.getPrivateCredentials(Credentials.class); 1536 if (!credentialsSet.isEmpty()){ 1537 credentials = credentialsSet.iterator().next(); 1538 } else { 1539 credentials = new Credentials(); 1540 subject.getPrivateCredentials().add(credentials); 1541 } 1542 return credentials; 1543 } 1544 1545 /** 1546 * Get the group names for this user. 1547 * @return the list of users with the primary group first. If the command 1548 * fails, it returns an empty list. 1549 */ 1550 public synchronized String[] getGroupNames() { 1551 ensureInitialized(); 1552 try { 1553 Set<String> result = new LinkedHashSet<String> 1554 (groups.getGroups(getShortUserName())); 1555 return result.toArray(new String[result.size()]); 1556 } catch (IOException ie) { 1557 LOG.warn("No groups available for user " + getShortUserName()); 1558 return new String[0]; 1559 } 1560 } 1561 1562 /** 1563 * Return the username. 1564 */ 1565 @Override 1566 public String toString() { 1567 StringBuilder sb = new StringBuilder(getUserName()); 1568 sb.append(" (auth:"+getAuthenticationMethod()+")"); 1569 if (getRealUser() != null) { 1570 sb.append(" via ").append(getRealUser().toString()); 1571 } 1572 return sb.toString(); 1573 } 1574 1575 /** 1576 * Sets the authentication method in the subject 1577 * 1578 * @param authMethod 1579 */ 1580 public synchronized 1581 void setAuthenticationMethod(AuthenticationMethod authMethod) { 1582 user.setAuthenticationMethod(authMethod); 1583 } 1584 1585 /** 1586 * Sets the authentication method in the subject 1587 * 1588 * @param authMethod 1589 */ 1590 public void setAuthenticationMethod(AuthMethod authMethod) { 1591 user.setAuthenticationMethod(AuthenticationMethod.valueOf(authMethod)); 1592 } 1593 1594 /** 1595 * Get the authentication method from the subject 1596 * 1597 * @return AuthenticationMethod in the subject, null if not present. 1598 */ 1599 public synchronized AuthenticationMethod getAuthenticationMethod() { 1600 return user.getAuthenticationMethod(); 1601 } 1602 1603 /** 1604 * Get the authentication method from the real user's subject. If there 1605 * is no real user, return the given user's authentication method. 1606 * 1607 * @return AuthenticationMethod in the subject, null if not present. 1608 */ 1609 public synchronized AuthenticationMethod getRealAuthenticationMethod() { 1610 UserGroupInformation ugi = getRealUser(); 1611 if (ugi == null) { 1612 ugi = this; 1613 } 1614 return ugi.getAuthenticationMethod(); 1615 } 1616 1617 /** 1618 * Returns the authentication method of a ugi. If the authentication method is 1619 * PROXY, returns the authentication method of the real user. 1620 * 1621 * @param ugi 1622 * @return AuthenticationMethod 1623 */ 1624 public static AuthenticationMethod getRealAuthenticationMethod( 1625 UserGroupInformation ugi) { 1626 AuthenticationMethod authMethod = ugi.getAuthenticationMethod(); 1627 if (authMethod == AuthenticationMethod.PROXY) { 1628 authMethod = ugi.getRealUser().getAuthenticationMethod(); 1629 } 1630 return authMethod; 1631 } 1632 1633 /** 1634 * Compare the subjects to see if they are equal to each other. 1635 */ 1636 @Override 1637 public boolean equals(Object o) { 1638 if (o == this) { 1639 return true; 1640 } else if (o == null || getClass() != o.getClass()) { 1641 return false; 1642 } else { 1643 return subject == ((UserGroupInformation) o).subject; 1644 } 1645 } 1646 1647 /** 1648 * Return the hash of the subject. 1649 */ 1650 @Override 1651 public int hashCode() { 1652 return System.identityHashCode(subject); 1653 } 1654 1655 /** 1656 * Get the underlying subject from this ugi. 1657 * @return the subject that represents this user. 1658 */ 1659 protected Subject getSubject() { 1660 return subject; 1661 } 1662 1663 /** 1664 * Run the given action as the user. 1665 * @param <T> the return type of the run method 1666 * @param action the method to execute 1667 * @return the value from the run method 1668 */ 1669 @InterfaceAudience.Public 1670 @InterfaceStability.Evolving 1671 public <T> T doAs(PrivilegedAction<T> action) { 1672 logPrivilegedAction(subject, action); 1673 return Subject.doAs(subject, action); 1674 } 1675 1676 /** 1677 * Run the given action as the user, potentially throwing an exception. 1678 * @param <T> the return type of the run method 1679 * @param action the method to execute 1680 * @return the value from the run method 1681 * @throws IOException if the action throws an IOException 1682 * @throws Error if the action throws an Error 1683 * @throws RuntimeException if the action throws a RuntimeException 1684 * @throws InterruptedException if the action throws an InterruptedException 1685 * @throws UndeclaredThrowableException if the action throws something else 1686 */ 1687 @InterfaceAudience.Public 1688 @InterfaceStability.Evolving 1689 public <T> T doAs(PrivilegedExceptionAction<T> action 1690 ) throws IOException, InterruptedException { 1691 try { 1692 logPrivilegedAction(subject, action); 1693 return Subject.doAs(subject, action); 1694 } catch (PrivilegedActionException pae) { 1695 Throwable cause = pae.getCause(); 1696 LOG.warn("PriviledgedActionException as:"+this+" cause:"+cause); 1697 if (cause instanceof IOException) { 1698 throw (IOException) cause; 1699 } else if (cause instanceof Error) { 1700 throw (Error) cause; 1701 } else if (cause instanceof RuntimeException) { 1702 throw (RuntimeException) cause; 1703 } else if (cause instanceof InterruptedException) { 1704 throw (InterruptedException) cause; 1705 } else { 1706 throw new UndeclaredThrowableException(cause); 1707 } 1708 } 1709 } 1710 1711 private void logPrivilegedAction(Subject subject, Object action) { 1712 if (LOG.isDebugEnabled()) { 1713 // would be nice if action included a descriptive toString() 1714 String where = new Throwable().getStackTrace()[2].toString(); 1715 LOG.debug("PrivilegedAction as:"+this+" from:"+where); 1716 } 1717 } 1718 1719 private void print() throws IOException { 1720 System.out.println("User: " + getUserName()); 1721 System.out.print("Group Ids: "); 1722 System.out.println(); 1723 String[] groups = getGroupNames(); 1724 System.out.print("Groups: "); 1725 for(int i=0; i < groups.length; i++) { 1726 System.out.print(groups[i] + " "); 1727 } 1728 System.out.println(); 1729 } 1730 1731 /** 1732 * A test method to print out the current user's UGI. 1733 * @param args if there are two arguments, read the user from the keytab 1734 * and print it out. 1735 * @throws Exception 1736 */ 1737 public static void main(String [] args) throws Exception { 1738 System.out.println("Getting UGI for current user"); 1739 UserGroupInformation ugi = getCurrentUser(); 1740 ugi.print(); 1741 System.out.println("UGI: " + ugi); 1742 System.out.println("Auth method " + ugi.user.getAuthenticationMethod()); 1743 System.out.println("Keytab " + ugi.isKeytab); 1744 System.out.println("============================================================"); 1745 1746 if (args.length == 2) { 1747 System.out.println("Getting UGI from keytab...."); 1748 loginUserFromKeytab(args[0], args[1]); 1749 getCurrentUser().print(); 1750 System.out.println("Keytab: " + ugi); 1751 System.out.println("Auth method " + loginUser.user.getAuthenticationMethod()); 1752 System.out.println("Keytab " + loginUser.isKeytab); 1753 } 1754 } 1755 1756}