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.
6 * This file is part of GnuPG.
8 * GnuPG is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
13 * GnuPG is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, see <http://www.gnu.org/licenses/>.
22 /* FIXME: we should not use the default assuan buffering but setup
23 some buffering in secure mempory to protect session keys etc. */
34 #include <sys/types.h>
41 #include "cvt-openpgp.h"
42 #include "../common/ssh-utils.h"
43 #include "../common/asshelp.h"
46 /* Maximum allowed size of the inquired ciphertext. */
47 #define MAXLEN_CIPHERTEXT 4096
48 /* Maximum allowed size of the key parameters. */
49 #define MAXLEN_KEYPARAM 1024
50 /* Maximum allowed size of key data as used in inquiries (bytes). */
51 #define MAXLEN_KEYDATA 4096
52 /* The size of the import/export KEK key (in bytes). */
53 #define KEYWRAP_KEYSIZE (128/8)
55 /* A shortcut to call assuan_set_error using an gpg_err_code_t and a
57 #define set_error(e,t) assuan_set_error (ctx, gpg_error (e), (t))
59 /* Check that the maximum digest length we support has at least the
60 length of the keygrip. */
61 #if MAX_DIGEST_LEN < 20
62 #error MAX_DIGEST_LEN shorter than keygrip
65 /* Data used to associate an Assuan context with local server data.
66 This is this modules local part of the server_control_s struct. */
69 /* Our Assuan context. */
70 assuan_context_t assuan_ctx;
72 /* If this flag is true, the passphrase cache is used for signing
73 operations. It defaults to true but may be set on a per
74 connection base. The global option opt.ignore_cache_for_signing
75 takes precedence over this flag. */
76 int use_cache_for_signing;
78 /* An allocated description for the next key operation. This is
79 used if a pinnetry needs to be popped up. */
82 /* Flags to suppress I/O logging during a command. */
85 /* If this flags is set to true the agent will be terminated after
86 the end of the current session. */
89 /* Flag indicating whether pinentry notifications shall be done. */
90 int allow_pinentry_notify;
92 /* Malloced KEK (Key-Encryption-Key) for the import_key command. */
95 /* Malloced KEK for the export_key command. */
98 /* Client is aware of the error code GPG_ERR_FULLY_CANCELED. */
99 int allow_fully_canceled;
101 /* Last CACHE_NONCE sent as status (malloced). */
102 char *last_cache_nonce;
104 /* Last PASSWD_NONCE sent as status (malloced). */
105 char *last_passwd_nonce;
109 /* An entry for the getval/putval commands. */
112 struct putval_item_s *next;
113 size_t off; /* Offset to the value into DATA. */
114 size_t len; /* Length of the value. */
115 char d[1]; /* Key | Nul | value. */
119 /* A list of key value pairs fpr the getval/putval commands. */
120 static struct putval_item_s *putval_list;
124 /* To help polling clients, we keep track of the number of certain
125 events. This structure keeps those counters. The counters are
126 integers and there should be no problem if they are overflowing as
127 callers need to check only whether a counter changed. The actual
128 values are not meaningful. */
131 /* Incremented if any of the other counters below changed. */
134 /* Incremented if a key is added or removed from the internal privat
138 /* Incremented if a change of the card readers stati has been
146 /* Local prototypes. */
147 static int command_has_option (const char *cmd, const char *cmdopt);
152 /* Release the memory buffer MB but first wipe out the used memory. */
154 clear_outbuf (membuf_t *mb)
159 p = get_membuf (mb, &n);
168 /* Write the content of memory buffer MB as assuan data to CTX and
169 wipe the buffer out afterwards. */
171 write_and_clear_outbuf (assuan_context_t ctx, membuf_t *mb)
177 p = get_membuf (mb, &n);
179 return out_of_core ();
180 ae = assuan_send_data (ctx, p, n);
187 /* Clear the nonces used to enable the passphrase cache for certain
188 multi-command command sequences. */
190 clear_nonce_cache (ctrl_t ctrl)
192 if (ctrl->server_local->last_cache_nonce)
194 agent_put_cache (ctrl->server_local->last_cache_nonce,
195 CACHE_MODE_NONCE, NULL, 0);
196 xfree (ctrl->server_local->last_cache_nonce);
197 ctrl->server_local->last_cache_nonce = NULL;
199 if (ctrl->server_local->last_passwd_nonce)
201 agent_put_cache (ctrl->server_local->last_passwd_nonce,
202 CACHE_MODE_NONCE, NULL, 0);
203 xfree (ctrl->server_local->last_passwd_nonce);
204 ctrl->server_local->last_passwd_nonce = NULL;
209 /* This function is called by Libassuan whenever thee client sends a
210 reset. It has been registered similar to the other Assuan
213 reset_notify (assuan_context_t ctx, char *line)
215 ctrl_t ctrl = assuan_get_pointer (ctx);
219 memset (ctrl->keygrip, 0, 20);
220 ctrl->have_keygrip = 0;
221 ctrl->digest.valuelen = 0;
223 xfree (ctrl->server_local->keydesc);
224 ctrl->server_local->keydesc = NULL;
226 clear_nonce_cache (ctrl);
232 /* Skip over options in LINE.
234 Blanks after the options are also removed. Options are indicated
235 by two leading dashes followed by a string consisting of non-space
236 characters. The special option "--" indicates an explicit end of
237 options; all what follows will not be considered an option. The
238 first no-option string also indicates the end of option parsing. */
240 skip_options (const char *line)
242 while (spacep (line))
244 while ( *line == '-' && line[1] == '-' )
246 while (*line && !spacep (line))
248 while (spacep (line))
255 /* Check whether the option NAME appears in LINE. An example for a
256 line with options is:
257 --algo=42 --data foo bar
258 This function would then only return true if NAME is "data". */
260 has_option (const char *line, const char *name)
263 int n = strlen (name);
265 s = strstr (line, name);
266 if (s && s >= skip_options (line))
268 return (s && (s == line || spacep (s-1)) && (!s[n] || spacep (s+n)));
272 /* Same as has_option but does only test for the name of the option
273 and ignores an argument, i.e. with NAME being "--hash" it would
274 return true for "--hash" as well as for "--hash=foo". */
276 has_option_name (const char *line, const char *name)
279 int n = strlen (name);
281 s = strstr (line, name);
282 if (s && s >= skip_options (line))
284 return (s && (s == line || spacep (s-1))
285 && (!s[n] || spacep (s+n) || s[n] == '='));
289 /* Return a pointer to the argument of the option with NAME. If such
290 an option is not given, NULL is retruned. */
292 option_value (const char *line, const char *name)
295 int n = strlen (name);
297 s = strstr (line, name);
298 if (s && s >= skip_options (line))
300 if (s && (s == line || spacep (s-1))
301 && s[n] && (spacep (s+n) || s[n] == '='))
304 s += strspn (s, " ");
305 if (*s && !spacep(s))
312 /* Replace all '+' by a blank in the string S. */
314 plus_to_blank (char *s)
324 /* Parse a hex string. Return an Assuan error code or 0 on success and the
325 length of the parsed string in LEN. */
327 parse_hexstring (assuan_context_t ctx, const char *string, size_t *len)
332 /* parse the hash value */
333 for (p=string, n=0; hexdigitp (p); p++, n++)
335 if (*p != ' ' && *p != '\t' && *p)
336 return set_error (GPG_ERR_ASS_PARAMETER, "invalid hexstring");
338 return set_error (GPG_ERR_ASS_PARAMETER, "odd number of digits");
344 /* Parse the keygrip in STRING into the provided buffer BUF. BUF must
345 provide space for 20 bytes. BUF is not changed if the function
348 parse_keygrip (assuan_context_t ctx, const char *string, unsigned char *buf)
353 rc = parse_hexstring (ctx, string, &n);
358 return set_error (GPG_ERR_ASS_PARAMETER, "invalid length of keygrip");
360 if (hex2bin (string, buf, 20) < 0)
361 return set_error (GPG_ERR_BUG, "hex2bin");
367 /* Write an Assuan status line. KEYWORD is the first item on the
368 status line. The following arguments are all separated by a space
369 in the output. The last argument must be a NULL. Linefeeds and
370 carriage returns characters (which are not allowed in an Assuan
371 status line) are silently quoted in C-style. */
373 agent_write_status (ctrl_t ctrl, const char *keyword, ...)
378 assuan_context_t ctx = ctrl->server_local->assuan_ctx;
382 va_start (arg_ptr, keyword);
386 while ( (text = va_arg (arg_ptr, const char *)) )
393 for ( ; *text && n < DIM (buf)-3; n++, text++)
400 else if (*text == '\r')
410 err = assuan_write_status (ctx, keyword, buf);
417 /* This function is similar to print_assuan_status but takes a CTRL
418 arg instead of an assuan context as first argument. */
420 agent_print_status (ctrl_t ctrl, const char *keyword, const char *format, ...)
424 assuan_context_t ctx = ctrl->server_local->assuan_ctx;
426 va_start (arg_ptr, format);
427 err = vprint_assuan_status (ctx, keyword, format, arg_ptr);
433 /* Helper to notify the client about a launched Pinentry. Because
434 that might disturb some older clients, this is only done if enabled
435 via an option. Returns an gpg error code. */
437 agent_inq_pinentry_launched (ctrl_t ctrl, unsigned long pid)
441 if (!ctrl || !ctrl->server_local
442 || !ctrl->server_local->allow_pinentry_notify)
444 snprintf (line, DIM(line)-1, "PINENTRY_LAUNCHED %lu", pid);
445 return assuan_inquire (ctrl->server_local->assuan_ctx, line, NULL, NULL, 0);
449 /* Helper to print a message while leaving a command. */
451 leave_cmd (assuan_context_t ctx, gpg_error_t err)
455 const char *name = assuan_get_command_name (ctx);
459 /* Not all users of gpg-agent know about the fully canceled
460 error code; map it back if needed. */
461 if (gpg_err_code (err) == GPG_ERR_FULLY_CANCELED)
463 ctrl_t ctrl = assuan_get_pointer (ctx);
465 if (!ctrl->server_local->allow_fully_canceled)
466 err = gpg_err_make (gpg_err_source (err), GPG_ERR_CANCELED);
469 /* Most code from common/ does not know the error source, thus
471 if (gpg_err_source (err) == GPG_ERR_SOURCE_UNKNOWN)
472 err = gpg_err_make (GPG_ERR_SOURCE_DEFAULT, gpg_err_code (err));
474 if (gpg_err_source (err) == GPG_ERR_SOURCE_DEFAULT)
475 log_error ("command '%s' failed: %s\n", name,
478 log_error ("command '%s' failed: %s <%s>\n", name,
479 gpg_strerror (err), gpg_strsource (err));
486 static const char hlp_geteventcounter[] =
489 "Return a a status line named EVENTCOUNTER with the current values\n"
490 "of all event counters. The values are decimal numbers in the range\n"
491 "0 to UINT_MAX and wrapping around to 0. The actual values should\n"
492 "not be relied upon, they shall only be used to detect a change.\n"
494 "The currently defined counters are:\n"
496 "ANY - Incremented with any change of any of the other counters.\n"
497 "KEY - Incremented for added or removed private keys.\n"
498 "CARD - Incremented for changes of the card readers stati.";
500 cmd_geteventcounter (assuan_context_t ctx, char *line)
502 ctrl_t ctrl = assuan_get_pointer (ctx);
506 if (ctrl->restricted)
507 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
509 return agent_print_status (ctrl, "EVENTCOUNTER", "%u %u %u",
516 /* This function should be called once for all key removals or
517 additions. This function is assured not to do any context
520 bump_key_eventcounter (void)
527 /* This function should be called for all card reader status
528 changes. This function is assured not to do any context
531 bump_card_eventcounter (void)
540 static const char hlp_istrusted[] =
541 "ISTRUSTED <hexstring_with_fingerprint>\n"
543 "Return OK when we have an entry with this fingerprint in our\n"
546 cmd_istrusted (assuan_context_t ctx, char *line)
548 ctrl_t ctrl = assuan_get_pointer (ctx);
553 /* Parse the fingerprint value. */
554 for (p=line,n=0; hexdigitp (p); p++, n++)
556 if (*p || !(n == 40 || n == 32))
557 return set_error (GPG_ERR_ASS_PARAMETER, "invalid fingerprint");
561 strcpy (fpr, "00000000");
564 for (p=line; i < 40; p++, i++)
565 fpr[i] = *p >= 'a'? (*p & 0xdf): *p;
567 rc = agent_istrusted (ctrl, fpr, NULL);
568 if (!rc || gpg_err_code (rc) == GPG_ERR_NOT_TRUSTED)
570 else if (rc == -1 || gpg_err_code (rc) == GPG_ERR_EOF )
571 return gpg_error (GPG_ERR_NOT_TRUSTED);
573 return leave_cmd (ctx, rc);
577 static const char hlp_listtrusted[] =
580 "List all entries from the trustlist.";
582 cmd_listtrusted (assuan_context_t ctx, char *line)
584 ctrl_t ctrl = assuan_get_pointer (ctx);
589 if (ctrl->restricted)
590 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
592 rc = agent_listtrusted (ctx);
593 return leave_cmd (ctx, rc);
597 static const char hlp_martrusted[] =
598 "MARKTRUSTED <hexstring_with_fingerprint> <flag> <display_name>\n"
600 "Store a new key in into the trustlist.";
602 cmd_marktrusted (assuan_context_t ctx, char *line)
604 ctrl_t ctrl = assuan_get_pointer (ctx);
610 if (ctrl->restricted)
611 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
613 /* parse the fingerprint value */
614 for (p=line,n=0; hexdigitp (p); p++, n++)
616 if (!spacep (p) || !(n == 40 || n == 32))
617 return set_error (GPG_ERR_ASS_PARAMETER, "invalid fingerprint");
621 strcpy (fpr, "00000000");
624 for (p=line; i < 40; p++, i++)
625 fpr[i] = *p >= 'a'? (*p & 0xdf): *p;
631 if ( (flag != 'S' && flag != 'P') || !spacep (p) )
632 return set_error (GPG_ERR_ASS_PARAMETER, "invalid flag - must be P or S");
636 rc = agent_marktrusted (ctrl, p, fpr, flag);
637 return leave_cmd (ctx, rc);
643 static const char hlp_havekey[] =
644 "HAVEKEY <hexstrings_with_keygrips>\n"
646 "Return success if at least one of the secret keys with the given\n"
647 "keygrips is available.";
649 cmd_havekey (assuan_context_t ctx, char *line)
652 unsigned char buf[20];
656 err = parse_keygrip (ctx, line, buf);
660 if (!agent_key_available (buf))
661 return 0; /* Found. */
663 while (*line && *line != ' ' && *line != '\t')
665 while (*line == ' ' || *line == '\t')
670 /* No leave_cmd() here because errors are expected and would clutter
672 return gpg_error (GPG_ERR_NO_SECKEY);
676 static const char hlp_sigkey[] =
677 "SIGKEY <hexstring_with_keygrip>\n"
678 "SETKEY <hexstring_with_keygrip>\n"
680 "Set the key used for a sign or decrypt operation.";
682 cmd_sigkey (assuan_context_t ctx, char *line)
685 ctrl_t ctrl = assuan_get_pointer (ctx);
687 rc = parse_keygrip (ctx, line, ctrl->keygrip);
690 ctrl->have_keygrip = 1;
695 static const char hlp_setkeydesc[] =
696 "SETKEYDESC plus_percent_escaped_string\n"
698 "Set a description to be used for the next PKSIGN, PKDECRYPT, IMPORT_KEY\n"
699 "or EXPORT_KEY operation if this operation requires a passphrase. If\n"
700 "this command is not used a default text will be used. Note, that\n"
701 "this description implictly selects the label used for the entry\n"
702 "box; if the string contains the string PIN (which in general will\n"
703 "not be translated), \"PIN\" is used, otherwise the translation of\n"
704 "\"passphrase\" is used. The description string should not contain\n"
705 "blanks unless they are percent or '+' escaped.\n"
707 "The description is only valid for the next PKSIGN, PKDECRYPT,\n"
708 "IMPORT_KEY, EXPORT_KEY, or DELETE_KEY operation.";
710 cmd_setkeydesc (assuan_context_t ctx, char *line)
712 ctrl_t ctrl = assuan_get_pointer (ctx);
715 for (p=line; *p == ' '; p++)
718 p = strchr (desc, ' ');
720 *p = 0; /* We ignore any garbage; we might late use it for other args. */
723 return set_error (GPG_ERR_ASS_PARAMETER, "no description given");
725 /* Note, that we only need to replace the + characters and should
726 leave the other escaping in place because the escaped string is
727 send verbatim to the pinentry which does the unescaping (but not
729 plus_to_blank (desc);
731 xfree (ctrl->server_local->keydesc);
733 if (ctrl->restricted)
735 ctrl->server_local->keydesc = strconcat
736 ((ctrl->restricted == 2
737 ? _("Note: Request from the web browser.")
738 : _("Note: Request from a remote site.") ), "%0A%0A", desc, NULL);
741 ctrl->server_local->keydesc = xtrystrdup (desc);
742 if (!ctrl->server_local->keydesc)
743 return out_of_core ();
748 static const char hlp_sethash[] =
749 "SETHASH (--hash=<name>)|(<algonumber>) <hexstring>\n"
751 "The client can use this command to tell the server about the data\n"
752 "(which usually is a hash) to be signed.";
754 cmd_sethash (assuan_context_t ctx, char *line)
759 ctrl_t ctrl = assuan_get_pointer (ctx);
764 /* Parse the alternative hash options which may be used instead of
766 if (has_option_name (line, "--hash"))
768 if (has_option (line, "--hash=sha1"))
770 else if (has_option (line, "--hash=sha224"))
771 algo = GCRY_MD_SHA224;
772 else if (has_option (line, "--hash=sha256"))
773 algo = GCRY_MD_SHA256;
774 else if (has_option (line, "--hash=sha384"))
775 algo = GCRY_MD_SHA384;
776 else if (has_option (line, "--hash=sha512"))
777 algo = GCRY_MD_SHA512;
778 else if (has_option (line, "--hash=rmd160"))
779 algo = GCRY_MD_RMD160;
780 else if (has_option (line, "--hash=md5"))
782 else if (has_option (line, "--hash=tls-md5sha1"))
783 algo = MD_USER_TLS_MD5SHA1;
785 return set_error (GPG_ERR_ASS_PARAMETER, "invalid hash algorithm");
790 line = skip_options (line);
794 /* No hash option has been given: require an algo number instead */
795 algo = (int)strtoul (line, &endp, 10);
796 for (line = endp; *line == ' ' || *line == '\t'; line++)
798 if (!algo || gcry_md_test_algo (algo))
799 return set_error (GPG_ERR_UNSUPPORTED_ALGORITHM, NULL);
801 ctrl->digest.algo = algo;
802 ctrl->digest.raw_value = 0;
804 /* Parse the hash value. */
806 rc = parse_hexstring (ctx, line, &n);
810 if (algo == MD_USER_TLS_MD5SHA1 && n == 36)
812 else if (n != 16 && n != 20 && n != 24
813 && n != 28 && n != 32 && n != 48 && n != 64)
814 return set_error (GPG_ERR_ASS_PARAMETER, "unsupported length of hash");
816 if (n > MAX_DIGEST_LEN)
817 return set_error (GPG_ERR_ASS_PARAMETER, "hash value to long");
819 buf = ctrl->digest.value;
820 ctrl->digest.valuelen = n;
821 for (p=line, n=0; n < ctrl->digest.valuelen; p += 2, n++)
823 for (; n < ctrl->digest.valuelen; n++)
829 static const char hlp_pksign[] =
830 "PKSIGN [<options>] [<cache_nonce>]\n"
832 "Perform the actual sign operation. Neither input nor output are\n"
833 "sensitive to eavesdropping.";
835 cmd_pksign (assuan_context_t ctx, char *line)
838 cache_mode_t cache_mode = CACHE_MODE_NORMAL;
839 ctrl_t ctrl = assuan_get_pointer (ctx);
841 char *cache_nonce = NULL;
844 line = skip_options (line);
847 for (p=line; *p && *p != ' ' && *p != '\t'; p++)
851 cache_nonce = xtrystrdup (line);
853 if (opt.ignore_cache_for_signing)
854 cache_mode = CACHE_MODE_IGNORE;
855 else if (!ctrl->server_local->use_cache_for_signing)
856 cache_mode = CACHE_MODE_IGNORE;
858 init_membuf (&outbuf, 512);
860 rc = agent_pksign (ctrl, cache_nonce, ctrl->server_local->keydesc,
861 &outbuf, cache_mode);
863 clear_outbuf (&outbuf);
865 rc = write_and_clear_outbuf (ctx, &outbuf);
868 xfree (ctrl->server_local->keydesc);
869 ctrl->server_local->keydesc = NULL;
870 return leave_cmd (ctx, rc);
874 static const char hlp_pkdecrypt[] =
875 "PKDECRYPT [<options>]\n"
877 "Perform the actual decrypt operation. Input is not\n"
878 "sensitive to eavesdropping.";
880 cmd_pkdecrypt (assuan_context_t ctx, char *line)
883 ctrl_t ctrl = assuan_get_pointer (ctx);
884 unsigned char *value;
891 /* First inquire the data to decrypt */
892 rc = print_assuan_status (ctx, "INQUIRE_MAXLEN", "%u", MAXLEN_CIPHERTEXT);
894 rc = assuan_inquire (ctx, "CIPHERTEXT",
895 &value, &valuelen, MAXLEN_CIPHERTEXT);
899 init_membuf (&outbuf, 512);
901 rc = agent_pkdecrypt (ctrl, ctrl->server_local->keydesc,
902 value, valuelen, &outbuf, &padding);
905 clear_outbuf (&outbuf);
909 rc = print_assuan_status (ctx, "PADDING", "%d", padding);
913 rc = write_and_clear_outbuf (ctx, &outbuf);
915 xfree (ctrl->server_local->keydesc);
916 ctrl->server_local->keydesc = NULL;
917 return leave_cmd (ctx, rc);
921 static const char hlp_genkey[] =
922 "GENKEY [--no-protection] [--preset] [--inq-passwd] [<cache_nonce>]\n"
924 "Generate a new key, store the secret part and return the public\n"
925 "part. Here is an example transaction:\n"
928 " S: INQUIRE KEYPARAM\n"
929 " C: D (genkey (rsa (nbits 2048)))\n"
931 " S: D (public-key\n"
932 " S: D (rsa (n 326487324683264) (e 10001)))\n"
933 " S: OK key created\n"
935 "When the --preset option is used the passphrase for the generated\n"
936 "key will be added to the cache. When --inq-passwd is used an inquire\n"
937 "with the keyword NEWPASSWD is used to request the passphrase for the\n"
940 cmd_genkey (assuan_context_t ctx, char *line)
942 ctrl_t ctrl = assuan_get_pointer (ctx);
945 unsigned char *value;
947 unsigned char *newpasswd = NULL;
949 char *cache_nonce = NULL;
955 if (ctrl->restricted)
956 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
958 no_protection = has_option (line, "--no-protection");
959 opt_preset = has_option (line, "--preset");
960 opt_inq_passwd = has_option (line, "--inq-passwd");
961 line = skip_options (line);
964 for (p=line; *p && *p != ' ' && *p != '\t'; p++)
968 cache_nonce = xtrystrdup (line);
970 /* First inquire the parameters */
971 rc = print_assuan_status (ctx, "INQUIRE_MAXLEN", "%u", MAXLEN_KEYPARAM);
973 rc = assuan_inquire (ctx, "KEYPARAM", &value, &valuelen, MAXLEN_KEYPARAM);
977 init_membuf (&outbuf, 512);
979 /* If requested, ask for the password to be used for the key. If
980 this is not used the regular Pinentry mechanism is used. */
981 if (opt_inq_passwd && !no_protection)
983 /* (N is used as a dummy) */
984 assuan_begin_confidential (ctx);
985 rc = assuan_inquire (ctx, "NEWPASSWD", &newpasswd, &n, 256);
986 assuan_end_confidential (ctx);
991 /* Empty password given - switch to no-protection mode. */
999 rc = agent_genkey (ctrl, cache_nonce, (char*)value, valuelen, no_protection,
1000 newpasswd, opt_preset, &outbuf);
1005 /* Assuan_inquire does not allow us to read into secure memory
1006 thus we need to wipe it ourself. */
1007 wipememory (newpasswd, strlen (newpasswd));
1012 clear_outbuf (&outbuf);
1014 rc = write_and_clear_outbuf (ctx, &outbuf);
1015 xfree (cache_nonce);
1016 return leave_cmd (ctx, rc);
1022 static const char hlp_readkey[] =
1023 "READKEY <hexstring_with_keygrip>\n"
1025 "Return the public key for the given keygrip.";
1027 cmd_readkey (assuan_context_t ctx, char *line)
1029 ctrl_t ctrl = assuan_get_pointer (ctx);
1031 unsigned char grip[20];
1032 gcry_sexp_t s_pkey = NULL;
1034 if (ctrl->restricted)
1035 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
1037 rc = parse_keygrip (ctx, line, grip);
1039 return rc; /* Return immediately as this is already an Assuan error code.*/
1041 rc = agent_public_key_from_file (ctrl, grip, &s_pkey);
1047 len = gcry_sexp_sprint (s_pkey, GCRYSEXP_FMT_CANON, NULL, 0);
1049 buf = xtrymalloc (len);
1051 rc = gpg_error_from_syserror ();
1054 len = gcry_sexp_sprint (s_pkey, GCRYSEXP_FMT_CANON, buf, len);
1056 rc = assuan_send_data (ctx, buf, len);
1059 gcry_sexp_release (s_pkey);
1062 return leave_cmd (ctx, rc);
1067 static const char hlp_keyinfo[] =
1068 "KEYINFO [--[ssh-]list] [--data] [--ssh-fpr] [--with-ssh] <keygrip>\n"
1070 "Return information about the key specified by the KEYGRIP. If the\n"
1071 "key is not available GPG_ERR_NOT_FOUND is returned. If the option\n"
1072 "--list is given the keygrip is ignored and information about all\n"
1073 "available keys are returned. If --ssh-list is given information\n"
1074 "about all keys listed in the sshcontrol are returned. With --with-ssh\n"
1075 "information from sshcontrol is always added to the info. Unless --data\n"
1076 "is given, the information is returned as a status line using the format:\n"
1078 " KEYINFO <keygrip> <type> <serialno> <idstr> <cached> <protection> <fpr>\n"
1080 "KEYGRIP is the keygrip.\n"
1082 "TYPE is describes the type of the key:\n"
1083 " 'D' - Regular key stored on disk,\n"
1084 " 'T' - Key is stored on a smartcard (token),\n"
1085 " 'X' - Unknown type,\n"
1086 " '-' - Key is missing.\n"
1088 "SERIALNO is an ASCII string with the serial number of the\n"
1089 " smartcard. If the serial number is not known a single\n"
1090 " dash '-' is used instead.\n"
1092 "IDSTR is the IDSTR used to distinguish keys on a smartcard. If it\n"
1093 " is not known a dash is used instead.\n"
1095 "CACHED is 1 if the passphrase for the key was found in the key cache.\n"
1096 " If not, a '-' is used instead.\n"
1098 "PROTECTION describes the key protection type:\n"
1099 " 'P' - The key is protected with a passphrase,\n"
1100 " 'C' - The key is not protected,\n"
1101 " '-' - Unknown protection.\n"
1103 "FPR returns the formatted ssh-style fingerprint of the key. It is only\n"
1104 " printed if the option --ssh-fpr has been used. It defaults to '-'.\n"
1106 "TTL is the TTL in seconds for that key or '-' if n/a.\n"
1108 "FLAGS is a word consisting of one-letter flags:\n"
1109 " 'D' - The key has been disabled,\n"
1110 " 'S' - The key is listed in sshcontrol (requires --with-ssh),\n"
1111 " 'c' - Use of the key needs to be confirmed,\n"
1112 " '-' - No flags given.\n"
1114 "More information may be added in the future.";
1116 do_one_keyinfo (ctrl_t ctrl, const unsigned char *grip, assuan_context_t ctx,
1117 int data, int with_ssh_fpr, int in_ssh,
1118 int ttl, int disabled, int confirm)
1124 unsigned char *shadow_info = NULL;
1125 char *serialno = NULL;
1127 const char *keytypestr;
1129 const char *protectionstr;
1131 int missing_key = 0;
1135 err = agent_key_info_from_file (ctrl, grip, &keytype, &shadow_info);
1138 if (in_ssh && gpg_err_code (err) == GPG_ERR_NOT_FOUND)
1144 /* Reformat the grip so that we use uppercase as good style. */
1145 bin2hex (grip, 20, hexgrip);
1148 snprintf (ttlbuf, sizeof ttlbuf, "%d", ttl);
1150 strcpy (ttlbuf, "-");
1154 strcat (flagsbuf, "D");
1156 strcat (flagsbuf, "S");
1158 strcat (flagsbuf, "c");
1160 strcpy (flagsbuf, "-");
1165 protectionstr = "-"; keytypestr = "-";
1171 case PRIVATE_KEY_CLEAR:
1172 case PRIVATE_KEY_OPENPGP_NONE:
1173 protectionstr = "C"; keytypestr = "D";
1175 case PRIVATE_KEY_PROTECTED: protectionstr = "P"; keytypestr = "D";
1177 case PRIVATE_KEY_SHADOWED: protectionstr = "-"; keytypestr = "T";
1179 default: protectionstr = "-"; keytypestr = "X";
1184 /* Compute the ssh fingerprint if requested. */
1189 if (!agent_raw_key_from_file (ctrl, grip, &key))
1191 ssh_get_fingerprint_string (key, &fpr);
1192 gcry_sexp_release (key);
1196 /* Here we have a little race by doing the cache check separately
1197 from the retrieval function. Given that the cache flag is only a
1198 hint, it should not really matter. */
1199 pw = agent_get_cache (hexgrip, CACHE_MODE_NORMAL);
1200 cached = pw ? "1" : "-";
1205 err = parse_shadow_info (shadow_info, &serialno, &idstr, NULL);
1211 err = agent_write_status (ctrl, "KEYINFO",
1214 serialno? serialno : "-",
1226 string = xtryasprintf ("%s %s %s %s %s %s %s %s %s\n",
1227 hexgrip, keytypestr,
1228 serialno? serialno : "-",
1229 idstr? idstr : "-", cached, protectionstr,
1234 err = gpg_error_from_syserror ();
1236 err = assuan_send_data (ctx, string, strlen(string));
1242 xfree (shadow_info);
1249 /* Entry int for the command KEYINFO. This function handles the
1250 command option processing. For details see hlp_keyinfo above. */
1252 cmd_keyinfo (assuan_context_t ctx, char *line)
1254 ctrl_t ctrl = assuan_get_pointer (ctx);
1256 unsigned char grip[20];
1259 int opt_data, opt_ssh_fpr, opt_with_ssh;
1260 ssh_control_file_t cf = NULL;
1262 int disabled, ttl, confirm, is_ssh;
1264 if (ctrl->restricted)
1265 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
1267 if (has_option (line, "--ssh-list"))
1270 list_mode = has_option (line, "--list");
1271 opt_data = has_option (line, "--data");
1272 opt_ssh_fpr = has_option (line, "--ssh-fpr");
1273 opt_with_ssh = has_option (line, "--with-ssh");
1274 line = skip_options (line);
1276 if (opt_with_ssh || list_mode == 2)
1277 cf = ssh_open_control_file ();
1283 while (!ssh_read_control_file (cf, hexgrip,
1284 &disabled, &ttl, &confirm))
1286 if (hex2bin (hexgrip, grip, 20) < 0 )
1287 continue; /* Bad hex string. */
1288 err = do_one_keyinfo (ctrl, grip, ctx, opt_data, opt_ssh_fpr, 1,
1289 ttl, disabled, confirm);
1299 struct dirent *dir_entry;
1301 dirname = make_filename_try (opt.homedir, GNUPG_PRIVATE_KEYS_DIR, NULL);
1304 err = gpg_error_from_syserror ();
1307 dir = opendir (dirname);
1310 err = gpg_error_from_syserror ();
1316 while ( (dir_entry = readdir (dir)) )
1318 if (strlen (dir_entry->d_name) != 44
1319 || strcmp (dir_entry->d_name + 40, ".key"))
1321 strncpy (hexgrip, dir_entry->d_name, 40);
1324 if ( hex2bin (hexgrip, grip, 20) < 0 )
1325 continue; /* Bad hex string. */
1327 disabled = ttl = confirm = is_ssh = 0;
1330 err = ssh_search_control_file (cf, hexgrip,
1331 &disabled, &ttl, &confirm);
1334 else if (gpg_err_code (err) != GPG_ERR_NOT_FOUND)
1338 err = do_one_keyinfo (ctrl, grip, ctx, opt_data, opt_ssh_fpr, is_ssh,
1339 ttl, disabled, confirm);
1347 err = parse_keygrip (ctx, line, grip);
1350 disabled = ttl = confirm = is_ssh = 0;
1353 err = ssh_search_control_file (cf, line,
1354 &disabled, &ttl, &confirm);
1357 else if (gpg_err_code (err) != GPG_ERR_NOT_FOUND)
1361 err = do_one_keyinfo (ctrl, grip, ctx, opt_data, opt_ssh_fpr, is_ssh,
1362 ttl, disabled, confirm);
1366 ssh_close_control_file (cf);
1369 if (err && gpg_err_code (err) != GPG_ERR_NOT_FOUND)
1370 leave_cmd (ctx, err);
1376 /* Helper for cmd_get_passphrase. */
1378 send_back_passphrase (assuan_context_t ctx, int via_data, const char *pw)
1383 assuan_begin_confidential (ctx);
1386 rc = assuan_send_data (ctx, pw, n);
1389 char *p = xtrymalloc_secure (n*2+1);
1391 rc = gpg_error_from_syserror ();
1395 rc = assuan_set_okay_line (ctx, p);
1403 static const char hlp_get_passphrase[] =
1404 "GET_PASSPHRASE [--data] [--check] [--no-ask] [--repeat[=N]]\n"
1405 " [--qualitybar] <cache_id>\n"
1406 " [<error_message> <prompt> <description>]\n"
1408 "This function is usually used to ask for a passphrase to be used\n"
1409 "for conventional encryption, but may also be used by programs which\n"
1410 "need specal handling of passphrases. This command uses a syntax\n"
1411 "which helps clients to use the agent with minimum effort. The\n"
1412 "agent either returns with an error or with a OK followed by the hex\n"
1413 "encoded passphrase. Note that the length of the strings is\n"
1414 "implicitly limited by the maximum length of a command.\n"
1416 "If the option \"--data\" is used the passphrase is returned by usual\n"
1417 "data lines and not on the okay line.\n"
1419 "If the option \"--check\" is used the passphrase constraints checks as\n"
1420 "implemented by gpg-agent are applied. A check is not done if the\n"
1421 "passphrase has been found in the cache.\n"
1423 "If the option \"--no-ask\" is used and the passphrase is not in the\n"
1424 "cache the user will not be asked to enter a passphrase but the error\n"
1425 "code GPG_ERR_NO_DATA is returned. \n"
1427 "If the option \"--qualitybar\" is used a visual indication of the\n"
1428 "entered passphrase quality is shown. (Unless no minimum passphrase\n"
1429 "length has been configured.)";
1431 cmd_get_passphrase (assuan_context_t ctx, char *line)
1433 ctrl_t ctrl = assuan_get_pointer (ctx);
1437 char *cacheid = NULL, *desc = NULL, *prompt = NULL, *errtext = NULL;
1438 const char *desc2 = _("Please re-enter this passphrase");
1440 int opt_data, opt_check, opt_no_ask, opt_qualbar;
1442 char *entry_errtext = NULL;
1444 if (ctrl->restricted)
1445 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
1447 opt_data = has_option (line, "--data");
1448 opt_check = has_option (line, "--check");
1449 opt_no_ask = has_option (line, "--no-ask");
1450 if (has_option_name (line, "--repeat"))
1452 p = option_value (line, "--repeat");
1454 opt_repeat = atoi (p);
1458 opt_qualbar = has_option (line, "--qualitybar");
1459 line = skip_options (line);
1462 p = strchr (cacheid, ' ');
1469 p = strchr (errtext, ' ');
1476 p = strchr (prompt, ' ');
1483 p = strchr (desc, ' ');
1485 *p = 0; /* Ignore trailing garbage. */
1489 if (!*cacheid || strlen (cacheid) > 50)
1490 return set_error (GPG_ERR_ASS_PARAMETER, "invalid length of cacheID");
1492 return set_error (GPG_ERR_ASS_PARAMETER, "no description given");
1494 if (!strcmp (cacheid, "X"))
1496 if (!strcmp (errtext, "X"))
1498 if (!strcmp (prompt, "X"))
1500 if (!strcmp (desc, "X"))
1503 pw = cacheid ? agent_get_cache (cacheid, CACHE_MODE_USER) : NULL;
1506 rc = send_back_passphrase (ctx, opt_data, pw);
1509 else if (opt_no_ask)
1510 rc = gpg_error (GPG_ERR_NO_DATA);
1513 /* Note, that we only need to replace the + characters and
1514 should leave the other escaping in place because the escaped
1515 string is send verbatim to the pinentry which does the
1516 unescaping (but not the + replacing) */
1518 plus_to_blank (errtext);
1520 plus_to_blank (prompt);
1522 plus_to_blank (desc);
1525 rc = agent_get_passphrase (ctrl, &response, desc, prompt,
1526 entry_errtext? entry_errtext:errtext,
1527 opt_qualbar, cacheid, CACHE_MODE_USER);
1528 xfree (entry_errtext);
1529 entry_errtext = NULL;
1535 && check_passphrase_constraints (ctrl, response, &entry_errtext))
1540 for (i = 0; i < opt_repeat; i++)
1544 if (ctrl->pinentry_mode == PINENTRY_MODE_LOOPBACK)
1547 rc = agent_get_passphrase (ctrl, &response2, desc2, prompt,
1549 cacheid, CACHE_MODE_USER);
1552 if (strcmp (response2, response))
1556 entry_errtext = try_percent_escape
1557 (_("does not match - try again"), NULL);
1560 rc = gpg_error_from_syserror ();
1570 agent_put_cache (cacheid, CACHE_MODE_USER, response, 0);
1571 rc = send_back_passphrase (ctx, opt_data, response);
1577 return leave_cmd (ctx, rc);
1581 static const char hlp_clear_passphrase[] =
1582 "CLEAR_PASSPHRASE [--mode=normal] <cache_id>\n"
1584 "may be used to invalidate the cache entry for a passphrase. The\n"
1585 "function returns with OK even when there is no cached passphrase.\n"
1586 "The --mode=normal option is used to clear an entry for a cacheid\n"
1587 "added by the agent.\n";
1589 cmd_clear_passphrase (assuan_context_t ctx, char *line)
1591 ctrl_t ctrl = assuan_get_pointer (ctx);
1592 char *cacheid = NULL;
1596 if (ctrl->restricted)
1597 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
1599 opt_normal = has_option (line, "--mode=normal");
1600 line = skip_options (line);
1602 /* parse the stuff */
1603 for (p=line; *p == ' '; p++)
1606 p = strchr (cacheid, ' ');
1608 *p = 0; /* ignore garbage */
1609 if (!*cacheid || strlen (cacheid) > 50)
1610 return set_error (GPG_ERR_ASS_PARAMETER, "invalid length of cacheID");
1612 agent_put_cache (cacheid, opt_normal ? CACHE_MODE_NORMAL : CACHE_MODE_USER,
1615 agent_clear_passphrase (ctrl, cacheid,
1616 opt_normal ? CACHE_MODE_NORMAL : CACHE_MODE_USER);
1622 static const char hlp_get_confirmation[] =
1623 "GET_CONFIRMATION <description>\n"
1625 "This command may be used to ask for a simple confirmation.\n"
1626 "DESCRIPTION is displayed along with a Okay and Cancel button. This\n"
1627 "command uses a syntax which helps clients to use the agent with\n"
1628 "minimum effort. The agent either returns with an error or with a\n"
1629 "OK. Note, that the length of DESCRIPTION is implicitly limited by\n"
1630 "the maximum length of a command. DESCRIPTION should not contain\n"
1631 "any spaces, those must be encoded either percent escaped or simply\n"
1634 cmd_get_confirmation (assuan_context_t ctx, char *line)
1636 ctrl_t ctrl = assuan_get_pointer (ctx);
1641 if (ctrl->restricted)
1642 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
1644 /* parse the stuff */
1645 for (p=line; *p == ' '; p++)
1648 p = strchr (desc, ' ');
1650 *p = 0; /* We ignore any garbage -may be later used for other args. */
1653 return set_error (GPG_ERR_ASS_PARAMETER, "no description given");
1655 if (!strcmp (desc, "X"))
1658 /* Note, that we only need to replace the + characters and should
1659 leave the other escaping in place because the escaped string is
1660 send verbatim to the pinentry which does the unescaping (but not
1663 plus_to_blank (desc);
1665 rc = agent_get_confirmation (ctrl, desc, NULL, NULL, 0);
1666 return leave_cmd (ctx, rc);
1671 static const char hlp_learn[] =
1672 "LEARN [--send] [--sendinfo] [--force]\n"
1674 "Learn something about the currently inserted smartcard. With\n"
1675 "--sendinfo information about the card is returned; with --send\n"
1676 "the available certificates are returned as D lines; with --force\n"
1677 "private key storage will be updated by the result.";
1679 cmd_learn (assuan_context_t ctx, char *line)
1681 ctrl_t ctrl = assuan_get_pointer (ctx);
1683 int send, sendinfo, force;
1685 send = has_option (line, "--send");
1686 sendinfo = send? 1 : has_option (line, "--sendinfo");
1687 force = has_option (line, "--force");
1689 if (ctrl->restricted)
1690 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
1692 err = agent_handle_learn (ctrl, send, sendinfo? ctx : NULL, force);
1693 return leave_cmd (ctx, err);
1698 static const char hlp_passwd[] =
1699 "PASSWD [--cache-nonce=<c>] [--passwd-nonce=<s>] [--preset]\n"
1700 " [--verify] <hexkeygrip>\n"
1702 "Change the passphrase/PIN for the key identified by keygrip in LINE. If\n"
1703 "--preset is used then the new passphrase will be added to the cache.\n"
1704 "If --verify is used the command asks for the passphrase and verifies\n"
1705 "that the passphrase valid.\n";
1707 cmd_passwd (assuan_context_t ctx, char *line)
1709 ctrl_t ctrl = assuan_get_pointer (ctx);
1712 char *cache_nonce = NULL;
1713 char *passwd_nonce = NULL;
1714 unsigned char grip[20];
1715 gcry_sexp_t s_skey = NULL;
1716 unsigned char *shadow_info = NULL;
1717 char *passphrase = NULL;
1719 int opt_preset, opt_verify;
1721 if (ctrl->restricted)
1722 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
1724 opt_preset = has_option (line, "--preset");
1725 cache_nonce = option_value (line, "--cache-nonce");
1726 opt_verify = has_option (line, "--verify");
1729 for (pend = cache_nonce; *pend && !spacep (pend); pend++)
1733 cache_nonce = xtrystrdup (cache_nonce);
1737 err = gpg_error_from_syserror ();
1742 passwd_nonce = option_value (line, "--passwd-nonce");
1745 for (pend = passwd_nonce; *pend && !spacep (pend); pend++)
1749 passwd_nonce = xtrystrdup (passwd_nonce);
1753 err = gpg_error_from_syserror ();
1758 line = skip_options (line);
1760 err = parse_keygrip (ctx, line, grip);
1765 err = agent_key_from_file (ctrl,
1766 opt_verify? NULL : cache_nonce,
1767 ctrl->server_local->keydesc,
1768 grip, &shadow_info, CACHE_MODE_IGNORE, NULL,
1769 &s_skey, &passphrase);
1772 else if (shadow_info)
1774 log_error ("changing a smartcard PIN is not yet supported\n");
1775 err = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1777 else if (opt_verify)
1783 char *newpass = NULL;
1786 newpass = agent_get_cache (passwd_nonce, CACHE_MODE_NONCE);
1787 err = agent_protect_and_store (ctrl, s_skey, &newpass);
1788 if (!err && passphrase)
1790 /* A passphrase existed on the old key and the change was
1791 successful. Return a nonce for that old passphrase to
1792 let the caller try to unprotect the other subkeys with
1797 gcry_create_nonce (buf, 12);
1798 cache_nonce = bin2hex (buf, 12, NULL);
1801 && !agent_put_cache (cache_nonce, CACHE_MODE_NONCE,
1802 passphrase, CACHE_TTL_NONCE))
1804 assuan_write_status (ctx, "CACHE_NONCE", cache_nonce);
1805 xfree (ctrl->server_local->last_cache_nonce);
1806 ctrl->server_local->last_cache_nonce = cache_nonce;
1811 /* If we have a new passphrase (which might be empty) we
1812 store it under a passwd nonce so that the caller may
1813 send that nonce again to use it for another key. */
1817 gcry_create_nonce (buf, 12);
1818 passwd_nonce = bin2hex (buf, 12, NULL);
1821 && !agent_put_cache (passwd_nonce, CACHE_MODE_NONCE,
1822 newpass, CACHE_TTL_NONCE))
1824 assuan_write_status (ctx, "PASSWD_NONCE", passwd_nonce);
1825 xfree (ctrl->server_local->last_passwd_nonce);
1826 ctrl->server_local->last_passwd_nonce = passwd_nonce;
1827 passwd_nonce = NULL;
1831 if (!err && opt_preset)
1834 bin2hex(grip, 20, hexgrip);
1835 err = agent_put_cache (hexgrip, CACHE_MODE_ANY, newpass,
1836 ctrl->cache_ttl_opt_preset);
1842 xfree (ctrl->server_local->keydesc);
1843 ctrl->server_local->keydesc = NULL;
1847 gcry_sexp_release (s_skey);
1848 xfree (shadow_info);
1849 xfree (cache_nonce);
1850 return leave_cmd (ctx, err);
1854 static const char hlp_preset_passphrase[] =
1855 "PRESET_PASSPHRASE [--inquire] <string_or_keygrip> <timeout> [<hexstring>]\n"
1857 "Set the cached passphrase/PIN for the key identified by the keygrip\n"
1858 "to passwd for the given time, where -1 means infinite and 0 means\n"
1859 "the default (currently only a timeout of -1 is allowed, which means\n"
1860 "to never expire it). If passwd is not provided, ask for it via the\n"
1861 "pinentry module unless --inquire is passed in which case the passphrase\n"
1862 "is retrieved from the client via a server inquire.\n";
1864 cmd_preset_passphrase (assuan_context_t ctx, char *line)
1866 ctrl_t ctrl = assuan_get_pointer (ctx);
1868 char *grip_clear = NULL;
1869 unsigned char *passphrase = NULL;
1874 if (ctrl->restricted)
1875 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
1877 if (!opt.allow_preset_passphrase)
1878 return set_error (GPG_ERR_NOT_SUPPORTED, "no --allow-preset-passphrase");
1880 opt_inquire = has_option (line, "--inquire");
1881 line = skip_options (line);
1883 while (*line && (*line != ' ' && *line != '\t'))
1886 return gpg_error (GPG_ERR_MISSING_VALUE);
1889 while (*line && (*line == ' ' || *line == '\t'))
1892 /* Currently, only infinite timeouts are allowed. */
1894 if (line[0] != '-' || line[1] != '1')
1895 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1898 while (!(*line != ' ' && *line != '\t'))
1901 /* Syntax check the hexstring. */
1903 rc = parse_hexstring (ctx, line, &len);
1908 /* If there is a passphrase, use it. Currently, a passphrase is
1914 rc = set_error (GPG_ERR_ASS_PARAMETER,
1915 "both --inquire and passphrase specified");
1919 /* Do in-place conversion. */
1921 if (!hex2str (passphrase, passphrase, strlen (passphrase)+1, NULL))
1922 rc = set_error (GPG_ERR_ASS_PARAMETER, "invalid hexstring");
1924 else if (opt_inquire)
1926 /* Note that the passphrase will be truncated at any null byte and the
1927 * limit is 480 characters. */
1928 size_t maxlen = 480;
1930 rc = print_assuan_status (ctx, "INQUIRE_MAXLEN", "%zu", maxlen);
1932 rc = assuan_inquire (ctx, "PASSPHRASE", &passphrase, &len, maxlen);
1935 rc = set_error (GPG_ERR_NOT_IMPLEMENTED, "passphrase is required");
1939 rc = agent_put_cache (grip_clear, CACHE_MODE_ANY, passphrase, ttl);
1945 return leave_cmd (ctx, rc);
1950 static const char hlp_scd[] =
1951 "SCD <commands to pass to the scdaemon>\n"
1953 "This is a general quote command to redirect everything to the\n"
1956 cmd_scd (assuan_context_t ctx, char *line)
1958 ctrl_t ctrl = assuan_get_pointer (ctx);
1961 if (ctrl->restricted)
1962 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
1964 rc = divert_generic_cmd (ctrl, line, ctx);
1971 static const char hlp_keywrap_key[] =
1972 "KEYWRAP_KEY [--clear] <mode>\n"
1974 "Return a key to wrap another key. For now the key is returned\n"
1975 "verbatim and and thus makes not much sense because an eavesdropper on\n"
1976 "the gpg-agent connection will see the key as well as the wrapped key.\n"
1977 "However, this function may either be equipped with a public key\n"
1978 "mechanism or not used at all if the key is a pre-shared key. In any\n"
1979 "case wrapping the import and export of keys is a requirement for\n"
1980 "certain cryptographic validations and thus useful. The key persists\n"
1981 "a RESET command but may be cleared using the option --clear.\n"
1983 "Supported modes are:\n"
1984 " --import - Return a key to import a key into gpg-agent\n"
1985 " --export - Return a key to export a key from gpg-agent";
1987 cmd_keywrap_key (assuan_context_t ctx, char *line)
1989 ctrl_t ctrl = assuan_get_pointer (ctx);
1990 gpg_error_t err = 0;
1991 int clearopt = has_option (line, "--clear");
1993 if (ctrl->restricted)
1994 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
1996 assuan_begin_confidential (ctx);
1997 if (has_option (line, "--import"))
1999 xfree (ctrl->server_local->import_key);
2001 ctrl->server_local->import_key = NULL;
2002 else if (!(ctrl->server_local->import_key =
2003 gcry_random_bytes (KEYWRAP_KEYSIZE, GCRY_STRONG_RANDOM)))
2004 err = gpg_error_from_syserror ();
2006 err = assuan_send_data (ctx, ctrl->server_local->import_key,
2009 else if (has_option (line, "--export"))
2011 xfree (ctrl->server_local->export_key);
2013 ctrl->server_local->export_key = NULL;
2014 else if (!(ctrl->server_local->export_key =
2015 gcry_random_bytes (KEYWRAP_KEYSIZE, GCRY_STRONG_RANDOM)))
2016 err = gpg_error_from_syserror ();
2018 err = assuan_send_data (ctx, ctrl->server_local->export_key,
2022 err = set_error (GPG_ERR_ASS_PARAMETER, "unknown value for MODE");
2023 assuan_end_confidential (ctx);
2025 return leave_cmd (ctx, err);
2030 static const char hlp_import_key[] =
2031 "IMPORT_KEY [--unattended] [<cache_nonce>]\n"
2033 "Import a secret key into the key store. The key is expected to be\n"
2034 "encrypted using the current session's key wrapping key (cf. command\n"
2035 "KEYWRAP_KEY) using the AESWRAP-128 algorithm. This function takes\n"
2036 "no arguments but uses the inquiry \"KEYDATA\" to ask for the actual\n"
2037 "key data. The unwrapped key must be a canonical S-expression. The\n"
2038 "option --unattended tries to import the key as-is without any\n"
2041 cmd_import_key (assuan_context_t ctx, char *line)
2043 ctrl_t ctrl = assuan_get_pointer (ctx);
2046 unsigned char *wrappedkey = NULL;
2047 size_t wrappedkeylen;
2048 gcry_cipher_hd_t cipherhd = NULL;
2049 unsigned char *key = NULL;
2050 size_t keylen, realkeylen;
2051 char *passphrase = NULL;
2052 unsigned char *finalkey = NULL;
2054 unsigned char grip[20];
2055 gcry_sexp_t openpgp_sexp = NULL;
2056 char *cache_nonce = NULL;
2059 if (ctrl->restricted)
2060 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
2062 if (!ctrl->server_local->import_key)
2064 err = gpg_error (GPG_ERR_MISSING_KEY);
2068 opt_unattended = has_option (line, "--unattended");
2069 line = skip_options (line);
2072 for (p=line; *p && *p != ' ' && *p != '\t'; p++)
2076 cache_nonce = xtrystrdup (line);
2078 assuan_begin_confidential (ctx);
2079 err = assuan_inquire (ctx, "KEYDATA",
2080 &wrappedkey, &wrappedkeylen, MAXLEN_KEYDATA);
2081 assuan_end_confidential (ctx);
2084 if (wrappedkeylen < 24)
2086 err = gpg_error (GPG_ERR_INV_LENGTH);
2089 keylen = wrappedkeylen - 8;
2090 key = xtrymalloc_secure (keylen);
2093 err = gpg_error_from_syserror ();
2097 err = gcry_cipher_open (&cipherhd, GCRY_CIPHER_AES128,
2098 GCRY_CIPHER_MODE_AESWRAP, 0);
2101 err = gcry_cipher_setkey (cipherhd,
2102 ctrl->server_local->import_key, KEYWRAP_KEYSIZE);
2105 err = gcry_cipher_decrypt (cipherhd, key, keylen, wrappedkey, wrappedkeylen);
2108 gcry_cipher_close (cipherhd);
2113 realkeylen = gcry_sexp_canon_len (key, keylen, NULL, &err);
2115 goto leave; /* Invalid canonical encoded S-expression. */
2117 err = keygrip_from_canon_sexp (key, realkeylen, grip);
2120 /* This might be due to an unsupported S-expression format.
2121 Check whether this is openpgp-private-key and trigger that
2123 if (!gcry_sexp_sscan (&openpgp_sexp, NULL, key, realkeylen))
2128 tag = gcry_sexp_nth_data (openpgp_sexp, 0, &taglen);
2129 if (tag && taglen == 19 && !memcmp (tag, "openpgp-private-key", 19))
2133 gcry_sexp_release (openpgp_sexp);
2134 openpgp_sexp = NULL;
2138 goto leave; /* Note that ERR is still set. */
2144 /* In most cases the key is encrypted and thus the conversion
2145 function from the OpenPGP format to our internal format will
2146 ask for a passphrase. That passphrase will be returned and
2147 used to protect the key using the same code as for regular
2152 err = convert_from_openpgp (ctrl, openpgp_sexp, grip,
2153 ctrl->server_local->keydesc, cache_nonce,
2154 &key, opt_unattended? NULL : &passphrase);
2157 realkeylen = gcry_sexp_canon_len (key, 0, NULL, &err);
2159 goto leave; /* Invalid canonical encoded S-expression. */
2162 assert (!opt_unattended);
2166 gcry_create_nonce (buf, 12);
2167 cache_nonce = bin2hex (buf, 12, NULL);
2170 && !agent_put_cache (cache_nonce, CACHE_MODE_NONCE,
2171 passphrase, CACHE_TTL_NONCE))
2172 assuan_write_status (ctx, "CACHE_NONCE", cache_nonce);
2175 else if (opt_unattended)
2177 err = set_error (GPG_ERR_ASS_PARAMETER,
2178 "\"--unattended\" may only be used with OpenPGP keys");
2183 if (!agent_key_available (grip))
2184 err = gpg_error (GPG_ERR_EEXIST);
2187 char *prompt = xtryasprintf
2188 (_("Please enter the passphrase to protect the "
2189 "imported object within the %s system."), GNUPG_NAME);
2191 err = gpg_error_from_syserror ();
2193 err = agent_ask_new_passphrase (ctrl, prompt, &passphrase);
2202 err = agent_protect (key, passphrase, &finalkey, &finalkeylen,
2205 err = agent_write_private_key (grip, finalkey, finalkeylen, 0);
2208 err = agent_write_private_key (grip, key, realkeylen, 0);
2211 gcry_sexp_release (openpgp_sexp);
2215 gcry_cipher_close (cipherhd);
2217 xfree (cache_nonce);
2218 xfree (ctrl->server_local->keydesc);
2219 ctrl->server_local->keydesc = NULL;
2220 return leave_cmd (ctx, err);
2225 static const char hlp_export_key[] =
2226 "EXPORT_KEY [--cache-nonce=<nonce>] [--openpgp] <hexstring_with_keygrip>\n"
2228 "Export a secret key from the key store. The key will be encrypted\n"
2229 "using the current session's key wrapping key (cf. command KEYWRAP_KEY)\n"
2230 "using the AESWRAP-128 algorithm. The caller needs to retrieve that key\n"
2231 "prior to using this command. The function takes the keygrip as argument.\n";
2233 cmd_export_key (assuan_context_t ctx, char *line)
2235 ctrl_t ctrl = assuan_get_pointer (ctx);
2237 unsigned char grip[20];
2238 gcry_sexp_t s_skey = NULL;
2239 unsigned char *key = NULL;
2241 gcry_cipher_hd_t cipherhd = NULL;
2242 unsigned char *wrappedkey = NULL;
2243 size_t wrappedkeylen;
2246 char *passphrase = NULL;
2247 unsigned char *shadow_info = NULL;
2251 if (ctrl->restricted)
2252 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
2254 openpgp = has_option (line, "--openpgp");
2255 cache_nonce = option_value (line, "--cache-nonce");
2258 for (pend = cache_nonce; *pend && !spacep (pend); pend++)
2262 cache_nonce = xtrystrdup (cache_nonce);
2266 err = gpg_error_from_syserror ();
2270 line = skip_options (line);
2272 if (!ctrl->server_local->export_key)
2274 err = set_error (GPG_ERR_MISSING_KEY, "did you run KEYWRAP_KEY ?");
2278 err = parse_keygrip (ctx, line, grip);
2282 if (agent_key_available (grip))
2284 err = gpg_error (GPG_ERR_NO_SECKEY);
2288 /* Get the key from the file. With the openpgp flag we also ask for
2289 the passphrase so that we can use it to re-encrypt it. */
2290 err = agent_key_from_file (ctrl, cache_nonce,
2291 ctrl->server_local->keydesc, grip,
2292 &shadow_info, CACHE_MODE_IGNORE, NULL, &s_skey,
2293 openpgp ? &passphrase : NULL);
2298 /* Key is on a smartcard. */
2299 err = gpg_error (GPG_ERR_UNUSABLE_SECKEY);
2305 /* The openpgp option changes the key format into the OpenPGP
2306 key transfer format. The result is already a padded
2307 canonical S-expression. */
2310 err = agent_ask_new_passphrase
2311 (ctrl, _("This key (or subkey) is not protected with a passphrase."
2312 " Please enter a new passphrase to export it."),
2317 err = convert_to_openpgp (ctrl, s_skey, passphrase, &key, &keylen);
2318 if (!err && passphrase)
2323 gcry_create_nonce (buf, 12);
2324 cache_nonce = bin2hex (buf, 12, NULL);
2327 && !agent_put_cache (cache_nonce, CACHE_MODE_NONCE,
2328 passphrase, CACHE_TTL_NONCE))
2330 assuan_write_status (ctx, "CACHE_NONCE", cache_nonce);
2331 xfree (ctrl->server_local->last_cache_nonce);
2332 ctrl->server_local->last_cache_nonce = cache_nonce;
2339 /* Convert into a canonical S-expression and wrap that. */
2340 err = make_canon_sexp_pad (s_skey, 1, &key, &keylen);
2344 gcry_sexp_release (s_skey);
2347 err = gcry_cipher_open (&cipherhd, GCRY_CIPHER_AES128,
2348 GCRY_CIPHER_MODE_AESWRAP, 0);
2351 err = gcry_cipher_setkey (cipherhd,
2352 ctrl->server_local->export_key, KEYWRAP_KEYSIZE);
2356 wrappedkeylen = keylen + 8;
2357 wrappedkey = xtrymalloc (wrappedkeylen);
2360 err = gpg_error_from_syserror ();
2364 err = gcry_cipher_encrypt (cipherhd, wrappedkey, wrappedkeylen, key, keylen);
2369 gcry_cipher_close (cipherhd);
2372 assuan_begin_confidential (ctx);
2373 err = assuan_send_data (ctx, wrappedkey, wrappedkeylen);
2374 assuan_end_confidential (ctx);
2378 xfree (cache_nonce);
2381 gcry_cipher_close (cipherhd);
2383 gcry_sexp_release (s_skey);
2384 xfree (ctrl->server_local->keydesc);
2385 ctrl->server_local->keydesc = NULL;
2386 xfree (shadow_info);
2388 return leave_cmd (ctx, err);
2393 static const char hlp_delete_key[] =
2394 "DELETE_KEY [--force] <hexstring_with_keygrip>\n"
2396 "Delete a secret key from the key store.\n"
2397 "Unless --force is used the agent asks the user for confirmation.\n";
2399 cmd_delete_key (assuan_context_t ctx, char *line)
2401 ctrl_t ctrl = assuan_get_pointer (ctx);
2404 unsigned char grip[20];
2406 if (ctrl->restricted)
2407 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
2409 force = has_option (line, "--force");
2410 line = skip_options (line);
2412 err = parse_keygrip (ctx, line, grip);
2416 err = agent_delete_key (ctrl, ctrl->server_local->keydesc, grip, force );
2421 xfree (ctrl->server_local->keydesc);
2422 ctrl->server_local->keydesc = NULL;
2424 return leave_cmd (ctx, err);
2429 static const char hlp_keytocard[] =
2430 "KEYTOCARD [--force] <hexstring_with_keygrip> <serialno> <id> <timestamp>\n"
2433 cmd_keytocard (assuan_context_t ctx, char *line)
2435 ctrl_t ctrl = assuan_get_pointer (ctx);
2437 gpg_error_t err = 0;
2438 unsigned char grip[20];
2439 gcry_sexp_t s_skey = NULL;
2440 unsigned char *keydata;
2441 size_t keydatalen, timestamplen;
2442 const char *serialno, *timestamp_str, *id;
2443 unsigned char *shadow_info = NULL;
2446 if (ctrl->restricted)
2447 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
2449 force = has_option (line, "--force");
2450 line = skip_options (line);
2452 err = parse_keygrip (ctx, line, grip);
2456 if (agent_key_available (grip))
2457 return gpg_error (GPG_ERR_NO_SECKEY);
2460 while (*line && (*line == ' ' || *line == '\t'))
2463 while (*line && (*line != ' ' && *line != '\t'))
2466 return gpg_error (GPG_ERR_MISSING_VALUE);
2469 while (*line && (*line == ' ' || *line == '\t'))
2472 while (*line && (*line != ' ' && *line != '\t'))
2475 return gpg_error (GPG_ERR_MISSING_VALUE);
2478 while (*line && (*line == ' ' || *line == '\t'))
2480 timestamp_str = line;
2481 while (*line && (*line != ' ' && *line != '\t'))
2485 timestamplen = line - timestamp_str;
2486 if (timestamplen != 15)
2487 return gpg_error (GPG_ERR_INV_VALUE);
2489 err = agent_key_from_file (ctrl, NULL, ctrl->server_local->keydesc, grip,
2490 &shadow_info, CACHE_MODE_IGNORE, NULL,
2494 xfree (shadow_info);
2499 /* Key is on a smartcard already. */
2500 xfree (shadow_info);
2501 gcry_sexp_release (s_skey);
2502 return gpg_error (GPG_ERR_UNUSABLE_SECKEY);
2505 keydatalen = gcry_sexp_sprint (s_skey, GCRYSEXP_FMT_CANON, NULL, 0);
2506 keydata = xtrymalloc_secure (keydatalen + 30);
2507 if (keydata == NULL)
2509 gcry_sexp_release (s_skey);
2510 return gpg_error_from_syserror ();
2513 gcry_sexp_sprint (s_skey, GCRYSEXP_FMT_CANON, keydata, keydatalen);
2514 gcry_sexp_release (s_skey);
2515 keydatalen--; /* Decrement for last '\0'. */
2516 /* Add timestamp "created-at" in the private key */
2517 timestamp = isotime2epoch (timestamp_str);
2518 snprintf (keydata+keydatalen-1, 30, "(10:created-at10:%010lu))", timestamp);
2519 keydatalen += 10 + 19 - 1;
2520 err = divert_writekey (ctrl, force, serialno, id, keydata, keydatalen);
2523 return leave_cmd (ctx, err);
2528 static const char hlp_getval[] =
2531 "Return the value for KEY from the special environment as created by\n"
2534 cmd_getval (assuan_context_t ctx, char *line)
2536 ctrl_t ctrl = assuan_get_pointer (ctx);
2540 struct putval_item_s *vl;
2542 if (ctrl->restricted)
2543 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
2545 for (p=line; *p == ' '; p++)
2548 p = strchr (key, ' ');
2552 for (; *p == ' '; p++)
2555 return set_error (GPG_ERR_ASS_PARAMETER, "too many arguments");
2558 return set_error (GPG_ERR_ASS_PARAMETER, "no key given");
2561 for (vl=putval_list; vl; vl = vl->next)
2562 if ( !strcmp (vl->d, key) )
2565 if (vl) /* Got an entry. */
2566 rc = assuan_send_data (ctx, vl->d+vl->off, vl->len);
2568 return gpg_error (GPG_ERR_NO_DATA);
2570 return leave_cmd (ctx, rc);
2574 static const char hlp_putval[] =
2575 "PUTVAL <key> [<percent_escaped_value>]\n"
2577 "The gpg-agent maintains a kind of environment which may be used to\n"
2578 "store key/value pairs in it, so that they can be retrieved later.\n"
2579 "This may be used by helper daemons to daemonize themself on\n"
2580 "invocation and register them with gpg-agent. Callers of the\n"
2581 "daemon's service may now first try connect to get the information\n"
2582 "for that service from gpg-agent through the GETVAL command and then\n"
2583 "try to connect to that daemon. Only if that fails they may start\n"
2584 "an own instance of the service daemon. \n"
2586 "KEY is an an arbitrary symbol with the same syntax rules as keys\n"
2587 "for shell environment variables. PERCENT_ESCAPED_VALUE is the\n"
2588 "corresponsing value; they should be similar to the values of\n"
2589 "envronment variables but gpg-agent does not enforce any\n"
2590 "restrictions. If that value is not given any value under that KEY\n"
2591 "is removed from this special environment.";
2593 cmd_putval (assuan_context_t ctx, char *line)
2595 ctrl_t ctrl = assuan_get_pointer (ctx);
2599 size_t valuelen = 0;
2601 struct putval_item_s *vl, *vlprev;
2603 if (ctrl->restricted)
2604 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
2606 for (p=line; *p == ' '; p++)
2609 p = strchr (key, ' ');
2613 for (; *p == ' '; p++)
2618 p = strchr (value, ' ');
2621 valuelen = percent_plus_unescape_inplace (value, 0);
2625 return set_error (GPG_ERR_ASS_PARAMETER, "no key given");
2628 for (vl=putval_list,vlprev=NULL; vl; vlprev=vl, vl = vl->next)
2629 if ( !strcmp (vl->d, key) )
2632 if (vl) /* Delete old entry. */
2635 vlprev->next = vl->next;
2637 putval_list = vl->next;
2641 if (valuelen) /* Add entry. */
2643 vl = xtrymalloc (sizeof *vl + strlen (key) + valuelen);
2645 rc = gpg_error_from_syserror ();
2649 vl->off = strlen (key) + 1;
2650 strcpy (vl->d, key);
2651 memcpy (vl->d + vl->off, value, valuelen);
2652 vl->next = putval_list;
2657 return leave_cmd (ctx, rc);
2663 static const char hlp_updatestartuptty[] =
2664 "UPDATESTARTUPTTY\n"
2666 "Set startup TTY and X11 DISPLAY variables to the values of this\n"
2667 "session. This command is useful to pull future pinentries to\n"
2668 "another screen. It is only required because there is no way in the\n"
2669 "ssh-agent protocol to convey this information.";
2671 cmd_updatestartuptty (assuan_context_t ctx, char *line)
2673 static const char *names[] =
2674 { "GPG_TTY", "DISPLAY", "TERM", "XAUTHORITY", "PINENTRY_USER_DATA", NULL };
2675 ctrl_t ctrl = assuan_get_pointer (ctx);
2676 gpg_error_t err = 0;
2679 char *lc_ctype = NULL;
2680 char *lc_messages = NULL;
2684 if (ctrl->restricted)
2685 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
2687 se = session_env_new ();
2689 err = gpg_error_from_syserror ();
2691 for (idx=0; !err && names[idx]; idx++)
2693 const char *value = session_env_getenv (ctrl->session_env, names[idx]);
2695 err = session_env_setenv (se, names[idx], value);
2698 if (!err && ctrl->lc_ctype)
2699 if (!(lc_ctype = xtrystrdup (ctrl->lc_ctype)))
2700 err = gpg_error_from_syserror ();
2702 if (!err && ctrl->lc_messages)
2703 if (!(lc_messages = xtrystrdup (ctrl->lc_messages)))
2704 err = gpg_error_from_syserror ();
2708 session_env_release (se);
2710 xfree (lc_messages);
2714 session_env_release (opt.startup_env);
2715 opt.startup_env = se;
2716 xfree (opt.startup_lc_ctype);
2717 opt.startup_lc_ctype = lc_ctype;
2718 xfree (opt.startup_lc_messages);
2719 opt.startup_lc_messages = lc_messages;
2727 static const char hlp_killagent[] =
2732 cmd_killagent (assuan_context_t ctx, char *line)
2734 ctrl_t ctrl = assuan_get_pointer (ctx);
2738 if (ctrl->restricted)
2739 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
2741 ctrl->server_local->stopme = 1;
2742 assuan_set_flag (ctx, ASSUAN_FORCE_CLOSE, 1);
2747 static const char hlp_reloadagent[] =
2750 "This command is an alternative to SIGHUP\n"
2751 "to reload the configuration.";
2753 cmd_reloadagent (assuan_context_t ctx, char *line)
2755 ctrl_t ctrl = assuan_get_pointer (ctx);
2759 if (ctrl->restricted)
2760 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
2762 agent_sighup_action ();
2768 static const char hlp_getinfo[] =
2771 "Multipurpose function to return a variety of information.\n"
2772 "Supported values for WHAT are:\n"
2774 " version - Return the version of the program.\n"
2775 " pid - Return the process id of the server.\n"
2776 " socket_name - Return the name of the socket.\n"
2777 " ssh_socket_name - Return the name of the ssh socket.\n"
2778 " scd_running - Return OK if the SCdaemon is already running.\n"
2779 " s2k_count - Return the calibrated S2K count.\n"
2780 " std_env_names - List the names of the standard environment.\n"
2781 " std_session_env - List the standard session environment.\n"
2782 " std_startup_env - List the standard startup environment.\n"
2784 " - Returns OK if the command CMD implements the option OPT.\n"
2785 " restricted - Returns OK if the connection is in restricted mode.\n";
2787 cmd_getinfo (assuan_context_t ctx, char *line)
2789 ctrl_t ctrl = assuan_get_pointer (ctx);
2792 if (!strcmp (line, "version"))
2794 const char *s = VERSION;
2795 rc = assuan_send_data (ctx, s, strlen (s));
2797 else if (!strncmp (line, "cmd_has_option", 14)
2798 && (line[14] == ' ' || line[14] == '\t' || !line[14]))
2802 while (*line == ' ' || *line == '\t')
2805 rc = gpg_error (GPG_ERR_MISSING_VALUE);
2809 while (*line && (*line != ' ' && *line != '\t'))
2812 rc = gpg_error (GPG_ERR_MISSING_VALUE);
2816 while (*line == ' ' || *line == '\t')
2819 rc = gpg_error (GPG_ERR_MISSING_VALUE);
2823 if (!command_has_option (cmd, cmdopt))
2824 rc = gpg_error (GPG_ERR_GENERAL);
2829 else if (!strcmp (line, "s2k_count"))
2833 snprintf (numbuf, sizeof numbuf, "%lu", get_standard_s2k_count ());
2834 rc = assuan_send_data (ctx, numbuf, strlen (numbuf));
2836 else if (!strcmp (line, "restricted"))
2838 rc = ctrl->restricted? 0 : gpg_error (GPG_ERR_GENERAL);
2840 else if (ctrl->restricted)
2842 rc = gpg_error (GPG_ERR_FORBIDDEN);
2844 /* All sub-commands below are not allowed in restricted mode. */
2845 else if (!strcmp (line, "pid"))
2849 snprintf (numbuf, sizeof numbuf, "%lu", (unsigned long)getpid ());
2850 rc = assuan_send_data (ctx, numbuf, strlen (numbuf));
2852 else if (!strcmp (line, "socket_name"))
2854 const char *s = get_agent_socket_name ();
2857 rc = assuan_send_data (ctx, s, strlen (s));
2859 rc = gpg_error (GPG_ERR_NO_DATA);
2861 else if (!strcmp (line, "ssh_socket_name"))
2863 const char *s = get_agent_ssh_socket_name ();
2866 rc = assuan_send_data (ctx, s, strlen (s));
2868 rc = gpg_error (GPG_ERR_NO_DATA);
2870 else if (!strcmp (line, "scd_running"))
2872 rc = agent_scd_check_running ()? 0 : gpg_error (GPG_ERR_GENERAL);
2874 else if (!strcmp (line, "std_env_names"))
2880 while ((name = session_env_list_stdenvnames (&iterator, NULL)))
2882 rc = assuan_send_data (ctx, name, strlen (name)+1);
2884 rc = assuan_send_data (ctx, NULL, 0);
2889 else if (!strcmp (line, "std_session_env")
2890 || !strcmp (line, "std_startup_env"))
2893 const char *name, *value;
2897 while ((name = session_env_list_stdenvnames (&iterator, NULL)))
2899 value = session_env_getenv_or_default
2900 (line[5] == 't'? opt.startup_env:ctrl->session_env, name, NULL);
2903 string = xtryasprintf ("%s=%s", name, value);
2905 rc = gpg_error_from_syserror ();
2908 rc = assuan_send_data (ctx, string, strlen (string)+1);
2910 rc = assuan_send_data (ctx, NULL, 0);
2918 rc = set_error (GPG_ERR_ASS_PARAMETER, "unknown value for WHAT");
2924 /* This function is called by Libassuan to parse the OPTION command.
2925 It has been registered similar to the other Assuan commands. */
2927 option_handler (assuan_context_t ctx, const char *key, const char *value)
2929 ctrl_t ctrl = assuan_get_pointer (ctx);
2930 gpg_error_t err = 0;
2932 if (!strcmp (key, "agent-awareness"))
2934 /* The value is a version string telling us of which agent
2935 version the caller is aware of. */
2936 ctrl->server_local->allow_fully_canceled =
2937 gnupg_compare_version (value, "2.1.0");
2939 else if (ctrl->restricted)
2941 err = gpg_error (GPG_ERR_FORBIDDEN);
2943 /* All options below are not allowed in restricted mode. */
2944 else if (!strcmp (key, "putenv"))
2946 /* Change the session's environment to be used for the
2947 Pinentry. Valid values are:
2948 <NAME> Delete envvar NAME
2949 <KEY>= Set envvar NAME to the empty string
2950 <KEY>=<VALUE> Set envvar NAME to VALUE
2952 err = session_env_putenv (ctrl->session_env, value);
2954 else if (!strcmp (key, "display"))
2956 err = session_env_setenv (ctrl->session_env, "DISPLAY", value);
2958 else if (!strcmp (key, "ttyname"))
2961 err = session_env_setenv (ctrl->session_env, "GPG_TTY", value);
2963 else if (!strcmp (key, "ttytype"))
2966 err = session_env_setenv (ctrl->session_env, "TERM", value);
2968 else if (!strcmp (key, "lc-ctype"))
2971 xfree (ctrl->lc_ctype);
2972 ctrl->lc_ctype = xtrystrdup (value);
2973 if (!ctrl->lc_ctype)
2974 return out_of_core ();
2976 else if (!strcmp (key, "lc-messages"))
2978 if (ctrl->lc_messages)
2979 xfree (ctrl->lc_messages);
2980 ctrl->lc_messages = xtrystrdup (value);
2981 if (!ctrl->lc_messages)
2982 return out_of_core ();
2984 else if (!strcmp (key, "xauthority"))
2986 err = session_env_setenv (ctrl->session_env, "XAUTHORITY", value);
2988 else if (!strcmp (key, "pinentry-user-data"))
2990 err = session_env_setenv (ctrl->session_env, "PINENTRY_USER_DATA", value);
2992 else if (!strcmp (key, "use-cache-for-signing"))
2993 ctrl->server_local->use_cache_for_signing = *value? atoi (value) : 0;
2994 else if (!strcmp (key, "allow-pinentry-notify"))
2995 ctrl->server_local->allow_pinentry_notify = 1;
2996 else if (!strcmp (key, "pinentry-mode"))
2998 int tmp = parse_pinentry_mode (value);
3000 err = gpg_error (GPG_ERR_INV_VALUE);
3001 else if (tmp == PINENTRY_MODE_LOOPBACK && !opt.allow_loopback_pinentry)
3002 err = gpg_error (GPG_ERR_NOT_SUPPORTED);
3004 ctrl->pinentry_mode = tmp;
3006 else if (!strcmp (key, "cache-ttl-opt-preset"))
3008 ctrl->cache_ttl_opt_preset = *value? atoi (value) : 0;
3010 else if (!strcmp (key, "s2k-count"))
3012 ctrl->s2k_count = *value? strtoul(value, NULL, 10) : 0;
3013 if (ctrl->s2k_count && ctrl->s2k_count < 65536)
3015 ctrl->s2k_count = 0;
3019 err = gpg_error (GPG_ERR_UNKNOWN_OPTION);
3027 /* Called by libassuan after all commands. ERR is the error from the
3028 last assuan operation and not the one returned from the command. */
3030 post_cmd_notify (assuan_context_t ctx, gpg_error_t err)
3032 ctrl_t ctrl = assuan_get_pointer (ctx);
3036 /* Switch off any I/O monitor controlled logging pausing. */
3037 ctrl->server_local->pause_io_logging = 0;
3041 /* This function is called by libassuan for all I/O. We use it here
3042 to disable logging for the GETEVENTCOUNTER commands. This is so
3043 that the debug output won't get cluttered by this primitive
3046 io_monitor (assuan_context_t ctx, void *hook, int direction,
3047 const char *line, size_t linelen)
3049 ctrl_t ctrl = assuan_get_pointer (ctx);
3053 /* Note that we only check for the uppercase name. This allows to
3054 see the logging for debugging if using a non-upercase command
3056 if (ctx && direction == ASSUAN_IO_FROM_PEER
3058 && !strncmp (line, "GETEVENTCOUNTER", 15)
3059 && (linelen == 15 || spacep (line+15)))
3061 ctrl->server_local->pause_io_logging = 1;
3064 return ctrl->server_local->pause_io_logging? ASSUAN_IO_MONITOR_NOLOG : 0;
3068 /* Return true if the command CMD implements the option OPT. */
3070 command_has_option (const char *cmd, const char *cmdopt)
3072 if (!strcmp (cmd, "GET_PASSPHRASE"))
3074 if (!strcmp (cmdopt, "repeat"))
3082 /* Tell Libassuan about our commands. Also register the other Assuan
3085 register_commands (assuan_context_t ctx)
3089 assuan_handler_t handler;
3090 const char * const help;
3092 { "GETEVENTCOUNTER",cmd_geteventcounter, hlp_geteventcounter },
3093 { "ISTRUSTED", cmd_istrusted, hlp_istrusted },
3094 { "HAVEKEY", cmd_havekey, hlp_havekey },
3095 { "KEYINFO", cmd_keyinfo, hlp_keyinfo },
3096 { "SIGKEY", cmd_sigkey, hlp_sigkey },
3097 { "SETKEY", cmd_sigkey, hlp_sigkey },
3098 { "SETKEYDESC", cmd_setkeydesc,hlp_setkeydesc },
3099 { "SETHASH", cmd_sethash, hlp_sethash },
3100 { "PKSIGN", cmd_pksign, hlp_pksign },
3101 { "PKDECRYPT", cmd_pkdecrypt, hlp_pkdecrypt },
3102 { "GENKEY", cmd_genkey, hlp_genkey },
3103 { "READKEY", cmd_readkey, hlp_readkey },
3104 { "GET_PASSPHRASE", cmd_get_passphrase, hlp_get_passphrase },
3105 { "PRESET_PASSPHRASE", cmd_preset_passphrase, hlp_preset_passphrase },
3106 { "CLEAR_PASSPHRASE", cmd_clear_passphrase, hlp_clear_passphrase },
3107 { "GET_CONFIRMATION", cmd_get_confirmation, hlp_get_confirmation },
3108 { "LISTTRUSTED", cmd_listtrusted, hlp_listtrusted },
3109 { "MARKTRUSTED", cmd_marktrusted, hlp_martrusted },
3110 { "LEARN", cmd_learn, hlp_learn },
3111 { "PASSWD", cmd_passwd, hlp_passwd },
3114 { "SCD", cmd_scd, hlp_scd },
3115 { "KEYWRAP_KEY", cmd_keywrap_key, hlp_keywrap_key },
3116 { "IMPORT_KEY", cmd_import_key, hlp_import_key },
3117 { "EXPORT_KEY", cmd_export_key, hlp_export_key },
3118 { "DELETE_KEY", cmd_delete_key, hlp_delete_key },
3119 { "GETVAL", cmd_getval, hlp_getval },
3120 { "PUTVAL", cmd_putval, hlp_putval },
3121 { "UPDATESTARTUPTTY", cmd_updatestartuptty, hlp_updatestartuptty },
3122 { "KILLAGENT", cmd_killagent, hlp_killagent },
3123 { "RELOADAGENT", cmd_reloadagent,hlp_reloadagent },
3124 { "GETINFO", cmd_getinfo, hlp_getinfo },
3125 { "KEYTOCARD", cmd_keytocard, hlp_keytocard },
3130 for (i=0; table[i].name; i++)
3132 rc = assuan_register_command (ctx, table[i].name, table[i].handler,
3137 assuan_register_post_cmd_notify (ctx, post_cmd_notify);
3138 assuan_register_reset_notify (ctx, reset_notify);
3139 assuan_register_option_handler (ctx, option_handler);
3144 /* Startup the server. If LISTEN_FD and FD is given as -1, this is a
3145 simple piper server, otherwise it is a regular server. CTRL is the
3146 control structure for this connection; it has only the basic
3149 start_command_handler (ctrl_t ctrl, gnupg_fd_t listen_fd, gnupg_fd_t fd)
3152 assuan_context_t ctx = NULL;
3154 if (ctrl->restricted)
3156 if (agent_copy_startup_env (ctrl))
3160 rc = assuan_new (&ctx);
3163 log_error ("failed to allocate assuan context: %s\n", gpg_strerror (rc));
3167 if (listen_fd == GNUPG_INVALID_FD && fd == GNUPG_INVALID_FD)
3169 assuan_fd_t filedes[2];
3171 filedes[0] = assuan_fdopen (0);
3172 filedes[1] = assuan_fdopen (1);
3173 rc = assuan_init_pipe_server (ctx, filedes);
3175 else if (listen_fd != GNUPG_INVALID_FD)
3177 rc = assuan_init_socket_server (ctx, listen_fd, 0);
3178 /* FIXME: Need to call assuan_sock_set_nonce for Windows. But
3179 this branch is currently not used. */
3183 rc = assuan_init_socket_server (ctx, fd, ASSUAN_SOCKET_SERVER_ACCEPTED);
3187 log_error ("failed to initialize the server: %s\n",
3191 rc = register_commands (ctx);
3194 log_error ("failed to register commands with Assuan: %s\n",
3199 assuan_set_pointer (ctx, ctrl);
3200 ctrl->server_local = xcalloc (1, sizeof *ctrl->server_local);
3201 ctrl->server_local->assuan_ctx = ctx;
3202 ctrl->server_local->use_cache_for_signing = 1;
3203 ctrl->digest.raw_value = 0;
3205 assuan_set_io_monitor (ctx, io_monitor, NULL);
3209 rc = assuan_accept (ctx);
3210 if (gpg_err_code (rc) == GPG_ERR_EOF || rc == -1)
3216 log_info ("Assuan accept problem: %s\n", gpg_strerror (rc));
3220 rc = assuan_process (ctx);
3223 log_info ("Assuan processing failed: %s\n", gpg_strerror (rc));
3228 /* Reset the nonce caches. */
3229 clear_nonce_cache (ctrl);
3231 /* Reset the SCD if needed. */
3232 agent_reset_scd (ctrl);
3234 /* Reset the pinentry (in case of popup messages). */
3235 agent_reset_query (ctrl);
3238 assuan_release (ctx);
3239 xfree (ctrl->server_local->keydesc);
3240 xfree (ctrl->server_local->import_key);
3241 xfree (ctrl->server_local->export_key);
3242 if (ctrl->server_local->stopme)
3244 xfree (ctrl->server_local);
3245 ctrl->server_local = NULL;
3249 /* Helper for the pinentry loopback mode. It merely passes the
3250 parameters on to the client. */
3252 pinentry_loopback(ctrl_t ctrl, const char *keyword,
3253 unsigned char **buffer, size_t *size,
3257 assuan_context_t ctx = ctrl->server_local->assuan_ctx;
3259 rc = print_assuan_status (ctx, "INQUIRE_MAXLEN", "%zu", max_length);
3263 assuan_begin_confidential (ctx);
3264 rc = assuan_inquire (ctx, keyword, buffer, size, max_length);
3265 assuan_end_confidential (ctx);