1 /* command-ssh.c - gpg-agent's ssh-agent emulation layer
2 * Copyright (C) 2004-2006, 2009, 2012 Free Software Foundation, Inc.
3 * Copyright (C) 2004-2006, 2009, 2012-2014 Werner Koch
5 * This file is part of GnuPG.
7 * GnuPG is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * GnuPG is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, see <http://www.gnu.org/licenses/>.
21 /* Only v2 of the ssh-agent protocol is implemented. Relevant RFCs
24 RFC-4250 - Protocol Assigned Numbers
25 RFC-4251 - Protocol Architecture
26 RFC-4252 - Authentication Protocol
27 RFC-4253 - Transport Layer Protocol
28 RFC-5656 - ECC support
30 The protocol for the agent is defined in OpenSSH's PROTOCL.agent
40 #include <sys/types.h>
47 #include "../common/ssh-utils.h"
53 #define SSH_REQUEST_REQUEST_IDENTITIES 11
54 #define SSH_REQUEST_SIGN_REQUEST 13
55 #define SSH_REQUEST_ADD_IDENTITY 17
56 #define SSH_REQUEST_REMOVE_IDENTITY 18
57 #define SSH_REQUEST_REMOVE_ALL_IDENTITIES 19
58 #define SSH_REQUEST_LOCK 22
59 #define SSH_REQUEST_UNLOCK 23
60 #define SSH_REQUEST_ADD_ID_CONSTRAINED 25
63 #define SSH_OPT_CONSTRAIN_LIFETIME 1
64 #define SSH_OPT_CONSTRAIN_CONFIRM 2
67 #define SSH_RESPONSE_SUCCESS 6
68 #define SSH_RESPONSE_FAILURE 5
69 #define SSH_RESPONSE_IDENTITIES_ANSWER 12
70 #define SSH_RESPONSE_SIGN_RESPONSE 14
72 /* Other constants. */
73 #define SSH_DSA_SIGNATURE_PADDING 20
74 #define SSH_DSA_SIGNATURE_ELEMS 2
75 #define SPEC_FLAG_USE_PKCS1V2 (1 << 0)
76 #define SPEC_FLAG_IS_ECDSA (1 << 1)
77 #define SPEC_FLAG_IS_EdDSA (1 << 2) /*(lowercase 'd' on purpose.)*/
78 #define SPEC_FLAG_WITH_CERT (1 << 7)
80 /* The name of the control file. */
81 #define SSH_CONTROL_FILE_NAME "sshcontrol"
83 /* The blurb we put into the header of a newly created control file. */
84 static const char sshcontrolblurb[] =
85 "# List of allowed ssh keys. Only keys present in this file are used\n"
86 "# in the SSH protocol. The ssh-add tool may add new entries to this\n"
87 "# file to enable them; you may also add them manually. Comment\n"
88 "# lines, like this one, as well as empty lines are ignored. Lines do\n"
89 "# have a certain length limit but this is not serious limitation as\n"
90 "# the format of the entries is fixed and checked by gpg-agent. A\n"
91 "# non-comment line starts with optional white spaces, followed by the\n"
92 "# keygrip of the key given as 40 hex digits, optionally followed by a\n"
93 "# caching TTL in seconds, and another optional field for arbitrary\n"
94 "# flags. Prepend the keygrip with an '!' mark to disable it.\n"
100 /* Return a new uint32 with b0 being the most significant byte and b3
101 being the least significant byte. */
102 #define uint32_construct(b0, b1, b2, b3) \
103 ((b0 << 24) | (b1 << 16) | (b2 << 8) | b3)
112 /* Type for a request handler. */
113 typedef gpg_error_t (*ssh_request_handler_t) (ctrl_t ctrl,
118 struct ssh_key_type_spec;
119 typedef struct ssh_key_type_spec ssh_key_type_spec_t;
121 /* Type, which is used for associating request handlers with the
122 appropriate request IDs. */
123 typedef struct ssh_request_spec
126 ssh_request_handler_t handler;
127 const char *identifier;
128 unsigned int secret_input;
129 } ssh_request_spec_t;
131 /* Type for "key modifier functions", which are necessary since
132 OpenSSH and GnuPG treat key material slightly different. A key
133 modifier is called right after a new key identity has been received
134 in order to "sanitize" the material. */
135 typedef gpg_error_t (*ssh_key_modifier_t) (const char *elems,
138 /* The encoding of a generated signature is dependent on the
139 algorithm; therefore algorithm specific signature encoding
140 functions are necessary. */
141 typedef gpg_error_t (*ssh_signature_encoder_t) (ssh_key_type_spec_t *spec,
142 estream_t signature_blob,
145 /* Type, which is used for boundling all the algorithm specific
146 information together in a single object. */
147 struct ssh_key_type_spec
149 /* Algorithm identifier as used by OpenSSH. */
150 const char *ssh_identifier;
152 /* Human readable name of the algorithm. */
155 /* Algorithm identifier as used by GnuPG. */
156 const char *identifier;
158 /* List of MPI names for secret keys; order matches the one of the
160 const char *elems_key_secret;
162 /* List of MPI names for public keys; order matches the one of the
164 const char *elems_key_public;
166 /* List of MPI names for signature data. */
167 const char *elems_signature;
169 /* List of MPI names for secret keys; order matches the one, which
170 is required by gpg-agent's key access layer. */
171 const char *elems_sexp_order;
173 /* Key modifier function. Key modifier functions are necessary in
174 order to fix any inconsistencies between the representation of
175 keys on the SSH and on the GnuPG side. */
176 ssh_key_modifier_t key_modifier;
178 /* Signature encoder function. Signature encoder functions are
179 necessary since the encoding of signatures depends on the used
181 ssh_signature_encoder_t signature_encoder;
183 /* The name of the ECC curve or NULL. */
184 const char *curve_name;
186 /* The hash algorithm to be used with this key. 0 for using the
195 /* Definition of an object to access the sshcontrol file. */
196 struct ssh_control_file_s
198 char *fname; /* Name of the file. */
199 FILE *fp; /* This is never NULL. */
200 int lnr; /* The current line number. */
202 int valid; /* True if the data of this structure is valid. */
203 int disabled; /* The item is disabled. */
204 int ttl; /* The TTL of the item. */
205 int confirm; /* The confirm flag is set. */
206 char hexgrip[40+1]; /* The hexgrip of the item (uppercase). */
212 static gpg_error_t ssh_handler_request_identities (ctrl_t ctrl,
215 static gpg_error_t ssh_handler_sign_request (ctrl_t ctrl,
218 static gpg_error_t ssh_handler_add_identity (ctrl_t ctrl,
221 static gpg_error_t ssh_handler_remove_identity (ctrl_t ctrl,
224 static gpg_error_t ssh_handler_remove_all_identities (ctrl_t ctrl,
227 static gpg_error_t ssh_handler_lock (ctrl_t ctrl,
230 static gpg_error_t ssh_handler_unlock (ctrl_t ctrl,
234 static gpg_error_t ssh_key_modifier_rsa (const char *elems, gcry_mpi_t *mpis);
235 static gpg_error_t ssh_signature_encoder_rsa (ssh_key_type_spec_t *spec,
236 estream_t signature_blob,
237 gcry_sexp_t signature);
238 static gpg_error_t ssh_signature_encoder_dsa (ssh_key_type_spec_t *spec,
239 estream_t signature_blob,
240 gcry_sexp_t signature);
241 static gpg_error_t ssh_signature_encoder_ecdsa (ssh_key_type_spec_t *spec,
242 estream_t signature_blob,
243 gcry_sexp_t signature);
244 static gpg_error_t ssh_signature_encoder_eddsa (ssh_key_type_spec_t *spec,
245 estream_t signature_blob,
246 gcry_sexp_t signature);
247 static gpg_error_t ssh_key_extract_comment (gcry_sexp_t key, char **comment);
251 /* Global variables. */
254 /* Associating request types with the corresponding request
257 static ssh_request_spec_t request_specs[] =
259 #define REQUEST_SPEC_DEFINE(id, name, secret_input) \
260 { SSH_REQUEST_##id, ssh_handler_##name, #name, secret_input }
262 REQUEST_SPEC_DEFINE (REQUEST_IDENTITIES, request_identities, 1),
263 REQUEST_SPEC_DEFINE (SIGN_REQUEST, sign_request, 0),
264 REQUEST_SPEC_DEFINE (ADD_IDENTITY, add_identity, 1),
265 REQUEST_SPEC_DEFINE (ADD_ID_CONSTRAINED, add_identity, 1),
266 REQUEST_SPEC_DEFINE (REMOVE_IDENTITY, remove_identity, 0),
267 REQUEST_SPEC_DEFINE (REMOVE_ALL_IDENTITIES, remove_all_identities, 0),
268 REQUEST_SPEC_DEFINE (LOCK, lock, 0),
269 REQUEST_SPEC_DEFINE (UNLOCK, unlock, 0)
270 #undef REQUEST_SPEC_DEFINE
274 /* Table holding key type specifications. */
275 static ssh_key_type_spec_t ssh_key_types[] =
278 "ssh-ed25519", "Ed25519", "ecc", "qd", "q", "rs", "qd",
279 NULL, ssh_signature_encoder_eddsa,
280 "Ed25519", 0, SPEC_FLAG_IS_EdDSA
283 "ssh-rsa", "RSA", "rsa", "nedupq", "en", "s", "nedpqu",
284 ssh_key_modifier_rsa, ssh_signature_encoder_rsa,
285 NULL, 0, SPEC_FLAG_USE_PKCS1V2
288 "ssh-dss", "DSA", "dsa", "pqgyx", "pqgy", "rs", "pqgyx",
289 NULL, ssh_signature_encoder_dsa,
293 "ecdsa-sha2-nistp256", "ECDSA", "ecdsa", "qd", "q", "rs", "qd",
294 NULL, ssh_signature_encoder_ecdsa,
295 "nistp256", GCRY_MD_SHA256, SPEC_FLAG_IS_ECDSA
298 "ecdsa-sha2-nistp384", "ECDSA", "ecdsa", "qd", "q", "rs", "qd",
299 NULL, ssh_signature_encoder_ecdsa,
300 "nistp384", GCRY_MD_SHA384, SPEC_FLAG_IS_ECDSA
303 "ecdsa-sha2-nistp521", "ECDSA", "ecdsa", "qd", "q", "rs", "qd",
304 NULL, ssh_signature_encoder_ecdsa,
305 "nistp521", GCRY_MD_SHA512, SPEC_FLAG_IS_ECDSA
308 "ssh-ed25519-cert-v01@openssh.com", "Ed25519",
309 "ecc", "qd", "q", "rs", "qd",
310 NULL, ssh_signature_encoder_eddsa,
311 "Ed25519", 0, SPEC_FLAG_IS_EdDSA | SPEC_FLAG_WITH_CERT
314 "ssh-rsa-cert-v01@openssh.com", "RSA",
315 "rsa", "nedupq", "en", "s", "nedpqu",
316 ssh_key_modifier_rsa, ssh_signature_encoder_rsa,
317 NULL, 0, SPEC_FLAG_USE_PKCS1V2 | SPEC_FLAG_WITH_CERT
320 "ssh-dss-cert-v01@openssh.com", "DSA",
321 "dsa", "pqgyx", "pqgy", "rs", "pqgyx",
322 NULL, ssh_signature_encoder_dsa,
323 NULL, 0, SPEC_FLAG_WITH_CERT | SPEC_FLAG_WITH_CERT
326 "ecdsa-sha2-nistp256-cert-v01@openssh.com", "ECDSA",
327 "ecdsa", "qd", "q", "rs", "qd",
328 NULL, ssh_signature_encoder_ecdsa,
329 "nistp256", GCRY_MD_SHA256, SPEC_FLAG_IS_ECDSA | SPEC_FLAG_WITH_CERT
332 "ecdsa-sha2-nistp384-cert-v01@openssh.com", "ECDSA",
333 "ecdsa", "qd", "q", "rs", "qd",
334 NULL, ssh_signature_encoder_ecdsa,
335 "nistp384", GCRY_MD_SHA384, SPEC_FLAG_IS_ECDSA | SPEC_FLAG_WITH_CERT
338 "ecdsa-sha2-nistp521-cert-v01@openssh.com", "ECDSA",
339 "ecdsa", "qd", "q", "rs", "qd",
340 NULL, ssh_signature_encoder_ecdsa,
341 "nistp521", GCRY_MD_SHA512, SPEC_FLAG_IS_ECDSA | SPEC_FLAG_WITH_CERT
350 General utility functions.
353 /* A secure realloc, i.e. it makes sure to allocate secure memory if A
354 is NULL. This is required because the standard gcry_realloc does
355 not know whether to allocate secure or normal if NULL is passed as
358 realloc_secure (void *a, size_t n)
363 p = gcry_realloc (a, n);
365 p = gcry_malloc_secure (n);
371 /* Create and return a new C-string from DATA/DATA_N (i.e.: add
372 NUL-termination); return NULL on OOM. */
374 make_cstring (const char *data, size_t data_n)
378 s = xtrymalloc (data_n + 1);
381 memcpy (s, data, data_n);
388 /* Lookup the ssh-identifier for the ECC curve CURVE_NAME. Returns
389 NULL if not found. */
391 ssh_identifier_from_curve_name (const char *curve_name)
395 for (i = 0; i < DIM (ssh_key_types); i++)
396 if (ssh_key_types[i].curve_name
397 && !strcmp (ssh_key_types[i].curve_name, curve_name))
398 return ssh_key_types[i].ssh_identifier;
405 Primitive I/O functions.
409 /* Read a byte from STREAM, store it in B. */
411 stream_read_byte (estream_t stream, unsigned char *b)
416 ret = es_fgetc (stream);
419 if (es_ferror (stream))
420 err = gpg_error_from_syserror ();
422 err = gpg_error (GPG_ERR_EOF);
434 /* Write the byte contained in B to STREAM. */
436 stream_write_byte (estream_t stream, unsigned char b)
441 ret = es_fputc (b, stream);
443 err = gpg_error_from_syserror ();
451 /* Read a uint32 from STREAM, store it in UINT32. */
453 stream_read_uint32 (estream_t stream, u32 *uint32)
455 unsigned char buffer[4];
460 ret = es_read (stream, buffer, sizeof (buffer), &bytes_read);
462 err = gpg_error_from_syserror ();
465 if (bytes_read != sizeof (buffer))
466 err = gpg_error (GPG_ERR_EOF);
471 n = uint32_construct (buffer[0], buffer[1], buffer[2], buffer[3]);
480 /* Write the uint32 contained in UINT32 to STREAM. */
482 stream_write_uint32 (estream_t stream, u32 uint32)
484 unsigned char buffer[4];
488 buffer[0] = uint32 >> 24;
489 buffer[1] = uint32 >> 16;
490 buffer[2] = uint32 >> 8;
491 buffer[3] = uint32 >> 0;
493 ret = es_write (stream, buffer, sizeof (buffer), NULL);
495 err = gpg_error_from_syserror ();
502 /* Read SIZE bytes from STREAM into BUFFER. */
504 stream_read_data (estream_t stream, unsigned char *buffer, size_t size)
510 ret = es_read (stream, buffer, size, &bytes_read);
512 err = gpg_error_from_syserror ();
515 if (bytes_read != size)
516 err = gpg_error (GPG_ERR_EOF);
524 /* Skip over SIZE bytes from STREAM. */
526 stream_read_skip (estream_t stream, size_t size)
529 size_t bytes_to_read, bytes_read;
534 bytes_to_read = size;
535 if (bytes_to_read > sizeof buffer)
536 bytes_to_read = sizeof buffer;
538 ret = es_read (stream, buffer, bytes_to_read, &bytes_read);
540 return gpg_error_from_syserror ();
541 else if (bytes_read != bytes_to_read)
542 return gpg_error (GPG_ERR_EOF);
544 size -= bytes_to_read;
552 /* Write SIZE bytes from BUFFER to STREAM. */
554 stream_write_data (estream_t stream, const unsigned char *buffer, size_t size)
559 ret = es_write (stream, buffer, size, NULL);
561 err = gpg_error_from_syserror ();
568 /* Read a binary string from STREAM into STRING, store size of string
569 in STRING_SIZE. Append a hidden nul so that the result may
570 directly be used as a C string. Depending on SECURE use secure
571 memory for STRING. If STRING is NULL do only a dummy read. */
573 stream_read_string (estream_t stream, unsigned int secure,
574 unsigned char **string, u32 *string_size)
577 unsigned char *buffer = NULL;
583 /* Read string length. */
584 err = stream_read_uint32 (stream, &length);
590 /* Allocate space. */
592 buffer = xtrymalloc_secure (length + 1);
594 buffer = xtrymalloc (length + 1);
597 err = gpg_error_from_syserror ();
602 err = stream_read_data (stream, buffer, length);
606 /* Finalize string object. */
610 else /* Dummy read requested. */
612 err = stream_read_skip (stream, length);
618 *string_size = length;
629 /* Read a binary string from STREAM and store it as an opaque MPI at
630 R_MPI, adding 0x40 (this is the prefix for EdDSA key in OpenPGP).
631 Depending on SECURE use secure memory. If the string is too large
632 for key material return an error. */
634 stream_read_blob (estream_t stream, unsigned int secure, gcry_mpi_t *r_mpi)
637 unsigned char *buffer = NULL;
642 /* Read string length. */
643 err = stream_read_uint32 (stream, &length);
647 /* To avoid excessive use of secure memory we check that an MPI is
649 if (length > (4096/8) + 8)
651 log_error (_("ssh keys greater than %d bits are not supported\n"), 4096);
652 err = GPG_ERR_TOO_LARGE;
656 /* Allocate space. */
658 buffer = xtrymalloc_secure (length+1);
660 buffer = xtrymalloc (length+1);
663 err = gpg_error_from_syserror ();
668 err = stream_read_data (stream, buffer + 1, length);
673 *r_mpi = gcry_mpi_set_opaque (NULL, buffer, 8*(length+1));
682 /* Read a C-string from STREAM, store copy in STRING. */
684 stream_read_cstring (estream_t stream, char **string)
687 unsigned char *buffer;
689 err = stream_read_string (stream, 0, &buffer, NULL);
691 *string = (char *)buffer;
696 /* Write a binary string from STRING of size STRING_N to STREAM. */
698 stream_write_string (estream_t stream,
699 const unsigned char *string, u32 string_n)
703 err = stream_write_uint32 (stream, string_n);
707 err = stream_write_data (stream, string, string_n);
714 /* Write a C-string from STRING to STREAM. */
716 stream_write_cstring (estream_t stream, const char *string)
720 err = stream_write_string (stream,
721 (const unsigned char *) string, strlen (string));
726 /* Read an MPI from STREAM, store it in MPINT. Depending on SECURE
727 use secure memory. */
729 stream_read_mpi (estream_t stream, unsigned int secure, gcry_mpi_t *mpint)
731 unsigned char *mpi_data;
738 err = stream_read_string (stream, secure, &mpi_data, &mpi_data_size);
742 /* To avoid excessive use of secure memory we check that an MPI is
744 if (mpi_data_size > 520)
746 log_error (_("ssh keys greater than %d bits are not supported\n"), 4096);
747 err = GPG_ERR_TOO_LARGE;
751 err = gcry_mpi_scan (&mpi, GCRYMPI_FMT_STD, mpi_data, mpi_data_size, NULL);
764 /* Write the MPI contained in MPINT to STREAM. */
766 stream_write_mpi (estream_t stream, gcry_mpi_t mpint)
768 unsigned char *mpi_buffer;
774 err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &mpi_buffer, &mpi_buffer_n, mpint);
778 err = stream_write_string (stream, mpi_buffer, mpi_buffer_n);
788 /* Copy data from SRC to DST until EOF is reached. */
790 stream_copy (estream_t dst, estream_t src)
800 ret = es_read (src, buffer, sizeof (buffer), &bytes_read);
801 if (ret || (! bytes_read))
804 err = gpg_error_from_syserror ();
807 ret = es_write (dst, buffer, bytes_read, NULL);
810 err = gpg_error_from_syserror ();
819 /* Read the content of the file specified by FILENAME into a newly
820 create buffer, which is to be stored in BUFFER; store length of
821 buffer in BUFFER_N. */
823 file_to_buffer (const char *filename, unsigned char **buffer, size_t *buffer_n)
825 unsigned char *buffer_new;
837 stream = es_fopen (filename, "rb");
840 err = gpg_error_from_syserror ();
844 ret = fstat (es_fileno (stream), &statbuf);
847 err = gpg_error_from_syserror ();
851 buffer_new = xtrymalloc (statbuf.st_size);
854 err = gpg_error_from_syserror ();
858 err = stream_read_data (stream, buffer_new, statbuf.st_size);
862 *buffer = buffer_new;
863 *buffer_n = statbuf.st_size;
879 /* Open the ssh control file and create it if not available. With
880 APPEND passed as true the file will be opened in append mode,
881 otherwise in read only mode. On success 0 is returned and a new
882 control file object stored at R_CF. On error an error code is
883 returned and NULL is stored at R_CF. */
885 open_control_file (ssh_control_file_t *r_cf, int append)
888 ssh_control_file_t cf;
890 cf = xtrycalloc (1, sizeof *cf);
893 err = gpg_error_from_syserror ();
897 /* Note: As soon as we start to use non blocking functions here
898 (i.e. where Pth might switch threads) we need to employ a
900 cf->fname = make_filename_try (opt.homedir, SSH_CONTROL_FILE_NAME, NULL);
903 err = gpg_error_from_syserror ();
906 /* FIXME: With "a+" we are not able to check whether this will
907 be created and thus the blurb needs to be written first. */
908 cf->fp = fopen (cf->fname, append? "a+":"r");
909 if (!cf->fp && errno == ENOENT)
911 estream_t stream = es_fopen (cf->fname, "wx,mode=-rw-r");
914 err = gpg_error_from_syserror ();
915 log_error (_("can't create '%s': %s\n"),
916 cf->fname, gpg_strerror (err));
919 es_fputs (sshcontrolblurb, stream);
921 cf->fp = fopen (cf->fname, append? "a+":"r");
926 err = gpg_error_from_syserror ();
927 log_error (_("can't open '%s': %s\n"),
928 cf->fname, gpg_strerror (err));
950 rewind_control_file (ssh_control_file_t cf)
952 fseek (cf->fp, 0, SEEK_SET);
959 close_control_file (ssh_control_file_t cf)
970 /* Read the next line from the control file and store the data in CF.
971 Returns 0 on success, GPG_ERR_EOF on EOF, or other error codes. */
973 read_control_file_item (ssh_control_file_t cf)
976 char *p, *pend, line[256];
984 if (!fgets (line, DIM(line)-1, cf->fp) )
987 return gpg_error (GPG_ERR_EOF);
988 return gpg_error_from_syserror ();
992 if (!*line || line[strlen(line)-1] != '\n')
994 /* Eat until end of line */
995 while ( (c=getc (cf->fp)) != EOF && c != '\n')
997 return gpg_error (*line? GPG_ERR_LINE_TOO_LONG
998 : GPG_ERR_INCOMPLETE_LINE);
1001 /* Allow for empty lines and spaces */
1002 for (p=line; spacep (p); p++)
1005 while (!*p || *p == '\n' || *p == '#');
1007 cf->item.disabled = 0;
1010 cf->item.disabled = 1;
1011 for (p++; spacep (p); p++)
1015 for (i=0; hexdigitp (p) && i < 40; p++, i++)
1016 cf->item.hexgrip[i] = (*p >= 'a'? (*p & 0xdf): *p);
1017 cf->item.hexgrip[i] = 0;
1018 if (i != 40 || !(spacep (p) || *p == '\n'))
1020 log_error ("%s:%d: invalid formatted line\n", cf->fname, cf->lnr);
1021 return gpg_error (GPG_ERR_BAD_DATA);
1024 ttl = strtol (p, &pend, 10);
1026 if (!(spacep (p) || *p == '\n') || (int)ttl < -1)
1028 log_error ("%s:%d: invalid TTL value; assuming 0\n", cf->fname, cf->lnr);
1033 /* Now check for key-value pairs of the form NAME[=VALUE]. */
1034 cf->item.confirm = 0;
1037 for (; spacep (p) && *p != '\n'; p++)
1039 if (!*p || *p == '\n')
1041 n = strcspn (p, "= \t\n");
1044 log_error ("%s:%d: assigning a value to a flag is not yet supported; "
1045 "flag ignored\n", cf->fname, cf->lnr);
1048 else if (n == 7 && !memcmp (p, "confirm", 7))
1050 cf->item.confirm = 1;
1053 log_error ("%s:%d: invalid flag '%.*s'; ignored\n",
1054 cf->fname, cf->lnr, n, p);
1058 /* log_debug ("%s:%d: grip=%s ttl=%d%s%s\n", */
1059 /* cf->fname, cf->lnr, */
1060 /* cf->item.hexgrip, cf->item.ttl, */
1061 /* cf->item.disabled? " disabled":"", */
1062 /* cf->item.confirm? " confirm":""); */
1065 return 0; /* Okay: valid entry found. */
1070 /* Search the control file CF from the beginning until a matching
1071 HEXGRIP is found; return success in this case and store true at
1072 DISABLED if the found key has been disabled. If R_TTL is not NULL
1073 a specified TTL for that key is stored there. If R_CONFIRM is not
1074 NULL it is set to 1 if the key has the confirm flag set. */
1076 search_control_file (ssh_control_file_t cf, const char *hexgrip,
1077 int *r_disabled, int *r_ttl, int *r_confirm)
1081 assert (strlen (hexgrip) == 40 );
1090 rewind_control_file (cf);
1091 while (!(err=read_control_file_item (cf)))
1093 if (!cf->item.valid)
1094 continue; /* Should not happen. */
1095 if (!strcmp (hexgrip, cf->item.hexgrip))
1101 *r_disabled = cf->item.disabled;
1103 *r_ttl = cf->item.ttl;
1105 *r_confirm = cf->item.confirm;
1112 /* Add an entry to the control file to mark the key with the keygrip
1113 HEXGRIP as usable for SSH; i.e. it will be returned when ssh asks
1114 for it. FMTFPR is the fingerprint string. This function is in
1115 general used to add a key received through the ssh-add function.
1116 We can assume that the user wants to allow ssh using this key. */
1118 add_control_entry (ctrl_t ctrl, ssh_key_type_spec_t *spec,
1119 const char *hexgrip, const char *fmtfpr,
1120 int ttl, int confirm)
1123 ssh_control_file_t cf;
1128 err = open_control_file (&cf, 1);
1132 err = search_control_file (cf, hexgrip, &disabled, NULL, NULL);
1133 if (err && gpg_err_code(err) == GPG_ERR_EOF)
1136 time_t atime = time (NULL);
1138 /* Not yet in the file - add it. Because the file has been
1139 opened in append mode, we simply need to write to it. */
1140 tp = localtime (&atime);
1142 ("# %s key added on: %04d-%02d-%02d %02d:%02d:%02d\n"
1143 "# MD5 Fingerprint: %s\n"
1146 1900+tp->tm_year, tp->tm_mon+1, tp->tm_mday,
1147 tp->tm_hour, tp->tm_min, tp->tm_sec,
1148 fmtfpr, hexgrip, ttl, confirm? " confirm":"");
1151 close_control_file (cf);
1156 /* Scan the sshcontrol file and return the TTL. */
1158 ttl_from_sshcontrol (const char *hexgrip)
1160 ssh_control_file_t cf;
1163 if (!hexgrip || strlen (hexgrip) != 40)
1164 return 0; /* Wrong input: Use global default. */
1166 if (open_control_file (&cf, 0))
1167 return 0; /* Error: Use the global default TTL. */
1169 if (search_control_file (cf, hexgrip, &disabled, &ttl, NULL)
1171 ttl = 0; /* Use the global default if not found or disabled. */
1173 close_control_file (cf);
1179 /* Scan the sshcontrol file and return the confirm flag. */
1181 confirm_flag_from_sshcontrol (const char *hexgrip)
1183 ssh_control_file_t cf;
1184 int disabled, confirm;
1186 if (!hexgrip || strlen (hexgrip) != 40)
1187 return 1; /* Wrong input: Better ask for confirmation. */
1189 if (open_control_file (&cf, 0))
1190 return 1; /* Error: Better ask for confirmation. */
1192 if (search_control_file (cf, hexgrip, &disabled, NULL, &confirm)
1194 confirm = 0; /* If not found or disabled, there is no reason to
1195 ask for confirmation. */
1197 close_control_file (cf);
1205 /* Open the ssh control file for reading. This is a public version of
1206 open_control_file. The caller must use ssh_close_control_file to
1207 release the retruned handle. */
1209 ssh_open_control_file (void)
1211 ssh_control_file_t cf;
1213 /* Then look at all the registered and non-disabled keys. */
1214 if (open_control_file (&cf, 0))
1219 /* Close an ssh control file handle. This is the public version of
1220 close_control_file. CF may be NULL. */
1222 ssh_close_control_file (ssh_control_file_t cf)
1224 close_control_file (cf);
1227 /* Read the next item from the ssh control file. The function returns
1228 0 if a item was read, GPG_ERR_EOF on eof or another error value.
1229 R_HEXGRIP shall either be null or a BUFFER of at least 41 byte.
1230 R_DISABLED, R_TTLm and R_CONFIRM return flags from the control
1231 file; they are only set on success. */
1233 ssh_read_control_file (ssh_control_file_t cf,
1235 int *r_disabled, int *r_ttl, int *r_confirm)
1240 err = read_control_file_item (cf);
1241 while (!err && !cf->item.valid);
1245 strcpy (r_hexgrip, cf->item.hexgrip);
1247 *r_disabled = cf->item.disabled;
1249 *r_ttl = cf->item.ttl;
1251 *r_confirm = cf->item.confirm;
1257 /* Search for a key with HEXGRIP in sshcontrol and return all
1260 ssh_search_control_file (ssh_control_file_t cf,
1261 const char *hexgrip,
1262 int *r_disabled, int *r_ttl, int *r_confirm)
1269 /* We need to make sure that HEXGRIP is all uppercase. The easiest
1270 way to do this and also check its length is by copying to a
1272 for (i=0, s=hexgrip; i < 40 && *s; s++, i++)
1273 uphexgrip[i] = *s >= 'a'? (*s & 0xdf): *s;
1276 err = gpg_error (GPG_ERR_INV_LENGTH);
1278 err = search_control_file (cf, uphexgrip, r_disabled, r_ttl, r_confirm);
1279 if (gpg_err_code (err) == GPG_ERR_EOF)
1280 err = gpg_error (GPG_ERR_NOT_FOUND);
1293 /* Free the list of MPIs MPI_LIST. */
1295 mpint_list_free (gcry_mpi_t *mpi_list)
1301 for (i = 0; mpi_list[i]; i++)
1302 gcry_mpi_release (mpi_list[i]);
1307 /* Receive key material MPIs from STREAM according to KEY_SPEC;
1308 depending on SECRET expect a public key or secret key. CERT is the
1309 certificate blob used if KEY_SPEC indicates the certificate format;
1310 it needs to be positioned to the end of the nonce. The newly
1311 allocated list of MPIs is stored in MPI_LIST. Returns usual error
1314 ssh_receive_mpint_list (estream_t stream, int secret,
1315 ssh_key_type_spec_t *spec, estream_t cert,
1316 gcry_mpi_t **mpi_list)
1318 const char *elems_public;
1319 unsigned int elems_n;
1322 gcry_mpi_t *mpis = NULL;
1323 gpg_error_t err = 0;
1327 elems = spec->elems_key_secret;
1329 elems = spec->elems_key_public;
1330 elems_n = strlen (elems);
1331 elems_public = spec->elems_key_public;
1333 /* Check that either noth, CERT and the WITH_CERT flag, are given or
1335 if (!(!!(spec->flags & SPEC_FLAG_WITH_CERT) ^ !cert))
1337 err = gpg_error (GPG_ERR_INV_CERT_OBJ);
1341 mpis = xtrycalloc (elems_n + 1, sizeof *mpis );
1344 err = gpg_error_from_syserror ();
1349 for (i = 0; i < elems_n; i++)
1352 elem_is_secret = !strchr (elems_public, elems[i]);
1354 if (cert && !elem_is_secret)
1355 err = stream_read_mpi (cert, elem_is_secret, &mpis[i]);
1357 err = stream_read_mpi (stream, elem_is_secret, &mpis[i]);
1367 mpint_list_free (mpis);
1374 /* Key modifier function for RSA. */
1376 ssh_key_modifier_rsa (const char *elems, gcry_mpi_t *mpis)
1382 if (strcmp (elems, "nedupq"))
1383 /* Modifying only necessary for secret keys. */
1390 if (gcry_mpi_cmp (p, q) > 0)
1392 /* P shall be smaller then Q! Swap primes. iqmp becomes u. */
1400 /* U needs to be recomputed. */
1401 gcry_mpi_invm (u, p, q);
1408 /* Signature encoder function for RSA. */
1410 ssh_signature_encoder_rsa (ssh_key_type_spec_t *spec,
1411 estream_t signature_blob,
1412 gcry_sexp_t s_signature)
1414 gpg_error_t err = 0;
1415 gcry_sexp_t valuelist = NULL;
1416 gcry_sexp_t sublist = NULL;
1417 gcry_mpi_t sig_value = NULL;
1418 gcry_mpi_t *mpis = NULL;
1423 unsigned char *data;
1427 valuelist = gcry_sexp_nth (s_signature, 1);
1430 err = gpg_error (GPG_ERR_INV_SEXP);
1434 elems = spec->elems_signature;
1435 elems_n = strlen (elems);
1437 mpis = xtrycalloc (elems_n + 1, sizeof *mpis);
1440 err = gpg_error_from_syserror ();
1444 for (i = 0; i < elems_n; i++)
1446 sublist = gcry_sexp_find_token (valuelist, spec->elems_signature + i, 1);
1449 err = gpg_error (GPG_ERR_INV_SEXP);
1453 sig_value = gcry_sexp_nth_mpi (sublist, 1, GCRYMPI_FMT_USG);
1456 err = gpg_error (GPG_ERR_INTERNAL); /* FIXME? */
1459 gcry_sexp_release (sublist);
1462 mpis[i] = sig_value;
1470 err = gcry_mpi_aprint (GCRYMPI_FMT_USG, &data, &data_n, s);
1474 err = stream_write_string (signature_blob, data, data_n);
1478 gcry_sexp_release (valuelist);
1479 gcry_sexp_release (sublist);
1480 mpint_list_free (mpis);
1485 /* Signature encoder function for DSA. */
1487 ssh_signature_encoder_dsa (ssh_key_type_spec_t *spec,
1488 estream_t signature_blob,
1489 gcry_sexp_t s_signature)
1491 gpg_error_t err = 0;
1492 gcry_sexp_t valuelist = NULL;
1493 gcry_sexp_t sublist = NULL;
1494 gcry_mpi_t sig_value = NULL;
1495 gcry_mpi_t *mpis = NULL;
1500 unsigned char buffer[SSH_DSA_SIGNATURE_PADDING * SSH_DSA_SIGNATURE_ELEMS];
1501 unsigned char *data = NULL;
1504 valuelist = gcry_sexp_nth (s_signature, 1);
1507 err = gpg_error (GPG_ERR_INV_SEXP);
1511 elems = spec->elems_signature;
1512 elems_n = strlen (elems);
1514 mpis = xtrycalloc (elems_n + 1, sizeof *mpis);
1517 err = gpg_error_from_syserror ();
1521 for (i = 0; i < elems_n; i++)
1523 sublist = gcry_sexp_find_token (valuelist, spec->elems_signature + i, 1);
1526 err = gpg_error (GPG_ERR_INV_SEXP);
1530 sig_value = gcry_sexp_nth_mpi (sublist, 1, GCRYMPI_FMT_USG);
1533 err = gpg_error (GPG_ERR_INTERNAL); /* FIXME? */
1536 gcry_sexp_release (sublist);
1539 mpis[i] = sig_value;
1544 /* DSA specific code. */
1546 /* FIXME: Why this complicated code? Why collecting boths mpis in a
1547 buffer instead of writing them out one after the other? */
1548 for (i = 0; i < 2; i++)
1550 err = gcry_mpi_aprint (GCRYMPI_FMT_USG, &data, &data_n, mpis[i]);
1554 if (data_n > SSH_DSA_SIGNATURE_PADDING)
1556 err = gpg_error (GPG_ERR_INTERNAL); /* FIXME? */
1560 memset (buffer + (i * SSH_DSA_SIGNATURE_PADDING), 0,
1561 SSH_DSA_SIGNATURE_PADDING - data_n);
1562 memcpy (buffer + (i * SSH_DSA_SIGNATURE_PADDING)
1563 + (SSH_DSA_SIGNATURE_PADDING - data_n), data, data_n);
1571 err = stream_write_string (signature_blob, buffer, sizeof (buffer));
1575 gcry_sexp_release (valuelist);
1576 gcry_sexp_release (sublist);
1577 mpint_list_free (mpis);
1582 /* Signature encoder function for ECDSA. */
1584 ssh_signature_encoder_ecdsa (ssh_key_type_spec_t *spec,
1585 estream_t stream, gcry_sexp_t s_signature)
1587 gpg_error_t err = 0;
1588 gcry_sexp_t valuelist = NULL;
1589 gcry_sexp_t sublist = NULL;
1590 gcry_mpi_t sig_value = NULL;
1591 gcry_mpi_t *mpis = NULL;
1596 unsigned char *data[2] = {NULL, NULL};
1600 valuelist = gcry_sexp_nth (s_signature, 1);
1603 err = gpg_error (GPG_ERR_INV_SEXP);
1607 elems = spec->elems_signature;
1608 elems_n = strlen (elems);
1610 mpis = xtrycalloc (elems_n + 1, sizeof *mpis);
1613 err = gpg_error_from_syserror ();
1617 for (i = 0; i < elems_n; i++)
1619 sublist = gcry_sexp_find_token (valuelist, spec->elems_signature + i, 1);
1622 err = gpg_error (GPG_ERR_INV_SEXP);
1626 sig_value = gcry_sexp_nth_mpi (sublist, 1, GCRYMPI_FMT_USG);
1629 err = gpg_error (GPG_ERR_INTERNAL); /* FIXME? */
1632 gcry_sexp_release (sublist);
1635 mpis[i] = sig_value;
1640 /* ECDSA specific */
1643 for (i = 0; i < DIM(data); i++)
1645 err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &data[i], &data_n[i], mpis[i]);
1648 innerlen += 4 + data_n[i];
1651 err = stream_write_uint32 (stream, innerlen);
1655 for (i = 0; i < DIM(data); i++)
1657 err = stream_write_string (stream, data[i], data_n[i]);
1663 for (i = 0; i < DIM(data); i++)
1665 gcry_sexp_release (valuelist);
1666 gcry_sexp_release (sublist);
1667 mpint_list_free (mpis);
1672 /* Signature encoder function for EdDSA. */
1674 ssh_signature_encoder_eddsa (ssh_key_type_spec_t *spec,
1675 estream_t stream, gcry_sexp_t s_signature)
1677 gpg_error_t err = 0;
1678 gcry_sexp_t valuelist = NULL;
1679 gcry_sexp_t sublist = NULL;
1684 unsigned char *data[2] = {NULL, NULL};
1686 size_t totallen = 0;
1688 valuelist = gcry_sexp_nth (s_signature, 1);
1691 err = gpg_error (GPG_ERR_INV_SEXP);
1695 elems = spec->elems_signature;
1696 elems_n = strlen (elems);
1698 if (elems_n != DIM(data))
1700 err = gpg_error (GPG_ERR_INV_SEXP);
1704 for (i = 0; i < DIM(data); i++)
1706 sublist = gcry_sexp_find_token (valuelist, spec->elems_signature + i, 1);
1709 err = gpg_error (GPG_ERR_INV_SEXP);
1713 data[i] = gcry_sexp_nth_buffer (sublist, 1, &data_n[i]);
1716 err = gpg_error (GPG_ERR_INTERNAL); /* FIXME? */
1719 totallen += data_n[i];
1720 gcry_sexp_release (sublist);
1726 err = stream_write_uint32 (stream, totallen);
1730 for (i = 0; i < DIM(data); i++)
1732 err = stream_write_data (stream, data[i], data_n[i]);
1738 for (i = 0; i < DIM(data); i++)
1740 gcry_sexp_release (valuelist);
1741 gcry_sexp_release (sublist);
1751 /* This function constructs a new S-Expression for the key identified
1752 by the KEY_SPEC, SECRET, CURVE_NAME, MPIS, and COMMENT, which is to
1753 be stored at R_SEXP. Returns an error code. */
1755 sexp_key_construct (gcry_sexp_t *r_sexp,
1756 ssh_key_type_spec_t key_spec, int secret,
1757 const char *curve_name, gcry_mpi_t *mpis,
1758 const char *comment)
1761 gcry_sexp_t sexp_new = NULL;
1762 void *formatbuf = NULL;
1763 void **arg_list = NULL;
1764 estream_t format = NULL;
1767 if ((key_spec.flags & SPEC_FLAG_IS_EdDSA))
1769 /* It is much easier and more readable to use a separate code
1772 err = gpg_error (GPG_ERR_INV_CURVE);
1773 else if (!mpis[0] || !gcry_mpi_get_flag (mpis[0], GCRYMPI_FLAG_OPAQUE))
1774 err = gpg_error (GPG_ERR_BAD_PUBKEY);
1777 || !gcry_mpi_get_flag (mpis[1], GCRYMPI_FLAG_OPAQUE)))
1778 err = gpg_error (GPG_ERR_BAD_SECKEY);
1780 err = gcry_sexp_build (&sexp_new, NULL,
1781 "(private-key(ecc(curve %s)"
1782 "(flags eddsa)(q %m)(d %m))"
1786 comment? comment:"");
1788 err = gcry_sexp_build (&sexp_new, NULL,
1789 "(public-key(ecc(curve %s)"
1790 "(flags eddsa)(q %m))"
1794 comment? comment:"");
1798 const char *key_identifier[] = { "public-key", "private-key" };
1805 elems = key_spec.elems_sexp_order;
1807 elems = key_spec.elems_key_public;
1808 elems_n = strlen (elems);
1810 format = es_fopenmem (0, "a+b");
1813 err = gpg_error_from_syserror ();
1817 /* Key identifier, algorithm identifier, mpis, comment, and a NULL
1819 arg_list = xtrymalloc (sizeof (*arg_list) * (2 + 1 + elems_n + 1 + 1));
1822 err = gpg_error_from_syserror ();
1827 es_fputs ("(%s(%s", format);
1828 arg_list[arg_idx++] = &key_identifier[secret];
1829 arg_list[arg_idx++] = &key_spec.identifier;
1832 es_fputs ("(curve%s)", format);
1833 arg_list[arg_idx++] = &curve_name;
1836 for (i = 0; i < elems_n; i++)
1838 es_fprintf (format, "(%c%%m)", elems[i]);
1841 for (j = 0; j < elems_n; j++)
1842 if (key_spec.elems_key_secret[j] == elems[i])
1847 arg_list[arg_idx++] = &mpis[j];
1849 es_fputs (")(comment%s))", format);
1850 arg_list[arg_idx++] = &comment;
1851 arg_list[arg_idx] = NULL;
1853 es_putc (0, format);
1854 if (es_ferror (format))
1856 err = gpg_error_from_syserror ();
1859 if (es_fclose_snatch (format, &formatbuf, NULL))
1861 err = gpg_error_from_syserror ();
1866 err = gcry_sexp_build_array (&sexp_new, NULL, formatbuf, arg_list);
1881 /* This function extracts the key from the s-expression SEXP according
1882 to KEY_SPEC and stores it in ssh format at (R_BLOB, R_BLOBLEN). If
1883 WITH_SECRET is true, the secret key parts are also extracted if
1884 possible. Returns 0 on success or an error code. Note that data
1885 stored at R_BLOB must be freed using es_free! */
1887 ssh_key_to_blob (gcry_sexp_t sexp, int with_secret,
1888 ssh_key_type_spec_t key_spec,
1889 void **r_blob, size_t *r_blob_size)
1891 gpg_error_t err = 0;
1892 gcry_sexp_t value_list = NULL;
1893 gcry_sexp_t value_pair = NULL;
1894 char *curve_name = NULL;
1895 estream_t stream = NULL;
1898 const char *elems, *p_elems;
1905 stream = es_fopenmem (0, "r+b");
1908 err = gpg_error_from_syserror ();
1912 /* Get the type of the key extpression. */
1913 data = gcry_sexp_nth_data (sexp, 0, &datalen);
1916 err = gpg_error (GPG_ERR_INV_SEXP);
1920 if ((datalen == 10 && !strncmp (data, "public-key", 10))
1921 || (datalen == 21 && !strncmp (data, "protected-private-key", 21))
1922 || (datalen == 20 && !strncmp (data, "shadowed-private-key", 20)))
1923 elems = key_spec.elems_key_public;
1924 else if (datalen == 11 && !strncmp (data, "private-key", 11))
1925 elems = with_secret? key_spec.elems_key_secret : key_spec.elems_key_public;
1928 err = gpg_error (GPG_ERR_INV_SEXP);
1932 /* Get the algorithm identifier. */
1933 value_list = gcry_sexp_find_token (sexp, key_spec.identifier, 0);
1936 err = gpg_error (GPG_ERR_INV_SEXP);
1940 /* Write the ssh algorithm identifier. */
1941 if ((key_spec.flags & SPEC_FLAG_IS_ECDSA))
1943 /* Parse the "curve" parameter. We currently expect the curve
1944 name for ECC and not the parameters of the curve. This can
1945 easily be changed but then we need to find the curve name
1946 from the parameters using gcry_pk_get_curve. */
1948 const char *sshname;
1950 gcry_sexp_release (value_pair);
1951 value_pair = gcry_sexp_find_token (value_list, "curve", 5);
1954 err = gpg_error (GPG_ERR_INV_CURVE);
1957 curve_name = gcry_sexp_nth_string (value_pair, 1);
1960 err = gpg_error (GPG_ERR_INV_CURVE); /* (Or out of core.) */
1964 /* Fixme: The mapping should be done by using gcry_pk_get_curve
1965 et al to iterate over all name aliases. */
1966 if (!strcmp (curve_name, "NIST P-256"))
1967 mapped = "nistp256";
1968 else if (!strcmp (curve_name, "NIST P-384"))
1969 mapped = "nistp384";
1970 else if (!strcmp (curve_name, "NIST P-521"))
1971 mapped = "nistp521";
1977 curve_name = xtrystrdup (mapped);
1980 err = gpg_error_from_syserror ();
1985 sshname = ssh_identifier_from_curve_name (curve_name);
1988 err = gpg_error (GPG_ERR_UNKNOWN_CURVE);
1991 err = stream_write_cstring (stream, sshname);
1994 err = stream_write_cstring (stream, curve_name);
2000 /* Note: This is also used for EdDSA. */
2001 err = stream_write_cstring (stream, key_spec.ssh_identifier);
2006 /* Write the parameters. */
2007 for (p_elems = elems; *p_elems; p_elems++)
2009 gcry_sexp_release (value_pair);
2010 value_pair = gcry_sexp_find_token (value_list, p_elems, 1);
2013 err = gpg_error (GPG_ERR_INV_SEXP);
2016 if ((key_spec.flags & SPEC_FLAG_IS_EdDSA))
2019 data = gcry_sexp_nth_data (value_pair, 1, &datalen);
2022 err = gpg_error (GPG_ERR_INV_SEXP);
2025 if (*p_elems == 'q' && datalen)
2026 { /* Remove the prefix 0x40. */
2030 err = stream_write_string (stream, data, datalen);
2038 /* Note that we need to use STD format; i.e. prepend a 0x00
2039 to indicate a positive number if the high bit is set. */
2040 mpi = gcry_sexp_nth_mpi (value_pair, 1, GCRYMPI_FMT_STD);
2043 err = gpg_error (GPG_ERR_INV_SEXP);
2046 err = stream_write_mpi (stream, mpi);
2047 gcry_mpi_release (mpi);
2053 if (es_fclose_snatch (stream, &blob, &blob_size))
2055 err = gpg_error_from_syserror ();
2062 *r_blob_size = blob_size;
2065 gcry_sexp_release (value_list);
2066 gcry_sexp_release (value_pair);
2074 /* Extract the car from SEXP, and create a newly created C-string
2075 which is to be stored in IDENTIFIER. */
2077 sexp_extract_identifier (gcry_sexp_t sexp, char **identifier)
2079 char *identifier_new;
2080 gcry_sexp_t sublist;
2085 identifier_new = NULL;
2088 sublist = gcry_sexp_nth (sexp, 1);
2091 err = gpg_error (GPG_ERR_INV_SEXP);
2095 data = gcry_sexp_nth_data (sublist, 0, &data_n);
2098 err = gpg_error (GPG_ERR_INV_SEXP);
2102 identifier_new = make_cstring (data, data_n);
2103 if (! identifier_new)
2105 err = gpg_err_code_from_errno (errno);
2109 *identifier = identifier_new;
2113 gcry_sexp_release (sublist);
2126 /* Search for a key specification entry. If SSH_NAME is not NULL,
2127 search for an entry whose "ssh_name" is equal to SSH_NAME;
2128 otherwise, search for an entry whose "name" is equal to NAME.
2129 Store found entry in SPEC on success, return error otherwise. */
2131 ssh_key_type_lookup (const char *ssh_name, const char *name,
2132 ssh_key_type_spec_t *spec)
2137 /* FIXME: Although this sees to work, it not be correct if the
2138 lookup is done via name which might be "ecc" but actually it need
2139 to check the flags to see whether it is eddsa or ecdsa. Maybe
2140 the entire parameter controlled logic is too complicated and we
2141 would do better by just switching on the ssh_name. */
2142 for (i = 0; i < DIM (ssh_key_types); i++)
2143 if ((ssh_name && (! strcmp (ssh_name, ssh_key_types[i].ssh_identifier)))
2144 || (name && (! strcmp (name, ssh_key_types[i].identifier))))
2147 if (i == DIM (ssh_key_types))
2148 err = gpg_error (GPG_ERR_NOT_FOUND);
2151 *spec = ssh_key_types[i];
2159 /* Receive a key from STREAM, according to the key specification given
2160 as KEY_SPEC. Depending on SECRET, receive a secret or a public
2161 key. If READ_COMMENT is true, receive a comment string as well.
2162 Constructs a new S-Expression from received data and stores it in
2163 KEY_NEW. Returns zero on success or an error code. */
2165 ssh_receive_key (estream_t stream, gcry_sexp_t *key_new, int secret,
2166 int read_comment, ssh_key_type_spec_t *key_spec)
2169 char *key_type = NULL;
2170 char *comment = NULL;
2171 estream_t cert = NULL;
2172 gcry_sexp_t key = NULL;
2173 ssh_key_type_spec_t spec;
2174 gcry_mpi_t *mpi_list = NULL;
2176 char *curve_name = NULL;
2179 err = stream_read_cstring (stream, &key_type);
2183 err = ssh_key_type_lookup (key_type, NULL, &spec);
2187 if ((spec.flags & SPEC_FLAG_WITH_CERT))
2189 /* This is an OpenSSH certificate+private key. The certificate
2190 is an SSH string and which we store in an estream object. */
2191 unsigned char *buffer;
2193 char *cert_key_type;
2195 err = stream_read_string (stream, 0, &buffer, &buflen);
2198 cert = es_fopenmem_init (0, "rb", buffer, buflen);
2202 err = gpg_error_from_syserror ();
2206 /* Check that the key type matches. */
2207 err = stream_read_cstring (cert, &cert_key_type);
2210 if (strcmp (cert_key_type, key_type) )
2212 xfree (cert_key_type);
2213 log_error ("key types in received ssh certificate do not match\n");
2214 err = gpg_error (GPG_ERR_INV_CERT_OBJ);
2217 xfree (cert_key_type);
2219 /* Skip the nonce. */
2220 err = stream_read_string (cert, 0, NULL, NULL);
2225 if ((spec.flags & SPEC_FLAG_IS_EdDSA))
2227 /* The format of an EdDSA key is:
2228 * string key_type ("ssh-ed25519")
2230 * string private_key
2232 * Note that the private key is the concatenation of the private
2233 * key with the public key. Thus theres are 64 bytes; however
2234 * we only want the real 32 byte private key - Libgcrypt expects
2237 mpi_list = xtrycalloc (3, sizeof *mpi_list);
2240 err = gpg_error_from_syserror ();
2244 err = stream_read_blob (cert? cert : stream, 0, &mpi_list[0]);
2250 unsigned char *buffer;
2252 /* Read string length. */
2253 err = stream_read_uint32 (stream, &len);
2256 if (len != 32 && len != 64)
2258 err = gpg_error (GPG_ERR_BAD_SECKEY);
2261 buffer = xtrymalloc_secure (32);
2264 err = gpg_error_from_syserror ();
2267 err = stream_read_data (stream, buffer, 32);
2273 mpi_list[1] = gcry_mpi_set_opaque (NULL, buffer, 8*32);
2277 err = stream_read_skip (stream, 32);
2283 else if ((spec.flags & SPEC_FLAG_IS_ECDSA))
2285 /* The format of an ECDSA key is:
2286 * string key_type ("ecdsa-sha2-nistp256" |
2287 * "ecdsa-sha2-nistp384" |
2288 * "ecdsa-sha2-nistp521" )
2289 * string ecdsa_curve_name
2290 * string ecdsa_public_key
2291 * mpint ecdsa_private
2293 * Note that we use the mpint reader instead of the string
2294 * reader for ecsa_public_key. For the certificate variante
2295 * ecdsa_curve_name+ecdsa_public_key are replaced by the
2298 unsigned char *buffer;
2301 err = stream_read_string (cert? cert : stream, 0, &buffer, NULL);
2304 curve_name = buffer;
2305 /* Fixme: Check that curve_name matches the keytype. */
2306 /* Because Libgcrypt < 1.6 has no support for the "nistpNNN"
2307 curve names, we need to translate them here to Libgcrypt's
2309 if (!strcmp (curve_name, "nistp256"))
2310 mapped = "NIST P-256";
2311 else if (!strcmp (curve_name, "nistp384"))
2312 mapped = "NIST P-384";
2313 else if (!strcmp (curve_name, "nistp521"))
2314 mapped = "NIST P-521";
2320 curve_name = xtrystrdup (mapped);
2323 err = gpg_error_from_syserror ();
2328 err = ssh_receive_mpint_list (stream, secret, &spec, cert, &mpi_list);
2334 err = ssh_receive_mpint_list (stream, secret, &spec, cert, &mpi_list);
2341 err = stream_read_cstring (stream, &comment);
2347 elems = spec.elems_key_secret;
2349 elems = spec.elems_key_public;
2351 if (spec.key_modifier)
2353 err = (*spec.key_modifier) (elems, mpi_list);
2358 if ((spec.flags & SPEC_FLAG_IS_EdDSA))
2362 err = gcry_sexp_build (&key, NULL,
2363 "(private-key(ecc(curve \"Ed25519\")"
2364 "(flags eddsa)(q %m)(d %m))"
2366 mpi_list[0], mpi_list[1],
2367 comment? comment:"");
2371 err = gcry_sexp_build (&key, NULL,
2372 "(public-key(ecc(curve \"Ed25519\")"
2373 "(flags eddsa)(q %m))"
2376 comment? comment:"");
2381 err = sexp_key_construct (&key, spec, secret, curve_name, mpi_list,
2382 comment? comment:"");
2393 mpint_list_free (mpi_list);
2402 /* Write the public key from KEY to STREAM in SSH key format. If
2403 OVERRIDE_COMMENT is not NULL, it will be used instead of the
2404 comment stored in the key. */
2406 ssh_send_key_public (estream_t stream, gcry_sexp_t key,
2407 const char *override_comment)
2409 ssh_key_type_spec_t spec;
2410 char *key_type = NULL;
2411 char *comment = NULL;
2416 err = sexp_extract_identifier (key, &key_type);
2420 err = ssh_key_type_lookup (NULL, key_type, &spec);
2424 err = ssh_key_to_blob (key, 0, spec, &blob, &bloblen);
2428 err = stream_write_string (stream, blob, bloblen);
2432 if (override_comment)
2433 err = stream_write_cstring (stream, override_comment);
2436 err = ssh_key_extract_comment (key, &comment);
2438 err = stream_write_cstring (stream, "(none)");
2440 err = stream_write_cstring (stream, comment);
2454 /* Read a public key out of BLOB/BLOB_SIZE according to the key
2455 specification given as KEY_SPEC, storing the new key in KEY_PUBLIC.
2456 Returns zero on success or an error code. */
2458 ssh_read_key_public_from_blob (unsigned char *blob, size_t blob_size,
2459 gcry_sexp_t *key_public,
2460 ssh_key_type_spec_t *key_spec)
2463 estream_t blob_stream;
2465 blob_stream = es_fopenmem (0, "r+b");
2468 err = gpg_error_from_syserror ();
2472 err = stream_write_data (blob_stream, blob, blob_size);
2476 err = es_fseek (blob_stream, 0, SEEK_SET);
2480 err = ssh_receive_key (blob_stream, key_public, 0, 0, key_spec);
2483 es_fclose (blob_stream);
2489 /* This function calculates the key grip for the key contained in the
2490 S-Expression KEY and writes it to BUFFER, which must be large
2491 enough to hold it. Returns usual error code. */
2493 ssh_key_grip (gcry_sexp_t key, unsigned char *buffer)
2495 if (!gcry_pk_get_keygrip (key, buffer))
2497 gpg_error_t err = gcry_pk_testkey (key);
2498 return err? err : gpg_error (GPG_ERR_INTERNAL);
2505 /* Check whether a smartcard is available and whether it has a usable
2506 key. Store a copy of that key at R_PK and return 0. If no key is
2507 available store NULL at R_PK and return an error code. If CARDSN
2508 is not NULL, a string with the serial number of the card will be
2509 a malloced and stored there. */
2511 card_key_available (ctrl_t ctrl, gcry_sexp_t *r_pk, char **cardsn)
2515 char *serialno = NULL;
2516 unsigned char *pkbuf;
2519 unsigned char grip[20];
2525 /* First see whether a card is available and whether the application
2527 err = agent_card_getattr (ctrl, "$AUTHKEYID", &authkeyid);
2528 if ( gpg_err_code (err) == GPG_ERR_CARD_REMOVED )
2530 /* Ask for the serial number to reset the card. */
2531 err = agent_card_serialno (ctrl, &serialno);
2535 log_info (_("error getting serial number of card: %s\n"),
2536 gpg_strerror (err));
2539 log_info (_("detected card with S/N: %s\n"), serialno);
2540 err = agent_card_getattr (ctrl, "$AUTHKEYID", &authkeyid);
2544 log_error (_("no authentication key for ssh on card: %s\n"),
2545 gpg_strerror (err));
2550 /* Get the S/N if we don't have it yet. Use the fast getattr method. */
2551 if (!serialno && (err = agent_card_getattr (ctrl, "SERIALNO", &serialno)) )
2553 log_error (_("error getting serial number of card: %s\n"),
2554 gpg_strerror (err));
2559 /* Read the public key. */
2560 err = agent_card_readkey (ctrl, authkeyid, &pkbuf);
2564 log_info (_("no suitable card key found: %s\n"), gpg_strerror (err));
2570 pkbuflen = gcry_sexp_canon_len (pkbuf, 0, NULL, NULL);
2571 err = gcry_sexp_sscan (&s_pk, NULL, (char*)pkbuf, pkbuflen);
2574 log_error ("failed to build S-Exp from received card key: %s\n",
2575 gpg_strerror (err));
2582 err = ssh_key_grip (s_pk, grip);
2585 log_debug ("error computing keygrip from received card key: %s\n",
2586 gcry_strerror (err));
2588 gcry_sexp_release (s_pk);
2594 if ( agent_key_available (grip) )
2596 /* (Shadow)-key is not available in our key storage. */
2597 unsigned char *shadow_info;
2600 shadow_info = make_shadow_info (serialno, authkeyid);
2603 err = gpg_error_from_syserror ();
2605 gcry_sexp_release (s_pk);
2610 err = agent_shadow_key (pkbuf, shadow_info, &tmp);
2611 xfree (shadow_info);
2614 log_error (_("shadowing the key failed: %s\n"), gpg_strerror (err));
2616 gcry_sexp_release (s_pk);
2623 pkbuflen = gcry_sexp_canon_len (pkbuf, 0, NULL, NULL);
2626 err = agent_write_private_key (grip, pkbuf, pkbuflen, 0);
2629 log_error (_("error writing key: %s\n"), gpg_strerror (err));
2631 gcry_sexp_release (s_pk);
2642 /* If the card handler is able to return a short serialnumber,
2643 use that one, else use the complete serialno. */
2644 if (!agent_card_getattr (ctrl, "$DISPSERIALNO", &dispsn))
2646 *cardsn = xtryasprintf ("cardno:%s", dispsn);
2650 *cardsn = xtryasprintf ("cardno:%s", serialno);
2653 err = gpg_error_from_syserror ();
2655 gcry_sexp_release (s_pk);
2674 Request handler. Each handler is provided with a CTRL context, a
2675 REQUEST object and a RESPONSE object. The actual request is to be
2676 read from REQUEST, the response needs to be written to RESPONSE.
2681 /* Handler for the "request_identities" command. */
2683 ssh_handler_request_identities (ctrl_t ctrl,
2684 estream_t request, estream_t response)
2686 ssh_key_type_spec_t spec;
2687 char *key_fname = NULL;
2690 estream_t key_blobs;
2691 gcry_sexp_t key_secret;
2692 gcry_sexp_t key_public;
2695 ssh_control_file_t cf = NULL;
2697 gpg_error_t ret_err;
2701 /* Prepare buffer stream. */
2708 key_blobs = es_fopenmem (0, "r+b");
2711 err = gpg_error_from_syserror ();
2715 /* First check whether a key is currently available in the card
2716 reader - this should be allowed even without being listed in
2719 if (!opt.disable_scdaemon
2720 && !card_key_available (ctrl, &key_public, &cardsn))
2722 err = ssh_send_key_public (key_blobs, key_public, cardsn);
2723 gcry_sexp_release (key_public);
2733 /* Prepare buffer for key name construction. */
2737 dname = make_filename (opt.homedir, GNUPG_PRIVATE_KEYS_DIR, NULL);
2740 err = gpg_err_code_from_syserror ();
2744 key_fname = xtrymalloc (strlen (dname) + 1 + 40 + 4 + 1);
2747 err = gpg_err_code_from_syserror ();
2751 fnameptr = stpcpy (stpcpy (key_fname, dname), "/");
2755 /* Then look at all the registered and non-disabled keys. */
2756 err = open_control_file (&cf, 0);
2760 while (!read_control_file_item (cf))
2762 if (!cf->item.valid)
2763 continue; /* Should not happen. */
2764 if (cf->item.disabled)
2766 assert (strlen (cf->item.hexgrip) == 40);
2768 stpcpy (stpcpy (fnameptr, cf->item.hexgrip), ".key");
2770 /* Read file content. */
2772 unsigned char *buffer;
2775 err = file_to_buffer (key_fname, &buffer, &buffer_n);
2778 log_error ("%s:%d: key '%s' skipped: %s\n",
2779 cf->fname, cf->lnr, cf->item.hexgrip,
2780 gpg_strerror (err));
2784 err = gcry_sexp_sscan (&key_secret, NULL, (char*)buffer, buffer_n);
2791 char *key_type = NULL;
2793 err = sexp_extract_identifier (key_secret, &key_type);
2797 err = ssh_key_type_lookup (NULL, key_type, &spec);
2803 err = ssh_send_key_public (key_blobs, key_secret, NULL);
2806 gcry_sexp_release (key_secret);
2813 ret = es_fseek (key_blobs, 0, SEEK_SET);
2816 err = gpg_error_from_syserror ();
2821 /* Send response. */
2823 gcry_sexp_release (key_secret);
2824 gcry_sexp_release (key_public);
2828 ret_err = stream_write_byte (response, SSH_RESPONSE_IDENTITIES_ANSWER);
2830 ret_err = stream_write_uint32 (response, key_counter);
2832 ret_err = stream_copy (response, key_blobs);
2836 ret_err = stream_write_byte (response, SSH_RESPONSE_FAILURE);
2839 es_fclose (key_blobs);
2840 close_control_file (cf);
2847 /* This function hashes the data contained in DATA of size DATA_N
2848 according to the message digest algorithm specified by MD_ALGORITHM
2849 and writes the message digest to HASH, which needs to large enough
2852 data_hash (unsigned char *data, size_t data_n,
2853 int md_algorithm, unsigned char *hash)
2855 gcry_md_hash_buffer (md_algorithm, hash, data, data_n);
2861 /* This function signs the data described by CTRL. If HASH is is not
2862 NULL, (HASH,HASHLEN) overrides the hash stored in CTRL. This is to
2863 allow the use of signature algorithms that implement the hashing
2864 internally (e.g. Ed25519). On success the created signature is
2865 stored in ssh format at R_SIG and it's size at R_SIGLEN; the caller
2866 must use es_free to releaase this memory. */
2868 data_sign (ctrl_t ctrl, ssh_key_type_spec_t *spec,
2869 const void *hash, size_t hashlen,
2870 unsigned char **r_sig, size_t *r_siglen)
2873 gcry_sexp_t signature_sexp = NULL;
2874 estream_t stream = NULL;
2882 /* Quick check to see whether we have a valid keygrip and convert it
2884 if (!ctrl->have_keygrip)
2886 err = gpg_error (GPG_ERR_NO_SECKEY);
2889 bin2hex (ctrl->keygrip, 20, hexgrip);
2891 /* Ask for confirmation if needed. */
2892 if (confirm_flag_from_sshcontrol (hexgrip))
2896 char *comment = NULL;
2898 err = agent_raw_key_from_file (ctrl, ctrl->keygrip, &key);
2901 err = ssh_get_fingerprint_string (key, &fpr);
2904 gcry_sexp_t tmpsxp = gcry_sexp_find_token (key, "comment", 0);
2906 comment = gcry_sexp_nth_string (tmpsxp, 1);
2907 gcry_sexp_release (tmpsxp);
2909 gcry_sexp_release (key);
2912 prompt = xtryasprintf (L_("An ssh process requested the use of key%%0A"
2915 "Do you want to allow this?"),
2916 fpr, comment? comment:"");
2918 gcry_free (comment);
2919 err = agent_get_confirmation (ctrl, prompt, L_("Allow"), L_("Deny"), 0);
2925 /* Create signature. */
2926 ctrl->use_auth_call = 1;
2927 err = agent_pksign_do (ctrl, NULL,
2928 L_("Please enter the passphrase "
2929 "for the ssh key%%0A %F%%0A (%c)"),
2931 CACHE_MODE_SSH, ttl_from_sshcontrol,
2933 ctrl->use_auth_call = 0;
2937 stream = es_fopenmem (0, "r+b");
2940 err = gpg_error_from_syserror ();
2944 err = stream_write_cstring (stream, spec->ssh_identifier);
2948 err = spec->signature_encoder (spec, stream, signature_sexp);
2952 err = es_fclose_snatch (stream, &blob, &bloblen);
2957 *r_sig = blob; blob = NULL;
2958 *r_siglen = bloblen;
2963 gcry_sexp_release (signature_sexp);
2969 /* Handler for the "sign_request" command. */
2971 ssh_handler_sign_request (ctrl_t ctrl, estream_t request, estream_t response)
2973 gcry_sexp_t key = NULL;
2974 ssh_key_type_spec_t spec;
2975 unsigned char hash[MAX_DIGEST_LEN];
2976 unsigned int hash_n;
2977 unsigned char key_grip[20];
2978 unsigned char *key_blob = NULL;
2980 unsigned char *data = NULL;
2981 unsigned char *sig = NULL;
2986 gpg_error_t ret_err;
2991 err = stream_read_string (request, 0, &key_blob, &key_blob_size);
2995 err = ssh_read_key_public_from_blob (key_blob, key_blob_size, &key, &spec);
2999 /* Receive data to sign. */
3000 err = stream_read_string (request, 0, &data, &data_size);
3005 err = stream_read_uint32 (request, &flags);
3009 hash_algo = spec.hash_algo;
3011 hash_algo = GCRY_MD_SHA1; /* Use the default. */
3012 ctrl->digest.algo = hash_algo;
3013 if ((spec.flags & SPEC_FLAG_USE_PKCS1V2))
3014 ctrl->digest.raw_value = 0;
3016 ctrl->digest.raw_value = 1;
3018 /* Calculate key grip. */
3019 err = ssh_key_grip (key, key_grip);
3022 ctrl->have_keygrip = 1;
3023 memcpy (ctrl->keygrip, key_grip, 20);
3025 /* Hash data unless we use EdDSA. */
3026 if ((spec.flags & SPEC_FLAG_IS_EdDSA))
3028 ctrl->digest.valuelen = 0;
3032 hash_n = gcry_md_get_algo_dlen (hash_algo);
3035 err = gpg_error (GPG_ERR_INTERNAL);
3038 err = data_hash (data, data_size, hash_algo, hash);
3041 memcpy (ctrl->digest.value, hash, hash_n);
3042 ctrl->digest.valuelen = hash_n;
3046 if ((spec.flags & SPEC_FLAG_IS_EdDSA))
3047 err = data_sign (ctrl, &spec, data, data_size, &sig, &sig_n);
3049 err = data_sign (ctrl, &spec, NULL, 0, &sig, &sig_n);
3055 ret_err = stream_write_byte (response, SSH_RESPONSE_SIGN_RESPONSE);
3058 ret_err = stream_write_string (response, sig, sig_n);
3064 log_error ("ssh sign request failed: %s <%s>\n",
3065 gpg_strerror (err), gpg_strsource (err));
3066 ret_err = stream_write_byte (response, SSH_RESPONSE_FAILURE);
3073 gcry_sexp_release (key);
3082 /* This function extracts the comment contained in the key
3083 s-expression KEY and stores a copy in COMMENT. Returns usual error
3086 ssh_key_extract_comment (gcry_sexp_t key, char **r_comment)
3088 gcry_sexp_t comment_list;
3092 comment_list = gcry_sexp_find_token (key, "comment", 0);
3094 return gpg_error (GPG_ERR_INV_SEXP);
3096 *r_comment = gcry_sexp_nth_string (comment_list, 1);
3097 gcry_sexp_release (comment_list);
3099 return gpg_error (GPG_ERR_INV_SEXP);
3105 /* This function converts the key contained in the S-Expression KEY
3106 into a buffer, which is protected by the passphrase PASSPHRASE.
3107 Returns usual error code. */
3109 ssh_key_to_protected_buffer (gcry_sexp_t key, const char *passphrase,
3110 unsigned char **buffer, size_t *buffer_n)
3112 unsigned char *buffer_new;
3113 unsigned int buffer_new_n;
3117 buffer_new_n = gcry_sexp_sprint (key, GCRYSEXP_FMT_CANON, NULL, 0);
3118 buffer_new = xtrymalloc_secure (buffer_new_n);
3121 err = gpg_error_from_syserror ();
3125 gcry_sexp_sprint (key, GCRYSEXP_FMT_CANON, buffer_new, buffer_new_n);
3126 /* FIXME: guarantee? */
3128 err = agent_protect (buffer_new, passphrase, buffer, buffer_n, 0);
3139 /* Callback function to compare the first entered PIN with the one
3140 currently being entered. */
3142 reenter_compare_cb (struct pin_entry_info_s *pi)
3144 const char *pin1 = pi->check_cb_arg;
3146 if (!strcmp (pin1, pi->pin))
3147 return 0; /* okay */
3148 return gpg_error (GPG_ERR_BAD_PASSPHRASE);
3152 /* Store the ssh KEY into our local key storage and protect it after
3153 asking for a passphrase. Cache that passphrase. TTL is the
3154 maximum caching time for that key. If the key already exists in
3155 our key storage, don't do anything. When entering a new key also
3156 add an entry to the sshcontrol file. */
3158 ssh_identity_register (ctrl_t ctrl, ssh_key_type_spec_t *spec,
3159 gcry_sexp_t key, int ttl, int confirm)
3162 unsigned char key_grip_raw[20];
3164 unsigned char *buffer = NULL;
3166 char *description = NULL;
3167 const char *description2 = L_("Please re-enter this passphrase");
3168 char *comment = NULL;
3169 char *key_fpr = NULL;
3170 const char *initial_errtext = NULL;
3171 struct pin_entry_info_s *pi = NULL;
3172 struct pin_entry_info_s *pi2 = NULL;
3174 err = ssh_key_grip (key, key_grip_raw);
3178 /* Check whether the key is already in our key storage. Don't do
3180 if ( !agent_key_available (key_grip_raw) )
3181 goto out; /* Yes, key is available. */
3183 err = ssh_get_fingerprint_string (key, &key_fpr);
3187 err = ssh_key_extract_comment (key, &comment);
3191 if ( asprintf (&description,
3192 L_("Please enter a passphrase to protect"
3193 " the received secret key%%0A"
3196 "within gpg-agent's key storage"),
3197 key_fpr, comment ? comment : "") < 0)
3199 err = gpg_error_from_syserror ();
3203 pi = gcry_calloc_secure (1, sizeof (*pi) + MAX_PASSPHRASE_LEN + 1);
3206 err = gpg_error_from_syserror ();
3209 pi2 = gcry_calloc_secure (1, sizeof (*pi2) + MAX_PASSPHRASE_LEN + 1);
3212 err = gpg_error_from_syserror ();
3215 pi->max_length = MAX_PASSPHRASE_LEN + 1;
3217 pi->with_repeat = 1;
3218 pi2->max_length = MAX_PASSPHRASE_LEN + 1;
3220 pi2->check_cb = reenter_compare_cb;
3221 pi2->check_cb_arg = pi->pin;
3224 err = agent_askpin (ctrl, description, NULL, initial_errtext, pi, NULL, 0);
3225 initial_errtext = NULL;
3229 /* Unless the passphrase is empty or the pinentry told us that
3230 it already did the repetition check, ask to confirm it. */
3231 if (*pi->pin && !pi->repeat_okay)
3233 err = agent_askpin (ctrl, description2, NULL, NULL, pi2, NULL, 0);
3234 if (gpg_err_code (err) == GPG_ERR_BAD_PASSPHRASE)
3235 { /* The re-entered one did not match and the user did not
3237 initial_errtext = L_("does not match - try again");
3242 err = ssh_key_to_protected_buffer (key, pi->pin, &buffer, &buffer_n);
3246 /* Store this key to our key storage. */
3247 err = agent_write_private_key (key_grip_raw, buffer, buffer_n, 0);
3251 /* Cache this passphrase. */
3252 bin2hex (key_grip_raw, 20, key_grip);
3253 err = agent_put_cache (key_grip, CACHE_MODE_SSH, pi->pin, ttl);
3257 /* And add an entry to the sshcontrol file. */
3258 err = add_control_entry (ctrl, spec, key_grip, key_fpr, ttl, confirm);
3262 if (pi2 && pi2->max_length)
3263 wipememory (pi2->pin, pi2->max_length);
3265 if (pi && pi->max_length)
3266 wipememory (pi->pin, pi->max_length);
3271 xfree (description);
3277 /* This function removes the key contained in the S-Expression KEY
3278 from the local key storage, in case it exists there. Returns usual
3279 error code. FIXME: this function is a stub. */
3281 ssh_identity_drop (gcry_sexp_t key)
3283 unsigned char key_grip[21] = { 0 };
3286 err = ssh_key_grip (key, key_grip);
3290 key_grip[sizeof (key_grip) - 1] = 0;
3292 /* FIXME: What to do here - forgetting the passphrase or deleting
3293 the key from key cache? */
3300 /* Handler for the "add_identity" command. */
3302 ssh_handler_add_identity (ctrl_t ctrl, estream_t request, estream_t response)
3304 gpg_error_t ret_err;
3305 ssh_key_type_spec_t spec;
3317 err = ssh_receive_key (request, &key, 1, 1, &spec);
3323 err = stream_read_byte (request, &b);
3324 if (gpg_err_code (err) == GPG_ERR_EOF)
3332 case SSH_OPT_CONSTRAIN_LIFETIME:
3336 err = stream_read_uint32 (request, &n);
3342 case SSH_OPT_CONSTRAIN_CONFIRM:
3349 /* FIXME: log/bad? */
3356 err = ssh_identity_register (ctrl, &spec, key, ttl, confirm);
3360 gcry_sexp_release (key);
3363 ret_err = stream_write_byte (response, SSH_RESPONSE_SUCCESS);
3365 ret_err = stream_write_byte (response, SSH_RESPONSE_FAILURE);
3370 /* Handler for the "remove_identity" command. */
3372 ssh_handler_remove_identity (ctrl_t ctrl,
3373 estream_t request, estream_t response)
3375 unsigned char *key_blob;
3378 gpg_error_t ret_err;
3388 err = stream_read_string (request, 0, &key_blob, &key_blob_size);
3392 err = ssh_read_key_public_from_blob (key_blob, key_blob_size, &key, NULL);
3396 err = ssh_identity_drop (key);
3401 gcry_sexp_release (key);
3404 ret_err = stream_write_byte (response, SSH_RESPONSE_SUCCESS);
3406 ret_err = stream_write_byte (response, SSH_RESPONSE_FAILURE);
3411 /* FIXME: stub function. Actually useful? */
3413 ssh_identities_remove_all (void)
3419 /* FIXME: shall we remove _all_ cache entries or only those
3420 registered through the ssh emulation? */
3425 /* Handler for the "remove_all_identities" command. */
3427 ssh_handler_remove_all_identities (ctrl_t ctrl,
3428 estream_t request, estream_t response)
3430 gpg_error_t ret_err;
3436 err = ssh_identities_remove_all ();
3439 ret_err = stream_write_byte (response, SSH_RESPONSE_SUCCESS);
3441 ret_err = stream_write_byte (response, SSH_RESPONSE_FAILURE);
3446 /* Lock agent? FIXME: stub function. */
3453 log_error ("ssh-agent's lock command is not implemented\n");
3459 /* Unock agent? FIXME: stub function. */
3465 log_error ("ssh-agent's unlock command is not implemented\n");
3471 /* Handler for the "lock" command. */
3473 ssh_handler_lock (ctrl_t ctrl, estream_t request, estream_t response)
3475 gpg_error_t ret_err;
3484 ret_err = stream_write_byte (response, SSH_RESPONSE_SUCCESS);
3486 ret_err = stream_write_byte (response, SSH_RESPONSE_FAILURE);
3491 /* Handler for the "unlock" command. */
3493 ssh_handler_unlock (ctrl_t ctrl, estream_t request, estream_t response)
3495 gpg_error_t ret_err;
3501 err = ssh_unlock ();
3504 ret_err = stream_write_byte (response, SSH_RESPONSE_SUCCESS);
3506 ret_err = stream_write_byte (response, SSH_RESPONSE_FAILURE);
3513 /* Return the request specification for the request identified by TYPE
3514 or NULL in case the requested request specification could not be
3516 static ssh_request_spec_t *
3517 request_spec_lookup (int type)
3519 ssh_request_spec_t *spec;
3522 for (i = 0; i < DIM (request_specs); i++)
3523 if (request_specs[i].type == type)
3525 if (i == DIM (request_specs))
3528 log_info ("ssh request %u is not supported\n", type);
3532 spec = request_specs + i;
3537 /* Process a single request. The request is read from and the
3538 response is written to STREAM_SOCK. Uses CTRL as context. Returns
3539 zero in case of success, non zero in case of failure. */
3541 ssh_request_process (ctrl_t ctrl, estream_t stream_sock)
3543 ssh_request_spec_t *spec;
3544 estream_t response = NULL;
3545 estream_t request = NULL;
3546 unsigned char request_type;
3550 unsigned char *request_data = NULL;
3551 u32 request_data_size;
3554 /* Create memory streams for request/response data. The entire
3555 request will be stored in secure memory, since it might contain
3556 secret key material. The response does not have to be stored in
3557 secure memory, since we never give out secret keys.
3559 Note: we only have little secure memory, but there is NO
3560 possibility of DoS here; only trusted clients are allowed to
3561 connect to the agent. What could happen is that the agent
3562 returns out-of-secure-memory errors on requests in case the
3563 agent's owner floods his own agent with many large messages.
3566 /* Retrieve request. */
3567 err = stream_read_string (stream_sock, 1, &request_data, &request_data_size);
3571 if (opt.verbose > 1)
3572 log_info ("received ssh request of length %u\n",
3573 (unsigned int)request_data_size);
3575 if (! request_data_size)
3579 /* Broken request; FIXME. */
3582 request_type = request_data[0];
3583 spec = request_spec_lookup (request_type);
3588 /* Unknown request; FIXME. */
3591 if (spec->secret_input)
3592 request = es_mopen (NULL, 0, 0, 1, realloc_secure, gcry_free, "r+b");
3594 request = es_mopen (NULL, 0, 0, 1, gcry_realloc, gcry_free, "r+b");
3597 err = gpg_error_from_syserror ();
3600 ret = es_setvbuf (request, NULL, _IONBF, 0);
3603 err = gpg_error_from_syserror ();
3606 err = stream_write_data (request, request_data + 1, request_data_size - 1);
3609 es_rewind (request);
3611 response = es_fopenmem (0, "r+b");
3614 err = gpg_error_from_syserror ();
3619 log_info ("ssh request handler for %s (%u) started\n",
3620 spec->identifier, spec->type);
3622 err = (*spec->handler) (ctrl, request, response);
3627 log_info ("ssh request handler for %s (%u) failed: %s\n",
3628 spec->identifier, spec->type, gpg_strerror (err));
3630 log_info ("ssh request handler for %s (%u) ready\n",
3631 spec->identifier, spec->type);
3640 response_size = es_ftell (response);
3641 if (opt.verbose > 1)
3642 log_info ("sending ssh response of length %u\n",
3643 (unsigned int)response_size);
3645 err = es_fseek (response, 0, SEEK_SET);
3652 err = stream_write_uint32 (stream_sock, response_size);
3659 err = stream_copy (stream_sock, response);
3663 err = es_fflush (stream_sock);
3669 if (err && es_feof (stream_sock))
3670 log_error ("error occurred while processing request: %s\n",
3671 gpg_strerror (err));
3675 if (opt.verbose > 1)
3676 log_info ("sending ssh error response\n");
3677 err = stream_write_uint32 (stream_sock, 1);
3680 err = stream_write_byte (stream_sock, SSH_RESPONSE_FAILURE);
3687 es_fclose (request);
3688 es_fclose (response);
3689 xfree (request_data);
3695 /* Start serving client on SOCK_CLIENT. */
3697 start_command_handler_ssh (ctrl_t ctrl, gnupg_fd_t sock_client)
3699 estream_t stream_sock = NULL;
3703 err = agent_copy_startup_env (ctrl);
3707 /* Create stream from socket. */
3708 stream_sock = es_fdopen (FD2INT(sock_client), "r+");
3711 err = gpg_error_from_syserror ();
3712 log_error (_("failed to create stream from socket: %s\n"),
3713 gpg_strerror (err));
3716 /* We have to disable the estream buffering, because the estream
3717 core doesn't know about secure memory. */
3718 ret = es_setvbuf (stream_sock, NULL, _IONBF, 0);
3721 err = gpg_error_from_syserror ();
3722 log_error ("failed to disable buffering "
3723 "on socket stream: %s\n", gpg_strerror (err));
3727 /* Main processing loop. */
3728 while ( !ssh_request_process (ctrl, stream_sock) )
3730 /* Check wether we have reached EOF before trying to read
3734 c = es_fgetc (stream_sock);
3737 es_ungetc (c, stream_sock);
3740 /* Reset the SCD in case it has been used. */
3741 agent_reset_scd (ctrl);
3746 es_fclose (stream_sock);
3750 #ifdef HAVE_W32_SYSTEM
3751 /* Serve one ssh-agent request. This is used for the Putty support.
3752 REQUEST is the the mmapped memory which may be accessed up to a
3753 length of MAXREQLEN. Returns 0 on success which also indicates
3754 that a valid SSH response message is now in REQUEST. */
3756 serve_mmapped_ssh_request (ctrl_t ctrl,
3757 unsigned char *request, size_t maxreqlen)
3761 int valid_response = 0;
3762 ssh_request_spec_t *spec;
3764 estream_t request_stream, response_stream;
3766 if (agent_copy_startup_env (ctrl))
3767 goto leave; /* Error setting up the environment. */
3770 goto leave; /* Caller error. */
3772 msglen = uint32_construct (request[0], request[1], request[2], request[3]);
3773 if (msglen < 1 || msglen > maxreqlen - 4)
3775 log_error ("ssh message len (%u) out of range", (unsigned int)msglen);
3779 spec = request_spec_lookup (request[4]);
3782 send_err = 1; /* Unknown request type. */
3786 /* Create a stream object with the data part of the request. */
3787 if (spec->secret_input)
3788 request_stream = es_mopen (NULL, 0, 0, 1, realloc_secure, gcry_free, "r+");
3790 request_stream = es_mopen (NULL, 0, 0, 1, gcry_realloc, gcry_free, "r+");
3791 if (!request_stream)
3793 err = gpg_error_from_syserror ();
3796 /* We have to disable the estream buffering, because the estream
3797 core doesn't know about secure memory. */
3798 if (es_setvbuf (request_stream, NULL, _IONBF, 0))
3800 err = gpg_error_from_syserror ();
3803 /* Copy the request to the stream but omit the request type. */
3804 err = stream_write_data (request_stream, request + 5, msglen - 1);
3807 es_rewind (request_stream);
3809 response_stream = es_fopenmem (0, "r+b");
3810 if (!response_stream)
3812 err = gpg_error_from_syserror ();
3817 log_info ("ssh request handler for %s (%u) started\n",
3818 spec->identifier, spec->type);
3820 err = (*spec->handler) (ctrl, request_stream, response_stream);
3825 log_info ("ssh request handler for %s (%u) failed: %s\n",
3826 spec->identifier, spec->type, gpg_strerror (err));
3828 log_info ("ssh request handler for %s (%u) ready\n",
3829 spec->identifier, spec->type);
3832 es_fclose (request_stream);
3833 request_stream = NULL;
3841 /* Put the response back into the mmapped buffer. */
3843 void *response_data;
3844 size_t response_size;
3846 /* NB: In contrast to the request-stream, the response stream
3847 includes the the message type byte. */
3848 if (es_fclose_snatch (response_stream, &response_data, &response_size))
3850 log_error ("snatching ssh response failed: %s",
3851 gpg_strerror (gpg_error_from_syserror ()));
3852 send_err = 1; /* Ooops. */
3856 if (opt.verbose > 1)
3857 log_info ("sending ssh response of length %u\n",
3858 (unsigned int)response_size);
3859 if (response_size > maxreqlen - 4)
3861 log_error ("invalid length of the ssh response: %s",
3862 gpg_strerror (GPG_ERR_INTERNAL));
3863 es_free (response_data);
3868 request[0] = response_size >> 24;
3869 request[1] = response_size >> 16;
3870 request[2] = response_size >> 8;
3871 request[3] = response_size >> 0;
3872 memcpy (request+4, response_data, response_size);
3873 es_free (response_data);
3884 request[4] = SSH_RESPONSE_FAILURE;
3888 /* Reset the SCD in case it has been used. */
3889 agent_reset_scd (ctrl);
3891 return valid_response? 0 : -1;
3893 #endif /*HAVE_W32_SYSTEM*/