1 /* gpgsm.c - GnuPG for S/MIME
2 * Copyright (C) 2001, 2002, 2003, 2004, 2005,
3 * 2006, 2007, 2008 Free Software Foundation, Inc.
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 <http://www.gnu.org/licenses/>.
29 /*#include <mcheck.h>*/
33 #include <assuan.h> /* malloc hooks */
35 #include "../kbx/keybox.h" /* malloc hooks */
39 #include "gc-opt-flags.h"
46 enum cmd_and_opt_values {
54 aListSecretKeys = 'K',
86 aKeydbClearSomeCertFlags,
96 oDebugNoChainValidation,
97 oDebugIgnoreExpiration,
104 oEnableSpecialFilenames,
114 oPreferSystemDirmngr,
131 oDisableTrustedCertCRLCheck,
132 oEnableTrustedCertCRLCheck,
140 oDisablePolicyChecks,
142 oAutoIssuerKeyRetrieve,
179 oNoCommonCertsImport,
184 static ARGPARSE_OPTS opts[] = {
186 ARGPARSE_group (300, N_("@Commands:\n ")),
188 ARGPARSE_c (aSign, "sign", N_("make a signature")),
189 ARGPARSE_c (aClearsign, "clearsign", N_("make a clear text signature") ),
190 ARGPARSE_c (aDetachedSign, "detach-sign", N_("make a detached signature")),
191 ARGPARSE_c (aEncr, "encrypt", N_("encrypt data")),
192 ARGPARSE_c (aSym, "symmetric", N_("encryption only with symmetric cipher")),
193 ARGPARSE_c (aDecrypt, "decrypt", N_("decrypt data (default)")),
194 ARGPARSE_c (aVerify, "verify", N_("verify a signature")),
195 ARGPARSE_c (aListKeys, "list-keys", N_("list keys")),
196 ARGPARSE_c (aListExternalKeys, "list-external-keys",
197 N_("list external keys")),
198 ARGPARSE_c (aListSecretKeys, "list-secret-keys", N_("list secret keys")),
199 ARGPARSE_c (aListChain, "list-chain", N_("list certificate chain")),
200 ARGPARSE_c (aFingerprint, "fingerprint", N_("list keys and fingerprints")),
201 ARGPARSE_c (aKeygen, "gen-key", N_("generate a new key pair")),
202 ARGPARSE_c (aDeleteKey, "delete-keys",
203 N_("remove keys from the public keyring")),
204 ARGPARSE_c (aSendKeys, "send-keys", N_("export keys to a key server")),
205 ARGPARSE_c (aRecvKeys, "recv-keys", N_("import keys from a key server")),
206 ARGPARSE_c (aImport, "import", N_("import certificates")),
207 ARGPARSE_c (aExport, "export", N_("export certificates")),
208 ARGPARSE_c (aExportSecretKeyP12, "export-secret-key-p12", "@"),
209 ARGPARSE_c (aLearnCard, "learn-card", N_("register a smartcard")),
210 ARGPARSE_c (aServer, "server", N_("run in server mode")),
211 ARGPARSE_c (aCallDirmngr, "call-dirmngr",
212 N_("pass a command to the dirmngr")),
213 ARGPARSE_c (aCallProtectTool, "call-protect-tool",
214 N_("invoke gpg-protect-tool")),
215 ARGPARSE_c (aPasswd, "passwd", N_("change a passphrase")),
216 ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"),
217 ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"),
219 ARGPARSE_c (aDumpKeys, "dump-cert", "@"),
220 ARGPARSE_c (aDumpKeys, "dump-keys", "@"),
221 ARGPARSE_c (aDumpChain, "dump-chain", "@"),
222 ARGPARSE_c (aDumpExternalKeys, "dump-external-keys", "@"),
223 ARGPARSE_c (aDumpSecretKeys, "dump-secret-keys", "@"),
224 ARGPARSE_c (aKeydbClearSomeCertFlags, "keydb-clear-some-cert-flags", "@"),
226 ARGPARSE_group (301, N_("@\nOptions:\n ")),
228 ARGPARSE_s_n (oArmor, "armor", N_("create ascii armored output")),
229 ARGPARSE_s_n (oArmor, "armour", "@"),
230 ARGPARSE_s_n (oBase64, "base64", N_("create base-64 encoded output")),
232 ARGPARSE_s_s (oP12Charset, "p12-charset", "@"),
234 ARGPARSE_s_n (oAssumeArmor, "assume-armor",
235 N_("assume input is in PEM format")),
236 ARGPARSE_s_n (oAssumeBase64, "assume-base64",
237 N_("assume input is in base-64 format")),
238 ARGPARSE_s_n (oAssumeBinary, "assume-binary",
239 N_("assume input is in binary format")),
241 ARGPARSE_s_s (oRecipient, "recipient", N_("|USER-ID|encrypt for USER-ID")),
243 ARGPARSE_s_n (oPreferSystemDirmngr,"prefer-system-dirmngr",
244 N_("use system's dirmngr if available")),
246 ARGPARSE_s_n (oDisableCRLChecks, "disable-crl-checks",
247 N_("never consult a CRL")),
248 ARGPARSE_s_n (oEnableCRLChecks, "enable-crl-checks", "@"),
249 ARGPARSE_s_n (oDisableTrustedCertCRLCheck,
250 "disable-trusted-cert-crl-check", "@"),
251 ARGPARSE_s_n (oEnableTrustedCertCRLCheck,
252 "enable-trusted-cert-crl-check", "@"),
254 ARGPARSE_s_n (oForceCRLRefresh, "force-crl-refresh", "@"),
256 ARGPARSE_s_n (oDisableOCSP, "disable-ocsp", "@"),
257 ARGPARSE_s_n (oEnableOCSP, "enable-ocsp", N_("check validity using OCSP")),
259 ARGPARSE_s_s (oValidationModel, "validation-model", "@"),
261 ARGPARSE_s_i (oIncludeCerts, "include-certs",
262 N_("|N|number of certificates to include") ),
264 ARGPARSE_s_s (oPolicyFile, "policy-file",
265 N_("|FILE|take policy information from FILE")),
267 ARGPARSE_s_n (oDisablePolicyChecks, "disable-policy-checks",
268 N_("do not check certificate policies")),
269 ARGPARSE_s_n (oEnablePolicyChecks, "enable-policy-checks", "@"),
271 ARGPARSE_s_n (oAutoIssuerKeyRetrieve, "auto-issuer-key-retrieve",
272 N_("fetch missing issuer certificates")),
274 ARGPARSE_s_s (oEncryptTo, "encrypt-to", "@"),
275 ARGPARSE_s_n (oNoEncryptTo, "no-encrypt-to", "@"),
277 ARGPARSE_s_s (oUser, "local-user",
278 N_("|USER-ID|use USER-ID to sign or decrypt")),
280 ARGPARSE_s_s (oOutput, "output", N_("|FILE|write output to FILE")),
281 ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
282 ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")),
283 ARGPARSE_s_n (oNoTTY, "no-tty", N_("don't use the terminal at all")),
284 ARGPARSE_s_s (oLogFile, "log-file",
285 N_("|FILE|write a server mode log to FILE")),
286 ARGPARSE_s_n (oNoLogFile, "no-log-file", "@"),
287 ARGPARSE_s_i (oLoggerFD, "logger-fd", "@"),
289 ARGPARSE_s_s (oAuditLog, "audit-log",
290 N_("|FILE|write an audit log to FILE")),
291 ARGPARSE_s_s (oHtmlAuditLog, "html-audit-log", "@"),
292 ARGPARSE_s_n (oDryRun, "dry-run", N_("do not make any changes")),
293 ARGPARSE_s_n (oBatch, "batch", N_("batch mode: never ask")),
294 ARGPARSE_s_n (oAnswerYes, "yes", N_("assume yes on most questions")),
295 ARGPARSE_s_n (oAnswerNo, "no", N_("assume no on most questions")),
297 ARGPARSE_s_s (oKeyring, "keyring",
298 N_("|FILE|add keyring to the list of keyrings")),
300 ARGPARSE_s_s (oDefaultKey, "default-key",
301 N_("|USER-ID|use USER-ID as default secret key")),
304 /* ARGPARSE_s_s (oDefRecipient, "default-recipient", */
305 /* N_("|NAME|use NAME as default recipient")), */
306 /* ARGPARSE_s_n (oDefRecipientSelf, "default-recipient-self", */
307 /* N_("use the default key as default recipient")), */
308 /* ARGPARSE_s_n (oNoDefRecipient, "no-default-recipient", "@"), */
310 ARGPARSE_s_s (oKeyServer, "keyserver",
311 N_("|SPEC|use this keyserver to lookup keys")),
312 ARGPARSE_s_s (oOptions, "options", N_("|FILE|read options from FILE")),
314 ARGPARSE_p_u (oDebug, "debug", "@"),
315 ARGPARSE_s_s (oDebugLevel, "debug-level",
316 N_("|LEVEL|set the debugging level to LEVEL")),
317 ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
318 ARGPARSE_s_n (oDebugNone, "debug-none", "@"),
319 ARGPARSE_s_i (oDebugWait, "debug-wait", "@"),
320 ARGPARSE_s_n (oDebugAllowCoreDump, "debug-allow-core-dump", "@"),
321 ARGPARSE_s_n (oDebugNoChainValidation, "debug-no-chain-validation", "@"),
322 ARGPARSE_s_n (oDebugIgnoreExpiration, "debug-ignore-expiration", "@"),
323 ARGPARSE_s_s (oFixedPassphrase, "fixed-passphrase", "@"),
325 ARGPARSE_s_i (oStatusFD, "status-fd",
326 N_("|FD|write status info to this FD")),
328 ARGPARSE_s_s (oCipherAlgo, "cipher-algo",
329 N_("|NAME|use cipher algorithm NAME")),
330 ARGPARSE_s_s (oDigestAlgo, "digest-algo",
331 N_("|NAME|use message digest algorithm NAME")),
332 ARGPARSE_s_s (oExtraDigestAlgo, "extra-digest-algo", "@"),
335 ARGPARSE_group (302, N_(
336 "@\n(See the man page for a complete listing of all commands and options)\n"
339 ARGPARSE_group (303, N_("@\nExamples:\n\n"
340 " -se -r Bob [file] sign and encrypt for user Bob\n"
341 " --clearsign [file] make a clear text signature\n"
342 " --detach-sign [file] make a detached signature\n"
343 " --list-keys [names] show keys\n"
344 " --fingerprint [names] show fingerprints\n" )),
346 /* Hidden options. */
347 ARGPARSE_s_n (oNoVerbose, "no-verbose", "@"),
348 ARGPARSE_s_n (oEnableSpecialFilenames, "enable-special-filenames", "@"),
349 ARGPARSE_s_n (oNoSecmemWarn, "no-secmem-warning", "@"),
350 ARGPARSE_s_n (oNoArmor, "no-armor", "@"),
351 ARGPARSE_s_n (oNoArmor, "no-armour", "@"),
352 ARGPARSE_s_n (oNoDefKeyring, "no-default-keyring", "@"),
353 ARGPARSE_s_n (oNoGreeting, "no-greeting", "@"),
354 ARGPARSE_s_n (oNoOptions, "no-options", "@"),
355 ARGPARSE_s_s (oHomedir, "homedir", "@"),
356 ARGPARSE_s_s (oAgentProgram, "agent-program", "@"),
357 ARGPARSE_s_s (oDisplay, "display", "@"),
358 ARGPARSE_s_s (oTTYname, "ttyname", "@"),
359 ARGPARSE_s_s (oTTYtype, "ttytype", "@"),
360 ARGPARSE_s_s (oLCctype, "lc-ctype", "@"),
361 ARGPARSE_s_s (oLCmessages, "lc-messages", "@"),
362 ARGPARSE_s_s (oXauthority, "xauthority", "@"),
363 ARGPARSE_s_s (oDirmngrProgram, "dirmngr-program", "@"),
364 ARGPARSE_s_n (oDisableDirmngr, "disable-dirmngr", "@"),
365 ARGPARSE_s_s (oProtectToolProgram, "protect-tool-program", "@"),
366 ARGPARSE_s_s (oFakedSystemTime, "faked-system-time", "@"),
367 ARGPARSE_s_n (oNoBatch, "no-batch", "@"),
368 ARGPARSE_s_n (oWithColons, "with-colons", "@"),
369 ARGPARSE_s_n (oWithKeyData,"with-key-data", "@"),
370 ARGPARSE_s_n (oWithValidation, "with-validation", "@"),
371 ARGPARSE_s_n (oWithMD5Fingerprint, "with-md5-fingerprint", "@"),
372 ARGPARSE_s_n (oWithEphemeralKeys, "with-ephemeral-keys", "@"),
373 ARGPARSE_s_n (oSkipVerify, "skip-verify", "@"),
374 ARGPARSE_s_n (oWithFingerprint, "with-fingerprint", "@"),
375 ARGPARSE_s_s (oDisableCipherAlgo, "disable-cipher-algo", "@"),
376 ARGPARSE_s_s (oDisablePubkeyAlgo, "disable-pubkey-algo", "@"),
377 ARGPARSE_s_n (oIgnoreTimeConflict, "ignore-time-conflict", "@"),
378 ARGPARSE_s_n (oNoRandomSeedFile, "no-random-seed-file", "@"),
379 ARGPARSE_s_n (oNoCommonCertsImport, "no-common-certs-import", "@"),
380 ARGPARSE_s_s (oIgnoreCertExtension, "ignore-cert-extension", "@"),
382 /* Command aliases. */
383 ARGPARSE_c (aListKeys, "list-key", "@"),
384 ARGPARSE_c (aListChain, "list-sig", "@"),
385 ARGPARSE_c (aListChain, "list-sigs", "@"),
386 ARGPARSE_c (aListChain, "check-sig", "@"),
387 ARGPARSE_c (aListChain, "check-sigs", "@"),
388 ARGPARSE_c (aDeleteKey, "delete-key", "@"),
396 /* Global variable to keep an error count. */
397 int gpgsm_errors_seen = 0;
399 /* It is possible that we are currentlu running under setuid permissions */
400 static int maybe_setuid = 1;
402 /* Helper to implement --debug-level and --debug*/
403 static const char *debug_level;
404 static unsigned int debug_value;
406 /* Option --enable-special-filenames */
407 static int allow_special_filenames;
409 /* Default value for include-certs. We need an extra macro for
410 gpgconf-list because the variable will be changed by the command
412 #define DEFAULT_INCLUDE_CERTS -2 /* Include all certs but root. */
413 static int default_include_certs = DEFAULT_INCLUDE_CERTS;
415 /* Whether the chain mode shall be used for validation. */
416 static int default_validation_model;
419 static char *build_list (const char *text,
420 const char *(*mapf)(int), int (*chkf)(int));
421 static void set_cmd (enum cmd_and_opt_values *ret_cmd,
422 enum cmd_and_opt_values new_cmd );
424 static void emergency_cleanup (void);
425 static int check_special_filename (const char *fname, int for_write);
426 static int open_read (const char *filename);
427 static estream_t open_es_fread (const char *filename);
428 static FILE *open_fwrite (const char *filename);
429 static estream_t open_es_fwrite (const char *filename);
430 static void run_protect_tool (int argc, char **argv);
433 our_pk_test_algo (int algo)
439 return gcry_pk_test_algo (algo);
446 our_cipher_test_algo (int algo)
450 case GCRY_CIPHER_3DES:
451 case GCRY_CIPHER_AES128:
452 case GCRY_CIPHER_AES192:
453 case GCRY_CIPHER_AES256:
454 case GCRY_CIPHER_SERPENT128:
455 case GCRY_CIPHER_SERPENT192:
456 case GCRY_CIPHER_SERPENT256:
457 case GCRY_CIPHER_SEED:
458 case GCRY_CIPHER_CAMELLIA128:
459 case GCRY_CIPHER_CAMELLIA192:
460 case GCRY_CIPHER_CAMELLIA256:
461 return gcry_cipher_test_algo (algo);
469 our_md_test_algo (int algo)
480 case GCRY_MD_WHIRLPOOL:
481 return gcry_md_test_algo (algo);
489 make_libversion (const char *libname, const char *(*getfnc)(const char*))
496 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
500 result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
501 strcpy (stpcpy (stpcpy (result, libname), " "), s);
507 my_strusage( int level )
509 static char *digests, *pubkeys, *ciphers;
510 static char *ver_gcry, *ver_ksba;
515 case 11: p = "gpgsm (GnuPG)";
517 case 13: p = VERSION; break;
518 case 17: p = PRINTABLE_OS_NAME; break;
519 case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
522 case 40: p = _("Usage: gpgsm [options] [files] (-h for help)");
525 p = _("Syntax: gpgsm [options] [files]\n"
526 "Sign, check, encrypt or decrypt using the S/MIME protocol\n"
527 "Default operation depends on the input data\n");
532 ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
537 ver_ksba = make_libversion ("libksba", ksba_check_version);
541 case 31: p = "\nHome: "; break;
542 case 32: p = opt.homedir; break;
543 case 33: p = _("\nSupported algorithms:\n"); break;
546 ciphers = build_list ("Cipher: ", gcry_cipher_algo_name,
547 our_cipher_test_algo );
552 pubkeys = build_list ("Pubkey: ", gcry_pk_algo_name,
558 digests = build_list("Hash: ", gcry_md_algo_name, our_md_test_algo );
562 default: p = NULL; break;
569 build_list (const char *text, const char * (*mapf)(int), int (*chkf)(int))
572 size_t n=strlen(text)+2;
576 gcry_control (GCRYCTL_DROP_PRIVS); /* drop setuid */
579 for (i=1; i < 400; i++ )
581 n += strlen(mapf(i)) + 2;
582 list = xmalloc (21 + n);
584 for (p=NULL, i=1; i < 400; i++)
589 p = stpcpy (list, text );
591 p = stpcpy (p, ", ");
592 p = stpcpy (p, mapf(i) );
596 p = stpcpy(p, "\n" );
601 /* Set the file pointer into binary mode if required. */
603 set_binary (FILE *fp)
605 #ifdef HAVE_DOSISH_SYSTEM
606 setmode (fileno (fp), O_BINARY);
615 wrong_args (const char *text)
617 fputs (_("usage: gpgsm [options] "), stderr);
618 fputs (text, stderr);
625 set_opt_session_env (const char *name, const char *value)
629 err = session_env_setenv (opt.session_env, name, value);
631 log_fatal ("error setting session environment: %s\n",
636 /* Setup the debugging. With a DEBUG_LEVEL of NULL only the active
637 debug flags are propagated to the subsystems. With DEBUG_LEVEL
638 set, a specific set of debug flags is set; and individual debugging
639 flags will be added on top. */
643 int numok = (debug_level && digitp (debug_level));
644 int numlvl = numok? atoi (debug_level) : 0;
648 else if (!strcmp (debug_level, "none") || (numok && numlvl < 1))
650 else if (!strcmp (debug_level, "basic") || (numok && numlvl <= 2))
651 opt.debug = DBG_ASSUAN_VALUE;
652 else if (!strcmp (debug_level, "advanced") || (numok && numlvl <= 5))
653 opt.debug = DBG_ASSUAN_VALUE|DBG_X509_VALUE;
654 else if (!strcmp (debug_level, "expert") || (numok && numlvl <= 8))
655 opt.debug = (DBG_ASSUAN_VALUE|DBG_X509_VALUE
656 |DBG_CACHE_VALUE|DBG_CRYPTO_VALUE);
657 else if (!strcmp (debug_level, "guru") || numok)
660 /* Unless the "guru" string has been used we don't want to allow
661 hashing debugging. The rationale is that people tend to
662 select the highest debug value and would then clutter their
663 disk with debug files which may reveal confidential data. */
665 opt.debug &= ~(DBG_HASHING_VALUE);
669 log_error (_("invalid debug-level `%s' given\n"), debug_level);
673 opt.debug |= debug_value;
675 if (opt.debug && !opt.verbose)
680 if (opt.debug & DBG_MPI_VALUE)
681 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
682 if (opt.debug & DBG_CRYPTO_VALUE )
683 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
684 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
687 log_info ("enabled debug flags:%s%s%s%s%s%s%s%s\n",
688 (opt.debug & DBG_X509_VALUE )? " x509":"",
689 (opt.debug & DBG_MPI_VALUE )? " mpi":"",
690 (opt.debug & DBG_CRYPTO_VALUE )? " crypto":"",
691 (opt.debug & DBG_MEMORY_VALUE )? " memory":"",
692 (opt.debug & DBG_CACHE_VALUE )? " cache":"",
693 (opt.debug & DBG_MEMSTAT_VALUE)? " memstat":"",
694 (opt.debug & DBG_HASHING_VALUE)? " hashing":"",
695 (opt.debug & DBG_ASSUAN_VALUE )? " assuan":"" );
701 set_cmd (enum cmd_and_opt_values *ret_cmd, enum cmd_and_opt_values new_cmd)
703 enum cmd_and_opt_values cmd = *ret_cmd;
705 if (!cmd || cmd == new_cmd)
707 else if ( cmd == aSign && new_cmd == aEncr )
709 else if ( cmd == aEncr && new_cmd == aSign )
711 else if ( (cmd == aSign && new_cmd == aClearsign)
712 || (cmd == aClearsign && new_cmd == aSign) )
716 log_error(_("conflicting commands\n"));
724 /* Helper to add recipients to a list. */
726 do_add_recipient (ctrl_t ctrl, const char *name,
727 certlist_t *recplist, int is_encrypt_to, int recp_required)
729 int rc = gpgsm_add_to_certlist (ctrl, name, 0, recplist, is_encrypt_to);
734 log_error ("can't encrypt to `%s': %s\n", name, gpg_strerror (rc));
735 gpgsm_status2 (ctrl, STATUS_INV_RECP,
736 get_inv_recpsgnr_code (rc), name, NULL);
739 log_info (_("NOTE: won't be able to encrypt to `%s': %s\n"),
740 name, gpg_strerror (rc));
746 parse_validation_model (const char *model)
748 int i = gpgsm_parse_validation_model (model);
750 log_error (_("unknown validation model `%s'\n"), model);
752 default_validation_model = i;
756 /* Release the list of SERVERS. As usual it is okay to call this
757 function with SERVERS passed as NULL. */
759 keyserver_list_free (struct keyserver_spec *servers)
763 struct keyserver_spec *tmp = servers->next;
764 xfree (servers->host);
765 xfree (servers->user);
767 memset (servers->pass, 0, strlen (servers->pass));
768 xfree (servers->pass);
769 xfree (servers->base);
775 /* See also dirmngr ldapserver_parse_one(). */
776 struct keyserver_spec *
777 parse_keyserver_line (char *line,
778 const char *filename, unsigned int lineno)
782 struct keyserver_spec *server;
786 /* Parse the colon separated fields. */
787 server = xcalloc (1, sizeof *server);
788 for (fieldno = 1, p = line; p; p = endp, fieldno++ )
790 endp = strchr (p, ':');
798 server->host = xstrdup (p);
801 log_error (_("%s:%u: no hostname given\n"),
809 server->port = atoi (p);
814 server->user = xstrdup (p);
818 if (*p && !server->user)
820 log_error (_("%s:%u: password given without user\n"),
825 server->pass = xstrdup (p);
830 server->base = xstrdup (p);
834 /* (We silently ignore extra fields.) */
841 log_info (_("%s:%u: skipping this line\n"), filename, lineno);
842 keyserver_list_free (server);
850 main ( int argc, char **argv)
857 strlist_t sl, remusr= NULL, locusr=NULL;
858 strlist_t nrings=NULL;
859 int detached_sig = 0;
860 FILE *configfp = NULL;
861 char *configname = NULL;
862 unsigned configlineno;
864 int no_more_options = 0;
865 int default_config =1;
866 int default_keyring = 1;
867 char *logfile = NULL;
868 char *auditlog = NULL;
869 char *htmlauditlog = NULL;
873 int use_random_seed = 1;
874 int no_common_certs_import = 0;
876 const char *forced_digest_algo = NULL;
877 const char *extra_digest_algo = NULL;
878 enum cmd_and_opt_values cmd = 0;
879 struct server_control_s ctrl;
880 certlist_t recplist = NULL;
881 certlist_t signerlist = NULL;
882 int do_not_setup_keys = 0;
883 int recp_required = 0;
884 estream_t auditfp = NULL;
885 estream_t htmlauditfp = NULL;
886 struct assuan_malloc_hooks malloc_hooks;
890 gnupg_reopen_std ("gpgsm");
891 /* trap_unaligned ();*/
892 gnupg_rl_initialize ();
893 set_strusage (my_strusage);
894 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
895 /* We don't need any locking in libgcrypt unless we use any kind of
897 gcry_control (GCRYCTL_DISABLE_INTERNAL_LOCKING);
899 /* Please note that we may running SUID(ROOT), so be very CAREFUL
900 when adding any stuff between here and the call to secmem_init()
901 somewhere after the option parsing */
902 log_set_prefix ("gpgsm", 1);
904 /* Make sure that our subsystems are ready. */
906 init_common_subsystems ();
908 /* Check that the libraries are suitable. Do it here because the
909 option parse may need services of the library */
910 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
911 log_fatal (_("%s is too old (need %s, have %s)\n"), "libgcrypt",
912 NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
913 if (!ksba_check_version (NEED_KSBA_VERSION) )
914 log_fatal (_("%s is too old (need %s, have %s)\n"), "libksba",
915 NEED_KSBA_VERSION, ksba_check_version (NULL) );
918 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
920 may_coredump = disable_core_dumps ();
922 gnupg_init_signals (0, emergency_cleanup);
924 create_dotlock (NULL); /* register locking cleanup */
926 opt.session_env = session_env_new ();
927 if (!opt.session_env)
928 log_fatal ("error allocating session environment block: %s\n",
931 /* Note: If you change this default cipher algorithm , please
932 remember to update the Gpgconflist entry as well. */
933 opt.def_cipher_algoid = "3DES"; /*des-EDE3-CBC*/
935 opt.homedir = default_homedir ();
937 /* First check whether we have a config file on the commandline */
942 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
943 while (arg_parse( &pargs, opts))
945 if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
947 else if (pargs.r_opt == oOptions)
948 { /* yes there is one, so we do not try the default one but
949 read the config file when it is encountered at the
953 else if (pargs.r_opt == oNoOptions)
955 default_config = 0; /* --no-options */
956 opt.no_homedir_creation = 1;
958 else if (pargs.r_opt == oHomedir)
959 opt.homedir = pargs.r.ret_str;
960 else if (pargs.r_opt == aCallProtectTool)
961 break; /* This break makes sure that --version and --help are
962 passed to the protect-tool. */
966 /* Initialize the secure memory. */
967 gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
971 Now we are now working under our real uid
974 ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free );
976 malloc_hooks.malloc = gcry_malloc;
977 malloc_hooks.realloc = gcry_realloc;
978 malloc_hooks.free = gcry_free;
979 assuan_set_malloc_hooks (&malloc_hooks);
980 assuan_set_assuan_log_prefix (log_get_prefix (NULL));
981 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
983 keybox_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
985 /* Setup a default control structure for command line mode */
986 memset (&ctrl, 0, sizeof ctrl);
987 gpgsm_init_default_ctrl (&ctrl);
989 ctrl.status_fd = -1; /* No status output. */
990 ctrl.autodetect_encoding = 1;
992 /* Set the default option file */
994 configname = make_filename (opt.homedir, "gpgsm.conf", NULL);
995 /* Set the default policy file */
996 opt.policy_file = make_filename (opt.homedir, "policies.txt", NULL);
1002 pargs.flags = 1; /* do not remove the args */
1007 configfp = fopen (configname, "r");
1013 log_info (_("NOTE: no default option file `%s'\n"), configname);
1017 log_error (_("option file `%s': %s\n"), configname, strerror(errno));
1023 if (parse_debug && configname)
1024 log_info (_("reading options from `%s'\n"), configname);
1028 while (!no_more_options
1029 && optfile_parse (configfp, configname, &configlineno, &pargs, opts))
1031 switch (pargs.r_opt)
1035 set_cmd (&cmd, pargs.r_opt);
1036 do_not_setup_keys = 1;
1042 set_cmd (&cmd, aServer);
1047 set_cmd (&cmd, aCallDirmngr);
1048 do_not_setup_keys = 1;
1051 case aCallProtectTool:
1053 set_cmd (&cmd, aCallProtectTool);
1054 no_more_options = 1; /* Stop parsing. */
1055 do_not_setup_keys = 1;
1059 set_cmd (&cmd, aDeleteKey);
1061 do_not_setup_keys = 1;
1066 set_cmd (&cmd, aSign );
1070 set_cmd (&cmd, aKeygen);
1072 do_not_setup_keys = 1;
1079 case aExportSecretKeyP12:
1082 case aDumpExternalKeys:
1083 case aDumpSecretKeys:
1085 case aListExternalKeys:
1086 case aListSecretKeys:
1090 case aKeydbClearSomeCertFlags:
1091 do_not_setup_keys = 1;
1092 set_cmd (&cmd, pargs.r_opt);
1097 set_cmd (&cmd, pargs.r_opt);
1105 set_cmd (&cmd, pargs.r_opt);
1108 /* Output encoding selection. */
1110 ctrl.create_pem = 1;
1113 ctrl.create_pem = 0;
1114 ctrl.create_base64 = 1;
1117 ctrl.create_pem = 0;
1118 ctrl.create_base64 = 0;
1122 opt.p12_charset = pargs.r.ret_str;
1125 /* Input encoding selection. */
1127 ctrl.autodetect_encoding = 0;
1132 ctrl.autodetect_encoding = 0;
1137 ctrl.autodetect_encoding = 0;
1142 case oDisableCRLChecks:
1143 opt.no_crl_check = 1;
1145 case oEnableCRLChecks:
1146 opt.no_crl_check = 0;
1148 case oDisableTrustedCertCRLCheck:
1149 opt.no_trusted_cert_crl_check = 1;
1151 case oEnableTrustedCertCRLCheck:
1152 opt.no_trusted_cert_crl_check = 0;
1154 case oForceCRLRefresh:
1155 opt.force_crl_refresh = 1;
1159 ctrl.use_ocsp = opt.enable_ocsp = 0;
1162 ctrl.use_ocsp = opt.enable_ocsp = 1;
1166 ctrl.include_certs = default_include_certs = pargs.r.ret_int;
1170 xfree (opt.policy_file);
1171 if (*pargs.r.ret_str)
1172 opt.policy_file = xstrdup (pargs.r.ret_str);
1174 opt.policy_file = NULL;
1177 case oDisablePolicyChecks:
1178 opt.no_policy_check = 1;
1180 case oEnablePolicyChecks:
1181 opt.no_policy_check = 0;
1184 case oAutoIssuerKeyRetrieve:
1185 opt.auto_issuer_key_retrieve = 1;
1188 case oOutput: opt.outfile = pargs.r.ret_str; break;
1191 case oQuiet: opt.quiet = 1; break;
1192 case oNoTTY: /* fixme:tty_no_terminal(1);*/ break;
1193 case oDryRun: opt.dry_run = 1; break;
1197 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
1201 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
1204 case oLogFile: logfile = pargs.r.ret_str; break;
1205 case oNoLogFile: logfile = NULL; break;
1207 case oAuditLog: auditlog = pargs.r.ret_str; break;
1208 case oHtmlAuditLog: htmlauditlog = pargs.r.ret_str; break;
1214 case oNoBatch: opt.batch = 0; break;
1216 case oAnswerYes: opt.answer_yes = 1; break;
1217 case oAnswerNo: opt.answer_no = 1; break;
1219 case oKeyring: append_to_strlist (&nrings, pargs.r.ret_str); break;
1221 case oDebug: debug_value |= pargs.r.ret_ulong; break;
1222 case oDebugAll: debug_value = ~0; break;
1223 case oDebugNone: debug_value = 0; break;
1224 case oDebugLevel: debug_level = pargs.r.ret_str; break;
1225 case oDebugWait: debug_wait = pargs.r.ret_int; break;
1226 case oDebugAllowCoreDump:
1227 may_coredump = enable_core_dumps ();
1229 case oDebugNoChainValidation: opt.no_chain_validation = 1; break;
1230 case oDebugIgnoreExpiration: opt.ignore_expiration = 1; break;
1231 case oFixedPassphrase: opt.fixed_passphrase = pargs.r.ret_str; break;
1233 case oStatusFD: ctrl.status_fd = pargs.r.ret_int; break;
1234 case oLoggerFD: log_set_fd (pargs.r.ret_int ); break;
1235 case oWithMD5Fingerprint:
1236 opt.with_md5_fingerprint=1; /*fall thru*/
1237 case oWithFingerprint:
1238 with_fpr=1; /*fall thru*/
1244 /* config files may not be nested (silently ignore them) */
1248 configname = xstrdup (pargs.r.ret_str);
1252 case oNoOptions: opt.no_homedir_creation = 1; break; /* no-options */
1253 case oHomedir: opt.homedir = pargs.r.ret_str; break;
1254 case oAgentProgram: opt.agent_program = pargs.r.ret_str; break;
1257 set_opt_session_env ("DISPLAY", pargs.r.ret_str);
1260 set_opt_session_env ("GPG_TTY", pargs.r.ret_str);
1263 set_opt_session_env ("TERM", pargs.r.ret_str);
1266 set_opt_session_env ("XAUTHORITY", pargs.r.ret_str);
1269 case oLCctype: opt.lc_ctype = xstrdup (pargs.r.ret_str); break;
1270 case oLCmessages: opt.lc_messages = xstrdup (pargs.r.ret_str); break;
1272 case oDirmngrProgram: opt.dirmngr_program = pargs.r.ret_str; break;
1273 case oDisableDirmngr: opt.disable_dirmngr = 1; break;
1274 case oPreferSystemDirmngr: opt.prefer_system_dirmngr = 1; break;
1275 case oProtectToolProgram:
1276 opt.protect_tool_program = pargs.r.ret_str;
1279 case oFakedSystemTime:
1281 time_t faked_time = isotime2epoch (pargs.r.ret_str);
1282 if (faked_time == (time_t)(-1))
1283 faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
1284 gnupg_set_time (faked_time, 0);
1288 case oNoDefKeyring: default_keyring = 0; break;
1289 case oNoGreeting: nogreeting = 1; break;
1292 if (*pargs.r.ret_str)
1294 xfree (opt.local_user);
1295 opt.local_user = xstrdup (pargs.r.ret_str);
1299 if (*pargs.r.ret_str)
1300 opt.def_recipient = xstrdup (pargs.r.ret_str);
1302 case oDefRecipientSelf:
1303 xfree (opt.def_recipient);
1304 opt.def_recipient = NULL;
1305 opt.def_recipient_self = 1;
1307 case oNoDefRecipient:
1308 xfree (opt.def_recipient);
1309 opt.def_recipient = NULL;
1310 opt.def_recipient_self = 0;
1313 case oWithKeyData: opt.with_key_data=1; /* fall thru */
1314 case oWithColons: ctrl.with_colons = 1; break;
1315 case oWithValidation: ctrl.with_validation=1; break;
1316 case oWithEphemeralKeys: ctrl.with_ephemeral_keys=1; break;
1318 case oSkipVerify: opt.skip_verify=1; break;
1320 case oNoEncryptTo: opt.no_encrypt_to = 1; break;
1321 case oEncryptTo: /* Store the recipient in the second list */
1322 sl = add_to_strlist (&remusr, pargs.r.ret_str);
1326 case oRecipient: /* store the recipient */
1327 add_to_strlist ( &remusr, pargs.r.ret_str);
1330 case oUser: /* Store the local users, the first one is the default */
1331 if (!opt.local_user)
1332 opt.local_user = xstrdup (pargs.r.ret_str);
1333 add_to_strlist (&locusr, pargs.r.ret_str);
1337 gcry_control (GCRYCTL_DISABLE_SECMEM_WARN);
1341 opt.def_cipher_algoid = pargs.r.ret_str;
1344 case oDisableCipherAlgo:
1346 int algo = gcry_cipher_map_name (pargs.r.ret_str);
1347 gcry_cipher_ctl (NULL, GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
1350 case oDisablePubkeyAlgo:
1352 int algo = gcry_pk_map_name (pargs.r.ret_str);
1353 gcry_pk_ctl (GCRYCTL_DISABLE_ALGO,&algo, sizeof algo );
1358 forced_digest_algo = pargs.r.ret_str;
1361 case oExtraDigestAlgo:
1362 extra_digest_algo = pargs.r.ret_str;
1365 case oIgnoreTimeConflict: opt.ignore_time_conflict = 1; break;
1366 case oNoRandomSeedFile: use_random_seed = 0; break;
1367 case oNoCommonCertsImport: no_common_certs_import = 1; break;
1369 case oEnableSpecialFilenames: allow_special_filenames =1; break;
1371 case oValidationModel: parse_validation_model (pargs.r.ret_str); break;
1375 struct keyserver_spec *keyserver;
1376 keyserver = parse_keyserver_line (pargs.r.ret_str,
1377 configname, configlineno);
1379 log_error (_("could not parse keyserver\n"));
1382 /* FIXME: Keep last next pointer. */
1383 struct keyserver_spec **next_p = &opt.keyserver;
1385 next_p = &(*next_p)->next;
1386 *next_p = keyserver;
1391 case oIgnoreCertExtension:
1392 add_to_strlist (&opt.ignored_cert_extensions, pargs.r.ret_str);
1396 pargs.err = configfp? ARGPARSE_PRINT_WARNING:ARGPARSE_PRINT_ERROR;
1405 /* Keep a copy of the config filename. */
1406 opt.config_filename = configname;
1413 if (!opt.config_filename)
1414 opt.config_filename = make_filename (opt.homedir, "gpgsm.conf", NULL);
1416 if (log_get_errorcount(0))
1419 /* Now that we have the options parsed we need to update the default
1420 control structure. */
1421 gpgsm_init_default_ctrl (&ctrl);
1428 fprintf(stderr, "%s %s; %s\n",
1429 strusage(11), strusage(13), strusage(14) );
1430 fprintf(stderr, "%s\n", strusage(15) );
1432 # ifdef IS_DEVELOPMENT_VERSION
1435 log_info ("NOTE: THIS IS A DEVELOPMENT VERSION!\n");
1436 log_info ("It is only intended for test purposes and should NOT be\n");
1437 log_info ("used in a production environment or with production keys!\n");
1441 if (may_coredump && !opt.quiet)
1442 log_info (_("WARNING: program may create a core file!\n"));
1444 /* if (opt.qualsig_approval && !opt.quiet) */
1445 /* log_info (_("This software has offically been approved to " */
1446 /* "create and verify\n" */
1447 /* "qualified signatures according to German law.\n")); */
1449 if (logfile && cmd == aServer)
1451 log_set_file (logfile);
1452 log_set_prefix (NULL, 1|2|4);
1455 if (gnupg_faked_time_p ())
1457 gnupg_isotime_t tbuf;
1459 log_info (_("WARNING: running with faked system time: "));
1460 gnupg_get_isotime (tbuf);
1461 dump_isotime (tbuf);
1465 /*FIXME if (opt.batch) */
1466 /* tty_batchmode (1); */
1468 gcry_control (GCRYCTL_RESUME_SECMEM_WARN);
1472 /* Although we alwasy use gpgsm_exit, we better install a regualr
1473 exit handler so that at least the secure memory gets wiped
1475 if (atexit (emergency_cleanup))
1477 log_error ("atexit failed\n");
1481 /* Must do this after dropping setuid, because the mapping functions
1482 may try to load an module and we may have disabled an algorithm.
1483 We remap the commonly used algorithms to the OIDs for
1484 convenience. We need to work with the OIDs because they are used
1485 to check whether the encryption mode is actually available. */
1486 if (!strcmp (opt.def_cipher_algoid, "3DES") )
1487 opt.def_cipher_algoid = "1.2.840.113549.3.7";
1488 else if (!strcmp (opt.def_cipher_algoid, "AES")
1489 || !strcmp (opt.def_cipher_algoid, "AES128"))
1490 opt.def_cipher_algoid = "2.16.840.1.101.3.4.1.2";
1491 else if (!strcmp (opt.def_cipher_algoid, "AES256") )
1492 opt.def_cipher_algoid = "2.16.840.1.101.3.4.1.42";
1493 else if (!strcmp (opt.def_cipher_algoid, "SERPENT")
1494 || !strcmp (opt.def_cipher_algoid, "SERPENT128") )
1495 opt.def_cipher_algoid = "1.3.6.1.4.1.11591.13.2.2";
1496 else if (!strcmp (opt.def_cipher_algoid, "SERPENT192") )
1497 opt.def_cipher_algoid = "1.3.6.1.4.1.11591.13.2.22";
1498 else if (!strcmp (opt.def_cipher_algoid, "SERPENT192") )
1499 opt.def_cipher_algoid = "1.3.6.1.4.1.11591.13.2.42";
1500 else if (!strcmp (opt.def_cipher_algoid, "SEED") )
1501 opt.def_cipher_algoid = "1.2.410.200004.1.4";
1502 else if (!strcmp (opt.def_cipher_algoid, "CAMELLIA")
1503 || !strcmp (opt.def_cipher_algoid, "CAMELLIA128") )
1504 opt.def_cipher_algoid = "1.2.392.200011.61.1.1.1.2";
1505 else if (!strcmp (opt.def_cipher_algoid, "CAMELLIA192") )
1506 opt.def_cipher_algoid = "1.2.392.200011.61.1.1.1.3";
1507 else if (!strcmp (opt.def_cipher_algoid, "CAMELLIA256") )
1508 opt.def_cipher_algoid = "1.2.392.200011.61.1.1.1.4";
1510 if (cmd != aGPGConfList)
1512 if ( !gcry_cipher_map_name (opt.def_cipher_algoid)
1513 || !gcry_cipher_mode_from_oid (opt.def_cipher_algoid))
1514 log_error (_("selected cipher algorithm is invalid\n"));
1516 if (forced_digest_algo)
1518 opt.forced_digest_algo = gcry_md_map_name (forced_digest_algo);
1519 if (our_md_test_algo(opt.forced_digest_algo) )
1520 log_error (_("selected digest algorithm is invalid\n"));
1522 if (extra_digest_algo)
1524 opt.extra_digest_algo = gcry_md_map_name (extra_digest_algo);
1525 if (our_md_test_algo (opt.extra_digest_algo) )
1526 log_error (_("selected digest algorithm is invalid\n"));
1530 if (log_get_errorcount(0))
1533 /* Set the random seed file. */
1534 if (use_random_seed)
1536 char *p = make_filename (opt.homedir, "random_seed", NULL);
1537 gcry_control (GCRYCTL_SET_RANDOM_SEED_FILE, p);
1541 if (!cmd && opt.fingerprint && !with_fpr)
1542 set_cmd (&cmd, aListKeys);
1544 /* Add default keybox. */
1545 if (!nrings && default_keyring)
1549 keydb_add_resource ("pubring.kbx", 0, 0, &created);
1550 if (created && !no_common_certs_import)
1552 /* Import the standard certificates for a new default keybox. */
1555 filelist[0] = make_filename (gnupg_datadir (),"com-certs.pem", NULL);
1557 if (!access (filelist[0], F_OK))
1559 log_info (_("importing common certificates `%s'\n"),
1561 gpgsm_import_files (&ctrl, 1, filelist, open_read);
1563 xfree (filelist[0]);
1566 for (sl = nrings; sl; sl = sl->next)
1567 keydb_add_resource (sl->d, 0, 0, NULL);
1568 FREE_STRLIST(nrings);
1571 /* Prepare the audit log feature for certain commands. */
1572 if (auditlog || htmlauditlog)
1580 audit_release (ctrl.audit);
1581 ctrl.audit = audit_new ();
1583 auditfp = open_es_fwrite (auditlog);
1585 htmlauditfp = open_es_fwrite (htmlauditlog);
1593 if (!do_not_setup_keys)
1595 for (sl = locusr; sl ; sl = sl->next)
1597 int rc = gpgsm_add_to_certlist (&ctrl, sl->d, 1, &signerlist, 0);
1600 log_error (_("can't sign using `%s': %s\n"),
1601 sl->d, gpg_strerror (rc));
1602 gpgsm_status2 (&ctrl, STATUS_INV_SGNR,
1603 get_inv_recpsgnr_code (rc), sl->d, NULL);
1604 gpgsm_status2 (&ctrl, STATUS_INV_RECP,
1605 get_inv_recpsgnr_code (rc), sl->d, NULL);
1609 /* Build the recipient list. We first add the regular ones and then
1610 the encrypt-to ones because the underlying function will silently
1611 ignore duplicates and we can't allow to keep a duplicate which is
1612 flagged as encrypt-to as the actually encrypt function would then
1613 complain about no (regular) recipients. */
1614 for (sl = remusr; sl; sl = sl->next)
1615 if (!(sl->flags & 1))
1616 do_add_recipient (&ctrl, sl->d, &recplist, 0, recp_required);
1617 if (!opt.no_encrypt_to)
1619 for (sl = remusr; sl; sl = sl->next)
1620 if ((sl->flags & 1))
1621 do_add_recipient (&ctrl, sl->d, &recplist, 1, recp_required);
1625 if (log_get_errorcount(0))
1626 gpgsm_exit(1); /* Must stop for invalid recipients. */
1628 /* Dispatch command. */
1632 { /* List options and default values in the GPG Conf format. */
1633 char *config_filename_esc = percent_escape (opt.config_filename, NULL);
1635 printf ("gpgconf-gpgsm.conf:%lu:\"%s\n",
1636 GC_OPT_FLAG_DEFAULT, config_filename_esc);
1637 xfree (config_filename_esc);
1639 printf ("verbose:%lu:\n", GC_OPT_FLAG_NONE);
1640 printf ("quiet:%lu:\n", GC_OPT_FLAG_NONE);
1641 printf ("debug-level:%lu:\"none:\n", GC_OPT_FLAG_DEFAULT);
1642 printf ("log-file:%lu:\n", GC_OPT_FLAG_NONE);
1643 printf ("disable-crl-checks:%lu:\n", GC_OPT_FLAG_NONE);
1644 printf ("disable-trusted-cert-crl-check:%lu:\n", GC_OPT_FLAG_NONE);
1645 printf ("enable-ocsp:%lu:\n", GC_OPT_FLAG_NONE);
1646 printf ("include-certs:%lu:%d:\n", GC_OPT_FLAG_DEFAULT,
1647 DEFAULT_INCLUDE_CERTS);
1648 printf ("disable-policy-checks:%lu:\n", GC_OPT_FLAG_NONE);
1649 printf ("auto-issuer-key-retrieve:%lu:\n", GC_OPT_FLAG_NONE);
1650 printf ("disable-dirmngr:%lu:\n", GC_OPT_FLAG_NONE);
1651 #ifndef HAVE_W32_SYSTEM
1652 printf ("prefer-system-dirmngr:%lu:\n", GC_OPT_FLAG_NONE);
1654 printf ("cipher-algo:%lu:\"3DES:\n", GC_OPT_FLAG_DEFAULT);
1655 printf ("p12-charset:%lu:\n", GC_OPT_FLAG_DEFAULT);
1656 printf ("default-key:%lu:\n", GC_OPT_FLAG_DEFAULT);
1657 printf ("encrypt-to:%lu:\n", GC_OPT_FLAG_DEFAULT);
1658 printf ("keyserver:%lu:\n", GC_OPT_FLAG_NONE);
1660 /* The next one is an info only item and should match what
1661 proc_parameters actually implements. */
1662 printf ("default_pubkey_algo:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT,
1667 /* This is merely a dummy command to test whether the
1668 configuration file is valid. */
1674 log_debug ("waiting for debugger - my pid is %u .....\n",
1675 (unsigned int)getpid());
1676 gnupg_sleep (debug_wait);
1677 log_debug ("... okay\n");
1679 gpgsm_server (recplist);
1684 wrong_args ("--call-dirmngr <command> {args}");
1686 if (gpgsm_dirmngr_run_command (&ctrl, *argv, argc-1, argv+1))
1690 case aCallProtectTool:
1691 run_protect_tool (argc, argv);
1694 case aEncr: /* Encrypt the given file. */
1696 FILE *fp = open_fwrite (opt.outfile?opt.outfile:"-");
1700 if (!argc) /* Source is stdin. */
1701 gpgsm_encrypt (&ctrl, recplist, 0, fp);
1702 else if (argc == 1) /* Source is the given file. */
1703 gpgsm_encrypt (&ctrl, recplist, open_read (*argv), fp);
1705 wrong_args ("--encrypt [datafile]");
1712 case aSign: /* Sign the given file. */
1714 FILE *fp = open_fwrite (opt.outfile?opt.outfile:"-");
1716 /* Fixme: We should also allow to concatenate multiple files for
1717 signing because that is what gpg does.*/
1719 if (!argc) /* Create from stdin. */
1720 gpgsm_sign (&ctrl, signerlist, 0, detached_sig, fp);
1721 else if (argc == 1) /* From file. */
1722 gpgsm_sign (&ctrl, signerlist,
1723 open_read (*argv), detached_sig, fp);
1725 wrong_args ("--sign [datafile]");
1732 case aSignEncr: /* sign and encrypt the given file */
1733 log_error ("this command has not yet been implemented\n");
1736 case aClearsign: /* make a clearsig */
1737 log_error ("this command has not yet been implemented\n");
1745 if (argc == 2 && opt.outfile)
1746 log_info ("option --output ignored for a detached signature\n");
1747 else if (opt.outfile)
1748 fp = open_fwrite (opt.outfile);
1751 gpgsm_verify (&ctrl, 0, -1, fp); /* normal signature from stdin */
1753 gpgsm_verify (&ctrl, open_read (*argv), -1, fp); /* std signature */
1754 else if (argc == 2) /* detached signature (sig, detached) */
1755 gpgsm_verify (&ctrl, open_read (*argv), open_read (argv[1]), NULL);
1757 wrong_args ("--verify [signature [detached_data]]");
1759 if (fp && fp != stdout)
1766 FILE *fp = open_fwrite (opt.outfile?opt.outfile:"-");
1770 gpgsm_decrypt (&ctrl, 0, fp); /* from stdin */
1772 gpgsm_decrypt (&ctrl, open_read (*argv), fp); /* from file */
1774 wrong_args ("--decrypt [filename]");
1781 for (sl=NULL; argc; argc--, argv++)
1782 add_to_strlist (&sl, *argv);
1783 gpgsm_delete (&ctrl, sl);
1789 ctrl.with_chain = 1;
1792 case aListExternalKeys:
1793 case aDumpExternalKeys:
1794 case aListSecretKeys:
1795 case aDumpSecretKeys:
1803 case aListKeys: mode = (0 | 0 | (1<<6)); break;
1805 case aDumpKeys: mode = (256 | 0 | (1<<6)); break;
1806 case aListExternalKeys: mode = (0 | 0 | (1<<7)); break;
1807 case aDumpExternalKeys: mode = (256 | 0 | (1<<7)); break;
1808 case aListSecretKeys: mode = (0 | 2 | (1<<6)); break;
1809 case aDumpSecretKeys: mode = (256 | 2 | (1<<6)); break;
1813 fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
1814 for (sl=NULL; argc; argc--, argv++)
1815 add_to_strlist (&sl, *argv);
1816 gpgsm_list_keys (&ctrl, sl, fp, mode);
1823 case aKeygen: /* Generate a key; well kind of. */
1825 estream_t fpin = NULL;
1830 if (!argc) /* Create from stdin. */
1831 fpin = open_es_fread ("-");
1832 else if (argc == 1) /* From file. */
1833 fpin = open_es_fread (*argv);
1835 wrong_args ("--gen-key --batch [parmfile]");
1838 fpout = open_fwrite (opt.outfile?opt.outfile:"-");
1841 gpgsm_genkey (&ctrl, fpin, fpout);
1843 gpgsm_gencertreq_tty (&ctrl, fpout);
1845 if (fpout != stdout)
1852 gpgsm_import_files (&ctrl, argc, argv, open_read);
1857 FILE *fp = open_fwrite (opt.outfile?opt.outfile:"-");
1859 for (sl=NULL; argc; argc--, argv++)
1860 add_to_strlist (&sl, *argv);
1861 gpgsm_export (&ctrl, sl, fp, NULL);
1868 case aExportSecretKeyP12:
1870 FILE *fp = open_fwrite (opt.outfile?opt.outfile:"-");
1873 gpgsm_p12_export (&ctrl, *argv, fp);
1875 wrong_args ("--export-secret-key-p12 KEY-ID");
1883 log_error ("this command has not yet been implemented\n");
1889 wrong_args ("--learn-card");
1892 int rc = gpgsm_agent_learn (&ctrl);
1894 log_error ("error learning card: %s\n", gpg_strerror (rc));
1900 wrong_args ("--passwd <key-Id>");
1904 ksba_cert_t cert = NULL;
1907 rc = gpgsm_find_cert (*argv, NULL, &cert);
1910 else if (!(grip = gpgsm_get_keygrip_hexstring (cert)))
1911 rc = gpg_error (GPG_ERR_BUG);
1914 char *desc = gpgsm_format_keydesc (cert);
1915 rc = gpgsm_agent_passwd (&ctrl, grip, desc);
1919 log_error ("error changing passphrase: %s\n", gpg_strerror (rc));
1921 ksba_cert_release (cert);
1925 case aKeydbClearSomeCertFlags:
1926 for (sl=NULL; argc; argc--, argv++)
1927 add_to_strlist (&sl, *argv);
1928 keydb_clear_some_cert_flags (&ctrl, sl);
1934 log_error (_("invalid command (there is no implicit command)\n"));
1938 /* Print the audit result if needed. */
1939 if ((auditlog && auditfp) || (htmlauditlog && htmlauditfp))
1941 if (auditlog && auditfp)
1942 audit_print_result (ctrl.audit, auditfp, 0);
1943 if (htmlauditlog && htmlauditfp)
1944 audit_print_result (ctrl.audit, htmlauditfp, 1);
1945 audit_release (ctrl.audit);
1947 es_fclose (auditfp);
1948 es_fclose (htmlauditfp);
1952 keyserver_list_free (opt.keyserver);
1953 opt.keyserver = NULL;
1954 gpgsm_release_certlist (recplist);
1955 gpgsm_release_certlist (signerlist);
1956 FREE_STRLIST (remusr);
1957 FREE_STRLIST (locusr);
1959 return 8; /*NOTREACHED*/
1962 /* Note: This function is used by signal handlers!. */
1964 emergency_cleanup (void)
1966 gcry_control (GCRYCTL_TERM_SECMEM );
1973 gcry_control (GCRYCTL_UPDATE_RANDOM_SEED_FILE);
1974 if (opt.debug & DBG_MEMSTAT_VALUE)
1976 gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
1977 gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
1980 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
1981 emergency_cleanup ();
1982 rc = rc? rc : log_get_errorcount(0)? 2 : gpgsm_errors_seen? 1 : 0;
1988 gpgsm_init_default_ctrl (struct server_control_s *ctrl)
1990 ctrl->include_certs = default_include_certs;
1991 ctrl->use_ocsp = opt.enable_ocsp;
1992 ctrl->validation_model = default_validation_model;
1997 gpgsm_parse_validation_model (const char *model)
1999 if (!ascii_strcasecmp (model, "shell") )
2001 else if ( !ascii_strcasecmp (model, "chain") )
2008 /* Check whether the filename has the form "-&nnnn", where n is a
2009 non-zero number. Returns this number or -1 if it is not the case. */
2011 check_special_filename (const char *fname, int for_write)
2013 if (allow_special_filenames
2014 && fname && *fname == '-' && fname[1] == '&' ) {
2018 for (i=0; isdigit (fname[i]); i++ )
2021 return translate_sys2libc_fd_int (atoi (fname), for_write);
2028 /* Open the FILENAME for read and return the filedescriptor. Stop
2029 with an error message in case of problems. "-" denotes stdin and
2030 if special filenames are allowed the given fd is opened instead. */
2032 open_read (const char *filename)
2036 if (filename[0] == '-' && !filename[1])
2039 return 0; /* stdin */
2041 fd = check_special_filename (filename, 0);
2044 fd = open (filename, O_RDONLY | O_BINARY);
2047 log_error (_("can't open `%s': %s\n"), filename, strerror (errno));
2053 /* Same as open_read but return an estream_t. */
2055 open_es_fread (const char *filename)
2060 if (filename[0] == '-' && !filename[1])
2061 fd = fileno (stdin);
2063 fd = check_special_filename (filename, 0);
2066 fp = es_fdopen_nc (fd, "rb");
2069 log_error ("es_fdopen(%d) failed: %s\n", fd, strerror (errno));
2074 fp = es_fopen (filename, "rb");
2077 log_error (_("can't open `%s': %s\n"), filename, strerror (errno));
2084 /* Open FILENAME for fwrite and return the stream. Stop with an error
2085 message in case of problems. "-" denotes stdout and if special
2086 filenames are allowed the given fd is opened instead. Caller must
2087 close the returned stream unless it is stdout. */
2089 open_fwrite (const char *filename)
2094 if (filename[0] == '-' && !filename[1])
2096 set_binary (stdout);
2100 fd = check_special_filename (filename, 1);
2103 fp = fdopen (dup (fd), "wb");
2106 log_error ("fdopen(%d) failed: %s\n", fd, strerror (errno));
2112 fp = fopen (filename, "wb");
2115 log_error (_("can't open `%s': %s\n"), filename, strerror (errno));
2122 /* Open FILENAME for fwrite and return an extended stream. Stop with
2123 an error message in case of problems. "-" denotes stdout and if
2124 special filenames are allowed the given fd is opened instead.
2125 Caller must close the returned stream. */
2127 open_es_fwrite (const char *filename)
2132 if (filename[0] == '-' && !filename[1])
2135 fp = es_fdopen_nc (fileno(stdout), "wb");
2139 fd = check_special_filename (filename, 1);
2142 fp = es_fdopen_nc (fd, "wb");
2145 log_error ("es_fdopen(%d) failed: %s\n", fd, strerror (errno));
2150 fp = es_fopen (filename, "wb");
2153 log_error (_("can't open `%s': %s\n"), filename, strerror (errno));
2161 run_protect_tool (int argc, char **argv)
2163 #ifndef HAVE_W32_SYSTEM
2168 if (!opt.protect_tool_program || !*opt.protect_tool_program)
2169 pgm = gnupg_module_name (GNUPG_MODULE_NAME_PROTECT_TOOL);
2171 pgm = opt.protect_tool_program;
2173 av = xcalloc (argc+2, sizeof *av);
2174 av[0] = strrchr (pgm, '/');
2176 av[0] = xstrdup (pgm);
2177 for (i=1; argc; i++, argc--, argv++)
2181 log_error ("error executing `%s': %s\n", pgm, strerror (errno));
2182 #endif /*HAVE_W32_SYSTEM*/