1 /* call-agent.c - Divert GPG operations to the agent.
2  * Copyright (C) 2001-2003, 2006-2011, 2013 Free Software Foundation, Inc.
3  * Copyright (C) 2013-2015  Werner Koch
4  * Copyright (C) 2020       g10 Code GmbH
5  *
6  * This file is part of GnuPG.
7  *
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.
12  *
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.
17  *
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/>.
20  */
21 
22 #include <config.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <errno.h>
27 #include <unistd.h>
28 #include <time.h>
29 #ifdef HAVE_LOCALE_H
30 #include <locale.h>
31 #endif
32 
33 #include "gpg.h"
34 #include <assuan.h>
35 #include "../common/util.h"
36 #include "../common/membuf.h"
37 #include "options.h"
38 #include "../common/i18n.h"
39 #include "../common/asshelp.h"
40 #include "../common/sysutils.h"
41 #include "call-agent.h"
42 #include "../common/status.h"
43 #include "../common/shareddefs.h"
44 #include "../common/host2net.h"
45 #include "../common/ttyio.h"
46 
47 #define CONTROL_D ('D' - 'A' + 1)
48 
49 
50 static assuan_context_t agent_ctx = NULL;
51 static int did_early_card_test;
52 
53 struct confirm_parm_s
54 {
55   char *desc;
56   char *ok;
57   char *notok;
58 };
59 
60 struct default_inq_parm_s
61 {
62   ctrl_t ctrl;
63   assuan_context_t ctx;
64   struct {
65     u32 *keyid;
66     u32 *mainkeyid;
67     int pubkey_algo;
68   } keyinfo;
69   struct confirm_parm_s *confirm;
70 };
71 
72 struct cipher_parm_s
73 {
74   struct default_inq_parm_s *dflt;
75   assuan_context_t ctx;
76   unsigned char *ciphertext;
77   size_t ciphertextlen;
78 };
79 
80 struct writecert_parm_s
81 {
82   struct default_inq_parm_s *dflt;
83   const unsigned char *certdata;
84   size_t certdatalen;
85 };
86 
87 struct writekey_parm_s
88 {
89   struct default_inq_parm_s *dflt;
90   const unsigned char *keydata;
91   size_t keydatalen;
92 };
93 
94 struct genkey_parm_s
95 {
96   struct default_inq_parm_s *dflt;
97   const char *keyparms;
98   const char *passphrase;
99 };
100 
101 struct import_key_parm_s
102 {
103   struct default_inq_parm_s *dflt;
104   const void *key;
105   size_t keylen;
106 };
107 
108 
109 struct cache_nonce_parm_s
110 {
111   char **cache_nonce_addr;
112   char **passwd_nonce_addr;
113 };
114 
115 
116 static gpg_error_t learn_status_cb (void *opaque, const char *line);
117 
118 
119 
120 /* If RC is not 0, write an appropriate status message. */
121 static void
status_sc_op_failure(int rc)122 status_sc_op_failure (int rc)
123 {
124   switch (gpg_err_code (rc))
125     {
126     case 0:
127       break;
128     case GPG_ERR_CANCELED:
129     case GPG_ERR_FULLY_CANCELED:
130       write_status_text (STATUS_SC_OP_FAILURE, "1");
131       break;
132     case GPG_ERR_BAD_PIN:
133       write_status_text (STATUS_SC_OP_FAILURE, "2");
134       break;
135     default:
136       write_status (STATUS_SC_OP_FAILURE);
137       break;
138     }
139 }
140 
141 
142 /* This is the default inquiry callback.  It mainly handles the
143    Pinentry notifications.  */
144 static gpg_error_t
default_inq_cb(void * opaque,const char * line)145 default_inq_cb (void *opaque, const char *line)
146 {
147   gpg_error_t err = 0;
148   struct default_inq_parm_s *parm = opaque;
149   const char *s;
150 
151   if (has_leading_keyword (line, "PINENTRY_LAUNCHED"))
152     {
153       err = gpg_proxy_pinentry_notify (parm->ctrl, line);
154       if (err)
155         log_error (_("failed to proxy %s inquiry to client\n"),
156                    "PINENTRY_LAUNCHED");
157       /* We do not pass errors to avoid breaking other code.  */
158     }
159   else if ((has_leading_keyword (line, "PASSPHRASE")
160             || has_leading_keyword (line, "NEW_PASSPHRASE"))
161            && opt.pinentry_mode == PINENTRY_MODE_LOOPBACK)
162     {
163       if (have_static_passphrase ())
164         {
165           s = get_static_passphrase ();
166           err = assuan_send_data (parm->ctx, s, strlen (s));
167         }
168       else
169         {
170           char *pw;
171           char buf[32];
172 
173           if (parm->keyinfo.keyid)
174             emit_status_need_passphrase (parm->ctrl,
175                                          parm->keyinfo.keyid,
176                                          parm->keyinfo.mainkeyid,
177                                          parm->keyinfo.pubkey_algo);
178 
179           snprintf (buf, sizeof (buf), "%u", 100);
180           write_status_text (STATUS_INQUIRE_MAXLEN, buf);
181           pw = cpr_get_hidden ("passphrase.enter", _("Enter passphrase: "));
182           cpr_kill_prompt ();
183           if (*pw == CONTROL_D && !pw[1])
184             err = gpg_error (GPG_ERR_CANCELED);
185           else
186             err = assuan_send_data (parm->ctx, pw, strlen (pw));
187           xfree (pw);
188         }
189     }
190   else if ((s = has_leading_keyword (line, "CONFIRM"))
191            && opt.pinentry_mode == PINENTRY_MODE_LOOPBACK
192            && parm->confirm)
193     {
194       int ask = atoi (s);
195       int yes;
196 
197       if (ask)
198         {
199           yes = cpr_get_answer_is_yes (NULL, parm->confirm->desc);
200           if (yes)
201             err = assuan_send_data (parm->ctx, NULL, 0);
202           else
203             err = gpg_error (GPG_ERR_NOT_CONFIRMED);
204         }
205       else
206         {
207           tty_printf ("%s", parm->confirm->desc);
208           err = assuan_send_data (parm->ctx, NULL, 0);
209         }
210     }
211   else
212     log_debug ("ignoring gpg-agent inquiry '%s'\n", line);
213 
214   return err;
215 }
216 
217 
218 /* Print a warning if the server's version number is less than our
219    version number.  Returns an error code on a connection problem.  */
220 static gpg_error_t
warn_version_mismatch(assuan_context_t ctx,const char * servername,int mode)221 warn_version_mismatch (assuan_context_t ctx, const char *servername, int mode)
222 {
223   return warn_server_version_mismatch (ctx, servername, mode,
224                                        write_status_strings2, NULL,
225                                        !opt.quiet);
226 }
227 
228 
229 #define FLAG_FOR_CARD_SUPPRESS_ERRORS 2
230 
231 /* Try to connect to the agent via socket or fork it off and work by
232    pipes.  Handle the server's initial greeting */
233 static int
start_agent(ctrl_t ctrl,int flag_for_card)234 start_agent (ctrl_t ctrl, int flag_for_card)
235 {
236   int rc;
237 
238   (void)ctrl;  /* Not yet used.  */
239 
240   /* Fixme: We need a context for each thread or serialize the access
241      to the agent. */
242   if (agent_ctx)
243     rc = 0;
244   else
245     {
246       rc = start_new_gpg_agent (&agent_ctx,
247                                 GPG_ERR_SOURCE_DEFAULT,
248                                 opt.agent_program,
249                                 opt.lc_ctype, opt.lc_messages,
250                                 opt.session_env,
251                                 opt.autostart, opt.verbose, DBG_IPC,
252                                 NULL, NULL);
253       if (!opt.autostart && gpg_err_code (rc) == GPG_ERR_NO_AGENT)
254         {
255           static int shown;
256 
257           if (!shown)
258             {
259               shown = 1;
260               log_info (_("no gpg-agent running in this session\n"));
261             }
262         }
263       else if (!rc
264                && !(rc = warn_version_mismatch (agent_ctx, GPG_AGENT_NAME, 0)))
265         {
266           /* Tell the agent that we support Pinentry notifications.
267              No error checking so that it will work also with older
268              agents.  */
269           assuan_transact (agent_ctx, "OPTION allow-pinentry-notify",
270                            NULL, NULL, NULL, NULL, NULL, NULL);
271           /* Tell the agent about what version we are aware.  This is
272              here used to indirectly enable GPG_ERR_FULLY_CANCELED.  */
273           assuan_transact (agent_ctx, "OPTION agent-awareness=2.1.0",
274                            NULL, NULL, NULL, NULL, NULL, NULL);
275           /* Pass on the pinentry mode.  */
276           if (opt.pinentry_mode)
277             {
278               char *tmp = xasprintf ("OPTION pinentry-mode=%s",
279                                      str_pinentry_mode (opt.pinentry_mode));
280               rc = assuan_transact (agent_ctx, tmp,
281                                NULL, NULL, NULL, NULL, NULL, NULL);
282               xfree (tmp);
283               if (rc)
284                 {
285                   log_error ("setting pinentry mode '%s' failed: %s\n",
286                              str_pinentry_mode (opt.pinentry_mode),
287                              gpg_strerror (rc));
288                   write_status_error ("set_pinentry_mode", rc);
289                 }
290             }
291 
292           /* Pass on the request origin.  */
293           if (opt.request_origin)
294             {
295               char *tmp = xasprintf ("OPTION pretend-request-origin=%s",
296                                      str_request_origin (opt.request_origin));
297               rc = assuan_transact (agent_ctx, tmp,
298                                NULL, NULL, NULL, NULL, NULL, NULL);
299               xfree (tmp);
300               if (rc)
301                 {
302                   log_error ("setting request origin '%s' failed: %s\n",
303                              str_request_origin (opt.request_origin),
304                              gpg_strerror (rc));
305                   write_status_error ("set_request_origin", rc);
306                 }
307             }
308 
309           /* In DE_VS mode under Windows we require that the JENT RNG
310            * is active.  */
311 #ifdef HAVE_W32_SYSTEM
312           if (!rc && opt.compliance == CO_DE_VS)
313             {
314               if (assuan_transact (agent_ctx, "GETINFO jent_active",
315                                    NULL, NULL, NULL, NULL, NULL, NULL))
316                 {
317                   rc = gpg_error (GPG_ERR_FORBIDDEN);
318                   log_error (_("%s is not compliant with %s mode\n"),
319                              GPG_AGENT_NAME,
320                              gnupg_compliance_option_string (opt.compliance));
321                   write_status_error ("random-compliance", rc);
322                 }
323             }
324 #endif /*HAVE_W32_SYSTEM*/
325 
326         }
327     }
328 
329   if (!rc && flag_for_card && !did_early_card_test)
330     {
331       /* Request the serial number of the card for an early test.  */
332       struct agent_card_info_s info;
333 
334       memset (&info, 0, sizeof info);
335 
336       if (!(flag_for_card & FLAG_FOR_CARD_SUPPRESS_ERRORS))
337         rc = warn_version_mismatch (agent_ctx, SCDAEMON_NAME, 2);
338       if (!rc)
339         rc = assuan_transact (agent_ctx,
340                               opt.flags.use_only_openpgp_card?
341                               "SCD SERIALNO openpgp" : "SCD SERIALNO",
342                               NULL, NULL, NULL, NULL,
343                               learn_status_cb, &info);
344       if (rc && !(flag_for_card & FLAG_FOR_CARD_SUPPRESS_ERRORS))
345         {
346           switch (gpg_err_code (rc))
347             {
348             case GPG_ERR_NOT_SUPPORTED:
349             case GPG_ERR_NO_SCDAEMON:
350               write_status_text (STATUS_CARDCTRL, "6");
351               break;
352             case GPG_ERR_OBJ_TERM_STATE:
353               write_status_text (STATUS_CARDCTRL, "7");
354               break;
355             default:
356               write_status_text (STATUS_CARDCTRL, "4");
357               log_info ("selecting card failed: %s\n", gpg_strerror (rc));
358               break;
359             }
360         }
361 
362       if (!rc && is_status_enabled () && info.serialno)
363         {
364           char *buf;
365 
366           buf = xasprintf ("3 %s", info.serialno);
367           write_status_text (STATUS_CARDCTRL, buf);
368           xfree (buf);
369         }
370 
371       agent_release_card_info (&info);
372 
373       if (!rc)
374         did_early_card_test = 1;
375     }
376 
377 
378   return rc;
379 }
380 
381 
382 /* Return a new malloced string by unescaping the string S.  Escaping
383    is percent escaping and '+'/space mapping.  A binary nul will
384    silently be replaced by a 0xFF.  Function returns NULL to indicate
385    an out of memory status. */
386 static char *
unescape_status_string(const unsigned char * s)387 unescape_status_string (const unsigned char *s)
388 {
389   return percent_plus_unescape (s, 0xff);
390 }
391 
392 
393 /* Take a 20 or 32 byte hexencoded string and put it into the provided
394  * FPRLEN byte long buffer FPR in binary format.  Returns the actual
395  * used length of the FPR buffer or 0 on error.  */
396 static unsigned int
unhexify_fpr(const char * hexstr,unsigned char * fpr,unsigned int fprlen)397 unhexify_fpr (const char *hexstr, unsigned char *fpr, unsigned int fprlen)
398 {
399   const char *s;
400   int n;
401 
402   for (s=hexstr, n=0; hexdigitp (s); s++, n++)
403     ;
404   if ((*s && *s != ' ') || !(n == 40 || n == 64))
405     return 0; /* no fingerprint (invalid or wrong length). */
406   for (s=hexstr, n=0; *s && n < fprlen; s += 2, n++)
407     fpr[n] = xtoi_2 (s);
408 
409   return (n == 20 || n == 32)? n : 0;
410 }
411 
412 /* Take the serial number from LINE and return it verbatim in a newly
413    allocated string.  We make sure that only hex characters are
414    returned. */
415 static char *
store_serialno(const char * line)416 store_serialno (const char *line)
417 {
418   const char *s;
419   char *p;
420 
421   for (s=line; hexdigitp (s); s++)
422     ;
423   p = xtrymalloc (s + 1 - line);
424   if (p)
425     {
426       memcpy (p, line, s-line);
427       p[s-line] = 0;
428     }
429   return p;
430 }
431 
432 
433 
434 /* This is a dummy data line callback.  */
435 static gpg_error_t
dummy_data_cb(void * opaque,const void * buffer,size_t length)436 dummy_data_cb (void *opaque, const void *buffer, size_t length)
437 {
438   (void)opaque;
439   (void)buffer;
440   (void)length;
441   return 0;
442 }
443 
444 /* A simple callback used to return the serialnumber of a card.  */
445 static gpg_error_t
get_serialno_cb(void * opaque,const char * line)446 get_serialno_cb (void *opaque, const char *line)
447 {
448   char **serialno = opaque;
449   const char *keyword = line;
450   const char *s;
451   int keywordlen, n;
452 
453   for (keywordlen=0; *line && !spacep (line); line++, keywordlen++)
454     ;
455   while (spacep (line))
456     line++;
457 
458   if (keywordlen == 8 && !memcmp (keyword, "SERIALNO", keywordlen))
459     {
460       if (*serialno)
461         return gpg_error (GPG_ERR_CONFLICT); /* Unexpected status line. */
462       for (n=0,s=line; hexdigitp (s); s++, n++)
463         ;
464       if (!n || (n&1)|| !(spacep (s) || !*s) )
465         return gpg_error (GPG_ERR_ASS_PARAMETER);
466       *serialno = xtrymalloc (n+1);
467       if (!*serialno)
468         return out_of_core ();
469       memcpy (*serialno, line, n);
470       (*serialno)[n] = 0;
471     }
472 
473   return 0;
474 }
475 
476 
477 
478 /* Release the card info structure INFO. */
479 void
agent_release_card_info(struct agent_card_info_s * info)480 agent_release_card_info (struct agent_card_info_s *info)
481 {
482   int i;
483 
484   if (!info)
485     return;
486 
487   xfree (info->reader); info->reader = NULL;
488   xfree (info->manufacturer_name); info->manufacturer_name = NULL;
489   xfree (info->serialno); info->serialno = NULL;
490   xfree (info->apptype); info->apptype = NULL;
491   xfree (info->disp_name); info->disp_name = NULL;
492   xfree (info->disp_lang); info->disp_lang = NULL;
493   xfree (info->pubkey_url); info->pubkey_url = NULL;
494   xfree (info->login_data); info->login_data = NULL;
495   info->cafpr1len = info->cafpr2len = info->cafpr3len = 0;
496   info->fpr1len = info->fpr2len = info->fpr3len = 0;
497   for (i=0; i < DIM(info->private_do); i++)
498     {
499       xfree (info->private_do[i]);
500       info->private_do[i] = NULL;
501     }
502   for (i=0; i < DIM(info->supported_keyalgo); i++)
503     {
504       free_strlist (info->supported_keyalgo[i]);
505       info->supported_keyalgo[i] = NULL;
506     }
507 }
508 
509 
510 static gpg_error_t
learn_status_cb(void * opaque,const char * line)511 learn_status_cb (void *opaque, const char *line)
512 {
513   struct agent_card_info_s *parm = opaque;
514   const char *keyword = line;
515   int keywordlen;
516   int i;
517   char *endp;
518 
519   for (keywordlen=0; *line && !spacep (line); line++, keywordlen++)
520     ;
521   while (spacep (line))
522     line++;
523 
524   if (keywordlen == 6 && !memcmp (keyword, "READER", keywordlen))
525     {
526       xfree (parm->reader);
527       parm->reader = unescape_status_string (line);
528     }
529   else if (keywordlen == 8 && !memcmp (keyword, "SERIALNO", keywordlen))
530     {
531       xfree (parm->serialno);
532       parm->serialno = store_serialno (line);
533       parm->is_v2 = (strlen (parm->serialno) >= 16
534                      && (xtoi_2 (parm->serialno+12) == 0 /* Yubikey */
535                          || xtoi_2 (parm->serialno+12) >= 2));
536     }
537   else if (keywordlen == 7 && !memcmp (keyword, "APPTYPE", keywordlen))
538     {
539       xfree (parm->apptype);
540       parm->apptype = unescape_status_string (line);
541     }
542   else if (keywordlen == 9 && !memcmp (keyword, "DISP-NAME", keywordlen))
543     {
544       xfree (parm->disp_name);
545       parm->disp_name = unescape_status_string (line);
546     }
547   else if (keywordlen == 9 && !memcmp (keyword, "DISP-LANG", keywordlen))
548     {
549       xfree (parm->disp_lang);
550       parm->disp_lang = unescape_status_string (line);
551     }
552   else if (keywordlen == 8 && !memcmp (keyword, "DISP-SEX", keywordlen))
553     {
554       parm->disp_sex = *line == '1'? 1 : *line == '2' ? 2: 0;
555     }
556   else if (keywordlen == 10 && !memcmp (keyword, "PUBKEY-URL", keywordlen))
557     {
558       xfree (parm->pubkey_url);
559       parm->pubkey_url = unescape_status_string (line);
560     }
561   else if (keywordlen == 10 && !memcmp (keyword, "LOGIN-DATA", keywordlen))
562     {
563       xfree (parm->login_data);
564       parm->login_data = unescape_status_string (line);
565     }
566   else if (keywordlen == 11 && !memcmp (keyword, "SIG-COUNTER", keywordlen))
567     {
568       parm->sig_counter = strtoul (line, NULL, 0);
569     }
570   else if (keywordlen == 10 && !memcmp (keyword, "CHV-STATUS", keywordlen))
571     {
572       char *p, *buf;
573 
574       buf = p = unescape_status_string (line);
575       if (buf)
576         {
577           while (spacep (p))
578             p++;
579           parm->chv1_cached = atoi (p);
580           while (*p && !spacep (p))
581             p++;
582           while (spacep (p))
583             p++;
584           for (i=0; *p && i < 3; i++)
585             {
586               parm->chvmaxlen[i] = atoi (p);
587               while (*p && !spacep (p))
588                 p++;
589               while (spacep (p))
590                 p++;
591             }
592           for (i=0; *p && i < 3; i++)
593             {
594               parm->chvretry[i] = atoi (p);
595               while (*p && !spacep (p))
596                 p++;
597               while (spacep (p))
598                 p++;
599             }
600           xfree (buf);
601         }
602     }
603   else if (keywordlen == 6 && !memcmp (keyword, "EXTCAP", keywordlen))
604     {
605       char *p, *p2, *buf;
606       int abool;
607 
608       buf = p = unescape_status_string (line);
609       if (buf)
610         {
611           for (p = strtok (buf, " "); p; p = strtok (NULL, " "))
612             {
613               p2 = strchr (p, '=');
614               if (p2)
615                 {
616                   *p2++ = 0;
617                   abool = (*p2 == '1');
618                   if (!strcmp (p, "ki"))
619                     parm->extcap.ki = abool;
620                   else if (!strcmp (p, "aac"))
621                     parm->extcap.aac = abool;
622                   else if (!strcmp (p, "bt"))
623                     parm->extcap.bt = abool;
624                   else if (!strcmp (p, "kdf"))
625                     parm->extcap.kdf = abool;
626                   else if (!strcmp (p, "si"))
627                     parm->status_indicator = strtoul (p2, NULL, 10);
628                 }
629             }
630           xfree (buf);
631         }
632     }
633   else if (keywordlen == 7 && !memcmp (keyword, "KEY-FPR", keywordlen))
634     {
635       int no = atoi (line);
636       while (*line && !spacep (line))
637         line++;
638       while (spacep (line))
639         line++;
640       if (no == 1)
641         parm->fpr1len = unhexify_fpr (line, parm->fpr1, sizeof parm->fpr1);
642       else if (no == 2)
643         parm->fpr2len = unhexify_fpr (line, parm->fpr2, sizeof parm->fpr2);
644       else if (no == 3)
645         parm->fpr3len = unhexify_fpr (line, parm->fpr3, sizeof parm->fpr3);
646     }
647   else if (keywordlen == 8 && !memcmp (keyword, "KEY-TIME", keywordlen))
648     {
649       int no = atoi (line);
650       while (* line && !spacep (line))
651         line++;
652       while (spacep (line))
653         line++;
654       if (no == 1)
655         parm->fpr1time = strtoul (line, NULL, 10);
656       else if (no == 2)
657         parm->fpr2time = strtoul (line, NULL, 10);
658       else if (no == 3)
659         parm->fpr3time = strtoul (line, NULL, 10);
660     }
661   else if (keywordlen == 11 && !memcmp (keyword, "KEYPAIRINFO", keywordlen))
662     {
663       const char *hexgrp = line;
664       int no;
665 
666       while (*line && !spacep (line))
667         line++;
668       while (spacep (line))
669         line++;
670       if (strncmp (line, "OPENPGP.", 8))
671         ;
672       else if ((no = atoi (line+8)) == 1)
673         unhexify_fpr (hexgrp, parm->grp1, sizeof parm->grp1);
674       else if (no == 2)
675         unhexify_fpr (hexgrp, parm->grp2, sizeof parm->grp2);
676       else if (no == 3)
677         unhexify_fpr (hexgrp, parm->grp3, sizeof parm->grp3);
678     }
679   else if (keywordlen == 6 && !memcmp (keyword, "CA-FPR", keywordlen))
680     {
681       int no = atoi (line);
682       while (*line && !spacep (line))
683         line++;
684       while (spacep (line))
685         line++;
686       if (no == 1)
687         parm->cafpr1len = unhexify_fpr (line, parm->cafpr1,sizeof parm->cafpr1);
688       else if (no == 2)
689         parm->cafpr2len = unhexify_fpr (line, parm->cafpr2,sizeof parm->cafpr2);
690       else if (no == 3)
691         parm->cafpr3len = unhexify_fpr (line, parm->cafpr3,sizeof parm->cafpr3);
692     }
693   else if (keywordlen == 8 && !memcmp (keyword, "KEY-ATTR", keywordlen))
694     {
695       int keyno = 0;
696       int algo = PUBKEY_ALGO_RSA;
697       int n = 0;
698 
699       sscanf (line, "%d %d %n", &keyno, &algo, &n);
700       keyno--;
701       if (keyno < 0 || keyno >= DIM (parm->key_attr))
702         return 0;
703 
704       parm->key_attr[keyno].algo = algo;
705       if (algo == PUBKEY_ALGO_RSA)
706         parm->key_attr[keyno].nbits = strtoul (line+n+3, NULL, 10);
707       else if (algo == PUBKEY_ALGO_ECDH || algo == PUBKEY_ALGO_ECDSA
708                || algo == PUBKEY_ALGO_EDDSA)
709         parm->key_attr[keyno].curve = openpgp_is_curve_supported (line + n,
710                                                                   NULL, NULL);
711     }
712   else if (keywordlen == 12 && !memcmp (keyword, "PRIVATE-DO-", 11)
713            && strchr("1234", keyword[11]))
714     {
715       int no = keyword[11] - '1';
716       log_assert (no >= 0 && no <= 3);
717       xfree (parm->private_do[no]);
718       parm->private_do[no] = unescape_status_string (line);
719     }
720   else if (keywordlen == 12 && !memcmp (keyword, "MANUFACTURER", 12))
721     {
722       xfree (parm->manufacturer_name);
723       parm->manufacturer_name = NULL;
724       parm->manufacturer_id = strtoul (line, &endp, 0);
725       while (endp && spacep (endp))
726         endp++;
727       if (endp && *endp)
728         parm->manufacturer_name = xstrdup (endp);
729     }
730   else if (keywordlen == 3 && !memcmp (keyword, "KDF", 3))
731     {
732       unsigned char *data = unescape_status_string (line);
733 
734       if (data[2] != 0x03)
735         parm->kdf_do_enabled = 0;
736       else if (data[22] != 0x85)
737         parm->kdf_do_enabled = 1;
738       else
739         parm->kdf_do_enabled = 2;
740       xfree (data);
741     }
742   else if (keywordlen == 5 && !memcmp (keyword, "UIF-", 4)
743            && strchr("123", keyword[4]))
744     {
745       unsigned char *data;
746       int no = keyword[4] - '1';
747 
748       log_assert (no >= 0 && no <= 2);
749       data = unescape_status_string (line);
750       parm->uif[no] = (data[0] != 0xff);
751       xfree (data);
752     }
753   else if (keywordlen == 13 && !memcmp (keyword, "KEY-ATTR-INFO", 13))
754     {
755       if (!strncmp (line, "OPENPGP.", 8))
756         {
757           int no;
758 
759           line += 8;
760           no = atoi (line);
761           if (no >= 1 && no <= 3)
762             {
763               no--;
764               line++;
765               while (spacep (line))
766                 line++;
767               append_to_strlist (&parm->supported_keyalgo[no], xstrdup (line));
768             }
769         }
770         /* Skip when it's not "OPENPGP.[123]".  */
771     }
772 
773   return 0;
774 }
775 
776 
777 /* Call the scdaemon to learn about a smartcard.  Note that in
778  * contradiction to the function's name, gpg-agent's LEARN command is
779  * used and not the low-level "SCD LEARN".
780  * Used by:
781  *  card-util.c
782  *  keyedit_menu
783  *  card_store_key_with_backup  (Woth force to remove secret key data)
784  */
785 int
agent_scd_learn(struct agent_card_info_s * info,int force)786 agent_scd_learn (struct agent_card_info_s *info, int force)
787 {
788   int rc;
789   struct default_inq_parm_s parm;
790   struct agent_card_info_s dummyinfo;
791 
792   if (!info)
793     info = &dummyinfo;
794   memset (info, 0, sizeof *info);
795   memset (&parm, 0, sizeof parm);
796 
797   rc = start_agent (NULL, 1);
798   if (rc)
799     return rc;
800 
801   parm.ctx = agent_ctx;
802   rc = assuan_transact (agent_ctx,
803                         force ? "LEARN --sendinfo --force" : "LEARN --sendinfo",
804                         dummy_data_cb, NULL, default_inq_cb, &parm,
805                         learn_status_cb, info);
806   /* Also try to get the key attributes.  */
807   if (!rc)
808     agent_scd_getattr ("KEY-ATTR", info);
809 
810   if (info == &dummyinfo)
811     agent_release_card_info (info);
812 
813   return rc;
814 }
815 
816 
817 
818 struct keypairinfo_cb_parm_s
819 {
820   keypair_info_t kpinfo;
821   keypair_info_t *kpinfo_tail;
822 };
823 
824 
825 /* Callback for the agent_scd_keypairinfo function.  */
826 static gpg_error_t
scd_keypairinfo_status_cb(void * opaque,const char * line)827 scd_keypairinfo_status_cb (void *opaque, const char *line)
828 {
829   struct keypairinfo_cb_parm_s *parm = opaque;
830   gpg_error_t err = 0;
831   const char *keyword = line;
832   int keywordlen;
833   char *line_buffer = NULL;
834   keypair_info_t kpi = NULL;
835 
836   for (keywordlen=0; *line && !spacep (line); line++, keywordlen++)
837     ;
838   while (spacep (line))
839     line++;
840 
841   if (keywordlen == 11 && !memcmp (keyword, "KEYPAIRINFO", keywordlen))
842     {
843       /* The format of such a line is:
844        *   KEYPAIRINFO <hexgrip> <keyref> [usage] [keytime] [algostr]
845        */
846       const char *fields[4];
847       int nfields;
848       const char *hexgrp, *keyref, *usage;
849       time_t atime;
850       u32 keytime;
851 
852       line_buffer = xtrystrdup (line);
853       if (!line_buffer)
854         {
855           err = gpg_error_from_syserror ();
856           goto leave;
857         }
858       if ((nfields = split_fields (line_buffer, fields, DIM (fields))) < 2)
859         goto leave;  /* not enough args - invalid status line - ignore  */
860 
861       hexgrp = fields[0];
862       keyref = fields[1];
863       if (nfields > 2)
864         usage = fields[2];
865       else
866         usage = "";
867       if (nfields > 3)
868         {
869           atime = parse_timestamp (fields[3], NULL);
870           if (atime == (time_t)(-1))
871             atime = 0;
872           keytime = atime;
873         }
874       else
875         keytime = 0;
876 
877       kpi = xtrycalloc (1, sizeof *kpi);
878       if (!kpi)
879         {
880           err = gpg_error_from_syserror ();
881           goto leave;
882         }
883 
884       if (*hexgrp == 'X' && !hexgrp[1])
885         *kpi->keygrip = 0; /* No hexgrip.  */
886       else if (strlen (hexgrp) == 2*KEYGRIP_LEN)
887         mem2str (kpi->keygrip, hexgrp, sizeof kpi->keygrip);
888       else
889         {
890           err = gpg_error (GPG_ERR_INV_DATA);
891           goto leave;
892         }
893 
894       if (!*keyref)
895         {
896           err = gpg_error (GPG_ERR_INV_DATA);
897           goto leave;
898         }
899       kpi->idstr = xtrystrdup (keyref);
900       if (!kpi->idstr)
901         {
902           err = gpg_error_from_syserror ();
903           goto leave;
904         }
905 
906       /* Parse and set the usage.  */
907       for (; *usage; usage++)
908         {
909           switch (*usage)
910             {
911             case 's': kpi->usage |= GCRY_PK_USAGE_SIGN; break;
912             case 'c': kpi->usage |= GCRY_PK_USAGE_CERT; break;
913             case 'a': kpi->usage |= GCRY_PK_USAGE_AUTH; break;
914             case 'e': kpi->usage |= GCRY_PK_USAGE_ENCR; break;
915             }
916         }
917 
918       kpi->keytime = keytime;
919 
920       /* Append to the list.  */
921       *parm->kpinfo_tail = kpi;
922       parm->kpinfo_tail = &kpi->next;
923       kpi = NULL;
924     }
925 
926  leave:
927   free_keypair_info (kpi);
928   xfree (line_buffer);
929   return err;
930 }
931 
932 
933 /* Read the keypairinfo lines of the current card directly from
934  * scdaemon.  The list is returned as a string made up of the keygrip,
935  * a space and the keyref.  The flags of the string carry the usage
936  * bits.  If KEYREF is not NULL, only a single string is returned
937  * which matches the given keyref. */
938 gpg_error_t
agent_scd_keypairinfo(ctrl_t ctrl,const char * keyref,keypair_info_t * r_list)939 agent_scd_keypairinfo (ctrl_t ctrl, const char *keyref, keypair_info_t *r_list)
940 {
941   gpg_error_t err;
942   struct keypairinfo_cb_parm_s parm;
943   struct default_inq_parm_s inq_parm;
944   char line[ASSUAN_LINELENGTH];
945 
946   *r_list = NULL;
947   err= start_agent (ctrl, 1);
948   if (err)
949     return err;
950   memset (&inq_parm, 0, sizeof inq_parm);
951   inq_parm.ctx = agent_ctx;
952 
953   parm.kpinfo = NULL;
954   parm.kpinfo_tail = &parm.kpinfo;
955 
956   if (keyref)
957     snprintf (line, DIM(line), "SCD READKEY --info-only %s", keyref);
958   else
959     snprintf (line, DIM(line), "SCD LEARN --keypairinfo");
960 
961   err = assuan_transact (agent_ctx, line,
962                          NULL, NULL,
963                          default_inq_cb, &inq_parm,
964                          scd_keypairinfo_status_cb, &parm);
965   if (!err && !parm.kpinfo)
966     err = gpg_error (GPG_ERR_NO_DATA);
967 
968   if (err)
969     free_keypair_info (parm.kpinfo);
970   else
971     *r_list = parm.kpinfo;
972   return err;
973 }
974 
975 
976 
977 /* Send an APDU to the current card.  On success the status word is
978  * stored at R_SW unless R_SQ is NULL.  With HEXAPDU being NULL only a
979  * RESET command is send to scd.  HEXAPDU may also be one of theseo
980  * special strings:
981  *
982  *   "undefined"       :: Send the command "SCD SERIALNO undefined"
983  *   "lock"            :: Send the command "SCD LOCK --wait"
984  *   "trylock"         :: Send the command "SCD LOCK"
985  *   "unlock"          :: Send the command "SCD UNLOCK"
986  *   "reset-keep-lock" :: Send the command "SCD RESET --keep-lock"
987  *
988  * Used by:
989  *  card-util.c
990  */
991 gpg_error_t
agent_scd_apdu(const char * hexapdu,unsigned int * r_sw)992 agent_scd_apdu (const char *hexapdu, unsigned int *r_sw)
993 {
994   gpg_error_t err;
995 
996   /* Start the agent but not with the card flag so that we do not
997      autoselect the openpgp application.  */
998   err = start_agent (NULL, 0);
999   if (err)
1000     return err;
1001 
1002   if (!hexapdu)
1003     {
1004       err = assuan_transact (agent_ctx, "SCD RESET",
1005                              NULL, NULL, NULL, NULL, NULL, NULL);
1006 
1007     }
1008   else if (!strcmp (hexapdu, "reset-keep-lock"))
1009     {
1010       err = assuan_transact (agent_ctx, "SCD RESET --keep-lock",
1011                              NULL, NULL, NULL, NULL, NULL, NULL);
1012     }
1013   else if (!strcmp (hexapdu, "lock"))
1014     {
1015       err = assuan_transact (agent_ctx, "SCD LOCK --wait",
1016                              NULL, NULL, NULL, NULL, NULL, NULL);
1017     }
1018   else if (!strcmp (hexapdu, "trylock"))
1019     {
1020       err = assuan_transact (agent_ctx, "SCD LOCK",
1021                              NULL, NULL, NULL, NULL, NULL, NULL);
1022     }
1023   else if (!strcmp (hexapdu, "unlock"))
1024     {
1025       err = assuan_transact (agent_ctx, "SCD UNLOCK",
1026                              NULL, NULL, NULL, NULL, NULL, NULL);
1027     }
1028   else if (!strcmp (hexapdu, "undefined"))
1029     {
1030       err = assuan_transact (agent_ctx, "SCD SERIALNO undefined",
1031                              NULL, NULL, NULL, NULL, NULL, NULL);
1032     }
1033   else
1034     {
1035       char line[ASSUAN_LINELENGTH];
1036       membuf_t mb;
1037       unsigned char *data;
1038       size_t datalen;
1039 
1040       init_membuf (&mb, 256);
1041 
1042       snprintf (line, DIM(line), "SCD APDU %s", hexapdu);
1043       err = assuan_transact (agent_ctx, line,
1044                              put_membuf_cb, &mb, NULL, NULL, NULL, NULL);
1045       if (!err)
1046         {
1047           data = get_membuf (&mb, &datalen);
1048           if (!data)
1049             err = gpg_error_from_syserror ();
1050           else if (datalen < 2) /* Ooops */
1051             err = gpg_error (GPG_ERR_CARD);
1052           else
1053             {
1054               *r_sw = buf16_to_uint (data+datalen-2);
1055             }
1056           xfree (data);
1057         }
1058     }
1059 
1060   return err;
1061 }
1062 
1063 int
agent_keytotpm(ctrl_t ctrl,const char * hexgrip)1064 agent_keytotpm (ctrl_t ctrl, const char *hexgrip)
1065 {
1066   int rc;
1067   char line[ASSUAN_LINELENGTH];
1068   struct default_inq_parm_s parm;
1069 
1070   snprintf(line, DIM(line), "KEYTOTPM %s\n", hexgrip);
1071 
1072   rc = start_agent (ctrl, 0);
1073   if (rc)
1074     return rc;
1075   parm.ctx = agent_ctx;
1076   parm.ctrl = ctrl;
1077 
1078   rc = assuan_transact (agent_ctx, line, NULL, NULL, default_inq_cb, &parm,
1079 			NULL, NULL);
1080   if (rc)
1081     log_log (GPGRT_LOGLVL_ERROR, _("error from TPM: %s\n"), gpg_strerror (rc));
1082   return rc;
1083 }
1084 
1085 
1086 /* Used by:
1087  *  card_store_subkey
1088  *  card_store_key_with_backup
1089  */
1090 int
agent_keytocard(const char * hexgrip,int keyno,int force,const char * serialno,const char * timestamp)1091 agent_keytocard (const char *hexgrip, int keyno, int force,
1092                  const char *serialno, const char *timestamp)
1093 {
1094   int rc;
1095   char line[ASSUAN_LINELENGTH];
1096   struct default_inq_parm_s parm;
1097 
1098   memset (&parm, 0, sizeof parm);
1099 
1100   snprintf (line, DIM(line), "KEYTOCARD %s%s %s OPENPGP.%d %s",
1101             force?"--force ": "", hexgrip, serialno, keyno, timestamp);
1102 
1103   rc = start_agent (NULL, 1);
1104   if (rc)
1105     return rc;
1106   parm.ctx = agent_ctx;
1107 
1108   rc = assuan_transact (agent_ctx, line, NULL, NULL, default_inq_cb, &parm,
1109                         NULL, NULL);
1110   if (rc)
1111     return rc;
1112 
1113   return rc;
1114 }
1115 
1116 
1117 
1118 /* Object used with the agent_scd_getattr_one.  */
1119 struct getattr_one_parm_s {
1120   const char *keyword;  /* Keyword to look for.  */
1121   char *data;           /* Malloced and unescaped data.  */
1122   gpg_error_t err;      /* Error code or 0 on success. */
1123 };
1124 
1125 
1126 /* Callback for agent_scd_getattr_one.  */
1127 static gpg_error_t
getattr_one_status_cb(void * opaque,const char * line)1128 getattr_one_status_cb (void *opaque, const char *line)
1129 {
1130   struct getattr_one_parm_s *parm = opaque;
1131   const char *s;
1132 
1133   if (parm->data)
1134     return 0; /* We want only the first occurrence.  */
1135 
1136   if ((s=has_leading_keyword (line, parm->keyword)))
1137     {
1138       parm->data = percent_plus_unescape (s, 0xff);
1139       if (!parm->data)
1140         parm->err = gpg_error_from_syserror ();
1141     }
1142 
1143   return 0;
1144 }
1145 
1146 
1147 /* Simplified version of agent_scd_getattr.  This function returns
1148  * only the first occurrence of the attribute NAME and stores it at
1149  * R_VALUE.  A nul in the result is silennly replaced by 0xff.  On
1150  * error NULL is stored at R_VALUE.  */
1151 gpg_error_t
agent_scd_getattr_one(const char * name,char ** r_value)1152 agent_scd_getattr_one (const char *name, char **r_value)
1153 {
1154   gpg_error_t err;
1155   char line[ASSUAN_LINELENGTH];
1156   struct default_inq_parm_s inqparm;
1157   struct getattr_one_parm_s parm;
1158 
1159   *r_value = NULL;
1160 
1161   if (!*name)
1162     return gpg_error (GPG_ERR_INV_VALUE);
1163 
1164   memset (&inqparm, 0, sizeof inqparm);
1165   inqparm.ctx = agent_ctx;
1166 
1167   memset (&parm, 0, sizeof parm);
1168   parm.keyword = name;
1169 
1170   /* We assume that NAME does not need escaping. */
1171   if (12 + strlen (name) > DIM(line)-1)
1172     return gpg_error (GPG_ERR_TOO_LARGE);
1173   stpcpy (stpcpy (line, "SCD GETATTR "), name);
1174 
1175   err = start_agent (NULL, 1);
1176   if (err)
1177     return err;
1178 
1179   err = assuan_transact (agent_ctx, line,
1180                          NULL, NULL,
1181                          default_inq_cb, &inqparm,
1182                          getattr_one_status_cb, &parm);
1183   if (!err && parm.err)
1184     err = parm.err;
1185   else if (!err && !parm.data)
1186     err = gpg_error (GPG_ERR_NO_DATA);
1187 
1188   if (!err)
1189     *r_value = parm.data;
1190   else
1191     xfree (parm.data);
1192 
1193   return err;
1194 }
1195 
1196 
1197 
1198 /* Call the agent to retrieve a data object.  This function returns
1199  * the data in the same structure as used by the learn command.  It is
1200  * allowed to update such a structure using this command.
1201  *
1202  *  Used by:
1203  *     build_sk_list
1204  *     enum_secret_keys
1205  *     get_signature_count
1206  *     card-util.c
1207  *     generate_keypair (KEY-ATTR)
1208  *     card_store_key_with_backup (SERIALNO)
1209  *     generate_card_subkeypair  (KEY-ATTR)
1210  */
1211 int
agent_scd_getattr(const char * name,struct agent_card_info_s * info)1212 agent_scd_getattr (const char *name, struct agent_card_info_s *info)
1213 {
1214   int rc;
1215   char line[ASSUAN_LINELENGTH];
1216   struct default_inq_parm_s parm;
1217 
1218   memset (&parm, 0, sizeof parm);
1219 
1220   if (!*name)
1221     return gpg_error (GPG_ERR_INV_VALUE);
1222 
1223   /* We assume that NAME does not need escaping. */
1224   if (12 + strlen (name) > DIM(line)-1)
1225     return gpg_error (GPG_ERR_TOO_LARGE);
1226   stpcpy (stpcpy (line, "SCD GETATTR "), name);
1227 
1228   rc = start_agent (NULL, 1);
1229   if (rc)
1230     return rc;
1231 
1232   parm.ctx = agent_ctx;
1233   rc = assuan_transact (agent_ctx, line, NULL, NULL, default_inq_cb, &parm,
1234                         learn_status_cb, info);
1235   if (!rc && !strcmp (name, "KEY-FPR"))
1236     {
1237       /* Let the agent create the shadow keys if not yet done.  */
1238       if (info->fpr1len)
1239         assuan_transact (agent_ctx, "READKEY --card --no-data -- $SIGNKEYID",
1240                          NULL, NULL, NULL, NULL, NULL, NULL);
1241       if (info->fpr2len)
1242         assuan_transact (agent_ctx, "READKEY --card --no-data -- $ENCRKEYID",
1243                          NULL, NULL, NULL, NULL, NULL, NULL);
1244     }
1245 
1246   return rc;
1247 }
1248 
1249 
1250 
1251 /* Send an setattr command to the SCdaemon.
1252  * Used by:
1253  *   card-util.c
1254  */
1255 gpg_error_t
agent_scd_setattr(const char * name,const void * value_arg,size_t valuelen)1256 agent_scd_setattr (const char *name, const void *value_arg, size_t valuelen)
1257 {
1258   gpg_error_t err;
1259   const unsigned char *value = value_arg;
1260   char line[ASSUAN_LINELENGTH];
1261   char *p;
1262   struct default_inq_parm_s parm;
1263 
1264   memset (&parm, 0, sizeof parm);
1265 
1266   if (!*name || !valuelen)
1267     return gpg_error (GPG_ERR_INV_VALUE);
1268 
1269   /* We assume that NAME does not need escaping. */
1270   if (12 + strlen (name) > DIM(line)-1)
1271     return gpg_error (GPG_ERR_TOO_LARGE);
1272 
1273   p = stpcpy (stpcpy (line, "SCD SETATTR "), name);
1274   *p++ = ' ';
1275   for (; valuelen; value++, valuelen--)
1276     {
1277       if (p >= line + DIM(line)-5 )
1278         return gpg_error (GPG_ERR_TOO_LARGE);
1279       if (*value < ' ' || *value == '+' || *value == '%')
1280         {
1281           sprintf (p, "%%%02X", *value);
1282           p += 3;
1283         }
1284       else if (*value == ' ')
1285         *p++ = '+';
1286       else
1287         *p++ = *value;
1288     }
1289   *p = 0;
1290 
1291   err = start_agent (NULL, 1);
1292   if (!err)
1293     {
1294       parm.ctx = agent_ctx;
1295       err = assuan_transact (agent_ctx, line, NULL, NULL,
1296                             default_inq_cb, &parm, NULL, NULL);
1297     }
1298 
1299   status_sc_op_failure (err);
1300   return err;
1301 }
1302 
1303 
1304 
1305 /* Handle a CERTDATA inquiry.  Note, we only send the data,
1306    assuan_transact takes care of flushing and writing the END
1307    command. */
1308 static gpg_error_t
inq_writecert_parms(void * opaque,const char * line)1309 inq_writecert_parms (void *opaque, const char *line)
1310 {
1311   int rc;
1312   struct writecert_parm_s *parm = opaque;
1313 
1314   if (has_leading_keyword (line, "CERTDATA"))
1315     {
1316       rc = assuan_send_data (parm->dflt->ctx,
1317                              parm->certdata, parm->certdatalen);
1318     }
1319   else
1320     rc = default_inq_cb (parm->dflt, line);
1321 
1322   return rc;
1323 }
1324 
1325 
1326 /* Send a WRITECERT command to the SCdaemon.
1327  * Used by:
1328  *  card-util.c
1329  */
1330 int
agent_scd_writecert(const char * certidstr,const unsigned char * certdata,size_t certdatalen)1331 agent_scd_writecert (const char *certidstr,
1332                      const unsigned char *certdata, size_t certdatalen)
1333 {
1334   int rc;
1335   char line[ASSUAN_LINELENGTH];
1336   struct writecert_parm_s parms;
1337   struct default_inq_parm_s dfltparm;
1338 
1339   memset (&dfltparm, 0, sizeof dfltparm);
1340 
1341   rc = start_agent (NULL, 1);
1342   if (rc)
1343     return rc;
1344 
1345   memset (&parms, 0, sizeof parms);
1346 
1347   snprintf (line, DIM(line), "SCD WRITECERT %s", certidstr);
1348   dfltparm.ctx = agent_ctx;
1349   parms.dflt = &dfltparm;
1350   parms.certdata = certdata;
1351   parms.certdatalen = certdatalen;
1352 
1353   rc = assuan_transact (agent_ctx, line, NULL, NULL,
1354                         inq_writecert_parms, &parms, NULL, NULL);
1355 
1356   return rc;
1357 }
1358 
1359 
1360 
1361 /* Status callback for the SCD GENKEY command. */
1362 static gpg_error_t
scd_genkey_cb(void * opaque,const char * line)1363 scd_genkey_cb (void *opaque, const char *line)
1364 {
1365   u32 *createtime = opaque;
1366   const char *keyword = line;
1367   int keywordlen;
1368 
1369   for (keywordlen=0; *line && !spacep (line); line++, keywordlen++)
1370     ;
1371   while (spacep (line))
1372     line++;
1373 
1374  if (keywordlen == 14 && !memcmp (keyword,"KEY-CREATED-AT", keywordlen))
1375     {
1376       *createtime = (u32)strtoul (line, NULL, 10);
1377     }
1378   else if (keywordlen == 8 && !memcmp (keyword, "PROGRESS", keywordlen))
1379     {
1380       write_status_text (STATUS_PROGRESS, line);
1381     }
1382 
1383   return 0;
1384 }
1385 
1386 /* Send a GENKEY command to the SCdaemon.  If *CREATETIME is not 0,
1387  * the value will be passed to SCDAEMON with --timestamp option so that
1388  * the key is created with this.  Otherwise, timestamp was generated by
1389  * SCDEAMON.  On success, creation time is stored back to
1390  * CREATETIME.
1391  * Used by:
1392  *   gen_card_key
1393  */
1394 int
agent_scd_genkey(int keyno,int force,u32 * createtime)1395 agent_scd_genkey (int keyno, int force, u32 *createtime)
1396 {
1397   int rc;
1398   char line[ASSUAN_LINELENGTH];
1399   gnupg_isotime_t tbuf;
1400   struct default_inq_parm_s dfltparm;
1401 
1402   memset (&dfltparm, 0, sizeof dfltparm);
1403 
1404   rc = start_agent (NULL, 1);
1405   if (rc)
1406     return rc;
1407 
1408   if (*createtime)
1409     epoch2isotime (tbuf, *createtime);
1410   else
1411     *tbuf = 0;
1412 
1413   snprintf (line, DIM(line), "SCD GENKEY %s%s %s %d",
1414             *tbuf? "--timestamp=":"", tbuf,
1415             force? "--force":"",
1416             keyno);
1417 
1418   dfltparm.ctx = agent_ctx;
1419   rc = assuan_transact (agent_ctx, line,
1420                         NULL, NULL, default_inq_cb, &dfltparm,
1421                         scd_genkey_cb, createtime);
1422 
1423   status_sc_op_failure (rc);
1424   return rc;
1425 }
1426 
1427 
1428 
1429 /* Return the serial number of the card or an appropriate error.  The
1430  * serial number is returned as a hexstring.  With DEMAND the active
1431  * card is switched to the card with that serialno.
1432  * Used by:
1433  *   card-util.c
1434  *   build_sk_list
1435  *   enum_secret_keys
1436  */
1437 int
agent_scd_serialno(char ** r_serialno,const char * demand)1438 agent_scd_serialno (char **r_serialno, const char *demand)
1439 {
1440   int err;
1441   char *serialno = NULL;
1442   char line[ASSUAN_LINELENGTH];
1443 
1444   if (r_serialno)
1445     *r_serialno = NULL;
1446 
1447   err = start_agent (NULL, (1 | FLAG_FOR_CARD_SUPPRESS_ERRORS));
1448   if (err)
1449     return err;
1450 
1451   if (!demand)
1452     strcpy (line, "SCD SERIALNO");
1453   else
1454     snprintf (line, DIM(line), "SCD SERIALNO --demand=%s", demand);
1455 
1456   err = assuan_transact (agent_ctx, line,
1457                          NULL, NULL, NULL, NULL,
1458                          get_serialno_cb, &serialno);
1459   if (err)
1460     {
1461       xfree (serialno);
1462       return err;
1463     }
1464 
1465   if (r_serialno)
1466     *r_serialno = serialno;
1467   else
1468     xfree (serialno);
1469 
1470   return 0;
1471 }
1472 
1473 
1474 
1475 /* Send a READCERT command to the SCdaemon.
1476  * Used by:
1477  *  card-util.c
1478  */
1479 int
agent_scd_readcert(const char * certidstr,void ** r_buf,size_t * r_buflen)1480 agent_scd_readcert (const char *certidstr,
1481                     void **r_buf, size_t *r_buflen)
1482 {
1483   int rc;
1484   char line[ASSUAN_LINELENGTH];
1485   membuf_t data;
1486   size_t len;
1487   struct default_inq_parm_s dfltparm;
1488 
1489   memset (&dfltparm, 0, sizeof dfltparm);
1490 
1491   *r_buf = NULL;
1492   rc = start_agent (NULL, 1);
1493   if (rc)
1494     return rc;
1495 
1496   dfltparm.ctx = agent_ctx;
1497 
1498   init_membuf (&data, 2048);
1499 
1500   snprintf (line, DIM(line), "SCD READCERT %s", certidstr);
1501   rc = assuan_transact (agent_ctx, line,
1502                         put_membuf_cb, &data,
1503                         default_inq_cb, &dfltparm,
1504                         NULL, NULL);
1505   if (rc)
1506     {
1507       xfree (get_membuf (&data, &len));
1508       return rc;
1509     }
1510   *r_buf = get_membuf (&data, r_buflen);
1511   if (!*r_buf)
1512     return gpg_error (GPG_ERR_ENOMEM);
1513 
1514   return 0;
1515 }
1516 
1517 
1518 /* Callback for the agent_scd_readkey function.  */
1519 static gpg_error_t
readkey_status_cb(void * opaque,const char * line)1520 readkey_status_cb (void *opaque, const char *line)
1521 {
1522   u32 *keytimep = opaque;
1523   gpg_error_t err = 0;
1524   const char *args;
1525   char *line_buffer = NULL;
1526 
1527   /* FIXME: Get that info from the KEYPAIRINFO line.  */
1528   if ((args = has_leading_keyword (line, "KEYPAIRINFO"))
1529       && !*keytimep)
1530     {
1531       /* The format of such a line is:
1532        *   KEYPAIRINFO <hexgrip> <keyref> [usage] [keytime]
1533        *
1534        * Note that we use only the first valid KEYPAIRINFO line.  More
1535        * lines are possible if a second card carries the same key.
1536        */
1537       const char *fields[4];
1538       int nfields;
1539       time_t atime;
1540 
1541       line_buffer = xtrystrdup (line);
1542       if (!line_buffer)
1543         {
1544           err = gpg_error_from_syserror ();
1545           goto leave;
1546         }
1547       if ((nfields = split_fields (line_buffer, fields, DIM (fields))) < 4)
1548         goto leave;  /* not enough args - ignore  */
1549 
1550       if (nfields > 3)
1551         {
1552           atime = parse_timestamp (fields[3], NULL);
1553           if (atime == (time_t)(-1))
1554             atime = 0;
1555           *keytimep = atime;
1556         }
1557       else
1558         *keytimep = 0;
1559     }
1560 
1561  leave:
1562   xfree (line_buffer);
1563   return err;
1564 }
1565 
1566 
1567 /* This is a variant of agent_readkey which sends a READKEY command
1568  * directly Scdaemon.  On success a new s-expression is stored at
1569  * R_RESULT.  If R_KEYTIME is not NULL the key cresation time of an
1570  * OpenPGP card is stored there - if that is not known 0 is stored.
1571  * In the latter case it is allowed to pass NULL for R_RESULT.  */
1572 gpg_error_t
agent_scd_readkey(ctrl_t ctrl,const char * keyrefstr,gcry_sexp_t * r_result,u32 * r_keytime)1573 agent_scd_readkey (ctrl_t ctrl, const char *keyrefstr,
1574                    gcry_sexp_t *r_result, u32 *r_keytime)
1575 {
1576   gpg_error_t err;
1577   char line[ASSUAN_LINELENGTH];
1578   membuf_t data;
1579   unsigned char *buf;
1580   size_t len, buflen;
1581   struct default_inq_parm_s dfltparm;
1582   u32 keytime;
1583 
1584   memset (&dfltparm, 0, sizeof dfltparm);
1585   dfltparm.ctx = agent_ctx;
1586 
1587   if (r_result)
1588     *r_result = NULL;
1589   if (r_keytime)
1590     *r_keytime = 0;
1591   err = start_agent (ctrl, 1);
1592   if (err)
1593     return err;
1594 
1595   init_membuf (&data, 1024);
1596   snprintf (line, DIM(line),
1597             "SCD READKEY --info%s -- %s",
1598             r_result? "":"-only", keyrefstr);
1599   keytime = 0;
1600   err = assuan_transact (agent_ctx, line,
1601                          put_membuf_cb, &data,
1602                          default_inq_cb, &dfltparm,
1603                          readkey_status_cb, &keytime);
1604   if (err)
1605     {
1606       xfree (get_membuf (&data, &len));
1607       return err;
1608     }
1609   buf = get_membuf (&data, &buflen);
1610   if (!buf)
1611     return gpg_error_from_syserror ();
1612 
1613   if (r_result)
1614     err = gcry_sexp_new (r_result, buf, buflen, 0);
1615   else
1616     err = 0;
1617   xfree (buf);
1618 
1619   if (!err && r_keytime)
1620     *r_keytime = keytime;
1621   return err;
1622 }
1623 
1624 
1625 
1626 struct card_cardlist_parm_s {
1627   int error;
1628   strlist_t list;
1629 };
1630 
1631 
1632 /* Callback function for agent_card_cardlist.  */
1633 static gpg_error_t
card_cardlist_cb(void * opaque,const char * line)1634 card_cardlist_cb (void *opaque, const char *line)
1635 {
1636   struct card_cardlist_parm_s *parm = opaque;
1637   const char *keyword = line;
1638   int keywordlen;
1639 
1640   for (keywordlen=0; *line && !spacep (line); line++, keywordlen++)
1641     ;
1642   while (spacep (line))
1643     line++;
1644 
1645   if (keywordlen == 8 && !memcmp (keyword, "SERIALNO", keywordlen))
1646     {
1647       const char *s;
1648       int n;
1649 
1650       for (n=0,s=line; hexdigitp (s); s++, n++)
1651         ;
1652 
1653       if (!n || (n&1) || *s)
1654         parm->error = gpg_error (GPG_ERR_ASS_PARAMETER);
1655       else
1656         add_to_strlist (&parm->list, line);
1657     }
1658 
1659   return 0;
1660 }
1661 
1662 
1663 /* Return a list of currently available cards.
1664  * Used by:
1665  *   card-util.c
1666  *   skclist.c
1667  */
1668 int
agent_scd_cardlist(strlist_t * result)1669 agent_scd_cardlist (strlist_t *result)
1670 {
1671   int err;
1672   char line[ASSUAN_LINELENGTH];
1673   struct card_cardlist_parm_s parm;
1674 
1675   memset (&parm, 0, sizeof parm);
1676   *result = NULL;
1677   err = start_agent (NULL, 1 | FLAG_FOR_CARD_SUPPRESS_ERRORS);
1678   if (err)
1679     return err;
1680 
1681   strcpy (line, "SCD GETINFO card_list");
1682 
1683   err = assuan_transact (agent_ctx, line,
1684                          NULL, NULL, NULL, NULL,
1685                          card_cardlist_cb, &parm);
1686   if (!err && parm.error)
1687     err = parm.error;
1688 
1689   if (!err)
1690     *result = parm.list;
1691   else
1692     free_strlist (parm.list);
1693 
1694   return 0;
1695 }
1696 
1697 
1698 
1699 struct card_keyinfo_parm_s {
1700   int error;
1701   keypair_info_t list;
1702 };
1703 
1704 /* Callback function for agent_card_keylist.  */
1705 static gpg_error_t
card_keyinfo_cb(void * opaque,const char * line)1706 card_keyinfo_cb (void *opaque, const char *line)
1707 {
1708   gpg_error_t err = 0;
1709   struct card_keyinfo_parm_s *parm = opaque;
1710   const char *keyword = line;
1711   int keywordlen;
1712   keypair_info_t keyinfo = NULL;
1713 
1714   for (keywordlen=0; *line && !spacep (line); line++, keywordlen++)
1715     ;
1716   while (spacep (line))
1717     line++;
1718 
1719   if (keywordlen == 7 && !memcmp (keyword, "KEYINFO", keywordlen))
1720     {
1721       const char *s;
1722       int n;
1723       keypair_info_t *l_p = &parm->list;
1724 
1725       while ((*l_p))
1726         l_p = &(*l_p)->next;
1727 
1728       keyinfo = xtrycalloc (1, sizeof *keyinfo);
1729       if (!keyinfo)
1730         goto alloc_error;
1731 
1732       for (n=0,s=line; hexdigitp (s); s++, n++)
1733         ;
1734 
1735       if (n != 40)
1736         goto parm_error;
1737 
1738       memcpy (keyinfo->keygrip, line, 40);
1739       keyinfo->keygrip[40] = 0;
1740 
1741       line = s;
1742 
1743       if (!*line)
1744         goto parm_error;
1745 
1746       while (spacep (line))
1747         line++;
1748 
1749       if (*line++ != 'T')
1750         goto parm_error;
1751 
1752       if (!*line)
1753         goto parm_error;
1754 
1755       while (spacep (line))
1756         line++;
1757 
1758       for (n=0,s=line; hexdigitp (s); s++, n++)
1759         ;
1760 
1761       if (!n)
1762         goto parm_error;
1763 
1764       keyinfo->serialno = xtrymalloc (n+1);
1765       if (!keyinfo->serialno)
1766         goto alloc_error;
1767 
1768       memcpy (keyinfo->serialno, line, n);
1769       keyinfo->serialno[n] = 0;
1770 
1771       line = s;
1772 
1773       if (!*line)
1774         goto parm_error;
1775 
1776       while (spacep (line))
1777         line++;
1778 
1779       if (!*line)
1780         goto parm_error;
1781 
1782       keyinfo->idstr = xtrystrdup (line);
1783       if (!keyinfo->idstr)
1784         goto alloc_error;
1785 
1786       *l_p = keyinfo;
1787     }
1788 
1789   return err;
1790 
1791  alloc_error:
1792   xfree (keyinfo);
1793   if (!parm->error)
1794     parm->error = gpg_error_from_syserror ();
1795   return 0;
1796 
1797  parm_error:
1798   xfree (keyinfo);
1799   if (!parm->error)
1800     parm->error = gpg_error (GPG_ERR_ASS_PARAMETER);
1801   return 0;
1802 }
1803 
1804 
1805 /* Free a keypair info list.  */
1806 void
free_keypair_info(keypair_info_t l)1807 free_keypair_info (keypair_info_t l)
1808 {
1809   keypair_info_t l_next;
1810 
1811   for (; l; l = l_next)
1812     {
1813       l_next = l->next;
1814       xfree (l->serialno);
1815       xfree (l->idstr);
1816       xfree (l);
1817     }
1818 }
1819 
1820 /* Call the scdaemon to check if a key of KEYGRIP is available, or
1821    retrieve list of available keys on cards.  With CAP, we can limit
1822    keys with specified capability.  On success, the allocated
1823    structure is stored at RESULT.  On error, an error code is returned
1824    and NULL is stored at RESULT.  */
1825 gpg_error_t
agent_scd_keyinfo(const char * keygrip,int cap,keypair_info_t * result)1826 agent_scd_keyinfo (const char *keygrip, int cap,
1827                    keypair_info_t *result)
1828 {
1829   int err;
1830   struct card_keyinfo_parm_s parm;
1831   char line[ASSUAN_LINELENGTH];
1832   char *list_option;
1833 
1834   *result = NULL;
1835 
1836   switch (cap)
1837     {
1838     case                  0: list_option = "--list";      break;
1839     case GCRY_PK_USAGE_SIGN: list_option = "--list=sign"; break;
1840     case GCRY_PK_USAGE_ENCR: list_option = "--list=encr"; break;
1841     case GCRY_PK_USAGE_AUTH: list_option = "--list=auth"; break;
1842     default:                 return gpg_error (GPG_ERR_INV_VALUE);
1843     }
1844 
1845   memset (&parm, 0, sizeof parm);
1846   snprintf (line, sizeof line, "SCD KEYINFO %s",
1847             keygrip ? keygrip : list_option);
1848 
1849   err = start_agent (NULL, 1 | FLAG_FOR_CARD_SUPPRESS_ERRORS);
1850   if (err)
1851     return err;
1852 
1853   err = assuan_transact (agent_ctx, line,
1854                          NULL, NULL, NULL, NULL,
1855                          card_keyinfo_cb, &parm);
1856   if (!err && parm.error)
1857     err = parm.error;
1858 
1859   if (!err)
1860     *result = parm.list;
1861   else
1862     free_keypair_info (parm.list);
1863 
1864   return err;
1865 }
1866 
1867 /* Change the PIN of an OpenPGP card or reset the retry counter.
1868  * CHVNO 1: Change the PIN
1869  *       2: For v1 cards: Same as 1.
1870  *          For v2 cards: Reset the PIN using the Reset Code.
1871  *       3: Change the admin PIN
1872  *     101: Set a new PIN and reset the retry counter
1873  *     102: For v1 cars: Same as 101.
1874  *          For v2 cards: Set a new Reset Code.
1875  * SERIALNO is not used.
1876  * Used by:
1877  *  card-util.c
1878  */
1879 int
agent_scd_change_pin(int chvno,const char * serialno)1880 agent_scd_change_pin (int chvno, const char *serialno)
1881 {
1882   int rc;
1883   char line[ASSUAN_LINELENGTH];
1884   const char *reset = "";
1885   struct default_inq_parm_s dfltparm;
1886 
1887   memset (&dfltparm, 0, sizeof dfltparm);
1888 
1889   (void)serialno;
1890 
1891   if (chvno >= 100)
1892     reset = "--reset";
1893   chvno %= 100;
1894 
1895   rc = start_agent (NULL, 1);
1896   if (rc)
1897     return rc;
1898   dfltparm.ctx = agent_ctx;
1899 
1900   snprintf (line, DIM(line), "SCD PASSWD %s %d", reset, chvno);
1901   rc = assuan_transact (agent_ctx, line,
1902                         NULL, NULL,
1903                         default_inq_cb, &dfltparm,
1904                         NULL, NULL);
1905   status_sc_op_failure (rc);
1906   return rc;
1907 }
1908 
1909 
1910 /* Perform a CHECKPIN operation.  SERIALNO should be the serial
1911  * number of the card - optionally followed by the fingerprint;
1912  * however the fingerprint is ignored here.
1913  * Used by:
1914  *  card-util.c
1915  */
1916 int
agent_scd_checkpin(const char * serialno)1917 agent_scd_checkpin  (const char *serialno)
1918 {
1919   int rc;
1920   char line[ASSUAN_LINELENGTH];
1921   struct default_inq_parm_s dfltparm;
1922 
1923   memset (&dfltparm, 0, sizeof dfltparm);
1924 
1925   rc = start_agent (NULL, 1);
1926   if (rc)
1927     return rc;
1928   dfltparm.ctx = agent_ctx;
1929 
1930   snprintf (line, DIM(line), "SCD CHECKPIN %s", serialno);
1931   rc = assuan_transact (agent_ctx, line,
1932                         NULL, NULL,
1933                         default_inq_cb, &dfltparm,
1934                         NULL, NULL);
1935   status_sc_op_failure (rc);
1936   return rc;
1937 }
1938 
1939 
1940 
1941 /* Note: All strings shall be UTF-8. On success the caller needs to
1942    free the string stored at R_PASSPHRASE. On error NULL will be
1943    stored at R_PASSPHRASE and an appropriate error code returned.
1944    Only called from passphrase.c:passphrase_get - see there for more
1945    comments on this ugly API. */
1946 gpg_error_t
agent_get_passphrase(const char * cache_id,const char * err_msg,const char * prompt,const char * desc_msg,int newsymkey,int repeat,int check,char ** r_passphrase)1947 agent_get_passphrase (const char *cache_id,
1948                       const char *err_msg,
1949                       const char *prompt,
1950                       const char *desc_msg,
1951                       int newsymkey,
1952                       int repeat,
1953                       int check,
1954                       char **r_passphrase)
1955 {
1956   int rc;
1957   char line[ASSUAN_LINELENGTH];
1958   char *arg1 = NULL;
1959   char *arg2 = NULL;
1960   char *arg3 = NULL;
1961   char *arg4 = NULL;
1962   membuf_t data;
1963   struct default_inq_parm_s dfltparm;
1964   int have_newsymkey;
1965 
1966   memset (&dfltparm, 0, sizeof dfltparm);
1967 
1968   *r_passphrase = NULL;
1969 
1970   rc = start_agent (NULL, 0);
1971   if (rc)
1972     return rc;
1973   dfltparm.ctx = agent_ctx;
1974 
1975   /* Check that the gpg-agent understands the repeat option.  */
1976   if (assuan_transact (agent_ctx,
1977                        "GETINFO cmd_has_option GET_PASSPHRASE repeat",
1978                        NULL, NULL, NULL, NULL, NULL, NULL))
1979     return gpg_error (GPG_ERR_NOT_SUPPORTED);
1980   have_newsymkey = !(assuan_transact
1981                      (agent_ctx,
1982                       "GETINFO cmd_has_option GET_PASSPHRASE newsymkey",
1983                       NULL, NULL, NULL, NULL, NULL, NULL));
1984 
1985   if (cache_id && *cache_id)
1986     if (!(arg1 = percent_plus_escape (cache_id)))
1987       goto no_mem;
1988   if (err_msg && *err_msg)
1989     if (!(arg2 = percent_plus_escape (err_msg)))
1990       goto no_mem;
1991   if (prompt && *prompt)
1992     if (!(arg3 = percent_plus_escape (prompt)))
1993       goto no_mem;
1994   if (desc_msg && *desc_msg)
1995     if (!(arg4 = percent_plus_escape (desc_msg)))
1996       goto no_mem;
1997 
1998   /* CHECK && REPEAT or NEWSYMKEY is here an indication that a new
1999    * passphrase for symmetric encryption is requested; if the agent
2000    * supports this we enable the modern API by also passing --newsymkey.  */
2001   snprintf (line, DIM(line),
2002             "GET_PASSPHRASE --data --repeat=%d%s%s -- %s %s %s %s",
2003             repeat,
2004             ((repeat && check) || newsymkey)? " --check":"",
2005             (have_newsymkey && newsymkey)? " --newsymkey":"",
2006             arg1? arg1:"X",
2007             arg2? arg2:"X",
2008             arg3? arg3:"X",
2009             arg4? arg4:"X");
2010   xfree (arg1);
2011   xfree (arg2);
2012   xfree (arg3);
2013   xfree (arg4);
2014 
2015   init_membuf_secure (&data, 64);
2016   rc = assuan_transact (agent_ctx, line,
2017                         put_membuf_cb, &data,
2018                         default_inq_cb, &dfltparm,
2019                         NULL, NULL);
2020 
2021   if (rc)
2022     xfree (get_membuf (&data, NULL));
2023   else
2024     {
2025       put_membuf (&data, "", 1);
2026       *r_passphrase = get_membuf (&data, NULL);
2027       if (!*r_passphrase)
2028         rc = gpg_error_from_syserror ();
2029     }
2030   return rc;
2031  no_mem:
2032   rc = gpg_error_from_syserror ();
2033   xfree (arg1);
2034   xfree (arg2);
2035   xfree (arg3);
2036   xfree (arg4);
2037   return rc;
2038 }
2039 
2040 
2041 gpg_error_t
agent_clear_passphrase(const char * cache_id)2042 agent_clear_passphrase (const char *cache_id)
2043 {
2044   int rc;
2045   char line[ASSUAN_LINELENGTH];
2046   struct default_inq_parm_s dfltparm;
2047 
2048   memset (&dfltparm, 0, sizeof dfltparm);
2049 
2050   if (!cache_id || !*cache_id)
2051     return 0;
2052 
2053   rc = start_agent (NULL, 0);
2054   if (rc)
2055     return rc;
2056   dfltparm.ctx = agent_ctx;
2057 
2058   snprintf (line, DIM(line), "CLEAR_PASSPHRASE %s", cache_id);
2059   return assuan_transact (agent_ctx, line,
2060                           NULL, NULL,
2061                           default_inq_cb, &dfltparm,
2062                           NULL, NULL);
2063 }
2064 
2065 
2066 /* Ask the agent to pop up a confirmation dialog with the text DESC
2067    and an okay and cancel button. */
2068 gpg_error_t
gpg_agent_get_confirmation(const char * desc)2069 gpg_agent_get_confirmation (const char *desc)
2070 {
2071   int rc;
2072   char *tmp;
2073   char line[ASSUAN_LINELENGTH];
2074   struct default_inq_parm_s dfltparm;
2075 
2076   memset (&dfltparm, 0, sizeof dfltparm);
2077 
2078   rc = start_agent (NULL, 0);
2079   if (rc)
2080     return rc;
2081   dfltparm.ctx = agent_ctx;
2082 
2083   tmp = percent_plus_escape (desc);
2084   if (!tmp)
2085     return gpg_error_from_syserror ();
2086   snprintf (line, DIM(line), "GET_CONFIRMATION %s", tmp);
2087   xfree (tmp);
2088 
2089   rc = assuan_transact (agent_ctx, line,
2090                         NULL, NULL,
2091                         default_inq_cb, &dfltparm,
2092                         NULL, NULL);
2093   return rc;
2094 }
2095 
2096 
2097 /* Return the S2K iteration count as computed by gpg-agent.  On error
2098  * print a warning and return a default value. */
2099 unsigned long
agent_get_s2k_count(void)2100 agent_get_s2k_count (void)
2101 {
2102   gpg_error_t err;
2103   membuf_t data;
2104   char *buf;
2105   unsigned long count = 0;
2106 
2107   err = start_agent (NULL, 0);
2108   if (err)
2109     goto leave;
2110 
2111   init_membuf (&data, 32);
2112   err = assuan_transact (agent_ctx, "GETINFO s2k_count",
2113                         put_membuf_cb, &data,
2114                         NULL, NULL, NULL, NULL);
2115   if (err)
2116     xfree (get_membuf (&data, NULL));
2117   else
2118     {
2119       put_membuf (&data, "", 1);
2120       buf = get_membuf (&data, NULL);
2121       if (!buf)
2122         err = gpg_error_from_syserror ();
2123       else
2124         {
2125           count = strtoul (buf, NULL, 10);
2126           xfree (buf);
2127         }
2128     }
2129 
2130  leave:
2131   if (err || count < 65536)
2132     {
2133       /* Don't print an error if an older agent is used.  */
2134       if (err && gpg_err_code (err) != GPG_ERR_ASS_PARAMETER)
2135         log_error (_("problem with the agent: %s\n"), gpg_strerror (err));
2136 
2137       /* Default to 65536 which was used up to 2.0.13.  */
2138       count = 65536;
2139     }
2140 
2141   return count;
2142 }
2143 
2144 
2145 
2146 struct keyinfo_data_parm_s
2147 {
2148   char *serialno;
2149   int is_smartcard;
2150   int passphrase_cached;
2151   int cleartext;
2152   int card_available;
2153 };
2154 
2155 
2156 static gpg_error_t
keyinfo_status_cb(void * opaque,const char * line)2157 keyinfo_status_cb (void *opaque, const char *line)
2158 {
2159   struct keyinfo_data_parm_s *data = opaque;
2160   char *s;
2161 
2162   if ((s = has_leading_keyword (line, "KEYINFO")) && data)
2163     {
2164       /* Parse the arguments:
2165        *      0        1        2        3       4          5
2166        *   <keygrip> <type> <serialno> <idstr> <cached> <protection>
2167        *
2168        *      6        7        8
2169        *   <sshfpr>  <ttl>  <flags>
2170        */
2171       const char *fields[9];
2172 
2173       if (split_fields (s, fields, DIM (fields)) == 9)
2174         {
2175           data->is_smartcard = (fields[1][0] == 'T');
2176           if (data->is_smartcard && !data->serialno && strcmp (fields[2], "-"))
2177             data->serialno = xtrystrdup (fields[2]);
2178           /* '1' for cached */
2179           data->passphrase_cached = (fields[4][0] == '1');
2180           /* 'P' for protected, 'C' for clear */
2181           data->cleartext = (fields[5][0] == 'C');
2182           /* 'A' for card is available */
2183           data->card_available = (fields[8][0] == 'A');
2184         }
2185     }
2186   return 0;
2187 }
2188 
2189 
2190 /* Ask the agent whether a secret key for the given public key is
2191    available.  Returns 0 if not available.  Bigger value is preferred.  */
2192 int
agent_probe_secret_key(ctrl_t ctrl,PKT_public_key * pk)2193 agent_probe_secret_key (ctrl_t ctrl, PKT_public_key *pk)
2194 {
2195   gpg_error_t err;
2196   char line[ASSUAN_LINELENGTH];
2197   char *hexgrip;
2198 
2199   struct keyinfo_data_parm_s keyinfo;
2200 
2201   memset (&keyinfo, 0, sizeof keyinfo);
2202 
2203   err = start_agent (ctrl, 0);
2204   if (err)
2205     return err;
2206 
2207   err = hexkeygrip_from_pk (pk, &hexgrip);
2208   if (err)
2209     return err;
2210 
2211   snprintf (line, sizeof line, "KEYINFO %s", hexgrip);
2212   xfree (hexgrip);
2213 
2214   err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL,
2215                          keyinfo_status_cb, &keyinfo);
2216   xfree (keyinfo.serialno);
2217   if (err)
2218     return 0;
2219 
2220   if (keyinfo.card_available)
2221     return 4;
2222 
2223   if (keyinfo.passphrase_cached)
2224     return 3;
2225 
2226   if (keyinfo.is_smartcard)
2227     return 2;
2228 
2229   return 1;
2230 }
2231 
2232 /* Ask the agent whether a secret key is available for any of the
2233    keys (primary or sub) in KEYBLOCK.  Returns 0 if available.  */
2234 gpg_error_t
agent_probe_any_secret_key(ctrl_t ctrl,kbnode_t keyblock)2235 agent_probe_any_secret_key (ctrl_t ctrl, kbnode_t keyblock)
2236 {
2237   gpg_error_t err;
2238   char line[ASSUAN_LINELENGTH];
2239   char *p;
2240   kbnode_t kbctx, node;
2241   int nkeys;  /* (always zero in secret_keygrips mode)  */
2242   unsigned char grip[KEYGRIP_LEN];
2243   const unsigned char *s;
2244   unsigned int n;
2245 
2246   err = start_agent (ctrl, 0);
2247   if (err)
2248     return err;
2249 
2250   /* If we have not yet issued a "HAVEKEY --list" do that now.  We use
2251    * a more or less arbitray limit of 1000 keys.  */
2252   if (ctrl && !ctrl->secret_keygrips && !ctrl->no_more_secret_keygrips)
2253     {
2254       membuf_t data;
2255 
2256       init_membuf (&data, 4096);
2257       err = assuan_transact (agent_ctx, "HAVEKEY --list=1000",
2258                              put_membuf_cb, &data,
2259                              NULL, NULL, NULL, NULL);
2260       if (err)
2261         xfree (get_membuf (&data, NULL));
2262       else
2263         {
2264           ctrl->secret_keygrips = get_membuf (&data,
2265                                               &ctrl->secret_keygrips_len);
2266           if (!ctrl->secret_keygrips)
2267             err = gpg_error_from_syserror ();
2268           if ((ctrl->secret_keygrips_len % 20))
2269             {
2270               err = gpg_error (GPG_ERR_INV_DATA);
2271               xfree (ctrl->secret_keygrips);
2272               ctrl->secret_keygrips = NULL;
2273             }
2274         }
2275       if (err)
2276         {
2277           log_info ("problem with fast path key listing: %s - ignored\n",
2278                     gpg_strerror (err));
2279           err = 0;
2280         }
2281       /* We want to do this only once.  */
2282       ctrl->no_more_secret_keygrips = 1;
2283     }
2284 
2285   err = gpg_error (GPG_ERR_NO_SECKEY); /* Just in case no key was
2286                                           found in KEYBLOCK.  */
2287   p = stpcpy (line, "HAVEKEY");
2288   for (kbctx=NULL, nkeys=0; (node = walk_kbnode (keyblock, &kbctx, 0)); )
2289     if (node->pkt->pkttype == PKT_PUBLIC_KEY
2290         || node->pkt->pkttype == PKT_PUBLIC_SUBKEY
2291         || node->pkt->pkttype == PKT_SECRET_KEY
2292         || node->pkt->pkttype == PKT_SECRET_SUBKEY)
2293       {
2294         if (ctrl && ctrl->secret_keygrips)
2295           {
2296             /* We got an array with all secret keygrips.  Check this.  */
2297             err = keygrip_from_pk (node->pkt->pkt.public_key, grip);
2298             if (err)
2299               return err;
2300             for (s=ctrl->secret_keygrips, n = 0;
2301                  n < ctrl->secret_keygrips_len;
2302                  s += 20, n += 20)
2303               {
2304                 if (!memcmp (s, grip, 20))
2305                   return 0;
2306               }
2307             err = gpg_error (GPG_ERR_NO_SECKEY);
2308             /* Keep on looping over the keyblock.  Never bump nkeys.  */
2309           }
2310         else
2311           {
2312             if (nkeys && ((p - line) + 41) > (ASSUAN_LINELENGTH - 2))
2313               {
2314                 err = assuan_transact (agent_ctx, line,
2315                                        NULL, NULL, NULL, NULL, NULL, NULL);
2316                 if (err != gpg_err_code (GPG_ERR_NO_SECKEY))
2317                   break; /* Seckey available or unexpected error - ready.  */
2318                 p = stpcpy (line, "HAVEKEY");
2319                 nkeys = 0;
2320               }
2321 
2322             err = keygrip_from_pk (node->pkt->pkt.public_key, grip);
2323             if (err)
2324               return err;
2325             *p++ = ' ';
2326             bin2hex (grip, 20, p);
2327             p += 40;
2328             nkeys++;
2329           }
2330       }
2331 
2332   if (!err && nkeys)
2333     err = assuan_transact (agent_ctx, line,
2334                            NULL, NULL, NULL, NULL, NULL, NULL);
2335 
2336   return err;
2337 }
2338 
2339 
2340 
2341 /* Return the serial number for a secret key.  If the returned serial
2342    number is NULL, the key is not stored on a smartcard.  Caller needs
2343    to free R_SERIALNO.
2344 
2345    if r_cleartext is not NULL, the referenced int will be set to 1 if
2346    the agent's copy of the key is stored in the clear, or 0 otherwise
2347 */
2348 gpg_error_t
agent_get_keyinfo(ctrl_t ctrl,const char * hexkeygrip,char ** r_serialno,int * r_cleartext)2349 agent_get_keyinfo (ctrl_t ctrl, const char *hexkeygrip,
2350                    char **r_serialno, int *r_cleartext)
2351 {
2352   gpg_error_t err;
2353   char line[ASSUAN_LINELENGTH];
2354   struct keyinfo_data_parm_s keyinfo;
2355 
2356   memset (&keyinfo, 0,sizeof keyinfo);
2357 
2358   *r_serialno = NULL;
2359 
2360   err = start_agent (ctrl, 0);
2361   if (err)
2362     return err;
2363 
2364   if (!hexkeygrip || strlen (hexkeygrip) != 40)
2365     return gpg_error (GPG_ERR_INV_VALUE);
2366 
2367   snprintf (line, DIM(line), "KEYINFO %s", hexkeygrip);
2368 
2369   err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL,
2370                          keyinfo_status_cb, &keyinfo);
2371   if (!err && keyinfo.serialno)
2372     {
2373       /* Sanity check for bad characters.  */
2374       if (strpbrk (keyinfo.serialno, ":\n\r"))
2375         err = GPG_ERR_INV_VALUE;
2376     }
2377   if (err)
2378     xfree (keyinfo.serialno);
2379   else
2380     {
2381       *r_serialno = keyinfo.serialno;
2382       if (r_cleartext)
2383         *r_cleartext = keyinfo.cleartext;
2384     }
2385   return err;
2386 }
2387 
2388 
2389 /* Status callback for agent_import_key, agent_export_key and
2390    agent_genkey.  */
2391 static gpg_error_t
cache_nonce_status_cb(void * opaque,const char * line)2392 cache_nonce_status_cb (void *opaque, const char *line)
2393 {
2394   struct cache_nonce_parm_s *parm = opaque;
2395   const char *s;
2396 
2397   if ((s = has_leading_keyword (line, "CACHE_NONCE")))
2398     {
2399       if (parm->cache_nonce_addr)
2400         {
2401           xfree (*parm->cache_nonce_addr);
2402           *parm->cache_nonce_addr = xtrystrdup (s);
2403         }
2404     }
2405   else if ((s = has_leading_keyword (line, "PASSWD_NONCE")))
2406     {
2407       if (parm->passwd_nonce_addr)
2408         {
2409           xfree (*parm->passwd_nonce_addr);
2410           *parm->passwd_nonce_addr = xtrystrdup (s);
2411         }
2412     }
2413   else if ((s = has_leading_keyword (line, "PROGRESS")))
2414     {
2415       if (opt.enable_progress_filter)
2416         write_status_text (STATUS_PROGRESS, s);
2417     }
2418 
2419   return 0;
2420 }
2421 
2422 
2423 
2424 /* Handle a KEYPARMS inquiry.  Note, we only send the data,
2425    assuan_transact takes care of flushing and writing the end */
2426 static gpg_error_t
inq_genkey_parms(void * opaque,const char * line)2427 inq_genkey_parms (void *opaque, const char *line)
2428 {
2429   struct genkey_parm_s *parm = opaque;
2430   gpg_error_t err;
2431 
2432   if (has_leading_keyword (line, "KEYPARAM"))
2433     {
2434       err = assuan_send_data (parm->dflt->ctx,
2435                               parm->keyparms, strlen (parm->keyparms));
2436     }
2437   else if (has_leading_keyword (line, "NEWPASSWD") && parm->passphrase)
2438     {
2439       err = assuan_send_data (parm->dflt->ctx,
2440                               parm->passphrase,  strlen (parm->passphrase));
2441     }
2442   else
2443     err = default_inq_cb (parm->dflt, line);
2444 
2445   return err;
2446 }
2447 
2448 
2449 /* Call the agent to generate a new key.  KEYPARMS is the usual
2450    S-expression giving the parameters of the key.  gpg-agent passes it
2451    gcry_pk_genkey.  If NO_PROTECTION is true the agent is advised not
2452    to protect the generated key.  If NO_PROTECTION is not set and
2453    PASSPHRASE is not NULL the agent is requested to protect the key
2454    with that passphrase instead of asking for one.  TIMESTAMP is the
2455    creation time of the key or zero.  */
2456 gpg_error_t
agent_genkey(ctrl_t ctrl,char ** cache_nonce_addr,char ** passwd_nonce_addr,const char * keyparms,int no_protection,const char * passphrase,time_t timestamp,gcry_sexp_t * r_pubkey)2457 agent_genkey (ctrl_t ctrl, char **cache_nonce_addr, char **passwd_nonce_addr,
2458               const char *keyparms, int no_protection,
2459               const char *passphrase, time_t timestamp, gcry_sexp_t *r_pubkey)
2460 {
2461   gpg_error_t err;
2462   struct genkey_parm_s gk_parm;
2463   struct cache_nonce_parm_s cn_parm;
2464   struct default_inq_parm_s dfltparm;
2465   membuf_t data;
2466   size_t len;
2467   unsigned char *buf;
2468   char timestamparg[16 + 16];  /* The 2nd 16 is sizeof(gnupg_isotime_t) */
2469   char line[ASSUAN_LINELENGTH];
2470 
2471   memset (&dfltparm, 0, sizeof dfltparm);
2472   dfltparm.ctrl = ctrl;
2473 
2474   *r_pubkey = NULL;
2475   err = start_agent (ctrl, 0);
2476   if (err)
2477     return err;
2478   dfltparm.ctx = agent_ctx;
2479 
2480   /* Do not use our cache of secret keygrips anymore - this command
2481    * would otherwise requiring to update that cache.  */
2482   if (ctrl && ctrl->secret_keygrips)
2483     {
2484       xfree (ctrl->secret_keygrips);
2485       ctrl->secret_keygrips = 0;
2486     }
2487 
2488   if (timestamp)
2489     {
2490       strcpy (timestamparg, " --timestamp=");
2491       epoch2isotime (timestamparg+13, timestamp);
2492     }
2493   else
2494     *timestamparg = 0;
2495 
2496   if (passwd_nonce_addr && *passwd_nonce_addr)
2497     ; /* A RESET would flush the passwd nonce cache.  */
2498   else
2499     {
2500       err = assuan_transact (agent_ctx, "RESET",
2501                              NULL, NULL, NULL, NULL, NULL, NULL);
2502       if (err)
2503         return err;
2504     }
2505 
2506   init_membuf (&data, 1024);
2507   gk_parm.dflt     = &dfltparm;
2508   gk_parm.keyparms = keyparms;
2509   gk_parm.passphrase = passphrase;
2510   snprintf (line, sizeof line, "GENKEY%s%s%s%s%s%s",
2511             *timestamparg? timestamparg : "",
2512             no_protection? " --no-protection" :
2513             passphrase   ? " --inq-passwd" :
2514             /*          */ "",
2515             passwd_nonce_addr && *passwd_nonce_addr? " --passwd-nonce=":"",
2516             passwd_nonce_addr && *passwd_nonce_addr? *passwd_nonce_addr:"",
2517             cache_nonce_addr && *cache_nonce_addr? " ":"",
2518             cache_nonce_addr && *cache_nonce_addr? *cache_nonce_addr:"");
2519   cn_parm.cache_nonce_addr = cache_nonce_addr;
2520   cn_parm.passwd_nonce_addr = NULL;
2521   err = assuan_transact (agent_ctx, line,
2522                          put_membuf_cb, &data,
2523                          inq_genkey_parms, &gk_parm,
2524                          cache_nonce_status_cb, &cn_parm);
2525   if (err)
2526     {
2527       xfree (get_membuf (&data, &len));
2528       return err;
2529     }
2530 
2531   buf = get_membuf (&data, &len);
2532   if (!buf)
2533     err = gpg_error_from_syserror ();
2534   else
2535     {
2536       err = gcry_sexp_sscan (r_pubkey, NULL, buf, len);
2537       xfree (buf);
2538     }
2539   return err;
2540 }
2541 
2542 
2543 
2544 /* Call the agent to read the public key part for a given keygrip.
2545  * Values from FROMCARD:
2546  *   0 - Standard
2547  *   1 - The key is read from the current card
2548  *       via the agent and a stub file is created.
2549  */
2550 gpg_error_t
agent_readkey(ctrl_t ctrl,int fromcard,const char * hexkeygrip,unsigned char ** r_pubkey)2551 agent_readkey (ctrl_t ctrl, int fromcard, const char *hexkeygrip,
2552                unsigned char **r_pubkey)
2553 {
2554   gpg_error_t err;
2555   membuf_t data;
2556   size_t len;
2557   unsigned char *buf;
2558   char line[ASSUAN_LINELENGTH];
2559   struct default_inq_parm_s dfltparm;
2560 
2561   memset (&dfltparm, 0, sizeof dfltparm);
2562   dfltparm.ctrl = ctrl;
2563 
2564   *r_pubkey = NULL;
2565   err = start_agent (ctrl, 0);
2566   if (err)
2567     return err;
2568   dfltparm.ctx = agent_ctx;
2569 
2570   err = assuan_transact (agent_ctx, "RESET",NULL, NULL, NULL, NULL, NULL, NULL);
2571   if (err)
2572     return err;
2573 
2574   if (fromcard)
2575     snprintf (line, DIM(line), "READKEY --card -- %s", hexkeygrip);
2576   else
2577     snprintf (line, DIM(line), "READKEY -- %s", hexkeygrip);
2578 
2579   init_membuf (&data, 1024);
2580   err = assuan_transact (agent_ctx, line,
2581                          put_membuf_cb, &data,
2582                          default_inq_cb, &dfltparm,
2583                          NULL, NULL);
2584   if (err)
2585     {
2586       xfree (get_membuf (&data, &len));
2587       return err;
2588     }
2589   buf = get_membuf (&data, &len);
2590   if (!buf)
2591     return gpg_error_from_syserror ();
2592   if (!gcry_sexp_canon_len (buf, len, NULL, NULL))
2593     {
2594       xfree (buf);
2595       return gpg_error (GPG_ERR_INV_SEXP);
2596     }
2597   *r_pubkey = buf;
2598   return 0;
2599 }
2600 
2601 
2602 
2603 /* Call the agent to do a sign operation using the key identified by
2604    the hex string KEYGRIP.  DESC is a description of the key to be
2605    displayed if the agent needs to ask for the PIN.  DIGEST and
2606    DIGESTLEN is the hash value to sign and DIGESTALGO the algorithm id
2607    used to compute the digest.  If CACHE_NONCE is used the agent is
2608    advised to first try a passphrase associated with that nonce. */
2609 gpg_error_t
agent_pksign(ctrl_t ctrl,const char * cache_nonce,const char * keygrip,const char * desc,u32 * keyid,u32 * mainkeyid,int pubkey_algo,unsigned char * digest,size_t digestlen,int digestalgo,gcry_sexp_t * r_sigval)2610 agent_pksign (ctrl_t ctrl, const char *cache_nonce,
2611               const char *keygrip, const char *desc,
2612               u32 *keyid, u32 *mainkeyid, int pubkey_algo,
2613               unsigned char *digest, size_t digestlen, int digestalgo,
2614               gcry_sexp_t *r_sigval)
2615 {
2616   gpg_error_t err;
2617   char line[ASSUAN_LINELENGTH];
2618   membuf_t data;
2619   struct default_inq_parm_s dfltparm;
2620 
2621   memset (&dfltparm, 0, sizeof dfltparm);
2622   dfltparm.ctrl = ctrl;
2623   dfltparm.keyinfo.keyid       = keyid;
2624   dfltparm.keyinfo.mainkeyid   = mainkeyid;
2625   dfltparm.keyinfo.pubkey_algo = pubkey_algo;
2626 
2627   *r_sigval = NULL;
2628   err = start_agent (ctrl, 0);
2629   if (err)
2630     return err;
2631   dfltparm.ctx = agent_ctx;
2632 
2633   if (digestlen*2 + 50 > DIM(line))
2634     return gpg_error (GPG_ERR_GENERAL);
2635 
2636   err = assuan_transact (agent_ctx, "RESET",
2637                          NULL, NULL, NULL, NULL, NULL, NULL);
2638   if (err)
2639     return err;
2640 
2641   snprintf (line, DIM(line), "SIGKEY %s", keygrip);
2642   err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL);
2643   if (err)
2644     return err;
2645 
2646   if (desc)
2647     {
2648       snprintf (line, DIM(line), "SETKEYDESC %s", desc);
2649       err = assuan_transact (agent_ctx, line,
2650                             NULL, NULL, NULL, NULL, NULL, NULL);
2651       if (err)
2652         return err;
2653     }
2654 
2655   snprintf (line, sizeof line, "SETHASH %d ", digestalgo);
2656   bin2hex (digest, digestlen, line + strlen (line));
2657   err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL);
2658   if (err)
2659     return err;
2660 
2661   init_membuf (&data, 1024);
2662 
2663   snprintf (line, sizeof line, "PKSIGN%s%s",
2664             cache_nonce? " -- ":"",
2665             cache_nonce? cache_nonce:"");
2666 
2667   if (DBG_CLOCK)
2668     log_clock ("enter signing");
2669   err = assuan_transact (agent_ctx, line,
2670                          put_membuf_cb, &data,
2671                          default_inq_cb, &dfltparm,
2672                          NULL, NULL);
2673   if (DBG_CLOCK)
2674     log_clock ("leave signing");
2675 
2676   if (err)
2677     xfree (get_membuf (&data, NULL));
2678   else
2679     {
2680       unsigned char *buf;
2681       size_t len;
2682 
2683       buf = get_membuf (&data, &len);
2684       if (!buf)
2685         err = gpg_error_from_syserror ();
2686       else
2687         {
2688           err = gcry_sexp_sscan (r_sigval, NULL, buf, len);
2689           xfree (buf);
2690         }
2691     }
2692   return err;
2693 }
2694 
2695 
2696 
2697 /* Handle a CIPHERTEXT inquiry.  Note, we only send the data,
2698    assuan_transact takes care of flushing and writing the END. */
2699 static gpg_error_t
inq_ciphertext_cb(void * opaque,const char * line)2700 inq_ciphertext_cb (void *opaque, const char *line)
2701 {
2702   struct cipher_parm_s *parm = opaque;
2703   int rc;
2704 
2705   if (has_leading_keyword (line, "CIPHERTEXT"))
2706     {
2707       assuan_begin_confidential (parm->ctx);
2708       rc = assuan_send_data (parm->dflt->ctx,
2709                              parm->ciphertext, parm->ciphertextlen);
2710       assuan_end_confidential (parm->ctx);
2711     }
2712   else
2713     rc = default_inq_cb (parm->dflt, line);
2714 
2715   return rc;
2716 }
2717 
2718 
2719 /* Check whether there is any padding info from the agent.  */
2720 static gpg_error_t
padding_info_cb(void * opaque,const char * line)2721 padding_info_cb (void *opaque, const char *line)
2722 {
2723   int *r_padding = opaque;
2724   const char *s;
2725 
2726   if ((s=has_leading_keyword (line, "PADDING")))
2727     {
2728       *r_padding = atoi (s);
2729     }
2730 
2731   return 0;
2732 }
2733 
2734 
2735 /* Call the agent to do a decrypt operation using the key identified
2736    by the hex string KEYGRIP and the input data S_CIPHERTEXT.  On the
2737    success the decoded value is stored verbatim at R_BUF and its
2738    length at R_BUF; the callers needs to release it.  KEYID, MAINKEYID
2739    and PUBKEY_ALGO are used to construct additional promots or status
2740    messages.   The padding information is stored at R_PADDING with -1
2741    for not known.  */
2742 gpg_error_t
agent_pkdecrypt(ctrl_t ctrl,const char * keygrip,const char * desc,u32 * keyid,u32 * mainkeyid,int pubkey_algo,gcry_sexp_t s_ciphertext,unsigned char ** r_buf,size_t * r_buflen,int * r_padding)2743 agent_pkdecrypt (ctrl_t ctrl, const char *keygrip, const char *desc,
2744                  u32 *keyid, u32 *mainkeyid, int pubkey_algo,
2745                  gcry_sexp_t s_ciphertext,
2746                  unsigned char **r_buf, size_t *r_buflen, int *r_padding)
2747 {
2748   gpg_error_t err;
2749   char line[ASSUAN_LINELENGTH];
2750   membuf_t data;
2751   size_t n, len;
2752   char *p, *buf, *endp;
2753   struct default_inq_parm_s dfltparm;
2754 
2755   memset (&dfltparm, 0, sizeof dfltparm);
2756   dfltparm.ctrl = ctrl;
2757   dfltparm.keyinfo.keyid       = keyid;
2758   dfltparm.keyinfo.mainkeyid   = mainkeyid;
2759   dfltparm.keyinfo.pubkey_algo = pubkey_algo;
2760 
2761   if (!keygrip || strlen(keygrip) != 40
2762       || !s_ciphertext || !r_buf || !r_buflen || !r_padding)
2763     return gpg_error (GPG_ERR_INV_VALUE);
2764 
2765   *r_buf = NULL;
2766   *r_padding = -1;
2767 
2768   err = start_agent (ctrl, 0);
2769   if (err)
2770     return err;
2771   dfltparm.ctx = agent_ctx;
2772 
2773   err = assuan_transact (agent_ctx, "RESET",
2774                          NULL, NULL, NULL, NULL, NULL, NULL);
2775   if (err)
2776     return err;
2777 
2778   snprintf (line, sizeof line, "SETKEY %s", keygrip);
2779   err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL);
2780   if (err)
2781     return err;
2782 
2783   if (desc)
2784     {
2785       snprintf (line, DIM(line), "SETKEYDESC %s", desc);
2786       err = assuan_transact (agent_ctx, line,
2787                             NULL, NULL, NULL, NULL, NULL, NULL);
2788       if (err)
2789         return err;
2790     }
2791 
2792   init_membuf_secure (&data, 1024);
2793   {
2794     struct cipher_parm_s parm;
2795 
2796     parm.dflt = &dfltparm;
2797     parm.ctx = agent_ctx;
2798     err = make_canon_sexp (s_ciphertext, &parm.ciphertext, &parm.ciphertextlen);
2799     if (err)
2800       return err;
2801     err = assuan_transact (agent_ctx, "PKDECRYPT",
2802                            put_membuf_cb, &data,
2803                            inq_ciphertext_cb, &parm,
2804                            padding_info_cb, r_padding);
2805     xfree (parm.ciphertext);
2806   }
2807   if (err)
2808     {
2809       xfree (get_membuf (&data, &len));
2810       return err;
2811     }
2812 
2813   buf = get_membuf (&data, &len);
2814   if (!buf)
2815     return gpg_error_from_syserror ();
2816 
2817   if (len == 0 || *buf != '(')
2818     {
2819       xfree (buf);
2820       return gpg_error (GPG_ERR_INV_SEXP);
2821     }
2822 
2823   if (len < 12 || memcmp (buf, "(5:value", 8) ) /* "(5:valueN:D)" */
2824     {
2825       xfree (buf);
2826       return gpg_error (GPG_ERR_INV_SEXP);
2827     }
2828   while (buf[len-1] == 0)
2829     len--;
2830   if (buf[len-1] != ')')
2831     return gpg_error (GPG_ERR_INV_SEXP);
2832   len--; /* Drop the final close-paren. */
2833   p = buf + 8; /* Skip leading parenthesis and the value tag. */
2834   len -= 8;   /* Count only the data of the second part. */
2835 
2836   n = strtoul (p, &endp, 10);
2837   if (!n || *endp != ':')
2838     {
2839       xfree (buf);
2840       return gpg_error (GPG_ERR_INV_SEXP);
2841     }
2842   endp++;
2843   if (endp-p+n > len)
2844     {
2845       xfree (buf);
2846       return gpg_error (GPG_ERR_INV_SEXP); /* Oops: Inconsistent S-Exp. */
2847     }
2848 
2849   memmove (buf, endp, n);
2850 
2851   *r_buflen = n;
2852   *r_buf = buf;
2853   return 0;
2854 }
2855 
2856 
2857 
2858 /* Retrieve a key encryption key from the agent.  With FOREXPORT true
2859    the key shall be used for export, with false for import.  On success
2860    the new key is stored at R_KEY and its length at R_KEKLEN.  */
2861 gpg_error_t
agent_keywrap_key(ctrl_t ctrl,int forexport,void ** r_kek,size_t * r_keklen)2862 agent_keywrap_key (ctrl_t ctrl, int forexport, void **r_kek, size_t *r_keklen)
2863 {
2864   gpg_error_t err;
2865   membuf_t data;
2866   size_t len;
2867   unsigned char *buf;
2868   char line[ASSUAN_LINELENGTH];
2869   struct default_inq_parm_s dfltparm;
2870 
2871   memset (&dfltparm, 0, sizeof dfltparm);
2872   dfltparm.ctrl = ctrl;
2873 
2874   *r_kek = NULL;
2875   err = start_agent (ctrl, 0);
2876   if (err)
2877     return err;
2878   dfltparm.ctx = agent_ctx;
2879 
2880   snprintf (line, DIM(line), "KEYWRAP_KEY %s",
2881             forexport? "--export":"--import");
2882 
2883   init_membuf_secure (&data, 64);
2884   err = assuan_transact (agent_ctx, line,
2885                          put_membuf_cb, &data,
2886                          default_inq_cb, &dfltparm,
2887                          NULL, NULL);
2888   if (err)
2889     {
2890       xfree (get_membuf (&data, &len));
2891       return err;
2892     }
2893   buf = get_membuf (&data, &len);
2894   if (!buf)
2895     return gpg_error_from_syserror ();
2896   *r_kek = buf;
2897   *r_keklen = len;
2898   return 0;
2899 }
2900 
2901 
2902 
2903 /* Handle the inquiry for an IMPORT_KEY command.  */
2904 static gpg_error_t
inq_import_key_parms(void * opaque,const char * line)2905 inq_import_key_parms (void *opaque, const char *line)
2906 {
2907   struct import_key_parm_s *parm = opaque;
2908   gpg_error_t err;
2909 
2910   if (has_leading_keyword (line, "KEYDATA"))
2911     {
2912       err = assuan_send_data (parm->dflt->ctx, parm->key, parm->keylen);
2913     }
2914   else
2915     err = default_inq_cb (parm->dflt, line);
2916 
2917   return err;
2918 }
2919 
2920 
2921 /* Call the agent to import a key into the agent.  */
2922 gpg_error_t
agent_import_key(ctrl_t ctrl,const char * desc,char ** cache_nonce_addr,const void * key,size_t keylen,int unattended,int force,u32 * keyid,u32 * mainkeyid,int pubkey_algo,u32 timestamp)2923 agent_import_key (ctrl_t ctrl, const char *desc, char **cache_nonce_addr,
2924                   const void *key, size_t keylen, int unattended, int force,
2925 		  u32 *keyid, u32 *mainkeyid, int pubkey_algo, u32 timestamp)
2926 {
2927   gpg_error_t err;
2928   struct import_key_parm_s parm;
2929   struct cache_nonce_parm_s cn_parm;
2930   char timestamparg[16 + 16];  /* The 2nd 16 is sizeof(gnupg_isotime_t) */
2931   char line[ASSUAN_LINELENGTH];
2932   struct default_inq_parm_s dfltparm;
2933 
2934   memset (&dfltparm, 0, sizeof dfltparm);
2935   dfltparm.ctrl = ctrl;
2936   dfltparm.keyinfo.keyid       = keyid;
2937   dfltparm.keyinfo.mainkeyid   = mainkeyid;
2938   dfltparm.keyinfo.pubkey_algo = pubkey_algo;
2939 
2940   err = start_agent (ctrl, 0);
2941   if (err)
2942     return err;
2943   dfltparm.ctx = agent_ctx;
2944 
2945   /* Do not use our cache of secret keygrips anymore - this command
2946    * would otherwise requiring to update that cache.  */
2947   if (ctrl && ctrl->secret_keygrips)
2948     {
2949       xfree (ctrl->secret_keygrips);
2950       ctrl->secret_keygrips = 0;
2951     }
2952 
2953   if (timestamp)
2954     {
2955       strcpy (timestamparg, " --timestamp=");
2956       epoch2isotime (timestamparg+13, timestamp);
2957     }
2958   else
2959     *timestamparg = 0;
2960 
2961   if (desc)
2962     {
2963       snprintf (line, DIM(line), "SETKEYDESC %s", desc);
2964       err = assuan_transact (agent_ctx, line,
2965                             NULL, NULL, NULL, NULL, NULL, NULL);
2966       if (err)
2967         return err;
2968     }
2969 
2970   parm.dflt   = &dfltparm;
2971   parm.key    = key;
2972   parm.keylen = keylen;
2973 
2974   snprintf (line, sizeof line, "IMPORT_KEY%s%s%s%s%s",
2975             *timestamparg? timestamparg : "",
2976             unattended? " --unattended":"",
2977             force? " --force":"",
2978             cache_nonce_addr && *cache_nonce_addr? " ":"",
2979             cache_nonce_addr && *cache_nonce_addr? *cache_nonce_addr:"");
2980   cn_parm.cache_nonce_addr = cache_nonce_addr;
2981   cn_parm.passwd_nonce_addr = NULL;
2982   err = assuan_transact (agent_ctx, line,
2983                          NULL, NULL,
2984                          inq_import_key_parms, &parm,
2985                          cache_nonce_status_cb, &cn_parm);
2986   return err;
2987 }
2988 
2989 
2990 
2991 /* Receive a secret key from the agent.  HEXKEYGRIP is the hexified
2992    keygrip, DESC a prompt to be displayed with the agent's passphrase
2993    question (needs to be plus+percent escaped).  if OPENPGP_PROTECTED
2994    is not zero, ensure that the key material is returned in RFC
2995    4880-compatible passphrased-protected form.  If CACHE_NONCE_ADDR is
2996    not NULL the agent is advised to first try a passphrase associated
2997    with that nonce.  On success the key is stored as a canonical
2998    S-expression at R_RESULT and R_RESULTLEN.  */
2999 gpg_error_t
agent_export_key(ctrl_t ctrl,const char * hexkeygrip,const char * desc,int openpgp_protected,char ** cache_nonce_addr,unsigned char ** r_result,size_t * r_resultlen,u32 * keyid,u32 * mainkeyid,int pubkey_algo)3000 agent_export_key (ctrl_t ctrl, const char *hexkeygrip, const char *desc,
3001                   int openpgp_protected, char **cache_nonce_addr,
3002                   unsigned char **r_result, size_t *r_resultlen,
3003 		  u32 *keyid, u32 *mainkeyid, int pubkey_algo)
3004 {
3005   gpg_error_t err;
3006   struct cache_nonce_parm_s cn_parm;
3007   membuf_t data;
3008   size_t len;
3009   unsigned char *buf;
3010   char line[ASSUAN_LINELENGTH];
3011   struct default_inq_parm_s dfltparm;
3012 
3013   memset (&dfltparm, 0, sizeof dfltparm);
3014   dfltparm.ctrl = ctrl;
3015   dfltparm.keyinfo.keyid       = keyid;
3016   dfltparm.keyinfo.mainkeyid   = mainkeyid;
3017   dfltparm.keyinfo.pubkey_algo = pubkey_algo;
3018 
3019   *r_result = NULL;
3020 
3021   err = start_agent (ctrl, 0);
3022   if (err)
3023     return err;
3024   dfltparm.ctx = agent_ctx;
3025 
3026   if (desc)
3027     {
3028       snprintf (line, DIM(line), "SETKEYDESC %s", desc);
3029       err = assuan_transact (agent_ctx, line,
3030                              NULL, NULL, NULL, NULL, NULL, NULL);
3031       if (err)
3032         return err;
3033     }
3034 
3035   snprintf (line, DIM(line), "EXPORT_KEY %s%s%s %s",
3036             openpgp_protected ? "--openpgp ":"",
3037             cache_nonce_addr && *cache_nonce_addr? "--cache-nonce=":"",
3038             cache_nonce_addr && *cache_nonce_addr? *cache_nonce_addr:"",
3039             hexkeygrip);
3040 
3041   init_membuf_secure (&data, 1024);
3042   cn_parm.cache_nonce_addr = cache_nonce_addr;
3043   cn_parm.passwd_nonce_addr = NULL;
3044   err = assuan_transact (agent_ctx, line,
3045                          put_membuf_cb, &data,
3046                          default_inq_cb, &dfltparm,
3047                          cache_nonce_status_cb, &cn_parm);
3048   if (err)
3049     {
3050       xfree (get_membuf (&data, &len));
3051       return err;
3052     }
3053   buf = get_membuf (&data, &len);
3054   if (!buf)
3055     return gpg_error_from_syserror ();
3056   *r_result = buf;
3057   *r_resultlen = len;
3058   return 0;
3059 }
3060 
3061 
3062 /* Status callback for handling confirmation.  */
3063 static gpg_error_t
confirm_status_cb(void * opaque,const char * line)3064 confirm_status_cb (void *opaque, const char *line)
3065 {
3066   struct confirm_parm_s *parm = opaque;
3067   const char *s;
3068 
3069   if ((s = has_leading_keyword (line, "SETDESC")))
3070     {
3071       xfree (parm->desc);
3072       parm->desc = unescape_status_string (s);
3073     }
3074   else if ((s = has_leading_keyword (line, "SETOK")))
3075     {
3076       xfree (parm->ok);
3077       parm->ok = unescape_status_string (s);
3078     }
3079   else if ((s = has_leading_keyword (line, "SETNOTOK")))
3080     {
3081       xfree (parm->notok);
3082       parm->notok = unescape_status_string (s);
3083     }
3084 
3085   return 0;
3086 }
3087 
3088 /* Ask the agent to delete the key identified by HEXKEYGRIP.  If DESC
3089    is not NULL, display DESC instead of the default description
3090    message.  If FORCE is true the agent is advised not to ask for
3091    confirmation. */
3092 gpg_error_t
agent_delete_key(ctrl_t ctrl,const char * hexkeygrip,const char * desc,int force)3093 agent_delete_key (ctrl_t ctrl, const char *hexkeygrip, const char *desc,
3094                   int force)
3095 {
3096   gpg_error_t err;
3097   char line[ASSUAN_LINELENGTH];
3098   struct default_inq_parm_s dfltparm;
3099   struct confirm_parm_s confirm_parm;
3100 
3101   memset (&confirm_parm, 0, sizeof confirm_parm);
3102   memset (&dfltparm, 0, sizeof dfltparm);
3103   dfltparm.ctrl = ctrl;
3104   dfltparm.confirm = &confirm_parm;
3105 
3106   err = start_agent (ctrl, 0);
3107   if (err)
3108     return err;
3109   dfltparm.ctx = agent_ctx;
3110 
3111   if (!hexkeygrip || strlen (hexkeygrip) != 40)
3112     return gpg_error (GPG_ERR_INV_VALUE);
3113 
3114   if (desc)
3115     {
3116       snprintf (line, DIM(line), "SETKEYDESC %s", desc);
3117       err = assuan_transact (agent_ctx, line,
3118                              NULL, NULL, NULL, NULL, NULL, NULL);
3119       if (err)
3120         return err;
3121     }
3122 
3123   snprintf (line, DIM(line), "DELETE_KEY%s %s",
3124             force? " --force":"", hexkeygrip);
3125   err = assuan_transact (agent_ctx, line, NULL, NULL,
3126                          default_inq_cb, &dfltparm,
3127                          confirm_status_cb, &confirm_parm);
3128   xfree (confirm_parm.desc);
3129   xfree (confirm_parm.ok);
3130   xfree (confirm_parm.notok);
3131   return err;
3132 }
3133 
3134 
3135 
3136 /* Ask the agent to change the passphrase of the key identified by
3137  * HEXKEYGRIP.  If DESC is not NULL, display DESC instead of the
3138  * default description message.  If CACHE_NONCE_ADDR is not NULL the
3139  * agent is advised to first try a passphrase associated with that
3140  * nonce.  If PASSWD_NONCE_ADDR is not NULL the agent will try to use
3141  * the passphrase associated with that nonce for the new passphrase.
3142  * If VERIFY is true the passphrase is only verified.  */
3143 gpg_error_t
agent_passwd(ctrl_t ctrl,const char * hexkeygrip,const char * desc,int verify,char ** cache_nonce_addr,char ** passwd_nonce_addr)3144 agent_passwd (ctrl_t ctrl, const char *hexkeygrip, const char *desc, int verify,
3145               char **cache_nonce_addr, char **passwd_nonce_addr)
3146 {
3147   gpg_error_t err;
3148   struct cache_nonce_parm_s cn_parm;
3149   char line[ASSUAN_LINELENGTH];
3150   struct default_inq_parm_s dfltparm;
3151 
3152   memset (&dfltparm, 0, sizeof dfltparm);
3153   dfltparm.ctrl = ctrl;
3154 
3155   err = start_agent (ctrl, 0);
3156   if (err)
3157     return err;
3158   dfltparm.ctx = agent_ctx;
3159 
3160   if (!hexkeygrip || strlen (hexkeygrip) != 40)
3161     return gpg_error (GPG_ERR_INV_VALUE);
3162 
3163   if (desc)
3164     {
3165       snprintf (line, DIM(line), "SETKEYDESC %s", desc);
3166       err = assuan_transact (agent_ctx, line,
3167                              NULL, NULL, NULL, NULL, NULL, NULL);
3168       if (err)
3169         return err;
3170     }
3171 
3172   if (verify)
3173     snprintf (line, DIM(line), "PASSWD %s%s --verify %s",
3174               cache_nonce_addr && *cache_nonce_addr? "--cache-nonce=":"",
3175               cache_nonce_addr && *cache_nonce_addr? *cache_nonce_addr:"",
3176               hexkeygrip);
3177   else
3178     snprintf (line, DIM(line), "PASSWD %s%s %s%s %s",
3179               cache_nonce_addr && *cache_nonce_addr? "--cache-nonce=":"",
3180               cache_nonce_addr && *cache_nonce_addr? *cache_nonce_addr:"",
3181               passwd_nonce_addr && *passwd_nonce_addr? "--passwd-nonce=":"",
3182               passwd_nonce_addr && *passwd_nonce_addr? *passwd_nonce_addr:"",
3183               hexkeygrip);
3184   cn_parm.cache_nonce_addr = cache_nonce_addr;
3185   cn_parm.passwd_nonce_addr = passwd_nonce_addr;
3186   err = assuan_transact (agent_ctx, line, NULL, NULL,
3187                          default_inq_cb, &dfltparm,
3188                          cache_nonce_status_cb, &cn_parm);
3189   return err;
3190 }
3191 
3192 
3193 /* Return the version reported by gpg-agent.  */
3194 gpg_error_t
agent_get_version(ctrl_t ctrl,char ** r_version)3195 agent_get_version (ctrl_t ctrl, char **r_version)
3196 {
3197   gpg_error_t err;
3198 
3199   err = start_agent (ctrl, 0);
3200   if (err)
3201     return err;
3202 
3203   err = get_assuan_server_version (agent_ctx, 0, r_version);
3204   return err;
3205 }
3206