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 */
018
019package org.apache.hadoop.security.token;
020
021import com.google.common.collect.Maps;
022import com.google.protobuf.ByteString;
023import com.google.common.primitives.Bytes;
024
025import org.apache.commons.codec.binary.Base64;
026import org.apache.commons.logging.Log;
027import org.apache.commons.logging.LogFactory;
028import org.apache.hadoop.classification.InterfaceAudience;
029import org.apache.hadoop.classification.InterfaceStability;
030import org.apache.hadoop.conf.Configuration;
031import org.apache.hadoop.io.*;
032import org.apache.hadoop.security.proto.SecurityProtos.TokenProto;
033import org.apache.hadoop.util.ReflectionUtils;
034
035import java.io.*;
036import java.util.Arrays;
037import java.util.Map;
038import java.util.ServiceLoader;
039import java.util.UUID;
040
041/**
042 * The client-side form of the token.
043 */
044@InterfaceAudience.Public
045@InterfaceStability.Evolving
046public class Token<T extends TokenIdentifier> implements Writable {
047  public static final Log LOG = LogFactory.getLog(Token.class);
048
049  private static Map<Text, Class<? extends TokenIdentifier>> tokenKindMap;
050
051  private byte[] identifier;
052  private byte[] password;
053  private Text kind;
054  private Text service;
055  private TokenRenewer renewer;
056
057  /**
058   * Construct a token given a token identifier and a secret manager for the
059   * type of the token identifier.
060   * @param id the token identifier
061   * @param mgr the secret manager
062   */
063  public Token(T id, SecretManager<T> mgr) {
064    password = mgr.createPassword(id);
065    identifier = id.getBytes();
066    kind = id.getKind();
067    service = new Text();
068  }
069
070  /**
071   * Construct a token from the components.
072   * @param identifier the token identifier
073   * @param password the token's password
074   * @param kind the kind of token
075   * @param service the service for this token
076   */
077  public Token(byte[] identifier, byte[] password, Text kind, Text service) {
078    this.identifier = (identifier == null)? new byte[0] : identifier;
079    this.password = (password == null)? new byte[0] : password;
080    this.kind = (kind == null)? new Text() : kind;
081    this.service = (service == null)? new Text() : service;
082  }
083
084  /**
085   * Default constructor.
086   */
087  public Token() {
088    identifier = new byte[0];
089    password = new byte[0];
090    kind = new Text();
091    service = new Text();
092  }
093
094  /**
095   * Clone a token.
096   * @param other the token to clone
097   */
098  public Token(Token<T> other) {
099    this.identifier = other.identifier;
100    this.password = other.password;
101    this.kind = other.kind;
102    this.service = other.service;
103  }
104
105  public Token<T> copyToken() {
106    return new Token<T>(this);
107  }
108
109  /**
110   * Construct a Token from a TokenProto.
111   * @param tokenPB the TokenProto object
112   */
113  public Token(TokenProto tokenPB) {
114    this.identifier = tokenPB.getIdentifier().toByteArray();
115    this.password = tokenPB.getPassword().toByteArray();
116    this.kind = new Text(tokenPB.getKindBytes().toByteArray());
117    this.service = new Text(tokenPB.getServiceBytes().toByteArray());
118  }
119
120  /**
121   * Construct a TokenProto from this Token instance.
122   * @return a new TokenProto object holding copies of data in this instance
123   */
124  public TokenProto toTokenProto() {
125    return TokenProto.newBuilder().
126        setIdentifier(ByteString.copyFrom(this.getIdentifier())).
127        setPassword(ByteString.copyFrom(this.getPassword())).
128        setKindBytes(ByteString.copyFrom(
129            this.getKind().getBytes(), 0, this.getKind().getLength())).
130        setServiceBytes(ByteString.copyFrom(
131            this.getService().getBytes(), 0, this.getService().getLength())).
132        build();
133  }
134
135  /**
136   * Get the token identifier's byte representation.
137   * @return the token identifier's byte representation
138   */
139  public byte[] getIdentifier() {
140    return identifier;
141  }
142
143  private static Class<? extends TokenIdentifier>
144      getClassForIdentifier(Text kind) {
145    Class<? extends TokenIdentifier> cls = null;
146    synchronized (Token.class) {
147      if (tokenKindMap == null) {
148        tokenKindMap = Maps.newHashMap();
149        for (TokenIdentifier id : ServiceLoader.load(TokenIdentifier.class)) {
150          tokenKindMap.put(id.getKind(), id.getClass());
151        }
152      }
153      cls = tokenKindMap.get(kind);
154    }
155    if (cls == null) {
156      LOG.debug("Cannot find class for token kind " + kind);
157      return null;
158    }
159    return cls;
160  }
161
162  /**
163   * Get the token identifier object, or null if it could not be constructed
164   * (because the class could not be loaded, for example).
165   * @return the token identifier, or null
166   * @throws IOException
167   */
168  @SuppressWarnings("unchecked")
169  public T decodeIdentifier() throws IOException {
170    Class<? extends TokenIdentifier> cls = getClassForIdentifier(getKind());
171    if (cls == null) {
172      return null;
173    }
174    TokenIdentifier tokenIdentifier = ReflectionUtils.newInstance(cls, null);
175    ByteArrayInputStream buf = new ByteArrayInputStream(identifier);
176    DataInputStream in = new DataInputStream(buf);
177    tokenIdentifier.readFields(in);
178    in.close();
179    return (T) tokenIdentifier;
180  }
181
182  /**
183   * Get the token password/secret.
184   * @return the token password/secret
185   */
186  public byte[] getPassword() {
187    return password;
188  }
189
190  /**
191   * Get the token kind.
192   * @return the kind of the token
193   */
194  public synchronized Text getKind() {
195    return kind;
196  }
197
198  /**
199   * Set the token kind. This is only intended to be used by services that
200   * wrap another service's token.
201   * @param newKind
202   */
203  @InterfaceAudience.Private
204  public synchronized void setKind(Text newKind) {
205    kind = newKind;
206    renewer = null;
207  }
208
209  /**
210   * Get the service on which the token is supposed to be used.
211   * @return the service name
212   */
213  public Text getService() {
214    return service;
215  }
216
217  /**
218   * Set the service on which the token is supposed to be used.
219   * @param newService the service name
220   */
221  public void setService(Text newService) {
222    service = newService;
223  }
224
225  /**
226   * Indicates whether the token is a clone.  Used by HA failover proxy
227   * to indicate a token should not be visible to the user via
228   * UGI.getCredentials()
229   */
230  @InterfaceAudience.Private
231  @InterfaceStability.Unstable
232  public static class PrivateToken<T extends TokenIdentifier> extends Token<T> {
233    public PrivateToken(Token<T> token) {
234      super(token);
235    }
236  }
237
238  @Override
239  public void readFields(DataInput in) throws IOException {
240    int len = WritableUtils.readVInt(in);
241    if (identifier == null || identifier.length != len) {
242      identifier = new byte[len];
243    }
244    in.readFully(identifier);
245    len = WritableUtils.readVInt(in);
246    if (password == null || password.length != len) {
247      password = new byte[len];
248    }
249    in.readFully(password);
250    kind.readFields(in);
251    service.readFields(in);
252  }
253
254  @Override
255  public void write(DataOutput out) throws IOException {
256    WritableUtils.writeVInt(out, identifier.length);
257    out.write(identifier);
258    WritableUtils.writeVInt(out, password.length);
259    out.write(password);
260    kind.write(out);
261    service.write(out);
262  }
263
264  /**
265   * Generate a string with the url-quoted base64 encoded serialized form
266   * of the Writable.
267   * @param obj the object to serialize
268   * @return the encoded string
269   * @throws IOException
270   */
271  private static String encodeWritable(Writable obj) throws IOException {
272    DataOutputBuffer buf = new DataOutputBuffer();
273    obj.write(buf);
274    Base64 encoder = new Base64(0, null, true);
275    byte[] raw = new byte[buf.getLength()];
276    System.arraycopy(buf.getData(), 0, raw, 0, buf.getLength());
277    return encoder.encodeToString(raw);
278  }
279
280  /**
281   * Modify the writable to the value from the newValue.
282   * @param obj the object to read into
283   * @param newValue the string with the url-safe base64 encoded bytes
284   * @throws IOException
285   */
286  private static void decodeWritable(Writable obj,
287                                     String newValue) throws IOException {
288    Base64 decoder = new Base64(0, null, true);
289    DataInputBuffer buf = new DataInputBuffer();
290    byte[] decoded = decoder.decode(newValue);
291    buf.reset(decoded, decoded.length);
292    obj.readFields(buf);
293  }
294
295  /**
296   * Encode this token as a url safe string.
297   * @return the encoded string
298   * @throws IOException
299   */
300  public String encodeToUrlString() throws IOException {
301    return encodeWritable(this);
302  }
303
304  /**
305   * Decode the given url safe string into this token.
306   * @param newValue the encoded string
307   * @throws IOException
308   */
309  public void decodeFromUrlString(String newValue) throws IOException {
310    decodeWritable(this, newValue);
311  }
312
313  @SuppressWarnings("unchecked")
314  @Override
315  public boolean equals(Object right) {
316    if (this == right) {
317      return true;
318    } else if (right == null || getClass() != right.getClass()) {
319      return false;
320    } else {
321      Token<T> r = (Token<T>) right;
322      return Arrays.equals(identifier, r.identifier) &&
323             Arrays.equals(password, r.password) &&
324             kind.equals(r.kind) &&
325             service.equals(r.service);
326    }
327  }
328
329  @Override
330  public int hashCode() {
331    return WritableComparator.hashBytes(identifier, identifier.length);
332  }
333
334  private static void addBinaryBuffer(StringBuilder buffer, byte[] bytes) {
335    for (int idx = 0; idx < bytes.length; idx++) {
336      // if not the first, put a blank separator in
337      if (idx != 0) {
338        buffer.append(' ');
339      }
340      String num = Integer.toHexString(0xff & bytes[idx]);
341      // if it is only one digit, add a leading 0.
342      if (num.length() < 2) {
343        buffer.append('0');
344      }
345      buffer.append(num);
346    }
347  }
348
349  private void identifierToString(StringBuilder buffer) {
350    T id = null;
351    try {
352      id = decodeIdentifier();
353    } catch (IOException e) {
354      // handle in the finally block
355    } finally {
356      if (id != null) {
357        buffer.append("(").append(id).append(")");
358      } else {
359        addBinaryBuffer(buffer, identifier);
360      }
361    }
362  }
363
364  @Override
365  public String toString() {
366    StringBuilder buffer = new StringBuilder();
367    buffer.append("Kind: ");
368    buffer.append(kind.toString());
369    buffer.append(", Service: ");
370    buffer.append(service.toString());
371    buffer.append(", Ident: ");
372    identifierToString(buffer);
373    return buffer.toString();
374  }
375
376  public String buildCacheKey() {
377    return UUID.nameUUIDFromBytes(
378        Bytes.concat(kind.getBytes(), identifier, password)).toString();
379  }
380
381  private static ServiceLoader<TokenRenewer> renewers =
382      ServiceLoader.load(TokenRenewer.class);
383
384  private synchronized TokenRenewer getRenewer() throws IOException {
385    if (renewer != null) {
386      return renewer;
387    }
388    renewer = TRIVIAL_RENEWER;
389    synchronized (renewers) {
390      for (TokenRenewer canidate : renewers) {
391        if (canidate.handleKind(this.kind)) {
392          renewer = canidate;
393          return renewer;
394        }
395      }
396    }
397    LOG.warn("No TokenRenewer defined for token kind " + this.kind);
398    return renewer;
399  }
400
401  /**
402   * Is this token managed so that it can be renewed or cancelled?
403   * @return true, if it can be renewed and cancelled.
404   */
405  public boolean isManaged() throws IOException {
406    return getRenewer().isManaged(this);
407  }
408
409  /**
410   * Renew this delegation token.
411   * @return the new expiration time
412   * @throws IOException
413   * @throws InterruptedException
414   */
415  public long renew(Configuration conf
416                    ) throws IOException, InterruptedException {
417    return getRenewer().renew(this, conf);
418  }
419
420  /**
421   * Cancel this delegation token.
422   * @throws IOException
423   * @throws InterruptedException
424   */
425  public void cancel(Configuration conf
426                     ) throws IOException, InterruptedException {
427    getRenewer().cancel(this, conf);
428  }
429
430  /**
431   * A trivial renewer for token kinds that aren't managed. Sub-classes need
432   * to implement getKind for their token kind.
433   */
434  @InterfaceAudience.LimitedPrivate({"HDFS", "MapReduce"})
435  @InterfaceStability.Evolving
436  public static class TrivialRenewer extends TokenRenewer {
437
438    // define the kind for this renewer
439    protected Text getKind() {
440      return null;
441    }
442
443    @Override
444    public boolean handleKind(Text kind) {
445      return kind.equals(getKind());
446    }
447
448    @Override
449    public boolean isManaged(Token<?> token) {
450      return false;
451    }
452
453    @Override
454    public long renew(Token<?> token, Configuration conf) {
455      throw new UnsupportedOperationException("Token renewal is not supported "+
456                                              " for " + token.kind + " tokens");
457    }
458
459    @Override
460    public void cancel(Token<?> token, Configuration conf) throws IOException,
461        InterruptedException {
462      throw new UnsupportedOperationException("Token cancel is not supported " +
463          " for " + token.kind + " tokens");
464    }
465
466  }
467  private static final TokenRenewer TRIVIAL_RENEWER = new TrivialRenewer();
468}