summaryrefslogtreecommitdiffstats
path: root/base/java-tools/src/com/netscape/cmstools/cli/MainCLI.java
blob: 1510cc7af07f316fbd1cfa68bdf141d27c123b3f (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
// --- 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.File;
import java.lang.reflect.Field;
import java.net.InetAddress;
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.cli.Options;
import org.apache.commons.lang.StringUtils;
import org.mozilla.jss.CryptoManager;
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.account.AccountClient;
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.group.GroupCLI;
import com.netscape.cmstools.key.KeyCLI;
import com.netscape.cmstools.system.KRAConnectorCLI;
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;
    public Collection<Integer> ignoredCertStatuses;

    public PKIClient client;
    public PKIConnection connection;
    public AccountClient accountClient;

    String output;

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

        addModule(new CertCLI(this));
        addModule(new GroupCLI(this));
        addModule(new KeyCLI(this));
        addModule(new KRAConnectorCLI(this));
        addModule(new SecurityDomainCLI(this));
        addModule(new UserCLI(this));
    }

    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();
        System.out.println("Commands:");

        int leftPadding = 1;
        int rightPadding = 18;

        for (CLI plugin : modules.values()) {
            String label = plugin.getName();

            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(plugin.getDescription());
        }
    }

    public void printHelpCommand(String pluginName) {
        CLI plugin = getModule(pluginName);
        plugin.printHelp();
    }

    public void createOptions(Options options) 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 (default: ca)");
        option.setArgName("type");
        options.addOption(option);

        option = new Option("d", true, "Certificate database");
        option.setArgName("database");
        options.addOption(option);

        option = new Option("n", true, "Certificate nickname");
        option.setArgName("nickname");
        options.addOption(option);

        option = new Option("u", true, "Username");
        option.setArgName("username");
        options.addOption(option);

        option = new Option("w", true, "Password");
        option.setArgName("password");
        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);

        options.addOption("v", false, "Verbose");
        options.addOption(null, "help", false, "Help");
        options.addOption(null, "version", false, "Version");
    }

    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 type = cmd.getOptionValue("t", "ca");

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

        config.setServerURI(uri);

        String certDatabase = cmd.getOptionValue("d");
        String certNickname = cmd.getOptionValue("n");
        String username = cmd.getOptionValue("u");
        String password = cmd.getOptionValue("w");

        // convert into absolute path
        if (certDatabase != null)
            config.setCertDatabase(new File(certDatabase).getAbsolutePath());

        if (certNickname != null)
            config.setCertNickname(certNickname);

        if (username != null)
            config.setUsername(username);

        if (password != null)
            config.setPassword(password);

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

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

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

        if (list == null) return null;

        Collection<Integer> statuses = new HashSet<Integer>();

        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);
            }
        }

        return statuses;
    }

    public void connect() throws Exception {

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

        connection = client.getConnection();
        connection.setRejectedCertStatuses(rejectedCertStatuses);
        connection.setIgnoredCertStatuses(ignoredCertStatuses);

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

        accountClient = new AccountClient(client);
    }

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

        CLI module;
        String[] moduleArgs;

        try {
            createOptions(options);

            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(1);
            }

            if (cmdArgs.length == 0 || cmd.hasOption("help")) {
                printHelp();
                System.exit(1);
            }

            parseOptions(cmd);

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

            String command = cmdArgs[0];
            String moduleName;
            String moduleCommand;

            // If a command contains a '-' sign it will be
            // split into module name and module command.
            // Otherwise it's a single command.
            int i = command.indexOf('-');
            if (i >= 0) { // <module name>-<module command>
                moduleName = command.substring(0, i);
                moduleCommand = command.substring(i+1);

            } else { // <command>
                moduleName = command;
                moduleCommand = null;
            }

            // get command module
            module = getModule(moduleName);
            if (module == null)
                throw new Error("Invalid command \"" + command + "\".");

            // prepare module arguments
            if (moduleCommand != null) {
                moduleArgs = new String[cmdArgs.length];
                moduleArgs[0] = moduleCommand;
                System.arraycopy(cmdArgs, 1, moduleArgs, 1, cmdArgs.length-1);

            } else {
                moduleArgs = new String[cmdArgs.length-1];
                System.arraycopy(cmdArgs, 1, moduleArgs, 0, cmdArgs.length-1);
            }

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

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

        // initialize certificate database if specified
        if (config.getCertDatabase() != null) {

            try {
                if (verbose) System.out.println("Certificate database: "+config.getCertDatabase());
                CryptoManager.initialize(config.getCertDatabase());

                if (config.getPassword() != null) {
                    try {
                        CryptoManager manager = CryptoManager.getInstance();
                        CryptoToken token = manager.getInternalKeyStorageToken();
                        Password password = new Password(config.getPassword().toCharArray());
                        token.login(password);

                    } catch (IncorrectPasswordException e) {
                        throw new Error("Incorrect certificate database password.", e);
                    }
                }

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

        // execute command
        boolean loggedIn = false;
        try {
            connect();

            // login if username or nickname is specified
            if (config.getUsername() != null || config.getCertNickname() != null) {
                accountClient.login();
                loggedIn = true;
            }

            // execute module command
            module.execute(moduleArgs);

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

        } finally {
            if (loggedIn) accountClient.logout();
        }
    }

    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[]) throws Exception {
        MainCLI cli = new MainCLI();
        cli.execute(args);
    }
}