2008-01-15 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / agent / command.c
blob91279fa0f5b04e229b97352a4b835af627aa3f16
1 /* command.c - gpg-agent command handler
2 * Copyright (C) 2001, 2002, 2003, 2004, 2005,
3 * 2006 Free Software Foundation, Inc.
5 * This file is part of GnuPG.
7 * GnuPG is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * GnuPG is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, see <http://www.gnu.org/licenses/>.
21 /* FIXME: we should not use the default assuan buffering but setup
22 some buffering in secure mempory to protect session keys etc. */
24 #include <config.h>
26 #include <errno.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <ctype.h>
31 #include <unistd.h>
32 #include <assert.h>
34 #include <assuan.h>
36 #include "agent.h"
38 /* maximum allowed size of the inquired ciphertext */
39 #define MAXLEN_CIPHERTEXT 4096
40 /* maximum allowed size of the key parameters */
41 #define MAXLEN_KEYPARAM 1024
43 #define set_error(e,t) assuan_set_error (ctx, gpg_error (e), (t))
46 #if MAX_DIGEST_LEN < 20
47 #error MAX_DIGEST_LEN shorter than keygrip
48 #endif
50 /* Data used to associate an Assuan context with local server data */
51 struct server_local_s
53 assuan_context_t assuan_ctx;
54 int message_fd;
55 int use_cache_for_signing;
56 char *keydesc; /* Allocated description for the next key
57 operation. */
58 int pause_io_logging; /* Used to suppress I/O logging during a command */
59 #ifdef HAVE_W32_SYSTEM
60 int stopme; /* If set to true the agent will be terminated after
61 the end of this session. */
62 #endif
66 /* An entry for the getval/putval commands. */
67 struct putval_item_s
69 struct putval_item_s *next;
70 size_t off; /* Offset to the value into DATA. */
71 size_t len; /* Length of the value. */
72 char d[1]; /* Key | Nul | value. */
76 /* A list of key value pairs fpr the getval/putval commands. */
77 static struct putval_item_s *putval_list;
81 /* To help polling clients, we keep tarck of the number of certain
82 events. This structure keeps those counters. The counters are
83 integers and there should be no problem if they are overflowing as
84 callers need to check only whether a counter changed. The actual
85 values are not meaningful. */
86 struct
88 /* Incremented if any of the other counters below changed. */
89 unsigned int any;
91 /* Incremented if a key is added or removed from the internal privat
92 key database. */
93 unsigned int key;
95 /* Incremented if a change of the card readers stati has been
96 detected. */
97 unsigned int card;
99 } eventcounter;
105 /* Release the memory buffer MB but first wipe out the used memory. */
106 static void
107 clear_outbuf (membuf_t *mb)
109 void *p;
110 size_t n;
112 p = get_membuf (mb, &n);
113 if (p)
115 memset (p, 0, n);
116 xfree (p);
121 /* Write the content of memory buffer MB as assuan data to CTX and
122 wipe the buffer out afterwards. */
123 static gpg_error_t
124 write_and_clear_outbuf (assuan_context_t ctx, membuf_t *mb)
126 assuan_error_t ae;
127 void *p;
128 size_t n;
130 p = get_membuf (mb, &n);
131 if (!p)
132 return out_of_core ();
133 ae = assuan_send_data (ctx, p, n);
134 memset (p, 0, n);
135 xfree (p);
136 return ae;
140 static void
141 reset_notify (assuan_context_t ctx)
143 ctrl_t ctrl = assuan_get_pointer (ctx);
145 memset (ctrl->keygrip, 0, 20);
146 ctrl->have_keygrip = 0;
147 ctrl->digest.valuelen = 0;
149 xfree (ctrl->server_local->keydesc);
150 ctrl->server_local->keydesc = NULL;
154 /* Check whether the option NAME appears in LINE */
155 static int
156 has_option (const char *line, const char *name)
158 const char *s;
159 int n = strlen (name);
161 s = strstr (line, name);
162 return (s && (s == line || spacep (s-1)) && (!s[n] || spacep (s+n)));
165 /* Same as has_option but does only test for the name of the option
166 and ignores an argument, i.e. with NAME being "--hash" it would
167 return true for "--hash" as well as for "--hash=foo". */
168 static int
169 has_option_name (const char *line, const char *name)
171 const char *s;
172 int n = strlen (name);
174 s = strstr (line, name);
175 return (s && (s == line || spacep (s-1))
176 && (!s[n] || spacep (s+n) || s[n] == '='));
180 /* Skip over options. It is assumed that leading spaces have been
181 removed (this is the case for lines passed to a handler from
182 assuan). Blanks after the options are also removed. */
183 static char *
184 skip_options (char *line)
186 while ( *line == '-' && line[1] == '-' )
188 while (*line && !spacep (line))
189 line++;
190 while (spacep (line))
191 line++;
193 return line;
197 /* Replace all '+' by a blank. */
198 static void
199 plus_to_blank (char *s)
201 for (; *s; s++)
203 if (*s == '+')
204 *s = ' ';
209 /* Do the percent and plus/space unescaping in place and return the
210 length of the valid buffer. */
211 static size_t
212 percent_plus_unescape (char *string)
214 unsigned char *p = (unsigned char *)string;
215 size_t n = 0;
217 while (*string)
219 if (*string == '%' && string[1] && string[2])
221 string++;
222 *p++ = xtoi_2 (string);
223 n++;
224 string+= 2;
226 else if (*string == '+')
228 *p++ = ' ';
229 n++;
230 string++;
232 else
234 *p++ = *string++;
235 n++;
239 return n;
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)
250 const char *p;
251 size_t n;
253 /* parse the hash value */
254 for (p=string, n=0; hexdigitp (p); p++, n++)
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;
264 /* Parse the keygrip in STRING into the provided buffer BUF. BUF must
265 provide space for 20 bytes. BUF is not changed if the function
266 returns an error. */
267 static int
268 parse_keygrip (assuan_context_t ctx, const char *string, unsigned char *buf)
270 int rc;
271 size_t n;
272 const unsigned char *p;
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");
281 for (p=(const unsigned char*)string, n=0; n < 20; p += 2, n++)
282 buf[n] = xtoi_2 (p);
284 return 0;
288 /* Write an assuan status line. */
289 gpg_error_t
290 agent_write_status (ctrl_t ctrl, const char *keyword, ...)
292 gpg_error_t err = 0;
293 va_list arg_ptr;
294 const char *text;
295 assuan_context_t ctx = ctrl->server_local->assuan_ctx;
296 char buf[950], *p;
297 size_t n;
299 va_start (arg_ptr, keyword);
301 p = buf;
302 n = 0;
303 while ( (text = va_arg (arg_ptr, const char *)) )
305 if (n)
307 *p++ = ' ';
308 n++;
310 for ( ; *text && n < DIM (buf)-2; n++)
311 *p++ = *text++;
313 *p = 0;
314 err = assuan_write_status (ctx, keyword, buf);
316 va_end (arg_ptr);
317 return err;
322 /* GETEVENTCOUNTER
324 Return a a status line named EVENTCOUNTER with the current values
325 of all event counters. The values are decimal numbers in the range
326 0 to UINT_MAX and wrapping around to 0. The actual values should
327 not be relied upon, they shall only be used to detect a change.
329 The currently defined counters are:
331 ANY - Incremented with any change of any of the other counters.
332 KEY - Incremented for added or removed private keys.
333 CARD - Incremented for changes of the card readers stati.
335 static int
336 cmd_geteventcounter (assuan_context_t ctx, char *line)
338 ctrl_t ctrl = assuan_get_pointer (ctx);
339 char any_counter[25];
340 char key_counter[25];
341 char card_counter[25];
343 snprintf (any_counter, sizeof any_counter, "%u", eventcounter.any);
344 snprintf (key_counter, sizeof key_counter, "%u", eventcounter.key);
345 snprintf (card_counter, sizeof card_counter, "%u", eventcounter.card);
347 return agent_write_status (ctrl, "EVENTCOUNTER",
348 any_counter,
349 key_counter,
350 card_counter,
351 NULL);
355 /* This function should be called once for all key removals or
356 additions. This function is assured not to do any context
357 switches. */
358 void
359 bump_key_eventcounter (void)
361 eventcounter.key++;
362 eventcounter.any++;
365 /* This function should be called for all card reader status
366 changes. This function is assured not to do any context
367 switches. */
368 void
369 bump_card_eventcounter (void)
371 eventcounter.card++;
372 eventcounter.any++;
378 /* ISTRUSTED <hexstring_with_fingerprint>
380 Return OK when we have an entry with this fingerprint in our
381 trustlist */
382 static int
383 cmd_istrusted (assuan_context_t ctx, char *line)
385 ctrl_t ctrl = assuan_get_pointer (ctx);
386 int rc, n, i;
387 char *p;
388 char fpr[41];
390 /* Parse the fingerprint value. */
391 for (p=line,n=0; hexdigitp (p); p++, n++)
393 if (*p || !(n == 40 || n == 32))
394 return set_error (GPG_ERR_ASS_PARAMETER, "invalid fingerprint");
395 i = 0;
396 if (n==32)
398 strcpy (fpr, "00000000");
399 i += 8;
401 for (p=line; i < 40; p++, i++)
402 fpr[i] = *p >= 'a'? (*p & 0xdf): *p;
403 fpr[i] = 0;
404 rc = agent_istrusted (ctrl, fpr);
405 if (!rc || gpg_err_code (rc) == GPG_ERR_NOT_TRUSTED)
406 return rc;
407 else if (rc == -1 || gpg_err_code (rc) == GPG_ERR_EOF )
408 return gpg_error (GPG_ERR_NOT_TRUSTED);
409 else
411 log_error ("command is_trusted failed: %s\n", gpg_strerror (rc));
412 return rc;
416 /* LISTTRUSTED
418 List all entries from the trustlist */
419 static int
420 cmd_listtrusted (assuan_context_t ctx, char *line)
422 int rc = agent_listtrusted (ctx);
423 if (rc)
424 log_error ("command listtrusted failed: %s\n", gpg_strerror (rc));
425 return rc;
429 /* MARKTRUSTED <hexstring_with_fingerprint> <flag> <display_name>
431 Store a new key in into the trustlist*/
432 static int
433 cmd_marktrusted (assuan_context_t ctx, char *line)
435 ctrl_t ctrl = assuan_get_pointer (ctx);
436 int rc, n, i;
437 char *p;
438 char fpr[41];
439 int flag;
441 /* parse the fingerprint value */
442 for (p=line,n=0; hexdigitp (p); p++, n++)
444 if (!spacep (p) || !(n == 40 || n == 32))
445 return set_error (GPG_ERR_ASS_PARAMETER, "invalid fingerprint");
446 i = 0;
447 if (n==32)
449 strcpy (fpr, "00000000");
450 i += 8;
452 for (p=line; i < 40; p++, i++)
453 fpr[i] = *p >= 'a'? (*p & 0xdf): *p;
454 fpr[i] = 0;
456 while (spacep (p))
457 p++;
458 flag = *p++;
459 if ( (flag != 'S' && flag != 'P') || !spacep (p) )
460 return set_error (GPG_ERR_ASS_PARAMETER, "invalid flag - must be P or S");
461 while (spacep (p))
462 p++;
464 rc = agent_marktrusted (ctrl, p, fpr, flag);
465 if (rc)
466 log_error ("command marktrusted failed: %s\n", gpg_strerror (rc));
467 return rc;
473 /* HAVEKEY <hexstring_with_keygrip>
475 Return success when the secret key is available */
476 static int
477 cmd_havekey (assuan_context_t ctx, char *line)
479 int rc;
480 unsigned char buf[20];
482 rc = parse_keygrip (ctx, line, buf);
483 if (rc)
484 return rc;
486 if (agent_key_available (buf))
487 return gpg_error (GPG_ERR_NO_SECKEY);
489 return 0;
493 /* SIGKEY <hexstring_with_keygrip>
494 SETKEY <hexstring_with_keygrip>
496 Set the key used for a sign or decrypt operation */
497 static int
498 cmd_sigkey (assuan_context_t ctx, char *line)
500 int rc;
501 ctrl_t ctrl = assuan_get_pointer (ctx);
503 rc = parse_keygrip (ctx, line, ctrl->keygrip);
504 if (rc)
505 return rc;
506 ctrl->have_keygrip = 1;
507 return 0;
511 /* SETKEYDESC plus_percent_escaped_string
513 Set a description to be used for the next PKSIGN or PKDECRYPT
514 operation if this operation requires the entry of a passphrase. If
515 this command is not used a default text will be used. Note, that
516 this description implictly selects the label used for the entry
517 box; if the string contains the string PIN (which in general will
518 not be translated), "PIN" is used, otherwise the translation of
519 "passphrase" is used. The description string should not contain
520 blanks unless they are percent or '+' escaped.
522 The description is only valid for the next PKSIGN or PKDECRYPT
523 operation.
525 static int
526 cmd_setkeydesc (assuan_context_t ctx, char *line)
528 ctrl_t ctrl = assuan_get_pointer (ctx);
529 char *desc, *p;
531 for (p=line; *p == ' '; p++)
533 desc = p;
534 p = strchr (desc, ' ');
535 if (p)
536 *p = 0; /* We ignore any garbage; we might late use it for other args. */
538 if (!desc || !*desc)
539 return set_error (GPG_ERR_ASS_PARAMETER, "no description given");
541 /* Note, that we only need to replace the + characters and should
542 leave the other escaping in place because the escaped string is
543 send verbatim to the pinentry which does the unescaping (but not
544 the + replacing) */
545 plus_to_blank (desc);
547 xfree (ctrl->server_local->keydesc);
548 ctrl->server_local->keydesc = xtrystrdup (desc);
549 if (!ctrl->server_local->keydesc)
550 return out_of_core ();
551 return 0;
555 /* SETHASH --hash=<name>|<algonumber> <hexstring>
557 The client can use this command to tell the server about the data
558 (which usually is a hash) to be signed. */
559 static int
560 cmd_sethash (assuan_context_t ctx, char *line)
562 int rc;
563 size_t n;
564 char *p;
565 ctrl_t ctrl = assuan_get_pointer (ctx);
566 unsigned char *buf;
567 char *endp;
568 int algo;
570 /* Parse the alternative hash options which may be used instead of
571 the algo number. */
572 if (has_option_name (line, "--hash"))
574 if (has_option (line, "--hash=sha1"))
575 algo = GCRY_MD_SHA1;
576 else if (has_option (line, "--hash=sha256"))
577 algo = GCRY_MD_SHA256;
578 else if (has_option (line, "--hash=rmd160"))
579 algo = GCRY_MD_RMD160;
580 else if (has_option (line, "--hash=md5"))
581 algo = GCRY_MD_MD5;
582 else if (has_option (line, "--hash=tls-md5sha1"))
583 algo = GCRY_MD_USER_TLS_MD5SHA1;
584 else
585 return set_error (GPG_ERR_ASS_PARAMETER, "invalid hash algorithm");
587 else
588 algo = 0;
590 line = skip_options (line);
592 if (!algo)
594 /* No hash option has been given: require an algo number instead */
595 algo = (int)strtoul (line, &endp, 10);
596 for (line = endp; *line == ' ' || *line == '\t'; line++)
598 if (!algo || gcry_md_test_algo (algo))
599 return set_error (GPG_ERR_UNSUPPORTED_ALGORITHM, NULL);
601 ctrl->digest.algo = algo;
603 /* Parse the hash value. */
604 rc = parse_hexstring (ctx, line, &n);
605 if (rc)
606 return rc;
607 n /= 2;
608 if (algo == GCRY_MD_USER_TLS_MD5SHA1 && n == 36)
610 else if (n != 16 && n != 20 && n != 24 && n != 32)
611 return set_error (GPG_ERR_ASS_PARAMETER, "unsupported length of hash");
613 if (n > MAX_DIGEST_LEN)
614 return set_error (GPG_ERR_ASS_PARAMETER, "hash value to long");
616 buf = ctrl->digest.value;
617 ctrl->digest.valuelen = n;
618 for (p=line, n=0; n < ctrl->digest.valuelen; p += 2, n++)
619 buf[n] = xtoi_2 (p);
620 for (; n < ctrl->digest.valuelen; n++)
621 buf[n] = 0;
622 return 0;
626 /* PKSIGN <options>
628 Perform the actual sign operation. Neither input nor output are
629 sensitive to eavesdropping. */
630 static int
631 cmd_pksign (assuan_context_t ctx, char *line)
633 int rc;
634 cache_mode_t cache_mode = CACHE_MODE_NORMAL;
635 ctrl_t ctrl = assuan_get_pointer (ctx);
636 membuf_t outbuf;
638 if (opt.ignore_cache_for_signing)
639 cache_mode = CACHE_MODE_IGNORE;
640 else if (!ctrl->server_local->use_cache_for_signing)
641 cache_mode = CACHE_MODE_IGNORE;
643 init_membuf (&outbuf, 512);
645 rc = agent_pksign (ctrl, ctrl->server_local->keydesc,
646 &outbuf, cache_mode);
647 if (rc)
648 clear_outbuf (&outbuf);
649 else
650 rc = write_and_clear_outbuf (ctx, &outbuf);
651 if (rc)
652 log_error ("command pksign failed: %s\n", gpg_strerror (rc));
653 xfree (ctrl->server_local->keydesc);
654 ctrl->server_local->keydesc = NULL;
655 return rc;
658 /* PKDECRYPT <options>
660 Perform the actual decrypt operation. Input is not
661 sensitive to eavesdropping */
662 static int
663 cmd_pkdecrypt (assuan_context_t ctx, char *line)
665 int rc;
666 ctrl_t ctrl = assuan_get_pointer (ctx);
667 unsigned char *value;
668 size_t valuelen;
669 membuf_t outbuf;
671 /* First inquire the data to decrypt */
672 rc = assuan_inquire (ctx, "CIPHERTEXT",
673 &value, &valuelen, MAXLEN_CIPHERTEXT);
674 if (rc)
675 return rc;
677 init_membuf (&outbuf, 512);
679 rc = agent_pkdecrypt (ctrl, ctrl->server_local->keydesc,
680 value, valuelen, &outbuf);
681 xfree (value);
682 if (rc)
683 clear_outbuf (&outbuf);
684 else
685 rc = write_and_clear_outbuf (ctx, &outbuf);
686 if (rc)
687 log_error ("command pkdecrypt failed: %s\n", gpg_strerror (rc));
688 xfree (ctrl->server_local->keydesc);
689 ctrl->server_local->keydesc = NULL;
690 return rc;
694 /* GENKEY
696 Generate a new key, store the secret part and return the public
697 part. Here is an example transaction:
699 C: GENKEY
700 S: INQUIRE KEYPARM
701 C: D (genkey (rsa (nbits 1024)))
702 C: END
703 S: D (public-key
704 S: D (rsa (n 326487324683264) (e 10001)))
705 S OK key created
708 static int
709 cmd_genkey (assuan_context_t ctx, char *line)
711 ctrl_t ctrl = assuan_get_pointer (ctx);
712 int rc;
713 unsigned char *value;
714 size_t valuelen;
715 membuf_t outbuf;
717 /* First inquire the parameters */
718 rc = assuan_inquire (ctx, "KEYPARAM", &value, &valuelen, MAXLEN_KEYPARAM);
719 if (rc)
720 return rc;
722 init_membuf (&outbuf, 512);
724 rc = agent_genkey (ctrl, (char*)value, valuelen, &outbuf);
725 xfree (value);
726 if (rc)
727 clear_outbuf (&outbuf);
728 else
729 rc = write_and_clear_outbuf (ctx, &outbuf);
730 if (rc)
731 log_error ("command genkey failed: %s\n", gpg_strerror (rc));
732 return rc;
738 /* READKEY <hexstring_with_keygrip>
740 Return the public key for the given keygrip. */
741 static int
742 cmd_readkey (assuan_context_t ctx, char *line)
744 ctrl_t ctrl = assuan_get_pointer (ctx);
745 int rc;
746 unsigned char grip[20];
747 gcry_sexp_t s_pkey = NULL;
749 rc = parse_keygrip (ctx, line, grip);
750 if (rc)
751 return rc; /* Return immediately as this is already an Assuan error code.*/
753 rc = agent_public_key_from_file (ctrl, grip, &s_pkey);
754 if (!rc)
756 size_t len;
757 unsigned char *buf;
759 len = gcry_sexp_sprint (s_pkey, GCRYSEXP_FMT_CANON, NULL, 0);
760 assert (len);
761 buf = xtrymalloc (len);
762 if (!buf)
763 rc = gpg_error_from_syserror ();
764 else
766 len = gcry_sexp_sprint (s_pkey, GCRYSEXP_FMT_CANON, buf, len);
767 assert (len);
768 rc = assuan_send_data (ctx, buf, len);
769 xfree (buf);
771 gcry_sexp_release (s_pkey);
774 if (rc)
775 log_error ("command readkey failed: %s\n", gpg_strerror (rc));
776 return rc;
784 static int
785 send_back_passphrase (assuan_context_t ctx, int via_data, const char *pw)
787 size_t n;
788 int rc;
790 assuan_begin_confidential (ctx);
791 n = strlen (pw);
792 if (via_data)
793 rc = assuan_send_data (ctx, pw, n);
794 else
796 char *p = xtrymalloc_secure (n*2+1);
797 if (!p)
798 rc = gpg_error_from_syserror ();
799 else
801 bin2hex (pw, n, p);
802 rc = assuan_set_okay_line (ctx, p);
803 xfree (p);
806 return rc;
810 /* GET_PASSPHRASE [--data] [--check] <cache_id>
811 [<error_message> <prompt> <description>]
813 This function is usually used to ask for a passphrase to be used
814 for conventional encryption, but may also be used by programs which
815 need specal handling of passphrases. This command uses a syntax
816 which helps clients to use the agent with minimum effort. The
817 agent either returns with an error or with a OK followed by the hex
818 encoded passphrase. Note that the length of the strings is
819 implicitly limited by the maximum length of a command.
821 If the option "--data" is used the passphrase is returned by usual
822 data lines and not on the okay line.
824 If the option "--check" is used the passphrase constraints checks as
825 implemented by gpg-agent are applied. A check is not done if the
826 passphrase has been found in the cache.
829 static int
830 cmd_get_passphrase (assuan_context_t ctx, char *line)
832 ctrl_t ctrl = assuan_get_pointer (ctx);
833 int rc;
834 const char *pw;
835 char *response;
836 char *cacheid = NULL, *desc = NULL, *prompt = NULL, *errtext = NULL;
837 char *p;
838 void *cache_marker;
839 int opt_data, opt_check;
841 opt_data = has_option (line, "--data");
842 opt_check = has_option (line, "--check");
843 line = skip_options (line);
845 cacheid = line;
846 p = strchr (cacheid, ' ');
847 if (p)
849 *p++ = 0;
850 while (*p == ' ')
851 p++;
852 errtext = p;
853 p = strchr (errtext, ' ');
854 if (p)
856 *p++ = 0;
857 while (*p == ' ')
858 p++;
859 prompt = p;
860 p = strchr (prompt, ' ');
861 if (p)
863 *p++ = 0;
864 while (*p == ' ')
865 p++;
866 desc = p;
867 p = strchr (desc, ' ');
868 if (p)
869 *p = 0; /* Ignore trailing garbage. */
873 if (!cacheid || !*cacheid || strlen (cacheid) > 50)
874 return set_error (GPG_ERR_ASS_PARAMETER, "invalid length of cacheID");
875 if (!desc)
876 return set_error (GPG_ERR_ASS_PARAMETER, "no description given");
878 if (!strcmp (cacheid, "X"))
879 cacheid = NULL;
880 if (!strcmp (errtext, "X"))
881 errtext = NULL;
882 if (!strcmp (prompt, "X"))
883 prompt = NULL;
884 if (!strcmp (desc, "X"))
885 desc = NULL;
887 pw = cacheid ? agent_get_cache (cacheid, CACHE_MODE_NORMAL, &cache_marker)
888 : NULL;
889 if (pw)
891 rc = send_back_passphrase (ctx, opt_data, pw);
892 agent_unlock_cache_entry (&cache_marker);
894 else
896 /* Note, that we only need to replace the + characters and
897 should leave the other escaping in place because the escaped
898 string is send verbatim to the pinentry which does the
899 unescaping (but not the + replacing) */
900 if (errtext)
901 plus_to_blank (errtext);
902 if (prompt)
903 plus_to_blank (prompt);
904 if (desc)
905 plus_to_blank (desc);
907 response = NULL;
910 xfree (response);
911 rc = agent_get_passphrase (ctrl, &response, desc, prompt, errtext);
913 while (!rc
914 && opt_check
915 && check_passphrase_constraints (ctrl, response, 0));
917 if (!rc)
919 if (cacheid)
920 agent_put_cache (cacheid, CACHE_MODE_USER, response, 0);
921 rc = send_back_passphrase (ctx, opt_data, response);
922 xfree (response);
926 if (rc)
927 log_error ("command get_passphrase failed: %s\n", gpg_strerror (rc));
928 return rc;
932 /* CLEAR_PASSPHRASE <cache_id>
934 may be used to invalidate the cache entry for a passphrase. The
935 function returns with OK even when there is no cached passphrase.
938 static int
939 cmd_clear_passphrase (assuan_context_t ctx, char *line)
941 char *cacheid = NULL;
942 char *p;
944 /* parse the stuff */
945 for (p=line; *p == ' '; p++)
947 cacheid = p;
948 p = strchr (cacheid, ' ');
949 if (p)
950 *p = 0; /* ignore garbage */
951 if (!cacheid || !*cacheid || strlen (cacheid) > 50)
952 return set_error (GPG_ERR_ASS_PARAMETER, "invalid length of cacheID");
954 agent_put_cache (cacheid, CACHE_MODE_USER, NULL, 0);
955 return 0;
959 /* GET_CONFIRMATION <description>
961 This command may be used to ask for a simple confirmation.
962 DESCRIPTION is displayed along with a Okay and Cancel button. This
963 command uses a syntax which helps clients to use the agent with
964 minimum effort. The agent either returns with an error or with a
965 OK. Note, that the length of DESCRIPTION is implicitly limited by
966 the maximum length of a command. DESCRIPTION should not contain
967 any spaces, those must be encoded either percent escaped or simply
968 as '+'.
971 static int
972 cmd_get_confirmation (assuan_context_t ctx, char *line)
974 ctrl_t ctrl = assuan_get_pointer (ctx);
975 int rc;
976 char *desc = NULL;
977 char *p;
979 /* parse the stuff */
980 for (p=line; *p == ' '; p++)
982 desc = p;
983 p = strchr (desc, ' ');
984 if (p)
985 *p = 0; /* We ignore any garbage -may be later used for other args. */
987 if (!desc || !*desc)
988 return set_error (GPG_ERR_ASS_PARAMETER, "no description given");
990 if (!strcmp (desc, "X"))
991 desc = NULL;
993 /* Note, that we only need to replace the + characters and should
994 leave the other escaping in place because the escaped string is
995 send verbatim to the pinentry which does the unescaping (but not
996 the + replacing) */
997 if (desc)
998 plus_to_blank (desc);
1000 rc = agent_get_confirmation (ctrl, desc, NULL, NULL);
1001 if (rc)
1002 log_error ("command get_confirmation failed: %s\n", gpg_strerror (rc));
1003 return rc;
1008 /* LEARN [--send]
1010 Learn something about the currently inserted smartcard. With
1011 --send the new certificates are send back. */
1012 static int
1013 cmd_learn (assuan_context_t ctx, char *line)
1015 ctrl_t ctrl = assuan_get_pointer (ctx);
1016 int rc;
1018 rc = agent_handle_learn (ctrl, has_option (line, "--send")? ctx : NULL);
1019 if (rc)
1020 log_error ("command learn failed: %s\n", gpg_strerror (rc));
1021 return rc;
1026 /* PASSWD <hexstring_with_keygrip>
1028 Change the passphrase/PID for the key identified by keygrip in LINE. */
1029 static int
1030 cmd_passwd (assuan_context_t ctx, char *line)
1032 ctrl_t ctrl = assuan_get_pointer (ctx);
1033 int rc;
1034 unsigned char grip[20];
1035 gcry_sexp_t s_skey = NULL;
1036 unsigned char *shadow_info = NULL;
1038 rc = parse_keygrip (ctx, line, grip);
1039 if (rc)
1040 goto leave;
1042 ctrl->in_passwd++;
1043 rc = agent_key_from_file (ctrl, ctrl->server_local->keydesc,
1044 grip, &shadow_info, CACHE_MODE_IGNORE, &s_skey);
1045 if (rc)
1047 else if (!s_skey)
1049 log_error ("changing a smartcard PIN is not yet supported\n");
1050 rc = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1052 else
1053 rc = agent_protect_and_store (ctrl, s_skey);
1054 ctrl->in_passwd--;
1056 xfree (ctrl->server_local->keydesc);
1057 ctrl->server_local->keydesc = NULL;
1059 leave:
1060 gcry_sexp_release (s_skey);
1061 xfree (shadow_info);
1062 if (rc)
1063 log_error ("command passwd failed: %s\n", gpg_strerror (rc));
1064 return rc;
1067 /* PRESET_PASSPHRASE <hexstring_with_keygrip> <timeout> <hexstring>
1069 Set the cached passphrase/PIN for the key identified by the keygrip
1070 to passwd for the given time, where -1 means infinite and 0 means
1071 the default (currently only a timeout of -1 is allowed, which means
1072 to never expire it). If passwd is not provided, ask for it via the
1073 pinentry module. */
1074 static int
1075 cmd_preset_passphrase (assuan_context_t ctx, char *line)
1077 int rc;
1078 unsigned char grip[20];
1079 char *grip_clear = NULL;
1080 char *passphrase = NULL;
1081 int ttl;
1082 size_t len;
1084 if (!opt.allow_preset_passphrase)
1085 return gpg_error (GPG_ERR_NOT_SUPPORTED);
1087 rc = parse_keygrip (ctx, line, grip);
1088 if (rc)
1089 return rc;
1091 /* FIXME: parse_keygrip should return a tail pointer. */
1092 grip_clear = line;
1093 while (*line && (*line != ' ' && *line != '\t'))
1094 line++;
1095 if (!*line)
1096 return gpg_error (GPG_ERR_MISSING_VALUE);
1097 *line = '\0';
1098 line++;
1099 while (*line && (*line == ' ' || *line == '\t'))
1100 line++;
1102 /* Currently, only infinite timeouts are allowed. */
1103 ttl = -1;
1104 if (line[0] != '-' || line[1] != '1')
1105 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1106 line++;
1107 line++;
1108 while (!(*line != ' ' && *line != '\t'))
1109 line++;
1111 /* Syntax check the hexstring. */
1112 rc = parse_hexstring (ctx, line, &len);
1113 if (rc)
1114 return rc;
1115 line[len] = '\0';
1117 /* If there is a passphrase, use it. Currently, a passphrase is
1118 required. */
1119 if (*line)
1120 passphrase = line;
1121 else
1122 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1124 rc = agent_put_cache (grip_clear, CACHE_MODE_ANY, passphrase, ttl);
1126 if (rc)
1127 log_error ("command preset_passwd failed: %s\n", gpg_strerror (rc));
1129 return rc;
1133 /* SCD <commands to pass to the scdaemon>
1135 This is a general quote command to redirect everything to the
1136 SCDAEMON. */
1137 static int
1138 cmd_scd (assuan_context_t ctx, char *line)
1140 ctrl_t ctrl = assuan_get_pointer (ctx);
1141 int rc;
1143 rc = divert_generic_cmd (ctrl, line, ctx);
1145 return rc;
1150 /* GETVAL <key>
1152 Return the value for KEY from the special environment as created by
1153 PUTVAL.
1155 static int
1156 cmd_getval (assuan_context_t ctx, char *line)
1158 int rc = 0;
1159 char *key = NULL;
1160 char *p;
1161 struct putval_item_s *vl;
1163 for (p=line; *p == ' '; p++)
1165 key = p;
1166 p = strchr (key, ' ');
1167 if (p)
1169 *p++ = 0;
1170 for (; *p == ' '; p++)
1172 if (*p)
1173 return set_error (GPG_ERR_ASS_PARAMETER, "too many arguments");
1175 if (!key || !*key)
1176 return set_error (GPG_ERR_ASS_PARAMETER, "no key given");
1179 for (vl=putval_list; vl; vl = vl->next)
1180 if ( !strcmp (vl->d, key) )
1181 break;
1183 if (vl) /* Got an entry. */
1184 rc = assuan_send_data (ctx, vl->d+vl->off, vl->len);
1185 else
1186 return gpg_error (GPG_ERR_NO_DATA);
1188 if (rc)
1189 log_error ("command getval failed: %s\n", gpg_strerror (rc));
1190 return rc;
1194 /* PUTVAL <key> [<percent_escaped_value>]
1196 The gpg-agent maintains a kind of environment which may be used to
1197 store key/value pairs in it, so that they can be retrieved later.
1198 This may be used by helper daemons to daemonize themself on
1199 invocation and register them with gpg-agent. Callers of the
1200 daemon's service may now first try connect to get the information
1201 for that service from gpg-agent through the GETVAL command and then
1202 try to connect to that daemon. Only if that fails they may start
1203 an own instance of the service daemon.
1205 KEY is an an arbitrary symbol with the same syntax rules as keys
1206 for shell environment variables. PERCENT_ESCAPED_VALUE is the
1207 corresponsing value; they should be similar to the values of
1208 envronment variables but gpg-agent does not enforce any
1209 restrictions. If that value is not given any value under that KEY
1210 is removed from this special environment.
1212 static int
1213 cmd_putval (assuan_context_t ctx, char *line)
1215 int rc = 0;
1216 char *key = NULL;
1217 char *value = NULL;
1218 size_t valuelen = 0;
1219 char *p;
1220 struct putval_item_s *vl, *vlprev;
1222 for (p=line; *p == ' '; p++)
1224 key = p;
1225 p = strchr (key, ' ');
1226 if (p)
1228 *p++ = 0;
1229 for (; *p == ' '; p++)
1231 if (*p)
1233 value = p;
1234 p = strchr (value, ' ');
1235 if (p)
1236 *p = 0;
1237 valuelen = percent_plus_unescape (value);
1240 if (!key || !*key)
1241 return set_error (GPG_ERR_ASS_PARAMETER, "no key given");
1244 for (vl=putval_list,vlprev=NULL; vl; vlprev=vl, vl = vl->next)
1245 if ( !strcmp (vl->d, key) )
1246 break;
1248 if (vl) /* Delete old entry. */
1250 if (vlprev)
1251 vlprev->next = vl->next;
1252 else
1253 putval_list = vl->next;
1254 xfree (vl);
1257 if (valuelen) /* Add entry. */
1259 vl = xtrymalloc (sizeof *vl + strlen (key) + valuelen);
1260 if (!vl)
1261 rc = gpg_error_from_syserror ();
1262 else
1264 vl->len = valuelen;
1265 vl->off = strlen (key) + 1;
1266 strcpy (vl->d, key);
1267 memcpy (vl->d + vl->off, value, valuelen);
1268 vl->next = putval_list;
1269 putval_list = vl;
1273 if (rc)
1274 log_error ("command putval failed: %s\n", gpg_strerror (rc));
1275 return rc;
1281 /* UPDATESTARTUPTTY
1283 Set startup TTY and X DISPLAY variables to the values of this
1284 session. This command is useful to pull future pinentries to
1285 another screen. It is only required because there is no way in the
1286 ssh-agent protocol to convey this information. */
1287 static int
1288 cmd_updatestartuptty (assuan_context_t ctx, char *line)
1290 ctrl_t ctrl = assuan_get_pointer (ctx);
1292 xfree (opt.startup_display); opt.startup_display = NULL;
1293 xfree (opt.startup_ttyname); opt.startup_ttyname = NULL;
1294 xfree (opt.startup_ttytype); opt.startup_ttytype = NULL;
1295 xfree (opt.startup_lc_ctype); opt.startup_lc_ctype = NULL;
1296 xfree (opt.startup_lc_messages); opt.startup_lc_messages = NULL;
1297 xfree (opt.startup_xauthority); opt.startup_xauthority = NULL;
1299 if (ctrl->display)
1300 opt.startup_display = xtrystrdup (ctrl->display);
1301 if (ctrl->ttyname)
1302 opt.startup_ttyname = xtrystrdup (ctrl->ttyname);
1303 if (ctrl->ttytype)
1304 opt.startup_ttytype = xtrystrdup (ctrl->ttytype);
1305 if (ctrl->lc_ctype)
1306 opt.startup_lc_ctype = xtrystrdup (ctrl->lc_ctype);
1307 if (ctrl->lc_messages)
1308 opt.startup_lc_messages = xtrystrdup (ctrl->lc_messages);
1309 if (ctrl->xauthority)
1310 opt.startup_xauthority = xtrystrdup (ctrl->xauthority);
1311 if (ctrl->pinentry_user_data)
1312 opt.startup_pinentry_user_data = xtrystrdup (ctrl->pinentry_user_data);
1314 return 0;
1319 #ifdef HAVE_W32_SYSTEM
1320 /* KILLAGENT
1322 Under Windows we start the agent on the fly. Thus it also make
1323 sense to allow a client to stop the agent. */
1324 static int
1325 cmd_killagent (assuan_context_t ctx, char *line)
1327 ctrl_t ctrl = assuan_get_pointer (ctx);
1328 ctrl->server_local->stopme = 1;
1329 return 0;
1332 /* RELOADAGENT
1334 As signals are inconvenient under Windows, we provide this command
1335 to allow reloading of the configuration. */
1336 static int
1337 cmd_reloadagent (assuan_context_t ctx, char *line)
1339 agent_sighup_action ();
1340 return 0;
1342 #endif /*HAVE_W32_SYSTEM*/
1346 /* GETINFO <what>
1348 Multipurpose function to return a variety of information.
1349 Supported values for WHAT are:
1351 version - Return the version of the program.
1352 pid - Return the process id of the server.
1353 socket_name - Return the name of the socket.
1354 ssh_socket_name - Return the name of the ssh socket.
1357 static int
1358 cmd_getinfo (assuan_context_t ctx, char *line)
1360 int rc = 0;
1362 if (!strcmp (line, "version"))
1364 const char *s = VERSION;
1365 rc = assuan_send_data (ctx, s, strlen (s));
1367 else if (!strcmp (line, "pid"))
1369 char numbuf[50];
1371 snprintf (numbuf, sizeof numbuf, "%lu", (unsigned long)getpid ());
1372 rc = assuan_send_data (ctx, numbuf, strlen (numbuf));
1374 else if (!strcmp (line, "socket_name"))
1376 const char *s = get_agent_socket_name ();
1378 if (s)
1379 rc = assuan_send_data (ctx, s, strlen (s));
1380 else
1381 rc = gpg_error (GPG_ERR_NO_DATA);
1383 else if (!strcmp (line, "ssh_socket_name"))
1385 const char *s = get_agent_ssh_socket_name ();
1387 if (s)
1388 rc = assuan_send_data (ctx, s, strlen (s));
1389 else
1390 rc = gpg_error (GPG_ERR_NO_DATA);
1392 else
1393 rc = set_error (GPG_ERR_ASS_PARAMETER, "unknown value for WHAT");
1394 return rc;
1399 static int
1400 option_handler (assuan_context_t ctx, const char *key, const char *value)
1402 ctrl_t ctrl = assuan_get_pointer (ctx);
1404 if (!strcmp (key, "display"))
1406 if (ctrl->display)
1407 free (ctrl->display);
1408 ctrl->display = strdup (value);
1409 if (!ctrl->display)
1410 return out_of_core ();
1412 else if (!strcmp (key, "ttyname"))
1414 if (!opt.keep_tty)
1416 if (ctrl->ttyname)
1417 free (ctrl->ttyname);
1418 ctrl->ttyname = strdup (value);
1419 if (!ctrl->ttyname)
1420 return out_of_core ();
1423 else if (!strcmp (key, "ttytype"))
1425 if (!opt.keep_tty)
1427 if (ctrl->ttytype)
1428 free (ctrl->ttytype);
1429 ctrl->ttytype = strdup (value);
1430 if (!ctrl->ttytype)
1431 return out_of_core ();
1434 else if (!strcmp (key, "lc-ctype"))
1436 if (ctrl->lc_ctype)
1437 free (ctrl->lc_ctype);
1438 ctrl->lc_ctype = strdup (value);
1439 if (!ctrl->lc_ctype)
1440 return out_of_core ();
1442 else if (!strcmp (key, "lc-messages"))
1444 if (ctrl->lc_messages)
1445 free (ctrl->lc_messages);
1446 ctrl->lc_messages = strdup (value);
1447 if (!ctrl->lc_messages)
1448 return out_of_core ();
1450 else if (!strcmp (key, "xauthority"))
1452 if (ctrl->xauthority)
1453 free (ctrl->xauthority);
1454 ctrl->xauthority = strdup (value);
1455 if (!ctrl->xauthority)
1456 return out_of_core ();
1458 else if (!strcmp (key, "pinentry-user-data"))
1460 if (ctrl->pinentry_user_data)
1461 free (ctrl->pinentry_user_data);
1462 ctrl->pinentry_user_data = strdup (value);
1463 if (!ctrl->pinentry_user_data)
1464 return out_of_core ();
1466 else if (!strcmp (key, "use-cache-for-signing"))
1467 ctrl->server_local->use_cache_for_signing = *value? atoi (value) : 0;
1468 else
1469 return gpg_error (GPG_ERR_UNKNOWN_OPTION);
1471 return 0;
1477 /* Called by libassuan after all commands. ERR is the error from the
1478 last assuan operation and not the one returned from the command. */
1479 static void
1480 post_cmd_notify (assuan_context_t ctx, int err)
1482 ctrl_t ctrl = assuan_get_pointer (ctx);
1484 /* Switch off any I/O monitor controlled logging pausing. */
1485 ctrl->server_local->pause_io_logging = 0;
1489 /* This function is called by libassuan for all I/O. We use it here
1490 to disable logging for the GETEVENTCOUNTER commands. This is so
1491 that the debug output won't get cluttered by this primitive
1492 command. */
1493 static unsigned int
1494 io_monitor (assuan_context_t ctx, int direction,
1495 const char *line, size_t linelen)
1497 ctrl_t ctrl = assuan_get_pointer (ctx);
1499 /* Note that we only check for the uppercase name. This allows to
1500 see the logging for debugging if using a non-upercase command
1501 name. */
1502 if (ctx && !direction
1503 && linelen >= 15
1504 && !strncmp (line, "GETEVENTCOUNTER", 15)
1505 && (linelen == 15 || spacep (line+15)))
1507 ctrl->server_local->pause_io_logging = 1;
1510 return ctrl->server_local->pause_io_logging? 1:0;
1514 /* Tell the assuan library about our commands */
1515 static int
1516 register_commands (assuan_context_t ctx)
1518 static struct {
1519 const char *name;
1520 int (*handler)(assuan_context_t, char *line);
1521 } table[] = {
1522 { "GETEVENTCOUNTER",cmd_geteventcounter },
1523 { "ISTRUSTED", cmd_istrusted },
1524 { "HAVEKEY", cmd_havekey },
1525 { "SIGKEY", cmd_sigkey },
1526 { "SETKEY", cmd_sigkey },
1527 { "SETKEYDESC", cmd_setkeydesc },
1528 { "SETHASH", cmd_sethash },
1529 { "PKSIGN", cmd_pksign },
1530 { "PKDECRYPT", cmd_pkdecrypt },
1531 { "GENKEY", cmd_genkey },
1532 { "READKEY", cmd_readkey },
1533 { "GET_PASSPHRASE", cmd_get_passphrase },
1534 { "PRESET_PASSPHRASE", cmd_preset_passphrase },
1535 { "CLEAR_PASSPHRASE", cmd_clear_passphrase },
1536 { "GET_CONFIRMATION", cmd_get_confirmation },
1537 { "LISTTRUSTED", cmd_listtrusted },
1538 { "MARKTRUSTED", cmd_marktrusted },
1539 { "LEARN", cmd_learn },
1540 { "PASSWD", cmd_passwd },
1541 { "INPUT", NULL },
1542 { "OUTPUT", NULL },
1543 { "SCD", cmd_scd },
1544 { "GETVAL", cmd_getval },
1545 { "PUTVAL", cmd_putval },
1546 { "UPDATESTARTUPTTY", cmd_updatestartuptty },
1547 #ifdef HAVE_W32_SYSTEM
1548 { "KILLAGENT", cmd_killagent },
1549 { "RELOADAGENT", cmd_reloadagent },
1550 #endif
1551 { "GETINFO", cmd_getinfo },
1552 { NULL }
1554 int i, rc;
1556 for (i=0; table[i].name; i++)
1558 rc = assuan_register_command (ctx, table[i].name, table[i].handler);
1559 if (rc)
1560 return rc;
1562 #ifdef HAVE_ASSUAN_SET_IO_MONITOR
1563 assuan_register_post_cmd_notify (ctx, post_cmd_notify);
1564 #endif
1565 assuan_register_reset_notify (ctx, reset_notify);
1566 assuan_register_option_handler (ctx, option_handler);
1567 return 0;
1571 /* Startup the server. If LISTEN_FD and FD is given as -1, this is a
1572 simple piper server, otherwise it is a regular server. CTRL is the
1573 control structure for this connection; it has only the basic
1574 intialization. */
1575 void
1576 start_command_handler (ctrl_t ctrl, gnupg_fd_t listen_fd, gnupg_fd_t fd)
1578 int rc;
1579 assuan_context_t ctx;
1581 if (listen_fd == GNUPG_INVALID_FD && fd == GNUPG_INVALID_FD)
1583 int filedes[2];
1585 filedes[0] = 0;
1586 filedes[1] = 1;
1587 rc = assuan_init_pipe_server (&ctx, filedes);
1589 else if (listen_fd != GNUPG_INVALID_FD)
1591 rc = assuan_init_socket_server_ext (&ctx, listen_fd, 0);
1593 else
1595 rc = assuan_init_socket_server_ext (&ctx, fd, 2);
1597 if (rc)
1599 log_error ("failed to initialize the server: %s\n",
1600 gpg_strerror(rc));
1601 agent_exit (2);
1603 rc = register_commands (ctx);
1604 if (rc)
1606 log_error ("failed to register commands with Assuan: %s\n",
1607 gpg_strerror(rc));
1608 agent_exit (2);
1611 assuan_set_pointer (ctx, ctrl);
1612 ctrl->server_local = xcalloc (1, sizeof *ctrl->server_local);
1613 ctrl->server_local->assuan_ctx = ctx;
1614 ctrl->server_local->message_fd = -1;
1615 ctrl->server_local->use_cache_for_signing = 1;
1616 ctrl->digest.raw_value = 0;
1618 if (DBG_ASSUAN)
1619 assuan_set_log_stream (ctx, log_get_stream ());
1621 #ifdef HAVE_ASSUAN_SET_IO_MONITOR
1622 assuan_set_io_monitor (ctx, io_monitor);
1623 #endif
1625 for (;;)
1627 rc = assuan_accept (ctx);
1628 if (rc == -1)
1630 break;
1632 else if (rc)
1634 log_info ("Assuan accept problem: %s\n", gpg_strerror (rc));
1635 break;
1638 rc = assuan_process (ctx);
1639 if (rc)
1641 log_info ("Assuan processing failed: %s\n", gpg_strerror (rc));
1642 continue;
1646 /* Reset the SCD if needed. */
1647 agent_reset_scd (ctrl);
1649 /* Reset the pinentry (in case of popup messages). */
1650 agent_reset_query (ctrl);
1652 /* Cleanup. */
1653 assuan_deinit_server (ctx);
1654 #ifdef HAVE_W32_SYSTEM
1655 if (ctrl->server_local->stopme)
1656 agent_exit (0);
1657 #endif
1658 xfree (ctrl->server_local);
1659 ctrl->server_local = NULL;