summaryrefslogtreecommitdiffstats
path: root/base/java-tools/src/com/netscape/cmstools/cli/MainCLI.java
blob: 159e4ac5a21e741ef7ee15b313a91f8e389dd941 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; version 2 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
// (C) 2012 Red Hat, Inc.
// All rights reserved.
// --- END COPYRIGHT BLOCK ---

package com.netscape.cmstools.cli;

import java.io.BufferedReader;
import java.io.Console;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.HashSet;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.lang.StringUtils;
import org.mozilla.jss.CryptoManager;
import org.mozilla.jss.CryptoManager.NotInitializedException;
import org.mozilla.jss.crypto.CryptoToken;
import org.mozilla.jss.ssl.SSLCertificateApprovalCallback;
import org.mozilla.jss.util.IncorrectPasswordException;
import org.mozilla.jss.util.Password;

import com.netscape.certsrv.ca.CAClient;
import com.netscape.certsrv.client.ClientConfig;
import com.netscape.certsrv.client.PKIClient;
import com.netscape.certsrv.client.PKIConnection;
import com.netscape.cmstools.cert.CertCLI;
import com.netscape.cmstools.client.ClientCLI;
import com.netscape.cmstools.group.GroupCLI;
import com.netscape.cmstools.key.KeyCLI;
import com.netscape.cmstools.system.SecurityDomainCLI;
import com.netscape.cmstools.user.UserCLI;

/**
 * @author Endi S. Dewata
 */
public class MainCLI extends CLI {

    public ClientConfig config = new ClientConfig();

    public Collection<Integer> rejectedCertStatuses = new HashSet<Integer>();
    public Collection<Integer> ignoredCertStatuses = new HashSet<Integer>();

    public File certDatabase;

    String output;

    public MainCLI() throws Exception {
        super("pki", "PKI command-line interface");

        addModule(new HelpCLI(this));

        addModule(new ClientCLI(this));

        addModule(new ProxyCLI(new CertCLI(this), "ca"));
        addModule(new ProxyCLI(new GroupCLI(this), "ca"));
        addModule(new ProxyCLI(new KeyCLI(this), "kra"));
        addModule(new ProxyCLI(new SecurityDomainCLI(this), "ca"));
        addModule(new ProxyCLI(new UserCLI(this), "ca"));

        addModule(new CACLI(this));
        addModule(new KRACLI(this));
        addModule(new OCSPCLI(this));
        addModule(new TKSCLI(this));
        addModule(new TPSCLI(this));

        createOptions();
    }

    public String getFullModuleName(String moduleName) {
        return moduleName;
    }

    @Override
    public String getManPage() {
        return "pki";
    }

    public void printVersion() {
        Package pkg = MainCLI.class.getPackage();
        System.out.println("PKI Command-Line Interface "+pkg.getImplementationVersion());
    }

    public void printHelp() {

        formatter.printHelp(name+" [OPTIONS..] <command> [ARGS..]", options);
        System.out.println();

        int leftPadding = 1;
        int rightPadding = 25;

        System.out.println("Commands:");

        for (CLI module : modules.values()) {
            String label = module.getFullName();

            int padding = rightPadding - leftPadding - label.length();
            if (padding < 1)
                padding = 1;

            System.out.print(StringUtils.repeat(" ", leftPadding));
            System.out.print(label);
            System.out.print(StringUtils.repeat(" ", padding));
            System.out.println(module.getDescription());
        }
    }

    public void createOptions() throws UnknownHostException {

        Option option = new Option("U", true, "Server URI");
        option.setArgName("uri");
        options.addOption(option);

        option = new Option("P", true, "Protocol (default: http)");
        option.setArgName("protocol");
        options.addOption(option);

        option = new Option("h", true, "Hostname (default: "+ InetAddress.getLocalHost().getCanonicalHostName() + ")");
        option.setArgName("hostname");
        options.addOption(option);

        option = new Option("p", true, "Port (default: 8080)");
        option.setArgName("port");
        options.addOption(option);

        option = new Option("t", true, "Subsystem type");
        option.setArgName("type");
        options.addOption(option);

        option = new Option("d", true, "Client security database location (default: ~/.dogtag/nssdb)");
        option.setArgName("database");
        options.addOption(option);

        option = new Option("c", true, "Client security database password (mutually exclusive to the '-C' option; requires the '-n' client authentication option)");
        option.setArgName("certpassword");
        options.addOption(option);

        option = new Option("C", true, "Client-side password file (mutually exclusive to the '-c' option; requires the '-n' client authentication option)");
        option.setArgName("certpasswordfile");
        options.addOption(option);

        option = new Option("n", true, "Client certificate nickname (signifies client authentication which is mutually exclusive to '-u' basic authentication option)");
        option.setArgName("nickname");
        options.addOption(option);

        option = new Option("u", true, "Username (signifies basic authentication which is mutually exclusive to '-n' client authentication option)");
        option.setArgName("username");
        options.addOption(option);

        option = new Option("w", true, "Password (mutually exclusive to the '-W' option; requires the '-u' basic authentication option)");
        option.setArgName("password");
        options.addOption(option);

        option = new Option("W", true, "Client-side password file (mutually exclusive to the '-w' option; requires the '-u' basic authentication option)");
        option.setArgName("passwordfile");
        options.addOption(option);

        option = new Option(null, "token", true, "Security token name");
        option.setArgName("token");
        options.addOption(option);

        option = new Option(null, "output", true, "Folder to store HTTP messages");
        option.setArgName("folder");
        options.addOption(option);

        option = new Option(null, "reject-cert-status", true, "Comma-separated list of rejected certificate validity statuses");
        option.setArgName("list");
        options.addOption(option);

        option = new Option(null, "ignore-cert-status", true, "Comma-separated list of ignored certificate validity statuses");
        option.setArgName("list");
        options.addOption(option);

        option = new Option(null, "message-format", true, "Message format: xml (default), json");
        option.setArgName("format");
        options.addOption(option);

        options.addOption("v", "verbose", false, "Run in verbose mode.");
        options.addOption(null, "help", false, "Show help message.");
        options.addOption(null, "version", false, "Show version number.");
    }

    public String[] readPlaintextPasswordFromFile(String pwfile) throws IOException {
        String[] tokenPassword = { null, null };
        BufferedReader br = null;
        String delimiter = "=";

        try {
            br = new BufferedReader(new FileReader(pwfile));

            String line = br.readLine();
            if (line != null) {
                if (line.isEmpty()) {
                    System.err.println("Error:  File '" + pwfile + "' does not define a token or a password!");
                    System.exit(-1);
                } else if (line.contains(delimiter)) {
                    // Process 'token=password' format:
                    //
                    //     Token:     tokenPassword[0]
                    //     Password:  tokenPassword[1]
                    //
                    tokenPassword = line.split(delimiter, 2);

                    // Always trim leading/trailing whitespace from 'token'
                    tokenPassword[0] = tokenPassword[0].trim();

                    // Check for undefined 'token'
                    if (tokenPassword[0].isEmpty()) {
                        // Set default 'token'
                        tokenPassword[0] = "internal";
                    }

                    // Check for undefined 'password'
                    if (tokenPassword[1].isEmpty()) {
                        System.err.println("Error:  File '" + pwfile + "' does not define a password!");
                        System.exit(-1);
                    }
                } else {
                    // Set default 'token'
                    tokenPassword[0] = "internal";

                    // Set simple 'password' (do not trim leading/trailing whitespace)
                    tokenPassword[1] = line;
                }
            } else {
                // Case of an empty password file
                System.err.println("Error:  File '" + pwfile + "' is empty!");
                System.exit(-1);
            }
        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
            System.exit(-1);
        } finally {
            if (br != null) {
                br.close();
            }
        }

        return tokenPassword;
    }

    public String promptForPassword(String prompt) throws IOException {
        char[] password = null;
        Console console = System.console();
        System.out.print(prompt);
        password = console.readPassword();
        return new String(password);
    }

    public String promptForPassword() throws IOException {
        return promptForPassword("Enter Password: ");
    }

    public static CAClient createCAClient(PKIClient client) throws Exception {

        ClientConfig config = client.getConfig();
        CAClient caClient = new CAClient(client);

        while (!caClient.exists()) {
            System.err.println("ERROR: CA subsystem not available");

            URI serverURI = config.getServerURI();
            String uri = serverURI.getScheme() + "://" + serverURI.getHost() + ":" + serverURI.getPort();

            System.out.print("CA server URI [" + uri + "]: ");
            System.out.flush();

            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            String line = reader.readLine().trim();
            if (!line.equals("")) {
                uri = line;
            }

            config = new ClientConfig(client.getConfig());
            config.setServerURI(uri);

            client = new PKIClient(config);
            caClient = new CAClient(client);
        }

        return caClient;
    }

    public void parseOptions(CommandLine cmd) throws Exception {

        verbose = cmd.hasOption("v");
        output = cmd.getOptionValue("output");

        String uri = cmd.getOptionValue("U");

        String protocol = cmd.getOptionValue("P", "http");
        String hostname = cmd.getOptionValue("h", InetAddress.getLocalHost().getCanonicalHostName());
        String port = cmd.getOptionValue("p", "8080");
        String subsystem = cmd.getOptionValue("t");

        if (uri == null)
            uri = protocol + "://" + hostname + ":" + port;

        if (subsystem != null)
            uri = uri + "/" + subsystem;

        config.setServerURI(uri);

        if (verbose) System.out.println("Server URI: "+uri);

        String certDatabase = cmd.getOptionValue("d");
        String certNickname = cmd.getOptionValue("n");
        String certPassword = cmd.getOptionValue("c");
        String certPasswordFile = cmd.getOptionValue("C");
        String tokenName = cmd.getOptionValue("token");

        String username = cmd.getOptionValue("u");
        String password = cmd.getOptionValue("w");
        String passwordFile = cmd.getOptionValue("W");
        String[] tokenPasswordPair = { null, null };

        // check authentication parameters
        if (certNickname != null && username != null) {
            System.err.println("Error: The '-n' and '-u' options are mutually exclusive.");
            System.exit(-1);

        } else if (certNickname != null) { // client certificate authentication

            if (certPasswordFile != null && certPassword != null) {
                System.err.println("Error: The '-C' and '-c' options are mutually exclusive.");
                System.exit(-1);

            } else if (certPasswordFile == null && certPassword == null) {
                System.err.println("Error: Missing security database password.");
                System.exit(-1);
            }

        } else if (username != null) { // basic authentication

            if (passwordFile != null && password != null) {
                System.err.println("Error: The '-W' and '-w' options are mutually exclusive.");
                System.exit(-1);

            } else if (passwordFile == null && password == null) {
                System.err.println("Error: Missing user password.");
                System.exit(-1);
            }
        }

        if (certDatabase != null) {
            // store user-provided security database location
            config.setCertDatabase(new File(certDatabase).getAbsolutePath());
        } else {
            // store default security database location
            config.setCertDatabase(System.getProperty("user.home") +
                    File.separator + ".dogtag" + File.separator + "nssdb");
        }

        // store token name
        config.setTokenName(tokenName);

        // store certificate nickname
        config.setCertNickname(certNickname);

        if (certPasswordFile != null) {
            // read client security database password from specified file
            tokenPasswordPair = readPlaintextPasswordFromFile(certPasswordFile);
            // XXX TBD set client security database token

            certPassword = tokenPasswordPair[1];

        } else if (certNickname != null && certPassword == null) {
            // prompt for security database password if required for authentication
            //
            // NOTE:  This overrides the password callback provided
            //        by JSS for NSS security database authentication.
            //
            try {
                certPassword = promptForPassword("Enter Client Security Database Password: ");

            } catch (Exception e) {
                System.err.println("Error: " + e.getMessage());
                System.exit(-1);
            }
        }

        // store security database password
        config.setCertPassword(certPassword);

        // store user name
        config.setUsername(username);

        if (passwordFile != null) {
            // read user password from specified file
            tokenPasswordPair = readPlaintextPasswordFromFile(passwordFile);
            // XXX TBD set user token

            password = tokenPasswordPair[1];

        } else if (username != null && password == null) {
            // prompt for user password if required for authentication
            try {
                password = promptForPassword();

            } catch (Exception e) {
                System.err.println("Error: " + e.getMessage());
                System.exit(-1);
            }
        }

        // store user password
        config.setPassword(password);

        String list = cmd.getOptionValue("reject-cert-status");
        convertCertStatusList(list, rejectedCertStatuses);

        list = cmd.getOptionValue("ignore-cert-status");
        convertCertStatusList(list, ignoredCertStatuses);

        this.certDatabase = new File(config.getCertDatabase());
        if (verbose) System.out.println("Client security database: "+this.certDatabase.getAbsolutePath());

        String messageFormat = cmd.getOptionValue("message-format");
        config.setMessageFormat(messageFormat);
        if (verbose) System.out.println("Message format: " + messageFormat);
    }

    public void convertCertStatusList(String list, Collection<Integer> statuses) throws Exception {

        if (list == null) return;

        Class<SSLCertificateApprovalCallback.ValidityStatus> clazz = SSLCertificateApprovalCallback.ValidityStatus.class;

        for (String status : list.split(",")) {
            try {
                Field field = clazz.getField(status);
                statuses.add(field.getInt(null));

            } catch (NoSuchFieldException e) {
                throw new Error("Invalid cert status \"" + status + "\".", e);
            }
        }
    }

    public void init() throws Exception {

        // Main program should initialize client security database
        if (certDatabase.exists()) {
            if (verbose) System.out.println("Initializing client security database");
            CryptoManager.initialize(certDatabase.getAbsolutePath());
        }

        // If password is specified, use password to access security token
        if (config.getCertPassword() != null) {
            if (verbose) System.out.println("Logging into security token");
            try {
                CryptoManager manager = CryptoManager.getInstance();

                CryptoToken token;
                String tokenName = config.getTokenName();
                if (tokenName == null) {
                    token = manager.getInternalKeyStorageToken();
                } else {
                    token = manager.getTokenByName(tokenName);
                }
                manager.setThreadToken(token);

                Password password = new Password(config.getCertPassword().toCharArray());
                token.login(password);

            } catch (NotInitializedException e) {
                // The original exception doesn't contain a message.
                throw new Error("Client security database does not exist.");

            } catch (IncorrectPasswordException e) {
                // The original exception doesn't contain a message.
                throw new IncorrectPasswordException("Incorrect client security database password.");
            }

        }

        client = new PKIClient(config, null);
        client.setVerbose(verbose);

        client.setRejectedCertStatuses(rejectedCertStatuses);
        client.setIgnoredCertStatuses(ignoredCertStatuses);

        if (output != null) {
            File file = new File(output);
            file.mkdirs();

            PKIConnection connection = client.getConnection();
            connection.setOutput(file);
        }
    }

    public void execute(String[] args) throws Exception {

        CommandLine cmd;
        try {
            cmd = parser.parse(options, args, true);
        } catch (Exception e) {
            throw new Error(e.getMessage(), e);
        }

        String[] cmdArgs = cmd.getArgs();

        if (cmd.hasOption("version")) {
            printVersion();
            System.exit(0);
        }

        if (cmdArgs.length == 0 || cmd.hasOption("help")) {
            // Print 'pki' usage
            printHelp();
            System.exit(0);
        }

        parseOptions(cmd);

        if (verbose) {
            System.out.print("Command:");
            for (String arg : cmdArgs) {
                if (arg.contains(" ")) arg = "\""+arg+"\"";
                System.out.print(" "+arg);
            }
            System.out.println();
        }

        // Do not call CryptoManager.initialize() on some commands
        // because otherwise the database will be locked.
        String command = cmdArgs[0];
        if (!command.equals("client-init") &&
                !command.equals("client-cert-import") &&
                !command.equals("client-cert-mod") &&
                !command.equals("client-cert-request") &&
                !command.equals("client-cert-show")) {
            init();
        }

        super.execute(cmdArgs);
    }

    public static void printMessage(String message) {
        System.out.println(StringUtils.repeat("-", message.length()));
        System.out.println(message);
        System.out.println(StringUtils.repeat("-", message.length()));
    }

    public static void main(String args[]) {
        try {
            MainCLI cli = new MainCLI();
            cli.execute(args);

        } catch (Throwable t) {
            if (verbose) {
                t.printStackTrace(System.err);
            } else {
                System.err.println(t.getClass().getSimpleName()+": "+t.getMessage());
            }
            System.exit(-1);
        }
    }
}