1
/* gpgsm.c - GnuPG for S/MIME
2
* Copyright (C) 2001, 2002, 2003, 2004 Free Software Foundation, Inc.
4
* This file is part of GnuPG.
6
* GnuPG is free software; you can redistribute it and/or modify
7
* it under the terms of the GNU General Public License as published by
8
* the Free Software Foundation; either version 2 of the License, or
9
* (at your option) any later version.
11
* GnuPG is distributed in the hope that it will be useful,
12
* but WITHOUT ANY WARRANTY; without even the implied warranty of
13
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
* GNU General Public License for more details.
16
* You should have received a copy of the GNU General Public License
17
* along with this program; if not, write to the Free Software
18
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
35
#include <assuan.h> /* malloc hooks */
37
#include "../kbx/keybox.h" /* malloc hooks */
47
enum cmd_and_opt_values {
56
aListSecretKeys = 'K',
96
aKeydbClearSomeCertFlags,
104
oDebugNoChainValidation,
105
oDebugIgnoreExpiration,
109
oEnableSpecialFilenames,
118
oPreferSystemDirmngr,
140
oDisablePolicyChecks,
142
oAutoIssuerKeyRetrieve,
191
oUseEmbeddedFilename,
214
oAllowNonSelfsignedUID,
233
static ARGPARSE_OPTS opts[] = {
235
{ 300, NULL, 0, N_("@Commands:\n ") },
237
{ aSign, "sign", 256, N_("|[FILE]|make a signature")},
238
{ aClearsign, "clearsign", 256, N_("|[FILE]|make a clear text signature") },
239
{ aDetachedSign, "detach-sign", 256, N_("make a detached signature")},
240
{ aEncr, "encrypt", 256, N_("encrypt data")},
241
{ aSym, "symmetric", 256, N_("encryption only with symmetric cipher")},
242
{ aDecrypt, "decrypt", 256, N_("decrypt data (default)")},
243
{ aVerify, "verify" , 256, N_("verify a signature")},
244
{ aVerifyFiles, "verify-files" , 256, "@" },
245
{ aListKeys, "list-keys", 256, N_("list keys")},
246
{ aListExternalKeys, "list-external-keys", 256, N_("list external keys")},
247
{ aListSecretKeys, "list-secret-keys", 256, N_("list secret keys")},
248
{ aListSigs, "list-sigs", 256, N_("list certificate chain")},
249
{ aListSigs, "check-sigs",256, "@"},
250
{ oFingerprint, "fingerprint", 256, N_("list keys and fingerprints")},
251
{ aKeygen, "gen-key", 256, N_("generate a new key pair")},
252
{ aDeleteKey, "delete-key",256, N_("remove key from the public keyring")},
253
{ aSendKeys, "send-keys" , 256, N_("export keys to a key server") },
254
{ aRecvKeys, "recv-keys" , 256, N_("import keys from a key server") },
255
{ aImport, "import", 256 , N_("import certificates")},
256
{ aExport, "export", 256 , N_("export certificates")},
257
{ aLearnCard, "learn-card", 256 ,N_("register a smartcard")},
258
{ aServer, "server", 256, N_("run in server mode")},
259
{ aCallDirmngr, "call-dirmngr", 256, N_("pass a command to the dirmngr")},
260
{ aCallProtectTool, "call-protect-tool", 256,
261
N_("invoke gpg-protect-tool")},
262
{ aPasswd, "passwd", 256, N_("change a passphrase")},
263
{ aGPGConfList, "gpgconf-list", 256, "@" },
265
{ aDumpKeys, "dump-keys", 256, "@"},
266
{ aDumpExternalKeys, "dump-external-keys", 256, "@"},
267
{ aDumpSecretKeys, "dump-secret-keys", 256, "@"},
268
{ aKeydbClearSomeCertFlags, "keydb-clear-some-cert-flags", 256, "@"},
270
{ 301, NULL, 0, N_("@\nOptions:\n ") },
272
{ oArmor, "armor", 0, N_("create ascii armored output")},
273
{ oArmor, "armour", 0, "@" },
274
{ oBase64, "base64", 0, N_("create base-64 encoded output")},
276
{ oAssumeArmor, "assume-armor", 0, N_("assume input is in PEM format")},
277
{ oAssumeBase64, "assume-base64", 0,
278
N_("assume input is in base-64 format")},
279
{ oAssumeBinary, "assume-binary", 0,
280
N_("assume input is in binary format")},
282
{ oRecipient, "recipient", 2, N_("|NAME|encrypt for NAME")},
284
{ oPreferSystemDirmngr,"prefer-system-dirmngr", 0,
285
N_("use system's dirmngr if available")},
286
{ oDisableCRLChecks, "disable-crl-checks", 0, N_("never consult a CRL")},
287
{ oEnableCRLChecks, "enable-crl-checks", 0, "@"},
288
{ oForceCRLRefresh, "force-crl-refresh", 0, "@"},
290
{ oDisableOCSP, "disable-ocsp", 0, "@" },
291
{ oEnableOCSP, "enable-ocsp", 0, N_("check validity using OCSP")},
293
{ oIncludeCerts, "include-certs", 1,
294
N_("|N|number of certificates to include") },
296
{ oPolicyFile, "policy-file", 2,
297
N_("|FILE|take policy information from FILE") },
299
{ oDisablePolicyChecks, "disable-policy-checks", 0,
300
N_("do not check certificate policies")},
301
{ oEnablePolicyChecks, "enable-policy-checks", 0, "@"},
303
{ oAutoIssuerKeyRetrieve, "auto-issuer-key-retrieve", 0,
304
N_("fetch missing issuer certificates")},
307
{ oDefRecipient, "default-recipient" ,2,
308
N_("|NAME|use NAME as default recipient")},
309
{ oDefRecipientSelf, "default-recipient-self" ,0,
310
N_("use the default key as default recipient")},
311
{ oNoDefRecipient, "no-default-recipient", 0, "@" },
313
{ oEncryptTo, "encrypt-to", 2, "@" },
314
{ oNoEncryptTo, "no-encrypt-to", 0, "@" },
316
{ oUser, "local-user",2, N_("use this user-id to sign or decrypt")},
319
{ oCompress, NULL, 1, N_("|N|set compress level N (0 disables)") },
320
{ oTextmodeShort, NULL, 0, "@"},
321
{ oTextmode, "textmode", 0, N_("use canonical text mode")},
324
{ oOutput, "output", 2, N_("use as output file")},
325
{ oVerbose, "verbose", 0, N_("verbose") },
326
{ oQuiet, "quiet", 0, N_("be somewhat more quiet") },
327
{ oNoTTY, "no-tty", 0, N_("don't use the terminal at all") },
328
{ oLogFile, "log-file" ,2, N_("use a log file for the server")},
330
{ oForceV3Sigs, "force-v3-sigs", 0, N_("force v3 signatures") },
331
{ oForceMDC, "force-mdc", 0, N_("always use a MDC for encryption") },
333
{ oDryRun, "dry-run", 0, N_("do not make any changes") },
334
/*{ oInteractive, "interactive", 0, N_("prompt before overwriting") }, */
335
/*{ oUseAgent, "use-agent",0, N_("use the gpg-agent")},*/
336
{ oBatch, "batch", 0, N_("batch mode: never ask")},
337
{ oAnswerYes, "yes", 0, N_("assume yes on most questions")},
338
{ oAnswerNo, "no", 0, N_("assume no on most questions")},
340
{ oKeyring, "keyring" ,2, N_("add this keyring to the list of keyrings")},
341
{ oSecretKeyring, "secret-keyring" ,2, N_("add this secret keyring to the list")},
342
{ oDefaultKey, "default-key" ,2, N_("|NAME|use NAME as default secret key")},
343
{ oKeyServer, "keyserver",2, N_("|HOST|use this keyserver to lookup keys")},
344
{ oCharset, "charset" , 2, N_("|NAME|set terminal charset to NAME") },
345
{ oOptions, "options" , 2, N_("read options from file")},
347
{ oDebug, "debug" ,4|16, "@"},
348
{ oDebugLevel, "debug-level" ,2, N_("|LEVEL|set the debugging level to LEVEL")},
349
{ oDebugAll, "debug-all" ,0, "@"},
350
{ oDebugWait, "debug-wait" ,1, "@"},
351
{ oDebugAllowCoreDump, "debug-allow-core-dump", 0, "@" },
352
{ oDebugNoChainValidation, "debug-no-chain-validation", 0, "@"},
353
{ oDebugIgnoreExpiration, "debug-ignore-expiration", 0, "@"},
354
{ oFixedPassphrase, "fixed-passphrase", 2, "@"},
355
{ oStatusFD, "status-fd" ,1, N_("|FD|write status info to this FD") },
356
{ aDummy, "no-comment", 0, "@"},
357
{ aDummy, "completes-needed", 1, "@"},
358
{ aDummy, "marginals-needed", 1, "@"},
359
{ oMaxCertDepth, "max-cert-depth", 1, "@" },
360
{ aDummy, "trusted-key", 2, "@"},
361
{ oLoadExtension, "load-extension" ,2,
362
N_("|FILE|load extension module FILE")},
363
{ aDummy, "rfc1991", 0, "@"},
364
{ aDummy, "openpgp", 0, "@"},
365
{ aDummy, "s2k-mode", 1, "@"},
366
{ aDummy, "s2k-digest-algo",2, "@"},
367
{ aDummy, "s2k-cipher-algo",2, "@"},
368
{ oCipherAlgo, "cipher-algo", 2 , N_("|NAME|use cipher algorithm NAME")},
369
{ oDigestAlgo, "digest-algo", 2 ,
370
N_("|NAME|use message digest algorithm NAME")},
372
{ oCompressAlgo, "compress-algo", 1 , N_("|N|use compress algorithm N")},
374
{ aDummy, "throw-keyid", 0, "@"},
375
{ aDummy, "notation-data", 2, "@"},
376
{ aExportSecretKeyP12, "export-secret-key-p12", 256, "@"},
380
"@\n(See the man page for a complete listing of all commands and options)\n"
383
{ 303, NULL, 0, N_("@\nExamples:\n\n"
384
" -se -r Bob [file] sign and encrypt for user Bob\n"
385
" --clearsign [file] make a clear text signature\n"
386
" --detach-sign [file] make a detached signature\n"
387
" --list-keys [names] show keys\n"
388
" --fingerprint [names] show fingerprints\n" ) },
391
{ oNoVerbose, "no-verbose", 0, "@"},
393
{ oEnableSpecialFilenames, "enable-special-filenames", 0, "@" },
396
{ oTrustDBName, "trustdb-name", 2, "@" },
397
{ oNoSecmemWarn, "no-secmem-warning", 0, "@" },
398
{ oNoArmor, "no-armor", 0, "@"},
399
{ oNoArmor, "no-armour", 0, "@"},
400
{ oNoDefKeyring, "no-default-keyring", 0, "@" },
401
{ oNoGreeting, "no-greeting", 0, "@" },
402
{ oNoOptions, "no-options", 0, "@" }, /* shortcut for --options /dev/null */
403
{ oHomedir, "homedir", 2, "@" }, /* defaults to "~/.gnupg" */
404
{ oAgentProgram, "agent-program", 2 , "@" },
405
{ oDisplay, "display", 2, "@" },
406
{ oTTYname, "ttyname", 2, "@" },
407
{ oTTYtype, "ttytype", 2, "@" },
408
{ oLCctype, "lc-ctype", 2, "@" },
409
{ oLCmessages, "lc-messages", 2, "@" },
410
{ oDirmngrProgram, "dirmngr-program", 2 , "@" },
411
{ oProtectToolProgram, "protect-tool-program", 2 , "@" },
412
{ oFakedSystemTime, "faked-system-time", 4, "@" }, /* (epoch time) */
415
{ oNoBatch, "no-batch", 0, "@" },
416
{ oWithColons, "with-colons", 0, "@"},
417
{ oWithKeyData,"with-key-data", 0, "@"},
418
{ oWithValidation, "with-validation", 0, "@"},
419
{ oWithMD5Fingerprint, "with-md5-fingerprint", 0, "@"},
420
{ oWithEphemeralKeys, "with-ephemeral-keys", 0, "@"},
421
{ aListKeys, "list-key", 0, "@" }, /* alias */
422
{ aListSigs, "list-sig", 0, "@" }, /* alias */
423
{ aListSigs, "check-sig",0, "@" }, /* alias */
424
{ oSkipVerify, "skip-verify",0, "@" },
425
{ oCompressKeys, "compress-keys",0, "@"},
426
{ oCompressSigs, "compress-sigs",0, "@"},
427
{ oAlwaysTrust, "always-trust", 0, "@"},
428
{ oNoVersion, "no-version", 0, "@"},
429
{ oLockOnce, "lock-once", 0, "@" },
430
{ oLockMultiple, "lock-multiple", 0, "@" },
431
{ oLockNever, "lock-never", 0, "@" },
432
{ oLoggerFD, "logger-fd",1, "@" },
433
{ oWithFingerprint, "with-fingerprint", 0, "@" },
434
{ oDisableCipherAlgo, "disable-cipher-algo", 2, "@" },
435
{ oDisablePubkeyAlgo, "disable-pubkey-algo", 2, "@" },
436
{ oHonorHttpProxy,"honor-http-proxy", 0, "@" },
437
{ oListOnly, "list-only", 0, "@"},
438
{ oIgnoreTimeConflict, "ignore-time-conflict", 0, "@" },
439
{ oNoRandomSeedFile, "no-random-seed-file", 0, "@" },
444
int gpgsm_errors_seen = 0;
446
/* It is possible that we are currentlu running under setuid permissions */
447
static int maybe_setuid = 1;
449
/* Helper to implement --debug-level and --debug*/
450
static const char *debug_level;
451
static unsigned int debug_value;
453
/* Option --enable-special-filenames */
454
static int allow_special_filenames;
457
static char *build_list (const char *text,
458
const char *(*mapf)(int), int (*chkf)(int));
459
static void set_cmd (enum cmd_and_opt_values *ret_cmd,
460
enum cmd_and_opt_values new_cmd );
462
static void emergency_cleanup (void);
463
static int check_special_filename (const char *fname);
464
static int open_read (const char *filename);
465
static FILE *open_fwrite (const char *filename);
466
static void run_protect_tool (int argc, char **argv);
470
our_pk_test_algo (int algo)
476
our_cipher_test_algo (int algo)
482
our_md_test_algo (int algo)
488
my_strusage( int level )
490
static char *digests, *pubkeys, *ciphers;
495
case 11: p = "gpgsm (GnuPG)";
497
case 13: p = VERSION; break;
498
case 17: p = PRINTABLE_OS_NAME; break;
499
case 19: p = _("Please report bugs to <" PACKAGE_BUGREPORT ">.\n");
502
case 40: p = _("Usage: gpgsm [options] [files] (-h for help)");
505
p = _("Syntax: gpgsm [options] [files]\n"
506
"sign, check, encrypt or decrypt using the S/MIME protocol\n"
507
"default operation depends on the input data\n");
510
case 31: p = "\nHome: "; break;
511
case 32: p = opt.homedir; break;
512
case 33: p = _("\nSupported algorithms:\n"); break;
515
ciphers = build_list ("Cipher: ", gcry_cipher_algo_name,
516
our_cipher_test_algo );
521
pubkeys = build_list ("Pubkey: ", gcry_pk_algo_name,
527
digests = build_list("Hash: ", gcry_md_algo_name, our_md_test_algo );
531
default: p = NULL; break;
538
build_list (const char *text, const char * (*mapf)(int), int (*chkf)(int))
541
size_t n=strlen(text)+2;
545
gcry_control (GCRYCTL_DROP_PRIVS); /* drop setuid */
548
for (i=1; i < 110; i++ )
550
n += strlen(mapf(i)) + 2;
551
list = xmalloc (21 + n);
553
for (p=NULL, i=1; i < 110; i++)
558
p = stpcpy (list, text );
560
p = stpcpy (p, ", ");
561
p = stpcpy (p, mapf(i) );
565
p = stpcpy(p, "\n" );
570
/* Set the file pointer into binary mode if required. */
572
set_binary (FILE *fp)
574
#ifdef HAVE_DOSISH_SYSTEM
575
setmode (fileno (fp), O_BINARY);
584
#ifdef USE_SIMPLE_GETTEXT
585
set_gettext_file (PACKAGE_GT);
588
setlocale (LC_ALL, "" );
589
bindtextdomain (PACKAGE_GT, LOCALEDIR);
590
textdomain (PACKAGE_GT);
597
wrong_args (const char *text)
599
fputs (_("usage: gpgsm [options] "), stderr);
600
fputs (text, stderr);
606
/* Setup the debugging. With a DEBUG_LEVEL of NULL only the active
607
debug flags are propagated to the subsystems. With DEBUG_LEVEL
608
set, a specific set of debug flags is set; and individual debugging
609
flags will be added on top. */
615
else if (!strcmp (debug_level, "none"))
617
else if (!strcmp (debug_level, "basic"))
618
opt.debug = DBG_ASSUAN_VALUE;
619
else if (!strcmp (debug_level, "advanced"))
620
opt.debug = DBG_ASSUAN_VALUE|DBG_X509_VALUE;
621
else if (!strcmp (debug_level, "expert"))
622
opt.debug = (DBG_ASSUAN_VALUE|DBG_X509_VALUE
623
|DBG_CACHE_VALUE|DBG_CRYPTO_VALUE);
624
else if (!strcmp (debug_level, "guru"))
628
log_error (_("invalid debug-level `%s' given\n"), debug_level);
632
opt.debug |= debug_value;
634
if (opt.debug && !opt.verbose)
639
if (opt.debug & DBG_MPI_VALUE)
640
gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
641
if (opt.debug & DBG_CRYPTO_VALUE )
642
gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
643
gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
649
set_cmd (enum cmd_and_opt_values *ret_cmd, enum cmd_and_opt_values new_cmd)
651
enum cmd_and_opt_values cmd = *ret_cmd;
653
if (!cmd || cmd == new_cmd)
655
else if ( cmd == aSign && new_cmd == aEncr )
657
else if ( cmd == aEncr && new_cmd == aSign )
659
else if ( (cmd == aSign && new_cmd == aClearsign)
660
|| (cmd == aClearsign && new_cmd == aSign) )
664
log_error(_("conflicting commands\n"));
672
/* Helper to add recipients to a list. */
674
do_add_recipient (ctrl_t ctrl, const char *name,
675
certlist_t *recplist, int is_encrypt_to)
677
int rc = gpgsm_add_to_certlist (ctrl, name, 0, recplist, is_encrypt_to);
680
log_error (_("can't encrypt to `%s': %s\n"), name, gpg_strerror (rc));
681
gpgsm_status2 (ctrl, STATUS_INV_RECP,
682
gpg_err_code (rc) == -1? "1":
683
gpg_err_code (rc) == GPG_ERR_NO_PUBKEY? "1":
684
gpg_err_code (rc) == GPG_ERR_AMBIGUOUS_NAME? "2":
685
gpg_err_code (rc) == GPG_ERR_WRONG_KEY_USAGE? "3":
686
gpg_err_code (rc) == GPG_ERR_CERT_REVOKED? "4":
687
gpg_err_code (rc) == GPG_ERR_CERT_EXPIRED? "5":
688
gpg_err_code (rc) == GPG_ERR_NO_CRL_KNOWN? "6":
689
gpg_err_code (rc) == GPG_ERR_CRL_TOO_OLD? "7":
690
gpg_err_code (rc) == GPG_ERR_NO_POLICY_MATCH? "8":
698
main ( int argc, char **argv)
706
STRLIST sl, remusr= NULL, locusr=NULL;
708
int detached_sig = 0;
709
FILE *configfp = NULL;
710
char *configname = NULL;
711
unsigned configlineno;
713
int no_more_options = 0;
714
int default_config =1;
715
int default_keyring = 1;
716
char *logfile = NULL;
720
int use_random_seed = 1;
722
char *def_digest_string = NULL;
723
enum cmd_and_opt_values cmd = 0;
724
struct server_control_s ctrl;
725
CERTLIST recplist = NULL;
726
CERTLIST signerlist = NULL;
727
int do_not_setup_keys = 0;
730
/* trap_unaligned ();*/
731
set_strusage (my_strusage);
732
gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
733
/* We don't need any locking in libgcrypt unless we use any kind of
735
gcry_control (GCRYCTL_DISABLE_INTERNAL_LOCKING);
737
/* Please note that we may running SUID(ROOT), so be very CAREFUL
738
when adding any stuff between here and the call to secmem_init()
739
somewhere after the option parsing */
740
log_set_prefix ("gpgsm", 1);
742
/* Try to auto set the character set. */
743
set_native_charset (NULL);
745
/* Check that the libraries are suitable. Do it here because the
746
option parse may need services of the library */
747
if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
749
log_fatal( _("libgcrypt is too old (need %s, have %s)\n"),
750
NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
752
if (!ksba_check_version (NEED_KSBA_VERSION) )
754
log_fatal( _("libksba is too old (need %s, have %s)\n"),
755
NEED_KSBA_VERSION, ksba_check_version (NULL) );
758
#ifdef HAVE_W32_SYSTEM
759
/* For W32 we need pth. */
764
gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
766
may_coredump = disable_core_dumps ();
768
gnupg_init_signals (0, emergency_cleanup);
770
create_dotlock (NULL); /* register locking cleanup */
773
opt.def_cipher_algoid = "1.2.840.113549.3.7"; /*des-EDE3-CBC*/
775
opt.homedir = default_homedir ();
776
#ifdef HAVE_W32_SYSTEM
777
opt.no_crl_check = 1;
780
/* First check whether we have a config file on the commandline */
785
pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
786
while (arg_parse( &pargs, opts))
788
if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
790
else if (pargs.r_opt == oOptions)
791
{ /* yes there is one, so we do not try the default one but
792
read the config file when it is encountered at the
796
else if (pargs.r_opt == oNoOptions)
797
default_config = 0; /* --no-options */
798
else if (pargs.r_opt == oHomedir)
799
opt.homedir = pargs.r.ret_str;
800
else if (pargs.r_opt == aCallProtectTool)
801
break; /* This break makes sure that --version and --help are
802
passed to the protect-tool. */
806
/* initialize the secure memory. */
807
gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
811
Now we are now working under our real uid
814
ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free );
816
assuan_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
817
assuan_set_assuan_log_stream (log_get_stream ());
818
assuan_set_assuan_log_prefix (log_get_prefix (NULL));
820
keybox_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
822
/* Setup a default control structure for command line mode */
823
memset (&ctrl, 0, sizeof ctrl);
824
gpgsm_init_default_ctrl (&ctrl);
826
ctrl.status_fd = -1; /* not status output */
827
ctrl.autodetect_encoding = 1;
829
/* Set the default option file */
831
configname = make_filename (opt.homedir, "gpgsm.conf", NULL);
832
/* Set the default policy file */
833
opt.policy_file = make_filename (opt.homedir, "policies.txt", NULL);
839
pargs.flags = 1; /* do not remove the args */
844
configfp = fopen (configname, "r");
850
log_info (_("NOTE: no default option file `%s'\n"), configname);
854
log_error (_("option file `%s': %s\n"), configname, strerror(errno));
860
if (parse_debug && configname)
861
log_info (_("reading options from `%s'\n"), configname);
865
while (!no_more_options
866
&& optfile_parse (configfp, configname, &configlineno, &pargs, opts))
871
set_cmd (&cmd, pargs.r_opt);
872
do_not_setup_keys = 1;
878
set_cmd (&cmd, aServer);
883
set_cmd (&cmd, aCallDirmngr);
884
do_not_setup_keys = 1;
887
case aCallProtectTool:
889
set_cmd (&cmd, aCallProtectTool);
890
no_more_options = 1; /* Stop parsing. */
891
do_not_setup_keys = 1;
895
set_cmd (&cmd, aDeleteKey);
897
do_not_setup_keys = 1;
902
set_cmd (&cmd, aSign );
906
set_cmd (&cmd, aKeygen);
908
do_not_setup_keys = 1;
916
case aExportSecretKeyP12:
918
case aDumpExternalKeys:
919
case aDumpSecretKeys:
921
case aListExternalKeys:
922
case aListSecretKeys:
926
case aKeydbClearSomeCertFlags:
927
do_not_setup_keys = 1;
928
set_cmd (&cmd, pargs.r_opt);
937
set_cmd (&cmd, pargs.r_opt);
940
/* output encoding selection */
946
ctrl.create_base64 = 1;
950
ctrl.create_base64 = 0;
953
/* Input encoding selection */
955
ctrl.autodetect_encoding = 0;
960
ctrl.autodetect_encoding = 0;
965
ctrl.autodetect_encoding = 0;
970
case oDisableCRLChecks:
971
opt.no_crl_check = 1;
973
case oEnableCRLChecks:
974
opt.no_crl_check = 0;
976
case oForceCRLRefresh:
977
opt.force_crl_refresh = 1;
981
ctrl.use_ocsp = opt.enable_ocsp = 0;
984
ctrl.use_ocsp = opt.enable_ocsp = 1;
987
case oIncludeCerts: ctrl.include_certs = pargs.r.ret_int; break;
990
xfree (opt.policy_file);
991
if (*pargs.r.ret_str)
992
opt.policy_file = xstrdup (pargs.r.ret_str);
994
opt.policy_file = NULL;
997
case oDisablePolicyChecks:
998
opt.no_policy_check = 1;
1000
case oEnablePolicyChecks:
1001
opt.no_policy_check = 0;
1004
case oAutoIssuerKeyRetrieve:
1005
opt.auto_issuer_key_retrieve = 1;
1008
case oOutput: opt.outfile = pargs.r.ret_str; break;
1011
case oQuiet: opt.quiet = 1; break;
1012
case oNoTTY: /* fixme:tty_no_terminal(1);*/ break;
1013
case oDryRun: opt.dry_run = 1; break;
1017
gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
1021
gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
1024
case oLogFile: logfile = pargs.r.ret_str; break;
1030
case oNoBatch: opt.batch = 0; break;
1032
case oAnswerYes: opt.answer_yes = 1; break;
1033
case oAnswerNo: opt.answer_no = 1; break;
1035
case oKeyring: append_to_strlist (&nrings, pargs.r.ret_str); break;
1037
case oDebug: debug_value |= pargs.r.ret_ulong; break;
1038
case oDebugAll: debug_value = ~0; break;
1039
case oDebugLevel: debug_level = pargs.r.ret_str; break;
1040
case oDebugWait: debug_wait = pargs.r.ret_int; break;
1041
case oDebugAllowCoreDump:
1042
may_coredump = enable_core_dumps ();
1044
case oDebugNoChainValidation: opt.no_chain_validation = 1; break;
1045
case oDebugIgnoreExpiration: opt.ignore_expiration = 1; break;
1046
case oFixedPassphrase: opt.fixed_passphrase = pargs.r.ret_str; break;
1048
case oStatusFD: ctrl.status_fd = pargs.r.ret_int; break;
1049
case oLoggerFD: log_set_fd (pargs.r.ret_int ); break;
1050
case oWithMD5Fingerprint:
1051
opt.with_md5_fingerprint=1; /*fall thru*/
1052
case oWithFingerprint:
1053
with_fpr=1; /*fall thru*/
1059
/* config files may not be nested (silently ignore them) */
1063
configname = xstrdup (pargs.r.ret_str);
1067
case oNoOptions: break; /* no-options */
1068
case oHomedir: opt.homedir = pargs.r.ret_str; break;
1069
case oAgentProgram: opt.agent_program = pargs.r.ret_str; break;
1070
case oDisplay: opt.display = xstrdup (pargs.r.ret_str); break;
1071
case oTTYname: opt.ttyname = xstrdup (pargs.r.ret_str); break;
1072
case oTTYtype: opt.ttytype = xstrdup (pargs.r.ret_str); break;
1073
case oLCctype: opt.lc_ctype = xstrdup (pargs.r.ret_str); break;
1074
case oLCmessages: opt.lc_messages = xstrdup (pargs.r.ret_str); break;
1075
case oDirmngrProgram: opt.dirmngr_program = pargs.r.ret_str; break;
1076
case oPreferSystemDirmngr: opt.prefer_system_dirmngr = 1; break;
1077
case oProtectToolProgram:
1078
opt.protect_tool_program = pargs.r.ret_str;
1081
case oFakedSystemTime:
1082
gnupg_set_time ( (time_t)pargs.r.ret_ulong, 0);
1085
case oNoDefKeyring: default_keyring = 0; break;
1086
case oNoGreeting: nogreeting = 1; break;
1089
/* fixme:opt.def_secret_key = pargs.r.ret_str;*/
1090
log_info ("WARNING: --default-key has not yet been implemented\n");
1093
if (*pargs.r.ret_str)
1094
opt.def_recipient = xstrdup (pargs.r.ret_str);
1096
case oDefRecipientSelf:
1097
xfree (opt.def_recipient);
1098
opt.def_recipient = NULL;
1099
opt.def_recipient_self = 1;
1101
case oNoDefRecipient:
1102
xfree (opt.def_recipient);
1103
opt.def_recipient = NULL;
1104
opt.def_recipient_self = 0;
1107
case oWithKeyData: opt.with_key_data=1; /* fall thru */
1108
case oWithColons: ctrl.with_colons = 1; break;
1109
case oWithValidation: ctrl.with_validation=1; break;
1110
case oWithEphemeralKeys: opt.with_ephemeral_keys=1; break;
1112
case oSkipVerify: opt.skip_verify=1; break;
1114
case oNoEncryptTo: opt.no_encrypt_to = 1; break;
1115
case oEncryptTo: /* Store the recipient in the second list */
1116
sl = add_to_strlist (&remusr, pargs.r.ret_str);
1120
case oRecipient: /* store the recipient */
1121
add_to_strlist ( &remusr, pargs.r.ret_str);
1124
case oTextmodeShort: /*fixme:opt.textmode = 2;*/ break;
1125
case oTextmode: /*fixme:opt.textmode=1;*/ break;
1127
case oUser: /* store the local users, the first one is the default */
1128
if (!opt.local_user)
1129
opt.local_user = pargs.r.ret_str;
1130
add_to_strlist (&locusr, pargs.r.ret_str);
1134
gcry_control (GCRYCTL_DISABLE_SECMEM_WARN);
1138
opt.def_cipher_algoid = pargs.r.ret_str;
1141
case oDisableCipherAlgo:
1143
int algo = gcry_cipher_map_name (pargs.r.ret_str);
1144
gcry_cipher_ctl (NULL, GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
1147
case oDisablePubkeyAlgo:
1149
int algo = gcry_pk_map_name (pargs.r.ret_str);
1150
gcry_pk_ctl (GCRYCTL_DISABLE_ALGO,&algo, sizeof algo );
1154
case oIgnoreTimeConflict: opt.ignore_time_conflict = 1; break;
1155
case oNoRandomSeedFile: use_random_seed = 0; break;
1157
case oEnableSpecialFilenames: allow_special_filenames =1; break;
1163
pargs.err = configfp? 1:2;
1172
/* Keep a copy of the config filename. */
1173
opt.config_filename = configname;
1180
if (!opt.config_filename)
1181
opt.config_filename = make_filename (opt.homedir, "gpgsm.conf", NULL);
1183
if (log_get_errorcount(0))
1191
fprintf(stderr, "%s %s; %s\n",
1192
strusage(11), strusage(13), strusage(14) );
1193
fprintf(stderr, "%s\n", strusage(15) );
1195
# ifdef IS_DEVELOPMENT_VERSION
1198
log_info ("NOTE: THIS IS A DEVELOPMENT VERSION!\n");
1199
log_info ("It is only intended for test purposes and should NOT be\n");
1200
log_info ("used in a production environment or with production keys!\n");
1204
if (may_coredump && !opt.quiet)
1205
log_info (_("WARNING: program may create a core file!\n"));
1207
if (logfile && cmd == aServer)
1209
log_set_file (logfile);
1210
log_set_prefix (NULL, 1|2|4);
1213
if (gnupg_faked_time_p ())
1215
gnupg_isotime_t tbuf;
1217
log_info (_("WARNING: running with faked system time: "));
1218
gnupg_get_isotime (tbuf);
1219
gpgsm_dump_time (tbuf);
1223
/*FIXME if (opt.batch) */
1224
/* tty_batchmode (1); */
1226
gcry_control (GCRYCTL_RESUME_SECMEM_WARN);
1230
/* Although we alwasy use gpgsm_exit, we better install a regualr
1231
exit handler so that at least the secure memory gets wiped
1233
if (atexit (emergency_cleanup))
1235
log_error ("atexit failed\n");
1239
/* Must do this after dropping setuid, because the mapping functions
1240
may try to load an module and we may have disabled an algorithm. */
1241
if ( !gcry_cipher_map_name (opt.def_cipher_algoid)
1242
|| !gcry_cipher_mode_from_oid (opt.def_cipher_algoid))
1243
log_error (_("selected cipher algorithm is invalid\n"));
1245
if (def_digest_string)
1247
opt.def_digest_algo = gcry_md_map_name (def_digest_string);
1248
xfree (def_digest_string);
1249
def_digest_string = NULL;
1250
if (our_md_test_algo(opt.def_digest_algo) )
1251
log_error (_("selected digest algorithm is invalid\n"));
1254
if (log_get_errorcount(0))
1257
/* Set the random seed file. */
1258
if (use_random_seed) {
1259
char *p = make_filename (opt.homedir, "random_seed", NULL);
1260
gcry_control (GCRYCTL_SET_RANDOM_SEED_FILE, p);
1265
if (!cmd && opt.fingerprint && !with_fpr)
1266
set_cmd (&cmd, aListKeys);
1268
if (!nrings && default_keyring) /* add default keybox */
1269
keydb_add_resource ("pubring.kbx", 0, 0);
1270
for (sl = nrings; sl; sl = sl->next)
1271
keydb_add_resource (sl->d, 0, 0);
1272
FREE_STRLIST(nrings);
1274
if (!do_not_setup_keys)
1276
for (sl = locusr; sl ; sl = sl->next)
1278
int rc = gpgsm_add_to_certlist (&ctrl, sl->d, 1, &signerlist, 0);
1281
log_error (_("can't sign using `%s': %s\n"),
1282
sl->d, gpg_strerror (rc));
1283
gpgsm_status2 (&ctrl, STATUS_INV_RECP,
1284
gpg_err_code (rc) == -1? "1":
1285
gpg_err_code (rc) == GPG_ERR_NO_PUBKEY? "1":
1286
gpg_err_code (rc) == GPG_ERR_AMBIGUOUS_NAME? "2":
1287
gpg_err_code (rc) == GPG_ERR_WRONG_KEY_USAGE? "3":
1288
gpg_err_code (rc) == GPG_ERR_CERT_REVOKED? "4":
1289
gpg_err_code (rc) == GPG_ERR_CERT_EXPIRED? "5":
1290
gpg_err_code (rc) == GPG_ERR_NO_CRL_KNOWN? "6":
1291
gpg_err_code (rc) == GPG_ERR_CRL_TOO_OLD? "7":
1292
gpg_err_code (rc) == GPG_ERR_NO_POLICY_MATCH? "8":
1293
gpg_err_code (rc) == GPG_ERR_NO_SECKEY? "9":
1299
/* Build the recipient list. We first add the regular ones and then
1300
the encrypt-to ones because the underlying function will silenty
1301
ignore duplicates and we can't allow to keep a duplicate which is
1302
flagged as encrypt-to as the actually encrypt function would then
1303
complain about no (regular) recipients. */
1304
for (sl = remusr; sl; sl = sl->next)
1305
if (!(sl->flags & 1))
1306
do_add_recipient (&ctrl, sl->d, &recplist, 0);
1307
if (!opt.no_encrypt_to)
1309
for (sl = remusr; sl; sl = sl->next)
1310
if ((sl->flags & 1))
1311
do_add_recipient (&ctrl, sl->d, &recplist, 1);
1315
if (log_get_errorcount(0))
1316
gpgsm_exit(1); /* must stop for invalid recipients */
1318
fname = argc? *argv : NULL;
1323
{ /* List options and default values in the GPG Conf format. */
1325
/* The following list is taken from gnupg/tools/gpgconf-comp.c. */
1326
/* Option flags. YOU MUST NOT CHANGE THE NUMBERS OF THE EXISTING
1327
FLAGS, AS THEY ARE PART OF THE EXTERNAL INTERFACE. */
1328
#define GC_OPT_FLAG_NONE 0UL
1329
/* The RUNTIME flag for an option indicates that the option can be
1330
changed at runtime. */
1331
#define GC_OPT_FLAG_RUNTIME (1UL << 3)
1332
/* The DEFAULT flag for an option indicates that the option has a
1334
#define GC_OPT_FLAG_DEFAULT (1UL << 4)
1335
/* The DEF_DESC flag for an option indicates that the option has a
1336
default, which is described by the value of the default field. */
1337
#define GC_OPT_FLAG_DEF_DESC (1UL << 5)
1338
/* The NO_ARG_DESC flag for an option indicates that the argument has
1339
a default, which is described by the value of the ARGDEF field. */
1340
#define GC_OPT_FLAG_NO_ARG_DESC (1UL << 6)
1342
printf ("gpgconf-gpgsm.conf:%lu:\"%s\n",
1343
GC_OPT_FLAG_DEFAULT, opt.config_filename);
1345
printf ("verbose:%lu:\n"
1347
"debug-level:%lu:\"none:\n"
1351
GC_OPT_FLAG_DEFAULT,
1353
printf ("disable-crl-checks:%lu:\n",
1355
printf ("enable-ocsp:%lu:\n",
1357
printf ("include-certs:%lu:1:\n",
1358
GC_OPT_FLAG_DEFAULT );
1359
printf ("disable-policy-checks:%lu:\n",
1361
printf ("auto-issuer-key-retrieve:%lu:\n",
1363
printf ("prefer-system-dirmngr:%lu:\n",
1372
log_debug ("waiting for debugger - my pid is %u .....\n",
1373
(unsigned int)getpid());
1375
log_debug ("... okay\n");
1377
gpgsm_server (recplist);
1382
wrong_args ("--call-dirmngr <command> {args}");
1384
if (gpgsm_dirmngr_run_command (&ctrl, *argv, argc-1, argv+1))
1388
case aCallProtectTool:
1389
run_protect_tool (argc, argv);
1392
case aEncr: /* encrypt the given file */
1394
set_binary (stdout);
1396
gpgsm_encrypt (&ctrl, recplist, 0, stdout); /* from stdin */
1398
gpgsm_encrypt (&ctrl, recplist, open_read (*argv), stdout); /* from file */
1400
wrong_args ("--encrypt [datafile]");
1403
case aSign: /* sign the given file */
1404
/* FIXME: We don't handle --output yet. We should also allow
1405
to concatenate multiple files for signing because that is
1408
set_binary (stdout);
1410
gpgsm_sign (&ctrl, signerlist,
1411
0, detached_sig, stdout); /* create from stdin */
1413
gpgsm_sign (&ctrl, signerlist,
1414
open_read (*argv), detached_sig, stdout); /* from file */
1416
wrong_args ("--sign [datafile]");
1419
case aSignEncr: /* sign and encrypt the given file */
1420
log_error ("this command has not yet been implemented\n");
1423
case aClearsign: /* make a clearsig */
1424
log_error ("this command has not yet been implemented\n");
1432
if (argc == 2 && opt.outfile)
1433
log_info ("option --output ignored for a detached signature\n");
1434
else if (opt.outfile)
1435
fp = open_fwrite (opt.outfile);
1438
gpgsm_verify (&ctrl, 0, -1, fp); /* normal signature from stdin */
1440
gpgsm_verify (&ctrl, open_read (*argv), -1, fp); /* std signature */
1441
else if (argc == 2) /* detached signature (sig, detached) */
1442
gpgsm_verify (&ctrl, open_read (*argv), open_read (argv[1]), NULL);
1444
wrong_args ("--verify [signature [detached_data]]");
1446
if (fp && fp != stdout)
1452
log_error (_("this command has not yet been implemented\n"));
1457
set_binary (stdout);
1459
gpgsm_decrypt (&ctrl, 0, stdout); /* from stdin */
1461
gpgsm_decrypt (&ctrl, open_read (*argv), stdout); /* from file */
1463
wrong_args ("--decrypt [filename]");
1467
for (sl=NULL; argc; argc--, argv++)
1468
add_to_strlist (&sl, *argv);
1469
gpgsm_delete (&ctrl, sl);
1474
ctrl.with_chain = 1;
1476
for (sl=NULL; argc; argc--, argv++)
1477
add_to_strlist (&sl, *argv);
1478
gpgsm_list_keys (&ctrl, sl, stdout, (0 | (1<<6)));
1483
for (sl=NULL; argc; argc--, argv++)
1484
add_to_strlist (&sl, *argv);
1485
gpgsm_list_keys (&ctrl, sl, stdout, (256 | (1<<6)));
1489
case aListExternalKeys:
1490
for (sl=NULL; argc; argc--, argv++)
1491
add_to_strlist (&sl, *argv);
1492
gpgsm_list_keys (&ctrl, sl, stdout,
1497
case aDumpExternalKeys:
1498
for (sl=NULL; argc; argc--, argv++)
1499
add_to_strlist (&sl, *argv);
1500
gpgsm_list_keys (&ctrl, sl, stdout,
1505
case aListSecretKeys:
1506
for (sl=NULL; argc; argc--, argv++)
1507
add_to_strlist (&sl, *argv);
1508
gpgsm_list_keys (&ctrl, sl, stdout, (2 | (1<<6)));
1512
case aDumpSecretKeys:
1513
for (sl=NULL; argc; argc--, argv++)
1514
add_to_strlist (&sl, *argv);
1515
gpgsm_list_keys (&ctrl, sl, stdout, (256 | 2 | (1<<6)));
1519
case aKeygen: /* generate a key */
1520
log_error ("this function is not yet available from the commandline\n");
1524
gpgsm_import_files (&ctrl, argc, argv, open_read);
1528
set_binary (stdout);
1529
for (sl=NULL; argc; argc--, argv++)
1530
add_to_strlist (&sl, *argv);
1531
gpgsm_export (&ctrl, sl, stdout);
1535
case aExportSecretKeyP12:
1536
set_binary (stdout);
1538
gpgsm_p12_export (&ctrl, *argv, stdout);
1540
wrong_args ("--export-secret-key-p12 KEY-ID");
1545
log_error ("this command has not yet been implemented\n");
1551
wrong_args ("--learn-card");
1554
int rc = gpgsm_agent_learn (&ctrl);
1556
log_error ("error learning card: %s\n", gpg_strerror (rc));
1562
wrong_args ("--passwd <key-Id>");
1566
ksba_cert_t cert = NULL;
1569
rc = gpgsm_find_cert (*argv, &cert);
1572
else if (!(grip = gpgsm_get_keygrip_hexstring (cert)))
1573
rc = gpg_error (GPG_ERR_BUG);
1576
char *desc = gpgsm_format_keydesc (cert);
1577
rc = gpgsm_agent_passwd (&ctrl, grip, desc);
1581
log_error ("error changing passphrase: %s\n", gpg_strerror (rc));
1583
ksba_cert_release (cert);
1587
case aKeydbClearSomeCertFlags:
1588
for (sl=NULL; argc; argc--, argv++)
1589
add_to_strlist (&sl, *argv);
1590
keydb_clear_some_cert_flags (&ctrl, sl);
1596
log_error ("invalid command (there is no implicit command)\n");
1601
gpgsm_release_certlist (recplist);
1602
gpgsm_release_certlist (signerlist);
1603
FREE_STRLIST(remusr);
1604
FREE_STRLIST(locusr);
1606
return 8; /*NEVER REACHED*/
1609
/* Note: This function is used by signal handlers!. */
1611
emergency_cleanup (void)
1613
gcry_control (GCRYCTL_TERM_SECMEM );
1620
gcry_control (GCRYCTL_UPDATE_RANDOM_SEED_FILE);
1621
if (opt.debug & DBG_MEMSTAT_VALUE)
1623
gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
1624
gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
1627
gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
1628
emergency_cleanup ();
1629
rc = rc? rc : log_get_errorcount(0)? 2 : gpgsm_errors_seen? 1 : 0;
1635
gpgsm_init_default_ctrl (struct server_control_s *ctrl)
1637
ctrl->include_certs = 1; /* only include the signer's cert */
1638
ctrl->use_ocsp = opt.enable_ocsp;
1643
/* Check whether the filename has the form "-&nnnn", where n is a
1644
non-zero number. Returns this number or -1 if it is not the case. */
1646
check_special_filename (const char *fname)
1648
if (allow_special_filenames
1649
&& fname && *fname == '-' && fname[1] == '&' ) {
1653
for (i=0; isdigit (fname[i]); i++ )
1656
return atoi (fname);
1663
/* Open the FILENAME for read and return the filedescriptor. Stop
1664
with an error message in case of problems. "-" denotes stdin and
1665
if special filenames are allowed the given fd is opened instead. */
1667
open_read (const char *filename)
1671
if (filename[0] == '-' && !filename[1])
1674
return 0; /* stdin */
1676
fd = check_special_filename (filename);
1679
fd = open (filename, O_RDONLY | O_BINARY);
1682
log_error (_("can't open `%s': %s\n"), filename, strerror (errno));
1688
/* Open FILENAME for fwrite and return the stream. Stop with an error
1689
message in case of problems. "-" denotes stdout and if special
1690
filenames are allowed the given fd is opened instead. Caller must
1691
close the returned stream unless it is stdout. */
1693
open_fwrite (const char *filename)
1698
if (filename[0] == '-' && !filename[1])
1700
set_binary (stdout);
1704
fd = check_special_filename (filename);
1707
fp = fdopen (dup (fd), "wb");
1710
log_error ("fdopen(%d) failed: %s\n", fd, strerror (errno));
1716
fp = fopen (filename, "wb");
1719
log_error (_("can't open `%s': %s\n"), filename, strerror (errno));
1727
run_protect_tool (int argc, char **argv)
1729
#ifndef HAVE_W32_SYSTEM
1734
if (!opt.protect_tool_program || !*opt.protect_tool_program)
1735
pgm = GNUPG_DEFAULT_PROTECT_TOOL;
1737
pgm = opt.protect_tool_program;
1739
av = xcalloc (argc+2, sizeof *av);
1740
av[0] = strrchr (pgm, '/');
1742
av[0] = xstrdup (pgm);
1743
for (i=1; argc; i++, argc--, argv++)
1747
log_error ("error executing `%s': %s\n", pgm, strerror (errno));
1748
#endif /*HAVE_W32_SYSTEM*/