1 /* gpg-wks-client.c - A client for the Web Key Service protocols.
2 * Copyright (C) 2016, 2022 g10 Code GmbH
3 * Copyright (C) 2016 Bundesamt für Sicherheit in der Informationstechnik
5 * This file is part of GnuPG.
7 * This file is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU Lesser General Public License as
9 * published by the Free Software Foundation; either version 2.1 of
10 * the License, or (at your option) any later version.
12 * This file 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 Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public License
18 * along with this program; if not, see <https://www.gnu.org/licenses/>.
19 * SPDX-License-Identifier: LGPL-2.1-or-later
27 #include <sys/types.h>
30 #define INCLUDED_BY_MAIN_MODULE 1
31 #include "../common/util.h"
32 #include "../common/status.h"
33 #include "../common/i18n.h"
34 #include "../common/sysutils.h"
35 #include "../common/init.h"
36 #include "../common/asshelp.h"
37 #include "../common/userids.h"
38 #include "../common/ccparray.h"
39 #include "../common/exectool.h"
40 #include "../common/mbox-util.h"
41 #include "../common/name-value.h"
42 #include "../common/comopt.h"
43 #include "call-dirmngr.h"
44 #include "mime-maker.h"
45 #include "send-mail.h"
49 /* Constants to identify the commands and options. */
50 enum cmd_and_opt_values
84 /* The list of commands and options. */
85 static gpgrt_opt_t opts[] = {
86 ARGPARSE_group (300, ("@Commands:\n ")),
88 ARGPARSE_c (aSupported, "supported",
89 ("check whether provider supports WKS")),
90 ARGPARSE_c (aCheck, "check",
91 ("check whether a key is available")),
92 ARGPARSE_c (aCreate, "create",
93 ("create a publication request")),
94 ARGPARSE_c (aReceive, "receive",
95 ("receive a MIME confirmation request")),
96 ARGPARSE_c (aRead, "read",
97 ("receive a plain text confirmation request")),
98 ARGPARSE_c (aMirror, "mirror",
99 "mirror an LDAP directory"),
100 ARGPARSE_c (aInstallKey, "install-key",
101 "install a key into a directory"),
102 ARGPARSE_c (aRemoveKey, "remove-key",
103 "remove a key from a directory"),
104 ARGPARSE_c (aPrintWKDHash, "print-wkd-hash",
105 "Print the WKD identifier for the given user ids"),
106 ARGPARSE_c (aPrintWKDURL, "print-wkd-url",
107 "Print the WKD URL for the given user id"),
109 ARGPARSE_group (301, ("@\nOptions:\n ")),
111 ARGPARSE_s_n (oVerbose, "verbose", ("verbose")),
112 ARGPARSE_s_n (oQuiet, "quiet", ("be somewhat more quiet")),
113 ARGPARSE_s_s (oDebug, "debug", "@"),
114 ARGPARSE_s_s (oGpgProgram, "gpg", "@"),
115 ARGPARSE_s_n (oSend, "send", "send the mail using sendmail"),
116 ARGPARSE_s_s (oOutput, "output", "|FILE|write the mail to FILE"),
117 ARGPARSE_s_i (oStatusFD, "status-fd", N_("|FD|write status info to this FD")),
118 ARGPARSE_s_n (oNoAutostart, "no-autostart", "@"),
119 ARGPARSE_s_n (oWithColons, "with-colons", "@"),
120 ARGPARSE_s_s (oBlacklist, "blacklist", "@"),
121 ARGPARSE_s_s (oDirectory, "directory", "@"),
123 ARGPARSE_s_s (oFakeSubmissionAddr, "fake-submission-addr", "@"),
129 /* The list of supported debug flags. */
130 static struct debug_flags_s debug_flags [] =
132 { DBG_MIME_VALUE , "mime" },
133 { DBG_PARSER_VALUE , "parser" },
134 { DBG_CRYPTO_VALUE , "crypto" },
135 { DBG_MEMORY_VALUE , "memory" },
136 { DBG_MEMSTAT_VALUE, "memstat" },
137 { DBG_IPC_VALUE , "ipc" },
138 { DBG_EXTPROG_VALUE, "extprog" },
144 /* Value of the option --fake-submission-addr. */
145 const char *fake_submission_addr;
147 /* An array with blacklisted addresses and its length. Use
148 * is_in_blacklist to check. */
149 static char **blacklist_array;
150 static size_t blacklist_array_len;
153 static void wrong_args (const char *text) GPGRT_ATTR_NORETURN;
154 static void add_blacklist (const char *fname);
155 static gpg_error_t proc_userid_from_stdin (gpg_error_t (*func)(const char *),
157 static gpg_error_t command_supported (char *userid);
158 static gpg_error_t command_check (char *userid);
159 static gpg_error_t command_send (const char *fingerprint, const char *userid);
160 static gpg_error_t encrypt_response (estream_t *r_output, estream_t input,
161 const char *addrspec,
162 const char *fingerprint);
163 static gpg_error_t read_confirmation_request (estream_t msg);
164 static gpg_error_t command_receive_cb (void *opaque,
165 const char *mediatype, estream_t fp,
167 static gpg_error_t command_mirror (char *domain[]);
171 /* Print usage information and provide strings for help. */
173 my_strusage( int level )
179 case 9: p = "LGPL-2.1-or-later"; break;
180 case 11: p = "gpg-wks-client"; break;
181 case 12: p = "@GNUPG@"; break;
182 case 13: p = VERSION; break;
183 case 14: p = GNUPG_DEF_COPYRIGHT_LINE; break;
184 case 17: p = PRINTABLE_OS_NAME; break;
185 case 19: p = ("Please report bugs to <@EMAIL@>.\n"); break;
189 p = ("Usage: gpg-wks-client [command] [options] [args] (-h for help)");
192 p = ("Syntax: gpg-wks-client [command] [options] [args]\n"
193 "Client for the Web Key Service\n");
196 default: p = NULL; break;
203 wrong_args (const char *text)
205 es_fprintf (es_stderr, _("usage: %s [options] %s\n"),
206 gpgrt_strusage (11), text);
212 /* Command line parsing. */
213 static enum cmd_and_opt_values
214 parse_arguments (gpgrt_argparse_t *pargs, gpgrt_opt_t *popts)
216 enum cmd_and_opt_values cmd = 0;
217 int no_more_options = 0;
219 while (!no_more_options && gpgrt_argparse (NULL, pargs, popts))
221 switch (pargs->r_opt)
223 case oQuiet: opt.quiet = 1; break;
224 case oVerbose: opt.verbose++; break;
226 if (parse_debug_flag (pargs->r.ret_str, &opt.debug, debug_flags))
228 pargs->r_opt = ARGPARSE_INVALID_ARG;
229 pargs->err = ARGPARSE_PRINT_ERROR;
234 opt.gpg_program = pargs->r.ret_str;
237 opt.directory = pargs->r.ret_str;
240 opt.use_sendmail = 1;
243 opt.output = pargs->r.ret_str;
245 case oFakeSubmissionAddr:
246 fake_submission_addr = pargs->r.ret_str;
249 wks_set_status_fd (translate_sys2libc_fd_int (pargs->r.ret_int, 1));
255 opt.no_autostart = 1;
258 add_blacklist (pargs->r.ret_str);
274 default: pargs->err = ARGPARSE_PRINT_ERROR; break;
283 /* gpg-wks-client main. */
285 main (int argc, char **argv)
287 gpg_error_t err, delayed_err;
288 gpgrt_argparse_t pargs;
289 enum cmd_and_opt_values cmd;
291 gnupg_reopen_std ("gpg-wks-client");
292 gpgrt_set_strusage (my_strusage);
293 log_set_prefix ("gpg-wks-client", GPGRT_LOG_WITH_PREFIX);
295 /* Make sure that our subsystems are ready. */
297 init_common_subsystems (&argc, &argv);
299 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
300 setup_libassuan_logging (&opt.debug, NULL);
302 /* Parse the command line. */
305 pargs.flags = ARGPARSE_FLAG_KEEP;
306 cmd = parse_arguments (&pargs, opts);
307 gpgrt_argparse (NULL, &pargs, NULL);
309 /* Check if gpg is build with sendmail support */
310 if (opt.use_sendmail && !NAME_OF_SENDMAIL[0])
312 err = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
313 log_error ("sending mail is not supported in this build: %s\n",
317 if (log_get_errorcount (0))
320 /* Process common component options. Note that we set the config
321 * dir only here so that --homedir will have an effect. */
322 gpgrt_set_confdir (GPGRT_CONFDIR_SYS, gnupg_sysconfdir ());
323 gpgrt_set_confdir (GPGRT_CONFDIR_USER, gnupg_homedir ());
324 if (parse_comopt (GNUPG_MODULE_NAME_CONNECT_AGENT, opt.verbose > 1))
326 if (comopt.no_autostart)
327 opt.no_autostart = 1;
329 /* Print a warning if an argument looks like an option. */
330 if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
334 for (i=0; i < argc; i++)
335 if (argv[i][0] == '-' && argv[i][1] == '-')
336 log_info (("NOTE: '%s' is not considered an option\n"), argv[i]);
339 /* Set defaults for non given options. */
340 if (!opt.gpg_program)
341 opt.gpg_program = gnupg_module_name (GNUPG_MODULE_NAME_GPG);
344 opt.directory = "openpgpkey";
346 /* Tell call-dirmngr what options we want. */
347 set_dirmngr_options (opt.verbose, (opt.debug & DBG_IPC_VALUE),
351 /* Check that the top directory exists. */
352 if (cmd == aInstallKey || cmd == aRemoveKey || cmd == aMirror)
356 if (gnupg_stat (opt.directory, &sb))
358 err = gpg_error_from_syserror ();
359 log_error ("error accessing directory '%s': %s\n",
360 opt.directory, gpg_strerror (err));
363 if (!S_ISDIR(sb.st_mode))
365 log_error ("error accessing directory '%s': %s\n",
366 opt.directory, "not a directory");
367 err = gpg_error (GPG_ERR_ENOENT);
372 /* Run the selected command. */
378 for (; argc; argc--, argv++)
379 command_supported (*argv);
385 wrong_args ("--supported DOMAIN");
386 err = command_supported (argv[0]);
387 if (err && gpg_err_code (err) != GPG_ERR_FALSE)
388 log_error ("checking support failed: %s\n", gpg_strerror (err));
394 wrong_args ("--create FINGERPRINT USER-ID");
395 err = command_send (argv[0], argv[1]);
397 log_error ("creating request failed: %s\n", gpg_strerror (err));
402 wrong_args ("--receive < MIME-DATA");
403 err = wks_receive (es_stdin, command_receive_cb, NULL);
405 log_error ("processing mail failed: %s\n", gpg_strerror (err));
410 wrong_args ("--read < WKS-DATA");
411 err = read_confirmation_request (es_stdin);
413 log_error ("processing mail failed: %s\n", gpg_strerror (err));
418 wrong_args ("--check USER-ID");
419 err = command_check (argv[0]);
424 err = command_mirror (NULL);
426 err = command_mirror (argv);
431 err = wks_cmd_install_key (NULL, NULL);
433 err = wks_cmd_install_key (*argv, argv[1]);
435 wrong_args ("--install-key [FILE|FINGERPRINT USER-ID]");
440 wrong_args ("--remove-key USER-ID");
441 err = wks_cmd_remove_key (*argv);
448 if (cmd == aPrintWKDHash)
449 err = proc_userid_from_stdin (wks_cmd_print_wkd_hash,
450 "printing WKD hash");
452 err = proc_userid_from_stdin (wks_cmd_print_wkd_url,
457 for (err = delayed_err = 0; !err && argc; argc--, argv++)
459 if (cmd == aPrintWKDHash)
460 err = wks_cmd_print_wkd_hash (*argv);
462 err = wks_cmd_print_wkd_url (*argv);
463 if (gpg_err_code (err) == GPG_ERR_INV_USER_ID)
465 /* Diagnostic already printed. */
470 log_error ("printing hash failed: %s\n", gpg_strerror (err));
485 wks_write_status (STATUS_FAILURE, "- %u", err);
486 else if (log_get_errorcount (0))
487 wks_write_status (STATUS_FAILURE, "- %u", GPG_ERR_GENERAL);
489 wks_write_status (STATUS_SUCCESS, NULL);
490 return (err || log_get_errorcount (0))? 1:0;
495 /* Read a file FNAME into a buffer and return that malloced buffer.
496 * Caller must free the buffer. On error NULL is returned, on success
497 * the valid length of the buffer is stored at R_LENGTH. The returned
498 * buffer is guaranteed to be Nul terminated. */
500 read_file (const char *fname, size_t *r_length)
506 if (!strcmp (fname, "-"))
508 size_t nread, bufsize = 0;
519 buf = xmalloc (bufsize+1);
521 buf = xrealloc (buf, bufsize+1);
523 nread = es_fread (buf+buflen, 1, NCHUNK, fp);
524 if (nread < NCHUNK && es_ferror (fp))
526 log_error ("error reading '[stdin]': %s\n", strerror (errno));
532 while (nread == NCHUNK);
539 fp = es_fopen (fname, "rb");
542 log_error ("can't open '%s': %s\n", fname, strerror (errno));
546 if (fstat (es_fileno (fp), &st))
548 log_error ("can't stat '%s': %s\n", fname, strerror (errno));
554 buf = xmalloc (buflen+1);
555 if (es_fread (buf, buflen, 1, fp) != 1)
557 log_error ("error reading '%s': %s\n", fname, strerror (errno));
572 cmp_blacklist (const void *arg_a, const void *arg_b)
574 const char *a = *(const char **)arg_a;
575 const char *b = *(const char **)arg_b;
576 return strcmp (a, b);
580 /* Add a blacklist to our global table. This is called during option
581 * parsing and thus any use of log_error will eventually stop further
584 add_blacklist (const char *fname)
589 size_t arraysize, arrayidx;
591 buffer = read_file (fname, NULL);
595 /* Estimate the number of entries by counting the non-comment lines. */
596 arraysize = 2; /* For the first and an extra NULL item. */
597 for (p=buffer; *p; p++)
598 if (*p == '\n' && p[1] && p[1] != '#')
601 array = xcalloc (arraysize, sizeof *array);
604 /* Loop over all lines. */
605 for (p = buffer; p && *p; p = pend)
607 pend = strchr (p, '\n');
611 if (!*p || *p == '#' )
614 log_assert (arrayidx < arraysize);
618 log_assert (arrayidx < arraysize);
620 qsort (array, arrayidx, sizeof *array, cmp_blacklist);
622 blacklist_array = array;
623 blacklist_array_len = arrayidx;
624 gpgrt_annotate_leaked_object (buffer);
625 gpgrt_annotate_leaked_object (blacklist_array);
629 /* Return true if NAME is in a blacklist. */
631 is_in_blacklist (const char *name)
633 if (!name || !blacklist_array)
635 return !!bsearch (&name, blacklist_array, blacklist_array_len,
636 sizeof *blacklist_array, cmp_blacklist);
641 /* Read user ids from stdin and call FUNC for each user id. TEXT is
642 * used for error messages. */
644 proc_userid_from_stdin (gpg_error_t (*func)(const char *), const char *text)
647 gpg_error_t delayed_err = 0;
651 /* If we are on a terminal disable buffering to get direct response. */
652 if (gnupg_isatty (es_fileno (es_stdin))
653 && gnupg_isatty (es_fileno (es_stdout)))
655 es_setvbuf (es_stdin, NULL, _IONBF, 0);
656 es_setvbuf (es_stdout, NULL, _IOLBF, 0);
659 while (es_fgets (line, sizeof line - 1, es_stdin))
662 if (!n || line[n-1] != '\n')
664 err = gpg_error (*line? GPG_ERR_LINE_TOO_LONG
665 : GPG_ERR_INCOMPLETE_LINE);
666 log_error ("error reading stdin: %s\n", gpg_strerror (err));
671 if (gpg_err_code (err) == GPG_ERR_INV_USER_ID)
677 log_error ("%s failed: %s\n", text, gpg_strerror (err));
679 if (es_ferror (es_stdin))
681 err = gpg_error_from_syserror ();
682 log_error ("error reading stdin: %s\n", gpg_strerror (err));
695 /* Add the user id UID to the key identified by FINGERPRINT. */
697 add_user_id (const char *fingerprint, const char *uid)
701 const char **argv = NULL;
703 ccparray_init (&ccp, 0);
705 ccparray_put (&ccp, "--no-options");
707 ccparray_put (&ccp, "--quiet");
709 ccparray_put (&ccp, "--verbose");
710 ccparray_put (&ccp, "--batch");
711 ccparray_put (&ccp, "--always-trust");
712 ccparray_put (&ccp, "--quick-add-uid");
713 ccparray_put (&ccp, fingerprint);
714 ccparray_put (&ccp, uid);
716 ccparray_put (&ccp, NULL);
717 argv = ccparray_get (&ccp, NULL);
720 err = gpg_error_from_syserror ();
723 err = gnupg_exec_tool_stream (opt.gpg_program, argv, NULL,
728 log_error ("adding user id failed: %s\n", gpg_strerror (err));
739 struct decrypt_stream_parm_s
747 decrypt_stream_status_cb (void *opaque, const char *keyword, char *args)
749 struct decrypt_stream_parm_s *decinfo = opaque;
752 log_debug ("gpg status: %s %s\n", keyword, args);
753 if (!strcmp (keyword, "DECRYPTION_KEY") && !decinfo->fpr)
755 const char *fields[3];
757 if (split_fields (args, fields, DIM (fields)) >= 3)
759 decinfo->fpr = xstrdup (fields[0]);
760 decinfo->mainfpr = xstrdup (fields[1]);
761 decinfo->otrust = *fields[2];
766 /* Decrypt the INPUT stream to a new stream which is stored at success
769 decrypt_stream (estream_t *r_output, struct decrypt_stream_parm_s *decinfo,
778 memset (decinfo, 0, sizeof *decinfo);
780 output = es_fopenmem (0, "w+b");
783 err = gpg_error_from_syserror ();
784 log_error ("error allocating memory buffer: %s\n", gpg_strerror (err));
788 ccparray_init (&ccp, 0);
790 ccparray_put (&ccp, "--no-options");
791 /* We limit the output to 64 KiB to avoid DoS using compression
792 * tricks. A regular client will anyway only send a minimal key;
793 * that is one w/o key signatures and attribute packets. */
794 ccparray_put (&ccp, "--max-output=0x10000");
796 ccparray_put (&ccp, "--quiet");
798 ccparray_put (&ccp, "--verbose");
799 ccparray_put (&ccp, "--batch");
800 ccparray_put (&ccp, "--status-fd=2");
801 ccparray_put (&ccp, "--decrypt");
802 ccparray_put (&ccp, "--");
804 ccparray_put (&ccp, NULL);
805 argv = ccparray_get (&ccp, NULL);
808 err = gpg_error_from_syserror ();
811 err = gnupg_exec_tool_stream (opt.gpg_program, argv, input,
813 decrypt_stream_status_cb, decinfo);
814 if (!err && (!decinfo->fpr || !decinfo->mainfpr || !decinfo->otrust))
815 err = gpg_error (GPG_ERR_INV_ENGINE);
818 log_error ("decryption failed: %s\n", gpg_strerror (err));
821 else if (opt.verbose)
822 log_info ("decryption succeeded\n");
831 xfree (decinfo->fpr);
832 xfree (decinfo->mainfpr);
833 memset (decinfo, 0, sizeof *decinfo);
841 /* Return the submission address for the address or just the domain in
842 * ADDRSPEC. The submission address is stored as a malloced string at
843 * R_SUBMISSION_ADDRESS. At R_POLICY the policy flags of the domain
844 * are stored. The caller needs to free them with wks_free_policy.
845 * The function returns an error code on failure to find a submission
846 * address or policy file. Note: The function may store NULL at
847 * R_SUBMISSION_ADDRESS but return success to indicate that the web
848 * key directory is supported but not the web key service. As per WKD
849 * specs a policy file is always required and will thus be return on
852 get_policy_and_sa (const char *addrspec, int silent,
853 policy_flags_t *r_policy, char **r_submission_address)
856 estream_t mbuf = NULL;
859 policy_flags_t policy = NULL;
860 char *submission_to = NULL;
862 *r_submission_address = NULL;
865 domain = strchr (addrspec, '@');
871 s = domain? domain : addrspec;
872 es_write_sanitized (es_stdout, s, strlen (s), ":", NULL);
873 es_putc (':', es_stdout);
876 /* We first try to get the submission address from the policy file
877 * (this is the new method). If both are available we check that
878 * they match and print a warning if not. In the latter case we
879 * keep on using the one from the submission-address file. */
880 err = wkd_get_policy_flags (addrspec, &mbuf);
881 if (err && gpg_err_code (err) != GPG_ERR_NO_DATA
882 && gpg_err_code (err) != GPG_ERR_NO_NAME)
884 if (!opt.with_colons)
885 log_error ("error reading policy flags for '%s': %s\n",
886 domain, gpg_strerror (err));
891 if (!opt.with_colons)
892 log_error ("provider for '%s' does NOT support the Web Key Directory\n",
894 err = gpg_error (GPG_ERR_FALSE);
898 policy = xtrycalloc (1, sizeof *policy);
900 err = gpg_error_from_syserror ();
902 err = wks_parse_policy (policy, mbuf, 1);
908 err = wkd_get_submission_address (addrspec, &submission_to);
909 if (err && !policy->submission_address)
911 if (!silent && !opt.with_colons)
912 log_error (_("error looking up submission address for domain '%s'"
913 ": %s\n"), domain, gpg_strerror (err));
914 if (!silent && gpg_err_code (err) == GPG_ERR_NO_DATA && !opt.with_colons)
915 log_error (_("this domain probably doesn't support WKS.\n"));
919 if (submission_to && policy->submission_address
920 && ascii_strcasecmp (submission_to, policy->submission_address))
921 log_info ("Warning: different submission addresses (sa=%s, po=%s)\n",
922 submission_to, policy->submission_address);
924 if (!submission_to && policy->submission_address)
926 submission_to = xtrystrdup (policy->submission_address);
929 err = gpg_error_from_syserror ();
935 *r_submission_address = submission_to;
936 submission_to = NULL;
942 if (*r_policy && !*r_submission_address)
943 es_fprintf (es_stdout, "1:0::");
944 else if (*r_policy && *r_submission_address)
945 es_fprintf (es_stdout, "1:1::");
946 else if (err && !(gpg_err_code (err) == GPG_ERR_FALSE
947 || gpg_err_code (err) == GPG_ERR_NO_DATA
948 || gpg_err_code (err) == GPG_ERR_UNKNOWN_HOST))
949 es_fprintf (es_stdout, "0:0:%d:", err);
951 es_fprintf (es_stdout, "0:0::");
954 es_fprintf (es_stdout, "%u:%u:%u:",
955 (*r_policy)->protocol_version,
956 (*r_policy)->auth_submit,
957 (*r_policy)->mailbox_only);
959 es_putc ('\n', es_stdout);
962 xfree (submission_to);
963 wks_free_policy (policy);
971 /* Check whether the provider supports the WKS protocol. */
973 command_supported (char *userid)
976 char *addrspec = NULL;
977 char *submission_to = NULL;
978 policy_flags_t policy = NULL;
980 if (!strchr (userid, '@'))
982 char *tmp = xstrconcat ("foo@", userid, NULL);
983 addrspec = mailbox_from_userid (tmp, 0);
987 addrspec = mailbox_from_userid (userid, 0);
990 log_error (_("\"%s\" is not a proper mail address\n"), userid);
991 err = gpg_error (GPG_ERR_INV_USER_ID);
995 /* Get the submission address. */
996 err = get_policy_and_sa (addrspec, 1, &policy, &submission_to);
997 if (err || !submission_to)
1000 || gpg_err_code (err) == GPG_ERR_FALSE
1001 || gpg_err_code (err) == GPG_ERR_NO_DATA
1002 || gpg_err_code (err) == GPG_ERR_UNKNOWN_HOST
1005 /* FALSE is returned if we already figured out that even the
1006 * Web Key Directory is not supported and thus printed an
1008 if (opt.verbose && gpg_err_code (err) != GPG_ERR_FALSE
1009 && !opt.with_colons)
1011 if (gpg_err_code (err) == GPG_ERR_NO_DATA)
1012 log_info ("provider for '%s' does NOT support WKS\n",
1015 log_info ("provider for '%s' does NOT support WKS (%s)\n",
1016 addrspec, gpg_strerror (err));
1018 err = gpg_error (GPG_ERR_FALSE);
1019 if (!opt.with_colons)
1020 log_inc_errorcount ();
1025 if (opt.verbose && !opt.with_colons)
1026 log_info ("provider for '%s' supports WKS\n", addrspec);
1029 wks_free_policy (policy);
1031 xfree (submission_to);
1038 /* Check whether the key for USERID is available in the WKD. */
1040 command_check (char *userid)
1043 char *addrspec = NULL;
1044 estream_t key = NULL;
1046 uidinfo_list_t mboxes = NULL;
1050 addrspec = mailbox_from_userid (userid, 0);
1053 log_error (_("\"%s\" is not a proper mail address\n"), userid);
1054 err = gpg_error (GPG_ERR_INV_USER_ID);
1058 /* Get the submission address. */
1059 err = wkd_get_key (addrspec, &key);
1060 switch (gpg_err_code (err))
1064 log_info ("public key for '%s' found via WKD\n", addrspec);
1065 /* Fixme: Check that the key contains the user id. */
1068 case GPG_ERR_NO_DATA: /* No such key. */
1070 log_info ("public key for '%s' NOT found via WKD\n", addrspec);
1071 err = gpg_error (GPG_ERR_NO_PUBKEY);
1072 log_inc_errorcount ();
1075 case GPG_ERR_UNKNOWN_HOST:
1077 log_info ("error looking up '%s' via WKD: %s\n",
1078 addrspec, gpg_strerror (err));
1079 err = gpg_error (GPG_ERR_NOT_SUPPORTED);
1083 log_error ("error looking up '%s' via WKD: %s\n",
1084 addrspec, gpg_strerror (err));
1091 /* Look closer at the key. */
1092 err = wks_list_key (key, &fpr, &mboxes);
1095 log_error ("error parsing key: %s\n", gpg_strerror (err));
1096 err = gpg_error (GPG_ERR_NO_PUBKEY);
1101 log_info ("fingerprint: %s\n", fpr);
1103 for (sl = mboxes; sl; sl = sl->next)
1105 if (sl->mbox && !strcmp (sl->mbox, addrspec))
1109 log_info (" user-id: %s\n", sl->uid);
1110 log_info (" created: %s\n", asctimestamp (sl->created));
1112 log_info (" addr-spec: %s\n", sl->mbox);
1117 log_error ("public key for '%s' has no user id with the mail address\n",
1119 err = gpg_error (GPG_ERR_CERT_REVOKED);
1124 free_uidinfo_list (mboxes);
1132 /* Locate the key by fingerprint and userid and send a publication
1135 command_send (const char *fingerprint, const char *userid)
1138 KEYDB_SEARCH_DESC desc;
1139 char *addrspec = NULL;
1140 estream_t key = NULL;
1141 estream_t keyenc = NULL;
1142 char *submission_to = NULL;
1143 mime_maker_t mime = NULL;
1144 policy_flags_t policy = NULL;
1146 int posteo_hack = 0;
1148 uidinfo_list_t uidlist = NULL;
1149 uidinfo_list_t uid, thisuid;
1152 if (classify_user_id (fingerprint, &desc, 1)
1153 || desc.mode != KEYDB_SEARCH_MODE_FPR)
1155 log_error (_("\"%s\" is not a fingerprint\n"), fingerprint);
1156 err = gpg_error (GPG_ERR_INV_NAME);
1160 addrspec = mailbox_from_userid (userid, 0);
1163 log_error (_("\"%s\" is not a proper mail address\n"), userid);
1164 err = gpg_error (GPG_ERR_INV_USER_ID);
1167 err = wks_get_key (&key, fingerprint, addrspec, 0);
1171 domain = strchr (addrspec, '@');
1172 log_assert (domain);
1175 /* Get the submission address. */
1176 if (fake_submission_addr)
1178 policy = xcalloc (1, sizeof *policy);
1179 submission_to = xstrdup (fake_submission_addr);
1184 err = get_policy_and_sa (addrspec, 0, &policy, &submission_to);
1189 log_error (_("this domain probably doesn't support WKS.\n"));
1190 err = gpg_error (GPG_ERR_NO_DATA);
1195 log_info ("submitting request to '%s'\n", submission_to);
1197 if (policy->auth_submit)
1198 log_info ("no confirmation required for '%s'\n", addrspec);
1200 /* In case the key has several uids with the same addr-spec we will
1201 * use the newest one. */
1202 err = wks_list_key (key, NULL, &uidlist);
1205 log_error ("error parsing key: %s\n",gpg_strerror (err));
1206 err = gpg_error (GPG_ERR_NO_PUBKEY);
1211 for (uid = uidlist; uid; uid = uid->next)
1214 continue; /* Should not happen anyway. */
1215 if (policy->mailbox_only && ascii_strcasecmp (uid->uid, uid->mbox))
1216 continue; /* UID has more than just the mailbox. */
1217 if (uid->created > thistime)
1219 thistime = uid->created;
1224 thisuid = uidlist; /* This is the case for a missing timestamp. */
1226 log_info ("submitting key with user id '%s'\n", thisuid->uid);
1228 /* If we have more than one user id we need to filter the key to
1229 * include only THISUID. */
1235 err = wks_filter_uid (&newkey, key, thisuid->uid, 0);
1238 log_error ("error filtering key: %s\n", gpg_strerror (err));
1239 err = gpg_error (GPG_ERR_NO_PUBKEY);
1246 if (policy->mailbox_only
1247 && (!thisuid->mbox || ascii_strcasecmp (thisuid->uid, thisuid->mbox)))
1249 log_info ("Warning: policy requires 'mailbox-only'"
1250 " - adding user id '%s'\n", addrspec);
1251 err = add_user_id (fingerprint, addrspec);
1255 /* Need to get the key again. This time we request filtering
1256 * for the full user id, so that we do not need check and filter
1260 err = wks_get_key (&key, fingerprint, addrspec, 1);
1265 /* Hack to support posteo but let them disable this by setting the
1266 * new policy-version flag. */
1267 if (policy->protocol_version < 3
1268 && !ascii_strcasecmp (domain, "posteo.de"))
1270 log_info ("Warning: Using draft-1 method for domain '%s'\n", domain);
1275 /* Encrypt the key part. */
1279 err = encrypt_response (&keyenc, key, submission_to, fingerprint);
1287 err = mime_maker_new (&mime, NULL);
1290 err = mime_maker_add_header (mime, "From", addrspec);
1293 err = mime_maker_add_header (mime, "To", submission_to);
1296 err = mime_maker_add_header (mime, "Subject", "Key publishing request");
1300 /* Tell server which draft we support. */
1301 err = mime_maker_add_header (mime, "Wks-Draft-Version",
1302 STR2(WKS_DRAFT_VERSION));
1313 /* Needs a multipart/mixed with one(!) attachment. It does
1314 * not grok a non-multipart mail. */
1315 err = mime_maker_add_header (mime, "Content-Type", "multipart/mixed");
1318 err = mime_maker_add_container (mime);
1323 err = mime_maker_add_header (mime, "Content-type",
1324 "application/pgp-keys");
1328 if (es_fclose_snatch (key, &data, &datalen))
1330 err = gpg_error_from_syserror ();
1334 /* We need to skip over the first line which has a content-type
1335 * header not needed here. */
1336 for (n=0; n < datalen ; n++)
1337 if (((const char *)data)[n] == '\n')
1343 err = mime_maker_add_body_data (mime, (char*)data + n, datalen - n);
1350 err = mime_maker_add_header (mime, "Content-Type",
1351 "multipart/encrypted; "
1352 "protocol=\"application/pgp-encrypted\"");
1355 err = mime_maker_add_container (mime);
1359 err = mime_maker_add_header (mime, "Content-Type",
1360 "application/pgp-encrypted");
1363 err = mime_maker_add_body (mime, "Version: 1\n");
1366 err = mime_maker_add_header (mime, "Content-Type",
1367 "application/octet-stream");
1371 err = mime_maker_add_stream (mime, &keyenc);
1376 err = wks_send_mime (mime);
1379 mime_maker_release (mime);
1380 xfree (submission_to);
1381 free_uidinfo_list (uidlist);
1384 wks_free_policy (policy);
1393 encrypt_response_status_cb (void *opaque, const char *keyword, char *args)
1395 gpg_error_t *failure = opaque;
1396 const char *fields[2];
1399 log_debug ("gpg status: %s %s\n", keyword, args);
1401 if (!strcmp (keyword, "FAILURE"))
1403 if (split_fields (args, fields, DIM (fields)) >= 2
1404 && !strcmp (fields[0], "encrypt"))
1405 *failure = strtoul (fields[1], NULL, 10);
1411 /* Encrypt the INPUT stream to a new stream which is stored at success
1412 * at R_OUTPUT. Encryption is done for ADDRSPEC and for FINGERPRINT
1413 * (so that the sent message may later be inspected by the user). We
1414 * currently retrieve that key from the WKD, DANE, or from "local".
1415 * "local" is last to prefer the latest key version but use a local
1416 * copy in case we are working offline. It might be useful for the
1417 * server to send the fingerprint of its encryption key - or even the
1418 * entire key back. */
1420 encrypt_response (estream_t *r_output, estream_t input, const char *addrspec,
1421 const char *fingerprint)
1427 gpg_error_t gpg_err = 0;
1431 output = es_fopenmem (0, "w+b");
1434 err = gpg_error_from_syserror ();
1435 log_error ("error allocating memory buffer: %s\n", gpg_strerror (err));
1439 ccparray_init (&ccp, 0);
1441 ccparray_put (&ccp, "--no-options");
1442 if (opt.verbose < 2)
1443 ccparray_put (&ccp, "--quiet");
1445 ccparray_put (&ccp, "--verbose");
1446 ccparray_put (&ccp, "--batch");
1447 ccparray_put (&ccp, "--status-fd=2");
1448 ccparray_put (&ccp, "--always-trust");
1449 ccparray_put (&ccp, "--armor");
1450 ccparray_put (&ccp, "-z0"); /* No compression for improved robustness. */
1451 if (fake_submission_addr)
1452 ccparray_put (&ccp, "--auto-key-locate=clear,local");
1454 ccparray_put (&ccp, "--auto-key-locate=clear,wkd,dane,local");
1455 ccparray_put (&ccp, "--recipient");
1456 ccparray_put (&ccp, addrspec);
1457 ccparray_put (&ccp, "--recipient");
1458 ccparray_put (&ccp, fingerprint);
1459 ccparray_put (&ccp, "--encrypt");
1460 ccparray_put (&ccp, "--");
1462 ccparray_put (&ccp, NULL);
1463 argv = ccparray_get (&ccp, NULL);
1466 err = gpg_error_from_syserror ();
1469 err = gnupg_exec_tool_stream (opt.gpg_program, argv, input,
1471 encrypt_response_status_cb, &gpg_err);
1476 log_error ("encryption failed: %s\n", gpg_strerror (err));
1492 send_confirmation_response (const char *sender, const char *address,
1493 const char *nonce, int encrypt,
1494 const char *fingerprint)
1497 estream_t body = NULL;
1498 estream_t bodyenc = NULL;
1499 mime_maker_t mime = NULL;
1501 body = es_fopenmem (0, "w+b");
1504 err = gpg_error_from_syserror ();
1505 log_error ("error allocating memory buffer: %s\n", gpg_strerror (err));
1509 /* It is fine to use 8 bit encoding because that is encrypted and
1510 * only our client will see it. */
1513 es_fputs ("Content-Type: application/vnd.gnupg.wks\n"
1514 "Content-Transfer-Encoding: 8bit\n"
1519 es_fprintf (body, ("type: confirmation-response\n"
1530 err = encrypt_response (&bodyenc, body, sender, fingerprint);
1537 err = mime_maker_new (&mime, NULL);
1540 err = mime_maker_add_header (mime, "From", address);
1543 err = mime_maker_add_header (mime, "To", sender);
1546 err = mime_maker_add_header (mime, "Subject", "Key publication confirmation");
1549 err = mime_maker_add_header (mime, "Wks-Draft-Version",
1550 STR2(WKS_DRAFT_VERSION));
1556 err = mime_maker_add_header (mime, "Content-Type",
1557 "multipart/encrypted; "
1558 "protocol=\"application/pgp-encrypted\"");
1561 err = mime_maker_add_container (mime);
1565 err = mime_maker_add_header (mime, "Content-Type",
1566 "application/pgp-encrypted");
1569 err = mime_maker_add_body (mime, "Version: 1\n");
1572 err = mime_maker_add_header (mime, "Content-Type",
1573 "application/octet-stream");
1577 err = mime_maker_add_stream (mime, &bodyenc);
1583 err = mime_maker_add_header (mime, "Content-Type",
1584 "application/vnd.gnupg.wks");
1587 err = mime_maker_add_stream (mime, &body);
1592 err = wks_send_mime (mime);
1595 mime_maker_release (mime);
1596 es_fclose (bodyenc);
1602 /* Reply to a confirmation request. The MSG has already been
1603 * decrypted and we only need to send the nonce back. MAINFPR is
1604 * either NULL or the primary key fingerprint of the key used to
1605 * decrypt the request. */
1607 process_confirmation_request (estream_t msg, const char *mainfpr)
1612 const char *value, *sender, *address, *fingerprint, *nonce;
1614 err = nvc_parse (&nvc, NULL, msg);
1617 log_error ("parsing the WKS message failed: %s\n", gpg_strerror (err));
1623 log_debug ("request follows:\n");
1624 nvc_write (nvc, log_get_stream ());
1627 /* Check that this is a confirmation request. */
1628 if (!((item = nvc_lookup (nvc, "type:")) && (value = nve_value (item))
1629 && !strcmp (value, "confirmation-request")))
1632 log_error ("received unexpected wks message '%s'\n", value);
1634 log_error ("received invalid wks message: %s\n", "'type' missing");
1635 err = gpg_error (GPG_ERR_UNEXPECTED_MSG);
1639 /* Get the fingerprint. */
1640 if (!((item = nvc_lookup (nvc, "fingerprint:"))
1641 && (value = nve_value (item))
1642 && strlen (value) >= 40))
1644 log_error ("received invalid wks message: %s\n",
1645 "'fingerprint' missing or invalid");
1646 err = gpg_error (GPG_ERR_INV_DATA);
1649 fingerprint = value;
1651 /* Check that the fingerprint matches the key used to decrypt the
1652 * message. In --read mode or with the old format we don't have the
1653 * decryption key; thus we can't bail out. */
1654 if (!mainfpr || ascii_strcasecmp (mainfpr, fingerprint))
1656 log_info ("target fingerprint: %s\n", fingerprint);
1657 log_info ("but decrypted with: %s\n", mainfpr);
1658 log_error ("confirmation request not decrypted with target key\n");
1661 err = gpg_error (GPG_ERR_INV_DATA);
1666 /* Get the address. */
1667 if (!((item = nvc_lookup (nvc, "address:")) && (value = nve_value (item))
1668 && is_valid_mailbox (value)))
1670 log_error ("received invalid wks message: %s\n",
1671 "'address' missing or invalid");
1672 err = gpg_error (GPG_ERR_INV_DATA);
1676 /* FIXME: Check that the "address" matches the User ID we want to
1679 /* Get the sender. */
1680 if (!((item = nvc_lookup (nvc, "sender:")) && (value = nve_value (item))
1681 && is_valid_mailbox (value)))
1683 log_error ("received invalid wks message: %s\n",
1684 "'sender' missing or invalid");
1685 err = gpg_error (GPG_ERR_INV_DATA);
1689 /* FIXME: Check that the "sender" matches the From: address. */
1691 /* Get the nonce. */
1692 if (!((item = nvc_lookup (nvc, "nonce:")) && (value = nve_value (item))
1693 && strlen (value) > 16))
1695 log_error ("received invalid wks message: %s\n",
1696 "'nonce' missing or too short");
1697 err = gpg_error (GPG_ERR_INV_DATA);
1702 /* Send the confirmation. If no key was found, try again without
1704 err = send_confirmation_response (sender, address, nonce, 1, fingerprint);
1705 if (gpg_err_code (err) == GPG_ERR_NO_PUBKEY)
1707 log_info ("no encryption key found - sending response in the clear\n");
1708 err = send_confirmation_response (sender, address, nonce, 0, NULL);
1717 /* Read a confirmation request and decrypt it if needed. This
1718 * function may not be used with a mail or MIME message but only with
1719 * the actual encrypted or plaintext WKS data. */
1721 read_confirmation_request (estream_t msg)
1725 estream_t plaintext = NULL;
1727 /* We take a really simple approach to check whether MSG is
1728 * encrypted: We know that an encrypted message is always armored
1729 * and thus starts with a few dashes. It is even sufficient to
1730 * check for a single dash, because that can never be a proper first
1731 * WKS data octet. We need to skip leading spaces, though. */
1732 while ((c = es_fgetc (msg)) == ' ' || c == '\t' || c == '\r' || c == '\n')
1736 log_error ("can't process an empty message\n");
1737 return gpg_error (GPG_ERR_INV_DATA);
1739 if (es_ungetc (c, msg) != c)
1741 log_error ("error ungetting octet from message\n");
1742 return gpg_error (GPG_ERR_INTERNAL);
1746 err = process_confirmation_request (msg, NULL);
1749 struct decrypt_stream_parm_s decinfo;
1751 err = decrypt_stream (&plaintext, &decinfo, msg);
1753 log_error ("decryption failed: %s\n", gpg_strerror (err));
1754 else if (decinfo.otrust != 'u')
1756 err = gpg_error (GPG_ERR_WRONG_SECKEY);
1757 log_error ("key used to decrypt the confirmation request"
1758 " was not generated by us (otrust=%c)\n", decinfo.otrust);
1761 err = process_confirmation_request (plaintext, decinfo.mainfpr);
1762 xfree (decinfo.fpr);
1763 xfree (decinfo.mainfpr);
1766 es_fclose (plaintext);
1771 /* Called from the MIME receiver to process the plain text data in MSG. */
1773 command_receive_cb (void *opaque, const char *mediatype,
1774 estream_t msg, unsigned int flags)
1781 if (!strcmp (mediatype, "application/vnd.gnupg.wks"))
1782 err = read_confirmation_request (msg);
1785 log_info ("ignoring unexpected message of type '%s'\n", mediatype);
1786 err = gpg_error (GPG_ERR_UNEXPECTED_MSG);
1794 /* An object used to communicate with the mirror_one_key callback. */
1799 unsigned int nkeys; /* Number of keys processed. */
1800 unsigned int nuids; /* Number of published user ids. */
1801 } mirror_one_key_parm;
1804 /* Return true if the Given a mail DOMAIN and the full addrspec MBOX
1807 domain_matches_mbox (const char *domain, const char *mbox)
1811 if (!domain || !mbox)
1813 s = strchr (domain, '@');
1817 return 0; /* Not a valid domain. */
1819 s = strchr (mbox, '@');
1821 return 0; /* Not a valid mbox. */
1824 return !ascii_strcasecmp (domain, mbox);
1828 /* Core of mirror_one_key with the goal of mirroring just one uid.
1829 * UIDLIST is used to figure out whether the given MBOX occurs several
1830 * times in UIDLIST and then to single out the newwest one. This is
1831 * so that for a key with
1832 * uid: Joe Someone <joe@example.org>
1833 * uid: Joe <joe@example.org>
1834 * only the news user id (and thus its self-signature) is used.
1835 * UIDLIST is nodified to set all MBOX fields to NULL for a processed
1836 * user id. FPR is the fingerprint of the key.
1839 mirror_one_keys_userid (estream_t key, const char *mbox, uidinfo_list_t uidlist,
1843 uidinfo_list_t uid, thisuid, firstuid;
1845 estream_t newkey = NULL;
1847 /* Find the UID we want to use. */
1849 thisuid = firstuid = NULL;
1850 for (uid = uidlist; uid; uid = uid->next)
1852 if ((uid->flags & 1) || !uid->mbox || strcmp (uid->mbox, mbox))
1853 continue; /* Already processed or no matching mbox. */
1854 uid->flags |= 1; /* Set "processed" flag. */
1857 if (uid->created > thistime)
1859 thistime = uid->created;
1864 thisuid = firstuid; /* This is the case for a missing timestamp. */
1867 log_error ("error finding the user id for %s (%s)\n", fpr, mbox);
1868 err = gpg_error (GPG_ERR_NO_USER_ID);
1871 /* FIXME: Consult blacklist. */
1874 /* Only if we have more than one user id we bother to run the
1875 * filter. In this case the result will be put into NEWKEY*/
1879 err = wks_filter_uid (&newkey, key, thisuid->uid, 0);
1882 log_error ("error filtering key %s: %s\n", fpr, gpg_strerror (err));
1883 err = gpg_error (GPG_ERR_NO_PUBKEY);
1888 err = wks_install_key_core (newkey? newkey : key, mbox);
1890 log_info ("key %s published for '%s'\n", fpr, mbox);
1891 mirror_one_key_parm.nuids++;
1892 if (!opt.quiet && !(mirror_one_key_parm.nuids % 25))
1893 log_info ("%u user ids from %d keys so far\n",
1894 mirror_one_key_parm.nuids, mirror_one_key_parm.nkeys);
1902 /* The callback used by command_mirror. It received an estream with
1903 * one key and should return success to process the next key. */
1905 mirror_one_key (estream_t key)
1907 gpg_error_t err = 0;
1909 uidinfo_list_t uidlist = NULL;
1911 const char *domain = mirror_one_key_parm.domain;
1913 /* List the key to get all user ids. */
1914 err = wks_list_key (key, &fpr, &uidlist);
1917 log_error ("error parsing a key: %s - skipped\n",
1918 gpg_strerror (err));
1919 mirror_one_key_parm.anyerror = 1;
1923 for (uid = uidlist; uid; uid = uid->next)
1925 if (!uid->mbox || (uid->flags & 1))
1926 continue; /* No mail box or already processed. */
1927 if (!domain_matches_mbox (domain, uid->mbox))
1928 continue; /* We don't want this one. */
1929 if (is_in_blacklist (uid->mbox))
1932 err = mirror_one_keys_userid (key, uid->mbox, uidlist, fpr);
1935 log_error ("error processing key %s: %s - skipped\n",
1936 fpr, gpg_strerror (err));
1937 mirror_one_key_parm.anyerror = 1;
1942 mirror_one_key_parm.nkeys++;
1946 free_uidinfo_list (uidlist);
1952 /* Copy the keys from the configured LDAP server into a local WKD.
1953 * DOMAINLIST is an array of domain names to restrict the copy to only
1954 * the given domains; if it is NULL all keys are mirrored. */
1956 command_mirror (char *domainlist[])
1960 char *domainbuf = NULL;
1962 mirror_one_key_parm.anyerror = 0;
1963 mirror_one_key_parm.nkeys = 0;
1964 mirror_one_key_parm.nuids = 0;
1968 mirror_one_key_parm.domain = "";
1969 err = wkd_dirmngr_ks_get (NULL, mirror_one_key);
1973 while ((domain = *domainlist++))
1975 if (*domain != '.' && domain[1] != '@')
1977 /* This does not already specify a mail search by
1978 * domain. Change it. */
1980 domainbuf = xstrconcat (".@", domain, NULL);
1983 mirror_one_key_parm.domain = domain;
1985 log_info ("mirroring keys for domain '%s'\n", domain+2);
1986 err = wkd_dirmngr_ks_get (domain, mirror_one_key);
1993 log_info ("a total of %u user ids from %d keys published\n",
1994 mirror_one_key_parm.nuids, mirror_one_key_parm.nkeys);
1996 log_error ("error mirroring LDAP directory: %s <%s>\n",
1997 gpg_strerror (err), gpg_strsource (err));
1998 else if (mirror_one_key_parm.anyerror)
1999 log_info ("warning: errors encountered - not all keys are mirrored\n");