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"
44 #include "../common/server-help.h"
47 /* Maximum allowed size of the inquired ciphertext. */
48 #define MAXLEN_CIPHERTEXT 4096
49 /* Maximum allowed size of the key parameters. */
50 #define MAXLEN_KEYPARAM 1024
51 /* Maximum allowed size of key data as used in inquiries (bytes). */
52 #define MAXLEN_KEYDATA 4096
53 /* The size of the import/export KEK key (in bytes). */
54 #define KEYWRAP_KEYSIZE (128/8)
56 /* A shortcut to call assuan_set_error using an gpg_err_code_t and a
58 #define set_error(e,t) assuan_set_error (ctx, gpg_error (e), (t))
60 /* Check that the maximum digest length we support has at least the
61 length of the keygrip. */
62 #if MAX_DIGEST_LEN < 20
63 #error MAX_DIGEST_LEN shorter than keygrip
66 /* Data used to associate an Assuan context with local server data.
67 This is this modules local part of the server_control_s struct. */
70 /* Our Assuan context. */
71 assuan_context_t assuan_ctx;
73 /* If this flag is true, the passphrase cache is used for signing
74 operations. It defaults to true but may be set on a per
75 connection base. The global option opt.ignore_cache_for_signing
76 takes precedence over this flag. */
77 int use_cache_for_signing;
79 /* An allocated description for the next key operation. This is
80 used if a pinnetry needs to be popped up. */
83 /* Flags to suppress I/O logging during a command. */
86 /* If this flags is set to true the agent will be terminated after
87 the end of the current session. */
90 /* Flag indicating whether pinentry notifications shall be done. */
91 int allow_pinentry_notify;
93 /* Malloced KEK (Key-Encryption-Key) for the import_key command. */
96 /* Malloced KEK for the export_key command. */
99 /* Client is aware of the error code GPG_ERR_FULLY_CANCELED. */
100 int allow_fully_canceled;
102 /* Last CACHE_NONCE sent as status (malloced). */
103 char *last_cache_nonce;
105 /* Last PASSWD_NONCE sent as status (malloced). */
106 char *last_passwd_nonce;
110 /* An entry for the getval/putval commands. */
113 struct putval_item_s *next;
114 size_t off; /* Offset to the value into DATA. */
115 size_t len; /* Length of the value. */
116 char d[1]; /* Key | Nul | value. */
120 /* A list of key value pairs fpr the getval/putval commands. */
121 static struct putval_item_s *putval_list;
125 /* To help polling clients, we keep track of the number of certain
126 events. This structure keeps those counters. The counters are
127 integers and there should be no problem if they are overflowing as
128 callers need to check only whether a counter changed. The actual
129 values are not meaningful. */
132 /* Incremented if any of the other counters below changed. */
135 /* Incremented if a key is added or removed from the internal privat
139 /* Incremented if a change of the card readers stati has been
147 /* Local prototypes. */
148 static int command_has_option (const char *cmd, const char *cmdopt);
153 /* Release the memory buffer MB but first wipe out the used memory. */
155 clear_outbuf (membuf_t *mb)
160 p = get_membuf (mb, &n);
169 /* Write the content of memory buffer MB as assuan data to CTX and
170 wipe the buffer out afterwards. */
172 write_and_clear_outbuf (assuan_context_t ctx, membuf_t *mb)
178 p = get_membuf (mb, &n);
180 return out_of_core ();
181 ae = assuan_send_data (ctx, p, n);
188 /* Clear the nonces used to enable the passphrase cache for certain
189 multi-command command sequences. */
191 clear_nonce_cache (ctrl_t ctrl)
193 if (ctrl->server_local->last_cache_nonce)
195 agent_put_cache (ctrl->server_local->last_cache_nonce,
196 CACHE_MODE_NONCE, NULL, 0);
197 xfree (ctrl->server_local->last_cache_nonce);
198 ctrl->server_local->last_cache_nonce = NULL;
200 if (ctrl->server_local->last_passwd_nonce)
202 agent_put_cache (ctrl->server_local->last_passwd_nonce,
203 CACHE_MODE_NONCE, NULL, 0);
204 xfree (ctrl->server_local->last_passwd_nonce);
205 ctrl->server_local->last_passwd_nonce = NULL;
210 /* This function is called by Libassuan whenever thee client sends a
211 reset. It has been registered similar to the other Assuan
214 reset_notify (assuan_context_t ctx, char *line)
216 ctrl_t ctrl = assuan_get_pointer (ctx);
220 memset (ctrl->keygrip, 0, 20);
221 ctrl->have_keygrip = 0;
222 ctrl->digest.valuelen = 0;
224 xfree (ctrl->server_local->keydesc);
225 ctrl->server_local->keydesc = NULL;
227 clear_nonce_cache (ctrl);
233 /* Replace all '+' by a blank in the string S. */
235 plus_to_blank (char *s)
245 /* Parse a hex string. Return an Assuan error code or 0 on success and the
246 length of the parsed string in LEN. */
248 parse_hexstring (assuan_context_t ctx, const char *string, size_t *len)
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");
259 return set_error (GPG_ERR_ASS_PARAMETER, "odd number of digits");
265 /* Parse the keygrip in STRING into the provided buffer BUF. BUF must
266 provide space for 20 bytes. BUF is not changed if the function
269 parse_keygrip (assuan_context_t ctx, const char *string, unsigned char *buf)
274 rc = parse_hexstring (ctx, string, &n);
279 return set_error (GPG_ERR_ASS_PARAMETER, "invalid length of keygrip");
281 if (hex2bin (string, buf, 20) < 0)
282 return set_error (GPG_ERR_BUG, "hex2bin");
288 /* Write an Assuan status line. KEYWORD is the first item on the
289 status line. The following arguments are all separated by a space
290 in the output. The last argument must be a NULL. Linefeeds and
291 carriage returns characters (which are not allowed in an Assuan
292 status line) are silently quoted in C-style. */
294 agent_write_status (ctrl_t ctrl, const char *keyword, ...)
299 assuan_context_t ctx = ctrl->server_local->assuan_ctx;
303 va_start (arg_ptr, keyword);
307 while ( (text = va_arg (arg_ptr, const char *)) )
314 for ( ; *text && n < DIM (buf)-3; n++, text++)
321 else if (*text == '\r')
331 err = assuan_write_status (ctx, keyword, buf);
338 /* This function is similar to print_assuan_status but takes a CTRL
339 arg instead of an assuan context as first argument. */
341 agent_print_status (ctrl_t ctrl, const char *keyword, const char *format, ...)
345 assuan_context_t ctx = ctrl->server_local->assuan_ctx;
347 va_start (arg_ptr, format);
348 err = vprint_assuan_status (ctx, keyword, format, arg_ptr);
354 /* Helper to notify the client about a launched Pinentry. Because
355 that might disturb some older clients, this is only done if enabled
356 via an option. Returns an gpg error code. */
358 agent_inq_pinentry_launched (ctrl_t ctrl, unsigned long pid)
362 if (!ctrl || !ctrl->server_local
363 || !ctrl->server_local->allow_pinentry_notify)
365 snprintf (line, DIM(line)-1, "PINENTRY_LAUNCHED %lu", pid);
366 return assuan_inquire (ctrl->server_local->assuan_ctx, line, NULL, NULL, 0);
370 /* An agent progress callback for Libgcrypt. This has been registered
371 * to be called via the progress dispatcher mechanism from
374 progress_cb (ctrl_t ctrl, const char *what, int printchar,
375 int current, int total)
377 if (!ctrl || !ctrl->server_local || !ctrl->server_local->assuan_ctx)
379 else if (printchar == '\n' && what && !strcmp (what, "primegen"))
380 agent_print_status (ctrl, "PROGRESS", "%.20s X 100 100", what);
382 agent_print_status (ctrl, "PROGRESS", "%.20s %c %d %d",
383 what, printchar=='\n'?'X':printchar, current, total);
387 /* Helper to print a message while leaving a command. */
389 leave_cmd (assuan_context_t ctx, gpg_error_t err)
393 const char *name = assuan_get_command_name (ctx);
397 /* Not all users of gpg-agent know about the fully canceled
398 error code; map it back if needed. */
399 if (gpg_err_code (err) == GPG_ERR_FULLY_CANCELED)
401 ctrl_t ctrl = assuan_get_pointer (ctx);
403 if (!ctrl->server_local->allow_fully_canceled)
404 err = gpg_err_make (gpg_err_source (err), GPG_ERR_CANCELED);
407 /* Most code from common/ does not know the error source, thus
409 if (gpg_err_source (err) == GPG_ERR_SOURCE_UNKNOWN)
410 err = gpg_err_make (GPG_ERR_SOURCE_DEFAULT, gpg_err_code (err));
412 if (gpg_err_source (err) == GPG_ERR_SOURCE_DEFAULT)
413 log_error ("command '%s' failed: %s\n", name,
416 log_error ("command '%s' failed: %s <%s>\n", name,
417 gpg_strerror (err), gpg_strsource (err));
424 static const char hlp_geteventcounter[] =
427 "Return a a status line named EVENTCOUNTER with the current values\n"
428 "of all event counters. The values are decimal numbers in the range\n"
429 "0 to UINT_MAX and wrapping around to 0. The actual values should\n"
430 "not be relied upon, they shall only be used to detect a change.\n"
432 "The currently defined counters are:\n"
434 "ANY - Incremented with any change of any of the other counters.\n"
435 "KEY - Incremented for added or removed private keys.\n"
436 "CARD - Incremented for changes of the card readers stati.";
438 cmd_geteventcounter (assuan_context_t ctx, char *line)
440 ctrl_t ctrl = assuan_get_pointer (ctx);
444 if (ctrl->restricted)
445 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
447 return agent_print_status (ctrl, "EVENTCOUNTER", "%u %u %u",
454 /* This function should be called once for all key removals or
455 additions. This function is assured not to do any context
458 bump_key_eventcounter (void)
465 /* This function should be called for all card reader status
466 changes. This function is assured not to do any context
469 bump_card_eventcounter (void)
478 static const char hlp_istrusted[] =
479 "ISTRUSTED <hexstring_with_fingerprint>\n"
481 "Return OK when we have an entry with this fingerprint in our\n"
484 cmd_istrusted (assuan_context_t ctx, char *line)
486 ctrl_t ctrl = assuan_get_pointer (ctx);
491 /* Parse the fingerprint value. */
492 for (p=line,n=0; hexdigitp (p); p++, n++)
494 if (*p || !(n == 40 || n == 32))
495 return set_error (GPG_ERR_ASS_PARAMETER, "invalid fingerprint");
499 strcpy (fpr, "00000000");
502 for (p=line; i < 40; p++, i++)
503 fpr[i] = *p >= 'a'? (*p & 0xdf): *p;
505 rc = agent_istrusted (ctrl, fpr, NULL);
506 if (!rc || gpg_err_code (rc) == GPG_ERR_NOT_TRUSTED)
508 else if (rc == -1 || gpg_err_code (rc) == GPG_ERR_EOF )
509 return gpg_error (GPG_ERR_NOT_TRUSTED);
511 return leave_cmd (ctx, rc);
515 static const char hlp_listtrusted[] =
518 "List all entries from the trustlist.";
520 cmd_listtrusted (assuan_context_t ctx, char *line)
522 ctrl_t ctrl = assuan_get_pointer (ctx);
527 if (ctrl->restricted)
528 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
530 rc = agent_listtrusted (ctx);
531 return leave_cmd (ctx, rc);
535 static const char hlp_martrusted[] =
536 "MARKTRUSTED <hexstring_with_fingerprint> <flag> <display_name>\n"
538 "Store a new key in into the trustlist.";
540 cmd_marktrusted (assuan_context_t ctx, char *line)
542 ctrl_t ctrl = assuan_get_pointer (ctx);
548 if (ctrl->restricted)
549 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
551 /* parse the fingerprint value */
552 for (p=line,n=0; hexdigitp (p); p++, n++)
554 if (!spacep (p) || !(n == 40 || n == 32))
555 return set_error (GPG_ERR_ASS_PARAMETER, "invalid fingerprint");
559 strcpy (fpr, "00000000");
562 for (p=line; i < 40; p++, i++)
563 fpr[i] = *p >= 'a'? (*p & 0xdf): *p;
569 if ( (flag != 'S' && flag != 'P') || !spacep (p) )
570 return set_error (GPG_ERR_ASS_PARAMETER, "invalid flag - must be P or S");
574 rc = agent_marktrusted (ctrl, p, fpr, flag);
575 return leave_cmd (ctx, rc);
581 static const char hlp_havekey[] =
582 "HAVEKEY <hexstrings_with_keygrips>\n"
584 "Return success if at least one of the secret keys with the given\n"
585 "keygrips is available.";
587 cmd_havekey (assuan_context_t ctx, char *line)
590 unsigned char buf[20];
594 err = parse_keygrip (ctx, line, buf);
598 if (!agent_key_available (buf))
599 return 0; /* Found. */
601 while (*line && *line != ' ' && *line != '\t')
603 while (*line == ' ' || *line == '\t')
608 /* No leave_cmd() here because errors are expected and would clutter
610 return gpg_error (GPG_ERR_NO_SECKEY);
614 static const char hlp_sigkey[] =
615 "SIGKEY <hexstring_with_keygrip>\n"
616 "SETKEY <hexstring_with_keygrip>\n"
618 "Set the key used for a sign or decrypt operation.";
620 cmd_sigkey (assuan_context_t ctx, char *line)
623 ctrl_t ctrl = assuan_get_pointer (ctx);
625 rc = parse_keygrip (ctx, line, ctrl->keygrip);
628 ctrl->have_keygrip = 1;
633 static const char hlp_setkeydesc[] =
634 "SETKEYDESC plus_percent_escaped_string\n"
636 "Set a description to be used for the next PKSIGN, PKDECRYPT, IMPORT_KEY\n"
637 "or EXPORT_KEY operation if this operation requires a passphrase. If\n"
638 "this command is not used a default text will be used. Note, that\n"
639 "this description implictly selects the label used for the entry\n"
640 "box; if the string contains the string PIN (which in general will\n"
641 "not be translated), \"PIN\" is used, otherwise the translation of\n"
642 "\"passphrase\" is used. The description string should not contain\n"
643 "blanks unless they are percent or '+' escaped.\n"
645 "The description is only valid for the next PKSIGN, PKDECRYPT,\n"
646 "IMPORT_KEY, EXPORT_KEY, or DELETE_KEY operation.";
648 cmd_setkeydesc (assuan_context_t ctx, char *line)
650 ctrl_t ctrl = assuan_get_pointer (ctx);
653 for (p=line; *p == ' '; p++)
656 p = strchr (desc, ' ');
658 *p = 0; /* We ignore any garbage; we might late use it for other args. */
661 return set_error (GPG_ERR_ASS_PARAMETER, "no description given");
663 /* Note, that we only need to replace the + characters and should
664 leave the other escaping in place because the escaped string is
665 send verbatim to the pinentry which does the unescaping (but not
667 plus_to_blank (desc);
669 xfree (ctrl->server_local->keydesc);
671 if (ctrl->restricted)
673 ctrl->server_local->keydesc = strconcat
674 ((ctrl->restricted == 2
675 ? _("Note: Request from the web browser.")
676 : _("Note: Request from a remote site.") ), "%0A%0A", desc, NULL);
679 ctrl->server_local->keydesc = xtrystrdup (desc);
680 if (!ctrl->server_local->keydesc)
681 return out_of_core ();
686 static const char hlp_sethash[] =
687 "SETHASH (--hash=<name>)|(<algonumber>) <hexstring>\n"
689 "The client can use this command to tell the server about the data\n"
690 "(which usually is a hash) to be signed.";
692 cmd_sethash (assuan_context_t ctx, char *line)
697 ctrl_t ctrl = assuan_get_pointer (ctx);
702 /* Parse the alternative hash options which may be used instead of
704 if (has_option_name (line, "--hash"))
706 if (has_option (line, "--hash=sha1"))
708 else if (has_option (line, "--hash=sha224"))
709 algo = GCRY_MD_SHA224;
710 else if (has_option (line, "--hash=sha256"))
711 algo = GCRY_MD_SHA256;
712 else if (has_option (line, "--hash=sha384"))
713 algo = GCRY_MD_SHA384;
714 else if (has_option (line, "--hash=sha512"))
715 algo = GCRY_MD_SHA512;
716 else if (has_option (line, "--hash=rmd160"))
717 algo = GCRY_MD_RMD160;
718 else if (has_option (line, "--hash=md5"))
720 else if (has_option (line, "--hash=tls-md5sha1"))
721 algo = MD_USER_TLS_MD5SHA1;
723 return set_error (GPG_ERR_ASS_PARAMETER, "invalid hash algorithm");
728 line = skip_options (line);
732 /* No hash option has been given: require an algo number instead */
733 algo = (int)strtoul (line, &endp, 10);
734 for (line = endp; *line == ' ' || *line == '\t'; line++)
736 if (!algo || gcry_md_test_algo (algo))
737 return set_error (GPG_ERR_UNSUPPORTED_ALGORITHM, NULL);
739 ctrl->digest.algo = algo;
740 ctrl->digest.raw_value = 0;
742 /* Parse the hash value. */
744 rc = parse_hexstring (ctx, line, &n);
748 if (algo == MD_USER_TLS_MD5SHA1 && n == 36)
750 else if (n != 16 && n != 20 && n != 24
751 && n != 28 && n != 32 && n != 48 && n != 64)
752 return set_error (GPG_ERR_ASS_PARAMETER, "unsupported length of hash");
754 if (n > MAX_DIGEST_LEN)
755 return set_error (GPG_ERR_ASS_PARAMETER, "hash value to long");
757 buf = ctrl->digest.value;
758 ctrl->digest.valuelen = n;
759 for (p=line, n=0; n < ctrl->digest.valuelen; p += 2, n++)
761 for (; n < ctrl->digest.valuelen; n++)
767 static const char hlp_pksign[] =
768 "PKSIGN [<options>] [<cache_nonce>]\n"
770 "Perform the actual sign operation. Neither input nor output are\n"
771 "sensitive to eavesdropping.";
773 cmd_pksign (assuan_context_t ctx, char *line)
776 cache_mode_t cache_mode = CACHE_MODE_NORMAL;
777 ctrl_t ctrl = assuan_get_pointer (ctx);
779 char *cache_nonce = NULL;
782 line = skip_options (line);
785 for (p=line; *p && *p != ' ' && *p != '\t'; p++)
789 cache_nonce = xtrystrdup (line);
791 if (opt.ignore_cache_for_signing)
792 cache_mode = CACHE_MODE_IGNORE;
793 else if (!ctrl->server_local->use_cache_for_signing)
794 cache_mode = CACHE_MODE_IGNORE;
796 init_membuf (&outbuf, 512);
798 rc = agent_pksign (ctrl, cache_nonce, ctrl->server_local->keydesc,
799 &outbuf, cache_mode);
801 clear_outbuf (&outbuf);
803 rc = write_and_clear_outbuf (ctx, &outbuf);
806 xfree (ctrl->server_local->keydesc);
807 ctrl->server_local->keydesc = NULL;
808 return leave_cmd (ctx, rc);
812 static const char hlp_pkdecrypt[] =
813 "PKDECRYPT [<options>]\n"
815 "Perform the actual decrypt operation. Input is not\n"
816 "sensitive to eavesdropping.";
818 cmd_pkdecrypt (assuan_context_t ctx, char *line)
821 ctrl_t ctrl = assuan_get_pointer (ctx);
822 unsigned char *value;
829 /* First inquire the data to decrypt */
830 rc = print_assuan_status (ctx, "INQUIRE_MAXLEN", "%u", MAXLEN_CIPHERTEXT);
832 rc = assuan_inquire (ctx, "CIPHERTEXT",
833 &value, &valuelen, MAXLEN_CIPHERTEXT);
837 init_membuf (&outbuf, 512);
839 rc = agent_pkdecrypt (ctrl, ctrl->server_local->keydesc,
840 value, valuelen, &outbuf, &padding);
843 clear_outbuf (&outbuf);
847 rc = print_assuan_status (ctx, "PADDING", "%d", padding);
851 rc = write_and_clear_outbuf (ctx, &outbuf);
853 xfree (ctrl->server_local->keydesc);
854 ctrl->server_local->keydesc = NULL;
855 return leave_cmd (ctx, rc);
859 static const char hlp_genkey[] =
860 "GENKEY [--no-protection] [--preset] [--inq-passwd] [<cache_nonce>]\n"
862 "Generate a new key, store the secret part and return the public\n"
863 "part. Here is an example transaction:\n"
866 " S: INQUIRE KEYPARAM\n"
867 " C: D (genkey (rsa (nbits 2048)))\n"
869 " S: D (public-key\n"
870 " S: D (rsa (n 326487324683264) (e 10001)))\n"
871 " S: OK key created\n"
873 "When the --preset option is used the passphrase for the generated\n"
874 "key will be added to the cache. When --inq-passwd is used an inquire\n"
875 "with the keyword NEWPASSWD is used to request the passphrase for the\n"
878 cmd_genkey (assuan_context_t ctx, char *line)
880 ctrl_t ctrl = assuan_get_pointer (ctx);
883 unsigned char *value;
885 unsigned char *newpasswd = NULL;
887 char *cache_nonce = NULL;
893 if (ctrl->restricted)
894 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
896 no_protection = has_option (line, "--no-protection");
897 opt_preset = has_option (line, "--preset");
898 opt_inq_passwd = has_option (line, "--inq-passwd");
899 line = skip_options (line);
902 for (p=line; *p && *p != ' ' && *p != '\t'; p++)
906 cache_nonce = xtrystrdup (line);
908 /* First inquire the parameters */
909 rc = print_assuan_status (ctx, "INQUIRE_MAXLEN", "%u", MAXLEN_KEYPARAM);
911 rc = assuan_inquire (ctx, "KEYPARAM", &value, &valuelen, MAXLEN_KEYPARAM);
915 init_membuf (&outbuf, 512);
917 /* If requested, ask for the password to be used for the key. If
918 this is not used the regular Pinentry mechanism is used. */
919 if (opt_inq_passwd && !no_protection)
921 /* (N is used as a dummy) */
922 assuan_begin_confidential (ctx);
923 rc = assuan_inquire (ctx, "NEWPASSWD", &newpasswd, &n, 256);
924 assuan_end_confidential (ctx);
929 /* Empty password given - switch to no-protection mode. */
937 rc = agent_genkey (ctrl, cache_nonce, (char*)value, valuelen, no_protection,
938 newpasswd, opt_preset, &outbuf);
943 /* Assuan_inquire does not allow us to read into secure memory
944 thus we need to wipe it ourself. */
945 wipememory (newpasswd, strlen (newpasswd));
950 clear_outbuf (&outbuf);
952 rc = write_and_clear_outbuf (ctx, &outbuf);
954 return leave_cmd (ctx, rc);
960 static const char hlp_readkey[] =
961 "READKEY <hexstring_with_keygrip>\n"
963 "Return the public key for the given keygrip.";
965 cmd_readkey (assuan_context_t ctx, char *line)
967 ctrl_t ctrl = assuan_get_pointer (ctx);
969 unsigned char grip[20];
970 gcry_sexp_t s_pkey = NULL;
972 if (ctrl->restricted)
973 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
975 rc = parse_keygrip (ctx, line, grip);
977 return rc; /* Return immediately as this is already an Assuan error code.*/
979 rc = agent_public_key_from_file (ctrl, grip, &s_pkey);
985 len = gcry_sexp_sprint (s_pkey, GCRYSEXP_FMT_CANON, NULL, 0);
987 buf = xtrymalloc (len);
989 rc = gpg_error_from_syserror ();
992 len = gcry_sexp_sprint (s_pkey, GCRYSEXP_FMT_CANON, buf, len);
994 rc = assuan_send_data (ctx, buf, len);
997 gcry_sexp_release (s_pkey);
1000 return leave_cmd (ctx, rc);
1005 static const char hlp_keyinfo[] =
1006 "KEYINFO [--[ssh-]list] [--data] [--ssh-fpr] [--with-ssh] <keygrip>\n"
1008 "Return information about the key specified by the KEYGRIP. If the\n"
1009 "key is not available GPG_ERR_NOT_FOUND is returned. If the option\n"
1010 "--list is given the keygrip is ignored and information about all\n"
1011 "available keys are returned. If --ssh-list is given information\n"
1012 "about all keys listed in the sshcontrol are returned. With --with-ssh\n"
1013 "information from sshcontrol is always added to the info. Unless --data\n"
1014 "is given, the information is returned as a status line using the format:\n"
1016 " KEYINFO <keygrip> <type> <serialno> <idstr> <cached> <protection> <fpr>\n"
1018 "KEYGRIP is the keygrip.\n"
1020 "TYPE is describes the type of the key:\n"
1021 " 'D' - Regular key stored on disk,\n"
1022 " 'T' - Key is stored on a smartcard (token),\n"
1023 " 'X' - Unknown type,\n"
1024 " '-' - Key is missing.\n"
1026 "SERIALNO is an ASCII string with the serial number of the\n"
1027 " smartcard. If the serial number is not known a single\n"
1028 " dash '-' is used instead.\n"
1030 "IDSTR is the IDSTR used to distinguish keys on a smartcard. If it\n"
1031 " is not known a dash is used instead.\n"
1033 "CACHED is 1 if the passphrase for the key was found in the key cache.\n"
1034 " If not, a '-' is used instead.\n"
1036 "PROTECTION describes the key protection type:\n"
1037 " 'P' - The key is protected with a passphrase,\n"
1038 " 'C' - The key is not protected,\n"
1039 " '-' - Unknown protection.\n"
1041 "FPR returns the formatted ssh-style fingerprint of the key. It is only\n"
1042 " printed if the option --ssh-fpr has been used. It defaults to '-'.\n"
1044 "TTL is the TTL in seconds for that key or '-' if n/a.\n"
1046 "FLAGS is a word consisting of one-letter flags:\n"
1047 " 'D' - The key has been disabled,\n"
1048 " 'S' - The key is listed in sshcontrol (requires --with-ssh),\n"
1049 " 'c' - Use of the key needs to be confirmed,\n"
1050 " '-' - No flags given.\n"
1052 "More information may be added in the future.";
1054 do_one_keyinfo (ctrl_t ctrl, const unsigned char *grip, assuan_context_t ctx,
1055 int data, int with_ssh_fpr, int in_ssh,
1056 int ttl, int disabled, int confirm)
1062 unsigned char *shadow_info = NULL;
1063 char *serialno = NULL;
1065 const char *keytypestr;
1067 const char *protectionstr;
1069 int missing_key = 0;
1073 err = agent_key_info_from_file (ctrl, grip, &keytype, &shadow_info);
1076 if (in_ssh && gpg_err_code (err) == GPG_ERR_NOT_FOUND)
1082 /* Reformat the grip so that we use uppercase as good style. */
1083 bin2hex (grip, 20, hexgrip);
1086 snprintf (ttlbuf, sizeof ttlbuf, "%d", ttl);
1088 strcpy (ttlbuf, "-");
1092 strcat (flagsbuf, "D");
1094 strcat (flagsbuf, "S");
1096 strcat (flagsbuf, "c");
1098 strcpy (flagsbuf, "-");
1103 protectionstr = "-"; keytypestr = "-";
1109 case PRIVATE_KEY_CLEAR:
1110 case PRIVATE_KEY_OPENPGP_NONE:
1111 protectionstr = "C"; keytypestr = "D";
1113 case PRIVATE_KEY_PROTECTED: protectionstr = "P"; keytypestr = "D";
1115 case PRIVATE_KEY_SHADOWED: protectionstr = "-"; keytypestr = "T";
1117 default: protectionstr = "-"; keytypestr = "X";
1122 /* Compute the ssh fingerprint if requested. */
1127 if (!agent_raw_key_from_file (ctrl, grip, &key))
1129 ssh_get_fingerprint_string (key, &fpr);
1130 gcry_sexp_release (key);
1134 /* Here we have a little race by doing the cache check separately
1135 from the retrieval function. Given that the cache flag is only a
1136 hint, it should not really matter. */
1137 pw = agent_get_cache (hexgrip, CACHE_MODE_NORMAL);
1138 cached = pw ? "1" : "-";
1143 err = parse_shadow_info (shadow_info, &serialno, &idstr, NULL);
1149 err = agent_write_status (ctrl, "KEYINFO",
1152 serialno? serialno : "-",
1164 string = xtryasprintf ("%s %s %s %s %s %s %s %s %s\n",
1165 hexgrip, keytypestr,
1166 serialno? serialno : "-",
1167 idstr? idstr : "-", cached, protectionstr,
1172 err = gpg_error_from_syserror ();
1174 err = assuan_send_data (ctx, string, strlen(string));
1180 xfree (shadow_info);
1187 /* Entry int for the command KEYINFO. This function handles the
1188 command option processing. For details see hlp_keyinfo above. */
1190 cmd_keyinfo (assuan_context_t ctx, char *line)
1192 ctrl_t ctrl = assuan_get_pointer (ctx);
1194 unsigned char grip[20];
1197 int opt_data, opt_ssh_fpr, opt_with_ssh;
1198 ssh_control_file_t cf = NULL;
1200 int disabled, ttl, confirm, is_ssh;
1202 if (ctrl->restricted)
1203 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
1205 if (has_option (line, "--ssh-list"))
1208 list_mode = has_option (line, "--list");
1209 opt_data = has_option (line, "--data");
1210 opt_ssh_fpr = has_option (line, "--ssh-fpr");
1211 opt_with_ssh = has_option (line, "--with-ssh");
1212 line = skip_options (line);
1214 if (opt_with_ssh || list_mode == 2)
1215 cf = ssh_open_control_file ();
1221 while (!ssh_read_control_file (cf, hexgrip,
1222 &disabled, &ttl, &confirm))
1224 if (hex2bin (hexgrip, grip, 20) < 0 )
1225 continue; /* Bad hex string. */
1226 err = do_one_keyinfo (ctrl, grip, ctx, opt_data, opt_ssh_fpr, 1,
1227 ttl, disabled, confirm);
1237 struct dirent *dir_entry;
1239 dirname = make_filename_try (opt.homedir, GNUPG_PRIVATE_KEYS_DIR, NULL);
1242 err = gpg_error_from_syserror ();
1245 dir = opendir (dirname);
1248 err = gpg_error_from_syserror ();
1254 while ( (dir_entry = readdir (dir)) )
1256 if (strlen (dir_entry->d_name) != 44
1257 || strcmp (dir_entry->d_name + 40, ".key"))
1259 strncpy (hexgrip, dir_entry->d_name, 40);
1262 if ( hex2bin (hexgrip, grip, 20) < 0 )
1263 continue; /* Bad hex string. */
1265 disabled = ttl = confirm = is_ssh = 0;
1268 err = ssh_search_control_file (cf, hexgrip,
1269 &disabled, &ttl, &confirm);
1272 else if (gpg_err_code (err) != GPG_ERR_NOT_FOUND)
1276 err = do_one_keyinfo (ctrl, grip, ctx, opt_data, opt_ssh_fpr, is_ssh,
1277 ttl, disabled, confirm);
1285 err = parse_keygrip (ctx, line, grip);
1288 disabled = ttl = confirm = is_ssh = 0;
1291 err = ssh_search_control_file (cf, line,
1292 &disabled, &ttl, &confirm);
1295 else if (gpg_err_code (err) != GPG_ERR_NOT_FOUND)
1299 err = do_one_keyinfo (ctrl, grip, ctx, opt_data, opt_ssh_fpr, is_ssh,
1300 ttl, disabled, confirm);
1304 ssh_close_control_file (cf);
1307 if (err && gpg_err_code (err) != GPG_ERR_NOT_FOUND)
1308 leave_cmd (ctx, err);
1314 /* Helper for cmd_get_passphrase. */
1316 send_back_passphrase (assuan_context_t ctx, int via_data, const char *pw)
1321 assuan_begin_confidential (ctx);
1324 rc = assuan_send_data (ctx, pw, n);
1327 char *p = xtrymalloc_secure (n*2+1);
1329 rc = gpg_error_from_syserror ();
1333 rc = assuan_set_okay_line (ctx, p);
1341 static const char hlp_get_passphrase[] =
1342 "GET_PASSPHRASE [--data] [--check] [--no-ask] [--repeat[=N]]\n"
1343 " [--qualitybar] <cache_id>\n"
1344 " [<error_message> <prompt> <description>]\n"
1346 "This function is usually used to ask for a passphrase to be used\n"
1347 "for conventional encryption, but may also be used by programs which\n"
1348 "need specal handling of passphrases. This command uses a syntax\n"
1349 "which helps clients to use the agent with minimum effort. The\n"
1350 "agent either returns with an error or with a OK followed by the hex\n"
1351 "encoded passphrase. Note that the length of the strings is\n"
1352 "implicitly limited by the maximum length of a command.\n"
1354 "If the option \"--data\" is used the passphrase is returned by usual\n"
1355 "data lines and not on the okay line.\n"
1357 "If the option \"--check\" is used the passphrase constraints checks as\n"
1358 "implemented by gpg-agent are applied. A check is not done if the\n"
1359 "passphrase has been found in the cache.\n"
1361 "If the option \"--no-ask\" is used and the passphrase is not in the\n"
1362 "cache the user will not be asked to enter a passphrase but the error\n"
1363 "code GPG_ERR_NO_DATA is returned. \n"
1365 "If the option \"--qualitybar\" is used a visual indication of the\n"
1366 "entered passphrase quality is shown. (Unless no minimum passphrase\n"
1367 "length has been configured.)";
1369 cmd_get_passphrase (assuan_context_t ctx, char *line)
1371 ctrl_t ctrl = assuan_get_pointer (ctx);
1375 char *cacheid = NULL, *desc = NULL, *prompt = NULL, *errtext = NULL;
1376 const char *desc2 = _("Please re-enter this passphrase");
1378 int opt_data, opt_check, opt_no_ask, opt_qualbar;
1380 char *entry_errtext = NULL;
1382 if (ctrl->restricted)
1383 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
1385 opt_data = has_option (line, "--data");
1386 opt_check = has_option (line, "--check");
1387 opt_no_ask = has_option (line, "--no-ask");
1388 if (has_option_name (line, "--repeat"))
1390 p = option_value (line, "--repeat");
1392 opt_repeat = atoi (p);
1396 opt_qualbar = has_option (line, "--qualitybar");
1397 line = skip_options (line);
1400 p = strchr (cacheid, ' ');
1407 p = strchr (errtext, ' ');
1414 p = strchr (prompt, ' ');
1421 p = strchr (desc, ' ');
1423 *p = 0; /* Ignore trailing garbage. */
1427 if (!*cacheid || strlen (cacheid) > 50)
1428 return set_error (GPG_ERR_ASS_PARAMETER, "invalid length of cacheID");
1430 return set_error (GPG_ERR_ASS_PARAMETER, "no description given");
1432 if (!strcmp (cacheid, "X"))
1434 if (!strcmp (errtext, "X"))
1436 if (!strcmp (prompt, "X"))
1438 if (!strcmp (desc, "X"))
1441 pw = cacheid ? agent_get_cache (cacheid, CACHE_MODE_USER) : NULL;
1444 rc = send_back_passphrase (ctx, opt_data, pw);
1447 else if (opt_no_ask)
1448 rc = gpg_error (GPG_ERR_NO_DATA);
1451 /* Note, that we only need to replace the + characters and
1452 should leave the other escaping in place because the escaped
1453 string is send verbatim to the pinentry which does the
1454 unescaping (but not the + replacing) */
1456 plus_to_blank (errtext);
1458 plus_to_blank (prompt);
1460 plus_to_blank (desc);
1463 rc = agent_get_passphrase (ctrl, &response, desc, prompt,
1464 entry_errtext? entry_errtext:errtext,
1465 opt_qualbar, cacheid, CACHE_MODE_USER);
1466 xfree (entry_errtext);
1467 entry_errtext = NULL;
1473 && check_passphrase_constraints (ctrl, response, &entry_errtext))
1478 for (i = 0; i < opt_repeat; i++)
1482 if (ctrl->pinentry_mode == PINENTRY_MODE_LOOPBACK)
1485 rc = agent_get_passphrase (ctrl, &response2, desc2, prompt,
1487 cacheid, CACHE_MODE_USER);
1490 if (strcmp (response2, response))
1494 entry_errtext = try_percent_escape
1495 (_("does not match - try again"), NULL);
1498 rc = gpg_error_from_syserror ();
1508 agent_put_cache (cacheid, CACHE_MODE_USER, response, 0);
1509 rc = send_back_passphrase (ctx, opt_data, response);
1515 return leave_cmd (ctx, rc);
1519 static const char hlp_clear_passphrase[] =
1520 "CLEAR_PASSPHRASE [--mode=normal] <cache_id>\n"
1522 "may be used to invalidate the cache entry for a passphrase. The\n"
1523 "function returns with OK even when there is no cached passphrase.\n"
1524 "The --mode=normal option is used to clear an entry for a cacheid\n"
1525 "added by the agent.\n";
1527 cmd_clear_passphrase (assuan_context_t ctx, char *line)
1529 ctrl_t ctrl = assuan_get_pointer (ctx);
1530 char *cacheid = NULL;
1534 if (ctrl->restricted)
1535 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
1537 opt_normal = has_option (line, "--mode=normal");
1538 line = skip_options (line);
1540 /* parse the stuff */
1541 for (p=line; *p == ' '; p++)
1544 p = strchr (cacheid, ' ');
1546 *p = 0; /* ignore garbage */
1547 if (!*cacheid || strlen (cacheid) > 50)
1548 return set_error (GPG_ERR_ASS_PARAMETER, "invalid length of cacheID");
1550 agent_put_cache (cacheid, opt_normal ? CACHE_MODE_NORMAL : CACHE_MODE_USER,
1553 agent_clear_passphrase (ctrl, cacheid,
1554 opt_normal ? CACHE_MODE_NORMAL : CACHE_MODE_USER);
1560 static const char hlp_get_confirmation[] =
1561 "GET_CONFIRMATION <description>\n"
1563 "This command may be used to ask for a simple confirmation.\n"
1564 "DESCRIPTION is displayed along with a Okay and Cancel button. This\n"
1565 "command uses a syntax which helps clients to use the agent with\n"
1566 "minimum effort. The agent either returns with an error or with a\n"
1567 "OK. Note, that the length of DESCRIPTION is implicitly limited by\n"
1568 "the maximum length of a command. DESCRIPTION should not contain\n"
1569 "any spaces, those must be encoded either percent escaped or simply\n"
1572 cmd_get_confirmation (assuan_context_t ctx, char *line)
1574 ctrl_t ctrl = assuan_get_pointer (ctx);
1579 if (ctrl->restricted)
1580 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
1582 /* parse the stuff */
1583 for (p=line; *p == ' '; p++)
1586 p = strchr (desc, ' ');
1588 *p = 0; /* We ignore any garbage -may be later used for other args. */
1591 return set_error (GPG_ERR_ASS_PARAMETER, "no description given");
1593 if (!strcmp (desc, "X"))
1596 /* Note, that we only need to replace the + characters and should
1597 leave the other escaping in place because the escaped string is
1598 send verbatim to the pinentry which does the unescaping (but not
1601 plus_to_blank (desc);
1603 rc = agent_get_confirmation (ctrl, desc, NULL, NULL, 0);
1604 return leave_cmd (ctx, rc);
1609 static const char hlp_learn[] =
1610 "LEARN [--send] [--sendinfo] [--force]\n"
1612 "Learn something about the currently inserted smartcard. With\n"
1613 "--sendinfo information about the card is returned; with --send\n"
1614 "the available certificates are returned as D lines; with --force\n"
1615 "private key storage will be updated by the result.";
1617 cmd_learn (assuan_context_t ctx, char *line)
1619 ctrl_t ctrl = assuan_get_pointer (ctx);
1621 int send, sendinfo, force;
1623 send = has_option (line, "--send");
1624 sendinfo = send? 1 : has_option (line, "--sendinfo");
1625 force = has_option (line, "--force");
1627 if (ctrl->restricted)
1628 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
1630 err = agent_handle_learn (ctrl, send, sendinfo? ctx : NULL, force);
1631 return leave_cmd (ctx, err);
1636 static const char hlp_passwd[] =
1637 "PASSWD [--cache-nonce=<c>] [--passwd-nonce=<s>] [--preset]\n"
1638 " [--verify] <hexkeygrip>\n"
1640 "Change the passphrase/PIN for the key identified by keygrip in LINE. If\n"
1641 "--preset is used then the new passphrase will be added to the cache.\n"
1642 "If --verify is used the command asks for the passphrase and verifies\n"
1643 "that the passphrase valid.\n";
1645 cmd_passwd (assuan_context_t ctx, char *line)
1647 ctrl_t ctrl = assuan_get_pointer (ctx);
1650 char *cache_nonce = NULL;
1651 char *passwd_nonce = NULL;
1652 unsigned char grip[20];
1653 gcry_sexp_t s_skey = NULL;
1654 unsigned char *shadow_info = NULL;
1655 char *passphrase = NULL;
1657 int opt_preset, opt_verify;
1659 if (ctrl->restricted)
1660 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
1662 opt_preset = has_option (line, "--preset");
1663 cache_nonce = option_value (line, "--cache-nonce");
1664 opt_verify = has_option (line, "--verify");
1667 for (pend = cache_nonce; *pend && !spacep (pend); pend++)
1671 cache_nonce = xtrystrdup (cache_nonce);
1675 err = gpg_error_from_syserror ();
1680 passwd_nonce = option_value (line, "--passwd-nonce");
1683 for (pend = passwd_nonce; *pend && !spacep (pend); pend++)
1687 passwd_nonce = xtrystrdup (passwd_nonce);
1691 err = gpg_error_from_syserror ();
1696 line = skip_options (line);
1698 err = parse_keygrip (ctx, line, grip);
1703 err = agent_key_from_file (ctrl,
1704 opt_verify? NULL : cache_nonce,
1705 ctrl->server_local->keydesc,
1706 grip, &shadow_info, CACHE_MODE_IGNORE, NULL,
1707 &s_skey, &passphrase);
1710 else if (shadow_info)
1712 log_error ("changing a smartcard PIN is not yet supported\n");
1713 err = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1715 else if (opt_verify)
1721 char *newpass = NULL;
1724 newpass = agent_get_cache (passwd_nonce, CACHE_MODE_NONCE);
1725 err = agent_protect_and_store (ctrl, s_skey, &newpass);
1726 if (!err && passphrase)
1728 /* A passphrase existed on the old key and the change was
1729 successful. Return a nonce for that old passphrase to
1730 let the caller try to unprotect the other subkeys with
1735 gcry_create_nonce (buf, 12);
1736 cache_nonce = bin2hex (buf, 12, NULL);
1739 && !agent_put_cache (cache_nonce, CACHE_MODE_NONCE,
1740 passphrase, CACHE_TTL_NONCE))
1742 assuan_write_status (ctx, "CACHE_NONCE", cache_nonce);
1743 xfree (ctrl->server_local->last_cache_nonce);
1744 ctrl->server_local->last_cache_nonce = cache_nonce;
1749 /* If we have a new passphrase (which might be empty) we
1750 store it under a passwd nonce so that the caller may
1751 send that nonce again to use it for another key. */
1755 gcry_create_nonce (buf, 12);
1756 passwd_nonce = bin2hex (buf, 12, NULL);
1759 && !agent_put_cache (passwd_nonce, CACHE_MODE_NONCE,
1760 newpass, CACHE_TTL_NONCE))
1762 assuan_write_status (ctx, "PASSWD_NONCE", passwd_nonce);
1763 xfree (ctrl->server_local->last_passwd_nonce);
1764 ctrl->server_local->last_passwd_nonce = passwd_nonce;
1765 passwd_nonce = NULL;
1769 if (!err && opt_preset)
1772 bin2hex(grip, 20, hexgrip);
1773 err = agent_put_cache (hexgrip, CACHE_MODE_ANY, newpass,
1774 ctrl->cache_ttl_opt_preset);
1780 xfree (ctrl->server_local->keydesc);
1781 ctrl->server_local->keydesc = NULL;
1785 gcry_sexp_release (s_skey);
1786 xfree (shadow_info);
1787 xfree (cache_nonce);
1788 return leave_cmd (ctx, err);
1792 static const char hlp_preset_passphrase[] =
1793 "PRESET_PASSPHRASE [--inquire] <string_or_keygrip> <timeout> [<hexstring>]\n"
1795 "Set the cached passphrase/PIN for the key identified by the keygrip\n"
1796 "to passwd for the given time, where -1 means infinite and 0 means\n"
1797 "the default (currently only a timeout of -1 is allowed, which means\n"
1798 "to never expire it). If passwd is not provided, ask for it via the\n"
1799 "pinentry module unless --inquire is passed in which case the passphrase\n"
1800 "is retrieved from the client via a server inquire.\n";
1802 cmd_preset_passphrase (assuan_context_t ctx, char *line)
1804 ctrl_t ctrl = assuan_get_pointer (ctx);
1806 char *grip_clear = NULL;
1807 unsigned char *passphrase = NULL;
1812 if (ctrl->restricted)
1813 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
1815 if (!opt.allow_preset_passphrase)
1816 return set_error (GPG_ERR_NOT_SUPPORTED, "no --allow-preset-passphrase");
1818 opt_inquire = has_option (line, "--inquire");
1819 line = skip_options (line);
1821 while (*line && (*line != ' ' && *line != '\t'))
1824 return gpg_error (GPG_ERR_MISSING_VALUE);
1827 while (*line && (*line == ' ' || *line == '\t'))
1830 /* Currently, only infinite timeouts are allowed. */
1832 if (line[0] != '-' || line[1] != '1')
1833 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1836 while (!(*line != ' ' && *line != '\t'))
1839 /* Syntax check the hexstring. */
1841 rc = parse_hexstring (ctx, line, &len);
1846 /* If there is a passphrase, use it. Currently, a passphrase is
1852 rc = set_error (GPG_ERR_ASS_PARAMETER,
1853 "both --inquire and passphrase specified");
1857 /* Do in-place conversion. */
1859 if (!hex2str (passphrase, passphrase, strlen (passphrase)+1, NULL))
1860 rc = set_error (GPG_ERR_ASS_PARAMETER, "invalid hexstring");
1862 else if (opt_inquire)
1864 /* Note that the passphrase will be truncated at any null byte and the
1865 * limit is 480 characters. */
1866 size_t maxlen = 480;
1868 rc = print_assuan_status (ctx, "INQUIRE_MAXLEN", "%zu", maxlen);
1870 rc = assuan_inquire (ctx, "PASSPHRASE", &passphrase, &len, maxlen);
1873 rc = set_error (GPG_ERR_NOT_IMPLEMENTED, "passphrase is required");
1877 rc = agent_put_cache (grip_clear, CACHE_MODE_ANY, passphrase, ttl);
1883 return leave_cmd (ctx, rc);
1888 static const char hlp_scd[] =
1889 "SCD <commands to pass to the scdaemon>\n"
1891 "This is a general quote command to redirect everything to the\n"
1894 cmd_scd (assuan_context_t ctx, char *line)
1896 ctrl_t ctrl = assuan_get_pointer (ctx);
1899 if (ctrl->restricted)
1900 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
1902 rc = divert_generic_cmd (ctrl, line, ctx);
1909 static const char hlp_keywrap_key[] =
1910 "KEYWRAP_KEY [--clear] <mode>\n"
1912 "Return a key to wrap another key. For now the key is returned\n"
1913 "verbatim and and thus makes not much sense because an eavesdropper on\n"
1914 "the gpg-agent connection will see the key as well as the wrapped key.\n"
1915 "However, this function may either be equipped with a public key\n"
1916 "mechanism or not used at all if the key is a pre-shared key. In any\n"
1917 "case wrapping the import and export of keys is a requirement for\n"
1918 "certain cryptographic validations and thus useful. The key persists\n"
1919 "until a RESET command but may be cleared using the option --clear.\n"
1921 "Supported modes are:\n"
1922 " --import - Return a key to import a key into gpg-agent\n"
1923 " --export - Return a key to export a key from gpg-agent";
1925 cmd_keywrap_key (assuan_context_t ctx, char *line)
1927 ctrl_t ctrl = assuan_get_pointer (ctx);
1928 gpg_error_t err = 0;
1929 int clearopt = has_option (line, "--clear");
1931 if (ctrl->restricted)
1932 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
1934 assuan_begin_confidential (ctx);
1935 if (has_option (line, "--import"))
1937 xfree (ctrl->server_local->import_key);
1939 ctrl->server_local->import_key = NULL;
1940 else if (!(ctrl->server_local->import_key =
1941 gcry_random_bytes (KEYWRAP_KEYSIZE, GCRY_STRONG_RANDOM)))
1942 err = gpg_error_from_syserror ();
1944 err = assuan_send_data (ctx, ctrl->server_local->import_key,
1947 else if (has_option (line, "--export"))
1949 xfree (ctrl->server_local->export_key);
1951 ctrl->server_local->export_key = NULL;
1952 else if (!(ctrl->server_local->export_key =
1953 gcry_random_bytes (KEYWRAP_KEYSIZE, GCRY_STRONG_RANDOM)))
1954 err = gpg_error_from_syserror ();
1956 err = assuan_send_data (ctx, ctrl->server_local->export_key,
1960 err = set_error (GPG_ERR_ASS_PARAMETER, "unknown value for MODE");
1961 assuan_end_confidential (ctx);
1963 return leave_cmd (ctx, err);
1968 static const char hlp_import_key[] =
1969 "IMPORT_KEY [--unattended] [--force] [<cache_nonce>]\n"
1971 "Import a secret key into the key store. The key is expected to be\n"
1972 "encrypted using the current session's key wrapping key (cf. command\n"
1973 "KEYWRAP_KEY) using the AESWRAP-128 algorithm. This function takes\n"
1974 "no arguments but uses the inquiry \"KEYDATA\" to ask for the actual\n"
1975 "key data. The unwrapped key must be a canonical S-expression. The\n"
1976 "option --unattended tries to import the key as-is without any\n"
1977 "re-encryption. Existing key can be overwritten with --force.";
1979 cmd_import_key (assuan_context_t ctx, char *line)
1981 ctrl_t ctrl = assuan_get_pointer (ctx);
1985 unsigned char *wrappedkey = NULL;
1986 size_t wrappedkeylen;
1987 gcry_cipher_hd_t cipherhd = NULL;
1988 unsigned char *key = NULL;
1989 size_t keylen, realkeylen;
1990 char *passphrase = NULL;
1991 unsigned char *finalkey = NULL;
1993 unsigned char grip[20];
1994 gcry_sexp_t openpgp_sexp = NULL;
1995 char *cache_nonce = NULL;
1998 if (ctrl->restricted)
1999 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
2001 if (!ctrl->server_local->import_key)
2003 err = gpg_error (GPG_ERR_MISSING_KEY);
2007 opt_unattended = has_option (line, "--unattended");
2008 force = has_option (line, "--force");
2009 line = skip_options (line);
2012 for (p=line; *p && *p != ' ' && *p != '\t'; p++)
2016 cache_nonce = xtrystrdup (line);
2018 assuan_begin_confidential (ctx);
2019 err = assuan_inquire (ctx, "KEYDATA",
2020 &wrappedkey, &wrappedkeylen, MAXLEN_KEYDATA);
2021 assuan_end_confidential (ctx);
2024 if (wrappedkeylen < 24)
2026 err = gpg_error (GPG_ERR_INV_LENGTH);
2029 keylen = wrappedkeylen - 8;
2030 key = xtrymalloc_secure (keylen);
2033 err = gpg_error_from_syserror ();
2037 err = gcry_cipher_open (&cipherhd, GCRY_CIPHER_AES128,
2038 GCRY_CIPHER_MODE_AESWRAP, 0);
2041 err = gcry_cipher_setkey (cipherhd,
2042 ctrl->server_local->import_key, KEYWRAP_KEYSIZE);
2045 err = gcry_cipher_decrypt (cipherhd, key, keylen, wrappedkey, wrappedkeylen);
2048 gcry_cipher_close (cipherhd);
2053 realkeylen = gcry_sexp_canon_len (key, keylen, NULL, &err);
2055 goto leave; /* Invalid canonical encoded S-expression. */
2057 err = keygrip_from_canon_sexp (key, realkeylen, grip);
2060 /* This might be due to an unsupported S-expression format.
2061 Check whether this is openpgp-private-key and trigger that
2063 if (!gcry_sexp_sscan (&openpgp_sexp, NULL, key, realkeylen))
2068 tag = gcry_sexp_nth_data (openpgp_sexp, 0, &taglen);
2069 if (tag && taglen == 19 && !memcmp (tag, "openpgp-private-key", 19))
2073 gcry_sexp_release (openpgp_sexp);
2074 openpgp_sexp = NULL;
2078 goto leave; /* Note that ERR is still set. */
2084 /* In most cases the key is encrypted and thus the conversion
2085 function from the OpenPGP format to our internal format will
2086 ask for a passphrase. That passphrase will be returned and
2087 used to protect the key using the same code as for regular
2092 err = convert_from_openpgp (ctrl, openpgp_sexp, force, grip,
2093 ctrl->server_local->keydesc, cache_nonce,
2094 &key, opt_unattended? NULL : &passphrase);
2097 realkeylen = gcry_sexp_canon_len (key, 0, NULL, &err);
2099 goto leave; /* Invalid canonical encoded S-expression. */
2102 assert (!opt_unattended);
2106 gcry_create_nonce (buf, 12);
2107 cache_nonce = bin2hex (buf, 12, NULL);
2110 && !agent_put_cache (cache_nonce, CACHE_MODE_NONCE,
2111 passphrase, CACHE_TTL_NONCE))
2112 assuan_write_status (ctx, "CACHE_NONCE", cache_nonce);
2115 else if (opt_unattended)
2117 err = set_error (GPG_ERR_ASS_PARAMETER,
2118 "\"--unattended\" may only be used with OpenPGP keys");
2123 if (!force && !agent_key_available (grip))
2124 err = gpg_error (GPG_ERR_EEXIST);
2127 char *prompt = xtryasprintf
2128 (_("Please enter the passphrase to protect the "
2129 "imported object within the %s system."), GNUPG_NAME);
2131 err = gpg_error_from_syserror ();
2133 err = agent_ask_new_passphrase (ctrl, prompt, &passphrase);
2142 err = agent_protect (key, passphrase, &finalkey, &finalkeylen,
2143 ctrl->s2k_count, -1);
2145 err = agent_write_private_key (grip, finalkey, finalkeylen, force);
2148 err = agent_write_private_key (grip, key, realkeylen, force);
2151 gcry_sexp_release (openpgp_sexp);
2155 gcry_cipher_close (cipherhd);
2157 xfree (cache_nonce);
2158 xfree (ctrl->server_local->keydesc);
2159 ctrl->server_local->keydesc = NULL;
2160 return leave_cmd (ctx, err);
2165 static const char hlp_export_key[] =
2166 "EXPORT_KEY [--cache-nonce=<nonce>] [--openpgp] <hexstring_with_keygrip>\n"
2168 "Export a secret key from the key store. The key will be encrypted\n"
2169 "using the current session's key wrapping key (cf. command KEYWRAP_KEY)\n"
2170 "using the AESWRAP-128 algorithm. The caller needs to retrieve that key\n"
2171 "prior to using this command. The function takes the keygrip as argument.\n";
2173 cmd_export_key (assuan_context_t ctx, char *line)
2175 ctrl_t ctrl = assuan_get_pointer (ctx);
2177 unsigned char grip[20];
2178 gcry_sexp_t s_skey = NULL;
2179 unsigned char *key = NULL;
2181 gcry_cipher_hd_t cipherhd = NULL;
2182 unsigned char *wrappedkey = NULL;
2183 size_t wrappedkeylen;
2186 char *passphrase = NULL;
2187 unsigned char *shadow_info = NULL;
2191 if (ctrl->restricted)
2192 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
2194 openpgp = has_option (line, "--openpgp");
2195 cache_nonce = option_value (line, "--cache-nonce");
2198 for (pend = cache_nonce; *pend && !spacep (pend); pend++)
2202 cache_nonce = xtrystrdup (cache_nonce);
2206 err = gpg_error_from_syserror ();
2210 line = skip_options (line);
2212 if (!ctrl->server_local->export_key)
2214 err = set_error (GPG_ERR_MISSING_KEY, "did you run KEYWRAP_KEY ?");
2218 err = parse_keygrip (ctx, line, grip);
2222 if (agent_key_available (grip))
2224 err = gpg_error (GPG_ERR_NO_SECKEY);
2228 /* Get the key from the file. With the openpgp flag we also ask for
2229 the passphrase so that we can use it to re-encrypt it. */
2230 err = agent_key_from_file (ctrl, cache_nonce,
2231 ctrl->server_local->keydesc, grip,
2232 &shadow_info, CACHE_MODE_IGNORE, NULL, &s_skey,
2233 openpgp ? &passphrase : NULL);
2238 /* Key is on a smartcard. */
2239 err = gpg_error (GPG_ERR_UNUSABLE_SECKEY);
2245 /* The openpgp option changes the key format into the OpenPGP
2246 key transfer format. The result is already a padded
2247 canonical S-expression. */
2250 err = agent_ask_new_passphrase
2251 (ctrl, _("This key (or subkey) is not protected with a passphrase."
2252 " Please enter a new passphrase to export it."),
2257 err = convert_to_openpgp (ctrl, s_skey, passphrase, &key, &keylen);
2258 if (!err && passphrase)
2263 gcry_create_nonce (buf, 12);
2264 cache_nonce = bin2hex (buf, 12, NULL);
2267 && !agent_put_cache (cache_nonce, CACHE_MODE_NONCE,
2268 passphrase, CACHE_TTL_NONCE))
2270 assuan_write_status (ctx, "CACHE_NONCE", cache_nonce);
2271 xfree (ctrl->server_local->last_cache_nonce);
2272 ctrl->server_local->last_cache_nonce = cache_nonce;
2279 /* Convert into a canonical S-expression and wrap that. */
2280 err = make_canon_sexp_pad (s_skey, 1, &key, &keylen);
2284 gcry_sexp_release (s_skey);
2287 err = gcry_cipher_open (&cipherhd, GCRY_CIPHER_AES128,
2288 GCRY_CIPHER_MODE_AESWRAP, 0);
2291 err = gcry_cipher_setkey (cipherhd,
2292 ctrl->server_local->export_key, KEYWRAP_KEYSIZE);
2296 wrappedkeylen = keylen + 8;
2297 wrappedkey = xtrymalloc (wrappedkeylen);
2300 err = gpg_error_from_syserror ();
2304 err = gcry_cipher_encrypt (cipherhd, wrappedkey, wrappedkeylen, key, keylen);
2309 gcry_cipher_close (cipherhd);
2312 assuan_begin_confidential (ctx);
2313 err = assuan_send_data (ctx, wrappedkey, wrappedkeylen);
2314 assuan_end_confidential (ctx);
2318 xfree (cache_nonce);
2321 gcry_cipher_close (cipherhd);
2323 gcry_sexp_release (s_skey);
2324 xfree (ctrl->server_local->keydesc);
2325 ctrl->server_local->keydesc = NULL;
2326 xfree (shadow_info);
2328 return leave_cmd (ctx, err);
2333 static const char hlp_delete_key[] =
2334 "DELETE_KEY [--force] <hexstring_with_keygrip>\n"
2336 "Delete a secret key from the key store.\n"
2337 "Unless --force is used the agent asks the user for confirmation.\n";
2339 cmd_delete_key (assuan_context_t ctx, char *line)
2341 ctrl_t ctrl = assuan_get_pointer (ctx);
2344 unsigned char grip[20];
2346 if (ctrl->restricted)
2347 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
2349 force = has_option (line, "--force");
2350 line = skip_options (line);
2352 err = parse_keygrip (ctx, line, grip);
2356 err = agent_delete_key (ctrl, ctrl->server_local->keydesc, grip, force );
2361 xfree (ctrl->server_local->keydesc);
2362 ctrl->server_local->keydesc = NULL;
2364 return leave_cmd (ctx, err);
2369 static const char hlp_keytocard[] =
2370 "KEYTOCARD [--force] <hexstring_with_keygrip> <serialno> <id> <timestamp>\n"
2373 cmd_keytocard (assuan_context_t ctx, char *line)
2375 ctrl_t ctrl = assuan_get_pointer (ctx);
2377 gpg_error_t err = 0;
2378 unsigned char grip[20];
2379 gcry_sexp_t s_skey = NULL;
2380 unsigned char *keydata;
2381 size_t keydatalen, timestamplen;
2382 const char *serialno, *timestamp_str, *id;
2383 unsigned char *shadow_info = NULL;
2386 if (ctrl->restricted)
2387 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
2389 force = has_option (line, "--force");
2390 line = skip_options (line);
2392 err = parse_keygrip (ctx, line, grip);
2396 if (agent_key_available (grip))
2397 return gpg_error (GPG_ERR_NO_SECKEY);
2400 while (*line && (*line == ' ' || *line == '\t'))
2403 while (*line && (*line != ' ' && *line != '\t'))
2406 return gpg_error (GPG_ERR_MISSING_VALUE);
2409 while (*line && (*line == ' ' || *line == '\t'))
2412 while (*line && (*line != ' ' && *line != '\t'))
2415 return gpg_error (GPG_ERR_MISSING_VALUE);
2418 while (*line && (*line == ' ' || *line == '\t'))
2420 timestamp_str = line;
2421 while (*line && (*line != ' ' && *line != '\t'))
2425 timestamplen = line - timestamp_str;
2426 if (timestamplen != 15)
2427 return gpg_error (GPG_ERR_INV_VALUE);
2429 err = agent_key_from_file (ctrl, NULL, ctrl->server_local->keydesc, grip,
2430 &shadow_info, CACHE_MODE_IGNORE, NULL,
2434 xfree (shadow_info);
2439 /* Key is on a smartcard already. */
2440 xfree (shadow_info);
2441 gcry_sexp_release (s_skey);
2442 return gpg_error (GPG_ERR_UNUSABLE_SECKEY);
2445 keydatalen = gcry_sexp_sprint (s_skey, GCRYSEXP_FMT_CANON, NULL, 0);
2446 keydata = xtrymalloc_secure (keydatalen + 30);
2447 if (keydata == NULL)
2449 gcry_sexp_release (s_skey);
2450 return gpg_error_from_syserror ();
2453 gcry_sexp_sprint (s_skey, GCRYSEXP_FMT_CANON, keydata, keydatalen);
2454 gcry_sexp_release (s_skey);
2455 keydatalen--; /* Decrement for last '\0'. */
2456 /* Add timestamp "created-at" in the private key */
2457 timestamp = isotime2epoch (timestamp_str);
2458 snprintf (keydata+keydatalen-1, 30, "(10:created-at10:%010lu))", timestamp);
2459 keydatalen += 10 + 19 - 1;
2460 err = divert_writekey (ctrl, force, serialno, id, keydata, keydatalen);
2463 return leave_cmd (ctx, err);
2468 static const char hlp_getval[] =
2471 "Return the value for KEY from the special environment as created by\n"
2474 cmd_getval (assuan_context_t ctx, char *line)
2476 ctrl_t ctrl = assuan_get_pointer (ctx);
2480 struct putval_item_s *vl;
2482 if (ctrl->restricted)
2483 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
2485 for (p=line; *p == ' '; p++)
2488 p = strchr (key, ' ');
2492 for (; *p == ' '; p++)
2495 return set_error (GPG_ERR_ASS_PARAMETER, "too many arguments");
2498 return set_error (GPG_ERR_ASS_PARAMETER, "no key given");
2501 for (vl=putval_list; vl; vl = vl->next)
2502 if ( !strcmp (vl->d, key) )
2505 if (vl) /* Got an entry. */
2506 rc = assuan_send_data (ctx, vl->d+vl->off, vl->len);
2508 return gpg_error (GPG_ERR_NO_DATA);
2510 return leave_cmd (ctx, rc);
2514 static const char hlp_putval[] =
2515 "PUTVAL <key> [<percent_escaped_value>]\n"
2517 "The gpg-agent maintains a kind of environment which may be used to\n"
2518 "store key/value pairs in it, so that they can be retrieved later.\n"
2519 "This may be used by helper daemons to daemonize themself on\n"
2520 "invocation and register them with gpg-agent. Callers of the\n"
2521 "daemon's service may now first try connect to get the information\n"
2522 "for that service from gpg-agent through the GETVAL command and then\n"
2523 "try to connect to that daemon. Only if that fails they may start\n"
2524 "an own instance of the service daemon. \n"
2526 "KEY is an an arbitrary symbol with the same syntax rules as keys\n"
2527 "for shell environment variables. PERCENT_ESCAPED_VALUE is the\n"
2528 "corresponding value; they should be similar to the values of\n"
2529 "envronment variables but gpg-agent does not enforce any\n"
2530 "restrictions. If that value is not given any value under that KEY\n"
2531 "is removed from this special environment.";
2533 cmd_putval (assuan_context_t ctx, char *line)
2535 ctrl_t ctrl = assuan_get_pointer (ctx);
2539 size_t valuelen = 0;
2541 struct putval_item_s *vl, *vlprev;
2543 if (ctrl->restricted)
2544 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
2546 for (p=line; *p == ' '; p++)
2549 p = strchr (key, ' ');
2553 for (; *p == ' '; p++)
2558 p = strchr (value, ' ');
2561 valuelen = percent_plus_unescape_inplace (value, 0);
2565 return set_error (GPG_ERR_ASS_PARAMETER, "no key given");
2568 for (vl=putval_list,vlprev=NULL; vl; vlprev=vl, vl = vl->next)
2569 if ( !strcmp (vl->d, key) )
2572 if (vl) /* Delete old entry. */
2575 vlprev->next = vl->next;
2577 putval_list = vl->next;
2581 if (valuelen) /* Add entry. */
2583 vl = xtrymalloc (sizeof *vl + strlen (key) + valuelen);
2585 rc = gpg_error_from_syserror ();
2589 vl->off = strlen (key) + 1;
2590 strcpy (vl->d, key);
2591 memcpy (vl->d + vl->off, value, valuelen);
2592 vl->next = putval_list;
2597 return leave_cmd (ctx, rc);
2603 static const char hlp_updatestartuptty[] =
2604 "UPDATESTARTUPTTY\n"
2606 "Set startup TTY and X11 DISPLAY variables to the values of this\n"
2607 "session. This command is useful to pull future pinentries to\n"
2608 "another screen. It is only required because there is no way in the\n"
2609 "ssh-agent protocol to convey this information.";
2611 cmd_updatestartuptty (assuan_context_t ctx, char *line)
2613 static const char *names[] =
2614 { "GPG_TTY", "DISPLAY", "TERM", "XAUTHORITY", "PINENTRY_USER_DATA", NULL };
2615 ctrl_t ctrl = assuan_get_pointer (ctx);
2616 gpg_error_t err = 0;
2619 char *lc_ctype = NULL;
2620 char *lc_messages = NULL;
2624 if (ctrl->restricted)
2625 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
2627 se = session_env_new ();
2629 err = gpg_error_from_syserror ();
2631 for (idx=0; !err && names[idx]; idx++)
2633 const char *value = session_env_getenv (ctrl->session_env, names[idx]);
2635 err = session_env_setenv (se, names[idx], value);
2638 if (!err && ctrl->lc_ctype)
2639 if (!(lc_ctype = xtrystrdup (ctrl->lc_ctype)))
2640 err = gpg_error_from_syserror ();
2642 if (!err && ctrl->lc_messages)
2643 if (!(lc_messages = xtrystrdup (ctrl->lc_messages)))
2644 err = gpg_error_from_syserror ();
2648 session_env_release (se);
2650 xfree (lc_messages);
2654 session_env_release (opt.startup_env);
2655 opt.startup_env = se;
2656 xfree (opt.startup_lc_ctype);
2657 opt.startup_lc_ctype = lc_ctype;
2658 xfree (opt.startup_lc_messages);
2659 opt.startup_lc_messages = lc_messages;
2667 static const char hlp_killagent[] =
2672 cmd_killagent (assuan_context_t ctx, char *line)
2674 ctrl_t ctrl = assuan_get_pointer (ctx);
2678 if (ctrl->restricted)
2679 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
2681 ctrl->server_local->stopme = 1;
2682 assuan_set_flag (ctx, ASSUAN_FORCE_CLOSE, 1);
2687 static const char hlp_reloadagent[] =
2690 "This command is an alternative to SIGHUP\n"
2691 "to reload the configuration.";
2693 cmd_reloadagent (assuan_context_t ctx, char *line)
2695 ctrl_t ctrl = assuan_get_pointer (ctx);
2699 if (ctrl->restricted)
2700 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
2702 agent_sighup_action ();
2708 static const char hlp_getinfo[] =
2711 "Multipurpose function to return a variety of information.\n"
2712 "Supported values for WHAT are:\n"
2714 " version - Return the version of the program.\n"
2715 " pid - Return the process id of the server.\n"
2716 " socket_name - Return the name of the socket.\n"
2717 " ssh_socket_name - Return the name of the ssh socket.\n"
2718 " scd_running - Return OK if the SCdaemon is already running.\n"
2719 " s2k_count - Return the calibrated S2K count.\n"
2720 " std_env_names - List the names of the standard environment.\n"
2721 " std_session_env - List the standard session environment.\n"
2722 " std_startup_env - List the standard startup environment.\n"
2724 " - Returns OK if the command CMD implements the option OPT.\n"
2725 " restricted - Returns OK if the connection is in restricted mode.\n";
2727 cmd_getinfo (assuan_context_t ctx, char *line)
2729 ctrl_t ctrl = assuan_get_pointer (ctx);
2732 if (!strcmp (line, "version"))
2734 const char *s = VERSION;
2735 rc = assuan_send_data (ctx, s, strlen (s));
2737 else if (!strncmp (line, "cmd_has_option", 14)
2738 && (line[14] == ' ' || line[14] == '\t' || !line[14]))
2742 while (*line == ' ' || *line == '\t')
2745 rc = gpg_error (GPG_ERR_MISSING_VALUE);
2749 while (*line && (*line != ' ' && *line != '\t'))
2752 rc = gpg_error (GPG_ERR_MISSING_VALUE);
2756 while (*line == ' ' || *line == '\t')
2759 rc = gpg_error (GPG_ERR_MISSING_VALUE);
2763 if (!command_has_option (cmd, cmdopt))
2764 rc = gpg_error (GPG_ERR_GENERAL);
2769 else if (!strcmp (line, "s2k_count"))
2773 snprintf (numbuf, sizeof numbuf, "%lu", get_standard_s2k_count ());
2774 rc = assuan_send_data (ctx, numbuf, strlen (numbuf));
2776 else if (!strcmp (line, "restricted"))
2778 rc = ctrl->restricted? 0 : gpg_error (GPG_ERR_GENERAL);
2780 else if (ctrl->restricted)
2782 rc = gpg_error (GPG_ERR_FORBIDDEN);
2784 /* All sub-commands below are not allowed in restricted mode. */
2785 else if (!strcmp (line, "pid"))
2789 snprintf (numbuf, sizeof numbuf, "%lu", (unsigned long)getpid ());
2790 rc = assuan_send_data (ctx, numbuf, strlen (numbuf));
2792 else if (!strcmp (line, "socket_name"))
2794 const char *s = get_agent_socket_name ();
2797 rc = assuan_send_data (ctx, s, strlen (s));
2799 rc = gpg_error (GPG_ERR_NO_DATA);
2801 else if (!strcmp (line, "ssh_socket_name"))
2803 const char *s = get_agent_ssh_socket_name ();
2806 rc = assuan_send_data (ctx, s, strlen (s));
2808 rc = gpg_error (GPG_ERR_NO_DATA);
2810 else if (!strcmp (line, "scd_running"))
2812 rc = agent_scd_check_running ()? 0 : gpg_error (GPG_ERR_GENERAL);
2814 else if (!strcmp (line, "std_env_names"))
2820 while ((name = session_env_list_stdenvnames (&iterator, NULL)))
2822 rc = assuan_send_data (ctx, name, strlen (name)+1);
2824 rc = assuan_send_data (ctx, NULL, 0);
2829 else if (!strcmp (line, "std_session_env")
2830 || !strcmp (line, "std_startup_env"))
2833 const char *name, *value;
2837 while ((name = session_env_list_stdenvnames (&iterator, NULL)))
2839 value = session_env_getenv_or_default
2840 (line[5] == 't'? opt.startup_env:ctrl->session_env, name, NULL);
2843 string = xtryasprintf ("%s=%s", name, value);
2845 rc = gpg_error_from_syserror ();
2848 rc = assuan_send_data (ctx, string, strlen (string)+1);
2850 rc = assuan_send_data (ctx, NULL, 0);
2858 rc = set_error (GPG_ERR_ASS_PARAMETER, "unknown value for WHAT");
2864 /* This function is called by Libassuan to parse the OPTION command.
2865 It has been registered similar to the other Assuan commands. */
2867 option_handler (assuan_context_t ctx, const char *key, const char *value)
2869 ctrl_t ctrl = assuan_get_pointer (ctx);
2870 gpg_error_t err = 0;
2872 if (!strcmp (key, "agent-awareness"))
2874 /* The value is a version string telling us of which agent
2875 version the caller is aware of. */
2876 ctrl->server_local->allow_fully_canceled =
2877 gnupg_compare_version (value, "2.1.0");
2879 else if (ctrl->restricted)
2881 err = gpg_error (GPG_ERR_FORBIDDEN);
2883 /* All options below are not allowed in restricted mode. */
2884 else if (!strcmp (key, "putenv"))
2886 /* Change the session's environment to be used for the
2887 Pinentry. Valid values are:
2888 <NAME> Delete envvar NAME
2889 <KEY>= Set envvar NAME to the empty string
2890 <KEY>=<VALUE> Set envvar NAME to VALUE
2892 err = session_env_putenv (ctrl->session_env, value);
2894 else if (!strcmp (key, "display"))
2896 err = session_env_setenv (ctrl->session_env, "DISPLAY", value);
2898 else if (!strcmp (key, "ttyname"))
2901 err = session_env_setenv (ctrl->session_env, "GPG_TTY", value);
2903 else if (!strcmp (key, "ttytype"))
2906 err = session_env_setenv (ctrl->session_env, "TERM", value);
2908 else if (!strcmp (key, "lc-ctype"))
2911 xfree (ctrl->lc_ctype);
2912 ctrl->lc_ctype = xtrystrdup (value);
2913 if (!ctrl->lc_ctype)
2914 return out_of_core ();
2916 else if (!strcmp (key, "lc-messages"))
2918 if (ctrl->lc_messages)
2919 xfree (ctrl->lc_messages);
2920 ctrl->lc_messages = xtrystrdup (value);
2921 if (!ctrl->lc_messages)
2922 return out_of_core ();
2924 else if (!strcmp (key, "xauthority"))
2926 err = session_env_setenv (ctrl->session_env, "XAUTHORITY", value);
2928 else if (!strcmp (key, "pinentry-user-data"))
2930 err = session_env_setenv (ctrl->session_env, "PINENTRY_USER_DATA", value);
2932 else if (!strcmp (key, "use-cache-for-signing"))
2933 ctrl->server_local->use_cache_for_signing = *value? atoi (value) : 0;
2934 else if (!strcmp (key, "allow-pinentry-notify"))
2935 ctrl->server_local->allow_pinentry_notify = 1;
2936 else if (!strcmp (key, "pinentry-mode"))
2938 int tmp = parse_pinentry_mode (value);
2940 err = gpg_error (GPG_ERR_INV_VALUE);
2941 else if (tmp == PINENTRY_MODE_LOOPBACK && !opt.allow_loopback_pinentry)
2942 err = gpg_error (GPG_ERR_NOT_SUPPORTED);
2944 ctrl->pinentry_mode = tmp;
2946 else if (!strcmp (key, "cache-ttl-opt-preset"))
2948 ctrl->cache_ttl_opt_preset = *value? atoi (value) : 0;
2950 else if (!strcmp (key, "s2k-count"))
2952 ctrl->s2k_count = *value? strtoul(value, NULL, 10) : 0;
2953 if (ctrl->s2k_count && ctrl->s2k_count < 65536)
2955 ctrl->s2k_count = 0;
2959 err = gpg_error (GPG_ERR_UNKNOWN_OPTION);
2967 /* Called by libassuan after all commands. ERR is the error from the
2968 last assuan operation and not the one returned from the command. */
2970 post_cmd_notify (assuan_context_t ctx, gpg_error_t err)
2972 ctrl_t ctrl = assuan_get_pointer (ctx);
2976 /* Switch off any I/O monitor controlled logging pausing. */
2977 ctrl->server_local->pause_io_logging = 0;
2981 /* This function is called by libassuan for all I/O. We use it here
2982 to disable logging for the GETEVENTCOUNTER commands. This is so
2983 that the debug output won't get cluttered by this primitive
2986 io_monitor (assuan_context_t ctx, void *hook, int direction,
2987 const char *line, size_t linelen)
2989 ctrl_t ctrl = assuan_get_pointer (ctx);
2993 /* Note that we only check for the uppercase name. This allows to
2994 see the logging for debugging if using a non-upercase command
2996 if (ctx && direction == ASSUAN_IO_FROM_PEER
2998 && !strncmp (line, "GETEVENTCOUNTER", 15)
2999 && (linelen == 15 || spacep (line+15)))
3001 ctrl->server_local->pause_io_logging = 1;
3004 return ctrl->server_local->pause_io_logging? ASSUAN_IO_MONITOR_NOLOG : 0;
3008 /* Return true if the command CMD implements the option OPT. */
3010 command_has_option (const char *cmd, const char *cmdopt)
3012 if (!strcmp (cmd, "GET_PASSPHRASE"))
3014 if (!strcmp (cmdopt, "repeat"))
3022 /* Tell Libassuan about our commands. Also register the other Assuan
3025 register_commands (assuan_context_t ctx)
3029 assuan_handler_t handler;
3030 const char * const help;
3032 { "GETEVENTCOUNTER",cmd_geteventcounter, hlp_geteventcounter },
3033 { "ISTRUSTED", cmd_istrusted, hlp_istrusted },
3034 { "HAVEKEY", cmd_havekey, hlp_havekey },
3035 { "KEYINFO", cmd_keyinfo, hlp_keyinfo },
3036 { "SIGKEY", cmd_sigkey, hlp_sigkey },
3037 { "SETKEY", cmd_sigkey, hlp_sigkey },
3038 { "SETKEYDESC", cmd_setkeydesc,hlp_setkeydesc },
3039 { "SETHASH", cmd_sethash, hlp_sethash },
3040 { "PKSIGN", cmd_pksign, hlp_pksign },
3041 { "PKDECRYPT", cmd_pkdecrypt, hlp_pkdecrypt },
3042 { "GENKEY", cmd_genkey, hlp_genkey },
3043 { "READKEY", cmd_readkey, hlp_readkey },
3044 { "GET_PASSPHRASE", cmd_get_passphrase, hlp_get_passphrase },
3045 { "PRESET_PASSPHRASE", cmd_preset_passphrase, hlp_preset_passphrase },
3046 { "CLEAR_PASSPHRASE", cmd_clear_passphrase, hlp_clear_passphrase },
3047 { "GET_CONFIRMATION", cmd_get_confirmation, hlp_get_confirmation },
3048 { "LISTTRUSTED", cmd_listtrusted, hlp_listtrusted },
3049 { "MARKTRUSTED", cmd_marktrusted, hlp_martrusted },
3050 { "LEARN", cmd_learn, hlp_learn },
3051 { "PASSWD", cmd_passwd, hlp_passwd },
3054 { "SCD", cmd_scd, hlp_scd },
3055 { "KEYWRAP_KEY", cmd_keywrap_key, hlp_keywrap_key },
3056 { "IMPORT_KEY", cmd_import_key, hlp_import_key },
3057 { "EXPORT_KEY", cmd_export_key, hlp_export_key },
3058 { "DELETE_KEY", cmd_delete_key, hlp_delete_key },
3059 { "GETVAL", cmd_getval, hlp_getval },
3060 { "PUTVAL", cmd_putval, hlp_putval },
3061 { "UPDATESTARTUPTTY", cmd_updatestartuptty, hlp_updatestartuptty },
3062 { "KILLAGENT", cmd_killagent, hlp_killagent },
3063 { "RELOADAGENT", cmd_reloadagent,hlp_reloadagent },
3064 { "GETINFO", cmd_getinfo, hlp_getinfo },
3065 { "KEYTOCARD", cmd_keytocard, hlp_keytocard },
3070 for (i=0; table[i].name; i++)
3072 rc = assuan_register_command (ctx, table[i].name, table[i].handler,
3077 assuan_register_post_cmd_notify (ctx, post_cmd_notify);
3078 assuan_register_reset_notify (ctx, reset_notify);
3079 assuan_register_option_handler (ctx, option_handler);
3084 /* Startup the server. If LISTEN_FD and FD is given as -1, this is a
3085 simple piper server, otherwise it is a regular server. CTRL is the
3086 control structure for this connection; it has only the basic
3089 start_command_handler (ctrl_t ctrl, gnupg_fd_t listen_fd, gnupg_fd_t fd)
3092 assuan_context_t ctx = NULL;
3094 if (ctrl->restricted)
3096 if (agent_copy_startup_env (ctrl))
3100 rc = assuan_new (&ctx);
3103 log_error ("failed to allocate assuan context: %s\n", gpg_strerror (rc));
3107 if (listen_fd == GNUPG_INVALID_FD && fd == GNUPG_INVALID_FD)
3109 assuan_fd_t filedes[2];
3111 filedes[0] = assuan_fdopen (0);
3112 filedes[1] = assuan_fdopen (1);
3113 rc = assuan_init_pipe_server (ctx, filedes);
3115 else if (listen_fd != GNUPG_INVALID_FD)
3117 rc = assuan_init_socket_server (ctx, listen_fd, 0);
3118 /* FIXME: Need to call assuan_sock_set_nonce for Windows. But
3119 this branch is currently not used. */
3123 rc = assuan_init_socket_server (ctx, fd, ASSUAN_SOCKET_SERVER_ACCEPTED);
3127 log_error ("failed to initialize the server: %s\n",
3131 rc = register_commands (ctx);
3134 log_error ("failed to register commands with Assuan: %s\n",
3139 assuan_set_pointer (ctx, ctrl);
3140 ctrl->server_local = xcalloc (1, sizeof *ctrl->server_local);
3141 ctrl->server_local->assuan_ctx = ctx;
3142 ctrl->server_local->use_cache_for_signing = 1;
3143 ctrl->digest.raw_value = 0;
3145 assuan_set_io_monitor (ctx, io_monitor, NULL);
3146 agent_set_progress_cb (progress_cb, ctrl);
3150 rc = assuan_accept (ctx);
3151 if (gpg_err_code (rc) == GPG_ERR_EOF || rc == -1)
3157 log_info ("Assuan accept problem: %s\n", gpg_strerror (rc));
3161 rc = assuan_process (ctx);
3164 log_info ("Assuan processing failed: %s\n", gpg_strerror (rc));
3169 /* Reset the nonce caches. */
3170 clear_nonce_cache (ctrl);
3172 /* Reset the SCD if needed. */
3173 agent_reset_scd (ctrl);
3175 /* Reset the pinentry (in case of popup messages). */
3176 agent_reset_query (ctrl);
3179 assuan_release (ctx);
3180 xfree (ctrl->server_local->keydesc);
3181 xfree (ctrl->server_local->import_key);
3182 xfree (ctrl->server_local->export_key);
3183 if (ctrl->server_local->stopme)
3185 xfree (ctrl->server_local);
3186 ctrl->server_local = NULL;
3190 /* Helper for the pinentry loopback mode. It merely passes the
3191 parameters on to the client. */
3193 pinentry_loopback(ctrl_t ctrl, const char *keyword,
3194 unsigned char **buffer, size_t *size,
3198 assuan_context_t ctx = ctrl->server_local->assuan_ctx;
3200 rc = print_assuan_status (ctx, "INQUIRE_MAXLEN", "%zu", max_length);
3204 assuan_begin_confidential (ctx);
3205 rc = assuan_inquire (ctx, keyword, buffer, size, max_length);
3206 assuan_end_confidential (ctx);