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)
954 default_config = 0; /* --no-options */
955 else if (pargs.r_opt == oHomedir)
956 opt.homedir = pargs.r.ret_str;
957 else if (pargs.r_opt == aCallProtectTool)
958 break; /* This break makes sure that --version and --help are
959 passed to the protect-tool. */
963 /* Initialize the secure memory. */
964 gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
968 Now we are now working under our real uid
971 ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free );
973 malloc_hooks.malloc = gcry_malloc;
974 malloc_hooks.realloc = gcry_realloc;
975 malloc_hooks.free = gcry_free;
976 assuan_set_malloc_hooks (&malloc_hooks);
977 assuan_set_assuan_log_prefix (log_get_prefix (NULL));
978 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
980 keybox_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
982 /* Setup a default control structure for command line mode */
983 memset (&ctrl, 0, sizeof ctrl);
984 gpgsm_init_default_ctrl (&ctrl);
986 ctrl.status_fd = -1; /* No status output. */
987 ctrl.autodetect_encoding = 1;
989 /* Set the default option file */
991 configname = make_filename (opt.homedir, "gpgsm.conf", NULL);
992 /* Set the default policy file */
993 opt.policy_file = make_filename (opt.homedir, "policies.txt", NULL);
999 pargs.flags = 1; /* do not remove the args */
1004 configfp = fopen (configname, "r");
1010 log_info (_("NOTE: no default option file `%s'\n"), configname);
1014 log_error (_("option file `%s': %s\n"), configname, strerror(errno));
1020 if (parse_debug && configname)
1021 log_info (_("reading options from `%s'\n"), configname);
1025 while (!no_more_options
1026 && optfile_parse (configfp, configname, &configlineno, &pargs, opts))
1028 switch (pargs.r_opt)
1032 set_cmd (&cmd, pargs.r_opt);
1033 do_not_setup_keys = 1;
1039 set_cmd (&cmd, aServer);
1044 set_cmd (&cmd, aCallDirmngr);
1045 do_not_setup_keys = 1;
1048 case aCallProtectTool:
1050 set_cmd (&cmd, aCallProtectTool);
1051 no_more_options = 1; /* Stop parsing. */
1052 do_not_setup_keys = 1;
1056 set_cmd (&cmd, aDeleteKey);
1058 do_not_setup_keys = 1;
1063 set_cmd (&cmd, aSign );
1067 set_cmd (&cmd, aKeygen);
1069 do_not_setup_keys = 1;
1076 case aExportSecretKeyP12:
1079 case aDumpExternalKeys:
1080 case aDumpSecretKeys:
1082 case aListExternalKeys:
1083 case aListSecretKeys:
1087 case aKeydbClearSomeCertFlags:
1088 do_not_setup_keys = 1;
1089 set_cmd (&cmd, pargs.r_opt);
1094 set_cmd (&cmd, pargs.r_opt);
1102 set_cmd (&cmd, pargs.r_opt);
1105 /* Output encoding selection. */
1107 ctrl.create_pem = 1;
1110 ctrl.create_pem = 0;
1111 ctrl.create_base64 = 1;
1114 ctrl.create_pem = 0;
1115 ctrl.create_base64 = 0;
1119 opt.p12_charset = pargs.r.ret_str;
1122 /* Input encoding selection. */
1124 ctrl.autodetect_encoding = 0;
1129 ctrl.autodetect_encoding = 0;
1134 ctrl.autodetect_encoding = 0;
1139 case oDisableCRLChecks:
1140 opt.no_crl_check = 1;
1142 case oEnableCRLChecks:
1143 opt.no_crl_check = 0;
1145 case oDisableTrustedCertCRLCheck:
1146 opt.no_trusted_cert_crl_check = 1;
1148 case oEnableTrustedCertCRLCheck:
1149 opt.no_trusted_cert_crl_check = 0;
1151 case oForceCRLRefresh:
1152 opt.force_crl_refresh = 1;
1156 ctrl.use_ocsp = opt.enable_ocsp = 0;
1159 ctrl.use_ocsp = opt.enable_ocsp = 1;
1163 ctrl.include_certs = default_include_certs = pargs.r.ret_int;
1167 xfree (opt.policy_file);
1168 if (*pargs.r.ret_str)
1169 opt.policy_file = xstrdup (pargs.r.ret_str);
1171 opt.policy_file = NULL;
1174 case oDisablePolicyChecks:
1175 opt.no_policy_check = 1;
1177 case oEnablePolicyChecks:
1178 opt.no_policy_check = 0;
1181 case oAutoIssuerKeyRetrieve:
1182 opt.auto_issuer_key_retrieve = 1;
1185 case oOutput: opt.outfile = pargs.r.ret_str; break;
1188 case oQuiet: opt.quiet = 1; break;
1189 case oNoTTY: /* fixme:tty_no_terminal(1);*/ break;
1190 case oDryRun: opt.dry_run = 1; break;
1194 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
1198 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
1201 case oLogFile: logfile = pargs.r.ret_str; break;
1202 case oNoLogFile: logfile = NULL; break;
1204 case oAuditLog: auditlog = pargs.r.ret_str; break;
1205 case oHtmlAuditLog: htmlauditlog = pargs.r.ret_str; break;
1211 case oNoBatch: opt.batch = 0; break;
1213 case oAnswerYes: opt.answer_yes = 1; break;
1214 case oAnswerNo: opt.answer_no = 1; break;
1216 case oKeyring: append_to_strlist (&nrings, pargs.r.ret_str); break;
1218 case oDebug: debug_value |= pargs.r.ret_ulong; break;
1219 case oDebugAll: debug_value = ~0; break;
1220 case oDebugNone: debug_value = 0; break;
1221 case oDebugLevel: debug_level = pargs.r.ret_str; break;
1222 case oDebugWait: debug_wait = pargs.r.ret_int; break;
1223 case oDebugAllowCoreDump:
1224 may_coredump = enable_core_dumps ();
1226 case oDebugNoChainValidation: opt.no_chain_validation = 1; break;
1227 case oDebugIgnoreExpiration: opt.ignore_expiration = 1; break;
1228 case oFixedPassphrase: opt.fixed_passphrase = pargs.r.ret_str; break;
1230 case oStatusFD: ctrl.status_fd = pargs.r.ret_int; break;
1231 case oLoggerFD: log_set_fd (pargs.r.ret_int ); break;
1232 case oWithMD5Fingerprint:
1233 opt.with_md5_fingerprint=1; /*fall thru*/
1234 case oWithFingerprint:
1235 with_fpr=1; /*fall thru*/
1241 /* config files may not be nested (silently ignore them) */
1245 configname = xstrdup (pargs.r.ret_str);
1249 case oNoOptions: break; /* no-options */
1250 case oHomedir: opt.homedir = pargs.r.ret_str; break;
1251 case oAgentProgram: opt.agent_program = pargs.r.ret_str; break;
1254 set_opt_session_env ("DISPLAY", pargs.r.ret_str);
1257 set_opt_session_env ("GPG_TTY", pargs.r.ret_str);
1260 set_opt_session_env ("TERM", pargs.r.ret_str);
1263 set_opt_session_env ("XAUTHORITY", pargs.r.ret_str);
1266 case oLCctype: opt.lc_ctype = xstrdup (pargs.r.ret_str); break;
1267 case oLCmessages: opt.lc_messages = xstrdup (pargs.r.ret_str); break;
1269 case oDirmngrProgram: opt.dirmngr_program = pargs.r.ret_str; break;
1270 case oDisableDirmngr: opt.disable_dirmngr = 1; break;
1271 case oPreferSystemDirmngr: opt.prefer_system_dirmngr = 1; break;
1272 case oProtectToolProgram:
1273 opt.protect_tool_program = pargs.r.ret_str;
1276 case oFakedSystemTime:
1278 time_t faked_time = isotime2epoch (pargs.r.ret_str);
1279 if (faked_time == (time_t)(-1))
1280 faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
1281 gnupg_set_time (faked_time, 0);
1285 case oNoDefKeyring: default_keyring = 0; break;
1286 case oNoGreeting: nogreeting = 1; break;
1289 if (*pargs.r.ret_str)
1291 xfree (opt.local_user);
1292 opt.local_user = xstrdup (pargs.r.ret_str);
1296 if (*pargs.r.ret_str)
1297 opt.def_recipient = xstrdup (pargs.r.ret_str);
1299 case oDefRecipientSelf:
1300 xfree (opt.def_recipient);
1301 opt.def_recipient = NULL;
1302 opt.def_recipient_self = 1;
1304 case oNoDefRecipient:
1305 xfree (opt.def_recipient);
1306 opt.def_recipient = NULL;
1307 opt.def_recipient_self = 0;
1310 case oWithKeyData: opt.with_key_data=1; /* fall thru */
1311 case oWithColons: ctrl.with_colons = 1; break;
1312 case oWithValidation: ctrl.with_validation=1; break;
1313 case oWithEphemeralKeys: ctrl.with_ephemeral_keys=1; break;
1315 case oSkipVerify: opt.skip_verify=1; break;
1317 case oNoEncryptTo: opt.no_encrypt_to = 1; break;
1318 case oEncryptTo: /* Store the recipient in the second list */
1319 sl = add_to_strlist (&remusr, pargs.r.ret_str);
1323 case oRecipient: /* store the recipient */
1324 add_to_strlist ( &remusr, pargs.r.ret_str);
1327 case oUser: /* Store the local users, the first one is the default */
1328 if (!opt.local_user)
1329 opt.local_user = xstrdup (pargs.r.ret_str);
1330 add_to_strlist (&locusr, pargs.r.ret_str);
1334 gcry_control (GCRYCTL_DISABLE_SECMEM_WARN);
1338 opt.def_cipher_algoid = pargs.r.ret_str;
1341 case oDisableCipherAlgo:
1343 int algo = gcry_cipher_map_name (pargs.r.ret_str);
1344 gcry_cipher_ctl (NULL, GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
1347 case oDisablePubkeyAlgo:
1349 int algo = gcry_pk_map_name (pargs.r.ret_str);
1350 gcry_pk_ctl (GCRYCTL_DISABLE_ALGO,&algo, sizeof algo );
1355 forced_digest_algo = pargs.r.ret_str;
1358 case oExtraDigestAlgo:
1359 extra_digest_algo = pargs.r.ret_str;
1362 case oIgnoreTimeConflict: opt.ignore_time_conflict = 1; break;
1363 case oNoRandomSeedFile: use_random_seed = 0; break;
1364 case oNoCommonCertsImport: no_common_certs_import = 1; break;
1366 case oEnableSpecialFilenames: allow_special_filenames =1; break;
1368 case oValidationModel: parse_validation_model (pargs.r.ret_str); break;
1372 struct keyserver_spec *keyserver;
1373 keyserver = parse_keyserver_line (pargs.r.ret_str,
1374 configname, configlineno);
1376 log_error (_("could not parse keyserver\n"));
1379 /* FIXME: Keep last next pointer. */
1380 struct keyserver_spec **next_p = &opt.keyserver;
1382 next_p = &(*next_p)->next;
1383 *next_p = keyserver;
1388 case oIgnoreCertExtension:
1389 add_to_strlist (&opt.ignored_cert_extensions, pargs.r.ret_str);
1393 pargs.err = configfp? ARGPARSE_PRINT_WARNING:ARGPARSE_PRINT_ERROR;
1402 /* Keep a copy of the config filename. */
1403 opt.config_filename = configname;
1410 if (!opt.config_filename)
1411 opt.config_filename = make_filename (opt.homedir, "gpgsm.conf", NULL);
1413 if (log_get_errorcount(0))
1416 /* Now that we have the options parsed we need to update the default
1417 control structure. */
1418 gpgsm_init_default_ctrl (&ctrl);
1425 fprintf(stderr, "%s %s; %s\n",
1426 strusage(11), strusage(13), strusage(14) );
1427 fprintf(stderr, "%s\n", strusage(15) );
1429 # ifdef IS_DEVELOPMENT_VERSION
1432 log_info ("NOTE: THIS IS A DEVELOPMENT VERSION!\n");
1433 log_info ("It is only intended for test purposes and should NOT be\n");
1434 log_info ("used in a production environment or with production keys!\n");
1438 if (may_coredump && !opt.quiet)
1439 log_info (_("WARNING: program may create a core file!\n"));
1441 /* if (opt.qualsig_approval && !opt.quiet) */
1442 /* log_info (_("This software has offically been approved to " */
1443 /* "create and verify\n" */
1444 /* "qualified signatures according to German law.\n")); */
1446 if (logfile && cmd == aServer)
1448 log_set_file (logfile);
1449 log_set_prefix (NULL, 1|2|4);
1452 if (gnupg_faked_time_p ())
1454 gnupg_isotime_t tbuf;
1456 log_info (_("WARNING: running with faked system time: "));
1457 gnupg_get_isotime (tbuf);
1458 dump_isotime (tbuf);
1462 /*FIXME if (opt.batch) */
1463 /* tty_batchmode (1); */
1465 gcry_control (GCRYCTL_RESUME_SECMEM_WARN);
1469 /* Although we alwasy use gpgsm_exit, we better install a regualr
1470 exit handler so that at least the secure memory gets wiped
1472 if (atexit (emergency_cleanup))
1474 log_error ("atexit failed\n");
1478 /* Must do this after dropping setuid, because the mapping functions
1479 may try to load an module and we may have disabled an algorithm.
1480 We remap the commonly used algorithms to the OIDs for
1481 convenience. We need to work with the OIDs because they are used
1482 to check whether the encryption mode is actually available. */
1483 if (!strcmp (opt.def_cipher_algoid, "3DES") )
1484 opt.def_cipher_algoid = "1.2.840.113549.3.7";
1485 else if (!strcmp (opt.def_cipher_algoid, "AES")
1486 || !strcmp (opt.def_cipher_algoid, "AES128"))
1487 opt.def_cipher_algoid = "2.16.840.1.101.3.4.1.2";
1488 else if (!strcmp (opt.def_cipher_algoid, "AES256") )
1489 opt.def_cipher_algoid = "2.16.840.1.101.3.4.1.42";
1490 else if (!strcmp (opt.def_cipher_algoid, "SERPENT")
1491 || !strcmp (opt.def_cipher_algoid, "SERPENT128") )
1492 opt.def_cipher_algoid = "1.3.6.1.4.1.11591.13.2.2";
1493 else if (!strcmp (opt.def_cipher_algoid, "SERPENT192") )
1494 opt.def_cipher_algoid = "1.3.6.1.4.1.11591.13.2.22";
1495 else if (!strcmp (opt.def_cipher_algoid, "SERPENT192") )
1496 opt.def_cipher_algoid = "1.3.6.1.4.1.11591.13.2.42";
1497 else if (!strcmp (opt.def_cipher_algoid, "SEED") )
1498 opt.def_cipher_algoid = "1.2.410.200004.1.4";
1499 else if (!strcmp (opt.def_cipher_algoid, "CAMELLIA")
1500 || !strcmp (opt.def_cipher_algoid, "CAMELLIA128") )
1501 opt.def_cipher_algoid = "1.2.392.200011.61.1.1.1.2";
1502 else if (!strcmp (opt.def_cipher_algoid, "CAMELLIA192") )
1503 opt.def_cipher_algoid = "1.2.392.200011.61.1.1.1.3";
1504 else if (!strcmp (opt.def_cipher_algoid, "CAMELLIA256") )
1505 opt.def_cipher_algoid = "1.2.392.200011.61.1.1.1.4";
1507 if (cmd != aGPGConfList)
1509 if ( !gcry_cipher_map_name (opt.def_cipher_algoid)
1510 || !gcry_cipher_mode_from_oid (opt.def_cipher_algoid))
1511 log_error (_("selected cipher algorithm is invalid\n"));
1513 if (forced_digest_algo)
1515 opt.forced_digest_algo = gcry_md_map_name (forced_digest_algo);
1516 if (our_md_test_algo(opt.forced_digest_algo) )
1517 log_error (_("selected digest algorithm is invalid\n"));
1519 if (extra_digest_algo)
1521 opt.extra_digest_algo = gcry_md_map_name (extra_digest_algo);
1522 if (our_md_test_algo (opt.extra_digest_algo) )
1523 log_error (_("selected digest algorithm is invalid\n"));
1527 if (log_get_errorcount(0))
1530 /* Set the random seed file. */
1531 if (use_random_seed)
1533 char *p = make_filename (opt.homedir, "random_seed", NULL);
1534 gcry_control (GCRYCTL_SET_RANDOM_SEED_FILE, p);
1538 if (!cmd && opt.fingerprint && !with_fpr)
1539 set_cmd (&cmd, aListKeys);
1541 /* Add default keybox. */
1542 if (!nrings && default_keyring)
1546 keydb_add_resource ("pubring.kbx", 0, 0, &created);
1547 if (created && !no_common_certs_import)
1549 /* Import the standard certificates for a new default keybox. */
1552 filelist[0] = make_filename (gnupg_datadir (),"com-certs.pem", NULL);
1554 if (!access (filelist[0], F_OK))
1556 log_info (_("importing common certificates `%s'\n"),
1558 gpgsm_import_files (&ctrl, 1, filelist, open_read);
1560 xfree (filelist[0]);
1563 for (sl = nrings; sl; sl = sl->next)
1564 keydb_add_resource (sl->d, 0, 0, NULL);
1565 FREE_STRLIST(nrings);
1568 /* Prepare the audit log feature for certain commands. */
1569 if (auditlog || htmlauditlog)
1577 audit_release (ctrl.audit);
1578 ctrl.audit = audit_new ();
1580 auditfp = open_es_fwrite (auditlog);
1582 htmlauditfp = open_es_fwrite (htmlauditlog);
1590 if (!do_not_setup_keys)
1592 for (sl = locusr; sl ; sl = sl->next)
1594 int rc = gpgsm_add_to_certlist (&ctrl, sl->d, 1, &signerlist, 0);
1597 log_error (_("can't sign using `%s': %s\n"),
1598 sl->d, gpg_strerror (rc));
1599 gpgsm_status2 (&ctrl, STATUS_INV_SGNR,
1600 get_inv_recpsgnr_code (rc), sl->d, NULL);
1601 gpgsm_status2 (&ctrl, STATUS_INV_RECP,
1602 get_inv_recpsgnr_code (rc), sl->d, NULL);
1606 /* Build the recipient list. We first add the regular ones and then
1607 the encrypt-to ones because the underlying function will silently
1608 ignore duplicates and we can't allow to keep a duplicate which is
1609 flagged as encrypt-to as the actually encrypt function would then
1610 complain about no (regular) recipients. */
1611 for (sl = remusr; sl; sl = sl->next)
1612 if (!(sl->flags & 1))
1613 do_add_recipient (&ctrl, sl->d, &recplist, 0, recp_required);
1614 if (!opt.no_encrypt_to)
1616 for (sl = remusr; sl; sl = sl->next)
1617 if ((sl->flags & 1))
1618 do_add_recipient (&ctrl, sl->d, &recplist, 1, recp_required);
1622 if (log_get_errorcount(0))
1623 gpgsm_exit(1); /* Must stop for invalid recipients. */
1625 /* Dispatch command. */
1629 { /* List options and default values in the GPG Conf format. */
1630 char *config_filename_esc = percent_escape (opt.config_filename, NULL);
1632 printf ("gpgconf-gpgsm.conf:%lu:\"%s\n",
1633 GC_OPT_FLAG_DEFAULT, config_filename_esc);
1634 xfree (config_filename_esc);
1636 printf ("verbose:%lu:\n", GC_OPT_FLAG_NONE);
1637 printf ("quiet:%lu:\n", GC_OPT_FLAG_NONE);
1638 printf ("debug-level:%lu:\"none:\n", GC_OPT_FLAG_DEFAULT);
1639 printf ("log-file:%lu:\n", GC_OPT_FLAG_NONE);
1640 printf ("disable-crl-checks:%lu:\n", GC_OPT_FLAG_NONE);
1641 printf ("disable-trusted-cert-crl-check:%lu:\n", GC_OPT_FLAG_NONE);
1642 printf ("enable-ocsp:%lu:\n", GC_OPT_FLAG_NONE);
1643 printf ("include-certs:%lu:%d:\n", GC_OPT_FLAG_DEFAULT,
1644 DEFAULT_INCLUDE_CERTS);
1645 printf ("disable-policy-checks:%lu:\n", GC_OPT_FLAG_NONE);
1646 printf ("auto-issuer-key-retrieve:%lu:\n", GC_OPT_FLAG_NONE);
1647 printf ("disable-dirmngr:%lu:\n", GC_OPT_FLAG_NONE);
1648 #ifndef HAVE_W32_SYSTEM
1649 printf ("prefer-system-dirmngr:%lu:\n", GC_OPT_FLAG_NONE);
1651 printf ("cipher-algo:%lu:\"3DES:\n", GC_OPT_FLAG_DEFAULT);
1652 printf ("p12-charset:%lu:\n", GC_OPT_FLAG_DEFAULT);
1653 printf ("default-key:%lu:\n", GC_OPT_FLAG_DEFAULT);
1654 printf ("encrypt-to:%lu:\n", GC_OPT_FLAG_DEFAULT);
1655 printf ("keyserver:%lu:\n", GC_OPT_FLAG_NONE);
1657 /* The next one is an info only item and should match what
1658 proc_parameters actually implements. */
1659 printf ("default_pubkey_algo:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT,
1664 /* This is merely a dummy command to test whether the
1665 configuration file is valid. */
1671 log_debug ("waiting for debugger - my pid is %u .....\n",
1672 (unsigned int)getpid());
1673 gnupg_sleep (debug_wait);
1674 log_debug ("... okay\n");
1676 gpgsm_server (recplist);
1681 wrong_args ("--call-dirmngr <command> {args}");
1683 if (gpgsm_dirmngr_run_command (&ctrl, *argv, argc-1, argv+1))
1687 case aCallProtectTool:
1688 run_protect_tool (argc, argv);
1691 case aEncr: /* Encrypt the given file. */
1693 FILE *fp = open_fwrite (opt.outfile?opt.outfile:"-");
1697 if (!argc) /* Source is stdin. */
1698 gpgsm_encrypt (&ctrl, recplist, 0, fp);
1699 else if (argc == 1) /* Source is the given file. */
1700 gpgsm_encrypt (&ctrl, recplist, open_read (*argv), fp);
1702 wrong_args ("--encrypt [datafile]");
1709 case aSign: /* Sign the given file. */
1711 FILE *fp = open_fwrite (opt.outfile?opt.outfile:"-");
1713 /* Fixme: We should also allow to concatenate multiple files for
1714 signing because that is what gpg does.*/
1716 if (!argc) /* Create from stdin. */
1717 gpgsm_sign (&ctrl, signerlist, 0, detached_sig, fp);
1718 else if (argc == 1) /* From file. */
1719 gpgsm_sign (&ctrl, signerlist,
1720 open_read (*argv), detached_sig, fp);
1722 wrong_args ("--sign [datafile]");
1729 case aSignEncr: /* sign and encrypt the given file */
1730 log_error ("this command has not yet been implemented\n");
1733 case aClearsign: /* make a clearsig */
1734 log_error ("this command has not yet been implemented\n");
1742 if (argc == 2 && opt.outfile)
1743 log_info ("option --output ignored for a detached signature\n");
1744 else if (opt.outfile)
1745 fp = open_fwrite (opt.outfile);
1748 gpgsm_verify (&ctrl, 0, -1, fp); /* normal signature from stdin */
1750 gpgsm_verify (&ctrl, open_read (*argv), -1, fp); /* std signature */
1751 else if (argc == 2) /* detached signature (sig, detached) */
1752 gpgsm_verify (&ctrl, open_read (*argv), open_read (argv[1]), NULL);
1754 wrong_args ("--verify [signature [detached_data]]");
1756 if (fp && fp != stdout)
1763 FILE *fp = open_fwrite (opt.outfile?opt.outfile:"-");
1767 gpgsm_decrypt (&ctrl, 0, fp); /* from stdin */
1769 gpgsm_decrypt (&ctrl, open_read (*argv), fp); /* from file */
1771 wrong_args ("--decrypt [filename]");
1778 for (sl=NULL; argc; argc--, argv++)
1779 add_to_strlist (&sl, *argv);
1780 gpgsm_delete (&ctrl, sl);
1786 ctrl.with_chain = 1;
1789 case aListExternalKeys:
1790 case aDumpExternalKeys:
1791 case aListSecretKeys:
1792 case aDumpSecretKeys:
1800 case aListKeys: mode = (0 | 0 | (1<<6)); break;
1802 case aDumpKeys: mode = (256 | 0 | (1<<6)); break;
1803 case aListExternalKeys: mode = (0 | 0 | (1<<7)); break;
1804 case aDumpExternalKeys: mode = (256 | 0 | (1<<7)); break;
1805 case aListSecretKeys: mode = (0 | 2 | (1<<6)); break;
1806 case aDumpSecretKeys: mode = (256 | 2 | (1<<6)); break;
1810 fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
1811 for (sl=NULL; argc; argc--, argv++)
1812 add_to_strlist (&sl, *argv);
1813 gpgsm_list_keys (&ctrl, sl, fp, mode);
1820 case aKeygen: /* Generate a key; well kind of. */
1822 estream_t fpin = NULL;
1827 if (!argc) /* Create from stdin. */
1828 fpin = open_es_fread ("-");
1829 else if (argc == 1) /* From file. */
1830 fpin = open_es_fread (*argv);
1832 wrong_args ("--gen-key --batch [parmfile]");
1835 fpout = open_fwrite (opt.outfile?opt.outfile:"-");
1838 gpgsm_genkey (&ctrl, fpin, fpout);
1840 gpgsm_gencertreq_tty (&ctrl, fpout);
1842 if (fpout != stdout)
1849 gpgsm_import_files (&ctrl, argc, argv, open_read);
1854 FILE *fp = open_fwrite (opt.outfile?opt.outfile:"-");
1856 for (sl=NULL; argc; argc--, argv++)
1857 add_to_strlist (&sl, *argv);
1858 gpgsm_export (&ctrl, sl, fp, NULL);
1865 case aExportSecretKeyP12:
1867 FILE *fp = open_fwrite (opt.outfile?opt.outfile:"-");
1870 gpgsm_p12_export (&ctrl, *argv, fp);
1872 wrong_args ("--export-secret-key-p12 KEY-ID");
1880 log_error ("this command has not yet been implemented\n");
1886 wrong_args ("--learn-card");
1889 int rc = gpgsm_agent_learn (&ctrl);
1891 log_error ("error learning card: %s\n", gpg_strerror (rc));
1897 wrong_args ("--passwd <key-Id>");
1901 ksba_cert_t cert = NULL;
1904 rc = gpgsm_find_cert (*argv, NULL, &cert);
1907 else if (!(grip = gpgsm_get_keygrip_hexstring (cert)))
1908 rc = gpg_error (GPG_ERR_BUG);
1911 char *desc = gpgsm_format_keydesc (cert);
1912 rc = gpgsm_agent_passwd (&ctrl, grip, desc);
1916 log_error ("error changing passphrase: %s\n", gpg_strerror (rc));
1918 ksba_cert_release (cert);
1922 case aKeydbClearSomeCertFlags:
1923 for (sl=NULL; argc; argc--, argv++)
1924 add_to_strlist (&sl, *argv);
1925 keydb_clear_some_cert_flags (&ctrl, sl);
1931 log_error (_("invalid command (there is no implicit command)\n"));
1935 /* Print the audit result if needed. */
1936 if ((auditlog && auditfp) || (htmlauditlog && htmlauditfp))
1938 if (auditlog && auditfp)
1939 audit_print_result (ctrl.audit, auditfp, 0);
1940 if (htmlauditlog && htmlauditfp)
1941 audit_print_result (ctrl.audit, htmlauditfp, 1);
1942 audit_release (ctrl.audit);
1944 es_fclose (auditfp);
1945 es_fclose (htmlauditfp);
1949 keyserver_list_free (opt.keyserver);
1950 opt.keyserver = NULL;
1951 gpgsm_release_certlist (recplist);
1952 gpgsm_release_certlist (signerlist);
1953 FREE_STRLIST (remusr);
1954 FREE_STRLIST (locusr);
1956 return 8; /*NOTREACHED*/
1959 /* Note: This function is used by signal handlers!. */
1961 emergency_cleanup (void)
1963 gcry_control (GCRYCTL_TERM_SECMEM );
1970 gcry_control (GCRYCTL_UPDATE_RANDOM_SEED_FILE);
1971 if (opt.debug & DBG_MEMSTAT_VALUE)
1973 gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
1974 gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
1977 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
1978 emergency_cleanup ();
1979 rc = rc? rc : log_get_errorcount(0)? 2 : gpgsm_errors_seen? 1 : 0;
1985 gpgsm_init_default_ctrl (struct server_control_s *ctrl)
1987 ctrl->include_certs = default_include_certs;
1988 ctrl->use_ocsp = opt.enable_ocsp;
1989 ctrl->validation_model = default_validation_model;
1994 gpgsm_parse_validation_model (const char *model)
1996 if (!ascii_strcasecmp (model, "shell") )
1998 else if ( !ascii_strcasecmp (model, "chain") )
2005 /* Check whether the filename has the form "-&nnnn", where n is a
2006 non-zero number. Returns this number or -1 if it is not the case. */
2008 check_special_filename (const char *fname, int for_write)
2010 if (allow_special_filenames
2011 && fname && *fname == '-' && fname[1] == '&' ) {
2015 for (i=0; isdigit (fname[i]); i++ )
2018 return translate_sys2libc_fd_int (atoi (fname), for_write);
2025 /* Open the FILENAME for read and return the filedescriptor. Stop
2026 with an error message in case of problems. "-" denotes stdin and
2027 if special filenames are allowed the given fd is opened instead. */
2029 open_read (const char *filename)
2033 if (filename[0] == '-' && !filename[1])
2036 return 0; /* stdin */
2038 fd = check_special_filename (filename, 0);
2041 fd = open (filename, O_RDONLY | O_BINARY);
2044 log_error (_("can't open `%s': %s\n"), filename, strerror (errno));
2050 /* Same as open_read but return an estream_t. */
2052 open_es_fread (const char *filename)
2057 if (filename[0] == '-' && !filename[1])
2058 fd = fileno (stdin);
2060 fd = check_special_filename (filename, 0);
2063 fp = es_fdopen_nc (fd, "rb");
2066 log_error ("es_fdopen(%d) failed: %s\n", fd, strerror (errno));
2071 fp = es_fopen (filename, "rb");
2074 log_error (_("can't open `%s': %s\n"), filename, strerror (errno));
2081 /* Open FILENAME for fwrite and return the stream. Stop with an error
2082 message in case of problems. "-" denotes stdout and if special
2083 filenames are allowed the given fd is opened instead. Caller must
2084 close the returned stream unless it is stdout. */
2086 open_fwrite (const char *filename)
2091 if (filename[0] == '-' && !filename[1])
2093 set_binary (stdout);
2097 fd = check_special_filename (filename, 1);
2100 fp = fdopen (dup (fd), "wb");
2103 log_error ("fdopen(%d) failed: %s\n", fd, strerror (errno));
2109 fp = fopen (filename, "wb");
2112 log_error (_("can't open `%s': %s\n"), filename, strerror (errno));
2119 /* Open FILENAME for fwrite and return an extended stream. Stop with
2120 an error message in case of problems. "-" denotes stdout and if
2121 special filenames are allowed the given fd is opened instead.
2122 Caller must close the returned stream. */
2124 open_es_fwrite (const char *filename)
2129 if (filename[0] == '-' && !filename[1])
2132 fp = es_fdopen_nc (fileno(stdout), "wb");
2136 fd = check_special_filename (filename, 1);
2139 fp = es_fdopen_nc (fd, "wb");
2142 log_error ("es_fdopen(%d) failed: %s\n", fd, strerror (errno));
2147 fp = es_fopen (filename, "wb");
2150 log_error (_("can't open `%s': %s\n"), filename, strerror (errno));
2158 run_protect_tool (int argc, char **argv)
2160 #ifndef HAVE_W32_SYSTEM
2165 if (!opt.protect_tool_program || !*opt.protect_tool_program)
2166 pgm = gnupg_module_name (GNUPG_MODULE_NAME_PROTECT_TOOL);
2168 pgm = opt.protect_tool_program;
2170 av = xcalloc (argc+2, sizeof *av);
2171 av[0] = strrchr (pgm, '/');
2173 av[0] = xstrdup (pgm);
2174 for (i=1; argc; i++, argc--, argv++)
2178 log_error ("error executing `%s': %s\n", pgm, strerror (errno));
2179 #endif /*HAVE_W32_SYSTEM*/