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',
87 aKeydbClearSomeCertFlags
,
97 oDebugNoChainValidation
,
98 oDebugIgnoreExpiration
,
104 oEnableSpecialFilenames
,
114 oPreferSystemDirmngr
,
131 oDisableTrustedCertCRLCheck
,
132 oEnableTrustedCertCRLCheck
,
140 oDisablePolicyChecks
,
142 oAutoIssuerKeyRetrieve
,
183 static ARGPARSE_OPTS opts
[] = {
185 ARGPARSE_group (300, N_("@Commands:\n ")),
187 ARGPARSE_c (aSign
, "sign", N_("make a signature")),
188 ARGPARSE_c (aClearsign
, "clearsign", N_("make a clear text signature") ),
189 ARGPARSE_c (aDetachedSign
, "detach-sign", N_("make a detached signature")),
190 ARGPARSE_c (aEncr
, "encrypt", N_("encrypt data")),
191 ARGPARSE_c (aSym
, "symmetric", N_("encryption only with symmetric cipher")),
192 ARGPARSE_c (aDecrypt
, "decrypt", N_("decrypt data (default)")),
193 ARGPARSE_c (aVerify
, "verify", N_("verify a signature")),
194 ARGPARSE_c (aVerifyFiles
, "verify-files", "@"),
195 ARGPARSE_c (aListKeys
, "list-keys", N_("list keys")),
196 ARGPARSE_c (aListExternalKeys
, "list-external-keys",
197 N_("list external keys")),
198 ARGPARSE_c (aListSecretKeys
, "list-secret-keys", N_("list secret keys")),
199 ARGPARSE_c (aListChain
, "list-chain", N_("list certificate chain")),
200 ARGPARSE_c (aFingerprint
, "fingerprint", N_("list keys and fingerprints")),
201 ARGPARSE_c (aKeygen
, "gen-key", "@"),
202 ARGPARSE_c (aDeleteKey
, "delete-keys",
203 N_("remove keys from the public keyring")),
204 ARGPARSE_c (aSendKeys
, "send-keys", N_("export keys to a key server")),
205 ARGPARSE_c (aRecvKeys
, "recv-keys", N_("import keys from a key server")),
206 ARGPARSE_c (aImport
, "import", N_("import certificates")),
207 ARGPARSE_c (aExport
, "export", N_("export certificates")),
208 ARGPARSE_c (aExportSecretKeyP12
, "export-secret-key-p12", "@"),
209 ARGPARSE_c (aLearnCard
, "learn-card", N_("register a smartcard")),
210 ARGPARSE_c (aServer
, "server", N_("run in server mode")),
211 ARGPARSE_c (aCallDirmngr
, "call-dirmngr",
212 N_("pass a command to the dirmngr")),
213 ARGPARSE_c (aCallProtectTool
, "call-protect-tool",
214 N_("invoke gpg-protect-tool")),
215 ARGPARSE_c (aPasswd
, "passwd", N_("change a passphrase")),
216 ARGPARSE_c (aGPGConfList
, "gpgconf-list", "@"),
217 ARGPARSE_c (aGPGConfTest
, "gpgconf-test", "@"),
219 ARGPARSE_c (aDumpKeys
, "dump-cert", "@"),
220 ARGPARSE_c (aDumpKeys
, "dump-keys", "@"),
221 ARGPARSE_c (aDumpChain
, "dump-chain", "@"),
222 ARGPARSE_c (aDumpExternalKeys
, "dump-external-keys", "@"),
223 ARGPARSE_c (aDumpSecretKeys
, "dump-secret-keys", "@"),
224 ARGPARSE_c (aKeydbClearSomeCertFlags
, "keydb-clear-some-cert-flags", "@"),
226 ARGPARSE_group (301, N_("@\nOptions:\n ")),
228 ARGPARSE_s_n (oArmor
, "armor", N_("create ascii armored output")),
229 ARGPARSE_s_n (oArmor
, "armour", "@"),
230 ARGPARSE_s_n (oBase64
, "base64", N_("create base-64 encoded output")),
232 ARGPARSE_s_s (oP12Charset
, "p12-charset", "@"),
234 ARGPARSE_s_n (oAssumeArmor
, "assume-armor",
235 N_("assume input is in PEM format")),
236 ARGPARSE_s_n (oAssumeBase64
, "assume-base64",
237 N_("assume input is in base-64 format")),
238 ARGPARSE_s_n (oAssumeBinary
, "assume-binary",
239 N_("assume input is in binary format")),
241 ARGPARSE_s_s (oRecipient
, "recipient", N_("|USER-ID|encrypt for USER-ID")),
243 ARGPARSE_s_n (oPreferSystemDirmngr
,"prefer-system-dirmngr",
244 N_("use system's dirmngr if available")),
246 ARGPARSE_s_n (oDisableCRLChecks
, "disable-crl-checks",
247 N_("never consult a CRL")),
248 ARGPARSE_s_n (oEnableCRLChecks
, "enable-crl-checks", "@"),
249 ARGPARSE_s_n (oDisableTrustedCertCRLCheck
,
250 "disable-trusted-cert-crl-check", "@"),
251 ARGPARSE_s_n (oEnableTrustedCertCRLCheck
,
252 "enable-trusted-cert-crl-check", "@"),
254 ARGPARSE_s_n (oForceCRLRefresh
, "force-crl-refresh", "@"),
256 ARGPARSE_s_n (oDisableOCSP
, "disable-ocsp", "@"),
257 ARGPARSE_s_n (oEnableOCSP
, "enable-ocsp", N_("check validity using OCSP")),
259 ARGPARSE_s_s (oValidationModel
, "validation-model", "@"),
261 ARGPARSE_s_i (oIncludeCerts
, "include-certs",
262 N_("|N|number of certificates to include") ),
264 ARGPARSE_s_s (oPolicyFile
, "policy-file",
265 N_("|FILE|take policy information from FILE")),
267 ARGPARSE_s_n (oDisablePolicyChecks
, "disable-policy-checks",
268 N_("do not check certificate policies")),
269 ARGPARSE_s_n (oEnablePolicyChecks
, "enable-policy-checks", "@"),
271 ARGPARSE_s_n (oAutoIssuerKeyRetrieve
, "auto-issuer-key-retrieve",
272 N_("fetch missing issuer certificates")),
274 ARGPARSE_s_s (oEncryptTo
, "encrypt-to", "@"),
275 ARGPARSE_s_n (oNoEncryptTo
, "no-encrypt-to", "@"),
277 ARGPARSE_s_s (oUser
, "local-user",
278 N_("|USER-ID|use USER-ID to sign or decrypt")),
280 ARGPARSE_s_s (oOutput
, "output", N_("|FILE|write output to FILE")),
281 ARGPARSE_s_n (oVerbose
, "verbose", N_("verbose")),
282 ARGPARSE_s_n (oQuiet
, "quiet", N_("be somewhat more quiet")),
283 ARGPARSE_s_n (oNoTTY
, "no-tty", N_("don't use the terminal at all")),
284 ARGPARSE_s_s (oLogFile
, "log-file",
285 N_("|FILE|write a server mode log to FILE")),
286 ARGPARSE_s_n (oNoLogFile
, "no-log-file", "@"),
287 ARGPARSE_s_i (oLoggerFD
, "logger-fd", "@"),
289 ARGPARSE_s_s (oAuditLog
, "audit-log",
290 N_("|FILE|write an audit log to FILE")),
291 ARGPARSE_s_n (oDryRun
, "dry-run", N_("do not make any changes")),
292 ARGPARSE_s_n (oBatch
, "batch", N_("batch mode: never ask")),
293 ARGPARSE_s_n (oAnswerYes
, "yes", N_("assume yes on most questions")),
294 ARGPARSE_s_n (oAnswerNo
, "no", N_("assume no on most questions")),
296 ARGPARSE_s_s (oKeyring
, "keyring",
297 N_("|FILE|add keyring to the list of keyrings")),
299 ARGPARSE_s_s (oDefaultKey
, "default-key",
300 N_("|USER-ID|use USER-ID as default secret key")),
303 /* ARGPARSE_s_s (oDefRecipient, "default-recipient", */
304 /* N_("|NAME|use NAME as default recipient")), */
305 /* ARGPARSE_s_n (oDefRecipientSelf, "default-recipient-self", */
306 /* N_("use the default key as default recipient")), */
307 /* ARGPARSE_s_n (oNoDefRecipient, "no-default-recipient", "@"), */
309 ARGPARSE_s_s (oKeyServer
, "keyserver",
310 N_("|SPEC|use this keyserver to lookup keys")),
311 ARGPARSE_s_s (oOptions
, "options", N_("|FILE|read options from FILE")),
313 ARGPARSE_p_u (oDebug
, "debug", "@"),
314 ARGPARSE_s_s (oDebugLevel
, "debug-level",
315 N_("|LEVEL|set the debugging level to LEVEL")),
316 ARGPARSE_s_n (oDebugAll
, "debug-all", "@"),
317 ARGPARSE_s_n (oDebugNone
, "debug-none", "@"),
318 ARGPARSE_s_i (oDebugWait
, "debug-wait", "@"),
319 ARGPARSE_s_n (oDebugAllowCoreDump
, "debug-allow-core-dump", "@"),
320 ARGPARSE_s_n (oDebugNoChainValidation
, "debug-no-chain-validation", "@"),
321 ARGPARSE_s_n (oDebugIgnoreExpiration
, "debug-ignore-expiration", "@"),
322 ARGPARSE_s_s (oFixedPassphrase
, "fixed-passphrase", "@"),
324 ARGPARSE_s_i (oStatusFD
, "status-fd",
325 N_("|FD|write status info to this FD")),
327 ARGPARSE_s_s (oCipherAlgo
, "cipher-algo",
328 N_("|NAME|use cipher algorithm NAME")),
329 ARGPARSE_s_s (oDigestAlgo
, "digest-algo",
330 N_("|NAME|use message digest algorithm NAME")),
331 ARGPARSE_s_s (oExtraDigestAlgo
, "extra-digest-algo", "@"),
334 ARGPARSE_group (302, N_(
335 "@\n(See the man page for a complete listing of all commands and options)\n"
338 ARGPARSE_group (303, N_("@\nExamples:\n\n"
339 " -se -r Bob [file] sign and encrypt for user Bob\n"
340 " --clearsign [file] make a clear text signature\n"
341 " --detach-sign [file] make a detached signature\n"
342 " --list-keys [names] show keys\n"
343 " --fingerprint [names] show fingerprints\n" )),
345 /* Hidden options. */
346 ARGPARSE_s_n (oNoVerbose
, "no-verbose", "@"),
347 ARGPARSE_s_n (oEnableSpecialFilenames
, "enable-special-filenames", "@"),
348 ARGPARSE_s_n (oNoSecmemWarn
, "no-secmem-warning", "@"),
349 ARGPARSE_s_n (oNoArmor
, "no-armor", "@"),
350 ARGPARSE_s_n (oNoArmor
, "no-armour", "@"),
351 ARGPARSE_s_n (oNoDefKeyring
, "no-default-keyring", "@"),
352 ARGPARSE_s_n (oNoGreeting
, "no-greeting", "@"),
353 ARGPARSE_s_n (oNoOptions
, "no-options", "@"),
354 ARGPARSE_s_s (oHomedir
, "homedir", "@"),
355 ARGPARSE_s_s (oAgentProgram
, "agent-program", "@"),
356 ARGPARSE_s_s (oDisplay
, "display", "@"),
357 ARGPARSE_s_s (oTTYname
, "ttyname", "@"),
358 ARGPARSE_s_s (oTTYtype
, "ttytype", "@"),
359 ARGPARSE_s_s (oLCctype
, "lc-ctype", "@"),
360 ARGPARSE_s_s (oLCmessages
, "lc-messages", "@"),
361 ARGPARSE_s_s (oXauthority
, "xauthority", "@"),
362 ARGPARSE_s_s (oDirmngrProgram
, "dirmngr-program", "@"),
363 ARGPARSE_s_n (oDisableDirmngr
, "disable-dirmngr", "@"),
364 ARGPARSE_s_s (oProtectToolProgram
, "protect-tool-program", "@"),
365 ARGPARSE_s_s (oFakedSystemTime
, "faked-system-time", "@"),
366 ARGPARSE_s_n (oNoBatch
, "no-batch", "@"),
367 ARGPARSE_s_n (oWithColons
, "with-colons", "@"),
368 ARGPARSE_s_n (oWithKeyData
,"with-key-data", "@"),
369 ARGPARSE_s_n (oWithValidation
, "with-validation", "@"),
370 ARGPARSE_s_n (oWithMD5Fingerprint
, "with-md5-fingerprint", "@"),
371 ARGPARSE_s_n (oWithEphemeralKeys
, "with-ephemeral-keys", "@"),
372 ARGPARSE_s_n (oSkipVerify
, "skip-verify", "@"),
373 ARGPARSE_s_n (oWithFingerprint
, "with-fingerprint", "@"),
374 ARGPARSE_s_s (oDisableCipherAlgo
, "disable-cipher-algo", "@"),
375 ARGPARSE_s_s (oDisablePubkeyAlgo
, "disable-pubkey-algo", "@"),
376 ARGPARSE_s_n (oIgnoreTimeConflict
, "ignore-time-conflict", "@"),
377 ARGPARSE_s_n (oNoRandomSeedFile
, "no-random-seed-file", "@"),
378 ARGPARSE_s_n (oNoCommonCertsImport
, "no-common-certs-import", "@"),
380 /* Command aliases. */
381 ARGPARSE_c (aListKeys
, "list-key", "@"),
382 ARGPARSE_c (aListChain
, "list-sig", "@"),
383 ARGPARSE_c (aListChain
, "list-sigs", "@"),
384 ARGPARSE_c (aListChain
, "check-sig", "@"),
385 ARGPARSE_c (aListChain
, "check-sigs", "@"),
386 ARGPARSE_c (aDeleteKey
, "delete-key", "@"),
394 /* Global variable to keep an error count. */
395 int gpgsm_errors_seen
= 0;
397 /* It is possible that we are currentlu running under setuid permissions */
398 static int maybe_setuid
= 1;
400 /* Helper to implement --debug-level and --debug*/
401 static const char *debug_level
;
402 static unsigned int debug_value
;
404 /* Option --enable-special-filenames */
405 static int allow_special_filenames
;
407 /* Default value for include-certs. */
408 static int default_include_certs
= 1; /* Only include the signer's cert. */
410 /* Whether the chain mode shall be used for validation. */
411 static int default_validation_model
;
414 static char *build_list (const char *text
,
415 const char *(*mapf
)(int), int (*chkf
)(int));
416 static void set_cmd (enum cmd_and_opt_values
*ret_cmd
,
417 enum cmd_and_opt_values new_cmd
);
419 static void emergency_cleanup (void);
420 static int check_special_filename (const char *fname
, int for_write
);
421 static int open_read (const char *filename
);
422 static FILE *open_fwrite (const char *filename
);
423 static estream_t
open_es_fwrite (const char *filename
);
424 static void run_protect_tool (int argc
, char **argv
);
427 our_pk_test_algo (int algo
)
433 return gcry_pk_test_algo (algo
);
440 our_cipher_test_algo (int algo
)
444 case GCRY_CIPHER_3DES
:
445 case GCRY_CIPHER_AES128
:
446 case GCRY_CIPHER_AES192
:
447 case GCRY_CIPHER_AES256
:
448 case GCRY_CIPHER_SERPENT128
:
449 case GCRY_CIPHER_SERPENT192
:
450 case GCRY_CIPHER_SERPENT256
:
451 case GCRY_CIPHER_SEED
:
452 case GCRY_CIPHER_CAMELLIA128
:
453 case GCRY_CIPHER_CAMELLIA192
:
454 case GCRY_CIPHER_CAMELLIA256
:
455 return gcry_cipher_test_algo (algo
);
463 our_md_test_algo (int algo
)
474 case GCRY_MD_WHIRLPOOL
:
475 return gcry_md_test_algo (algo
);
483 make_libversion (const char *libname
, const char *(*getfnc
)(const char*))
490 gcry_control (GCRYCTL_INIT_SECMEM
, 0, 0); /* Drop setuid. */
494 result
= xmalloc (strlen (libname
) + 1 + strlen (s
) + 1);
495 strcpy (stpcpy (stpcpy (result
, libname
), " "), s
);
501 my_strusage( int level
)
503 static char *digests
, *pubkeys
, *ciphers
;
504 static char *ver_gcry
, *ver_ksba
;
509 case 11: p
= "gpgsm (GnuPG)";
511 case 13: p
= VERSION
; break;
512 case 17: p
= PRINTABLE_OS_NAME
; break;
513 case 19: p
= _("Please report bugs to <" PACKAGE_BUGREPORT
">.\n");
516 case 40: p
= _("Usage: gpgsm [options] [files] (-h for help)");
519 p
= _("Syntax: gpgsm [options] [files]\n"
520 "sign, check, encrypt or decrypt using the S/MIME protocol\n"
521 "default operation depends on the input data\n");
526 ver_gcry
= make_libversion ("libgcrypt", gcry_check_version
);
531 ver_ksba
= make_libversion ("libksba", ksba_check_version
);
535 case 31: p
= "\nHome: "; break;
536 case 32: p
= opt
.homedir
; break;
537 case 33: p
= _("\nSupported algorithms:\n"); break;
540 ciphers
= build_list ("Cipher: ", gcry_cipher_algo_name
,
541 our_cipher_test_algo
);
546 pubkeys
= build_list ("Pubkey: ", gcry_pk_algo_name
,
552 digests
= build_list("Hash: ", gcry_md_algo_name
, our_md_test_algo
);
556 default: p
= NULL
; break;
563 build_list (const char *text
, const char * (*mapf
)(int), int (*chkf
)(int))
566 size_t n
=strlen(text
)+2;
570 gcry_control (GCRYCTL_DROP_PRIVS
); /* drop setuid */
573 for (i
=1; i
< 400; i
++ )
575 n
+= strlen(mapf(i
)) + 2;
576 list
= xmalloc (21 + n
);
578 for (p
=NULL
, i
=1; i
< 400; i
++)
583 p
= stpcpy (list
, text
);
585 p
= stpcpy (p
, ", ");
586 p
= stpcpy (p
, mapf(i
) );
590 p
= stpcpy(p
, "\n" );
595 /* Set the file pointer into binary mode if required. */
597 set_binary (FILE *fp
)
599 #ifdef HAVE_DOSISH_SYSTEM
600 setmode (fileno (fp
), O_BINARY
);
609 wrong_args (const char *text
)
611 fputs (_("usage: gpgsm [options] "), stderr
);
612 fputs (text
, stderr
);
618 /* Setup the debugging. With a DEBUG_LEVEL of NULL only the active
619 debug flags are propagated to the subsystems. With DEBUG_LEVEL
620 set, a specific set of debug flags is set; and individual debugging
621 flags will be added on top. */
627 else if (!strcmp (debug_level
, "none"))
629 else if (!strcmp (debug_level
, "basic"))
630 opt
.debug
= DBG_ASSUAN_VALUE
;
631 else if (!strcmp (debug_level
, "advanced"))
632 opt
.debug
= DBG_ASSUAN_VALUE
|DBG_X509_VALUE
;
633 else if (!strcmp (debug_level
, "expert"))
634 opt
.debug
= (DBG_ASSUAN_VALUE
|DBG_X509_VALUE
635 |DBG_CACHE_VALUE
|DBG_CRYPTO_VALUE
);
636 else if (!strcmp (debug_level
, "guru"))
640 log_error (_("invalid debug-level `%s' given\n"), debug_level
);
644 opt
.debug
|= debug_value
;
646 if (opt
.debug
&& !opt
.verbose
)
651 if (opt
.debug
& DBG_MPI_VALUE
)
652 gcry_control (GCRYCTL_SET_DEBUG_FLAGS
, 2);
653 if (opt
.debug
& DBG_CRYPTO_VALUE
)
654 gcry_control (GCRYCTL_SET_DEBUG_FLAGS
, 1);
655 gcry_control (GCRYCTL_SET_VERBOSITY
, (int)opt
.verbose
);
661 set_cmd (enum cmd_and_opt_values
*ret_cmd
, enum cmd_and_opt_values new_cmd
)
663 enum cmd_and_opt_values cmd
= *ret_cmd
;
665 if (!cmd
|| cmd
== new_cmd
)
667 else if ( cmd
== aSign
&& new_cmd
== aEncr
)
669 else if ( cmd
== aEncr
&& new_cmd
== aSign
)
671 else if ( (cmd
== aSign
&& new_cmd
== aClearsign
)
672 || (cmd
== aClearsign
&& new_cmd
== aSign
) )
676 log_error(_("conflicting commands\n"));
684 /* Helper to add recipients to a list. */
686 do_add_recipient (ctrl_t ctrl
, const char *name
,
687 certlist_t
*recplist
, int is_encrypt_to
, int recp_required
)
689 int rc
= gpgsm_add_to_certlist (ctrl
, name
, 0, recplist
, is_encrypt_to
);
694 log_error ("can't encrypt to `%s': %s\n", name
, gpg_strerror (rc
));
695 gpgsm_status2 (ctrl
, STATUS_INV_RECP
,
696 gpg_err_code (rc
) == -1? "1":
697 gpg_err_code (rc
) == GPG_ERR_NO_PUBKEY
? "1":
698 gpg_err_code (rc
) == GPG_ERR_AMBIGUOUS_NAME
? "2":
699 gpg_err_code (rc
) == GPG_ERR_WRONG_KEY_USAGE
? "3":
700 gpg_err_code (rc
) == GPG_ERR_CERT_REVOKED
? "4":
701 gpg_err_code (rc
) == GPG_ERR_CERT_EXPIRED
? "5":
702 gpg_err_code (rc
) == GPG_ERR_NO_CRL_KNOWN
? "6":
703 gpg_err_code (rc
) == GPG_ERR_CRL_TOO_OLD
? "7":
704 gpg_err_code (rc
) == GPG_ERR_NO_POLICY_MATCH
? "8":
709 log_info (_("NOTE: won't be able to encrypt to `%s': %s\n"),
710 name
, gpg_strerror (rc
));
716 parse_validation_model (const char *model
)
718 int i
= gpgsm_parse_validation_model (model
);
720 log_error (_("unknown validation model `%s'\n"), model
);
722 default_validation_model
= i
;
726 /* Release the list of SERVERS. As usual it is okay to call this
727 function with SERVERS passed as NULL. */
729 keyserver_list_free (struct keyserver_spec
*servers
)
733 struct keyserver_spec
*tmp
= servers
->next
;
734 xfree (servers
->host
);
735 xfree (servers
->user
);
737 memset (servers
->pass
, 0, strlen (servers
->pass
));
738 xfree (servers
->pass
);
739 xfree (servers
->base
);
745 /* See also dirmngr ldapserver_parse_one(). */
746 struct keyserver_spec
*
747 parse_keyserver_line (char *line
,
748 const char *filename
, unsigned int lineno
)
752 struct keyserver_spec
*server
;
756 /* Parse the colon separated fields. */
757 server
= xcalloc (1, sizeof *server
);
758 for (fieldno
= 1, p
= line
; p
; p
= endp
, fieldno
++ )
760 endp
= strchr (p
, ':');
768 server
->host
= xstrdup (p
);
771 log_error (_("%s:%u: no hostname given\n"),
779 server
->port
= atoi (p
);
784 server
->user
= xstrdup (p
);
788 if (*p
&& !server
->user
)
790 log_error (_("%s:%u: password given without user\n"),
795 server
->pass
= xstrdup (p
);
800 server
->base
= xstrdup (p
);
804 /* (We silently ignore extra fields.) */
811 log_info (_("%s:%u: skipping this line\n"), filename
, lineno
);
812 keyserver_list_free (server
);
820 main ( int argc
, char **argv
)
828 strlist_t sl
, remusr
= NULL
, locusr
=NULL
;
829 strlist_t nrings
=NULL
;
830 int detached_sig
= 0;
831 FILE *configfp
= NULL
;
832 char *configname
= NULL
;
833 unsigned configlineno
;
835 int no_more_options
= 0;
836 int default_config
=1;
837 int default_keyring
= 1;
838 char *logfile
= NULL
;
839 char *auditlog
= NULL
;
843 int use_random_seed
= 1;
844 int no_common_certs_import
= 0;
846 char *def_digest_string
= NULL
;
847 char *extra_digest_algo
= NULL
;
848 enum cmd_and_opt_values cmd
= 0;
849 struct server_control_s ctrl
;
850 certlist_t recplist
= NULL
;
851 certlist_t signerlist
= NULL
;
852 int do_not_setup_keys
= 0;
853 int recp_required
= 0;
854 estream_t auditfp
= NULL
;
858 gnupg_reopen_std ("gpgsm");
859 /* trap_unaligned ();*/
860 gnupg_rl_initialize ();
861 set_strusage (my_strusage
);
862 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN
);
863 /* We don't need any locking in libgcrypt unless we use any kind of
865 gcry_control (GCRYCTL_DISABLE_INTERNAL_LOCKING
);
867 /* Please note that we may running SUID(ROOT), so be very CAREFUL
868 when adding any stuff between here and the call to secmem_init()
869 somewhere after the option parsing */
870 log_set_prefix ("gpgsm", 1);
872 /* Make sure that our subsystems are ready. */
874 init_common_subsystems ();
876 /* Check that the libraries are suitable. Do it here because the
877 option parse may need services of the library */
878 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION
) )
879 log_fatal (_("%s is too old (need %s, have %s)\n"), "libgcrypt",
880 NEED_LIBGCRYPT_VERSION
, gcry_check_version (NULL
) );
881 if (!ksba_check_version (NEED_KSBA_VERSION
) )
882 log_fatal (_("%s is too old (need %s, have %s)\n"), "libksba",
883 NEED_KSBA_VERSION
, ksba_check_version (NULL
) );
886 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL
);
888 may_coredump
= disable_core_dumps ();
890 gnupg_init_signals (0, emergency_cleanup
);
892 create_dotlock (NULL
); /* register locking cleanup */
894 /* Note: If you change this default cipher algorithm , please
895 remember to update the Gpgconflist entry as well. */
896 opt
.def_cipher_algoid
= "3DES"; /*des-EDE3-CBC*/
898 opt
.homedir
= default_homedir ();
900 /* First check whether we have a config file on the commandline */
905 pargs
.flags
= 1|(1<<6); /* do not remove the args, ignore version */
906 while (arg_parse( &pargs
, opts
))
908 if (pargs
.r_opt
== oDebug
|| pargs
.r_opt
== oDebugAll
)
910 else if (pargs
.r_opt
== oOptions
)
911 { /* yes there is one, so we do not try the default one but
912 read the config file when it is encountered at the
916 else if (pargs
.r_opt
== oNoOptions
)
917 default_config
= 0; /* --no-options */
918 else if (pargs
.r_opt
== oHomedir
)
919 opt
.homedir
= pargs
.r
.ret_str
;
920 else if (pargs
.r_opt
== aCallProtectTool
)
921 break; /* This break makes sure that --version and --help are
922 passed to the protect-tool. */
926 /* Initialize the secure memory. */
927 gcry_control (GCRYCTL_INIT_SECMEM
, 16384, 0);
931 Now we are now working under our real uid
934 ksba_set_malloc_hooks (gcry_malloc
, gcry_realloc
, gcry_free
);
936 assuan_set_malloc_hooks (gcry_malloc
, gcry_realloc
, gcry_free
);
937 assuan_set_assuan_log_stream (log_get_stream ());
938 assuan_set_assuan_log_prefix (log_get_prefix (NULL
));
939 assuan_set_assuan_err_source (GPG_ERR_SOURCE_DEFAULT
);
941 keybox_set_malloc_hooks (gcry_malloc
, gcry_realloc
, gcry_free
);
943 /* Setup a default control structure for command line mode */
944 memset (&ctrl
, 0, sizeof ctrl
);
945 gpgsm_init_default_ctrl (&ctrl
);
947 ctrl
.status_fd
= -1; /* not status output */
948 ctrl
.autodetect_encoding
= 1;
950 /* Set the default option file */
952 configname
= make_filename (opt
.homedir
, "gpgsm.conf", NULL
);
953 /* Set the default policy file */
954 opt
.policy_file
= make_filename (opt
.homedir
, "policies.txt", NULL
);
960 pargs
.flags
= 1; /* do not remove the args */
965 configfp
= fopen (configname
, "r");
971 log_info (_("NOTE: no default option file `%s'\n"), configname
);
975 log_error (_("option file `%s': %s\n"), configname
, strerror(errno
));
981 if (parse_debug
&& configname
)
982 log_info (_("reading options from `%s'\n"), configname
);
986 while (!no_more_options
987 && optfile_parse (configfp
, configname
, &configlineno
, &pargs
, opts
))
993 set_cmd (&cmd
, pargs
.r_opt
);
994 do_not_setup_keys
= 1;
1000 set_cmd (&cmd
, aServer
);
1005 set_cmd (&cmd
, aCallDirmngr
);
1006 do_not_setup_keys
= 1;
1009 case aCallProtectTool
:
1011 set_cmd (&cmd
, aCallProtectTool
);
1012 no_more_options
= 1; /* Stop parsing. */
1013 do_not_setup_keys
= 1;
1017 set_cmd (&cmd
, aDeleteKey
);
1019 do_not_setup_keys
= 1;
1024 set_cmd (&cmd
, aSign
);
1028 set_cmd (&cmd
, aKeygen
);
1030 do_not_setup_keys
= 1;
1037 case aExportSecretKeyP12
:
1040 case aDumpExternalKeys
:
1041 case aDumpSecretKeys
:
1043 case aListExternalKeys
:
1044 case aListSecretKeys
:
1048 case aKeydbClearSomeCertFlags
:
1049 do_not_setup_keys
= 1;
1050 set_cmd (&cmd
, pargs
.r_opt
);
1055 set_cmd (&cmd
, pargs
.r_opt
);
1063 set_cmd (&cmd
, pargs
.r_opt
);
1066 /* Output encoding selection. */
1068 ctrl
.create_pem
= 1;
1071 ctrl
.create_pem
= 0;
1072 ctrl
.create_base64
= 1;
1075 ctrl
.create_pem
= 0;
1076 ctrl
.create_base64
= 0;
1080 opt
.p12_charset
= pargs
.r
.ret_str
;
1083 /* Input encoding selection. */
1085 ctrl
.autodetect_encoding
= 0;
1090 ctrl
.autodetect_encoding
= 0;
1095 ctrl
.autodetect_encoding
= 0;
1100 case oDisableCRLChecks
:
1101 opt
.no_crl_check
= 1;
1103 case oEnableCRLChecks
:
1104 opt
.no_crl_check
= 0;
1106 case oDisableTrustedCertCRLCheck
:
1107 opt
.no_trusted_cert_crl_check
= 1;
1109 case oEnableTrustedCertCRLCheck
:
1110 opt
.no_trusted_cert_crl_check
= 0;
1112 case oForceCRLRefresh
:
1113 opt
.force_crl_refresh
= 1;
1117 ctrl
.use_ocsp
= opt
.enable_ocsp
= 0;
1120 ctrl
.use_ocsp
= opt
.enable_ocsp
= 1;
1124 ctrl
.include_certs
= default_include_certs
= pargs
.r
.ret_int
;
1128 xfree (opt
.policy_file
);
1129 if (*pargs
.r
.ret_str
)
1130 opt
.policy_file
= xstrdup (pargs
.r
.ret_str
);
1132 opt
.policy_file
= NULL
;
1135 case oDisablePolicyChecks
:
1136 opt
.no_policy_check
= 1;
1138 case oEnablePolicyChecks
:
1139 opt
.no_policy_check
= 0;
1142 case oAutoIssuerKeyRetrieve
:
1143 opt
.auto_issuer_key_retrieve
= 1;
1146 case oOutput
: opt
.outfile
= pargs
.r
.ret_str
; break;
1149 case oQuiet
: opt
.quiet
= 1; break;
1150 case oNoTTY
: /* fixme:tty_no_terminal(1);*/ break;
1151 case oDryRun
: opt
.dry_run
= 1; break;
1155 gcry_control (GCRYCTL_SET_VERBOSITY
, (int)opt
.verbose
);
1159 gcry_control (GCRYCTL_SET_VERBOSITY
, (int)opt
.verbose
);
1162 case oLogFile
: logfile
= pargs
.r
.ret_str
; break;
1163 case oNoLogFile
: logfile
= NULL
; break;
1165 case oAuditLog
: auditlog
= pargs
.r
.ret_str
; break;
1171 case oNoBatch
: opt
.batch
= 0; break;
1173 case oAnswerYes
: opt
.answer_yes
= 1; break;
1174 case oAnswerNo
: opt
.answer_no
= 1; break;
1176 case oKeyring
: append_to_strlist (&nrings
, pargs
.r
.ret_str
); break;
1178 case oDebug
: debug_value
|= pargs
.r
.ret_ulong
; break;
1179 case oDebugAll
: debug_value
= ~0; break;
1180 case oDebugNone
: debug_value
= 0; break;
1181 case oDebugLevel
: debug_level
= pargs
.r
.ret_str
; break;
1182 case oDebugWait
: debug_wait
= pargs
.r
.ret_int
; break;
1183 case oDebugAllowCoreDump
:
1184 may_coredump
= enable_core_dumps ();
1186 case oDebugNoChainValidation
: opt
.no_chain_validation
= 1; break;
1187 case oDebugIgnoreExpiration
: opt
.ignore_expiration
= 1; break;
1188 case oFixedPassphrase
: opt
.fixed_passphrase
= pargs
.r
.ret_str
; break;
1190 case oStatusFD
: ctrl
.status_fd
= pargs
.r
.ret_int
; break;
1191 case oLoggerFD
: log_set_fd (pargs
.r
.ret_int
); break;
1192 case oWithMD5Fingerprint
:
1193 opt
.with_md5_fingerprint
=1; /*fall thru*/
1194 case oWithFingerprint
:
1195 with_fpr
=1; /*fall thru*/
1201 /* config files may not be nested (silently ignore them) */
1205 configname
= xstrdup (pargs
.r
.ret_str
);
1209 case oNoOptions
: break; /* no-options */
1210 case oHomedir
: opt
.homedir
= pargs
.r
.ret_str
; break;
1211 case oAgentProgram
: opt
.agent_program
= pargs
.r
.ret_str
; break;
1212 case oDisplay
: opt
.display
= xstrdup (pargs
.r
.ret_str
); break;
1213 case oTTYname
: opt
.ttyname
= xstrdup (pargs
.r
.ret_str
); break;
1214 case oTTYtype
: opt
.ttytype
= xstrdup (pargs
.r
.ret_str
); break;
1215 case oLCctype
: opt
.lc_ctype
= xstrdup (pargs
.r
.ret_str
); break;
1216 case oLCmessages
: opt
.lc_messages
= xstrdup (pargs
.r
.ret_str
); break;
1217 case oXauthority
: opt
.xauthority
= xstrdup (pargs
.r
.ret_str
); break;
1218 case oDirmngrProgram
: opt
.dirmngr_program
= pargs
.r
.ret_str
; break;
1219 case oDisableDirmngr
: opt
.disable_dirmngr
= 1; break;
1220 case oPreferSystemDirmngr
: opt
.prefer_system_dirmngr
= 1; break;
1221 case oProtectToolProgram
:
1222 opt
.protect_tool_program
= pargs
.r
.ret_str
;
1225 case oFakedSystemTime
:
1227 time_t faked_time
= isotime2epoch (pargs
.r
.ret_str
);
1228 if (faked_time
== (time_t)(-1))
1229 faked_time
= (time_t)strtoul (pargs
.r
.ret_str
, NULL
, 10);
1230 gnupg_set_time (faked_time
, 0);
1234 case oNoDefKeyring
: default_keyring
= 0; break;
1235 case oNoGreeting
: nogreeting
= 1; break;
1238 if (*pargs
.r
.ret_str
)
1240 xfree (opt
.local_user
);
1241 opt
.local_user
= xstrdup (pargs
.r
.ret_str
);
1245 if (*pargs
.r
.ret_str
)
1246 opt
.def_recipient
= xstrdup (pargs
.r
.ret_str
);
1248 case oDefRecipientSelf
:
1249 xfree (opt
.def_recipient
);
1250 opt
.def_recipient
= NULL
;
1251 opt
.def_recipient_self
= 1;
1253 case oNoDefRecipient
:
1254 xfree (opt
.def_recipient
);
1255 opt
.def_recipient
= NULL
;
1256 opt
.def_recipient_self
= 0;
1259 case oWithKeyData
: opt
.with_key_data
=1; /* fall thru */
1260 case oWithColons
: ctrl
.with_colons
= 1; break;
1261 case oWithValidation
: ctrl
.with_validation
=1; break;
1262 case oWithEphemeralKeys
: opt
.with_ephemeral_keys
=1; break;
1264 case oSkipVerify
: opt
.skip_verify
=1; break;
1266 case oNoEncryptTo
: opt
.no_encrypt_to
= 1; break;
1267 case oEncryptTo
: /* Store the recipient in the second list */
1268 sl
= add_to_strlist (&remusr
, pargs
.r
.ret_str
);
1272 case oRecipient
: /* store the recipient */
1273 add_to_strlist ( &remusr
, pargs
.r
.ret_str
);
1276 case oUser
: /* Store the local users, the first one is the default */
1277 if (!opt
.local_user
)
1278 opt
.local_user
= xstrdup (pargs
.r
.ret_str
);
1279 add_to_strlist (&locusr
, pargs
.r
.ret_str
);
1283 gcry_control (GCRYCTL_DISABLE_SECMEM_WARN
);
1287 opt
.def_cipher_algoid
= pargs
.r
.ret_str
;
1290 case oDisableCipherAlgo
:
1292 int algo
= gcry_cipher_map_name (pargs
.r
.ret_str
);
1293 gcry_cipher_ctl (NULL
, GCRYCTL_DISABLE_ALGO
, &algo
, sizeof algo
);
1296 case oDisablePubkeyAlgo
:
1298 int algo
= gcry_pk_map_name (pargs
.r
.ret_str
);
1299 gcry_pk_ctl (GCRYCTL_DISABLE_ALGO
,&algo
, sizeof algo
);
1304 /* Dummy for now. */
1307 case oExtraDigestAlgo
:
1308 extra_digest_algo
= pargs
.r
.ret_str
;
1311 case oIgnoreTimeConflict
: opt
.ignore_time_conflict
= 1; break;
1312 case oNoRandomSeedFile
: use_random_seed
= 0; break;
1313 case oNoCommonCertsImport
: no_common_certs_import
= 1; break;
1315 case oEnableSpecialFilenames
: allow_special_filenames
=1; break;
1317 case oValidationModel
: parse_validation_model (pargs
.r
.ret_str
); break;
1321 struct keyserver_spec
*keyserver
;
1322 keyserver
= parse_keyserver_line (pargs
.r
.ret_str
,
1323 configname
, configlineno
);
1325 log_error (_("could not parse keyserver\n"));
1328 /* FIXME: Keep last next pointer. */
1329 struct keyserver_spec
**next_p
= &opt
.keyserver
;
1331 next_p
= &(*next_p
)->next
;
1332 *next_p
= keyserver
;
1338 pargs
.err
= configfp
? ARGPARSE_PRINT_WARNING
:ARGPARSE_PRINT_ERROR
;
1347 /* Keep a copy of the config filename. */
1348 opt
.config_filename
= configname
;
1355 if (!opt
.config_filename
)
1356 opt
.config_filename
= make_filename (opt
.homedir
, "gpgsm.conf", NULL
);
1358 if (log_get_errorcount(0))
1361 /* Now that we have the optiosn parsed we need to update the default
1362 control structure. */
1363 gpgsm_init_default_ctrl (&ctrl
);
1370 fprintf(stderr
, "%s %s; %s\n",
1371 strusage(11), strusage(13), strusage(14) );
1372 fprintf(stderr
, "%s\n", strusage(15) );
1374 # ifdef IS_DEVELOPMENT_VERSION
1377 log_info ("NOTE: THIS IS A DEVELOPMENT VERSION!\n");
1378 log_info ("It is only intended for test purposes and should NOT be\n");
1379 log_info ("used in a production environment or with production keys!\n");
1384 log_info ("NOTE: The audit log feature (--audit-log) is "
1385 "WORK IN PRORESS and not ready for use!\n");
1388 if (may_coredump
&& !opt
.quiet
)
1389 log_info (_("WARNING: program may create a core file!\n"));
1391 /* if (opt.qualsig_approval && !opt.quiet) */
1392 /* log_info (_("This software has offically been approved to " */
1393 /* "create and verify\n" */
1394 /* "qualified signatures according to German law.\n")); */
1396 if (logfile
&& cmd
== aServer
)
1398 log_set_file (logfile
);
1399 log_set_prefix (NULL
, 1|2|4);
1402 if (gnupg_faked_time_p ())
1404 gnupg_isotime_t tbuf
;
1406 log_info (_("WARNING: running with faked system time: "));
1407 gnupg_get_isotime (tbuf
);
1408 dump_isotime (tbuf
);
1412 /*FIXME if (opt.batch) */
1413 /* tty_batchmode (1); */
1415 gcry_control (GCRYCTL_RESUME_SECMEM_WARN
);
1419 /* Although we alwasy use gpgsm_exit, we better install a regualr
1420 exit handler so that at least the secure memory gets wiped
1422 if (atexit (emergency_cleanup
))
1424 log_error ("atexit failed\n");
1428 /* Must do this after dropping setuid, because the mapping functions
1429 may try to load an module and we may have disabled an algorithm.
1430 We remap the commonly used algorithms to the OIDs for
1431 convenience. We need to work with the OIDs because they are used
1432 to check whether the encryption mode is actually available. */
1433 if (!strcmp (opt
.def_cipher_algoid
, "3DES") )
1434 opt
.def_cipher_algoid
= "1.2.840.113549.3.7";
1435 else if (!strcmp (opt
.def_cipher_algoid
, "AES")
1436 || !strcmp (opt
.def_cipher_algoid
, "AES128"))
1437 opt
.def_cipher_algoid
= "2.16.840.1.101.3.4.1.2";
1438 else if (!strcmp (opt
.def_cipher_algoid
, "AES256") )
1439 opt
.def_cipher_algoid
= "2.16.840.1.101.3.4.1.42";
1440 else if (!strcmp (opt
.def_cipher_algoid
, "SERPENT")
1441 || !strcmp (opt
.def_cipher_algoid
, "SERPENT128") )
1442 opt
.def_cipher_algoid
= "1.3.6.1.4.1.11591.13.2.2";
1443 else if (!strcmp (opt
.def_cipher_algoid
, "SERPENT192") )
1444 opt
.def_cipher_algoid
= "1.3.6.1.4.1.11591.13.2.22";
1445 else if (!strcmp (opt
.def_cipher_algoid
, "SERPENT192") )
1446 opt
.def_cipher_algoid
= "1.3.6.1.4.1.11591.13.2.42";
1447 else if (!strcmp (opt
.def_cipher_algoid
, "SEED") )
1448 opt
.def_cipher_algoid
= "1.2.410.200004.1.4";
1449 else if (!strcmp (opt
.def_cipher_algoid
, "CAMELLIA")
1450 || !strcmp (opt
.def_cipher_algoid
, "CAMELLIA128") )
1451 opt
.def_cipher_algoid
= "1.2.392.200011.61.1.1.1.2";
1452 else if (!strcmp (opt
.def_cipher_algoid
, "CAMELLIA192") )
1453 opt
.def_cipher_algoid
= "1.2.392.200011.61.1.1.1.3";
1454 else if (!strcmp (opt
.def_cipher_algoid
, "CAMELLIA256") )
1455 opt
.def_cipher_algoid
= "1.2.392.200011.61.1.1.1.4";
1457 if (cmd
!= aGPGConfList
)
1459 if ( !gcry_cipher_map_name (opt
.def_cipher_algoid
)
1460 || !gcry_cipher_mode_from_oid (opt
.def_cipher_algoid
))
1461 log_error (_("selected cipher algorithm is invalid\n"));
1463 if (def_digest_string
)
1465 opt
.def_digest_algo
= gcry_md_map_name (def_digest_string
);
1466 xfree (def_digest_string
);
1467 def_digest_string
= NULL
;
1468 if (our_md_test_algo(opt
.def_digest_algo
) )
1469 log_error (_("selected digest algorithm is invalid\n"));
1471 if (extra_digest_algo
)
1473 opt
.extra_digest_algo
= gcry_md_map_name (extra_digest_algo
);
1474 if (our_md_test_algo (opt
.extra_digest_algo
) )
1475 log_error (_("selected digest algorithm is invalid\n"));
1479 if (log_get_errorcount(0))
1482 /* Set the random seed file. */
1483 if (use_random_seed
)
1485 char *p
= make_filename (opt
.homedir
, "random_seed", NULL
);
1486 gcry_control (GCRYCTL_SET_RANDOM_SEED_FILE
, p
);
1490 if (!cmd
&& opt
.fingerprint
&& !with_fpr
)
1491 set_cmd (&cmd
, aListKeys
);
1493 /* Add default keybox. */
1494 if (!nrings
&& default_keyring
)
1498 keydb_add_resource ("pubring.kbx", 0, 0, &created
);
1499 if (created
&& !no_common_certs_import
)
1501 /* Import the standard certificates for a new default keybox. */
1504 filelist
[0] = make_filename (gnupg_datadir (),"com-certs.pem", NULL
);
1506 if (!access (filelist
[0], F_OK
))
1508 log_info (_("importing common certificates `%s'\n"),
1510 gpgsm_import_files (&ctrl
, 1, filelist
, open_read
);
1512 xfree (filelist
[0]);
1515 for (sl
= nrings
; sl
; sl
= sl
->next
)
1516 keydb_add_resource (sl
->d
, 0, 0, NULL
);
1517 FREE_STRLIST(nrings
);
1520 /* Prepare the audit log feature for certain commands. */
1529 audit_release (ctrl
.audit
);
1530 ctrl
.audit
= audit_new ();
1531 auditfp
= open_es_fwrite (auditlog
);
1539 if (!do_not_setup_keys
)
1541 for (sl
= locusr
; sl
; sl
= sl
->next
)
1543 int rc
= gpgsm_add_to_certlist (&ctrl
, sl
->d
, 1, &signerlist
, 0);
1546 log_error (_("can't sign using `%s': %s\n"),
1547 sl
->d
, gpg_strerror (rc
));
1548 gpgsm_status2 (&ctrl
, STATUS_INV_RECP
,
1549 gpg_err_code (rc
) == -1? "1":
1550 gpg_err_code (rc
) == GPG_ERR_NO_PUBKEY
? "1":
1551 gpg_err_code (rc
) == GPG_ERR_AMBIGUOUS_NAME
? "2":
1552 gpg_err_code (rc
) == GPG_ERR_WRONG_KEY_USAGE
? "3":
1553 gpg_err_code (rc
) == GPG_ERR_CERT_REVOKED
? "4":
1554 gpg_err_code (rc
) == GPG_ERR_CERT_EXPIRED
? "5":
1555 gpg_err_code (rc
) == GPG_ERR_NO_CRL_KNOWN
? "6":
1556 gpg_err_code (rc
) == GPG_ERR_CRL_TOO_OLD
? "7":
1557 gpg_err_code (rc
) == GPG_ERR_NO_POLICY_MATCH
? "8":
1558 gpg_err_code (rc
) == GPG_ERR_NO_SECKEY
? "9":
1564 /* Build the recipient list. We first add the regular ones and then
1565 the encrypt-to ones because the underlying function will silently
1566 ignore duplicates and we can't allow to keep a duplicate which is
1567 flagged as encrypt-to as the actually encrypt function would then
1568 complain about no (regular) recipients. */
1569 for (sl
= remusr
; sl
; sl
= sl
->next
)
1570 if (!(sl
->flags
& 1))
1571 do_add_recipient (&ctrl
, sl
->d
, &recplist
, 0, recp_required
);
1572 if (!opt
.no_encrypt_to
)
1574 for (sl
= remusr
; sl
; sl
= sl
->next
)
1575 if ((sl
->flags
& 1))
1576 do_add_recipient (&ctrl
, sl
->d
, &recplist
, 1, recp_required
);
1580 if (log_get_errorcount(0))
1581 gpgsm_exit(1); /* Must stop for invalid recipients. */
1583 fname
= argc
? *argv
: NULL
;
1585 /* Dispatch command. */
1589 { /* List options and default values in the GPG Conf format. */
1590 char *config_filename_esc
= percent_escape (opt
.config_filename
, NULL
);
1592 printf ("gpgconf-gpgsm.conf:%lu:\"%s\n",
1593 GC_OPT_FLAG_DEFAULT
, config_filename_esc
);
1594 xfree (config_filename_esc
);
1596 printf ("verbose:%lu:\n", GC_OPT_FLAG_NONE
);
1597 printf ("quiet:%lu:\n", GC_OPT_FLAG_NONE
);
1598 printf ("debug-level:%lu:\"none:\n", GC_OPT_FLAG_DEFAULT
);
1599 printf ("log-file:%lu:\n", GC_OPT_FLAG_NONE
);
1600 printf ("disable-crl-checks:%lu:\n", GC_OPT_FLAG_NONE
);
1601 printf ("disable-trusted-cert-crl-check:%lu:\n", GC_OPT_FLAG_NONE
);
1602 printf ("enable-ocsp:%lu:\n", GC_OPT_FLAG_NONE
);
1603 printf ("include-certs:%lu:1:\n", GC_OPT_FLAG_DEFAULT
);
1604 printf ("disable-policy-checks:%lu:\n", GC_OPT_FLAG_NONE
);
1605 printf ("auto-issuer-key-retrieve:%lu:\n", GC_OPT_FLAG_NONE
);
1606 printf ("disable-dirmngr:%lu:\n", GC_OPT_FLAG_NONE
);
1607 #ifndef HAVE_W32_SYSTEM
1608 printf ("prefer-system-dirmngr:%lu:\n", GC_OPT_FLAG_NONE
);
1610 printf ("cipher-algo:%lu:\"3DES:\n", GC_OPT_FLAG_DEFAULT
);
1611 printf ("p12-charset:%lu:\n", GC_OPT_FLAG_DEFAULT
);
1612 printf ("default-key:%lu:\n", GC_OPT_FLAG_DEFAULT
);
1613 printf ("encrypt-to:%lu:\n", GC_OPT_FLAG_DEFAULT
);
1614 printf ("keyserver:%lu:\n", GC_OPT_FLAG_NONE
);
1619 /* This is merely a dummy command to test whether the
1620 configuration file is valid. */
1626 log_debug ("waiting for debugger - my pid is %u .....\n",
1627 (unsigned int)getpid());
1628 gnupg_sleep (debug_wait
);
1629 log_debug ("... okay\n");
1631 gpgsm_server (recplist
);
1636 wrong_args ("--call-dirmngr <command> {args}");
1638 if (gpgsm_dirmngr_run_command (&ctrl
, *argv
, argc
-1, argv
+1))
1642 case aCallProtectTool
:
1643 run_protect_tool (argc
, argv
);
1646 case aEncr
: /* Encrypt the given file. */
1648 FILE *fp
= open_fwrite (opt
.outfile
?opt
.outfile
:"-");
1652 if (!argc
) /* Source is stdin. */
1653 gpgsm_encrypt (&ctrl
, recplist
, 0, fp
);
1654 else if (argc
== 1) /* Source is the given file. */
1655 gpgsm_encrypt (&ctrl
, recplist
, open_read (*argv
), fp
);
1657 wrong_args ("--encrypt [datafile]");
1664 case aSign
: /* Sign the given file. */
1666 FILE *fp
= open_fwrite (opt
.outfile
?opt
.outfile
:"-");
1668 /* Fixme: We should also allow to concatenate multiple files for
1669 signing because that is what gpg does.*/
1671 if (!argc
) /* Create from stdin. */
1672 gpgsm_sign (&ctrl
, signerlist
, 0, detached_sig
, fp
);
1673 else if (argc
== 1) /* From file. */
1674 gpgsm_sign (&ctrl
, signerlist
,
1675 open_read (*argv
), detached_sig
, fp
);
1677 wrong_args ("--sign [datafile]");
1684 case aSignEncr
: /* sign and encrypt the given file */
1685 log_error ("this command has not yet been implemented\n");
1688 case aClearsign
: /* make a clearsig */
1689 log_error ("this command has not yet been implemented\n");
1697 if (argc
== 2 && opt
.outfile
)
1698 log_info ("option --output ignored for a detached signature\n");
1699 else if (opt
.outfile
)
1700 fp
= open_fwrite (opt
.outfile
);
1703 gpgsm_verify (&ctrl
, 0, -1, fp
); /* normal signature from stdin */
1705 gpgsm_verify (&ctrl
, open_read (*argv
), -1, fp
); /* std signature */
1706 else if (argc
== 2) /* detached signature (sig, detached) */
1707 gpgsm_verify (&ctrl
, open_read (*argv
), open_read (argv
[1]), NULL
);
1709 wrong_args ("--verify [signature [detached_data]]");
1711 if (fp
&& fp
!= stdout
)
1717 log_error (_("this command has not yet been implemented\n"));
1722 FILE *fp
= open_fwrite (opt
.outfile
?opt
.outfile
:"-");
1726 gpgsm_decrypt (&ctrl
, 0, fp
); /* from stdin */
1728 gpgsm_decrypt (&ctrl
, open_read (*argv
), fp
); /* from file */
1730 wrong_args ("--decrypt [filename]");
1737 for (sl
=NULL
; argc
; argc
--, argv
++)
1738 add_to_strlist (&sl
, *argv
);
1739 gpgsm_delete (&ctrl
, sl
);
1745 ctrl
.with_chain
= 1;
1748 case aListExternalKeys
:
1749 case aDumpExternalKeys
:
1750 case aListSecretKeys
:
1751 case aDumpSecretKeys
:
1759 case aListKeys
: mode
= (0 | 0 | (1<<6)); break;
1761 case aDumpKeys
: mode
= (256 | 0 | (1<<6)); break;
1762 case aListExternalKeys
: mode
= (0 | 0 | (1<<7)); break;
1763 case aDumpExternalKeys
: mode
= (256 | 0 | (1<<7)); break;
1764 case aListSecretKeys
: mode
= (0 | 2 | (1<<6)); break;
1765 case aDumpSecretKeys
: mode
= (256 | 2 | (1<<6)); break;
1769 fp
= open_es_fwrite (opt
.outfile
?opt
.outfile
:"-");
1770 for (sl
=NULL
; argc
; argc
--, argv
++)
1771 add_to_strlist (&sl
, *argv
);
1772 gpgsm_list_keys (&ctrl
, sl
, fp
, mode
);
1779 case aKeygen
: /* Generate a key; well kind of. */
1781 FILE *fp
= open_fwrite (opt
.outfile
?opt
.outfile
:"-");
1782 gpgsm_gencertreq_tty (&ctrl
, fp
);
1790 gpgsm_import_files (&ctrl
, argc
, argv
, open_read
);
1795 FILE *fp
= open_fwrite (opt
.outfile
?opt
.outfile
:"-");
1797 for (sl
=NULL
; argc
; argc
--, argv
++)
1798 add_to_strlist (&sl
, *argv
);
1799 gpgsm_export (&ctrl
, sl
, fp
, NULL
);
1806 case aExportSecretKeyP12
:
1808 FILE *fp
= open_fwrite (opt
.outfile
?opt
.outfile
:"-");
1811 gpgsm_p12_export (&ctrl
, *argv
, fp
);
1813 wrong_args ("--export-secret-key-p12 KEY-ID");
1821 log_error ("this command has not yet been implemented\n");
1827 wrong_args ("--learn-card");
1830 int rc
= gpgsm_agent_learn (&ctrl
);
1832 log_error ("error learning card: %s\n", gpg_strerror (rc
));
1838 wrong_args ("--passwd <key-Id>");
1842 ksba_cert_t cert
= NULL
;
1845 rc
= gpgsm_find_cert (*argv
, NULL
, &cert
);
1848 else if (!(grip
= gpgsm_get_keygrip_hexstring (cert
)))
1849 rc
= gpg_error (GPG_ERR_BUG
);
1852 char *desc
= gpgsm_format_keydesc (cert
);
1853 rc
= gpgsm_agent_passwd (&ctrl
, grip
, desc
);
1857 log_error ("error changing passphrase: %s\n", gpg_strerror (rc
));
1859 ksba_cert_release (cert
);
1863 case aKeydbClearSomeCertFlags
:
1864 for (sl
=NULL
; argc
; argc
--, argv
++)
1865 add_to_strlist (&sl
, *argv
);
1866 keydb_clear_some_cert_flags (&ctrl
, sl
);
1872 log_error (_("invalid command (there is no implicit command)\n"));
1876 /* Print the audit result if needed. */
1877 if (auditlog
&& auditfp
)
1879 audit_print_result (ctrl
.audit
, auditfp
, 0);
1880 audit_release (ctrl
.audit
);
1882 es_fclose (auditfp
);
1886 keyserver_list_free (opt
.keyserver
);
1887 opt
.keyserver
= NULL
;
1888 gpgsm_release_certlist (recplist
);
1889 gpgsm_release_certlist (signerlist
);
1890 FREE_STRLIST (remusr
);
1891 FREE_STRLIST (locusr
);
1893 return 8; /*NOTREACHED*/
1896 /* Note: This function is used by signal handlers!. */
1898 emergency_cleanup (void)
1900 gcry_control (GCRYCTL_TERM_SECMEM
);
1907 gcry_control (GCRYCTL_UPDATE_RANDOM_SEED_FILE
);
1908 if (opt
.debug
& DBG_MEMSTAT_VALUE
)
1910 gcry_control( GCRYCTL_DUMP_MEMORY_STATS
);
1911 gcry_control( GCRYCTL_DUMP_RANDOM_STATS
);
1914 gcry_control (GCRYCTL_DUMP_SECMEM_STATS
);
1915 emergency_cleanup ();
1916 rc
= rc
? rc
: log_get_errorcount(0)? 2 : gpgsm_errors_seen
? 1 : 0;
1922 gpgsm_init_default_ctrl (struct server_control_s
*ctrl
)
1924 ctrl
->include_certs
= default_include_certs
;
1925 ctrl
->use_ocsp
= opt
.enable_ocsp
;
1926 ctrl
->validation_model
= default_validation_model
;
1931 gpgsm_parse_validation_model (const char *model
)
1933 if (!ascii_strcasecmp (model
, "shell") )
1935 else if ( !ascii_strcasecmp (model
, "chain") )
1942 /* Check whether the filename has the form "-&nnnn", where n is a
1943 non-zero number. Returns this number or -1 if it is not the case. */
1945 check_special_filename (const char *fname
, int for_write
)
1947 if (allow_special_filenames
1948 && fname
&& *fname
== '-' && fname
[1] == '&' ) {
1952 for (i
=0; isdigit (fname
[i
]); i
++ )
1955 return translate_sys2libc_fd_int (atoi (fname
), for_write
);
1962 /* Open the FILENAME for read and return the filedescriptor. Stop
1963 with an error message in case of problems. "-" denotes stdin and
1964 if special filenames are allowed the given fd is opened instead. */
1966 open_read (const char *filename
)
1970 if (filename
[0] == '-' && !filename
[1])
1973 return 0; /* stdin */
1975 fd
= check_special_filename (filename
, 0);
1978 fd
= open (filename
, O_RDONLY
| O_BINARY
);
1981 log_error (_("can't open `%s': %s\n"), filename
, strerror (errno
));
1987 /* Open FILENAME for fwrite and return the stream. Stop with an error
1988 message in case of problems. "-" denotes stdout and if special
1989 filenames are allowed the given fd is opened instead. Caller must
1990 close the returned stream unless it is stdout. */
1992 open_fwrite (const char *filename
)
1997 if (filename
[0] == '-' && !filename
[1])
1999 set_binary (stdout
);
2003 fd
= check_special_filename (filename
, 1);
2006 fp
= fdopen (dup (fd
), "wb");
2009 log_error ("fdopen(%d) failed: %s\n", fd
, strerror (errno
));
2015 fp
= fopen (filename
, "wb");
2018 log_error (_("can't open `%s': %s\n"), filename
, strerror (errno
));
2025 /* Open FILENAME for fwrite and return an extended stream. Stop with
2026 an error message in case of problems. "-" denotes stdout and if
2027 special filenames are allowed the given fd is opened instead.
2028 Caller must close the returned stream. */
2030 open_es_fwrite (const char *filename
)
2035 if (filename
[0] == '-' && !filename
[1])
2038 fp
= es_fdopen_nc (fileno(stdout
), "wb");
2042 fd
= check_special_filename (filename
, 1);
2045 fp
= es_fdopen_nc (fd
, "wb");
2048 log_error ("es_fdopen(%d) failed: %s\n", fd
, strerror (errno
));
2053 fp
= es_fopen (filename
, "wb");
2056 log_error (_("can't open `%s': %s\n"), filename
, strerror (errno
));
2064 run_protect_tool (int argc
, char **argv
)
2066 #ifndef HAVE_W32_SYSTEM
2071 if (!opt
.protect_tool_program
|| !*opt
.protect_tool_program
)
2072 pgm
= gnupg_module_name (GNUPG_MODULE_NAME_PROTECT_TOOL
);
2074 pgm
= opt
.protect_tool_program
;
2076 av
= xcalloc (argc
+2, sizeof *av
);
2077 av
[0] = strrchr (pgm
, '/');
2079 av
[0] = xstrdup (pgm
);
2080 for (i
=1; argc
; i
++, argc
--, argv
++)
2084 log_error ("error executing `%s': %s\n", pgm
, strerror (errno
));
2085 #endif /*HAVE_W32_SYSTEM*/