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.alias;
020
021import java.io.Console;
022import java.io.IOException;
023import java.io.PrintStream;
024import java.security.InvalidParameterException;
025import java.security.NoSuchAlgorithmException;
026import java.util.Arrays;
027import java.util.List;
028
029import org.apache.hadoop.conf.Configuration;
030import org.apache.hadoop.conf.Configured;
031import org.apache.hadoop.util.Tool;
032import org.apache.hadoop.util.ToolRunner;
033
034/**
035 * This program is the CLI utility for the CredentialProvider facilities in 
036 * Hadoop.
037 */
038public class CredentialShell extends Configured implements Tool {
039  final static private String USAGE_PREFIX = "Usage: hadoop credential " +
040                "[generic options]\n";
041  final static private String COMMANDS =
042      "   [--help]\n" +
043      "   [" + CreateCommand.USAGE + "]\n" +
044      "   [" + DeleteCommand.USAGE + "]\n" +
045      "   [" + ListCommand.USAGE + "]\n";
046
047  private boolean interactive = true;
048  private Command command = null;
049
050  /** allows stdout to be captured if necessary */
051  public PrintStream out = System.out;
052  /** allows stderr to be captured if necessary */
053  public PrintStream err = System.err;
054
055  private boolean userSuppliedProvider = false;
056  private String value = null;
057  private PasswordReader passwordReader;
058
059  @Override
060  public int run(String[] args) throws Exception {
061    int exitCode = 0;
062    try {
063      exitCode = init(args);
064      if (exitCode != 0) {
065        return exitCode;
066      }
067      if (command.validate()) {
068          command.execute();
069      } else {
070        exitCode = 1;
071      }
072    } catch (Exception e) {
073      e.printStackTrace(err);
074      return 1;
075    }
076    return exitCode;
077  }
078
079  /**
080   * Parse the command line arguments and initialize the data
081   * <pre>
082   * % hadoop credential create alias [-provider providerPath]
083   * % hadoop credential list [-provider providerPath]
084   * % hadoop credential delete alias [-provider providerPath] [-i]
085   * </pre>
086   * @param args
087   * @return 0 if the argument(s) were recognized, 1 otherwise
088   * @throws IOException
089   */
090  protected int init(String[] args) throws IOException {
091    // no args should print the help message
092    if (0 == args.length) {
093      printCredShellUsage();
094      ToolRunner.printGenericCommandUsage(System.err);
095      return 1;
096    }
097
098    for (int i = 0; i < args.length; i++) { // parse command line
099      if (args[i].equals("create")) {
100        String alias = args[++i];
101        command = new CreateCommand(alias);
102        if (alias.equals("-help")) {
103          printCredShellUsage();
104          return 0;
105        }
106      } else if (args[i].equals("delete")) {
107        String alias = args[++i];
108        command = new DeleteCommand(alias);
109        if (alias.equals("-help")) {
110          printCredShellUsage();
111          return 0;
112        }
113      } else if (args[i].equals("list")) {
114        command = new ListCommand();
115      } else if (args[i].equals("-provider")) {
116        userSuppliedProvider = true;
117        getConf().set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH, 
118            args[++i]);
119      } else if (args[i].equals("-f") || (args[i].equals("-force"))) {
120        interactive = false;
121      } else if (args[i].equals("-v") || (args[i].equals("-value"))) {
122        value = args[++i];
123      } else if (args[i].equals("-help")) {
124        printCredShellUsage();
125        return 0;
126      } else {
127        printCredShellUsage();
128        ToolRunner.printGenericCommandUsage(System.err);
129        return 1;
130      }
131    }
132    return 0;
133  }
134
135  private void printCredShellUsage() {
136    out.println(USAGE_PREFIX + COMMANDS);
137    if (command != null) {
138      out.println(command.getUsage());
139    }
140    else {
141      out.println("=========================================================" +
142                "======");
143      out.println(CreateCommand.USAGE + ":\n\n" + CreateCommand.DESC);
144      out.println("=========================================================" +
145          "======");
146      out.println(DeleteCommand.USAGE + ":\n\n" + DeleteCommand.DESC);
147      out.println("=========================================================" +
148          "======");
149      out.println(ListCommand.USAGE + ":\n\n" + ListCommand.DESC);
150    }
151  }
152
153  private abstract class Command {
154    protected CredentialProvider provider = null;
155
156    public boolean validate() {
157      return true;
158    }
159
160    protected CredentialProvider getCredentialProvider() {
161      CredentialProvider provider = null;
162      List<CredentialProvider> providers;
163      try {
164        providers = CredentialProviderFactory.getProviders(getConf());
165        if (userSuppliedProvider) {
166          provider = providers.get(0);
167        }
168        else {
169          for (CredentialProvider p : providers) {
170            if (!p.isTransient()) {
171              provider = p;
172              break;
173            }
174          }
175        }
176      } catch (IOException e) {
177        e.printStackTrace(err);
178      }
179      return provider;
180    }
181
182    protected void printProviderWritten() {
183        out.println(provider.getClass().getName() + " has been updated.");
184    }
185
186    protected void warnIfTransientProvider() {
187      if (provider.isTransient()) {
188        out.println("WARNING: you are modifying a transient provider.");
189      }
190    }
191
192    public abstract void execute() throws Exception;
193
194    public abstract String getUsage();
195  }
196
197  private class ListCommand extends Command {
198    public static final String USAGE = "list [-provider] [-help]";
199    public static final String DESC =
200        "The list subcommand displays the aliases contained within \n" +
201        "a particular provider - as configured in core-site.xml or " +
202        "indicated\nthrough the -provider argument.";
203
204    public boolean validate() {
205      boolean rc = true;
206      provider = getCredentialProvider();
207      if (provider == null) {
208        out.println("There are no non-transient CredentialProviders configured.\n"
209            + "Consider using the -provider option to indicate the provider\n"
210            + "to use. If you want to list a transient provider then you\n"
211            + "you MUST use the -provider argument.");
212        rc = false;
213      }
214      return rc;
215    }
216
217    public void execute() throws IOException {
218      List<String> aliases;
219      try {
220        aliases = provider.getAliases();
221        out.println("Listing aliases for CredentialProvider: " + provider.toString());
222        for (String alias : aliases) {
223          out.println(alias);
224        }
225      } catch (IOException e) {
226        out.println("Cannot list aliases for CredentialProvider: " + provider.toString()
227            + ": " + e.getMessage());
228        throw e;
229      }
230    }
231
232    @Override
233    public String getUsage() {
234      return USAGE + ":\n\n" + DESC;
235    }
236  }
237
238  private class DeleteCommand extends Command {
239    public static final String USAGE =
240        "delete <alias> [-provider] [-f] [-help]";
241    public static final String DESC =
242        "The delete subcommand deletes the credential\n" +
243        "specified as the <alias> argument from within the provider\n" +
244        "indicated through the -provider argument. The command asks for\n" +
245        "confirmation unless the -f option is specified.";
246
247    String alias = null;
248    boolean cont = true;
249
250    public DeleteCommand(String alias) {
251      this.alias = alias;
252    }
253
254    @Override
255    public boolean validate() {
256      provider = getCredentialProvider();
257      if (provider == null) {
258        out.println("There are no valid CredentialProviders configured.\n"
259            + "Nothing will be deleted.\n"
260            + "Consider using the -provider option to indicate the provider"
261            + " to use.");
262        return false;
263      }
264      if (alias == null) {
265        out.println("There is no alias specified. Please provide the" +
266            "mandatory <alias>. See the usage description with -help.");
267        return false;
268      }
269      if (interactive) {
270        try {
271          cont = ToolRunner
272              .confirmPrompt("You are about to DELETE the credential " +
273                  alias + " from CredentialProvider " + provider.toString() +
274                  ". Continue? ");
275          if (!cont) {
276            out.println("Nothing has been be deleted.");
277          }
278          return cont;
279        } catch (IOException e) {
280          out.println(alias + " will not be deleted.");
281          e.printStackTrace(err);
282        }
283      }
284      return true;
285    }
286
287    public void execute() throws IOException {
288      warnIfTransientProvider();
289      out.println("Deleting credential: " + alias + " from CredentialProvider: "
290          + provider.toString());
291      if (cont) {
292        try {
293          provider.deleteCredentialEntry(alias);
294          out.println(alias + " has been successfully deleted.");
295          provider.flush();
296          printProviderWritten();
297        } catch (IOException e) {
298          out.println(alias + " has NOT been deleted.");
299          throw e;
300        }
301      }
302    }
303
304    @Override
305    public String getUsage() {
306      return USAGE + ":\n\n" + DESC;
307    }
308  }
309
310  private class CreateCommand extends Command {
311    public static final String USAGE = "create <alias> [-provider] [-help]";
312    public static final String DESC =
313        "The create subcommand creates a new credential for the name specified\n" +
314        "as the <alias> argument within the provider indicated through\n" +
315        "the -provider argument.";
316
317    String alias = null;
318
319    public CreateCommand(String alias) {
320      this.alias = alias;
321    }
322
323    public boolean validate() {
324      boolean rc = true;
325      provider = getCredentialProvider();
326      if (provider == null) {
327        out.println("There are no valid CredentialProviders configured." +
328                        "\nCredential will not be created.\n"
329            + "Consider using the -provider option to indicate the provider" +
330            " to use.");
331        rc = false;
332      }
333      if (alias == null) {
334        out.println("There is no alias specified. Please provide the" +
335            "mandatory <alias>. See the usage description with -help.");
336        rc = false;
337      }
338      return rc;
339    }
340
341    public void execute() throws IOException, NoSuchAlgorithmException {
342      warnIfTransientProvider();
343      try {
344        char[] credential = null;
345        if (value != null) {
346          // testing only
347          credential = value.toCharArray();
348        }
349        else {
350           credential = promptForCredential();
351        }
352        provider.createCredentialEntry(alias, credential);
353        out.println(alias + " has been successfully created.");
354        provider.flush();
355        printProviderWritten();
356      } catch (InvalidParameterException e) {
357        out.println(alias + " has NOT been created. " + e.getMessage());
358        throw e;
359      } catch (IOException e) {
360        out.println(alias + " has NOT been created. " + e.getMessage());
361        throw e;
362      }
363    }
364
365    @Override
366    public String getUsage() {
367      return USAGE + ":\n\n" + DESC;
368    }
369  }
370  
371  protected char[] promptForCredential() throws IOException {
372    PasswordReader c = getPasswordReader();
373    if (c == null) {
374      throw new IOException("No console available for prompting user.");
375    }
376    
377    char[] cred = null;
378
379    boolean noMatch;
380    do {
381      char[] newPassword1 = c.readPassword("Enter password: ");
382      char[] newPassword2 = c.readPassword("Enter password again: ");
383      noMatch = !Arrays.equals(newPassword1, newPassword2);
384      if (noMatch) {
385        if (newPassword1 != null) Arrays.fill(newPassword1, ' ');
386        c.format("Passwords don't match. Try again.%n");
387      } else {
388        cred = newPassword1;
389      }
390      if (newPassword2 != null) Arrays.fill(newPassword2, ' ');
391    } while (noMatch);
392    return cred;
393  }
394  
395  public PasswordReader getPasswordReader() {
396    if (passwordReader == null) {
397      passwordReader = new PasswordReader();
398    }
399    return passwordReader;
400  }
401  
402  public void setPasswordReader(PasswordReader reader) {
403    passwordReader = reader;
404  }
405  
406  // to facilitate testing since Console is a final class...
407  public static class PasswordReader {
408    public char[] readPassword(String prompt) {
409      Console console = System.console();
410      char[] pass = console.readPassword(prompt);
411      return pass;
412    }
413
414    public void format(String message) {
415      Console console = System.console();
416      console.format(message);
417    }
418  }
419  
420  
421  /**
422   * Main program.
423   *
424   * @param args
425   *          Command line arguments
426   * @throws Exception
427   */
428  public static void main(String[] args) throws Exception {
429    int res = ToolRunner.run(new Configuration(), new CredentialShell(), args);
430    System.exit(res);
431  }
432}