1 /* gpgsm.c - GnuPG for S/MIME
2 * Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008,
3 * 2010 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"
41 #include "../common/init.h"
48 enum cmd_and_opt_values {
56 aListSecretKeys = 'K',
90 aKeydbClearSomeCertFlags,
100 oDebugNoChainValidation,
101 oDebugIgnoreExpiration,
108 oEnableSpecialFilenames,
118 oPreferSystemDirmngr,
135 oDisableTrustedCertCRLCheck,
136 oEnableTrustedCertCRLCheck,
144 oDisablePolicyChecks,
146 oAutoIssuerKeyRetrieve,
185 oNoCommonCertsImport,
190 static ARGPARSE_OPTS opts[] = {
192 ARGPARSE_group (300, N_("@Commands:\n ")),
194 ARGPARSE_c (aSign, "sign", N_("make a signature")),
195 /*ARGPARSE_c (aClearsign, "clearsign", N_("make a clear text signature") ),*/
196 ARGPARSE_c (aDetachedSign, "detach-sign", N_("make a detached signature")),
197 ARGPARSE_c (aEncr, "encrypt", N_("encrypt data")),
198 /*ARGPARSE_c (aSym, "symmetric", N_("encryption only with symmetric cipher")),*/
199 ARGPARSE_c (aDecrypt, "decrypt", N_("decrypt data (default)")),
200 ARGPARSE_c (aVerify, "verify", N_("verify a signature")),
201 ARGPARSE_c (aListKeys, "list-keys", N_("list keys")),
202 ARGPARSE_c (aListExternalKeys, "list-external-keys",
203 N_("list external keys")),
204 ARGPARSE_c (aListSecretKeys, "list-secret-keys", N_("list secret keys")),
205 ARGPARSE_c (aListChain, "list-chain", N_("list certificate chain")),
206 ARGPARSE_c (aFingerprint, "fingerprint", N_("list keys and fingerprints")),
207 ARGPARSE_c (aKeygen, "gen-key", N_("generate a new key pair")),
208 ARGPARSE_c (aDeleteKey, "delete-keys",
209 N_("remove keys from the public keyring")),
210 /*ARGPARSE_c (aSendKeys, "send-keys", N_("export keys to a key server")),*/
211 /*ARGPARSE_c (aRecvKeys, "recv-keys", N_("import keys from a key server")),*/
212 ARGPARSE_c (aImport, "import", N_("import certificates")),
213 ARGPARSE_c (aExport, "export", N_("export certificates")),
215 /* We use -raw and not -p1 for pkcs#1 secret key export so that it
216 won't accidently be used in case -p12 was intended. */
217 ARGPARSE_c (aExportSecretKeyP12, "export-secret-key-p12", "@"),
218 ARGPARSE_c (aExportSecretKeyP8, "export-secret-key-p8", "@"),
219 ARGPARSE_c (aExportSecretKeyRaw, "export-secret-key-raw", "@"),
221 ARGPARSE_c (aLearnCard, "learn-card", N_("register a smartcard")),
222 ARGPARSE_c (aServer, "server", N_("run in server mode")),
223 ARGPARSE_c (aCallDirmngr, "call-dirmngr",
224 N_("pass a command to the dirmngr")),
225 ARGPARSE_c (aCallProtectTool, "call-protect-tool",
226 N_("invoke gpg-protect-tool")),
227 ARGPARSE_c (aPasswd, "passwd", N_("change a passphrase")),
228 ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"),
229 ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"),
231 ARGPARSE_c (aDumpKeys, "dump-cert", "@"),
232 ARGPARSE_c (aDumpKeys, "dump-keys", "@"),
233 ARGPARSE_c (aDumpChain, "dump-chain", "@"),
234 ARGPARSE_c (aDumpExternalKeys, "dump-external-keys", "@"),
235 ARGPARSE_c (aDumpSecretKeys, "dump-secret-keys", "@"),
236 ARGPARSE_c (aKeydbClearSomeCertFlags, "keydb-clear-some-cert-flags", "@"),
238 ARGPARSE_group (301, N_("@\nOptions:\n ")),
240 ARGPARSE_s_n (oArmor, "armor", N_("create ascii armored output")),
241 ARGPARSE_s_n (oArmor, "armour", "@"),
242 ARGPARSE_s_n (oBase64, "base64", N_("create base-64 encoded output")),
244 ARGPARSE_s_s (oP12Charset, "p12-charset", "@"),
246 ARGPARSE_s_n (oAssumeArmor, "assume-armor",
247 N_("assume input is in PEM format")),
248 ARGPARSE_s_n (oAssumeBase64, "assume-base64",
249 N_("assume input is in base-64 format")),
250 ARGPARSE_s_n (oAssumeBinary, "assume-binary",
251 N_("assume input is in binary format")),
253 ARGPARSE_s_s (oRecipient, "recipient", N_("|USER-ID|encrypt for USER-ID")),
255 ARGPARSE_s_n (oPreferSystemDirmngr,"prefer-system-dirmngr", "@"),
257 ARGPARSE_s_n (oDisableCRLChecks, "disable-crl-checks",
258 N_("never consult a CRL")),
259 ARGPARSE_s_n (oEnableCRLChecks, "enable-crl-checks", "@"),
260 ARGPARSE_s_n (oDisableTrustedCertCRLCheck,
261 "disable-trusted-cert-crl-check", "@"),
262 ARGPARSE_s_n (oEnableTrustedCertCRLCheck,
263 "enable-trusted-cert-crl-check", "@"),
265 ARGPARSE_s_n (oForceCRLRefresh, "force-crl-refresh", "@"),
267 ARGPARSE_s_n (oDisableOCSP, "disable-ocsp", "@"),
268 ARGPARSE_s_n (oEnableOCSP, "enable-ocsp", N_("check validity using OCSP")),
270 ARGPARSE_s_s (oValidationModel, "validation-model", "@"),
272 ARGPARSE_s_i (oIncludeCerts, "include-certs",
273 N_("|N|number of certificates to include") ),
275 ARGPARSE_s_s (oPolicyFile, "policy-file",
276 N_("|FILE|take policy information from FILE")),
278 ARGPARSE_s_n (oDisablePolicyChecks, "disable-policy-checks",
279 N_("do not check certificate policies")),
280 ARGPARSE_s_n (oEnablePolicyChecks, "enable-policy-checks", "@"),
282 ARGPARSE_s_n (oAutoIssuerKeyRetrieve, "auto-issuer-key-retrieve",
283 N_("fetch missing issuer certificates")),
285 ARGPARSE_s_s (oEncryptTo, "encrypt-to", "@"),
286 ARGPARSE_s_n (oNoEncryptTo, "no-encrypt-to", "@"),
288 ARGPARSE_s_s (oUser, "local-user",
289 N_("|USER-ID|use USER-ID to sign or decrypt")),
291 ARGPARSE_s_s (oOutput, "output", N_("|FILE|write output to FILE")),
292 ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
293 ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")),
294 ARGPARSE_s_n (oNoTTY, "no-tty", N_("don't use the terminal at all")),
295 ARGPARSE_s_s (oLogFile, "log-file",
296 N_("|FILE|write a server mode log to FILE")),
297 ARGPARSE_s_n (oNoLogFile, "no-log-file", "@"),
298 ARGPARSE_s_i (oLoggerFD, "logger-fd", "@"),
300 ARGPARSE_s_s (oAuditLog, "audit-log",
301 N_("|FILE|write an audit log to FILE")),
302 ARGPARSE_s_s (oHtmlAuditLog, "html-audit-log", "@"),
303 ARGPARSE_s_n (oDryRun, "dry-run", N_("do not make any changes")),
304 ARGPARSE_s_n (oBatch, "batch", N_("batch mode: never ask")),
305 ARGPARSE_s_n (oAnswerYes, "yes", N_("assume yes on most questions")),
306 ARGPARSE_s_n (oAnswerNo, "no", N_("assume no on most questions")),
308 ARGPARSE_s_s (oKeyring, "keyring",
309 N_("|FILE|add keyring to the list of keyrings")),
311 ARGPARSE_s_s (oDefaultKey, "default-key",
312 N_("|USER-ID|use USER-ID as default secret key")),
315 /* ARGPARSE_s_s (oDefRecipient, "default-recipient", */
316 /* N_("|NAME|use NAME as default recipient")), */
317 /* ARGPARSE_s_n (oDefRecipientSelf, "default-recipient-self", */
318 /* N_("use the default key as default recipient")), */
319 /* ARGPARSE_s_n (oNoDefRecipient, "no-default-recipient", "@"), */
321 ARGPARSE_s_s (oKeyServer, "keyserver",
322 N_("|SPEC|use this keyserver to lookup keys")),
323 ARGPARSE_s_s (oOptions, "options", N_("|FILE|read options from FILE")),
325 ARGPARSE_p_u (oDebug, "debug", "@"),
326 ARGPARSE_s_s (oDebugLevel, "debug-level",
327 N_("|LEVEL|set the debugging level to LEVEL")),
328 ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
329 ARGPARSE_s_n (oDebugNone, "debug-none", "@"),
330 ARGPARSE_s_i (oDebugWait, "debug-wait", "@"),
331 ARGPARSE_s_n (oDebugAllowCoreDump, "debug-allow-core-dump", "@"),
332 ARGPARSE_s_n (oDebugNoChainValidation, "debug-no-chain-validation", "@"),
333 ARGPARSE_s_n (oDebugIgnoreExpiration, "debug-ignore-expiration", "@"),
334 ARGPARSE_s_s (oFixedPassphrase, "fixed-passphrase", "@"),
336 ARGPARSE_s_i (oStatusFD, "status-fd",
337 N_("|FD|write status info to this FD")),
339 ARGPARSE_s_s (oCipherAlgo, "cipher-algo",
340 N_("|NAME|use cipher algorithm NAME")),
341 ARGPARSE_s_s (oDigestAlgo, "digest-algo",
342 N_("|NAME|use message digest algorithm NAME")),
343 ARGPARSE_s_s (oExtraDigestAlgo, "extra-digest-algo", "@"),
346 ARGPARSE_group (302, N_(
347 "@\n(See the man page for a complete listing of all commands and options)\n"
350 ARGPARSE_group (303, N_("@\nExamples:\n\n"
351 " -se -r Bob [file] sign and encrypt for user Bob\n"
352 " --clearsign [file] make a clear text signature\n"
353 " --detach-sign [file] make a detached signature\n"
354 " --list-keys [names] show keys\n"
355 " --fingerprint [names] show fingerprints\n" )),
357 /* Hidden options. */
358 ARGPARSE_s_n (oNoVerbose, "no-verbose", "@"),
359 ARGPARSE_s_n (oEnableSpecialFilenames, "enable-special-filenames", "@"),
360 ARGPARSE_s_n (oNoSecmemWarn, "no-secmem-warning", "@"),
361 ARGPARSE_s_n (oNoArmor, "no-armor", "@"),
362 ARGPARSE_s_n (oNoArmor, "no-armour", "@"),
363 ARGPARSE_s_n (oNoDefKeyring, "no-default-keyring", "@"),
364 ARGPARSE_s_n (oNoGreeting, "no-greeting", "@"),
365 ARGPARSE_s_n (oNoOptions, "no-options", "@"),
366 ARGPARSE_s_s (oHomedir, "homedir", "@"),
367 ARGPARSE_s_s (oAgentProgram, "agent-program", "@"),
368 ARGPARSE_s_s (oDisplay, "display", "@"),
369 ARGPARSE_s_s (oTTYname, "ttyname", "@"),
370 ARGPARSE_s_s (oTTYtype, "ttytype", "@"),
371 ARGPARSE_s_s (oLCctype, "lc-ctype", "@"),
372 ARGPARSE_s_s (oLCmessages, "lc-messages", "@"),
373 ARGPARSE_s_s (oXauthority, "xauthority", "@"),
374 ARGPARSE_s_s (oDirmngrProgram, "dirmngr-program", "@"),
375 ARGPARSE_s_n (oDisableDirmngr, "disable-dirmngr", "@"),
376 ARGPARSE_s_s (oProtectToolProgram, "protect-tool-program", "@"),
377 ARGPARSE_s_s (oFakedSystemTime, "faked-system-time", "@"),
378 ARGPARSE_s_n (oNoBatch, "no-batch", "@"),
379 ARGPARSE_s_n (oWithColons, "with-colons", "@"),
380 ARGPARSE_s_n (oWithKeyData,"with-key-data", "@"),
381 ARGPARSE_s_n (oWithValidation, "with-validation", "@"),
382 ARGPARSE_s_n (oWithMD5Fingerprint, "with-md5-fingerprint", "@"),
383 ARGPARSE_s_n (oWithEphemeralKeys, "with-ephemeral-keys", "@"),
384 ARGPARSE_s_n (oSkipVerify, "skip-verify", "@"),
385 ARGPARSE_s_n (oWithFingerprint, "with-fingerprint", "@"),
386 ARGPARSE_s_n (oWithKeygrip, "with-keygrip", "@"),
387 ARGPARSE_s_n (oWithSecret, "with-secret", "@"),
388 ARGPARSE_s_s (oDisableCipherAlgo, "disable-cipher-algo", "@"),
389 ARGPARSE_s_s (oDisablePubkeyAlgo, "disable-pubkey-algo", "@"),
390 ARGPARSE_s_n (oIgnoreTimeConflict, "ignore-time-conflict", "@"),
391 ARGPARSE_s_n (oNoRandomSeedFile, "no-random-seed-file", "@"),
392 ARGPARSE_s_n (oNoCommonCertsImport, "no-common-certs-import", "@"),
393 ARGPARSE_s_s (oIgnoreCertExtension, "ignore-cert-extension", "@"),
395 /* Command aliases. */
396 ARGPARSE_c (aListKeys, "list-key", "@"),
397 ARGPARSE_c (aListChain, "list-sig", "@"),
398 ARGPARSE_c (aListChain, "list-sigs", "@"),
399 ARGPARSE_c (aListChain, "check-sig", "@"),
400 ARGPARSE_c (aListChain, "check-sigs", "@"),
401 ARGPARSE_c (aDeleteKey, "delete-key", "@"),
409 /* Global variable to keep an error count. */
410 int gpgsm_errors_seen = 0;
412 /* It is possible that we are currentlu running under setuid permissions */
413 static int maybe_setuid = 1;
415 /* Helper to implement --debug-level and --debug*/
416 static const char *debug_level;
417 static unsigned int debug_value;
419 /* Option --enable-special-filenames */
420 static int allow_special_filenames;
422 /* Default value for include-certs. We need an extra macro for
423 gpgconf-list because the variable will be changed by the command
426 It is often cumbersome to locate intermediate certificates, thus by
427 default we include all certificates in the chain. However we leave
428 out the root certificate because that would make it too easy for
429 the recipient to import that root certificate. A root certificate
430 should be installed only after due checks and thus it won't help to
431 send it along with each message. */
432 #define DEFAULT_INCLUDE_CERTS -2 /* Include all certs but root. */
433 static int default_include_certs = DEFAULT_INCLUDE_CERTS;
435 /* Whether the chain mode shall be used for validation. */
436 static int default_validation_model;
438 /* The default cipher algo. */
439 #define DEFAULT_CIPHER_ALGO "3DES" /*des-EDE3-CBC*/
442 static char *build_list (const char *text,
443 const char *(*mapf)(int), int (*chkf)(int));
444 static void set_cmd (enum cmd_and_opt_values *ret_cmd,
445 enum cmd_and_opt_values new_cmd );
447 static void emergency_cleanup (void);
448 static int check_special_filename (const char *fname, int for_write);
449 static int open_read (const char *filename);
450 static estream_t open_es_fread (const char *filename, const char *mode);
451 static estream_t open_es_fwrite (const char *filename);
452 static void run_protect_tool (int argc, char **argv);
455 our_pk_test_algo (int algo)
461 return gcry_pk_test_algo (algo);
468 our_cipher_test_algo (int algo)
472 case GCRY_CIPHER_3DES:
473 case GCRY_CIPHER_AES128:
474 case GCRY_CIPHER_AES192:
475 case GCRY_CIPHER_AES256:
476 case GCRY_CIPHER_SERPENT128:
477 case GCRY_CIPHER_SERPENT192:
478 case GCRY_CIPHER_SERPENT256:
479 case GCRY_CIPHER_SEED:
480 case GCRY_CIPHER_CAMELLIA128:
481 case GCRY_CIPHER_CAMELLIA192:
482 case GCRY_CIPHER_CAMELLIA256:
483 return gcry_cipher_test_algo (algo);
491 our_md_test_algo (int algo)
502 case GCRY_MD_WHIRLPOOL:
503 return gcry_md_test_algo (algo);
511 make_libversion (const char *libname, const char *(*getfnc)(const char*))
518 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
522 result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
523 strcpy (stpcpy (stpcpy (result, libname), " "), s);
529 my_strusage( int level )
531 static char *digests, *pubkeys, *ciphers;
532 static char *ver_gcry, *ver_ksba;
537 case 11: p = "@GPGSM@ (@GNUPG@)";
539 case 13: p = VERSION; break;
540 case 17: p = PRINTABLE_OS_NAME; break;
541 case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
544 case 40: p = _("Usage: @GPGSM@ [options] [files] (-h for help)");
547 p = _("Syntax: @GPGSM@ [options] [files]\n"
548 "Sign, check, encrypt or decrypt using the S/MIME protocol\n"
549 "Default operation depends on the input data\n");
554 ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
559 ver_ksba = make_libversion ("libksba", ksba_check_version);
563 case 31: p = "\nHome: "; break;
564 case 32: p = opt.homedir; break;
565 case 33: p = _("\nSupported algorithms:\n"); break;
568 ciphers = build_list ("Cipher: ", gnupg_cipher_algo_name,
569 our_cipher_test_algo );
574 pubkeys = build_list ("Pubkey: ", gcry_pk_algo_name,
580 digests = build_list("Hash: ", gcry_md_algo_name, our_md_test_algo );
584 default: p = NULL; break;
591 build_list (const char *text, const char * (*mapf)(int), int (*chkf)(int))
594 size_t n=strlen(text)+2;
598 gcry_control (GCRYCTL_DROP_PRIVS); /* drop setuid */
601 for (i=1; i < 400; i++ )
603 n += strlen(mapf(i)) + 2;
604 list = xmalloc (21 + n);
606 for (p=NULL, i=1; i < 400; i++)
611 p = stpcpy (list, text );
613 p = stpcpy (p, ", ");
614 p = stpcpy (p, mapf(i) );
618 p = stpcpy(p, "\n" );
623 /* Set the file pointer into binary mode if required. */
625 set_binary (FILE *fp)
627 #ifdef HAVE_DOSISH_SYSTEM
628 setmode (fileno (fp), O_BINARY);
637 wrong_args (const char *text)
639 fprintf (stderr, _("usage: %s [options] %s\n"), GPGSM_NAME, text);
645 set_opt_session_env (const char *name, const char *value)
649 err = session_env_setenv (opt.session_env, name, value);
651 log_fatal ("error setting session environment: %s\n",
656 /* Setup the debugging. With a DEBUG_LEVEL of NULL only the active
657 debug flags are propagated to the subsystems. With DEBUG_LEVEL
658 set, a specific set of debug flags is set; and individual debugging
659 flags will be added on top. */
663 int numok = (debug_level && digitp (debug_level));
664 int numlvl = numok? atoi (debug_level) : 0;
668 else if (!strcmp (debug_level, "none") || (numok && numlvl < 1))
670 else if (!strcmp (debug_level, "basic") || (numok && numlvl <= 2))
671 opt.debug = DBG_ASSUAN_VALUE;
672 else if (!strcmp (debug_level, "advanced") || (numok && numlvl <= 5))
673 opt.debug = DBG_ASSUAN_VALUE|DBG_X509_VALUE;
674 else if (!strcmp (debug_level, "expert") || (numok && numlvl <= 8))
675 opt.debug = (DBG_ASSUAN_VALUE|DBG_X509_VALUE
676 |DBG_CACHE_VALUE|DBG_CRYPTO_VALUE);
677 else if (!strcmp (debug_level, "guru") || numok)
680 /* Unless the "guru" string has been used we don't want to allow
681 hashing debugging. The rationale is that people tend to
682 select the highest debug value and would then clutter their
683 disk with debug files which may reveal confidential data. */
685 opt.debug &= ~(DBG_HASHING_VALUE);
689 log_error (_("invalid debug-level '%s' given\n"), debug_level);
693 opt.debug |= debug_value;
695 if (opt.debug && !opt.verbose)
700 if (opt.debug & DBG_MPI_VALUE)
701 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
702 if (opt.debug & DBG_CRYPTO_VALUE )
703 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
704 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
707 log_info ("enabled debug flags:%s%s%s%s%s%s%s%s\n",
708 (opt.debug & DBG_X509_VALUE )? " x509":"",
709 (opt.debug & DBG_MPI_VALUE )? " mpi":"",
710 (opt.debug & DBG_CRYPTO_VALUE )? " crypto":"",
711 (opt.debug & DBG_MEMORY_VALUE )? " memory":"",
712 (opt.debug & DBG_CACHE_VALUE )? " cache":"",
713 (opt.debug & DBG_MEMSTAT_VALUE)? " memstat":"",
714 (opt.debug & DBG_HASHING_VALUE)? " hashing":"",
715 (opt.debug & DBG_ASSUAN_VALUE )? " assuan":"" );
721 set_cmd (enum cmd_and_opt_values *ret_cmd, enum cmd_and_opt_values new_cmd)
723 enum cmd_and_opt_values cmd = *ret_cmd;
725 if (!cmd || cmd == new_cmd)
727 else if ( cmd == aSign && new_cmd == aEncr )
729 else if ( cmd == aEncr && new_cmd == aSign )
731 else if ( (cmd == aSign && new_cmd == aClearsign)
732 || (cmd == aClearsign && new_cmd == aSign) )
736 log_error(_("conflicting commands\n"));
744 /* Helper to add recipients to a list. */
746 do_add_recipient (ctrl_t ctrl, const char *name,
747 certlist_t *recplist, int is_encrypt_to, int recp_required)
749 int rc = gpgsm_add_to_certlist (ctrl, name, 0, recplist, is_encrypt_to);
754 log_error ("can't encrypt to '%s': %s\n", name, gpg_strerror (rc));
755 gpgsm_status2 (ctrl, STATUS_INV_RECP,
756 get_inv_recpsgnr_code (rc), name, NULL);
759 log_info (_("NOTE: won't be able to encrypt to '%s': %s\n"),
760 name, gpg_strerror (rc));
766 parse_validation_model (const char *model)
768 int i = gpgsm_parse_validation_model (model);
770 log_error (_("unknown validation model '%s'\n"), model);
772 default_validation_model = i;
776 /* Release the list of SERVERS. As usual it is okay to call this
777 function with SERVERS passed as NULL. */
779 keyserver_list_free (struct keyserver_spec *servers)
783 struct keyserver_spec *tmp = servers->next;
784 xfree (servers->host);
785 xfree (servers->user);
787 memset (servers->pass, 0, strlen (servers->pass));
788 xfree (servers->pass);
789 xfree (servers->base);
795 /* See also dirmngr ldapserver_parse_one(). */
796 struct keyserver_spec *
797 parse_keyserver_line (char *line,
798 const char *filename, unsigned int lineno)
802 struct keyserver_spec *server;
806 /* Parse the colon separated fields. */
807 server = xcalloc (1, sizeof *server);
808 for (fieldno = 1, p = line; p; p = endp, fieldno++ )
810 endp = strchr (p, ':');
818 server->host = xstrdup (p);
821 log_error (_("%s:%u: no hostname given\n"),
829 server->port = atoi (p);
834 server->user = xstrdup (p);
838 if (*p && !server->user)
840 log_error (_("%s:%u: password given without user\n"),
845 server->pass = xstrdup (p);
850 server->base = xstrdup (p);
854 /* (We silently ignore extra fields.) */
861 log_info (_("%s:%u: skipping this line\n"), filename, lineno);
862 keyserver_list_free (server);
870 main ( int argc, char **argv)
877 strlist_t sl, remusr= NULL, locusr=NULL;
878 strlist_t nrings=NULL;
879 int detached_sig = 0;
880 FILE *configfp = NULL;
881 char *configname = NULL;
882 unsigned configlineno;
884 int no_more_options = 0;
885 int default_config =1;
886 int default_keyring = 1;
887 char *logfile = NULL;
888 char *auditlog = NULL;
889 char *htmlauditlog = NULL;
893 int use_random_seed = 1;
894 int no_common_certs_import = 0;
896 const char *forced_digest_algo = NULL;
897 const char *extra_digest_algo = NULL;
898 enum cmd_and_opt_values cmd = 0;
899 struct server_control_s ctrl;
900 certlist_t recplist = NULL;
901 certlist_t signerlist = NULL;
902 int do_not_setup_keys = 0;
903 int recp_required = 0;
904 estream_t auditfp = NULL;
905 estream_t htmlauditfp = NULL;
906 struct assuan_malloc_hooks malloc_hooks;
910 gnupg_reopen_std (GPGSM_NAME);
911 /* trap_unaligned ();*/
912 gnupg_rl_initialize ();
913 set_strusage (my_strusage);
914 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
916 /* Please note that we may running SUID(ROOT), so be very CAREFUL
917 when adding any stuff between here and the call to secmem_init()
918 somewhere after the option parsing */
919 log_set_prefix (GPGSM_NAME, 1);
921 /* Make sure that our subsystems are ready. */
923 init_common_subsystems (&argc, &argv);
925 /* Check that the libraries are suitable. Do it here because the
926 option parse may need services of the library */
927 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
928 log_fatal (_("%s is too old (need %s, have %s)\n"), "libgcrypt",
929 NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
930 if (!ksba_check_version (NEED_KSBA_VERSION) )
931 log_fatal (_("%s is too old (need %s, have %s)\n"), "libksba",
932 NEED_KSBA_VERSION, ksba_check_version (NULL) );
935 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
937 may_coredump = disable_core_dumps ();
939 gnupg_init_signals (0, emergency_cleanup);
941 dotlock_create (NULL, 0); /* Register lockfile cleanup. */
943 opt.session_env = session_env_new ();
944 if (!opt.session_env)
945 log_fatal ("error allocating session environment block: %s\n",
948 /* Note: If you change this default cipher algorithm , please
949 remember to update the Gpgconflist entry as well. */
950 opt.def_cipher_algoid = DEFAULT_CIPHER_ALGO;
952 opt.homedir = default_homedir ();
955 /* First check whether we have a config file on the commandline */
960 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
961 while (arg_parse( &pargs, opts))
963 if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
965 else if (pargs.r_opt == oOptions)
966 { /* yes there is one, so we do not try the default one but
967 read the config file when it is encountered at the
971 else if (pargs.r_opt == oNoOptions)
972 default_config = 0; /* --no-options */
973 else if (pargs.r_opt == oHomedir)
974 opt.homedir = pargs.r.ret_str;
975 else if (pargs.r_opt == aCallProtectTool)
976 break; /* This break makes sure that --version and --help are
977 passed to the protect-tool. */
981 /* Initialize the secure memory. */
982 gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
986 Now we are now working under our real uid
989 ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free );
991 malloc_hooks.malloc = gcry_malloc;
992 malloc_hooks.realloc = gcry_realloc;
993 malloc_hooks.free = gcry_free;
994 assuan_set_malloc_hooks (&malloc_hooks);
995 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
996 setup_libassuan_logging (&opt.debug);
998 keybox_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
1000 /* Setup a default control structure for command line mode */
1001 memset (&ctrl, 0, sizeof ctrl);
1002 gpgsm_init_default_ctrl (&ctrl);
1004 ctrl.status_fd = -1; /* No status output. */
1005 ctrl.autodetect_encoding = 1;
1007 /* Set the default option file */
1008 if (default_config )
1009 configname = make_filename (opt.homedir, GPGSM_NAME EXTSEP_S "conf", NULL);
1010 /* Set the default policy file */
1011 opt.policy_file = make_filename (opt.homedir, "policies.txt", NULL);
1017 pargs.flags = 1; /* do not remove the args */
1022 configfp = fopen (configname, "r");
1028 log_info (_("NOTE: no default option file '%s'\n"), configname);
1032 log_error (_("option file '%s': %s\n"), configname, strerror(errno));
1038 if (parse_debug && configname)
1039 log_info (_("reading options from '%s'\n"), configname);
1043 while (!no_more_options
1044 && optfile_parse (configfp, configname, &configlineno, &pargs, opts))
1046 switch (pargs.r_opt)
1050 set_cmd (&cmd, pargs.r_opt);
1051 do_not_setup_keys = 1;
1057 set_cmd (&cmd, aServer);
1062 set_cmd (&cmd, aCallDirmngr);
1063 do_not_setup_keys = 1;
1066 case aCallProtectTool:
1068 set_cmd (&cmd, aCallProtectTool);
1069 no_more_options = 1; /* Stop parsing. */
1070 do_not_setup_keys = 1;
1074 set_cmd (&cmd, aDeleteKey);
1076 do_not_setup_keys = 1;
1081 set_cmd (&cmd, aSign );
1085 set_cmd (&cmd, aKeygen);
1087 do_not_setup_keys = 1;
1094 case aExportSecretKeyP12:
1095 case aExportSecretKeyP8:
1096 case aExportSecretKeyRaw:
1099 case aDumpExternalKeys:
1100 case aDumpSecretKeys:
1102 case aListExternalKeys:
1103 case aListSecretKeys:
1107 case aKeydbClearSomeCertFlags:
1108 do_not_setup_keys = 1;
1109 set_cmd (&cmd, pargs.r_opt);
1114 set_cmd (&cmd, pargs.r_opt);
1122 set_cmd (&cmd, pargs.r_opt);
1125 /* Output encoding selection. */
1127 ctrl.create_pem = 1;
1130 ctrl.create_pem = 0;
1131 ctrl.create_base64 = 1;
1134 ctrl.create_pem = 0;
1135 ctrl.create_base64 = 0;
1139 opt.p12_charset = pargs.r.ret_str;
1142 /* Input encoding selection. */
1144 ctrl.autodetect_encoding = 0;
1149 ctrl.autodetect_encoding = 0;
1154 ctrl.autodetect_encoding = 0;
1159 case oDisableCRLChecks:
1160 opt.no_crl_check = 1;
1162 case oEnableCRLChecks:
1163 opt.no_crl_check = 0;
1165 case oDisableTrustedCertCRLCheck:
1166 opt.no_trusted_cert_crl_check = 1;
1168 case oEnableTrustedCertCRLCheck:
1169 opt.no_trusted_cert_crl_check = 0;
1171 case oForceCRLRefresh:
1172 opt.force_crl_refresh = 1;
1176 ctrl.use_ocsp = opt.enable_ocsp = 0;
1179 ctrl.use_ocsp = opt.enable_ocsp = 1;
1183 ctrl.include_certs = default_include_certs = pargs.r.ret_int;
1187 xfree (opt.policy_file);
1188 if (*pargs.r.ret_str)
1189 opt.policy_file = xstrdup (pargs.r.ret_str);
1191 opt.policy_file = NULL;
1194 case oDisablePolicyChecks:
1195 opt.no_policy_check = 1;
1197 case oEnablePolicyChecks:
1198 opt.no_policy_check = 0;
1201 case oAutoIssuerKeyRetrieve:
1202 opt.auto_issuer_key_retrieve = 1;
1205 case oOutput: opt.outfile = pargs.r.ret_str; break;
1208 case oQuiet: opt.quiet = 1; break;
1209 case oNoTTY: /* fixme:tty_no_terminal(1);*/ break;
1210 case oDryRun: opt.dry_run = 1; break;
1214 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
1218 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
1221 case oLogFile: logfile = pargs.r.ret_str; break;
1222 case oNoLogFile: logfile = NULL; break;
1224 case oAuditLog: auditlog = pargs.r.ret_str; break;
1225 case oHtmlAuditLog: htmlauditlog = pargs.r.ret_str; break;
1231 case oNoBatch: opt.batch = 0; break;
1233 case oAnswerYes: opt.answer_yes = 1; break;
1234 case oAnswerNo: opt.answer_no = 1; break;
1236 case oKeyring: append_to_strlist (&nrings, pargs.r.ret_str); break;
1238 case oDebug: debug_value |= pargs.r.ret_ulong; break;
1239 case oDebugAll: debug_value = ~0; break;
1240 case oDebugNone: debug_value = 0; break;
1241 case oDebugLevel: debug_level = pargs.r.ret_str; break;
1242 case oDebugWait: debug_wait = pargs.r.ret_int; break;
1243 case oDebugAllowCoreDump:
1244 may_coredump = enable_core_dumps ();
1246 case oDebugNoChainValidation: opt.no_chain_validation = 1; break;
1247 case oDebugIgnoreExpiration: opt.ignore_expiration = 1; break;
1248 case oFixedPassphrase: opt.fixed_passphrase = pargs.r.ret_str; break;
1250 case oStatusFD: ctrl.status_fd = pargs.r.ret_int; break;
1251 case oLoggerFD: log_set_fd (pargs.r.ret_int ); break;
1252 case oWithMD5Fingerprint:
1253 opt.with_md5_fingerprint=1; /*fall thru*/
1254 case oWithFingerprint:
1255 with_fpr=1; /*fall thru*/
1261 opt.with_keygrip = 1;
1265 /* config files may not be nested (silently ignore them) */
1269 configname = xstrdup (pargs.r.ret_str);
1273 case oNoOptions: break; /* no-options */
1274 case oHomedir: opt.homedir = pargs.r.ret_str; break;
1275 case oAgentProgram: opt.agent_program = pargs.r.ret_str; break;
1278 set_opt_session_env ("DISPLAY", pargs.r.ret_str);
1281 set_opt_session_env ("GPG_TTY", pargs.r.ret_str);
1284 set_opt_session_env ("TERM", pargs.r.ret_str);
1287 set_opt_session_env ("XAUTHORITY", pargs.r.ret_str);
1290 case oLCctype: opt.lc_ctype = xstrdup (pargs.r.ret_str); break;
1291 case oLCmessages: opt.lc_messages = xstrdup (pargs.r.ret_str); break;
1293 case oDirmngrProgram: opt.dirmngr_program = pargs.r.ret_str; break;
1294 case oDisableDirmngr: opt.disable_dirmngr = 1; break;
1295 case oPreferSystemDirmngr: /* Obsolete */; break;
1296 case oProtectToolProgram:
1297 opt.protect_tool_program = pargs.r.ret_str;
1300 case oFakedSystemTime:
1302 time_t faked_time = isotime2epoch (pargs.r.ret_str);
1303 if (faked_time == (time_t)(-1))
1304 faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
1305 gnupg_set_time (faked_time, 0);
1309 case oNoDefKeyring: default_keyring = 0; break;
1310 case oNoGreeting: nogreeting = 1; break;
1313 if (*pargs.r.ret_str)
1315 xfree (opt.local_user);
1316 opt.local_user = xstrdup (pargs.r.ret_str);
1320 if (*pargs.r.ret_str)
1321 opt.def_recipient = xstrdup (pargs.r.ret_str);
1323 case oDefRecipientSelf:
1324 xfree (opt.def_recipient);
1325 opt.def_recipient = NULL;
1326 opt.def_recipient_self = 1;
1328 case oNoDefRecipient:
1329 xfree (opt.def_recipient);
1330 opt.def_recipient = NULL;
1331 opt.def_recipient_self = 0;
1334 case oWithKeyData: opt.with_key_data=1; /* fall thru */
1335 case oWithColons: ctrl.with_colons = 1; break;
1336 case oWithSecret: ctrl.with_secret = 1; break;
1337 case oWithValidation: ctrl.with_validation=1; break;
1338 case oWithEphemeralKeys: ctrl.with_ephemeral_keys=1; break;
1340 case oSkipVerify: opt.skip_verify=1; break;
1342 case oNoEncryptTo: opt.no_encrypt_to = 1; break;
1343 case oEncryptTo: /* Store the recipient in the second list */
1344 sl = add_to_strlist (&remusr, pargs.r.ret_str);
1348 case oRecipient: /* store the recipient */
1349 add_to_strlist ( &remusr, pargs.r.ret_str);
1352 case oUser: /* Store the local users, the first one is the default */
1353 if (!opt.local_user)
1354 opt.local_user = xstrdup (pargs.r.ret_str);
1355 add_to_strlist (&locusr, pargs.r.ret_str);
1359 gcry_control (GCRYCTL_DISABLE_SECMEM_WARN);
1363 opt.def_cipher_algoid = pargs.r.ret_str;
1366 case oDisableCipherAlgo:
1368 int algo = gcry_cipher_map_name (pargs.r.ret_str);
1369 gcry_cipher_ctl (NULL, GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
1372 case oDisablePubkeyAlgo:
1374 int algo = gcry_pk_map_name (pargs.r.ret_str);
1375 gcry_pk_ctl (GCRYCTL_DISABLE_ALGO,&algo, sizeof algo );
1380 forced_digest_algo = pargs.r.ret_str;
1383 case oExtraDigestAlgo:
1384 extra_digest_algo = pargs.r.ret_str;
1387 case oIgnoreTimeConflict: opt.ignore_time_conflict = 1; break;
1388 case oNoRandomSeedFile: use_random_seed = 0; break;
1389 case oNoCommonCertsImport: no_common_certs_import = 1; break;
1391 case oEnableSpecialFilenames: allow_special_filenames =1; break;
1393 case oValidationModel: parse_validation_model (pargs.r.ret_str); break;
1397 struct keyserver_spec *keyserver;
1398 keyserver = parse_keyserver_line (pargs.r.ret_str,
1399 configname, configlineno);
1401 log_error (_("could not parse keyserver\n"));
1404 /* FIXME: Keep last next pointer. */
1405 struct keyserver_spec **next_p = &opt.keyserver;
1407 next_p = &(*next_p)->next;
1408 *next_p = keyserver;
1413 case oIgnoreCertExtension:
1414 add_to_strlist (&opt.ignored_cert_extensions, pargs.r.ret_str);
1418 pargs.err = configfp? ARGPARSE_PRINT_WARNING:ARGPARSE_PRINT_ERROR;
1427 /* Keep a copy of the config filename. */
1428 opt.config_filename = configname;
1435 if (!opt.config_filename)
1436 opt.config_filename = make_filename (opt.homedir,
1437 GPGSM_NAME EXTSEP_S "conf",
1440 if (log_get_errorcount(0))
1443 /* Now that we have the options parsed we need to update the default
1444 control structure. */
1445 gpgsm_init_default_ctrl (&ctrl);
1452 es_fprintf (es_stderr, "%s %s; %s\n",
1453 strusage(11), strusage(13), strusage(14) );
1454 es_fprintf (es_stderr, "%s\n", strusage(15) );
1456 # ifdef IS_DEVELOPMENT_VERSION
1459 log_info ("NOTE: THIS IS A DEVELOPMENT VERSION!\n");
1460 log_info ("It is only intended for test purposes and should NOT be\n");
1461 log_info ("used in a production environment or with production keys!\n");
1465 if (may_coredump && !opt.quiet)
1466 log_info (_("WARNING: program may create a core file!\n"));
1468 /* if (opt.qualsig_approval && !opt.quiet) */
1469 /* log_info (_("This software has offically been approved to " */
1470 /* "create and verify\n" */
1471 /* "qualified signatures according to German law.\n")); */
1473 if (logfile && cmd == aServer)
1475 log_set_file (logfile);
1476 log_set_prefix (NULL, 1|2|4);
1479 if (gnupg_faked_time_p ())
1481 gnupg_isotime_t tbuf;
1483 log_info (_("WARNING: running with faked system time: "));
1484 gnupg_get_isotime (tbuf);
1485 dump_isotime (tbuf);
1489 /* Print a warning if an argument looks like an option. */
1490 if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
1494 for (i=0; i < argc; i++)
1495 if (argv[i][0] == '-' && argv[i][1] == '-')
1496 log_info (_("NOTE: '%s' is not considered an option\n"), argv[i]);
1499 /*FIXME if (opt.batch) */
1500 /* tty_batchmode (1); */
1502 gcry_control (GCRYCTL_RESUME_SECMEM_WARN);
1506 /* Although we alwasy use gpgsm_exit, we better install a regualr
1507 exit handler so that at least the secure memory gets wiped
1509 if (atexit (emergency_cleanup))
1511 log_error ("atexit failed\n");
1515 /* Must do this after dropping setuid, because the mapping functions
1516 may try to load an module and we may have disabled an algorithm.
1517 We remap the commonly used algorithms to the OIDs for
1518 convenience. We need to work with the OIDs because they are used
1519 to check whether the encryption mode is actually available. */
1520 if (!strcmp (opt.def_cipher_algoid, "3DES") )
1521 opt.def_cipher_algoid = "1.2.840.113549.3.7";
1522 else if (!strcmp (opt.def_cipher_algoid, "AES")
1523 || !strcmp (opt.def_cipher_algoid, "AES128"))
1524 opt.def_cipher_algoid = "2.16.840.1.101.3.4.1.2";
1525 else if (!strcmp (opt.def_cipher_algoid, "AES256") )
1526 opt.def_cipher_algoid = "2.16.840.1.101.3.4.1.42";
1527 else if (!strcmp (opt.def_cipher_algoid, "SERPENT")
1528 || !strcmp (opt.def_cipher_algoid, "SERPENT128") )
1529 opt.def_cipher_algoid = "1.3.6.1.4.1.11591.13.2.2";
1530 else if (!strcmp (opt.def_cipher_algoid, "SERPENT192") )
1531 opt.def_cipher_algoid = "1.3.6.1.4.1.11591.13.2.22";
1532 else if (!strcmp (opt.def_cipher_algoid, "SERPENT192") )
1533 opt.def_cipher_algoid = "1.3.6.1.4.1.11591.13.2.42";
1534 else if (!strcmp (opt.def_cipher_algoid, "SEED") )
1535 opt.def_cipher_algoid = "1.2.410.200004.1.4";
1536 else if (!strcmp (opt.def_cipher_algoid, "CAMELLIA")
1537 || !strcmp (opt.def_cipher_algoid, "CAMELLIA128") )
1538 opt.def_cipher_algoid = "1.2.392.200011.61.1.1.1.2";
1539 else if (!strcmp (opt.def_cipher_algoid, "CAMELLIA192") )
1540 opt.def_cipher_algoid = "1.2.392.200011.61.1.1.1.3";
1541 else if (!strcmp (opt.def_cipher_algoid, "CAMELLIA256") )
1542 opt.def_cipher_algoid = "1.2.392.200011.61.1.1.1.4";
1544 if (cmd != aGPGConfList)
1546 if ( !gcry_cipher_map_name (opt.def_cipher_algoid)
1547 || !gcry_cipher_mode_from_oid (opt.def_cipher_algoid))
1548 log_error (_("selected cipher algorithm is invalid\n"));
1550 if (forced_digest_algo)
1552 opt.forced_digest_algo = gcry_md_map_name (forced_digest_algo);
1553 if (our_md_test_algo(opt.forced_digest_algo) )
1554 log_error (_("selected digest algorithm is invalid\n"));
1556 if (extra_digest_algo)
1558 opt.extra_digest_algo = gcry_md_map_name (extra_digest_algo);
1559 if (our_md_test_algo (opt.extra_digest_algo) )
1560 log_error (_("selected digest algorithm is invalid\n"));
1564 if (log_get_errorcount(0))
1567 /* Set the random seed file. */
1568 if (use_random_seed)
1570 char *p = make_filename (opt.homedir, "random_seed", NULL);
1571 gcry_control (GCRYCTL_SET_RANDOM_SEED_FILE, p);
1575 if (!cmd && opt.fingerprint && !with_fpr)
1576 set_cmd (&cmd, aListKeys);
1578 /* Add default keybox. */
1579 if (!nrings && default_keyring)
1583 keydb_add_resource ("pubring.kbx", 0, 0, &created);
1584 if (created && !no_common_certs_import)
1586 /* Import the standard certificates for a new default keybox. */
1589 filelist[0] = make_filename (gnupg_datadir (),"com-certs.pem", NULL);
1591 if (!access (filelist[0], F_OK))
1593 log_info (_("importing common certificates '%s'\n"),
1595 gpgsm_import_files (&ctrl, 1, filelist, open_read);
1597 xfree (filelist[0]);
1600 for (sl = nrings; sl; sl = sl->next)
1601 keydb_add_resource (sl->d, 0, 0, NULL);
1602 FREE_STRLIST(nrings);
1605 /* Prepare the audit log feature for certain commands. */
1606 if (auditlog || htmlauditlog)
1614 audit_release (ctrl.audit);
1615 ctrl.audit = audit_new ();
1617 auditfp = open_es_fwrite (auditlog);
1619 htmlauditfp = open_es_fwrite (htmlauditlog);
1627 if (!do_not_setup_keys)
1629 for (sl = locusr; sl ; sl = sl->next)
1631 int rc = gpgsm_add_to_certlist (&ctrl, sl->d, 1, &signerlist, 0);
1634 log_error (_("can't sign using '%s': %s\n"),
1635 sl->d, gpg_strerror (rc));
1636 gpgsm_status2 (&ctrl, STATUS_INV_SGNR,
1637 get_inv_recpsgnr_code (rc), sl->d, NULL);
1638 gpgsm_status2 (&ctrl, STATUS_INV_RECP,
1639 get_inv_recpsgnr_code (rc), sl->d, NULL);
1643 /* Build the recipient list. We first add the regular ones and then
1644 the encrypt-to ones because the underlying function will silently
1645 ignore duplicates and we can't allow to keep a duplicate which is
1646 flagged as encrypt-to as the actually encrypt function would then
1647 complain about no (regular) recipients. */
1648 for (sl = remusr; sl; sl = sl->next)
1649 if (!(sl->flags & 1))
1650 do_add_recipient (&ctrl, sl->d, &recplist, 0, recp_required);
1651 if (!opt.no_encrypt_to)
1653 for (sl = remusr; sl; sl = sl->next)
1654 if ((sl->flags & 1))
1655 do_add_recipient (&ctrl, sl->d, &recplist, 1, recp_required);
1659 if (log_get_errorcount(0))
1660 gpgsm_exit(1); /* Must stop for invalid recipients. */
1662 /* Dispatch command. */
1666 { /* List options and default values in the GPG Conf format. */
1667 char *config_filename_esc = percent_escape (opt.config_filename, NULL);
1669 es_printf ("%s-%s.conf:%lu:\"%s\n",
1670 GPGCONF_NAME, GPGSM_NAME,
1671 GC_OPT_FLAG_DEFAULT, config_filename_esc);
1672 xfree (config_filename_esc);
1674 es_printf ("verbose:%lu:\n", GC_OPT_FLAG_NONE);
1675 es_printf ("quiet:%lu:\n", GC_OPT_FLAG_NONE);
1676 es_printf ("debug-level:%lu:\"none:\n", GC_OPT_FLAG_DEFAULT);
1677 es_printf ("log-file:%lu:\n", GC_OPT_FLAG_NONE);
1678 es_printf ("disable-crl-checks:%lu:\n", GC_OPT_FLAG_NONE);
1679 es_printf ("disable-trusted-cert-crl-check:%lu:\n", GC_OPT_FLAG_NONE);
1680 es_printf ("enable-ocsp:%lu:\n", GC_OPT_FLAG_NONE);
1681 es_printf ("include-certs:%lu:%d:\n", GC_OPT_FLAG_DEFAULT,
1682 DEFAULT_INCLUDE_CERTS);
1683 es_printf ("disable-policy-checks:%lu:\n", GC_OPT_FLAG_NONE);
1684 es_printf ("auto-issuer-key-retrieve:%lu:\n", GC_OPT_FLAG_NONE);
1685 es_printf ("disable-dirmngr:%lu:\n", GC_OPT_FLAG_NONE);
1686 es_printf ("cipher-algo:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT,
1687 DEFAULT_CIPHER_ALGO);
1688 es_printf ("p12-charset:%lu:\n", GC_OPT_FLAG_DEFAULT);
1689 es_printf ("default-key:%lu:\n", GC_OPT_FLAG_DEFAULT);
1690 es_printf ("encrypt-to:%lu:\n", GC_OPT_FLAG_DEFAULT);
1691 es_printf ("keyserver:%lu:\n", GC_OPT_FLAG_NONE);
1693 /* The next one is an info only item and should match what
1694 proc_parameters actually implements. */
1695 es_printf ("default_pubkey_algo:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT,
1701 /* This is merely a dummy command to test whether the
1702 configuration file is valid. */
1708 log_debug ("waiting for debugger - my pid is %u .....\n",
1709 (unsigned int)getpid());
1710 gnupg_sleep (debug_wait);
1711 log_debug ("... okay\n");
1713 gpgsm_server (recplist);
1718 wrong_args ("--call-dirmngr <command> {args}");
1720 if (gpgsm_dirmngr_run_command (&ctrl, *argv, argc-1, argv+1))
1724 case aCallProtectTool:
1725 run_protect_tool (argc, argv);
1728 case aEncr: /* Encrypt the given file. */
1730 estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
1734 if (!argc) /* Source is stdin. */
1735 gpgsm_encrypt (&ctrl, recplist, 0, fp);
1736 else if (argc == 1) /* Source is the given file. */
1737 gpgsm_encrypt (&ctrl, recplist, open_read (*argv), fp);
1739 wrong_args ("--encrypt [datafile]");
1745 case aSign: /* Sign the given file. */
1747 estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
1749 /* Fixme: We should also allow to concatenate multiple files for
1750 signing because that is what gpg does.*/
1752 if (!argc) /* Create from stdin. */
1753 gpgsm_sign (&ctrl, signerlist, 0, detached_sig, fp);
1754 else if (argc == 1) /* From file. */
1755 gpgsm_sign (&ctrl, signerlist,
1756 open_read (*argv), detached_sig, fp);
1758 wrong_args ("--sign [datafile]");
1764 case aSignEncr: /* sign and encrypt the given file */
1765 log_error ("this command has not yet been implemented\n");
1768 case aClearsign: /* make a clearsig */
1769 log_error ("this command has not yet been implemented\n");
1774 estream_t fp = NULL;
1777 if (argc == 2 && opt.outfile)
1778 log_info ("option --output ignored for a detached signature\n");
1779 else if (opt.outfile)
1780 fp = open_es_fwrite (opt.outfile);
1783 gpgsm_verify (&ctrl, 0, -1, fp); /* normal signature from stdin */
1785 gpgsm_verify (&ctrl, open_read (*argv), -1, fp); /* std signature */
1786 else if (argc == 2) /* detached signature (sig, detached) */
1787 gpgsm_verify (&ctrl, open_read (*argv), open_read (argv[1]), NULL);
1789 wrong_args ("--verify [signature [detached_data]]");
1797 estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
1801 gpgsm_decrypt (&ctrl, 0, fp); /* from stdin */
1803 gpgsm_decrypt (&ctrl, open_read (*argv), fp); /* from file */
1805 wrong_args ("--decrypt [filename]");
1812 for (sl=NULL; argc; argc--, argv++)
1813 add_to_strlist (&sl, *argv);
1814 gpgsm_delete (&ctrl, sl);
1820 ctrl.with_chain = 1;
1823 case aListExternalKeys:
1824 case aDumpExternalKeys:
1825 case aListSecretKeys:
1826 case aDumpSecretKeys:
1834 case aListKeys: mode = (0 | 0 | (1<<6)); break;
1836 case aDumpKeys: mode = (256 | 0 | (1<<6)); break;
1837 case aListExternalKeys: mode = (0 | 0 | (1<<7)); break;
1838 case aDumpExternalKeys: mode = (256 | 0 | (1<<7)); break;
1839 case aListSecretKeys: mode = (0 | 2 | (1<<6)); break;
1840 case aDumpSecretKeys: mode = (256 | 2 | (1<<6)); break;
1844 fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
1845 for (sl=NULL; argc; argc--, argv++)
1846 add_to_strlist (&sl, *argv);
1847 gpgsm_list_keys (&ctrl, sl, fp, mode);
1854 case aKeygen: /* Generate a key; well kind of. */
1856 estream_t fpin = NULL;
1861 if (!argc) /* Create from stdin. */
1862 fpin = open_es_fread ("-", "r");
1863 else if (argc == 1) /* From file. */
1864 fpin = open_es_fread (*argv, "r");
1866 wrong_args ("--gen-key --batch [parmfile]");
1869 fpout = open_es_fwrite (opt.outfile?opt.outfile:"-");
1872 gpgsm_genkey (&ctrl, fpin, fpout);
1874 gpgsm_gencertreq_tty (&ctrl, fpout);
1882 gpgsm_import_files (&ctrl, argc, argv, open_read);
1889 fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
1890 for (sl=NULL; argc; argc--, argv++)
1891 add_to_strlist (&sl, *argv);
1892 gpgsm_export (&ctrl, sl, fp);
1898 case aExportSecretKeyP12:
1900 estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
1903 gpgsm_p12_export (&ctrl, *argv, fp, 0);
1905 wrong_args ("--export-secret-key-p12 KEY-ID");
1906 if (fp != es_stdout)
1911 case aExportSecretKeyP8:
1913 estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
1916 gpgsm_p12_export (&ctrl, *argv, fp, 1);
1918 wrong_args ("--export-secret-key-p8 KEY-ID");
1919 if (fp != es_stdout)
1924 case aExportSecretKeyRaw:
1926 estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
1929 gpgsm_p12_export (&ctrl, *argv, fp, 2);
1931 wrong_args ("--export-secret-key-raw KEY-ID");
1932 if (fp != es_stdout)
1939 log_error ("this command has not yet been implemented\n");
1945 wrong_args ("--learn-card");
1948 int rc = gpgsm_agent_learn (&ctrl);
1950 log_error ("error learning card: %s\n", gpg_strerror (rc));
1956 wrong_args ("--passwd <key-Id>");
1960 ksba_cert_t cert = NULL;
1963 rc = gpgsm_find_cert (*argv, NULL, &cert);
1966 else if (!(grip = gpgsm_get_keygrip_hexstring (cert)))
1967 rc = gpg_error (GPG_ERR_BUG);
1970 char *desc = gpgsm_format_keydesc (cert);
1971 rc = gpgsm_agent_passwd (&ctrl, grip, desc);
1975 log_error ("error changing passphrase: %s\n", gpg_strerror (rc));
1977 ksba_cert_release (cert);
1981 case aKeydbClearSomeCertFlags:
1982 for (sl=NULL; argc; argc--, argv++)
1983 add_to_strlist (&sl, *argv);
1984 keydb_clear_some_cert_flags (&ctrl, sl);
1990 log_error (_("invalid command (there is no implicit command)\n"));
1994 /* Print the audit result if needed. */
1995 if ((auditlog && auditfp) || (htmlauditlog && htmlauditfp))
1997 if (auditlog && auditfp)
1998 audit_print_result (ctrl.audit, auditfp, 0);
1999 if (htmlauditlog && htmlauditfp)
2000 audit_print_result (ctrl.audit, htmlauditfp, 1);
2001 audit_release (ctrl.audit);
2003 es_fclose (auditfp);
2004 es_fclose (htmlauditfp);
2008 keyserver_list_free (opt.keyserver);
2009 opt.keyserver = NULL;
2010 gpgsm_release_certlist (recplist);
2011 gpgsm_release_certlist (signerlist);
2012 FREE_STRLIST (remusr);
2013 FREE_STRLIST (locusr);
2015 return 8; /*NOTREACHED*/
2018 /* Note: This function is used by signal handlers!. */
2020 emergency_cleanup (void)
2022 gcry_control (GCRYCTL_TERM_SECMEM );
2029 gcry_control (GCRYCTL_UPDATE_RANDOM_SEED_FILE);
2030 if (opt.debug & DBG_MEMSTAT_VALUE)
2032 gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
2033 gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
2036 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
2037 emergency_cleanup ();
2038 rc = rc? rc : log_get_errorcount(0)? 2 : gpgsm_errors_seen? 1 : 0;
2044 gpgsm_init_default_ctrl (struct server_control_s *ctrl)
2046 ctrl->include_certs = default_include_certs;
2047 ctrl->use_ocsp = opt.enable_ocsp;
2048 ctrl->validation_model = default_validation_model;
2053 gpgsm_parse_validation_model (const char *model)
2055 if (!ascii_strcasecmp (model, "shell") )
2057 else if ( !ascii_strcasecmp (model, "chain") )
2059 else if ( !ascii_strcasecmp (model, "steed") )
2066 /* Check whether the filename has the form "-&nnnn", where n is a
2067 non-zero number. Returns this number or -1 if it is not the case. */
2069 check_special_filename (const char *fname, int for_write)
2071 if (allow_special_filenames
2072 && fname && *fname == '-' && fname[1] == '&' ) {
2076 for (i=0; isdigit (fname[i]); i++ )
2079 return translate_sys2libc_fd_int (atoi (fname), for_write);
2086 /* Open the FILENAME for read and return the file descriptor. Stop
2087 with an error message in case of problems. "-" denotes stdin and
2088 if special filenames are allowed the given fd is opened instead. */
2090 open_read (const char *filename)
2094 if (filename[0] == '-' && !filename[1])
2097 return 0; /* stdin */
2099 fd = check_special_filename (filename, 0);
2102 fd = open (filename, O_RDONLY | O_BINARY);
2105 log_error (_("can't open '%s': %s\n"), filename, strerror (errno));
2111 /* Same as open_read but return an estream_t. */
2113 open_es_fread (const char *filename, const char *mode)
2118 if (filename[0] == '-' && !filename[1])
2119 fd = fileno (stdin);
2121 fd = check_special_filename (filename, 0);
2124 fp = es_fdopen_nc (fd, mode);
2127 log_error ("es_fdopen(%d) failed: %s\n", fd, strerror (errno));
2132 fp = es_fopen (filename, mode);
2135 log_error (_("can't open '%s': %s\n"), filename, strerror (errno));
2142 /* Open FILENAME for fwrite and return an extended stream. Stop with
2143 an error message in case of problems. "-" denotes stdout and if
2144 special filenames are allowed the given fd is opened instead.
2145 Caller must close the returned stream. */
2147 open_es_fwrite (const char *filename)
2152 if (filename[0] == '-' && !filename[1])
2155 fp = es_fdopen_nc (fileno(stdout), "wb");
2159 fd = check_special_filename (filename, 1);
2162 fp = es_fdopen_nc (fd, "wb");
2165 log_error ("es_fdopen(%d) failed: %s\n", fd, strerror (errno));
2170 fp = es_fopen (filename, "wb");
2173 log_error (_("can't open '%s': %s\n"), filename, strerror (errno));
2181 run_protect_tool (int argc, char **argv)
2183 #ifdef HAVE_W32_SYSTEM
2191 if (!opt.protect_tool_program || !*opt.protect_tool_program)
2192 pgm = gnupg_module_name (GNUPG_MODULE_NAME_PROTECT_TOOL);
2194 pgm = opt.protect_tool_program;
2196 av = xcalloc (argc+2, sizeof *av);
2197 av[0] = strrchr (pgm, '/');
2199 av[0] = xstrdup (pgm);
2200 for (i=1; argc; i++, argc--, argv++)
2204 log_error ("error executing '%s': %s\n", pgm, strerror (errno));
2205 #endif /*!HAVE_W32_SYSTEM*/