1 /* call-dirmngr.c - GPG operations to the Dirmngr.
2 * Copyright (C) 2011 Free Software Foundation, Inc.
3 * Copyright (C) 2015 g10 Code GmbH
5 * This file is part of GnuPG.
7 * GnuPG is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * GnuPG is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, see <http://www.gnu.org/licenses/>.
40 #include "keyserver.h"
41 #include "call-dirmngr.h"
44 /* Parameter structure used to gather status info. */
45 struct ks_status_parm_s
51 /* Parameter structure used with the KS_SEARCH command. */
52 struct ks_search_parm_s
54 gpg_error_t lasterr; /* Last error code. */
55 membuf_t saveddata; /* Buffer to build complete lines. */
56 char *helpbuf; /* NULL or malloced buffer. */
57 size_t helpbufsize; /* Allocated size of HELPBUF. */
58 gpg_error_t (*data_cb)(void*, int, char*); /* Callback. */
59 void *data_cb_value; /* First argument for DATA_CB. */
60 struct ks_status_parm_s *stparm; /* Link to the status parameter. */
64 /* Parameter structure used with the KS_GET command. */
71 /* Parameter structure used with the KS_PUT command. */
75 kbnode_t keyblock; /* The optional keyblock. */
76 const void *data; /* The key in OpenPGP binary format. */
77 size_t datalen; /* The length of DATA. */
81 /* Data used to associate an session with dirmngr contexts. We can't
82 use a simple one to one mapping because we sometimes need two
83 connections to the dirmngr; for example while doing a listing and
84 being in a data callback we may want to retrieve a key. The local
85 dirmngr data takes care of this. At the end of the session the
86 function dirmngr_deinit_session_data is called by gpg.c to cleanup
87 these resources. Note that gpg.h defines a typedef dirmngr_local_t
88 for this structure. */
89 struct dirmngr_local_s
91 /* Link to other contexts which are used simultaneously. */
92 struct dirmngr_local_s *next;
94 /* The active Assuan context. */
97 /* Flag set to true while an operation is running on CTX. */
103 /* Deinitialize all session data of dirmngr pertaining to CTRL. */
105 gpg_dirmngr_deinit_session_data (ctrl_t ctrl)
109 while ((dml = ctrl->dirmngr_local))
111 ctrl->dirmngr_local = dml->next;
113 log_error ("oops: trying to cleanup an active dirmngr context\n");
115 assuan_release (dml->ctx);
121 /* Try to connect to the Dirmngr via a socket or spawn it if possible.
122 Handle the server's initial greeting and set global options. */
124 create_context (ctrl_t ctrl, assuan_context_t *r_ctx)
127 assuan_context_t ctx;
130 err = start_new_dirmngr (&ctx,
131 GPG_ERR_SOURCE_DEFAULT,
134 opt.autostart, opt.verbose, DBG_IPC,
135 NULL /*gpg_status2*/, ctrl);
136 if (!opt.autostart && gpg_err_code (err) == GPG_ERR_NO_DIRMNGR)
143 log_info (_("no dirmngr running in this session\n"));
148 keyserver_spec_t ksi;
150 /* Tell the dirmngr that we want to collect audit event. */
151 /* err = assuan_transact (agent_ctx, "OPTION audit-events=1", */
152 /* NULL, NULL, NULL, NULL, NULL, NULL); */
154 /* Set all configured keyservers. We clear existing keyservers
155 so that any keyserver configured in GPG overrides keyservers
156 possibly still configured in Dirmngr for the session (Note
157 that the keyserver list of a session in Dirmngr survives a
159 for (ksi = opt.keyserver; !err && ksi; ksi = ksi->next)
163 line = xtryasprintf ("KEYSERVER%s %s",
164 ksi == opt.keyserver? " --clear":"", ksi->uri);
166 err = gpg_error_from_syserror ();
169 err = assuan_transact (ctx, line,
170 NULL, NULL, NULL, NULL, NULL, NULL);
177 assuan_release (ctx);
180 /* audit_log_ok (ctrl->audit, AUDIT_DIRMNGR_READY, err); */
188 /* Get a context for accessing dirmngr. If no context is available a
189 new one is created and - if required - dirmngr started. On success
190 an assuan context is stored at R_CTX. This context may only be
191 released by means of close_context. Note that NULL is stored at
194 open_context (ctrl_t ctrl, assuan_context_t *r_ctx)
202 for (dml = ctrl->dirmngr_local; dml && dml->is_active; dml = dml->next)
206 /* Found an inactive local session - return that. */
207 assert (!dml->is_active);
213 dml = xtrycalloc (1, sizeof *dml);
215 return gpg_error_from_syserror ();
216 err = create_context (ctrl, &dml->ctx);
222 /* To be on the nPth thread safe site we need to add it to a
223 list; this is far easier than to have a lock for this
224 function. It should not happen anyway but the code is free
225 because we need it for the is_active check above. */
226 dml->next = ctrl->dirmngr_local;
227 ctrl->dirmngr_local = dml;
232 /* Close the assuan context CTX or return it to a pool of unused
233 contexts. If CTX is NULL, the function does nothing. */
235 close_context (ctrl_t ctrl, assuan_context_t ctx)
242 for (dml = ctrl->dirmngr_local; dml; dml = dml->next)
247 log_fatal ("closing inactive dirmngr context %p\n", ctx);
252 log_fatal ("closing unknown dirmngr ctx %p\n", ctx);
257 /* Status callback for ks_get and ks_search. */
259 ks_status_cb (void *opaque, const char *line)
261 struct ks_status_parm_s *parm = opaque;
265 if ((s = has_leading_keyword (line, "SOURCE")))
269 parm->source = xtrystrdup (s);
271 err = gpg_error_from_syserror ();
280 /* Data callback for the KS_SEARCH command. */
282 ks_search_data_cb (void *opaque, const void *data, size_t datalen)
285 struct ks_search_parm_s *parm = opaque;
286 const char *line, *s;
287 size_t rawlen, linelen;
293 if (parm->stparm->source)
295 err = parm->data_cb (parm->data_cb_value, 1, parm->stparm->source);
301 /* Clear it so that we won't get back here unless the server
302 accidentally sends a second source status line. Note that
303 will not see all accidentally sent source lines because it
304 depends on whether data lines have been send in between. */
305 xfree (parm->stparm->source);
306 parm->stparm->source = NULL;
310 return 0; /* Ignore END commands. */
312 put_membuf (&parm->saveddata, data, datalen);
315 line = peek_membuf (&parm->saveddata, &rawlen);
318 parm->lasterr = gpg_error_from_syserror ();
319 return parm->lasterr; /* Tell the server about our problem. */
321 if ((s = memchr (line, '\n', rawlen)))
323 linelen = s - line; /* That is the length excluding the LF. */
324 if (linelen + 1 < sizeof fixedbuf)
326 /* We can use the static buffer. */
327 memcpy (fixedbuf, line, linelen);
328 fixedbuf[linelen] = 0;
329 if (linelen && fixedbuf[linelen-1] == '\r')
330 fixedbuf[linelen-1] = 0;
331 err = parm->data_cb (parm->data_cb_value, 0, fixedbuf);
335 if (linelen + 1 >= parm->helpbufsize)
337 xfree (parm->helpbuf);
338 parm->helpbufsize = linelen + 1 + 1024;
339 parm->helpbuf = xtrymalloc (parm->helpbufsize);
342 parm->lasterr = gpg_error_from_syserror ();
343 return parm->lasterr;
346 memcpy (parm->helpbuf, line, linelen);
347 parm->helpbuf[linelen] = 0;
348 if (linelen && parm->helpbuf[linelen-1] == '\r')
349 parm->helpbuf[linelen-1] = 0;
350 err = parm->data_cb (parm->data_cb_value, 0, parm->helpbuf);
356 clear_membuf (&parm->saveddata, linelen+1);
357 goto again; /* There might be another complete line. */
365 /* Run the KS_SEARCH command using the search string SEARCHSTR. All
366 data lines are passed to the CB function. That function is called
367 with CB_VALUE as its first argument, a 0 as second argument, and
368 the decoded data line as third argument. The callback function may
369 modify the data line and it is guaranteed that this data line is a
370 complete line with a terminating 0 character but without the
371 linefeed. NULL is passed to the callback to indicate EOF. */
373 gpg_dirmngr_ks_search (ctrl_t ctrl, const char *searchstr,
374 gpg_error_t (*cb)(void*, int, char *), void *cb_value)
377 assuan_context_t ctx;
378 struct ks_status_parm_s stparm;
379 struct ks_search_parm_s parm;
380 char line[ASSUAN_LINELENGTH];
382 err = open_context (ctrl, &ctx);
387 char *escsearchstr = percent_plus_escape (searchstr);
390 err = gpg_error_from_syserror ();
391 close_context (ctrl, ctx);
394 snprintf (line, sizeof line, "KS_SEARCH -- %s", escsearchstr);
395 xfree (escsearchstr);
398 memset (&stparm, 0, sizeof stparm);
399 memset (&parm, 0, sizeof parm);
400 init_membuf (&parm.saveddata, 1024);
402 parm.data_cb_value = cb_value;
403 parm.stparm = &stparm;
405 err = assuan_transact (ctx, line, ks_search_data_cb, &parm,
406 NULL, NULL, ks_status_cb, &stparm);
408 err = cb (cb_value, 0, NULL); /* Send EOF. */
410 xfree (get_membuf (&parm.saveddata, NULL));
411 xfree (parm.helpbuf);
412 xfree (stparm.source);
414 close_context (ctrl, ctx);
420 /* Data callback for the KS_GET and KS_FETCH commands. */
422 ks_get_data_cb (void *opaque, const void *data, size_t datalen)
425 struct ks_get_parm_s *parm = opaque;
429 return 0; /* Ignore END commands. */
431 if (es_write (parm->memfp, data, datalen, &nwritten))
432 err = gpg_error_from_syserror ();
438 /* Run the KS_GET command using the patterns in the array PATTERN. On
439 success an estream object is returned to retrieve the keys. On
440 error an error code is returned and NULL stored at R_FP.
442 The pattern may only use search specification which a keyserver can
443 use to retrieve keys. Because we know the format of the pattern we
444 don't need to escape the patterns before sending them to the
447 If R_SOURCE is not NULL the source of the data is stored as a
448 malloced string there. If a source is not known NULL is stored.
450 If there are too many patterns the function returns an error. That
451 could be fixed by issuing several search commands or by
452 implementing a different interface. However with long keyids we
453 are able to ask for (1000-10-1)/(2+8+1) = 90 keys at once. */
455 gpg_dirmngr_ks_get (ctrl_t ctrl, char **pattern,
456 estream_t *r_fp, char **r_source)
459 assuan_context_t ctx;
460 struct ks_status_parm_s stparm;
461 struct ks_get_parm_s parm;
467 memset (&stparm, 0, sizeof stparm);
468 memset (&parm, 0, sizeof parm);
474 err = open_context (ctrl, &ctx);
478 /* Lump all patterns into one string. */
479 init_membuf (&mb, 1024);
480 put_membuf_str (&mb, "KS_GET --");
481 for (idx=0; pattern[idx]; idx++)
483 put_membuf (&mb, " ", 1); /* Append Delimiter. */
484 put_membuf_str (&mb, pattern[idx]);
486 put_membuf (&mb, "", 1); /* Append Nul. */
487 line = get_membuf (&mb, &linelen);
490 err = gpg_error_from_syserror ();
493 if (linelen + 2 >= ASSUAN_LINELENGTH)
495 err = gpg_error (GPG_ERR_TOO_MANY);
499 parm.memfp = es_fopenmem (0, "rwb");
502 err = gpg_error_from_syserror ();
505 err = assuan_transact (ctx, line, ks_get_data_cb, &parm,
506 NULL, NULL, ks_status_cb, &stparm);
510 es_rewind (parm.memfp);
516 *r_source = stparm.source;
517 stparm.source = NULL;
521 es_fclose (parm.memfp);
522 xfree (stparm.source);
524 close_context (ctrl, ctx);
529 /* Run the KS_FETCH and pass URL as argument. On success an estream
530 object is returned to retrieve the keys. On error an error code is
531 returned and NULL stored at R_FP.
533 The url is expected to point to a small set of keys; in many cases
534 only to one key. However, schemes like finger may return several
535 keys. Note that the configured keyservers are ignored by the
538 gpg_dirmngr_ks_fetch (ctrl_t ctrl, const char *url, estream_t *r_fp)
541 assuan_context_t ctx;
542 struct ks_get_parm_s parm;
545 memset (&parm, 0, sizeof parm);
549 err = open_context (ctrl, &ctx);
553 line = strconcat ("KS_FETCH -- ", url, NULL);
556 err = gpg_error_from_syserror ();
559 if (strlen (line) + 2 >= ASSUAN_LINELENGTH)
561 err = gpg_error (GPG_ERR_TOO_LARGE);
565 parm.memfp = es_fopenmem (0, "rwb");
568 err = gpg_error_from_syserror ();
571 err = assuan_transact (ctx, line, ks_get_data_cb, &parm,
572 NULL, NULL, NULL, NULL);
576 es_rewind (parm.memfp);
581 es_fclose (parm.memfp);
583 close_context (ctrl, ctx);
590 record_output (estream_t output,
592 const char *validity,
593 /* The public key length or -1. */
595 /* The public key algo or -1. */
597 /* 2 ulongs or NULL. */
599 /* The creation / expiration date or 0. */
604 const char *type_str = NULL;
605 char *pub_key_length_str = NULL;
606 char *pub_key_algo_str = NULL;
607 char *keyid_str = NULL;
608 char *creation_date_str = NULL;
609 char *expiration_date_str = NULL;
610 char *userid_escaped = NULL;
617 case PKT_PUBLIC_SUBKEY:
627 assert (! "Unhandled type.");
630 if (pub_key_length > 0)
631 pub_key_length_str = xasprintf ("%d", pub_key_length);
633 if (pub_key_algo != -1)
634 pub_key_algo_str = xasprintf ("%d", pub_key_algo);
637 keyid_str = xasprintf ("%08lX%08lX", (ulong) keyid[0], (ulong) keyid[1]);
640 creation_date_str = xstrdup (colon_strtime (creation_date));
643 expiration_date_str = xstrdup (colon_strtime (expiration_date));
645 /* Quote ':', '%', and any 8-bit characters. */
651 int len = strlen (userid);
652 /* A 100k character limit on the uid should be way more than
654 if (len > 100 * 1024)
657 /* The minimum amount of space that we need. */
658 userid_escaped = xmalloc (len * 3 + 1);
660 for (r = 0; r < len; r++)
662 if (userid[r] == ':' || userid[r]== '%' || (userid[r] & 0x80))
664 sprintf (&userid_escaped[w], "%%%02X", (byte) userid[r]);
668 userid_escaped[w ++] = userid[r];
670 userid_escaped[w] = '\0';
673 es_fprintf (output, "%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s\n",
676 pub_key_length_str ?: "",
677 pub_key_algo_str ?: "",
679 creation_date_str ?: "",
680 expiration_date_str ?: "",
681 "" /* Certificate S/N */,
682 "" /* Ownertrust. */,
683 userid_escaped ?: "",
684 "" /* Signature class. */,
685 "" /* Key capabilities. */,
686 "" /* Issuer certificate fingerprint. */,
687 "" /* Flag field. */,
688 "" /* S/N of a token. */,
690 "" /* Curve name. */);
692 xfree (userid_escaped);
693 xfree (expiration_date_str);
694 xfree (creation_date_str);
696 xfree (pub_key_algo_str);
697 xfree (pub_key_length_str);
700 /* Handle the KS_PUT inquiries. */
702 ks_put_inq_cb (void *opaque, const char *line)
704 struct ks_put_parm_s *parm = opaque;
707 if (has_leading_keyword (line, "KEYBLOCK"))
710 err = assuan_send_data (parm->ctx, parm->data, parm->datalen);
712 else if (has_leading_keyword (line, "KEYBLOCK_INFO"))
717 /* Parse the keyblock and send info lines back to the server. */
718 fp = es_fopenmem (0, "rw,samethread");
720 err = gpg_error_from_syserror ();
722 /* Note: the output format for the INFO block follows the colon
723 format as described in doc/DETAILS. We don't actually reuse
724 the functionality from g10/keylist.c to produce the output,
725 because we don't need all of it and some of it is quite
726 expensive to generate.
728 The fields are (the starred fields are the ones we need):
730 * Field 1 - Type of record
732 * Field 3 - Key length
733 * Field 4 - Public key algorithm
735 * Field 6 - Creation date
736 * Field 7 - Expiration date
737 Field 8 - Certificate S/N, UID hash, trust signature info
740 Field 11 - Signature class
741 Field 12 - Key capabilities
742 Field 13 - Issuer certificate fingerprint or other info
743 Field 14 - Flag field
744 Field 15 - S/N of a token
745 Field 16 - Hash algorithm
746 Field 17 - Curve name
748 for (node = parm->keyblock; !err && node; node=node->next)
750 switch (node->pkt->pkttype)
753 case PKT_PUBLIC_SUBKEY:
755 PKT_public_key *pk = node->pkt->pkt.public_key;
761 if (pk->flags.revoked)
762 validity[i ++] = 'r';
764 validity[i ++] = 'e';
767 keyid_from_pk (pk, NULL);
769 record_output (fp, node->pkt->pkttype, validity,
770 nbits_from_pk (pk), pk->pubkey_algo,
771 pk->keyid, pk->timestamp, pk->expiredate,
778 PKT_user_id *uid = node->pkt->pkt.user_id;
780 if (!uid->attrib_data)
787 validity[i ++] = 'r';
789 validity[i ++] = 'e';
792 record_output (fp, node->pkt->pkttype, validity,
794 uid->created, uid->expiredate,
800 /* This bit is really for the benefit of people who
801 store their keys in LDAP servers. It makes it easy
802 to do queries for things like "all keys signed by
806 PKT_signature *sig = node->pkt->pkt.signature;
808 if (IS_UID_SIG (sig))
809 record_output (fp, node->pkt->pkttype, NULL,
811 sig->timestamp, sig->expiredate, NULL);
818 /* Given that the last operation was an es_fprintf we should
819 get the correct ERRNO if ferror indicates an error. */
821 err = gpg_error_from_syserror ();
824 /* Without an error and if we have an keyblock at all, send the
826 if (!err && parm->keyblock)
833 while (!(rc=es_read (fp, buffer, sizeof buffer, &nread)) && nread)
835 err = assuan_send_data (parm->ctx, buffer, nread);
840 err = gpg_error_from_syserror ();
845 return gpg_error (GPG_ERR_ASS_UNKNOWN_INQUIRE);
851 /* Send a key to the configured server. {DATA,DATLEN} contains the
852 key in OpenPGP binary transport format. If KEYBLOCK is not NULL it
853 has the internal representaion of that key; this is for example
854 used to convey meta data to LDAP keyservers. */
856 gpg_dirmngr_ks_put (ctrl_t ctrl, void *data, size_t datalen, kbnode_t keyblock)
859 assuan_context_t ctx;
860 struct ks_put_parm_s parm;
862 memset (&parm, 0, sizeof parm);
864 /* We are going to parse the keyblock, thus we better make sure the
865 all information is readily available. */
867 merge_keys_and_selfsig (keyblock);
869 err = open_context (ctrl, &ctx);
874 parm.keyblock = keyblock;
876 parm.datalen = datalen;
878 err = assuan_transact (ctx, "KS_PUT", NULL, NULL,
879 ks_put_inq_cb, &parm, NULL, NULL);
881 close_context (ctrl, ctx);