1 /* server.c - LDAP and Keyserver access server
2 * Copyright (C) 2002 Klarälvdalens Datakonsult AB
3 * Copyright (C) 2003, 2004, 2005, 2007, 2008, 2009, 2011, 2015 g10 Code GmbH
4 * Copyright (C) 2014, 2015, 2016 Werner Koch
6 * This file is part of GnuPG.
8 * GnuPG is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
13 * GnuPG is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, see <https://www.gnu.org/licenses/>.
28 #include <sys/types.h>
39 # include "ldapserver.h"
42 #include "certcache.h"
46 # include "ldap-wrapper.h"
48 #include "ks-action.h"
49 #include "ks-engine.h" /* (ks_hkp_print_hosttable) */
51 # include "ldap-parse-uri.h"
53 #include "dns-stuff.h"
54 #include "mbox-util.h"
56 #include "server-help.h"
58 /* To avoid DoS attacks we limit the size of a certificate to
59 something reasonable. The DoS was actually only an issue back when
60 Dirmngr was a system service and not a user service. */
61 #define MAX_CERT_LENGTH (16*1024)
63 /* The same goes for OpenPGP keyblocks, but here we need to allow for
64 much longer blocks; a 200k keyblock is not too unusual for keys
65 with a lot of signatures (e.g. 0x5b0358a2). 9C31503C6D866396 even
66 has 770 KiB as of 2015-08-23. To avoid adding a runtime option we
67 now use 20MiB which should really be enough. Well, a key with
68 several pictures could be larger (the parser as a 18MiB limit for
69 attribute packets) but it won't be nice to the keyservers to send
70 them such large blobs. */
71 #define MAX_KEYBLOCK_LENGTH (20*1024*1024)
74 #define PARM_ERROR(t) assuan_set_error (ctx, \
75 gpg_error (GPG_ERR_ASS_PARAMETER), (t))
76 #define set_error(e,t) assuan_set_error (ctx, gpg_error (e), (t))
80 /* Control structure per connection. */
83 /* Data used to associate an Assuan context with local server data */
84 assuan_context_t assuan_ctx;
86 /* Per-session LDAP servers. */
87 ldap_server_t ldapservers;
89 /* Per-session list of keyservers. */
90 uri_item_t keyservers;
92 /* If this flag is set to true this dirmngr process will be
93 terminated after the end of this session. */
96 /* State variable private to is_tor_running. */
99 /* If the first both flags are set the assuan logging of data lines
100 * is suppressed. The count variable is used to show the number of
101 * non-logged bytes. */
102 size_t inhibit_data_logging_count;
103 unsigned int inhibit_data_logging : 1;
104 unsigned int inhibit_data_logging_now : 1;
108 /* Cookie definition for assuan data line output. */
109 static gpgrt_ssize_t data_line_cookie_write (void *cookie,
110 const void *buffer, size_t size);
111 static int data_line_cookie_close (void *cookie);
112 static es_cookie_io_functions_t data_line_cookie_functions =
115 data_line_cookie_write,
117 data_line_cookie_close
124 /* Accessor for the local ldapservers variable. */
126 get_ldapservers_from_ctrl (ctrl_t ctrl)
128 if (ctrl && ctrl->server_local)
129 return ctrl->server_local->ldapservers;
134 /* Release an uri_item_t list. */
136 release_uri_item_list (uri_item_t list)
140 uri_item_t tmp = list->next;
141 http_release_parsed_uri (list->parsed_uri);
147 /* Release all configured keyserver info from CTRL. */
149 release_ctrl_keyservers (ctrl_t ctrl)
151 if (! ctrl->server_local)
154 release_uri_item_list (ctrl->server_local->keyservers);
155 ctrl->server_local->keyservers = NULL;
160 /* Helper to print a message while leaving a command. */
162 leave_cmd (assuan_context_t ctx, gpg_error_t err)
166 const char *name = assuan_get_command_name (ctx);
169 if (gpg_err_source (err) == GPG_ERR_SOURCE_DEFAULT)
170 log_error ("command '%s' failed: %s\n", name,
173 log_error ("command '%s' failed: %s <%s>\n", name,
174 gpg_strerror (err), gpg_strsource (err));
180 /* This is a wrapper around assuan_send_data which makes debugging the
181 output in verbose mode easier. */
183 data_line_write (assuan_context_t ctx, const void *buffer_arg, size_t size)
185 ctrl_t ctrl = assuan_get_pointer (ctx);
186 const char *buffer = buffer_arg;
189 /* If we do not want logging, enable it it here. */
190 if (ctrl && ctrl->server_local && ctrl->server_local->inhibit_data_logging)
191 ctrl->server_local->inhibit_data_logging_now = 1;
193 if (opt.verbose && buffer && size)
195 /* Ease reading of output by sending a physical line at each LF. */
202 p = memchr (buffer, '\n', nbytes);
203 n = p ? (p - buffer) + 1 : nbytes;
204 err = assuan_send_data (ctx, buffer, n);
207 gpg_err_set_errno (EIO);
212 if (nbytes && (err=assuan_send_data (ctx, NULL, 0))) /* Flush line. */
214 gpg_err_set_errno (EIO);
222 err = assuan_send_data (ctx, buffer, size);
225 gpg_err_set_errno (EIO); /* For use by data_line_cookie_write. */
231 if (ctrl && ctrl->server_local && ctrl->server_local->inhibit_data_logging)
233 ctrl->server_local->inhibit_data_logging_now = 0;
234 ctrl->server_local->inhibit_data_logging_count += size;
241 /* A write handler used by es_fopencookie to write assuan data
244 data_line_cookie_write (void *cookie, const void *buffer, size_t size)
246 assuan_context_t ctx = cookie;
248 if (data_line_write (ctx, buffer, size))
250 return (gpgrt_ssize_t)size;
255 data_line_cookie_close (void *cookie)
257 assuan_context_t ctx = cookie;
261 ctrl_t ctrl = assuan_get_pointer (ctx);
263 if (ctrl && ctrl->server_local
264 && ctrl->server_local->inhibit_data_logging
265 && ctrl->server_local->inhibit_data_logging_count)
266 log_debug ("(%zu bytes sent via D lines not shown)\n",
267 ctrl->server_local->inhibit_data_logging_count);
269 if (assuan_send_data (ctx, NULL, 0))
271 gpg_err_set_errno (EIO);
279 /* Copy the % and + escaped string S into the buffer D and replace the
280 escape sequences. Note, that it is sufficient to allocate the
281 target string D as long as the source string S, i.e.: strlen(s)+1.
282 Note further that if S contains an escaped binary Nul the resulting
283 string D will contain the 0 as well as all other characters but it
284 will be impossible to know whether this is the original EOS or a
287 strcpy_escaped_plus (char *d, const unsigned char *s)
291 if (*s == '%' && s[1] && s[2])
306 /* This function returns true if a Tor server is running. The sattus
307 is cached for the current connection. */
309 is_tor_running (ctrl_t ctrl)
311 /* Check whether we can connect to the proxy. */
313 if (!ctrl || !ctrl->server_local)
314 return 0; /* Ooops. */
316 if (!ctrl->server_local->tor_state)
320 sock = assuan_sock_connect_byname (NULL, 0, 0, NULL, ASSUAN_SOCK_TOR);
321 if (sock == ASSUAN_INVALID_FD)
322 ctrl->server_local->tor_state = -1; /* Not running. */
325 assuan_sock_close (sock);
326 ctrl->server_local->tor_state = 1; /* Running. */
329 return (ctrl->server_local->tor_state > 0);
333 /* Return an error if the assuan context does not belong to the owner
334 of the process or to root. On error FAILTEXT is set as Assuan
337 check_owner_permission (assuan_context_t ctx, const char *failtext)
339 #ifdef HAVE_W32_SYSTEM
340 /* Under Windows the dirmngr is always run under the control of the
346 assuan_peercred_t cred;
348 ec = gpg_err_code (assuan_get_peercred (ctx, &cred));
349 if (!ec && cred->uid && cred->uid != getuid ())
352 return set_error (ec, failtext);
359 /* Common code for get_cert_local and get_issuer_cert_local. */
361 do_get_cert_local (ctrl_t ctrl, const char *name, const char *command)
363 unsigned char *value;
371 buf = xmalloc ( strlen (command) + 1 + strlen(name) + 1);
372 strcpy (stpcpy (stpcpy (buf, command), " "), name);
375 buf = xstrdup (command);
377 rc = assuan_inquire (ctrl->server_local->assuan_ctx, buf,
378 &value, &valuelen, MAX_CERT_LENGTH);
382 log_error (_("assuan_inquire(%s) failed: %s\n"),
383 command, gpg_strerror (rc));
393 rc = ksba_cert_new (&cert);
396 rc = ksba_cert_init_from_mem (cert, value, valuelen);
399 ksba_cert_release (cert);
409 /* Ask back to return a certificate for name, given as a regular
410 gpgsm certificate indentificates (e.g. fingerprint or one of the
411 other methods). Alternatively, NULL may be used for NAME to
412 return the current target certificate. Either return the certificate
413 in a KSBA object or NULL if it is not available.
416 get_cert_local (ctrl_t ctrl, const char *name)
418 if (!ctrl || !ctrl->server_local || !ctrl->server_local->assuan_ctx)
421 log_debug ("get_cert_local called w/o context\n");
424 return do_get_cert_local (ctrl, name, "SENDCERT");
428 /* Ask back to return the issuing certificate for name, given as a
429 regular gpgsm certificate indentificates (e.g. fingerprint or one
430 of the other methods). Alternatively, NULL may be used for NAME to
431 return thecurrent target certificate. Either return the certificate
432 in a KSBA object or NULL if it is not available.
436 get_issuing_cert_local (ctrl_t ctrl, const char *name)
438 if (!ctrl || !ctrl->server_local || !ctrl->server_local->assuan_ctx)
441 log_debug ("get_issuing_cert_local called w/o context\n");
444 return do_get_cert_local (ctrl, name, "SENDISSUERCERT");
447 /* Ask back to return a certificate with subject NAME and a
448 subjectKeyIdentifier of KEYID. */
450 get_cert_local_ski (ctrl_t ctrl, const char *name, ksba_sexp_t keyid)
452 unsigned char *value;
459 if (!ctrl || !ctrl->server_local || !ctrl->server_local->assuan_ctx)
462 log_debug ("get_cert_local_ski called w/o context\n");
467 log_debug ("get_cert_local_ski called with insufficient arguments\n");
471 hexkeyid = serial_hex (keyid);
474 log_debug ("serial_hex() failed\n");
478 buf = xtrymalloc (15 + strlen (hexkeyid) + 2 + strlen(name) + 1);
482 log_error ("can't allocate enough memory: %s\n", strerror (errno));
486 strcpy (stpcpy (stpcpy (stpcpy (buf, "SENDCERT_SKI "), hexkeyid)," /"),name);
489 rc = assuan_inquire (ctrl->server_local->assuan_ctx, buf,
490 &value, &valuelen, MAX_CERT_LENGTH);
494 log_error (_("assuan_inquire(%s) failed: %s\n"), "SENDCERT_SKI",
505 rc = ksba_cert_new (&cert);
508 rc = ksba_cert_init_from_mem (cert, value, valuelen);
511 ksba_cert_release (cert);
520 /* Ask the client via an inquiry to check the istrusted status of the
521 certificate specified by the hexified fingerprint HEXFPR. Returns
522 0 if the certificate is trusted by the client or an error code. */
524 get_istrusted_from_client (ctrl_t ctrl, const char *hexfpr)
526 unsigned char *value;
531 if (!ctrl || !ctrl->server_local || !ctrl->server_local->assuan_ctx
533 return gpg_error (GPG_ERR_INV_ARG);
535 snprintf (request, sizeof request, "ISTRUSTED %s", hexfpr);
536 rc = assuan_inquire (ctrl->server_local->assuan_ctx, request,
537 &value, &valuelen, 100);
540 log_error (_("assuan_inquire(%s) failed: %s\n"),
541 request, gpg_strerror (rc));
544 /* The expected data is: "1" or "1 cruft" (not a C-string). */
545 if (valuelen && *value == '1' && (valuelen == 1 || spacep (value+1)))
548 rc = gpg_error (GPG_ERR_NOT_TRUSTED);
556 /* Ask the client to return the certificate associated with the
557 current command. This is sometimes needed because the client usually
558 sends us just the cert ID, assuming that the request can be
559 satisfied from the cache, where the cert ID is used as key. */
561 inquire_cert_and_load_crl (assuan_context_t ctx)
563 ctrl_t ctrl = assuan_get_pointer (ctx);
565 unsigned char *value = NULL;
567 ksba_cert_t cert = NULL;
569 err = assuan_inquire( ctx, "SENDCERT", &value, &valuelen, 0);
574 /* FILE *fp = fopen ("foo.der", "r"); */
575 /* value = xmalloc (2000); */
576 /* valuelen = fread (value, 1, 2000, fp); */
580 if (!valuelen) /* No data returned; return a comprehensible error. */
581 return gpg_error (GPG_ERR_MISSING_CERT);
583 err = ksba_cert_new (&cert);
586 err = ksba_cert_init_from_mem (cert, value, valuelen);
589 xfree (value); value = NULL;
591 err = crl_cache_reload_crl (ctrl, cert);
594 ksba_cert_release (cert);
600 /* Handle OPTION commands. */
602 option_handler (assuan_context_t ctx, const char *key, const char *value)
604 ctrl_t ctrl = assuan_get_pointer (ctx);
607 if (!strcmp (key, "force-crl-refresh"))
609 int i = *value? atoi (value) : 0;
610 ctrl->force_crl_refresh = i;
612 else if (!strcmp (key, "audit-events"))
614 int i = *value? atoi (value) : 0;
615 ctrl->audit_events = i;
617 else if (!strcmp (key, "http-proxy"))
619 xfree (ctrl->http_proxy);
620 if (!*value || !strcmp (value, "none"))
621 ctrl->http_proxy = NULL;
622 else if (!(ctrl->http_proxy = xtrystrdup (value)))
623 err = gpg_error_from_syserror ();
625 else if (!strcmp (key, "honor-keyserver-url-used"))
627 /* Return an error if we are running in Tor mode. */
629 err = gpg_error (GPG_ERR_FORBIDDEN);
632 err = gpg_error (GPG_ERR_UNKNOWN_OPTION);
639 static const char hlp_dns_cert[] =
640 "DNS_CERT <subtype> <name>\n"
641 "DNS_CERT --pka <user_id>\n"
642 "DNS_CERT --dane <user_id>\n"
644 "Return the CERT record for <name>. <subtype> is one of\n"
645 " * Return the first record of any supported subtype\n"
646 " PGP Return the first record of subtype PGP (3)\n"
647 " IPGP Return the first record of subtype IPGP (6)\n"
648 "If the content of a certificate is available (PGP) it is returned\n"
649 "by data lines. Fingerprints and URLs are returned via status lines.\n"
650 "In --pka mode the fingerprint and if available an URL is returned.\n"
651 "In --dane mode the key is returned from RR type 61";
653 cmd_dns_cert (assuan_context_t ctx, char *line)
655 /* ctrl_t ctrl = assuan_get_pointer (ctx); */
657 int pka_mode, dane_mode;
659 char *namebuf = NULL;
660 char *encodedhash = NULL;
666 unsigned char *fpr = NULL;
670 pka_mode = has_option (line, "--pka");
671 dane_mode = has_option (line, "--dane");
672 line = skip_options (line);
674 if (pka_mode && dane_mode)
676 err = PARM_ERROR ("either --pka or --dane may be given");
680 if (pka_mode || dane_mode)
681 ; /* No need to parse here - we do this later. */
684 p = strchr (line, ' ');
687 err = PARM_ERROR ("missing arguments");
691 if (!strcmp (line, "*"))
692 certtype = DNS_CERTTYPE_ANY;
693 else if (!strcmp (line, "IPGP"))
694 certtype = DNS_CERTTYPE_IPGP;
695 else if (!strcmp (line, "PGP"))
696 certtype = DNS_CERTTYPE_PGP;
699 err = PARM_ERROR ("unknown subtype");
707 err = PARM_ERROR ("name missing");
712 if (opt.use_tor && (err = enable_dns_tormode (0)))
714 /* Tor mode is requested but the DNS code can't enable it. */
715 assuan_set_error (ctx, err, "error enabling Tor mode");
719 if (pka_mode || dane_mode)
721 char *domain; /* Points to mbox. */
722 char hashbuf[32]; /* For SHA-1 and SHA-256. */
724 /* We lowercase ascii characters but the DANE I-D does not allow
725 this. FIXME: Check after the release of the RFC whether to
727 mbox = mailbox_from_userid (line);
728 if (!mbox || !(domain = strchr (mbox, '@')))
730 err = set_error (GPG_ERR_INV_USER_ID, "no mailbox in user id");
737 gcry_md_hash_buffer (GCRY_MD_SHA1, hashbuf, mbox, strlen (mbox));
738 encodedhash = zb32_encode (hashbuf, 8*20);
741 err = gpg_error_from_syserror ();
744 namebuf = strconcat (encodedhash, "._pka.", domain, NULL);
747 err = gpg_error_from_syserror ();
751 certtype = DNS_CERTTYPE_IPGP;
755 /* Note: The hash is truncated to 28 bytes and we lowercase
756 the result only for aesthetic reasons. */
757 gcry_md_hash_buffer (GCRY_MD_SHA256, hashbuf, mbox, strlen (mbox));
758 encodedhash = bin2hex (hashbuf, 28, NULL);
761 err = gpg_error_from_syserror ();
764 ascii_strlwr (encodedhash);
765 namebuf = strconcat (encodedhash, "._openpgpkey.", domain, NULL);
768 err = gpg_error_from_syserror ();
772 certtype = DNS_CERTTYPE_RR61;
778 err = get_dns_cert (name, certtype, &key, &keylen, &fpr, &fprlen, &url);
784 err = data_line_write (ctx, key, keylen);
793 tmpstr = bin2hex (fpr, fprlen, NULL);
795 err = gpg_error_from_syserror ();
798 err = assuan_write_status (ctx, "FPR", tmpstr);
807 err = assuan_write_status (ctx, "URL", url);
820 return leave_cmd (ctx, err);
825 static const char hlp_wkd_get[] =
826 "WKD_GET [--submission-address|--policy-flags] <user_id>\n"
828 "Return the key or other info for <user_id>\n"
829 "from the Web Key Directory.";
831 cmd_wkd_get (assuan_context_t ctx, char *line)
833 ctrl_t ctrl = assuan_get_pointer (ctx);
836 char *domain; /* Points to mbox. */
839 char *encodedhash = NULL;
840 int opt_submission_addr;
841 int opt_policy_flags;
844 opt_submission_addr = has_option (line, "--submission-address");
845 opt_policy_flags = has_option (line, "--policy-flags");
846 line = skip_options (line);
848 mbox = mailbox_from_userid (line);
849 if (!mbox || !(domain = strchr (mbox, '@')))
851 err = set_error (GPG_ERR_INV_USER_ID, "no mailbox in user id");
856 gcry_md_hash_buffer (GCRY_MD_SHA1, sha1buf, mbox, strlen (mbox));
857 encodedhash = zb32_encode (sha1buf, 8*20);
860 err = gpg_error_from_syserror ();
864 if (opt_submission_addr)
866 uri = strconcat ("https://",
868 "/.well-known/openpgpkey/submission-address",
871 else if (opt_policy_flags)
873 uri = strconcat ("https://",
875 "/.well-known/openpgpkey/policy",
880 uri = strconcat ("https://",
882 "/.well-known/openpgpkey/hu/",
889 err = gpg_error_from_syserror ();
893 /* Setup an output stream and perform the get. */
897 outfp = es_fopencookie (ctx, "w", data_line_cookie_functions);
899 err = set_error (GPG_ERR_ASS_GENERAL,
900 "error setting up a data stream");
904 ctrl->server_local->inhibit_data_logging = 1;
905 ctrl->server_local->inhibit_data_logging_now = 0;
906 ctrl->server_local->inhibit_data_logging_count = 0;
907 err = ks_action_fetch (ctrl, uri, outfp);
909 ctrl->server_local->inhibit_data_logging = 0;
917 return leave_cmd (ctx, err);
922 static const char hlp_ldapserver[] =
923 "LDAPSERVER <data>\n"
925 "Add a new LDAP server to the list of configured LDAP servers.\n"
926 "DATA is in the same format as expected in the configure file.";
928 cmd_ldapserver (assuan_context_t ctx, char *line)
931 ctrl_t ctrl = assuan_get_pointer (ctx);
932 ldap_server_t server;
933 ldap_server_t *last_next_p;
935 while (spacep (line))
938 return leave_cmd (ctx, PARM_ERROR (_("ldapserver missing")));
940 server = ldapserver_parse_one (line, "", 0);
942 return leave_cmd (ctx, gpg_error (GPG_ERR_INV_ARG));
944 last_next_p = &ctrl->server_local->ldapservers;
946 last_next_p = &(*last_next_p)->next;
947 *last_next_p = server;
948 return leave_cmd (ctx, 0);
951 return leave_cmd (ctx, gpg_error (GPG_ERR_NOT_IMPLEMENTED));
956 static const char hlp_isvalid[] =
957 "ISVALID [--only-ocsp] [--force-default-responder]"
958 " <certificate_id>|<certificate_fpr>\n"
960 "This command checks whether the certificate identified by the\n"
961 "certificate_id is valid. This is done by consulting CRLs or\n"
962 "whatever has been configured. Note, that the returned error codes\n"
963 "are from gpg-error.h. The command may callback using the inquire\n"
964 "function. See the manual for details.\n"
966 "The CERTIFICATE_ID is a hex encoded string consisting of two parts,\n"
967 "delimited by a single dot. The first part is the SHA-1 hash of the\n"
968 "issuer name and the second part the serial number.\n"
970 "Alternatively the certificate's fingerprint may be given in which\n"
971 "case an OCSP request is done before consulting the CRL.\n"
973 "If the option --only-ocsp is given, no fallback to a CRL check will\n"
976 "If the option --force-default-responder is given, only the default\n"
977 "OCSP responder will be used and any other methods of obtaining an\n"
978 "OCSP responder URL won't be used.";
980 cmd_isvalid (assuan_context_t ctx, char *line)
982 ctrl_t ctrl = assuan_get_pointer (ctx);
983 char *issuerhash, *serialno;
988 int force_default_responder;
990 only_ocsp = has_option (line, "--only-ocsp");
991 force_default_responder = has_option (line, "--force-default-responder");
992 line = skip_options (line);
994 issuerhash = xstrdup (line); /* We need to work on a copy of the
995 line because that same Assuan
996 context may be used for an inquiry.
997 That is because Assuan reuses its
1001 serialno = strchr (issuerhash, '.');
1006 char *endp = strchr (issuerhash, ' ');
1009 if (strlen (issuerhash) != 40)
1012 return leave_cmd (ctx, PARM_ERROR (_("serialno missing in cert ID")));
1021 /* Note, that we ignore the given issuer hash and instead rely
1022 on the current certificate semantics used with this
1024 if (!opt.allow_ocsp)
1025 err = gpg_error (GPG_ERR_NOT_SUPPORTED);
1027 err = ocsp_isvalid (ctrl, NULL, NULL, force_default_responder);
1028 /* Fixme: If we got no ocsp response and --only-ocsp is not used
1029 we should fall back to CRL mode. Thus we need to clear
1030 OCSP_MODE, get the issuerhash and the serialno from the
1031 current certificate and jump to again. */
1034 err = gpg_error (GPG_ERR_NO_CRL_KNOWN);
1037 switch (crl_cache_isvalid (ctrl,
1038 issuerhash, serialno,
1039 ctrl->force_crl_refresh))
1041 case CRL_CACHE_VALID:
1044 case CRL_CACHE_INVALID:
1045 err = gpg_error (GPG_ERR_CERT_REVOKED);
1047 case CRL_CACHE_DONTKNOW:
1049 err = gpg_error (GPG_ERR_NO_CRL_KNOWN);
1050 else if (!(err = inquire_cert_and_load_crl (ctx)))
1056 case CRL_CACHE_CANTUSE:
1057 err = gpg_error (GPG_ERR_NO_CRL_KNOWN);
1060 log_fatal ("crl_cache_isvalid returned invalid code\n");
1065 return leave_cmd (ctx, err);
1069 /* If the line contains a SHA-1 fingerprint as the first argument,
1070 return the FPR vuffer on success. The function checks that the
1071 fingerprint consists of valid characters and prints and error
1072 message if it does not and returns NULL. Fingerprints are
1073 considered optional and thus no explicit error is returned. NULL is
1074 also returned if there is no fingerprint at all available.
1075 FPR must be a caller provided buffer of at least 20 bytes.
1077 Note that colons within the fingerprint are allowed to separate 2
1078 hex digits; this allows for easier cutting and pasting using the
1079 usual fingerprint rendering.
1081 static unsigned char *
1082 get_fingerprint_from_line (const char *line, unsigned char *fpr)
1087 for (s=line, i=0; *s && *s != ' '; s++ )
1089 if ( hexdigitp (s) && hexdigitp (s+1) )
1092 return NULL; /* Fingerprint too long. */
1093 fpr[i++] = xtoi_2 (s);
1096 else if ( *s != ':' )
1097 return NULL; /* Invalid. */
1100 return NULL; /* Fingerprint to short. */
1106 static const char hlp_checkcrl[] =
1107 "CHECKCRL [<fingerprint>]\n"
1109 "Check whether the certificate with FINGERPRINT (SHA-1 hash of the\n"
1110 "entire X.509 certificate blob) is valid or not by consulting the\n"
1111 "CRL responsible for this certificate. If the fingerprint has not\n"
1112 "been given or the certificate is not known, the function \n"
1113 "inquires the certificate using an\n"
1115 " INQUIRE TARGETCERT\n"
1117 "and the caller is expected to return the certificate for the\n"
1118 "request (which should match FINGERPRINT) as a binary blob.\n"
1119 "Processing then takes place without further interaction; in\n"
1120 "particular dirmngr tries to locate other required certificate by\n"
1121 "its own mechanism which includes a local certificate store as well\n"
1122 "as a list of trusted root certificates.\n"
1124 "The return value is the usual gpg-error code or 0 for ducesss;\n"
1125 "i.e. the certificate validity has been confirmed by a valid CRL.";
1127 cmd_checkcrl (assuan_context_t ctx, char *line)
1129 ctrl_t ctrl = assuan_get_pointer (ctx);
1131 unsigned char fprbuffer[20], *fpr;
1134 fpr = get_fingerprint_from_line (line, fprbuffer);
1135 cert = fpr? get_cert_byfpr (fpr) : NULL;
1139 /* We do not have this certificate yet or the fingerprint has
1140 not been given. Inquire it from the client. */
1141 unsigned char *value = NULL;
1144 err = assuan_inquire (ctrl->server_local->assuan_ctx, "TARGETCERT",
1145 &value, &valuelen, MAX_CERT_LENGTH);
1148 log_error (_("assuan_inquire failed: %s\n"), gpg_strerror (err));
1152 if (!valuelen) /* No data returned; return a comprehensible error. */
1153 err = gpg_error (GPG_ERR_MISSING_CERT);
1156 err = ksba_cert_new (&cert);
1158 err = ksba_cert_init_from_mem (cert, value, valuelen);
1167 err = crl_cache_cert_isvalid (ctrl, cert, ctrl->force_crl_refresh);
1168 if (gpg_err_code (err) == GPG_ERR_NO_CRL_KNOWN)
1170 err = crl_cache_reload_crl (ctrl, cert);
1172 err = crl_cache_cert_isvalid (ctrl, cert, 0);
1176 ksba_cert_release (cert);
1177 return leave_cmd (ctx, err);
1181 static const char hlp_checkocsp[] =
1182 "CHECKOCSP [--force-default-responder] [<fingerprint>]\n"
1184 "Check whether the certificate with FINGERPRINT (SHA-1 hash of the\n"
1185 "entire X.509 certificate blob) is valid or not by asking an OCSP\n"
1186 "responder responsible for this certificate. The optional\n"
1187 "fingerprint may be used for a quick check in case an OCSP check has\n"
1188 "been done for this certificate recently (we always cache OCSP\n"
1189 "responses for a couple of minutes). If the fingerprint has not been\n"
1190 "given or there is no cached result, the function inquires the\n"
1191 "certificate using an\n"
1193 " INQUIRE TARGETCERT\n"
1195 "and the caller is expected to return the certificate for the\n"
1196 "request (which should match FINGERPRINT) as a binary blob.\n"
1197 "Processing then takes place without further interaction; in\n"
1198 "particular dirmngr tries to locate other required certificates by\n"
1199 "its own mechanism which includes a local certificate store as well\n"
1200 "as a list of trusted root certificates.\n"
1202 "If the option --force-default-responder is given, only the default\n"
1203 "OCSP responder will be used and any other methods of obtaining an\n"
1204 "OCSP responder URL won't be used.\n"
1206 "The return value is the usual gpg-error code or 0 for ducesss;\n"
1207 "i.e. the certificate validity has been confirmed by a valid CRL.";
1209 cmd_checkocsp (assuan_context_t ctx, char *line)
1211 ctrl_t ctrl = assuan_get_pointer (ctx);
1213 unsigned char fprbuffer[20], *fpr;
1215 int force_default_responder;
1217 force_default_responder = has_option (line, "--force-default-responder");
1218 line = skip_options (line);
1220 fpr = get_fingerprint_from_line (line, fprbuffer);
1221 cert = fpr? get_cert_byfpr (fpr) : NULL;
1225 /* We do not have this certificate yet or the fingerprint has
1226 not been given. Inquire it from the client. */
1227 unsigned char *value = NULL;
1230 err = assuan_inquire (ctrl->server_local->assuan_ctx, "TARGETCERT",
1231 &value, &valuelen, MAX_CERT_LENGTH);
1234 log_error (_("assuan_inquire failed: %s\n"), gpg_strerror (err));
1238 if (!valuelen) /* No data returned; return a comprehensible error. */
1239 err = gpg_error (GPG_ERR_MISSING_CERT);
1242 err = ksba_cert_new (&cert);
1244 err = ksba_cert_init_from_mem (cert, value, valuelen);
1253 if (!opt.allow_ocsp)
1254 err = gpg_error (GPG_ERR_NOT_SUPPORTED);
1256 err = ocsp_isvalid (ctrl, cert, NULL, force_default_responder);
1259 ksba_cert_release (cert);
1260 return leave_cmd (ctx, err);
1266 lookup_cert_by_url (assuan_context_t ctx, const char *url)
1268 ctrl_t ctrl = assuan_get_pointer (ctx);
1269 gpg_error_t err = 0;
1270 unsigned char *value = NULL;
1273 /* Fetch single certificate given it's URL. */
1274 err = fetch_cert_by_url (ctrl, url, &value, &valuelen);
1277 log_error (_("fetch_cert_by_url failed: %s\n"), gpg_strerror (err));
1281 /* Send the data, flush the buffer and then send an END. */
1282 err = assuan_send_data (ctx, value, valuelen);
1284 err = assuan_send_data (ctx, NULL, 0);
1286 err = assuan_write_line (ctx, "END");
1289 log_error (_("error sending data: %s\n"), gpg_strerror (err));
1299 /* Send the certificate, flush the buffer and then send an END. */
1301 return_one_cert (void *opaque, ksba_cert_t cert)
1303 assuan_context_t ctx = opaque;
1305 const unsigned char *der;
1308 der = ksba_cert_get_image (cert, &derlen);
1310 err = gpg_error (GPG_ERR_INV_CERT_OBJ);
1313 err = assuan_send_data (ctx, der, derlen);
1315 err = assuan_send_data (ctx, NULL, 0);
1317 err = assuan_write_line (ctx, "END");
1320 log_error (_("error sending data: %s\n"), gpg_strerror (err));
1325 /* Lookup certificates from the internal cache or using the ldap
1328 lookup_cert_by_pattern (assuan_context_t ctx, char *line,
1329 int single, int cache_only)
1331 gpg_error_t err = 0;
1333 strlist_t sl, list = NULL;
1334 int truncated = 0, truncation_forced = 0;
1336 int local_count = 0;
1338 ctrl_t ctrl = assuan_get_pointer (ctx);
1339 unsigned char *value = NULL;
1341 struct ldapserver_iter ldapserver_iter;
1342 cert_fetch_context_t fetch_context;
1344 int any_no_data = 0;
1346 /* Break the line down into an STRLIST */
1347 for (p=line; *p; line = p)
1349 while (*p && *p != ' ')
1356 sl = xtrymalloc (sizeof *sl + strlen (line));
1359 err = gpg_error_from_errno (errno);
1362 memset (sl, 0, sizeof *sl);
1363 strcpy_escaped_plus (sl->d, line);
1369 /* First look through the internal cache. The certifcates returned
1370 here are not counted towards the truncation limit. */
1371 if (single && !cache_only)
1372 ; /* Do not read from the local cache in this case. */
1375 for (sl=list; sl; sl = sl->next)
1377 err = get_certs_bypattern (sl->d, return_one_cert, ctx);
1383 if (gpg_err_code (err) == GPG_ERR_NO_DATA)
1389 else if (gpg_err_code (err) == GPG_ERR_INV_NAME && !cache_only)
1391 /* No real fault because the internal pattern lookup
1392 can't yet cope with all types of pattern. */
1400 /* Loop over all configured servers unless we want only the
1401 certificates from the cache. */
1403 for (ldapserver_iter_begin (&ldapserver_iter, ctrl);
1404 !cache_only && !ldapserver_iter_end_p (&ldapserver_iter)
1405 && ldapserver_iter.server->host && !truncation_forced;
1406 ldapserver_iter_next (&ldapserver_iter))
1408 ldap_server_t ldapserver = ldapserver_iter.server;
1411 log_debug ("cmd_lookup: trying %s:%d base=%s\n",
1412 ldapserver->host, ldapserver->port,
1413 ldapserver->base?ldapserver->base : "[default]");
1415 /* Fetch certificates matching pattern */
1416 err = start_cert_fetch (ctrl, &fetch_context, list, ldapserver);
1417 if ( gpg_err_code (err) == GPG_ERR_NO_DATA )
1420 log_debug ("cmd_lookup: no data\n");
1427 log_error (_("start_cert_fetch failed: %s\n"), gpg_strerror (err));
1431 /* Fetch the certificates for this query. */
1432 while (!truncation_forced)
1434 xfree (value); value = NULL;
1435 err = fetch_next_cert (fetch_context, &value, &valuelen);
1436 if (gpg_err_code (err) == GPG_ERR_NO_DATA )
1442 if (gpg_err_code (err) == GPG_ERR_TRUNCATED)
1448 if (gpg_err_code (err) == GPG_ERR_EOF)
1455 err = gpg_error (GPG_ERR_BUG);
1460 log_error (_("fetch_next_cert failed: %s\n"),
1461 gpg_strerror (err));
1462 end_cert_fetch (fetch_context);
1467 log_debug ("cmd_lookup: returning one cert%s\n",
1468 truncated? " (truncated)":"");
1470 /* Send the data, flush the buffer and then send an END line
1471 as a certificate delimiter. */
1472 err = assuan_send_data (ctx, value, valuelen);
1474 err = assuan_send_data (ctx, NULL, 0);
1476 err = assuan_write_line (ctx, "END");
1479 log_error (_("error sending data: %s\n"), gpg_strerror (err));
1480 end_cert_fetch (fetch_context);
1484 if (++count >= opt.max_replies )
1486 truncation_forced = 1;
1487 log_info (_("max_replies %d exceeded\n"), opt.max_replies );
1493 end_cert_fetch (fetch_context);
1498 if (truncated || truncation_forced)
1502 sprintf (str, "%d", count);
1503 assuan_write_status (ctx, "TRUNCATED", str);
1506 if (!err && !count && !local_count && any_no_data)
1507 err = gpg_error (GPG_ERR_NO_DATA);
1510 free_strlist (list);
1515 static const char hlp_lookup[] =
1516 "LOOKUP [--url] [--single] [--cache-only] <pattern>\n"
1518 "Lookup certificates matching PATTERN. With --url the pattern is\n"
1519 "expected to be one URL.\n"
1521 "If --url is not given: To allow for multiple patterns (which are ORed)\n"
1522 "quoting is required: Spaces are translated to \"+\" or \"%20\";\n"
1523 "obviously this requires that the usual escape quoting rules are applied.\n"
1525 "If --url is given no special escaping is required because URLs are\n"
1526 "already escaped this way.\n"
1528 "If --single is given the first and only the first match will be\n"
1529 "returned. If --cache-only is _not_ given, no local query will be\n"
1532 "If --cache-only is given no external lookup is done so that only\n"
1533 "certificates from the cache may get returned.";
1535 cmd_lookup (assuan_context_t ctx, char *line)
1538 int lookup_url, single, cache_only;
1540 lookup_url = has_leading_option (line, "--url");
1541 single = has_leading_option (line, "--single");
1542 cache_only = has_leading_option (line, "--cache-only");
1543 line = skip_options (line);
1545 if (lookup_url && cache_only)
1546 err = gpg_error (GPG_ERR_NOT_FOUND);
1547 else if (lookup_url && single)
1548 err = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1549 else if (lookup_url)
1550 err = lookup_cert_by_url (ctx, line);
1552 err = lookup_cert_by_pattern (ctx, line, single, cache_only);
1554 return leave_cmd (ctx, err);
1558 static const char hlp_loadcrl[] =
1559 "LOADCRL [--url] <filename|url>\n"
1561 "Load the CRL in the file with name FILENAME into our cache. Note\n"
1562 "that FILENAME should be given with an absolute path because\n"
1563 "Dirmngrs cwd is not known. With --url the CRL is directly loaded\n"
1564 "from the given URL.\n"
1566 "This command is usually used by gpgsm using the invocation \"gpgsm\n"
1567 "--call-dirmngr loadcrl <filename>\". A direct invocation of Dirmngr\n"
1568 "is not useful because gpgsm might need to callback gpgsm to ask for\n"
1569 "the CA's certificate.";
1571 cmd_loadcrl (assuan_context_t ctx, char *line)
1573 ctrl_t ctrl = assuan_get_pointer (ctx);
1574 gpg_error_t err = 0;
1575 int use_url = has_leading_option (line, "--url");
1577 line = skip_options (line);
1581 ksba_reader_t reader;
1583 err = crl_fetch (ctrl, line, &reader);
1585 log_error (_("fetching CRL from '%s' failed: %s\n"),
1586 line, gpg_strerror (err));
1589 err = crl_cache_insert (ctrl, line, reader);
1591 log_error (_("processing CRL from '%s' failed: %s\n"),
1592 line, gpg_strerror (err));
1593 crl_close_reader (reader);
1600 buf = xtrymalloc (strlen (line)+1);
1602 err = gpg_error_from_syserror ();
1605 strcpy_escaped_plus (buf, line);
1606 err = crl_cache_load (ctrl, buf);
1611 return leave_cmd (ctx, err);
1615 static const char hlp_listcrls[] =
1618 "List the content of all CRLs in a readable format. This command is\n"
1619 "usually used by gpgsm using the invocation \"gpgsm --call-dirmngr\n"
1620 "listcrls\". It may also be used directly using \"dirmngr\n"
1623 cmd_listcrls (assuan_context_t ctx, char *line)
1630 fp = es_fopencookie (ctx, "w", data_line_cookie_functions);
1632 err = set_error (GPG_ERR_ASS_GENERAL, "error setting up a data stream");
1635 err = crl_cache_list (fp);
1638 return leave_cmd (ctx, err);
1642 static const char hlp_cachecert[] =
1645 "Put a certificate into the internal cache. This command might be\n"
1646 "useful if a client knows in advance certificates required for a\n"
1647 "test and wants to make sure they get added to the internal cache.\n"
1648 "It is also helpful for debugging. To get the actual certificate,\n"
1649 "this command immediately inquires it using\n"
1651 " INQUIRE TARGETCERT\n"
1653 "and the caller is expected to return the certificate for the\n"
1654 "request as a binary blob.";
1656 cmd_cachecert (assuan_context_t ctx, char *line)
1658 ctrl_t ctrl = assuan_get_pointer (ctx);
1660 ksba_cert_t cert = NULL;
1661 unsigned char *value = NULL;
1666 err = assuan_inquire (ctrl->server_local->assuan_ctx, "TARGETCERT",
1667 &value, &valuelen, MAX_CERT_LENGTH);
1670 log_error (_("assuan_inquire failed: %s\n"), gpg_strerror (err));
1674 if (!valuelen) /* No data returned; return a comprehensible error. */
1675 err = gpg_error (GPG_ERR_MISSING_CERT);
1678 err = ksba_cert_new (&cert);
1680 err = ksba_cert_init_from_mem (cert, value, valuelen);
1686 err = cache_cert (cert);
1689 ksba_cert_release (cert);
1690 return leave_cmd (ctx, err);
1694 static const char hlp_validate[] =
1697 "Validate a certificate using the certificate validation function\n"
1698 "used internally by dirmngr. This command is only useful for\n"
1699 "debugging. To get the actual certificate, this command immediately\n"
1700 "inquires it using\n"
1702 " INQUIRE TARGETCERT\n"
1704 "and the caller is expected to return the certificate for the\n"
1705 "request as a binary blob.";
1707 cmd_validate (assuan_context_t ctx, char *line)
1709 ctrl_t ctrl = assuan_get_pointer (ctx);
1711 ksba_cert_t cert = NULL;
1712 unsigned char *value = NULL;
1717 err = assuan_inquire (ctrl->server_local->assuan_ctx, "TARGETCERT",
1718 &value, &valuelen, MAX_CERT_LENGTH);
1721 log_error (_("assuan_inquire failed: %s\n"), gpg_strerror (err));
1725 if (!valuelen) /* No data returned; return a comprehensible error. */
1726 err = gpg_error (GPG_ERR_MISSING_CERT);
1729 err = ksba_cert_new (&cert);
1731 err = ksba_cert_init_from_mem (cert, value, valuelen);
1737 /* If we have this certificate already in our cache, use the cached
1738 version for validation because this will take care of any cached
1741 unsigned char fpr[20];
1742 ksba_cert_t tmpcert;
1744 cert_compute_fpr (cert, fpr);
1745 tmpcert = get_cert_byfpr (fpr);
1748 ksba_cert_release (cert);
1753 err = validate_cert_chain (ctrl, cert, NULL, VALIDATE_MODE_CERT, NULL);
1756 ksba_cert_release (cert);
1757 return leave_cmd (ctx, err);
1762 /* Parse an keyserver URI and store it in a new uri item which is
1763 returned at R_ITEM. On error return an error code. */
1765 make_keyserver_item (const char *uri, uri_item_t *r_item)
1771 item = xtrymalloc (sizeof *item + strlen (uri));
1773 return gpg_error_from_syserror ();
1776 item->parsed_uri = NULL;
1777 strcpy (item->uri, uri);
1780 if (ldap_uri_p (item->uri))
1781 err = ldap_parse_uri (&item->parsed_uri, uri);
1785 err = http_parse_uri (&item->parsed_uri, uri, 1);
1796 /* If no keyserver is stored in CTRL but a global keyserver has been
1797 set, put that global keyserver into CTRL. We need use this
1798 function to help migrate from the old gpg based keyserver
1799 configuration to the new dirmngr based configuration. */
1801 ensure_keyserver (ctrl_t ctrl)
1805 uri_item_t onion_items = NULL;
1806 uri_item_t plain_items = NULL;
1810 if (ctrl->server_local->keyservers)
1811 return 0; /* Already set for this session. */
1814 /* No global option set. Fall back to default: */
1815 return make_keyserver_item (DIRMNGR_DEFAULT_KEYSERVER,
1816 &ctrl->server_local->keyservers);
1819 for (sl = opt.keyserver; sl; sl = sl->next)
1821 err = make_keyserver_item (sl->d, &item);
1824 if (item->parsed_uri->onion)
1826 item->next = onion_items;
1831 item->next = plain_items;
1836 /* Decide which to use. Note that the sesssion has no keyservers
1838 if (onion_items && !onion_items->next && plain_items && !plain_items->next)
1840 /* If there is just one onion and one plain keyserver given, we take
1841 only one depending on whether Tor is running or not. */
1842 if (is_tor_running (ctrl))
1844 ctrl->server_local->keyservers = onion_items;
1849 ctrl->server_local->keyservers = plain_items;
1853 else if (!is_tor_running (ctrl))
1855 /* Tor is not running. It does not make sense to add Onion
1857 ctrl->server_local->keyservers = plain_items;
1862 /* In all other cases add all keyservers. */
1863 ctrl->server_local->keyservers = onion_items;
1865 for (ui = ctrl->server_local->keyservers; ui && ui->next; ui = ui->next)
1868 ui->next = plain_items;
1870 ctrl->server_local->keyservers = plain_items;
1875 release_uri_item_list (onion_items);
1876 release_uri_item_list (plain_items);
1882 static const char hlp_keyserver[] =
1883 "KEYSERVER [<options>] [<uri>|<host>]\n"
1886 " --clear Remove all configured keyservers\n"
1887 " --resolve Resolve HKP host names and rotate\n"
1888 " --hosttable Print table of known hosts and pools\n"
1889 " --dead Mark <host> as dead\n"
1890 " --alive Mark <host> as alive\n"
1892 "If called without arguments list all configured keyserver URLs.\n"
1893 "If called with an URI add this as keyserver. Note that keyservers\n"
1894 "are configured on a per-session base. A default keyserver may already be\n"
1895 "present, thus the \"--clear\" option must be used to get full control.\n"
1896 "If \"--clear\" and an URI are used together the clear command is\n"
1897 "obviously executed first. A RESET command does not change the list\n"
1898 "of configured keyservers.";
1900 cmd_keyserver (assuan_context_t ctx, char *line)
1902 ctrl_t ctrl = assuan_get_pointer (ctx);
1903 gpg_error_t err = 0;
1904 int clear_flag, add_flag, help_flag, host_flag, resolve_flag;
1905 int dead_flag, alive_flag;
1906 uri_item_t item = NULL; /* gcc 4.4.5 is not able to detect that it
1907 is always initialized. */
1909 clear_flag = has_option (line, "--clear");
1910 help_flag = has_option (line, "--help");
1911 resolve_flag = has_option (line, "--resolve");
1912 host_flag = has_option (line, "--hosttable");
1913 dead_flag = has_option (line, "--dead");
1914 alive_flag = has_option (line, "--alive");
1915 line = skip_options (line);
1920 err = ks_action_help (ctrl, line);
1926 err = ensure_keyserver (ctrl);
1928 err = ks_action_resolve (ctrl, ctrl->server_local->keyservers);
1933 if (alive_flag && dead_flag)
1935 err = set_error (GPG_ERR_ASS_PARAMETER, "no support for zombies");
1940 err = check_owner_permission (ctx, "no permission to use --dead");
1944 if (alive_flag || dead_flag)
1948 err = set_error (GPG_ERR_ASS_PARAMETER, "name of host missing");
1952 err = ks_hkp_mark_host (ctrl, line, alive_flag);
1959 err = ks_hkp_print_hosttable (ctrl);
1963 if (resolve_flag || host_flag || alive_flag || dead_flag)
1968 err = make_keyserver_item (line, &item);
1973 release_ctrl_keyservers (ctrl);
1976 item->next = ctrl->server_local->keyservers;
1977 ctrl->server_local->keyservers = item;
1980 if (!add_flag && !clear_flag && !help_flag)
1982 /* List configured keyservers. However, we first add a global
1986 err = ensure_keyserver (ctrl);
1989 assuan_set_error (ctx, err,
1990 "Bad keyserver configuration in dirmngr.conf");
1994 for (u=ctrl->server_local->keyservers; u; u = u->next)
1995 dirmngr_status (ctrl, "KEYSERVER", u->uri, NULL);
2000 return leave_cmd (ctx, err);
2005 static const char hlp_ks_search[] =
2006 "KS_SEARCH {<pattern>}\n"
2008 "Search the configured OpenPGP keyservers (see command KEYSERVER)\n"
2009 "for keys matching PATTERN";
2011 cmd_ks_search (assuan_context_t ctx, char *line)
2013 ctrl_t ctrl = assuan_get_pointer (ctx);
2019 /* No options for now. */
2020 line = skip_options (line);
2022 /* Break the line down into an strlist. Each pattern is
2023 percent-plus escaped. */
2025 for (p=line; *p; line = p)
2027 while (*p && *p != ' ')
2033 sl = xtrymalloc (sizeof *sl + strlen (line));
2036 err = gpg_error_from_syserror ();
2040 strcpy_escaped_plus (sl->d, line);
2046 err = ensure_keyserver (ctrl);
2050 /* Setup an output stream and perform the search. */
2051 outfp = es_fopencookie (ctx, "w", data_line_cookie_functions);
2053 err = set_error (GPG_ERR_ASS_GENERAL, "error setting up a data stream");
2056 err = ks_action_search (ctrl, ctrl->server_local->keyservers,
2062 free_strlist (list);
2063 return leave_cmd (ctx, err);
2068 static const char hlp_ks_get[] =
2069 "KS_GET {<pattern>}\n"
2071 "Get the keys matching PATTERN from the configured OpenPGP keyservers\n"
2072 "(see command KEYSERVER). Each pattern should be a keyid, a fingerprint,\n"
2073 "or an exact name indicated by the '=' prefix.";
2075 cmd_ks_get (assuan_context_t ctx, char *line)
2077 ctrl_t ctrl = assuan_get_pointer (ctx);
2083 /* No options for now. */
2084 line = skip_options (line);
2086 /* Break the line into a strlist. Each pattern is by
2087 definition percent-plus escaped. However we only support keyids
2088 and fingerprints and thus the client has no need to apply the
2091 for (p=line; *p; line = p)
2093 while (*p && *p != ' ')
2099 sl = xtrymalloc (sizeof *sl + strlen (line));
2102 err = gpg_error_from_syserror ();
2106 strcpy_escaped_plus (sl->d, line);
2112 err = ensure_keyserver (ctrl);
2116 /* Setup an output stream and perform the get. */
2117 outfp = es_fopencookie (ctx, "w", data_line_cookie_functions);
2119 err = set_error (GPG_ERR_ASS_GENERAL, "error setting up a data stream");
2122 ctrl->server_local->inhibit_data_logging = 1;
2123 ctrl->server_local->inhibit_data_logging_now = 0;
2124 ctrl->server_local->inhibit_data_logging_count = 0;
2125 err = ks_action_get (ctrl, ctrl->server_local->keyservers, list, outfp);
2127 ctrl->server_local->inhibit_data_logging = 0;
2131 free_strlist (list);
2132 return leave_cmd (ctx, err);
2136 static const char hlp_ks_fetch[] =
2139 "Get the key(s) from URL.";
2141 cmd_ks_fetch (assuan_context_t ctx, char *line)
2143 ctrl_t ctrl = assuan_get_pointer (ctx);
2147 /* No options for now. */
2148 line = skip_options (line);
2150 err = ensure_keyserver (ctrl); /* FIXME: Why do we needs this here? */
2154 /* Setup an output stream and perform the get. */
2155 outfp = es_fopencookie (ctx, "w", data_line_cookie_functions);
2157 err = set_error (GPG_ERR_ASS_GENERAL, "error setting up a data stream");
2160 ctrl->server_local->inhibit_data_logging = 1;
2161 ctrl->server_local->inhibit_data_logging_now = 0;
2162 ctrl->server_local->inhibit_data_logging_count = 0;
2163 err = ks_action_fetch (ctrl, line, outfp);
2165 ctrl->server_local->inhibit_data_logging = 0;
2169 return leave_cmd (ctx, err);
2174 static const char hlp_ks_put[] =
2177 "Send a key to the configured OpenPGP keyservers. The actual key material\n"
2178 "is then requested by Dirmngr using\n"
2180 " INQUIRE KEYBLOCK\n"
2182 "The client shall respond with a binary version of the keyblock (e.g.,\n"
2183 "the output of `gpg --export KEYID'). For LDAP\n"
2184 "keyservers Dirmngr may ask for meta information of the provided keyblock\n"
2187 " INQUIRE KEYBLOCK_INFO\n"
2189 "The client shall respond with a colon delimited info lines (the output\n"
2190 "of 'for x in keys sigs; do gpg --list-$x --with-colons KEYID; done').\n";
2192 cmd_ks_put (assuan_context_t ctx, char *line)
2194 ctrl_t ctrl = assuan_get_pointer (ctx);
2196 unsigned char *value = NULL;
2198 unsigned char *info = NULL;
2201 /* No options for now. */
2202 line = skip_options (line);
2204 err = ensure_keyserver (ctrl);
2208 /* Ask for the key material. */
2209 err = assuan_inquire (ctx, "KEYBLOCK",
2210 &value, &valuelen, MAX_KEYBLOCK_LENGTH);
2213 log_error (_("assuan_inquire failed: %s\n"), gpg_strerror (err));
2217 if (!valuelen) /* No data returned; return a comprehensible error. */
2219 err = gpg_error (GPG_ERR_MISSING_CERT);
2223 /* Ask for the key meta data. Not actually needed for HKP servers
2224 but we do it anyway to test the client implementaion. */
2225 err = assuan_inquire (ctx, "KEYBLOCK_INFO",
2226 &info, &infolen, MAX_KEYBLOCK_LENGTH);
2229 log_error (_("assuan_inquire failed: %s\n"), gpg_strerror (err));
2234 err = ks_action_put (ctrl, ctrl->server_local->keyservers,
2235 value, valuelen, info, infolen);
2240 return leave_cmd (ctx, err);
2245 static const char hlp_loadswdb[] =
2246 "LOADSWDB [--force]\n"
2248 "Load and verify the swdb.lst from the Net.";
2250 cmd_loadswdb (assuan_context_t ctx, char *line)
2252 ctrl_t ctrl = assuan_get_pointer (ctx);
2255 err = dirmngr_load_swdb (ctrl, has_option (line, "--force"));
2257 return leave_cmd (ctx, err);
2262 static const char hlp_getinfo[] =
2265 "Multi purpose command to return certain information. \n"
2266 "Supported values of WHAT are:\n"
2268 "version - Return the version of the program.\n"
2269 "pid - Return the process id of the server.\n"
2270 "tor - Return OK if running in Tor mode\n"
2271 "dnsinfo - Return info about the DNS resolver\n"
2272 "socket_name - Return the name of the socket.\n";
2274 cmd_getinfo (assuan_context_t ctx, char *line)
2276 ctrl_t ctrl = assuan_get_pointer (ctx);
2279 if (!strcmp (line, "version"))
2281 const char *s = VERSION;
2282 err = assuan_send_data (ctx, s, strlen (s));
2284 else if (!strcmp (line, "pid"))
2288 snprintf (numbuf, sizeof numbuf, "%lu", (unsigned long)getpid ());
2289 err = assuan_send_data (ctx, numbuf, strlen (numbuf));
2291 else if (!strcmp (line, "socket_name"))
2293 const char *s = dirmngr_get_current_socket_name ();
2294 err = assuan_send_data (ctx, s, strlen (s));
2296 else if (!strcmp (line, "tor"))
2300 if (!is_tor_running (ctrl))
2301 err = assuan_write_status (ctx, "NO_TOR", "Tor not running");
2305 assuan_set_okay_line (ctx, "- Tor mode is enabled");
2308 err = set_error (GPG_ERR_FALSE, "Tor mode is NOT enabled");
2310 else if (!strcmp (line, "dnsinfo"))
2312 if (standard_resolver_p ())
2313 assuan_set_okay_line
2314 (ctx, "- Forced use of System resolver (w/o Tor support)");
2318 assuan_set_okay_line (ctx, (recursive_resolver_p ()
2319 ? "- Libdns recursive resolver"
2320 : "- Libdns stub resolver"));
2322 assuan_set_okay_line (ctx, "- System resolver (w/o Tor support)");
2328 err = set_error (GPG_ERR_ASS_PARAMETER, "unknown value for WHAT");
2330 return leave_cmd (ctx, err);
2335 static const char hlp_killdirmngr[] =
2338 "This command allows a user - given sufficient permissions -\n"
2339 "to kill this dirmngr process.\n";
2341 cmd_killdirmngr (assuan_context_t ctx, char *line)
2343 ctrl_t ctrl = assuan_get_pointer (ctx);
2347 ctrl->server_local->stopme = 1;
2348 assuan_set_flag (ctx, ASSUAN_FORCE_CLOSE, 1);
2349 return gpg_error (GPG_ERR_EOF);
2353 static const char hlp_reloaddirmngr[] =
2356 "This command is an alternative to SIGHUP\n"
2357 "to reload the configuration.";
2359 cmd_reloaddirmngr (assuan_context_t ctx, char *line)
2364 dirmngr_sighup_action ();
2370 /* Tell the assuan library about our commands. */
2372 register_commands (assuan_context_t ctx)
2376 assuan_handler_t handler;
2377 const char * const help;
2379 { "DNS_CERT", cmd_dns_cert, hlp_dns_cert },
2380 { "WKD_GET", cmd_wkd_get, hlp_wkd_get },
2381 { "LDAPSERVER", cmd_ldapserver, hlp_ldapserver },
2382 { "ISVALID", cmd_isvalid, hlp_isvalid },
2383 { "CHECKCRL", cmd_checkcrl, hlp_checkcrl },
2384 { "CHECKOCSP", cmd_checkocsp, hlp_checkocsp },
2385 { "LOOKUP", cmd_lookup, hlp_lookup },
2386 { "LOADCRL", cmd_loadcrl, hlp_loadcrl },
2387 { "LISTCRLS", cmd_listcrls, hlp_listcrls },
2388 { "CACHECERT", cmd_cachecert, hlp_cachecert },
2389 { "VALIDATE", cmd_validate, hlp_validate },
2390 { "KEYSERVER", cmd_keyserver, hlp_keyserver },
2391 { "KS_SEARCH", cmd_ks_search, hlp_ks_search },
2392 { "KS_GET", cmd_ks_get, hlp_ks_get },
2393 { "KS_FETCH", cmd_ks_fetch, hlp_ks_fetch },
2394 { "KS_PUT", cmd_ks_put, hlp_ks_put },
2395 { "GETINFO", cmd_getinfo, hlp_getinfo },
2396 { "LOADSWDB", cmd_loadswdb, hlp_loadswdb },
2397 { "KILLDIRMNGR",cmd_killdirmngr,hlp_killdirmngr },
2398 { "RELOADDIRMNGR",cmd_reloaddirmngr,hlp_reloaddirmngr },
2403 for (i=j=0; table[i].name; i++)
2405 rc = assuan_register_command (ctx, table[i].name, table[i].handler,
2414 /* Note that we do not reset the list of configured keyservers. */
2416 reset_notify (assuan_context_t ctx, char *line)
2418 ctrl_t ctrl = assuan_get_pointer (ctx);
2422 ldapserver_list_free (ctrl->server_local->ldapservers);
2424 ctrl->server_local->ldapservers = NULL;
2429 /* This function is called by our assuan log handler to test whether a
2430 * log message shall really be printed. The function must return
2431 * false to inhibit the logging of MSG. CAT gives the requested log
2432 * category. MSG might be NULL. */
2434 dirmngr_assuan_log_monitor (assuan_context_t ctx, unsigned int cat,
2437 ctrl_t ctrl = assuan_get_pointer (ctx);
2442 if (!ctrl || !ctrl->server_local)
2443 return 1; /* Can't decide - allow logging. */
2445 if (!ctrl->server_local->inhibit_data_logging)
2446 return 1; /* Not requested - allow logging. */
2448 /* Disallow logging if *_now is true. */
2449 return !ctrl->server_local->inhibit_data_logging_now;
2453 /* Startup the server and run the main command loop. With FD = -1,
2454 use stdin/stdout. */
2456 start_command_handler (assuan_fd_t fd)
2458 static const char hello[] = "Dirmngr " VERSION " at your service";
2459 static char *hello_line;
2461 assuan_context_t ctx;
2464 ctrl = xtrycalloc (1, sizeof *ctrl);
2466 ctrl->server_local = xtrycalloc (1, sizeof *ctrl->server_local);
2467 if (!ctrl || !ctrl->server_local)
2469 log_error (_("can't allocate control structure: %s\n"),
2475 dirmngr_init_default_ctrl (ctrl);
2477 rc = assuan_new (&ctx);
2480 log_error (_("failed to allocate assuan context: %s\n"),
2485 if (fd == ASSUAN_INVALID_FD)
2487 assuan_fd_t filedes[2];
2489 filedes[0] = assuan_fdopen (0);
2490 filedes[1] = assuan_fdopen (1);
2491 rc = assuan_init_pipe_server (ctx, filedes);
2495 rc = assuan_init_socket_server (ctx, fd, ASSUAN_SOCKET_SERVER_ACCEPTED);
2500 assuan_release (ctx);
2501 log_error (_("failed to initialize the server: %s\n"),
2506 rc = register_commands (ctx);
2509 log_error (_("failed to the register commands with Assuan: %s\n"),
2517 hello_line = xtryasprintf
2522 opt.config_filename? opt.config_filename : "[none]",
2526 ctrl->server_local->assuan_ctx = ctx;
2527 assuan_set_pointer (ctx, ctrl);
2529 assuan_set_hello_line (ctx, hello_line);
2530 assuan_register_option_handler (ctx, option_handler);
2531 assuan_register_reset_notify (ctx, reset_notify);
2535 rc = assuan_accept (ctx);
2540 log_info (_("Assuan accept problem: %s\n"), gpg_strerror (rc));
2544 #ifndef HAVE_W32_SYSTEM
2547 assuan_peercred_t peercred;
2549 if (!assuan_get_peercred (ctx, &peercred))
2550 log_info ("connection from process %ld (%ld:%ld)\n",
2551 (long)peercred->pid, (long)peercred->uid,
2552 (long)peercred->gid);
2556 rc = assuan_process (ctx);
2559 log_info (_("Assuan processing failed: %s\n"), gpg_strerror (rc));
2566 ldap_wrapper_connection_cleanup (ctrl);
2568 ldapserver_list_free (ctrl->server_local->ldapservers);
2570 ctrl->server_local->ldapservers = NULL;
2572 release_ctrl_keyservers (ctrl);
2574 ctrl->server_local->assuan_ctx = NULL;
2575 assuan_release (ctx);
2577 if (ctrl->server_local->stopme)
2581 log_error ("oops: connection control structure still referenced (%d)\n",
2585 release_ctrl_ocsp_certs (ctrl);
2586 xfree (ctrl->server_local);
2587 dirmngr_deinit_default_ctrl (ctrl);
2593 /* Send a status line back to the client. KEYWORD is the status
2594 keyword, the optional string arguments are blank separated added to
2595 the line, the last argument must be a NULL. */
2597 dirmngr_status (ctrl_t ctrl, const char *keyword, ...)
2599 gpg_error_t err = 0;
2603 va_start (arg_ptr, keyword);
2605 if (ctrl->server_local)
2607 assuan_context_t ctx = ctrl->server_local->assuan_ctx;
2613 while ( (text = va_arg (arg_ptr, const char *)) )
2620 for ( ; *text && n < DIM (buf)-2; n++)
2624 err = assuan_write_status (ctx, keyword, buf);
2632 /* Print a help status line. TEXTLEN gives the length of the text
2633 from TEXT to be printed. The function splits text at LFs. */
2635 dirmngr_status_help (ctrl_t ctrl, const char *text)
2637 gpg_error_t err = 0;
2639 if (ctrl->server_local)
2641 assuan_context_t ctx = ctrl->server_local->assuan_ctx;
2649 for ( ; *text && *text != '\n' && n < DIM (buf)-2; n++)
2654 err = assuan_write_status (ctx, "#", buf);
2656 while (!err && *text);
2662 /* Send a tick progress indicator back. Fixme: This is only done for
2663 the currently active channel. */
2665 dirmngr_tick (ctrl_t ctrl)
2667 static time_t next_tick = 0;
2668 gpg_error_t err = 0;
2669 time_t now = time (NULL);
2673 next_tick = now + 1;
2675 else if ( now > next_tick )
2679 err = dirmngr_status (ctrl, "PROGRESS", "tick", "? 0 0", NULL);
2682 /* Take this as in indication for a cancel request. */
2683 err = gpg_error (GPG_ERR_CANCELED);
2688 next_tick = now + 1;