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 */
38 #include "../common/i18n.h"
40 #include "../common/sysutils.h"
41 #include "../common/gc-opt-flags.h"
42 #include "../common/asshelp.h"
43 #include "../common/init.h"
44 #include "../common/compliance.h"
51 enum cmd_and_opt_values {
59 aListSecretKeys = 'K',
93 aKeydbClearSomeCertFlags,
103 oDebugNoChainValidation,
104 oDebugIgnoreExpiration,
110 oEnableSpecialFilenames,
120 oPreferSystemDirmngr,
141 oDisableTrustedCertCRLCheck,
142 oEnableTrustedCertCRLCheck,
150 oDisablePolicyChecks,
152 oAutoIssuerKeyRetrieve,
191 oNoCommonCertsImport,
192 oIgnoreCertExtension,
197 static ARGPARSE_OPTS opts[] = {
199 ARGPARSE_group (300, N_("@Commands:\n ")),
201 ARGPARSE_c (aSign, "sign", N_("make a signature")),
202 /*ARGPARSE_c (aClearsign, "clearsign", N_("make a clear text signature") ),*/
203 ARGPARSE_c (aDetachedSign, "detach-sign", N_("make a detached signature")),
204 ARGPARSE_c (aEncr, "encrypt", N_("encrypt data")),
205 /*ARGPARSE_c (aSym, "symmetric", N_("encryption only with symmetric cipher")),*/
206 ARGPARSE_c (aDecrypt, "decrypt", N_("decrypt data (default)")),
207 ARGPARSE_c (aVerify, "verify", N_("verify a signature")),
208 ARGPARSE_c (aListKeys, "list-keys", N_("list keys")),
209 ARGPARSE_c (aListExternalKeys, "list-external-keys",
210 N_("list external keys")),
211 ARGPARSE_c (aListSecretKeys, "list-secret-keys", N_("list secret keys")),
212 ARGPARSE_c (aListChain, "list-chain", N_("list certificate chain")),
213 ARGPARSE_c (aFingerprint, "fingerprint", N_("list keys and fingerprints")),
214 ARGPARSE_c (aKeygen, "generate-key", N_("generate a new key pair")),
215 ARGPARSE_c (aKeygen, "gen-key", "@"),
216 ARGPARSE_c (aDeleteKey, "delete-keys",
217 N_("remove keys from the public keyring")),
218 /*ARGPARSE_c (aSendKeys, "send-keys", N_("export keys to a keyserver")),*/
219 /*ARGPARSE_c (aRecvKeys, "recv-keys", N_("import keys from a keyserver")),*/
220 ARGPARSE_c (aImport, "import", N_("import certificates")),
221 ARGPARSE_c (aExport, "export", N_("export certificates")),
223 /* We use -raw and not -p1 for pkcs#1 secret key export so that it
224 won't accidentally be used in case -p12 was intended. */
225 ARGPARSE_c (aExportSecretKeyP12, "export-secret-key-p12", "@"),
226 ARGPARSE_c (aExportSecretKeyP8, "export-secret-key-p8", "@"),
227 ARGPARSE_c (aExportSecretKeyRaw, "export-secret-key-raw", "@"),
229 ARGPARSE_c (aLearnCard, "learn-card", N_("register a smartcard")),
230 ARGPARSE_c (aServer, "server", N_("run in server mode")),
231 ARGPARSE_c (aCallDirmngr, "call-dirmngr",
232 N_("pass a command to the dirmngr")),
233 ARGPARSE_c (aCallProtectTool, "call-protect-tool",
234 N_("invoke gpg-protect-tool")),
235 ARGPARSE_c (aPasswd, "change-passphrase", N_("change a passphrase")),
236 ARGPARSE_c (aPasswd, "passwd", "@"),
237 ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"),
238 ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"),
240 ARGPARSE_c (aDumpKeys, "dump-cert", "@"),
241 ARGPARSE_c (aDumpKeys, "dump-keys", "@"),
242 ARGPARSE_c (aDumpChain, "dump-chain", "@"),
243 ARGPARSE_c (aDumpExternalKeys, "dump-external-keys", "@"),
244 ARGPARSE_c (aDumpSecretKeys, "dump-secret-keys", "@"),
245 ARGPARSE_c (aKeydbClearSomeCertFlags, "keydb-clear-some-cert-flags", "@"),
247 ARGPARSE_group (301, N_("@\nOptions:\n ")),
249 ARGPARSE_s_n (oArmor, "armor", N_("create ascii armored output")),
250 ARGPARSE_s_n (oArmor, "armour", "@"),
251 ARGPARSE_s_n (oBase64, "base64", N_("create base-64 encoded output")),
253 ARGPARSE_s_s (oP12Charset, "p12-charset", "@"),
255 ARGPARSE_s_i (oPassphraseFD, "passphrase-fd", "@"),
256 ARGPARSE_s_s (oPinentryMode, "pinentry-mode", "@"),
258 ARGPARSE_s_n (oAssumeArmor, "assume-armor",
259 N_("assume input is in PEM format")),
260 ARGPARSE_s_n (oAssumeBase64, "assume-base64",
261 N_("assume input is in base-64 format")),
262 ARGPARSE_s_n (oAssumeBinary, "assume-binary",
263 N_("assume input is in binary format")),
265 ARGPARSE_s_s (oRecipient, "recipient", N_("|USER-ID|encrypt for USER-ID")),
267 ARGPARSE_s_n (oPreferSystemDirmngr,"prefer-system-dirmngr", "@"),
269 ARGPARSE_s_n (oDisableCRLChecks, "disable-crl-checks",
270 N_("never consult a CRL")),
271 ARGPARSE_s_n (oEnableCRLChecks, "enable-crl-checks", "@"),
272 ARGPARSE_s_n (oDisableTrustedCertCRLCheck,
273 "disable-trusted-cert-crl-check", "@"),
274 ARGPARSE_s_n (oEnableTrustedCertCRLCheck,
275 "enable-trusted-cert-crl-check", "@"),
277 ARGPARSE_s_n (oForceCRLRefresh, "force-crl-refresh", "@"),
279 ARGPARSE_s_n (oDisableOCSP, "disable-ocsp", "@"),
280 ARGPARSE_s_n (oEnableOCSP, "enable-ocsp", N_("check validity using OCSP")),
282 ARGPARSE_s_s (oValidationModel, "validation-model", "@"),
284 ARGPARSE_s_i (oIncludeCerts, "include-certs",
285 N_("|N|number of certificates to include") ),
287 ARGPARSE_s_s (oPolicyFile, "policy-file",
288 N_("|FILE|take policy information from FILE")),
290 ARGPARSE_s_n (oDisablePolicyChecks, "disable-policy-checks",
291 N_("do not check certificate policies")),
292 ARGPARSE_s_n (oEnablePolicyChecks, "enable-policy-checks", "@"),
294 ARGPARSE_s_n (oAutoIssuerKeyRetrieve, "auto-issuer-key-retrieve",
295 N_("fetch missing issuer certificates")),
297 ARGPARSE_s_s (oEncryptTo, "encrypt-to", "@"),
298 ARGPARSE_s_n (oNoEncryptTo, "no-encrypt-to", "@"),
300 ARGPARSE_s_s (oUser, "local-user",
301 N_("|USER-ID|use USER-ID to sign or decrypt")),
303 ARGPARSE_s_s (oOutput, "output", N_("|FILE|write output to FILE")),
304 ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
305 ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")),
306 ARGPARSE_s_n (oNoTTY, "no-tty", N_("don't use the terminal at all")),
307 ARGPARSE_s_s (oLogFile, "log-file",
308 N_("|FILE|write a server mode log to FILE")),
309 ARGPARSE_s_n (oNoLogFile, "no-log-file", "@"),
310 ARGPARSE_s_i (oLoggerFD, "logger-fd", "@"),
312 ARGPARSE_s_s (oAuditLog, "audit-log",
313 N_("|FILE|write an audit log to FILE")),
314 ARGPARSE_s_s (oHtmlAuditLog, "html-audit-log", "@"),
315 ARGPARSE_s_n (oDryRun, "dry-run", N_("do not make any changes")),
316 ARGPARSE_s_n (oBatch, "batch", N_("batch mode: never ask")),
317 ARGPARSE_s_n (oAnswerYes, "yes", N_("assume yes on most questions")),
318 ARGPARSE_s_n (oAnswerNo, "no", N_("assume no on most questions")),
320 ARGPARSE_s_s (oKeyring, "keyring",
321 N_("|FILE|add keyring to the list of keyrings")),
323 ARGPARSE_s_s (oDefaultKey, "default-key",
324 N_("|USER-ID|use USER-ID as default secret key")),
327 /* ARGPARSE_s_s (oDefRecipient, "default-recipient", */
328 /* N_("|NAME|use NAME as default recipient")), */
329 /* ARGPARSE_s_n (oDefRecipientSelf, "default-recipient-self", */
330 /* N_("use the default key as default recipient")), */
331 /* ARGPARSE_s_n (oNoDefRecipient, "no-default-recipient", "@"), */
333 ARGPARSE_s_s (oKeyServer, "keyserver",
334 N_("|SPEC|use this keyserver to lookup keys")),
335 ARGPARSE_s_s (oOptions, "options", N_("|FILE|read options from FILE")),
337 ARGPARSE_s_s (oDebug, "debug", "@"),
338 ARGPARSE_s_s (oDebugLevel, "debug-level",
339 N_("|LEVEL|set the debugging level to LEVEL")),
340 ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
341 ARGPARSE_s_n (oDebugNone, "debug-none", "@"),
342 ARGPARSE_s_i (oDebugWait, "debug-wait", "@"),
343 ARGPARSE_s_n (oDebugAllowCoreDump, "debug-allow-core-dump", "@"),
344 ARGPARSE_s_n (oDebugNoChainValidation, "debug-no-chain-validation", "@"),
345 ARGPARSE_s_n (oDebugIgnoreExpiration, "debug-ignore-expiration", "@"),
347 ARGPARSE_s_i (oStatusFD, "status-fd",
348 N_("|FD|write status info to this FD")),
350 ARGPARSE_s_s (oCipherAlgo, "cipher-algo",
351 N_("|NAME|use cipher algorithm NAME")),
352 ARGPARSE_s_s (oDigestAlgo, "digest-algo",
353 N_("|NAME|use message digest algorithm NAME")),
354 ARGPARSE_s_s (oExtraDigestAlgo, "extra-digest-algo", "@"),
357 ARGPARSE_group (302, N_(
358 "@\n(See the man page for a complete listing of all commands and options)\n"
362 /* Hidden options. */
363 ARGPARSE_s_s (oCompliance, "compliance", "@"),
364 ARGPARSE_s_n (oNoVerbose, "no-verbose", "@"),
365 ARGPARSE_s_n (oEnableSpecialFilenames, "enable-special-filenames", "@"),
366 ARGPARSE_s_n (oNoSecmemWarn, "no-secmem-warning", "@"),
367 ARGPARSE_s_n (oNoArmor, "no-armor", "@"),
368 ARGPARSE_s_n (oNoArmor, "no-armour", "@"),
369 ARGPARSE_s_n (oNoDefKeyring, "no-default-keyring", "@"),
370 ARGPARSE_s_n (oNoGreeting, "no-greeting", "@"),
371 ARGPARSE_s_n (oNoOptions, "no-options", "@"),
372 ARGPARSE_s_s (oHomedir, "homedir", "@"),
373 ARGPARSE_s_s (oAgentProgram, "agent-program", "@"),
374 ARGPARSE_s_s (oDisplay, "display", "@"),
375 ARGPARSE_s_s (oTTYname, "ttyname", "@"),
376 ARGPARSE_s_s (oTTYtype, "ttytype", "@"),
377 ARGPARSE_s_s (oLCctype, "lc-ctype", "@"),
378 ARGPARSE_s_s (oLCmessages, "lc-messages", "@"),
379 ARGPARSE_s_s (oXauthority, "xauthority", "@"),
380 ARGPARSE_s_s (oDirmngrProgram, "dirmngr-program", "@"),
381 ARGPARSE_s_n (oDisableDirmngr, "disable-dirmngr", "@"),
382 ARGPARSE_s_s (oProtectToolProgram, "protect-tool-program", "@"),
383 ARGPARSE_s_s (oFakedSystemTime, "faked-system-time", "@"),
384 ARGPARSE_s_n (oNoBatch, "no-batch", "@"),
385 ARGPARSE_s_n (oWithColons, "with-colons", "@"),
386 ARGPARSE_s_n (oWithKeyData,"with-key-data", "@"),
387 ARGPARSE_s_n (oWithValidation, "with-validation", "@"),
388 ARGPARSE_s_n (oWithMD5Fingerprint, "with-md5-fingerprint", "@"),
389 ARGPARSE_s_n (oWithEphemeralKeys, "with-ephemeral-keys", "@"),
390 ARGPARSE_s_n (oSkipVerify, "skip-verify", "@"),
391 ARGPARSE_s_n (oWithFingerprint, "with-fingerprint", "@"),
392 ARGPARSE_s_n (oWithKeygrip, "with-keygrip", "@"),
393 ARGPARSE_s_n (oWithSecret, "with-secret", "@"),
394 ARGPARSE_s_s (oDisableCipherAlgo, "disable-cipher-algo", "@"),
395 ARGPARSE_s_s (oDisablePubkeyAlgo, "disable-pubkey-algo", "@"),
396 ARGPARSE_s_n (oIgnoreTimeConflict, "ignore-time-conflict", "@"),
397 ARGPARSE_s_n (oNoRandomSeedFile, "no-random-seed-file", "@"),
398 ARGPARSE_s_n (oNoCommonCertsImport, "no-common-certs-import", "@"),
399 ARGPARSE_s_s (oIgnoreCertExtension, "ignore-cert-extension", "@"),
400 ARGPARSE_s_n (oNoAutostart, "no-autostart", "@"),
402 /* Command aliases. */
403 ARGPARSE_c (aListKeys, "list-key", "@"),
404 ARGPARSE_c (aListChain, "list-signatures", "@"),
405 ARGPARSE_c (aListChain, "list-sigs", "@"),
406 ARGPARSE_c (aListChain, "check-signatures", "@"),
407 ARGPARSE_c (aListChain, "check-sigs", "@"),
408 ARGPARSE_c (aDeleteKey, "delete-key", "@"),
414 /* The list of supported debug flags. */
415 static struct debug_flags_s debug_flags [] =
417 { DBG_X509_VALUE , "x509" },
418 { DBG_MPI_VALUE , "mpi" },
419 { DBG_CRYPTO_VALUE , "crypto" },
420 { DBG_MEMORY_VALUE , "memory" },
421 { DBG_CACHE_VALUE , "cache" },
422 { DBG_MEMSTAT_VALUE, "memstat" },
423 { DBG_HASHING_VALUE, "hashing" },
424 { DBG_IPC_VALUE , "ipc" },
429 /* Global variable to keep an error count. */
430 int gpgsm_errors_seen = 0;
432 /* It is possible that we are currentlu running under setuid permissions */
433 static int maybe_setuid = 1;
435 /* Helper to implement --debug-level and --debug*/
436 static const char *debug_level;
437 static unsigned int debug_value;
439 /* Default value for include-certs. We need an extra macro for
440 gpgconf-list because the variable will be changed by the command
443 It is often cumbersome to locate intermediate certificates, thus by
444 default we include all certificates in the chain. However we leave
445 out the root certificate because that would make it too easy for
446 the recipient to import that root certificate. A root certificate
447 should be installed only after due checks and thus it won't help to
448 send it along with each message. */
449 #define DEFAULT_INCLUDE_CERTS -2 /* Include all certs but root. */
450 static int default_include_certs = DEFAULT_INCLUDE_CERTS;
452 /* Whether the chain mode shall be used for validation. */
453 static int default_validation_model;
455 /* The default cipher algo. */
456 #define DEFAULT_CIPHER_ALGO "AES"
459 static char *build_list (const char *text,
460 const char *(*mapf)(int), int (*chkf)(int));
461 static void set_cmd (enum cmd_and_opt_values *ret_cmd,
462 enum cmd_and_opt_values new_cmd );
464 static void emergency_cleanup (void);
465 static int open_read (const char *filename);
466 static estream_t open_es_fread (const char *filename, const char *mode);
467 static estream_t open_es_fwrite (const char *filename);
468 static void run_protect_tool (int argc, char **argv);
471 our_pk_test_algo (int algo)
477 return gcry_pk_test_algo (algo);
484 our_cipher_test_algo (int algo)
488 case GCRY_CIPHER_3DES:
489 case GCRY_CIPHER_AES128:
490 case GCRY_CIPHER_AES192:
491 case GCRY_CIPHER_AES256:
492 case GCRY_CIPHER_SERPENT128:
493 case GCRY_CIPHER_SERPENT192:
494 case GCRY_CIPHER_SERPENT256:
495 case GCRY_CIPHER_SEED:
496 case GCRY_CIPHER_CAMELLIA128:
497 case GCRY_CIPHER_CAMELLIA192:
498 case GCRY_CIPHER_CAMELLIA256:
499 return gcry_cipher_test_algo (algo);
507 our_md_test_algo (int algo)
518 case GCRY_MD_WHIRLPOOL:
519 return gcry_md_test_algo (algo);
527 make_libversion (const char *libname, const char *(*getfnc)(const char*))
534 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
538 result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
539 strcpy (stpcpy (stpcpy (result, libname), " "), s);
545 my_strusage( int level )
547 static char *digests, *pubkeys, *ciphers;
548 static char *ver_gcry, *ver_ksba;
553 case 11: p = "@GPGSM@ (@GNUPG@)";
555 case 13: p = VERSION; break;
556 case 17: p = PRINTABLE_OS_NAME; break;
557 case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
560 case 40: p = _("Usage: @GPGSM@ [options] [files] (-h for help)");
563 p = _("Syntax: @GPGSM@ [options] [files]\n"
564 "Sign, check, encrypt or decrypt using the S/MIME protocol\n"
565 "Default operation depends on the input data\n");
570 ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
575 ver_ksba = make_libversion ("libksba", ksba_check_version);
579 case 31: p = "\nHome: "; break;
580 case 32: p = gnupg_homedir (); break;
581 case 33: p = _("\nSupported algorithms:\n"); break;
584 ciphers = build_list ("Cipher: ", gnupg_cipher_algo_name,
585 our_cipher_test_algo );
590 pubkeys = build_list ("Pubkey: ", gcry_pk_algo_name,
596 digests = build_list("Hash: ", gcry_md_algo_name, our_md_test_algo );
600 default: p = NULL; break;
607 build_list (const char *text, const char * (*mapf)(int), int (*chkf)(int))
610 size_t n=strlen(text)+2;
614 gcry_control (GCRYCTL_DROP_PRIVS); /* drop setuid */
617 for (i=1; i < 400; i++ )
619 n += strlen(mapf(i)) + 2;
620 list = xmalloc (21 + n);
622 for (p=NULL, i=1; i < 400; i++)
627 p = stpcpy (list, text );
629 p = stpcpy (p, ", ");
630 p = stpcpy (p, mapf(i) );
639 /* Set the file pointer into binary mode if required. */
641 set_binary (FILE *fp)
643 #ifdef HAVE_DOSISH_SYSTEM
644 setmode (fileno (fp), O_BINARY);
653 wrong_args (const char *text)
655 fprintf (stderr, _("usage: %s [options] %s\n"), GPGSM_NAME, text);
661 set_opt_session_env (const char *name, const char *value)
665 err = session_env_setenv (opt.session_env, name, value);
667 log_fatal ("error setting session environment: %s\n",
672 /* Setup the debugging. With a DEBUG_LEVEL of NULL only the active
673 debug flags are propagated to the subsystems. With DEBUG_LEVEL
674 set, a specific set of debug flags is set; and individual debugging
675 flags will be added on top. */
679 int numok = (debug_level && digitp (debug_level));
680 int numlvl = numok? atoi (debug_level) : 0;
684 else if (!strcmp (debug_level, "none") || (numok && numlvl < 1))
686 else if (!strcmp (debug_level, "basic") || (numok && numlvl <= 2))
687 opt.debug = DBG_IPC_VALUE;
688 else if (!strcmp (debug_level, "advanced") || (numok && numlvl <= 5))
689 opt.debug = DBG_IPC_VALUE|DBG_X509_VALUE;
690 else if (!strcmp (debug_level, "expert") || (numok && numlvl <= 8))
691 opt.debug = (DBG_IPC_VALUE|DBG_X509_VALUE
692 |DBG_CACHE_VALUE|DBG_CRYPTO_VALUE);
693 else if (!strcmp (debug_level, "guru") || numok)
696 /* Unless the "guru" string has been used we don't want to allow
697 hashing debugging. The rationale is that people tend to
698 select the highest debug value and would then clutter their
699 disk with debug files which may reveal confidential data. */
701 opt.debug &= ~(DBG_HASHING_VALUE);
705 log_error (_("invalid debug-level '%s' given\n"), debug_level);
709 opt.debug |= debug_value;
711 if (opt.debug && !opt.verbose)
716 if (opt.debug & DBG_MPI_VALUE)
717 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
718 if (opt.debug & DBG_CRYPTO_VALUE )
719 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
720 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
723 parse_debug_flag (NULL, &opt.debug, debug_flags);
729 set_cmd (enum cmd_and_opt_values *ret_cmd, enum cmd_and_opt_values new_cmd)
731 enum cmd_and_opt_values cmd = *ret_cmd;
733 if (!cmd || cmd == new_cmd)
735 else if ( cmd == aSign && new_cmd == aEncr )
737 else if ( cmd == aEncr && new_cmd == aSign )
739 else if ( (cmd == aSign && new_cmd == aClearsign)
740 || (cmd == aClearsign && new_cmd == aSign) )
744 log_error(_("conflicting commands\n"));
752 /* Helper to add recipients to a list. */
754 do_add_recipient (ctrl_t ctrl, const char *name,
755 certlist_t *recplist, int is_encrypt_to, int recp_required)
757 int rc = gpgsm_add_to_certlist (ctrl, name, 0, recplist, is_encrypt_to);
762 log_error ("can't encrypt to '%s': %s\n", name, gpg_strerror (rc));
763 gpgsm_status2 (ctrl, STATUS_INV_RECP,
764 get_inv_recpsgnr_code (rc), name, NULL);
767 log_info (_("Note: won't be able to encrypt to '%s': %s\n"),
768 name, gpg_strerror (rc));
774 parse_validation_model (const char *model)
776 int i = gpgsm_parse_validation_model (model);
778 log_error (_("unknown validation model '%s'\n"), model);
780 default_validation_model = i;
784 /* Release the list of SERVERS. As usual it is okay to call this
785 function with SERVERS passed as NULL. */
787 keyserver_list_free (struct keyserver_spec *servers)
791 struct keyserver_spec *tmp = servers->next;
792 xfree (servers->host);
793 xfree (servers->user);
795 memset (servers->pass, 0, strlen (servers->pass));
796 xfree (servers->pass);
797 xfree (servers->base);
803 /* See also dirmngr ldapserver_parse_one(). */
804 struct keyserver_spec *
805 parse_keyserver_line (char *line,
806 const char *filename, unsigned int lineno)
810 struct keyserver_spec *server;
814 /* Parse the colon separated fields. */
815 server = xcalloc (1, sizeof *server);
816 for (fieldno = 1, p = line; p; p = endp, fieldno++ )
818 endp = strchr (p, ':');
826 server->host = xstrdup (p);
829 log_error (_("%s:%u: no hostname given\n"),
837 server->port = atoi (p);
842 server->user = xstrdup (p);
846 if (*p && !server->user)
848 log_error (_("%s:%u: password given without user\n"),
853 server->pass = xstrdup (p);
858 server->base = xstrdup (p);
862 /* (We silently ignore extra fields.) */
869 log_info (_("%s:%u: skipping this line\n"), filename, lineno);
870 keyserver_list_free (server);
879 main ( int argc, char **argv)
886 strlist_t sl, remusr= NULL, locusr=NULL;
887 strlist_t nrings=NULL;
888 int detached_sig = 0;
889 FILE *configfp = NULL;
890 char *configname = NULL;
891 unsigned configlineno;
893 int no_more_options = 0;
894 int default_config =1;
895 int default_keyring = 1;
896 char *logfile = NULL;
897 char *auditlog = NULL;
898 char *htmlauditlog = NULL;
902 int use_random_seed = 1;
903 int no_common_certs_import = 0;
905 const char *forced_digest_algo = NULL;
906 const char *extra_digest_algo = NULL;
907 enum cmd_and_opt_values cmd = 0;
908 struct server_control_s ctrl;
909 certlist_t recplist = NULL;
910 certlist_t signerlist = NULL;
911 int do_not_setup_keys = 0;
912 int recp_required = 0;
913 estream_t auditfp = NULL;
914 estream_t htmlauditfp = NULL;
915 struct assuan_malloc_hooks malloc_hooks;
919 early_system_init ();
920 gnupg_reopen_std (GPGSM_NAME);
921 /* trap_unaligned ();*/
922 gnupg_rl_initialize ();
923 set_strusage (my_strusage);
924 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
926 /* Please note that we may running SUID(ROOT), so be very CAREFUL
927 when adding any stuff between here and the call to secmem_init()
928 somewhere after the option parsing */
929 log_set_prefix (GPGSM_NAME, GPGRT_LOG_WITH_PREFIX);
931 /* Make sure that our subsystems are ready. */
933 init_common_subsystems (&argc, &argv);
935 /* Check that the libraries are suitable. Do it here because the
936 option parse may need services of the library */
937 if (!ksba_check_version (NEED_KSBA_VERSION) )
938 log_fatal (_("%s is too old (need %s, have %s)\n"), "libksba",
939 NEED_KSBA_VERSION, ksba_check_version (NULL) );
942 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
944 may_coredump = disable_core_dumps ();
946 gnupg_init_signals (0, emergency_cleanup);
948 dotlock_create (NULL, 0); /* Register lockfile cleanup. */
950 /* Tell the compliance module who we are. */
951 gnupg_initialize_compliance (GNUPG_MODULE_NAME_GPGSM);
954 opt.session_env = session_env_new ();
955 if (!opt.session_env)
956 log_fatal ("error allocating session environment block: %s\n",
959 /* Note: If you change this default cipher algorithm , please
960 remember to update the Gpgconflist entry as well. */
961 opt.def_cipher_algoid = DEFAULT_CIPHER_ALGO;
964 /* First check whether we have a config file on the commandline */
969 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
970 while (arg_parse( &pargs, opts))
972 if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
974 else if (pargs.r_opt == oOptions)
975 { /* yes there is one, so we do not try the default one but
976 read the config file when it is encountered at the
980 else if (pargs.r_opt == oNoOptions)
982 default_config = 0; /* --no-options */
983 opt.no_homedir_creation = 1;
985 else if (pargs.r_opt == oHomedir)
986 gnupg_set_homedir (pargs.r.ret_str);
987 else if (pargs.r_opt == aCallProtectTool)
988 break; /* This break makes sure that --version and --help are
989 passed to the protect-tool. */
993 /* Initialize the secure memory. */
994 gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
998 Now we are now working under our real uid
1001 ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free );
1003 malloc_hooks.malloc = gcry_malloc;
1004 malloc_hooks.realloc = gcry_realloc;
1005 malloc_hooks.free = gcry_free;
1006 assuan_set_malloc_hooks (&malloc_hooks);
1007 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
1008 setup_libassuan_logging (&opt.debug, NULL);
1010 keybox_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
1012 /* Setup a default control structure for command line mode */
1013 memset (&ctrl, 0, sizeof ctrl);
1014 gpgsm_init_default_ctrl (&ctrl);
1016 ctrl.status_fd = -1; /* No status output. */
1017 ctrl.autodetect_encoding = 1;
1019 /* Set the default option file */
1020 if (default_config )
1021 configname = make_filename (gnupg_homedir (),
1022 GPGSM_NAME EXTSEP_S "conf", NULL);
1023 /* Set the default policy file */
1024 opt.policy_file = make_filename (gnupg_homedir (), "policies.txt", NULL);
1030 pargs.flags = 1; /* do not remove the args */
1035 configfp = fopen (configname, "r");
1041 log_info (_("Note: no default option file '%s'\n"), configname);
1045 log_error (_("option file '%s': %s\n"), configname, strerror(errno));
1051 if (parse_debug && configname)
1052 log_info (_("reading options from '%s'\n"), configname);
1056 while (!no_more_options
1057 && optfile_parse (configfp, configname, &configlineno, &pargs, opts))
1059 switch (pargs.r_opt)
1063 set_cmd (&cmd, pargs.r_opt);
1064 do_not_setup_keys = 1;
1070 set_cmd (&cmd, aServer);
1075 set_cmd (&cmd, aCallDirmngr);
1076 do_not_setup_keys = 1;
1079 case aCallProtectTool:
1081 set_cmd (&cmd, aCallProtectTool);
1082 no_more_options = 1; /* Stop parsing. */
1083 do_not_setup_keys = 1;
1087 set_cmd (&cmd, aDeleteKey);
1089 do_not_setup_keys = 1;
1094 set_cmd (&cmd, aSign );
1098 set_cmd (&cmd, aKeygen);
1100 do_not_setup_keys = 1;
1107 case aExportSecretKeyP12:
1108 case aExportSecretKeyP8:
1109 case aExportSecretKeyRaw:
1112 case aDumpExternalKeys:
1113 case aDumpSecretKeys:
1115 case aListExternalKeys:
1116 case aListSecretKeys:
1120 case aKeydbClearSomeCertFlags:
1121 do_not_setup_keys = 1;
1122 set_cmd (&cmd, pargs.r_opt);
1127 set_cmd (&cmd, pargs.r_opt);
1135 set_cmd (&cmd, pargs.r_opt);
1138 /* Output encoding selection. */
1140 ctrl.create_pem = 1;
1143 ctrl.create_pem = 0;
1144 ctrl.create_base64 = 1;
1147 ctrl.create_pem = 0;
1148 ctrl.create_base64 = 0;
1152 opt.p12_charset = pargs.r.ret_str;
1156 pwfd = translate_sys2libc_fd_int (pargs.r.ret_int, 0);
1160 opt.pinentry_mode = parse_pinentry_mode (pargs.r.ret_str);
1161 if (opt.pinentry_mode == -1)
1162 log_error (_("invalid pinentry mode '%s'\n"), pargs.r.ret_str);
1165 /* Input encoding selection. */
1167 ctrl.autodetect_encoding = 0;
1172 ctrl.autodetect_encoding = 0;
1177 ctrl.autodetect_encoding = 0;
1182 case oDisableCRLChecks:
1183 opt.no_crl_check = 1;
1185 case oEnableCRLChecks:
1186 opt.no_crl_check = 0;
1188 case oDisableTrustedCertCRLCheck:
1189 opt.no_trusted_cert_crl_check = 1;
1191 case oEnableTrustedCertCRLCheck:
1192 opt.no_trusted_cert_crl_check = 0;
1194 case oForceCRLRefresh:
1195 opt.force_crl_refresh = 1;
1199 ctrl.use_ocsp = opt.enable_ocsp = 0;
1202 ctrl.use_ocsp = opt.enable_ocsp = 1;
1206 ctrl.include_certs = default_include_certs = pargs.r.ret_int;
1210 xfree (opt.policy_file);
1211 if (*pargs.r.ret_str)
1212 opt.policy_file = xstrdup (pargs.r.ret_str);
1214 opt.policy_file = NULL;
1217 case oDisablePolicyChecks:
1218 opt.no_policy_check = 1;
1220 case oEnablePolicyChecks:
1221 opt.no_policy_check = 0;
1224 case oAutoIssuerKeyRetrieve:
1225 opt.auto_issuer_key_retrieve = 1;
1228 case oOutput: opt.outfile = pargs.r.ret_str; break;
1231 case oQuiet: opt.quiet = 1; break;
1232 case oNoTTY: /* fixme:tty_no_terminal(1);*/ break;
1233 case oDryRun: opt.dry_run = 1; break;
1237 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
1241 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
1244 case oLogFile: logfile = pargs.r.ret_str; break;
1245 case oNoLogFile: logfile = NULL; break;
1247 case oAuditLog: auditlog = pargs.r.ret_str; break;
1248 case oHtmlAuditLog: htmlauditlog = pargs.r.ret_str; break;
1254 case oNoBatch: opt.batch = 0; break;
1256 case oAnswerYes: opt.answer_yes = 1; break;
1257 case oAnswerNo: opt.answer_no = 1; break;
1259 case oKeyring: append_to_strlist (&nrings, pargs.r.ret_str); break;
1262 if (parse_debug_flag (pargs.r.ret_str, &debug_value, debug_flags))
1264 pargs.r_opt = ARGPARSE_INVALID_ARG;
1265 pargs.err = ARGPARSE_PRINT_ERROR;
1268 case oDebugAll: debug_value = ~0; break;
1269 case oDebugNone: debug_value = 0; break;
1270 case oDebugLevel: debug_level = pargs.r.ret_str; break;
1271 case oDebugWait: debug_wait = pargs.r.ret_int; break;
1272 case oDebugAllowCoreDump:
1273 may_coredump = enable_core_dumps ();
1275 case oDebugNoChainValidation: opt.no_chain_validation = 1; break;
1276 case oDebugIgnoreExpiration: opt.ignore_expiration = 1; break;
1278 case oStatusFD: ctrl.status_fd = pargs.r.ret_int; break;
1279 case oLoggerFD: log_set_fd (pargs.r.ret_int ); break;
1280 case oWithMD5Fingerprint:
1281 opt.with_md5_fingerprint=1; /*fall through*/
1282 case oWithFingerprint:
1283 with_fpr=1; /*fall through*/
1289 opt.with_keygrip = 1;
1293 /* config files may not be nested (silently ignore them) */
1297 configname = xstrdup (pargs.r.ret_str);
1301 case oNoOptions: opt.no_homedir_creation = 1; break; /* no-options */
1302 case oHomedir: gnupg_set_homedir (pargs.r.ret_str); break;
1303 case oAgentProgram: opt.agent_program = pargs.r.ret_str; break;
1306 set_opt_session_env ("DISPLAY", pargs.r.ret_str);
1309 set_opt_session_env ("GPG_TTY", pargs.r.ret_str);
1312 set_opt_session_env ("TERM", pargs.r.ret_str);
1315 set_opt_session_env ("XAUTHORITY", pargs.r.ret_str);
1318 case oLCctype: opt.lc_ctype = xstrdup (pargs.r.ret_str); break;
1319 case oLCmessages: opt.lc_messages = xstrdup (pargs.r.ret_str); break;
1321 case oDirmngrProgram: opt.dirmngr_program = pargs.r.ret_str; break;
1322 case oDisableDirmngr: opt.disable_dirmngr = 1; break;
1323 case oPreferSystemDirmngr: /* Obsolete */; break;
1324 case oProtectToolProgram:
1325 opt.protect_tool_program = pargs.r.ret_str;
1328 case oFakedSystemTime:
1330 time_t faked_time = isotime2epoch (pargs.r.ret_str);
1331 if (faked_time == (time_t)(-1))
1332 faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
1333 gnupg_set_time (faked_time, 0);
1337 case oNoDefKeyring: default_keyring = 0; break;
1338 case oNoGreeting: nogreeting = 1; break;
1341 if (*pargs.r.ret_str)
1343 xfree (opt.local_user);
1344 opt.local_user = xstrdup (pargs.r.ret_str);
1348 if (*pargs.r.ret_str)
1349 opt.def_recipient = xstrdup (pargs.r.ret_str);
1351 case oDefRecipientSelf:
1352 xfree (opt.def_recipient);
1353 opt.def_recipient = NULL;
1354 opt.def_recipient_self = 1;
1356 case oNoDefRecipient:
1357 xfree (opt.def_recipient);
1358 opt.def_recipient = NULL;
1359 opt.def_recipient_self = 0;
1362 case oWithKeyData: opt.with_key_data=1; /* fall through */
1363 case oWithColons: ctrl.with_colons = 1; break;
1364 case oWithSecret: ctrl.with_secret = 1; break;
1365 case oWithValidation: ctrl.with_validation=1; break;
1366 case oWithEphemeralKeys: ctrl.with_ephemeral_keys=1; break;
1368 case oSkipVerify: opt.skip_verify=1; break;
1370 case oNoEncryptTo: opt.no_encrypt_to = 1; break;
1371 case oEncryptTo: /* Store the recipient in the second list */
1372 sl = add_to_strlist (&remusr, pargs.r.ret_str);
1376 case oRecipient: /* store the recipient */
1377 add_to_strlist ( &remusr, pargs.r.ret_str);
1380 case oUser: /* Store the local users, the first one is the default */
1381 if (!opt.local_user)
1382 opt.local_user = xstrdup (pargs.r.ret_str);
1383 add_to_strlist (&locusr, pargs.r.ret_str);
1387 gcry_control (GCRYCTL_DISABLE_SECMEM_WARN);
1391 opt.def_cipher_algoid = pargs.r.ret_str;
1394 case oDisableCipherAlgo:
1396 int algo = gcry_cipher_map_name (pargs.r.ret_str);
1397 gcry_cipher_ctl (NULL, GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
1400 case oDisablePubkeyAlgo:
1402 int algo = gcry_pk_map_name (pargs.r.ret_str);
1403 gcry_pk_ctl (GCRYCTL_DISABLE_ALGO,&algo, sizeof algo );
1408 forced_digest_algo = pargs.r.ret_str;
1411 case oExtraDigestAlgo:
1412 extra_digest_algo = pargs.r.ret_str;
1415 case oIgnoreTimeConflict: opt.ignore_time_conflict = 1; break;
1416 case oNoRandomSeedFile: use_random_seed = 0; break;
1417 case oNoCommonCertsImport: no_common_certs_import = 1; break;
1419 case oEnableSpecialFilenames:
1420 enable_special_filenames ();
1423 case oValidationModel: parse_validation_model (pargs.r.ret_str); break;
1427 struct keyserver_spec *keyserver;
1428 keyserver = parse_keyserver_line (pargs.r.ret_str,
1429 configname, configlineno);
1431 log_error (_("could not parse keyserver\n"));
1434 /* FIXME: Keep last next pointer. */
1435 struct keyserver_spec **next_p = &opt.keyserver;
1437 next_p = &(*next_p)->next;
1438 *next_p = keyserver;
1443 case oIgnoreCertExtension:
1444 add_to_strlist (&opt.ignored_cert_extensions, pargs.r.ret_str);
1447 case oNoAutostart: opt.autostart = 0; break;
1451 struct gnupg_compliance_option compliance_options[] =
1453 { "de-vs", CO_DE_VS }
1455 int compliance = gnupg_parse_compliance_option (pargs.r.ret_str,
1457 DIM (compliance_options),
1461 opt.compliance = compliance;
1466 pargs.err = configfp? ARGPARSE_PRINT_WARNING:ARGPARSE_PRINT_ERROR;
1475 /* Keep a copy of the config filename. */
1476 opt.config_filename = configname;
1483 if (!opt.config_filename)
1484 opt.config_filename = make_filename (gnupg_homedir (),
1485 GPGSM_NAME EXTSEP_S "conf",
1488 if (log_get_errorcount(0))
1491 if (pwfd != -1) /* Read the passphrase now. */
1492 read_passphrase_from_fd (pwfd);
1494 /* Now that we have the options parsed we need to update the default
1495 control structure. */
1496 gpgsm_init_default_ctrl (&ctrl);
1503 es_fprintf (es_stderr, "%s %s; %s\n",
1504 strusage(11), strusage(13), strusage(14) );
1505 es_fprintf (es_stderr, "%s\n", strusage(15) );
1507 # ifdef IS_DEVELOPMENT_VERSION
1510 log_info ("NOTE: THIS IS A DEVELOPMENT VERSION!\n");
1511 log_info ("It is only intended for test purposes and should NOT be\n");
1512 log_info ("used in a production environment or with production keys!\n");
1516 if (may_coredump && !opt.quiet)
1517 log_info (_("WARNING: program may create a core file!\n"));
1519 /* if (opt.qualsig_approval && !opt.quiet) */
1520 /* log_info (_("This software has officially been approved to " */
1521 /* "create and verify\n" */
1522 /* "qualified signatures according to German law.\n")); */
1524 if (logfile && cmd == aServer)
1526 log_set_file (logfile);
1527 log_set_prefix (NULL, GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_TIME | GPGRT_LOG_WITH_PID);
1530 if (gnupg_faked_time_p ())
1532 gnupg_isotime_t tbuf;
1534 log_info (_("WARNING: running with faked system time: "));
1535 gnupg_get_isotime (tbuf);
1536 dump_isotime (tbuf);
1540 /* Print a warning if an argument looks like an option. */
1541 if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
1545 for (i=0; i < argc; i++)
1546 if (argv[i][0] == '-' && argv[i][1] == '-')
1547 log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
1550 /*FIXME if (opt.batch) */
1551 /* tty_batchmode (1); */
1553 gcry_control (GCRYCTL_RESUME_SECMEM_WARN);
1557 /* Although we always use gpgsm_exit, we better install a regualr
1558 exit handler so that at least the secure memory gets wiped
1560 if (atexit (emergency_cleanup))
1562 log_error ("atexit failed\n");
1566 /* Must do this after dropping setuid, because the mapping functions
1567 may try to load an module and we may have disabled an algorithm.
1568 We remap the commonly used algorithms to the OIDs for
1569 convenience. We need to work with the OIDs because they are used
1570 to check whether the encryption mode is actually available. */
1571 if (!strcmp (opt.def_cipher_algoid, "3DES") )
1572 opt.def_cipher_algoid = "1.2.840.113549.3.7";
1573 else if (!strcmp (opt.def_cipher_algoid, "AES")
1574 || !strcmp (opt.def_cipher_algoid, "AES128"))
1575 opt.def_cipher_algoid = "2.16.840.1.101.3.4.1.2";
1576 else if (!strcmp (opt.def_cipher_algoid, "AES192") )
1577 opt.def_cipher_algoid = "2.16.840.1.101.3.4.1.22";
1578 else if (!strcmp (opt.def_cipher_algoid, "AES256") )
1579 opt.def_cipher_algoid = "2.16.840.1.101.3.4.1.42";
1580 else if (!strcmp (opt.def_cipher_algoid, "SERPENT")
1581 || !strcmp (opt.def_cipher_algoid, "SERPENT128") )
1582 opt.def_cipher_algoid = "1.3.6.1.4.1.11591.13.2.2";
1583 else if (!strcmp (opt.def_cipher_algoid, "SERPENT192") )
1584 opt.def_cipher_algoid = "1.3.6.1.4.1.11591.13.2.22";
1585 else if (!strcmp (opt.def_cipher_algoid, "SERPENT256") )
1586 opt.def_cipher_algoid = "1.3.6.1.4.1.11591.13.2.42";
1587 else if (!strcmp (opt.def_cipher_algoid, "SEED") )
1588 opt.def_cipher_algoid = "1.2.410.200004.1.4";
1589 else if (!strcmp (opt.def_cipher_algoid, "CAMELLIA")
1590 || !strcmp (opt.def_cipher_algoid, "CAMELLIA128") )
1591 opt.def_cipher_algoid = "1.2.392.200011.61.1.1.1.2";
1592 else if (!strcmp (opt.def_cipher_algoid, "CAMELLIA192") )
1593 opt.def_cipher_algoid = "1.2.392.200011.61.1.1.1.3";
1594 else if (!strcmp (opt.def_cipher_algoid, "CAMELLIA256") )
1595 opt.def_cipher_algoid = "1.2.392.200011.61.1.1.1.4";
1597 if (cmd != aGPGConfList)
1599 if ( !gcry_cipher_map_name (opt.def_cipher_algoid)
1600 || !gcry_cipher_mode_from_oid (opt.def_cipher_algoid))
1601 log_error (_("selected cipher algorithm is invalid\n"));
1603 if (forced_digest_algo)
1605 opt.forced_digest_algo = gcry_md_map_name (forced_digest_algo);
1606 if (our_md_test_algo(opt.forced_digest_algo) )
1607 log_error (_("selected digest algorithm is invalid\n"));
1609 if (extra_digest_algo)
1611 opt.extra_digest_algo = gcry_md_map_name (extra_digest_algo);
1612 if (our_md_test_algo (opt.extra_digest_algo) )
1613 log_error (_("selected digest algorithm is invalid\n"));
1617 /* Check our chosen algorithms against the list of allowed
1618 * algorithms in the current compliance mode, and fail hard if it is
1619 * not. This is us being nice to the user informing her early that
1620 * the chosen algorithms are not available. We also check and
1621 * enforce this right before the actual operation. */
1622 if (! gnupg_cipher_is_allowed (opt.compliance,
1623 cmd == aEncr || cmd == aSignEncr,
1624 gcry_cipher_map_name (opt.def_cipher_algoid),
1625 GCRY_CIPHER_MODE_NONE)
1626 && ! gnupg_cipher_is_allowed (opt.compliance,
1627 cmd == aEncr || cmd == aSignEncr,
1628 gcry_cipher_mode_from_oid
1629 (opt.def_cipher_algoid),
1630 GCRY_CIPHER_MODE_NONE))
1631 log_error (_("cipher algorithm '%s' may not be used in %s mode\n"),
1632 opt.def_cipher_algoid,
1633 gnupg_compliance_option_string (opt.compliance));
1635 if (forced_digest_algo
1636 && ! gnupg_digest_is_allowed (opt.compliance,
1639 || cmd == aClearsign,
1640 opt.forced_digest_algo))
1641 log_error (_("digest algorithm '%s' may not be used in %s mode\n"),
1643 gnupg_compliance_option_string (opt.compliance));
1645 if (extra_digest_algo
1646 && ! gnupg_digest_is_allowed (opt.compliance,
1649 || cmd == aClearsign,
1650 opt.extra_digest_algo))
1651 log_error (_("digest algorithm '%s' may not be used in %s mode\n"),
1653 gnupg_compliance_option_string (opt.compliance));
1655 if (log_get_errorcount(0))
1658 /* Set the random seed file. */
1659 if (use_random_seed)
1661 char *p = make_filename (gnupg_homedir (), "random_seed", NULL);
1662 gcry_control (GCRYCTL_SET_RANDOM_SEED_FILE, p);
1666 if (!cmd && opt.fingerprint && !with_fpr)
1667 set_cmd (&cmd, aListKeys);
1669 /* Add default keybox. */
1670 if (!nrings && default_keyring)
1674 keydb_add_resource (&ctrl, "pubring.kbx", 0, &created);
1675 if (created && !no_common_certs_import)
1677 /* Import the standard certificates for a new default keybox. */
1680 filelist[0] = make_filename (gnupg_datadir (),"com-certs.pem", NULL);
1682 if (!access (filelist[0], F_OK))
1684 log_info (_("importing common certificates '%s'\n"),
1686 gpgsm_import_files (&ctrl, 1, filelist, open_read);
1688 xfree (filelist[0]);
1691 for (sl = nrings; sl; sl = sl->next)
1692 keydb_add_resource (&ctrl, sl->d, 0, NULL);
1693 FREE_STRLIST(nrings);
1696 /* Prepare the audit log feature for certain commands. */
1697 if (auditlog || htmlauditlog)
1705 audit_release (ctrl.audit);
1706 ctrl.audit = audit_new ();
1708 auditfp = open_es_fwrite (auditlog);
1710 htmlauditfp = open_es_fwrite (htmlauditlog);
1718 if (!do_not_setup_keys)
1720 for (sl = locusr; sl ; sl = sl->next)
1722 int rc = gpgsm_add_to_certlist (&ctrl, sl->d, 1, &signerlist, 0);
1725 log_error (_("can't sign using '%s': %s\n"),
1726 sl->d, gpg_strerror (rc));
1727 gpgsm_status2 (&ctrl, STATUS_INV_SGNR,
1728 get_inv_recpsgnr_code (rc), sl->d, NULL);
1729 gpgsm_status2 (&ctrl, STATUS_INV_RECP,
1730 get_inv_recpsgnr_code (rc), sl->d, NULL);
1734 /* Build the recipient list. We first add the regular ones and then
1735 the encrypt-to ones because the underlying function will silently
1736 ignore duplicates and we can't allow keeping a duplicate which is
1737 flagged as encrypt-to as the actually encrypt function would then
1738 complain about no (regular) recipients. */
1739 for (sl = remusr; sl; sl = sl->next)
1740 if (!(sl->flags & 1))
1741 do_add_recipient (&ctrl, sl->d, &recplist, 0, recp_required);
1742 if (!opt.no_encrypt_to)
1744 for (sl = remusr; sl; sl = sl->next)
1745 if ((sl->flags & 1))
1746 do_add_recipient (&ctrl, sl->d, &recplist, 1, recp_required);
1750 if (log_get_errorcount(0))
1751 gpgsm_exit(1); /* Must stop for invalid recipients. */
1753 /* Dispatch command. */
1757 { /* List options and default values in the GPG Conf format. */
1758 char *config_filename_esc = percent_escape (opt.config_filename, NULL);
1760 es_printf ("%s-%s.conf:%lu:\"%s\n",
1761 GPGCONF_NAME, GPGSM_NAME,
1762 GC_OPT_FLAG_DEFAULT, config_filename_esc);
1763 xfree (config_filename_esc);
1765 es_printf ("verbose:%lu:\n", GC_OPT_FLAG_NONE);
1766 es_printf ("quiet:%lu:\n", GC_OPT_FLAG_NONE);
1767 es_printf ("debug-level:%lu:\"none:\n", GC_OPT_FLAG_DEFAULT);
1768 es_printf ("log-file:%lu:\n", GC_OPT_FLAG_NONE);
1769 es_printf ("disable-crl-checks:%lu:\n", GC_OPT_FLAG_NONE);
1770 es_printf ("enable-crl-checks:%lu:\n", GC_OPT_FLAG_NONE);
1771 es_printf ("disable-trusted-cert-crl-check:%lu:\n", GC_OPT_FLAG_NONE);
1772 es_printf ("enable-ocsp:%lu:\n", GC_OPT_FLAG_NONE);
1773 es_printf ("include-certs:%lu:%d:\n", GC_OPT_FLAG_DEFAULT,
1774 DEFAULT_INCLUDE_CERTS);
1775 es_printf ("disable-policy-checks:%lu:\n", GC_OPT_FLAG_NONE);
1776 es_printf ("auto-issuer-key-retrieve:%lu:\n", GC_OPT_FLAG_NONE);
1777 es_printf ("disable-dirmngr:%lu:\n", GC_OPT_FLAG_NONE);
1778 es_printf ("cipher-algo:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT,
1779 DEFAULT_CIPHER_ALGO);
1780 es_printf ("p12-charset:%lu:\n", GC_OPT_FLAG_DEFAULT);
1781 es_printf ("default-key:%lu:\n", GC_OPT_FLAG_DEFAULT);
1782 es_printf ("encrypt-to:%lu:\n", GC_OPT_FLAG_DEFAULT);
1783 es_printf ("keyserver:%lu:\n", GC_OPT_FLAG_NONE);
1785 /* The next one is an info only item and should match what
1786 proc_parameters actually implements. */
1787 es_printf ("default_pubkey_algo:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT,
1793 /* This is merely a dummy command to test whether the
1794 configuration file is valid. */
1800 log_debug ("waiting for debugger - my pid is %u .....\n",
1801 (unsigned int)getpid());
1802 gnupg_sleep (debug_wait);
1803 log_debug ("... okay\n");
1805 gpgsm_server (recplist);
1810 wrong_args ("--call-dirmngr <command> {args}");
1812 if (gpgsm_dirmngr_run_command (&ctrl, *argv, argc-1, argv+1))
1816 case aCallProtectTool:
1817 run_protect_tool (argc, argv);
1820 case aEncr: /* Encrypt the given file. */
1822 estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
1826 if (!argc) /* Source is stdin. */
1827 gpgsm_encrypt (&ctrl, recplist, 0, fp);
1828 else if (argc == 1) /* Source is the given file. */
1829 gpgsm_encrypt (&ctrl, recplist, open_read (*argv), fp);
1831 wrong_args ("--encrypt [datafile]");
1837 case aSign: /* Sign the given file. */
1839 estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
1841 /* Fixme: We should also allow concatenation of multiple files for
1842 signing because that is what gpg does.*/
1844 if (!argc) /* Create from stdin. */
1845 gpgsm_sign (&ctrl, signerlist, 0, detached_sig, fp);
1846 else if (argc == 1) /* From file. */
1847 gpgsm_sign (&ctrl, signerlist,
1848 open_read (*argv), detached_sig, fp);
1850 wrong_args ("--sign [datafile]");
1856 case aSignEncr: /* sign and encrypt the given file */
1857 log_error ("this command has not yet been implemented\n");
1860 case aClearsign: /* make a clearsig */
1861 log_error ("this command has not yet been implemented\n");
1866 estream_t fp = NULL;
1869 if (argc == 2 && opt.outfile)
1870 log_info ("option --output ignored for a detached signature\n");
1871 else if (opt.outfile)
1872 fp = open_es_fwrite (opt.outfile);
1875 gpgsm_verify (&ctrl, 0, -1, fp); /* normal signature from stdin */
1877 gpgsm_verify (&ctrl, open_read (*argv), -1, fp); /* std signature */
1878 else if (argc == 2) /* detached signature (sig, detached) */
1879 gpgsm_verify (&ctrl, open_read (*argv), open_read (argv[1]), NULL);
1881 wrong_args ("--verify [signature [detached_data]]");
1889 estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
1893 gpgsm_decrypt (&ctrl, 0, fp); /* from stdin */
1895 gpgsm_decrypt (&ctrl, open_read (*argv), fp); /* from file */
1897 wrong_args ("--decrypt [filename]");
1904 for (sl=NULL; argc; argc--, argv++)
1905 add_to_strlist (&sl, *argv);
1906 gpgsm_delete (&ctrl, sl);
1912 ctrl.with_chain = 1; /* fall through */
1915 case aListExternalKeys:
1916 case aDumpExternalKeys:
1917 case aListSecretKeys:
1918 case aDumpSecretKeys:
1926 case aListKeys: mode = (0 | 0 | (1<<6)); break;
1928 case aDumpKeys: mode = (256 | 0 | (1<<6)); break;
1929 case aListExternalKeys: mode = (0 | 0 | (1<<7)); break;
1930 case aDumpExternalKeys: mode = (256 | 0 | (1<<7)); break;
1931 case aListSecretKeys: mode = (0 | 2 | (1<<6)); break;
1932 case aDumpSecretKeys: mode = (256 | 2 | (1<<6)); break;
1936 fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
1937 for (sl=NULL; argc; argc--, argv++)
1938 add_to_strlist (&sl, *argv);
1939 gpgsm_list_keys (&ctrl, sl, fp, mode);
1946 case aKeygen: /* Generate a key; well kind of. */
1948 estream_t fpin = NULL;
1953 if (!argc) /* Create from stdin. */
1954 fpin = open_es_fread ("-", "r");
1955 else if (argc == 1) /* From file. */
1956 fpin = open_es_fread (*argv, "r");
1958 wrong_args ("--generate-key --batch [parmfile]");
1961 fpout = open_es_fwrite (opt.outfile?opt.outfile:"-");
1964 gpgsm_genkey (&ctrl, fpin, fpout);
1966 gpgsm_gencertreq_tty (&ctrl, fpout);
1974 gpgsm_import_files (&ctrl, argc, argv, open_read);
1981 fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
1982 for (sl=NULL; argc; argc--, argv++)
1983 add_to_strlist (&sl, *argv);
1984 gpgsm_export (&ctrl, sl, fp);
1990 case aExportSecretKeyP12:
1992 estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
1995 gpgsm_p12_export (&ctrl, *argv, fp, 0);
1997 wrong_args ("--export-secret-key-p12 KEY-ID");
1998 if (fp != es_stdout)
2003 case aExportSecretKeyP8:
2005 estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
2008 gpgsm_p12_export (&ctrl, *argv, fp, 1);
2010 wrong_args ("--export-secret-key-p8 KEY-ID");
2011 if (fp != es_stdout)
2016 case aExportSecretKeyRaw:
2018 estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
2021 gpgsm_p12_export (&ctrl, *argv, fp, 2);
2023 wrong_args ("--export-secret-key-raw KEY-ID");
2024 if (fp != es_stdout)
2031 log_error ("this command has not yet been implemented\n");
2037 wrong_args ("--learn-card");
2040 int rc = gpgsm_agent_learn (&ctrl);
2042 log_error ("error learning card: %s\n", gpg_strerror (rc));
2048 wrong_args ("--change-passphrase <key-Id>");
2052 ksba_cert_t cert = NULL;
2055 rc = gpgsm_find_cert (&ctrl, *argv, NULL, &cert, 0);
2058 else if (!(grip = gpgsm_get_keygrip_hexstring (cert)))
2059 rc = gpg_error (GPG_ERR_BUG);
2062 char *desc = gpgsm_format_keydesc (cert);
2063 rc = gpgsm_agent_passwd (&ctrl, grip, desc);
2067 log_error ("error changing passphrase: %s\n", gpg_strerror (rc));
2069 ksba_cert_release (cert);
2073 case aKeydbClearSomeCertFlags:
2074 for (sl=NULL; argc; argc--, argv++)
2075 add_to_strlist (&sl, *argv);
2076 keydb_clear_some_cert_flags (&ctrl, sl);
2082 log_error (_("invalid command (there is no implicit command)\n"));
2086 /* Print the audit result if needed. */
2087 if ((auditlog && auditfp) || (htmlauditlog && htmlauditfp))
2089 if (auditlog && auditfp)
2090 audit_print_result (ctrl.audit, auditfp, 0);
2091 if (htmlauditlog && htmlauditfp)
2092 audit_print_result (ctrl.audit, htmlauditfp, 1);
2093 audit_release (ctrl.audit);
2095 es_fclose (auditfp);
2096 es_fclose (htmlauditfp);
2100 keyserver_list_free (opt.keyserver);
2101 opt.keyserver = NULL;
2102 gpgsm_release_certlist (recplist);
2103 gpgsm_release_certlist (signerlist);
2104 FREE_STRLIST (remusr);
2105 FREE_STRLIST (locusr);
2107 return 8; /*NOTREACHED*/
2110 /* Note: This function is used by signal handlers!. */
2112 emergency_cleanup (void)
2114 gcry_control (GCRYCTL_TERM_SECMEM );
2121 gcry_control (GCRYCTL_UPDATE_RANDOM_SEED_FILE);
2122 if (opt.debug & DBG_MEMSTAT_VALUE)
2124 gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
2125 gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
2128 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
2129 emergency_cleanup ();
2130 rc = rc? rc : log_get_errorcount(0)? 2 : gpgsm_errors_seen? 1 : 0;
2136 gpgsm_init_default_ctrl (struct server_control_s *ctrl)
2138 ctrl->include_certs = default_include_certs;
2139 ctrl->use_ocsp = opt.enable_ocsp;
2140 ctrl->validation_model = default_validation_model;
2141 ctrl->offline = opt.disable_dirmngr;
2146 gpgsm_parse_validation_model (const char *model)
2148 if (!ascii_strcasecmp (model, "shell") )
2150 else if ( !ascii_strcasecmp (model, "chain") )
2152 else if ( !ascii_strcasecmp (model, "steed") )
2160 /* Open the FILENAME for read and return the file descriptor. Stop
2161 with an error message in case of problems. "-" denotes stdin and
2162 if special filenames are allowed the given fd is opened instead. */
2164 open_read (const char *filename)
2168 if (filename[0] == '-' && !filename[1])
2171 return 0; /* stdin */
2173 fd = check_special_filename (filename, 0, 0);
2176 fd = open (filename, O_RDONLY | O_BINARY);
2179 log_error (_("can't open '%s': %s\n"), filename, strerror (errno));
2185 /* Same as open_read but return an estream_t. */
2187 open_es_fread (const char *filename, const char *mode)
2192 if (filename[0] == '-' && !filename[1])
2193 fd = fileno (stdin);
2195 fd = check_special_filename (filename, 0, 0);
2198 fp = es_fdopen_nc (fd, mode);
2201 log_error ("es_fdopen(%d) failed: %s\n", fd, strerror (errno));
2206 fp = es_fopen (filename, mode);
2209 log_error (_("can't open '%s': %s\n"), filename, strerror (errno));
2216 /* Open FILENAME for fwrite and return an extended stream. Stop with
2217 an error message in case of problems. "-" denotes stdout and if
2218 special filenames are allowed the given fd is opened instead.
2219 Caller must close the returned stream. */
2221 open_es_fwrite (const char *filename)
2226 if (filename[0] == '-' && !filename[1])
2229 fp = es_fdopen_nc (fileno(stdout), "wb");
2233 fd = check_special_filename (filename, 1, 0);
2236 fp = es_fdopen_nc (fd, "wb");
2239 log_error ("es_fdopen(%d) failed: %s\n", fd, strerror (errno));
2244 fp = es_fopen (filename, "wb");
2247 log_error (_("can't open '%s': %s\n"), filename, strerror (errno));
2255 run_protect_tool (int argc, char **argv)
2257 #ifdef HAVE_W32_SYSTEM
2265 if (!opt.protect_tool_program || !*opt.protect_tool_program)
2266 pgm = gnupg_module_name (GNUPG_MODULE_NAME_PROTECT_TOOL);
2268 pgm = opt.protect_tool_program;
2270 av = xcalloc (argc+2, sizeof *av);
2271 av[0] = strrchr (pgm, '/');
2273 av[0] = xstrdup (pgm);
2274 for (i=1; argc; i++, argc--, argv++)
2278 log_error ("error executing '%s': %s\n", pgm, strerror (errno));
2279 #endif /*!HAVE_W32_SYSTEM*/