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