View Javadoc

1   /*
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  
20  package org.apache.hadoop.hbase.security;
21  
22  import java.io.IOException;
23  import java.lang.reflect.UndeclaredThrowableException;
24  import java.security.PrivilegedAction;
25  import java.security.PrivilegedExceptionAction;
26  
27  import org.apache.commons.logging.Log;
28  import org.apache.commons.logging.LogFactory;
29  import org.apache.hadoop.hbase.classification.InterfaceAudience;
30  import org.apache.hadoop.conf.Configuration;
31  import org.apache.hadoop.hbase.util.Methods;
32  import org.apache.hadoop.mapred.JobConf;
33  import org.apache.hadoop.mapreduce.Job;
34  import org.apache.hadoop.security.SecurityUtil;
35  import org.apache.hadoop.security.UserGroupInformation;
36  import org.apache.hadoop.security.token.Token;
37  
38  /**
39   * Wrapper to abstract out usage of user and group information in HBase.
40   *
41   * <p>
42   * This class provides a common interface for interacting with user and group
43   * information across changing APIs in different versions of Hadoop.  It only
44   * provides access to the common set of functionality in
45   * {@link org.apache.hadoop.security.UserGroupInformation} currently needed by
46   * HBase, but can be extended as needs change.
47   * </p>
48   */
49  @InterfaceAudience.Private
50  public abstract class User {
51    public static final String HBASE_SECURITY_CONF_KEY =
52        "hbase.security.authentication";
53  
54    private static Log LOG = LogFactory.getLog(User.class);
55  
56    protected UserGroupInformation ugi;
57  
58    public UserGroupInformation getUGI() {
59      return ugi;
60    }
61  
62    /**
63     * Returns the full user name.  For Kerberos principals this will include
64     * the host and realm portions of the principal name.
65     * @return User full name.
66     */
67    public String getName() {
68      return ugi.getUserName();
69    }
70  
71    /**
72     * Returns the list of groups of which this user is a member.  On secure
73     * Hadoop this returns the group information for the user as resolved on the
74     * server.  For 0.20 based Hadoop, the group names are passed from the client.
75     */
76    public String[] getGroupNames() {
77      return ugi.getGroupNames();
78    }
79  
80    /**
81     * Returns the shortened version of the user name -- the portion that maps
82     * to an operating system user name.
83     * @return Short name
84     */
85    public abstract String getShortName();
86  
87    /**
88     * Executes the given action within the context of this user.
89     */
90    public abstract <T> T runAs(PrivilegedAction<T> action);
91  
92    /**
93     * Executes the given action within the context of this user.
94     */
95    public abstract <T> T runAs(PrivilegedExceptionAction<T> action)
96        throws IOException, InterruptedException;
97  
98    /**
99     * Requests an authentication token for this user and stores it in the
100    * user's credentials.
101    *
102    * @throws IOException
103    */
104   public abstract void obtainAuthTokenForJob(Configuration conf, Job job)
105       throws IOException, InterruptedException;
106 
107   /**
108    * Requests an authentication token for this user and stores it in the
109    * user's credentials.
110    *
111    * @throws IOException
112    */
113   public abstract void obtainAuthTokenForJob(JobConf job)
114       throws IOException, InterruptedException;
115 
116   /**
117    * Returns the Token of the specified kind associated with this user,
118    * or null if the Token is not present.
119    *
120    * @param kind the kind of token
121    * @param service service on which the token is supposed to be used
122    * @return the token of the specified kind.
123    */
124   public Token<?> getToken(String kind, String service) throws IOException {
125     for (Token<?> token: ugi.getTokens()) {
126       if (token.getKind().toString().equals(kind) &&
127           (service != null && token.getService().toString().equals(service)))
128       {
129         return token;
130       }
131     }
132     return null;
133   }
134 
135   @Override
136   public boolean equals(Object o) {
137     if (this == o) {
138       return true;
139     }
140     if (o == null || getClass() != o.getClass()) {
141       return false;
142     }
143     return ugi.equals(((User) o).ugi);
144   }
145 
146   @Override
147   public int hashCode() {
148     return ugi.hashCode();
149   }
150 
151   @Override
152   public String toString() {
153     return ugi.toString();
154   }
155 
156   /**
157    * Returns the {@code User} instance within current execution context.
158    */
159   public static User getCurrent() throws IOException {
160     User user = new SecureHadoopUser();
161     if (user.getUGI() == null) {
162       return null;
163     }
164     return user;
165   }
166 
167   /**
168    * Executes the given action as the login user
169    * @param action
170    * @return
171    * @throws IOException
172    * @throws InterruptedException
173    */
174   @SuppressWarnings({ "rawtypes", "unchecked" })
175   public static <T> T runAsLoginUser(PrivilegedExceptionAction<T> action) throws IOException {
176     return doAsUser(UserGroupInformation.getCurrentUser(), action);
177   }
178 
179   private static <T> T doAsUser(UserGroupInformation ugi,
180       PrivilegedExceptionAction<T> action) throws IOException {
181     try {
182       return ugi.doAs(action);
183     } catch (InterruptedException ie) {
184       throw new IOException(ie);
185     }
186   }
187 
188   /**
189    * Wraps an underlying {@code UserGroupInformation} instance.
190    * @param ugi The base Hadoop user
191    * @return User
192    */
193   public static User create(UserGroupInformation ugi) {
194     if (ugi == null) {
195       return null;
196     }
197     return new SecureHadoopUser(ugi);
198   }
199 
200   /**
201    * Generates a new {@code User} instance specifically for use in test code.
202    * @param name the full username
203    * @param groups the group names to which the test user will belong
204    * @return a new <code>User</code> instance
205    */
206   public static User createUserForTesting(Configuration conf,
207       String name, String[] groups) {
208     return SecureHadoopUser.createUserForTesting(conf, name, groups);
209   }
210 
211   /**
212    * Log in the current process using the given configuration keys for the
213    * credential file and login principal.
214    *
215    * <p><strong>This is only applicable when
216    * running on secure Hadoop</strong> -- see
217    * org.apache.hadoop.security.SecurityUtil#login(Configuration,String,String,String).
218    * On regular Hadoop (without security features), this will safely be ignored.
219    * </p>
220    *
221    * @param conf The configuration data to use
222    * @param fileConfKey Property key used to configure path to the credential file
223    * @param principalConfKey Property key used to configure login principal
224    * @param localhost Current hostname to use in any credentials
225    * @throws IOException underlying exception from SecurityUtil.login() call
226    */
227   public static void login(Configuration conf, String fileConfKey,
228       String principalConfKey, String localhost) throws IOException {
229     SecureHadoopUser.login(conf, fileConfKey, principalConfKey, localhost);
230   }
231 
232   /**
233    * Returns whether or not Kerberos authentication is configured for Hadoop.
234    * For non-secure Hadoop, this always returns <code>false</code>.
235    * For secure Hadoop, it will return the value from
236    * {@code UserGroupInformation.isSecurityEnabled()}.
237    */
238   public static boolean isSecurityEnabled() {
239     return SecureHadoopUser.isSecurityEnabled();
240   }
241 
242   /**
243    * Returns whether or not secure authentication is enabled for HBase. Note that
244    * HBase security requires HDFS security to provide any guarantees, so it is
245    * recommended that secure HBase should run on secure HDFS.
246    */
247   public static boolean isHBaseSecurityEnabled(Configuration conf) {
248     return "kerberos".equalsIgnoreCase(conf.get(HBASE_SECURITY_CONF_KEY));
249   }
250 
251   /* Concrete implementations */
252 
253   /**
254    * Bridges {@code User} invocations to underlying calls to
255    * {@link org.apache.hadoop.security.UserGroupInformation} for secure Hadoop
256    * 0.20 and versions 0.21 and above.
257    */
258   private static class SecureHadoopUser extends User {
259     private String shortName;
260 
261     private SecureHadoopUser() throws IOException {
262       ugi = UserGroupInformation.getCurrentUser();
263     }
264 
265     private SecureHadoopUser(UserGroupInformation ugi) {
266       this.ugi = ugi;
267     }
268 
269     @Override
270     public String getShortName() {
271       if (shortName != null) return shortName;
272       try {
273         shortName = ugi.getShortUserName();
274         return shortName;
275       } catch (Exception e) {
276         throw new RuntimeException("Unexpected error getting user short name",
277           e);
278       }
279     }
280 
281     @Override
282     public <T> T runAs(PrivilegedAction<T> action) {
283       return ugi.doAs(action);
284     }
285 
286     @Override
287     public <T> T runAs(PrivilegedExceptionAction<T> action)
288         throws IOException, InterruptedException {
289       return ugi.doAs(action);
290     }
291 
292     @Override
293     public void obtainAuthTokenForJob(Configuration conf, Job job)
294         throws IOException, InterruptedException {
295       try {
296         Class<?> c = Class.forName(
297             "org.apache.hadoop.hbase.security.token.TokenUtil");
298         Methods.call(c, null, "obtainTokenForJob",
299             new Class[]{Configuration.class, UserGroupInformation.class,
300                 Job.class},
301             new Object[]{conf, ugi, job});
302       } catch (ClassNotFoundException cnfe) {
303         throw new RuntimeException("Failure loading TokenUtil class, "
304             +"is secure RPC available?", cnfe);
305       } catch (IOException ioe) {
306         throw ioe;
307       } catch (InterruptedException ie) {
308         throw ie;
309       } catch (RuntimeException re) {
310         throw re;
311       } catch (Exception e) {
312         throw new UndeclaredThrowableException(e,
313             "Unexpected error calling TokenUtil.obtainAndCacheToken()");
314       }
315     }
316 
317     @Override
318     public void obtainAuthTokenForJob(JobConf job)
319         throws IOException, InterruptedException {
320       try {
321         Class<?> c = Class.forName(
322             "org.apache.hadoop.hbase.security.token.TokenUtil");
323         Methods.call(c, null, "obtainTokenForJob",
324             new Class[]{JobConf.class, UserGroupInformation.class},
325             new Object[]{job, ugi});
326       } catch (ClassNotFoundException cnfe) {
327         throw new RuntimeException("Failure loading TokenUtil class, "
328             +"is secure RPC available?", cnfe);
329       } catch (IOException ioe) {
330         throw ioe;
331       } catch (InterruptedException ie) {
332         throw ie;
333       } catch (RuntimeException re) {
334         throw re;
335       } catch (Exception e) {
336         throw new UndeclaredThrowableException(e,
337             "Unexpected error calling TokenUtil.obtainAndCacheToken()");
338       }
339     }
340 
341     /** @see User#createUserForTesting(org.apache.hadoop.conf.Configuration, String, String[]) */
342     public static User createUserForTesting(Configuration conf,
343         String name, String[] groups) {
344       return new SecureHadoopUser(UserGroupInformation.createUserForTesting(name, groups));
345     }
346 
347     /**
348      * Obtain credentials for the current process using the configured
349      * Kerberos keytab file and principal.
350      * @see User#login(org.apache.hadoop.conf.Configuration, String, String, String)
351      *
352      * @param conf the Configuration to use
353      * @param fileConfKey Configuration property key used to store the path
354      * to the keytab file
355      * @param principalConfKey Configuration property key used to store the
356      * principal name to login as
357      * @param localhost the local hostname
358      */
359     public static void login(Configuration conf, String fileConfKey,
360         String principalConfKey, String localhost) throws IOException {
361       if (isSecurityEnabled()) {
362         SecurityUtil.login(conf, fileConfKey, principalConfKey, localhost);
363       }
364     }
365 
366     /**
367      * Returns the result of {@code UserGroupInformation.isSecurityEnabled()}.
368      */
369     public static boolean isSecurityEnabled() {
370       return UserGroupInformation.isSecurityEnabled();
371     }
372   }
373 }