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 get_inv_recpsgnr_code (rc
), name
, NULL
);
710 log_info (_("NOTE: won't be able to encrypt to `%s': %s\n"),
711 name
, gpg_strerror (rc
));
717 parse_validation_model (const char *model
)
719 int i
= gpgsm_parse_validation_model (model
);
721 log_error (_("unknown validation model `%s'\n"), model
);
723 default_validation_model
= i
;
727 /* Release the list of SERVERS. As usual it is okay to call this
728 function with SERVERS passed as NULL. */
730 keyserver_list_free (struct keyserver_spec
*servers
)
734 struct keyserver_spec
*tmp
= servers
->next
;
735 xfree (servers
->host
);
736 xfree (servers
->user
);
738 memset (servers
->pass
, 0, strlen (servers
->pass
));
739 xfree (servers
->pass
);
740 xfree (servers
->base
);
746 /* See also dirmngr ldapserver_parse_one(). */
747 struct keyserver_spec
*
748 parse_keyserver_line (char *line
,
749 const char *filename
, unsigned int lineno
)
753 struct keyserver_spec
*server
;
757 /* Parse the colon separated fields. */
758 server
= xcalloc (1, sizeof *server
);
759 for (fieldno
= 1, p
= line
; p
; p
= endp
, fieldno
++ )
761 endp
= strchr (p
, ':');
769 server
->host
= xstrdup (p
);
772 log_error (_("%s:%u: no hostname given\n"),
780 server
->port
= atoi (p
);
785 server
->user
= xstrdup (p
);
789 if (*p
&& !server
->user
)
791 log_error (_("%s:%u: password given without user\n"),
796 server
->pass
= xstrdup (p
);
801 server
->base
= xstrdup (p
);
805 /* (We silently ignore extra fields.) */
812 log_info (_("%s:%u: skipping this line\n"), filename
, lineno
);
813 keyserver_list_free (server
);
821 main ( int argc
, char **argv
)
829 strlist_t sl
, remusr
= NULL
, locusr
=NULL
;
830 strlist_t nrings
=NULL
;
831 int detached_sig
= 0;
832 FILE *configfp
= NULL
;
833 char *configname
= NULL
;
834 unsigned configlineno
;
836 int no_more_options
= 0;
837 int default_config
=1;
838 int default_keyring
= 1;
839 char *logfile
= NULL
;
840 char *auditlog
= NULL
;
844 int use_random_seed
= 1;
845 int no_common_certs_import
= 0;
847 const char *forced_digest_algo
= NULL
;
848 const char *extra_digest_algo
= NULL
;
849 enum cmd_and_opt_values cmd
= 0;
850 struct server_control_s ctrl
;
851 certlist_t recplist
= NULL
;
852 certlist_t signerlist
= NULL
;
853 int do_not_setup_keys
= 0;
854 int recp_required
= 0;
855 estream_t auditfp
= NULL
;
859 gnupg_reopen_std ("gpgsm");
860 /* trap_unaligned ();*/
861 gnupg_rl_initialize ();
862 set_strusage (my_strusage
);
863 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN
);
864 /* We don't need any locking in libgcrypt unless we use any kind of
866 gcry_control (GCRYCTL_DISABLE_INTERNAL_LOCKING
);
868 /* Please note that we may running SUID(ROOT), so be very CAREFUL
869 when adding any stuff between here and the call to secmem_init()
870 somewhere after the option parsing */
871 log_set_prefix ("gpgsm", 1);
873 /* Make sure that our subsystems are ready. */
875 init_common_subsystems ();
877 /* Check that the libraries are suitable. Do it here because the
878 option parse may need services of the library */
879 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION
) )
880 log_fatal (_("%s is too old (need %s, have %s)\n"), "libgcrypt",
881 NEED_LIBGCRYPT_VERSION
, gcry_check_version (NULL
) );
882 if (!ksba_check_version (NEED_KSBA_VERSION
) )
883 log_fatal (_("%s is too old (need %s, have %s)\n"), "libksba",
884 NEED_KSBA_VERSION
, ksba_check_version (NULL
) );
887 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL
);
889 may_coredump
= disable_core_dumps ();
891 gnupg_init_signals (0, emergency_cleanup
);
893 create_dotlock (NULL
); /* register locking cleanup */
895 opt
.session_env
= session_env_new ();
896 if (!opt
.session_env
)
897 log_fatal ("error allocating session environment block: %s\n",
900 /* Note: If you change this default cipher algorithm , please
901 remember to update the Gpgconflist entry as well. */
902 opt
.def_cipher_algoid
= "3DES"; /*des-EDE3-CBC*/
904 opt
.homedir
= default_homedir ();
906 /* First check whether we have a config file on the commandline */
911 pargs
.flags
= 1|(1<<6); /* do not remove the args, ignore version */
912 while (arg_parse( &pargs
, opts
))
914 if (pargs
.r_opt
== oDebug
|| pargs
.r_opt
== oDebugAll
)
916 else if (pargs
.r_opt
== oOptions
)
917 { /* yes there is one, so we do not try the default one but
918 read the config file when it is encountered at the
922 else if (pargs
.r_opt
== oNoOptions
)
923 default_config
= 0; /* --no-options */
924 else if (pargs
.r_opt
== oHomedir
)
925 opt
.homedir
= pargs
.r
.ret_str
;
926 else if (pargs
.r_opt
== aCallProtectTool
)
927 break; /* This break makes sure that --version and --help are
928 passed to the protect-tool. */
932 /* Initialize the secure memory. */
933 gcry_control (GCRYCTL_INIT_SECMEM
, 16384, 0);
937 Now we are now working under our real uid
940 ksba_set_malloc_hooks (gcry_malloc
, gcry_realloc
, gcry_free
);
942 assuan_set_malloc_hooks (gcry_malloc
, gcry_realloc
, gcry_free
);
943 assuan_set_assuan_log_stream (log_get_stream ());
944 assuan_set_assuan_log_prefix (log_get_prefix (NULL
));
945 assuan_set_assuan_err_source (GPG_ERR_SOURCE_DEFAULT
);
947 keybox_set_malloc_hooks (gcry_malloc
, gcry_realloc
, gcry_free
);
949 /* Setup a default control structure for command line mode */
950 memset (&ctrl
, 0, sizeof ctrl
);
951 gpgsm_init_default_ctrl (&ctrl
);
953 ctrl
.status_fd
= -1; /* No status output. */
954 ctrl
.autodetect_encoding
= 1;
956 /* Set the default option file */
958 configname
= make_filename (opt
.homedir
, "gpgsm.conf", NULL
);
959 /* Set the default policy file */
960 opt
.policy_file
= make_filename (opt
.homedir
, "policies.txt", NULL
);
966 pargs
.flags
= 1; /* do not remove the args */
971 configfp
= fopen (configname
, "r");
977 log_info (_("NOTE: no default option file `%s'\n"), configname
);
981 log_error (_("option file `%s': %s\n"), configname
, strerror(errno
));
987 if (parse_debug
&& configname
)
988 log_info (_("reading options from `%s'\n"), configname
);
992 while (!no_more_options
993 && optfile_parse (configfp
, configname
, &configlineno
, &pargs
, opts
))
999 set_cmd (&cmd
, pargs
.r_opt
);
1000 do_not_setup_keys
= 1;
1006 set_cmd (&cmd
, aServer
);
1011 set_cmd (&cmd
, aCallDirmngr
);
1012 do_not_setup_keys
= 1;
1015 case aCallProtectTool
:
1017 set_cmd (&cmd
, aCallProtectTool
);
1018 no_more_options
= 1; /* Stop parsing. */
1019 do_not_setup_keys
= 1;
1023 set_cmd (&cmd
, aDeleteKey
);
1025 do_not_setup_keys
= 1;
1030 set_cmd (&cmd
, aSign
);
1034 set_cmd (&cmd
, aKeygen
);
1036 do_not_setup_keys
= 1;
1043 case aExportSecretKeyP12
:
1046 case aDumpExternalKeys
:
1047 case aDumpSecretKeys
:
1049 case aListExternalKeys
:
1050 case aListSecretKeys
:
1054 case aKeydbClearSomeCertFlags
:
1055 do_not_setup_keys
= 1;
1056 set_cmd (&cmd
, pargs
.r_opt
);
1061 set_cmd (&cmd
, pargs
.r_opt
);
1069 set_cmd (&cmd
, pargs
.r_opt
);
1072 /* Output encoding selection. */
1074 ctrl
.create_pem
= 1;
1077 ctrl
.create_pem
= 0;
1078 ctrl
.create_base64
= 1;
1081 ctrl
.create_pem
= 0;
1082 ctrl
.create_base64
= 0;
1086 opt
.p12_charset
= pargs
.r
.ret_str
;
1089 /* Input encoding selection. */
1091 ctrl
.autodetect_encoding
= 0;
1096 ctrl
.autodetect_encoding
= 0;
1101 ctrl
.autodetect_encoding
= 0;
1106 case oDisableCRLChecks
:
1107 opt
.no_crl_check
= 1;
1109 case oEnableCRLChecks
:
1110 opt
.no_crl_check
= 0;
1112 case oDisableTrustedCertCRLCheck
:
1113 opt
.no_trusted_cert_crl_check
= 1;
1115 case oEnableTrustedCertCRLCheck
:
1116 opt
.no_trusted_cert_crl_check
= 0;
1118 case oForceCRLRefresh
:
1119 opt
.force_crl_refresh
= 1;
1123 ctrl
.use_ocsp
= opt
.enable_ocsp
= 0;
1126 ctrl
.use_ocsp
= opt
.enable_ocsp
= 1;
1130 ctrl
.include_certs
= default_include_certs
= pargs
.r
.ret_int
;
1134 xfree (opt
.policy_file
);
1135 if (*pargs
.r
.ret_str
)
1136 opt
.policy_file
= xstrdup (pargs
.r
.ret_str
);
1138 opt
.policy_file
= NULL
;
1141 case oDisablePolicyChecks
:
1142 opt
.no_policy_check
= 1;
1144 case oEnablePolicyChecks
:
1145 opt
.no_policy_check
= 0;
1148 case oAutoIssuerKeyRetrieve
:
1149 opt
.auto_issuer_key_retrieve
= 1;
1152 case oOutput
: opt
.outfile
= pargs
.r
.ret_str
; break;
1155 case oQuiet
: opt
.quiet
= 1; break;
1156 case oNoTTY
: /* fixme:tty_no_terminal(1);*/ break;
1157 case oDryRun
: opt
.dry_run
= 1; break;
1161 gcry_control (GCRYCTL_SET_VERBOSITY
, (int)opt
.verbose
);
1165 gcry_control (GCRYCTL_SET_VERBOSITY
, (int)opt
.verbose
);
1168 case oLogFile
: logfile
= pargs
.r
.ret_str
; break;
1169 case oNoLogFile
: logfile
= NULL
; break;
1171 case oAuditLog
: auditlog
= pargs
.r
.ret_str
; break;
1177 case oNoBatch
: opt
.batch
= 0; break;
1179 case oAnswerYes
: opt
.answer_yes
= 1; break;
1180 case oAnswerNo
: opt
.answer_no
= 1; break;
1182 case oKeyring
: append_to_strlist (&nrings
, pargs
.r
.ret_str
); break;
1184 case oDebug
: debug_value
|= pargs
.r
.ret_ulong
; break;
1185 case oDebugAll
: debug_value
= ~0; break;
1186 case oDebugNone
: debug_value
= 0; break;
1187 case oDebugLevel
: debug_level
= pargs
.r
.ret_str
; break;
1188 case oDebugWait
: debug_wait
= pargs
.r
.ret_int
; break;
1189 case oDebugAllowCoreDump
:
1190 may_coredump
= enable_core_dumps ();
1192 case oDebugNoChainValidation
: opt
.no_chain_validation
= 1; break;
1193 case oDebugIgnoreExpiration
: opt
.ignore_expiration
= 1; break;
1194 case oFixedPassphrase
: opt
.fixed_passphrase
= pargs
.r
.ret_str
; break;
1196 case oStatusFD
: ctrl
.status_fd
= pargs
.r
.ret_int
; break;
1197 case oLoggerFD
: log_set_fd (pargs
.r
.ret_int
); break;
1198 case oWithMD5Fingerprint
:
1199 opt
.with_md5_fingerprint
=1; /*fall thru*/
1200 case oWithFingerprint
:
1201 with_fpr
=1; /*fall thru*/
1207 /* config files may not be nested (silently ignore them) */
1211 configname
= xstrdup (pargs
.r
.ret_str
);
1215 case oNoOptions
: break; /* no-options */
1216 case oHomedir
: opt
.homedir
= pargs
.r
.ret_str
; break;
1217 case oAgentProgram
: opt
.agent_program
= pargs
.r
.ret_str
; break;
1220 set_opt_session_env ("DISPLAY", pargs
.r
.ret_str
);
1223 set_opt_session_env ("GPG_TTY", pargs
.r
.ret_str
);
1226 set_opt_session_env ("TERM", pargs
.r
.ret_str
);
1229 set_opt_session_env ("XAUTHORITY", pargs
.r
.ret_str
);
1232 case oLCctype
: opt
.lc_ctype
= xstrdup (pargs
.r
.ret_str
); break;
1233 case oLCmessages
: opt
.lc_messages
= xstrdup (pargs
.r
.ret_str
); break;
1235 case oDirmngrProgram
: opt
.dirmngr_program
= pargs
.r
.ret_str
; break;
1236 case oDisableDirmngr
: opt
.disable_dirmngr
= 1; break;
1237 case oPreferSystemDirmngr
: opt
.prefer_system_dirmngr
= 1; break;
1238 case oProtectToolProgram
:
1239 opt
.protect_tool_program
= pargs
.r
.ret_str
;
1242 case oFakedSystemTime
:
1244 time_t faked_time
= isotime2epoch (pargs
.r
.ret_str
);
1245 if (faked_time
== (time_t)(-1))
1246 faked_time
= (time_t)strtoul (pargs
.r
.ret_str
, NULL
, 10);
1247 gnupg_set_time (faked_time
, 0);
1251 case oNoDefKeyring
: default_keyring
= 0; break;
1252 case oNoGreeting
: nogreeting
= 1; break;
1255 if (*pargs
.r
.ret_str
)
1257 xfree (opt
.local_user
);
1258 opt
.local_user
= xstrdup (pargs
.r
.ret_str
);
1262 if (*pargs
.r
.ret_str
)
1263 opt
.def_recipient
= xstrdup (pargs
.r
.ret_str
);
1265 case oDefRecipientSelf
:
1266 xfree (opt
.def_recipient
);
1267 opt
.def_recipient
= NULL
;
1268 opt
.def_recipient_self
= 1;
1270 case oNoDefRecipient
:
1271 xfree (opt
.def_recipient
);
1272 opt
.def_recipient
= NULL
;
1273 opt
.def_recipient_self
= 0;
1276 case oWithKeyData
: opt
.with_key_data
=1; /* fall thru */
1277 case oWithColons
: ctrl
.with_colons
= 1; break;
1278 case oWithValidation
: ctrl
.with_validation
=1; break;
1279 case oWithEphemeralKeys
: ctrl
.with_ephemeral_keys
=1; break;
1281 case oSkipVerify
: opt
.skip_verify
=1; break;
1283 case oNoEncryptTo
: opt
.no_encrypt_to
= 1; break;
1284 case oEncryptTo
: /* Store the recipient in the second list */
1285 sl
= add_to_strlist (&remusr
, pargs
.r
.ret_str
);
1289 case oRecipient
: /* store the recipient */
1290 add_to_strlist ( &remusr
, pargs
.r
.ret_str
);
1293 case oUser
: /* Store the local users, the first one is the default */
1294 if (!opt
.local_user
)
1295 opt
.local_user
= xstrdup (pargs
.r
.ret_str
);
1296 add_to_strlist (&locusr
, pargs
.r
.ret_str
);
1300 gcry_control (GCRYCTL_DISABLE_SECMEM_WARN
);
1304 opt
.def_cipher_algoid
= pargs
.r
.ret_str
;
1307 case oDisableCipherAlgo
:
1309 int algo
= gcry_cipher_map_name (pargs
.r
.ret_str
);
1310 gcry_cipher_ctl (NULL
, GCRYCTL_DISABLE_ALGO
, &algo
, sizeof algo
);
1313 case oDisablePubkeyAlgo
:
1315 int algo
= gcry_pk_map_name (pargs
.r
.ret_str
);
1316 gcry_pk_ctl (GCRYCTL_DISABLE_ALGO
,&algo
, sizeof algo
);
1321 forced_digest_algo
= pargs
.r
.ret_str
;
1324 case oExtraDigestAlgo
:
1325 extra_digest_algo
= pargs
.r
.ret_str
;
1328 case oIgnoreTimeConflict
: opt
.ignore_time_conflict
= 1; break;
1329 case oNoRandomSeedFile
: use_random_seed
= 0; break;
1330 case oNoCommonCertsImport
: no_common_certs_import
= 1; break;
1332 case oEnableSpecialFilenames
: allow_special_filenames
=1; break;
1334 case oValidationModel
: parse_validation_model (pargs
.r
.ret_str
); break;
1338 struct keyserver_spec
*keyserver
;
1339 keyserver
= parse_keyserver_line (pargs
.r
.ret_str
,
1340 configname
, configlineno
);
1342 log_error (_("could not parse keyserver\n"));
1345 /* FIXME: Keep last next pointer. */
1346 struct keyserver_spec
**next_p
= &opt
.keyserver
;
1348 next_p
= &(*next_p
)->next
;
1349 *next_p
= keyserver
;
1355 pargs
.err
= configfp
? ARGPARSE_PRINT_WARNING
:ARGPARSE_PRINT_ERROR
;
1364 /* Keep a copy of the config filename. */
1365 opt
.config_filename
= configname
;
1372 if (!opt
.config_filename
)
1373 opt
.config_filename
= make_filename (opt
.homedir
, "gpgsm.conf", NULL
);
1375 if (log_get_errorcount(0))
1378 /* Now that we have the options parsed we need to update the default
1379 control structure. */
1380 gpgsm_init_default_ctrl (&ctrl
);
1387 fprintf(stderr
, "%s %s; %s\n",
1388 strusage(11), strusage(13), strusage(14) );
1389 fprintf(stderr
, "%s\n", strusage(15) );
1391 # ifdef IS_DEVELOPMENT_VERSION
1394 log_info ("NOTE: THIS IS A DEVELOPMENT VERSION!\n");
1395 log_info ("It is only intended for test purposes and should NOT be\n");
1396 log_info ("used in a production environment or with production keys!\n");
1401 log_info ("NOTE: The audit log feature (--audit-log) is "
1402 "WORK IN PRORESS and not ready for use!\n");
1405 if (may_coredump
&& !opt
.quiet
)
1406 log_info (_("WARNING: program may create a core file!\n"));
1408 /* if (opt.qualsig_approval && !opt.quiet) */
1409 /* log_info (_("This software has offically been approved to " */
1410 /* "create and verify\n" */
1411 /* "qualified signatures according to German law.\n")); */
1413 if (logfile
&& cmd
== aServer
)
1415 log_set_file (logfile
);
1416 log_set_prefix (NULL
, 1|2|4);
1419 if (gnupg_faked_time_p ())
1421 gnupg_isotime_t tbuf
;
1423 log_info (_("WARNING: running with faked system time: "));
1424 gnupg_get_isotime (tbuf
);
1425 dump_isotime (tbuf
);
1429 /*FIXME if (opt.batch) */
1430 /* tty_batchmode (1); */
1432 gcry_control (GCRYCTL_RESUME_SECMEM_WARN
);
1436 /* Although we alwasy use gpgsm_exit, we better install a regualr
1437 exit handler so that at least the secure memory gets wiped
1439 if (atexit (emergency_cleanup
))
1441 log_error ("atexit failed\n");
1445 /* Must do this after dropping setuid, because the mapping functions
1446 may try to load an module and we may have disabled an algorithm.
1447 We remap the commonly used algorithms to the OIDs for
1448 convenience. We need to work with the OIDs because they are used
1449 to check whether the encryption mode is actually available. */
1450 if (!strcmp (opt
.def_cipher_algoid
, "3DES") )
1451 opt
.def_cipher_algoid
= "1.2.840.113549.3.7";
1452 else if (!strcmp (opt
.def_cipher_algoid
, "AES")
1453 || !strcmp (opt
.def_cipher_algoid
, "AES128"))
1454 opt
.def_cipher_algoid
= "2.16.840.1.101.3.4.1.2";
1455 else if (!strcmp (opt
.def_cipher_algoid
, "AES256") )
1456 opt
.def_cipher_algoid
= "2.16.840.1.101.3.4.1.42";
1457 else if (!strcmp (opt
.def_cipher_algoid
, "SERPENT")
1458 || !strcmp (opt
.def_cipher_algoid
, "SERPENT128") )
1459 opt
.def_cipher_algoid
= "1.3.6.1.4.1.11591.13.2.2";
1460 else if (!strcmp (opt
.def_cipher_algoid
, "SERPENT192") )
1461 opt
.def_cipher_algoid
= "1.3.6.1.4.1.11591.13.2.22";
1462 else if (!strcmp (opt
.def_cipher_algoid
, "SERPENT192") )
1463 opt
.def_cipher_algoid
= "1.3.6.1.4.1.11591.13.2.42";
1464 else if (!strcmp (opt
.def_cipher_algoid
, "SEED") )
1465 opt
.def_cipher_algoid
= "1.2.410.200004.1.4";
1466 else if (!strcmp (opt
.def_cipher_algoid
, "CAMELLIA")
1467 || !strcmp (opt
.def_cipher_algoid
, "CAMELLIA128") )
1468 opt
.def_cipher_algoid
= "1.2.392.200011.61.1.1.1.2";
1469 else if (!strcmp (opt
.def_cipher_algoid
, "CAMELLIA192") )
1470 opt
.def_cipher_algoid
= "1.2.392.200011.61.1.1.1.3";
1471 else if (!strcmp (opt
.def_cipher_algoid
, "CAMELLIA256") )
1472 opt
.def_cipher_algoid
= "1.2.392.200011.61.1.1.1.4";
1474 if (cmd
!= aGPGConfList
)
1476 if ( !gcry_cipher_map_name (opt
.def_cipher_algoid
)
1477 || !gcry_cipher_mode_from_oid (opt
.def_cipher_algoid
))
1478 log_error (_("selected cipher algorithm is invalid\n"));
1480 if (forced_digest_algo
)
1482 opt
.forced_digest_algo
= gcry_md_map_name (forced_digest_algo
);
1483 if (our_md_test_algo(opt
.forced_digest_algo
) )
1484 log_error (_("selected digest algorithm is invalid\n"));
1486 if (extra_digest_algo
)
1488 opt
.extra_digest_algo
= gcry_md_map_name (extra_digest_algo
);
1489 if (our_md_test_algo (opt
.extra_digest_algo
) )
1490 log_error (_("selected digest algorithm is invalid\n"));
1494 if (log_get_errorcount(0))
1497 /* Set the random seed file. */
1498 if (use_random_seed
)
1500 char *p
= make_filename (opt
.homedir
, "random_seed", NULL
);
1501 gcry_control (GCRYCTL_SET_RANDOM_SEED_FILE
, p
);
1505 if (!cmd
&& opt
.fingerprint
&& !with_fpr
)
1506 set_cmd (&cmd
, aListKeys
);
1508 /* Add default keybox. */
1509 if (!nrings
&& default_keyring
)
1513 keydb_add_resource ("pubring.kbx", 0, 0, &created
);
1514 if (created
&& !no_common_certs_import
)
1516 /* Import the standard certificates for a new default keybox. */
1519 filelist
[0] = make_filename (gnupg_datadir (),"com-certs.pem", NULL
);
1521 if (!access (filelist
[0], F_OK
))
1523 log_info (_("importing common certificates `%s'\n"),
1525 gpgsm_import_files (&ctrl
, 1, filelist
, open_read
);
1527 xfree (filelist
[0]);
1530 for (sl
= nrings
; sl
; sl
= sl
->next
)
1531 keydb_add_resource (sl
->d
, 0, 0, NULL
);
1532 FREE_STRLIST(nrings
);
1535 /* Prepare the audit log feature for certain commands. */
1544 audit_release (ctrl
.audit
);
1545 ctrl
.audit
= audit_new ();
1546 auditfp
= open_es_fwrite (auditlog
);
1554 if (!do_not_setup_keys
)
1556 for (sl
= locusr
; sl
; sl
= sl
->next
)
1558 int rc
= gpgsm_add_to_certlist (&ctrl
, sl
->d
, 1, &signerlist
, 0);
1561 log_error (_("can't sign using `%s': %s\n"),
1562 sl
->d
, gpg_strerror (rc
));
1563 gpgsm_status2 (&ctrl
, STATUS_INV_SGNR
,
1564 get_inv_recpsgnr_code (rc
), sl
->d
, NULL
);
1565 gpgsm_status2 (&ctrl
, STATUS_INV_RECP
,
1566 get_inv_recpsgnr_code (rc
), sl
->d
, NULL
);
1570 /* Build the recipient list. We first add the regular ones and then
1571 the encrypt-to ones because the underlying function will silently
1572 ignore duplicates and we can't allow to keep a duplicate which is
1573 flagged as encrypt-to as the actually encrypt function would then
1574 complain about no (regular) recipients. */
1575 for (sl
= remusr
; sl
; sl
= sl
->next
)
1576 if (!(sl
->flags
& 1))
1577 do_add_recipient (&ctrl
, sl
->d
, &recplist
, 0, recp_required
);
1578 if (!opt
.no_encrypt_to
)
1580 for (sl
= remusr
; sl
; sl
= sl
->next
)
1581 if ((sl
->flags
& 1))
1582 do_add_recipient (&ctrl
, sl
->d
, &recplist
, 1, recp_required
);
1586 if (log_get_errorcount(0))
1587 gpgsm_exit(1); /* Must stop for invalid recipients. */
1589 fname
= argc
? *argv
: NULL
;
1591 /* Dispatch command. */
1595 { /* List options and default values in the GPG Conf format. */
1596 char *config_filename_esc
= percent_escape (opt
.config_filename
, NULL
);
1598 printf ("gpgconf-gpgsm.conf:%lu:\"%s\n",
1599 GC_OPT_FLAG_DEFAULT
, config_filename_esc
);
1600 xfree (config_filename_esc
);
1602 printf ("verbose:%lu:\n", GC_OPT_FLAG_NONE
);
1603 printf ("quiet:%lu:\n", GC_OPT_FLAG_NONE
);
1604 printf ("debug-level:%lu:\"none:\n", GC_OPT_FLAG_DEFAULT
);
1605 printf ("log-file:%lu:\n", GC_OPT_FLAG_NONE
);
1606 printf ("disable-crl-checks:%lu:\n", GC_OPT_FLAG_NONE
);
1607 printf ("disable-trusted-cert-crl-check:%lu:\n", GC_OPT_FLAG_NONE
);
1608 printf ("enable-ocsp:%lu:\n", GC_OPT_FLAG_NONE
);
1609 printf ("include-certs:%lu:1:\n", GC_OPT_FLAG_DEFAULT
);
1610 printf ("disable-policy-checks:%lu:\n", GC_OPT_FLAG_NONE
);
1611 printf ("auto-issuer-key-retrieve:%lu:\n", GC_OPT_FLAG_NONE
);
1612 printf ("disable-dirmngr:%lu:\n", GC_OPT_FLAG_NONE
);
1613 #ifndef HAVE_W32_SYSTEM
1614 printf ("prefer-system-dirmngr:%lu:\n", GC_OPT_FLAG_NONE
);
1616 printf ("cipher-algo:%lu:\"3DES:\n", GC_OPT_FLAG_DEFAULT
);
1617 printf ("p12-charset:%lu:\n", GC_OPT_FLAG_DEFAULT
);
1618 printf ("default-key:%lu:\n", GC_OPT_FLAG_DEFAULT
);
1619 printf ("encrypt-to:%lu:\n", GC_OPT_FLAG_DEFAULT
);
1620 printf ("keyserver:%lu:\n", GC_OPT_FLAG_NONE
);
1625 /* This is merely a dummy command to test whether the
1626 configuration file is valid. */
1632 log_debug ("waiting for debugger - my pid is %u .....\n",
1633 (unsigned int)getpid());
1634 gnupg_sleep (debug_wait
);
1635 log_debug ("... okay\n");
1637 gpgsm_server (recplist
);
1642 wrong_args ("--call-dirmngr <command> {args}");
1644 if (gpgsm_dirmngr_run_command (&ctrl
, *argv
, argc
-1, argv
+1))
1648 case aCallProtectTool
:
1649 run_protect_tool (argc
, argv
);
1652 case aEncr
: /* Encrypt the given file. */
1654 FILE *fp
= open_fwrite (opt
.outfile
?opt
.outfile
:"-");
1658 if (!argc
) /* Source is stdin. */
1659 gpgsm_encrypt (&ctrl
, recplist
, 0, fp
);
1660 else if (argc
== 1) /* Source is the given file. */
1661 gpgsm_encrypt (&ctrl
, recplist
, open_read (*argv
), fp
);
1663 wrong_args ("--encrypt [datafile]");
1670 case aSign
: /* Sign the given file. */
1672 FILE *fp
= open_fwrite (opt
.outfile
?opt
.outfile
:"-");
1674 /* Fixme: We should also allow to concatenate multiple files for
1675 signing because that is what gpg does.*/
1677 if (!argc
) /* Create from stdin. */
1678 gpgsm_sign (&ctrl
, signerlist
, 0, detached_sig
, fp
);
1679 else if (argc
== 1) /* From file. */
1680 gpgsm_sign (&ctrl
, signerlist
,
1681 open_read (*argv
), detached_sig
, fp
);
1683 wrong_args ("--sign [datafile]");
1690 case aSignEncr
: /* sign and encrypt the given file */
1691 log_error ("this command has not yet been implemented\n");
1694 case aClearsign
: /* make a clearsig */
1695 log_error ("this command has not yet been implemented\n");
1703 if (argc
== 2 && opt
.outfile
)
1704 log_info ("option --output ignored for a detached signature\n");
1705 else if (opt
.outfile
)
1706 fp
= open_fwrite (opt
.outfile
);
1709 gpgsm_verify (&ctrl
, 0, -1, fp
); /* normal signature from stdin */
1711 gpgsm_verify (&ctrl
, open_read (*argv
), -1, fp
); /* std signature */
1712 else if (argc
== 2) /* detached signature (sig, detached) */
1713 gpgsm_verify (&ctrl
, open_read (*argv
), open_read (argv
[1]), NULL
);
1715 wrong_args ("--verify [signature [detached_data]]");
1717 if (fp
&& fp
!= stdout
)
1724 FILE *fp
= open_fwrite (opt
.outfile
?opt
.outfile
:"-");
1728 gpgsm_decrypt (&ctrl
, 0, fp
); /* from stdin */
1730 gpgsm_decrypt (&ctrl
, open_read (*argv
), fp
); /* from file */
1732 wrong_args ("--decrypt [filename]");
1739 for (sl
=NULL
; argc
; argc
--, argv
++)
1740 add_to_strlist (&sl
, *argv
);
1741 gpgsm_delete (&ctrl
, sl
);
1747 ctrl
.with_chain
= 1;
1750 case aListExternalKeys
:
1751 case aDumpExternalKeys
:
1752 case aListSecretKeys
:
1753 case aDumpSecretKeys
:
1761 case aListKeys
: mode
= (0 | 0 | (1<<6)); break;
1763 case aDumpKeys
: mode
= (256 | 0 | (1<<6)); break;
1764 case aListExternalKeys
: mode
= (0 | 0 | (1<<7)); break;
1765 case aDumpExternalKeys
: mode
= (256 | 0 | (1<<7)); break;
1766 case aListSecretKeys
: mode
= (0 | 2 | (1<<6)); break;
1767 case aDumpSecretKeys
: mode
= (256 | 2 | (1<<6)); break;
1771 fp
= open_es_fwrite (opt
.outfile
?opt
.outfile
:"-");
1772 for (sl
=NULL
; argc
; argc
--, argv
++)
1773 add_to_strlist (&sl
, *argv
);
1774 gpgsm_list_keys (&ctrl
, sl
, fp
, mode
);
1781 case aKeygen
: /* Generate a key; well kind of. */
1783 estream_t fpin
= NULL
;
1788 if (!argc
) /* Create from stdin. */
1789 fpin
= open_es_fread ("-");
1790 else if (argc
== 1) /* From file. */
1791 fpin
= open_es_fread (*argv
);
1793 wrong_args ("--gen-key --batch [parmfile]");
1796 fpout
= open_fwrite (opt
.outfile
?opt
.outfile
:"-");
1799 gpgsm_genkey (&ctrl
, fpin
, fpout
);
1801 gpgsm_gencertreq_tty (&ctrl
, fpout
);
1803 if (fpout
!= stdout
)
1810 gpgsm_import_files (&ctrl
, argc
, argv
, open_read
);
1815 FILE *fp
= open_fwrite (opt
.outfile
?opt
.outfile
:"-");
1817 for (sl
=NULL
; argc
; argc
--, argv
++)
1818 add_to_strlist (&sl
, *argv
);
1819 gpgsm_export (&ctrl
, sl
, fp
, NULL
);
1826 case aExportSecretKeyP12
:
1828 FILE *fp
= open_fwrite (opt
.outfile
?opt
.outfile
:"-");
1831 gpgsm_p12_export (&ctrl
, *argv
, fp
);
1833 wrong_args ("--export-secret-key-p12 KEY-ID");
1841 log_error ("this command has not yet been implemented\n");
1847 wrong_args ("--learn-card");
1850 int rc
= gpgsm_agent_learn (&ctrl
);
1852 log_error ("error learning card: %s\n", gpg_strerror (rc
));
1858 wrong_args ("--passwd <key-Id>");
1862 ksba_cert_t cert
= NULL
;
1865 rc
= gpgsm_find_cert (*argv
, NULL
, &cert
);
1868 else if (!(grip
= gpgsm_get_keygrip_hexstring (cert
)))
1869 rc
= gpg_error (GPG_ERR_BUG
);
1872 char *desc
= gpgsm_format_keydesc (cert
);
1873 rc
= gpgsm_agent_passwd (&ctrl
, grip
, desc
);
1877 log_error ("error changing passphrase: %s\n", gpg_strerror (rc
));
1879 ksba_cert_release (cert
);
1883 case aKeydbClearSomeCertFlags
:
1884 for (sl
=NULL
; argc
; argc
--, argv
++)
1885 add_to_strlist (&sl
, *argv
);
1886 keydb_clear_some_cert_flags (&ctrl
, sl
);
1892 log_error (_("invalid command (there is no implicit command)\n"));
1896 /* Print the audit result if needed. */
1897 if (auditlog
&& auditfp
)
1899 audit_print_result (ctrl
.audit
, auditfp
, 0);
1900 audit_release (ctrl
.audit
);
1902 es_fclose (auditfp
);
1906 keyserver_list_free (opt
.keyserver
);
1907 opt
.keyserver
= NULL
;
1908 gpgsm_release_certlist (recplist
);
1909 gpgsm_release_certlist (signerlist
);
1910 FREE_STRLIST (remusr
);
1911 FREE_STRLIST (locusr
);
1913 return 8; /*NOTREACHED*/
1916 /* Note: This function is used by signal handlers!. */
1918 emergency_cleanup (void)
1920 gcry_control (GCRYCTL_TERM_SECMEM
);
1927 gcry_control (GCRYCTL_UPDATE_RANDOM_SEED_FILE
);
1928 if (opt
.debug
& DBG_MEMSTAT_VALUE
)
1930 gcry_control( GCRYCTL_DUMP_MEMORY_STATS
);
1931 gcry_control( GCRYCTL_DUMP_RANDOM_STATS
);
1934 gcry_control (GCRYCTL_DUMP_SECMEM_STATS
);
1935 emergency_cleanup ();
1936 rc
= rc
? rc
: log_get_errorcount(0)? 2 : gpgsm_errors_seen
? 1 : 0;
1942 gpgsm_init_default_ctrl (struct server_control_s
*ctrl
)
1944 ctrl
->include_certs
= default_include_certs
;
1945 ctrl
->use_ocsp
= opt
.enable_ocsp
;
1946 ctrl
->validation_model
= default_validation_model
;
1951 gpgsm_parse_validation_model (const char *model
)
1953 if (!ascii_strcasecmp (model
, "shell") )
1955 else if ( !ascii_strcasecmp (model
, "chain") )
1962 /* Check whether the filename has the form "-&nnnn", where n is a
1963 non-zero number. Returns this number or -1 if it is not the case. */
1965 check_special_filename (const char *fname
, int for_write
)
1967 if (allow_special_filenames
1968 && fname
&& *fname
== '-' && fname
[1] == '&' ) {
1972 for (i
=0; isdigit (fname
[i
]); i
++ )
1975 return translate_sys2libc_fd_int (atoi (fname
), for_write
);
1982 /* Open the FILENAME for read and return the filedescriptor. Stop
1983 with an error message in case of problems. "-" denotes stdin and
1984 if special filenames are allowed the given fd is opened instead. */
1986 open_read (const char *filename
)
1990 if (filename
[0] == '-' && !filename
[1])
1993 return 0; /* stdin */
1995 fd
= check_special_filename (filename
, 0);
1998 fd
= open (filename
, O_RDONLY
| O_BINARY
);
2001 log_error (_("can't open `%s': %s\n"), filename
, strerror (errno
));
2007 /* Same as open_read but return an estream_t. */
2009 open_es_fread (const char *filename
)
2014 if (filename
[0] == '-' && !filename
[1])
2015 fd
= fileno (stdin
);
2017 fd
= check_special_filename (filename
, 0);
2020 fp
= es_fdopen_nc (fd
, "rb");
2023 log_error ("es_fdopen(%d) failed: %s\n", fd
, strerror (errno
));
2028 fp
= es_fopen (filename
, "rb");
2031 log_error (_("can't open `%s': %s\n"), filename
, strerror (errno
));
2038 /* Open FILENAME for fwrite and return the stream. Stop with an error
2039 message in case of problems. "-" denotes stdout and if special
2040 filenames are allowed the given fd is opened instead. Caller must
2041 close the returned stream unless it is stdout. */
2043 open_fwrite (const char *filename
)
2048 if (filename
[0] == '-' && !filename
[1])
2050 set_binary (stdout
);
2054 fd
= check_special_filename (filename
, 1);
2057 fp
= fdopen (dup (fd
), "wb");
2060 log_error ("fdopen(%d) failed: %s\n", fd
, strerror (errno
));
2066 fp
= fopen (filename
, "wb");
2069 log_error (_("can't open `%s': %s\n"), filename
, strerror (errno
));
2076 /* Open FILENAME for fwrite and return an extended stream. Stop with
2077 an error message in case of problems. "-" denotes stdout and if
2078 special filenames are allowed the given fd is opened instead.
2079 Caller must close the returned stream. */
2081 open_es_fwrite (const char *filename
)
2086 if (filename
[0] == '-' && !filename
[1])
2089 fp
= es_fdopen_nc (fileno(stdout
), "wb");
2093 fd
= check_special_filename (filename
, 1);
2096 fp
= es_fdopen_nc (fd
, "wb");
2099 log_error ("es_fdopen(%d) failed: %s\n", fd
, strerror (errno
));
2104 fp
= es_fopen (filename
, "wb");
2107 log_error (_("can't open `%s': %s\n"), filename
, strerror (errno
));
2115 run_protect_tool (int argc
, char **argv
)
2117 #ifndef HAVE_W32_SYSTEM
2122 if (!opt
.protect_tool_program
|| !*opt
.protect_tool_program
)
2123 pgm
= gnupg_module_name (GNUPG_MODULE_NAME_PROTECT_TOOL
);
2125 pgm
= opt
.protect_tool_program
;
2127 av
= xcalloc (argc
+2, sizeof *av
);
2128 av
[0] = strrchr (pgm
, '/');
2130 av
[0] = xstrdup (pgm
);
2131 for (i
=1; argc
; i
++, argc
--, argv
++)
2135 log_error ("error executing `%s': %s\n", pgm
, strerror (errno
));
2136 #endif /*HAVE_W32_SYSTEM*/