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.crypto.key;
020
021import com.google.common.base.Preconditions;
022import org.apache.commons.io.IOUtils;
023import org.apache.hadoop.classification.InterfaceAudience;
024import org.apache.hadoop.conf.Configuration;
025import org.apache.hadoop.fs.FSDataOutputStream;
026import org.apache.hadoop.fs.FileStatus;
027import org.apache.hadoop.fs.FileSystem;
028import org.apache.hadoop.fs.Path;
029import org.apache.hadoop.fs.permission.FsPermission;
030import org.apache.hadoop.security.ProviderUtils;
031import org.slf4j.Logger;
032import org.slf4j.LoggerFactory;
033
034import com.google.common.annotations.VisibleForTesting;
035
036import javax.crypto.spec.SecretKeySpec;
037
038import java.io.IOException;
039import java.io.InputStream;
040import java.io.ObjectInputStream;
041import java.io.ObjectOutputStream;
042import java.io.Serializable;
043import java.net.URI;
044import java.net.URL;
045import java.security.Key;
046import java.security.KeyStore;
047import java.security.KeyStoreException;
048import java.security.NoSuchAlgorithmException;
049import java.security.UnrecoverableKeyException;
050import java.security.cert.CertificateException;
051import java.util.ArrayList;
052import java.util.Date;
053import java.util.Enumeration;
054import java.util.HashMap;
055import java.util.List;
056import java.util.Map;
057import java.util.concurrent.locks.Lock;
058import java.util.concurrent.locks.ReadWriteLock;
059import java.util.concurrent.locks.ReentrantReadWriteLock;
060
061/**
062 * KeyProvider based on Java's KeyStore file format. The file may be stored in
063 * any Hadoop FileSystem using the following name mangling:
064 *  jks://hdfs@nn1.example.com/my/keys.jks -> hdfs://nn1.example.com/my/keys.jks
065 *  jks://file/home/owen/keys.jks -> file:///home/owen/keys.jks
066 * <p/>
067 * If the <code>HADOOP_KEYSTORE_PASSWORD</code> environment variable is set,
068 * its value is used as the password for the keystore.
069 * <p/>
070 * If the <code>HADOOP_KEYSTORE_PASSWORD</code> environment variable is not set,
071 * the password for the keystore is read from file specified in the
072 * {@link #KEYSTORE_PASSWORD_FILE_KEY} configuration property. The password file
073 * is looked up in Hadoop's configuration directory via the classpath.
074 * <p/>
075 * <b>NOTE:</b> Make sure the password in the password file does not have an
076 * ENTER at the end, else it won't be valid for the Java KeyStore.
077 * <p/>
078 * If the environment variable, nor the property are not set, the password used
079 * is 'none'.
080 * <p/>
081 * It is expected for encrypted InputFormats and OutputFormats to copy the keys
082 * from the original provider into the job's Credentials object, which is
083 * accessed via the UserProvider. Therefore, this provider won't be used by
084 * MapReduce tasks.
085 */
086@InterfaceAudience.Private
087public class JavaKeyStoreProvider extends KeyProvider {
088  private static final String KEY_METADATA = "KeyMetadata";
089  private static Logger LOG =
090      LoggerFactory.getLogger(JavaKeyStoreProvider.class);
091
092  public static final String SCHEME_NAME = "jceks";
093
094  public static final String KEYSTORE_PASSWORD_FILE_KEY =
095      "hadoop.security.keystore.java-keystore-provider.password-file";
096
097  public static final String KEYSTORE_PASSWORD_ENV_VAR =
098      "HADOOP_KEYSTORE_PASSWORD";
099  public static final char[] KEYSTORE_PASSWORD_DEFAULT = "none".toCharArray();
100
101  private final URI uri;
102  private final Path path;
103  private final FileSystem fs;
104  private final FsPermission permissions;
105  private final KeyStore keyStore;
106  private char[] password;
107  private boolean changed = false;
108  private Lock readLock;
109  private Lock writeLock;
110
111  private final Map<String, Metadata> cache = new HashMap<String, Metadata>();
112
113  @VisibleForTesting
114  JavaKeyStoreProvider(JavaKeyStoreProvider other) {
115    super(new Configuration());
116    uri = other.uri;
117    path = other.path;
118    fs = other.fs;
119    permissions = other.permissions;
120    keyStore = other.keyStore;
121    password = other.password;
122    changed = other.changed;
123    readLock = other.readLock;
124    writeLock = other.writeLock;
125  }
126
127  private JavaKeyStoreProvider(URI uri, Configuration conf) throws IOException {
128    super(conf);
129    this.uri = uri;
130    path = ProviderUtils.unnestUri(uri);
131    fs = path.getFileSystem(conf);
132    // Get the password file from the conf, if not present from the user's
133    // environment var
134    if (System.getenv().containsKey(KEYSTORE_PASSWORD_ENV_VAR)) {
135      password = System.getenv(KEYSTORE_PASSWORD_ENV_VAR).toCharArray();
136    }
137    if (password == null) {
138      String pwFile = conf.get(KEYSTORE_PASSWORD_FILE_KEY);
139      if (pwFile != null) {
140        ClassLoader cl = Thread.currentThread().getContextClassLoader();
141        URL pwdFile = cl.getResource(pwFile);
142        if (pwdFile == null) {
143          // Provided Password file does not exist
144          throw new IOException("Password file does not exists");
145        }
146        if (pwdFile != null) {
147          InputStream is = pwdFile.openStream();
148          try {
149            password = IOUtils.toString(is).trim().toCharArray();
150          } finally {
151            is.close();
152          }
153        }
154      }
155    }
156    if (password == null) {
157      password = KEYSTORE_PASSWORD_DEFAULT;
158    }
159    try {
160      Path oldPath = constructOldPath(path);
161      Path newPath = constructNewPath(path);
162      keyStore = KeyStore.getInstance(SCHEME_NAME);
163      FsPermission perm = null;
164      if (fs.exists(path)) {
165        // flush did not proceed to completion
166        // _NEW should not exist
167        if (fs.exists(newPath)) {
168          throw new IOException(
169              String.format("Keystore not loaded due to some inconsistency "
170              + "('%s' and '%s' should not exist together)!!", path, newPath));
171        }
172        perm = tryLoadFromPath(path, oldPath);
173      } else {
174        perm = tryLoadIncompleteFlush(oldPath, newPath);
175      }
176      // Need to save off permissions in case we need to
177      // rewrite the keystore in flush()
178      permissions = perm;
179    } catch (KeyStoreException e) {
180      throw new IOException("Can't create keystore", e);
181    } catch (NoSuchAlgorithmException e) {
182      throw new IOException("Can't load keystore " + path, e);
183    } catch (CertificateException e) {
184      throw new IOException("Can't load keystore " + path, e);
185    }
186    ReadWriteLock lock = new ReentrantReadWriteLock(true);
187    readLock = lock.readLock();
188    writeLock = lock.writeLock();
189  }
190
191  /**
192   * Try loading from the user specified path, else load from the backup
193   * path in case Exception is not due to bad/wrong password
194   * @param path Actual path to load from
195   * @param backupPath Backup path (_OLD)
196   * @return The permissions of the loaded file
197   * @throws NoSuchAlgorithmException
198   * @throws CertificateException
199   * @throws IOException
200   */
201  private FsPermission tryLoadFromPath(Path path, Path backupPath)
202      throws NoSuchAlgorithmException, CertificateException,
203      IOException {
204    FsPermission perm = null;
205    try {
206      perm = loadFromPath(path, password);
207      // Remove _OLD if exists
208      if (fs.exists(backupPath)) {
209        fs.delete(backupPath, true);
210      }
211      LOG.debug("KeyStore loaded successfully !!");
212    } catch (IOException ioe) {
213      // If file is corrupted for some reason other than
214      // wrong password try the _OLD file if exits
215      if (!isBadorWrongPassword(ioe)) {
216        perm = loadFromPath(backupPath, password);
217        // Rename CURRENT to CORRUPTED
218        renameOrFail(path, new Path(path.toString() + "_CORRUPTED_"
219            + System.currentTimeMillis()));
220        renameOrFail(backupPath, path);
221        LOG.debug(String.format(
222            "KeyStore loaded successfully from '%s' since '%s'"
223                + "was corrupted !!", backupPath, path));
224      } else {
225        throw ioe;
226      }
227    }
228    return perm;
229  }
230
231  /**
232   * The KeyStore might have gone down during a flush, In which case either the
233   * _NEW or _OLD files might exists. This method tries to load the KeyStore
234   * from one of these intermediate files.
235   * @param oldPath the _OLD file created during flush
236   * @param newPath the _NEW file created during flush
237   * @return The permissions of the loaded file
238   * @throws IOException
239   * @throws NoSuchAlgorithmException
240   * @throws CertificateException
241   */
242  private FsPermission tryLoadIncompleteFlush(Path oldPath, Path newPath)
243      throws IOException, NoSuchAlgorithmException, CertificateException {
244    FsPermission perm = null;
245    // Check if _NEW exists (in case flush had finished writing but not
246    // completed the re-naming)
247    if (fs.exists(newPath)) {
248      perm = loadAndReturnPerm(newPath, oldPath);
249    }
250    // try loading from _OLD (An earlier Flushing MIGHT not have completed
251    // writing completely)
252    if ((perm == null) && fs.exists(oldPath)) {
253      perm = loadAndReturnPerm(oldPath, newPath);
254    }
255    // If not loaded yet,
256    // required to create an empty keystore. *sigh*
257    if (perm == null) {
258      keyStore.load(null, password);
259      LOG.debug("KeyStore initialized anew successfully !!");
260      perm = new FsPermission("700");
261    }
262    return perm;
263  }
264
265  private FsPermission loadAndReturnPerm(Path pathToLoad, Path pathToDelete)
266      throws NoSuchAlgorithmException, CertificateException,
267      IOException {
268    FsPermission perm = null;
269    try {
270      perm = loadFromPath(pathToLoad, password);
271      renameOrFail(pathToLoad, path);
272      LOG.debug(String.format("KeyStore loaded successfully from '%s'!!",
273          pathToLoad));
274      if (fs.exists(pathToDelete)) {
275        fs.delete(pathToDelete, true);
276      }
277    } catch (IOException e) {
278      // Check for password issue : don't want to trash file due
279      // to wrong password
280      if (isBadorWrongPassword(e)) {
281        throw e;
282      }
283    }
284    return perm;
285  }
286
287  private boolean isBadorWrongPassword(IOException ioe) {
288    // As per documentation this is supposed to be the way to figure
289    // if password was correct
290    if (ioe.getCause() instanceof UnrecoverableKeyException) {
291      return true;
292    }
293    // Unfortunately that doesn't seem to work..
294    // Workaround :
295    if ((ioe.getCause() == null)
296        && (ioe.getMessage() != null)
297        && ((ioe.getMessage().contains("Keystore was tampered")) || (ioe
298            .getMessage().contains("password was incorrect")))) {
299      return true;
300    }
301    return false;
302  }
303
304  private FsPermission loadFromPath(Path p, char[] password)
305      throws IOException, NoSuchAlgorithmException, CertificateException {
306    FileStatus s = fs.getFileStatus(p);
307    keyStore.load(fs.open(p), password);
308    return s.getPermission();
309  }
310
311  private Path constructNewPath(Path path) {
312    Path newPath = new Path(path.toString() + "_NEW");
313    return newPath;
314  }
315
316  private Path constructOldPath(Path path) {
317    Path oldPath = new Path(path.toString() + "_OLD");
318    return oldPath;
319  }
320
321  @Override
322  public KeyVersion getKeyVersion(String versionName) throws IOException {
323    readLock.lock();
324    try {
325      SecretKeySpec key = null;
326      try {
327        if (!keyStore.containsAlias(versionName)) {
328          return null;
329        }
330        key = (SecretKeySpec) keyStore.getKey(versionName, password);
331      } catch (KeyStoreException e) {
332        throw new IOException("Can't get key " + versionName + " from " +
333                              path, e);
334      } catch (NoSuchAlgorithmException e) {
335        throw new IOException("Can't get algorithm for key " + key + " from " +
336                              path, e);
337      } catch (UnrecoverableKeyException e) {
338        throw new IOException("Can't recover key " + key + " from " + path, e);
339      }
340      return new KeyVersion(getBaseName(versionName), versionName, key.getEncoded());
341    } finally {
342      readLock.unlock();
343    }
344  }
345
346  @Override
347  public List<String> getKeys() throws IOException {
348    readLock.lock();
349    try {
350      ArrayList<String> list = new ArrayList<String>();
351      String alias = null;
352      try {
353        Enumeration<String> e = keyStore.aliases();
354        while (e.hasMoreElements()) {
355           alias = e.nextElement();
356           // only include the metadata key names in the list of names
357           if (!alias.contains("@")) {
358               list.add(alias);
359           }
360        }
361      } catch (KeyStoreException e) {
362        throw new IOException("Can't get key " + alias + " from " + path, e);
363      }
364      return list;
365    } finally {
366      readLock.unlock();
367    }
368  }
369
370  @Override
371  public List<KeyVersion> getKeyVersions(String name) throws IOException {
372    readLock.lock();
373    try {
374      List<KeyVersion> list = new ArrayList<KeyVersion>();
375      Metadata km = getMetadata(name);
376      if (km != null) {
377        int latestVersion = km.getVersions();
378        KeyVersion v = null;
379        String versionName = null;
380        for (int i = 0; i < latestVersion; i++) {
381          versionName = buildVersionName(name, i);
382          v = getKeyVersion(versionName);
383          if (v != null) {
384            list.add(v);
385          }
386        }
387      }
388      return list;
389    } finally {
390      readLock.unlock();
391    }
392  }
393
394  @Override
395  public Metadata getMetadata(String name) throws IOException {
396    readLock.lock();
397    try {
398      if (cache.containsKey(name)) {
399        return cache.get(name);
400      }
401      try {
402        if (!keyStore.containsAlias(name)) {
403          return null;
404        }
405        Metadata meta = ((KeyMetadata) keyStore.getKey(name, password)).metadata;
406        cache.put(name, meta);
407        return meta;
408      } catch (ClassCastException e) {
409        throw new IOException("Can't cast key for " + name + " in keystore " +
410            path + " to a KeyMetadata. Key may have been added using " +
411            " keytool or some other non-Hadoop method.", e);
412      } catch (KeyStoreException e) {
413        throw new IOException("Can't get metadata for " + name +
414            " from keystore " + path, e);
415      } catch (NoSuchAlgorithmException e) {
416        throw new IOException("Can't get algorithm for " + name +
417            " from keystore " + path, e);
418      } catch (UnrecoverableKeyException e) {
419        throw new IOException("Can't recover key for " + name +
420            " from keystore " + path, e);
421      }
422    } finally {
423      readLock.unlock();
424    }
425  }
426
427  @Override
428  public KeyVersion createKey(String name, byte[] material,
429                               Options options) throws IOException {
430    Preconditions.checkArgument(name.equals(name.toLowerCase()),
431        "Uppercase key names are unsupported: %s", name);
432    writeLock.lock();
433    try {
434      try {
435        if (keyStore.containsAlias(name) || cache.containsKey(name)) {
436          throw new IOException("Key " + name + " already exists in " + this);
437        }
438      } catch (KeyStoreException e) {
439        throw new IOException("Problem looking up key " + name + " in " + this,
440            e);
441      }
442      Metadata meta = new Metadata(options.getCipher(), options.getBitLength(),
443          options.getDescription(), options.getAttributes(), new Date(), 1);
444      if (options.getBitLength() != 8 * material.length) {
445        throw new IOException("Wrong key length. Required " +
446            options.getBitLength() + ", but got " + (8 * material.length));
447      }
448      cache.put(name, meta);
449      String versionName = buildVersionName(name, 0);
450      return innerSetKeyVersion(name, versionName, material, meta.getCipher());
451    } finally {
452      writeLock.unlock();
453    }
454  }
455
456  @Override
457  public void deleteKey(String name) throws IOException {
458    writeLock.lock();
459    try {
460      Metadata meta = getMetadata(name);
461      if (meta == null) {
462        throw new IOException("Key " + name + " does not exist in " + this);
463      }
464      for(int v=0; v < meta.getVersions(); ++v) {
465        String versionName = buildVersionName(name, v);
466        try {
467          if (keyStore.containsAlias(versionName)) {
468            keyStore.deleteEntry(versionName);
469          }
470        } catch (KeyStoreException e) {
471          throw new IOException("Problem removing " + versionName + " from " +
472              this, e);
473        }
474      }
475      try {
476        if (keyStore.containsAlias(name)) {
477          keyStore.deleteEntry(name);
478        }
479      } catch (KeyStoreException e) {
480        throw new IOException("Problem removing " + name + " from " + this, e);
481      }
482      cache.remove(name);
483      changed = true;
484    } finally {
485      writeLock.unlock();
486    }
487  }
488
489  KeyVersion innerSetKeyVersion(String name, String versionName, byte[] material,
490                                String cipher) throws IOException {
491    try {
492      keyStore.setKeyEntry(versionName, new SecretKeySpec(material, cipher),
493          password, null);
494    } catch (KeyStoreException e) {
495      throw new IOException("Can't store key " + versionName + " in " + this,
496          e);
497    }
498    changed = true;
499    return new KeyVersion(name, versionName, material);
500  }
501
502  @Override
503  public KeyVersion rollNewVersion(String name,
504                                    byte[] material) throws IOException {
505    writeLock.lock();
506    try {
507      Metadata meta = getMetadata(name);
508      if (meta == null) {
509        throw new IOException("Key " + name + " not found");
510      }
511      if (meta.getBitLength() != 8 * material.length) {
512        throw new IOException("Wrong key length. Required " +
513            meta.getBitLength() + ", but got " + (8 * material.length));
514      }
515      int nextVersion = meta.addVersion();
516      String versionName = buildVersionName(name, nextVersion);
517      return innerSetKeyVersion(name, versionName, material, meta.getCipher());
518    } finally {
519      writeLock.unlock();
520    }
521  }
522
523  @Override
524  public void flush() throws IOException {
525    Path newPath = constructNewPath(path);
526    Path oldPath = constructOldPath(path);
527    Path resetPath = path;
528    writeLock.lock();
529    try {
530      if (!changed) {
531        return;
532      }
533      // Might exist if a backup has been restored etc.
534      if (fs.exists(newPath)) {
535        renameOrFail(newPath, new Path(newPath.toString()
536            + "_ORPHANED_" + System.currentTimeMillis()));
537      }
538      if (fs.exists(oldPath)) {
539        renameOrFail(oldPath, new Path(oldPath.toString()
540            + "_ORPHANED_" + System.currentTimeMillis()));
541      }
542      // put all of the updates into the keystore
543      for(Map.Entry<String, Metadata> entry: cache.entrySet()) {
544        try {
545          keyStore.setKeyEntry(entry.getKey(), new KeyMetadata(entry.getValue()),
546              password, null);
547        } catch (KeyStoreException e) {
548          throw new IOException("Can't set metadata key " + entry.getKey(),e );
549        }
550      }
551
552      // Save old File first
553      boolean fileExisted = backupToOld(oldPath);
554      if (fileExisted) {
555        resetPath = oldPath;
556      }
557      // write out the keystore
558      // Write to _NEW path first :
559      try {
560        writeToNew(newPath);
561      } catch (IOException ioe) {
562        // rename _OLD back to curent and throw Exception
563        revertFromOld(oldPath, fileExisted);
564        resetPath = path;
565        throw ioe;
566      }
567      // Rename _NEW to CURRENT and delete _OLD
568      cleanupNewAndOld(newPath, oldPath);
569      changed = false;
570    } catch (IOException ioe) {
571      resetKeyStoreState(resetPath);
572      throw ioe;
573    } finally {
574      writeLock.unlock();
575    }
576  }
577
578  private void resetKeyStoreState(Path path) {
579    LOG.debug("Could not flush Keystore.."
580        + "attempting to reset to previous state !!");
581    // 1) flush cache
582    cache.clear();
583    // 2) load keyStore from previous path
584    try {
585      loadFromPath(path, password);
586      LOG.debug("KeyStore resetting to previously flushed state !!");
587    } catch (Exception e) {
588      LOG.debug("Could not reset Keystore to previous state", e);
589    }
590  }
591
592  private void cleanupNewAndOld(Path newPath, Path oldPath) throws IOException {
593    // Rename _NEW to CURRENT
594    renameOrFail(newPath, path);
595    // Delete _OLD
596    if (fs.exists(oldPath)) {
597      fs.delete(oldPath, true);
598    }
599  }
600
601  protected void writeToNew(Path newPath) throws IOException {
602    FSDataOutputStream out =
603        FileSystem.create(fs, newPath, permissions);
604    try {
605      keyStore.store(out, password);
606    } catch (KeyStoreException e) {
607      throw new IOException("Can't store keystore " + this, e);
608    } catch (NoSuchAlgorithmException e) {
609      throw new IOException(
610          "No such algorithm storing keystore " + this, e);
611    } catch (CertificateException e) {
612      throw new IOException(
613          "Certificate exception storing keystore " + this, e);
614    }
615    out.close();
616  }
617
618  protected boolean backupToOld(Path oldPath)
619      throws IOException {
620    boolean fileExisted = false;
621    if (fs.exists(path)) {
622      renameOrFail(path, oldPath);
623      fileExisted = true;
624    }
625    return fileExisted;
626  }
627
628  private void revertFromOld(Path oldPath, boolean fileExisted)
629      throws IOException {
630    if (fileExisted) {
631      renameOrFail(oldPath, path);
632    }
633  }
634
635
636  private void renameOrFail(Path src, Path dest)
637      throws IOException {
638    if (!fs.rename(src, dest)) {
639      throw new IOException("Rename unsuccessful : "
640          + String.format("'%s' to '%s'", src, dest));
641    }
642  }
643
644  @Override
645  public String toString() {
646    return uri.toString();
647  }
648
649  /**
650   * The factory to create JksProviders, which is used by the ServiceLoader.
651   */
652  public static class Factory extends KeyProviderFactory {
653    @Override
654    public KeyProvider createProvider(URI providerName,
655                                      Configuration conf) throws IOException {
656      if (SCHEME_NAME.equals(providerName.getScheme())) {
657        return new JavaKeyStoreProvider(providerName, conf);
658      }
659      return null;
660    }
661  }
662
663  /**
664   * An adapter between a KeyStore Key and our Metadata. This is used to store
665   * the metadata in a KeyStore even though isn't really a key.
666   */
667  public static class KeyMetadata implements Key, Serializable {
668    private Metadata metadata;
669    private final static long serialVersionUID = 8405872419967874451L;
670
671    private KeyMetadata(Metadata meta) {
672      this.metadata = meta;
673    }
674
675    @Override
676    public String getAlgorithm() {
677      return metadata.getCipher();
678    }
679
680    @Override
681    public String getFormat() {
682      return KEY_METADATA;
683    }
684
685    @Override
686    public byte[] getEncoded() {
687      return new byte[0];
688    }
689
690    private void writeObject(ObjectOutputStream out) throws IOException {
691      byte[] serialized = metadata.serialize();
692      out.writeInt(serialized.length);
693      out.write(serialized);
694    }
695
696    private void readObject(ObjectInputStream in
697                            ) throws IOException, ClassNotFoundException {
698      byte[] buf = new byte[in.readInt()];
699      in.readFully(buf);
700      metadata = new Metadata(buf);
701    }
702
703  }
704}