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
,
103 oEnableSpecialFilenames
,
113 oPreferSystemDirmngr
,
130 oDisableTrustedCertCRLCheck
,
131 oEnableTrustedCertCRLCheck
,
139 oDisablePolicyChecks
,
141 oAutoIssuerKeyRetrieve
,
182 static ARGPARSE_OPTS opts
[] = {
184 ARGPARSE_group (300, N_("@Commands:\n ")),
186 ARGPARSE_c (aSign
, "sign", N_("make a signature")),
187 ARGPARSE_c (aClearsign
, "clearsign", N_("make a clear text signature") ),
188 ARGPARSE_c (aDetachedSign
, "detach-sign", N_("make a detached signature")),
189 ARGPARSE_c (aEncr
, "encrypt", N_("encrypt data")),
190 ARGPARSE_c (aSym
, "symmetric", N_("encryption only with symmetric cipher")),
191 ARGPARSE_c (aDecrypt
, "decrypt", N_("decrypt data (default)")),
192 ARGPARSE_c (aVerify
, "verify", N_("verify a signature")),
193 ARGPARSE_c (aListKeys
, "list-keys", N_("list keys")),
194 ARGPARSE_c (aListExternalKeys
, "list-external-keys",
195 N_("list external keys")),
196 ARGPARSE_c (aListSecretKeys
, "list-secret-keys", N_("list secret keys")),
197 ARGPARSE_c (aListChain
, "list-chain", N_("list certificate chain")),
198 ARGPARSE_c (aFingerprint
, "fingerprint", N_("list keys and fingerprints")),
199 ARGPARSE_c (aKeygen
, "gen-key", N_("generate a new key pair")),
200 ARGPARSE_c (aDeleteKey
, "delete-keys",
201 N_("remove keys from the public keyring")),
202 ARGPARSE_c (aSendKeys
, "send-keys", N_("export keys to a key server")),
203 ARGPARSE_c (aRecvKeys
, "recv-keys", N_("import keys from a key server")),
204 ARGPARSE_c (aImport
, "import", N_("import certificates")),
205 ARGPARSE_c (aExport
, "export", N_("export certificates")),
206 ARGPARSE_c (aExportSecretKeyP12
, "export-secret-key-p12", "@"),
207 ARGPARSE_c (aLearnCard
, "learn-card", N_("register a smartcard")),
208 ARGPARSE_c (aServer
, "server", N_("run in server mode")),
209 ARGPARSE_c (aCallDirmngr
, "call-dirmngr",
210 N_("pass a command to the dirmngr")),
211 ARGPARSE_c (aCallProtectTool
, "call-protect-tool",
212 N_("invoke gpg-protect-tool")),
213 ARGPARSE_c (aPasswd
, "passwd", N_("change a passphrase")),
214 ARGPARSE_c (aGPGConfList
, "gpgconf-list", "@"),
215 ARGPARSE_c (aGPGConfTest
, "gpgconf-test", "@"),
217 ARGPARSE_c (aDumpKeys
, "dump-cert", "@"),
218 ARGPARSE_c (aDumpKeys
, "dump-keys", "@"),
219 ARGPARSE_c (aDumpChain
, "dump-chain", "@"),
220 ARGPARSE_c (aDumpExternalKeys
, "dump-external-keys", "@"),
221 ARGPARSE_c (aDumpSecretKeys
, "dump-secret-keys", "@"),
222 ARGPARSE_c (aKeydbClearSomeCertFlags
, "keydb-clear-some-cert-flags", "@"),
224 ARGPARSE_group (301, N_("@\nOptions:\n ")),
226 ARGPARSE_s_n (oArmor
, "armor", N_("create ascii armored output")),
227 ARGPARSE_s_n (oArmor
, "armour", "@"),
228 ARGPARSE_s_n (oBase64
, "base64", N_("create base-64 encoded output")),
230 ARGPARSE_s_s (oP12Charset
, "p12-charset", "@"),
232 ARGPARSE_s_n (oAssumeArmor
, "assume-armor",
233 N_("assume input is in PEM format")),
234 ARGPARSE_s_n (oAssumeBase64
, "assume-base64",
235 N_("assume input is in base-64 format")),
236 ARGPARSE_s_n (oAssumeBinary
, "assume-binary",
237 N_("assume input is in binary format")),
239 ARGPARSE_s_s (oRecipient
, "recipient", N_("|USER-ID|encrypt for USER-ID")),
241 ARGPARSE_s_n (oPreferSystemDirmngr
,"prefer-system-dirmngr",
242 N_("use system's dirmngr if available")),
244 ARGPARSE_s_n (oDisableCRLChecks
, "disable-crl-checks",
245 N_("never consult a CRL")),
246 ARGPARSE_s_n (oEnableCRLChecks
, "enable-crl-checks", "@"),
247 ARGPARSE_s_n (oDisableTrustedCertCRLCheck
,
248 "disable-trusted-cert-crl-check", "@"),
249 ARGPARSE_s_n (oEnableTrustedCertCRLCheck
,
250 "enable-trusted-cert-crl-check", "@"),
252 ARGPARSE_s_n (oForceCRLRefresh
, "force-crl-refresh", "@"),
254 ARGPARSE_s_n (oDisableOCSP
, "disable-ocsp", "@"),
255 ARGPARSE_s_n (oEnableOCSP
, "enable-ocsp", N_("check validity using OCSP")),
257 ARGPARSE_s_s (oValidationModel
, "validation-model", "@"),
259 ARGPARSE_s_i (oIncludeCerts
, "include-certs",
260 N_("|N|number of certificates to include") ),
262 ARGPARSE_s_s (oPolicyFile
, "policy-file",
263 N_("|FILE|take policy information from FILE")),
265 ARGPARSE_s_n (oDisablePolicyChecks
, "disable-policy-checks",
266 N_("do not check certificate policies")),
267 ARGPARSE_s_n (oEnablePolicyChecks
, "enable-policy-checks", "@"),
269 ARGPARSE_s_n (oAutoIssuerKeyRetrieve
, "auto-issuer-key-retrieve",
270 N_("fetch missing issuer certificates")),
272 ARGPARSE_s_s (oEncryptTo
, "encrypt-to", "@"),
273 ARGPARSE_s_n (oNoEncryptTo
, "no-encrypt-to", "@"),
275 ARGPARSE_s_s (oUser
, "local-user",
276 N_("|USER-ID|use USER-ID to sign or decrypt")),
278 ARGPARSE_s_s (oOutput
, "output", N_("|FILE|write output to FILE")),
279 ARGPARSE_s_n (oVerbose
, "verbose", N_("verbose")),
280 ARGPARSE_s_n (oQuiet
, "quiet", N_("be somewhat more quiet")),
281 ARGPARSE_s_n (oNoTTY
, "no-tty", N_("don't use the terminal at all")),
282 ARGPARSE_s_s (oLogFile
, "log-file",
283 N_("|FILE|write a server mode log to FILE")),
284 ARGPARSE_s_n (oNoLogFile
, "no-log-file", "@"),
285 ARGPARSE_s_i (oLoggerFD
, "logger-fd", "@"),
287 ARGPARSE_s_s (oAuditLog
, "audit-log",
288 N_("|FILE|write an audit log to FILE")),
289 ARGPARSE_s_n (oDryRun
, "dry-run", N_("do not make any changes")),
290 ARGPARSE_s_n (oBatch
, "batch", N_("batch mode: never ask")),
291 ARGPARSE_s_n (oAnswerYes
, "yes", N_("assume yes on most questions")),
292 ARGPARSE_s_n (oAnswerNo
, "no", N_("assume no on most questions")),
294 ARGPARSE_s_s (oKeyring
, "keyring",
295 N_("|FILE|add keyring to the list of keyrings")),
297 ARGPARSE_s_s (oDefaultKey
, "default-key",
298 N_("|USER-ID|use USER-ID as default secret key")),
301 /* ARGPARSE_s_s (oDefRecipient, "default-recipient", */
302 /* N_("|NAME|use NAME as default recipient")), */
303 /* ARGPARSE_s_n (oDefRecipientSelf, "default-recipient-self", */
304 /* N_("use the default key as default recipient")), */
305 /* ARGPARSE_s_n (oNoDefRecipient, "no-default-recipient", "@"), */
307 ARGPARSE_s_s (oKeyServer
, "keyserver",
308 N_("|SPEC|use this keyserver to lookup keys")),
309 ARGPARSE_s_s (oOptions
, "options", N_("|FILE|read options from FILE")),
311 ARGPARSE_p_u (oDebug
, "debug", "@"),
312 ARGPARSE_s_s (oDebugLevel
, "debug-level",
313 N_("|LEVEL|set the debugging level to LEVEL")),
314 ARGPARSE_s_n (oDebugAll
, "debug-all", "@"),
315 ARGPARSE_s_n (oDebugNone
, "debug-none", "@"),
316 ARGPARSE_s_i (oDebugWait
, "debug-wait", "@"),
317 ARGPARSE_s_n (oDebugAllowCoreDump
, "debug-allow-core-dump", "@"),
318 ARGPARSE_s_n (oDebugNoChainValidation
, "debug-no-chain-validation", "@"),
319 ARGPARSE_s_n (oDebugIgnoreExpiration
, "debug-ignore-expiration", "@"),
320 ARGPARSE_s_s (oFixedPassphrase
, "fixed-passphrase", "@"),
322 ARGPARSE_s_i (oStatusFD
, "status-fd",
323 N_("|FD|write status info to this FD")),
325 ARGPARSE_s_s (oCipherAlgo
, "cipher-algo",
326 N_("|NAME|use cipher algorithm NAME")),
327 ARGPARSE_s_s (oDigestAlgo
, "digest-algo",
328 N_("|NAME|use message digest algorithm NAME")),
329 ARGPARSE_s_s (oExtraDigestAlgo
, "extra-digest-algo", "@"),
332 ARGPARSE_group (302, N_(
333 "@\n(See the man page for a complete listing of all commands and options)\n"
336 ARGPARSE_group (303, N_("@\nExamples:\n\n"
337 " -se -r Bob [file] sign and encrypt for user Bob\n"
338 " --clearsign [file] make a clear text signature\n"
339 " --detach-sign [file] make a detached signature\n"
340 " --list-keys [names] show keys\n"
341 " --fingerprint [names] show fingerprints\n" )),
343 /* Hidden options. */
344 ARGPARSE_s_n (oNoVerbose
, "no-verbose", "@"),
345 ARGPARSE_s_n (oEnableSpecialFilenames
, "enable-special-filenames", "@"),
346 ARGPARSE_s_n (oNoSecmemWarn
, "no-secmem-warning", "@"),
347 ARGPARSE_s_n (oNoArmor
, "no-armor", "@"),
348 ARGPARSE_s_n (oNoArmor
, "no-armour", "@"),
349 ARGPARSE_s_n (oNoDefKeyring
, "no-default-keyring", "@"),
350 ARGPARSE_s_n (oNoGreeting
, "no-greeting", "@"),
351 ARGPARSE_s_n (oNoOptions
, "no-options", "@"),
352 ARGPARSE_s_s (oHomedir
, "homedir", "@"),
353 ARGPARSE_s_s (oAgentProgram
, "agent-program", "@"),
354 ARGPARSE_s_s (oDisplay
, "display", "@"),
355 ARGPARSE_s_s (oTTYname
, "ttyname", "@"),
356 ARGPARSE_s_s (oTTYtype
, "ttytype", "@"),
357 ARGPARSE_s_s (oLCctype
, "lc-ctype", "@"),
358 ARGPARSE_s_s (oLCmessages
, "lc-messages", "@"),
359 ARGPARSE_s_s (oXauthority
, "xauthority", "@"),
360 ARGPARSE_s_s (oDirmngrProgram
, "dirmngr-program", "@"),
361 ARGPARSE_s_n (oDisableDirmngr
, "disable-dirmngr", "@"),
362 ARGPARSE_s_s (oProtectToolProgram
, "protect-tool-program", "@"),
363 ARGPARSE_s_s (oFakedSystemTime
, "faked-system-time", "@"),
364 ARGPARSE_s_n (oNoBatch
, "no-batch", "@"),
365 ARGPARSE_s_n (oWithColons
, "with-colons", "@"),
366 ARGPARSE_s_n (oWithKeyData
,"with-key-data", "@"),
367 ARGPARSE_s_n (oWithValidation
, "with-validation", "@"),
368 ARGPARSE_s_n (oWithMD5Fingerprint
, "with-md5-fingerprint", "@"),
369 ARGPARSE_s_n (oWithEphemeralKeys
, "with-ephemeral-keys", "@"),
370 ARGPARSE_s_n (oSkipVerify
, "skip-verify", "@"),
371 ARGPARSE_s_n (oWithFingerprint
, "with-fingerprint", "@"),
372 ARGPARSE_s_s (oDisableCipherAlgo
, "disable-cipher-algo", "@"),
373 ARGPARSE_s_s (oDisablePubkeyAlgo
, "disable-pubkey-algo", "@"),
374 ARGPARSE_s_n (oIgnoreTimeConflict
, "ignore-time-conflict", "@"),
375 ARGPARSE_s_n (oNoRandomSeedFile
, "no-random-seed-file", "@"),
376 ARGPARSE_s_n (oNoCommonCertsImport
, "no-common-certs-import", "@"),
378 /* Command aliases. */
379 ARGPARSE_c (aListKeys
, "list-key", "@"),
380 ARGPARSE_c (aListChain
, "list-sig", "@"),
381 ARGPARSE_c (aListChain
, "list-sigs", "@"),
382 ARGPARSE_c (aListChain
, "check-sig", "@"),
383 ARGPARSE_c (aListChain
, "check-sigs", "@"),
384 ARGPARSE_c (aDeleteKey
, "delete-key", "@"),
392 /* Global variable to keep an error count. */
393 int gpgsm_errors_seen
= 0;
395 /* It is possible that we are currentlu running under setuid permissions */
396 static int maybe_setuid
= 1;
398 /* Helper to implement --debug-level and --debug*/
399 static const char *debug_level
;
400 static unsigned int debug_value
;
402 /* Option --enable-special-filenames */
403 static int allow_special_filenames
;
405 /* Default value for include-certs. */
406 static int default_include_certs
= 1; /* Only include the signer's cert. */
408 /* Whether the chain mode shall be used for validation. */
409 static int default_validation_model
;
412 static char *build_list (const char *text
,
413 const char *(*mapf
)(int), int (*chkf
)(int));
414 static void set_cmd (enum cmd_and_opt_values
*ret_cmd
,
415 enum cmd_and_opt_values new_cmd
);
417 static void emergency_cleanup (void);
418 static int check_special_filename (const char *fname
, int for_write
);
419 static int open_read (const char *filename
);
420 static estream_t
open_es_fread (const char *filename
);
421 static FILE *open_fwrite (const char *filename
);
422 static estream_t
open_es_fwrite (const char *filename
);
423 static void run_protect_tool (int argc
, char **argv
);
426 our_pk_test_algo (int algo
)
432 return gcry_pk_test_algo (algo
);
439 our_cipher_test_algo (int algo
)
443 case GCRY_CIPHER_3DES
:
444 case GCRY_CIPHER_AES128
:
445 case GCRY_CIPHER_AES192
:
446 case GCRY_CIPHER_AES256
:
447 case GCRY_CIPHER_SERPENT128
:
448 case GCRY_CIPHER_SERPENT192
:
449 case GCRY_CIPHER_SERPENT256
:
450 case GCRY_CIPHER_SEED
:
451 case GCRY_CIPHER_CAMELLIA128
:
452 case GCRY_CIPHER_CAMELLIA192
:
453 case GCRY_CIPHER_CAMELLIA256
:
454 return gcry_cipher_test_algo (algo
);
462 our_md_test_algo (int algo
)
473 case GCRY_MD_WHIRLPOOL
:
474 return gcry_md_test_algo (algo
);
482 make_libversion (const char *libname
, const char *(*getfnc
)(const char*))
489 gcry_control (GCRYCTL_INIT_SECMEM
, 0, 0); /* Drop setuid. */
493 result
= xmalloc (strlen (libname
) + 1 + strlen (s
) + 1);
494 strcpy (stpcpy (stpcpy (result
, libname
), " "), s
);
500 my_strusage( int level
)
502 static char *digests
, *pubkeys
, *ciphers
;
503 static char *ver_gcry
, *ver_ksba
;
508 case 11: p
= "gpgsm (GnuPG)";
510 case 13: p
= VERSION
; break;
511 case 17: p
= PRINTABLE_OS_NAME
; break;
512 case 19: p
= _("Please report bugs to <@EMAIL@>.\n"); break;
515 case 40: p
= _("Usage: gpgsm [options] [files] (-h for help)");
518 p
= _("Syntax: gpgsm [options] [files]\n"
519 "sign, check, encrypt or decrypt using the S/MIME protocol\n"
520 "default operation depends on the input data\n");
525 ver_gcry
= make_libversion ("libgcrypt", gcry_check_version
);
530 ver_ksba
= make_libversion ("libksba", ksba_check_version
);
534 case 31: p
= "\nHome: "; break;
535 case 32: p
= opt
.homedir
; break;
536 case 33: p
= _("\nSupported algorithms:\n"); break;
539 ciphers
= build_list ("Cipher: ", gcry_cipher_algo_name
,
540 our_cipher_test_algo
);
545 pubkeys
= build_list ("Pubkey: ", gcry_pk_algo_name
,
551 digests
= build_list("Hash: ", gcry_md_algo_name
, our_md_test_algo
);
555 default: p
= NULL
; break;
562 build_list (const char *text
, const char * (*mapf
)(int), int (*chkf
)(int))
565 size_t n
=strlen(text
)+2;
569 gcry_control (GCRYCTL_DROP_PRIVS
); /* drop setuid */
572 for (i
=1; i
< 400; i
++ )
574 n
+= strlen(mapf(i
)) + 2;
575 list
= xmalloc (21 + n
);
577 for (p
=NULL
, i
=1; i
< 400; i
++)
582 p
= stpcpy (list
, text
);
584 p
= stpcpy (p
, ", ");
585 p
= stpcpy (p
, mapf(i
) );
589 p
= stpcpy(p
, "\n" );
594 /* Set the file pointer into binary mode if required. */
596 set_binary (FILE *fp
)
598 #ifdef HAVE_DOSISH_SYSTEM
599 setmode (fileno (fp
), O_BINARY
);
608 wrong_args (const char *text
)
610 fputs (_("usage: gpgsm [options] "), stderr
);
611 fputs (text
, stderr
);
618 set_opt_session_env (const char *name
, const char *value
)
622 err
= session_env_setenv (opt
.session_env
, name
, value
);
624 log_fatal ("error setting session environment: %s\n",
629 /* Setup the debugging. With a DEBUG_LEVEL of NULL only the active
630 debug flags are propagated to the subsystems. With DEBUG_LEVEL
631 set, a specific set of debug flags is set; and individual debugging
632 flags will be added on top. */
638 else if (!strcmp (debug_level
, "none"))
640 else if (!strcmp (debug_level
, "basic"))
641 opt
.debug
= DBG_ASSUAN_VALUE
;
642 else if (!strcmp (debug_level
, "advanced"))
643 opt
.debug
= DBG_ASSUAN_VALUE
|DBG_X509_VALUE
;
644 else if (!strcmp (debug_level
, "expert"))
645 opt
.debug
= (DBG_ASSUAN_VALUE
|DBG_X509_VALUE
646 |DBG_CACHE_VALUE
|DBG_CRYPTO_VALUE
);
647 else if (!strcmp (debug_level
, "guru"))
651 log_error (_("invalid debug-level `%s' given\n"), debug_level
);
655 opt
.debug
|= debug_value
;
657 if (opt
.debug
&& !opt
.verbose
)
662 if (opt
.debug
& DBG_MPI_VALUE
)
663 gcry_control (GCRYCTL_SET_DEBUG_FLAGS
, 2);
664 if (opt
.debug
& DBG_CRYPTO_VALUE
)
665 gcry_control (GCRYCTL_SET_DEBUG_FLAGS
, 1);
666 gcry_control (GCRYCTL_SET_VERBOSITY
, (int)opt
.verbose
);
672 set_cmd (enum cmd_and_opt_values
*ret_cmd
, enum cmd_and_opt_values new_cmd
)
674 enum cmd_and_opt_values cmd
= *ret_cmd
;
676 if (!cmd
|| cmd
== new_cmd
)
678 else if ( cmd
== aSign
&& new_cmd
== aEncr
)
680 else if ( cmd
== aEncr
&& new_cmd
== aSign
)
682 else if ( (cmd
== aSign
&& new_cmd
== aClearsign
)
683 || (cmd
== aClearsign
&& new_cmd
== aSign
) )
687 log_error(_("conflicting commands\n"));
695 /* Helper to add recipients to a list. */
697 do_add_recipient (ctrl_t ctrl
, const char *name
,
698 certlist_t
*recplist
, int is_encrypt_to
, int recp_required
)
700 int rc
= gpgsm_add_to_certlist (ctrl
, name
, 0, recplist
, is_encrypt_to
);
705 log_error ("can't encrypt to `%s': %s\n", name
, gpg_strerror (rc
));
706 gpgsm_status2 (ctrl
, STATUS_INV_RECP
,
707 gpg_err_code (rc
) == -1? "1":
708 gpg_err_code (rc
) == GPG_ERR_NO_PUBKEY
? "1":
709 gpg_err_code (rc
) == GPG_ERR_AMBIGUOUS_NAME
? "2":
710 gpg_err_code (rc
) == GPG_ERR_WRONG_KEY_USAGE
? "3":
711 gpg_err_code (rc
) == GPG_ERR_CERT_REVOKED
? "4":
712 gpg_err_code (rc
) == GPG_ERR_CERT_EXPIRED
? "5":
713 gpg_err_code (rc
) == GPG_ERR_NO_CRL_KNOWN
? "6":
714 gpg_err_code (rc
) == GPG_ERR_CRL_TOO_OLD
? "7":
715 gpg_err_code (rc
) == GPG_ERR_NO_POLICY_MATCH
? "8":
720 log_info (_("NOTE: won't be able to encrypt to `%s': %s\n"),
721 name
, gpg_strerror (rc
));
727 parse_validation_model (const char *model
)
729 int i
= gpgsm_parse_validation_model (model
);
731 log_error (_("unknown validation model `%s'\n"), model
);
733 default_validation_model
= i
;
737 /* Release the list of SERVERS. As usual it is okay to call this
738 function with SERVERS passed as NULL. */
740 keyserver_list_free (struct keyserver_spec
*servers
)
744 struct keyserver_spec
*tmp
= servers
->next
;
745 xfree (servers
->host
);
746 xfree (servers
->user
);
748 memset (servers
->pass
, 0, strlen (servers
->pass
));
749 xfree (servers
->pass
);
750 xfree (servers
->base
);
756 /* See also dirmngr ldapserver_parse_one(). */
757 struct keyserver_spec
*
758 parse_keyserver_line (char *line
,
759 const char *filename
, unsigned int lineno
)
763 struct keyserver_spec
*server
;
767 /* Parse the colon separated fields. */
768 server
= xcalloc (1, sizeof *server
);
769 for (fieldno
= 1, p
= line
; p
; p
= endp
, fieldno
++ )
771 endp
= strchr (p
, ':');
779 server
->host
= xstrdup (p
);
782 log_error (_("%s:%u: no hostname given\n"),
790 server
->port
= atoi (p
);
795 server
->user
= xstrdup (p
);
799 if (*p
&& !server
->user
)
801 log_error (_("%s:%u: password given without user\n"),
806 server
->pass
= xstrdup (p
);
811 server
->base
= xstrdup (p
);
815 /* (We silently ignore extra fields.) */
822 log_info (_("%s:%u: skipping this line\n"), filename
, lineno
);
823 keyserver_list_free (server
);
831 main ( int argc
, char **argv
)
839 strlist_t sl
, remusr
= NULL
, locusr
=NULL
;
840 strlist_t nrings
=NULL
;
841 int detached_sig
= 0;
842 FILE *configfp
= NULL
;
843 char *configname
= NULL
;
844 unsigned configlineno
;
846 int no_more_options
= 0;
847 int default_config
=1;
848 int default_keyring
= 1;
849 char *logfile
= NULL
;
850 char *auditlog
= NULL
;
854 int use_random_seed
= 1;
855 int no_common_certs_import
= 0;
857 const char *forced_digest_algo
= NULL
;
858 const char *extra_digest_algo
= NULL
;
859 enum cmd_and_opt_values cmd
= 0;
860 struct server_control_s ctrl
;
861 certlist_t recplist
= NULL
;
862 certlist_t signerlist
= NULL
;
863 int do_not_setup_keys
= 0;
864 int recp_required
= 0;
865 estream_t auditfp
= NULL
;
869 gnupg_reopen_std ("gpgsm");
870 /* trap_unaligned ();*/
871 gnupg_rl_initialize ();
872 set_strusage (my_strusage
);
873 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN
);
874 /* We don't need any locking in libgcrypt unless we use any kind of
876 gcry_control (GCRYCTL_DISABLE_INTERNAL_LOCKING
);
878 /* Please note that we may running SUID(ROOT), so be very CAREFUL
879 when adding any stuff between here and the call to secmem_init()
880 somewhere after the option parsing */
881 log_set_prefix ("gpgsm", 1);
883 /* Make sure that our subsystems are ready. */
885 init_common_subsystems ();
887 /* Check that the libraries are suitable. Do it here because the
888 option parse may need services of the library */
889 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION
) )
890 log_fatal (_("%s is too old (need %s, have %s)\n"), "libgcrypt",
891 NEED_LIBGCRYPT_VERSION
, gcry_check_version (NULL
) );
892 if (!ksba_check_version (NEED_KSBA_VERSION
) )
893 log_fatal (_("%s is too old (need %s, have %s)\n"), "libksba",
894 NEED_KSBA_VERSION
, ksba_check_version (NULL
) );
897 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL
);
899 may_coredump
= disable_core_dumps ();
901 gnupg_init_signals (0, emergency_cleanup
);
903 create_dotlock (NULL
); /* register locking cleanup */
905 opt
.session_env
= session_env_new ();
906 if (!opt
.session_env
)
907 log_fatal ("error allocating session environment block: %s\n",
910 /* Note: If you change this default cipher algorithm , please
911 remember to update the Gpgconflist entry as well. */
912 opt
.def_cipher_algoid
= "3DES"; /*des-EDE3-CBC*/
914 opt
.homedir
= default_homedir ();
916 /* First check whether we have a config file on the commandline */
921 pargs
.flags
= 1|(1<<6); /* do not remove the args, ignore version */
922 while (arg_parse( &pargs
, opts
))
924 if (pargs
.r_opt
== oDebug
|| pargs
.r_opt
== oDebugAll
)
926 else if (pargs
.r_opt
== oOptions
)
927 { /* yes there is one, so we do not try the default one but
928 read the config file when it is encountered at the
932 else if (pargs
.r_opt
== oNoOptions
)
933 default_config
= 0; /* --no-options */
934 else if (pargs
.r_opt
== oHomedir
)
935 opt
.homedir
= pargs
.r
.ret_str
;
936 else if (pargs
.r_opt
== aCallProtectTool
)
937 break; /* This break makes sure that --version and --help are
938 passed to the protect-tool. */
942 /* Initialize the secure memory. */
943 gcry_control (GCRYCTL_INIT_SECMEM
, 16384, 0);
947 Now we are now working under our real uid
950 ksba_set_malloc_hooks (gcry_malloc
, gcry_realloc
, gcry_free
);
952 assuan_set_malloc_hooks (gcry_malloc
, gcry_realloc
, gcry_free
);
953 assuan_set_assuan_log_stream (log_get_stream ());
954 assuan_set_assuan_log_prefix (log_get_prefix (NULL
));
955 assuan_set_assuan_err_source (GPG_ERR_SOURCE_DEFAULT
);
957 keybox_set_malloc_hooks (gcry_malloc
, gcry_realloc
, gcry_free
);
959 /* Setup a default control structure for command line mode */
960 memset (&ctrl
, 0, sizeof ctrl
);
961 gpgsm_init_default_ctrl (&ctrl
);
963 ctrl
.status_fd
= -1; /* No status output. */
964 ctrl
.autodetect_encoding
= 1;
966 /* Set the default option file */
968 configname
= make_filename (opt
.homedir
, "gpgsm.conf", NULL
);
969 /* Set the default policy file */
970 opt
.policy_file
= make_filename (opt
.homedir
, "policies.txt", NULL
);
976 pargs
.flags
= 1; /* do not remove the args */
981 configfp
= fopen (configname
, "r");
987 log_info (_("NOTE: no default option file `%s'\n"), configname
);
991 log_error (_("option file `%s': %s\n"), configname
, strerror(errno
));
997 if (parse_debug
&& configname
)
998 log_info (_("reading options from `%s'\n"), configname
);
1002 while (!no_more_options
1003 && optfile_parse (configfp
, configname
, &configlineno
, &pargs
, opts
))
1005 switch (pargs
.r_opt
)
1009 set_cmd (&cmd
, pargs
.r_opt
);
1010 do_not_setup_keys
= 1;
1016 set_cmd (&cmd
, aServer
);
1021 set_cmd (&cmd
, aCallDirmngr
);
1022 do_not_setup_keys
= 1;
1025 case aCallProtectTool
:
1027 set_cmd (&cmd
, aCallProtectTool
);
1028 no_more_options
= 1; /* Stop parsing. */
1029 do_not_setup_keys
= 1;
1033 set_cmd (&cmd
, aDeleteKey
);
1035 do_not_setup_keys
= 1;
1040 set_cmd (&cmd
, aSign
);
1044 set_cmd (&cmd
, aKeygen
);
1046 do_not_setup_keys
= 1;
1053 case aExportSecretKeyP12
:
1056 case aDumpExternalKeys
:
1057 case aDumpSecretKeys
:
1059 case aListExternalKeys
:
1060 case aListSecretKeys
:
1064 case aKeydbClearSomeCertFlags
:
1065 do_not_setup_keys
= 1;
1066 set_cmd (&cmd
, pargs
.r_opt
);
1071 set_cmd (&cmd
, pargs
.r_opt
);
1079 set_cmd (&cmd
, pargs
.r_opt
);
1082 /* Output encoding selection. */
1084 ctrl
.create_pem
= 1;
1087 ctrl
.create_pem
= 0;
1088 ctrl
.create_base64
= 1;
1091 ctrl
.create_pem
= 0;
1092 ctrl
.create_base64
= 0;
1096 opt
.p12_charset
= pargs
.r
.ret_str
;
1099 /* Input encoding selection. */
1101 ctrl
.autodetect_encoding
= 0;
1106 ctrl
.autodetect_encoding
= 0;
1111 ctrl
.autodetect_encoding
= 0;
1116 case oDisableCRLChecks
:
1117 opt
.no_crl_check
= 1;
1119 case oEnableCRLChecks
:
1120 opt
.no_crl_check
= 0;
1122 case oDisableTrustedCertCRLCheck
:
1123 opt
.no_trusted_cert_crl_check
= 1;
1125 case oEnableTrustedCertCRLCheck
:
1126 opt
.no_trusted_cert_crl_check
= 0;
1128 case oForceCRLRefresh
:
1129 opt
.force_crl_refresh
= 1;
1133 ctrl
.use_ocsp
= opt
.enable_ocsp
= 0;
1136 ctrl
.use_ocsp
= opt
.enable_ocsp
= 1;
1140 ctrl
.include_certs
= default_include_certs
= pargs
.r
.ret_int
;
1144 xfree (opt
.policy_file
);
1145 if (*pargs
.r
.ret_str
)
1146 opt
.policy_file
= xstrdup (pargs
.r
.ret_str
);
1148 opt
.policy_file
= NULL
;
1151 case oDisablePolicyChecks
:
1152 opt
.no_policy_check
= 1;
1154 case oEnablePolicyChecks
:
1155 opt
.no_policy_check
= 0;
1158 case oAutoIssuerKeyRetrieve
:
1159 opt
.auto_issuer_key_retrieve
= 1;
1162 case oOutput
: opt
.outfile
= pargs
.r
.ret_str
; break;
1165 case oQuiet
: opt
.quiet
= 1; break;
1166 case oNoTTY
: /* fixme:tty_no_terminal(1);*/ break;
1167 case oDryRun
: opt
.dry_run
= 1; break;
1171 gcry_control (GCRYCTL_SET_VERBOSITY
, (int)opt
.verbose
);
1175 gcry_control (GCRYCTL_SET_VERBOSITY
, (int)opt
.verbose
);
1178 case oLogFile
: logfile
= pargs
.r
.ret_str
; break;
1179 case oNoLogFile
: logfile
= NULL
; break;
1181 case oAuditLog
: auditlog
= pargs
.r
.ret_str
; break;
1187 case oNoBatch
: opt
.batch
= 0; break;
1189 case oAnswerYes
: opt
.answer_yes
= 1; break;
1190 case oAnswerNo
: opt
.answer_no
= 1; break;
1192 case oKeyring
: append_to_strlist (&nrings
, pargs
.r
.ret_str
); break;
1194 case oDebug
: debug_value
|= pargs
.r
.ret_ulong
; break;
1195 case oDebugAll
: debug_value
= ~0; break;
1196 case oDebugNone
: debug_value
= 0; break;
1197 case oDebugLevel
: debug_level
= pargs
.r
.ret_str
; break;
1198 case oDebugWait
: debug_wait
= pargs
.r
.ret_int
; break;
1199 case oDebugAllowCoreDump
:
1200 may_coredump
= enable_core_dumps ();
1202 case oDebugNoChainValidation
: opt
.no_chain_validation
= 1; break;
1203 case oDebugIgnoreExpiration
: opt
.ignore_expiration
= 1; break;
1204 case oFixedPassphrase
: opt
.fixed_passphrase
= pargs
.r
.ret_str
; break;
1206 case oStatusFD
: ctrl
.status_fd
= pargs
.r
.ret_int
; break;
1207 case oLoggerFD
: log_set_fd (pargs
.r
.ret_int
); break;
1208 case oWithMD5Fingerprint
:
1209 opt
.with_md5_fingerprint
=1; /*fall thru*/
1210 case oWithFingerprint
:
1211 with_fpr
=1; /*fall thru*/
1217 /* config files may not be nested (silently ignore them) */
1221 configname
= xstrdup (pargs
.r
.ret_str
);
1225 case oNoOptions
: break; /* no-options */
1226 case oHomedir
: opt
.homedir
= pargs
.r
.ret_str
; break;
1227 case oAgentProgram
: opt
.agent_program
= pargs
.r
.ret_str
; break;
1230 set_opt_session_env ("DISPLAY", pargs
.r
.ret_str
);
1233 set_opt_session_env ("GPG_TTY", pargs
.r
.ret_str
);
1236 set_opt_session_env ("TERM", pargs
.r
.ret_str
);
1239 set_opt_session_env ("XAUTHORITY", pargs
.r
.ret_str
);
1242 case oLCctype
: opt
.lc_ctype
= xstrdup (pargs
.r
.ret_str
); break;
1243 case oLCmessages
: opt
.lc_messages
= xstrdup (pargs
.r
.ret_str
); break;
1245 case oDirmngrProgram
: opt
.dirmngr_program
= pargs
.r
.ret_str
; break;
1246 case oDisableDirmngr
: opt
.disable_dirmngr
= 1; break;
1247 case oPreferSystemDirmngr
: opt
.prefer_system_dirmngr
= 1; break;
1248 case oProtectToolProgram
:
1249 opt
.protect_tool_program
= pargs
.r
.ret_str
;
1252 case oFakedSystemTime
:
1254 time_t faked_time
= isotime2epoch (pargs
.r
.ret_str
);
1255 if (faked_time
== (time_t)(-1))
1256 faked_time
= (time_t)strtoul (pargs
.r
.ret_str
, NULL
, 10);
1257 gnupg_set_time (faked_time
, 0);
1261 case oNoDefKeyring
: default_keyring
= 0; break;
1262 case oNoGreeting
: nogreeting
= 1; break;
1265 if (*pargs
.r
.ret_str
)
1267 xfree (opt
.local_user
);
1268 opt
.local_user
= xstrdup (pargs
.r
.ret_str
);
1272 if (*pargs
.r
.ret_str
)
1273 opt
.def_recipient
= xstrdup (pargs
.r
.ret_str
);
1275 case oDefRecipientSelf
:
1276 xfree (opt
.def_recipient
);
1277 opt
.def_recipient
= NULL
;
1278 opt
.def_recipient_self
= 1;
1280 case oNoDefRecipient
:
1281 xfree (opt
.def_recipient
);
1282 opt
.def_recipient
= NULL
;
1283 opt
.def_recipient_self
= 0;
1286 case oWithKeyData
: opt
.with_key_data
=1; /* fall thru */
1287 case oWithColons
: ctrl
.with_colons
= 1; break;
1288 case oWithValidation
: ctrl
.with_validation
=1; break;
1289 case oWithEphemeralKeys
: ctrl
.with_ephemeral_keys
=1; break;
1291 case oSkipVerify
: opt
.skip_verify
=1; break;
1293 case oNoEncryptTo
: opt
.no_encrypt_to
= 1; break;
1294 case oEncryptTo
: /* Store the recipient in the second list */
1295 sl
= add_to_strlist (&remusr
, pargs
.r
.ret_str
);
1299 case oRecipient
: /* store the recipient */
1300 add_to_strlist ( &remusr
, pargs
.r
.ret_str
);
1303 case oUser
: /* Store the local users, the first one is the default */
1304 if (!opt
.local_user
)
1305 opt
.local_user
= xstrdup (pargs
.r
.ret_str
);
1306 add_to_strlist (&locusr
, pargs
.r
.ret_str
);
1310 gcry_control (GCRYCTL_DISABLE_SECMEM_WARN
);
1314 opt
.def_cipher_algoid
= pargs
.r
.ret_str
;
1317 case oDisableCipherAlgo
:
1319 int algo
= gcry_cipher_map_name (pargs
.r
.ret_str
);
1320 gcry_cipher_ctl (NULL
, GCRYCTL_DISABLE_ALGO
, &algo
, sizeof algo
);
1323 case oDisablePubkeyAlgo
:
1325 int algo
= gcry_pk_map_name (pargs
.r
.ret_str
);
1326 gcry_pk_ctl (GCRYCTL_DISABLE_ALGO
,&algo
, sizeof algo
);
1331 forced_digest_algo
= pargs
.r
.ret_str
;
1334 case oExtraDigestAlgo
:
1335 extra_digest_algo
= pargs
.r
.ret_str
;
1338 case oIgnoreTimeConflict
: opt
.ignore_time_conflict
= 1; break;
1339 case oNoRandomSeedFile
: use_random_seed
= 0; break;
1340 case oNoCommonCertsImport
: no_common_certs_import
= 1; break;
1342 case oEnableSpecialFilenames
: allow_special_filenames
=1; break;
1344 case oValidationModel
: parse_validation_model (pargs
.r
.ret_str
); break;
1348 struct keyserver_spec
*keyserver
;
1349 keyserver
= parse_keyserver_line (pargs
.r
.ret_str
,
1350 configname
, configlineno
);
1352 log_error (_("could not parse keyserver\n"));
1355 /* FIXME: Keep last next pointer. */
1356 struct keyserver_spec
**next_p
= &opt
.keyserver
;
1358 next_p
= &(*next_p
)->next
;
1359 *next_p
= keyserver
;
1365 pargs
.err
= configfp
? ARGPARSE_PRINT_WARNING
:ARGPARSE_PRINT_ERROR
;
1374 /* Keep a copy of the config filename. */
1375 opt
.config_filename
= configname
;
1382 if (!opt
.config_filename
)
1383 opt
.config_filename
= make_filename (opt
.homedir
, "gpgsm.conf", NULL
);
1385 if (log_get_errorcount(0))
1388 /* Now that we have the options parsed we need to update the default
1389 control structure. */
1390 gpgsm_init_default_ctrl (&ctrl
);
1397 fprintf(stderr
, "%s %s; %s\n",
1398 strusage(11), strusage(13), strusage(14) );
1399 fprintf(stderr
, "%s\n", strusage(15) );
1401 # ifdef IS_DEVELOPMENT_VERSION
1404 log_info ("NOTE: THIS IS A DEVELOPMENT VERSION!\n");
1405 log_info ("It is only intended for test purposes and should NOT be\n");
1406 log_info ("used in a production environment or with production keys!\n");
1411 log_info ("NOTE: The audit log feature (--audit-log) is "
1412 "WORK IN PRORESS and not ready for use!\n");
1415 if (may_coredump
&& !opt
.quiet
)
1416 log_info (_("WARNING: program may create a core file!\n"));
1418 /* if (opt.qualsig_approval && !opt.quiet) */
1419 /* log_info (_("This software has offically been approved to " */
1420 /* "create and verify\n" */
1421 /* "qualified signatures according to German law.\n")); */
1423 if (logfile
&& cmd
== aServer
)
1425 log_set_file (logfile
);
1426 log_set_prefix (NULL
, 1|2|4);
1429 if (gnupg_faked_time_p ())
1431 gnupg_isotime_t tbuf
;
1433 log_info (_("WARNING: running with faked system time: "));
1434 gnupg_get_isotime (tbuf
);
1435 dump_isotime (tbuf
);
1439 /*FIXME if (opt.batch) */
1440 /* tty_batchmode (1); */
1442 gcry_control (GCRYCTL_RESUME_SECMEM_WARN
);
1446 /* Although we alwasy use gpgsm_exit, we better install a regualr
1447 exit handler so that at least the secure memory gets wiped
1449 if (atexit (emergency_cleanup
))
1451 log_error ("atexit failed\n");
1455 /* Must do this after dropping setuid, because the mapping functions
1456 may try to load an module and we may have disabled an algorithm.
1457 We remap the commonly used algorithms to the OIDs for
1458 convenience. We need to work with the OIDs because they are used
1459 to check whether the encryption mode is actually available. */
1460 if (!strcmp (opt
.def_cipher_algoid
, "3DES") )
1461 opt
.def_cipher_algoid
= "1.2.840.113549.3.7";
1462 else if (!strcmp (opt
.def_cipher_algoid
, "AES")
1463 || !strcmp (opt
.def_cipher_algoid
, "AES128"))
1464 opt
.def_cipher_algoid
= "2.16.840.1.101.3.4.1.2";
1465 else if (!strcmp (opt
.def_cipher_algoid
, "AES256") )
1466 opt
.def_cipher_algoid
= "2.16.840.1.101.3.4.1.42";
1467 else if (!strcmp (opt
.def_cipher_algoid
, "SERPENT")
1468 || !strcmp (opt
.def_cipher_algoid
, "SERPENT128") )
1469 opt
.def_cipher_algoid
= "1.3.6.1.4.1.11591.13.2.2";
1470 else if (!strcmp (opt
.def_cipher_algoid
, "SERPENT192") )
1471 opt
.def_cipher_algoid
= "1.3.6.1.4.1.11591.13.2.22";
1472 else if (!strcmp (opt
.def_cipher_algoid
, "SERPENT192") )
1473 opt
.def_cipher_algoid
= "1.3.6.1.4.1.11591.13.2.42";
1474 else if (!strcmp (opt
.def_cipher_algoid
, "SEED") )
1475 opt
.def_cipher_algoid
= "1.2.410.200004.1.4";
1476 else if (!strcmp (opt
.def_cipher_algoid
, "CAMELLIA")
1477 || !strcmp (opt
.def_cipher_algoid
, "CAMELLIA128") )
1478 opt
.def_cipher_algoid
= "1.2.392.200011.61.1.1.1.2";
1479 else if (!strcmp (opt
.def_cipher_algoid
, "CAMELLIA192") )
1480 opt
.def_cipher_algoid
= "1.2.392.200011.61.1.1.1.3";
1481 else if (!strcmp (opt
.def_cipher_algoid
, "CAMELLIA256") )
1482 opt
.def_cipher_algoid
= "1.2.392.200011.61.1.1.1.4";
1484 if (cmd
!= aGPGConfList
)
1486 if ( !gcry_cipher_map_name (opt
.def_cipher_algoid
)
1487 || !gcry_cipher_mode_from_oid (opt
.def_cipher_algoid
))
1488 log_error (_("selected cipher algorithm is invalid\n"));
1490 if (forced_digest_algo
)
1492 opt
.forced_digest_algo
= gcry_md_map_name (forced_digest_algo
);
1493 if (our_md_test_algo(opt
.forced_digest_algo
) )
1494 log_error (_("selected digest algorithm is invalid\n"));
1496 if (extra_digest_algo
)
1498 opt
.extra_digest_algo
= gcry_md_map_name (extra_digest_algo
);
1499 if (our_md_test_algo (opt
.extra_digest_algo
) )
1500 log_error (_("selected digest algorithm is invalid\n"));
1504 if (log_get_errorcount(0))
1507 /* Set the random seed file. */
1508 if (use_random_seed
)
1510 char *p
= make_filename (opt
.homedir
, "random_seed", NULL
);
1511 gcry_control (GCRYCTL_SET_RANDOM_SEED_FILE
, p
);
1515 if (!cmd
&& opt
.fingerprint
&& !with_fpr
)
1516 set_cmd (&cmd
, aListKeys
);
1518 /* Add default keybox. */
1519 if (!nrings
&& default_keyring
)
1523 keydb_add_resource ("pubring.kbx", 0, 0, &created
);
1524 if (created
&& !no_common_certs_import
)
1526 /* Import the standard certificates for a new default keybox. */
1529 filelist
[0] = make_filename (gnupg_datadir (),"com-certs.pem", NULL
);
1531 if (!access (filelist
[0], F_OK
))
1533 log_info (_("importing common certificates `%s'\n"),
1535 gpgsm_import_files (&ctrl
, 1, filelist
, open_read
);
1537 xfree (filelist
[0]);
1540 for (sl
= nrings
; sl
; sl
= sl
->next
)
1541 keydb_add_resource (sl
->d
, 0, 0, NULL
);
1542 FREE_STRLIST(nrings
);
1545 /* Prepare the audit log feature for certain commands. */
1554 audit_release (ctrl
.audit
);
1555 ctrl
.audit
= audit_new ();
1556 auditfp
= open_es_fwrite (auditlog
);
1564 if (!do_not_setup_keys
)
1566 for (sl
= locusr
; sl
; sl
= sl
->next
)
1568 int rc
= gpgsm_add_to_certlist (&ctrl
, sl
->d
, 1, &signerlist
, 0);
1571 log_error (_("can't sign using `%s': %s\n"),
1572 sl
->d
, gpg_strerror (rc
));
1573 gpgsm_status2 (&ctrl
, STATUS_INV_RECP
,
1574 gpg_err_code (rc
) == -1? "1":
1575 gpg_err_code (rc
) == GPG_ERR_NO_PUBKEY
? "1":
1576 gpg_err_code (rc
) == GPG_ERR_AMBIGUOUS_NAME
? "2":
1577 gpg_err_code (rc
) == GPG_ERR_WRONG_KEY_USAGE
? "3":
1578 gpg_err_code (rc
) == GPG_ERR_CERT_REVOKED
? "4":
1579 gpg_err_code (rc
) == GPG_ERR_CERT_EXPIRED
? "5":
1580 gpg_err_code (rc
) == GPG_ERR_NO_CRL_KNOWN
? "6":
1581 gpg_err_code (rc
) == GPG_ERR_CRL_TOO_OLD
? "7":
1582 gpg_err_code (rc
) == GPG_ERR_NO_POLICY_MATCH
? "8":
1583 gpg_err_code (rc
) == GPG_ERR_NO_SECKEY
? "9":
1589 /* Build the recipient list. We first add the regular ones and then
1590 the encrypt-to ones because the underlying function will silently
1591 ignore duplicates and we can't allow to keep a duplicate which is
1592 flagged as encrypt-to as the actually encrypt function would then
1593 complain about no (regular) recipients. */
1594 for (sl
= remusr
; sl
; sl
= sl
->next
)
1595 if (!(sl
->flags
& 1))
1596 do_add_recipient (&ctrl
, sl
->d
, &recplist
, 0, recp_required
);
1597 if (!opt
.no_encrypt_to
)
1599 for (sl
= remusr
; sl
; sl
= sl
->next
)
1600 if ((sl
->flags
& 1))
1601 do_add_recipient (&ctrl
, sl
->d
, &recplist
, 1, recp_required
);
1605 if (log_get_errorcount(0))
1606 gpgsm_exit(1); /* Must stop for invalid recipients. */
1608 fname
= argc
? *argv
: NULL
;
1610 /* Dispatch command. */
1614 { /* List options and default values in the GPG Conf format. */
1615 char *config_filename_esc
= percent_escape (opt
.config_filename
, NULL
);
1617 printf ("gpgconf-gpgsm.conf:%lu:\"%s\n",
1618 GC_OPT_FLAG_DEFAULT
, config_filename_esc
);
1619 xfree (config_filename_esc
);
1621 printf ("verbose:%lu:\n", GC_OPT_FLAG_NONE
);
1622 printf ("quiet:%lu:\n", GC_OPT_FLAG_NONE
);
1623 printf ("debug-level:%lu:\"none:\n", GC_OPT_FLAG_DEFAULT
);
1624 printf ("log-file:%lu:\n", GC_OPT_FLAG_NONE
);
1625 printf ("disable-crl-checks:%lu:\n", GC_OPT_FLAG_NONE
);
1626 printf ("disable-trusted-cert-crl-check:%lu:\n", GC_OPT_FLAG_NONE
);
1627 printf ("enable-ocsp:%lu:\n", GC_OPT_FLAG_NONE
);
1628 printf ("include-certs:%lu:1:\n", GC_OPT_FLAG_DEFAULT
);
1629 printf ("disable-policy-checks:%lu:\n", GC_OPT_FLAG_NONE
);
1630 printf ("auto-issuer-key-retrieve:%lu:\n", GC_OPT_FLAG_NONE
);
1631 printf ("disable-dirmngr:%lu:\n", GC_OPT_FLAG_NONE
);
1632 #ifndef HAVE_W32_SYSTEM
1633 printf ("prefer-system-dirmngr:%lu:\n", GC_OPT_FLAG_NONE
);
1635 printf ("cipher-algo:%lu:\"3DES:\n", GC_OPT_FLAG_DEFAULT
);
1636 printf ("p12-charset:%lu:\n", GC_OPT_FLAG_DEFAULT
);
1637 printf ("default-key:%lu:\n", GC_OPT_FLAG_DEFAULT
);
1638 printf ("encrypt-to:%lu:\n", GC_OPT_FLAG_DEFAULT
);
1639 printf ("keyserver:%lu:\n", GC_OPT_FLAG_NONE
);
1644 /* This is merely a dummy command to test whether the
1645 configuration file is valid. */
1651 log_debug ("waiting for debugger - my pid is %u .....\n",
1652 (unsigned int)getpid());
1653 gnupg_sleep (debug_wait
);
1654 log_debug ("... okay\n");
1656 gpgsm_server (recplist
);
1661 wrong_args ("--call-dirmngr <command> {args}");
1663 if (gpgsm_dirmngr_run_command (&ctrl
, *argv
, argc
-1, argv
+1))
1667 case aCallProtectTool
:
1668 run_protect_tool (argc
, argv
);
1671 case aEncr
: /* Encrypt the given file. */
1673 FILE *fp
= open_fwrite (opt
.outfile
?opt
.outfile
:"-");
1677 if (!argc
) /* Source is stdin. */
1678 gpgsm_encrypt (&ctrl
, recplist
, 0, fp
);
1679 else if (argc
== 1) /* Source is the given file. */
1680 gpgsm_encrypt (&ctrl
, recplist
, open_read (*argv
), fp
);
1682 wrong_args ("--encrypt [datafile]");
1689 case aSign
: /* Sign the given file. */
1691 FILE *fp
= open_fwrite (opt
.outfile
?opt
.outfile
:"-");
1693 /* Fixme: We should also allow to concatenate multiple files for
1694 signing because that is what gpg does.*/
1696 if (!argc
) /* Create from stdin. */
1697 gpgsm_sign (&ctrl
, signerlist
, 0, detached_sig
, fp
);
1698 else if (argc
== 1) /* From file. */
1699 gpgsm_sign (&ctrl
, signerlist
,
1700 open_read (*argv
), detached_sig
, fp
);
1702 wrong_args ("--sign [datafile]");
1709 case aSignEncr
: /* sign and encrypt the given file */
1710 log_error ("this command has not yet been implemented\n");
1713 case aClearsign
: /* make a clearsig */
1714 log_error ("this command has not yet been implemented\n");
1722 if (argc
== 2 && opt
.outfile
)
1723 log_info ("option --output ignored for a detached signature\n");
1724 else if (opt
.outfile
)
1725 fp
= open_fwrite (opt
.outfile
);
1728 gpgsm_verify (&ctrl
, 0, -1, fp
); /* normal signature from stdin */
1730 gpgsm_verify (&ctrl
, open_read (*argv
), -1, fp
); /* std signature */
1731 else if (argc
== 2) /* detached signature (sig, detached) */
1732 gpgsm_verify (&ctrl
, open_read (*argv
), open_read (argv
[1]), NULL
);
1734 wrong_args ("--verify [signature [detached_data]]");
1736 if (fp
&& fp
!= stdout
)
1743 FILE *fp
= open_fwrite (opt
.outfile
?opt
.outfile
:"-");
1747 gpgsm_decrypt (&ctrl
, 0, fp
); /* from stdin */
1749 gpgsm_decrypt (&ctrl
, open_read (*argv
), fp
); /* from file */
1751 wrong_args ("--decrypt [filename]");
1758 for (sl
=NULL
; argc
; argc
--, argv
++)
1759 add_to_strlist (&sl
, *argv
);
1760 gpgsm_delete (&ctrl
, sl
);
1766 ctrl
.with_chain
= 1;
1769 case aListExternalKeys
:
1770 case aDumpExternalKeys
:
1771 case aListSecretKeys
:
1772 case aDumpSecretKeys
:
1780 case aListKeys
: mode
= (0 | 0 | (1<<6)); break;
1782 case aDumpKeys
: mode
= (256 | 0 | (1<<6)); break;
1783 case aListExternalKeys
: mode
= (0 | 0 | (1<<7)); break;
1784 case aDumpExternalKeys
: mode
= (256 | 0 | (1<<7)); break;
1785 case aListSecretKeys
: mode
= (0 | 2 | (1<<6)); break;
1786 case aDumpSecretKeys
: mode
= (256 | 2 | (1<<6)); break;
1790 fp
= open_es_fwrite (opt
.outfile
?opt
.outfile
:"-");
1791 for (sl
=NULL
; argc
; argc
--, argv
++)
1792 add_to_strlist (&sl
, *argv
);
1793 gpgsm_list_keys (&ctrl
, sl
, fp
, mode
);
1800 case aKeygen
: /* Generate a key; well kind of. */
1802 estream_t fpin
= NULL
;
1807 if (!argc
) /* Create from stdin. */
1808 fpin
= open_es_fread ("-");
1809 else if (argc
== 1) /* From file. */
1810 fpin
= open_es_fread (*argv
);
1812 wrong_args ("--gen-key --batch [parmfile]");
1815 fpout
= open_fwrite (opt
.outfile
?opt
.outfile
:"-");
1818 gpgsm_genkey (&ctrl
, fpin
, fpout
);
1820 gpgsm_gencertreq_tty (&ctrl
, fpout
);
1822 if (fpout
!= stdout
)
1829 gpgsm_import_files (&ctrl
, argc
, argv
, open_read
);
1834 FILE *fp
= open_fwrite (opt
.outfile
?opt
.outfile
:"-");
1836 for (sl
=NULL
; argc
; argc
--, argv
++)
1837 add_to_strlist (&sl
, *argv
);
1838 gpgsm_export (&ctrl
, sl
, fp
, NULL
);
1845 case aExportSecretKeyP12
:
1847 FILE *fp
= open_fwrite (opt
.outfile
?opt
.outfile
:"-");
1850 gpgsm_p12_export (&ctrl
, *argv
, fp
);
1852 wrong_args ("--export-secret-key-p12 KEY-ID");
1860 log_error ("this command has not yet been implemented\n");
1866 wrong_args ("--learn-card");
1869 int rc
= gpgsm_agent_learn (&ctrl
);
1871 log_error ("error learning card: %s\n", gpg_strerror (rc
));
1877 wrong_args ("--passwd <key-Id>");
1881 ksba_cert_t cert
= NULL
;
1884 rc
= gpgsm_find_cert (*argv
, NULL
, &cert
);
1887 else if (!(grip
= gpgsm_get_keygrip_hexstring (cert
)))
1888 rc
= gpg_error (GPG_ERR_BUG
);
1891 char *desc
= gpgsm_format_keydesc (cert
);
1892 rc
= gpgsm_agent_passwd (&ctrl
, grip
, desc
);
1896 log_error ("error changing passphrase: %s\n", gpg_strerror (rc
));
1898 ksba_cert_release (cert
);
1902 case aKeydbClearSomeCertFlags
:
1903 for (sl
=NULL
; argc
; argc
--, argv
++)
1904 add_to_strlist (&sl
, *argv
);
1905 keydb_clear_some_cert_flags (&ctrl
, sl
);
1911 log_error (_("invalid command (there is no implicit command)\n"));
1915 /* Print the audit result if needed. */
1916 if (auditlog
&& auditfp
)
1918 audit_print_result (ctrl
.audit
, auditfp
, 0);
1919 audit_release (ctrl
.audit
);
1921 es_fclose (auditfp
);
1925 keyserver_list_free (opt
.keyserver
);
1926 opt
.keyserver
= NULL
;
1927 gpgsm_release_certlist (recplist
);
1928 gpgsm_release_certlist (signerlist
);
1929 FREE_STRLIST (remusr
);
1930 FREE_STRLIST (locusr
);
1932 return 8; /*NOTREACHED*/
1935 /* Note: This function is used by signal handlers!. */
1937 emergency_cleanup (void)
1939 gcry_control (GCRYCTL_TERM_SECMEM
);
1946 gcry_control (GCRYCTL_UPDATE_RANDOM_SEED_FILE
);
1947 if (opt
.debug
& DBG_MEMSTAT_VALUE
)
1949 gcry_control( GCRYCTL_DUMP_MEMORY_STATS
);
1950 gcry_control( GCRYCTL_DUMP_RANDOM_STATS
);
1953 gcry_control (GCRYCTL_DUMP_SECMEM_STATS
);
1954 emergency_cleanup ();
1955 rc
= rc
? rc
: log_get_errorcount(0)? 2 : gpgsm_errors_seen
? 1 : 0;
1961 gpgsm_init_default_ctrl (struct server_control_s
*ctrl
)
1963 ctrl
->include_certs
= default_include_certs
;
1964 ctrl
->use_ocsp
= opt
.enable_ocsp
;
1965 ctrl
->validation_model
= default_validation_model
;
1970 gpgsm_parse_validation_model (const char *model
)
1972 if (!ascii_strcasecmp (model
, "shell") )
1974 else if ( !ascii_strcasecmp (model
, "chain") )
1981 /* Check whether the filename has the form "-&nnnn", where n is a
1982 non-zero number. Returns this number or -1 if it is not the case. */
1984 check_special_filename (const char *fname
, int for_write
)
1986 if (allow_special_filenames
1987 && fname
&& *fname
== '-' && fname
[1] == '&' ) {
1991 for (i
=0; isdigit (fname
[i
]); i
++ )
1994 return translate_sys2libc_fd_int (atoi (fname
), for_write
);
2001 /* Open the FILENAME for read and return the filedescriptor. Stop
2002 with an error message in case of problems. "-" denotes stdin and
2003 if special filenames are allowed the given fd is opened instead. */
2005 open_read (const char *filename
)
2009 if (filename
[0] == '-' && !filename
[1])
2012 return 0; /* stdin */
2014 fd
= check_special_filename (filename
, 0);
2017 fd
= open (filename
, O_RDONLY
| O_BINARY
);
2020 log_error (_("can't open `%s': %s\n"), filename
, strerror (errno
));
2026 /* Same as open_read but return an estream_t. */
2028 open_es_fread (const char *filename
)
2033 if (filename
[0] == '-' && !filename
[1])
2034 fd
= fileno (stdin
);
2036 fd
= check_special_filename (filename
, 0);
2039 fp
= es_fdopen_nc (fd
, "rb");
2042 log_error ("es_fdopen(%d) failed: %s\n", fd
, strerror (errno
));
2047 fp
= es_fopen (filename
, "rb");
2050 log_error (_("can't open `%s': %s\n"), filename
, strerror (errno
));
2057 /* Open FILENAME for fwrite and return the stream. Stop with an error
2058 message in case of problems. "-" denotes stdout and if special
2059 filenames are allowed the given fd is opened instead. Caller must
2060 close the returned stream unless it is stdout. */
2062 open_fwrite (const char *filename
)
2067 if (filename
[0] == '-' && !filename
[1])
2069 set_binary (stdout
);
2073 fd
= check_special_filename (filename
, 1);
2076 fp
= fdopen (dup (fd
), "wb");
2079 log_error ("fdopen(%d) failed: %s\n", fd
, strerror (errno
));
2085 fp
= fopen (filename
, "wb");
2088 log_error (_("can't open `%s': %s\n"), filename
, strerror (errno
));
2095 /* Open FILENAME for fwrite and return an extended stream. Stop with
2096 an error message in case of problems. "-" denotes stdout and if
2097 special filenames are allowed the given fd is opened instead.
2098 Caller must close the returned stream. */
2100 open_es_fwrite (const char *filename
)
2105 if (filename
[0] == '-' && !filename
[1])
2108 fp
= es_fdopen_nc (fileno(stdout
), "wb");
2112 fd
= check_special_filename (filename
, 1);
2115 fp
= es_fdopen_nc (fd
, "wb");
2118 log_error ("es_fdopen(%d) failed: %s\n", fd
, strerror (errno
));
2123 fp
= es_fopen (filename
, "wb");
2126 log_error (_("can't open `%s': %s\n"), filename
, strerror (errno
));
2134 run_protect_tool (int argc
, char **argv
)
2136 #ifndef HAVE_W32_SYSTEM
2141 if (!opt
.protect_tool_program
|| !*opt
.protect_tool_program
)
2142 pgm
= gnupg_module_name (GNUPG_MODULE_NAME_PROTECT_TOOL
);
2144 pgm
= opt
.protect_tool_program
;
2146 av
= xcalloc (argc
+2, sizeof *av
);
2147 av
[0] = strrchr (pgm
, '/');
2149 av
[0] = xstrdup (pgm
);
2150 for (i
=1; argc
; i
++, argc
--, argv
++)
2154 log_error ("error executing `%s': %s\n", pgm
, strerror (errno
));
2155 #endif /*HAVE_W32_SYSTEM*/