c94fdd37abaec84ff3b6b7181385e0e999ec6a3d
[platform/upstream/gpg2.git] / agent / command.c
1 /* command.c - gpg-agent command handler
2  * Copyright (C) 2001-2011 Free Software Foundation, Inc.
3  * Copyright (C) 2001-2013 Werner Koch
4  * Copyright (C) 2015 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 <http://www.gnu.org/licenses/>.
20  */
21
22 /* FIXME: we should not use the default assuan buffering but setup
23    some buffering in secure mempory to protect session keys etc. */
24
25 #include <config.h>
26
27 #include <errno.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <ctype.h>
32 #include <unistd.h>
33 #include <assert.h>
34 #include <sys/types.h>
35 #include <sys/stat.h>
36 #include <dirent.h>
37
38 #include "agent.h"
39 #include <assuan.h>
40 #include "i18n.h"
41 #include "cvt-openpgp.h"
42 #include "../common/ssh-utils.h"
43 #include "../common/asshelp.h"
44 #include "../common/server-help.h"
45
46
47 /* Maximum allowed size of the inquired ciphertext.  */
48 #define MAXLEN_CIPHERTEXT 4096
49 /* Maximum allowed size of the key parameters.  */
50 #define MAXLEN_KEYPARAM 1024
51 /* Maximum allowed size of key data as used in inquiries (bytes). */
52 #define MAXLEN_KEYDATA 4096
53 /* The size of the import/export KEK key (in bytes).  */
54 #define KEYWRAP_KEYSIZE (128/8)
55
56 /* A shortcut to call assuan_set_error using an gpg_err_code_t and a
57    text string.  */
58 #define set_error(e,t) assuan_set_error (ctx, gpg_error (e), (t))
59
60 /* Check that the maximum digest length we support has at least the
61    length of the keygrip.  */
62 #if MAX_DIGEST_LEN < 20
63 #error MAX_DIGEST_LEN shorter than keygrip
64 #endif
65
66 /* Data used to associate an Assuan context with local server data.
67    This is this modules local part of the server_control_s struct.  */
68 struct server_local_s
69 {
70   /* Our Assuan context.  */
71   assuan_context_t assuan_ctx;
72
73   /* If this flag is true, the passphrase cache is used for signing
74      operations.  It defaults to true but may be set on a per
75      connection base.  The global option opt.ignore_cache_for_signing
76      takes precedence over this flag.  */
77   int use_cache_for_signing;
78
79   /* An allocated description for the next key operation.  This is
80      used if a pinnetry needs to be popped up.  */
81   char *keydesc;
82
83   /* Flags to suppress I/O logging during a command.  */
84   int pause_io_logging;
85
86   /* If this flags is set to true the agent will be terminated after
87      the end of the current session.  */
88   int stopme;
89
90   /* Flag indicating whether pinentry notifications shall be done. */
91   int allow_pinentry_notify;
92
93   /* Malloced KEK (Key-Encryption-Key) for the import_key command.  */
94   void *import_key;
95
96   /* Malloced KEK for the export_key command.  */
97   void *export_key;
98
99   /* Client is aware of the error code GPG_ERR_FULLY_CANCELED.  */
100   int allow_fully_canceled;
101
102   /* Last CACHE_NONCE sent as status (malloced).  */
103   char *last_cache_nonce;
104
105   /* Last PASSWD_NONCE sent as status (malloced). */
106   char *last_passwd_nonce;
107 };
108
109
110 /* An entry for the getval/putval commands. */
111 struct putval_item_s
112 {
113   struct putval_item_s *next;
114   size_t off;  /* Offset to the value into DATA.  */
115   size_t len;  /* Length of the value.  */
116   char d[1];   /* Key | Nul | value.  */
117 };
118
119
120 /* A list of key value pairs fpr the getval/putval commands.  */
121 static struct putval_item_s *putval_list;
122
123
124 \f
125 /* To help polling clients, we keep track of the number of certain
126    events.  This structure keeps those counters.  The counters are
127    integers and there should be no problem if they are overflowing as
128    callers need to check only whether a counter changed.  The actual
129    values are not meaningful. */
130 struct
131 {
132   /* Incremented if any of the other counters below changed. */
133   unsigned int any;
134
135   /* Incremented if a key is added or removed from the internal privat
136      key database. */
137   unsigned int key;
138
139   /* Incremented if a change of the card readers stati has been
140      detected. */
141   unsigned int card;
142
143 } eventcounter;
144
145
146 \f
147 /*  Local prototypes.  */
148 static int command_has_option (const char *cmd, const char *cmdopt);
149
150
151
152 \f
153 /* Release the memory buffer MB but first wipe out the used memory. */
154 static void
155 clear_outbuf (membuf_t *mb)
156 {
157   void *p;
158   size_t n;
159
160   p = get_membuf (mb, &n);
161   if (p)
162     {
163       wipememory (p, n);
164       xfree (p);
165     }
166 }
167
168
169 /* Write the content of memory buffer MB as assuan data to CTX and
170    wipe the buffer out afterwards. */
171 static gpg_error_t
172 write_and_clear_outbuf (assuan_context_t ctx, membuf_t *mb)
173 {
174   gpg_error_t ae;
175   void *p;
176   size_t n;
177
178   p = get_membuf (mb, &n);
179   if (!p)
180     return out_of_core ();
181   ae = assuan_send_data (ctx, p, n);
182   memset (p, 0, n);
183   xfree (p);
184   return ae;
185 }
186
187
188 /* Clear the nonces used to enable the passphrase cache for certain
189    multi-command command sequences.  */
190 static void
191 clear_nonce_cache (ctrl_t ctrl)
192 {
193   if (ctrl->server_local->last_cache_nonce)
194     {
195       agent_put_cache (ctrl->server_local->last_cache_nonce,
196                        CACHE_MODE_NONCE, NULL, 0);
197       xfree (ctrl->server_local->last_cache_nonce);
198       ctrl->server_local->last_cache_nonce = NULL;
199     }
200   if (ctrl->server_local->last_passwd_nonce)
201     {
202       agent_put_cache (ctrl->server_local->last_passwd_nonce,
203                        CACHE_MODE_NONCE, NULL, 0);
204       xfree (ctrl->server_local->last_passwd_nonce);
205       ctrl->server_local->last_passwd_nonce = NULL;
206     }
207 }
208
209
210 /* This function is called by Libassuan whenever thee client sends a
211    reset.  It has been registered similar to the other Assuan
212    commands.  */
213 static gpg_error_t
214 reset_notify (assuan_context_t ctx, char *line)
215 {
216   ctrl_t ctrl = assuan_get_pointer (ctx);
217
218   (void) line;
219
220   memset (ctrl->keygrip, 0, 20);
221   ctrl->have_keygrip = 0;
222   ctrl->digest.valuelen = 0;
223
224   xfree (ctrl->server_local->keydesc);
225   ctrl->server_local->keydesc = NULL;
226
227   clear_nonce_cache (ctrl);
228
229   return 0;
230 }
231
232
233 /* Replace all '+' by a blank in the string S. */
234 static void
235 plus_to_blank (char *s)
236 {
237   for (; *s; s++)
238     {
239       if (*s == '+')
240         *s = ' ';
241     }
242 }
243
244
245 /* Parse a hex string.  Return an Assuan error code or 0 on success and the
246    length of the parsed string in LEN. */
247 static int
248 parse_hexstring (assuan_context_t ctx, const char *string, size_t *len)
249 {
250   const char *p;
251   size_t n;
252
253   /* parse the hash value */
254   for (p=string, n=0; hexdigitp (p); p++, n++)
255     ;
256   if (*p != ' ' && *p != '\t' && *p)
257     return set_error (GPG_ERR_ASS_PARAMETER, "invalid hexstring");
258   if ((n&1))
259     return set_error (GPG_ERR_ASS_PARAMETER, "odd number of digits");
260   *len = n;
261   return 0;
262 }
263
264
265 /* Parse the keygrip in STRING into the provided buffer BUF.  BUF must
266    provide space for 20 bytes.  BUF is not changed if the function
267    returns an error. */
268 static int
269 parse_keygrip (assuan_context_t ctx, const char *string, unsigned char *buf)
270 {
271   int rc;
272   size_t n = 0;
273
274   rc = parse_hexstring (ctx, string, &n);
275   if (rc)
276     return rc;
277   n /= 2;
278   if (n != 20)
279     return set_error (GPG_ERR_ASS_PARAMETER, "invalid length of keygrip");
280
281   if (hex2bin (string, buf, 20) < 0)
282     return set_error (GPG_ERR_BUG, "hex2bin");
283
284   return 0;
285 }
286
287
288 /* Write an Assuan status line.  KEYWORD is the first item on the
289    status line.  The following arguments are all separated by a space
290    in the output.  The last argument must be a NULL.  Linefeeds and
291    carriage returns characters (which are not allowed in an Assuan
292    status line) are silently quoted in C-style.  */
293 gpg_error_t
294 agent_write_status (ctrl_t ctrl, const char *keyword, ...)
295 {
296   gpg_error_t err = 0;
297   va_list arg_ptr;
298   const char *text;
299   assuan_context_t ctx = ctrl->server_local->assuan_ctx;
300   char buf[950], *p;
301   size_t n;
302
303   va_start (arg_ptr, keyword);
304
305   p = buf;
306   n = 0;
307   while ( (text = va_arg (arg_ptr, const char *)) )
308     {
309       if (n)
310         {
311           *p++ = ' ';
312           n++;
313         }
314       for ( ; *text && n < DIM (buf)-3; n++, text++)
315         {
316           if (*text == '\n')
317             {
318               *p++ = '\\';
319               *p++ = 'n';
320             }
321           else if (*text == '\r')
322             {
323               *p++ = '\\';
324               *p++ = 'r';
325             }
326           else
327             *p++ = *text;
328         }
329     }
330   *p = 0;
331   err = assuan_write_status (ctx, keyword, buf);
332
333   va_end (arg_ptr);
334   return err;
335 }
336
337
338 /* This function is similar to print_assuan_status but takes a CTRL
339    arg instead of an assuan context as first argument.  */
340 gpg_error_t
341 agent_print_status (ctrl_t ctrl, const char *keyword, const char *format, ...)
342 {
343   gpg_error_t err;
344   va_list arg_ptr;
345   assuan_context_t ctx = ctrl->server_local->assuan_ctx;
346
347   va_start (arg_ptr, format);
348   err = vprint_assuan_status (ctx, keyword, format, arg_ptr);
349   va_end (arg_ptr);
350   return err;
351 }
352
353
354 /* Helper to notify the client about a launched Pinentry.  Because
355    that might disturb some older clients, this is only done if enabled
356    via an option.  Returns an gpg error code. */
357 gpg_error_t
358 agent_inq_pinentry_launched (ctrl_t ctrl, unsigned long pid)
359 {
360   char line[100];
361
362   if (!ctrl || !ctrl->server_local
363       || !ctrl->server_local->allow_pinentry_notify)
364     return 0;
365   snprintf (line, DIM(line)-1, "PINENTRY_LAUNCHED %lu", pid);
366   return assuan_inquire (ctrl->server_local->assuan_ctx, line, NULL, NULL, 0);
367 }
368
369
370 /* An agent progress callback for Libgcrypt.  This has been registered
371  * to be called via the progress dispatcher mechanism from
372  * gpg-agent.c  */
373 static void
374 progress_cb (ctrl_t ctrl, const char *what, int printchar,
375              int current, int total)
376 {
377   if (!ctrl || !ctrl->server_local || !ctrl->server_local->assuan_ctx)
378     ;
379   else if (printchar == '\n' && what && !strcmp (what, "primegen"))
380     agent_print_status (ctrl, "PROGRESS", "%.20s X 100 100", what);
381   else
382     agent_print_status (ctrl, "PROGRESS", "%.20s %c %d %d",
383                         what, printchar=='\n'?'X':printchar, current, total);
384 }
385
386
387 /* Helper to print a message while leaving a command.  */
388 static gpg_error_t
389 leave_cmd (assuan_context_t ctx, gpg_error_t err)
390 {
391   if (err)
392     {
393       const char *name = assuan_get_command_name (ctx);
394       if (!name)
395         name = "?";
396
397       /* Not all users of gpg-agent know about the fully canceled
398          error code; map it back if needed.  */
399       if (gpg_err_code (err) == GPG_ERR_FULLY_CANCELED)
400         {
401           ctrl_t ctrl = assuan_get_pointer (ctx);
402
403           if (!ctrl->server_local->allow_fully_canceled)
404             err = gpg_err_make (gpg_err_source (err), GPG_ERR_CANCELED);
405         }
406
407       /* Most code from common/ does not know the error source, thus
408          we fix this here.  */
409       if (gpg_err_source (err) == GPG_ERR_SOURCE_UNKNOWN)
410         err = gpg_err_make (GPG_ERR_SOURCE_DEFAULT, gpg_err_code (err));
411
412       if (gpg_err_source (err) == GPG_ERR_SOURCE_DEFAULT)
413         log_error ("command '%s' failed: %s\n", name,
414                    gpg_strerror (err));
415       else
416         log_error ("command '%s' failed: %s <%s>\n", name,
417                    gpg_strerror (err), gpg_strsource (err));
418     }
419   return err;
420 }
421
422
423 \f
424 static const char hlp_geteventcounter[] =
425   "GETEVENTCOUNTER\n"
426   "\n"
427   "Return a a status line named EVENTCOUNTER with the current values\n"
428   "of all event counters.  The values are decimal numbers in the range\n"
429   "0 to UINT_MAX and wrapping around to 0.  The actual values should\n"
430   "not be relied upon, they shall only be used to detect a change.\n"
431   "\n"
432   "The currently defined counters are:\n"
433   "\n"
434   "ANY  - Incremented with any change of any of the other counters.\n"
435   "KEY  - Incremented for added or removed private keys.\n"
436   "CARD - Incremented for changes of the card readers stati.";
437 static gpg_error_t
438 cmd_geteventcounter (assuan_context_t ctx, char *line)
439 {
440   ctrl_t ctrl = assuan_get_pointer (ctx);
441
442   (void)line;
443
444   if (ctrl->restricted)
445     return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
446
447   return agent_print_status (ctrl, "EVENTCOUNTER", "%u %u %u",
448                              eventcounter.any,
449                              eventcounter.key,
450                              eventcounter.card);
451 }
452
453
454 /* This function should be called once for all key removals or
455    additions.  This function is assured not to do any context
456    switches. */
457 void
458 bump_key_eventcounter (void)
459 {
460   eventcounter.key++;
461   eventcounter.any++;
462 }
463
464
465 /* This function should be called for all card reader status
466    changes.  This function is assured not to do any context
467    switches. */
468 void
469 bump_card_eventcounter (void)
470 {
471   eventcounter.card++;
472   eventcounter.any++;
473 }
474
475
476
477 \f
478 static const char hlp_istrusted[] =
479   "ISTRUSTED <hexstring_with_fingerprint>\n"
480   "\n"
481   "Return OK when we have an entry with this fingerprint in our\n"
482   "trustlist";
483 static gpg_error_t
484 cmd_istrusted (assuan_context_t ctx, char *line)
485 {
486   ctrl_t ctrl = assuan_get_pointer (ctx);
487   int rc, n, i;
488   char *p;
489   char fpr[41];
490
491   /* Parse the fingerprint value. */
492   for (p=line,n=0; hexdigitp (p); p++, n++)
493     ;
494   if (*p || !(n == 40 || n == 32))
495     return set_error (GPG_ERR_ASS_PARAMETER, "invalid fingerprint");
496   i = 0;
497   if (n==32)
498     {
499       strcpy (fpr, "00000000");
500       i += 8;
501     }
502   for (p=line; i < 40; p++, i++)
503     fpr[i] = *p >= 'a'? (*p & 0xdf): *p;
504   fpr[i] = 0;
505   rc = agent_istrusted (ctrl, fpr, NULL);
506   if (!rc || gpg_err_code (rc) == GPG_ERR_NOT_TRUSTED)
507     return rc;
508   else if (rc == -1 || gpg_err_code (rc) == GPG_ERR_EOF )
509     return gpg_error (GPG_ERR_NOT_TRUSTED);
510   else
511     return leave_cmd (ctx, rc);
512 }
513
514
515 static const char hlp_listtrusted[] =
516   "LISTTRUSTED\n"
517   "\n"
518   "List all entries from the trustlist.";
519 static gpg_error_t
520 cmd_listtrusted (assuan_context_t ctx, char *line)
521 {
522   ctrl_t ctrl = assuan_get_pointer (ctx);
523   int rc;
524
525   (void)line;
526
527   if (ctrl->restricted)
528     return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
529
530   rc = agent_listtrusted (ctx);
531   return leave_cmd (ctx, rc);
532 }
533
534
535 static const char hlp_martrusted[] =
536   "MARKTRUSTED <hexstring_with_fingerprint> <flag> <display_name>\n"
537   "\n"
538   "Store a new key in into the trustlist.";
539 static gpg_error_t
540 cmd_marktrusted (assuan_context_t ctx, char *line)
541 {
542   ctrl_t ctrl = assuan_get_pointer (ctx);
543   int rc, n, i;
544   char *p;
545   char fpr[41];
546   int flag;
547
548   if (ctrl->restricted)
549     return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
550
551   /* parse the fingerprint value */
552   for (p=line,n=0; hexdigitp (p); p++, n++)
553     ;
554   if (!spacep (p) || !(n == 40 || n == 32))
555     return set_error (GPG_ERR_ASS_PARAMETER, "invalid fingerprint");
556   i = 0;
557   if (n==32)
558     {
559       strcpy (fpr, "00000000");
560       i += 8;
561     }
562   for (p=line; i < 40; p++, i++)
563     fpr[i] = *p >= 'a'? (*p & 0xdf): *p;
564   fpr[i] = 0;
565
566   while (spacep (p))
567     p++;
568   flag = *p++;
569   if ( (flag != 'S' && flag != 'P') || !spacep (p) )
570     return set_error (GPG_ERR_ASS_PARAMETER, "invalid flag - must be P or S");
571   while (spacep (p))
572     p++;
573
574   rc = agent_marktrusted (ctrl, p, fpr, flag);
575   return leave_cmd (ctx, rc);
576 }
577
578
579
580 \f
581 static const char hlp_havekey[] =
582   "HAVEKEY <hexstrings_with_keygrips>\n"
583   "\n"
584   "Return success if at least one of the secret keys with the given\n"
585   "keygrips is available.";
586 static gpg_error_t
587 cmd_havekey (assuan_context_t ctx, char *line)
588 {
589   gpg_error_t err;
590   unsigned char buf[20];
591
592   do
593     {
594       err = parse_keygrip (ctx, line, buf);
595       if (err)
596         return err;
597
598       if (!agent_key_available (buf))
599         return 0; /* Found.  */
600
601       while (*line && *line != ' ' && *line != '\t')
602         line++;
603       while (*line == ' ' || *line == '\t')
604         line++;
605     }
606   while (*line);
607
608   /* No leave_cmd() here because errors are expected and would clutter
609      the log.  */
610   return gpg_error (GPG_ERR_NO_SECKEY);
611 }
612
613
614 static const char hlp_sigkey[] =
615   "SIGKEY <hexstring_with_keygrip>\n"
616   "SETKEY <hexstring_with_keygrip>\n"
617   "\n"
618   "Set the  key used for a sign or decrypt operation.";
619 static gpg_error_t
620 cmd_sigkey (assuan_context_t ctx, char *line)
621 {
622   int rc;
623   ctrl_t ctrl = assuan_get_pointer (ctx);
624
625   rc = parse_keygrip (ctx, line, ctrl->keygrip);
626   if (rc)
627     return rc;
628   ctrl->have_keygrip = 1;
629   return 0;
630 }
631
632
633 static const char hlp_setkeydesc[] =
634   "SETKEYDESC plus_percent_escaped_string\n"
635   "\n"
636   "Set a description to be used for the next PKSIGN, PKDECRYPT, IMPORT_KEY\n"
637   "or EXPORT_KEY operation if this operation requires a passphrase.  If\n"
638   "this command is not used a default text will be used.  Note, that\n"
639   "this description implictly selects the label used for the entry\n"
640   "box; if the string contains the string PIN (which in general will\n"
641   "not be translated), \"PIN\" is used, otherwise the translation of\n"
642   "\"passphrase\" is used.  The description string should not contain\n"
643   "blanks unless they are percent or '+' escaped.\n"
644   "\n"
645   "The description is only valid for the next PKSIGN, PKDECRYPT,\n"
646   "IMPORT_KEY, EXPORT_KEY, or DELETE_KEY operation.";
647 static gpg_error_t
648 cmd_setkeydesc (assuan_context_t ctx, char *line)
649 {
650   ctrl_t ctrl = assuan_get_pointer (ctx);
651   char *desc, *p;
652
653   for (p=line; *p == ' '; p++)
654     ;
655   desc = p;
656   p = strchr (desc, ' ');
657   if (p)
658     *p = 0; /* We ignore any garbage; we might late use it for other args. */
659
660   if (!*desc)
661     return set_error (GPG_ERR_ASS_PARAMETER, "no description given");
662
663   /* Note, that we only need to replace the + characters and should
664      leave the other escaping in place because the escaped string is
665      send verbatim to the pinentry which does the unescaping (but not
666      the + replacing) */
667   plus_to_blank (desc);
668
669   xfree (ctrl->server_local->keydesc);
670
671   if (ctrl->restricted)
672     {
673       ctrl->server_local->keydesc = strconcat
674         ((ctrl->restricted == 2
675          ? _("Note: Request from the web browser.")
676          : _("Note: Request from a remote site.")  ), "%0A%0A", desc, NULL);
677     }
678   else
679     ctrl->server_local->keydesc = xtrystrdup (desc);
680   if (!ctrl->server_local->keydesc)
681     return out_of_core ();
682   return 0;
683 }
684
685
686 static const char hlp_sethash[] =
687   "SETHASH (--hash=<name>)|(<algonumber>) <hexstring>\n"
688   "\n"
689   "The client can use this command to tell the server about the data\n"
690   "(which usually is a hash) to be signed.";
691 static gpg_error_t
692 cmd_sethash (assuan_context_t ctx, char *line)
693 {
694   int rc;
695   size_t n;
696   char *p;
697   ctrl_t ctrl = assuan_get_pointer (ctx);
698   unsigned char *buf;
699   char *endp;
700   int algo;
701
702   /* Parse the alternative hash options which may be used instead of
703      the algo number.  */
704   if (has_option_name (line, "--hash"))
705     {
706       if (has_option (line, "--hash=sha1"))
707         algo = GCRY_MD_SHA1;
708       else if (has_option (line, "--hash=sha224"))
709         algo = GCRY_MD_SHA224;
710       else if (has_option (line, "--hash=sha256"))
711         algo = GCRY_MD_SHA256;
712       else if (has_option (line, "--hash=sha384"))
713         algo = GCRY_MD_SHA384;
714       else if (has_option (line, "--hash=sha512"))
715         algo = GCRY_MD_SHA512;
716       else if (has_option (line, "--hash=rmd160"))
717         algo = GCRY_MD_RMD160;
718       else if (has_option (line, "--hash=md5"))
719         algo = GCRY_MD_MD5;
720       else if (has_option (line, "--hash=tls-md5sha1"))
721         algo = MD_USER_TLS_MD5SHA1;
722       else
723         return set_error (GPG_ERR_ASS_PARAMETER, "invalid hash algorithm");
724     }
725   else
726     algo = 0;
727
728   line = skip_options (line);
729
730   if (!algo)
731     {
732       /* No hash option has been given: require an algo number instead  */
733       algo = (int)strtoul (line, &endp, 10);
734       for (line = endp; *line == ' ' || *line == '\t'; line++)
735         ;
736       if (!algo || gcry_md_test_algo (algo))
737         return set_error (GPG_ERR_UNSUPPORTED_ALGORITHM, NULL);
738     }
739   ctrl->digest.algo = algo;
740   ctrl->digest.raw_value = 0;
741
742   /* Parse the hash value. */
743   n = 0;
744   rc = parse_hexstring (ctx, line, &n);
745   if (rc)
746     return rc;
747   n /= 2;
748   if (algo == MD_USER_TLS_MD5SHA1 && n == 36)
749     ;
750   else if (n != 16 && n != 20 && n != 24
751            && n != 28 && n != 32 && n != 48 && n != 64)
752     return set_error (GPG_ERR_ASS_PARAMETER, "unsupported length of hash");
753
754   if (n > MAX_DIGEST_LEN)
755     return set_error (GPG_ERR_ASS_PARAMETER, "hash value to long");
756
757   buf = ctrl->digest.value;
758   ctrl->digest.valuelen = n;
759   for (p=line, n=0; n < ctrl->digest.valuelen; p += 2, n++)
760     buf[n] = xtoi_2 (p);
761   for (; n < ctrl->digest.valuelen; n++)
762     buf[n] = 0;
763   return 0;
764 }
765
766
767 static const char hlp_pksign[] =
768   "PKSIGN [<options>] [<cache_nonce>]\n"
769   "\n"
770   "Perform the actual sign operation.  Neither input nor output are\n"
771   "sensitive to eavesdropping.";
772 static gpg_error_t
773 cmd_pksign (assuan_context_t ctx, char *line)
774 {
775   int rc;
776   cache_mode_t cache_mode = CACHE_MODE_NORMAL;
777   ctrl_t ctrl = assuan_get_pointer (ctx);
778   membuf_t outbuf;
779   char *cache_nonce = NULL;
780   char *p;
781
782   line = skip_options (line);
783
784   p = line;
785   for (p=line; *p && *p != ' ' && *p != '\t'; p++)
786     ;
787   *p = '\0';
788   if (*line)
789     cache_nonce = xtrystrdup (line);
790
791   if (opt.ignore_cache_for_signing)
792     cache_mode = CACHE_MODE_IGNORE;
793   else if (!ctrl->server_local->use_cache_for_signing)
794     cache_mode = CACHE_MODE_IGNORE;
795
796   init_membuf (&outbuf, 512);
797
798   rc = agent_pksign (ctrl, cache_nonce, ctrl->server_local->keydesc,
799                      &outbuf, cache_mode);
800   if (rc)
801     clear_outbuf (&outbuf);
802   else
803     rc = write_and_clear_outbuf (ctx, &outbuf);
804
805   xfree (cache_nonce);
806   xfree (ctrl->server_local->keydesc);
807   ctrl->server_local->keydesc = NULL;
808   return leave_cmd (ctx, rc);
809 }
810
811
812 static const char hlp_pkdecrypt[] =
813   "PKDECRYPT [<options>]\n"
814   "\n"
815   "Perform the actual decrypt operation.  Input is not\n"
816   "sensitive to eavesdropping.";
817 static gpg_error_t
818 cmd_pkdecrypt (assuan_context_t ctx, char *line)
819 {
820   int rc;
821   ctrl_t ctrl = assuan_get_pointer (ctx);
822   unsigned char *value;
823   size_t valuelen;
824   membuf_t outbuf;
825   int padding;
826
827   (void)line;
828
829   /* First inquire the data to decrypt */
830   rc = print_assuan_status (ctx, "INQUIRE_MAXLEN", "%u", MAXLEN_CIPHERTEXT);
831   if (!rc)
832     rc = assuan_inquire (ctx, "CIPHERTEXT",
833                         &value, &valuelen, MAXLEN_CIPHERTEXT);
834   if (rc)
835     return rc;
836
837   init_membuf (&outbuf, 512);
838
839   rc = agent_pkdecrypt (ctrl, ctrl->server_local->keydesc,
840                         value, valuelen, &outbuf, &padding);
841   xfree (value);
842   if (rc)
843     clear_outbuf (&outbuf);
844   else
845     {
846       if (padding != -1)
847         rc = print_assuan_status (ctx, "PADDING", "%d", padding);
848       else
849         rc = 0;
850       if (!rc)
851         rc = write_and_clear_outbuf (ctx, &outbuf);
852     }
853   xfree (ctrl->server_local->keydesc);
854   ctrl->server_local->keydesc = NULL;
855   return leave_cmd (ctx, rc);
856 }
857
858
859 static const char hlp_genkey[] =
860   "GENKEY [--no-protection] [--preset] [--inq-passwd] [<cache_nonce>]\n"
861   "\n"
862   "Generate a new key, store the secret part and return the public\n"
863   "part.  Here is an example transaction:\n"
864   "\n"
865   "  C: GENKEY\n"
866   "  S: INQUIRE KEYPARAM\n"
867   "  C: D (genkey (rsa (nbits  2048)))\n"
868   "  C: END\n"
869   "  S: D (public-key\n"
870   "  S: D   (rsa (n 326487324683264) (e 10001)))\n"
871   "  S: OK key created\n"
872   "\n"
873   "When the --preset option is used the passphrase for the generated\n"
874   "key will be added to the cache.  When --inq-passwd is used an inquire\n"
875   "with the keyword NEWPASSWD is used to request the passphrase for the\n"
876   "new key.\n";
877 static gpg_error_t
878 cmd_genkey (assuan_context_t ctx, char *line)
879 {
880   ctrl_t ctrl = assuan_get_pointer (ctx);
881   int rc;
882   int no_protection;
883   unsigned char *value;
884   size_t valuelen;
885   unsigned char *newpasswd = NULL;
886   membuf_t outbuf;
887   char *cache_nonce = NULL;
888   int opt_preset;
889   int opt_inq_passwd;
890   size_t n;
891   char *p;
892
893   if (ctrl->restricted)
894     return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
895
896   no_protection = has_option (line, "--no-protection");
897   opt_preset = has_option (line, "--preset");
898   opt_inq_passwd = has_option (line, "--inq-passwd");
899   line = skip_options (line);
900
901   p = line;
902   for (p=line; *p && *p != ' ' && *p != '\t'; p++)
903     ;
904   *p = '\0';
905   if (*line)
906     cache_nonce = xtrystrdup (line);
907
908   /* First inquire the parameters */
909   rc = print_assuan_status (ctx, "INQUIRE_MAXLEN", "%u", MAXLEN_KEYPARAM);
910   if (!rc)
911     rc = assuan_inquire (ctx, "KEYPARAM", &value, &valuelen, MAXLEN_KEYPARAM);
912   if (rc)
913     return rc;
914
915   init_membuf (&outbuf, 512);
916
917   /* If requested, ask for the password to be used for the key.  If
918      this is not used the regular Pinentry mechanism is used.  */
919   if (opt_inq_passwd && !no_protection)
920     {
921       /* (N is used as a dummy) */
922       assuan_begin_confidential (ctx);
923       rc = assuan_inquire (ctx, "NEWPASSWD", &newpasswd, &n, 256);
924       assuan_end_confidential (ctx);
925       if (rc)
926         goto leave;
927       if (!*newpasswd)
928         {
929           /* Empty password given - switch to no-protection mode.  */
930           xfree (newpasswd);
931           newpasswd = NULL;
932           no_protection = 1;
933         }
934
935     }
936
937   rc = agent_genkey (ctrl, cache_nonce, (char*)value, valuelen, no_protection,
938                      newpasswd, opt_preset, &outbuf);
939
940  leave:
941   if (newpasswd)
942     {
943       /* Assuan_inquire does not allow us to read into secure memory
944          thus we need to wipe it ourself.  */
945       wipememory (newpasswd, strlen (newpasswd));
946       xfree (newpasswd);
947     }
948   xfree (value);
949   if (rc)
950     clear_outbuf (&outbuf);
951   else
952     rc = write_and_clear_outbuf (ctx, &outbuf);
953   xfree (cache_nonce);
954   return leave_cmd (ctx, rc);
955 }
956
957
958
959 \f
960 static const char hlp_readkey[] =
961   "READKEY <hexstring_with_keygrip>\n"
962   "\n"
963   "Return the public key for the given keygrip.";
964 static gpg_error_t
965 cmd_readkey (assuan_context_t ctx, char *line)
966 {
967   ctrl_t ctrl = assuan_get_pointer (ctx);
968   int rc;
969   unsigned char grip[20];
970   gcry_sexp_t s_pkey = NULL;
971
972   if (ctrl->restricted)
973     return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
974
975   rc = parse_keygrip (ctx, line, grip);
976   if (rc)
977     return rc; /* Return immediately as this is already an Assuan error code.*/
978
979   rc = agent_public_key_from_file (ctrl, grip, &s_pkey);
980   if (!rc)
981     {
982       size_t len;
983       unsigned char *buf;
984
985       len = gcry_sexp_sprint (s_pkey, GCRYSEXP_FMT_CANON, NULL, 0);
986       assert (len);
987       buf = xtrymalloc (len);
988       if (!buf)
989         rc = gpg_error_from_syserror ();
990       else
991         {
992           len = gcry_sexp_sprint (s_pkey, GCRYSEXP_FMT_CANON, buf, len);
993           assert (len);
994           rc = assuan_send_data (ctx, buf, len);
995           xfree (buf);
996         }
997       gcry_sexp_release (s_pkey);
998     }
999
1000   return leave_cmd (ctx, rc);
1001 }
1002
1003
1004 \f
1005 static const char hlp_keyinfo[] =
1006   "KEYINFO [--[ssh-]list] [--data] [--ssh-fpr] [--with-ssh] <keygrip>\n"
1007   "\n"
1008   "Return information about the key specified by the KEYGRIP.  If the\n"
1009   "key is not available GPG_ERR_NOT_FOUND is returned.  If the option\n"
1010   "--list is given the keygrip is ignored and information about all\n"
1011   "available keys are returned.  If --ssh-list is given information\n"
1012   "about all keys listed in the sshcontrol are returned.  With --with-ssh\n"
1013   "information from sshcontrol is always added to the info. Unless --data\n"
1014   "is given, the information is returned as a status line using the format:\n"
1015   "\n"
1016   "  KEYINFO <keygrip> <type> <serialno> <idstr> <cached> <protection> <fpr>\n"
1017   "\n"
1018   "KEYGRIP is the keygrip.\n"
1019   "\n"
1020   "TYPE is describes the type of the key:\n"
1021   "    'D' - Regular key stored on disk,\n"
1022   "    'T' - Key is stored on a smartcard (token),\n"
1023   "    'X' - Unknown type,\n"
1024   "    '-' - Key is missing.\n"
1025   "\n"
1026   "SERIALNO is an ASCII string with the serial number of the\n"
1027   "         smartcard.  If the serial number is not known a single\n"
1028   "         dash '-' is used instead.\n"
1029   "\n"
1030   "IDSTR is the IDSTR used to distinguish keys on a smartcard.  If it\n"
1031   "      is not known a dash is used instead.\n"
1032   "\n"
1033   "CACHED is 1 if the passphrase for the key was found in the key cache.\n"
1034   "       If not, a '-' is used instead.\n"
1035   "\n"
1036   "PROTECTION describes the key protection type:\n"
1037   "    'P' - The key is protected with a passphrase,\n"
1038   "    'C' - The key is not protected,\n"
1039   "    '-' - Unknown protection.\n"
1040   "\n"
1041   "FPR returns the formatted ssh-style fingerprint of the key.  It is only\n"
1042   "    printed if the option --ssh-fpr has been used.  It defaults to '-'.\n"
1043   "\n"
1044   "TTL is the TTL in seconds for that key or '-' if n/a.\n"
1045   "\n"
1046   "FLAGS is a word consisting of one-letter flags:\n"
1047   "      'D' - The key has been disabled,\n"
1048   "      'S' - The key is listed in sshcontrol (requires --with-ssh),\n"
1049   "      'c' - Use of the key needs to be confirmed,\n"
1050   "      '-' - No flags given.\n"
1051   "\n"
1052   "More information may be added in the future.";
1053 static gpg_error_t
1054 do_one_keyinfo (ctrl_t ctrl, const unsigned char *grip, assuan_context_t ctx,
1055                 int data, int with_ssh_fpr, int in_ssh,
1056                 int ttl, int disabled, int confirm)
1057 {
1058   gpg_error_t err;
1059   char hexgrip[40+1];
1060   char *fpr = NULL;
1061   int keytype;
1062   unsigned char *shadow_info = NULL;
1063   char *serialno = NULL;
1064   char *idstr = NULL;
1065   const char *keytypestr;
1066   const char *cached;
1067   const char *protectionstr;
1068   char *pw;
1069   int missing_key = 0;
1070   char ttlbuf[20];
1071   char flagsbuf[5];
1072
1073   err = agent_key_info_from_file (ctrl, grip, &keytype, &shadow_info);
1074   if (err)
1075     {
1076       if (in_ssh && gpg_err_code (err) == GPG_ERR_NOT_FOUND)
1077         missing_key = 1;
1078       else
1079         goto leave;
1080     }
1081
1082   /* Reformat the grip so that we use uppercase as good style. */
1083   bin2hex (grip, 20, hexgrip);
1084
1085   if (ttl > 0)
1086     snprintf (ttlbuf, sizeof ttlbuf, "%d", ttl);
1087   else
1088     strcpy (ttlbuf, "-");
1089
1090   *flagsbuf = 0;
1091   if (disabled)
1092     strcat (flagsbuf, "D");
1093   if (in_ssh)
1094     strcat (flagsbuf, "S");
1095   if (confirm)
1096     strcat (flagsbuf, "c");
1097   if (!*flagsbuf)
1098     strcpy (flagsbuf, "-");
1099
1100
1101   if (missing_key)
1102     {
1103       protectionstr = "-"; keytypestr = "-";
1104     }
1105   else
1106     {
1107       switch (keytype)
1108         {
1109         case PRIVATE_KEY_CLEAR:
1110         case PRIVATE_KEY_OPENPGP_NONE:
1111           protectionstr = "C"; keytypestr = "D";
1112           break;
1113         case PRIVATE_KEY_PROTECTED: protectionstr = "P"; keytypestr = "D";
1114           break;
1115         case PRIVATE_KEY_SHADOWED: protectionstr = "-"; keytypestr = "T";
1116           break;
1117         default: protectionstr = "-"; keytypestr = "X";
1118           break;
1119         }
1120     }
1121
1122   /* Compute the ssh fingerprint if requested.  */
1123   if (with_ssh_fpr)
1124     {
1125       gcry_sexp_t key;
1126
1127       if (!agent_raw_key_from_file (ctrl, grip, &key))
1128         {
1129           ssh_get_fingerprint_string (key, &fpr);
1130           gcry_sexp_release (key);
1131         }
1132     }
1133
1134   /* Here we have a little race by doing the cache check separately
1135      from the retrieval function.  Given that the cache flag is only a
1136      hint, it should not really matter.  */
1137   pw = agent_get_cache (hexgrip, CACHE_MODE_NORMAL);
1138   cached = pw ? "1" : "-";
1139   xfree (pw);
1140
1141   if (shadow_info)
1142     {
1143       err = parse_shadow_info (shadow_info, &serialno, &idstr, NULL);
1144       if (err)
1145         goto leave;
1146     }
1147
1148   if (!data)
1149     err = agent_write_status (ctrl, "KEYINFO",
1150                               hexgrip,
1151                               keytypestr,
1152                               serialno? serialno : "-",
1153                               idstr? idstr : "-",
1154                               cached,
1155                               protectionstr,
1156                               fpr? fpr : "-",
1157                               ttlbuf,
1158                               flagsbuf,
1159                               NULL);
1160   else
1161     {
1162       char *string;
1163
1164       string = xtryasprintf ("%s %s %s %s %s %s %s %s %s\n",
1165                              hexgrip, keytypestr,
1166                              serialno? serialno : "-",
1167                              idstr? idstr : "-", cached, protectionstr,
1168                              fpr? fpr : "-",
1169                              ttlbuf,
1170                              flagsbuf);
1171       if (!string)
1172         err = gpg_error_from_syserror ();
1173       else
1174         err = assuan_send_data (ctx, string, strlen(string));
1175       xfree (string);
1176     }
1177
1178  leave:
1179   xfree (fpr);
1180   xfree (shadow_info);
1181   xfree (serialno);
1182   xfree (idstr);
1183   return err;
1184 }
1185
1186
1187 /* Entry int for the command KEYINFO.  This function handles the
1188    command option processing.  For details see hlp_keyinfo above.  */
1189 static gpg_error_t
1190 cmd_keyinfo (assuan_context_t ctx, char *line)
1191 {
1192   ctrl_t ctrl = assuan_get_pointer (ctx);
1193   int err;
1194   unsigned char grip[20];
1195   DIR *dir = NULL;
1196   int list_mode;
1197   int opt_data, opt_ssh_fpr, opt_with_ssh;
1198   ssh_control_file_t cf = NULL;
1199   char hexgrip[41];
1200   int disabled, ttl, confirm, is_ssh;
1201
1202   if (ctrl->restricted)
1203     return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
1204
1205   if (has_option (line, "--ssh-list"))
1206     list_mode = 2;
1207   else
1208     list_mode = has_option (line, "--list");
1209   opt_data = has_option (line, "--data");
1210   opt_ssh_fpr = has_option (line, "--ssh-fpr");
1211   opt_with_ssh = has_option (line, "--with-ssh");
1212   line = skip_options (line);
1213
1214   if (opt_with_ssh || list_mode == 2)
1215     cf = ssh_open_control_file ();
1216
1217   if (list_mode == 2)
1218     {
1219       if (cf)
1220         {
1221           while (!ssh_read_control_file (cf, hexgrip,
1222                                          &disabled, &ttl, &confirm))
1223             {
1224               if (hex2bin (hexgrip, grip, 20) < 0 )
1225                 continue; /* Bad hex string.  */
1226               err = do_one_keyinfo (ctrl, grip, ctx, opt_data, opt_ssh_fpr, 1,
1227                                     ttl, disabled, confirm);
1228               if (err)
1229                 goto leave;
1230             }
1231         }
1232       err = 0;
1233     }
1234   else if (list_mode)
1235     {
1236       char *dirname;
1237       struct dirent *dir_entry;
1238
1239       dirname = make_filename_try (opt.homedir, GNUPG_PRIVATE_KEYS_DIR, NULL);
1240       if (!dirname)
1241         {
1242           err = gpg_error_from_syserror ();
1243           goto leave;
1244         }
1245       dir = opendir (dirname);
1246       if (!dir)
1247         {
1248           err = gpg_error_from_syserror ();
1249           xfree (dirname);
1250           goto leave;
1251         }
1252       xfree (dirname);
1253
1254       while ( (dir_entry = readdir (dir)) )
1255         {
1256           if (strlen (dir_entry->d_name) != 44
1257               || strcmp (dir_entry->d_name + 40, ".key"))
1258             continue;
1259           strncpy (hexgrip, dir_entry->d_name, 40);
1260           hexgrip[40] = 0;
1261
1262           if ( hex2bin (hexgrip, grip, 20) < 0 )
1263             continue; /* Bad hex string.  */
1264
1265           disabled = ttl = confirm = is_ssh = 0;
1266           if (opt_with_ssh)
1267             {
1268               err = ssh_search_control_file (cf, hexgrip,
1269                                              &disabled, &ttl, &confirm);
1270               if (!err)
1271                 is_ssh = 1;
1272               else if (gpg_err_code (err) != GPG_ERR_NOT_FOUND)
1273                 goto leave;
1274             }
1275
1276           err = do_one_keyinfo (ctrl, grip, ctx, opt_data, opt_ssh_fpr, is_ssh,
1277                                 ttl, disabled, confirm);
1278           if (err)
1279             goto leave;
1280         }
1281       err = 0;
1282     }
1283   else
1284     {
1285       err = parse_keygrip (ctx, line, grip);
1286       if (err)
1287         goto leave;
1288       disabled = ttl = confirm = is_ssh = 0;
1289       if (opt_with_ssh)
1290         {
1291           err = ssh_search_control_file (cf, line,
1292                                          &disabled, &ttl, &confirm);
1293           if (!err)
1294             is_ssh = 1;
1295           else if (gpg_err_code (err) != GPG_ERR_NOT_FOUND)
1296             goto leave;
1297         }
1298
1299       err = do_one_keyinfo (ctrl, grip, ctx, opt_data, opt_ssh_fpr, is_ssh,
1300                             ttl, disabled, confirm);
1301     }
1302
1303  leave:
1304   ssh_close_control_file (cf);
1305   if (dir)
1306     closedir (dir);
1307   if (err && gpg_err_code (err) != GPG_ERR_NOT_FOUND)
1308     leave_cmd (ctx, err);
1309   return err;
1310 }
1311
1312
1313 \f
1314 /* Helper for cmd_get_passphrase.  */
1315 static int
1316 send_back_passphrase (assuan_context_t ctx, int via_data, const char *pw)
1317 {
1318   size_t n;
1319   int rc;
1320
1321   assuan_begin_confidential (ctx);
1322   n = strlen (pw);
1323   if (via_data)
1324     rc = assuan_send_data (ctx, pw, n);
1325   else
1326     {
1327       char *p = xtrymalloc_secure (n*2+1);
1328       if (!p)
1329         rc = gpg_error_from_syserror ();
1330       else
1331         {
1332           bin2hex (pw, n, p);
1333           rc = assuan_set_okay_line (ctx, p);
1334           xfree (p);
1335         }
1336     }
1337   return rc;
1338 }
1339
1340
1341 static const char hlp_get_passphrase[] =
1342   "GET_PASSPHRASE [--data] [--check] [--no-ask] [--repeat[=N]]\n"
1343   "               [--qualitybar] <cache_id>\n"
1344   "               [<error_message> <prompt> <description>]\n"
1345   "\n"
1346   "This function is usually used to ask for a passphrase to be used\n"
1347   "for conventional encryption, but may also be used by programs which\n"
1348   "need specal handling of passphrases.  This command uses a syntax\n"
1349   "which helps clients to use the agent with minimum effort.  The\n"
1350   "agent either returns with an error or with a OK followed by the hex\n"
1351   "encoded passphrase.  Note that the length of the strings is\n"
1352   "implicitly limited by the maximum length of a command.\n"
1353   "\n"
1354   "If the option \"--data\" is used the passphrase is returned by usual\n"
1355   "data lines and not on the okay line.\n"
1356   "\n"
1357   "If the option \"--check\" is used the passphrase constraints checks as\n"
1358   "implemented by gpg-agent are applied.  A check is not done if the\n"
1359   "passphrase has been found in the cache.\n"
1360   "\n"
1361   "If the option \"--no-ask\" is used and the passphrase is not in the\n"
1362   "cache the user will not be asked to enter a passphrase but the error\n"
1363   "code GPG_ERR_NO_DATA is returned.  \n"
1364   "\n"
1365   "If the option \"--qualitybar\" is used a visual indication of the\n"
1366   "entered passphrase quality is shown.  (Unless no minimum passphrase\n"
1367   "length has been configured.)";
1368 static gpg_error_t
1369 cmd_get_passphrase (assuan_context_t ctx, char *line)
1370 {
1371   ctrl_t ctrl = assuan_get_pointer (ctx);
1372   int rc;
1373   char *pw;
1374   char *response;
1375   char *cacheid = NULL, *desc = NULL, *prompt = NULL, *errtext = NULL;
1376   const char *desc2 = _("Please re-enter this passphrase");
1377   char *p;
1378   int opt_data, opt_check, opt_no_ask, opt_qualbar;
1379   int opt_repeat = 0;
1380   char *entry_errtext = NULL;
1381
1382   if (ctrl->restricted)
1383     return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
1384
1385   opt_data = has_option (line, "--data");
1386   opt_check = has_option (line, "--check");
1387   opt_no_ask = has_option (line, "--no-ask");
1388   if (has_option_name (line, "--repeat"))
1389     {
1390       p = option_value (line, "--repeat");
1391       if (p)
1392         opt_repeat = atoi (p);
1393       else
1394         opt_repeat = 1;
1395     }
1396   opt_qualbar = has_option (line, "--qualitybar");
1397   line = skip_options (line);
1398
1399   cacheid = line;
1400   p = strchr (cacheid, ' ');
1401   if (p)
1402     {
1403       *p++ = 0;
1404       while (*p == ' ')
1405         p++;
1406       errtext = p;
1407       p = strchr (errtext, ' ');
1408       if (p)
1409         {
1410           *p++ = 0;
1411           while (*p == ' ')
1412             p++;
1413           prompt = p;
1414           p = strchr (prompt, ' ');
1415           if (p)
1416             {
1417               *p++ = 0;
1418               while (*p == ' ')
1419                 p++;
1420               desc = p;
1421               p = strchr (desc, ' ');
1422               if (p)
1423                 *p = 0; /* Ignore trailing garbage. */
1424             }
1425         }
1426     }
1427   if (!*cacheid || strlen (cacheid) > 50)
1428     return set_error (GPG_ERR_ASS_PARAMETER, "invalid length of cacheID");
1429   if (!desc)
1430     return set_error (GPG_ERR_ASS_PARAMETER, "no description given");
1431
1432   if (!strcmp (cacheid, "X"))
1433     cacheid = NULL;
1434   if (!strcmp (errtext, "X"))
1435     errtext = NULL;
1436   if (!strcmp (prompt, "X"))
1437     prompt = NULL;
1438   if (!strcmp (desc, "X"))
1439     desc = NULL;
1440
1441   pw = cacheid ? agent_get_cache (cacheid, CACHE_MODE_USER) : NULL;
1442   if (pw)
1443     {
1444       rc = send_back_passphrase (ctx, opt_data, pw);
1445       xfree (pw);
1446     }
1447   else if (opt_no_ask)
1448     rc = gpg_error (GPG_ERR_NO_DATA);
1449   else
1450     {
1451       /* Note, that we only need to replace the + characters and
1452          should leave the other escaping in place because the escaped
1453          string is send verbatim to the pinentry which does the
1454          unescaping (but not the + replacing) */
1455       if (errtext)
1456         plus_to_blank (errtext);
1457       if (prompt)
1458         plus_to_blank (prompt);
1459       if (desc)
1460         plus_to_blank (desc);
1461
1462     next_try:
1463       rc = agent_get_passphrase (ctrl, &response, desc, prompt,
1464                                  entry_errtext? entry_errtext:errtext,
1465                                  opt_qualbar, cacheid, CACHE_MODE_USER);
1466       xfree (entry_errtext);
1467       entry_errtext = NULL;
1468       if (!rc)
1469         {
1470           int i;
1471
1472           if (opt_check
1473               && check_passphrase_constraints (ctrl, response, &entry_errtext))
1474             {
1475               xfree (response);
1476               goto next_try;
1477             }
1478           for (i = 0; i < opt_repeat; i++)
1479             {
1480               char *response2;
1481
1482               if (ctrl->pinentry_mode == PINENTRY_MODE_LOOPBACK)
1483                 break;
1484
1485               rc = agent_get_passphrase (ctrl, &response2, desc2, prompt,
1486                                          errtext, 0,
1487                                          cacheid, CACHE_MODE_USER);
1488               if (rc)
1489                 break;
1490               if (strcmp (response2, response))
1491                 {
1492                   xfree (response2);
1493                   xfree (response);
1494                   entry_errtext = try_percent_escape
1495                     (_("does not match - try again"), NULL);
1496                   if (!entry_errtext)
1497                     {
1498                       rc = gpg_error_from_syserror ();
1499                       break;
1500                     }
1501                   goto next_try;
1502                 }
1503               xfree (response2);
1504             }
1505           if (!rc)
1506             {
1507               if (cacheid)
1508                 agent_put_cache (cacheid, CACHE_MODE_USER, response, 0);
1509               rc = send_back_passphrase (ctx, opt_data, response);
1510             }
1511           xfree (response);
1512         }
1513     }
1514
1515   return leave_cmd (ctx, rc);
1516 }
1517
1518
1519 static const char hlp_clear_passphrase[] =
1520   "CLEAR_PASSPHRASE [--mode=normal] <cache_id>\n"
1521   "\n"
1522   "may be used to invalidate the cache entry for a passphrase.  The\n"
1523   "function returns with OK even when there is no cached passphrase.\n"
1524   "The --mode=normal option is used to clear an entry for a cacheid\n"
1525   "added by the agent.\n";
1526 static gpg_error_t
1527 cmd_clear_passphrase (assuan_context_t ctx, char *line)
1528 {
1529   ctrl_t ctrl = assuan_get_pointer (ctx);
1530   char *cacheid = NULL;
1531   char *p;
1532   int opt_normal;
1533
1534   if (ctrl->restricted)
1535     return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
1536
1537   opt_normal = has_option (line, "--mode=normal");
1538   line = skip_options (line);
1539
1540   /* parse the stuff */
1541   for (p=line; *p == ' '; p++)
1542     ;
1543   cacheid = p;
1544   p = strchr (cacheid, ' ');
1545   if (p)
1546     *p = 0; /* ignore garbage */
1547   if (!*cacheid || strlen (cacheid) > 50)
1548     return set_error (GPG_ERR_ASS_PARAMETER, "invalid length of cacheID");
1549
1550   agent_put_cache (cacheid, opt_normal ? CACHE_MODE_NORMAL : CACHE_MODE_USER,
1551                    NULL, 0);
1552
1553   agent_clear_passphrase (ctrl, cacheid,
1554                           opt_normal ? CACHE_MODE_NORMAL : CACHE_MODE_USER);
1555
1556   return 0;
1557 }
1558
1559
1560 static const char hlp_get_confirmation[] =
1561   "GET_CONFIRMATION <description>\n"
1562   "\n"
1563   "This command may be used to ask for a simple confirmation.\n"
1564   "DESCRIPTION is displayed along with a Okay and Cancel button.  This\n"
1565   "command uses a syntax which helps clients to use the agent with\n"
1566   "minimum effort.  The agent either returns with an error or with a\n"
1567   "OK.  Note, that the length of DESCRIPTION is implicitly limited by\n"
1568   "the maximum length of a command. DESCRIPTION should not contain\n"
1569   "any spaces, those must be encoded either percent escaped or simply\n"
1570   "as '+'.";
1571 static gpg_error_t
1572 cmd_get_confirmation (assuan_context_t ctx, char *line)
1573 {
1574   ctrl_t ctrl = assuan_get_pointer (ctx);
1575   int rc;
1576   char *desc = NULL;
1577   char *p;
1578
1579   if (ctrl->restricted)
1580     return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
1581
1582   /* parse the stuff */
1583   for (p=line; *p == ' '; p++)
1584     ;
1585   desc = p;
1586   p = strchr (desc, ' ');
1587   if (p)
1588     *p = 0; /* We ignore any garbage -may be later used for other args. */
1589
1590   if (!*desc)
1591     return set_error (GPG_ERR_ASS_PARAMETER, "no description given");
1592
1593   if (!strcmp (desc, "X"))
1594     desc = NULL;
1595
1596   /* Note, that we only need to replace the + characters and should
1597      leave the other escaping in place because the escaped string is
1598      send verbatim to the pinentry which does the unescaping (but not
1599      the + replacing) */
1600   if (desc)
1601     plus_to_blank (desc);
1602
1603   rc = agent_get_confirmation (ctrl, desc, NULL, NULL, 0);
1604   return leave_cmd (ctx, rc);
1605 }
1606
1607
1608 \f
1609 static const char hlp_learn[] =
1610   "LEARN [--send] [--sendinfo] [--force]\n"
1611   "\n"
1612   "Learn something about the currently inserted smartcard.  With\n"
1613   "--sendinfo information about the card is returned; with --send\n"
1614   "the available certificates are returned as D lines; with --force\n"
1615   "private key storage will be updated by the result.";
1616 static gpg_error_t
1617 cmd_learn (assuan_context_t ctx, char *line)
1618 {
1619   ctrl_t ctrl = assuan_get_pointer (ctx);
1620   gpg_error_t err;
1621   int send, sendinfo, force;
1622
1623   send = has_option (line, "--send");
1624   sendinfo = send? 1 : has_option (line, "--sendinfo");
1625   force = has_option (line, "--force");
1626
1627   if (ctrl->restricted)
1628     return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
1629
1630   err = agent_handle_learn (ctrl, send, sendinfo? ctx : NULL, force);
1631   return leave_cmd (ctx, err);
1632 }
1633
1634
1635 \f
1636 static const char hlp_passwd[] =
1637   "PASSWD [--cache-nonce=<c>] [--passwd-nonce=<s>] [--preset]\n"
1638   "       [--verify] <hexkeygrip>\n"
1639   "\n"
1640   "Change the passphrase/PIN for the key identified by keygrip in LINE.  If\n"
1641   "--preset is used then the new passphrase will be added to the cache.\n"
1642   "If --verify is used the command asks for the passphrase and verifies\n"
1643   "that the passphrase valid.\n";
1644 static gpg_error_t
1645 cmd_passwd (assuan_context_t ctx, char *line)
1646 {
1647   ctrl_t ctrl = assuan_get_pointer (ctx);
1648   gpg_error_t err;
1649   int c;
1650   char *cache_nonce = NULL;
1651   char *passwd_nonce = NULL;
1652   unsigned char grip[20];
1653   gcry_sexp_t s_skey = NULL;
1654   unsigned char *shadow_info = NULL;
1655   char *passphrase = NULL;
1656   char *pend;
1657   int opt_preset, opt_verify;
1658
1659   if (ctrl->restricted)
1660     return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
1661
1662   opt_preset = has_option (line, "--preset");
1663   cache_nonce = option_value (line, "--cache-nonce");
1664   opt_verify = has_option (line, "--verify");
1665   if (cache_nonce)
1666     {
1667       for (pend = cache_nonce; *pend && !spacep (pend); pend++)
1668         ;
1669       c = *pend;
1670       *pend = '\0';
1671       cache_nonce = xtrystrdup (cache_nonce);
1672       *pend = c;
1673       if (!cache_nonce)
1674         {
1675           err = gpg_error_from_syserror ();
1676           goto leave;
1677         }
1678     }
1679
1680   passwd_nonce = option_value (line, "--passwd-nonce");
1681   if (passwd_nonce)
1682     {
1683       for (pend = passwd_nonce; *pend && !spacep (pend); pend++)
1684         ;
1685       c = *pend;
1686       *pend = '\0';
1687       passwd_nonce = xtrystrdup (passwd_nonce);
1688       *pend = c;
1689       if (!passwd_nonce)
1690         {
1691           err = gpg_error_from_syserror ();
1692           goto leave;
1693         }
1694     }
1695
1696   line = skip_options (line);
1697
1698   err = parse_keygrip (ctx, line, grip);
1699   if (err)
1700     goto leave;
1701
1702   ctrl->in_passwd++;
1703   err = agent_key_from_file (ctrl,
1704                              opt_verify? NULL : cache_nonce,
1705                              ctrl->server_local->keydesc,
1706                              grip, &shadow_info, CACHE_MODE_IGNORE, NULL,
1707                              &s_skey, &passphrase);
1708   if (err)
1709     ;
1710   else if (shadow_info)
1711     {
1712       log_error ("changing a smartcard PIN is not yet supported\n");
1713       err = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1714     }
1715   else if (opt_verify)
1716     {
1717       /* All done.  */
1718     }
1719   else
1720     {
1721       char *newpass = NULL;
1722
1723       if (passwd_nonce)
1724         newpass = agent_get_cache (passwd_nonce, CACHE_MODE_NONCE);
1725       err = agent_protect_and_store (ctrl, s_skey, &newpass);
1726       if (!err && passphrase)
1727         {
1728           /* A passphrase existed on the old key and the change was
1729              successful.  Return a nonce for that old passphrase to
1730              let the caller try to unprotect the other subkeys with
1731              the same key.  */
1732           if (!cache_nonce)
1733             {
1734               char buf[12];
1735               gcry_create_nonce (buf, 12);
1736               cache_nonce = bin2hex (buf, 12, NULL);
1737             }
1738           if (cache_nonce
1739               && !agent_put_cache (cache_nonce, CACHE_MODE_NONCE,
1740                                    passphrase, CACHE_TTL_NONCE))
1741             {
1742               assuan_write_status (ctx, "CACHE_NONCE", cache_nonce);
1743               xfree (ctrl->server_local->last_cache_nonce);
1744               ctrl->server_local->last_cache_nonce = cache_nonce;
1745               cache_nonce = NULL;
1746             }
1747           if (newpass)
1748             {
1749               /* If we have a new passphrase (which might be empty) we
1750                  store it under a passwd nonce so that the caller may
1751                  send that nonce again to use it for another key. */
1752               if (!passwd_nonce)
1753                 {
1754                   char buf[12];
1755                   gcry_create_nonce (buf, 12);
1756                   passwd_nonce = bin2hex (buf, 12, NULL);
1757                 }
1758               if (passwd_nonce
1759                   && !agent_put_cache (passwd_nonce, CACHE_MODE_NONCE,
1760                                        newpass, CACHE_TTL_NONCE))
1761                 {
1762                   assuan_write_status (ctx, "PASSWD_NONCE", passwd_nonce);
1763                   xfree (ctrl->server_local->last_passwd_nonce);
1764                   ctrl->server_local->last_passwd_nonce = passwd_nonce;
1765                   passwd_nonce = NULL;
1766                 }
1767             }
1768         }
1769       if (!err && opt_preset)
1770         {
1771           char hexgrip[40+1];
1772           bin2hex(grip, 20, hexgrip);
1773           err = agent_put_cache (hexgrip, CACHE_MODE_ANY, newpass,
1774                                  ctrl->cache_ttl_opt_preset);
1775         }
1776       xfree (newpass);
1777     }
1778   ctrl->in_passwd--;
1779
1780   xfree (ctrl->server_local->keydesc);
1781   ctrl->server_local->keydesc = NULL;
1782
1783  leave:
1784   xfree (passphrase);
1785   gcry_sexp_release (s_skey);
1786   xfree (shadow_info);
1787   xfree (cache_nonce);
1788   return leave_cmd (ctx, err);
1789 }
1790
1791
1792 static const char hlp_preset_passphrase[] =
1793   "PRESET_PASSPHRASE [--inquire] <string_or_keygrip> <timeout> [<hexstring>]\n"
1794   "\n"
1795   "Set the cached passphrase/PIN for the key identified by the keygrip\n"
1796   "to passwd for the given time, where -1 means infinite and 0 means\n"
1797   "the default (currently only a timeout of -1 is allowed, which means\n"
1798   "to never expire it).  If passwd is not provided, ask for it via the\n"
1799   "pinentry module unless --inquire is passed in which case the passphrase\n"
1800   "is retrieved from the client via a server inquire.\n";
1801 static gpg_error_t
1802 cmd_preset_passphrase (assuan_context_t ctx, char *line)
1803 {
1804   ctrl_t ctrl = assuan_get_pointer (ctx);
1805   int rc;
1806   char *grip_clear = NULL;
1807   unsigned char *passphrase = NULL;
1808   int ttl;
1809   size_t len;
1810   int opt_inquire;
1811
1812   if (ctrl->restricted)
1813     return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
1814
1815   if (!opt.allow_preset_passphrase)
1816     return set_error (GPG_ERR_NOT_SUPPORTED, "no --allow-preset-passphrase");
1817
1818   opt_inquire = has_option (line, "--inquire");
1819   line = skip_options (line);
1820   grip_clear = line;
1821   while (*line && (*line != ' ' && *line != '\t'))
1822     line++;
1823   if (!*line)
1824     return gpg_error (GPG_ERR_MISSING_VALUE);
1825   *line = '\0';
1826   line++;
1827   while (*line && (*line == ' ' || *line == '\t'))
1828     line++;
1829
1830   /* Currently, only infinite timeouts are allowed.  */
1831   ttl = -1;
1832   if (line[0] != '-' || line[1] != '1')
1833     return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1834   line++;
1835   line++;
1836   while (!(*line != ' ' && *line != '\t'))
1837     line++;
1838
1839   /* Syntax check the hexstring.  */
1840   len = 0;
1841   rc = parse_hexstring (ctx, line, &len);
1842   if (rc)
1843     return rc;
1844   line[len] = '\0';
1845
1846   /* If there is a passphrase, use it.  Currently, a passphrase is
1847      required.  */
1848   if (*line)
1849     {
1850       if (opt_inquire)
1851         {
1852           rc = set_error (GPG_ERR_ASS_PARAMETER,
1853                           "both --inquire and passphrase specified");
1854           goto leave;
1855         }
1856
1857       /* Do in-place conversion.  */
1858       passphrase = line;
1859       if (!hex2str (passphrase, passphrase, strlen (passphrase)+1, NULL))
1860         rc = set_error (GPG_ERR_ASS_PARAMETER, "invalid hexstring");
1861     }
1862   else if (opt_inquire)
1863     {
1864       /* Note that the passphrase will be truncated at any null byte and the
1865        * limit is 480 characters. */
1866       size_t maxlen = 480;
1867
1868       rc = print_assuan_status (ctx, "INQUIRE_MAXLEN", "%zu", maxlen);
1869       if (!rc)
1870         rc = assuan_inquire (ctx, "PASSPHRASE", &passphrase, &len, maxlen);
1871     }
1872   else
1873     rc = set_error (GPG_ERR_NOT_IMPLEMENTED, "passphrase is required");
1874
1875   if (!rc)
1876     {
1877       rc = agent_put_cache (grip_clear, CACHE_MODE_ANY, passphrase, ttl);
1878       if (opt_inquire)
1879         xfree (passphrase);
1880     }
1881
1882 leave:
1883   return leave_cmd (ctx, rc);
1884 }
1885
1886
1887 \f
1888 static const char hlp_scd[] =
1889   "SCD <commands to pass to the scdaemon>\n"
1890   " \n"
1891   "This is a general quote command to redirect everything to the\n"
1892   "SCdaemon.";
1893 static gpg_error_t
1894 cmd_scd (assuan_context_t ctx, char *line)
1895 {
1896   ctrl_t ctrl = assuan_get_pointer (ctx);
1897   int rc;
1898
1899   if (ctrl->restricted)
1900     return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
1901
1902   rc = divert_generic_cmd (ctrl, line, ctx);
1903
1904   return rc;
1905 }
1906
1907
1908 \f
1909 static const char hlp_keywrap_key[] =
1910   "KEYWRAP_KEY [--clear] <mode>\n"
1911   "\n"
1912   "Return a key to wrap another key.  For now the key is returned\n"
1913   "verbatim and and thus makes not much sense because an eavesdropper on\n"
1914   "the gpg-agent connection will see the key as well as the wrapped key.\n"
1915   "However, this function may either be equipped with a public key\n"
1916   "mechanism or not used at all if the key is a pre-shared key.  In any\n"
1917   "case wrapping the import and export of keys is a requirement for\n"
1918   "certain cryptographic validations and thus useful.  The key persists\n"
1919   "until a RESET command but may be cleared using the option --clear.\n"
1920   "\n"
1921   "Supported modes are:\n"
1922   "  --import  - Return a key to import a key into gpg-agent\n"
1923   "  --export  - Return a key to export a key from gpg-agent";
1924 static gpg_error_t
1925 cmd_keywrap_key (assuan_context_t ctx, char *line)
1926 {
1927   ctrl_t ctrl = assuan_get_pointer (ctx);
1928   gpg_error_t err = 0;
1929   int clearopt = has_option (line, "--clear");
1930
1931   if (ctrl->restricted)
1932     return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
1933
1934   assuan_begin_confidential (ctx);
1935   if (has_option (line, "--import"))
1936     {
1937       xfree (ctrl->server_local->import_key);
1938       if (clearopt)
1939         ctrl->server_local->import_key = NULL;
1940       else if (!(ctrl->server_local->import_key =
1941                  gcry_random_bytes (KEYWRAP_KEYSIZE, GCRY_STRONG_RANDOM)))
1942         err = gpg_error_from_syserror ();
1943       else
1944         err = assuan_send_data (ctx, ctrl->server_local->import_key,
1945                                 KEYWRAP_KEYSIZE);
1946     }
1947   else if (has_option (line, "--export"))
1948     {
1949       xfree (ctrl->server_local->export_key);
1950       if (clearopt)
1951         ctrl->server_local->export_key = NULL;
1952       else if (!(ctrl->server_local->export_key =
1953             gcry_random_bytes (KEYWRAP_KEYSIZE, GCRY_STRONG_RANDOM)))
1954         err = gpg_error_from_syserror ();
1955       else
1956         err = assuan_send_data (ctx, ctrl->server_local->export_key,
1957                                 KEYWRAP_KEYSIZE);
1958     }
1959   else
1960     err = set_error (GPG_ERR_ASS_PARAMETER, "unknown value for MODE");
1961   assuan_end_confidential (ctx);
1962
1963   return leave_cmd (ctx, err);
1964 }
1965
1966
1967 \f
1968 static const char hlp_import_key[] =
1969   "IMPORT_KEY [--unattended] [--force] [<cache_nonce>]\n"
1970   "\n"
1971   "Import a secret key into the key store.  The key is expected to be\n"
1972   "encrypted using the current session's key wrapping key (cf. command\n"
1973   "KEYWRAP_KEY) using the AESWRAP-128 algorithm.  This function takes\n"
1974   "no arguments but uses the inquiry \"KEYDATA\" to ask for the actual\n"
1975   "key data.  The unwrapped key must be a canonical S-expression.  The\n"
1976   "option --unattended tries to import the key as-is without any\n"
1977   "re-encryption.  Existing key can be overwritten with --force.";
1978 static gpg_error_t
1979 cmd_import_key (assuan_context_t ctx, char *line)
1980 {
1981   ctrl_t ctrl = assuan_get_pointer (ctx);
1982   gpg_error_t err;
1983   int opt_unattended;
1984   int force;
1985   unsigned char *wrappedkey = NULL;
1986   size_t wrappedkeylen;
1987   gcry_cipher_hd_t cipherhd = NULL;
1988   unsigned char *key = NULL;
1989   size_t keylen, realkeylen;
1990   char *passphrase = NULL;
1991   unsigned char *finalkey = NULL;
1992   size_t finalkeylen;
1993   unsigned char grip[20];
1994   gcry_sexp_t openpgp_sexp = NULL;
1995   char *cache_nonce = NULL;
1996   char *p;
1997
1998   if (ctrl->restricted)
1999     return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
2000
2001   if (!ctrl->server_local->import_key)
2002     {
2003       err = gpg_error (GPG_ERR_MISSING_KEY);
2004       goto leave;
2005     }
2006
2007   opt_unattended = has_option (line, "--unattended");
2008   force = has_option (line, "--force");
2009   line = skip_options (line);
2010
2011   p = line;
2012   for (p=line; *p && *p != ' ' && *p != '\t'; p++)
2013     ;
2014   *p = '\0';
2015   if (*line)
2016     cache_nonce = xtrystrdup (line);
2017
2018   assuan_begin_confidential (ctx);
2019   err = assuan_inquire (ctx, "KEYDATA",
2020                         &wrappedkey, &wrappedkeylen, MAXLEN_KEYDATA);
2021   assuan_end_confidential (ctx);
2022   if (err)
2023     goto leave;
2024   if (wrappedkeylen < 24)
2025     {
2026       err = gpg_error (GPG_ERR_INV_LENGTH);
2027       goto leave;
2028     }
2029   keylen = wrappedkeylen - 8;
2030   key = xtrymalloc_secure (keylen);
2031   if (!key)
2032     {
2033       err = gpg_error_from_syserror ();
2034       goto leave;
2035     }
2036
2037   err = gcry_cipher_open (&cipherhd, GCRY_CIPHER_AES128,
2038                           GCRY_CIPHER_MODE_AESWRAP, 0);
2039   if (err)
2040     goto leave;
2041   err = gcry_cipher_setkey (cipherhd,
2042                             ctrl->server_local->import_key, KEYWRAP_KEYSIZE);
2043   if (err)
2044     goto leave;
2045   err = gcry_cipher_decrypt (cipherhd, key, keylen, wrappedkey, wrappedkeylen);
2046   if (err)
2047     goto leave;
2048   gcry_cipher_close (cipherhd);
2049   cipherhd = NULL;
2050   xfree (wrappedkey);
2051   wrappedkey = NULL;
2052
2053   realkeylen = gcry_sexp_canon_len (key, keylen, NULL, &err);
2054   if (!realkeylen)
2055     goto leave; /* Invalid canonical encoded S-expression.  */
2056
2057   err = keygrip_from_canon_sexp (key, realkeylen, grip);
2058   if (err)
2059     {
2060       /* This might be due to an unsupported S-expression format.
2061          Check whether this is openpgp-private-key and trigger that
2062          import code.  */
2063       if (!gcry_sexp_sscan (&openpgp_sexp, NULL, key, realkeylen))
2064         {
2065           const char *tag;
2066           size_t taglen;
2067
2068           tag = gcry_sexp_nth_data (openpgp_sexp, 0, &taglen);
2069           if (tag && taglen == 19 && !memcmp (tag, "openpgp-private-key", 19))
2070             ;
2071           else
2072             {
2073               gcry_sexp_release (openpgp_sexp);
2074               openpgp_sexp = NULL;
2075             }
2076         }
2077       if (!openpgp_sexp)
2078         goto leave; /* Note that ERR is still set.  */
2079     }
2080
2081
2082   if (openpgp_sexp)
2083     {
2084       /* In most cases the key is encrypted and thus the conversion
2085          function from the OpenPGP format to our internal format will
2086          ask for a passphrase.  That passphrase will be returned and
2087          used to protect the key using the same code as for regular
2088          key import. */
2089
2090       xfree (key);
2091       key = NULL;
2092       err = convert_from_openpgp (ctrl, openpgp_sexp, force, grip,
2093                                   ctrl->server_local->keydesc, cache_nonce,
2094                                   &key, opt_unattended? NULL : &passphrase);
2095       if (err)
2096         goto leave;
2097       realkeylen = gcry_sexp_canon_len (key, 0, NULL, &err);
2098       if (!realkeylen)
2099         goto leave; /* Invalid canonical encoded S-expression.  */
2100       if (passphrase)
2101         {
2102           assert (!opt_unattended);
2103           if (!cache_nonce)
2104             {
2105               char buf[12];
2106               gcry_create_nonce (buf, 12);
2107               cache_nonce = bin2hex (buf, 12, NULL);
2108             }
2109           if (cache_nonce
2110               && !agent_put_cache (cache_nonce, CACHE_MODE_NONCE,
2111                                    passphrase, CACHE_TTL_NONCE))
2112             assuan_write_status (ctx, "CACHE_NONCE", cache_nonce);
2113         }
2114     }
2115   else if (opt_unattended)
2116     {
2117       err = set_error (GPG_ERR_ASS_PARAMETER,
2118                        "\"--unattended\" may only be used with OpenPGP keys");
2119       goto leave;
2120     }
2121   else
2122     {
2123       if (!force && !agent_key_available (grip))
2124         err = gpg_error (GPG_ERR_EEXIST);
2125       else
2126         {
2127           char *prompt = xtryasprintf
2128             (_("Please enter the passphrase to protect the "
2129                "imported object within the %s system."), GNUPG_NAME);
2130           if (!prompt)
2131             err = gpg_error_from_syserror ();
2132           else
2133             err = agent_ask_new_passphrase (ctrl, prompt, &passphrase);
2134           xfree (prompt);
2135         }
2136       if (err)
2137         goto leave;
2138     }
2139
2140   if (passphrase)
2141     {
2142       err = agent_protect (key, passphrase, &finalkey, &finalkeylen,
2143                            ctrl->s2k_count, -1);
2144       if (!err)
2145         err = agent_write_private_key (grip, finalkey, finalkeylen, force);
2146     }
2147   else
2148     err = agent_write_private_key (grip, key, realkeylen, force);
2149
2150  leave:
2151   gcry_sexp_release (openpgp_sexp);
2152   xfree (finalkey);
2153   xfree (passphrase);
2154   xfree (key);
2155   gcry_cipher_close (cipherhd);
2156   xfree (wrappedkey);
2157   xfree (cache_nonce);
2158   xfree (ctrl->server_local->keydesc);
2159   ctrl->server_local->keydesc = NULL;
2160   return leave_cmd (ctx, err);
2161 }
2162
2163
2164 \f
2165 static const char hlp_export_key[] =
2166   "EXPORT_KEY [--cache-nonce=<nonce>] [--openpgp] <hexstring_with_keygrip>\n"
2167   "\n"
2168   "Export a secret key from the key store.  The key will be encrypted\n"
2169   "using the current session's key wrapping key (cf. command KEYWRAP_KEY)\n"
2170   "using the AESWRAP-128 algorithm.  The caller needs to retrieve that key\n"
2171   "prior to using this command.  The function takes the keygrip as argument.\n";
2172 static gpg_error_t
2173 cmd_export_key (assuan_context_t ctx, char *line)
2174 {
2175   ctrl_t ctrl = assuan_get_pointer (ctx);
2176   gpg_error_t err;
2177   unsigned char grip[20];
2178   gcry_sexp_t s_skey = NULL;
2179   unsigned char *key = NULL;
2180   size_t keylen;
2181   gcry_cipher_hd_t cipherhd = NULL;
2182   unsigned char *wrappedkey = NULL;
2183   size_t wrappedkeylen;
2184   int openpgp;
2185   char *cache_nonce;
2186   char *passphrase = NULL;
2187   unsigned char *shadow_info = NULL;
2188   char *pend;
2189   int c;
2190
2191   if (ctrl->restricted)
2192     return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
2193
2194   openpgp = has_option (line, "--openpgp");
2195   cache_nonce = option_value (line, "--cache-nonce");
2196   if (cache_nonce)
2197     {
2198       for (pend = cache_nonce; *pend && !spacep (pend); pend++)
2199         ;
2200       c = *pend;
2201       *pend = '\0';
2202       cache_nonce = xtrystrdup (cache_nonce);
2203       *pend = c;
2204       if (!cache_nonce)
2205         {
2206           err = gpg_error_from_syserror ();
2207           goto leave;
2208         }
2209     }
2210   line = skip_options (line);
2211
2212   if (!ctrl->server_local->export_key)
2213     {
2214       err = set_error (GPG_ERR_MISSING_KEY, "did you run KEYWRAP_KEY ?");
2215       goto leave;
2216     }
2217
2218   err = parse_keygrip (ctx, line, grip);
2219   if (err)
2220     goto leave;
2221
2222   if (agent_key_available (grip))
2223     {
2224       err = gpg_error (GPG_ERR_NO_SECKEY);
2225       goto leave;
2226     }
2227
2228   /* Get the key from the file.  With the openpgp flag we also ask for
2229      the passphrase so that we can use it to re-encrypt it.  */
2230   err = agent_key_from_file (ctrl, cache_nonce,
2231                              ctrl->server_local->keydesc, grip,
2232                              &shadow_info, CACHE_MODE_IGNORE, NULL, &s_skey,
2233                              openpgp ? &passphrase : NULL);
2234   if (err)
2235     goto leave;
2236   if (shadow_info)
2237     {
2238       /* Key is on a smartcard.  */
2239       err = gpg_error (GPG_ERR_UNUSABLE_SECKEY);
2240       goto leave;
2241     }
2242
2243   if (openpgp)
2244     {
2245       /* The openpgp option changes the key format into the OpenPGP
2246          key transfer format.  The result is already a padded
2247          canonical S-expression.  */
2248       if (!passphrase)
2249         {
2250           err = agent_ask_new_passphrase
2251             (ctrl, _("This key (or subkey) is not protected with a passphrase."
2252                      "  Please enter a new passphrase to export it."),
2253              &passphrase);
2254           if (err)
2255             goto leave;
2256         }
2257       err = convert_to_openpgp (ctrl, s_skey, passphrase, &key, &keylen);
2258       if (!err && passphrase)
2259         {
2260           if (!cache_nonce)
2261             {
2262               char buf[12];
2263               gcry_create_nonce (buf, 12);
2264               cache_nonce = bin2hex (buf, 12, NULL);
2265             }
2266           if (cache_nonce
2267               && !agent_put_cache (cache_nonce, CACHE_MODE_NONCE,
2268                                    passphrase, CACHE_TTL_NONCE))
2269             {
2270               assuan_write_status (ctx, "CACHE_NONCE", cache_nonce);
2271               xfree (ctrl->server_local->last_cache_nonce);
2272               ctrl->server_local->last_cache_nonce = cache_nonce;
2273               cache_nonce = NULL;
2274             }
2275         }
2276     }
2277   else
2278     {
2279       /* Convert into a canonical S-expression and wrap that.  */
2280       err = make_canon_sexp_pad (s_skey, 1, &key, &keylen);
2281     }
2282   if (err)
2283     goto leave;
2284   gcry_sexp_release (s_skey);
2285   s_skey = NULL;
2286
2287   err = gcry_cipher_open (&cipherhd, GCRY_CIPHER_AES128,
2288                           GCRY_CIPHER_MODE_AESWRAP, 0);
2289   if (err)
2290     goto leave;
2291   err = gcry_cipher_setkey (cipherhd,
2292                             ctrl->server_local->export_key, KEYWRAP_KEYSIZE);
2293   if (err)
2294     goto leave;
2295
2296   wrappedkeylen = keylen + 8;
2297   wrappedkey = xtrymalloc (wrappedkeylen);
2298   if (!wrappedkey)
2299     {
2300       err = gpg_error_from_syserror ();
2301       goto leave;
2302     }
2303
2304   err = gcry_cipher_encrypt (cipherhd, wrappedkey, wrappedkeylen, key, keylen);
2305   if (err)
2306     goto leave;
2307   xfree (key);
2308   key = NULL;
2309   gcry_cipher_close (cipherhd);
2310   cipherhd = NULL;
2311
2312   assuan_begin_confidential (ctx);
2313   err = assuan_send_data (ctx, wrappedkey, wrappedkeylen);
2314   assuan_end_confidential (ctx);
2315
2316
2317  leave:
2318   xfree (cache_nonce);
2319   xfree (passphrase);
2320   xfree (wrappedkey);
2321   gcry_cipher_close (cipherhd);
2322   xfree (key);
2323   gcry_sexp_release (s_skey);
2324   xfree (ctrl->server_local->keydesc);
2325   ctrl->server_local->keydesc = NULL;
2326   xfree (shadow_info);
2327
2328   return leave_cmd (ctx, err);
2329 }
2330
2331
2332 \f
2333 static const char hlp_delete_key[] =
2334   "DELETE_KEY [--force] <hexstring_with_keygrip>\n"
2335   "\n"
2336   "Delete a secret key from the key store.\n"
2337   "Unless --force is used the agent asks the user for confirmation.\n";
2338 static gpg_error_t
2339 cmd_delete_key (assuan_context_t ctx, char *line)
2340 {
2341   ctrl_t ctrl = assuan_get_pointer (ctx);
2342   gpg_error_t err;
2343   int force;
2344   unsigned char grip[20];
2345
2346   if (ctrl->restricted)
2347     return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
2348
2349   force = has_option (line, "--force");
2350   line = skip_options (line);
2351
2352   err = parse_keygrip (ctx, line, grip);
2353   if (err)
2354     goto leave;
2355
2356   err = agent_delete_key (ctrl, ctrl->server_local->keydesc, grip, force );
2357   if (err)
2358     goto leave;
2359
2360  leave:
2361   xfree (ctrl->server_local->keydesc);
2362   ctrl->server_local->keydesc = NULL;
2363
2364   return leave_cmd (ctx, err);
2365 }
2366
2367
2368 \f
2369 static const char hlp_keytocard[] =
2370   "KEYTOCARD [--force] <hexstring_with_keygrip> <serialno> <id> <timestamp>\n"
2371   "\n";
2372 static gpg_error_t
2373 cmd_keytocard (assuan_context_t ctx, char *line)
2374 {
2375   ctrl_t ctrl = assuan_get_pointer (ctx);
2376   int force;
2377   gpg_error_t err = 0;
2378   unsigned char grip[20];
2379   gcry_sexp_t s_skey = NULL;
2380   unsigned char *keydata;
2381   size_t keydatalen, timestamplen;
2382   const char *serialno, *timestamp_str, *id;
2383   unsigned char *shadow_info = NULL;
2384   time_t timestamp;
2385
2386   if (ctrl->restricted)
2387     return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
2388
2389   force = has_option (line, "--force");
2390   line = skip_options (line);
2391
2392   err = parse_keygrip (ctx, line, grip);
2393   if (err)
2394     return err;
2395
2396   if (agent_key_available (grip))
2397     return gpg_error (GPG_ERR_NO_SECKEY);
2398
2399   line += 40;
2400   while (*line && (*line == ' ' || *line == '\t'))
2401     line++;
2402   serialno = line;
2403   while (*line && (*line != ' ' && *line != '\t'))
2404     line++;
2405   if (!*line)
2406     return gpg_error (GPG_ERR_MISSING_VALUE);
2407   *line = '\0';
2408   line++;
2409   while (*line && (*line == ' ' || *line == '\t'))
2410     line++;
2411   id = line;
2412   while (*line && (*line != ' ' && *line != '\t'))
2413     line++;
2414   if (!*line)
2415     return gpg_error (GPG_ERR_MISSING_VALUE);
2416   *line = '\0';
2417   line++;
2418   while (*line && (*line == ' ' || *line == '\t'))
2419     line++;
2420   timestamp_str = line;
2421   while (*line && (*line != ' ' && *line != '\t'))
2422     line++;
2423   if (*line)
2424     *line = '\0';
2425   timestamplen = line - timestamp_str;
2426   if (timestamplen != 15)
2427     return gpg_error (GPG_ERR_INV_VALUE);
2428
2429   err = agent_key_from_file (ctrl, NULL, ctrl->server_local->keydesc, grip,
2430                              &shadow_info, CACHE_MODE_IGNORE, NULL,
2431                              &s_skey, NULL);
2432   if (err)
2433     {
2434       xfree (shadow_info);
2435       return err;
2436     }
2437   if (shadow_info)
2438     {
2439       /* Key is on a smartcard already.  */
2440       xfree (shadow_info);
2441       gcry_sexp_release (s_skey);
2442       return gpg_error (GPG_ERR_UNUSABLE_SECKEY);
2443     }
2444
2445   keydatalen =  gcry_sexp_sprint (s_skey, GCRYSEXP_FMT_CANON, NULL, 0);
2446   keydata = xtrymalloc_secure (keydatalen + 30);
2447   if (keydata == NULL)
2448     {
2449       gcry_sexp_release (s_skey);
2450       return gpg_error_from_syserror ();
2451     }
2452
2453   gcry_sexp_sprint (s_skey, GCRYSEXP_FMT_CANON, keydata, keydatalen);
2454   gcry_sexp_release (s_skey);
2455   keydatalen--;                 /* Decrement for last '\0'.  */
2456   /* Add timestamp "created-at" in the private key */
2457   timestamp = isotime2epoch (timestamp_str);
2458   snprintf (keydata+keydatalen-1, 30, "(10:created-at10:%010lu))", timestamp);
2459   keydatalen += 10 + 19 - 1;
2460   err = divert_writekey (ctrl, force, serialno, id, keydata, keydatalen);
2461   xfree (keydata);
2462
2463   return leave_cmd (ctx, err);
2464 }
2465
2466
2467 \f
2468 static const char hlp_getval[] =
2469   "GETVAL <key>\n"
2470   "\n"
2471   "Return the value for KEY from the special environment as created by\n"
2472   "PUTVAL.";
2473 static gpg_error_t
2474 cmd_getval (assuan_context_t ctx, char *line)
2475 {
2476   ctrl_t ctrl = assuan_get_pointer (ctx);
2477   int rc = 0;
2478   char *key = NULL;
2479   char *p;
2480   struct putval_item_s *vl;
2481
2482   if (ctrl->restricted)
2483     return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
2484
2485   for (p=line; *p == ' '; p++)
2486     ;
2487   key = p;
2488   p = strchr (key, ' ');
2489   if (p)
2490     {
2491       *p++ = 0;
2492       for (; *p == ' '; p++)
2493         ;
2494       if (*p)
2495         return set_error (GPG_ERR_ASS_PARAMETER, "too many arguments");
2496     }
2497   if (!*key)
2498     return set_error (GPG_ERR_ASS_PARAMETER, "no key given");
2499
2500
2501   for (vl=putval_list; vl; vl = vl->next)
2502     if ( !strcmp (vl->d, key) )
2503       break;
2504
2505   if (vl) /* Got an entry. */
2506     rc = assuan_send_data (ctx, vl->d+vl->off, vl->len);
2507   else
2508     return gpg_error (GPG_ERR_NO_DATA);
2509
2510   return leave_cmd (ctx, rc);
2511 }
2512
2513
2514 static const char hlp_putval[] =
2515   "PUTVAL <key> [<percent_escaped_value>]\n"
2516   "\n"
2517   "The gpg-agent maintains a kind of environment which may be used to\n"
2518   "store key/value pairs in it, so that they can be retrieved later.\n"
2519   "This may be used by helper daemons to daemonize themself on\n"
2520   "invocation and register them with gpg-agent.  Callers of the\n"
2521   "daemon's service may now first try connect to get the information\n"
2522   "for that service from gpg-agent through the GETVAL command and then\n"
2523   "try to connect to that daemon.  Only if that fails they may start\n"
2524   "an own instance of the service daemon. \n"
2525   "\n"
2526   "KEY is an an arbitrary symbol with the same syntax rules as keys\n"
2527   "for shell environment variables.  PERCENT_ESCAPED_VALUE is the\n"
2528   "corresponding value; they should be similar to the values of\n"
2529   "envronment variables but gpg-agent does not enforce any\n"
2530   "restrictions.  If that value is not given any value under that KEY\n"
2531   "is removed from this special environment.";
2532 static gpg_error_t
2533 cmd_putval (assuan_context_t ctx, char *line)
2534 {
2535   ctrl_t ctrl = assuan_get_pointer (ctx);
2536   int rc = 0;
2537   char *key = NULL;
2538   char *value = NULL;
2539   size_t valuelen = 0;
2540   char *p;
2541   struct putval_item_s *vl, *vlprev;
2542
2543   if (ctrl->restricted)
2544     return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
2545
2546   for (p=line; *p == ' '; p++)
2547     ;
2548   key = p;
2549   p = strchr (key, ' ');
2550   if (p)
2551     {
2552       *p++ = 0;
2553       for (; *p == ' '; p++)
2554         ;
2555       if (*p)
2556         {
2557           value = p;
2558           p = strchr (value, ' ');
2559           if (p)
2560             *p = 0;
2561           valuelen = percent_plus_unescape_inplace (value, 0);
2562         }
2563     }
2564   if (!*key)
2565     return set_error (GPG_ERR_ASS_PARAMETER, "no key given");
2566
2567
2568   for (vl=putval_list,vlprev=NULL; vl; vlprev=vl, vl = vl->next)
2569     if ( !strcmp (vl->d, key) )
2570       break;
2571
2572   if (vl) /* Delete old entry. */
2573     {
2574       if (vlprev)
2575         vlprev->next = vl->next;
2576       else
2577         putval_list = vl->next;
2578       xfree (vl);
2579     }
2580
2581   if (valuelen) /* Add entry. */
2582     {
2583       vl = xtrymalloc (sizeof *vl + strlen (key) + valuelen);
2584       if (!vl)
2585         rc = gpg_error_from_syserror ();
2586       else
2587         {
2588           vl->len = valuelen;
2589           vl->off = strlen (key) + 1;
2590           strcpy (vl->d, key);
2591           memcpy (vl->d + vl->off, value, valuelen);
2592           vl->next = putval_list;
2593           putval_list = vl;
2594         }
2595     }
2596
2597   return leave_cmd (ctx, rc);
2598 }
2599
2600
2601
2602 \f
2603 static const char hlp_updatestartuptty[] =
2604   "UPDATESTARTUPTTY\n"
2605   "\n"
2606   "Set startup TTY and X11 DISPLAY variables to the values of this\n"
2607   "session.  This command is useful to pull future pinentries to\n"
2608   "another screen.  It is only required because there is no way in the\n"
2609   "ssh-agent protocol to convey this information.";
2610 static gpg_error_t
2611 cmd_updatestartuptty (assuan_context_t ctx, char *line)
2612 {
2613   static const char *names[] =
2614     { "GPG_TTY", "DISPLAY", "TERM", "XAUTHORITY", "PINENTRY_USER_DATA", NULL };
2615   ctrl_t ctrl = assuan_get_pointer (ctx);
2616   gpg_error_t err = 0;
2617   session_env_t se;
2618   int idx;
2619   char *lc_ctype = NULL;
2620   char *lc_messages = NULL;
2621
2622   (void)line;
2623
2624   if (ctrl->restricted)
2625     return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
2626
2627   se = session_env_new ();
2628   if (!se)
2629     err = gpg_error_from_syserror ();
2630
2631   for (idx=0; !err && names[idx]; idx++)
2632     {
2633       const char *value = session_env_getenv (ctrl->session_env, names[idx]);
2634       if (value)
2635         err = session_env_setenv (se, names[idx], value);
2636     }
2637
2638   if (!err && ctrl->lc_ctype)
2639     if (!(lc_ctype = xtrystrdup (ctrl->lc_ctype)))
2640       err = gpg_error_from_syserror ();
2641
2642   if (!err && ctrl->lc_messages)
2643     if (!(lc_messages = xtrystrdup (ctrl->lc_messages)))
2644       err = gpg_error_from_syserror ();
2645
2646   if (err)
2647     {
2648       session_env_release (se);
2649       xfree (lc_ctype);
2650       xfree (lc_messages);
2651     }
2652   else
2653     {
2654       session_env_release (opt.startup_env);
2655       opt.startup_env = se;
2656       xfree (opt.startup_lc_ctype);
2657       opt.startup_lc_ctype = lc_ctype;
2658       xfree (opt.startup_lc_messages);
2659       opt.startup_lc_messages = lc_messages;
2660     }
2661
2662   return err;
2663 }
2664
2665
2666 \f
2667 static const char hlp_killagent[] =
2668   "KILLAGENT\n"
2669   "\n"
2670   "Stop the agent.";
2671 static gpg_error_t
2672 cmd_killagent (assuan_context_t ctx, char *line)
2673 {
2674   ctrl_t ctrl = assuan_get_pointer (ctx);
2675
2676   (void)line;
2677
2678   if (ctrl->restricted)
2679     return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
2680
2681   ctrl->server_local->stopme = 1;
2682   assuan_set_flag (ctx, ASSUAN_FORCE_CLOSE, 1);
2683   return 0;
2684 }
2685
2686
2687 static const char hlp_reloadagent[] =
2688   "RELOADAGENT\n"
2689   "\n"
2690   "This command is an alternative to SIGHUP\n"
2691   "to reload the configuration.";
2692 static gpg_error_t
2693 cmd_reloadagent (assuan_context_t ctx, char *line)
2694 {
2695   ctrl_t ctrl = assuan_get_pointer (ctx);
2696
2697   (void)line;
2698
2699   if (ctrl->restricted)
2700     return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
2701
2702   agent_sighup_action ();
2703   return 0;
2704 }
2705
2706
2707 \f
2708 static const char hlp_getinfo[] =
2709   "GETINFO <what>\n"
2710   "\n"
2711   "Multipurpose function to return a variety of information.\n"
2712   "Supported values for WHAT are:\n"
2713   "\n"
2714   "  version     - Return the version of the program.\n"
2715   "  pid         - Return the process id of the server.\n"
2716   "  socket_name - Return the name of the socket.\n"
2717   "  ssh_socket_name - Return the name of the ssh socket.\n"
2718   "  scd_running - Return OK if the SCdaemon is already running.\n"
2719   "  s2k_count   - Return the calibrated S2K count.\n"
2720   "  std_env_names   - List the names of the standard environment.\n"
2721   "  std_session_env - List the standard session environment.\n"
2722   "  std_startup_env - List the standard startup environment.\n"
2723   "  cmd_has_option\n"
2724   "              - Returns OK if the command CMD implements the option OPT.\n"
2725   "  restricted  - Returns OK if the connection is in restricted mode.\n";
2726 static gpg_error_t
2727 cmd_getinfo (assuan_context_t ctx, char *line)
2728 {
2729   ctrl_t ctrl = assuan_get_pointer (ctx);
2730   int rc = 0;
2731
2732   if (!strcmp (line, "version"))
2733     {
2734       const char *s = VERSION;
2735       rc = assuan_send_data (ctx, s, strlen (s));
2736     }
2737   else if (!strncmp (line, "cmd_has_option", 14)
2738            && (line[14] == ' ' || line[14] == '\t' || !line[14]))
2739     {
2740       char *cmd, *cmdopt;
2741       line += 14;
2742       while (*line == ' ' || *line == '\t')
2743         line++;
2744       if (!*line)
2745         rc = gpg_error (GPG_ERR_MISSING_VALUE);
2746       else
2747         {
2748           cmd = line;
2749           while (*line && (*line != ' ' && *line != '\t'))
2750             line++;
2751           if (!*line)
2752             rc = gpg_error (GPG_ERR_MISSING_VALUE);
2753           else
2754             {
2755               *line++ = 0;
2756               while (*line == ' ' || *line == '\t')
2757                 line++;
2758               if (!*line)
2759                 rc = gpg_error (GPG_ERR_MISSING_VALUE);
2760               else
2761                 {
2762                   cmdopt = line;
2763                   if (!command_has_option (cmd, cmdopt))
2764                     rc = gpg_error (GPG_ERR_GENERAL);
2765                 }
2766             }
2767         }
2768     }
2769   else if (!strcmp (line, "s2k_count"))
2770     {
2771       char numbuf[50];
2772
2773       snprintf (numbuf, sizeof numbuf, "%lu", get_standard_s2k_count ());
2774       rc = assuan_send_data (ctx, numbuf, strlen (numbuf));
2775     }
2776   else if (!strcmp (line, "restricted"))
2777     {
2778       rc = ctrl->restricted? 0 : gpg_error (GPG_ERR_GENERAL);
2779     }
2780   else if (ctrl->restricted)
2781     {
2782       rc = gpg_error (GPG_ERR_FORBIDDEN);
2783     }
2784   /* All sub-commands below are not allowed in restricted mode.  */
2785   else if (!strcmp (line, "pid"))
2786     {
2787       char numbuf[50];
2788
2789       snprintf (numbuf, sizeof numbuf, "%lu", (unsigned long)getpid ());
2790       rc = assuan_send_data (ctx, numbuf, strlen (numbuf));
2791     }
2792   else if (!strcmp (line, "socket_name"))
2793     {
2794       const char *s = get_agent_socket_name ();
2795
2796       if (s)
2797         rc = assuan_send_data (ctx, s, strlen (s));
2798       else
2799         rc = gpg_error (GPG_ERR_NO_DATA);
2800     }
2801   else if (!strcmp (line, "ssh_socket_name"))
2802     {
2803       const char *s = get_agent_ssh_socket_name ();
2804
2805       if (s)
2806         rc = assuan_send_data (ctx, s, strlen (s));
2807       else
2808         rc = gpg_error (GPG_ERR_NO_DATA);
2809     }
2810   else if (!strcmp (line, "scd_running"))
2811     {
2812       rc = agent_scd_check_running ()? 0 : gpg_error (GPG_ERR_GENERAL);
2813     }
2814   else if (!strcmp (line, "std_env_names"))
2815     {
2816       int iterator;
2817       const char *name;
2818
2819       iterator = 0;
2820       while ((name = session_env_list_stdenvnames (&iterator, NULL)))
2821         {
2822           rc = assuan_send_data (ctx, name, strlen (name)+1);
2823           if (!rc)
2824             rc = assuan_send_data (ctx, NULL, 0);
2825           if (rc)
2826             break;
2827         }
2828     }
2829   else if (!strcmp (line, "std_session_env")
2830            || !strcmp (line, "std_startup_env"))
2831     {
2832       int iterator;
2833       const char *name, *value;
2834       char *string;
2835
2836       iterator = 0;
2837       while ((name = session_env_list_stdenvnames (&iterator, NULL)))
2838         {
2839           value = session_env_getenv_or_default
2840             (line[5] == 't'? opt.startup_env:ctrl->session_env, name, NULL);
2841           if (value)
2842             {
2843               string = xtryasprintf ("%s=%s", name, value);
2844               if (!string)
2845                 rc = gpg_error_from_syserror ();
2846               else
2847                 {
2848                   rc = assuan_send_data (ctx, string, strlen (string)+1);
2849                   if (!rc)
2850                     rc = assuan_send_data (ctx, NULL, 0);
2851                 }
2852               if (rc)
2853                 break;
2854             }
2855         }
2856     }
2857   else
2858     rc = set_error (GPG_ERR_ASS_PARAMETER, "unknown value for WHAT");
2859   return rc;
2860 }
2861
2862
2863 \f
2864 /* This function is called by Libassuan to parse the OPTION command.
2865    It has been registered similar to the other Assuan commands.  */
2866 static gpg_error_t
2867 option_handler (assuan_context_t ctx, const char *key, const char *value)
2868 {
2869   ctrl_t ctrl = assuan_get_pointer (ctx);
2870   gpg_error_t err = 0;
2871
2872   if (!strcmp (key, "agent-awareness"))
2873     {
2874       /* The value is a version string telling us of which agent
2875          version the caller is aware of.  */
2876       ctrl->server_local->allow_fully_canceled =
2877         gnupg_compare_version (value, "2.1.0");
2878     }
2879   else if (ctrl->restricted)
2880     {
2881       err = gpg_error (GPG_ERR_FORBIDDEN);
2882     }
2883   /* All options below are not allowed in restricted mode.  */
2884   else if (!strcmp (key, "putenv"))
2885     {
2886       /* Change the session's environment to be used for the
2887          Pinentry.  Valid values are:
2888           <NAME>            Delete envvar NAME
2889           <KEY>=            Set envvar NAME to the empty string
2890           <KEY>=<VALUE>     Set envvar NAME to VALUE
2891       */
2892       err = session_env_putenv (ctrl->session_env, value);
2893     }
2894   else if (!strcmp (key, "display"))
2895     {
2896       err = session_env_setenv (ctrl->session_env, "DISPLAY", value);
2897     }
2898   else if (!strcmp (key, "ttyname"))
2899     {
2900       if (!opt.keep_tty)
2901         err = session_env_setenv (ctrl->session_env, "GPG_TTY", value);
2902     }
2903   else if (!strcmp (key, "ttytype"))
2904     {
2905       if (!opt.keep_tty)
2906         err = session_env_setenv (ctrl->session_env, "TERM", value);
2907     }
2908   else if (!strcmp (key, "lc-ctype"))
2909     {
2910       if (ctrl->lc_ctype)
2911         xfree (ctrl->lc_ctype);
2912       ctrl->lc_ctype = xtrystrdup (value);
2913       if (!ctrl->lc_ctype)
2914         return out_of_core ();
2915     }
2916   else if (!strcmp (key, "lc-messages"))
2917     {
2918       if (ctrl->lc_messages)
2919         xfree (ctrl->lc_messages);
2920       ctrl->lc_messages = xtrystrdup (value);
2921       if (!ctrl->lc_messages)
2922         return out_of_core ();
2923     }
2924   else if (!strcmp (key, "xauthority"))
2925     {
2926       err = session_env_setenv (ctrl->session_env, "XAUTHORITY", value);
2927     }
2928   else if (!strcmp (key, "pinentry-user-data"))
2929     {
2930       err = session_env_setenv (ctrl->session_env, "PINENTRY_USER_DATA", value);
2931     }
2932   else if (!strcmp (key, "use-cache-for-signing"))
2933     ctrl->server_local->use_cache_for_signing = *value? atoi (value) : 0;
2934   else if (!strcmp (key, "allow-pinentry-notify"))
2935     ctrl->server_local->allow_pinentry_notify = 1;
2936   else if (!strcmp (key, "pinentry-mode"))
2937     {
2938       int tmp = parse_pinentry_mode (value);
2939       if (tmp == -1)
2940         err = gpg_error (GPG_ERR_INV_VALUE);
2941       else if (tmp == PINENTRY_MODE_LOOPBACK && !opt.allow_loopback_pinentry)
2942         err = gpg_error (GPG_ERR_NOT_SUPPORTED);
2943       else
2944         ctrl->pinentry_mode = tmp;
2945     }
2946   else if (!strcmp (key, "cache-ttl-opt-preset"))
2947     {
2948       ctrl->cache_ttl_opt_preset = *value? atoi (value) : 0;
2949     }
2950   else if (!strcmp (key, "s2k-count"))
2951     {
2952       ctrl->s2k_count = *value? strtoul(value, NULL, 10) : 0;
2953       if (ctrl->s2k_count && ctrl->s2k_count < 65536)
2954         {
2955           ctrl->s2k_count = 0;
2956         }
2957     }
2958   else
2959     err = gpg_error (GPG_ERR_UNKNOWN_OPTION);
2960
2961   return err;
2962 }
2963
2964
2965
2966 \f
2967 /* Called by libassuan after all commands. ERR is the error from the
2968    last assuan operation and not the one returned from the command. */
2969 static void
2970 post_cmd_notify (assuan_context_t ctx, gpg_error_t err)
2971 {
2972   ctrl_t ctrl = assuan_get_pointer (ctx);
2973
2974   (void)err;
2975
2976   /* Switch off any I/O monitor controlled logging pausing. */
2977   ctrl->server_local->pause_io_logging = 0;
2978 }
2979
2980
2981 /* This function is called by libassuan for all I/O.  We use it here
2982    to disable logging for the GETEVENTCOUNTER commands.  This is so
2983    that the debug output won't get cluttered by this primitive
2984    command.  */
2985 static unsigned int
2986 io_monitor (assuan_context_t ctx, void *hook, int direction,
2987             const char *line, size_t linelen)
2988 {
2989   ctrl_t ctrl = assuan_get_pointer (ctx);
2990
2991   (void) hook;
2992
2993   /* Note that we only check for the uppercase name.  This allows to
2994      see the logging for debugging if using a non-upercase command
2995      name. */
2996   if (ctx && direction == ASSUAN_IO_FROM_PEER
2997       && linelen >= 15
2998       && !strncmp (line, "GETEVENTCOUNTER", 15)
2999       && (linelen == 15 || spacep (line+15)))
3000     {
3001       ctrl->server_local->pause_io_logging = 1;
3002     }
3003
3004   return ctrl->server_local->pause_io_logging? ASSUAN_IO_MONITOR_NOLOG : 0;
3005 }
3006
3007
3008 /* Return true if the command CMD implements the option OPT.  */
3009 static int
3010 command_has_option (const char *cmd, const char *cmdopt)
3011 {
3012   if (!strcmp (cmd, "GET_PASSPHRASE"))
3013     {
3014       if (!strcmp (cmdopt, "repeat"))
3015           return 1;
3016     }
3017
3018   return 0;
3019 }
3020
3021
3022 /* Tell Libassuan about our commands.  Also register the other Assuan
3023    handlers. */
3024 static int
3025 register_commands (assuan_context_t ctx)
3026 {
3027   static struct {
3028     const char *name;
3029     assuan_handler_t handler;
3030     const char * const help;
3031   } table[] = {
3032     { "GETEVENTCOUNTER",cmd_geteventcounter, hlp_geteventcounter },
3033     { "ISTRUSTED",      cmd_istrusted, hlp_istrusted },
3034     { "HAVEKEY",        cmd_havekey,   hlp_havekey },
3035     { "KEYINFO",        cmd_keyinfo,   hlp_keyinfo },
3036     { "SIGKEY",         cmd_sigkey,    hlp_sigkey },
3037     { "SETKEY",         cmd_sigkey,    hlp_sigkey },
3038     { "SETKEYDESC",     cmd_setkeydesc,hlp_setkeydesc },
3039     { "SETHASH",        cmd_sethash,   hlp_sethash },
3040     { "PKSIGN",         cmd_pksign,    hlp_pksign },
3041     { "PKDECRYPT",      cmd_pkdecrypt, hlp_pkdecrypt },
3042     { "GENKEY",         cmd_genkey,    hlp_genkey },
3043     { "READKEY",        cmd_readkey,   hlp_readkey },
3044     { "GET_PASSPHRASE", cmd_get_passphrase, hlp_get_passphrase },
3045     { "PRESET_PASSPHRASE", cmd_preset_passphrase, hlp_preset_passphrase },
3046     { "CLEAR_PASSPHRASE", cmd_clear_passphrase,   hlp_clear_passphrase },
3047     { "GET_CONFIRMATION", cmd_get_confirmation,   hlp_get_confirmation },
3048     { "LISTTRUSTED",    cmd_listtrusted, hlp_listtrusted },
3049     { "MARKTRUSTED",    cmd_marktrusted, hlp_martrusted },
3050     { "LEARN",          cmd_learn,     hlp_learn },
3051     { "PASSWD",         cmd_passwd,    hlp_passwd },
3052     { "INPUT",          NULL },
3053     { "OUTPUT",         NULL },
3054     { "SCD",            cmd_scd,       hlp_scd },
3055     { "KEYWRAP_KEY",    cmd_keywrap_key, hlp_keywrap_key },
3056     { "IMPORT_KEY",     cmd_import_key, hlp_import_key },
3057     { "EXPORT_KEY",     cmd_export_key, hlp_export_key },
3058     { "DELETE_KEY",     cmd_delete_key, hlp_delete_key },
3059     { "GETVAL",         cmd_getval,    hlp_getval },
3060     { "PUTVAL",         cmd_putval,    hlp_putval },
3061     { "UPDATESTARTUPTTY",  cmd_updatestartuptty, hlp_updatestartuptty },
3062     { "KILLAGENT",      cmd_killagent,  hlp_killagent },
3063     { "RELOADAGENT",    cmd_reloadagent,hlp_reloadagent },
3064     { "GETINFO",        cmd_getinfo,   hlp_getinfo },
3065     { "KEYTOCARD",      cmd_keytocard, hlp_keytocard },
3066     { NULL }
3067   };
3068   int i, rc;
3069
3070   for (i=0; table[i].name; i++)
3071     {
3072       rc = assuan_register_command (ctx, table[i].name, table[i].handler,
3073                                     table[i].help);
3074       if (rc)
3075         return rc;
3076     }
3077   assuan_register_post_cmd_notify (ctx, post_cmd_notify);
3078   assuan_register_reset_notify (ctx, reset_notify);
3079   assuan_register_option_handler (ctx, option_handler);
3080   return 0;
3081 }
3082
3083
3084 /* Startup the server.  If LISTEN_FD and FD is given as -1, this is a
3085    simple piper server, otherwise it is a regular server.  CTRL is the
3086    control structure for this connection; it has only the basic
3087    intialization. */
3088 void
3089 start_command_handler (ctrl_t ctrl, gnupg_fd_t listen_fd, gnupg_fd_t fd)
3090 {
3091   int rc;
3092   assuan_context_t ctx = NULL;
3093
3094   if (ctrl->restricted)
3095     {
3096       if (agent_copy_startup_env (ctrl))
3097         return;
3098     }
3099
3100   rc = assuan_new (&ctx);
3101   if (rc)
3102     {
3103       log_error ("failed to allocate assuan context: %s\n", gpg_strerror (rc));
3104       agent_exit (2);
3105     }
3106
3107   if (listen_fd == GNUPG_INVALID_FD && fd == GNUPG_INVALID_FD)
3108     {
3109       assuan_fd_t filedes[2];
3110
3111       filedes[0] = assuan_fdopen (0);
3112       filedes[1] = assuan_fdopen (1);
3113       rc = assuan_init_pipe_server (ctx, filedes);
3114     }
3115   else if (listen_fd != GNUPG_INVALID_FD)
3116     {
3117       rc = assuan_init_socket_server (ctx, listen_fd, 0);
3118       /* FIXME: Need to call assuan_sock_set_nonce for Windows.  But
3119          this branch is currently not used.  */
3120     }
3121   else
3122     {
3123       rc = assuan_init_socket_server (ctx, fd, ASSUAN_SOCKET_SERVER_ACCEPTED);
3124     }
3125   if (rc)
3126     {
3127       log_error ("failed to initialize the server: %s\n",
3128                  gpg_strerror(rc));
3129       agent_exit (2);
3130     }
3131   rc = register_commands (ctx);
3132   if (rc)
3133     {
3134       log_error ("failed to register commands with Assuan: %s\n",
3135                  gpg_strerror(rc));
3136       agent_exit (2);
3137     }
3138
3139   assuan_set_pointer (ctx, ctrl);
3140   ctrl->server_local = xcalloc (1, sizeof *ctrl->server_local);
3141   ctrl->server_local->assuan_ctx = ctx;
3142   ctrl->server_local->use_cache_for_signing = 1;
3143   ctrl->digest.raw_value = 0;
3144
3145   assuan_set_io_monitor (ctx, io_monitor, NULL);
3146   agent_set_progress_cb (progress_cb, ctrl);
3147
3148   for (;;)
3149     {
3150       rc = assuan_accept (ctx);
3151       if (gpg_err_code (rc) == GPG_ERR_EOF || rc == -1)
3152         {
3153           break;
3154         }
3155       else if (rc)
3156         {
3157           log_info ("Assuan accept problem: %s\n", gpg_strerror (rc));
3158           break;
3159         }
3160
3161       rc = assuan_process (ctx);
3162       if (rc)
3163         {
3164           log_info ("Assuan processing failed: %s\n", gpg_strerror (rc));
3165           continue;
3166         }
3167     }
3168
3169   /* Reset the nonce caches.  */
3170   clear_nonce_cache (ctrl);
3171
3172   /* Reset the SCD if needed. */
3173   agent_reset_scd (ctrl);
3174
3175   /* Reset the pinentry (in case of popup messages). */
3176   agent_reset_query (ctrl);
3177
3178   /* Cleanup.  */
3179   assuan_release (ctx);
3180   xfree (ctrl->server_local->keydesc);
3181   xfree (ctrl->server_local->import_key);
3182   xfree (ctrl->server_local->export_key);
3183   if (ctrl->server_local->stopme)
3184     agent_exit (0);
3185   xfree (ctrl->server_local);
3186   ctrl->server_local = NULL;
3187 }
3188
3189
3190 /* Helper for the pinentry loopback mode.  It merely passes the
3191    parameters on to the client.  */
3192 gpg_error_t
3193 pinentry_loopback(ctrl_t ctrl, const char *keyword,
3194                   unsigned char **buffer, size_t *size,
3195                   size_t max_length)
3196 {
3197   gpg_error_t rc;
3198   assuan_context_t ctx = ctrl->server_local->assuan_ctx;
3199
3200   rc = print_assuan_status (ctx, "INQUIRE_MAXLEN", "%zu", max_length);
3201   if (rc)
3202     return rc;
3203
3204   assuan_begin_confidential (ctx);
3205   rc = assuan_inquire (ctx, keyword, buffer, size, max_length);
3206   assuan_end_confidential (ctx);
3207   return rc;
3208 }