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