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_SECURITY_AUTHENTICATION;
021
022import java.io.File;
023import java.io.IOException;
024import java.lang.reflect.UndeclaredThrowableException;
025import java.security.AccessControlContext;
026import java.security.AccessController;
027import java.security.Principal;
028import java.security.PrivilegedAction;
029import java.security.PrivilegedActionException;
030import java.security.PrivilegedExceptionAction;
031import java.util.Arrays;
032import java.util.Collection;
033import java.util.Collections;
034import java.util.HashMap;
035import java.util.List;
036import java.util.Map;
037import java.util.Set;
038
039import javax.security.auth.Subject;
040import javax.security.auth.callback.CallbackHandler;
041import javax.security.auth.kerberos.KerberosKey;
042import javax.security.auth.kerberos.KerberosPrincipal;
043import javax.security.auth.kerberos.KerberosTicket;
044import javax.security.auth.login.AppConfigurationEntry;
045import javax.security.auth.login.LoginContext;
046import javax.security.auth.login.LoginException;
047import javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag;
048import javax.security.auth.spi.LoginModule;
049
050import org.apache.commons.logging.Log;
051import org.apache.commons.logging.LogFactory;
052import org.apache.hadoop.classification.InterfaceAudience;
053import org.apache.hadoop.classification.InterfaceStability;
054import org.apache.hadoop.conf.Configuration;
055import org.apache.hadoop.fs.Path;
056import org.apache.hadoop.io.Text;
057import org.apache.hadoop.metrics2.annotation.Metric;
058import org.apache.hadoop.metrics2.annotation.Metrics;
059import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
060import org.apache.hadoop.metrics2.lib.MutableRate;
061import org.apache.hadoop.security.authentication.util.KerberosName;
062import org.apache.hadoop.security.authentication.util.KerberosUtil;
063import org.apache.hadoop.security.token.Token;
064import org.apache.hadoop.security.token.TokenIdentifier;
065import org.apache.hadoop.util.Shell;
066
067import com.google.common.annotations.VisibleForTesting;
068
069/**
070 * User and group information for Hadoop.
071 * This class wraps around a JAAS Subject and provides methods to determine the
072 * user's username and groups. It supports both the Windows, Unix and Kerberos 
073 * login modules.
074 */
075@InterfaceAudience.LimitedPrivate({"HDFS", "MapReduce"})
076@InterfaceStability.Evolving
077public class UserGroupInformation {
078  private static final Log LOG =  LogFactory.getLog(UserGroupInformation.class);
079  /**
080   * Percentage of the ticket window to use before we renew ticket.
081   */
082  private static final float TICKET_RENEW_WINDOW = 0.80f;
083  static final String HADOOP_USER_NAME = "HADOOP_USER_NAME";
084  static final String HADOOP_PROXY_USER = "HADOOP_PROXY_USER";
085  
086  /** 
087   * UgiMetrics maintains UGI activity statistics
088   * and publishes them through the metrics interfaces.
089   */
090  @Metrics(about="User and group related metrics", context="ugi")
091  static class UgiMetrics {
092    @Metric("Rate of successful kerberos logins and latency (milliseconds)")
093    MutableRate loginSuccess;
094    @Metric("Rate of failed kerberos logins and latency (milliseconds)")
095    MutableRate loginFailure;
096
097    static UgiMetrics create() {
098      return DefaultMetricsSystem.instance().register(new UgiMetrics());
099    }
100  }
101  
102  /**
103   * A login module that looks at the Kerberos, Unix, or Windows principal and
104   * adds the corresponding UserName.
105   */
106  @InterfaceAudience.Private
107  public static class HadoopLoginModule implements LoginModule {
108    private Subject subject;
109
110    @Override
111    public boolean abort() throws LoginException {
112      return true;
113    }
114
115    private <T extends Principal> T getCanonicalUser(Class<T> cls) {
116      for(T user: subject.getPrincipals(cls)) {
117        return user;
118      }
119      return null;
120    }
121
122    @Override
123    public boolean commit() throws LoginException {
124      if (LOG.isDebugEnabled()) {
125        LOG.debug("hadoop login commit");
126      }
127      // if we already have a user, we are done.
128      if (!subject.getPrincipals(User.class).isEmpty()) {
129        if (LOG.isDebugEnabled()) {
130          LOG.debug("using existing subject:"+subject.getPrincipals());
131        }
132        return true;
133      }
134      Principal user = null;
135      // if we are using kerberos, try it out
136      if (useKerberos) {
137        user = getCanonicalUser(KerberosPrincipal.class);
138        if (LOG.isDebugEnabled()) {
139          LOG.debug("using kerberos user:"+user);
140        }
141      }
142      //If we don't have a kerberos user and security is disabled, check
143      //if user is specified in the environment or properties
144      if (!isSecurityEnabled() && (user == null)) {
145        String envUser = System.getenv(HADOOP_USER_NAME);
146        if (envUser == null) {
147          envUser = System.getProperty(HADOOP_USER_NAME);
148        }
149        user = envUser == null ? null : new User(envUser);
150      }
151      // use the OS user
152      if (user == null) {
153        user = getCanonicalUser(OS_PRINCIPAL_CLASS);
154        if (LOG.isDebugEnabled()) {
155          LOG.debug("using local user:"+user);
156        }
157      }
158      // if we found the user, add our principal
159      if (user != null) {
160        subject.getPrincipals().add(new User(user.getName()));
161        return true;
162      }
163      LOG.error("Can't find user in " + subject);
164      throw new LoginException("Can't find user name");
165    }
166
167    @Override
168    public void initialize(Subject subject, CallbackHandler callbackHandler,
169                           Map<String, ?> sharedState, Map<String, ?> options) {
170      this.subject = subject;
171    }
172
173    @Override
174    public boolean login() throws LoginException {
175      if (LOG.isDebugEnabled()) {
176        LOG.debug("hadoop login");
177      }
178      return true;
179    }
180
181    @Override
182    public boolean logout() throws LoginException {
183      if (LOG.isDebugEnabled()) {
184        LOG.debug("hadoop logout");
185      }
186      return true;
187    }
188  }
189
190  /** Metrics to track UGI activity */
191  static UgiMetrics metrics = UgiMetrics.create();
192  /** Are the static variables that depend on configuration initialized? */
193  /** Should we use Kerberos configuration? */
194  private static boolean useKerberos;
195  /** Server-side groups fetching service */
196  private static Groups groups;
197  /** The configuration to use */
198  private static Configuration conf;
199
200  
201  /** Leave 10 minutes between relogin attempts. */
202  private static final long MIN_TIME_BEFORE_RELOGIN = 10 * 60 * 1000L;
203  
204  /**Environment variable pointing to the token cache file*/
205  public static final String HADOOP_TOKEN_FILE_LOCATION = 
206    "HADOOP_TOKEN_FILE_LOCATION";
207  
208  /** 
209   * A method to initialize the fields that depend on a configuration.
210   * Must be called before useKerberos or groups is used.
211   */
212  private static void ensureInitialized() {
213    if (conf == null) {
214      synchronized(UserGroupInformation.class) {
215        if (conf == null) { // someone might have beat us
216          initialize(new Configuration(), KerberosName.hasRulesBeenSet());
217        }
218      }
219    }
220  }
221
222  /**
223   * Initialize UGI and related classes.
224   * @param conf the configuration to use
225   */
226  private static synchronized void initialize(Configuration conf, boolean skipRulesSetting) {
227    initUGI(conf);
228    // give the configuration on how to translate Kerberos names
229    try {
230      if (!skipRulesSetting) {
231        HadoopKerberosName.setConfiguration(conf);
232      }
233    } catch (IOException ioe) {
234      throw new RuntimeException("Problem with Kerberos auth_to_local name " +
235          "configuration", ioe);
236    }
237  }
238  
239  /**
240   * Set the configuration values for UGI.
241   * @param conf the configuration to use
242   */
243  private static synchronized void initUGI(Configuration conf) {
244    String value = conf.get(HADOOP_SECURITY_AUTHENTICATION);
245    if (value == null || "simple".equals(value)) {
246      useKerberos = false;
247    } else if ("kerberos".equals(value)) {
248      useKerberos = true;
249    } else {
250      throw new IllegalArgumentException("Invalid attribute value for " +
251                                         HADOOP_SECURITY_AUTHENTICATION + 
252                                         " of " + value);
253    }
254    // If we haven't set up testing groups, use the configuration to find it
255    if (!(groups instanceof TestingGroups)) {
256      groups = Groups.getUserToGroupsMappingService(conf);
257    }
258    UserGroupInformation.conf = conf;
259  }
260
261  /**
262   * Set the static configuration for UGI.
263   * In particular, set the security authentication mechanism and the
264   * group look up service.
265   * @param conf the configuration to use
266   */
267  public static void setConfiguration(Configuration conf) {
268    initialize(conf, false);
269  }
270  
271  /**
272   * Determine if UserGroupInformation is using Kerberos to determine
273   * user identities or is relying on simple authentication
274   * 
275   * @return true if UGI is working in a secure environment
276   */
277  public static boolean isSecurityEnabled() {
278    ensureInitialized();
279    return useKerberos;
280  }
281  
282  /**
283   * Information about the logged in user.
284   */
285  private static UserGroupInformation loginUser = null;
286  private static String keytabPrincipal = null;
287  private static String keytabFile = null;
288
289  private final Subject subject;
290  // All non-static fields must be read-only caches that come from the subject.
291  private final User user;
292  private final boolean isKeytab;
293  private final boolean isKrbTkt;
294  
295  private static String OS_LOGIN_MODULE_NAME;
296  private static Class<? extends Principal> OS_PRINCIPAL_CLASS;
297  private static final boolean windows = 
298                           System.getProperty("os.name").startsWith("Windows");
299  /* Return the OS login module class name */
300  private static String getOSLoginModuleName() {
301    if (System.getProperty("java.vendor").contains("IBM")) {
302      return windows ? "com.ibm.security.auth.module.NTLoginModule"
303       : "com.ibm.security.auth.module.LinuxLoginModule";
304    } else {
305      return windows ? "com.sun.security.auth.module.NTLoginModule"
306        : "com.sun.security.auth.module.UnixLoginModule";
307    }
308  }
309
310  /* Return the OS principal class */
311  @SuppressWarnings("unchecked")
312  private static Class<? extends Principal> getOsPrincipalClass() {
313    ClassLoader cl = ClassLoader.getSystemClassLoader();
314    try {
315      if (System.getProperty("java.vendor").contains("IBM")) {
316        if (windows) {
317          return (Class<? extends Principal>)
318            cl.loadClass("com.ibm.security.auth.UsernamePrincipal");
319        } else {
320          return (Class<? extends Principal>)
321            (System.getProperty("os.arch").contains("64")
322             ? cl.loadClass("com.ibm.security.auth.UsernamePrincipal")
323             : cl.loadClass("com.ibm.security.auth.LinuxPrincipal"));
324        }
325      } else {
326        return (Class<? extends Principal>) (windows
327           ? cl.loadClass("com.sun.security.auth.NTUserPrincipal")
328           : cl.loadClass("com.sun.security.auth.UnixPrincipal"));
329      }
330    } catch (ClassNotFoundException e) {
331      LOG.error("Unable to find JAAS classes:" + e.getMessage());
332    }
333    return null;
334  }
335  static {
336    OS_LOGIN_MODULE_NAME = getOSLoginModuleName();
337    OS_PRINCIPAL_CLASS = getOsPrincipalClass();
338  }
339
340  private static class RealUser implements Principal {
341    private final UserGroupInformation realUser;
342    
343    RealUser(UserGroupInformation realUser) {
344      this.realUser = realUser;
345    }
346    
347    public String getName() {
348      return realUser.getUserName();
349    }
350    
351    public UserGroupInformation getRealUser() {
352      return realUser;
353    }
354    
355    @Override
356    public boolean equals(Object o) {
357      if (this == o) {
358        return true;
359      } else if (o == null || getClass() != o.getClass()) {
360        return false;
361      } else {
362        return realUser.equals(((RealUser) o).realUser);
363      }
364    }
365    
366    @Override
367    public int hashCode() {
368      return realUser.hashCode();
369    }
370    
371    @Override
372    public String toString() {
373      return realUser.toString();
374    }
375  }
376  
377  /**
378   * A JAAS configuration that defines the login modules that we want
379   * to use for login.
380   */
381  private static class HadoopConfiguration 
382      extends javax.security.auth.login.Configuration {
383    private static final String SIMPLE_CONFIG_NAME = "hadoop-simple";
384    private static final String USER_KERBEROS_CONFIG_NAME = 
385      "hadoop-user-kerberos";
386    private static final String KEYTAB_KERBEROS_CONFIG_NAME = 
387      "hadoop-keytab-kerberos";
388
389    private static final Map<String, String> BASIC_JAAS_OPTIONS =
390      new HashMap<String,String>();
391    static {
392      String jaasEnvVar = System.getenv("HADOOP_JAAS_DEBUG");
393      if (jaasEnvVar != null && "true".equalsIgnoreCase(jaasEnvVar)) {
394        BASIC_JAAS_OPTIONS.put("debug", "true");
395      }
396    }
397    
398    private static final AppConfigurationEntry OS_SPECIFIC_LOGIN =
399      new AppConfigurationEntry(OS_LOGIN_MODULE_NAME,
400                                LoginModuleControlFlag.REQUIRED,
401                                BASIC_JAAS_OPTIONS);
402    private static final AppConfigurationEntry HADOOP_LOGIN =
403      new AppConfigurationEntry(HadoopLoginModule.class.getName(),
404                                LoginModuleControlFlag.REQUIRED,
405                                BASIC_JAAS_OPTIONS);
406    private static final Map<String,String> USER_KERBEROS_OPTIONS = 
407      new HashMap<String,String>();
408    static {
409      USER_KERBEROS_OPTIONS.put("doNotPrompt", "true");
410      USER_KERBEROS_OPTIONS.put("useTicketCache", "true");
411      USER_KERBEROS_OPTIONS.put("renewTGT", "true");
412      String ticketCache = System.getenv("KRB5CCNAME");
413      if (ticketCache != null) {
414        USER_KERBEROS_OPTIONS.put("ticketCache", ticketCache);
415      }
416      USER_KERBEROS_OPTIONS.putAll(BASIC_JAAS_OPTIONS);
417    }
418    private static final AppConfigurationEntry USER_KERBEROS_LOGIN =
419      new AppConfigurationEntry(KerberosUtil.getKrb5LoginModuleName(),
420                                LoginModuleControlFlag.OPTIONAL,
421                                USER_KERBEROS_OPTIONS);
422    private static final Map<String,String> KEYTAB_KERBEROS_OPTIONS = 
423      new HashMap<String,String>();
424    static {
425      KEYTAB_KERBEROS_OPTIONS.put("doNotPrompt", "true");
426      KEYTAB_KERBEROS_OPTIONS.put("useKeyTab", "true");
427      KEYTAB_KERBEROS_OPTIONS.put("storeKey", "true");
428      KEYTAB_KERBEROS_OPTIONS.put("refreshKrb5Config", "true");
429      KEYTAB_KERBEROS_OPTIONS.putAll(BASIC_JAAS_OPTIONS);      
430    }
431    private static final AppConfigurationEntry KEYTAB_KERBEROS_LOGIN =
432      new AppConfigurationEntry(KerberosUtil.getKrb5LoginModuleName(),
433                                LoginModuleControlFlag.REQUIRED,
434                                KEYTAB_KERBEROS_OPTIONS);
435    
436    private static final AppConfigurationEntry[] SIMPLE_CONF = 
437      new AppConfigurationEntry[]{OS_SPECIFIC_LOGIN, HADOOP_LOGIN};
438    
439    private static final AppConfigurationEntry[] USER_KERBEROS_CONF =
440      new AppConfigurationEntry[]{OS_SPECIFIC_LOGIN, USER_KERBEROS_LOGIN,
441                                  HADOOP_LOGIN};
442
443    private static final AppConfigurationEntry[] KEYTAB_KERBEROS_CONF =
444      new AppConfigurationEntry[]{KEYTAB_KERBEROS_LOGIN, HADOOP_LOGIN};
445
446    @Override
447    public AppConfigurationEntry[] getAppConfigurationEntry(String appName) {
448      if (SIMPLE_CONFIG_NAME.equals(appName)) {
449        return SIMPLE_CONF;
450      } else if (USER_KERBEROS_CONFIG_NAME.equals(appName)) {
451        return USER_KERBEROS_CONF;
452      } else if (KEYTAB_KERBEROS_CONFIG_NAME.equals(appName)) {
453        KEYTAB_KERBEROS_OPTIONS.put("keyTab", keytabFile);
454        KEYTAB_KERBEROS_OPTIONS.put("principal", keytabPrincipal);
455        return KEYTAB_KERBEROS_CONF;
456      }
457      return null;
458    }
459  }
460  
461  private static LoginContext
462  newLoginContext(String appName, Subject subject) throws LoginException {
463    // Temporarily switch the thread's ContextClassLoader to match this
464    // class's classloader, so that we can properly load HadoopLoginModule
465    // from the JAAS libraries.
466    Thread t = Thread.currentThread();
467    ClassLoader oldCCL = t.getContextClassLoader();
468    t.setContextClassLoader(HadoopLoginModule.class.getClassLoader());
469    try {
470      return new LoginContext(appName, subject, null, new HadoopConfiguration());
471    } finally {
472      t.setContextClassLoader(oldCCL);
473    }
474  }
475
476  private LoginContext getLogin() {
477    return user.getLogin();
478  }
479  
480  private void setLogin(LoginContext login) {
481    user.setLogin(login);
482  }
483
484  /**
485   * Create a UserGroupInformation for the given subject.
486   * This does not change the subject or acquire new credentials.
487   * @param subject the user's subject
488   */
489  UserGroupInformation(Subject subject) {
490    this.subject = subject;
491    this.user = subject.getPrincipals(User.class).iterator().next();
492    this.isKeytab = !subject.getPrivateCredentials(KerberosKey.class).isEmpty();
493    this.isKrbTkt = !subject.getPrivateCredentials(KerberosTicket.class).isEmpty();
494  }
495  
496  /**
497   * checks if logged in using kerberos
498   * @return true if the subject logged via keytab or has a Kerberos TGT
499   */
500  public boolean hasKerberosCredentials() {
501    return isKeytab || isKrbTkt;
502  }
503
504  /**
505   * Return the current user, including any doAs in the current stack.
506   * @return the current user
507   * @throws IOException if login fails
508   */
509  public synchronized
510  static UserGroupInformation getCurrentUser() throws IOException {
511    AccessControlContext context = AccessController.getContext();
512    Subject subject = Subject.getSubject(context);
513    if (subject == null || subject.getPrincipals(User.class).isEmpty()) {
514      return getLoginUser();
515    } else {
516      return new UserGroupInformation(subject);
517    }
518  }
519
520  /**
521   * Get the currently logged in user.
522   * @return the logged in user
523   * @throws IOException if login fails
524   */
525  public synchronized 
526  static UserGroupInformation getLoginUser() throws IOException {
527    if (loginUser == null) {
528      loginUserFromSubject(null);
529    }
530    return loginUser;
531  }
532  
533  /**
534   * Log in a user using the given subject
535   * @parma subject the subject to use when logging in a user, or null to 
536   * create a new subject.
537   * @throws IOException if login fails
538   */
539  @InterfaceAudience.Public
540  @InterfaceStability.Evolving
541  public synchronized 
542  static void loginUserFromSubject(Subject subject) throws IOException {
543    ensureInitialized();
544    try {
545      if (subject == null) {
546        subject = new Subject();
547      }
548      LoginContext login;
549      if (isSecurityEnabled()) {
550        login = newLoginContext(HadoopConfiguration.USER_KERBEROS_CONFIG_NAME,
551            subject);
552      } else {
553        login = newLoginContext(HadoopConfiguration.SIMPLE_CONFIG_NAME, 
554            subject);
555      }
556      login.login();
557      UserGroupInformation realUser = new UserGroupInformation(subject);
558      realUser.setLogin(login);
559      realUser.setAuthenticationMethod(isSecurityEnabled() ?
560                                       AuthenticationMethod.KERBEROS :
561                                       AuthenticationMethod.SIMPLE);
562      realUser = new UserGroupInformation(login.getSubject());
563      // If the HADOOP_PROXY_USER environment variable or property
564      // is specified, create a proxy user as the logged in user.
565      String proxyUser = System.getenv(HADOOP_PROXY_USER);
566      if (proxyUser == null) {
567        proxyUser = System.getProperty(HADOOP_PROXY_USER);
568      }
569      setLoginUser(proxyUser == null ? realUser : createProxyUser(proxyUser, realUser));
570
571      String fileLocation = System.getenv(HADOOP_TOKEN_FILE_LOCATION);
572      if (fileLocation != null) {
573        // Load the token storage file and put all of the tokens into the
574        // user. Don't use the FileSystem API for reading since it has a lock
575        // cycle (HADOOP-9212).
576        Credentials cred = Credentials.readTokenStorageFile(
577            new File(fileLocation), conf);
578        loginUser.addCredentials(cred);
579      }
580      loginUser.spawnAutoRenewalThreadForUserCreds();
581    } catch (LoginException le) {
582      throw new IOException("failure to login", le);
583    }
584    if (LOG.isDebugEnabled()) {
585      LOG.debug("UGI loginUser:"+loginUser);
586    } 
587  }
588
589  @InterfaceAudience.Private
590  @InterfaceStability.Unstable
591  @VisibleForTesting
592  public synchronized static void setLoginUser(UserGroupInformation ugi) {
593    // if this is to become stable, should probably logout the currently
594    // logged in ugi if it's different
595    loginUser = ugi;
596  }
597
598  /**
599   * Is this user logged in from a keytab file?
600   * @return true if the credentials are from a keytab file.
601   */
602  public boolean isFromKeytab() {
603    return isKeytab;
604  }
605  
606  /**
607   * Get the Kerberos TGT
608   * @return the user's TGT or null if none was found
609   */
610  private synchronized KerberosTicket getTGT() {
611    Set<KerberosTicket> tickets = subject
612        .getPrivateCredentials(KerberosTicket.class);
613    for (KerberosTicket ticket : tickets) {
614      if (SecurityUtil.isOriginalTGT(ticket)) {
615        if (LOG.isDebugEnabled()) {
616          LOG.debug("Found tgt " + ticket);
617        }
618        return ticket;
619      }
620    }
621    return null;
622  }
623  
624  private long getRefreshTime(KerberosTicket tgt) {
625    long start = tgt.getStartTime().getTime();
626    long end = tgt.getEndTime().getTime();
627    return start + (long) ((end - start) * TICKET_RENEW_WINDOW);
628  }
629
630  /**Spawn a thread to do periodic renewals of kerberos credentials*/
631  private void spawnAutoRenewalThreadForUserCreds() {
632    if (isSecurityEnabled()) {
633      //spawn thread only if we have kerb credentials
634      if (user.getAuthenticationMethod() == AuthenticationMethod.KERBEROS &&
635          !isKeytab) {
636        Thread t = new Thread(new Runnable() {
637          
638          public void run() {
639            String cmd = conf.get("hadoop.kerberos.kinit.command",
640                                  "kinit");
641            KerberosTicket tgt = getTGT();
642            if (tgt == null) {
643              return;
644            }
645            long nextRefresh = getRefreshTime(tgt);
646            while (true) {
647              try {
648                long now = System.currentTimeMillis();
649                if(LOG.isDebugEnabled()) {
650                  LOG.debug("Current time is " + now);
651                  LOG.debug("Next refresh is " + nextRefresh);
652                }
653                if (now < nextRefresh) {
654                  Thread.sleep(nextRefresh - now);
655                }
656                Shell.execCommand(cmd, "-R");
657                if(LOG.isDebugEnabled()) {
658                  LOG.debug("renewed ticket");
659                }
660                reloginFromTicketCache();
661                tgt = getTGT();
662                if (tgt == null) {
663                  LOG.warn("No TGT after renewal. Aborting renew thread for " +
664                           getUserName());
665                  return;
666                }
667                nextRefresh = Math.max(getRefreshTime(tgt),
668                                       now + MIN_TIME_BEFORE_RELOGIN);
669              } catch (InterruptedException ie) {
670                LOG.warn("Terminating renewal thread");
671                return;
672              } catch (IOException ie) {
673                LOG.warn("Exception encountered while running the" +
674                    " renewal command. Aborting renew thread. " + ie);
675                return;
676              }
677            }
678          }
679        });
680        t.setDaemon(true);
681        t.setName("TGT Renewer for " + getUserName());
682        t.start();
683      }
684    }
685  }
686  /**
687   * Log a user in from a keytab file. Loads a user identity from a keytab
688   * file and logs them in. They become the currently logged-in user.
689   * @param user the principal name to load from the keytab
690   * @param path the path to the keytab file
691   * @throws IOException if the keytab file can't be read
692   */
693  public synchronized
694  static void loginUserFromKeytab(String user,
695                                  String path
696                                  ) throws IOException {
697    if (!isSecurityEnabled())
698      return;
699
700    keytabFile = path;
701    keytabPrincipal = user;
702    Subject subject = new Subject();
703    LoginContext login; 
704    long start = 0;
705    try {
706      login = 
707        newLoginContext(HadoopConfiguration.KEYTAB_KERBEROS_CONFIG_NAME, subject);
708      start = System.currentTimeMillis();
709      login.login();
710      metrics.loginSuccess.add(System.currentTimeMillis() - start);
711      setLoginUser(new UserGroupInformation(subject));
712      loginUser.setLogin(login);
713      loginUser.setAuthenticationMethod(AuthenticationMethod.KERBEROS);
714    } catch (LoginException le) {
715      if (start > 0) {
716        metrics.loginFailure.add(System.currentTimeMillis() - start);
717      }
718      throw new IOException("Login failure for " + user + " from keytab " + 
719                            path, le);
720    }
721    LOG.info("Login successful for user " + keytabPrincipal
722        + " using keytab file " + keytabFile);
723  }
724  
725  /**
726   * Re-login a user from keytab if TGT is expired or is close to expiry.
727   * 
728   * @throws IOException
729   */
730  public synchronized void checkTGTAndReloginFromKeytab() throws IOException {
731    if (!isSecurityEnabled()
732        || user.getAuthenticationMethod() != AuthenticationMethod.KERBEROS
733        || !isKeytab)
734      return;
735    KerberosTicket tgt = getTGT();
736    if (tgt != null && System.currentTimeMillis() < getRefreshTime(tgt)) {
737      return;
738    }
739    reloginFromKeytab();
740  }
741
742  /**
743   * Re-Login a user in from a keytab file. Loads a user identity from a keytab
744   * file and logs them in. They become the currently logged-in user. This
745   * method assumes that {@link #loginUserFromKeytab(String, String)} had 
746   * happened already.
747   * The Subject field of this UserGroupInformation object is updated to have
748   * the new credentials.
749   * @throws IOException on a failure
750   */
751  public synchronized void reloginFromKeytab()
752  throws IOException {
753    if (!isSecurityEnabled() ||
754         user.getAuthenticationMethod() != AuthenticationMethod.KERBEROS ||
755         !isKeytab)
756      return;
757    
758    long now = System.currentTimeMillis();
759    if (!hasSufficientTimeElapsed(now)) {
760      return;
761    }
762
763    KerberosTicket tgt = getTGT();
764    //Return if TGT is valid and is not going to expire soon.
765    if (tgt != null && now < getRefreshTime(tgt)) {
766      return;
767    }
768    
769    LoginContext login = getLogin();
770    if (login == null || keytabFile == null) {
771      throw new IOException("loginUserFromKeyTab must be done first");
772    }
773    
774    long start = 0;
775    // register most recent relogin attempt
776    user.setLastLogin(now);
777    try {
778      LOG.info("Initiating logout for " + getUserName());
779      synchronized (UserGroupInformation.class) {
780        // clear up the kerberos state. But the tokens are not cleared! As per
781        // the Java kerberos login module code, only the kerberos credentials
782        // are cleared
783        login.logout();
784        // login and also update the subject field of this instance to
785        // have the new credentials (pass it to the LoginContext constructor)
786        login = newLoginContext(
787            HadoopConfiguration.KEYTAB_KERBEROS_CONFIG_NAME, getSubject());
788        LOG.info("Initiating re-login for " + keytabPrincipal);
789        start = System.currentTimeMillis();
790        login.login();
791        metrics.loginSuccess.add(System.currentTimeMillis() - start);
792        setLogin(login);
793      }
794    } catch (LoginException le) {
795      if (start > 0) {
796        metrics.loginFailure.add(System.currentTimeMillis() - start);
797      }
798      throw new IOException("Login failure for " + keytabPrincipal + 
799          " from keytab " + keytabFile, le);
800    } 
801  }
802
803  /**
804   * Re-Login a user in from the ticket cache.  This
805   * method assumes that login had happened already.
806   * The Subject field of this UserGroupInformation object is updated to have
807   * the new credentials.
808   * @throws IOException on a failure
809   */
810  public synchronized void reloginFromTicketCache()
811  throws IOException {
812    if (!isSecurityEnabled() || 
813        user.getAuthenticationMethod() != AuthenticationMethod.KERBEROS ||
814        !isKrbTkt)
815      return;
816    LoginContext login = getLogin();
817    if (login == null) {
818      throw new IOException("login must be done first");
819    }
820    long now = System.currentTimeMillis();
821    if (!hasSufficientTimeElapsed(now)) {
822      return;
823    }
824    // register most recent relogin attempt
825    user.setLastLogin(now);
826    try {
827      LOG.info("Initiating logout for " + getUserName());
828      //clear up the kerberos state. But the tokens are not cleared! As per 
829      //the Java kerberos login module code, only the kerberos credentials
830      //are cleared
831      login.logout();
832      //login and also update the subject field of this instance to 
833      //have the new credentials (pass it to the LoginContext constructor)
834      login = 
835        newLoginContext(HadoopConfiguration.USER_KERBEROS_CONFIG_NAME, 
836            getSubject());
837      LOG.info("Initiating re-login for " + getUserName());
838      login.login();
839      setLogin(login);
840    } catch (LoginException le) {
841      throw new IOException("Login failure for " + getUserName(), le);
842    } 
843  }
844
845
846  /**
847   * Log a user in from a keytab file. Loads a user identity from a keytab
848   * file and login them in. This new user does not affect the currently
849   * logged-in user.
850   * @param user the principal name to load from the keytab
851   * @param path the path to the keytab file
852   * @throws IOException if the keytab file can't be read
853   */
854  public synchronized
855  static UserGroupInformation loginUserFromKeytabAndReturnUGI(String user,
856                                  String path
857                                  ) throws IOException {
858    if (!isSecurityEnabled())
859      return UserGroupInformation.getCurrentUser();
860    String oldKeytabFile = null;
861    String oldKeytabPrincipal = null;
862
863    long start = 0;
864    try {
865      oldKeytabFile = keytabFile;
866      oldKeytabPrincipal = keytabPrincipal;
867      keytabFile = path;
868      keytabPrincipal = user;
869      Subject subject = new Subject();
870      
871      LoginContext login = 
872        newLoginContext(HadoopConfiguration.KEYTAB_KERBEROS_CONFIG_NAME, subject); 
873       
874      start = System.currentTimeMillis();
875      login.login();
876      metrics.loginSuccess.add(System.currentTimeMillis() - start);
877      UserGroupInformation newLoginUser = new UserGroupInformation(subject);
878      newLoginUser.setLogin(login);
879      newLoginUser.setAuthenticationMethod(AuthenticationMethod.KERBEROS);
880      
881      return newLoginUser;
882    } catch (LoginException le) {
883      if (start > 0) {
884        metrics.loginFailure.add(System.currentTimeMillis() - start);
885      }
886      throw new IOException("Login failure for " + user + " from keytab " + 
887                            path, le);
888    } finally {
889      if(oldKeytabFile != null) keytabFile = oldKeytabFile;
890      if(oldKeytabPrincipal != null) keytabPrincipal = oldKeytabPrincipal;
891    }
892  }
893
894  private boolean hasSufficientTimeElapsed(long now) {
895    if (now - user.getLastLogin() < MIN_TIME_BEFORE_RELOGIN ) {
896      LOG.warn("Not attempting to re-login since the last re-login was " +
897          "attempted less than " + (MIN_TIME_BEFORE_RELOGIN/1000) + " seconds"+
898          " before.");
899      return false;
900    }
901    return true;
902  }
903  
904  /**
905   * Did the login happen via keytab
906   * @return true or false
907   */
908  public synchronized static boolean isLoginKeytabBased() throws IOException {
909    return getLoginUser().isKeytab;
910  }
911
912  /**
913   * Create a user from a login name. It is intended to be used for remote
914   * users in RPC, since it won't have any credentials.
915   * @param user the full user principal name, must not be empty or null
916   * @return the UserGroupInformation for the remote user.
917   */
918  public static UserGroupInformation createRemoteUser(String user) {
919    if (user == null || "".equals(user)) {
920      throw new IllegalArgumentException("Null user");
921    }
922    Subject subject = new Subject();
923    subject.getPrincipals().add(new User(user));
924    UserGroupInformation result = new UserGroupInformation(subject);
925    result.setAuthenticationMethod(AuthenticationMethod.SIMPLE);
926    return result;
927  }
928
929  /**
930   * existing types of authentications' methods
931   */
932  @InterfaceStability.Evolving
933  public static enum AuthenticationMethod {
934    SIMPLE,
935    KERBEROS,
936    TOKEN,
937    CERTIFICATE,
938    KERBEROS_SSL,
939    PROXY;
940  }
941
942  /**
943   * Create a proxy user using username of the effective user and the ugi of the
944   * real user.
945   * @param user
946   * @param realUser
947   * @return proxyUser ugi
948   */
949  public static UserGroupInformation createProxyUser(String user,
950      UserGroupInformation realUser) {
951    if (user == null || "".equals(user)) {
952      throw new IllegalArgumentException("Null user");
953    }
954    if (realUser == null) {
955      throw new IllegalArgumentException("Null real user");
956    }
957    Subject subject = new Subject();
958    Set<Principal> principals = subject.getPrincipals();
959    principals.add(new User(user));
960    principals.add(new RealUser(realUser));
961    UserGroupInformation result =new UserGroupInformation(subject);
962    result.setAuthenticationMethod(AuthenticationMethod.PROXY);
963    return result;
964  }
965
966  /**
967   * get RealUser (vs. EffectiveUser)
968   * @return realUser running over proxy user
969   */
970  public UserGroupInformation getRealUser() {
971    for (RealUser p: subject.getPrincipals(RealUser.class)) {
972      return p.getRealUser();
973    }
974    return null;
975  }
976
977
978  
979  /**
980   * This class is used for storing the groups for testing. It stores a local
981   * map that has the translation of usernames to groups.
982   */
983  private static class TestingGroups extends Groups {
984    private final Map<String, List<String>> userToGroupsMapping = 
985      new HashMap<String,List<String>>();
986    private Groups underlyingImplementation;
987    
988    private TestingGroups(Groups underlyingImplementation) {
989      super(new org.apache.hadoop.conf.Configuration());
990      this.underlyingImplementation = underlyingImplementation;
991    }
992    
993    @Override
994    public List<String> getGroups(String user) throws IOException {
995      List<String> result = userToGroupsMapping.get(user);
996      
997      if (result == null) {
998        result = underlyingImplementation.getGroups(user);
999      }
1000
1001      return result;
1002    }
1003
1004    private void setUserGroups(String user, String[] groups) {
1005      userToGroupsMapping.put(user, Arrays.asList(groups));
1006    }
1007  }
1008
1009  /**
1010   * Create a UGI for testing HDFS and MapReduce
1011   * @param user the full user principal name
1012   * @param userGroups the names of the groups that the user belongs to
1013   * @return a fake user for running unit tests
1014   */
1015  @InterfaceAudience.LimitedPrivate({"HDFS", "MapReduce"})
1016  public static UserGroupInformation createUserForTesting(String user, 
1017                                                          String[] userGroups) {
1018    ensureInitialized();
1019    UserGroupInformation ugi = createRemoteUser(user);
1020    // make sure that the testing object is setup
1021    if (!(groups instanceof TestingGroups)) {
1022      groups = new TestingGroups(groups);
1023    }
1024    // add the user groups
1025    ((TestingGroups) groups).setUserGroups(ugi.getShortUserName(), userGroups);
1026    return ugi;
1027  }
1028
1029
1030  /**
1031   * Create a proxy user UGI for testing HDFS and MapReduce
1032   * 
1033   * @param user
1034   *          the full user principal name for effective user
1035   * @param realUser
1036   *          UGI of the real user
1037   * @param userGroups
1038   *          the names of the groups that the user belongs to
1039   * @return a fake user for running unit tests
1040   */
1041  @InterfaceAudience.LimitedPrivate( { "HDFS", "MapReduce" })
1042  public static UserGroupInformation createProxyUserForTesting(String user,
1043      UserGroupInformation realUser, String[] userGroups) {
1044    ensureInitialized();
1045    UserGroupInformation ugi = createProxyUser(user, realUser);
1046    // make sure that the testing object is setup
1047    if (!(groups instanceof TestingGroups)) {
1048      groups = new TestingGroups(groups);
1049    }
1050    // add the user groups
1051    ((TestingGroups) groups).setUserGroups(ugi.getShortUserName(), userGroups);
1052    return ugi;
1053  }
1054  
1055  /**
1056   * Get the user's login name.
1057   * @return the user's name up to the first '/' or '@'.
1058   */
1059  public String getShortUserName() {
1060    for (User p: subject.getPrincipals(User.class)) {
1061      return p.getShortName();
1062    }
1063    return null;
1064  }
1065
1066  /**
1067   * Get the user's full principal name.
1068   * @return the user's full principal name.
1069   */
1070  public String getUserName() {
1071    return user.getName();
1072  }
1073
1074  /**
1075   * Add a TokenIdentifier to this UGI. The TokenIdentifier has typically been
1076   * authenticated by the RPC layer as belonging to the user represented by this
1077   * UGI.
1078   * 
1079   * @param tokenId
1080   *          tokenIdentifier to be added
1081   * @return true on successful add of new tokenIdentifier
1082   */
1083  public synchronized boolean addTokenIdentifier(TokenIdentifier tokenId) {
1084    return subject.getPublicCredentials().add(tokenId);
1085  }
1086
1087  /**
1088   * Get the set of TokenIdentifiers belonging to this UGI
1089   * 
1090   * @return the set of TokenIdentifiers belonging to this UGI
1091   */
1092  public synchronized Set<TokenIdentifier> getTokenIdentifiers() {
1093    return subject.getPublicCredentials(TokenIdentifier.class);
1094  }
1095  
1096  /**
1097   * Add a token to this UGI
1098   * 
1099   * @param token Token to be added
1100   * @return true on successful add of new token
1101   */
1102  public synchronized boolean addToken(Token<? extends TokenIdentifier> token) {
1103    return (token != null) ? addToken(token.getService(), token) : false;
1104  }
1105
1106  /**
1107   * Add a named token to this UGI
1108   * 
1109   * @param alias Name of the token
1110   * @param token Token to be added
1111   * @return true on successful add of new token
1112   */
1113  public synchronized boolean addToken(Text alias,
1114                                       Token<? extends TokenIdentifier> token) {
1115    getCredentialsInternal().addToken(alias, token);
1116    return true;
1117  }
1118  
1119  /**
1120   * Obtain the collection of tokens associated with this user.
1121   * 
1122   * @return an unmodifiable collection of tokens associated with user
1123   */
1124  public synchronized
1125  Collection<Token<? extends TokenIdentifier>> getTokens() {
1126    return Collections.unmodifiableCollection(
1127        getCredentialsInternal().getAllTokens());
1128  }
1129
1130  /**
1131   * Obtain the tokens in credentials form associated with this user.
1132   * 
1133   * @return Credentials of tokens associated with this user
1134   */
1135  public synchronized Credentials getCredentials() {
1136    return new Credentials(getCredentialsInternal());
1137  }
1138  
1139  /**
1140   * Add the given Credentials to this user.
1141   * @param credentials of tokens and secrets
1142   */
1143  public synchronized void addCredentials(Credentials credentials) {
1144    getCredentialsInternal().addAll(credentials);
1145  }
1146
1147  private synchronized Credentials getCredentialsInternal() {
1148    final Credentials credentials;
1149    final Set<Credentials> credentialsSet =
1150      subject.getPrivateCredentials(Credentials.class);
1151    if (!credentialsSet.isEmpty()){
1152      credentials = credentialsSet.iterator().next();
1153    } else {
1154      credentials = new Credentials();
1155      subject.getPrivateCredentials().add(credentials);
1156    }
1157    return credentials;
1158  }
1159
1160  /**
1161   * Get the group names for this user.
1162   * @return the list of users with the primary group first. If the command
1163   *    fails, it returns an empty list.
1164   */
1165  public synchronized String[] getGroupNames() {
1166    ensureInitialized();
1167    try {
1168      List<String> result = groups.getGroups(getShortUserName());
1169      return result.toArray(new String[result.size()]);
1170    } catch (IOException ie) {
1171      LOG.warn("No groups available for user " + getShortUserName());
1172      return new String[0];
1173    }
1174  }
1175  
1176  /**
1177   * Return the username.
1178   */
1179  @Override
1180  public String toString() {
1181    StringBuilder sb = new StringBuilder(getUserName());
1182    sb.append(" (auth:"+getAuthenticationMethod()+")");
1183    if (getRealUser() != null) {
1184      sb.append(" via ").append(getRealUser().toString());
1185    }
1186    return sb.toString();
1187  }
1188
1189  /**
1190   * Sets the authentication method in the subject
1191   * 
1192   * @param authMethod
1193   */
1194  public synchronized 
1195  void setAuthenticationMethod(AuthenticationMethod authMethod) {
1196    user.setAuthenticationMethod(authMethod);
1197  }
1198
1199  /**
1200   * Get the authentication method from the subject
1201   * 
1202   * @return AuthenticationMethod in the subject, null if not present.
1203   */
1204  public synchronized AuthenticationMethod getAuthenticationMethod() {
1205    return user.getAuthenticationMethod();
1206  }
1207  
1208  /**
1209   * Returns the authentication method of a ugi. If the authentication method is
1210   * PROXY, returns the authentication method of the real user.
1211   * 
1212   * @param ugi
1213   * @return AuthenticationMethod
1214   */
1215  public static AuthenticationMethod getRealAuthenticationMethod(
1216      UserGroupInformation ugi) {
1217    AuthenticationMethod authMethod = ugi.getAuthenticationMethod();
1218    if (authMethod == AuthenticationMethod.PROXY) {
1219      authMethod = ugi.getRealUser().getAuthenticationMethod();
1220    }
1221    return authMethod;
1222  }
1223
1224  /**
1225   * Compare the subjects to see if they are equal to each other.
1226   */
1227  @Override
1228  public boolean equals(Object o) {
1229    if (o == this) {
1230      return true;
1231    } else if (o == null || getClass() != o.getClass()) {
1232      return false;
1233    } else {
1234      return subject == ((UserGroupInformation) o).subject;
1235    }
1236  }
1237
1238  /**
1239   * Return the hash of the subject.
1240   */
1241  @Override
1242  public int hashCode() {
1243    return System.identityHashCode(subject);
1244  }
1245
1246  /**
1247   * Get the underlying subject from this ugi.
1248   * @return the subject that represents this user.
1249   */
1250  protected Subject getSubject() {
1251    return subject;
1252  }
1253
1254  /**
1255   * Run the given action as the user.
1256   * @param <T> the return type of the run method
1257   * @param action the method to execute
1258   * @return the value from the run method
1259   */
1260  public <T> T doAs(PrivilegedAction<T> action) {
1261    logPrivilegedAction(subject, action);
1262    return Subject.doAs(subject, action);
1263  }
1264  
1265  /**
1266   * Run the given action as the user, potentially throwing an exception.
1267   * @param <T> the return type of the run method
1268   * @param action the method to execute
1269   * @return the value from the run method
1270   * @throws IOException if the action throws an IOException
1271   * @throws Error if the action throws an Error
1272   * @throws RuntimeException if the action throws a RuntimeException
1273   * @throws InterruptedException if the action throws an InterruptedException
1274   * @throws UndeclaredThrowableException if the action throws something else
1275   */
1276  public <T> T doAs(PrivilegedExceptionAction<T> action
1277                    ) throws IOException, InterruptedException {
1278    try {
1279      logPrivilegedAction(subject, action);
1280      return Subject.doAs(subject, action);
1281    } catch (PrivilegedActionException pae) {
1282      Throwable cause = pae.getCause();
1283      LOG.error("PriviledgedActionException as:"+this+" cause:"+cause);
1284      if (cause instanceof IOException) {
1285        throw (IOException) cause;
1286      } else if (cause instanceof Error) {
1287        throw (Error) cause;
1288      } else if (cause instanceof RuntimeException) {
1289        throw (RuntimeException) cause;
1290      } else if (cause instanceof InterruptedException) {
1291        throw (InterruptedException) cause;
1292      } else {
1293        throw new UndeclaredThrowableException(pae,"Unknown exception in doAs");
1294      }
1295    }
1296  }
1297
1298  private void logPrivilegedAction(Subject subject, Object action) {
1299    if (LOG.isDebugEnabled()) {
1300      // would be nice if action included a descriptive toString()
1301      String where = new Throwable().getStackTrace()[2].toString();
1302      LOG.debug("PrivilegedAction as:"+this+" from:"+where);
1303    }
1304  }
1305
1306  private void print() throws IOException {
1307    System.out.println("User: " + getUserName());
1308    System.out.print("Group Ids: ");
1309    System.out.println();
1310    String[] groups = getGroupNames();
1311    System.out.print("Groups: ");
1312    for(int i=0; i < groups.length; i++) {
1313      System.out.print(groups[i] + " ");
1314    }
1315    System.out.println();    
1316  }
1317
1318  /**
1319   * A test method to print out the current user's UGI.
1320   * @param args if there are two arguments, read the user from the keytab
1321   * and print it out.
1322   * @throws Exception
1323   */
1324  public static void main(String [] args) throws Exception {
1325  System.out.println("Getting UGI for current user");
1326    UserGroupInformation ugi = getCurrentUser();
1327    ugi.print();
1328    System.out.println("UGI: " + ugi);
1329    System.out.println("Auth method " + ugi.user.getAuthenticationMethod());
1330    System.out.println("Keytab " + ugi.isKeytab);
1331    System.out.println("============================================================");
1332    
1333    if (args.length == 2) {
1334      System.out.println("Getting UGI from keytab....");
1335      loginUserFromKeytab(args[0], args[1]);
1336      getCurrentUser().print();
1337      System.out.println("Keytab: " + ugi);
1338      System.out.println("Auth method " + loginUser.user.getAuthenticationMethod());
1339      System.out.println("Keytab " + loginUser.isKeytab);
1340    }
1341  }
1342
1343}