]> git.saurik.com Git - apple/security.git/blob - SecurityTool/security.c
Security-58286.51.6.tar.gz
[apple/security.git] / SecurityTool / security.c
1 /*
2 * Copyright (c) 2003-2017 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 *
23 * security.c
24 */
25
26 #include "security_tool.h"
27
28 #include "leaks.h"
29 #include "readline_cssm.h"
30
31 #include "cmsutil.h"
32 #include "db_commands.h"
33 #include "keychain_add.h"
34 #include "keychain_create.h"
35 #include "keychain_delete.h"
36 #include "keychain_list.h"
37 #include "keychain_lock.h"
38 #include "keychain_set_settings.h"
39 #include "keychain_show_info.h"
40 #include "keychain_unlock.h"
41 #include "keychain_recode.h"
42 #include "key_create.h"
43 #include "keychain_find.h"
44 #include "keychain_import.h"
45 #include "keychain_export.h"
46 #include "identity_find.h"
47 #include "identity_prefs.h"
48 #include "mds_install.h"
49 #include "trusted_cert_add.h"
50 #include "trusted_cert_dump.h"
51 #include "user_trust_enable.h"
52 #include "trust_settings_impexp.h"
53 #include "verify_cert.h"
54 #include "authz.h"
55 #include "smartcards.h"
56 #include "display_error_code.h"
57 #include "createFVMaster.h"
58 #include "smartcards.h"
59 #include "translocate.h"
60
61 #include <ctype.h>
62 #include <stdio.h>
63 #include <stdlib.h>
64 #include <string.h>
65 #include <unistd.h>
66 #include <dispatch/dispatch.h>
67
68 #include <CoreFoundation/CFRunLoop.h>
69 #include <Security/SecBasePriv.h>
70 #include <Security/SecKeychainPriv.h>
71 #include <security_asn1/secerr.h>
72
73 /* Maximum length of an input line in interactive mode. */
74 #define MAX_LINE_LEN 4096
75 /* Maximum number of arguments on an input line in interactive mode. */
76 #define MAX_ARGS 32
77
78 /* Entry in commands array for a command. */
79 typedef struct command
80 {
81 const char *c_name; /* name of the command. */
82 command_func c_func; /* function to execute the command. */
83 const char *c_usage; /* usage sting for command. */
84 const char *c_help; /* help string for (or description of) command. */
85 } command;
86
87 /* The default prompt. */
88 const char *prompt_string = "security> ";
89
90 /* Forward declarations of static functions. */
91 static int help(int argc, char * const *argv);
92
93 /*
94 * The command array itself.
95 * Add commands here at will.
96 * Matching is done on a prefix basis. The first command in the array
97 * gets matched first.
98 */
99 const command commands[] =
100 {
101 { "help", help,
102 "[command ...]",
103 "Show all commands, or show usage for a command." },
104
105 { "list-keychains", keychain_list,
106 "[-d user|system|common|dynamic] [-s [keychain...]]\n"
107 " -d Use the specified preference domain\n"
108 " -s Set the search list to the specified keychains\n"
109 "With no parameters, display the search list.",
110 "Display or manipulate the keychain search list." },
111
112 { "list-smartcards", ctk_list,
113 "Display IDs of available smartcards.",
114 "Display available smartcards." },
115
116 { "default-keychain", keychain_default,
117 "[-d user|system|common|dynamic] [-s [keychain]]\n"
118 " -d Use the specified preference domain\n"
119 " -s Set the default keychain to the specified keychain\n"
120 "With no parameters, display the default keychain.",
121 "Display or set the default keychain." },
122
123 { "login-keychain", keychain_login,
124 "[-d user|system|common|dynamic] [-s [keychain]]\n"
125 " -d Use the specified preference domain\n"
126 " -s Set the login keychain to the specified keychain\n"
127 "With no parameters, display the login keychain.",
128 "Display or set the login keychain." },
129
130 { "create-keychain", keychain_create,
131 "[-P] [-p password] [keychains...]\n"
132 " -p Use \"password\" as the password for the keychains being created\n"
133 " -P Prompt the user for a password using the SecurityAgent\n"
134 "Use of the -p option is insecure",
135 "Create keychains and add them to the search list.",
136 },
137
138 { "delete-keychain", keychain_delete,
139 "[keychains...]",
140 "Delete keychains and remove them from the search list." },
141
142 { "lock-keychain", keychain_lock,
143 "[-a | keychain]\n"
144 " -a Lock all keychains",
145 "Lock the specified keychain."},
146
147 { "unlock-keychain", keychain_unlock,
148 "[-u] [-p password] [keychain]\n"
149 " -p Use \"password\" as the password to unlock the keychain\n"
150 " -u Do not use the password\n"
151 "Use of the -p option is insecure",
152 "Unlock the specified keychain."},
153
154 { "set-keychain-settings", keychain_set_settings,
155 "[-lu] [-t timeout] [keychain]\n"
156 " -l Lock keychain when the system sleeps\n"
157 " -u Lock keychain after timeout interval\n"
158 " -t Timeout in seconds (omitting this option specifies \"no timeout\")\n",
159 "Set settings for a keychain."},
160
161 { "set-keychain-password", keychain_set_password,
162 "[-o oldPassword] [-p newPassword] [keychain]\n"
163 " -o Old keychain password (if not provided, will prompt)\n"
164 " -p New keychain password (if not provided, will prompt)\n"
165 "Use of either the -o or -p options is insecure\n",
166 "Set password for a keychain."},
167
168 { "show-keychain-info", keychain_show_info,
169 "[keychain]",
170 "Show the settings for keychain." },
171
172 { "dump-keychain", keychain_dump,
173 "[-adir] [keychain...]\n"
174 " -a Dump access control list of items\n"
175 " -d Dump (decrypted) data of items\n"
176 " -i Interactive access control list editing mode\n"
177 " -r Dump the raw (encrypted) data of items",
178 "Dump the contents of one or more keychains." },
179
180 #ifndef NDEBUG
181 { "recode-keychain", keychain_recode,
182 "keychain_to_recode keychain_to_get_secrets_from",
183 "Recode a keychain to use the secrets from another one."},
184 #endif
185
186 { "create-keypair", key_create_pair,
187 "[-a alg] [-s size] [-f date] [-t date] [-d days] [-k keychain] [-A|-T appPath] description\n"
188 " -a Use alg as the algorithm, can be rsa, dh, dsa or fee (default rsa)\n"
189 " -s Specify the keysize in bits (default 512)\n"
190 " -f Make a key valid from the specified date\n"
191 " -t Make a key valid to the specified date\n"
192 " -d Make a key valid for the number of days specified from today\n"
193 " -k Use the specified keychain rather than the default\n"
194 " -A Allow any application to access this key without warning (insecure, not recommended!)\n"
195 " -T Specify an application which may access this key (multiple -T options are allowed)\n"
196 "If no options are provided, ask the user interactively.",
197 "Create an asymmetric key pair." },
198
199 #if 0
200 /* this was added in mb's integration of PR-3420772, but this is an unimplemented command */
201 { "create-csr", csr_create,
202 "[-a alg] [-s size] [-f date] [-t date] [-d days] [-k keychain] [-A|-T appPath] description\n"
203 " -a Use alg as the algorithm, can be rsa, dh, dsa or fee (default rsa)\n"
204 " -s Specify the keysize in bits (default 512)\n"
205 " -f Make a key valid from the specified date\n"
206 " -t Make a key valid to the specified date\n"
207 " -d Make a key valid for the number of days specified from today\n"
208 " -k Use the specified keychain rather than the default\n"
209 " -A Allow any application to access this key without warning (insecure, not recommended!)\n"
210 " -T Specify an application which may access this key (multiple -T options are allowed)\n"
211 "If no options are provided, ask the user interactively.",
212 "Create a certificate signing request." },
213 #endif
214
215 { "add-generic-password", keychain_add_generic_password,
216 "[-a account] [-s service] [-w password] [options...] [-A|-T appPath] [keychain]\n"
217 " -a Specify account name (required)\n"
218 " -c Specify item creator (optional four-character code)\n"
219 " -C Specify item type (optional four-character code)\n"
220 " -D Specify kind (default is \"application password\")\n"
221 " -G Specify generic attribute (optional)\n"
222 " -j Specify comment string (optional)\n"
223 " -l Specify label (if omitted, service name is used as default label)\n"
224 " -s Specify service name (required)\n"
225 " -p Specify password to be added (legacy option, equivalent to -w)\n"
226 " -w Specify password to be added\n"
227 " -A Allow any application to access this item without warning (insecure, not recommended!)\n"
228 " -T Specify an application which may access this item (multiple -T options are allowed)\n"
229 " -U Update item if it already exists (if omitted, the item cannot already exist)\n"
230 "\n"
231 "By default, the application which creates an item is trusted to access its data without warning.\n"
232 "You can remove this default access by explicitly specifying an empty app pathname: -T \"\"\n"
233 "If no keychain is specified, the password is added to the default keychain.\n"
234 "Use of the -p or -w options is insecure. Specify -w as the last option to be prompted.\n",
235 "Add a generic password item."},
236
237 { "add-internet-password", keychain_add_internet_password,
238 "[-a account] [-s server] [-w password] [options...] [-A|-T appPath] [keychain]\n"
239 " -a Specify account name (required)\n"
240 " -c Specify item creator (optional four-character code)\n"
241 " -C Specify item type (optional four-character code)\n"
242 " -d Specify security domain string (optional)\n"
243 " -D Specify kind (default is \"Internet password\")\n"
244 " -j Specify comment string (optional)\n"
245 " -l Specify label (if omitted, server name is used as default label)\n"
246 " -p Specify path string (optional)\n"
247 " -P Specify port number (optional)\n"
248 " -r Specify protocol (optional four-character SecProtocolType, e.g. \"http\", \"ftp \")\n"
249 " -s Specify server name (required)\n"
250 " -t Specify authentication type (as a four-character SecAuthenticationType, default is \"dflt\")\n"
251 " -w Specify password to be added\n"
252 " -A Allow any application to access this item without warning (insecure, not recommended!)\n"
253 " -T Specify an application which may access this item (multiple -T options are allowed)\n"
254 " -U Update item if it already exists (if omitted, the item cannot already exist)\n"
255 "\n"
256 "By default, the application which creates an item is trusted to access its data without warning.\n"
257 "You can remove this default access by explicitly specifying an empty app pathname: -T \"\"\n"
258 "If no keychain is specified, the password is added to the default keychain.\n"
259 "Use of the -p or -w options is insecure. Specify -w as the last option to be prompted.\n",
260 "Add an internet password item."},
261
262 { "add-certificates", keychain_add_certificates,
263 "[-k keychain] file...\n"
264 "If no keychain is specified, the certificates are added to the default keychain.",
265 "Add certificates to a keychain."},
266
267 { "find-generic-password", keychain_find_generic_password,
268 "[-a account] [-s service] [options...] [-g] [keychain...]\n"
269 " -a Match \"account\" string\n"
270 " -c Match \"creator\" (four-character code)\n"
271 " -C Match \"type\" (four-character code)\n"
272 " -D Match \"kind\" string\n"
273 " -G Match \"value\" string (generic attribute)\n"
274 " -j Match \"comment\" string\n"
275 " -l Match \"label\" string\n"
276 " -s Match \"service\" string\n"
277 " -g Display the password for the item found\n"
278 " -w Display only the password on stdout\n"
279 "If no keychains are specified to search, the default search list is used.",
280 "Find a generic password item."},
281
282 { "delete-generic-password", keychain_delete_generic_password,
283 "[-a account] [-s service] [options...] [keychain...]\n"
284 " -a Match \"account\" string\n"
285 " -c Match \"creator\" (four-character code)\n"
286 " -C Match \"type\" (four-character code)\n"
287 " -D Match \"kind\" string\n"
288 " -G Match \"value\" string (generic attribute)\n"
289 " -j Match \"comment\" string\n"
290 " -l Match \"label\" string\n"
291 " -s Match \"service\" string\n"
292 "If no keychains are specified to search, the default search list is used.",
293 "Delete a generic password item."},
294
295 { "set-generic-password-partition-list", keychain_set_generic_password_partition_list,
296 "[-a account] [-s service] [-S partition-list] [-k keychain password] [options...] [keychain]\n"
297 " -a Match \"account\" string\n"
298 " -c Match \"creator\" (four-character code)\n"
299 " -C Match \"type\" (four-character code)\n"
300 " -D Match \"kind\" string\n"
301 " -G Match \"value\" string (generic attribute)\n"
302 " -j Match \"comment\" string\n"
303 " -l Match \"label\" string\n"
304 " -s Match \"service\" string\n"
305 " -S Comma-separated list of allowed partition IDs\n"
306 " -k The password for the keychain (required)\n"
307 "If no keychains are specified to search, the default search list is used.\n"
308 "Use of the -k option is insecure. Omit it to be prompted.\n",
309 "Set the partition list of a generic password item."},
310
311 { "find-internet-password", keychain_find_internet_password,
312 "[-a account] [-s server] [options...] [-g] [keychain...]\n"
313 " -a Match \"account\" string\n"
314 " -c Match \"creator\" (four-character code)\n"
315 " -C Match \"type\" (four-character code)\n"
316 " -d Match \"securityDomain\" string\n"
317 " -D Match \"kind\" string\n"
318 " -j Match \"comment\" string\n"
319 " -l Match \"label\" string\n"
320 " -p Match \"path\" string\n"
321 " -P Match port number\n"
322 " -r Match \"protocol\" (four-character code)\n"
323 " -s Match \"server\" string\n"
324 " -t Match \"authenticationType\" (four-character code)\n"
325 " -g Display the password for the item found\n"
326 " -w Display only the password on stdout\n"
327 "If no keychains are specified to search, the default search list is used.",
328 "Find an internet password item."},
329
330 { "delete-internet-password", keychain_delete_internet_password,
331 "[-a account] [-s server] [options...] [keychain...]\n"
332 " -a Match \"account\" string\n"
333 " -c Match \"creator\" (four-character code)\n"
334 " -C Match \"type\" (four-character code)\n"
335 " -d Match \"securityDomain\" string\n"
336 " -D Match \"kind\" string\n"
337 " -j Match \"comment\" string\n"
338 " -l Match \"label\" string\n"
339 " -p Match \"path\" string\n"
340 " -P Match port number\n"
341 " -r Match \"protocol\" (four-character code)\n"
342 " -s Match \"server\" string\n"
343 " -t Match \"authenticationType\" (four-character code)\n"
344 "If no keychains are specified to search, the default search list is used.",
345 "Delete an internet password item."},
346
347 { "set-internet-password-partition-list", keychain_set_internet_password_partition_list,
348 "[-a account] [-s service] [-S partition-list] [-k keychain password] [options...] [keychain]\n"
349 " -a Match \"account\" string\n"
350 " -c Match \"creator\" (four-character code)\n"
351 " -C Match \"type\" (four-character code)\n"
352 " -d Match \"securityDomain\" string\n"
353 " -D Match \"kind\" string\n"
354 " -j Match \"comment\" string\n"
355 " -l Match \"label\" string\n"
356 " -p Match \"path\" string\n"
357 " -P Match port number\n"
358 " -r Match \"protocol\" (four-character code)\n"
359 " -s Match \"server\" string\n"
360 " -t Match \"authenticationType\" (four-character code)\n"
361 " -S Comma-separated list of allowed partition IDs\n"
362 " -k password for keychain (required)\n"
363
364 "If no keychains are specified to search, the default search list is used.\n"
365 "Use of the -k option is insecure. Omit it to be prompted.\n",
366 "Set the partition list of a internet password item."},
367
368 { "find-key", keychain_find_key,
369 "[options...] [keychain...]\n"
370 " -a Match \"application label\" string\n"
371 " -c Match \"creator\" (four-character code)\n"
372 " -d Match keys that can decrypt\n"
373 " -D Match \"description\" string\n"
374 " -e Match keys that can encrypt\n"
375 " -j Match \"comment\" string\n"
376 " -l Match \"label\" string\n"
377 " -r Match keys that can derive\n"
378 " -s Match keys that can sign\n"
379 " -t Type of key to find: one of \"symmetric\", \"public\", or \"private\"\n"
380 " -u Match keys that can unwrap\n"
381 " -v Match keys that can verify\n"
382 " -w Match keys that can wrap\n"
383
384 "If no keychains are specified to search, the default search list is used.",
385 "Find keys in the keychain"},
386
387 { "set-key-partition-list", keychain_set_key_partition_list,
388 "[options...] [keychain]\n"
389 " -a Match \"application label\" string\n"
390 " -c Match \"creator\" (four-character code)\n"
391 " -d Match keys that can decrypt\n"
392 " -D Match \"description\" string\n"
393 " -e Match keys that can encrypt\n"
394 " -j Match \"comment\" string\n"
395 " -l Match \"label\" string\n"
396 " -r Match keys that can derive\n"
397 " -s Match keys that can sign\n"
398 " -t Type of key to find: one of \"symmetric\", \"public\", or \"private\"\n"
399 " -u Match keys that can unwrap\n"
400 " -v Match keys that can verify\n"
401 " -w Match keys that can wrap\n"
402 " -S Comma-separated list of allowed partition IDs\n"
403 " -k password for keychain (required)\n"
404
405 "If no keychains are specified to search, the default search list is used.",
406 "Set the partition list of a key."},
407
408 { "find-certificate", keychain_find_certificate,
409 "[-a] [-c name] [-e emailAddress] [-m] [-p] [-Z] [keychain...]\n"
410 " -a Find all matching certificates, not just the first one\n"
411 " -c Match on \"name\" when searching (optional)\n"
412 " -e Match on \"emailAddress\" when searching (optional)\n"
413 " -m Show the email addresses in the certificate\n"
414 " -p Output certificate in pem format\n"
415 " -Z Print SHA-1 hash of the certificate\n"
416 "If no keychains are specified to search, the default search list is used.",
417 "Find a certificate item."},
418
419 { "find-identity", keychain_find_identity,
420 "[-p policy] [-s string] [-v] [keychain...]\n"
421 " -p Specify policy to evaluate (multiple -p options are allowed)\n"
422 " Supported policies: basic, ssl-client, ssl-server, smime, eap,\n"
423 " ipsec, ichat, codesigning, sys-default, sys-kerberos-kdc, macappstore, appleID\n"
424 " -s Specify optional policy-specific string (e.g. DNS hostname for SSL,\n"
425 " or RFC822 email address for S/MIME)\n"
426 " -v Show valid identities only (default is to show all identities)\n"
427 "If no keychains are specified to search, the default search list is used.",
428 "Find an identity (certificate + private key)."},
429
430 { "delete-certificate", keychain_delete_certificate,
431 "[-c name] [-Z hash] [-t] [keychain...]\n"
432 " -c Specify certificate to delete by its common name\n"
433 " -Z Specify certificate to delete by its SHA-1 hash value\n"
434 " -t Also delete user trust settings for this certificate\n"
435 "The certificate to be deleted must be uniquely specified either by a\n"
436 "string found in its common name, or by its SHA-1 hash.\n"
437 "If no keychains are specified to search, the default search list is used.",
438 "Delete a certificate from a keychain."},
439
440 { "delete-identity", keychain_delete_identity,
441 "[-c name] [-Z hash] [-t] [keychain...]\n"
442 " -c Specify certificate to delete by its common name\n"
443 " -Z Specify certificate to delete by its SHA-1 hash value\n"
444 " -t Also delete user trust settings for this identity certificate\n"
445 "The identity to be deleted must be uniquely specified either by a\n"
446 "string found in its common name, or by its SHA-1 hash.\n"
447 "If no keychains are specified to search, the default search list is used.",
448 "Delete an identity (certificate + private key) from a keychain."},
449
450 { "set-identity-preference", set_identity_preference,
451 "[-n] [-c identity] [-s service] [-u keyUsage] [-Z hash] [keychain...]\n"
452 " -n Specify no identity (clears existing preference for service)\n"
453 " -c Specify identity by common name of the certificate\n"
454 " -s Specify service (may be a URL, RFC822 email address, DNS host, or\n"
455 " other name) for which this identity is to be preferred\n"
456 " -u Specify key usage (optional) - see man page for values\n"
457 " -Z Specify identity by SHA-1 hash of certificate (optional)\n",
458 "Set the preferred identity to use for a service."},
459
460 { "get-identity-preference", get_identity_preference,
461 "[-s service] [-u keyUsage] [-p] [-c] [-Z] [keychain...]\n"
462 " -s Specify service (may be a URL, RFC822 email address, DNS host, or\n"
463 " other name)\n"
464 " -u Specify key usage (optional) - see man page for values\n"
465 " -p Output identity certificate in pem format\n"
466 " -c Print common name of the preferred identity certificate\n"
467 " -Z Print SHA-1 hash of the preferred identity certificate\n",
468 "Get the preferred identity to use for a service."},
469
470 { "create-db", db_create,
471 "[-ao0] [-g dl|cspdl] [-m mode] [name]\n"
472 " -a Turn off autocommit\n"
473 " -g Attach to \"guid\" rather than the AppleFileDL\n"
474 " -m Set the inital mode of the created db to \"mode\"\n"
475 " -o Force using openparams argument\n"
476 " -0 Force using version 0 openparams\n"
477 "If no name is provided, ask the user interactively.",
478 "Create a db using the DL." },
479
480 { "export" , keychain_export,
481 "[-k keychain] [-t type] [-f format] [-w] [-p] [-P passphrase] [-o outfile]\n"
482 " -k keychain to export items from\n"
483 " -t Type = certs|allKeys|pubKeys|privKeys|identities|all (Default: all)\n"
484 " -f Format = openssl|openssh1|openssh2|bsafe|pkcs7|pkcs8|pkcs12|pemseq|x509\n"
485 " ...default format is pemseq for aggregate, openssl for single\n"
486 " -w Private keys are wrapped\n"
487 " -p PEM encode the output\n"
488 " -P Specify wrapping passphrase immediately (default is secure passphrase via GUI)\n"
489 " -o Specify output file (default is stdout)\n"
490 "Use of the -P option is insecure\n",
491 "Export items from a keychain." },
492
493 { "import", keychain_import,
494 "inputfile [-k keychain] [-t type] [-f format] [-w] [-P passphrase] [options...]\n"
495 " -k Target keychain to import into\n"
496 " -t Type = pub|priv|session|cert|agg\n"
497 " -f Format = openssl|openssh1|openssh2|bsafe|raw|pkcs7|pkcs8|pkcs12|netscape|pemseq\n"
498 " -w Specify that private keys are wrapped and must be unwrapped on import\n"
499 " -x Specify that private keys are non-extractable after being imported\n"
500 " -P Specify wrapping passphrase immediately (default is secure passphrase via GUI)\n"
501 " -a Specify name and value of extended attribute (can be used multiple times)\n"
502 " -A Allow any application to access the imported key without warning (insecure, not recommended!)\n"
503 " -T Specify an application which may access the imported key (multiple -T options are allowed)\n"
504 "Use of the -P option is insecure\n",
505 "Import items into a keychain." },
506
507 { "export-smartcard" , ctk_export,
508 "[-i id] [-t type] \n"
509 " -i id of the smartcard to export (available IDs can be listed by list-smartcards\n"
510 " command, default: export all smartcards)\n"
511 " -t Type = certs|privKeys|identities|all (Default: all)\n",
512 "Export items from a smartcard." },
513
514 { "cms", cms_util,
515 "[-C|-D|-E|-S] [<options>]\n"
516 " -C create a CMS encrypted message\n"
517 " -D decode a CMS message\n"
518 " -E create a CMS enveloped message\n"
519 " -S create a CMS signed message\n"
520 "\n"
521 "Decoding options:\n"
522 " -c content use this detached content file\n"
523 " -h level generate email headers with info about CMS message\n"
524 " (output level >= 0)\n"
525 " -n suppress output of content\n"
526 "\n"
527 "Encoding options:\n"
528 " -r id,... create envelope for these recipients,\n"
529 " where id can be a certificate nickname or email address\n"
530 " -G include a signing time attribute\n"
531 " -H hash hash = MD2|MD4|MD5|SHA1|SHA256|SHA384|SHA512 (default: SHA1)\n"
532 " -N nick use certificate named \"nick\" for signing\n"
533 " -P include a SMIMECapabilities attribute\n"
534 " -T do not include content in CMS message\n"
535 " -Y nick include an EncryptionKeyPreference attribute with certificate\n"
536 " (use \"NONE\" to omit)\n"
537 " -Z hash find a certificate by subject key ID\n"
538 "\n"
539 "Common options:\n"
540 " -e envelope specify envelope file (valid with -D or -E)\n"
541 " -k keychain specify keychain to use\n"
542 " -i infile use infile as source of data (default: stdin)\n"
543 " -o outfile use outfile as destination of data (default: stdout)\n"
544 " -p password use password as key db password (default: prompt). Using -p is insecure\n"
545 " -s pass data a single byte at a time to CMS\n"
546 " -u certusage set type of certificate usage (default: certUsageEmailSigner)\n"
547 " -v print debugging information\n"
548 "\n"
549 "Cert usage codes:\n"
550 " 0 - certUsageSSLClient\n"
551 " 1 - certUsageSSLServer\n"
552 " 2 - certUsageSSLServerWithStepUp\n"
553 " 3 - certUsageSSLCA\n"
554 " 4 - certUsageEmailSigner\n"
555 " 5 - certUsageEmailRecipient\n"
556 " 6 - certUsageObjectSigner\n"
557 " 7 - certUsageUserCertImport\n"
558 " 8 - certUsageVerifyCA\n"
559 " 9 - certUsageProtectedObjectSigner\n"
560 " 10 - certUsageStatusResponder\n"
561 " 11 - certUsageAnyCA",
562 "Encode or decode CMS messages." },
563
564 { "install-mds" , mds_install,
565 "", /* no options */
566 "Install (or re-install) the MDS database." },
567
568 { "add-trusted-cert" , trusted_cert_add,
569 " [<options>] [certFile]\n"
570 " -d Add to admin cert store; default is user\n"
571 " -r resultType resultType = trustRoot|trustAsRoot|deny|unspecified;\n"
572 " default is trustRoot\n"
573 " -p policy Specify policy constraint (ssl, smime, codeSign, IPSec, iChat,\n"
574 " basic, swUpdate, pkgSign, pkinitClient, pkinitServer, eap)\n"
575 " -a appPath Specify application constraint\n"
576 " -s policyString Specify policy-specific string\n"
577 " -e allowedError Specify allowed error (certExpired, hostnameMismatch) or integer\n"
578 " -u keyUsage Specify key usage, an integer\n"
579 " -k keychain Specify keychain to which cert is added\n"
580 " -i settingsFileIn Input trust settings file; default is user domain\n"
581 " -o settingsFileOut Output trust settings file; default is user domain\n"
582 " certFile Certificate(s)",
583 "Add trusted certificate(s)." },
584
585 { "remove-trusted-cert" , trusted_cert_remove,
586 " [-d] [-D] [certFile]\n"
587 " -d Remove from admin cert store (default is user)\n"
588 " -D Remove default setting instead of per-cert setting\n"
589 " certFile Certificate(s)",
590 "Remove trusted certificate(s)." },
591
592 { "dump-trust-settings" , trusted_cert_dump,
593 " [-s] [-d]\n"
594 " -s Display trusted system certs (default is user)\n"
595 " -d Display trusted admin certs (default is user)\n",
596 "Display contents of trust settings." },
597
598 { "user-trust-settings-enable", user_trust_enable,
599 "[-d] [-e]\n"
600 " -d Disable user-level trust Settings\n"
601 " -e Enable user-level trust Settings\n"
602 "With no parameters, show current enable state of user-level trust settings.",
603 "Display or manipulate user-level trust settings." },
604
605 { "trust-settings-export", trust_settings_export,
606 " [-s] [-d] settings_file\n"
607 " -s Export system trust settings (default is user)\n"
608 " -d Export admin trust settings (default is user)\n",
609 "Export trust settings." },
610
611 { "trust-settings-import", trust_settings_import,
612 " [-d] settings_file\n"
613 " -d Import admin trust settings (default is user)\n",
614 "Import trust settings." },
615
616 { "verify-cert" , verify_cert,
617 " [<options>]\n"
618 " -c certFile Certificate to verify. Can be specified multiple times, leaf first.\n"
619 " -r rootCertFile Root Certificate. Can be specified multiple times.\n"
620 " -p policy Verify Policy (basic, ssl, smime, codeSign, IPSec, swUpdate, pkgSign,\n"
621 " eap, appleID, macappstore, timestamping); default is basic.\n"
622 " -C Set client policy to true. Default is server policy. (ssl, IPSec, eap)\n"
623 " -d date Set date and time to use when verifying certificate,\n"
624 " provided in the form of YYYY-MM-DD-hh:mm:ss (time optional) in GMT.\n"
625 " e.g: 2016-04-25-15:59:59 for April 25, 2016 at 3:59:59 pm in GMT\n"
626 " -k keychain Keychain. Can be specified multiple times. Default is default search list.\n"
627 " -n name Name to be verified. (ssl, IPSec, smime)\n"
628 " -N No keychain search list. (For backward compatibility, -n without a\n"
629 " subsequent name argument is interpreted as equivalent to -N.)\n"
630 " -L Local certificates only (do not try to fetch missing CA certs from net).\n"
631 " -l Leaf cert is a CA (normally an error, unless this option is given).\n"
632 " -e emailAddress Email address for smime policy. (Deprecated; use -n instead.)\n"
633 " -s sslHost SSL host name for ssl policy. (Deprecated; use -n instead.)\n"
634 " -q Quiet.\n"
635 " -R revCheckOption Perform revocation checking with one of the following options:\n"
636 " ocsp Check revocation status using OCSP method.\n"
637 " crl Check revocation status using CRL method.\n"
638 " require Require a positive response for successful verification.\n"
639 " offline Consult cached responses only (no network requests).\n"
640 " Can be specified multiple times; e.g. to enable revocation checking\n"
641 " via either OCSP or CRL methods and require a positive response, use\n"
642 " \"-R ocsp -R crl -R require\".\n",
643 "Verify certificate(s)." },
644
645 { "authorize" , authorize,
646 "[<options>] <right(s)...>\n"
647 " -u Allow user interaction.\n"
648 " -c Use login name and prompt for password.\n"
649 " -C login Use given login name and prompt for password.\n"
650 " -x Do NOT share -c/-C explicit credentials\n"
651 #ifndef NDEBUG
652 " -E Don't extend rights.\n"
653 #endif
654 " -p Allow returning partial rights.\n"
655 " -d Destroy acquired rights.\n"
656 " -P Pre-authorize rights only.\n"
657 " -l Operate authorizations in least privileged mode.\n"
658 " -i Internalize authref passed on stdin.\n"
659 " -e Externalize authref to stdout.\n"
660 " -w Wait until stdout is closed (to allow reading authref from pipe).\n"
661 "Extend rights flag is passed per default.",
662 "Perform authorization operations." },
663
664 { "authorizationdb" , authorizationdb,
665 "read <right-name>\n"
666 " authorizationdb remove <right-name>\n"
667 " authorizationdb write <right-name> [allow|deny|<rulename>]\n"
668 "If no rulename is specified, write will read a plist from stdin.\n"
669 " authorizationdb merge source [destination]\n"
670 "If no destination path is specified, merge will merge to /etc/authorization.\n"
671 " authorizationdb smartcard <enable|disable|status>\n"
672 "Enables/disables smartcard login support or report current status.",
673 "Make changes to the authorization policy database." },
674
675 { "execute-with-privileges" , execute_with_privileges,
676 "<program> [args...]\n"
677 "On success, stdin will be read and forwarded to the tool.",
678 "Execute tool with privileges." },
679
680 { "leaks", leaks,
681 "[-cycles] [-nocontext] [-nostacks] [-exclude symbol]\n"
682 " -cycles Use a stricter algorithm (\"man leaks\" for details)\n"
683 " -nocontext Withhold hex dumps of the leaked memory\n"
684 " -nostacks Don't show stack traces of leaked memory\n"
685 " -exclude Ignore leaks called from \"symbol\"\n"
686 "(Set the environment variable MallocStackLogging to get symbolic traces.)",
687 "Run /usr/bin/leaks on this process." },
688
689 { "error", display_error_code,
690 "<error code(s)...>\n"
691 "Display an error string for the given security-related error code.\n"
692 "The error can be in decimal or hex, e.g. 1234 or 0x1234. Multiple "
693 "errors can be separated by spaces.",
694 "Display a descriptive message for the given error code(s)." },
695
696 { "create-filevaultmaster-keychain", keychain_createMFV,
697 "[-p password] [keychain name]\n"
698 " -p Use \"password\" as the password for the keychain being created\n"
699 " -s Specify the keysize in bits (default 2048; 1024 & 4096 are allowed)\n"
700 "By default the keychain will be created in ~/Library/Keychains/.\n"
701 "Use of the -p option is insecure. Omit it to be prompted.\n",
702 "Create a keychain containing a key pair for FileVault recovery use."
703 },
704
705 { "smartcards" , smartcards,
706 "token [-l] [-e token] [-d token]\n"
707 " -l List disabled smartcard tokens]\n"
708 " -e token Enable specified token\n"
709 " -d token Disable specified token\n",
710 "Enable, disable or list disabled smartcard tokens." },
711
712 { "translocate-create", translocate_create,
713 "<path to translocate>\n"
714 "Displays the created path or the error returned.",
715 "Create a translocation point for the provided path" },
716
717 { "translocate-policy-check", translocate_policy,
718 "<path to check>\n"
719 "Displays \"Would translocate\" or \"Would not translocate\"\n"
720 "based on the current state of the path and system policy.",
721 "Check whether a path would be translocated." },
722
723 { "translocate-status-check", translocate_check,
724 "<path to check>\n"
725 "Displays \"TRANSLOCATED\" or \"NOT TRANSLOCATED\"\n"
726 "for the given path.",
727 "Check whether a path is translocated." },
728
729 { "translocate-original-path", translocate_original_path,
730 "<path to check>\n"
731 "If the provided path is translocated, display the original path\n"
732 "If the provided path is not translocated, display the passed in path",
733 "Find the original path for a translocated path." },
734 {}
735 };
736
737 /* Global variables. */
738 int do_quiet = 0;
739 int do_verbose = 0;
740
741 /* Return 1 if name matches command. */
742 static int
743 match_command(const char *command, const char *name)
744 {
745 return !strncmp(command, name, strlen(name));
746 }
747
748 /* The help command. */
749 static int
750 help(int argc, char * const *argv)
751 {
752 const command *c;
753
754 if (argc > 1)
755 {
756 char * const *arg;
757 for (arg = argv + 1; *arg; ++arg)
758 {
759 int found = 0;
760
761 for (c = commands; c->c_name; ++c)
762 {
763 if (match_command(c->c_name, *arg))
764 {
765 found = 1;
766 break;
767 }
768 }
769
770 if (found)
771 printf("Usage: %s %s\n", c->c_name, c->c_usage);
772 else
773 {
774 sec_error("%s: no such command: %s", argv[0], *arg);
775 return 1;
776 }
777 }
778 }
779 else
780 {
781 for (c = commands; c->c_name; ++c)
782 printf(" %-36s %s\n", c->c_name, c->c_help);
783 }
784
785 return 0;
786 }
787
788 /* States for split_line parser. */
789 typedef enum
790 {
791 SKIP_WS,
792 READ_ARG,
793 READ_ARG_ESCAPED,
794 QUOTED_ARG,
795 QUOTED_ARG_ESCAPED
796 } parse_state;
797
798 /* Split a line into multiple arguments and return them in *pargc and *pargv. */
799 static void
800 split_line(char *line, int *pargc, char * const **pargv)
801 {
802 static char *argvec[MAX_ARGS + 1];
803 int argc = 0;
804 char *ptr = line;
805 char *dst = line;
806 parse_state state = SKIP_WS;
807 int quote_ch = 0;
808
809 for (ptr = line; *ptr; ++ptr)
810 {
811 if (state == SKIP_WS)
812 {
813 if (isspace(*ptr))
814 continue;
815
816 if (*ptr == '"' || *ptr == '\'')
817 {
818 quote_ch = *ptr;
819 state = QUOTED_ARG;
820 argvec[argc] = dst;
821 continue; /* Skip the quote. */
822 }
823 else
824 {
825 state = READ_ARG;
826 argvec[argc] = dst;
827 }
828 }
829
830 if (state == READ_ARG)
831 {
832 if (*ptr == '\\')
833 {
834 state = READ_ARG_ESCAPED;
835 continue;
836 }
837 else if (isspace(*ptr))
838 {
839 /* 0 terminate each arg. */
840 *dst++ = '\0';
841 argc++;
842 state = SKIP_WS;
843 if (argc >= MAX_ARGS)
844 break;
845 }
846 else
847 *dst++ = *ptr;
848 }
849
850 if (state == QUOTED_ARG)
851 {
852 if (*ptr == '\\')
853 {
854 state = QUOTED_ARG_ESCAPED;
855 continue;
856 }
857 if (*ptr == quote_ch)
858 {
859 /* 0 terminate each arg. */
860 *dst++ = '\0';
861 argc++;
862 state = SKIP_WS;
863 if (argc >= MAX_ARGS)
864 break;
865 }
866 else
867 *dst++ = *ptr;
868 }
869
870 if (state == READ_ARG_ESCAPED)
871 {
872 *dst++ = *ptr;
873 state = READ_ARG;
874 }
875
876 if (state == QUOTED_ARG_ESCAPED)
877 {
878 *dst++ = *ptr;
879 state = QUOTED_ARG;
880 }
881 }
882
883 if (state != SKIP_WS)
884 {
885 /* Terminate last arg. */
886 *dst++ = '\0';
887 argc++;
888 }
889
890 /* Teminate arg vector. */
891 argvec[argc] = NULL;
892
893 *pargv = argvec;
894 *pargc = argc;
895 }
896
897 /* Print a (hopefully) useful usage message. */
898 static int
899 usage(void)
900 {
901 printf(
902 "Usage: %s [-h] [-i] [-l] [-p prompt] [-q] [-v] [command] [opt ...]\n"
903 " -i Run in interactive mode.\n"
904 " -l Run /usr/bin/leaks -nocontext before exiting.\n"
905 " -p Set the prompt to \"prompt\" (implies -i).\n"
906 " -q Be less verbose.\n"
907 " -v Be more verbose about what's going on.\n"
908 "%s commands are:\n", getprogname(), getprogname());
909 help(0, NULL);
910 return SHOW_USAGE_MESSAGE;
911 }
912
913 /* Execute a single command. */
914 static int
915 execute_command(int argc, char * const *argv)
916 {
917 const command *c;
918 int found = 0;
919
920 /* Nothing to do. */
921 if (argc == 0)
922 return 0;
923
924 for (c = commands; c->c_name; ++c)
925 {
926 if (match_command(c->c_name, argv[0]))
927 {
928 found = 1;
929 break;
930 }
931 }
932
933 if (found)
934 {
935 int result;
936
937 /* Reset getopt for command proc. */
938 optind = 1;
939 optreset = 1;
940
941 if (do_verbose)
942 {
943 int ix;
944
945 fprintf(stderr, "%s", c->c_name);
946 for (ix = 1; ix < argc; ++ix)
947 fprintf(stderr, " \"%s\"", argv[ix]);
948 fprintf(stderr, "\n");
949 }
950
951 result = c->c_func(argc, argv);
952 if (result == 2)
953 fprintf(stderr, "Usage: %s %s\n %s\n", c->c_name, c->c_usage, c->c_help);
954
955 return result;
956 }
957 else
958 {
959 sec_error("unknown command \"%s\"", argv[0]);
960 return 1;
961 }
962 }
963
964 static void
965 receive_notifications(void)
966 {
967 /* Run the CFRunloop to get any pending notifications. */
968 while (CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.0, TRUE) == kCFRunLoopRunHandledSource);
969 }
970
971
972 const char *
973 sec_errstr(int err)
974 {
975 const char *errString;
976 if (IS_SEC_ERROR(err))
977 errString = SECErrorString(err);
978 else
979 errString = cssmErrorString(err);
980 return errString;
981 }
982
983 void
984 sec_error(const char *msg, ...)
985 {
986 va_list args;
987
988 fprintf(stderr, "%s: ", getprogname());
989
990 va_start(args, msg);
991 vfprintf(stderr, msg, args);
992 va_end(args);
993
994 fprintf(stderr, "\n");
995 }
996
997 void
998 sec_perror(const char *msg, int err)
999 {
1000 sec_error("%s: %s", msg, sec_errstr(err));
1001 }
1002
1003 int
1004 main(int argc, char * const *argv)
1005 {
1006 int result = 0;
1007 int do_help = 0;
1008 int do_interactive = 0;
1009 int do_leaks = 0;
1010 int ch;
1011
1012
1013 /* Do getopt stuff for global options. */
1014 optind = 1;
1015 optreset = 1;
1016 while ((ch = getopt(argc, argv, "hilp:qvR")) != -1)
1017 {
1018 switch (ch)
1019 {
1020 case 'h':
1021 do_help = 1;
1022 break;
1023 case 'i':
1024 do_interactive = 1;
1025 break;
1026 case 'l':
1027 do_leaks = 1;
1028 break;
1029 case 'p':
1030 do_interactive = 1;
1031 prompt_string = optarg;
1032 break;
1033 case 'q':
1034 do_quiet = 1;
1035 break;
1036 case 'v':
1037 do_verbose = 1;
1038 break;
1039 case 'R':
1040 // "Recovery mode", do NOT ask security-checksystem to run when using keychain APIs
1041 // NOTE: this is a hidden option (not in the usage message)
1042 SecKeychainSystemKeychainCheckWouldDeadlock();
1043 break;
1044 case '?':
1045 default:
1046 return usage();
1047 }
1048 }
1049
1050 argc -= optind;
1051 argv += optind;
1052
1053 if (do_help)
1054 {
1055 /* Munge argc/argv so that argv[0] is something. */
1056 return help(argc + 1, argv - 1);
1057 }
1058 else if (argc > 0)
1059 {
1060 receive_notifications();
1061 result = execute_command(argc, argv);
1062 receive_notifications();
1063 }
1064 else if (do_interactive)
1065 {
1066 /* In interactive mode we just read commands and run them until readline returns NULL. */
1067
1068 /* Only show prompt string if stdin is a tty. */
1069 int show_prompt = isatty(0);
1070
1071 for (;;)
1072 {
1073 static char buffer[MAX_LINE_LEN];
1074 char * const *av, *input;
1075 int ac;
1076
1077 if (show_prompt)
1078 fprintf(stderr, "%s", prompt_string);
1079
1080 input = readline(buffer, MAX_LINE_LEN);
1081 if (!input)
1082 break;
1083
1084 split_line(input, &ac, &av);
1085 receive_notifications();
1086 result = execute_command(ac, av);
1087 receive_notifications();
1088 if (result == -1)
1089 {
1090 result = 0;
1091 break;
1092 }
1093
1094 if (result && ! do_quiet)
1095 {
1096 fprintf(stderr, "%s: returned %d\n", av[0], result);
1097 }
1098 }
1099 }
1100 else
1101 result = usage();
1102
1103 if (do_leaks)
1104 {
1105 char *const argvec[3] = { "leaks", "-nocontext", NULL };
1106 leaks(2, argvec);
1107 }
1108
1109 return result;
1110 }