1 /* gpgsm.c - GnuPG for S/MIME
2 * Copyright (C) 2001-2008, 2010 Free Software Foundation, Inc.
3 * Copyright (C) 2001-2008, 2010 Werner Koch
5 * This file is part of GnuPG.
7 * GnuPG is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * GnuPG is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, see <https://www.gnu.org/licenses/>.
29 /*#include <mcheck.h>*/
33 #include <assuan.h> /* malloc hooks */
35 #include "passphrase.h"
36 #include "../common/shareddefs.h"
37 #include "../kbx/keybox.h" /* malloc hooks */
41 #include "gc-opt-flags.h"
43 #include "../common/init.h"
50 enum cmd_and_opt_values {
58 aListSecretKeys = 'K',
92 aKeydbClearSomeCertFlags,
102 oDebugNoChainValidation,
103 oDebugIgnoreExpiration,
109 oEnableSpecialFilenames,
119 oPreferSystemDirmngr,
140 oDisableTrustedCertCRLCheck,
141 oEnableTrustedCertCRLCheck,
149 oDisablePolicyChecks,
151 oAutoIssuerKeyRetrieve,
190 oNoCommonCertsImport,
191 oIgnoreCertExtension,
196 static ARGPARSE_OPTS opts[] = {
198 ARGPARSE_group (300, N_("@Commands:\n ")),
200 ARGPARSE_c (aSign, "sign", N_("make a signature")),
201 /*ARGPARSE_c (aClearsign, "clearsign", N_("make a clear text signature") ),*/
202 ARGPARSE_c (aDetachedSign, "detach-sign", N_("make a detached signature")),
203 ARGPARSE_c (aEncr, "encrypt", N_("encrypt data")),
204 /*ARGPARSE_c (aSym, "symmetric", N_("encryption only with symmetric cipher")),*/
205 ARGPARSE_c (aDecrypt, "decrypt", N_("decrypt data (default)")),
206 ARGPARSE_c (aVerify, "verify", N_("verify a signature")),
207 ARGPARSE_c (aListKeys, "list-keys", N_("list keys")),
208 ARGPARSE_c (aListExternalKeys, "list-external-keys",
209 N_("list external keys")),
210 ARGPARSE_c (aListSecretKeys, "list-secret-keys", N_("list secret keys")),
211 ARGPARSE_c (aListChain, "list-chain", N_("list certificate chain")),
212 ARGPARSE_c (aFingerprint, "fingerprint", N_("list keys and fingerprints")),
213 ARGPARSE_c (aKeygen, "generate-key", N_("generate a new key pair")),
214 ARGPARSE_c (aKeygen, "gen-key", "@"),
215 ARGPARSE_c (aDeleteKey, "delete-keys",
216 N_("remove keys from the public keyring")),
217 /*ARGPARSE_c (aSendKeys, "send-keys", N_("export keys to a keyserver")),*/
218 /*ARGPARSE_c (aRecvKeys, "recv-keys", N_("import keys from a keyserver")),*/
219 ARGPARSE_c (aImport, "import", N_("import certificates")),
220 ARGPARSE_c (aExport, "export", N_("export certificates")),
222 /* We use -raw and not -p1 for pkcs#1 secret key export so that it
223 won't accidentally be used in case -p12 was intended. */
224 ARGPARSE_c (aExportSecretKeyP12, "export-secret-key-p12", "@"),
225 ARGPARSE_c (aExportSecretKeyP8, "export-secret-key-p8", "@"),
226 ARGPARSE_c (aExportSecretKeyRaw, "export-secret-key-raw", "@"),
228 ARGPARSE_c (aLearnCard, "learn-card", N_("register a smartcard")),
229 ARGPARSE_c (aServer, "server", N_("run in server mode")),
230 ARGPARSE_c (aCallDirmngr, "call-dirmngr",
231 N_("pass a command to the dirmngr")),
232 ARGPARSE_c (aCallProtectTool, "call-protect-tool",
233 N_("invoke gpg-protect-tool")),
234 ARGPARSE_c (aPasswd, "change-passphrase", N_("change a passphrase")),
235 ARGPARSE_c (aPasswd, "passwd", "@"),
236 ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"),
237 ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"),
239 ARGPARSE_c (aDumpKeys, "dump-cert", "@"),
240 ARGPARSE_c (aDumpKeys, "dump-keys", "@"),
241 ARGPARSE_c (aDumpChain, "dump-chain", "@"),
242 ARGPARSE_c (aDumpExternalKeys, "dump-external-keys", "@"),
243 ARGPARSE_c (aDumpSecretKeys, "dump-secret-keys", "@"),
244 ARGPARSE_c (aKeydbClearSomeCertFlags, "keydb-clear-some-cert-flags", "@"),
246 ARGPARSE_group (301, N_("@\nOptions:\n ")),
248 ARGPARSE_s_n (oArmor, "armor", N_("create ascii armored output")),
249 ARGPARSE_s_n (oArmor, "armour", "@"),
250 ARGPARSE_s_n (oBase64, "base64", N_("create base-64 encoded output")),
252 ARGPARSE_s_s (oP12Charset, "p12-charset", "@"),
254 ARGPARSE_s_i (oPassphraseFD, "passphrase-fd", "@"),
255 ARGPARSE_s_s (oPinentryMode, "pinentry-mode", "@"),
257 ARGPARSE_s_n (oAssumeArmor, "assume-armor",
258 N_("assume input is in PEM format")),
259 ARGPARSE_s_n (oAssumeBase64, "assume-base64",
260 N_("assume input is in base-64 format")),
261 ARGPARSE_s_n (oAssumeBinary, "assume-binary",
262 N_("assume input is in binary format")),
264 ARGPARSE_s_s (oRecipient, "recipient", N_("|USER-ID|encrypt for USER-ID")),
266 ARGPARSE_s_n (oPreferSystemDirmngr,"prefer-system-dirmngr", "@"),
268 ARGPARSE_s_n (oDisableCRLChecks, "disable-crl-checks",
269 N_("never consult a CRL")),
270 ARGPARSE_s_n (oEnableCRLChecks, "enable-crl-checks", "@"),
271 ARGPARSE_s_n (oDisableTrustedCertCRLCheck,
272 "disable-trusted-cert-crl-check", "@"),
273 ARGPARSE_s_n (oEnableTrustedCertCRLCheck,
274 "enable-trusted-cert-crl-check", "@"),
276 ARGPARSE_s_n (oForceCRLRefresh, "force-crl-refresh", "@"),
278 ARGPARSE_s_n (oDisableOCSP, "disable-ocsp", "@"),
279 ARGPARSE_s_n (oEnableOCSP, "enable-ocsp", N_("check validity using OCSP")),
281 ARGPARSE_s_s (oValidationModel, "validation-model", "@"),
283 ARGPARSE_s_i (oIncludeCerts, "include-certs",
284 N_("|N|number of certificates to include") ),
286 ARGPARSE_s_s (oPolicyFile, "policy-file",
287 N_("|FILE|take policy information from FILE")),
289 ARGPARSE_s_n (oDisablePolicyChecks, "disable-policy-checks",
290 N_("do not check certificate policies")),
291 ARGPARSE_s_n (oEnablePolicyChecks, "enable-policy-checks", "@"),
293 ARGPARSE_s_n (oAutoIssuerKeyRetrieve, "auto-issuer-key-retrieve",
294 N_("fetch missing issuer certificates")),
296 ARGPARSE_s_s (oEncryptTo, "encrypt-to", "@"),
297 ARGPARSE_s_n (oNoEncryptTo, "no-encrypt-to", "@"),
299 ARGPARSE_s_s (oUser, "local-user",
300 N_("|USER-ID|use USER-ID to sign or decrypt")),
302 ARGPARSE_s_s (oOutput, "output", N_("|FILE|write output to FILE")),
303 ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
304 ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")),
305 ARGPARSE_s_n (oNoTTY, "no-tty", N_("don't use the terminal at all")),
306 ARGPARSE_s_s (oLogFile, "log-file",
307 N_("|FILE|write a server mode log to FILE")),
308 ARGPARSE_s_n (oNoLogFile, "no-log-file", "@"),
309 ARGPARSE_s_i (oLoggerFD, "logger-fd", "@"),
311 ARGPARSE_s_s (oAuditLog, "audit-log",
312 N_("|FILE|write an audit log to FILE")),
313 ARGPARSE_s_s (oHtmlAuditLog, "html-audit-log", "@"),
314 ARGPARSE_s_n (oDryRun, "dry-run", N_("do not make any changes")),
315 ARGPARSE_s_n (oBatch, "batch", N_("batch mode: never ask")),
316 ARGPARSE_s_n (oAnswerYes, "yes", N_("assume yes on most questions")),
317 ARGPARSE_s_n (oAnswerNo, "no", N_("assume no on most questions")),
319 ARGPARSE_s_s (oKeyring, "keyring",
320 N_("|FILE|add keyring to the list of keyrings")),
322 ARGPARSE_s_s (oDefaultKey, "default-key",
323 N_("|USER-ID|use USER-ID as default secret key")),
326 /* ARGPARSE_s_s (oDefRecipient, "default-recipient", */
327 /* N_("|NAME|use NAME as default recipient")), */
328 /* ARGPARSE_s_n (oDefRecipientSelf, "default-recipient-self", */
329 /* N_("use the default key as default recipient")), */
330 /* ARGPARSE_s_n (oNoDefRecipient, "no-default-recipient", "@"), */
332 ARGPARSE_s_s (oKeyServer, "keyserver",
333 N_("|SPEC|use this keyserver to lookup keys")),
334 ARGPARSE_s_s (oOptions, "options", N_("|FILE|read options from FILE")),
336 ARGPARSE_s_s (oDebug, "debug", "@"),
337 ARGPARSE_s_s (oDebugLevel, "debug-level",
338 N_("|LEVEL|set the debugging level to LEVEL")),
339 ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
340 ARGPARSE_s_n (oDebugNone, "debug-none", "@"),
341 ARGPARSE_s_i (oDebugWait, "debug-wait", "@"),
342 ARGPARSE_s_n (oDebugAllowCoreDump, "debug-allow-core-dump", "@"),
343 ARGPARSE_s_n (oDebugNoChainValidation, "debug-no-chain-validation", "@"),
344 ARGPARSE_s_n (oDebugIgnoreExpiration, "debug-ignore-expiration", "@"),
346 ARGPARSE_s_i (oStatusFD, "status-fd",
347 N_("|FD|write status info to this FD")),
349 ARGPARSE_s_s (oCipherAlgo, "cipher-algo",
350 N_("|NAME|use cipher algorithm NAME")),
351 ARGPARSE_s_s (oDigestAlgo, "digest-algo",
352 N_("|NAME|use message digest algorithm NAME")),
353 ARGPARSE_s_s (oExtraDigestAlgo, "extra-digest-algo", "@"),
356 ARGPARSE_group (302, N_(
357 "@\n(See the man page for a complete listing of all commands and options)\n"
361 /* Hidden options. */
362 ARGPARSE_s_s (oCompliance, "compliance", "@"),
363 ARGPARSE_s_n (oNoVerbose, "no-verbose", "@"),
364 ARGPARSE_s_n (oEnableSpecialFilenames, "enable-special-filenames", "@"),
365 ARGPARSE_s_n (oNoSecmemWarn, "no-secmem-warning", "@"),
366 ARGPARSE_s_n (oNoArmor, "no-armor", "@"),
367 ARGPARSE_s_n (oNoArmor, "no-armour", "@"),
368 ARGPARSE_s_n (oNoDefKeyring, "no-default-keyring", "@"),
369 ARGPARSE_s_n (oNoGreeting, "no-greeting", "@"),
370 ARGPARSE_s_n (oNoOptions, "no-options", "@"),
371 ARGPARSE_s_s (oHomedir, "homedir", "@"),
372 ARGPARSE_s_s (oAgentProgram, "agent-program", "@"),
373 ARGPARSE_s_s (oDisplay, "display", "@"),
374 ARGPARSE_s_s (oTTYname, "ttyname", "@"),
375 ARGPARSE_s_s (oTTYtype, "ttytype", "@"),
376 ARGPARSE_s_s (oLCctype, "lc-ctype", "@"),
377 ARGPARSE_s_s (oLCmessages, "lc-messages", "@"),
378 ARGPARSE_s_s (oXauthority, "xauthority", "@"),
379 ARGPARSE_s_s (oDirmngrProgram, "dirmngr-program", "@"),
380 ARGPARSE_s_n (oDisableDirmngr, "disable-dirmngr", "@"),
381 ARGPARSE_s_s (oProtectToolProgram, "protect-tool-program", "@"),
382 ARGPARSE_s_s (oFakedSystemTime, "faked-system-time", "@"),
383 ARGPARSE_s_n (oNoBatch, "no-batch", "@"),
384 ARGPARSE_s_n (oWithColons, "with-colons", "@"),
385 ARGPARSE_s_n (oWithKeyData,"with-key-data", "@"),
386 ARGPARSE_s_n (oWithValidation, "with-validation", "@"),
387 ARGPARSE_s_n (oWithMD5Fingerprint, "with-md5-fingerprint", "@"),
388 ARGPARSE_s_n (oWithEphemeralKeys, "with-ephemeral-keys", "@"),
389 ARGPARSE_s_n (oSkipVerify, "skip-verify", "@"),
390 ARGPARSE_s_n (oWithFingerprint, "with-fingerprint", "@"),
391 ARGPARSE_s_n (oWithKeygrip, "with-keygrip", "@"),
392 ARGPARSE_s_n (oWithSecret, "with-secret", "@"),
393 ARGPARSE_s_s (oDisableCipherAlgo, "disable-cipher-algo", "@"),
394 ARGPARSE_s_s (oDisablePubkeyAlgo, "disable-pubkey-algo", "@"),
395 ARGPARSE_s_n (oIgnoreTimeConflict, "ignore-time-conflict", "@"),
396 ARGPARSE_s_n (oNoRandomSeedFile, "no-random-seed-file", "@"),
397 ARGPARSE_s_n (oNoCommonCertsImport, "no-common-certs-import", "@"),
398 ARGPARSE_s_s (oIgnoreCertExtension, "ignore-cert-extension", "@"),
399 ARGPARSE_s_n (oNoAutostart, "no-autostart", "@"),
401 /* Command aliases. */
402 ARGPARSE_c (aListKeys, "list-key", "@"),
403 ARGPARSE_c (aListChain, "list-signatures", "@"),
404 ARGPARSE_c (aListChain, "list-sigs", "@"),
405 ARGPARSE_c (aListChain, "check-signatures", "@"),
406 ARGPARSE_c (aListChain, "check-sigs", "@"),
407 ARGPARSE_c (aDeleteKey, "delete-key", "@"),
413 /* The list of supported debug flags. */
414 static struct debug_flags_s debug_flags [] =
416 { DBG_X509_VALUE , "x509" },
417 { DBG_MPI_VALUE , "mpi" },
418 { DBG_CRYPTO_VALUE , "crypto" },
419 { DBG_MEMORY_VALUE , "memory" },
420 { DBG_CACHE_VALUE , "cache" },
421 { DBG_MEMSTAT_VALUE, "memstat" },
422 { DBG_HASHING_VALUE, "hashing" },
423 { DBG_IPC_VALUE , "ipc" },
428 /* Global variable to keep an error count. */
429 int gpgsm_errors_seen = 0;
431 /* It is possible that we are currentlu running under setuid permissions */
432 static int maybe_setuid = 1;
434 /* Helper to implement --debug-level and --debug*/
435 static const char *debug_level;
436 static unsigned int debug_value;
438 /* Default value for include-certs. We need an extra macro for
439 gpgconf-list because the variable will be changed by the command
442 It is often cumbersome to locate intermediate certificates, thus by
443 default we include all certificates in the chain. However we leave
444 out the root certificate because that would make it too easy for
445 the recipient to import that root certificate. A root certificate
446 should be installed only after due checks and thus it won't help to
447 send it along with each message. */
448 #define DEFAULT_INCLUDE_CERTS -2 /* Include all certs but root. */
449 static int default_include_certs = DEFAULT_INCLUDE_CERTS;
451 /* Whether the chain mode shall be used for validation. */
452 static int default_validation_model;
454 /* The default cipher algo. */
455 #define DEFAULT_CIPHER_ALGO "AES"
458 static char *build_list (const char *text,
459 const char *(*mapf)(int), int (*chkf)(int));
460 static void set_cmd (enum cmd_and_opt_values *ret_cmd,
461 enum cmd_and_opt_values new_cmd );
463 static void emergency_cleanup (void);
464 static int open_read (const char *filename);
465 static estream_t open_es_fread (const char *filename, const char *mode);
466 static estream_t open_es_fwrite (const char *filename);
467 static void run_protect_tool (int argc, char **argv);
470 our_pk_test_algo (int algo)
476 return gcry_pk_test_algo (algo);
483 our_cipher_test_algo (int algo)
487 case GCRY_CIPHER_3DES:
488 case GCRY_CIPHER_AES128:
489 case GCRY_CIPHER_AES192:
490 case GCRY_CIPHER_AES256:
491 case GCRY_CIPHER_SERPENT128:
492 case GCRY_CIPHER_SERPENT192:
493 case GCRY_CIPHER_SERPENT256:
494 case GCRY_CIPHER_SEED:
495 case GCRY_CIPHER_CAMELLIA128:
496 case GCRY_CIPHER_CAMELLIA192:
497 case GCRY_CIPHER_CAMELLIA256:
498 return gcry_cipher_test_algo (algo);
506 our_md_test_algo (int algo)
517 case GCRY_MD_WHIRLPOOL:
518 return gcry_md_test_algo (algo);
526 make_libversion (const char *libname, const char *(*getfnc)(const char*))
533 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
537 result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
538 strcpy (stpcpy (stpcpy (result, libname), " "), s);
544 my_strusage( int level )
546 static char *digests, *pubkeys, *ciphers;
547 static char *ver_gcry, *ver_ksba;
552 case 11: p = "@GPGSM@ (@GNUPG@)";
554 case 13: p = VERSION; break;
555 case 17: p = PRINTABLE_OS_NAME; break;
556 case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
559 case 40: p = _("Usage: @GPGSM@ [options] [files] (-h for help)");
562 p = _("Syntax: @GPGSM@ [options] [files]\n"
563 "Sign, check, encrypt or decrypt using the S/MIME protocol\n"
564 "Default operation depends on the input data\n");
569 ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
574 ver_ksba = make_libversion ("libksba", ksba_check_version);
578 case 31: p = "\nHome: "; break;
579 case 32: p = gnupg_homedir (); break;
580 case 33: p = _("\nSupported algorithms:\n"); break;
583 ciphers = build_list ("Cipher: ", gnupg_cipher_algo_name,
584 our_cipher_test_algo );
589 pubkeys = build_list ("Pubkey: ", gcry_pk_algo_name,
595 digests = build_list("Hash: ", gcry_md_algo_name, our_md_test_algo );
599 default: p = NULL; break;
606 build_list (const char *text, const char * (*mapf)(int), int (*chkf)(int))
609 size_t n=strlen(text)+2;
613 gcry_control (GCRYCTL_DROP_PRIVS); /* drop setuid */
616 for (i=1; i < 400; i++ )
618 n += strlen(mapf(i)) + 2;
619 list = xmalloc (21 + n);
621 for (p=NULL, i=1; i < 400; i++)
626 p = stpcpy (list, text );
628 p = stpcpy (p, ", ");
629 p = stpcpy (p, mapf(i) );
638 /* Set the file pointer into binary mode if required. */
640 set_binary (FILE *fp)
642 #ifdef HAVE_DOSISH_SYSTEM
643 setmode (fileno (fp), O_BINARY);
652 wrong_args (const char *text)
654 fprintf (stderr, _("usage: %s [options] %s\n"), GPGSM_NAME, text);
660 set_opt_session_env (const char *name, const char *value)
664 err = session_env_setenv (opt.session_env, name, value);
666 log_fatal ("error setting session environment: %s\n",
671 /* Setup the debugging. With a DEBUG_LEVEL of NULL only the active
672 debug flags are propagated to the subsystems. With DEBUG_LEVEL
673 set, a specific set of debug flags is set; and individual debugging
674 flags will be added on top. */
678 int numok = (debug_level && digitp (debug_level));
679 int numlvl = numok? atoi (debug_level) : 0;
683 else if (!strcmp (debug_level, "none") || (numok && numlvl < 1))
685 else if (!strcmp (debug_level, "basic") || (numok && numlvl <= 2))
686 opt.debug = DBG_IPC_VALUE;
687 else if (!strcmp (debug_level, "advanced") || (numok && numlvl <= 5))
688 opt.debug = DBG_IPC_VALUE|DBG_X509_VALUE;
689 else if (!strcmp (debug_level, "expert") || (numok && numlvl <= 8))
690 opt.debug = (DBG_IPC_VALUE|DBG_X509_VALUE
691 |DBG_CACHE_VALUE|DBG_CRYPTO_VALUE);
692 else if (!strcmp (debug_level, "guru") || numok)
695 /* Unless the "guru" string has been used we don't want to allow
696 hashing debugging. The rationale is that people tend to
697 select the highest debug value and would then clutter their
698 disk with debug files which may reveal confidential data. */
700 opt.debug &= ~(DBG_HASHING_VALUE);
704 log_error (_("invalid debug-level '%s' given\n"), debug_level);
708 opt.debug |= debug_value;
710 if (opt.debug && !opt.verbose)
715 if (opt.debug & DBG_MPI_VALUE)
716 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
717 if (opt.debug & DBG_CRYPTO_VALUE )
718 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
719 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
722 parse_debug_flag (NULL, &opt.debug, debug_flags);
728 set_cmd (enum cmd_and_opt_values *ret_cmd, enum cmd_and_opt_values new_cmd)
730 enum cmd_and_opt_values cmd = *ret_cmd;
732 if (!cmd || cmd == new_cmd)
734 else if ( cmd == aSign && new_cmd == aEncr )
736 else if ( cmd == aEncr && new_cmd == aSign )
738 else if ( (cmd == aSign && new_cmd == aClearsign)
739 || (cmd == aClearsign && new_cmd == aSign) )
743 log_error(_("conflicting commands\n"));
751 /* Helper to add recipients to a list. */
753 do_add_recipient (ctrl_t ctrl, const char *name,
754 certlist_t *recplist, int is_encrypt_to, int recp_required)
756 int rc = gpgsm_add_to_certlist (ctrl, name, 0, recplist, is_encrypt_to);
761 log_error ("can't encrypt to '%s': %s\n", name, gpg_strerror (rc));
762 gpgsm_status2 (ctrl, STATUS_INV_RECP,
763 get_inv_recpsgnr_code (rc), name, NULL);
766 log_info (_("Note: won't be able to encrypt to '%s': %s\n"),
767 name, gpg_strerror (rc));
773 parse_validation_model (const char *model)
775 int i = gpgsm_parse_validation_model (model);
777 log_error (_("unknown validation model '%s'\n"), model);
779 default_validation_model = i;
783 /* Release the list of SERVERS. As usual it is okay to call this
784 function with SERVERS passed as NULL. */
786 keyserver_list_free (struct keyserver_spec *servers)
790 struct keyserver_spec *tmp = servers->next;
791 xfree (servers->host);
792 xfree (servers->user);
794 memset (servers->pass, 0, strlen (servers->pass));
795 xfree (servers->pass);
796 xfree (servers->base);
802 /* See also dirmngr ldapserver_parse_one(). */
803 struct keyserver_spec *
804 parse_keyserver_line (char *line,
805 const char *filename, unsigned int lineno)
809 struct keyserver_spec *server;
813 /* Parse the colon separated fields. */
814 server = xcalloc (1, sizeof *server);
815 for (fieldno = 1, p = line; p; p = endp, fieldno++ )
817 endp = strchr (p, ':');
825 server->host = xstrdup (p);
828 log_error (_("%s:%u: no hostname given\n"),
836 server->port = atoi (p);
841 server->user = xstrdup (p);
845 if (*p && !server->user)
847 log_error (_("%s:%u: password given without user\n"),
852 server->pass = xstrdup (p);
857 server->base = xstrdup (p);
861 /* (We silently ignore extra fields.) */
868 log_info (_("%s:%u: skipping this line\n"), filename, lineno);
869 keyserver_list_free (server);
878 main ( int argc, char **argv)
885 strlist_t sl, remusr= NULL, locusr=NULL;
886 strlist_t nrings=NULL;
887 int detached_sig = 0;
888 FILE *configfp = NULL;
889 char *configname = NULL;
890 unsigned configlineno;
892 int no_more_options = 0;
893 int default_config =1;
894 int default_keyring = 1;
895 char *logfile = NULL;
896 char *auditlog = NULL;
897 char *htmlauditlog = NULL;
901 int use_random_seed = 1;
902 int no_common_certs_import = 0;
904 const char *forced_digest_algo = NULL;
905 const char *extra_digest_algo = NULL;
906 enum cmd_and_opt_values cmd = 0;
907 struct server_control_s ctrl;
908 certlist_t recplist = NULL;
909 certlist_t signerlist = NULL;
910 int do_not_setup_keys = 0;
911 int recp_required = 0;
912 estream_t auditfp = NULL;
913 estream_t htmlauditfp = NULL;
914 struct assuan_malloc_hooks malloc_hooks;
918 early_system_init ();
919 gnupg_reopen_std (GPGSM_NAME);
920 /* trap_unaligned ();*/
921 gnupg_rl_initialize ();
922 set_strusage (my_strusage);
923 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
925 /* Please note that we may running SUID(ROOT), so be very CAREFUL
926 when adding any stuff between here and the call to secmem_init()
927 somewhere after the option parsing */
928 log_set_prefix (GPGSM_NAME, GPGRT_LOG_WITH_PREFIX);
930 /* Make sure that our subsystems are ready. */
932 init_common_subsystems (&argc, &argv);
934 /* Check that the libraries are suitable. Do it here because the
935 option parse may need services of the library */
936 if (!ksba_check_version (NEED_KSBA_VERSION) )
937 log_fatal (_("%s is too old (need %s, have %s)\n"), "libksba",
938 NEED_KSBA_VERSION, ksba_check_version (NULL) );
941 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
943 may_coredump = disable_core_dumps ();
945 gnupg_init_signals (0, emergency_cleanup);
947 dotlock_create (NULL, 0); /* Register lockfile cleanup. */
950 opt.session_env = session_env_new ();
951 if (!opt.session_env)
952 log_fatal ("error allocating session environment block: %s\n",
955 /* Note: If you change this default cipher algorithm , please
956 remember to update the Gpgconflist entry as well. */
957 opt.def_cipher_algoid = DEFAULT_CIPHER_ALGO;
960 /* First check whether we have a config file on the commandline */
965 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
966 while (arg_parse( &pargs, opts))
968 if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
970 else if (pargs.r_opt == oOptions)
971 { /* yes there is one, so we do not try the default one but
972 read the config file when it is encountered at the
976 else if (pargs.r_opt == oNoOptions)
978 default_config = 0; /* --no-options */
979 opt.no_homedir_creation = 1;
981 else if (pargs.r_opt == oHomedir)
982 gnupg_set_homedir (pargs.r.ret_str);
983 else if (pargs.r_opt == aCallProtectTool)
984 break; /* This break makes sure that --version and --help are
985 passed to the protect-tool. */
989 /* Initialize the secure memory. */
990 gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
994 Now we are now working under our real uid
997 ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free );
999 malloc_hooks.malloc = gcry_malloc;
1000 malloc_hooks.realloc = gcry_realloc;
1001 malloc_hooks.free = gcry_free;
1002 assuan_set_malloc_hooks (&malloc_hooks);
1003 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
1004 setup_libassuan_logging (&opt.debug, NULL);
1006 keybox_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
1008 /* Setup a default control structure for command line mode */
1009 memset (&ctrl, 0, sizeof ctrl);
1010 gpgsm_init_default_ctrl (&ctrl);
1012 ctrl.status_fd = -1; /* No status output. */
1013 ctrl.autodetect_encoding = 1;
1015 /* Set the default option file */
1016 if (default_config )
1017 configname = make_filename (gnupg_homedir (),
1018 GPGSM_NAME EXTSEP_S "conf", NULL);
1019 /* Set the default policy file */
1020 opt.policy_file = make_filename (gnupg_homedir (), "policies.txt", NULL);
1026 pargs.flags = 1; /* do not remove the args */
1031 configfp = fopen (configname, "r");
1037 log_info (_("Note: no default option file '%s'\n"), configname);
1041 log_error (_("option file '%s': %s\n"), configname, strerror(errno));
1047 if (parse_debug && configname)
1048 log_info (_("reading options from '%s'\n"), configname);
1052 while (!no_more_options
1053 && optfile_parse (configfp, configname, &configlineno, &pargs, opts))
1055 switch (pargs.r_opt)
1059 set_cmd (&cmd, pargs.r_opt);
1060 do_not_setup_keys = 1;
1066 set_cmd (&cmd, aServer);
1071 set_cmd (&cmd, aCallDirmngr);
1072 do_not_setup_keys = 1;
1075 case aCallProtectTool:
1077 set_cmd (&cmd, aCallProtectTool);
1078 no_more_options = 1; /* Stop parsing. */
1079 do_not_setup_keys = 1;
1083 set_cmd (&cmd, aDeleteKey);
1085 do_not_setup_keys = 1;
1090 set_cmd (&cmd, aSign );
1094 set_cmd (&cmd, aKeygen);
1096 do_not_setup_keys = 1;
1103 case aExportSecretKeyP12:
1104 case aExportSecretKeyP8:
1105 case aExportSecretKeyRaw:
1108 case aDumpExternalKeys:
1109 case aDumpSecretKeys:
1111 case aListExternalKeys:
1112 case aListSecretKeys:
1116 case aKeydbClearSomeCertFlags:
1117 do_not_setup_keys = 1;
1118 set_cmd (&cmd, pargs.r_opt);
1123 set_cmd (&cmd, pargs.r_opt);
1131 set_cmd (&cmd, pargs.r_opt);
1134 /* Output encoding selection. */
1136 ctrl.create_pem = 1;
1139 ctrl.create_pem = 0;
1140 ctrl.create_base64 = 1;
1143 ctrl.create_pem = 0;
1144 ctrl.create_base64 = 0;
1148 opt.p12_charset = pargs.r.ret_str;
1152 pwfd = translate_sys2libc_fd_int (pargs.r.ret_int, 0);
1156 opt.pinentry_mode = parse_pinentry_mode (pargs.r.ret_str);
1157 if (opt.pinentry_mode == -1)
1158 log_error (_("invalid pinentry mode '%s'\n"), pargs.r.ret_str);
1161 /* Input encoding selection. */
1163 ctrl.autodetect_encoding = 0;
1168 ctrl.autodetect_encoding = 0;
1173 ctrl.autodetect_encoding = 0;
1178 case oDisableCRLChecks:
1179 opt.no_crl_check = 1;
1181 case oEnableCRLChecks:
1182 opt.no_crl_check = 0;
1184 case oDisableTrustedCertCRLCheck:
1185 opt.no_trusted_cert_crl_check = 1;
1187 case oEnableTrustedCertCRLCheck:
1188 opt.no_trusted_cert_crl_check = 0;
1190 case oForceCRLRefresh:
1191 opt.force_crl_refresh = 1;
1195 ctrl.use_ocsp = opt.enable_ocsp = 0;
1198 ctrl.use_ocsp = opt.enable_ocsp = 1;
1202 ctrl.include_certs = default_include_certs = pargs.r.ret_int;
1206 xfree (opt.policy_file);
1207 if (*pargs.r.ret_str)
1208 opt.policy_file = xstrdup (pargs.r.ret_str);
1210 opt.policy_file = NULL;
1213 case oDisablePolicyChecks:
1214 opt.no_policy_check = 1;
1216 case oEnablePolicyChecks:
1217 opt.no_policy_check = 0;
1220 case oAutoIssuerKeyRetrieve:
1221 opt.auto_issuer_key_retrieve = 1;
1224 case oOutput: opt.outfile = pargs.r.ret_str; break;
1227 case oQuiet: opt.quiet = 1; break;
1228 case oNoTTY: /* fixme:tty_no_terminal(1);*/ break;
1229 case oDryRun: opt.dry_run = 1; break;
1233 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
1237 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
1240 case oLogFile: logfile = pargs.r.ret_str; break;
1241 case oNoLogFile: logfile = NULL; break;
1243 case oAuditLog: auditlog = pargs.r.ret_str; break;
1244 case oHtmlAuditLog: htmlauditlog = pargs.r.ret_str; break;
1250 case oNoBatch: opt.batch = 0; break;
1252 case oAnswerYes: opt.answer_yes = 1; break;
1253 case oAnswerNo: opt.answer_no = 1; break;
1255 case oKeyring: append_to_strlist (&nrings, pargs.r.ret_str); break;
1258 if (parse_debug_flag (pargs.r.ret_str, &debug_value, debug_flags))
1260 pargs.r_opt = ARGPARSE_INVALID_ARG;
1261 pargs.err = ARGPARSE_PRINT_ERROR;
1264 case oDebugAll: debug_value = ~0; break;
1265 case oDebugNone: debug_value = 0; break;
1266 case oDebugLevel: debug_level = pargs.r.ret_str; break;
1267 case oDebugWait: debug_wait = pargs.r.ret_int; break;
1268 case oDebugAllowCoreDump:
1269 may_coredump = enable_core_dumps ();
1271 case oDebugNoChainValidation: opt.no_chain_validation = 1; break;
1272 case oDebugIgnoreExpiration: opt.ignore_expiration = 1; break;
1274 case oStatusFD: ctrl.status_fd = pargs.r.ret_int; break;
1275 case oLoggerFD: log_set_fd (pargs.r.ret_int ); break;
1276 case oWithMD5Fingerprint:
1277 opt.with_md5_fingerprint=1; /*fall through*/
1278 case oWithFingerprint:
1279 with_fpr=1; /*fall through*/
1285 opt.with_keygrip = 1;
1289 /* config files may not be nested (silently ignore them) */
1293 configname = xstrdup (pargs.r.ret_str);
1297 case oNoOptions: opt.no_homedir_creation = 1; break; /* no-options */
1298 case oHomedir: gnupg_set_homedir (pargs.r.ret_str); break;
1299 case oAgentProgram: opt.agent_program = pargs.r.ret_str; break;
1302 set_opt_session_env ("DISPLAY", pargs.r.ret_str);
1305 set_opt_session_env ("GPG_TTY", pargs.r.ret_str);
1308 set_opt_session_env ("TERM", pargs.r.ret_str);
1311 set_opt_session_env ("XAUTHORITY", pargs.r.ret_str);
1314 case oLCctype: opt.lc_ctype = xstrdup (pargs.r.ret_str); break;
1315 case oLCmessages: opt.lc_messages = xstrdup (pargs.r.ret_str); break;
1317 case oDirmngrProgram: opt.dirmngr_program = pargs.r.ret_str; break;
1318 case oDisableDirmngr: opt.disable_dirmngr = 1; break;
1319 case oPreferSystemDirmngr: /* Obsolete */; break;
1320 case oProtectToolProgram:
1321 opt.protect_tool_program = pargs.r.ret_str;
1324 case oFakedSystemTime:
1326 time_t faked_time = isotime2epoch (pargs.r.ret_str);
1327 if (faked_time == (time_t)(-1))
1328 faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
1329 gnupg_set_time (faked_time, 0);
1333 case oNoDefKeyring: default_keyring = 0; break;
1334 case oNoGreeting: nogreeting = 1; break;
1337 if (*pargs.r.ret_str)
1339 xfree (opt.local_user);
1340 opt.local_user = xstrdup (pargs.r.ret_str);
1344 if (*pargs.r.ret_str)
1345 opt.def_recipient = xstrdup (pargs.r.ret_str);
1347 case oDefRecipientSelf:
1348 xfree (opt.def_recipient);
1349 opt.def_recipient = NULL;
1350 opt.def_recipient_self = 1;
1352 case oNoDefRecipient:
1353 xfree (opt.def_recipient);
1354 opt.def_recipient = NULL;
1355 opt.def_recipient_self = 0;
1358 case oWithKeyData: opt.with_key_data=1; /* fall through */
1359 case oWithColons: ctrl.with_colons = 1; break;
1360 case oWithSecret: ctrl.with_secret = 1; break;
1361 case oWithValidation: ctrl.with_validation=1; break;
1362 case oWithEphemeralKeys: ctrl.with_ephemeral_keys=1; break;
1364 case oSkipVerify: opt.skip_verify=1; break;
1366 case oNoEncryptTo: opt.no_encrypt_to = 1; break;
1367 case oEncryptTo: /* Store the recipient in the second list */
1368 sl = add_to_strlist (&remusr, pargs.r.ret_str);
1372 case oRecipient: /* store the recipient */
1373 add_to_strlist ( &remusr, pargs.r.ret_str);
1376 case oUser: /* Store the local users, the first one is the default */
1377 if (!opt.local_user)
1378 opt.local_user = xstrdup (pargs.r.ret_str);
1379 add_to_strlist (&locusr, pargs.r.ret_str);
1383 gcry_control (GCRYCTL_DISABLE_SECMEM_WARN);
1387 opt.def_cipher_algoid = pargs.r.ret_str;
1390 case oDisableCipherAlgo:
1392 int algo = gcry_cipher_map_name (pargs.r.ret_str);
1393 gcry_cipher_ctl (NULL, GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
1396 case oDisablePubkeyAlgo:
1398 int algo = gcry_pk_map_name (pargs.r.ret_str);
1399 gcry_pk_ctl (GCRYCTL_DISABLE_ALGO,&algo, sizeof algo );
1404 forced_digest_algo = pargs.r.ret_str;
1407 case oExtraDigestAlgo:
1408 extra_digest_algo = pargs.r.ret_str;
1411 case oIgnoreTimeConflict: opt.ignore_time_conflict = 1; break;
1412 case oNoRandomSeedFile: use_random_seed = 0; break;
1413 case oNoCommonCertsImport: no_common_certs_import = 1; break;
1415 case oEnableSpecialFilenames:
1416 enable_special_filenames ();
1419 case oValidationModel: parse_validation_model (pargs.r.ret_str); break;
1423 struct keyserver_spec *keyserver;
1424 keyserver = parse_keyserver_line (pargs.r.ret_str,
1425 configname, configlineno);
1427 log_error (_("could not parse keyserver\n"));
1430 /* FIXME: Keep last next pointer. */
1431 struct keyserver_spec **next_p = &opt.keyserver;
1433 next_p = &(*next_p)->next;
1434 *next_p = keyserver;
1439 case oIgnoreCertExtension:
1440 add_to_strlist (&opt.ignored_cert_extensions, pargs.r.ret_str);
1443 case oNoAutostart: opt.autostart = 0; break;
1446 /* Dummy option for now. */
1450 pargs.err = configfp? ARGPARSE_PRINT_WARNING:ARGPARSE_PRINT_ERROR;
1459 /* Keep a copy of the config filename. */
1460 opt.config_filename = configname;
1467 if (!opt.config_filename)
1468 opt.config_filename = make_filename (gnupg_homedir (),
1469 GPGSM_NAME EXTSEP_S "conf",
1472 if (log_get_errorcount(0))
1475 if (pwfd != -1) /* Read the passphrase now. */
1476 read_passphrase_from_fd (pwfd);
1478 /* Now that we have the options parsed we need to update the default
1479 control structure. */
1480 gpgsm_init_default_ctrl (&ctrl);
1487 es_fprintf (es_stderr, "%s %s; %s\n",
1488 strusage(11), strusage(13), strusage(14) );
1489 es_fprintf (es_stderr, "%s\n", strusage(15) );
1491 # ifdef IS_DEVELOPMENT_VERSION
1494 log_info ("NOTE: THIS IS A DEVELOPMENT VERSION!\n");
1495 log_info ("It is only intended for test purposes and should NOT be\n");
1496 log_info ("used in a production environment or with production keys!\n");
1500 if (may_coredump && !opt.quiet)
1501 log_info (_("WARNING: program may create a core file!\n"));
1503 /* if (opt.qualsig_approval && !opt.quiet) */
1504 /* log_info (_("This software has officially been approved to " */
1505 /* "create and verify\n" */
1506 /* "qualified signatures according to German law.\n")); */
1508 if (logfile && cmd == aServer)
1510 log_set_file (logfile);
1511 log_set_prefix (NULL, GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_TIME | GPGRT_LOG_WITH_PID);
1514 if (gnupg_faked_time_p ())
1516 gnupg_isotime_t tbuf;
1518 log_info (_("WARNING: running with faked system time: "));
1519 gnupg_get_isotime (tbuf);
1520 dump_isotime (tbuf);
1524 /* Print a warning if an argument looks like an option. */
1525 if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
1529 for (i=0; i < argc; i++)
1530 if (argv[i][0] == '-' && argv[i][1] == '-')
1531 log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
1534 /*FIXME if (opt.batch) */
1535 /* tty_batchmode (1); */
1537 gcry_control (GCRYCTL_RESUME_SECMEM_WARN);
1541 /* Although we always use gpgsm_exit, we better install a regualr
1542 exit handler so that at least the secure memory gets wiped
1544 if (atexit (emergency_cleanup))
1546 log_error ("atexit failed\n");
1550 /* Must do this after dropping setuid, because the mapping functions
1551 may try to load an module and we may have disabled an algorithm.
1552 We remap the commonly used algorithms to the OIDs for
1553 convenience. We need to work with the OIDs because they are used
1554 to check whether the encryption mode is actually available. */
1555 if (!strcmp (opt.def_cipher_algoid, "3DES") )
1556 opt.def_cipher_algoid = "1.2.840.113549.3.7";
1557 else if (!strcmp (opt.def_cipher_algoid, "AES")
1558 || !strcmp (opt.def_cipher_algoid, "AES128"))
1559 opt.def_cipher_algoid = "2.16.840.1.101.3.4.1.2";
1560 else if (!strcmp (opt.def_cipher_algoid, "AES192") )
1561 opt.def_cipher_algoid = "2.16.840.1.101.3.4.1.22";
1562 else if (!strcmp (opt.def_cipher_algoid, "AES256") )
1563 opt.def_cipher_algoid = "2.16.840.1.101.3.4.1.42";
1564 else if (!strcmp (opt.def_cipher_algoid, "SERPENT")
1565 || !strcmp (opt.def_cipher_algoid, "SERPENT128") )
1566 opt.def_cipher_algoid = "1.3.6.1.4.1.11591.13.2.2";
1567 else if (!strcmp (opt.def_cipher_algoid, "SERPENT192") )
1568 opt.def_cipher_algoid = "1.3.6.1.4.1.11591.13.2.22";
1569 else if (!strcmp (opt.def_cipher_algoid, "SERPENT256") )
1570 opt.def_cipher_algoid = "1.3.6.1.4.1.11591.13.2.42";
1571 else if (!strcmp (opt.def_cipher_algoid, "SEED") )
1572 opt.def_cipher_algoid = "1.2.410.200004.1.4";
1573 else if (!strcmp (opt.def_cipher_algoid, "CAMELLIA")
1574 || !strcmp (opt.def_cipher_algoid, "CAMELLIA128") )
1575 opt.def_cipher_algoid = "1.2.392.200011.61.1.1.1.2";
1576 else if (!strcmp (opt.def_cipher_algoid, "CAMELLIA192") )
1577 opt.def_cipher_algoid = "1.2.392.200011.61.1.1.1.3";
1578 else if (!strcmp (opt.def_cipher_algoid, "CAMELLIA256") )
1579 opt.def_cipher_algoid = "1.2.392.200011.61.1.1.1.4";
1581 if (cmd != aGPGConfList)
1583 if ( !gcry_cipher_map_name (opt.def_cipher_algoid)
1584 || !gcry_cipher_mode_from_oid (opt.def_cipher_algoid))
1585 log_error (_("selected cipher algorithm is invalid\n"));
1587 if (forced_digest_algo)
1589 opt.forced_digest_algo = gcry_md_map_name (forced_digest_algo);
1590 if (our_md_test_algo(opt.forced_digest_algo) )
1591 log_error (_("selected digest algorithm is invalid\n"));
1593 if (extra_digest_algo)
1595 opt.extra_digest_algo = gcry_md_map_name (extra_digest_algo);
1596 if (our_md_test_algo (opt.extra_digest_algo) )
1597 log_error (_("selected digest algorithm is invalid\n"));
1601 if (log_get_errorcount(0))
1604 /* Set the random seed file. */
1605 if (use_random_seed)
1607 char *p = make_filename (gnupg_homedir (), "random_seed", NULL);
1608 gcry_control (GCRYCTL_SET_RANDOM_SEED_FILE, p);
1612 if (!cmd && opt.fingerprint && !with_fpr)
1613 set_cmd (&cmd, aListKeys);
1615 /* Add default keybox. */
1616 if (!nrings && default_keyring)
1620 keydb_add_resource (&ctrl, "pubring.kbx", 0, &created);
1621 if (created && !no_common_certs_import)
1623 /* Import the standard certificates for a new default keybox. */
1626 filelist[0] = make_filename (gnupg_datadir (),"com-certs.pem", NULL);
1628 if (!access (filelist[0], F_OK))
1630 log_info (_("importing common certificates '%s'\n"),
1632 gpgsm_import_files (&ctrl, 1, filelist, open_read);
1634 xfree (filelist[0]);
1637 for (sl = nrings; sl; sl = sl->next)
1638 keydb_add_resource (&ctrl, sl->d, 0, NULL);
1639 FREE_STRLIST(nrings);
1642 /* Prepare the audit log feature for certain commands. */
1643 if (auditlog || htmlauditlog)
1651 audit_release (ctrl.audit);
1652 ctrl.audit = audit_new ();
1654 auditfp = open_es_fwrite (auditlog);
1656 htmlauditfp = open_es_fwrite (htmlauditlog);
1664 if (!do_not_setup_keys)
1666 for (sl = locusr; sl ; sl = sl->next)
1668 int rc = gpgsm_add_to_certlist (&ctrl, sl->d, 1, &signerlist, 0);
1671 log_error (_("can't sign using '%s': %s\n"),
1672 sl->d, gpg_strerror (rc));
1673 gpgsm_status2 (&ctrl, STATUS_INV_SGNR,
1674 get_inv_recpsgnr_code (rc), sl->d, NULL);
1675 gpgsm_status2 (&ctrl, STATUS_INV_RECP,
1676 get_inv_recpsgnr_code (rc), sl->d, NULL);
1680 /* Build the recipient list. We first add the regular ones and then
1681 the encrypt-to ones because the underlying function will silently
1682 ignore duplicates and we can't allow keeping a duplicate which is
1683 flagged as encrypt-to as the actually encrypt function would then
1684 complain about no (regular) recipients. */
1685 for (sl = remusr; sl; sl = sl->next)
1686 if (!(sl->flags & 1))
1687 do_add_recipient (&ctrl, sl->d, &recplist, 0, recp_required);
1688 if (!opt.no_encrypt_to)
1690 for (sl = remusr; sl; sl = sl->next)
1691 if ((sl->flags & 1))
1692 do_add_recipient (&ctrl, sl->d, &recplist, 1, recp_required);
1696 if (log_get_errorcount(0))
1697 gpgsm_exit(1); /* Must stop for invalid recipients. */
1699 /* Dispatch command. */
1703 { /* List options and default values in the GPG Conf format. */
1704 char *config_filename_esc = percent_escape (opt.config_filename, NULL);
1706 es_printf ("%s-%s.conf:%lu:\"%s\n",
1707 GPGCONF_NAME, GPGSM_NAME,
1708 GC_OPT_FLAG_DEFAULT, config_filename_esc);
1709 xfree (config_filename_esc);
1711 es_printf ("verbose:%lu:\n", GC_OPT_FLAG_NONE);
1712 es_printf ("quiet:%lu:\n", GC_OPT_FLAG_NONE);
1713 es_printf ("debug-level:%lu:\"none:\n", GC_OPT_FLAG_DEFAULT);
1714 es_printf ("log-file:%lu:\n", GC_OPT_FLAG_NONE);
1715 es_printf ("disable-crl-checks:%lu:\n", GC_OPT_FLAG_NONE);
1716 es_printf ("enable-crl-checks:%lu:\n", GC_OPT_FLAG_NONE);
1717 es_printf ("disable-trusted-cert-crl-check:%lu:\n", GC_OPT_FLAG_NONE);
1718 es_printf ("enable-ocsp:%lu:\n", GC_OPT_FLAG_NONE);
1719 es_printf ("include-certs:%lu:%d:\n", GC_OPT_FLAG_DEFAULT,
1720 DEFAULT_INCLUDE_CERTS);
1721 es_printf ("disable-policy-checks:%lu:\n", GC_OPT_FLAG_NONE);
1722 es_printf ("auto-issuer-key-retrieve:%lu:\n", GC_OPT_FLAG_NONE);
1723 es_printf ("disable-dirmngr:%lu:\n", GC_OPT_FLAG_NONE);
1724 es_printf ("cipher-algo:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT,
1725 DEFAULT_CIPHER_ALGO);
1726 es_printf ("p12-charset:%lu:\n", GC_OPT_FLAG_DEFAULT);
1727 es_printf ("default-key:%lu:\n", GC_OPT_FLAG_DEFAULT);
1728 es_printf ("encrypt-to:%lu:\n", GC_OPT_FLAG_DEFAULT);
1729 es_printf ("keyserver:%lu:\n", GC_OPT_FLAG_NONE);
1731 /* The next one is an info only item and should match what
1732 proc_parameters actually implements. */
1733 es_printf ("default_pubkey_algo:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT,
1739 /* This is merely a dummy command to test whether the
1740 configuration file is valid. */
1746 log_debug ("waiting for debugger - my pid is %u .....\n",
1747 (unsigned int)getpid());
1748 gnupg_sleep (debug_wait);
1749 log_debug ("... okay\n");
1751 gpgsm_server (recplist);
1756 wrong_args ("--call-dirmngr <command> {args}");
1758 if (gpgsm_dirmngr_run_command (&ctrl, *argv, argc-1, argv+1))
1762 case aCallProtectTool:
1763 run_protect_tool (argc, argv);
1766 case aEncr: /* Encrypt the given file. */
1768 estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
1772 if (!argc) /* Source is stdin. */
1773 gpgsm_encrypt (&ctrl, recplist, 0, fp);
1774 else if (argc == 1) /* Source is the given file. */
1775 gpgsm_encrypt (&ctrl, recplist, open_read (*argv), fp);
1777 wrong_args ("--encrypt [datafile]");
1783 case aSign: /* Sign the given file. */
1785 estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
1787 /* Fixme: We should also allow concatenation of multiple files for
1788 signing because that is what gpg does.*/
1790 if (!argc) /* Create from stdin. */
1791 gpgsm_sign (&ctrl, signerlist, 0, detached_sig, fp);
1792 else if (argc == 1) /* From file. */
1793 gpgsm_sign (&ctrl, signerlist,
1794 open_read (*argv), detached_sig, fp);
1796 wrong_args ("--sign [datafile]");
1802 case aSignEncr: /* sign and encrypt the given file */
1803 log_error ("this command has not yet been implemented\n");
1806 case aClearsign: /* make a clearsig */
1807 log_error ("this command has not yet been implemented\n");
1812 estream_t fp = NULL;
1815 if (argc == 2 && opt.outfile)
1816 log_info ("option --output ignored for a detached signature\n");
1817 else if (opt.outfile)
1818 fp = open_es_fwrite (opt.outfile);
1821 gpgsm_verify (&ctrl, 0, -1, fp); /* normal signature from stdin */
1823 gpgsm_verify (&ctrl, open_read (*argv), -1, fp); /* std signature */
1824 else if (argc == 2) /* detached signature (sig, detached) */
1825 gpgsm_verify (&ctrl, open_read (*argv), open_read (argv[1]), NULL);
1827 wrong_args ("--verify [signature [detached_data]]");
1835 estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
1839 gpgsm_decrypt (&ctrl, 0, fp); /* from stdin */
1841 gpgsm_decrypt (&ctrl, open_read (*argv), fp); /* from file */
1843 wrong_args ("--decrypt [filename]");
1850 for (sl=NULL; argc; argc--, argv++)
1851 add_to_strlist (&sl, *argv);
1852 gpgsm_delete (&ctrl, sl);
1858 ctrl.with_chain = 1;
1861 case aListExternalKeys:
1862 case aDumpExternalKeys:
1863 case aListSecretKeys:
1864 case aDumpSecretKeys:
1872 case aListKeys: mode = (0 | 0 | (1<<6)); break;
1874 case aDumpKeys: mode = (256 | 0 | (1<<6)); break;
1875 case aListExternalKeys: mode = (0 | 0 | (1<<7)); break;
1876 case aDumpExternalKeys: mode = (256 | 0 | (1<<7)); break;
1877 case aListSecretKeys: mode = (0 | 2 | (1<<6)); break;
1878 case aDumpSecretKeys: mode = (256 | 2 | (1<<6)); break;
1882 fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
1883 for (sl=NULL; argc; argc--, argv++)
1884 add_to_strlist (&sl, *argv);
1885 gpgsm_list_keys (&ctrl, sl, fp, mode);
1892 case aKeygen: /* Generate a key; well kind of. */
1894 estream_t fpin = NULL;
1899 if (!argc) /* Create from stdin. */
1900 fpin = open_es_fread ("-", "r");
1901 else if (argc == 1) /* From file. */
1902 fpin = open_es_fread (*argv, "r");
1904 wrong_args ("--generate-key --batch [parmfile]");
1907 fpout = open_es_fwrite (opt.outfile?opt.outfile:"-");
1910 gpgsm_genkey (&ctrl, fpin, fpout);
1912 gpgsm_gencertreq_tty (&ctrl, fpout);
1920 gpgsm_import_files (&ctrl, argc, argv, open_read);
1927 fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
1928 for (sl=NULL; argc; argc--, argv++)
1929 add_to_strlist (&sl, *argv);
1930 gpgsm_export (&ctrl, sl, fp);
1936 case aExportSecretKeyP12:
1938 estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
1941 gpgsm_p12_export (&ctrl, *argv, fp, 0);
1943 wrong_args ("--export-secret-key-p12 KEY-ID");
1944 if (fp != es_stdout)
1949 case aExportSecretKeyP8:
1951 estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
1954 gpgsm_p12_export (&ctrl, *argv, fp, 1);
1956 wrong_args ("--export-secret-key-p8 KEY-ID");
1957 if (fp != es_stdout)
1962 case aExportSecretKeyRaw:
1964 estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
1967 gpgsm_p12_export (&ctrl, *argv, fp, 2);
1969 wrong_args ("--export-secret-key-raw KEY-ID");
1970 if (fp != es_stdout)
1977 log_error ("this command has not yet been implemented\n");
1983 wrong_args ("--learn-card");
1986 int rc = gpgsm_agent_learn (&ctrl);
1988 log_error ("error learning card: %s\n", gpg_strerror (rc));
1994 wrong_args ("--change-passphrase <key-Id>");
1998 ksba_cert_t cert = NULL;
2001 rc = gpgsm_find_cert (&ctrl, *argv, NULL, &cert);
2004 else if (!(grip = gpgsm_get_keygrip_hexstring (cert)))
2005 rc = gpg_error (GPG_ERR_BUG);
2008 char *desc = gpgsm_format_keydesc (cert);
2009 rc = gpgsm_agent_passwd (&ctrl, grip, desc);
2013 log_error ("error changing passphrase: %s\n", gpg_strerror (rc));
2015 ksba_cert_release (cert);
2019 case aKeydbClearSomeCertFlags:
2020 for (sl=NULL; argc; argc--, argv++)
2021 add_to_strlist (&sl, *argv);
2022 keydb_clear_some_cert_flags (&ctrl, sl);
2028 log_error (_("invalid command (there is no implicit command)\n"));
2032 /* Print the audit result if needed. */
2033 if ((auditlog && auditfp) || (htmlauditlog && htmlauditfp))
2035 if (auditlog && auditfp)
2036 audit_print_result (ctrl.audit, auditfp, 0);
2037 if (htmlauditlog && htmlauditfp)
2038 audit_print_result (ctrl.audit, htmlauditfp, 1);
2039 audit_release (ctrl.audit);
2041 es_fclose (auditfp);
2042 es_fclose (htmlauditfp);
2046 keyserver_list_free (opt.keyserver);
2047 opt.keyserver = NULL;
2048 gpgsm_release_certlist (recplist);
2049 gpgsm_release_certlist (signerlist);
2050 FREE_STRLIST (remusr);
2051 FREE_STRLIST (locusr);
2053 return 8; /*NOTREACHED*/
2056 /* Note: This function is used by signal handlers!. */
2058 emergency_cleanup (void)
2060 gcry_control (GCRYCTL_TERM_SECMEM );
2067 gcry_control (GCRYCTL_UPDATE_RANDOM_SEED_FILE);
2068 if (opt.debug & DBG_MEMSTAT_VALUE)
2070 gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
2071 gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
2074 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
2075 emergency_cleanup ();
2076 rc = rc? rc : log_get_errorcount(0)? 2 : gpgsm_errors_seen? 1 : 0;
2082 gpgsm_init_default_ctrl (struct server_control_s *ctrl)
2084 ctrl->include_certs = default_include_certs;
2085 ctrl->use_ocsp = opt.enable_ocsp;
2086 ctrl->validation_model = default_validation_model;
2087 ctrl->offline = opt.disable_dirmngr;
2092 gpgsm_parse_validation_model (const char *model)
2094 if (!ascii_strcasecmp (model, "shell") )
2096 else if ( !ascii_strcasecmp (model, "chain") )
2098 else if ( !ascii_strcasecmp (model, "steed") )
2106 /* Open the FILENAME for read and return the file descriptor. Stop
2107 with an error message in case of problems. "-" denotes stdin and
2108 if special filenames are allowed the given fd is opened instead. */
2110 open_read (const char *filename)
2114 if (filename[0] == '-' && !filename[1])
2117 return 0; /* stdin */
2119 fd = check_special_filename (filename, 0, 0);
2122 fd = open (filename, O_RDONLY | O_BINARY);
2125 log_error (_("can't open '%s': %s\n"), filename, strerror (errno));
2131 /* Same as open_read but return an estream_t. */
2133 open_es_fread (const char *filename, const char *mode)
2138 if (filename[0] == '-' && !filename[1])
2139 fd = fileno (stdin);
2141 fd = check_special_filename (filename, 0, 0);
2144 fp = es_fdopen_nc (fd, mode);
2147 log_error ("es_fdopen(%d) failed: %s\n", fd, strerror (errno));
2152 fp = es_fopen (filename, mode);
2155 log_error (_("can't open '%s': %s\n"), filename, strerror (errno));
2162 /* Open FILENAME for fwrite and return an extended stream. Stop with
2163 an error message in case of problems. "-" denotes stdout and if
2164 special filenames are allowed the given fd is opened instead.
2165 Caller must close the returned stream. */
2167 open_es_fwrite (const char *filename)
2172 if (filename[0] == '-' && !filename[1])
2175 fp = es_fdopen_nc (fileno(stdout), "wb");
2179 fd = check_special_filename (filename, 1, 0);
2182 fp = es_fdopen_nc (fd, "wb");
2185 log_error ("es_fdopen(%d) failed: %s\n", fd, strerror (errno));
2190 fp = es_fopen (filename, "wb");
2193 log_error (_("can't open '%s': %s\n"), filename, strerror (errno));
2201 run_protect_tool (int argc, char **argv)
2203 #ifdef HAVE_W32_SYSTEM
2211 if (!opt.protect_tool_program || !*opt.protect_tool_program)
2212 pgm = gnupg_module_name (GNUPG_MODULE_NAME_PROTECT_TOOL);
2214 pgm = opt.protect_tool_program;
2216 av = xcalloc (argc+2, sizeof *av);
2217 av[0] = strrchr (pgm, '/');
2219 av[0] = xstrdup (pgm);
2220 for (i=1; argc; i++, argc--, argv++)
2224 log_error ("error executing '%s': %s\n", pgm, strerror (errno));
2225 #endif /*!HAVE_W32_SYSTEM*/