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 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 <http://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"
54 #include "mbox-util.h"
56 /* To avoid DoS attacks we limit the size of a certificate to
57 something reasonable. The DoS was actually only an issue back when
58 Dirmngr was a system service and not a user service. */
59 #define MAX_CERT_LENGTH (16*1024)
61 /* The same goes for OpenPGP keyblocks, but here we need to allow for
62 much longer blocks; a 200k keyblock is not too unusual for keys
63 with a lot of signatures (e.g. 0x5b0358a2). 9C31503C6D866396 even
64 has 770 KiB as of 2015-08-23. To avoid adding a runtime option we
65 now use 20MiB which should really be enough. Well, a key with
66 several pictures could be larger (the parser as a 18MiB limit for
67 attribute packets) but it won't be nice to the keyservers to send
68 them such large blobs. */
69 #define MAX_KEYBLOCK_LENGTH (20*1024*1024)
72 #define PARM_ERROR(t) assuan_set_error (ctx, \
73 gpg_error (GPG_ERR_ASS_PARAMETER), (t))
74 #define set_error(e,t) assuan_set_error (ctx, gpg_error (e), (t))
78 /* Control structure per connection. */
81 /* Data used to associate an Assuan context with local server data */
82 assuan_context_t assuan_ctx;
84 /* Per-session LDAP servers. */
85 ldap_server_t ldapservers;
87 /* Per-session list of keyservers. */
88 uri_item_t keyservers;
90 /* If this flag is set to true this dirmngr process will be
91 terminated after the end of this session. */
96 /* Cookie definition for assuan data line output. */
97 static ssize_t data_line_cookie_write (void *cookie,
98 const void *buffer, size_t size);
99 static int data_line_cookie_close (void *cookie);
100 static es_cookie_io_functions_t data_line_cookie_functions =
103 data_line_cookie_write,
105 data_line_cookie_close
112 /* Accessor for the local ldapservers variable. */
114 get_ldapservers_from_ctrl (ctrl_t ctrl)
116 if (ctrl && ctrl->server_local)
117 return ctrl->server_local->ldapservers;
123 /* Release all configured keyserver info from CTRL. */
125 release_ctrl_keyservers (ctrl_t ctrl)
127 if (! ctrl->server_local)
130 while (ctrl->server_local->keyservers)
132 uri_item_t tmp = ctrl->server_local->keyservers->next;
133 http_release_parsed_uri (ctrl->server_local->keyservers->parsed_uri);
134 xfree (ctrl->server_local->keyservers);
135 ctrl->server_local->keyservers = tmp;
141 /* Helper to print a message while leaving a command. */
143 leave_cmd (assuan_context_t ctx, gpg_error_t err)
147 const char *name = assuan_get_command_name (ctx);
150 if (gpg_err_source (err) == GPG_ERR_SOURCE_DEFAULT)
151 log_error ("command '%s' failed: %s\n", name,
154 log_error ("command '%s' failed: %s <%s>\n", name,
155 gpg_strerror (err), gpg_strsource (err));
161 /* This is a wrapper around assuan_send_data which makes debugging the
162 output in verbose mode easier. */
164 data_line_write (assuan_context_t ctx, const void *buffer_arg, size_t size)
166 const char *buffer = buffer_arg;
169 if (opt.verbose && buffer && size)
171 /* Ease reading of output by sending a physical line at each LF. */
178 p = memchr (buffer, '\n', nbytes);
179 n = p ? (p - buffer) + 1 : nbytes;
180 err = assuan_send_data (ctx, buffer, n);
183 gpg_err_set_errno (EIO);
188 if (nbytes && (err=assuan_send_data (ctx, NULL, 0))) /* Flush line. */
190 gpg_err_set_errno (EIO);
198 err = assuan_send_data (ctx, buffer, size);
201 gpg_err_set_errno (EIO); /* For use by data_line_cookie_write. */
210 /* A write handler used by es_fopencookie to write assuan data
213 data_line_cookie_write (void *cookie, const void *buffer, size_t size)
215 assuan_context_t ctx = cookie;
217 if (data_line_write (ctx, buffer, size))
219 return (ssize_t)size;
224 data_line_cookie_close (void *cookie)
226 assuan_context_t ctx = cookie;
228 if (assuan_send_data (ctx, NULL, 0))
230 gpg_err_set_errno (EIO);
238 /* Copy the % and + escaped string S into the buffer D and replace the
239 escape sequences. Note, that it is sufficient to allocate the
240 target string D as long as the source string S, i.e.: strlen(s)+1.
241 Note further that if S contains an escaped binary Nul the resulting
242 string D will contain the 0 as well as all other characters but it
243 will be impossible to know whether this is the original EOS or a
246 strcpy_escaped_plus (char *d, const unsigned char *s)
250 if (*s == '%' && s[1] && s[2])
265 /* Check whether the option NAME appears in LINE */
267 has_option (const char *line, const char *name)
270 int n = strlen (name);
272 s = strstr (line, name);
273 return (s && (s == line || spacep (s-1)) && (!s[n] || spacep (s+n)));
276 /* Same as has_option but only considers options at the begin of the
277 line. This is useful for commands which allow arbitrary strings on
280 has_leading_option (const char *line, const char *name)
285 if (name[0] != '-' || name[1] != '-' || !name[2] || spacep (name+2))
288 while ( *line == '-' && line[1] == '-' )
291 while (*line && !spacep (line))
293 if (n == (line - s) && !strncmp (s, name, n))
295 while (spacep (line))
302 /* Same as has_option but does only test for the name of the option
303 and ignores an argument, i.e. with NAME being "--hash" it would
304 return a pointer for "--hash" as well as for "--hash=foo". If
305 thhere is no such option NULL is returned. The pointer returned
306 points right behind the option name, this may be an equal sign, Nul
308 /* static const char * */
309 /* has_option_name (const char *line, const char *name) */
312 /* int n = strlen (name); */
314 /* s = strstr (line, name); */
315 /* return (s && (s == line || spacep (s-1)) */
316 /* && (!s[n] || spacep (s+n) || s[n] == '=')) ? (s+n) : NULL; */
320 /* Skip over options. It is assumed that leading spaces have been
321 removed (this is the case for lines passed to a handler from
322 assuan). Blanks after the options are also removed. */
324 skip_options (char *line)
326 while ( *line == '-' && line[1] == '-' )
328 while (*line && !spacep (line))
330 while (spacep (line))
337 /* Return an error if the assuan context does not belong to the owner
338 of the process or to root. On error FAILTEXT is set as Assuan
341 check_owner_permission (assuan_context_t ctx, const char *failtext)
343 #ifdef HAVE_W32_SYSTEM
344 /* Under Windows the dirmngr is always run under the control of the
350 assuan_peercred_t cred;
352 ec = gpg_err_code (assuan_get_peercred (ctx, &cred));
353 if (!ec && cred->uid && cred->uid != getuid ())
356 return set_error (ec, failtext);
363 /* Common code for get_cert_local and get_issuer_cert_local. */
365 do_get_cert_local (ctrl_t ctrl, const char *name, const char *command)
367 unsigned char *value;
375 buf = xmalloc ( strlen (command) + 1 + strlen(name) + 1);
376 strcpy (stpcpy (stpcpy (buf, command), " "), name);
379 buf = xstrdup (command);
381 rc = assuan_inquire (ctrl->server_local->assuan_ctx, buf,
382 &value, &valuelen, MAX_CERT_LENGTH);
386 log_error (_("assuan_inquire(%s) failed: %s\n"),
387 command, gpg_strerror (rc));
397 rc = ksba_cert_new (&cert);
400 rc = ksba_cert_init_from_mem (cert, value, valuelen);
403 ksba_cert_release (cert);
413 /* Ask back to return a certificate for name, given as a regular
414 gpgsm certificate indentificates (e.g. fingerprint or one of the
415 other methods). Alternatively, NULL may be used for NAME to
416 return the current target certificate. Either return the certificate
417 in a KSBA object or NULL if it is not available.
420 get_cert_local (ctrl_t ctrl, const char *name)
422 if (!ctrl || !ctrl->server_local || !ctrl->server_local->assuan_ctx)
425 log_debug ("get_cert_local called w/o context\n");
428 return do_get_cert_local (ctrl, name, "SENDCERT");
432 /* Ask back to return the issuing certificate for name, given as a
433 regular gpgsm certificate indentificates (e.g. fingerprint or one
434 of the other methods). Alternatively, NULL may be used for NAME to
435 return thecurrent target certificate. Either return the certificate
436 in a KSBA object or NULL if it is not available.
440 get_issuing_cert_local (ctrl_t ctrl, const char *name)
442 if (!ctrl || !ctrl->server_local || !ctrl->server_local->assuan_ctx)
445 log_debug ("get_issuing_cert_local called w/o context\n");
448 return do_get_cert_local (ctrl, name, "SENDISSUERCERT");
451 /* Ask back to return a certificate with subject NAME and a
452 subjectKeyIdentifier of KEYID. */
454 get_cert_local_ski (ctrl_t ctrl, const char *name, ksba_sexp_t keyid)
456 unsigned char *value;
463 if (!ctrl || !ctrl->server_local || !ctrl->server_local->assuan_ctx)
466 log_debug ("get_cert_local_ski called w/o context\n");
471 log_debug ("get_cert_local_ski called with insufficient arguments\n");
475 hexkeyid = serial_hex (keyid);
478 log_debug ("serial_hex() failed\n");
482 buf = xtrymalloc (15 + strlen (hexkeyid) + 2 + strlen(name) + 1);
486 log_error ("can't allocate enough memory: %s\n", strerror (errno));
490 strcpy (stpcpy (stpcpy (stpcpy (buf, "SENDCERT_SKI "), hexkeyid)," /"),name);
493 rc = assuan_inquire (ctrl->server_local->assuan_ctx, buf,
494 &value, &valuelen, MAX_CERT_LENGTH);
498 log_error (_("assuan_inquire(%s) failed: %s\n"), "SENDCERT_SKI",
509 rc = ksba_cert_new (&cert);
512 rc = ksba_cert_init_from_mem (cert, value, valuelen);
515 ksba_cert_release (cert);
524 /* Ask the client via an inquiry to check the istrusted status of the
525 certificate specified by the hexified fingerprint HEXFPR. Returns
526 0 if the certificate is trusted by the client or an error code. */
528 get_istrusted_from_client (ctrl_t ctrl, const char *hexfpr)
530 unsigned char *value;
535 if (!ctrl || !ctrl->server_local || !ctrl->server_local->assuan_ctx
537 return gpg_error (GPG_ERR_INV_ARG);
539 snprintf (request, sizeof request, "ISTRUSTED %s", hexfpr);
540 rc = assuan_inquire (ctrl->server_local->assuan_ctx, request,
541 &value, &valuelen, 100);
544 log_error (_("assuan_inquire(%s) failed: %s\n"),
545 request, gpg_strerror (rc));
548 /* The expected data is: "1" or "1 cruft" (not a C-string). */
549 if (valuelen && *value == '1' && (valuelen == 1 || spacep (value+1)))
552 rc = gpg_error (GPG_ERR_NOT_TRUSTED);
560 /* Ask the client to return the certificate associated with the
561 current command. This is sometimes needed because the client usually
562 sends us just the cert ID, assuming that the request can be
563 satisfied from the cache, where the cert ID is used as key. */
565 inquire_cert_and_load_crl (assuan_context_t ctx)
567 ctrl_t ctrl = assuan_get_pointer (ctx);
569 unsigned char *value = NULL;
571 ksba_cert_t cert = NULL;
573 err = assuan_inquire( ctx, "SENDCERT", &value, &valuelen, 0);
578 /* FILE *fp = fopen ("foo.der", "r"); */
579 /* value = xmalloc (2000); */
580 /* valuelen = fread (value, 1, 2000, fp); */
584 if (!valuelen) /* No data returned; return a comprehensible error. */
585 return gpg_error (GPG_ERR_MISSING_CERT);
587 err = ksba_cert_new (&cert);
590 err = ksba_cert_init_from_mem (cert, value, valuelen);
593 xfree (value); value = NULL;
595 err = crl_cache_reload_crl (ctrl, cert);
598 ksba_cert_release (cert);
604 /* Handle OPTION commands. */
606 option_handler (assuan_context_t ctx, const char *key, const char *value)
608 ctrl_t ctrl = assuan_get_pointer (ctx);
611 if (!strcmp (key, "force-crl-refresh"))
613 int i = *value? atoi (value) : 0;
614 ctrl->force_crl_refresh = i;
616 else if (!strcmp (key, "audit-events"))
618 int i = *value? atoi (value) : 0;
619 ctrl->audit_events = i;
621 else if (!strcmp (key, "http-proxy"))
623 xfree (ctrl->http_proxy);
624 if (!*value || !strcmp (value, "none"))
625 ctrl->http_proxy = NULL;
626 else if (!(ctrl->http_proxy = xtrystrdup (value)))
627 err = gpg_error_from_syserror ();
629 else if (!strcmp (key, "honor-keyserver-url-used"))
631 /* Return an error if we are running in TOR mode. */
633 err = gpg_error (GPG_ERR_FORBIDDEN);
636 err = gpg_error (GPG_ERR_UNKNOWN_OPTION);
643 static const char hlp_dns_cert[] =
644 "DNS_CERT <subtype> <name>\n"
645 "DNS_CERT --pka <user_id>\n"
646 "DNS_CERT --dane <user_id>\n"
648 "Return the CERT record for <name>. <subtype> is one of\n"
649 " * Return the first record of any supported subtype\n"
650 " PGP Return the first record of subtype PGP (3)\n"
651 " IPGP Return the first record of subtype IPGP (6)\n"
652 "If the content of a certifciate is available (PGP) it is returned\n"
653 "by data lines. Fingerprints and URLs are returned via status lines.\n"
654 "In --pka mode the fingerprint and if available an URL is returned.\n"
655 "In --dane mode the key is returned from RR type 61";
657 cmd_dns_cert (assuan_context_t ctx, char *line)
659 /* ctrl_t ctrl = assuan_get_pointer (ctx); */
661 int pka_mode, dane_mode;
663 char *namebuf = NULL;
664 char *encodedhash = NULL;
670 unsigned char *fpr = NULL;
674 pka_mode = has_option (line, "--pka");
675 dane_mode = has_option (line, "--dane");
676 line = skip_options (line);
678 if (pka_mode && dane_mode)
680 err = PARM_ERROR ("either --pka or --dane may be given");
684 if (pka_mode || dane_mode)
685 ; /* No need to parse here - we do this later. */
688 p = strchr (line, ' ');
691 err = PARM_ERROR ("missing arguments");
695 if (!strcmp (line, "*"))
696 certtype = DNS_CERTTYPE_ANY;
697 else if (!strcmp (line, "IPGP"))
698 certtype = DNS_CERTTYPE_IPGP;
699 else if (!strcmp (line, "PGP"))
700 certtype = DNS_CERTTYPE_PGP;
703 err = PARM_ERROR ("unknown subtype");
711 err = PARM_ERROR ("name missing");
718 err = gpg_error (GPG_ERR_FORBIDDEN);
722 if (pka_mode || dane_mode)
724 char *domain; /* Points to mbox. */
725 char hashbuf[32]; /* For SHA-1 and SHA-256. */
727 /* We lowercase ascii characters but the DANE I-D does not allow
728 this. FIXME: Check after the release of the RFC whether to
730 mbox = mailbox_from_userid (line);
731 if (!mbox || !(domain = strchr (mbox, '@')))
733 err = set_error (GPG_ERR_INV_USER_ID, "no mailbox in user id");
740 gcry_md_hash_buffer (GCRY_MD_SHA1, hashbuf, mbox, strlen (mbox));
741 encodedhash = zb32_encode (hashbuf, 8*20);
744 err = gpg_error_from_syserror ();
747 namebuf = strconcat (encodedhash, "._pka.", domain, NULL);
750 err = gpg_error_from_syserror ();
754 certtype = DNS_CERTTYPE_IPGP;
758 /* Note: The hash is truncated to 28 bytes and we lowercase
759 the result only for aesthetic reasons. */
760 gcry_md_hash_buffer (GCRY_MD_SHA256, hashbuf, mbox, strlen (mbox));
761 encodedhash = bin2hex (hashbuf, 28, NULL);
764 err = gpg_error_from_syserror ();
767 ascii_strlwr (encodedhash);
768 namebuf = strconcat (encodedhash, "._openpgpkey.", domain, NULL);
771 err = gpg_error_from_syserror ();
775 certtype = DNS_CERTTYPE_RR61;
781 err = get_dns_cert (name, certtype, &key, &keylen, &fpr, &fprlen, &url);
787 err = data_line_write (ctx, key, keylen);
796 tmpstr = bin2hex (fpr, fprlen, NULL);
798 err = gpg_error_from_syserror ();
801 err = assuan_write_status (ctx, "FPR", tmpstr);
810 err = assuan_write_status (ctx, "URL", url);
823 return leave_cmd (ctx, err);
828 static const char hlp_ldapserver[] =
829 "LDAPSERVER <data>\n"
831 "Add a new LDAP server to the list of configured LDAP servers.\n"
832 "DATA is in the same format as expected in the configure file.";
834 cmd_ldapserver (assuan_context_t ctx, char *line)
837 ctrl_t ctrl = assuan_get_pointer (ctx);
838 ldap_server_t server;
839 ldap_server_t *last_next_p;
841 while (spacep (line))
844 return leave_cmd (ctx, PARM_ERROR (_("ldapserver missing")));
846 server = ldapserver_parse_one (line, "", 0);
848 return leave_cmd (ctx, gpg_error (GPG_ERR_INV_ARG));
850 last_next_p = &ctrl->server_local->ldapservers;
852 last_next_p = &(*last_next_p)->next;
853 *last_next_p = server;
854 return leave_cmd (ctx, 0);
857 return leave_cmd (ctx, gpg_error (GPG_ERR_NOT_IMPLEMENTED));
862 static const char hlp_isvalid[] =
863 "ISVALID [--only-ocsp] [--force-default-responder]"
864 " <certificate_id>|<certificate_fpr>\n"
866 "This command checks whether the certificate identified by the\n"
867 "certificate_id is valid. This is done by consulting CRLs or\n"
868 "whatever has been configured. Note, that the returned error codes\n"
869 "are from gpg-error.h. The command may callback using the inquire\n"
870 "function. See the manual for details.\n"
872 "The CERTIFICATE_ID is a hex encoded string consisting of two parts,\n"
873 "delimited by a single dot. The first part is the SHA-1 hash of the\n"
874 "issuer name and the second part the serial number.\n"
876 "Alternatively the certificate's fingerprint may be given in which\n"
877 "case an OCSP request is done before consulting the CRL.\n"
879 "If the option --only-ocsp is given, no fallback to a CRL check will\n"
882 "If the option --force-default-responder is given, only the default\n"
883 "OCSP responder will be used and any other methods of obtaining an\n"
884 "OCSP responder URL won't be used.";
886 cmd_isvalid (assuan_context_t ctx, char *line)
888 ctrl_t ctrl = assuan_get_pointer (ctx);
889 char *issuerhash, *serialno;
894 int force_default_responder;
896 only_ocsp = has_option (line, "--only-ocsp");
897 force_default_responder = has_option (line, "--force-default-responder");
898 line = skip_options (line);
900 issuerhash = xstrdup (line); /* We need to work on a copy of the
901 line because that same Assuan
902 context may be used for an inquiry.
903 That is because Assuan reuses its
907 serialno = strchr (issuerhash, '.');
912 char *endp = strchr (issuerhash, ' ');
915 if (strlen (issuerhash) != 40)
918 return leave_cmd (ctx, PARM_ERROR (_("serialno missing in cert ID")));
927 /* Note, that we ignore the given issuer hash and instead rely
928 on the current certificate semantics used with this
931 err = gpg_error (GPG_ERR_NOT_SUPPORTED);
933 err = ocsp_isvalid (ctrl, NULL, NULL, force_default_responder);
934 /* Fixme: If we got no ocsp response and --only-ocsp is not used
935 we should fall back to CRL mode. Thus we need to clear
936 OCSP_MODE, get the issuerhash and the serialno from the
937 current certificate and jump to again. */
940 err = gpg_error (GPG_ERR_NO_CRL_KNOWN);
943 switch (crl_cache_isvalid (ctrl,
944 issuerhash, serialno,
945 ctrl->force_crl_refresh))
947 case CRL_CACHE_VALID:
950 case CRL_CACHE_INVALID:
951 err = gpg_error (GPG_ERR_CERT_REVOKED);
953 case CRL_CACHE_DONTKNOW:
955 err = gpg_error (GPG_ERR_NO_CRL_KNOWN);
956 else if (!(err = inquire_cert_and_load_crl (ctx)))
962 case CRL_CACHE_CANTUSE:
963 err = gpg_error (GPG_ERR_NO_CRL_KNOWN);
966 log_fatal ("crl_cache_isvalid returned invalid code\n");
971 return leave_cmd (ctx, err);
975 /* If the line contains a SHA-1 fingerprint as the first argument,
976 return the FPR vuffer on success. The function checks that the
977 fingerprint consists of valid characters and prints and error
978 message if it does not and returns NULL. Fingerprints are
979 considered optional and thus no explicit error is returned. NULL is
980 also returned if there is no fingerprint at all available.
981 FPR must be a caller provided buffer of at least 20 bytes.
983 Note that colons within the fingerprint are allowed to separate 2
984 hex digits; this allows for easier cutting and pasting using the
985 usual fingerprint rendering.
987 static unsigned char *
988 get_fingerprint_from_line (const char *line, unsigned char *fpr)
993 for (s=line, i=0; *s && *s != ' '; s++ )
995 if ( hexdigitp (s) && hexdigitp (s+1) )
998 return NULL; /* Fingerprint too long. */
999 fpr[i++] = xtoi_2 (s);
1002 else if ( *s != ':' )
1003 return NULL; /* Invalid. */
1006 return NULL; /* Fingerprint to short. */
1012 static const char hlp_checkcrl[] =
1013 "CHECKCRL [<fingerprint>]\n"
1015 "Check whether the certificate with FINGERPRINT (SHA-1 hash of the\n"
1016 "entire X.509 certificate blob) is valid or not by consulting the\n"
1017 "CRL responsible for this certificate. If the fingerprint has not\n"
1018 "been given or the certificate is not known, the function \n"
1019 "inquires the certificate using an\n"
1021 " INQUIRE TARGETCERT\n"
1023 "and the caller is expected to return the certificate for the\n"
1024 "request (which should match FINGERPRINT) as a binary blob.\n"
1025 "Processing then takes place without further interaction; in\n"
1026 "particular dirmngr tries to locate other required certificate by\n"
1027 "its own mechanism which includes a local certificate store as well\n"
1028 "as a list of trusted root certificates.\n"
1030 "The return value is the usual gpg-error code or 0 for ducesss;\n"
1031 "i.e. the certificate validity has been confirmed by a valid CRL.";
1033 cmd_checkcrl (assuan_context_t ctx, char *line)
1035 ctrl_t ctrl = assuan_get_pointer (ctx);
1037 unsigned char fprbuffer[20], *fpr;
1040 fpr = get_fingerprint_from_line (line, fprbuffer);
1041 cert = fpr? get_cert_byfpr (fpr) : NULL;
1045 /* We do not have this certificate yet or the fingerprint has
1046 not been given. Inquire it from the client. */
1047 unsigned char *value = NULL;
1050 err = assuan_inquire (ctrl->server_local->assuan_ctx, "TARGETCERT",
1051 &value, &valuelen, MAX_CERT_LENGTH);
1054 log_error (_("assuan_inquire failed: %s\n"), gpg_strerror (err));
1058 if (!valuelen) /* No data returned; return a comprehensible error. */
1059 err = gpg_error (GPG_ERR_MISSING_CERT);
1062 err = ksba_cert_new (&cert);
1064 err = ksba_cert_init_from_mem (cert, value, valuelen);
1073 err = crl_cache_cert_isvalid (ctrl, cert, ctrl->force_crl_refresh);
1074 if (gpg_err_code (err) == GPG_ERR_NO_CRL_KNOWN)
1076 err = crl_cache_reload_crl (ctrl, cert);
1078 err = crl_cache_cert_isvalid (ctrl, cert, 0);
1082 ksba_cert_release (cert);
1083 return leave_cmd (ctx, err);
1087 static const char hlp_checkocsp[] =
1088 "CHECKOCSP [--force-default-responder] [<fingerprint>]\n"
1090 "Check whether the certificate with FINGERPRINT (SHA-1 hash of the\n"
1091 "entire X.509 certificate blob) is valid or not by asking an OCSP\n"
1092 "responder responsible for this certificate. The optional\n"
1093 "fingerprint may be used for a quick check in case an OCSP check has\n"
1094 "been done for this certificate recently (we always cache OCSP\n"
1095 "responses for a couple of minutes). If the fingerprint has not been\n"
1096 "given or there is no cached result, the function inquires the\n"
1097 "certificate using an\n"
1099 " INQUIRE TARGETCERT\n"
1101 "and the caller is expected to return the certificate for the\n"
1102 "request (which should match FINGERPRINT) as a binary blob.\n"
1103 "Processing then takes place without further interaction; in\n"
1104 "particular dirmngr tries to locate other required certificates by\n"
1105 "its own mechanism which includes a local certificate store as well\n"
1106 "as a list of trusted root certifciates.\n"
1108 "If the option --force-default-responder is given, only the default\n"
1109 "OCSP responder will be used and any other methods of obtaining an\n"
1110 "OCSP responder URL won't be used.\n"
1112 "The return value is the usual gpg-error code or 0 for ducesss;\n"
1113 "i.e. the certificate validity has been confirmed by a valid CRL.";
1115 cmd_checkocsp (assuan_context_t ctx, char *line)
1117 ctrl_t ctrl = assuan_get_pointer (ctx);
1119 unsigned char fprbuffer[20], *fpr;
1121 int force_default_responder;
1123 force_default_responder = has_option (line, "--force-default-responder");
1124 line = skip_options (line);
1126 fpr = get_fingerprint_from_line (line, fprbuffer);
1127 cert = fpr? get_cert_byfpr (fpr) : NULL;
1131 /* We do not have this certificate yet or the fingerprint has
1132 not been given. Inquire it from the client. */
1133 unsigned char *value = NULL;
1136 err = assuan_inquire (ctrl->server_local->assuan_ctx, "TARGETCERT",
1137 &value, &valuelen, MAX_CERT_LENGTH);
1140 log_error (_("assuan_inquire failed: %s\n"), gpg_strerror (err));
1144 if (!valuelen) /* No data returned; return a comprehensible error. */
1145 err = gpg_error (GPG_ERR_MISSING_CERT);
1148 err = ksba_cert_new (&cert);
1150 err = ksba_cert_init_from_mem (cert, value, valuelen);
1159 if (!opt.allow_ocsp)
1160 err = gpg_error (GPG_ERR_NOT_SUPPORTED);
1162 err = ocsp_isvalid (ctrl, cert, NULL, force_default_responder);
1165 ksba_cert_release (cert);
1166 return leave_cmd (ctx, err);
1172 lookup_cert_by_url (assuan_context_t ctx, const char *url)
1174 ctrl_t ctrl = assuan_get_pointer (ctx);
1175 gpg_error_t err = 0;
1176 unsigned char *value = NULL;
1179 /* Fetch single certificate given it's URL. */
1180 err = fetch_cert_by_url (ctrl, url, &value, &valuelen);
1183 log_error (_("fetch_cert_by_url failed: %s\n"), gpg_strerror (err));
1187 /* Send the data, flush the buffer and then send an END. */
1188 err = assuan_send_data (ctx, value, valuelen);
1190 err = assuan_send_data (ctx, NULL, 0);
1192 err = assuan_write_line (ctx, "END");
1195 log_error (_("error sending data: %s\n"), gpg_strerror (err));
1205 /* Send the certificate, flush the buffer and then send an END. */
1207 return_one_cert (void *opaque, ksba_cert_t cert)
1209 assuan_context_t ctx = opaque;
1211 const unsigned char *der;
1214 der = ksba_cert_get_image (cert, &derlen);
1216 err = gpg_error (GPG_ERR_INV_CERT_OBJ);
1219 err = assuan_send_data (ctx, der, derlen);
1221 err = assuan_send_data (ctx, NULL, 0);
1223 err = assuan_write_line (ctx, "END");
1226 log_error (_("error sending data: %s\n"), gpg_strerror (err));
1231 /* Lookup certificates from the internal cache or using the ldap
1234 lookup_cert_by_pattern (assuan_context_t ctx, char *line,
1235 int single, int cache_only)
1237 gpg_error_t err = 0;
1239 strlist_t sl, list = NULL;
1240 int truncated = 0, truncation_forced = 0;
1242 int local_count = 0;
1244 ctrl_t ctrl = assuan_get_pointer (ctx);
1245 unsigned char *value = NULL;
1247 struct ldapserver_iter ldapserver_iter;
1248 cert_fetch_context_t fetch_context;
1250 int any_no_data = 0;
1252 /* Break the line down into an STRLIST */
1253 for (p=line; *p; line = p)
1255 while (*p && *p != ' ')
1262 sl = xtrymalloc (sizeof *sl + strlen (line));
1265 err = gpg_error_from_errno (errno);
1268 memset (sl, 0, sizeof *sl);
1269 strcpy_escaped_plus (sl->d, line);
1275 /* First look through the internal cache. The certifcates retruned
1276 here are not counted towards the truncation limit. */
1277 if (single && !cache_only)
1278 ; /* Do not read from the local cache in this case. */
1281 for (sl=list; sl; sl = sl->next)
1283 err = get_certs_bypattern (sl->d, return_one_cert, ctx);
1289 if (gpg_err_code (err) == GPG_ERR_NO_DATA)
1295 else if (gpg_err_code (err) == GPG_ERR_INV_NAME && !cache_only)
1297 /* No real fault because the internal pattern lookup
1298 can't yet cope with all types of pattern. */
1306 /* Loop over all configured servers unless we want only the
1307 certificates from the cache. */
1309 for (ldapserver_iter_begin (&ldapserver_iter, ctrl);
1310 !cache_only && !ldapserver_iter_end_p (&ldapserver_iter)
1311 && ldapserver_iter.server->host && !truncation_forced;
1312 ldapserver_iter_next (&ldapserver_iter))
1314 ldap_server_t ldapserver = ldapserver_iter.server;
1317 log_debug ("cmd_lookup: trying %s:%d base=%s\n",
1318 ldapserver->host, ldapserver->port,
1319 ldapserver->base?ldapserver->base : "[default]");
1321 /* Fetch certificates matching pattern */
1322 err = start_cert_fetch (ctrl, &fetch_context, list, ldapserver);
1323 if ( gpg_err_code (err) == GPG_ERR_NO_DATA )
1326 log_debug ("cmd_lookup: no data\n");
1333 log_error (_("start_cert_fetch failed: %s\n"), gpg_strerror (err));
1337 /* Fetch the certificates for this query. */
1338 while (!truncation_forced)
1340 xfree (value); value = NULL;
1341 err = fetch_next_cert (fetch_context, &value, &valuelen);
1342 if (gpg_err_code (err) == GPG_ERR_NO_DATA )
1348 if (gpg_err_code (err) == GPG_ERR_TRUNCATED)
1354 if (gpg_err_code (err) == GPG_ERR_EOF)
1361 err = gpg_error (GPG_ERR_BUG);
1366 log_error (_("fetch_next_cert failed: %s\n"),
1367 gpg_strerror (err));
1368 end_cert_fetch (fetch_context);
1373 log_debug ("cmd_lookup: returning one cert%s\n",
1374 truncated? " (truncated)":"");
1376 /* Send the data, flush the buffer and then send an END line
1377 as a certificate delimiter. */
1378 err = assuan_send_data (ctx, value, valuelen);
1380 err = assuan_send_data (ctx, NULL, 0);
1382 err = assuan_write_line (ctx, "END");
1385 log_error (_("error sending data: %s\n"), gpg_strerror (err));
1386 end_cert_fetch (fetch_context);
1390 if (++count >= opt.max_replies )
1392 truncation_forced = 1;
1393 log_info (_("max_replies %d exceeded\n"), opt.max_replies );
1399 end_cert_fetch (fetch_context);
1404 if (truncated || truncation_forced)
1408 sprintf (str, "%d", count);
1409 assuan_write_status (ctx, "TRUNCATED", str);
1412 if (!err && !count && !local_count && any_no_data)
1413 err = gpg_error (GPG_ERR_NO_DATA);
1416 free_strlist (list);
1421 static const char hlp_lookup[] =
1422 "LOOKUP [--url] [--single] [--cache-only] <pattern>\n"
1424 "Lookup certificates matching PATTERN. With --url the pattern is\n"
1425 "expected to be one URL.\n"
1427 "If --url is not given: To allow for multiple patterns (which are ORed)\n"
1428 "quoting is required: Spaces are translated to \"+\" or \"%20\";\n"
1429 "obviously this requires that the usual escape quoting rules are applied.\n"
1431 "If --url is given no special escaping is required because URLs are\n"
1432 "already escaped this way.\n"
1434 "If --single is given the first and only the first match will be\n"
1435 "returned. If --cache-only is _not_ given, no local query will be\n"
1438 "If --cache-only is given no external lookup is done so that only\n"
1439 "certificates from the cache may get returned.";
1441 cmd_lookup (assuan_context_t ctx, char *line)
1444 int lookup_url, single, cache_only;
1446 lookup_url = has_leading_option (line, "--url");
1447 single = has_leading_option (line, "--single");
1448 cache_only = has_leading_option (line, "--cache-only");
1449 line = skip_options (line);
1451 if (lookup_url && cache_only)
1452 err = gpg_error (GPG_ERR_NOT_FOUND);
1453 else if (lookup_url && single)
1454 err = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1455 else if (lookup_url)
1456 err = lookup_cert_by_url (ctx, line);
1458 err = lookup_cert_by_pattern (ctx, line, single, cache_only);
1460 return leave_cmd (ctx, err);
1464 static const char hlp_loadcrl[] =
1465 "LOADCRL [--url] <filename|url>\n"
1467 "Load the CRL in the file with name FILENAME into our cache. Note\n"
1468 "that FILENAME should be given with an absolute path because\n"
1469 "Dirmngrs cwd is not known. With --url the CRL is directly loaded\n"
1470 "from the given URL.\n"
1472 "This command is usually used by gpgsm using the invocation \"gpgsm\n"
1473 "--call-dirmngr loadcrl <filename>\". A direct invocation of Dirmngr\n"
1474 "is not useful because gpgsm might need to callback gpgsm to ask for\n"
1475 "the CA's certificate.";
1477 cmd_loadcrl (assuan_context_t ctx, char *line)
1479 ctrl_t ctrl = assuan_get_pointer (ctx);
1480 gpg_error_t err = 0;
1481 int use_url = has_leading_option (line, "--url");
1483 line = skip_options (line);
1487 ksba_reader_t reader;
1489 err = crl_fetch (ctrl, line, &reader);
1491 log_error (_("fetching CRL from '%s' failed: %s\n"),
1492 line, gpg_strerror (err));
1495 err = crl_cache_insert (ctrl, line, reader);
1497 log_error (_("processing CRL from '%s' failed: %s\n"),
1498 line, gpg_strerror (err));
1499 crl_close_reader (reader);
1506 buf = xtrymalloc (strlen (line)+1);
1508 err = gpg_error_from_syserror ();
1511 strcpy_escaped_plus (buf, line);
1512 err = crl_cache_load (ctrl, buf);
1517 return leave_cmd (ctx, err);
1521 static const char hlp_listcrls[] =
1524 "List the content of all CRLs in a readable format. This command is\n"
1525 "usually used by gpgsm using the invocation \"gpgsm --call-dirmngr\n"
1526 "listcrls\". It may also be used directly using \"dirmngr\n"
1529 cmd_listcrls (assuan_context_t ctx, char *line)
1536 fp = es_fopencookie (ctx, "w", data_line_cookie_functions);
1538 err = set_error (GPG_ERR_ASS_GENERAL, "error setting up a data stream");
1541 err = crl_cache_list (fp);
1544 return leave_cmd (ctx, err);
1548 static const char hlp_cachecert[] =
1551 "Put a certificate into the internal cache. This command might be\n"
1552 "useful if a client knows in advance certificates required for a\n"
1553 "test and wants to make sure they get added to the internal cache.\n"
1554 "It is also helpful for debugging. To get the actual certificate,\n"
1555 "this command immediately inquires it using\n"
1557 " INQUIRE TARGETCERT\n"
1559 "and the caller is expected to return the certificate for the\n"
1560 "request as a binary blob.";
1562 cmd_cachecert (assuan_context_t ctx, char *line)
1564 ctrl_t ctrl = assuan_get_pointer (ctx);
1566 ksba_cert_t cert = NULL;
1567 unsigned char *value = NULL;
1572 err = assuan_inquire (ctrl->server_local->assuan_ctx, "TARGETCERT",
1573 &value, &valuelen, MAX_CERT_LENGTH);
1576 log_error (_("assuan_inquire failed: %s\n"), gpg_strerror (err));
1580 if (!valuelen) /* No data returned; return a comprehensible error. */
1581 err = gpg_error (GPG_ERR_MISSING_CERT);
1584 err = ksba_cert_new (&cert);
1586 err = ksba_cert_init_from_mem (cert, value, valuelen);
1592 err = cache_cert (cert);
1595 ksba_cert_release (cert);
1596 return leave_cmd (ctx, err);
1600 static const char hlp_validate[] =
1603 "Validate a certificate using the certificate validation function\n"
1604 "used internally by dirmngr. This command is only useful for\n"
1605 "debugging. To get the actual certificate, this command immediately\n"
1606 "inquires it using\n"
1608 " INQUIRE TARGETCERT\n"
1610 "and the caller is expected to return the certificate for the\n"
1611 "request as a binary blob.";
1613 cmd_validate (assuan_context_t ctx, char *line)
1615 ctrl_t ctrl = assuan_get_pointer (ctx);
1617 ksba_cert_t cert = NULL;
1618 unsigned char *value = NULL;
1623 err = assuan_inquire (ctrl->server_local->assuan_ctx, "TARGETCERT",
1624 &value, &valuelen, MAX_CERT_LENGTH);
1627 log_error (_("assuan_inquire failed: %s\n"), gpg_strerror (err));
1631 if (!valuelen) /* No data returned; return a comprehensible error. */
1632 err = gpg_error (GPG_ERR_MISSING_CERT);
1635 err = ksba_cert_new (&cert);
1637 err = ksba_cert_init_from_mem (cert, value, valuelen);
1643 /* If we have this certificate already in our cache, use the cached
1644 version for validation because this will take care of any cached
1647 unsigned char fpr[20];
1648 ksba_cert_t tmpcert;
1650 cert_compute_fpr (cert, fpr);
1651 tmpcert = get_cert_byfpr (fpr);
1654 ksba_cert_release (cert);
1659 err = validate_cert_chain (ctrl, cert, NULL, VALIDATE_MODE_CERT, NULL);
1662 ksba_cert_release (cert);
1663 return leave_cmd (ctx, err);
1668 /* Parse an keyserver URI and store it in a new uri item which is
1669 returned at R_ITEM. On error return an error code. */
1671 make_keyserver_item (const char *uri, uri_item_t *r_item)
1677 item = xtrymalloc (sizeof *item + strlen (uri));
1679 return gpg_error_from_syserror ();
1682 item->parsed_uri = NULL;
1683 strcpy (item->uri, uri);
1686 if (ldap_uri_p (item->uri))
1687 err = ldap_parse_uri (&item->parsed_uri, uri);
1691 err = http_parse_uri (&item->parsed_uri, uri, 1);
1702 /* If no keyserver is stored in CTRL but a global keyserver has been
1703 set, put that global keyserver into CTRL. We need use this
1704 function to help migrate from the old gpg based keyserver
1705 configuration to the new dirmngr based configuration. */
1707 ensure_keyserver (ctrl_t ctrl)
1712 if (ctrl->server_local->keyservers)
1713 return 0; /* Already set for this session. */
1715 return 0; /* No global option set. */
1717 err = make_keyserver_item (opt.keyserver, &item);
1719 ctrl->server_local->keyservers = item;
1725 static const char hlp_keyserver[] =
1726 "KEYSERVER [<options>] [<uri>|<host>]\n"
1729 " --clear Remove all configured keyservers\n"
1730 " --resolve Resolve HKP host names and rotate\n"
1731 " --hosttable Print table of known hosts and pools\n"
1732 " --dead Mark <host> as dead\n"
1733 " --alive Mark <host> as alive\n"
1735 "If called without arguments list all configured keyserver URLs.\n"
1736 "If called with an URI add this as keyserver. Note that keyservers\n"
1737 "are configured on a per-session base. A default keyserver may already be\n"
1738 "present, thus the \"--clear\" option must be used to get full control.\n"
1739 "If \"--clear\" and an URI are used together the clear command is\n"
1740 "obviously executed first. A RESET command does not change the list\n"
1741 "of configured keyservers.";
1743 cmd_keyserver (assuan_context_t ctx, char *line)
1745 ctrl_t ctrl = assuan_get_pointer (ctx);
1746 gpg_error_t err = 0;
1747 int clear_flag, add_flag, help_flag, host_flag, resolve_flag;
1748 int dead_flag, alive_flag;
1749 uri_item_t item = NULL; /* gcc 4.4.5 is not able to detect that it
1750 is always initialized. */
1752 clear_flag = has_option (line, "--clear");
1753 help_flag = has_option (line, "--help");
1754 resolve_flag = has_option (line, "--resolve");
1755 host_flag = has_option (line, "--hosttable");
1756 dead_flag = has_option (line, "--dead");
1757 alive_flag = has_option (line, "--alive");
1758 line = skip_options (line);
1763 err = ks_action_help (ctrl, line);
1769 err = ensure_keyserver (ctrl);
1771 err = ks_action_resolve (ctrl, ctrl->server_local->keyservers);
1776 if (alive_flag && dead_flag)
1778 err = set_error (GPG_ERR_ASS_PARAMETER, "no support for zombies");
1783 err = check_owner_permission (ctx, "no permission to use --dead");
1787 if (alive_flag || dead_flag)
1791 err = set_error (GPG_ERR_ASS_PARAMETER, "name of host missing");
1795 err = ks_hkp_mark_host (ctrl, line, alive_flag);
1802 err = ks_hkp_print_hosttable (ctrl);
1806 if (resolve_flag || host_flag || alive_flag || dead_flag)
1811 err = make_keyserver_item (line, &item);
1816 release_ctrl_keyservers (ctrl);
1819 item->next = ctrl->server_local->keyservers;
1820 ctrl->server_local->keyservers = item;
1823 if (!add_flag && !clear_flag && !help_flag)
1825 /* List configured keyservers. However, we first add a global
1829 err = ensure_keyserver (ctrl);
1832 assuan_set_error (ctx, err,
1833 "Bad keyserver configuration in dirmngr.conf");
1837 for (u=ctrl->server_local->keyservers; u; u = u->next)
1838 dirmngr_status (ctrl, "KEYSERVER", u->uri, NULL);
1843 return leave_cmd (ctx, err);
1848 static const char hlp_ks_search[] =
1849 "KS_SEARCH {<pattern>}\n"
1851 "Search the configured OpenPGP keyservers (see command KEYSERVER)\n"
1852 "for keys matching PATTERN";
1854 cmd_ks_search (assuan_context_t ctx, char *line)
1856 ctrl_t ctrl = assuan_get_pointer (ctx);
1862 /* No options for now. */
1863 line = skip_options (line);
1865 /* Break the line down into an strlist. Each pattern is
1866 percent-plus escaped. */
1868 for (p=line; *p; line = p)
1870 while (*p && *p != ' ')
1876 sl = xtrymalloc (sizeof *sl + strlen (line));
1879 err = gpg_error_from_syserror ();
1883 strcpy_escaped_plus (sl->d, line);
1889 err = ensure_keyserver (ctrl);
1893 /* Setup an output stream and perform the search. */
1894 outfp = es_fopencookie (ctx, "w", data_line_cookie_functions);
1896 err = set_error (GPG_ERR_ASS_GENERAL, "error setting up a data stream");
1899 err = ks_action_search (ctrl, ctrl->server_local->keyservers,
1905 free_strlist (list);
1906 return leave_cmd (ctx, err);
1911 static const char hlp_ks_get[] =
1912 "KS_GET {<pattern>}\n"
1914 "Get the keys matching PATTERN from the configured OpenPGP keyservers\n"
1915 "(see command KEYSERVER). Each pattern should be a keyid, a fingerprint,\n"
1916 "or an exact name indicated by the '=' prefix.";
1918 cmd_ks_get (assuan_context_t ctx, char *line)
1920 ctrl_t ctrl = assuan_get_pointer (ctx);
1926 /* No options for now. */
1927 line = skip_options (line);
1929 /* Break the line into a strlist. Each pattern is by
1930 definition percent-plus escaped. However we only support keyids
1931 and fingerprints and thus the client has no need to apply the
1934 for (p=line; *p; line = p)
1936 while (*p && *p != ' ')
1942 sl = xtrymalloc (sizeof *sl + strlen (line));
1945 err = gpg_error_from_syserror ();
1949 strcpy_escaped_plus (sl->d, line);
1955 err = ensure_keyserver (ctrl);
1959 /* Setup an output stream and perform the get. */
1960 outfp = es_fopencookie (ctx, "w", data_line_cookie_functions);
1962 err = set_error (GPG_ERR_ASS_GENERAL, "error setting up a data stream");
1965 err = ks_action_get (ctrl, ctrl->server_local->keyservers, list, outfp);
1970 free_strlist (list);
1971 return leave_cmd (ctx, err);
1975 static const char hlp_ks_fetch[] =
1978 "Get the key(s) from URL.";
1980 cmd_ks_fetch (assuan_context_t ctx, char *line)
1982 ctrl_t ctrl = assuan_get_pointer (ctx);
1986 /* No options for now. */
1987 line = skip_options (line);
1989 err = ensure_keyserver (ctrl);
1993 /* Setup an output stream and perform the get. */
1994 outfp = es_fopencookie (ctx, "w", data_line_cookie_functions);
1996 err = set_error (GPG_ERR_ASS_GENERAL, "error setting up a data stream");
1999 err = ks_action_fetch (ctrl, line, outfp);
2004 return leave_cmd (ctx, err);
2009 static const char hlp_ks_put[] =
2012 "Send a key to the configured OpenPGP keyservers. The actual key material\n"
2013 "is then requested by Dirmngr using\n"
2015 " INQUIRE KEYBLOCK\n"
2017 "The client shall respond with a binary version of the keyblock (e.g.,\n"
2018 "the output of `gpg --export KEYID'). For LDAP\n"
2019 "keyservers Dirmngr may ask for meta information of the provided keyblock\n"
2022 " INQUIRE KEYBLOCK_INFO\n"
2024 "The client shall respond with a colon delimited info lines (the output\n"
2025 "of 'for x in keys sigs; do gpg --list-$x --with-colons KEYID; done').\n";
2027 cmd_ks_put (assuan_context_t ctx, char *line)
2029 ctrl_t ctrl = assuan_get_pointer (ctx);
2031 unsigned char *value = NULL;
2033 unsigned char *info = NULL;
2036 /* No options for now. */
2037 line = skip_options (line);
2039 err = ensure_keyserver (ctrl);
2043 /* Ask for the key material. */
2044 err = assuan_inquire (ctx, "KEYBLOCK",
2045 &value, &valuelen, MAX_KEYBLOCK_LENGTH);
2048 log_error (_("assuan_inquire failed: %s\n"), gpg_strerror (err));
2052 if (!valuelen) /* No data returned; return a comprehensible error. */
2054 err = gpg_error (GPG_ERR_MISSING_CERT);
2058 /* Ask for the key meta data. Not actually needed for HKP servers
2059 but we do it anyway to test the client implementaion. */
2060 err = assuan_inquire (ctx, "KEYBLOCK_INFO",
2061 &info, &infolen, MAX_KEYBLOCK_LENGTH);
2064 log_error (_("assuan_inquire failed: %s\n"), gpg_strerror (err));
2069 err = ks_action_put (ctrl, ctrl->server_local->keyservers,
2070 value, valuelen, info, infolen);
2075 return leave_cmd (ctx, err);
2081 static const char hlp_getinfo[] =
2084 "Multi purpose command to return certain information. \n"
2085 "Supported values of WHAT are:\n"
2087 "version - Return the version of the program.\n"
2088 "pid - Return the process id of the server.\n"
2089 "tor - Return OK if running in TOR mode\n"
2090 "socket_name - Return the name of the socket.\n";
2092 cmd_getinfo (assuan_context_t ctx, char *line)
2096 if (!strcmp (line, "version"))
2098 const char *s = VERSION;
2099 err = assuan_send_data (ctx, s, strlen (s));
2101 else if (!strcmp (line, "pid"))
2105 snprintf (numbuf, sizeof numbuf, "%lu", (unsigned long)getpid ());
2106 err = assuan_send_data (ctx, numbuf, strlen (numbuf));
2108 else if (!strcmp (line, "socket_name"))
2110 const char *s = dirmngr_user_socket_name ();
2113 s = dirmngr_sys_socket_name ();
2116 err = assuan_send_data (ctx, s, strlen (s));
2118 err = gpg_error (GPG_ERR_NO_DATA);
2120 else if (!strcmp (line, "tor"))
2122 err = opt.use_tor? 0:set_error (GPG_ERR_GENERAL, "TOR mode not enabled");
2125 err = set_error (GPG_ERR_ASS_PARAMETER, "unknown value for WHAT");
2127 return leave_cmd (ctx, err);
2132 static const char hlp_killdirmngr[] =
2135 "This command allows a user - given sufficient permissions -\n"
2136 "to kill this dirmngr process.\n";
2138 cmd_killdirmngr (assuan_context_t ctx, char *line)
2140 ctrl_t ctrl = assuan_get_pointer (ctx);
2145 if (opt.system_daemon)
2147 if (opt.system_service)
2148 err = set_error (GPG_ERR_NOT_SUPPORTED,
2149 "can't do that whilst running as system service");
2151 err = check_owner_permission (ctx,
2152 "no permission to kill this process");
2159 ctrl->server_local->stopme = 1;
2160 assuan_set_flag (ctx, ASSUAN_FORCE_CLOSE, 1);
2161 err = gpg_error (GPG_ERR_EOF);
2167 static const char hlp_reloaddirmngr[] =
2170 "This command is an alternative to SIGHUP\n"
2171 "to reload the configuration.";
2173 cmd_reloaddirmngr (assuan_context_t ctx, char *line)
2178 if (opt.system_daemon)
2180 #ifndef HAVE_W32_SYSTEM
2184 err = check_owner_permission (ctx,
2185 "no permission to reload this process");
2192 dirmngr_sighup_action ();
2199 /* Tell the assuan library about our commands. */
2201 register_commands (assuan_context_t ctx)
2205 assuan_handler_t handler;
2206 const char * const help;
2208 { "DNS_CERT", cmd_dns_cert, hlp_dns_cert },
2209 { "LDAPSERVER", cmd_ldapserver, hlp_ldapserver },
2210 { "ISVALID", cmd_isvalid, hlp_isvalid },
2211 { "CHECKCRL", cmd_checkcrl, hlp_checkcrl },
2212 { "CHECKOCSP", cmd_checkocsp, hlp_checkocsp },
2213 { "LOOKUP", cmd_lookup, hlp_lookup },
2214 { "LOADCRL", cmd_loadcrl, hlp_loadcrl },
2215 { "LISTCRLS", cmd_listcrls, hlp_listcrls },
2216 { "CACHECERT", cmd_cachecert, hlp_cachecert },
2217 { "VALIDATE", cmd_validate, hlp_validate },
2218 { "KEYSERVER", cmd_keyserver, hlp_keyserver },
2219 { "KS_SEARCH", cmd_ks_search, hlp_ks_search },
2220 { "KS_GET", cmd_ks_get, hlp_ks_get },
2221 { "KS_FETCH", cmd_ks_fetch, hlp_ks_fetch },
2222 { "KS_PUT", cmd_ks_put, hlp_ks_put },
2223 { "GETINFO", cmd_getinfo, hlp_getinfo },
2224 { "KILLDIRMNGR",cmd_killdirmngr,hlp_killdirmngr },
2225 { "RELOADDIRMNGR",cmd_reloaddirmngr,hlp_reloaddirmngr },
2230 for (i=j=0; table[i].name; i++)
2232 rc = assuan_register_command (ctx, table[i].name, table[i].handler,
2241 /* Note that we do not reset the list of configured keyservers. */
2243 reset_notify (assuan_context_t ctx, char *line)
2245 ctrl_t ctrl = assuan_get_pointer (ctx);
2249 ldapserver_list_free (ctrl->server_local->ldapservers);
2251 ctrl->server_local->ldapservers = NULL;
2256 /* Startup the server and run the main command loop. With FD = -1,
2257 use stdin/stdout. */
2259 start_command_handler (assuan_fd_t fd)
2261 static const char hello[] = "Dirmngr " VERSION " at your service";
2262 static char *hello_line;
2264 assuan_context_t ctx;
2267 ctrl = xtrycalloc (1, sizeof *ctrl);
2269 ctrl->server_local = xtrycalloc (1, sizeof *ctrl->server_local);
2270 if (!ctrl || !ctrl->server_local)
2272 log_error (_("can't allocate control structure: %s\n"),
2278 dirmngr_init_default_ctrl (ctrl);
2280 rc = assuan_new (&ctx);
2283 log_error (_("failed to allocate assuan context: %s\n"),
2288 if (fd == ASSUAN_INVALID_FD)
2290 assuan_fd_t filedes[2];
2292 filedes[0] = assuan_fdopen (0);
2293 filedes[1] = assuan_fdopen (1);
2294 rc = assuan_init_pipe_server (ctx, filedes);
2298 rc = assuan_init_socket_server (ctx, fd, ASSUAN_SOCKET_SERVER_ACCEPTED);
2303 assuan_release (ctx);
2304 log_error (_("failed to initialize the server: %s\n"),
2309 rc = register_commands (ctx);
2312 log_error (_("failed to the register commands with Assuan: %s\n"),
2321 const char *cfgname;
2323 cfgname = opt.config_filename? opt.config_filename : "[none]";
2325 n = (30 + strlen (opt.homedir) + strlen (cfgname)
2326 + strlen (hello) + 1);
2327 hello_line = xmalloc (n+1);
2328 snprintf (hello_line, n,
2338 ctrl->server_local->assuan_ctx = ctx;
2339 assuan_set_pointer (ctx, ctrl);
2341 assuan_set_hello_line (ctx, hello_line);
2342 assuan_register_option_handler (ctx, option_handler);
2343 assuan_register_reset_notify (ctx, reset_notify);
2347 rc = assuan_accept (ctx);
2352 log_info (_("Assuan accept problem: %s\n"), gpg_strerror (rc));
2356 #ifndef HAVE_W32_SYSTEM
2359 assuan_peercred_t peercred;
2361 if (!assuan_get_peercred (ctx, &peercred))
2362 log_info ("connection from process %ld (%ld:%ld)\n",
2363 (long)peercred->pid, (long)peercred->uid,
2364 (long)peercred->gid);
2368 rc = assuan_process (ctx);
2371 log_info (_("Assuan processing failed: %s\n"), gpg_strerror (rc));
2377 ldap_wrapper_connection_cleanup (ctrl);
2379 ldapserver_list_free (ctrl->server_local->ldapservers);
2381 ctrl->server_local->ldapservers = NULL;
2383 ctrl->server_local->assuan_ctx = NULL;
2384 assuan_release (ctx);
2386 if (ctrl->server_local->stopme)
2390 log_error ("oops: connection control structure still referenced (%d)\n",
2394 release_ctrl_ocsp_certs (ctrl);
2395 xfree (ctrl->server_local);
2396 dirmngr_deinit_default_ctrl (ctrl);
2402 /* Send a status line back to the client. KEYWORD is the status
2403 keyword, the optional string arguments are blank separated added to
2404 the line, the last argument must be a NULL. */
2406 dirmngr_status (ctrl_t ctrl, const char *keyword, ...)
2408 gpg_error_t err = 0;
2412 va_start (arg_ptr, keyword);
2414 if (ctrl->server_local)
2416 assuan_context_t ctx = ctrl->server_local->assuan_ctx;
2422 while ( (text = va_arg (arg_ptr, const char *)) )
2429 for ( ; *text && n < DIM (buf)-2; n++)
2433 err = assuan_write_status (ctx, keyword, buf);
2441 /* Print a help status line. TEXTLEN gives the length of the text
2442 from TEXT to be printed. The function splits text at LFs. */
2444 dirmngr_status_help (ctrl_t ctrl, const char *text)
2446 gpg_error_t err = 0;
2448 if (ctrl->server_local)
2450 assuan_context_t ctx = ctrl->server_local->assuan_ctx;
2458 for ( ; *text && *text != '\n' && n < DIM (buf)-2; n++)
2463 err = assuan_write_status (ctx, "#", buf);
2465 while (!err && *text);
2471 /* Send a tick progress indicator back. Fixme: This is only done for
2472 the currently active channel. */
2474 dirmngr_tick (ctrl_t ctrl)
2476 static time_t next_tick = 0;
2477 gpg_error_t err = 0;
2478 time_t now = time (NULL);
2482 next_tick = now + 1;
2484 else if ( now > next_tick )
2488 err = dirmngr_status (ctrl, "PROGRESS", "tick", "? 0 0", NULL);
2491 /* Take this as in indication for a cancel request. */
2492 err = gpg_error (GPG_ERR_CANCELED);
2497 next_tick = now + 1;