1 /* gpgsm.c - GnuPG for S/MIME
2 * Copyright (C) 2001-2020 Free Software Foundation, Inc.
3 * Copyright (C) 2001-2019 Werner Koch
4 * Copyright (C) 2015-2021 g10 Code GmbH
5 *
6 * This file is part of GnuPG.
7 *
8 * GnuPG is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * GnuPG is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, see <https://www.gnu.org/licenses/>.
20 * SPDX-License-Identifier: GPL-3.0-or-later
21 */
22
23 #include <config.h>
24 #include <errno.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <ctype.h>
29 #include <unistd.h>
30 #include <fcntl.h>
31 /*#include <mcheck.h>*/
32 #include <npth.h>
33
34 #define INCLUDED_BY_MAIN_MODULE 1
35
36 #include "gpgsm.h"
37 #include <gcrypt.h>
38 #include <assuan.h> /* malloc hooks */
39
40 #include "passphrase.h"
41 #include "../common/shareddefs.h"
42 #include "../kbx/keybox.h" /* malloc hooks */
43 #include "../common/i18n.h"
44 #include "keydb.h"
45 #include "../common/sysutils.h"
46 #include "../common/gc-opt-flags.h"
47 #include "../common/asshelp.h"
48 #include "../common/init.h"
49 #include "../common/compliance.h"
50 #include "../common/comopt.h"
51 #include "minip12.h"
52
53 #ifndef O_BINARY
54 #define O_BINARY 0
55 #endif
56
57 enum cmd_and_opt_values {
58 aNull = 0,
59 oArmor = 'a',
60 aDetachedSign = 'b',
61 aSym = 'c',
62 aDecrypt = 'd',
63 aEncr = 'e',
64 aListKeys = 'k',
65 aListSecretKeys = 'K',
66 oDryRun = 'n',
67 oOutput = 'o',
68 oQuiet = 'q',
69 oRecipient = 'r',
70 aSign = 's',
71 oUser = 'u',
72 oVerbose = 'v',
73 oBatch = 500,
74 aClearsign,
75 aKeygen,
76 aSignEncr,
77 aDeleteKey,
78 aImport,
79 aVerify,
80 aListExternalKeys,
81 aListChain,
82 aSendKeys,
83 aRecvKeys,
84 aExport,
85 aExportSecretKeyP12,
86 aExportSecretKeyP8,
87 aExportSecretKeyRaw,
88 aServer,
89 aLearnCard,
90 aCallDirmngr,
91 aCallProtectTool,
92 aPasswd,
93 aGPGConfList,
94 aGPGConfTest,
95 aDumpKeys,
96 aDumpChain,
97 aDumpSecretKeys,
98 aDumpExternalKeys,
99 aShowCerts,
100 aKeydbClearSomeCertFlags,
101 aFingerprint,
102
103 oOptions,
104 oDebug,
105 oDebugLevel,
106 oDebugAll,
107 oDebugNone,
108 oDebugWait,
109 oDebugAllowCoreDump,
110 oDebugNoChainValidation,
111 oDebugIgnoreExpiration,
112 oDebugForceECDHSHA1KDF,
113 oLogFile,
114 oNoLogFile,
115 oAuditLog,
116 oHtmlAuditLog,
117
118 oEnableSpecialFilenames,
119
120 oAgentProgram,
121 oDisplay,
122 oTTYname,
123 oTTYtype,
124 oLCctype,
125 oLCmessages,
126 oXauthority,
127
128 oPreferSystemDirmngr,
129 oDirmngrProgram,
130 oDisableDirmngr,
131 oProtectToolProgram,
132 oFakedSystemTime,
133
134 oPassphraseFD,
135 oPinentryMode,
136 oRequestOrigin,
137
138 oAssumeArmor,
139 oAssumeBase64,
140 oAssumeBinary,
141
142 oBase64,
143 oNoArmor,
144 oP12Charset,
145
146 oCompliance,
147
148 oDisableCRLChecks,
149 oEnableCRLChecks,
150 oDisableTrustedCertCRLCheck,
151 oEnableTrustedCertCRLCheck,
152 oForceCRLRefresh,
153 oEnableIssuerBasedCRLCheck,
154
155 oDisableOCSP,
156 oEnableOCSP,
157
158 oIncludeCerts,
159 oPolicyFile,
160 oDisablePolicyChecks,
161 oEnablePolicyChecks,
162 oAutoIssuerKeyRetrieve,
163
164 oWithFingerprint,
165 oWithMD5Fingerprint,
166 oWithKeygrip,
167 oWithSecret,
168 oWithKeyScreening,
169 oAnswerYes,
170 oAnswerNo,
171 oKeyring,
172 oDefaultKey,
173 oDefRecipient,
174 oDefRecipientSelf,
175 oNoDefRecipient,
176 oStatusFD,
177 oCipherAlgo,
178 oDigestAlgo,
179 oExtraDigestAlgo,
180 oNoVerbose,
181 oNoSecmemWarn,
182 oNoDefKeyring,
183 oNoGreeting,
184 oNoTTY,
185 oNoOptions,
186 oNoBatch,
187 oHomedir,
188 oWithColons,
189 oWithKeyData,
190 oWithValidation,
191 oWithEphemeralKeys,
192 oSkipVerify,
193 oValidationModel,
194 oKeyServer,
195 oEncryptTo,
196 oNoEncryptTo,
197 oLoggerFD,
198 oDisableCipherAlgo,
199 oDisablePubkeyAlgo,
200 oIgnoreTimeConflict,
201 oNoRandomSeedFile,
202 oNoCommonCertsImport,
203 oIgnoreCertExtension,
204 oAuthenticode,
205 oAttribute,
206 oChUid,
207 oUseKeyboxd,
208 oKeyboxdProgram,
209 oNoAutostart
210 };
211
212
213 static gpgrt_opt_t opts[] = {
214
215 ARGPARSE_group (300, N_("@Commands:\n ")),
216
217 ARGPARSE_c (aSign, "sign", N_("make a signature")),
218 /*ARGPARSE_c (aClearsign, "clearsign", N_("make a clear text signature") ),*/
219 ARGPARSE_c (aDetachedSign, "detach-sign", N_("make a detached signature")),
220 ARGPARSE_c (aEncr, "encrypt", N_("encrypt data")),
221 /*ARGPARSE_c (aSym, "symmetric", N_("encryption only with symmetric cipher")),*/
222 ARGPARSE_c (aDecrypt, "decrypt", N_("decrypt data (default)")),
223 ARGPARSE_c (aVerify, "verify", N_("verify a signature")),
224 ARGPARSE_c (aListKeys, "list-keys", N_("list keys")),
225 ARGPARSE_c (aListExternalKeys, "list-external-keys",
226 N_("list external keys")),
227 ARGPARSE_c (aListSecretKeys, "list-secret-keys", N_("list secret keys")),
228 ARGPARSE_c (aListChain, "list-chain", N_("list certificate chain")),
229 ARGPARSE_c (aFingerprint, "fingerprint", N_("list keys and fingerprints")),
230 ARGPARSE_c (aKeygen, "generate-key", N_("generate a new key pair")),
231 ARGPARSE_c (aKeygen, "gen-key", "@"),
232 ARGPARSE_c (aDeleteKey, "delete-keys",
233 N_("remove keys from the public keyring")),
234 /*ARGPARSE_c (aSendKeys, "send-keys", N_("export keys to a keyserver")),*/
235 /*ARGPARSE_c (aRecvKeys, "recv-keys", N_("import keys from a keyserver")),*/
236 ARGPARSE_c (aImport, "import", N_("import certificates")),
237 ARGPARSE_c (aExport, "export", N_("export certificates")),
238
239 /* We use -raw and not -p1 for pkcs#1 secret key export so that it
240 won't accidentally be used in case -p12 was intended. */
241 ARGPARSE_c (aExportSecretKeyP12, "export-secret-key-p12", "@"),
242 ARGPARSE_c (aExportSecretKeyP8, "export-secret-key-p8", "@"),
243 ARGPARSE_c (aExportSecretKeyRaw, "export-secret-key-raw", "@"),
244
245 ARGPARSE_c (aLearnCard, "learn-card", N_("register a smartcard")),
246 ARGPARSE_c (aServer, "server", N_("run in server mode")),
247 ARGPARSE_c (aCallDirmngr, "call-dirmngr",
248 N_("pass a command to the dirmngr")),
249 ARGPARSE_c (aCallProtectTool, "call-protect-tool",
250 N_("invoke gpg-protect-tool")),
251 ARGPARSE_c (aPasswd, "change-passphrase", N_("change a passphrase")),
252 ARGPARSE_c (aPasswd, "passwd", "@"),
253 ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"),
254 ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"),
255
256 ARGPARSE_c (aShowCerts, "show-certs", "@"),
257 ARGPARSE_c (aDumpKeys, "dump-cert", "@"),
258 ARGPARSE_c (aDumpKeys, "dump-keys", "@"),
259 ARGPARSE_c (aDumpChain, "dump-chain", "@"),
260 ARGPARSE_c (aDumpExternalKeys, "dump-external-keys", "@"),
261 ARGPARSE_c (aDumpSecretKeys, "dump-secret-keys", "@"),
262 ARGPARSE_c (aKeydbClearSomeCertFlags, "keydb-clear-some-cert-flags", "@"),
263
264
265 ARGPARSE_header ("Monitor", N_("Options controlling the diagnostic output")),
266
267 ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
268 ARGPARSE_s_n (oNoVerbose, "no-verbose", "@"),
269 ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")),
270 ARGPARSE_s_n (oNoTTY, "no-tty", N_("don't use the terminal at all")),
271 ARGPARSE_s_n (oNoGreeting, "no-greeting", "@"),
272 ARGPARSE_s_s (oDebug, "debug", "@"),
273 ARGPARSE_s_s (oDebugLevel, "debug-level",
274 N_("|LEVEL|set the debugging level to LEVEL")),
275 ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
276 ARGPARSE_s_n (oDebugNone, "debug-none", "@"),
277 ARGPARSE_s_i (oDebugWait, "debug-wait", "@"),
278 ARGPARSE_s_n (oDebugAllowCoreDump, "debug-allow-core-dump", "@"),
279 ARGPARSE_s_n (oDebugNoChainValidation, "debug-no-chain-validation", "@"),
280 ARGPARSE_s_n (oDebugIgnoreExpiration, "debug-ignore-expiration", "@"),
281 ARGPARSE_s_n (oDebugForceECDHSHA1KDF, "debug-force-ecdh-sha1kdf", "@"),
282 ARGPARSE_s_s (oLogFile, "log-file",
283 N_("|FILE|write server mode logs to FILE")),
284 ARGPARSE_s_n (oNoLogFile, "no-log-file", "@"),
285 ARGPARSE_s_i (oLoggerFD, "logger-fd", "@"),
286 ARGPARSE_s_n (oNoSecmemWarn, "no-secmem-warning", "@"),
287
288
289 ARGPARSE_header ("Configuration",
290 N_("Options controlling the configuration")),
291
292 ARGPARSE_s_s (oHomedir, "homedir", "@"),
293 ARGPARSE_s_s (oFakedSystemTime, "faked-system-time", "@"),
294 ARGPARSE_s_n (oPreferSystemDirmngr,"prefer-system-dirmngr", "@"),
295 ARGPARSE_s_s (oValidationModel, "validation-model", "@"),
296 ARGPARSE_s_i (oIncludeCerts, "include-certs",
297 N_("|N|number of certificates to include") ),
298 ARGPARSE_s_s (oPolicyFile, "policy-file",
299 N_("|FILE|take policy information from FILE")),
300 ARGPARSE_s_s (oCompliance, "compliance", "@"),
301 ARGPARSE_s_n (oNoCommonCertsImport, "no-common-certs-import", "@"),
302 ARGPARSE_s_s (oIgnoreCertExtension, "ignore-cert-extension", "@"),
303 ARGPARSE_s_n (oNoAutostart, "no-autostart", "@"),
304 ARGPARSE_s_s (oAgentProgram, "agent-program", "@"),
305 ARGPARSE_s_s (oKeyboxdProgram, "keyboxd-program", "@"),
306 ARGPARSE_s_s (oDirmngrProgram, "dirmngr-program", "@"),
307 ARGPARSE_s_s (oProtectToolProgram, "protect-tool-program", "@"),
308
309
310 ARGPARSE_header ("Input", N_("Options controlling the input")),
311
312 ARGPARSE_s_n (oAssumeArmor, "assume-armor",
313 N_("assume input is in PEM format")),
314 ARGPARSE_s_n (oAssumeBase64, "assume-base64",
315 N_("assume input is in base-64 format")),
316 ARGPARSE_s_n (oAssumeBinary, "assume-binary",
317 N_("assume input is in binary format")),
318
319
320 ARGPARSE_header ("Output", N_("Options controlling the output")),
321
322 ARGPARSE_s_n (oArmor, "armor", N_("create ascii armored output")),
323 ARGPARSE_s_n (oArmor, "armour", "@"),
324 ARGPARSE_s_n (oNoArmor, "no-armor", "@"),
325 ARGPARSE_s_n (oNoArmor, "no-armour", "@"),
326 ARGPARSE_s_n (oBase64, "base64", N_("create base-64 encoded output")),
327 ARGPARSE_s_s (oOutput, "output", N_("|FILE|write output to FILE")),
328 ARGPARSE_s_n (oAuthenticode, "authenticode", "@"),
329 ARGPARSE_s_s (oAttribute, "attribute", "@"),
330
331
332 ARGPARSE_header (NULL, N_("Options to specify keys")),
333
334 ARGPARSE_s_s (oRecipient, "recipient", N_("|USER-ID|encrypt for USER-ID")),
335 ARGPARSE_s_s (oUser, "local-user",
336 N_("|USER-ID|use USER-ID to sign or decrypt")),
337 ARGPARSE_s_s (oDefaultKey, "default-key",
338 N_("|USER-ID|use USER-ID as default secret key")),
339 ARGPARSE_s_s (oEncryptTo, "encrypt-to",
340 N_("|NAME|encrypt to user ID NAME as well")),
341 ARGPARSE_s_n (oNoEncryptTo, "no-encrypt-to", "@"),
342 /* Not yet used: */
343 /* ARGPARSE_s_s (oDefRecipient, "default-recipient", */
344 /* N_("|NAME|use NAME as default recipient")), */
345 /* ARGPARSE_s_n (oDefRecipientSelf, "default-recipient-self", */
346 /* N_("use the default key as default recipient")), */
347 /* ARGPARSE_s_n (oNoDefRecipient, "no-default-recipient", "@"), */
348 ARGPARSE_s_s (oKeyring, "keyring",
349 N_("|FILE|add keyring to the list of keyrings")),
350 ARGPARSE_s_n (oNoDefKeyring, "no-default-keyring", "@"),
351 ARGPARSE_s_s (oKeyServer, "ldapserver",
352 N_("|SPEC|use this keyserver to lookup keys")),
353 ARGPARSE_s_s (oKeyServer, "keyserver", "@"),
354 ARGPARSE_s_n (oUseKeyboxd, "use-keyboxd", "@"),
355
356
357 ARGPARSE_header ("ImportExport",
358 N_("Options controlling key import and export")),
359
360 ARGPARSE_s_n (oDisableDirmngr, "disable-dirmngr",
361 N_("disable all access to the dirmngr")),
362 ARGPARSE_s_n (oAutoIssuerKeyRetrieve, "auto-issuer-key-retrieve",
363 N_("fetch missing issuer certificates")),
364 ARGPARSE_s_s (oP12Charset, "p12-charset",
365 N_("|NAME|use encoding NAME for PKCS#12 passphrases")),
366
367
368 ARGPARSE_header ("Keylist", N_("Options controlling key listings")),
369
370 ARGPARSE_s_n (oWithColons, "with-colons", "@"),
371 ARGPARSE_s_n (oWithKeyData,"with-key-data", "@"),
372 ARGPARSE_s_n (oWithValidation, "with-validation", "@"),
373 ARGPARSE_s_n (oWithMD5Fingerprint, "with-md5-fingerprint", "@"),
374 ARGPARSE_s_n (oWithEphemeralKeys, "with-ephemeral-keys", "@"),
375 ARGPARSE_s_n (oSkipVerify, "skip-verify", "@"),
376 ARGPARSE_s_n (oWithFingerprint, "with-fingerprint", "@"),
377 ARGPARSE_s_n (oWithKeygrip, "with-keygrip", "@"),
378 ARGPARSE_s_n (oWithSecret, "with-secret", "@"),
379 ARGPARSE_s_n (oWithKeyScreening,"with-key-screening", "@"),
380
381
382
383 ARGPARSE_header ("Security", N_("Options controlling the security")),
384
385 ARGPARSE_s_n (oDisableCRLChecks, "disable-crl-checks",
386 N_("never consult a CRL")),
387 ARGPARSE_s_n (oEnableCRLChecks, "enable-crl-checks", "@"),
388 ARGPARSE_s_n (oDisableTrustedCertCRLCheck,
389 "disable-trusted-cert-crl-check",
390 N_("do not check CRLs for root certificates")),
391 ARGPARSE_s_n (oEnableTrustedCertCRLCheck,
392 "enable-trusted-cert-crl-check", "@"),
393 ARGPARSE_s_n (oDisableOCSP, "disable-ocsp", "@"),
394 ARGPARSE_s_n (oEnableOCSP, "enable-ocsp", N_("check validity using OCSP")),
395 ARGPARSE_s_n (oDisablePolicyChecks, "disable-policy-checks",
396 N_("do not check certificate policies")),
397 ARGPARSE_s_n (oEnablePolicyChecks, "enable-policy-checks", "@"),
398 ARGPARSE_s_s (oCipherAlgo, "cipher-algo",
399 N_("|NAME|use cipher algorithm NAME")),
400 ARGPARSE_s_s (oDigestAlgo, "digest-algo",
401 N_("|NAME|use message digest algorithm NAME")),
402 ARGPARSE_s_s (oExtraDigestAlgo, "extra-digest-algo", "@"),
403 ARGPARSE_s_s (oDisableCipherAlgo, "disable-cipher-algo", "@"),
404 ARGPARSE_s_s (oDisablePubkeyAlgo, "disable-pubkey-algo", "@"),
405 ARGPARSE_s_n (oIgnoreTimeConflict, "ignore-time-conflict", "@"),
406 ARGPARSE_s_n (oNoRandomSeedFile, "no-random-seed-file", "@"),
407
408
409 ARGPARSE_header (NULL, N_("Options for unattended use")),
410
411 ARGPARSE_s_n (oBatch, "batch", N_("batch mode: never ask")),
412 ARGPARSE_s_n (oNoBatch, "no-batch", "@"),
413 ARGPARSE_s_n (oAnswerYes, "yes", N_("assume yes on most questions")),
414 ARGPARSE_s_n (oAnswerNo, "no", N_("assume no on most questions")),
415 ARGPARSE_s_i (oStatusFD, "status-fd", N_("|FD|write status info to this FD")),
416 ARGPARSE_s_n (oEnableSpecialFilenames, "enable-special-filenames", "@"),
417 ARGPARSE_s_i (oPassphraseFD, "passphrase-fd", "@"),
418 ARGPARSE_s_s (oPinentryMode, "pinentry-mode", "@"),
419
420
421 ARGPARSE_header (NULL, N_("Other options")),
422
423 ARGPARSE_conffile (oOptions, "options", N_("|FILE|read options from FILE")),
424 ARGPARSE_noconffile (oNoOptions, "no-options", "@"),
425 ARGPARSE_s_n (oDryRun, "dry-run", N_("do not make any changes")),
426 ARGPARSE_s_s (oRequestOrigin, "request-origin", "@"),
427 ARGPARSE_s_n (oForceCRLRefresh, "force-crl-refresh", "@"),
428 ARGPARSE_s_n (oEnableIssuerBasedCRLCheck, "enable-issuer-based-crl-check",
429 "@"),
430 ARGPARSE_s_s (oAuditLog, "audit-log",
431 N_("|FILE|write an audit log to FILE")),
432 ARGPARSE_s_s (oHtmlAuditLog, "html-audit-log", "@"),
433 ARGPARSE_s_s (oDisplay, "display", "@"),
434 ARGPARSE_s_s (oTTYname, "ttyname", "@"),
435 ARGPARSE_s_s (oTTYtype, "ttytype", "@"),
436 ARGPARSE_s_s (oLCctype, "lc-ctype", "@"),
437 ARGPARSE_s_s (oLCmessages, "lc-messages", "@"),
438 ARGPARSE_s_s (oXauthority, "xauthority", "@"),
439 ARGPARSE_s_s (oChUid, "chuid", "@"),
440
441
442 ARGPARSE_header (NULL, ""), /* Stop the header group. */
443
444
445 /* Command aliases. */
446 ARGPARSE_c (aListKeys, "list-key", "@"),
447 ARGPARSE_c (aListChain, "list-signatures", "@"),
448 ARGPARSE_c (aListChain, "list-sigs", "@"),
449 ARGPARSE_c (aListChain, "check-signatures", "@"),
450 ARGPARSE_c (aListChain, "check-sigs", "@"),
451 ARGPARSE_c (aDeleteKey, "delete-key", "@"),
452
453 ARGPARSE_group (302, N_(
454 "@\n(See the man page for a complete listing of all commands and options)\n"
455 )),
456
457 ARGPARSE_end ()
458 };
459
460
461 /* The list of supported debug flags. */
462 static struct debug_flags_s debug_flags [] =
463 {
464 { DBG_X509_VALUE , "x509" },
465 { DBG_MPI_VALUE , "mpi" },
466 { DBG_CRYPTO_VALUE , "crypto" },
467 { DBG_MEMORY_VALUE , "memory" },
468 { DBG_CACHE_VALUE , "cache" },
469 { DBG_MEMSTAT_VALUE, "memstat" },
470 { DBG_HASHING_VALUE, "hashing" },
471 { DBG_IPC_VALUE , "ipc" },
472 { DBG_CLOCK_VALUE , "clock" },
473 { DBG_LOOKUP_VALUE , "lookup" },
474 { 0, NULL }
475 };
476
477
478 /* Global variable to keep an error count. */
479 int gpgsm_errors_seen = 0;
480
481 /* It is possible that we are currentlu running under setuid permissions */
482 static int maybe_setuid = 1;
483
484 /* Helper to implement --debug-level and --debug*/
485 static const char *debug_level;
486 static unsigned int debug_value;
487
488 /* Default value for include-certs. We need an extra macro for
489 gpgconf-list because the variable will be changed by the command
490 line option.
491
492 It is often cumbersome to locate intermediate certificates, thus by
493 default we include all certificates in the chain. However we leave
494 out the root certificate because that would make it too easy for
495 the recipient to import that root certificate. A root certificate
496 should be installed only after due checks and thus it won't help to
497 send it along with each message. */
498 #define DEFAULT_INCLUDE_CERTS -2 /* Include all certs but root. */
499 static int default_include_certs = DEFAULT_INCLUDE_CERTS;
500
501 /* Whether the chain mode shall be used for validation. */
502 static int default_validation_model;
503
504 /* The default cipher algo. */
505 #define DEFAULT_CIPHER_ALGO "AES"
506
507
508 static char *build_list (const char *text,
509 const char *(*mapf)(int), int (*chkf)(int));
510 static void set_cmd (enum cmd_and_opt_values *ret_cmd,
511 enum cmd_and_opt_values new_cmd );
512
513 static void emergency_cleanup (void);
514 static int open_read (const char *filename);
515 static estream_t open_es_fread (const char *filename, const char *mode);
516 static estream_t open_es_fwrite (const char *filename);
517 static void run_protect_tool (int argc, char **argv);
518
519 static int
our_pk_test_algo(int algo)520 our_pk_test_algo (int algo)
521 {
522 switch (algo)
523 {
524 case GCRY_PK_RSA:
525 case GCRY_PK_ECDSA:
526 case GCRY_PK_EDDSA:
527 return gcry_pk_test_algo (algo);
528 default:
529 return 1;
530 }
531 }
532
533 static int
our_cipher_test_algo(int algo)534 our_cipher_test_algo (int algo)
535 {
536 switch (algo)
537 {
538 case GCRY_CIPHER_3DES:
539 case GCRY_CIPHER_AES128:
540 case GCRY_CIPHER_AES192:
541 case GCRY_CIPHER_AES256:
542 case GCRY_CIPHER_SERPENT128:
543 case GCRY_CIPHER_SERPENT192:
544 case GCRY_CIPHER_SERPENT256:
545 case GCRY_CIPHER_SEED:
546 case GCRY_CIPHER_CAMELLIA128:
547 case GCRY_CIPHER_CAMELLIA192:
548 case GCRY_CIPHER_CAMELLIA256:
549 return gcry_cipher_test_algo (algo);
550 default:
551 return 1;
552 }
553 }
554
555
556 static int
our_md_test_algo(int algo)557 our_md_test_algo (int algo)
558 {
559 switch (algo)
560 {
561 case GCRY_MD_MD5:
562 case GCRY_MD_SHA1:
563 case GCRY_MD_RMD160:
564 case GCRY_MD_SHA224:
565 case GCRY_MD_SHA256:
566 case GCRY_MD_SHA384:
567 case GCRY_MD_SHA512:
568 case GCRY_MD_WHIRLPOOL:
569 return gcry_md_test_algo (algo);
570 default:
571 return 1;
572 }
573 }
574
575
576 /* nPth wrapper function definitions. */
577 ASSUAN_SYSTEM_NPTH_IMPL;
578
579
580 static char *
make_libversion(const char * libname,const char * (* getfnc)(const char *))581 make_libversion (const char *libname, const char *(*getfnc)(const char*))
582 {
583 const char *s;
584 char *result;
585
586 if (maybe_setuid)
587 {
588 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
589 maybe_setuid = 0;
590 }
591 s = getfnc (NULL);
592 result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
593 strcpy (stpcpy (stpcpy (result, libname), " "), s);
594 return result;
595 }
596
597
598 static const char *
my_strusage(int level)599 my_strusage( int level )
600 {
601 static char *digests, *pubkeys, *ciphers;
602 static char *ver_gcry, *ver_ksba;
603 const char *p;
604
605 switch (level)
606 {
607 case 9: p = "GPL-3.0-or-later"; break;
608 case 11: p = "@GPGSM@ (@GNUPG@)";
609 break;
610 case 13: p = VERSION; break;
611 case 14: p = GNUPG_DEF_COPYRIGHT_LINE; break;
612 case 17: p = PRINTABLE_OS_NAME; break;
613 case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
614
615 case 1:
616 case 40: p = _("Usage: @GPGSM@ [options] [files] (-h for help)");
617 break;
618 case 41:
619 p = _("Syntax: @GPGSM@ [options] [files]\n"
620 "Sign, check, encrypt or decrypt using the S/MIME protocol\n"
621 "Default operation depends on the input data\n");
622 break;
623
624 case 20:
625 if (!ver_gcry)
626 ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
627 p = ver_gcry;
628 break;
629 case 21:
630 if (!ver_ksba)
631 ver_ksba = make_libversion ("libksba", ksba_check_version);
632 p = ver_ksba;
633 break;
634
635 case 31: p = "\nHome: "; break;
636 case 32: p = gnupg_homedir (); break;
637 case 33: p = _("\nSupported algorithms:\n"); break;
638 case 34:
639 if (!ciphers)
640 ciphers = build_list ("Cipher: ", gnupg_cipher_algo_name,
641 our_cipher_test_algo );
642 p = ciphers;
643 break;
644 case 35:
645 if (!pubkeys)
646 pubkeys = build_list ("Pubkey: ", gcry_pk_algo_name,
647 our_pk_test_algo );
648 p = pubkeys;
649 break;
650 case 36:
651 if (!digests)
652 digests = build_list("Hash: ", gcry_md_algo_name, our_md_test_algo );
653 p = digests;
654 break;
655
656 default: p = NULL; break;
657 }
658 return p;
659 }
660
661
662 static char *
build_list(const char * text,const char * (* mapf)(int),int (* chkf)(int))663 build_list (const char *text, const char * (*mapf)(int), int (*chkf)(int))
664 {
665 int i;
666 size_t n=strlen(text)+2;
667 char *list, *p;
668
669 if (maybe_setuid) {
670 gcry_control (GCRYCTL_DROP_PRIVS); /* drop setuid */
671 }
672
673 for (i=1; i < 400; i++ )
674 if (!chkf(i))
675 n += strlen(mapf(i)) + 2;
676 list = xmalloc (21 + n);
677 *list = 0;
678 for (p=NULL, i=1; i < 400; i++)
679 {
680 if (!chkf(i))
681 {
682 if( !p )
683 p = stpcpy (list, text );
684 else
685 p = stpcpy (p, ", ");
686 p = stpcpy (p, mapf(i) );
687 }
688 }
689 if (p)
690 strcpy (p, "\n" );
691 return list;
692 }
693
694
695 /* Set the file pointer into binary mode if required. */
696 static void
set_binary(FILE * fp)697 set_binary (FILE *fp)
698 {
699 #ifdef HAVE_DOSISH_SYSTEM
700 setmode (fileno (fp), O_BINARY);
701 #else
702 (void)fp;
703 #endif
704 }
705
706
707
708 static void
wrong_args(const char * text)709 wrong_args (const char *text)
710 {
711 fprintf (stderr, _("usage: %s [options] %s\n"), GPGSM_NAME, text);
712 gpgsm_exit (2);
713 }
714
715
716 static void
set_opt_session_env(const char * name,const char * value)717 set_opt_session_env (const char *name, const char *value)
718 {
719 gpg_error_t err;
720
721 err = session_env_setenv (opt.session_env, name, value);
722 if (err)
723 log_fatal ("error setting session environment: %s\n",
724 gpg_strerror (err));
725 }
726
727
728 /* Setup the debugging. With a DEBUG_LEVEL of NULL only the active
729 debug flags are propagated to the subsystems. With DEBUG_LEVEL
730 set, a specific set of debug flags is set; and individual debugging
731 flags will be added on top. */
732 static void
set_debug(void)733 set_debug (void)
734 {
735 int numok = (debug_level && digitp (debug_level));
736 int numlvl = numok? atoi (debug_level) : 0;
737
738 if (!debug_level)
739 ;
740 else if (!strcmp (debug_level, "none") || (numok && numlvl < 1))
741 opt.debug = 0;
742 else if (!strcmp (debug_level, "basic") || (numok && numlvl <= 2))
743 opt.debug = DBG_IPC_VALUE;
744 else if (!strcmp (debug_level, "advanced") || (numok && numlvl <= 5))
745 opt.debug = DBG_IPC_VALUE|DBG_X509_VALUE;
746 else if (!strcmp (debug_level, "expert") || (numok && numlvl <= 8))
747 opt.debug = (DBG_IPC_VALUE|DBG_X509_VALUE
748 |DBG_CACHE_VALUE|DBG_CRYPTO_VALUE);
749 else if (!strcmp (debug_level, "guru") || numok)
750 {
751 opt.debug = ~0;
752 /* Unless the "guru" string has been used we don't want to allow
753 hashing debugging. The rationale is that people tend to
754 select the highest debug value and would then clutter their
755 disk with debug files which may reveal confidential data. */
756 if (numok)
757 opt.debug &= ~(DBG_HASHING_VALUE);
758 }
759 else
760 {
761 log_error (_("invalid debug-level '%s' given\n"), debug_level);
762 gpgsm_exit (2);
763 }
764
765 opt.debug |= debug_value;
766
767 if (opt.debug && !opt.verbose)
768 opt.verbose = 1;
769 if (opt.debug)
770 opt.quiet = 0;
771
772 if (opt.debug & DBG_MPI_VALUE)
773 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
774 if (opt.debug & DBG_CRYPTO_VALUE )
775 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
776 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
777
778 if (opt.debug)
779 parse_debug_flag (NULL, &opt.debug, debug_flags);
780
781 /* minip12.c may be used outside of GnuPG, thus we don't have the
782 * opt structure over there. */
783 p12_set_verbosity (opt.verbose);
784 }
785
786
787
788 static void
set_cmd(enum cmd_and_opt_values * ret_cmd,enum cmd_and_opt_values new_cmd)789 set_cmd (enum cmd_and_opt_values *ret_cmd, enum cmd_and_opt_values new_cmd)
790 {
791 enum cmd_and_opt_values cmd = *ret_cmd;
792
793 if (!cmd || cmd == new_cmd)
794 cmd = new_cmd;
795 else if ( cmd == aSign && new_cmd == aEncr )
796 cmd = aSignEncr;
797 else if ( cmd == aEncr && new_cmd == aSign )
798 cmd = aSignEncr;
799 else if ( (cmd == aSign && new_cmd == aClearsign)
800 || (cmd == aClearsign && new_cmd == aSign) )
801 cmd = aClearsign;
802 else
803 {
804 log_error(_("conflicting commands\n"));
805 gpgsm_exit(2);
806 }
807
808 *ret_cmd = cmd;
809 }
810
811
812 /* Helper to add recipients to a list. */
813 static void
do_add_recipient(ctrl_t ctrl,const char * name,certlist_t * recplist,int is_encrypt_to,int recp_required)814 do_add_recipient (ctrl_t ctrl, const char *name,
815 certlist_t *recplist, int is_encrypt_to, int recp_required)
816 {
817 int rc = gpgsm_add_to_certlist (ctrl, name, 0, recplist, is_encrypt_to);
818 if (rc)
819 {
820 if (recp_required)
821 {
822 log_error ("can't encrypt to '%s': %s\n", name, gpg_strerror (rc));
823 gpgsm_status2 (ctrl, STATUS_INV_RECP,
824 get_inv_recpsgnr_code (rc), name, NULL);
825 }
826 else
827 log_info (_("Note: won't be able to encrypt to '%s': %s\n"),
828 name, gpg_strerror (rc));
829 }
830 }
831
832
833 static void
parse_validation_model(const char * model)834 parse_validation_model (const char *model)
835 {
836 int i = gpgsm_parse_validation_model (model);
837 if (i == -1)
838 log_error (_("unknown validation model '%s'\n"), model);
839 else
840 default_validation_model = i;
841 }
842
843
844
845 int
main(int argc,char ** argv)846 main ( int argc, char **argv)
847 {
848 gpg_error_t err = 0;
849 gpgrt_argparse_t pargs;
850 int orig_argc;
851 char **orig_argv;
852 /* char *username;*/
853 int may_coredump;
854 strlist_t sl, remusr= NULL, locusr=NULL;
855 strlist_t nrings=NULL;
856 int detached_sig = 0;
857 char *last_configname = NULL;
858 const char *configname = NULL; /* NULL or points to last_configname.
859 * NULL also indicates that we are
860 * processing options from the cmdline. */
861 int debug_argparser = 0;
862 int no_more_options = 0;
863 int default_keyring = 1;
864 char *logfile = NULL;
865 char *auditlog = NULL;
866 char *htmlauditlog = NULL;
867 int greeting = 0;
868 int nogreeting = 0;
869 int debug_wait = 0;
870 int use_random_seed = 1;
871 int no_common_certs_import = 0;
872 int with_fpr = 0;
873 const char *forced_digest_algo = NULL;
874 const char *extra_digest_algo = NULL;
875 enum cmd_and_opt_values cmd = 0;
876 struct server_control_s ctrl;
877 certlist_t recplist = NULL;
878 certlist_t signerlist = NULL;
879 int do_not_setup_keys = 0;
880 int recp_required = 0;
881 estream_t auditfp = NULL;
882 estream_t htmlauditfp = NULL;
883 struct assuan_malloc_hooks malloc_hooks;
884 int pwfd = -1;
885
886 static const char *homedirvalue;
887 static const char *changeuser;
888
889
890 early_system_init ();
891 gnupg_reopen_std (GPGSM_NAME);
892 /* trap_unaligned ();*/
893 gnupg_rl_initialize ();
894 gpgrt_set_strusage (my_strusage);
895 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
896
897 /* Please note that we may running SUID(ROOT), so be very CAREFUL
898 when adding any stuff between here and the call to secmem_init()
899 somewhere after the option parsing */
900 log_set_prefix (GPGSM_NAME, GPGRT_LOG_WITH_PREFIX);
901
902 /* Make sure that our subsystems are ready. */
903 i18n_init ();
904 init_common_subsystems (&argc, &argv);
905
906 /* Check that the libraries are suitable. Do it here because the
907 option parse may need services of the library */
908 if (!ksba_check_version (NEED_KSBA_VERSION) )
909 log_fatal (_("%s is too old (need %s, have %s)\n"), "libksba",
910 NEED_KSBA_VERSION, ksba_check_version (NULL) );
911
912
913 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
914
915 may_coredump = disable_core_dumps ();
916
917 gnupg_init_signals (0, emergency_cleanup);
918
919 dotlock_create (NULL, 0); /* Register lockfile cleanup. */
920
921 /* Tell the compliance module who we are. */
922 gnupg_initialize_compliance (GNUPG_MODULE_NAME_GPGSM);
923
924 opt.autostart = 1;
925 opt.session_env = session_env_new ();
926 if (!opt.session_env)
927 log_fatal ("error allocating session environment block: %s\n",
928 strerror (errno));
929
930 /* Note: If you change this default cipher algorithm , please
931 remember to update the Gpgconflist entry as well. */
932 opt.def_cipher_algoid = DEFAULT_CIPHER_ALGO;
933
934
935 /* First check whether we have a config file on the commandline */
936 orig_argc = argc;
937 orig_argv = argv;
938 pargs.argc = &argc;
939 pargs.argv = &argv;
940 pargs.flags= (ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_NOVERSION);
941 while (gpgrt_argparse (NULL, &pargs, opts))
942 {
943 switch (pargs.r_opt)
944 {
945 case oDebug:
946 case oDebugAll:
947 debug_argparser++;
948 break;
949
950 case oNoOptions:
951 /* Set here here because the homedir would otherwise be
952 * created before main option parsing starts. */
953 opt.no_homedir_creation = 1;
954 break;
955
956 case oHomedir:
957 homedirvalue = pargs.r.ret_str;
958 break;
959
960 case oChUid:
961 changeuser = pargs.r.ret_str;
962 break;
963
964 case aCallProtectTool:
965 /* Make sure that --version and --help are passed to the
966 * protect-tool. */
967 goto leave_cmdline_parser;
968 }
969 }
970 leave_cmdline_parser:
971 /* Reset the flags. */
972 pargs.flags &= ~(ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_NOVERSION);
973
974 /* Initialize the secure memory. */
975 gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
976 maybe_setuid = 0;
977
978 /*
979 Now we are now working under our real uid
980 */
981
982 ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free );
983
984 malloc_hooks.malloc = gcry_malloc;
985 malloc_hooks.realloc = gcry_realloc;
986 malloc_hooks.free = gcry_free;
987 assuan_set_malloc_hooks (&malloc_hooks);
988 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
989 setup_libassuan_logging (&opt.debug, NULL);
990
991 /* Change UID and then set homedir. */
992 if (changeuser && gnupg_chuid (changeuser, 0))
993 log_inc_errorcount (); /* Force later termination. */
994 gnupg_set_homedir (homedirvalue);
995
996 /* Setup a default control structure for command line mode */
997 memset (&ctrl, 0, sizeof ctrl);
998 gpgsm_init_default_ctrl (&ctrl);
999 ctrl.no_server = 1;
1000 ctrl.status_fd = -1; /* No status output. */
1001 ctrl.autodetect_encoding = 1;
1002
1003 /* Set the default policy file */
1004 opt.policy_file = make_filename (gnupg_homedir (), "policies.txt", NULL);
1005
1006 /* The configuraton directories for use by gpgrt_argparser. */
1007 gpgrt_set_confdir (GPGRT_CONFDIR_SYS, gnupg_sysconfdir ());
1008 gpgrt_set_confdir (GPGRT_CONFDIR_USER, gnupg_homedir ());
1009
1010 /* We are re-using the struct, thus the reset flag. We OR the
1011 * flags so that the internal intialized flag won't be cleared. */
1012 argc = orig_argc;
1013 argv = orig_argv;
1014 pargs.argc = &argc;
1015 pargs.argv = &argv;
1016 pargs.flags |= (ARGPARSE_FLAG_RESET
1017 | ARGPARSE_FLAG_KEEP
1018 | ARGPARSE_FLAG_SYS
1019 | ARGPARSE_FLAG_USER);
1020
1021 while (!no_more_options
1022 && gpgrt_argparser (&pargs, opts, GPGSM_NAME EXTSEP_S "conf"))
1023 {
1024 switch (pargs.r_opt)
1025 {
1026 case ARGPARSE_CONFFILE:
1027 if (debug_argparser)
1028 log_info (_("reading options from '%s'\n"),
1029 pargs.r_type? pargs.r.ret_str: "[cmdline]");
1030 if (pargs.r_type)
1031 {
1032 xfree (last_configname);
1033 last_configname = xstrdup (pargs.r.ret_str);
1034 configname = last_configname;
1035 }
1036 else
1037 configname = NULL;
1038 break;
1039
1040 case aGPGConfList:
1041 case aGPGConfTest:
1042 set_cmd (&cmd, pargs.r_opt);
1043 do_not_setup_keys = 1;
1044 default_keyring = 0;
1045 nogreeting = 1;
1046 break;
1047
1048 case aServer:
1049 opt.batch = 1;
1050 set_cmd (&cmd, aServer);
1051 break;
1052
1053 case aCallDirmngr:
1054 opt.batch = 1;
1055 set_cmd (&cmd, aCallDirmngr);
1056 do_not_setup_keys = 1;
1057 break;
1058
1059 case aCallProtectTool:
1060 opt.batch = 1;
1061 set_cmd (&cmd, aCallProtectTool);
1062 no_more_options = 1; /* Stop parsing. */
1063 do_not_setup_keys = 1;
1064 break;
1065
1066 case aDeleteKey:
1067 set_cmd (&cmd, aDeleteKey);
1068 /*greeting=1;*/
1069 do_not_setup_keys = 1;
1070 break;
1071
1072 case aDetachedSign:
1073 detached_sig = 1;
1074 set_cmd (&cmd, aSign );
1075 break;
1076
1077 case aKeygen:
1078 set_cmd (&cmd, aKeygen);
1079 greeting=1;
1080 do_not_setup_keys = 1;
1081 break;
1082
1083 case aImport:
1084 case aSendKeys:
1085 case aRecvKeys:
1086 case aExport:
1087 case aExportSecretKeyP12:
1088 case aExportSecretKeyP8:
1089 case aExportSecretKeyRaw:
1090 case aShowCerts:
1091 case aDumpKeys:
1092 case aDumpChain:
1093 case aDumpExternalKeys:
1094 case aDumpSecretKeys:
1095 case aListKeys:
1096 case aListExternalKeys:
1097 case aListSecretKeys:
1098 case aListChain:
1099 case aLearnCard:
1100 case aPasswd:
1101 case aKeydbClearSomeCertFlags:
1102 do_not_setup_keys = 1;
1103 set_cmd (&cmd, pargs.r_opt);
1104 break;
1105
1106 case aEncr:
1107 recp_required = 1;
1108 set_cmd (&cmd, pargs.r_opt);
1109 break;
1110
1111 case aSym:
1112 case aDecrypt:
1113 case aSign:
1114 case aClearsign:
1115 case aVerify:
1116 set_cmd (&cmd, pargs.r_opt);
1117 break;
1118
1119 /* Output encoding selection. */
1120 case oArmor:
1121 ctrl.create_pem = 1;
1122 break;
1123 case oBase64:
1124 ctrl.create_pem = 0;
1125 ctrl.create_base64 = 1;
1126 break;
1127 case oNoArmor:
1128 ctrl.create_pem = 0;
1129 ctrl.create_base64 = 0;
1130 break;
1131
1132 case oP12Charset:
1133 opt.p12_charset = pargs.r.ret_str;
1134 break;
1135
1136 case oPassphraseFD:
1137 pwfd = translate_sys2libc_fd_int (pargs.r.ret_int, 0);
1138 break;
1139
1140 case oPinentryMode:
1141 opt.pinentry_mode = parse_pinentry_mode (pargs.r.ret_str);
1142 if (opt.pinentry_mode == -1)
1143 log_error (_("invalid pinentry mode '%s'\n"), pargs.r.ret_str);
1144 break;
1145
1146 case oRequestOrigin:
1147 opt.request_origin = parse_request_origin (pargs.r.ret_str);
1148 if (opt.request_origin == -1)
1149 log_error (_("invalid request origin '%s'\n"), pargs.r.ret_str);
1150 break;
1151
1152 /* Input encoding selection. */
1153 case oAssumeArmor:
1154 ctrl.autodetect_encoding = 0;
1155 ctrl.is_pem = 1;
1156 ctrl.is_base64 = 0;
1157 break;
1158 case oAssumeBase64:
1159 ctrl.autodetect_encoding = 0;
1160 ctrl.is_pem = 0;
1161 ctrl.is_base64 = 1;
1162 break;
1163 case oAssumeBinary:
1164 ctrl.autodetect_encoding = 0;
1165 ctrl.is_pem = 0;
1166 ctrl.is_base64 = 0;
1167 break;
1168
1169 case oDisableCRLChecks:
1170 opt.no_crl_check = 1;
1171 break;
1172 case oEnableCRLChecks:
1173 opt.no_crl_check = 0;
1174 break;
1175 case oDisableTrustedCertCRLCheck:
1176 opt.no_trusted_cert_crl_check = 1;
1177 break;
1178 case oEnableTrustedCertCRLCheck:
1179 opt.no_trusted_cert_crl_check = 0;
1180 break;
1181 case oForceCRLRefresh:
1182 opt.force_crl_refresh = 1;
1183 break;
1184 case oEnableIssuerBasedCRLCheck:
1185 opt.enable_issuer_based_crl_check = 1;
1186 break;
1187
1188 case oDisableOCSP:
1189 ctrl.use_ocsp = opt.enable_ocsp = 0;
1190 break;
1191 case oEnableOCSP:
1192 ctrl.use_ocsp = opt.enable_ocsp = 1;
1193 break;
1194
1195 case oIncludeCerts:
1196 ctrl.include_certs = default_include_certs = pargs.r.ret_int;
1197 break;
1198
1199 case oPolicyFile:
1200 xfree (opt.policy_file);
1201 if (*pargs.r.ret_str)
1202 opt.policy_file = xstrdup (pargs.r.ret_str);
1203 else
1204 opt.policy_file = NULL;
1205 break;
1206
1207 case oDisablePolicyChecks:
1208 opt.no_policy_check = 1;
1209 break;
1210 case oEnablePolicyChecks:
1211 opt.no_policy_check = 0;
1212 break;
1213
1214 case oAutoIssuerKeyRetrieve:
1215 opt.auto_issuer_key_retrieve = 1;
1216 break;
1217
1218 case oOutput: opt.outfile = pargs.r.ret_str; break;
1219
1220
1221 case oQuiet: opt.quiet = 1; break;
1222 case oNoTTY: /* fixme:tty_no_terminal(1);*/ break;
1223 case oDryRun: opt.dry_run = 1; break;
1224
1225 case oVerbose:
1226 opt.verbose++;
1227 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
1228 break;
1229 case oNoVerbose:
1230 opt.verbose = 0;
1231 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
1232 break;
1233
1234 case oLogFile: logfile = pargs.r.ret_str; break;
1235 case oNoLogFile: logfile = NULL; break;
1236
1237 case oAuditLog: auditlog = pargs.r.ret_str; break;
1238 case oHtmlAuditLog: htmlauditlog = pargs.r.ret_str; break;
1239
1240 case oBatch:
1241 opt.batch = 1;
1242 greeting = 0;
1243 break;
1244 case oNoBatch: opt.batch = 0; break;
1245
1246 case oAnswerYes: opt.answer_yes = 1; break;
1247 case oAnswerNo: opt.answer_no = 1; break;
1248
1249 case oKeyring: append_to_strlist (&nrings, pargs.r.ret_str); break;
1250 case oUseKeyboxd: opt.use_keyboxd = 1; break;
1251
1252 case oDebug:
1253 if (parse_debug_flag (pargs.r.ret_str, &debug_value, debug_flags))
1254 {
1255 pargs.r_opt = ARGPARSE_INVALID_ARG;
1256 pargs.err = ARGPARSE_PRINT_ERROR;
1257 }
1258 break;
1259 case oDebugAll: debug_value = ~0; break;
1260 case oDebugNone: debug_value = 0; break;
1261 case oDebugLevel: debug_level = pargs.r.ret_str; break;
1262 case oDebugWait: debug_wait = pargs.r.ret_int; break;
1263 case oDebugAllowCoreDump:
1264 may_coredump = enable_core_dumps ();
1265 break;
1266 case oDebugNoChainValidation: opt.no_chain_validation = 1; break;
1267 case oDebugIgnoreExpiration: opt.ignore_expiration = 1; break;
1268 case oDebugForceECDHSHA1KDF: opt.force_ecdh_sha1kdf = 1; break;
1269
1270 case oStatusFD:
1271 ctrl.status_fd = translate_sys2libc_fd_int (pargs.r.ret_int, 1);
1272 break;
1273 case oLoggerFD:
1274 log_set_fd (translate_sys2libc_fd_int (pargs.r.ret_int, 1));
1275 break;
1276 case oWithMD5Fingerprint:
1277 opt.with_md5_fingerprint=1; /*fall through*/
1278 case oWithFingerprint:
1279 with_fpr=1; /*fall through*/
1280 case aFingerprint:
1281 opt.fingerprint++;
1282 break;
1283
1284 case oWithKeygrip:
1285 opt.with_keygrip = 1;
1286 break;
1287
1288 case oWithKeyScreening:
1289 opt.with_key_screening = 1;
1290 break;
1291
1292 case oHomedir: gnupg_set_homedir (pargs.r.ret_str); break;
1293 case oChUid: break; /* Command line only (see above). */
1294 case oAgentProgram: opt.agent_program = pargs.r.ret_str; break;
1295 case oKeyboxdProgram: opt.keyboxd_program = pargs.r.ret_str; break;
1296
1297 case oDisplay:
1298 set_opt_session_env ("DISPLAY", pargs.r.ret_str);
1299 break;
1300 case oTTYname:
1301 set_opt_session_env ("GPG_TTY", pargs.r.ret_str);
1302 break;
1303 case oTTYtype:
1304 set_opt_session_env ("TERM", pargs.r.ret_str);
1305 break;
1306 case oXauthority:
1307 set_opt_session_env ("XAUTHORITY", pargs.r.ret_str);
1308 break;
1309
1310 case oLCctype: opt.lc_ctype = xstrdup (pargs.r.ret_str); break;
1311 case oLCmessages: opt.lc_messages = xstrdup (pargs.r.ret_str); break;
1312
1313 case oDirmngrProgram: opt.dirmngr_program = pargs.r.ret_str; break;
1314 case oDisableDirmngr: opt.disable_dirmngr = 1; break;
1315 case oPreferSystemDirmngr: /* Obsolete */; break;
1316 case oProtectToolProgram:
1317 opt.protect_tool_program = pargs.r.ret_str;
1318 break;
1319
1320 case oFakedSystemTime:
1321 {
1322 time_t faked_time = isotime2epoch (pargs.r.ret_str);
1323 if (faked_time == (time_t)(-1))
1324 faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
1325 gnupg_set_time (faked_time, 0);
1326 }
1327 break;
1328
1329 case oNoDefKeyring: default_keyring = 0; break;
1330 case oNoGreeting: nogreeting = 1; break;
1331
1332 case oDefaultKey:
1333 if (*pargs.r.ret_str)
1334 {
1335 xfree (opt.local_user);
1336 opt.local_user = xstrdup (pargs.r.ret_str);
1337 }
1338 break;
1339 case oDefRecipient:
1340 if (*pargs.r.ret_str)
1341 opt.def_recipient = xstrdup (pargs.r.ret_str);
1342 break;
1343 case oDefRecipientSelf:
1344 xfree (opt.def_recipient);
1345 opt.def_recipient = NULL;
1346 opt.def_recipient_self = 1;
1347 break;
1348 case oNoDefRecipient:
1349 xfree (opt.def_recipient);
1350 opt.def_recipient = NULL;
1351 opt.def_recipient_self = 0;
1352 break;
1353
1354 case oWithKeyData: opt.with_key_data=1; /* fall through */
1355 case oWithColons: ctrl.with_colons = 1; break;
1356 case oWithSecret: ctrl.with_secret = 1; break;
1357 case oWithValidation: ctrl.with_validation=1; break;
1358 case oWithEphemeralKeys: ctrl.with_ephemeral_keys=1; break;
1359
1360 case oSkipVerify: opt.skip_verify=1; break;
1361
1362 case oNoEncryptTo: opt.no_encrypt_to = 1; break;
1363 case oEncryptTo: /* Store the recipient in the second list */
1364 sl = add_to_strlist (&remusr, pargs.r.ret_str);
1365 sl->flags = 1;
1366 break;
1367
1368 case oRecipient: /* store the recipient */
1369 add_to_strlist ( &remusr, pargs.r.ret_str);
1370 break;
1371
1372 case oUser: /* Store the local users, the first one is the default */
1373 if (!opt.local_user)
1374 opt.local_user = xstrdup (pargs.r.ret_str);
1375 add_to_strlist (&locusr, pargs.r.ret_str);
1376 break;
1377
1378 case oNoSecmemWarn:
1379 gcry_control (GCRYCTL_DISABLE_SECMEM_WARN);
1380 break;
1381
1382 case oCipherAlgo:
1383 opt.def_cipher_algoid = pargs.r.ret_str;
1384 break;
1385
1386 case oDisableCipherAlgo:
1387 {
1388 int algo = gcry_cipher_map_name (pargs.r.ret_str);
1389 gcry_cipher_ctl (NULL, GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
1390 }
1391 break;
1392 case oDisablePubkeyAlgo:
1393 {
1394 int algo = gcry_pk_map_name (pargs.r.ret_str);
1395 gcry_pk_ctl (GCRYCTL_DISABLE_ALGO,&algo, sizeof algo );
1396 }
1397 break;
1398
1399 case oDigestAlgo:
1400 forced_digest_algo = pargs.r.ret_str;
1401 break;
1402
1403 case oExtraDigestAlgo:
1404 extra_digest_algo = pargs.r.ret_str;
1405 break;
1406
1407 case oIgnoreTimeConflict: opt.ignore_time_conflict = 1; break;
1408 case oNoRandomSeedFile: use_random_seed = 0; break;
1409 case oNoCommonCertsImport: no_common_certs_import = 1; break;
1410
1411 case oEnableSpecialFilenames:
1412 enable_special_filenames ();
1413 break;
1414
1415 case oValidationModel: parse_validation_model (pargs.r.ret_str); break;
1416
1417 case oKeyServer:
1418 append_to_strlist (&opt.keyserver, pargs.r.ret_str);
1419 break;
1420
1421 case oIgnoreCertExtension:
1422 add_to_strlist (&opt.ignored_cert_extensions, pargs.r.ret_str);
1423 break;
1424
1425 case oAuthenticode: opt.authenticode = 1; break;
1426
1427 case oAttribute:
1428 add_to_strlist (&opt.attributes, pargs.r.ret_str);
1429 break;
1430
1431 case oNoAutostart: opt.autostart = 0; break;
1432
1433 case oCompliance:
1434 {
1435 struct gnupg_compliance_option compliance_options[] =
1436 {
1437 { "gnupg", CO_GNUPG },
1438 { "de-vs", CO_DE_VS }
1439 };
1440 int compliance = gnupg_parse_compliance_option
1441 (pargs.r.ret_str, compliance_options, DIM (compliance_options),
1442 opt.quiet);
1443 if (compliance < 0)
1444 log_inc_errorcount (); /* Force later termination. */
1445 opt.compliance = compliance;
1446 }
1447 break;
1448
1449 default:
1450 if (configname)
1451 pargs.err = ARGPARSE_PRINT_WARNING;
1452 else
1453 {
1454 pargs.err = ARGPARSE_PRINT_ERROR;
1455 /* The argparse function calls a plain exit and thus we
1456 * need to print a status here. */
1457 gpgsm_status_with_error (&ctrl, STATUS_FAILURE, "option-parser",
1458 gpg_error (GPG_ERR_GENERAL));
1459 }
1460 break;
1461 }
1462 }
1463
1464 gpgrt_argparse (NULL, &pargs, NULL); /* Release internal state. */
1465
1466 if (!last_configname)
1467 opt.config_filename = gpgrt_fnameconcat (gnupg_homedir (),
1468 GPGSM_NAME EXTSEP_S "conf",
1469 NULL);
1470 else
1471 opt.config_filename = last_configname;
1472
1473 if (log_get_errorcount(0))
1474 {
1475 gpgsm_status_with_error (&ctrl, STATUS_FAILURE,
1476 "option-parser", gpg_error (GPG_ERR_GENERAL));
1477 gpgsm_exit(2);
1478 }
1479
1480 /* Process common component options. */
1481 if (parse_comopt (GNUPG_MODULE_NAME_GPGSM, debug_argparser))
1482 {
1483 gpgsm_status_with_error (&ctrl, STATUS_FAILURE,
1484 "option-parser", gpg_error (GPG_ERR_GENERAL));
1485 gpgsm_exit(2);
1486 }
1487
1488 if (opt.use_keyboxd)
1489 log_info ("Note: Please move option \"%s\" to \"common.conf\"\n",
1490 "use-keyboxd");
1491 opt.use_keyboxd = comopt.use_keyboxd; /* Override. */
1492
1493 if (opt.keyboxd_program)
1494 log_info ("Note: Please move option \"%s\" to \"common.conf\"\n",
1495 "keyboxd-program");
1496 if (!opt.keyboxd_program && comopt.keyboxd_program)
1497 {
1498 opt.keyboxd_program = comopt.keyboxd_program;
1499 comopt.keyboxd_program = NULL;
1500 }
1501
1502 if (pwfd != -1) /* Read the passphrase now. */
1503 read_passphrase_from_fd (pwfd);
1504
1505 /* Now that we have the options parsed we need to update the default
1506 control structure. */
1507 gpgsm_init_default_ctrl (&ctrl);
1508
1509 if (nogreeting)
1510 greeting = 0;
1511
1512 if (greeting)
1513 {
1514 es_fprintf (es_stderr, "%s %s; %s\n",
1515 gpgrt_strusage(11), gpgrt_strusage(13), gpgrt_strusage(14) );
1516 es_fprintf (es_stderr, "%s\n", gpgrt_strusage(15) );
1517 }
1518 #ifdef IS_DEVELOPMENT_VERSION
1519 if (!opt.batch)
1520 {
1521 log_info ("NOTE: THIS IS A DEVELOPMENT VERSION!\n");
1522 log_info ("It is only intended for test purposes and should NOT be\n");
1523 log_info ("used in a production environment or with production keys!\n");
1524 }
1525 #endif
1526
1527 if (may_coredump && !opt.quiet)
1528 log_info (_("WARNING: program may create a core file!\n"));
1529
1530 npth_init ();
1531 assuan_set_system_hooks (ASSUAN_SYSTEM_NPTH);
1532 gpgrt_set_syscall_clamp (npth_unprotect, npth_protect);
1533
1534 /* if (opt.qualsig_approval && !opt.quiet) */
1535 /* log_info (_("This software has officially been approved to " */
1536 /* "create and verify\n" */
1537 /* "qualified signatures according to German law.\n")); */
1538
1539 if (logfile && cmd == aServer)
1540 {
1541 log_set_file (logfile);
1542 log_set_prefix (NULL, GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_TIME | GPGRT_LOG_WITH_PID);
1543 }
1544
1545 if (gnupg_faked_time_p ())
1546 {
1547 gnupg_isotime_t tbuf;
1548
1549 log_info (_("WARNING: running with faked system time: "));
1550 gnupg_get_isotime (tbuf);
1551 dump_isotime (tbuf);
1552 log_printf ("\n");
1553 }
1554
1555 /* Print a warning if an argument looks like an option. */
1556 if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
1557 {
1558 int i;
1559
1560 for (i=0; i < argc; i++)
1561 if (argv[i][0] == '-' && argv[i][1] == '-')
1562 log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
1563 }
1564
1565 /*FIXME if (opt.batch) */
1566 /* tty_batchmode (1); */
1567
1568 gcry_control (GCRYCTL_RESUME_SECMEM_WARN);
1569
1570 set_debug ();
1571
1572 /* Although we always use gpgsm_exit, we better install a regular
1573 exit handler so that at least the secure memory gets wiped
1574 out. */
1575 if (atexit (emergency_cleanup))
1576 {
1577 log_error ("atexit failed\n");
1578 gpgsm_exit (2);
1579 }
1580
1581 /* Must do this after dropping setuid, because the mapping functions
1582 may try to load an module and we may have disabled an algorithm.
1583 We remap the commonly used algorithms to the OIDs for
1584 convenience. We need to work with the OIDs because they are used
1585 to check whether the encryption mode is actually available. */
1586 if (!strcmp (opt.def_cipher_algoid, "3DES") )
1587 opt.def_cipher_algoid = "1.2.840.113549.3.7";
1588 else if (!strcmp (opt.def_cipher_algoid, "AES")
1589 || !strcmp (opt.def_cipher_algoid, "AES128"))
1590 opt.def_cipher_algoid = "2.16.840.1.101.3.4.1.2";
1591 else if (!strcmp (opt.def_cipher_algoid, "AES192") )
1592 opt.def_cipher_algoid = "2.16.840.1.101.3.4.1.22";
1593 else if (!strcmp (opt.def_cipher_algoid, "AES256") )
1594 opt.def_cipher_algoid = "2.16.840.1.101.3.4.1.42";
1595 else if (!strcmp (opt.def_cipher_algoid, "SERPENT")
1596 || !strcmp (opt.def_cipher_algoid, "SERPENT128") )
1597 opt.def_cipher_algoid = "1.3.6.1.4.1.11591.13.2.2";
1598 else if (!strcmp (opt.def_cipher_algoid, "SERPENT192") )
1599 opt.def_cipher_algoid = "1.3.6.1.4.1.11591.13.2.22";
1600 else if (!strcmp (opt.def_cipher_algoid, "SERPENT256") )
1601 opt.def_cipher_algoid = "1.3.6.1.4.1.11591.13.2.42";
1602 else if (!strcmp (opt.def_cipher_algoid, "SEED") )
1603 opt.def_cipher_algoid = "1.2.410.200004.1.4";
1604 else if (!strcmp (opt.def_cipher_algoid, "CAMELLIA")
1605 || !strcmp (opt.def_cipher_algoid, "CAMELLIA128") )
1606 opt.def_cipher_algoid = "1.2.392.200011.61.1.1.1.2";
1607 else if (!strcmp (opt.def_cipher_algoid, "CAMELLIA192") )
1608 opt.def_cipher_algoid = "1.2.392.200011.61.1.1.1.3";
1609 else if (!strcmp (opt.def_cipher_algoid, "CAMELLIA256") )
1610 opt.def_cipher_algoid = "1.2.392.200011.61.1.1.1.4";
1611
1612 if (cmd != aGPGConfList)
1613 {
1614 if ( !gcry_cipher_map_name (opt.def_cipher_algoid)
1615 || !gcry_cipher_mode_from_oid (opt.def_cipher_algoid))
1616 log_error (_("selected cipher algorithm is invalid\n"));
1617
1618 if (forced_digest_algo)
1619 {
1620 opt.forced_digest_algo = gcry_md_map_name (forced_digest_algo);
1621 if (our_md_test_algo(opt.forced_digest_algo) )
1622 log_error (_("selected digest algorithm is invalid\n"));
1623 }
1624 if (extra_digest_algo)
1625 {
1626 opt.extra_digest_algo = gcry_md_map_name (extra_digest_algo);
1627 if (our_md_test_algo (opt.extra_digest_algo) )
1628 log_error (_("selected digest algorithm is invalid\n"));
1629 }
1630 }
1631
1632 /* Check our chosen algorithms against the list of allowed
1633 * algorithms in the current compliance mode, and fail hard if it is
1634 * not. This is us being nice to the user informing her early that
1635 * the chosen algorithms are not available. We also check and
1636 * enforce this right before the actual operation. */
1637 if (! gnupg_cipher_is_allowed (opt.compliance,
1638 cmd == aEncr || cmd == aSignEncr,
1639 gcry_cipher_map_name (opt.def_cipher_algoid),
1640 GCRY_CIPHER_MODE_NONE)
1641 && ! gnupg_cipher_is_allowed (opt.compliance,
1642 cmd == aEncr || cmd == aSignEncr,
1643 gcry_cipher_mode_from_oid
1644 (opt.def_cipher_algoid),
1645 GCRY_CIPHER_MODE_NONE))
1646 log_error (_("cipher algorithm '%s' may not be used in %s mode\n"),
1647 opt.def_cipher_algoid,
1648 gnupg_compliance_option_string (opt.compliance));
1649
1650 if (forced_digest_algo
1651 && ! gnupg_digest_is_allowed (opt.compliance,
1652 cmd == aSign
1653 || cmd == aSignEncr
1654 || cmd == aClearsign,
1655 opt.forced_digest_algo))
1656 log_error (_("digest algorithm '%s' may not be used in %s mode\n"),
1657 forced_digest_algo,
1658 gnupg_compliance_option_string (opt.compliance));
1659
1660 if (extra_digest_algo
1661 && ! gnupg_digest_is_allowed (opt.compliance,
1662 cmd == aSign
1663 || cmd == aSignEncr
1664 || cmd == aClearsign,
1665 opt.extra_digest_algo))
1666 log_error (_("digest algorithm '%s' may not be used in %s mode\n"),
1667 extra_digest_algo,
1668 gnupg_compliance_option_string (opt.compliance));
1669
1670 if (log_get_errorcount(0))
1671 {
1672 gpgsm_status_with_error (&ctrl, STATUS_FAILURE, "option-postprocessing",
1673 gpg_error (GPG_ERR_GENERAL));
1674 gpgsm_exit (2);
1675 }
1676
1677 /* Set the random seed file. */
1678 if (use_random_seed)
1679 {
1680 char *p = make_filename (gnupg_homedir (), "random_seed", NULL);
1681 gcry_control (GCRYCTL_SET_RANDOM_SEED_FILE, p);
1682 xfree(p);
1683 }
1684
1685 if (!cmd && opt.fingerprint && !with_fpr)
1686 set_cmd (&cmd, aListKeys);
1687
1688 /* If no pinentry is expected shunt
1689 * gnupg_allow_set_foregound_window to avoid useless error
1690 * messages on Windows. */
1691 if (opt.pinentry_mode != PINENTRY_MODE_ASK)
1692 {
1693 gnupg_inhibit_set_foregound_window (1);
1694 }
1695
1696 /* Add default keybox. */
1697 if (!nrings && default_keyring && !opt.use_keyboxd)
1698 {
1699 int created;
1700
1701 keydb_add_resource (&ctrl, "pubring.kbx", 0, &created);
1702 if (created && !no_common_certs_import)
1703 {
1704 /* Import the standard certificates for a new default keybox. */
1705 char *filelist[2];
1706
1707 filelist[0] = make_filename (gnupg_datadir (),"com-certs.pem", NULL);
1708 filelist[1] = NULL;
1709 if (!gnupg_access (filelist[0], F_OK))
1710 {
1711 log_info (_("importing common certificates '%s'\n"),
1712 filelist[0]);
1713 gpgsm_import_files (&ctrl, 1, filelist, open_read);
1714 }
1715 xfree (filelist[0]);
1716 }
1717 }
1718 if (!opt.use_keyboxd)
1719 {
1720 for (sl = nrings; sl; sl = sl->next)
1721 keydb_add_resource (&ctrl, sl->d, 0, NULL);
1722 }
1723 FREE_STRLIST(nrings);
1724
1725
1726 /* Prepare the audit log feature for certain commands. */
1727 if (auditlog || htmlauditlog)
1728 {
1729 switch (cmd)
1730 {
1731 case aEncr:
1732 case aSign:
1733 case aDecrypt:
1734 case aVerify:
1735 audit_release (ctrl.audit);
1736 ctrl.audit = audit_new ();
1737 if (auditlog)
1738 auditfp = open_es_fwrite (auditlog);
1739 if (htmlauditlog)
1740 htmlauditfp = open_es_fwrite (htmlauditlog);
1741 break;
1742 default:
1743 break;
1744 }
1745 }
1746
1747
1748 if (!do_not_setup_keys)
1749 {
1750 int errcount = log_get_errorcount (0);
1751
1752 for (sl = locusr; sl ; sl = sl->next)
1753 {
1754 int rc = gpgsm_add_to_certlist (&ctrl, sl->d, 1, &signerlist, 0);
1755 if (rc)
1756 {
1757 log_error (_("can't sign using '%s': %s\n"),
1758 sl->d, gpg_strerror (rc));
1759 gpgsm_status2 (&ctrl, STATUS_INV_SGNR,
1760 get_inv_recpsgnr_code (rc), sl->d, NULL);
1761 gpgsm_status2 (&ctrl, STATUS_INV_RECP,
1762 get_inv_recpsgnr_code (rc), sl->d, NULL);
1763 }
1764 }
1765
1766 /* Build the recipient list. We first add the regular ones and then
1767 the encrypt-to ones because the underlying function will silently
1768 ignore duplicates and we can't allow keeping a duplicate which is
1769 flagged as encrypt-to as the actually encrypt function would then
1770 complain about no (regular) recipients. */
1771 for (sl = remusr; sl; sl = sl->next)
1772 if (!(sl->flags & 1))
1773 do_add_recipient (&ctrl, sl->d, &recplist, 0, recp_required);
1774 if (!opt.no_encrypt_to)
1775 {
1776 for (sl = remusr; sl; sl = sl->next)
1777 if ((sl->flags & 1))
1778 do_add_recipient (&ctrl, sl->d, &recplist, 1, recp_required);
1779 }
1780
1781 /* We do not require a recipient for decryption but because
1782 * recipients and signers are always checked and log_error is
1783 * sometimes used (for failed signing keys or due to a failed
1784 * CRL checking) that would have bumbed up the error counter.
1785 * We clear the counter in the decryption case because there is
1786 * no reason to force decryption to fail. */
1787 if (cmd == aDecrypt && !errcount)
1788 log_get_errorcount (1); /* clear counter */
1789 }
1790
1791 if (log_get_errorcount(0))
1792 gpgsm_exit(1); /* Must stop for invalid recipients. */
1793
1794 /* Dispatch command. */
1795 switch (cmd)
1796 {
1797 case aGPGConfList:
1798 { /* List default option values in the GPG Conf format. */
1799
1800 es_printf ("debug-level:%lu:\"none:\n", GC_OPT_FLAG_DEFAULT);
1801 es_printf ("include-certs:%lu:%d:\n", GC_OPT_FLAG_DEFAULT,
1802 DEFAULT_INCLUDE_CERTS);
1803 es_printf ("cipher-algo:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT,
1804 DEFAULT_CIPHER_ALGO);
1805 es_printf ("p12-charset:%lu:\n", GC_OPT_FLAG_DEFAULT);
1806 es_printf ("default-key:%lu:\n", GC_OPT_FLAG_DEFAULT);
1807 es_printf ("encrypt-to:%lu:\n", GC_OPT_FLAG_DEFAULT);
1808
1809 /* The next one is an info only item and should match what
1810 proc_parameters actually implements. */
1811 es_printf ("default_pubkey_algo:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT,
1812 "RSA-3072");
1813
1814 }
1815 break;
1816 case aGPGConfTest:
1817 /* This is merely a dummy command to test whether the
1818 configuration file is valid. */
1819 break;
1820
1821 case aServer:
1822 if (debug_wait)
1823 {
1824 log_debug ("waiting for debugger - my pid is %u .....\n",
1825 (unsigned int)getpid());
1826 gnupg_sleep (debug_wait);
1827 log_debug ("... okay\n");
1828 }
1829 gpgsm_server (recplist);
1830 break;
1831
1832 case aCallDirmngr:
1833 if (!argc)
1834 wrong_args ("--call-dirmngr <command> {args}");
1835 else
1836 if (gpgsm_dirmngr_run_command (&ctrl, *argv, argc-1, argv+1))
1837 gpgsm_exit (1);
1838 break;
1839
1840 case aCallProtectTool:
1841 run_protect_tool (argc, argv);
1842 break;
1843
1844 case aEncr: /* Encrypt the given file. */
1845 {
1846 estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
1847
1848 set_binary (stdin);
1849
1850 if (!argc) /* Source is stdin. */
1851 err = gpgsm_encrypt (&ctrl, recplist, 0, fp);
1852 else if (argc == 1) /* Source is the given file. */
1853 err = gpgsm_encrypt (&ctrl, recplist, open_read (*argv), fp);
1854 else
1855 wrong_args ("--encrypt [datafile]");
1856
1857 if (err)
1858 gpgrt_fcancel (fp);
1859 else
1860 es_fclose (fp);
1861 }
1862 break;
1863
1864 case aSign: /* Sign the given file. */
1865 {
1866 estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
1867
1868 /* Fixme: We should also allow concatenation of multiple files for
1869 signing because that is what gpg does.*/
1870 set_binary (stdin);
1871 if (!argc) /* Create from stdin. */
1872 err = gpgsm_sign (&ctrl, signerlist, 0, detached_sig, fp);
1873 else if (argc == 1) /* From file. */
1874 err = gpgsm_sign (&ctrl, signerlist,
1875 open_read (*argv), detached_sig, fp);
1876 else
1877 wrong_args ("--sign [datafile]");
1878
1879 #if GPGRT_VERSION_NUMBER >= 0x012700 /* >= 1.39 */
1880 if (err)
1881 gpgrt_fcancel (fp);
1882 else
1883 es_fclose (fp);
1884 #else
1885 (void)err;
1886 es_fclose (fp);
1887 #endif
1888 }
1889 break;
1890
1891 case aSignEncr: /* sign and encrypt the given file */
1892 log_error ("this command has not yet been implemented\n");
1893 break;
1894
1895 case aClearsign: /* make a clearsig */
1896 log_error ("this command has not yet been implemented\n");
1897 break;
1898
1899 case aVerify:
1900 {
1901 estream_t fp = NULL;
1902
1903 set_binary (stdin);
1904 if (argc == 2 && opt.outfile)
1905 log_info ("option --output ignored for a detached signature\n");
1906 else if (opt.outfile)
1907 fp = open_es_fwrite (opt.outfile);
1908
1909 if (!argc)
1910 gpgsm_verify (&ctrl, 0, -1, fp); /* normal signature from stdin */
1911 else if (argc == 1)
1912 gpgsm_verify (&ctrl, open_read (*argv), -1, fp); /* std signature */
1913 else if (argc == 2) /* detached signature (sig, detached) */
1914 gpgsm_verify (&ctrl, open_read (*argv), open_read (argv[1]), NULL);
1915 else
1916 wrong_args ("--verify [signature [detached_data]]");
1917
1918 es_fclose (fp);
1919 }
1920 break;
1921
1922 case aDecrypt:
1923 {
1924 estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
1925
1926 set_binary (stdin);
1927 if (!argc)
1928 err = gpgsm_decrypt (&ctrl, 0, fp); /* from stdin */
1929 else if (argc == 1)
1930 err = gpgsm_decrypt (&ctrl, open_read (*argv), fp); /* from file */
1931 else
1932 wrong_args ("--decrypt [filename]");
1933
1934 if (err)
1935 gpgrt_fcancel (fp);
1936 else
1937 es_fclose (fp);
1938 }
1939 break;
1940
1941 case aDeleteKey:
1942 for (sl=NULL; argc; argc--, argv++)
1943 add_to_strlist (&sl, *argv);
1944 gpgsm_delete (&ctrl, sl);
1945 free_strlist(sl);
1946 break;
1947
1948 case aListChain:
1949 case aDumpChain:
1950 ctrl.with_chain = 1; /* fall through */
1951 case aListKeys:
1952 case aDumpKeys:
1953 case aListExternalKeys:
1954 case aDumpExternalKeys:
1955 case aListSecretKeys:
1956 case aDumpSecretKeys:
1957 {
1958 unsigned int mode;
1959 estream_t fp;
1960
1961 switch (cmd)
1962 {
1963 case aListChain:
1964 case aListKeys: mode = (0 | 0 | (1<<6)); break;
1965 case aDumpChain:
1966 case aDumpKeys: mode = (256 | 0 | (1<<6)); break;
1967 case aListExternalKeys: mode = (0 | 0 | (1<<7)); break;
1968 case aDumpExternalKeys: mode = (256 | 0 | (1<<7)); break;
1969 case aListSecretKeys: mode = (0 | 2 | (1<<6)); break;
1970 case aDumpSecretKeys: mode = (256 | 2 | (1<<6)); break;
1971 default: BUG();
1972 }
1973
1974 fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
1975 for (sl=NULL; argc; argc--, argv++)
1976 add_to_strlist (&sl, *argv);
1977 gpgsm_list_keys (&ctrl, sl, fp, mode);
1978 free_strlist(sl);
1979 es_fclose (fp);
1980 }
1981 break;
1982
1983 case aShowCerts:
1984 {
1985 estream_t fp;
1986
1987 fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
1988 gpgsm_show_certs (&ctrl, argc, argv, fp);
1989 es_fclose (fp);
1990 }
1991 break;
1992
1993 case aKeygen: /* Generate a key; well kind of. */
1994 {
1995 estream_t fpin = NULL;
1996 estream_t fpout;
1997
1998 if (opt.batch)
1999 {
2000 if (!argc) /* Create from stdin. */
2001 fpin = open_es_fread ("-", "r");
2002 else if (argc == 1) /* From file. */
2003 fpin = open_es_fread (*argv, "r");
2004 else
2005 wrong_args ("--generate-key --batch [parmfile]");
2006 }
2007
2008 fpout = open_es_fwrite (opt.outfile?opt.outfile:"-");
2009
2010 if (fpin)
2011 gpgsm_genkey (&ctrl, fpin, fpout);
2012 else
2013 gpgsm_gencertreq_tty (&ctrl, fpout);
2014
2015 es_fclose (fpout);
2016 }
2017 break;
2018
2019
2020 case aImport:
2021 gpgsm_import_files (&ctrl, argc, argv, open_read);
2022 break;
2023
2024 case aExport:
2025 {
2026 estream_t fp;
2027
2028 fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
2029 for (sl=NULL; argc; argc--, argv++)
2030 add_to_strlist (&sl, *argv);
2031 gpgsm_export (&ctrl, sl, fp);
2032 free_strlist(sl);
2033 es_fclose (fp);
2034 }
2035 break;
2036
2037 case aExportSecretKeyP12:
2038 {
2039 estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
2040
2041 if (argc == 1)
2042 gpgsm_p12_export (&ctrl, *argv, fp, 0);
2043 else
2044 wrong_args ("--export-secret-key-p12 KEY-ID");
2045 if (fp != es_stdout)
2046 es_fclose (fp);
2047 }
2048 break;
2049
2050 case aExportSecretKeyP8:
2051 {
2052 estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
2053
2054 if (argc == 1)
2055 gpgsm_p12_export (&ctrl, *argv, fp, 1);
2056 else
2057 wrong_args ("--export-secret-key-p8 KEY-ID");
2058 if (fp != es_stdout)
2059 es_fclose (fp);
2060 }
2061 break;
2062
2063 case aExportSecretKeyRaw:
2064 {
2065 estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
2066
2067 if (argc == 1)
2068 gpgsm_p12_export (&ctrl, *argv, fp, 2);
2069 else
2070 wrong_args ("--export-secret-key-raw KEY-ID");
2071 if (fp != es_stdout)
2072 es_fclose (fp);
2073 }
2074 break;
2075
2076 case aSendKeys:
2077 case aRecvKeys:
2078 log_error ("this command has not yet been implemented\n");
2079 break;
2080
2081
2082 case aLearnCard:
2083 if (argc)
2084 wrong_args ("--learn-card");
2085 else
2086 {
2087 int rc = gpgsm_agent_learn (&ctrl);
2088 if (rc)
2089 log_error ("error learning card: %s\n", gpg_strerror (rc));
2090 }
2091 break;
2092
2093 case aPasswd:
2094 if (argc != 1)
2095 wrong_args ("--change-passphrase <key-Id>");
2096 else
2097 {
2098 int rc;
2099 ksba_cert_t cert = NULL;
2100 char *grip = NULL;
2101
2102 rc = gpgsm_find_cert (&ctrl, *argv, NULL, &cert, 0);
2103 if (rc)
2104 ;
2105 else if (!(grip = gpgsm_get_keygrip_hexstring (cert)))
2106 rc = gpg_error (GPG_ERR_BUG);
2107 else
2108 {
2109 char *desc = gpgsm_format_keydesc (cert);
2110 rc = gpgsm_agent_passwd (&ctrl, grip, desc);
2111 xfree (desc);
2112 }
2113 if (rc)
2114 log_error ("error changing passphrase: %s\n", gpg_strerror (rc));
2115 xfree (grip);
2116 ksba_cert_release (cert);
2117 }
2118 break;
2119
2120 case aKeydbClearSomeCertFlags:
2121 for (sl=NULL; argc; argc--, argv++)
2122 add_to_strlist (&sl, *argv);
2123 keydb_clear_some_cert_flags (&ctrl, sl);
2124 free_strlist(sl);
2125 break;
2126
2127
2128 default:
2129 log_error (_("invalid command (there is no implicit command)\n"));
2130 break;
2131 }
2132
2133 /* Print the audit result if needed. */
2134 if ((auditlog && auditfp) || (htmlauditlog && htmlauditfp))
2135 {
2136 if (auditlog && auditfp)
2137 audit_print_result (ctrl.audit, auditfp, 0);
2138 if (htmlauditlog && htmlauditfp)
2139 audit_print_result (ctrl.audit, htmlauditfp, 1);
2140 audit_release (ctrl.audit);
2141 ctrl.audit = NULL;
2142 es_fclose (auditfp);
2143 es_fclose (htmlauditfp);
2144 }
2145
2146 /* cleanup */
2147 gpgsm_deinit_default_ctrl (&ctrl);
2148 free_strlist (opt.keyserver);
2149 opt.keyserver = NULL;
2150 gpgsm_release_certlist (recplist);
2151 gpgsm_release_certlist (signerlist);
2152 FREE_STRLIST (remusr);
2153 FREE_STRLIST (locusr);
2154 gpgsm_exit(0);
2155 return 8; /*NOTREACHED*/
2156 }
2157
2158 /* Note: This function is used by signal handlers!. */
2159 static void
emergency_cleanup(void)2160 emergency_cleanup (void)
2161 {
2162 gcry_control (GCRYCTL_TERM_SECMEM );
2163 }
2164
2165
2166 void
gpgsm_exit(int rc)2167 gpgsm_exit (int rc)
2168 {
2169 gcry_control (GCRYCTL_UPDATE_RANDOM_SEED_FILE);
2170 if (opt.debug & DBG_MEMSTAT_VALUE)
2171 {
2172 gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
2173 gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
2174 }
2175 if (opt.debug)
2176 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
2177 emergency_cleanup ();
2178 rc = rc? rc : log_get_errorcount(0)? 2 : gpgsm_errors_seen? 1 : 0;
2179 exit (rc);
2180 }
2181
2182
2183 void
gpgsm_init_default_ctrl(struct server_control_s * ctrl)2184 gpgsm_init_default_ctrl (struct server_control_s *ctrl)
2185 {
2186 ctrl->include_certs = default_include_certs;
2187 ctrl->use_ocsp = opt.enable_ocsp;
2188 ctrl->validation_model = default_validation_model;
2189 ctrl->offline = opt.disable_dirmngr;
2190 }
2191
2192
2193 /* This function is called to deinitialize a control object. The
2194 * control object is is not released, though. */
2195 void
gpgsm_deinit_default_ctrl(ctrl_t ctrl)2196 gpgsm_deinit_default_ctrl (ctrl_t ctrl)
2197 {
2198 gpgsm_keydb_deinit_session_data (ctrl);
2199 }
2200
2201
2202 int
gpgsm_parse_validation_model(const char * model)2203 gpgsm_parse_validation_model (const char *model)
2204 {
2205 if (!ascii_strcasecmp (model, "shell") )
2206 return 0;
2207 else if ( !ascii_strcasecmp (model, "chain") )
2208 return 1;
2209 else if ( !ascii_strcasecmp (model, "steed") )
2210 return 2;
2211 else
2212 return -1;
2213 }
2214
2215
2216
2217 /* Open the FILENAME for read and return the file descriptor. Stop
2218 with an error message in case of problems. "-" denotes stdin and
2219 if special filenames are allowed the given fd is opened instead. */
2220 static int
open_read(const char * filename)2221 open_read (const char *filename)
2222 {
2223 int fd;
2224
2225 if (filename[0] == '-' && !filename[1])
2226 {
2227 set_binary (stdin);
2228 return 0; /* stdin */
2229 }
2230 fd = check_special_filename (filename, 0, 0);
2231 if (fd != -1)
2232 return fd;
2233 fd = gnupg_open (filename, O_RDONLY | O_BINARY, 0);
2234 if (fd == -1)
2235 {
2236 log_error (_("can't open '%s': %s\n"), filename, strerror (errno));
2237 gpgsm_exit (2);
2238 }
2239 return fd;
2240 }
2241
2242 /* Same as open_read but return an estream_t. */
2243 static estream_t
open_es_fread(const char * filename,const char * mode)2244 open_es_fread (const char *filename, const char *mode)
2245 {
2246 int fd;
2247 estream_t fp;
2248
2249 if (filename[0] == '-' && !filename[1])
2250 fd = fileno (stdin);
2251 else
2252 fd = check_special_filename (filename, 0, 0);
2253 if (fd != -1)
2254 {
2255 fp = es_fdopen_nc (fd, mode);
2256 if (!fp)
2257 {
2258 log_error ("es_fdopen(%d) failed: %s\n", fd, strerror (errno));
2259 gpgsm_exit (2);
2260 }
2261 return fp;
2262 }
2263 fp = es_fopen (filename, mode);
2264 if (!fp)
2265 {
2266 log_error (_("can't open '%s': %s\n"), filename, strerror (errno));
2267 gpgsm_exit (2);
2268 }
2269 return fp;
2270 }
2271
2272
2273 /* Open FILENAME for fwrite and return an extended stream. Stop with
2274 an error message in case of problems. "-" denotes stdout and if
2275 special filenames are allowed the given fd is opened instead.
2276 Caller must close the returned stream. */
2277 static estream_t
open_es_fwrite(const char * filename)2278 open_es_fwrite (const char *filename)
2279 {
2280 int fd;
2281 estream_t fp;
2282
2283 if (filename[0] == '-' && !filename[1])
2284 {
2285 fflush (stdout);
2286 fp = es_fdopen_nc (fileno(stdout), "wb");
2287 return fp;
2288 }
2289
2290 fd = check_special_filename (filename, 1, 0);
2291 if (fd != -1)
2292 {
2293 fp = es_fdopen_nc (fd, "wb");
2294 if (!fp)
2295 {
2296 log_error ("es_fdopen(%d) failed: %s\n", fd, strerror (errno));
2297 gpgsm_exit (2);
2298 }
2299 return fp;
2300 }
2301 fp = es_fopen (filename, "wb");
2302 if (!fp)
2303 {
2304 log_error (_("can't open '%s': %s\n"), filename, strerror (errno));
2305 gpgsm_exit (2);
2306 }
2307 return fp;
2308 }
2309
2310
2311 static void
run_protect_tool(int argc,char ** argv)2312 run_protect_tool (int argc, char **argv)
2313 {
2314 #ifdef HAVE_W32_SYSTEM
2315 (void)argc;
2316 (void)argv;
2317 #else
2318 const char *pgm;
2319 char **av;
2320 int i;
2321
2322 if (!opt.protect_tool_program || !*opt.protect_tool_program)
2323 pgm = gnupg_module_name (GNUPG_MODULE_NAME_PROTECT_TOOL);
2324 else
2325 pgm = opt.protect_tool_program;
2326
2327 av = xcalloc (argc+2, sizeof *av);
2328 av[0] = strrchr (pgm, '/');
2329 if (!av[0])
2330 av[0] = xstrdup (pgm);
2331 for (i=1; argc; i++, argc--, argv++)
2332 av[i] = *argv;
2333 av[i] = NULL;
2334 execv (pgm, av);
2335 log_error ("error executing '%s': %s\n", pgm, strerror (errno));
2336 #endif /*!HAVE_W32_SYSTEM*/
2337 gpgsm_exit (2);
2338 }
2339