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 <https://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 8192
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 unsigned int use_cache_for_signing : 1;
79 /* Flag to suppress I/O logging during a command. */
80 unsigned int pause_io_logging : 1;
82 /* Flag indicating that the connection is from ourselves. */
83 unsigned int connect_from_self : 1;
85 /* Helper flag for io_monitor to allow suppressing of our own
86 * greeting in some cases. See io_monitor for details. */
87 unsigned int greeting_seen : 1;
89 /* If this flag is set to true the agent will be terminated after
90 the end of the current session. */
91 unsigned int stopme : 1;
93 /* Flag indicating whether pinentry notifications shall be done. */
94 unsigned int allow_pinentry_notify : 1;
96 /* An allocated description for the next key operation. This is
97 used if a pinnetry needs to be popped up. */
100 /* Malloced KEK (Key-Encryption-Key) for the import_key command. */
103 /* Malloced KEK for the export_key command. */
106 /* Client is aware of the error code GPG_ERR_FULLY_CANCELED. */
107 int allow_fully_canceled;
109 /* Last CACHE_NONCE sent as status (malloced). */
110 char *last_cache_nonce;
112 /* Last PASSWD_NONCE sent as status (malloced). */
113 char *last_passwd_nonce;
117 /* An entry for the getval/putval commands. */
120 struct putval_item_s *next;
121 size_t off; /* Offset to the value into DATA. */
122 size_t len; /* Length of the value. */
123 char d[1]; /* Key | Nul | value. */
127 /* A list of key value pairs fpr the getval/putval commands. */
128 static struct putval_item_s *putval_list;
132 /* To help polling clients, we keep track of the number of certain
133 events. This structure keeps those counters. The counters are
134 integers and there should be no problem if they are overflowing as
135 callers need to check only whether a counter changed. The actual
136 values are not meaningful. */
139 /* Incremented if any of the other counters below changed. */
142 /* Incremented if a key is added or removed from the internal privat
146 /* Incremented if a change of the card readers stati has been
154 /* Local prototypes. */
155 static int command_has_option (const char *cmd, const char *cmdopt);
160 /* Release the memory buffer MB but first wipe out the used memory. */
162 clear_outbuf (membuf_t *mb)
167 p = get_membuf (mb, &n);
176 /* Write the content of memory buffer MB as assuan data to CTX and
177 wipe the buffer out afterwards. */
179 write_and_clear_outbuf (assuan_context_t ctx, membuf_t *mb)
185 p = get_membuf (mb, &n);
187 return out_of_core ();
188 ae = assuan_send_data (ctx, p, n);
195 /* Clear the nonces used to enable the passphrase cache for certain
196 multi-command command sequences. */
198 clear_nonce_cache (ctrl_t ctrl)
200 if (ctrl->server_local->last_cache_nonce)
202 agent_put_cache (ctrl->server_local->last_cache_nonce,
203 CACHE_MODE_NONCE, NULL, 0);
204 xfree (ctrl->server_local->last_cache_nonce);
205 ctrl->server_local->last_cache_nonce = NULL;
207 if (ctrl->server_local->last_passwd_nonce)
209 agent_put_cache (ctrl->server_local->last_passwd_nonce,
210 CACHE_MODE_NONCE, NULL, 0);
211 xfree (ctrl->server_local->last_passwd_nonce);
212 ctrl->server_local->last_passwd_nonce = NULL;
217 /* This function is called by Libassuan whenever the client sends a
218 reset. It has been registered similar to the other Assuan
221 reset_notify (assuan_context_t ctx, char *line)
223 ctrl_t ctrl = assuan_get_pointer (ctx);
227 memset (ctrl->keygrip, 0, 20);
228 ctrl->have_keygrip = 0;
229 ctrl->digest.valuelen = 0;
231 xfree (ctrl->server_local->keydesc);
232 ctrl->server_local->keydesc = NULL;
234 clear_nonce_cache (ctrl);
240 /* Replace all '+' by a blank in the string S. */
242 plus_to_blank (char *s)
252 /* Parse a hex string. Return an Assuan error code or 0 on success and the
253 length of the parsed string in LEN. */
255 parse_hexstring (assuan_context_t ctx, const char *string, size_t *len)
260 /* parse the hash value */
261 for (p=string, n=0; hexdigitp (p); p++, n++)
263 if (*p != ' ' && *p != '\t' && *p)
264 return set_error (GPG_ERR_ASS_PARAMETER, "invalid hexstring");
266 return set_error (GPG_ERR_ASS_PARAMETER, "odd number of digits");
272 /* Parse the keygrip in STRING into the provided buffer BUF. BUF must
273 provide space for 20 bytes. BUF is not changed if the function
276 parse_keygrip (assuan_context_t ctx, const char *string, unsigned char *buf)
281 rc = parse_hexstring (ctx, string, &n);
286 return set_error (GPG_ERR_ASS_PARAMETER, "invalid length of keygrip");
288 if (hex2bin (string, buf, 20) < 0)
289 return set_error (GPG_ERR_BUG, "hex2bin");
295 /* Write an Assuan status line. KEYWORD is the first item on the
296 status line. The following arguments are all separated by a space
297 in the output. The last argument must be a NULL. Linefeeds and
298 carriage returns characters (which are not allowed in an Assuan
299 status line) are silently quoted in C-style. */
301 agent_write_status (ctrl_t ctrl, const char *keyword, ...)
306 assuan_context_t ctx = ctrl->server_local->assuan_ctx;
310 va_start (arg_ptr, keyword);
314 while ( (text = va_arg (arg_ptr, const char *)) )
321 for ( ; *text && n < DIM (buf)-3; n++, text++)
328 else if (*text == '\r')
338 err = assuan_write_status (ctx, keyword, buf);
345 /* This function is similar to print_assuan_status but takes a CTRL
346 arg instead of an assuan context as first argument. */
348 agent_print_status (ctrl_t ctrl, const char *keyword, const char *format, ...)
352 assuan_context_t ctx = ctrl->server_local->assuan_ctx;
354 va_start (arg_ptr, format);
355 err = vprint_assuan_status (ctx, keyword, format, arg_ptr);
361 /* Helper to notify the client about a launched Pinentry. Because
362 that might disturb some older clients, this is only done if enabled
363 via an option. Returns an gpg error code. */
365 agent_inq_pinentry_launched (ctrl_t ctrl, unsigned long pid, const char *extra)
369 if (!ctrl || !ctrl->server_local
370 || !ctrl->server_local->allow_pinentry_notify)
372 snprintf (line, DIM(line), "PINENTRY_LAUNCHED %lu%s%s",
373 pid, extra?" ":"", extra? extra:"");
374 return assuan_inquire (ctrl->server_local->assuan_ctx, line, NULL, NULL, 0);
378 /* An agent progress callback for Libgcrypt. This has been registered
379 * to be called via the progress dispatcher mechanism from
382 progress_cb (ctrl_t ctrl, const char *what, int printchar,
383 int current, int total)
385 if (!ctrl || !ctrl->server_local || !ctrl->server_local->assuan_ctx)
387 else if (printchar == '\n' && what && !strcmp (what, "primegen"))
388 agent_print_status (ctrl, "PROGRESS", "%.20s X 100 100", what);
390 agent_print_status (ctrl, "PROGRESS", "%.20s %c %d %d",
391 what, printchar=='\n'?'X':printchar, current, total);
395 /* Helper to print a message while leaving a command. Note that this
396 * function does not call assuan_set_error; the caller may do this
397 * prior to calling us. */
399 leave_cmd (assuan_context_t ctx, gpg_error_t err)
403 const char *name = assuan_get_command_name (ctx);
407 /* Not all users of gpg-agent know about the fully canceled
408 error code; map it back if needed. */
409 if (gpg_err_code (err) == GPG_ERR_FULLY_CANCELED)
411 ctrl_t ctrl = assuan_get_pointer (ctx);
413 if (!ctrl->server_local->allow_fully_canceled)
414 err = gpg_err_make (gpg_err_source (err), GPG_ERR_CANCELED);
417 /* Most code from common/ does not know the error source, thus
419 if (gpg_err_source (err) == GPG_ERR_SOURCE_UNKNOWN)
420 err = gpg_err_make (GPG_ERR_SOURCE_DEFAULT, gpg_err_code (err));
422 if (gpg_err_source (err) == GPG_ERR_SOURCE_DEFAULT)
423 log_error ("command '%s' failed: %s\n", name,
426 log_error ("command '%s' failed: %s <%s>\n", name,
427 gpg_strerror (err), gpg_strsource (err));
434 static const char hlp_geteventcounter[] =
437 "Return a a status line named EVENTCOUNTER with the current values\n"
438 "of all event counters. The values are decimal numbers in the range\n"
439 "0 to UINT_MAX and wrapping around to 0. The actual values should\n"
440 "not be relied upon, they shall only be used to detect a change.\n"
442 "The currently defined counters are:\n"
444 "ANY - Incremented with any change of any of the other counters.\n"
445 "KEY - Incremented for added or removed private keys.\n"
446 "CARD - Incremented for changes of the card readers stati.";
448 cmd_geteventcounter (assuan_context_t ctx, char *line)
450 ctrl_t ctrl = assuan_get_pointer (ctx);
454 if (ctrl->restricted)
455 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
457 return agent_print_status (ctrl, "EVENTCOUNTER", "%u %u %u",
464 /* This function should be called once for all key removals or
465 additions. This function is assured not to do any context
468 bump_key_eventcounter (void)
475 /* This function should be called for all card reader status
476 changes. This function is assured not to do any context
479 bump_card_eventcounter (void)
488 static const char hlp_istrusted[] =
489 "ISTRUSTED <hexstring_with_fingerprint>\n"
491 "Return OK when we have an entry with this fingerprint in our\n"
494 cmd_istrusted (assuan_context_t ctx, char *line)
496 ctrl_t ctrl = assuan_get_pointer (ctx);
501 /* Parse the fingerprint value. */
502 for (p=line,n=0; hexdigitp (p); p++, n++)
504 if (*p || !(n == 40 || n == 32))
505 return set_error (GPG_ERR_ASS_PARAMETER, "invalid fingerprint");
509 strcpy (fpr, "00000000");
512 for (p=line; i < 40; p++, i++)
513 fpr[i] = *p >= 'a'? (*p & 0xdf): *p;
515 rc = agent_istrusted (ctrl, fpr, NULL);
516 if (!rc || gpg_err_code (rc) == GPG_ERR_NOT_TRUSTED)
518 else if (rc == -1 || gpg_err_code (rc) == GPG_ERR_EOF )
519 return gpg_error (GPG_ERR_NOT_TRUSTED);
521 return leave_cmd (ctx, rc);
525 static const char hlp_listtrusted[] =
528 "List all entries from the trustlist.";
530 cmd_listtrusted (assuan_context_t ctx, char *line)
532 ctrl_t ctrl = assuan_get_pointer (ctx);
537 if (ctrl->restricted)
538 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
540 rc = agent_listtrusted (ctx);
541 return leave_cmd (ctx, rc);
545 static const char hlp_martrusted[] =
546 "MARKTRUSTED <hexstring_with_fingerprint> <flag> <display_name>\n"
548 "Store a new key in into the trustlist.";
550 cmd_marktrusted (assuan_context_t ctx, char *line)
552 ctrl_t ctrl = assuan_get_pointer (ctx);
558 if (ctrl->restricted)
559 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
561 /* parse the fingerprint value */
562 for (p=line,n=0; hexdigitp (p); p++, n++)
564 if (!spacep (p) || !(n == 40 || n == 32))
565 return set_error (GPG_ERR_ASS_PARAMETER, "invalid fingerprint");
569 strcpy (fpr, "00000000");
572 for (p=line; i < 40; p++, i++)
573 fpr[i] = *p >= 'a'? (*p & 0xdf): *p;
579 if ( (flag != 'S' && flag != 'P') || !spacep (p) )
580 return set_error (GPG_ERR_ASS_PARAMETER, "invalid flag - must be P or S");
584 rc = agent_marktrusted (ctrl, p, fpr, flag);
585 return leave_cmd (ctx, rc);
591 static const char hlp_havekey[] =
592 "HAVEKEY <hexstrings_with_keygrips>\n"
594 "Return success if at least one of the secret keys with the given\n"
595 "keygrips is available.";
597 cmd_havekey (assuan_context_t ctx, char *line)
600 unsigned char buf[20];
604 err = parse_keygrip (ctx, line, buf);
608 if (!agent_key_available (buf))
609 return 0; /* Found. */
611 while (*line && *line != ' ' && *line != '\t')
613 while (*line == ' ' || *line == '\t')
618 /* No leave_cmd() here because errors are expected and would clutter
620 return gpg_error (GPG_ERR_NO_SECKEY);
624 static const char hlp_sigkey[] =
625 "SIGKEY <hexstring_with_keygrip>\n"
626 "SETKEY <hexstring_with_keygrip>\n"
628 "Set the key used for a sign or decrypt operation.";
630 cmd_sigkey (assuan_context_t ctx, char *line)
633 ctrl_t ctrl = assuan_get_pointer (ctx);
635 rc = parse_keygrip (ctx, line, ctrl->keygrip);
638 ctrl->have_keygrip = 1;
643 static const char hlp_setkeydesc[] =
644 "SETKEYDESC plus_percent_escaped_string\n"
646 "Set a description to be used for the next PKSIGN, PKDECRYPT, IMPORT_KEY\n"
647 "or EXPORT_KEY operation if this operation requires a passphrase. If\n"
648 "this command is not used a default text will be used. Note, that\n"
649 "this description implictly selects the label used for the entry\n"
650 "box; if the string contains the string PIN (which in general will\n"
651 "not be translated), \"PIN\" is used, otherwise the translation of\n"
652 "\"passphrase\" is used. The description string should not contain\n"
653 "blanks unless they are percent or '+' escaped.\n"
655 "The description is only valid for the next PKSIGN, PKDECRYPT,\n"
656 "IMPORT_KEY, EXPORT_KEY, or DELETE_KEY operation.";
658 cmd_setkeydesc (assuan_context_t ctx, char *line)
660 ctrl_t ctrl = assuan_get_pointer (ctx);
663 for (p=line; *p == ' '; p++)
666 p = strchr (desc, ' ');
668 *p = 0; /* We ignore any garbage; we might late use it for other args. */
671 return set_error (GPG_ERR_ASS_PARAMETER, "no description given");
673 /* Note, that we only need to replace the + characters and should
674 leave the other escaping in place because the escaped string is
675 send verbatim to the pinentry which does the unescaping (but not
677 plus_to_blank (desc);
679 xfree (ctrl->server_local->keydesc);
681 if (ctrl->restricted)
683 ctrl->server_local->keydesc = strconcat
684 ((ctrl->restricted == 2
685 ? _("Note: Request from the web browser.")
686 : _("Note: Request from a remote site.") ), "%0A%0A", desc, NULL);
689 ctrl->server_local->keydesc = xtrystrdup (desc);
690 if (!ctrl->server_local->keydesc)
691 return out_of_core ();
696 static const char hlp_sethash[] =
697 "SETHASH (--hash=<name>)|(<algonumber>) <hexstring>\n"
699 "The client can use this command to tell the server about the data\n"
700 "(which usually is a hash) to be signed.";
702 cmd_sethash (assuan_context_t ctx, char *line)
707 ctrl_t ctrl = assuan_get_pointer (ctx);
712 /* Parse the alternative hash options which may be used instead of
714 if (has_option_name (line, "--hash"))
716 if (has_option (line, "--hash=sha1"))
718 else if (has_option (line, "--hash=sha224"))
719 algo = GCRY_MD_SHA224;
720 else if (has_option (line, "--hash=sha256"))
721 algo = GCRY_MD_SHA256;
722 else if (has_option (line, "--hash=sha384"))
723 algo = GCRY_MD_SHA384;
724 else if (has_option (line, "--hash=sha512"))
725 algo = GCRY_MD_SHA512;
726 else if (has_option (line, "--hash=rmd160"))
727 algo = GCRY_MD_RMD160;
728 else if (has_option (line, "--hash=md5"))
730 else if (has_option (line, "--hash=tls-md5sha1"))
731 algo = MD_USER_TLS_MD5SHA1;
733 return set_error (GPG_ERR_ASS_PARAMETER, "invalid hash algorithm");
738 line = skip_options (line);
742 /* No hash option has been given: require an algo number instead */
743 algo = (int)strtoul (line, &endp, 10);
744 for (line = endp; *line == ' ' || *line == '\t'; line++)
746 if (!algo || gcry_md_test_algo (algo))
747 return set_error (GPG_ERR_UNSUPPORTED_ALGORITHM, NULL);
749 ctrl->digest.algo = algo;
750 ctrl->digest.raw_value = 0;
752 /* Parse the hash value. */
754 rc = parse_hexstring (ctx, line, &n);
758 if (algo == MD_USER_TLS_MD5SHA1 && n == 36)
760 else if (n != 16 && n != 20 && n != 24
761 && n != 28 && n != 32 && n != 48 && n != 64)
762 return set_error (GPG_ERR_ASS_PARAMETER, "unsupported length of hash");
764 if (n > MAX_DIGEST_LEN)
765 return set_error (GPG_ERR_ASS_PARAMETER, "hash value to long");
767 buf = ctrl->digest.value;
768 ctrl->digest.valuelen = n;
769 for (p=line, n=0; n < ctrl->digest.valuelen; p += 2, n++)
771 for (; n < ctrl->digest.valuelen; n++)
777 static const char hlp_pksign[] =
778 "PKSIGN [<options>] [<cache_nonce>]\n"
780 "Perform the actual sign operation. Neither input nor output are\n"
781 "sensitive to eavesdropping.";
783 cmd_pksign (assuan_context_t ctx, char *line)
786 cache_mode_t cache_mode = CACHE_MODE_NORMAL;
787 ctrl_t ctrl = assuan_get_pointer (ctx);
789 char *cache_nonce = NULL;
792 line = skip_options (line);
795 for (p=line; *p && *p != ' ' && *p != '\t'; p++)
799 cache_nonce = xtrystrdup (line);
801 if (opt.ignore_cache_for_signing)
802 cache_mode = CACHE_MODE_IGNORE;
803 else if (!ctrl->server_local->use_cache_for_signing)
804 cache_mode = CACHE_MODE_IGNORE;
806 init_membuf (&outbuf, 512);
808 rc = agent_pksign (ctrl, cache_nonce, ctrl->server_local->keydesc,
809 &outbuf, cache_mode);
811 clear_outbuf (&outbuf);
813 rc = write_and_clear_outbuf (ctx, &outbuf);
816 xfree (ctrl->server_local->keydesc);
817 ctrl->server_local->keydesc = NULL;
818 return leave_cmd (ctx, rc);
822 static const char hlp_pkdecrypt[] =
823 "PKDECRYPT [<options>]\n"
825 "Perform the actual decrypt operation. Input is not\n"
826 "sensitive to eavesdropping.";
828 cmd_pkdecrypt (assuan_context_t ctx, char *line)
831 ctrl_t ctrl = assuan_get_pointer (ctx);
832 unsigned char *value;
839 /* First inquire the data to decrypt */
840 rc = print_assuan_status (ctx, "INQUIRE_MAXLEN", "%u", MAXLEN_CIPHERTEXT);
842 rc = assuan_inquire (ctx, "CIPHERTEXT",
843 &value, &valuelen, MAXLEN_CIPHERTEXT);
847 init_membuf (&outbuf, 512);
849 rc = agent_pkdecrypt (ctrl, ctrl->server_local->keydesc,
850 value, valuelen, &outbuf, &padding);
853 clear_outbuf (&outbuf);
857 rc = print_assuan_status (ctx, "PADDING", "%d", padding);
861 rc = write_and_clear_outbuf (ctx, &outbuf);
863 xfree (ctrl->server_local->keydesc);
864 ctrl->server_local->keydesc = NULL;
865 return leave_cmd (ctx, rc);
869 static const char hlp_genkey[] =
870 "GENKEY [--no-protection] [--preset] [--inq-passwd]\n"
871 " [--passwd-nonce=<s>] [<cache_nonce>]\n"
873 "Generate a new key, store the secret part and return the public\n"
874 "part. Here is an example transaction:\n"
877 " S: INQUIRE KEYPARAM\n"
878 " C: D (genkey (rsa (nbits 2048)))\n"
880 " S: D (public-key\n"
881 " S: D (rsa (n 326487324683264) (e 10001)))\n"
882 " S: OK key created\n"
884 "When the --preset option is used the passphrase for the generated\n"
885 "key will be added to the cache. When --inq-passwd is used an inquire\n"
886 "with the keyword NEWPASSWD is used to request the passphrase for the\n"
887 "new key. When a --passwd-nonce is used, the corresponding cached\n"
888 "passphrase is used to protect the new key.";
890 cmd_genkey (assuan_context_t ctx, char *line)
892 ctrl_t ctrl = assuan_get_pointer (ctx);
895 unsigned char *value;
897 unsigned char *newpasswd = NULL;
899 char *cache_nonce = NULL;
900 char *passwd_nonce = NULL;
907 if (ctrl->restricted)
908 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
910 no_protection = has_option (line, "--no-protection");
911 opt_preset = has_option (line, "--preset");
912 opt_inq_passwd = has_option (line, "--inq-passwd");
913 passwd_nonce = option_value (line, "--passwd-nonce");
916 for (pend = passwd_nonce; *pend && !spacep (pend); pend++)
920 passwd_nonce = xtrystrdup (passwd_nonce);
924 rc = gpg_error_from_syserror ();
928 line = skip_options (line);
931 for (p=line; *p && *p != ' ' && *p != '\t'; p++)
935 cache_nonce = xtrystrdup (line);
937 /* First inquire the parameters */
938 rc = print_assuan_status (ctx, "INQUIRE_MAXLEN", "%u", MAXLEN_KEYPARAM);
940 rc = assuan_inquire (ctx, "KEYPARAM", &value, &valuelen, MAXLEN_KEYPARAM);
944 init_membuf (&outbuf, 512);
946 /* If requested, ask for the password to be used for the key. If
947 this is not used the regular Pinentry mechanism is used. */
948 if (opt_inq_passwd && !no_protection)
950 /* (N is used as a dummy) */
951 assuan_begin_confidential (ctx);
952 rc = assuan_inquire (ctx, "NEWPASSWD", &newpasswd, &n, 256);
953 assuan_end_confidential (ctx);
958 /* Empty password given - switch to no-protection mode. */
965 else if (passwd_nonce)
966 newpasswd = agent_get_cache (passwd_nonce, CACHE_MODE_NONCE);
968 rc = agent_genkey (ctrl, cache_nonce, (char*)value, valuelen, no_protection,
969 newpasswd, opt_preset, &outbuf);
974 /* Assuan_inquire does not allow us to read into secure memory
975 thus we need to wipe it ourself. */
976 wipememory (newpasswd, strlen (newpasswd));
981 clear_outbuf (&outbuf);
983 rc = write_and_clear_outbuf (ctx, &outbuf);
985 xfree (passwd_nonce);
986 return leave_cmd (ctx, rc);
992 static const char hlp_readkey[] =
993 "READKEY <hexstring_with_keygrip>\n"
996 "Return the public key for the given keygrip or keyid.\n"
997 "With --card, private key file with card information will be created.";
999 cmd_readkey (assuan_context_t ctx, char *line)
1001 ctrl_t ctrl = assuan_get_pointer (ctx);
1003 unsigned char grip[20];
1004 gcry_sexp_t s_pkey = NULL;
1005 unsigned char *pkbuf = NULL;
1006 char *serialno = NULL;
1008 const char *opt_card;
1010 if (ctrl->restricted)
1011 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
1013 opt_card = has_option_name (line, "--card");
1014 line = skip_options (line);
1018 const char *keyid = opt_card;
1020 rc = agent_card_getattr (ctrl, "SERIALNO", &serialno);
1023 log_error (_("error getting serial number of card: %s\n"),
1028 rc = agent_card_readkey (ctrl, keyid, &pkbuf);
1031 pkbuflen = gcry_sexp_canon_len (pkbuf, 0, NULL, NULL);
1032 rc = gcry_sexp_sscan (&s_pkey, NULL, (char*)pkbuf, pkbuflen);
1036 if (!gcry_pk_get_keygrip (s_pkey, grip))
1038 rc = gcry_pk_testkey (s_pkey);
1040 rc = gpg_error (GPG_ERR_INTERNAL);
1045 rc = agent_write_shadow_key (grip, serialno, keyid, pkbuf, 0);
1049 rc = assuan_send_data (ctx, pkbuf, pkbuflen);
1053 rc = parse_keygrip (ctx, line, grip);
1057 rc = agent_public_key_from_file (ctrl, grip, &s_pkey);
1060 pkbuflen = gcry_sexp_sprint (s_pkey, GCRYSEXP_FMT_CANON, NULL, 0);
1061 log_assert (pkbuflen);
1062 pkbuf = xtrymalloc (pkbuflen);
1064 rc = gpg_error_from_syserror ();
1067 gcry_sexp_sprint (s_pkey, GCRYSEXP_FMT_CANON, pkbuf, pkbuflen);
1068 rc = assuan_send_data (ctx, pkbuf, pkbuflen);
1076 gcry_sexp_release (s_pkey);
1077 return leave_cmd (ctx, rc);
1082 static const char hlp_keyinfo[] =
1083 "KEYINFO [--[ssh-]list] [--data] [--ssh-fpr] [--with-ssh] <keygrip>\n"
1085 "Return information about the key specified by the KEYGRIP. If the\n"
1086 "key is not available GPG_ERR_NOT_FOUND is returned. If the option\n"
1087 "--list is given the keygrip is ignored and information about all\n"
1088 "available keys are returned. If --ssh-list is given information\n"
1089 "about all keys listed in the sshcontrol are returned. With --with-ssh\n"
1090 "information from sshcontrol is always added to the info. Unless --data\n"
1091 "is given, the information is returned as a status line using the format:\n"
1093 " KEYINFO <keygrip> <type> <serialno> <idstr> <cached> <protection> <fpr>\n"
1095 "KEYGRIP is the keygrip.\n"
1097 "TYPE is describes the type of the key:\n"
1098 " 'D' - Regular key stored on disk,\n"
1099 " 'T' - Key is stored on a smartcard (token),\n"
1100 " 'X' - Unknown type,\n"
1101 " '-' - Key is missing.\n"
1103 "SERIALNO is an ASCII string with the serial number of the\n"
1104 " smartcard. If the serial number is not known a single\n"
1105 " dash '-' is used instead.\n"
1107 "IDSTR is the IDSTR used to distinguish keys on a smartcard. If it\n"
1108 " is not known a dash is used instead.\n"
1110 "CACHED is 1 if the passphrase for the key was found in the key cache.\n"
1111 " If not, a '-' is used instead.\n"
1113 "PROTECTION describes the key protection type:\n"
1114 " 'P' - The key is protected with a passphrase,\n"
1115 " 'C' - The key is not protected,\n"
1116 " '-' - Unknown protection.\n"
1118 "FPR returns the formatted ssh-style fingerprint of the key. It is only\n"
1119 " printed if the option --ssh-fpr has been used. It defaults to '-'.\n"
1121 "TTL is the TTL in seconds for that key or '-' if n/a.\n"
1123 "FLAGS is a word consisting of one-letter flags:\n"
1124 " 'D' - The key has been disabled,\n"
1125 " 'S' - The key is listed in sshcontrol (requires --with-ssh),\n"
1126 " 'c' - Use of the key needs to be confirmed,\n"
1127 " '-' - No flags given.\n"
1129 "More information may be added in the future.";
1131 do_one_keyinfo (ctrl_t ctrl, const unsigned char *grip, assuan_context_t ctx,
1132 int data, int with_ssh_fpr, int in_ssh,
1133 int ttl, int disabled, int confirm)
1139 unsigned char *shadow_info = NULL;
1140 char *serialno = NULL;
1142 const char *keytypestr;
1144 const char *protectionstr;
1146 int missing_key = 0;
1150 err = agent_key_info_from_file (ctrl, grip, &keytype, &shadow_info);
1153 if (in_ssh && gpg_err_code (err) == GPG_ERR_NOT_FOUND)
1159 /* Reformat the grip so that we use uppercase as good style. */
1160 bin2hex (grip, 20, hexgrip);
1163 snprintf (ttlbuf, sizeof ttlbuf, "%d", ttl);
1165 strcpy (ttlbuf, "-");
1169 strcat (flagsbuf, "D");
1171 strcat (flagsbuf, "S");
1173 strcat (flagsbuf, "c");
1175 strcpy (flagsbuf, "-");
1180 protectionstr = "-"; keytypestr = "-";
1186 case PRIVATE_KEY_CLEAR:
1187 case PRIVATE_KEY_OPENPGP_NONE:
1188 protectionstr = "C"; keytypestr = "D";
1190 case PRIVATE_KEY_PROTECTED: protectionstr = "P"; keytypestr = "D";
1192 case PRIVATE_KEY_SHADOWED: protectionstr = "-"; keytypestr = "T";
1194 default: protectionstr = "-"; keytypestr = "X";
1199 /* Compute the ssh fingerprint if requested. */
1204 if (!agent_raw_key_from_file (ctrl, grip, &key))
1206 ssh_get_fingerprint_string (key, &fpr);
1207 gcry_sexp_release (key);
1211 /* Here we have a little race by doing the cache check separately
1212 from the retrieval function. Given that the cache flag is only a
1213 hint, it should not really matter. */
1214 pw = agent_get_cache (hexgrip, CACHE_MODE_NORMAL);
1215 cached = pw ? "1" : "-";
1220 err = parse_shadow_info (shadow_info, &serialno, &idstr, NULL);
1226 err = agent_write_status (ctrl, "KEYINFO",
1229 serialno? serialno : "-",
1241 string = xtryasprintf ("%s %s %s %s %s %s %s %s %s\n",
1242 hexgrip, keytypestr,
1243 serialno? serialno : "-",
1244 idstr? idstr : "-", cached, protectionstr,
1249 err = gpg_error_from_syserror ();
1251 err = assuan_send_data (ctx, string, strlen(string));
1257 xfree (shadow_info);
1264 /* Entry int for the command KEYINFO. This function handles the
1265 command option processing. For details see hlp_keyinfo above. */
1267 cmd_keyinfo (assuan_context_t ctx, char *line)
1269 ctrl_t ctrl = assuan_get_pointer (ctx);
1271 unsigned char grip[20];
1274 int opt_data, opt_ssh_fpr, opt_with_ssh;
1275 ssh_control_file_t cf = NULL;
1277 int disabled, ttl, confirm, is_ssh;
1279 if (ctrl->restricted)
1280 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
1282 if (has_option (line, "--ssh-list"))
1285 list_mode = has_option (line, "--list");
1286 opt_data = has_option (line, "--data");
1287 opt_ssh_fpr = has_option (line, "--ssh-fpr");
1288 opt_with_ssh = has_option (line, "--with-ssh");
1289 line = skip_options (line);
1291 if (opt_with_ssh || list_mode == 2)
1292 cf = ssh_open_control_file ();
1298 while (!ssh_read_control_file (cf, hexgrip,
1299 &disabled, &ttl, &confirm))
1301 if (hex2bin (hexgrip, grip, 20) < 0 )
1302 continue; /* Bad hex string. */
1303 err = do_one_keyinfo (ctrl, grip, ctx, opt_data, opt_ssh_fpr, 1,
1304 ttl, disabled, confirm);
1314 struct dirent *dir_entry;
1316 dirname = make_filename_try (gnupg_homedir (),
1317 GNUPG_PRIVATE_KEYS_DIR, NULL);
1320 err = gpg_error_from_syserror ();
1323 dir = opendir (dirname);
1326 err = gpg_error_from_syserror ();
1332 while ( (dir_entry = readdir (dir)) )
1334 if (strlen (dir_entry->d_name) != 44
1335 || strcmp (dir_entry->d_name + 40, ".key"))
1337 strncpy (hexgrip, dir_entry->d_name, 40);
1340 if ( hex2bin (hexgrip, grip, 20) < 0 )
1341 continue; /* Bad hex string. */
1343 disabled = ttl = confirm = is_ssh = 0;
1346 err = ssh_search_control_file (cf, hexgrip,
1347 &disabled, &ttl, &confirm);
1350 else if (gpg_err_code (err) != GPG_ERR_NOT_FOUND)
1354 err = do_one_keyinfo (ctrl, grip, ctx, opt_data, opt_ssh_fpr, is_ssh,
1355 ttl, disabled, confirm);
1363 err = parse_keygrip (ctx, line, grip);
1366 disabled = ttl = confirm = is_ssh = 0;
1369 err = ssh_search_control_file (cf, line,
1370 &disabled, &ttl, &confirm);
1373 else if (gpg_err_code (err) != GPG_ERR_NOT_FOUND)
1377 err = do_one_keyinfo (ctrl, grip, ctx, opt_data, opt_ssh_fpr, is_ssh,
1378 ttl, disabled, confirm);
1382 ssh_close_control_file (cf);
1385 if (err && gpg_err_code (err) != GPG_ERR_NOT_FOUND)
1386 leave_cmd (ctx, err);
1392 /* Helper for cmd_get_passphrase. */
1394 send_back_passphrase (assuan_context_t ctx, int via_data, const char *pw)
1399 assuan_begin_confidential (ctx);
1402 rc = assuan_send_data (ctx, pw, n);
1405 char *p = xtrymalloc_secure (n*2+1);
1407 rc = gpg_error_from_syserror ();
1411 rc = assuan_set_okay_line (ctx, p);
1419 static const char hlp_get_passphrase[] =
1420 "GET_PASSPHRASE [--data] [--check] [--no-ask] [--repeat[=N]]\n"
1421 " [--qualitybar] <cache_id>\n"
1422 " [<error_message> <prompt> <description>]\n"
1424 "This function is usually used to ask for a passphrase to be used\n"
1425 "for conventional encryption, but may also be used by programs which\n"
1426 "need specal handling of passphrases. This command uses a syntax\n"
1427 "which helps clients to use the agent with minimum effort. The\n"
1428 "agent either returns with an error or with a OK followed by the hex\n"
1429 "encoded passphrase. Note that the length of the strings is\n"
1430 "implicitly limited by the maximum length of a command.\n"
1432 "If the option \"--data\" is used the passphrase is returned by usual\n"
1433 "data lines and not on the okay line.\n"
1435 "If the option \"--check\" is used the passphrase constraints checks as\n"
1436 "implemented by gpg-agent are applied. A check is not done if the\n"
1437 "passphrase has been found in the cache.\n"
1439 "If the option \"--no-ask\" is used and the passphrase is not in the\n"
1440 "cache the user will not be asked to enter a passphrase but the error\n"
1441 "code GPG_ERR_NO_DATA is returned. \n"
1443 "If the option \"--qualitybar\" is used a visual indication of the\n"
1444 "entered passphrase quality is shown. (Unless no minimum passphrase\n"
1445 "length has been configured.)";
1447 cmd_get_passphrase (assuan_context_t ctx, char *line)
1449 ctrl_t ctrl = assuan_get_pointer (ctx);
1453 char *cacheid = NULL, *desc = NULL, *prompt = NULL, *errtext = NULL;
1454 const char *desc2 = _("Please re-enter this passphrase");
1456 int opt_data, opt_check, opt_no_ask, opt_qualbar;
1458 char *entry_errtext = NULL;
1460 if (ctrl->restricted)
1461 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
1463 opt_data = has_option (line, "--data");
1464 opt_check = has_option (line, "--check");
1465 opt_no_ask = has_option (line, "--no-ask");
1466 if (has_option_name (line, "--repeat"))
1468 p = option_value (line, "--repeat");
1470 opt_repeat = atoi (p);
1474 opt_qualbar = has_option (line, "--qualitybar");
1475 line = skip_options (line);
1478 p = strchr (cacheid, ' ');
1485 p = strchr (errtext, ' ');
1492 p = strchr (prompt, ' ');
1499 p = strchr (desc, ' ');
1501 *p = 0; /* Ignore trailing garbage. */
1505 if (!*cacheid || strlen (cacheid) > 50)
1506 return set_error (GPG_ERR_ASS_PARAMETER, "invalid length of cacheID");
1508 return set_error (GPG_ERR_ASS_PARAMETER, "no description given");
1510 if (!strcmp (cacheid, "X"))
1512 if (!strcmp (errtext, "X"))
1514 if (!strcmp (prompt, "X"))
1516 if (!strcmp (desc, "X"))
1519 pw = cacheid ? agent_get_cache (cacheid, CACHE_MODE_USER) : NULL;
1522 rc = send_back_passphrase (ctx, opt_data, pw);
1525 else if (opt_no_ask)
1526 rc = gpg_error (GPG_ERR_NO_DATA);
1529 /* Note, that we only need to replace the + characters and
1530 should leave the other escaping in place because the escaped
1531 string is send verbatim to the pinentry which does the
1532 unescaping (but not the + replacing) */
1534 plus_to_blank (errtext);
1536 plus_to_blank (prompt);
1538 plus_to_blank (desc);
1541 rc = agent_get_passphrase (ctrl, &response, desc, prompt,
1542 entry_errtext? entry_errtext:errtext,
1543 opt_qualbar, cacheid, CACHE_MODE_USER);
1544 xfree (entry_errtext);
1545 entry_errtext = NULL;
1551 && check_passphrase_constraints (ctrl, response, &entry_errtext))
1556 for (i = 0; i < opt_repeat; i++)
1560 if (ctrl->pinentry_mode == PINENTRY_MODE_LOOPBACK)
1563 rc = agent_get_passphrase (ctrl, &response2, desc2, prompt,
1565 cacheid, CACHE_MODE_USER);
1568 if (strcmp (response2, response))
1572 entry_errtext = try_percent_escape
1573 (_("does not match - try again"), NULL);
1576 rc = gpg_error_from_syserror ();
1586 agent_put_cache (cacheid, CACHE_MODE_USER, response, 0);
1587 rc = send_back_passphrase (ctx, opt_data, response);
1593 return leave_cmd (ctx, rc);
1597 static const char hlp_clear_passphrase[] =
1598 "CLEAR_PASSPHRASE [--mode=normal] <cache_id>\n"
1600 "may be used to invalidate the cache entry for a passphrase. The\n"
1601 "function returns with OK even when there is no cached passphrase.\n"
1602 "The --mode=normal option is used to clear an entry for a cacheid\n"
1603 "added by the agent.\n";
1605 cmd_clear_passphrase (assuan_context_t ctx, char *line)
1607 ctrl_t ctrl = assuan_get_pointer (ctx);
1608 char *cacheid = NULL;
1612 if (ctrl->restricted)
1613 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
1615 opt_normal = has_option (line, "--mode=normal");
1616 line = skip_options (line);
1618 /* parse the stuff */
1619 for (p=line; *p == ' '; p++)
1622 p = strchr (cacheid, ' ');
1624 *p = 0; /* ignore garbage */
1625 if (!*cacheid || strlen (cacheid) > 50)
1626 return set_error (GPG_ERR_ASS_PARAMETER, "invalid length of cacheID");
1628 agent_put_cache (cacheid, opt_normal ? CACHE_MODE_NORMAL : CACHE_MODE_USER,
1631 agent_clear_passphrase (ctrl, cacheid,
1632 opt_normal ? CACHE_MODE_NORMAL : CACHE_MODE_USER);
1638 static const char hlp_get_confirmation[] =
1639 "GET_CONFIRMATION <description>\n"
1641 "This command may be used to ask for a simple confirmation.\n"
1642 "DESCRIPTION is displayed along with a Okay and Cancel button. This\n"
1643 "command uses a syntax which helps clients to use the agent with\n"
1644 "minimum effort. The agent either returns with an error or with a\n"
1645 "OK. Note, that the length of DESCRIPTION is implicitly limited by\n"
1646 "the maximum length of a command. DESCRIPTION should not contain\n"
1647 "any spaces, those must be encoded either percent escaped or simply\n"
1650 cmd_get_confirmation (assuan_context_t ctx, char *line)
1652 ctrl_t ctrl = assuan_get_pointer (ctx);
1657 if (ctrl->restricted)
1658 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
1660 /* parse the stuff */
1661 for (p=line; *p == ' '; p++)
1664 p = strchr (desc, ' ');
1666 *p = 0; /* We ignore any garbage -may be later used for other args. */
1669 return set_error (GPG_ERR_ASS_PARAMETER, "no description given");
1671 if (!strcmp (desc, "X"))
1674 /* Note, that we only need to replace the + characters and should
1675 leave the other escaping in place because the escaped string is
1676 send verbatim to the pinentry which does the unescaping (but not
1679 plus_to_blank (desc);
1681 rc = agent_get_confirmation (ctrl, desc, NULL, NULL, 0);
1682 return leave_cmd (ctx, rc);
1687 static const char hlp_learn[] =
1688 "LEARN [--send] [--sendinfo] [--force]\n"
1690 "Learn something about the currently inserted smartcard. With\n"
1691 "--sendinfo information about the card is returned; with --send\n"
1692 "the available certificates are returned as D lines; with --force\n"
1693 "private key storage will be updated by the result.";
1695 cmd_learn (assuan_context_t ctx, char *line)
1697 ctrl_t ctrl = assuan_get_pointer (ctx);
1699 int send, sendinfo, force;
1701 send = has_option (line, "--send");
1702 sendinfo = send? 1 : has_option (line, "--sendinfo");
1703 force = has_option (line, "--force");
1705 if (ctrl->restricted)
1706 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
1708 err = agent_handle_learn (ctrl, send, sendinfo? ctx : NULL, force);
1709 return leave_cmd (ctx, err);
1714 static const char hlp_passwd[] =
1715 "PASSWD [--cache-nonce=<c>] [--passwd-nonce=<s>] [--preset]\n"
1716 " [--verify] <hexkeygrip>\n"
1718 "Change the passphrase/PIN for the key identified by keygrip in LINE. If\n"
1719 "--preset is used then the new passphrase will be added to the cache.\n"
1720 "If --verify is used the command asks for the passphrase and verifies\n"
1721 "that the passphrase valid.\n";
1723 cmd_passwd (assuan_context_t ctx, char *line)
1725 ctrl_t ctrl = assuan_get_pointer (ctx);
1728 char *cache_nonce = NULL;
1729 char *passwd_nonce = NULL;
1730 unsigned char grip[20];
1731 gcry_sexp_t s_skey = NULL;
1732 unsigned char *shadow_info = NULL;
1733 char *passphrase = NULL;
1735 int opt_preset, opt_verify;
1737 if (ctrl->restricted)
1738 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
1740 opt_preset = has_option (line, "--preset");
1741 cache_nonce = option_value (line, "--cache-nonce");
1742 opt_verify = has_option (line, "--verify");
1745 for (pend = cache_nonce; *pend && !spacep (pend); pend++)
1749 cache_nonce = xtrystrdup (cache_nonce);
1753 err = gpg_error_from_syserror ();
1758 passwd_nonce = option_value (line, "--passwd-nonce");
1761 for (pend = passwd_nonce; *pend && !spacep (pend); pend++)
1765 passwd_nonce = xtrystrdup (passwd_nonce);
1769 err = gpg_error_from_syserror ();
1774 line = skip_options (line);
1776 err = parse_keygrip (ctx, line, grip);
1781 err = agent_key_from_file (ctrl,
1782 opt_verify? NULL : cache_nonce,
1783 ctrl->server_local->keydesc,
1784 grip, &shadow_info, CACHE_MODE_IGNORE, NULL,
1785 &s_skey, &passphrase);
1788 else if (shadow_info)
1790 log_error ("changing a smartcard PIN is not yet supported\n");
1791 err = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1793 else if (opt_verify)
1801 gcry_create_nonce (buf, 12);
1802 passwd_nonce = bin2hex (buf, 12, NULL);
1805 && !agent_put_cache (passwd_nonce, CACHE_MODE_NONCE,
1806 passphrase, CACHE_TTL_NONCE))
1808 assuan_write_status (ctx, "PASSWD_NONCE", passwd_nonce);
1809 xfree (ctrl->server_local->last_passwd_nonce);
1810 ctrl->server_local->last_passwd_nonce = passwd_nonce;
1811 passwd_nonce = NULL;
1817 char *newpass = NULL;
1820 newpass = agent_get_cache (passwd_nonce, CACHE_MODE_NONCE);
1821 err = agent_protect_and_store (ctrl, s_skey, &newpass);
1822 if (!err && passphrase)
1824 /* A passphrase existed on the old key and the change was
1825 successful. Return a nonce for that old passphrase to
1826 let the caller try to unprotect the other subkeys with
1831 gcry_create_nonce (buf, 12);
1832 cache_nonce = bin2hex (buf, 12, NULL);
1835 && !agent_put_cache (cache_nonce, CACHE_MODE_NONCE,
1836 passphrase, CACHE_TTL_NONCE))
1838 assuan_write_status (ctx, "CACHE_NONCE", cache_nonce);
1839 xfree (ctrl->server_local->last_cache_nonce);
1840 ctrl->server_local->last_cache_nonce = cache_nonce;
1845 /* If we have a new passphrase (which might be empty) we
1846 store it under a passwd nonce so that the caller may
1847 send that nonce again to use it for another key. */
1851 gcry_create_nonce (buf, 12);
1852 passwd_nonce = bin2hex (buf, 12, NULL);
1855 && !agent_put_cache (passwd_nonce, CACHE_MODE_NONCE,
1856 newpass, CACHE_TTL_NONCE))
1858 assuan_write_status (ctx, "PASSWD_NONCE", passwd_nonce);
1859 xfree (ctrl->server_local->last_passwd_nonce);
1860 ctrl->server_local->last_passwd_nonce = passwd_nonce;
1861 passwd_nonce = NULL;
1865 if (!err && opt_preset)
1868 bin2hex(grip, 20, hexgrip);
1869 err = agent_put_cache (hexgrip, CACHE_MODE_ANY, newpass,
1870 ctrl->cache_ttl_opt_preset);
1876 xfree (ctrl->server_local->keydesc);
1877 ctrl->server_local->keydesc = NULL;
1881 gcry_sexp_release (s_skey);
1882 xfree (shadow_info);
1883 xfree (cache_nonce);
1884 xfree (passwd_nonce);
1885 return leave_cmd (ctx, err);
1889 static const char hlp_preset_passphrase[] =
1890 "PRESET_PASSPHRASE [--inquire] <string_or_keygrip> <timeout> [<hexstring>]\n"
1892 "Set the cached passphrase/PIN for the key identified by the keygrip\n"
1893 "to passwd for the given time, where -1 means infinite and 0 means\n"
1894 "the default (currently only a timeout of -1 is allowed, which means\n"
1895 "to never expire it). If passwd is not provided, ask for it via the\n"
1896 "pinentry module unless --inquire is passed in which case the passphrase\n"
1897 "is retrieved from the client via a server inquire.\n";
1899 cmd_preset_passphrase (assuan_context_t ctx, char *line)
1901 ctrl_t ctrl = assuan_get_pointer (ctx);
1903 char *grip_clear = NULL;
1904 unsigned char *passphrase = NULL;
1909 if (ctrl->restricted)
1910 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
1912 if (!opt.allow_preset_passphrase)
1913 return set_error (GPG_ERR_NOT_SUPPORTED, "no --allow-preset-passphrase");
1915 opt_inquire = has_option (line, "--inquire");
1916 line = skip_options (line);
1918 while (*line && (*line != ' ' && *line != '\t'))
1921 return gpg_error (GPG_ERR_MISSING_VALUE);
1924 while (*line && (*line == ' ' || *line == '\t'))
1927 /* Currently, only infinite timeouts are allowed. */
1929 if (line[0] != '-' || line[1] != '1')
1930 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1933 while (!(*line != ' ' && *line != '\t'))
1936 /* Syntax check the hexstring. */
1938 rc = parse_hexstring (ctx, line, &len);
1943 /* If there is a passphrase, use it. Currently, a passphrase is
1949 rc = set_error (GPG_ERR_ASS_PARAMETER,
1950 "both --inquire and passphrase specified");
1954 /* Do in-place conversion. */
1956 if (!hex2str (passphrase, passphrase, strlen (passphrase)+1, NULL))
1957 rc = set_error (GPG_ERR_ASS_PARAMETER, "invalid hexstring");
1959 else if (opt_inquire)
1961 /* Note that the passphrase will be truncated at any null byte and the
1962 * limit is 480 characters. */
1963 size_t maxlen = 480;
1965 rc = print_assuan_status (ctx, "INQUIRE_MAXLEN", "%zu", maxlen);
1967 rc = assuan_inquire (ctx, "PASSPHRASE", &passphrase, &len, maxlen);
1970 rc = set_error (GPG_ERR_NOT_IMPLEMENTED, "passphrase is required");
1974 rc = agent_put_cache (grip_clear, CACHE_MODE_ANY, passphrase, ttl);
1980 return leave_cmd (ctx, rc);
1985 static const char hlp_scd[] =
1986 "SCD <commands to pass to the scdaemon>\n"
1988 "This is a general quote command to redirect everything to the\n"
1991 cmd_scd (assuan_context_t ctx, char *line)
1993 ctrl_t ctrl = assuan_get_pointer (ctx);
1996 if (ctrl->restricted)
1997 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
1999 rc = divert_generic_cmd (ctrl, line, ctx);
2006 static const char hlp_keywrap_key[] =
2007 "KEYWRAP_KEY [--clear] <mode>\n"
2009 "Return a key to wrap another key. For now the key is returned\n"
2010 "verbatim and and thus makes not much sense because an eavesdropper on\n"
2011 "the gpg-agent connection will see the key as well as the wrapped key.\n"
2012 "However, this function may either be equipped with a public key\n"
2013 "mechanism or not used at all if the key is a pre-shared key. In any\n"
2014 "case wrapping the import and export of keys is a requirement for\n"
2015 "certain cryptographic validations and thus useful. The key persists\n"
2016 "until a RESET command but may be cleared using the option --clear.\n"
2018 "Supported modes are:\n"
2019 " --import - Return a key to import a key into gpg-agent\n"
2020 " --export - Return a key to export a key from gpg-agent";
2022 cmd_keywrap_key (assuan_context_t ctx, char *line)
2024 ctrl_t ctrl = assuan_get_pointer (ctx);
2025 gpg_error_t err = 0;
2026 int clearopt = has_option (line, "--clear");
2028 if (ctrl->restricted)
2029 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
2031 assuan_begin_confidential (ctx);
2032 if (has_option (line, "--import"))
2034 xfree (ctrl->server_local->import_key);
2036 ctrl->server_local->import_key = NULL;
2037 else if (!(ctrl->server_local->import_key =
2038 gcry_random_bytes (KEYWRAP_KEYSIZE, GCRY_STRONG_RANDOM)))
2039 err = gpg_error_from_syserror ();
2041 err = assuan_send_data (ctx, ctrl->server_local->import_key,
2044 else if (has_option (line, "--export"))
2046 xfree (ctrl->server_local->export_key);
2048 ctrl->server_local->export_key = NULL;
2049 else if (!(ctrl->server_local->export_key =
2050 gcry_random_bytes (KEYWRAP_KEYSIZE, GCRY_STRONG_RANDOM)))
2051 err = gpg_error_from_syserror ();
2053 err = assuan_send_data (ctx, ctrl->server_local->export_key,
2057 err = set_error (GPG_ERR_ASS_PARAMETER, "unknown value for MODE");
2058 assuan_end_confidential (ctx);
2060 return leave_cmd (ctx, err);
2065 static const char hlp_import_key[] =
2066 "IMPORT_KEY [--unattended] [--force] [<cache_nonce>]\n"
2068 "Import a secret key into the key store. The key is expected to be\n"
2069 "encrypted using the current session's key wrapping key (cf. command\n"
2070 "KEYWRAP_KEY) using the AESWRAP-128 algorithm. This function takes\n"
2071 "no arguments but uses the inquiry \"KEYDATA\" to ask for the actual\n"
2072 "key data. The unwrapped key must be a canonical S-expression. The\n"
2073 "option --unattended tries to import the key as-is without any\n"
2074 "re-encryption. Existing key can be overwritten with --force.";
2076 cmd_import_key (assuan_context_t ctx, char *line)
2078 ctrl_t ctrl = assuan_get_pointer (ctx);
2082 unsigned char *wrappedkey = NULL;
2083 size_t wrappedkeylen;
2084 gcry_cipher_hd_t cipherhd = NULL;
2085 unsigned char *key = NULL;
2086 size_t keylen, realkeylen;
2087 char *passphrase = NULL;
2088 unsigned char *finalkey = NULL;
2090 unsigned char grip[20];
2091 gcry_sexp_t openpgp_sexp = NULL;
2092 char *cache_nonce = NULL;
2095 if (ctrl->restricted)
2096 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
2098 if (!ctrl->server_local->import_key)
2100 err = gpg_error (GPG_ERR_MISSING_KEY);
2104 opt_unattended = has_option (line, "--unattended");
2105 force = has_option (line, "--force");
2106 line = skip_options (line);
2109 for (p=line; *p && *p != ' ' && *p != '\t'; p++)
2113 cache_nonce = xtrystrdup (line);
2115 assuan_begin_confidential (ctx);
2116 err = assuan_inquire (ctx, "KEYDATA",
2117 &wrappedkey, &wrappedkeylen, MAXLEN_KEYDATA);
2118 assuan_end_confidential (ctx);
2121 if (wrappedkeylen < 24)
2123 err = gpg_error (GPG_ERR_INV_LENGTH);
2126 keylen = wrappedkeylen - 8;
2127 key = xtrymalloc_secure (keylen);
2130 err = gpg_error_from_syserror ();
2134 err = gcry_cipher_open (&cipherhd, GCRY_CIPHER_AES128,
2135 GCRY_CIPHER_MODE_AESWRAP, 0);
2138 err = gcry_cipher_setkey (cipherhd,
2139 ctrl->server_local->import_key, KEYWRAP_KEYSIZE);
2142 err = gcry_cipher_decrypt (cipherhd, key, keylen, wrappedkey, wrappedkeylen);
2145 gcry_cipher_close (cipherhd);
2150 realkeylen = gcry_sexp_canon_len (key, keylen, NULL, &err);
2152 goto leave; /* Invalid canonical encoded S-expression. */
2154 err = keygrip_from_canon_sexp (key, realkeylen, grip);
2157 /* This might be due to an unsupported S-expression format.
2158 Check whether this is openpgp-private-key and trigger that
2160 if (!gcry_sexp_sscan (&openpgp_sexp, NULL, key, realkeylen))
2165 tag = gcry_sexp_nth_data (openpgp_sexp, 0, &taglen);
2166 if (tag && taglen == 19 && !memcmp (tag, "openpgp-private-key", 19))
2170 gcry_sexp_release (openpgp_sexp);
2171 openpgp_sexp = NULL;
2175 goto leave; /* Note that ERR is still set. */
2181 /* In most cases the key is encrypted and thus the conversion
2182 function from the OpenPGP format to our internal format will
2183 ask for a passphrase. That passphrase will be returned and
2184 used to protect the key using the same code as for regular
2189 err = convert_from_openpgp (ctrl, openpgp_sexp, force, grip,
2190 ctrl->server_local->keydesc, cache_nonce,
2191 &key, opt_unattended? NULL : &passphrase);
2194 realkeylen = gcry_sexp_canon_len (key, 0, NULL, &err);
2196 goto leave; /* Invalid canonical encoded S-expression. */
2199 assert (!opt_unattended);
2203 gcry_create_nonce (buf, 12);
2204 cache_nonce = bin2hex (buf, 12, NULL);
2207 && !agent_put_cache (cache_nonce, CACHE_MODE_NONCE,
2208 passphrase, CACHE_TTL_NONCE))
2209 assuan_write_status (ctx, "CACHE_NONCE", cache_nonce);
2212 else if (opt_unattended)
2214 err = set_error (GPG_ERR_ASS_PARAMETER,
2215 "\"--unattended\" may only be used with OpenPGP keys");
2220 if (!force && !agent_key_available (grip))
2221 err = gpg_error (GPG_ERR_EEXIST);
2224 char *prompt = xtryasprintf
2225 (_("Please enter the passphrase to protect the "
2226 "imported object within the %s system."), GNUPG_NAME);
2228 err = gpg_error_from_syserror ();
2230 err = agent_ask_new_passphrase (ctrl, prompt, &passphrase);
2239 err = agent_protect (key, passphrase, &finalkey, &finalkeylen,
2240 ctrl->s2k_count, -1);
2242 err = agent_write_private_key (grip, finalkey, finalkeylen, force);
2245 err = agent_write_private_key (grip, key, realkeylen, force);
2248 gcry_sexp_release (openpgp_sexp);
2252 gcry_cipher_close (cipherhd);
2254 xfree (cache_nonce);
2255 xfree (ctrl->server_local->keydesc);
2256 ctrl->server_local->keydesc = NULL;
2257 return leave_cmd (ctx, err);
2262 static const char hlp_export_key[] =
2263 "EXPORT_KEY [--cache-nonce=<nonce>] [--openpgp] <hexstring_with_keygrip>\n"
2265 "Export a secret key from the key store. The key will be encrypted\n"
2266 "using the current session's key wrapping key (cf. command KEYWRAP_KEY)\n"
2267 "using the AESWRAP-128 algorithm. The caller needs to retrieve that key\n"
2268 "prior to using this command. The function takes the keygrip as argument.\n"
2270 "If --openpgp is used, the secret key material will be exported in RFC 4880\n"
2271 "compatible passphrase-protected form. Without --openpgp, the secret key\n"
2272 "material will be exported in the clear (after prompting the user to unlock\n"
2273 "it, if needed).\n";
2275 cmd_export_key (assuan_context_t ctx, char *line)
2277 ctrl_t ctrl = assuan_get_pointer (ctx);
2279 unsigned char grip[20];
2280 gcry_sexp_t s_skey = NULL;
2281 unsigned char *key = NULL;
2283 gcry_cipher_hd_t cipherhd = NULL;
2284 unsigned char *wrappedkey = NULL;
2285 size_t wrappedkeylen;
2288 char *passphrase = NULL;
2289 unsigned char *shadow_info = NULL;
2293 if (ctrl->restricted)
2294 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
2296 openpgp = has_option (line, "--openpgp");
2297 cache_nonce = option_value (line, "--cache-nonce");
2300 for (pend = cache_nonce; *pend && !spacep (pend); pend++)
2304 cache_nonce = xtrystrdup (cache_nonce);
2308 err = gpg_error_from_syserror ();
2312 line = skip_options (line);
2314 if (!ctrl->server_local->export_key)
2316 err = set_error (GPG_ERR_MISSING_KEY, "did you run KEYWRAP_KEY ?");
2320 err = parse_keygrip (ctx, line, grip);
2324 if (agent_key_available (grip))
2326 err = gpg_error (GPG_ERR_NO_SECKEY);
2330 /* Get the key from the file. With the openpgp flag we also ask for
2331 the passphrase so that we can use it to re-encrypt it. */
2332 err = agent_key_from_file (ctrl, cache_nonce,
2333 ctrl->server_local->keydesc, grip,
2334 &shadow_info, CACHE_MODE_IGNORE, NULL, &s_skey,
2335 openpgp ? &passphrase : NULL);
2340 /* Key is on a smartcard. */
2341 err = gpg_error (GPG_ERR_UNUSABLE_SECKEY);
2347 /* The openpgp option changes the key format into the OpenPGP
2348 key transfer format. The result is already a padded
2349 canonical S-expression. */
2352 err = agent_ask_new_passphrase
2353 (ctrl, _("This key (or subkey) is not protected with a passphrase."
2354 " Please enter a new passphrase to export it."),
2359 err = convert_to_openpgp (ctrl, s_skey, passphrase, &key, &keylen);
2360 if (!err && passphrase)
2365 gcry_create_nonce (buf, 12);
2366 cache_nonce = bin2hex (buf, 12, NULL);
2369 && !agent_put_cache (cache_nonce, CACHE_MODE_NONCE,
2370 passphrase, CACHE_TTL_NONCE))
2372 assuan_write_status (ctx, "CACHE_NONCE", cache_nonce);
2373 xfree (ctrl->server_local->last_cache_nonce);
2374 ctrl->server_local->last_cache_nonce = cache_nonce;
2381 /* Convert into a canonical S-expression and wrap that. */
2382 err = make_canon_sexp_pad (s_skey, 1, &key, &keylen);
2386 gcry_sexp_release (s_skey);
2389 err = gcry_cipher_open (&cipherhd, GCRY_CIPHER_AES128,
2390 GCRY_CIPHER_MODE_AESWRAP, 0);
2393 err = gcry_cipher_setkey (cipherhd,
2394 ctrl->server_local->export_key, KEYWRAP_KEYSIZE);
2398 wrappedkeylen = keylen + 8;
2399 wrappedkey = xtrymalloc (wrappedkeylen);
2402 err = gpg_error_from_syserror ();
2406 err = gcry_cipher_encrypt (cipherhd, wrappedkey, wrappedkeylen, key, keylen);
2411 gcry_cipher_close (cipherhd);
2414 assuan_begin_confidential (ctx);
2415 err = assuan_send_data (ctx, wrappedkey, wrappedkeylen);
2416 assuan_end_confidential (ctx);
2420 xfree (cache_nonce);
2423 gcry_cipher_close (cipherhd);
2425 gcry_sexp_release (s_skey);
2426 xfree (ctrl->server_local->keydesc);
2427 ctrl->server_local->keydesc = NULL;
2428 xfree (shadow_info);
2430 return leave_cmd (ctx, err);
2435 static const char hlp_delete_key[] =
2436 "DELETE_KEY [--force] <hexstring_with_keygrip>\n"
2438 "Delete a secret key from the key store. If --force is used\n"
2439 "and a loopback pinentry is allowed, the agent will not ask\n"
2440 "the user for confirmation.";
2442 cmd_delete_key (assuan_context_t ctx, char *line)
2444 ctrl_t ctrl = assuan_get_pointer (ctx);
2447 unsigned char grip[20];
2449 if (ctrl->restricted)
2450 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
2452 force = has_option (line, "--force");
2453 line = skip_options (line);
2455 /* If the use of a loopback pinentry has been disabled, we assume
2456 * that a silent deletion of keys shall also not be allowed. */
2457 if (!opt.allow_loopback_pinentry)
2460 err = parse_keygrip (ctx, line, grip);
2464 err = agent_delete_key (ctrl, ctrl->server_local->keydesc, grip, force );
2469 xfree (ctrl->server_local->keydesc);
2470 ctrl->server_local->keydesc = NULL;
2472 return leave_cmd (ctx, err);
2477 static const char hlp_keytocard[] =
2478 "KEYTOCARD [--force] <hexstring_with_keygrip> <serialno> <id> <timestamp>\n"
2481 cmd_keytocard (assuan_context_t ctx, char *line)
2483 ctrl_t ctrl = assuan_get_pointer (ctx);
2485 gpg_error_t err = 0;
2486 unsigned char grip[20];
2487 gcry_sexp_t s_skey = NULL;
2488 unsigned char *keydata;
2489 size_t keydatalen, timestamplen;
2490 const char *serialno, *timestamp_str, *id;
2491 unsigned char *shadow_info = NULL;
2494 if (ctrl->restricted)
2495 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
2497 force = has_option (line, "--force");
2498 line = skip_options (line);
2500 err = parse_keygrip (ctx, line, grip);
2504 if (agent_key_available (grip))
2505 return gpg_error (GPG_ERR_NO_SECKEY);
2508 while (*line && (*line == ' ' || *line == '\t'))
2511 while (*line && (*line != ' ' && *line != '\t'))
2514 return gpg_error (GPG_ERR_MISSING_VALUE);
2517 while (*line && (*line == ' ' || *line == '\t'))
2520 while (*line && (*line != ' ' && *line != '\t'))
2523 return gpg_error (GPG_ERR_MISSING_VALUE);
2526 while (*line && (*line == ' ' || *line == '\t'))
2528 timestamp_str = line;
2529 while (*line && (*line != ' ' && *line != '\t'))
2533 timestamplen = line - timestamp_str;
2534 if (timestamplen != 15)
2535 return gpg_error (GPG_ERR_INV_VALUE);
2537 err = agent_key_from_file (ctrl, NULL, ctrl->server_local->keydesc, grip,
2538 &shadow_info, CACHE_MODE_IGNORE, NULL,
2542 xfree (shadow_info);
2547 /* Key is on a smartcard already. */
2548 xfree (shadow_info);
2549 gcry_sexp_release (s_skey);
2550 return gpg_error (GPG_ERR_UNUSABLE_SECKEY);
2553 keydatalen = gcry_sexp_sprint (s_skey, GCRYSEXP_FMT_CANON, NULL, 0);
2554 keydata = xtrymalloc_secure (keydatalen + 30);
2555 if (keydata == NULL)
2557 gcry_sexp_release (s_skey);
2558 return gpg_error_from_syserror ();
2561 gcry_sexp_sprint (s_skey, GCRYSEXP_FMT_CANON, keydata, keydatalen);
2562 gcry_sexp_release (s_skey);
2563 keydatalen--; /* Decrement for last '\0'. */
2564 /* Add timestamp "created-at" in the private key */
2565 timestamp = isotime2epoch (timestamp_str);
2566 snprintf (keydata+keydatalen-1, 30, "(10:created-at10:%010lu))", timestamp);
2567 keydatalen += 10 + 19 - 1;
2568 err = divert_writekey (ctrl, force, serialno, id, keydata, keydatalen);
2571 return leave_cmd (ctx, err);
2576 static const char hlp_getval[] =
2579 "Return the value for KEY from the special environment as created by\n"
2582 cmd_getval (assuan_context_t ctx, char *line)
2584 ctrl_t ctrl = assuan_get_pointer (ctx);
2588 struct putval_item_s *vl;
2590 if (ctrl->restricted)
2591 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
2593 for (p=line; *p == ' '; p++)
2596 p = strchr (key, ' ');
2600 for (; *p == ' '; p++)
2603 return set_error (GPG_ERR_ASS_PARAMETER, "too many arguments");
2606 return set_error (GPG_ERR_ASS_PARAMETER, "no key given");
2609 for (vl=putval_list; vl; vl = vl->next)
2610 if ( !strcmp (vl->d, key) )
2613 if (vl) /* Got an entry. */
2614 rc = assuan_send_data (ctx, vl->d+vl->off, vl->len);
2616 return gpg_error (GPG_ERR_NO_DATA);
2618 return leave_cmd (ctx, rc);
2622 static const char hlp_putval[] =
2623 "PUTVAL <key> [<percent_escaped_value>]\n"
2625 "The gpg-agent maintains a kind of environment which may be used to\n"
2626 "store key/value pairs in it, so that they can be retrieved later.\n"
2627 "This may be used by helper daemons to daemonize themself on\n"
2628 "invocation and register them with gpg-agent. Callers of the\n"
2629 "daemon's service may now first try connect to get the information\n"
2630 "for that service from gpg-agent through the GETVAL command and then\n"
2631 "try to connect to that daemon. Only if that fails they may start\n"
2632 "an own instance of the service daemon. \n"
2634 "KEY is an an arbitrary symbol with the same syntax rules as keys\n"
2635 "for shell environment variables. PERCENT_ESCAPED_VALUE is the\n"
2636 "corresponding value; they should be similar to the values of\n"
2637 "envronment variables but gpg-agent does not enforce any\n"
2638 "restrictions. If that value is not given any value under that KEY\n"
2639 "is removed from this special environment.";
2641 cmd_putval (assuan_context_t ctx, char *line)
2643 ctrl_t ctrl = assuan_get_pointer (ctx);
2647 size_t valuelen = 0;
2649 struct putval_item_s *vl, *vlprev;
2651 if (ctrl->restricted)
2652 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
2654 for (p=line; *p == ' '; p++)
2657 p = strchr (key, ' ');
2661 for (; *p == ' '; p++)
2666 p = strchr (value, ' ');
2669 valuelen = percent_plus_unescape_inplace (value, 0);
2673 return set_error (GPG_ERR_ASS_PARAMETER, "no key given");
2676 for (vl=putval_list,vlprev=NULL; vl; vlprev=vl, vl = vl->next)
2677 if ( !strcmp (vl->d, key) )
2680 if (vl) /* Delete old entry. */
2683 vlprev->next = vl->next;
2685 putval_list = vl->next;
2689 if (valuelen) /* Add entry. */
2691 vl = xtrymalloc (sizeof *vl + strlen (key) + valuelen);
2693 rc = gpg_error_from_syserror ();
2697 vl->off = strlen (key) + 1;
2698 strcpy (vl->d, key);
2699 memcpy (vl->d + vl->off, value, valuelen);
2700 vl->next = putval_list;
2705 return leave_cmd (ctx, rc);
2711 static const char hlp_updatestartuptty[] =
2712 "UPDATESTARTUPTTY\n"
2714 "Set startup TTY and X11 DISPLAY variables to the values of this\n"
2715 "session. This command is useful to pull future pinentries to\n"
2716 "another screen. It is only required because there is no way in the\n"
2717 "ssh-agent protocol to convey this information.";
2719 cmd_updatestartuptty (assuan_context_t ctx, char *line)
2721 ctrl_t ctrl = assuan_get_pointer (ctx);
2722 gpg_error_t err = 0;
2724 char *lc_ctype = NULL;
2725 char *lc_messages = NULL;
2731 if (ctrl->restricted)
2732 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
2734 se = session_env_new ();
2736 err = gpg_error_from_syserror ();
2739 while (!err && (name = session_env_list_stdenvnames (&iterator, NULL)))
2741 const char *value = session_env_getenv (ctrl->session_env, name);
2743 err = session_env_setenv (se, name, value);
2746 if (!err && ctrl->lc_ctype)
2747 if (!(lc_ctype = xtrystrdup (ctrl->lc_ctype)))
2748 err = gpg_error_from_syserror ();
2750 if (!err && ctrl->lc_messages)
2751 if (!(lc_messages = xtrystrdup (ctrl->lc_messages)))
2752 err = gpg_error_from_syserror ();
2756 session_env_release (se);
2758 xfree (lc_messages);
2762 session_env_release (opt.startup_env);
2763 opt.startup_env = se;
2764 xfree (opt.startup_lc_ctype);
2765 opt.startup_lc_ctype = lc_ctype;
2766 xfree (opt.startup_lc_messages);
2767 opt.startup_lc_messages = lc_messages;
2775 static const char hlp_killagent[] =
2780 cmd_killagent (assuan_context_t ctx, char *line)
2782 ctrl_t ctrl = assuan_get_pointer (ctx);
2786 if (ctrl->restricted)
2787 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
2789 ctrl->server_local->stopme = 1;
2790 assuan_set_flag (ctx, ASSUAN_FORCE_CLOSE, 1);
2795 static const char hlp_reloadagent[] =
2798 "This command is an alternative to SIGHUP\n"
2799 "to reload the configuration.";
2801 cmd_reloadagent (assuan_context_t ctx, char *line)
2803 ctrl_t ctrl = assuan_get_pointer (ctx);
2807 if (ctrl->restricted)
2808 return leave_cmd (ctx, gpg_error (GPG_ERR_FORBIDDEN));
2810 agent_sighup_action ();
2816 static const char hlp_getinfo[] =
2819 "Multipurpose function to return a variety of information.\n"
2820 "Supported values for WHAT are:\n"
2822 " version - Return the version of the program.\n"
2823 " pid - Return the process id of the server.\n"
2824 " socket_name - Return the name of the socket.\n"
2825 " ssh_socket_name - Return the name of the ssh socket.\n"
2826 " scd_running - Return OK if the SCdaemon is already running.\n"
2827 " s2k_count - Return the calibrated S2K count.\n"
2828 " std_env_names - List the names of the standard environment.\n"
2829 " std_session_env - List the standard session environment.\n"
2830 " std_startup_env - List the standard startup environment.\n"
2832 " - Returns OK if the command CMD implements the option OPT.\n"
2833 " connections - Return number of active connections.\n"
2834 " restricted - Returns OK if the connection is in restricted mode.\n";
2836 cmd_getinfo (assuan_context_t ctx, char *line)
2838 ctrl_t ctrl = assuan_get_pointer (ctx);
2841 if (!strcmp (line, "version"))
2843 const char *s = VERSION;
2844 rc = assuan_send_data (ctx, s, strlen (s));
2846 else if (!strncmp (line, "cmd_has_option", 14)
2847 && (line[14] == ' ' || line[14] == '\t' || !line[14]))
2851 while (*line == ' ' || *line == '\t')
2854 rc = gpg_error (GPG_ERR_MISSING_VALUE);
2858 while (*line && (*line != ' ' && *line != '\t'))
2861 rc = gpg_error (GPG_ERR_MISSING_VALUE);
2865 while (*line == ' ' || *line == '\t')
2868 rc = gpg_error (GPG_ERR_MISSING_VALUE);
2872 if (!command_has_option (cmd, cmdopt))
2873 rc = gpg_error (GPG_ERR_GENERAL);
2878 else if (!strcmp (line, "s2k_count"))
2882 snprintf (numbuf, sizeof numbuf, "%lu", get_standard_s2k_count ());
2883 rc = assuan_send_data (ctx, numbuf, strlen (numbuf));
2885 else if (!strcmp (line, "restricted"))
2887 rc = ctrl->restricted? 0 : gpg_error (GPG_ERR_GENERAL);
2889 else if (ctrl->restricted)
2891 rc = gpg_error (GPG_ERR_FORBIDDEN);
2893 /* All sub-commands below are not allowed in restricted mode. */
2894 else if (!strcmp (line, "pid"))
2898 snprintf (numbuf, sizeof numbuf, "%lu", (unsigned long)getpid ());
2899 rc = assuan_send_data (ctx, numbuf, strlen (numbuf));
2901 else if (!strcmp (line, "socket_name"))
2903 const char *s = get_agent_socket_name ();
2906 rc = assuan_send_data (ctx, s, strlen (s));
2908 rc = gpg_error (GPG_ERR_NO_DATA);
2910 else if (!strcmp (line, "ssh_socket_name"))
2912 const char *s = get_agent_ssh_socket_name ();
2915 rc = assuan_send_data (ctx, s, strlen (s));
2917 rc = gpg_error (GPG_ERR_NO_DATA);
2919 else if (!strcmp (line, "scd_running"))
2921 rc = agent_scd_check_running ()? 0 : gpg_error (GPG_ERR_GENERAL);
2923 else if (!strcmp (line, "std_env_names"))
2929 while ((name = session_env_list_stdenvnames (&iterator, NULL)))
2931 rc = assuan_send_data (ctx, name, strlen (name)+1);
2933 rc = assuan_send_data (ctx, NULL, 0);
2938 else if (!strcmp (line, "std_session_env")
2939 || !strcmp (line, "std_startup_env"))
2942 const char *name, *value;
2946 while ((name = session_env_list_stdenvnames (&iterator, NULL)))
2948 value = session_env_getenv_or_default
2949 (line[5] == 't'? opt.startup_env:ctrl->session_env, name, NULL);
2952 string = xtryasprintf ("%s=%s", name, value);
2954 rc = gpg_error_from_syserror ();
2957 rc = assuan_send_data (ctx, string, strlen (string)+1);
2959 rc = assuan_send_data (ctx, NULL, 0);
2966 else if (!strcmp (line, "connections"))
2970 snprintf (numbuf, sizeof numbuf, "%d",
2971 get_agent_active_connection_count ());
2972 rc = assuan_send_data (ctx, numbuf, strlen (numbuf));
2975 rc = set_error (GPG_ERR_ASS_PARAMETER, "unknown value for WHAT");
2981 /* This function is called by Libassuan to parse the OPTION command.
2982 It has been registered similar to the other Assuan commands. */
2984 option_handler (assuan_context_t ctx, const char *key, const char *value)
2986 ctrl_t ctrl = assuan_get_pointer (ctx);
2987 gpg_error_t err = 0;
2989 if (!strcmp (key, "agent-awareness"))
2991 /* The value is a version string telling us of which agent
2992 version the caller is aware of. */
2993 ctrl->server_local->allow_fully_canceled =
2994 gnupg_compare_version (value, "2.1.0");
2996 else if (ctrl->restricted)
2998 err = gpg_error (GPG_ERR_FORBIDDEN);
3000 /* All options below are not allowed in restricted mode. */
3001 else if (!strcmp (key, "putenv"))
3003 /* Change the session's environment to be used for the
3004 Pinentry. Valid values are:
3005 <NAME> Delete envvar NAME
3006 <KEY>= Set envvar NAME to the empty string
3007 <KEY>=<VALUE> Set envvar NAME to VALUE
3009 err = session_env_putenv (ctrl->session_env, value);
3011 else if (!strcmp (key, "display"))
3013 err = session_env_setenv (ctrl->session_env, "DISPLAY", value);
3015 else if (!strcmp (key, "ttyname"))
3018 err = session_env_setenv (ctrl->session_env, "GPG_TTY", value);
3020 else if (!strcmp (key, "ttytype"))
3023 err = session_env_setenv (ctrl->session_env, "TERM", value);
3025 else if (!strcmp (key, "lc-ctype"))
3028 xfree (ctrl->lc_ctype);
3029 ctrl->lc_ctype = xtrystrdup (value);
3030 if (!ctrl->lc_ctype)
3031 return out_of_core ();
3033 else if (!strcmp (key, "lc-messages"))
3035 if (ctrl->lc_messages)
3036 xfree (ctrl->lc_messages);
3037 ctrl->lc_messages = xtrystrdup (value);
3038 if (!ctrl->lc_messages)
3039 return out_of_core ();
3041 else if (!strcmp (key, "xauthority"))
3043 err = session_env_setenv (ctrl->session_env, "XAUTHORITY", value);
3045 else if (!strcmp (key, "pinentry-user-data"))
3047 err = session_env_setenv (ctrl->session_env, "PINENTRY_USER_DATA", value);
3049 else if (!strcmp (key, "use-cache-for-signing"))
3050 ctrl->server_local->use_cache_for_signing = *value? !!atoi (value) : 0;
3051 else if (!strcmp (key, "allow-pinentry-notify"))
3052 ctrl->server_local->allow_pinentry_notify = 1;
3053 else if (!strcmp (key, "pinentry-mode"))
3055 int tmp = parse_pinentry_mode (value);
3057 err = gpg_error (GPG_ERR_INV_VALUE);
3058 else if (tmp == PINENTRY_MODE_LOOPBACK && !opt.allow_loopback_pinentry)
3059 err = gpg_error (GPG_ERR_NOT_SUPPORTED);
3061 ctrl->pinentry_mode = tmp;
3063 else if (!strcmp (key, "cache-ttl-opt-preset"))
3065 ctrl->cache_ttl_opt_preset = *value? atoi (value) : 0;
3067 else if (!strcmp (key, "s2k-count"))
3069 ctrl->s2k_count = *value? strtoul(value, NULL, 10) : 0;
3070 if (ctrl->s2k_count && ctrl->s2k_count < 65536)
3072 ctrl->s2k_count = 0;
3076 err = gpg_error (GPG_ERR_UNKNOWN_OPTION);
3084 /* Called by libassuan after all commands. ERR is the error from the
3085 last assuan operation and not the one returned from the command. */
3087 post_cmd_notify (assuan_context_t ctx, gpg_error_t err)
3089 ctrl_t ctrl = assuan_get_pointer (ctx);
3093 /* Switch off any I/O monitor controlled logging pausing. */
3094 ctrl->server_local->pause_io_logging = 0;
3098 /* This function is called by libassuan for all I/O. We use it here
3099 to disable logging for the GETEVENTCOUNTER commands. This is so
3100 that the debug output won't get cluttered by this primitive
3103 io_monitor (assuan_context_t ctx, void *hook, int direction,
3104 const char *line, size_t linelen)
3106 ctrl_t ctrl = assuan_get_pointer (ctx);
3110 /* We want to suppress all Assuan log messages for connections from
3111 * self. However, assuan_get_pid works only after
3112 * assuan_accept. Now, assuan_accept already logs a line ending with
3113 * the process id. We use this hack here to get the peers pid so
3114 * that we can compare it to our pid. We should add an assuan
3115 * function to return the pid for a file descriptor and use that to
3116 * detect connections to self. */
3117 if (ctx && !ctrl->server_local->greeting_seen
3118 && direction == ASSUAN_IO_TO_PEER)
3120 ctrl->server_local->greeting_seen = 1;
3122 && !strncmp (line, "OK Pleased to meet you, process ", 32)
3123 && strtoul (line+32, NULL, 10) == getpid ())
3124 return ASSUAN_IO_MONITOR_NOLOG;
3128 /* Do not log self-connections. This makes the log cleaner because
3129 * we won't see the check-our-own-socket calls. */
3130 if (ctx && ctrl->server_local->connect_from_self)
3131 return ASSUAN_IO_MONITOR_NOLOG;
3133 /* Note that we only check for the uppercase name. This allows the user to
3134 see the logging for debugging if using a non-upercase command
3136 if (ctx && direction == ASSUAN_IO_FROM_PEER
3138 && !strncmp (line, "GETEVENTCOUNTER", 15)
3139 && (linelen == 15 || spacep (line+15)))
3141 ctrl->server_local->pause_io_logging = 1;
3144 return ctrl->server_local->pause_io_logging? ASSUAN_IO_MONITOR_NOLOG : 0;
3148 /* Return true if the command CMD implements the option OPT. */
3150 command_has_option (const char *cmd, const char *cmdopt)
3152 if (!strcmp (cmd, "GET_PASSPHRASE"))
3154 if (!strcmp (cmdopt, "repeat"))
3162 /* Tell Libassuan about our commands. Also register the other Assuan
3165 register_commands (assuan_context_t ctx)
3169 assuan_handler_t handler;
3170 const char * const help;
3172 { "GETEVENTCOUNTER",cmd_geteventcounter, hlp_geteventcounter },
3173 { "ISTRUSTED", cmd_istrusted, hlp_istrusted },
3174 { "HAVEKEY", cmd_havekey, hlp_havekey },
3175 { "KEYINFO", cmd_keyinfo, hlp_keyinfo },
3176 { "SIGKEY", cmd_sigkey, hlp_sigkey },
3177 { "SETKEY", cmd_sigkey, hlp_sigkey },
3178 { "SETKEYDESC", cmd_setkeydesc,hlp_setkeydesc },
3179 { "SETHASH", cmd_sethash, hlp_sethash },
3180 { "PKSIGN", cmd_pksign, hlp_pksign },
3181 { "PKDECRYPT", cmd_pkdecrypt, hlp_pkdecrypt },
3182 { "GENKEY", cmd_genkey, hlp_genkey },
3183 { "READKEY", cmd_readkey, hlp_readkey },
3184 { "GET_PASSPHRASE", cmd_get_passphrase, hlp_get_passphrase },
3185 { "PRESET_PASSPHRASE", cmd_preset_passphrase, hlp_preset_passphrase },
3186 { "CLEAR_PASSPHRASE", cmd_clear_passphrase, hlp_clear_passphrase },
3187 { "GET_CONFIRMATION", cmd_get_confirmation, hlp_get_confirmation },
3188 { "LISTTRUSTED", cmd_listtrusted, hlp_listtrusted },
3189 { "MARKTRUSTED", cmd_marktrusted, hlp_martrusted },
3190 { "LEARN", cmd_learn, hlp_learn },
3191 { "PASSWD", cmd_passwd, hlp_passwd },
3194 { "SCD", cmd_scd, hlp_scd },
3195 { "KEYWRAP_KEY", cmd_keywrap_key, hlp_keywrap_key },
3196 { "IMPORT_KEY", cmd_import_key, hlp_import_key },
3197 { "EXPORT_KEY", cmd_export_key, hlp_export_key },
3198 { "DELETE_KEY", cmd_delete_key, hlp_delete_key },
3199 { "GETVAL", cmd_getval, hlp_getval },
3200 { "PUTVAL", cmd_putval, hlp_putval },
3201 { "UPDATESTARTUPTTY", cmd_updatestartuptty, hlp_updatestartuptty },
3202 { "KILLAGENT", cmd_killagent, hlp_killagent },
3203 { "RELOADAGENT", cmd_reloadagent,hlp_reloadagent },
3204 { "GETINFO", cmd_getinfo, hlp_getinfo },
3205 { "KEYTOCARD", cmd_keytocard, hlp_keytocard },
3210 for (i=0; table[i].name; i++)
3212 rc = assuan_register_command (ctx, table[i].name, table[i].handler,
3217 assuan_register_post_cmd_notify (ctx, post_cmd_notify);
3218 assuan_register_reset_notify (ctx, reset_notify);
3219 assuan_register_option_handler (ctx, option_handler);
3224 /* Startup the server. If LISTEN_FD and FD is given as -1, this is a
3225 simple piper server, otherwise it is a regular server. CTRL is the
3226 control structure for this connection; it has only the basic
3229 start_command_handler (ctrl_t ctrl, gnupg_fd_t listen_fd, gnupg_fd_t fd)
3232 assuan_context_t ctx = NULL;
3234 if (ctrl->restricted)
3236 if (agent_copy_startup_env (ctrl))
3240 rc = assuan_new (&ctx);
3243 log_error ("failed to allocate assuan context: %s\n", gpg_strerror (rc));
3247 if (listen_fd == GNUPG_INVALID_FD && fd == GNUPG_INVALID_FD)
3249 assuan_fd_t filedes[2];
3251 filedes[0] = assuan_fdopen (0);
3252 filedes[1] = assuan_fdopen (1);
3253 rc = assuan_init_pipe_server (ctx, filedes);
3255 else if (listen_fd != GNUPG_INVALID_FD)
3257 rc = assuan_init_socket_server (ctx, listen_fd, 0);
3258 /* FIXME: Need to call assuan_sock_set_nonce for Windows. But
3259 this branch is currently not used. */
3263 rc = assuan_init_socket_server (ctx, fd, ASSUAN_SOCKET_SERVER_ACCEPTED);
3267 log_error ("failed to initialize the server: %s\n",
3271 rc = register_commands (ctx);
3274 log_error ("failed to register commands with Assuan: %s\n",
3279 assuan_set_pointer (ctx, ctrl);
3280 ctrl->server_local = xcalloc (1, sizeof *ctrl->server_local);
3281 ctrl->server_local->assuan_ctx = ctx;
3282 ctrl->server_local->use_cache_for_signing = 1;
3284 ctrl->digest.raw_value = 0;
3286 assuan_set_io_monitor (ctx, io_monitor, NULL);
3287 agent_set_progress_cb (progress_cb, ctrl);
3291 rc = assuan_accept (ctx);
3292 if (gpg_err_code (rc) == GPG_ERR_EOF || rc == -1)
3298 log_info ("Assuan accept problem: %s\n", gpg_strerror (rc));
3302 ctrl->server_local->connect_from_self = (assuan_get_pid (ctx)==getpid ());
3304 rc = assuan_process (ctx);
3307 log_info ("Assuan processing failed: %s\n", gpg_strerror (rc));
3312 /* Reset the nonce caches. */
3313 clear_nonce_cache (ctrl);
3315 /* Reset the SCD if needed. */
3316 agent_reset_scd (ctrl);
3318 /* Reset the pinentry (in case of popup messages). */
3319 agent_reset_query (ctrl);
3322 assuan_release (ctx);
3323 xfree (ctrl->server_local->keydesc);
3324 xfree (ctrl->server_local->import_key);
3325 xfree (ctrl->server_local->export_key);
3326 if (ctrl->server_local->stopme)
3328 xfree (ctrl->server_local);
3329 ctrl->server_local = NULL;
3333 /* Helper for the pinentry loopback mode. It merely passes the
3334 parameters on to the client. */
3336 pinentry_loopback(ctrl_t ctrl, const char *keyword,
3337 unsigned char **buffer, size_t *size,
3341 assuan_context_t ctx = ctrl->server_local->assuan_ctx;
3343 rc = print_assuan_status (ctx, "INQUIRE_MAXLEN", "%zu", max_length);
3347 assuan_begin_confidential (ctx);
3348 rc = assuan_inquire (ctx, keyword, buffer, size, max_length);
3349 assuan_end_confidential (ctx);