]> git.saurik.com Git - apple/security.git/blob - SecurityTool/security.c
Security-58286.251.4.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] [-e exportPath] \n"
509 " -i id of the smartcard to export (available IDs can be listed by list-smartcards\n"
510 " command, default: export/display all smartcards)\n"
511 " -t Type = certs|privKeys|identities|all (Default: all)\n"
512 " -e Specify path to export certificates and public keys. This option cannot be combined with -t option.\n",
513 "Export items from a smartcard." },
514
515 { "cms", cms_util,
516 "[-C|-D|-E|-S] [<options>]\n"
517 " -C create a CMS encrypted message\n"
518 " -D decode a CMS message\n"
519 " -E create a CMS enveloped message\n"
520 " -S create a CMS signed message\n"
521 "\n"
522 "Decoding options:\n"
523 " -c content use this detached content file\n"
524 " -h level generate email headers with info about CMS message\n"
525 " (output level >= 0)\n"
526 " -n suppress output of content\n"
527 "\n"
528 "Encoding options:\n"
529 " -r id,... create envelope for these recipients,\n"
530 " where id can be a certificate nickname or email address\n"
531 " -G include a signing time attribute\n"
532 " -H hash hash = MD2|MD4|MD5|SHA1|SHA256|SHA384|SHA512 (default: SHA1)\n"
533 " -N nick use certificate named \"nick\" for signing\n"
534 " -P include a SMIMECapabilities attribute\n"
535 " -T do not include content in CMS message\n"
536 " -Y nick include an EncryptionKeyPreference attribute with certificate\n"
537 " (use \"NONE\" to omit)\n"
538 " -Z hash find a certificate by subject key ID\n"
539 "\n"
540 "Common options:\n"
541 " -e envelope specify envelope file (valid with -D or -E)\n"
542 " -k keychain specify keychain to use\n"
543 " -i infile use infile as source of data (default: stdin)\n"
544 " -o outfile use outfile as destination of data (default: stdout)\n"
545 " -p password use password as key db password (default: prompt). Using -p is insecure\n"
546 " -s pass data a single byte at a time to CMS\n"
547 " -u certusage set type of certificate usage (default: certUsageEmailSigner)\n"
548 " -v print debugging information\n"
549 "\n"
550 "Cert usage codes:\n"
551 " 0 - certUsageSSLClient\n"
552 " 1 - certUsageSSLServer\n"
553 " 2 - certUsageSSLServerWithStepUp\n"
554 " 3 - certUsageSSLCA\n"
555 " 4 - certUsageEmailSigner\n"
556 " 5 - certUsageEmailRecipient\n"
557 " 6 - certUsageObjectSigner\n"
558 " 7 - certUsageUserCertImport\n"
559 " 8 - certUsageVerifyCA\n"
560 " 9 - certUsageProtectedObjectSigner\n"
561 " 10 - certUsageStatusResponder\n"
562 " 11 - certUsageAnyCA",
563 "Encode or decode CMS messages." },
564
565 { "install-mds" , mds_install,
566 "", /* no options */
567 "Install (or re-install) the MDS database." },
568
569 { "add-trusted-cert" , trusted_cert_add,
570 " [<options>] [certFile]\n"
571 " -d Add to admin cert store; default is user\n"
572 " -r resultType resultType = trustRoot|trustAsRoot|deny|unspecified;\n"
573 " default is trustRoot\n"
574 " -p policy Specify policy constraint (ssl, smime, codeSign, IPSec, iChat,\n"
575 " basic, swUpdate, pkgSign, pkinitClient, pkinitServer, eap)\n"
576 " -a appPath Specify application constraint\n"
577 " -s policyString Specify policy-specific string\n"
578 " -e allowedError Specify allowed error (certExpired, hostnameMismatch) or integer\n"
579 " -u keyUsage Specify key usage, an integer\n"
580 " -k keychain Specify keychain to which cert is added\n"
581 " -i settingsFileIn Input trust settings file; default is user domain\n"
582 " -o settingsFileOut Output trust settings file; default is user domain\n"
583 " certFile Certificate(s)",
584 "Add trusted certificate(s)." },
585
586 { "remove-trusted-cert" , trusted_cert_remove,
587 " [-d] [-D] [certFile]\n"
588 " -d Remove from admin cert store (default is user)\n"
589 " -D Remove default setting instead of per-cert setting\n"
590 " certFile Certificate(s)",
591 "Remove trusted certificate(s)." },
592
593 { "dump-trust-settings" , trusted_cert_dump,
594 " [-s] [-d]\n"
595 " -s Display trusted system certs (default is user)\n"
596 " -d Display trusted admin certs (default is user)\n",
597 "Display contents of trust settings." },
598
599 { "user-trust-settings-enable", user_trust_enable,
600 "[-d] [-e]\n"
601 " -d Disable user-level trust Settings\n"
602 " -e Enable user-level trust Settings\n"
603 "With no parameters, show current enable state of user-level trust settings.",
604 "Display or manipulate user-level trust settings." },
605
606 { "trust-settings-export", trust_settings_export,
607 " [-s] [-d] settings_file\n"
608 " -s Export system trust settings (default is user)\n"
609 " -d Export admin trust settings (default is user)\n",
610 "Export trust settings." },
611
612 { "trust-settings-import", trust_settings_import,
613 " [-d] settings_file\n"
614 " -d Import admin trust settings (default is user)\n",
615 "Import trust settings." },
616
617 { "verify-cert" , verify_cert,
618 " [<options>]\n"
619 " -c certFile Certificate to verify. Can be specified multiple times, leaf first.\n"
620 " -r rootCertFile Root Certificate. Can be specified multiple times.\n"
621 " -p policy Verify Policy (basic, ssl, smime, codeSign, IPSec, swUpdate, pkgSign,\n"
622 " eap, appleID, macappstore, timestamping); default is basic.\n"
623 " -C Set client policy to true. Default is server policy. (ssl, IPSec, eap)\n"
624 " -d date Set date and time to use when verifying certificate,\n"
625 " provided in the form of YYYY-MM-DD-hh:mm:ss (time optional) in GMT.\n"
626 " e.g: 2016-04-25-15:59:59 for April 25, 2016 at 3:59:59 pm in GMT\n"
627 " -k keychain Keychain. Can be specified multiple times. Default is default search list.\n"
628 " -n name Name to be verified. (ssl, IPSec, smime)\n"
629 " -N No keychain search list. (For backward compatibility, -n without a\n"
630 " subsequent name argument is interpreted as equivalent to -N.)\n"
631 " -L Local certificates only (do not try to fetch missing CA certs from net).\n"
632 " -l Leaf cert is a CA (normally an error, unless this option is given).\n"
633 " -e emailAddress Email address for smime policy. (Deprecated; use -n instead.)\n"
634 " -s sslHost SSL host name for ssl policy. (Deprecated; use -n instead.)\n"
635 " -q Quiet.\n"
636 " -R revCheckOption Perform revocation checking with one of the following options:\n"
637 " ocsp Check revocation status using OCSP method.\n"
638 " crl Check revocation status using CRL method.\n"
639 " require Require a positive response for successful verification.\n"
640 " offline Consult cached responses only (no network requests).\n"
641 " Can be specified multiple times; e.g. to enable revocation checking\n"
642 " via either OCSP or CRL methods and require a positive response, use\n"
643 " \"-R ocsp -R crl -R require\".\n",
644 "Verify certificate(s)." },
645
646 { "authorize" , authorize,
647 "[<options>] <right(s)...>\n"
648 " -u Allow user interaction.\n"
649 " -c Use login name and prompt for password.\n"
650 " -C login Use given login name and prompt for password.\n"
651 " -x Do NOT share -c/-C explicit credentials\n"
652 #ifndef NDEBUG
653 " -E Don't extend rights.\n"
654 #endif
655 " -p Allow returning partial rights.\n"
656 " -d Destroy acquired rights.\n"
657 " -P Pre-authorize rights only.\n"
658 " -l Operate authorizations in least privileged mode.\n"
659 " -i Internalize authref passed on stdin.\n"
660 " -e Externalize authref to stdout.\n"
661 " -w Wait until stdout is closed (to allow reading authref from pipe).\n"
662 "Extend rights flag is passed per default.",
663 "Perform authorization operations." },
664
665 { "authorizationdb" , authorizationdb,
666 "read <right-name>\n"
667 " authorizationdb remove <right-name>\n"
668 " authorizationdb write <right-name> [allow|deny|<rulename>]\n"
669 "If no rulename is specified, write will read a plist from stdin.\n"
670 " authorizationdb merge source [destination]\n"
671 "If no destination path is specified, merge will merge to /etc/authorization.\n"
672 " authorizationdb smartcard <enable|disable|status>\n"
673 "Enables/disables smartcard login support or report current status.",
674 "Make changes to the authorization policy database." },
675
676 { "execute-with-privileges" , execute_with_privileges,
677 "<program> [args...]\n"
678 "On success, stdin will be read and forwarded to the tool.",
679 "Execute tool with privileges." },
680
681 { "leaks", leaks,
682 "[-cycles] [-nocontext] [-nostacks] [-exclude symbol]\n"
683 " -cycles Use a stricter algorithm (\"man leaks\" for details)\n"
684 " -nocontext Withhold hex dumps of the leaked memory\n"
685 " -nostacks Don't show stack traces of leaked memory\n"
686 " -exclude Ignore leaks called from \"symbol\"\n"
687 "(Set the environment variable MallocStackLogging to get symbolic traces.)",
688 "Run /usr/bin/leaks on this process." },
689
690 { "error", display_error_code,
691 "<error code(s)...>\n"
692 "Display an error string for the given security-related error code.\n"
693 "The error can be in decimal or hex, e.g. 1234 or 0x1234. Multiple "
694 "errors can be separated by spaces.",
695 "Display a descriptive message for the given error code(s)." },
696
697 { "create-filevaultmaster-keychain", keychain_createMFV,
698 "[-p password] [keychain name]\n"
699 " -p Use \"password\" as the password for the keychain being created\n"
700 " -s Specify the keysize in bits (default 2048; 1024 & 4096 are allowed)\n"
701 "By default the keychain will be created in ~/Library/Keychains/.\n"
702 "Use of the -p option is insecure. Omit it to be prompted.\n",
703 "Create a keychain containing a key pair for FileVault recovery use."
704 },
705
706 { "smartcards" , smartcards,
707 "token [-l] [-e token] [-d token]\n"
708 " -l List disabled smartcard tokens]\n"
709 " -e token Enable specified token\n"
710 " -d token Disable specified token\n",
711 "Enable, disable or list disabled smartcard tokens." },
712
713 { "translocate-create", translocate_create,
714 "<path to translocate>\n"
715 "Displays the created path or the error returned.",
716 "Create a translocation point for the provided path" },
717
718 { "translocate-policy-check", translocate_policy,
719 "<path to check>\n"
720 "Displays \"Would translocate\" or \"Would not translocate\"\n"
721 "based on the current state of the path and system policy.",
722 "Check whether a path would be translocated." },
723
724 { "translocate-status-check", translocate_check,
725 "<path to check>\n"
726 "Displays \"TRANSLOCATED\" or \"NOT TRANSLOCATED\"\n"
727 "for the given path.",
728 "Check whether a path is translocated." },
729
730 { "translocate-original-path", translocate_original_path,
731 "<path to check>\n"
732 "If the provided path is translocated, display the original path\n"
733 "If the provided path is not translocated, display the passed in path",
734 "Find the original path for a translocated path." },
735 {}
736 };
737
738 /* Global variables. */
739 int do_quiet = 0;
740 int do_verbose = 0;
741
742 /* Return 1 if name matches command. */
743 static int
744 match_command(const char *command, const char *name)
745 {
746 return !strncmp(command, name, strlen(name));
747 }
748
749 /* The help command. */
750 static int
751 help(int argc, char * const *argv)
752 {
753 const command *c;
754
755 if (argc > 1)
756 {
757 char * const *arg;
758 for (arg = argv + 1; *arg; ++arg)
759 {
760 int found = 0;
761
762 for (c = commands; c->c_name; ++c)
763 {
764 if (match_command(c->c_name, *arg))
765 {
766 found = 1;
767 break;
768 }
769 }
770
771 if (found)
772 printf("Usage: %s %s\n", c->c_name, c->c_usage);
773 else
774 {
775 sec_error("%s: no such command: %s", argv[0], *arg);
776 return 1;
777 }
778 }
779 }
780 else
781 {
782 for (c = commands; c->c_name; ++c)
783 printf(" %-36s %s\n", c->c_name, c->c_help);
784 }
785
786 return 0;
787 }
788
789 /* States for split_line parser. */
790 typedef enum
791 {
792 SKIP_WS,
793 READ_ARG,
794 READ_ARG_ESCAPED,
795 QUOTED_ARG,
796 QUOTED_ARG_ESCAPED
797 } parse_state;
798
799 /* Split a line into multiple arguments and return them in *pargc and *pargv. */
800 static void
801 split_line(char *line, int *pargc, char * const **pargv)
802 {
803 static char *argvec[MAX_ARGS + 1];
804 int argc = 0;
805 char *ptr = line;
806 char *dst = line;
807 parse_state state = SKIP_WS;
808 int quote_ch = 0;
809
810 for (ptr = line; *ptr; ++ptr)
811 {
812 if (state == SKIP_WS)
813 {
814 if (isspace(*ptr))
815 continue;
816
817 if (*ptr == '"' || *ptr == '\'')
818 {
819 quote_ch = *ptr;
820 state = QUOTED_ARG;
821 argvec[argc] = dst;
822 continue; /* Skip the quote. */
823 }
824 else
825 {
826 state = READ_ARG;
827 argvec[argc] = dst;
828 }
829 }
830
831 if (state == READ_ARG)
832 {
833 if (*ptr == '\\')
834 {
835 state = READ_ARG_ESCAPED;
836 continue;
837 }
838 else if (isspace(*ptr))
839 {
840 /* 0 terminate each arg. */
841 *dst++ = '\0';
842 argc++;
843 state = SKIP_WS;
844 if (argc >= MAX_ARGS)
845 break;
846 }
847 else
848 *dst++ = *ptr;
849 }
850
851 if (state == QUOTED_ARG)
852 {
853 if (*ptr == '\\')
854 {
855 state = QUOTED_ARG_ESCAPED;
856 continue;
857 }
858 if (*ptr == quote_ch)
859 {
860 /* 0 terminate each arg. */
861 *dst++ = '\0';
862 argc++;
863 state = SKIP_WS;
864 if (argc >= MAX_ARGS)
865 break;
866 }
867 else
868 *dst++ = *ptr;
869 }
870
871 if (state == READ_ARG_ESCAPED)
872 {
873 *dst++ = *ptr;
874 state = READ_ARG;
875 }
876
877 if (state == QUOTED_ARG_ESCAPED)
878 {
879 *dst++ = *ptr;
880 state = QUOTED_ARG;
881 }
882 }
883
884 if (state != SKIP_WS)
885 {
886 /* Terminate last arg. */
887 *dst++ = '\0';
888 argc++;
889 }
890
891 /* Teminate arg vector. */
892 argvec[argc] = NULL;
893
894 *pargv = argvec;
895 *pargc = argc;
896 }
897
898 /* Print a (hopefully) useful usage message. */
899 static int
900 usage(void)
901 {
902 printf(
903 "Usage: %s [-h] [-i] [-l] [-p prompt] [-q] [-v] [command] [opt ...]\n"
904 " -i Run in interactive mode.\n"
905 " -l Run /usr/bin/leaks -nocontext before exiting.\n"
906 " -p Set the prompt to \"prompt\" (implies -i).\n"
907 " -q Be less verbose.\n"
908 " -v Be more verbose about what's going on.\n"
909 "%s commands are:\n", getprogname(), getprogname());
910 help(0, NULL);
911 return SHOW_USAGE_MESSAGE;
912 }
913
914 /* Execute a single command. */
915 static int
916 execute_command(int argc, char * const *argv)
917 {
918 const command *c;
919 int found = 0;
920
921 /* Nothing to do. */
922 if (argc == 0)
923 return 0;
924
925 for (c = commands; c->c_name; ++c)
926 {
927 if (match_command(c->c_name, argv[0]))
928 {
929 found = 1;
930 break;
931 }
932 }
933
934 if (found)
935 {
936 int result;
937
938 /* Reset getopt for command proc. */
939 optind = 1;
940 optreset = 1;
941
942 if (do_verbose)
943 {
944 int ix;
945
946 fprintf(stderr, "%s", c->c_name);
947 for (ix = 1; ix < argc; ++ix)
948 fprintf(stderr, " \"%s\"", argv[ix]);
949 fprintf(stderr, "\n");
950 }
951
952 result = c->c_func(argc, argv);
953 if (result == 2)
954 fprintf(stderr, "Usage: %s %s\n %s\n", c->c_name, c->c_usage, c->c_help);
955
956 return result;
957 }
958 else
959 {
960 sec_error("unknown command \"%s\"", argv[0]);
961 return 1;
962 }
963 }
964
965 static void
966 receive_notifications(void)
967 {
968 /* Run the CFRunloop to get any pending notifications. */
969 while (CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.0, TRUE) == kCFRunLoopRunHandledSource);
970 }
971
972
973 const char *
974 sec_errstr(int err)
975 {
976 const char *errString;
977 if (IS_SEC_ERROR(err))
978 errString = SECErrorString(err);
979 else
980 errString = cssmErrorString(err);
981 return errString;
982 }
983
984 void
985 sec_error(const char *msg, ...)
986 {
987 va_list args;
988
989 fprintf(stderr, "%s: ", getprogname());
990
991 va_start(args, msg);
992 vfprintf(stderr, msg, args);
993 va_end(args);
994
995 fprintf(stderr, "\n");
996 }
997
998 void
999 sec_perror(const char *msg, int err)
1000 {
1001 sec_error("%s: %s", msg, sec_errstr(err));
1002 }
1003
1004 int
1005 main(int argc, char * const *argv)
1006 {
1007 int result = 0;
1008 int do_help = 0;
1009 int do_interactive = 0;
1010 int do_leaks = 0;
1011 int ch;
1012
1013
1014 /* Do getopt stuff for global options. */
1015 optind = 1;
1016 optreset = 1;
1017 while ((ch = getopt(argc, argv, "hilp:qvR")) != -1)
1018 {
1019 switch (ch)
1020 {
1021 case 'h':
1022 do_help = 1;
1023 break;
1024 case 'i':
1025 do_interactive = 1;
1026 break;
1027 case 'l':
1028 do_leaks = 1;
1029 break;
1030 case 'p':
1031 do_interactive = 1;
1032 prompt_string = optarg;
1033 break;
1034 case 'q':
1035 do_quiet = 1;
1036 break;
1037 case 'v':
1038 do_verbose = 1;
1039 break;
1040 case 'R':
1041 // "Recovery mode", do NOT ask security-checksystem to run when using keychain APIs
1042 // NOTE: this is a hidden option (not in the usage message)
1043 SecKeychainSystemKeychainCheckWouldDeadlock();
1044 break;
1045 case '?':
1046 default:
1047 return usage();
1048 }
1049 }
1050
1051 argc -= optind;
1052 argv += optind;
1053
1054 if (do_help)
1055 {
1056 /* Munge argc/argv so that argv[0] is something. */
1057 return help(argc + 1, argv - 1);
1058 }
1059 else if (argc > 0)
1060 {
1061 receive_notifications();
1062 result = execute_command(argc, argv);
1063 receive_notifications();
1064 }
1065 else if (do_interactive)
1066 {
1067 /* In interactive mode we just read commands and run them until readline returns NULL. */
1068
1069 /* Only show prompt string if stdin is a tty. */
1070 int show_prompt = isatty(0);
1071
1072 for (;;)
1073 {
1074 static char buffer[MAX_LINE_LEN];
1075 char * const *av, *input;
1076 int ac;
1077
1078 if (show_prompt)
1079 fprintf(stderr, "%s", prompt_string);
1080
1081 input = readline(buffer, MAX_LINE_LEN);
1082 if (!input)
1083 break;
1084
1085 split_line(input, &ac, &av);
1086 receive_notifications();
1087 result = execute_command(ac, av);
1088 receive_notifications();
1089 if (result == -1)
1090 {
1091 result = 0;
1092 break;
1093 }
1094
1095 if (result && ! do_quiet)
1096 {
1097 fprintf(stderr, "%s: returned %d\n", av[0], result);
1098 }
1099 }
1100 }
1101 else
1102 result = usage();
1103
1104 if (do_leaks)
1105 {
1106 char *const argvec[3] = { "leaks", "-nocontext", NULL };
1107 leaks(2, argvec);
1108 }
1109
1110 return result;
1111 }