Imported Upstream version 2.1.11
[platform/upstream/gpg2.git] / agent / command-ssh.c
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
4  *
5  * This file is part of GnuPG.
6  *
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.
11  *
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.
16  *
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/>.
19  */
20
21 /* Only v2 of the ssh-agent protocol is implemented.  Relevant RFCs
22    are:
23
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
29
30    The protocol for the agent is defined in OpenSSH's PROTOCL.agent
31    file.
32   */
33
34 #include <config.h>
35
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <errno.h>
40 #include <sys/types.h>
41 #include <sys/stat.h>
42 #include <assert.h>
43
44 #include "agent.h"
45
46 #include "i18n.h"
47 #include "../common/ssh-utils.h"
48
49
50 \f
51
52 /* Request types. */
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
61
62 /* Options. */
63 #define SSH_OPT_CONSTRAIN_LIFETIME         1
64 #define SSH_OPT_CONSTRAIN_CONFIRM          2
65
66 /* Response types. */
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
71
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)
79
80 /* The name of the control file.  */
81 #define SSH_CONTROL_FILE_NAME "sshcontrol"
82
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"
95 "\n";
96
97
98 /* Macros.  */
99
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)
104
105 \f
106
107
108 /*
109  * Basic types.
110  */
111
112 /* Type for a request handler.  */
113 typedef gpg_error_t (*ssh_request_handler_t) (ctrl_t ctrl,
114                                               estream_t request,
115                                               estream_t response);
116
117
118 struct ssh_key_type_spec;
119 typedef struct ssh_key_type_spec ssh_key_type_spec_t;
120
121 /* Type, which is used for associating request handlers with the
122    appropriate request IDs.  */
123 typedef struct ssh_request_spec
124 {
125   unsigned char type;
126   ssh_request_handler_t handler;
127   const char *identifier;
128   unsigned int secret_input;
129 } ssh_request_spec_t;
130
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,
136                                            gcry_mpi_t *mpis);
137
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,
143                                                 gcry_sexp_t sig);
144
145 /* Type, which is used for boundling all the algorithm specific
146    information together in a single object.  */
147 struct ssh_key_type_spec
148 {
149   /* Algorithm identifier as used by OpenSSH.  */
150   const char *ssh_identifier;
151
152   /* Human readable name of the algorithm.  */
153   const char *name;
154
155   /* Algorithm identifier as used by GnuPG.  */
156   const char *identifier;
157
158   /* List of MPI names for secret keys; order matches the one of the
159      agent protocol.  */
160   const char *elems_key_secret;
161
162   /* List of MPI names for public keys; order matches the one of the
163      agent protocol.  */
164   const char *elems_key_public;
165
166   /* List of MPI names for signature data.  */
167   const char *elems_signature;
168
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;
172
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;
177
178   /* Signature encoder function.  Signature encoder functions are
179      necessary since the encoding of signatures depends on the used
180      algorithm.  */
181   ssh_signature_encoder_t signature_encoder;
182
183   /* The name of the ECC curve or NULL.  */
184   const char *curve_name;
185
186   /* The hash algorithm to be used with this key.  0 for using the
187      default.  */
188   int hash_algo;
189
190   /* Misc flags.  */
191   unsigned int flags;
192 };
193
194
195 /* Definition of an object to access the sshcontrol file.  */
196 struct ssh_control_file_s
197 {
198   char *fname;  /* Name of the file.  */
199   FILE *fp;     /* This is never NULL. */
200   int lnr;      /* The current line number.  */
201   struct {
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).  */
207   } item;
208 };
209
210
211 /* Prototypes.  */
212 static gpg_error_t ssh_handler_request_identities (ctrl_t ctrl,
213                                                    estream_t request,
214                                                    estream_t response);
215 static gpg_error_t ssh_handler_sign_request (ctrl_t ctrl,
216                                              estream_t request,
217                                              estream_t response);
218 static gpg_error_t ssh_handler_add_identity (ctrl_t ctrl,
219                                              estream_t request,
220                                              estream_t response);
221 static gpg_error_t ssh_handler_remove_identity (ctrl_t ctrl,
222                                                 estream_t request,
223                                                 estream_t response);
224 static gpg_error_t ssh_handler_remove_all_identities (ctrl_t ctrl,
225                                                       estream_t request,
226                                                       estream_t response);
227 static gpg_error_t ssh_handler_lock (ctrl_t ctrl,
228                                      estream_t request,
229                                      estream_t response);
230 static gpg_error_t ssh_handler_unlock (ctrl_t ctrl,
231                                        estream_t request,
232                                        estream_t response);
233
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);
248
249
250
251 /* Global variables.  */
252
253
254 /* Associating request types with the corresponding request
255    handlers.  */
256
257 static ssh_request_spec_t request_specs[] =
258   {
259 #define REQUEST_SPEC_DEFINE(id, name, secret_input) \
260   { SSH_REQUEST_##id, ssh_handler_##name, #name, secret_input }
261
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
271   };
272
273
274 /* Table holding key type specifications.  */
275 static ssh_key_type_spec_t ssh_key_types[] =
276   {
277     {
278       "ssh-ed25519", "Ed25519", "ecc", "qd",  "q", "rs", "qd",
279       NULL,                 ssh_signature_encoder_eddsa,
280       "Ed25519", 0,               SPEC_FLAG_IS_EdDSA
281     },
282     {
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
286     },
287     {
288       "ssh-dss", "DSA", "dsa", "pqgyx",  "pqgy", "rs", "pqgyx",
289       NULL,                 ssh_signature_encoder_dsa,
290       NULL, 0, 0
291     },
292     {
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
296     },
297     {
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
301     },
302     {
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
306     },
307     {
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
312     },
313     {
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
318     },
319     {
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
324     },
325     {
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
330     },
331     {
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
336     },
337     {
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
342     }
343   };
344
345 \f
346
347
348
349 /*
350    General utility functions.
351  */
352
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
356    existing buffer.  */
357 static void *
358 realloc_secure (void *a, size_t n)
359 {
360   void *p;
361
362   if (a)
363     p = gcry_realloc (a, n);
364   else
365     p = gcry_malloc_secure (n);
366
367   return p;
368 }
369
370
371 /* Create and return a new C-string from DATA/DATA_N (i.e.: add
372    NUL-termination); return NULL on OOM.  */
373 static char *
374 make_cstring (const char *data, size_t data_n)
375 {
376   char *s;
377
378   s = xtrymalloc (data_n + 1);
379   if (s)
380     {
381       memcpy (s, data, data_n);
382       s[data_n] = 0;
383     }
384
385   return s;
386 }
387
388 /* Lookup the ssh-identifier for the ECC curve CURVE_NAME.  Returns
389    NULL if not found.  */
390 static const char *
391 ssh_identifier_from_curve_name (const char *curve_name)
392 {
393   int i;
394
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;
399
400   return NULL;
401 }
402
403
404 /*
405    Primitive I/O functions.
406  */
407
408
409 /* Read a byte from STREAM, store it in B.  */
410 static gpg_error_t
411 stream_read_byte (estream_t stream, unsigned char *b)
412 {
413   gpg_error_t err;
414   int ret;
415
416   ret = es_fgetc (stream);
417   if (ret == EOF)
418     {
419       if (es_ferror (stream))
420         err = gpg_error_from_syserror ();
421       else
422         err = gpg_error (GPG_ERR_EOF);
423       *b = 0;
424     }
425   else
426     {
427       *b = ret & 0xFF;
428       err = 0;
429     }
430
431   return err;
432 }
433
434 /* Write the byte contained in B to STREAM.  */
435 static gpg_error_t
436 stream_write_byte (estream_t stream, unsigned char b)
437 {
438   gpg_error_t err;
439   int ret;
440
441   ret = es_fputc (b, stream);
442   if (ret == EOF)
443     err = gpg_error_from_syserror ();
444   else
445     err = 0;
446
447   return err;
448 }
449
450
451 /* Read a uint32 from STREAM, store it in UINT32.  */
452 static gpg_error_t
453 stream_read_uint32 (estream_t stream, u32 *uint32)
454 {
455   unsigned char buffer[4];
456   size_t bytes_read;
457   gpg_error_t err;
458   int ret;
459
460   ret = es_read (stream, buffer, sizeof (buffer), &bytes_read);
461   if (ret)
462     err = gpg_error_from_syserror ();
463   else
464     {
465       if (bytes_read != sizeof (buffer))
466         err = gpg_error (GPG_ERR_EOF);
467       else
468         {
469           u32 n;
470
471           n = uint32_construct (buffer[0], buffer[1], buffer[2], buffer[3]);
472           *uint32 = n;
473           err = 0;
474         }
475     }
476
477   return err;
478 }
479
480 /* Write the uint32 contained in UINT32 to STREAM.  */
481 static gpg_error_t
482 stream_write_uint32 (estream_t stream, u32 uint32)
483 {
484   unsigned char buffer[4];
485   gpg_error_t err;
486   int ret;
487
488   buffer[0] = uint32 >> 24;
489   buffer[1] = uint32 >> 16;
490   buffer[2] = uint32 >>  8;
491   buffer[3] = uint32 >>  0;
492
493   ret = es_write (stream, buffer, sizeof (buffer), NULL);
494   if (ret)
495     err = gpg_error_from_syserror ();
496   else
497     err = 0;
498
499   return err;
500 }
501
502 /* Read SIZE bytes from STREAM into BUFFER.  */
503 static gpg_error_t
504 stream_read_data (estream_t stream, unsigned char *buffer, size_t size)
505 {
506   gpg_error_t err;
507   size_t bytes_read;
508   int ret;
509
510   ret = es_read (stream, buffer, size, &bytes_read);
511   if (ret)
512     err = gpg_error_from_syserror ();
513   else
514     {
515       if (bytes_read != size)
516         err = gpg_error (GPG_ERR_EOF);
517       else
518         err = 0;
519     }
520
521   return err;
522 }
523
524 /* Skip over SIZE bytes from STREAM.  */
525 static gpg_error_t
526 stream_read_skip (estream_t stream, size_t size)
527 {
528   char buffer[128];
529   size_t bytes_to_read, bytes_read;
530   int ret;
531
532   do
533     {
534       bytes_to_read = size;
535       if (bytes_to_read > sizeof buffer)
536         bytes_to_read = sizeof buffer;
537
538       ret = es_read (stream, buffer, bytes_to_read, &bytes_read);
539       if (ret)
540         return gpg_error_from_syserror ();
541       else if (bytes_read != bytes_to_read)
542         return gpg_error (GPG_ERR_EOF);
543       else
544         size -= bytes_to_read;
545     }
546   while (size);
547
548   return 0;
549 }
550
551
552 /* Write SIZE bytes from BUFFER to STREAM.  */
553 static gpg_error_t
554 stream_write_data (estream_t stream, const unsigned char *buffer, size_t size)
555 {
556   gpg_error_t err;
557   int ret;
558
559   ret = es_write (stream, buffer, size, NULL);
560   if (ret)
561     err = gpg_error_from_syserror ();
562   else
563     err = 0;
564
565   return err;
566 }
567
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.  */
572 static gpg_error_t
573 stream_read_string (estream_t stream, unsigned int secure,
574                     unsigned char **string, u32 *string_size)
575 {
576   gpg_error_t err;
577   unsigned char *buffer = NULL;
578   u32 length = 0;
579
580   if (string_size)
581     *string_size = 0;
582
583   /* Read string length.  */
584   err = stream_read_uint32 (stream, &length);
585   if (err)
586     goto out;
587
588   if (string)
589     {
590       /* Allocate space.  */
591       if (secure)
592         buffer = xtrymalloc_secure (length + 1);
593       else
594         buffer = xtrymalloc (length + 1);
595       if (! buffer)
596         {
597           err = gpg_error_from_syserror ();
598           goto out;
599         }
600
601       /* Read data.  */
602       err = stream_read_data (stream, buffer, length);
603       if (err)
604         goto out;
605
606       /* Finalize string object.  */
607       buffer[length] = 0;
608       *string = buffer;
609     }
610   else  /* Dummy read requested.  */
611     {
612       err = stream_read_skip (stream, length);
613       if (err)
614         goto out;
615     }
616
617   if (string_size)
618     *string_size = length;
619
620  out:
621
622   if (err)
623     xfree (buffer);
624
625   return err;
626 }
627
628
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.  */
633 static gpg_error_t
634 stream_read_blob (estream_t stream, unsigned int secure, gcry_mpi_t *r_mpi)
635 {
636   gpg_error_t err;
637   unsigned char *buffer = NULL;
638   u32 length = 0;
639
640   *r_mpi = NULL;
641
642   /* Read string length.  */
643   err = stream_read_uint32 (stream, &length);
644   if (err)
645     goto leave;
646
647   /* To avoid excessive use of secure memory we check that an MPI is
648      not too large. */
649   if (length > (4096/8) + 8)
650     {
651       log_error (_("ssh keys greater than %d bits are not supported\n"), 4096);
652       err = GPG_ERR_TOO_LARGE;
653       goto leave;
654     }
655
656   /* Allocate space.  */
657   if (secure)
658     buffer = xtrymalloc_secure (length+1);
659   else
660     buffer = xtrymalloc (length+1);
661   if (!buffer)
662     {
663       err = gpg_error_from_syserror ();
664       goto leave;
665     }
666
667   /* Read data.  */
668   err = stream_read_data (stream, buffer + 1, length);
669   if (err)
670     goto leave;
671
672   buffer[0] = 0x40;
673   *r_mpi = gcry_mpi_set_opaque (NULL, buffer, 8*(length+1));
674   buffer = NULL;
675
676  leave:
677   xfree (buffer);
678   return err;
679 }
680
681
682 /* Read a C-string from STREAM, store copy in STRING.  */
683 static gpg_error_t
684 stream_read_cstring (estream_t stream, char **string)
685 {
686   gpg_error_t err;
687   unsigned char *buffer;
688
689   err = stream_read_string (stream, 0, &buffer, NULL);
690   if (!err)
691     *string = (char *)buffer;
692   return err;
693 }
694
695
696 /* Write a binary string from STRING of size STRING_N to STREAM.  */
697 static gpg_error_t
698 stream_write_string (estream_t stream,
699                      const unsigned char *string, u32 string_n)
700 {
701   gpg_error_t err;
702
703   err = stream_write_uint32 (stream, string_n);
704   if (err)
705     goto out;
706
707   err = stream_write_data (stream, string, string_n);
708
709  out:
710
711   return err;
712 }
713
714 /* Write a C-string from STRING to STREAM.  */
715 static gpg_error_t
716 stream_write_cstring (estream_t stream, const char *string)
717 {
718   gpg_error_t err;
719
720   err = stream_write_string (stream,
721                              (const unsigned char *) string, strlen (string));
722
723   return err;
724 }
725
726 /* Read an MPI from STREAM, store it in MPINT.  Depending on SECURE
727    use secure memory.  */
728 static gpg_error_t
729 stream_read_mpi (estream_t stream, unsigned int secure, gcry_mpi_t *mpint)
730 {
731   unsigned char *mpi_data;
732   u32 mpi_data_size;
733   gpg_error_t err;
734   gcry_mpi_t mpi;
735
736   mpi_data = NULL;
737
738   err = stream_read_string (stream, secure, &mpi_data, &mpi_data_size);
739   if (err)
740     goto out;
741
742   /* To avoid excessive use of secure memory we check that an MPI is
743      not too large. */
744   if (mpi_data_size > 520)
745     {
746       log_error (_("ssh keys greater than %d bits are not supported\n"), 4096);
747       err = GPG_ERR_TOO_LARGE;
748       goto out;
749     }
750
751   err = gcry_mpi_scan (&mpi, GCRYMPI_FMT_STD, mpi_data, mpi_data_size, NULL);
752   if (err)
753     goto out;
754
755   *mpint = mpi;
756
757  out:
758
759   xfree (mpi_data);
760
761   return err;
762 }
763
764 /* Write the MPI contained in MPINT to STREAM.  */
765 static gpg_error_t
766 stream_write_mpi (estream_t stream, gcry_mpi_t mpint)
767 {
768   unsigned char *mpi_buffer;
769   size_t mpi_buffer_n;
770   gpg_error_t err;
771
772   mpi_buffer = NULL;
773
774   err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &mpi_buffer, &mpi_buffer_n, mpint);
775   if (err)
776     goto out;
777
778   err = stream_write_string (stream, mpi_buffer, mpi_buffer_n);
779
780  out:
781
782   xfree (mpi_buffer);
783
784   return err;
785 }
786
787
788 /* Copy data from SRC to DST until EOF is reached.  */
789 static gpg_error_t
790 stream_copy (estream_t dst, estream_t src)
791 {
792   char buffer[BUFSIZ];
793   size_t bytes_read;
794   gpg_error_t err;
795   int ret;
796
797   err = 0;
798   while (1)
799     {
800       ret = es_read (src, buffer, sizeof (buffer), &bytes_read);
801       if (ret || (! bytes_read))
802         {
803           if (ret)
804             err = gpg_error_from_syserror ();
805           break;
806         }
807       ret = es_write (dst, buffer, bytes_read, NULL);
808       if (ret)
809         {
810           err = gpg_error_from_syserror ();
811           break;
812         }
813     }
814
815   return err;
816 }
817
818
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.  */
822 static gpg_error_t
823 file_to_buffer (const char *filename, unsigned char **buffer, size_t *buffer_n)
824 {
825   unsigned char *buffer_new;
826   struct stat statbuf;
827   estream_t stream;
828   gpg_error_t err;
829   int ret;
830
831   *buffer = NULL;
832   *buffer_n = 0;
833
834   buffer_new = NULL;
835   err = 0;
836
837   stream = es_fopen (filename, "rb");
838   if (! stream)
839     {
840       err = gpg_error_from_syserror ();
841       goto out;
842     }
843
844   ret = fstat (es_fileno (stream), &statbuf);
845   if (ret)
846     {
847       err = gpg_error_from_syserror ();
848       goto out;
849     }
850
851   buffer_new = xtrymalloc (statbuf.st_size);
852   if (! buffer_new)
853     {
854       err = gpg_error_from_syserror ();
855       goto out;
856     }
857
858   err = stream_read_data (stream, buffer_new, statbuf.st_size);
859   if (err)
860     goto out;
861
862   *buffer = buffer_new;
863   *buffer_n = statbuf.st_size;
864
865  out:
866
867   if (stream)
868     es_fclose (stream);
869
870   if (err)
871     xfree (buffer_new);
872
873   return err;
874 }
875
876
877
878 \f
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.  */
884 static gpg_error_t
885 open_control_file (ssh_control_file_t *r_cf, int append)
886 {
887   gpg_error_t err;
888   ssh_control_file_t cf;
889
890   cf = xtrycalloc (1, sizeof *cf);
891   if (!cf)
892     {
893       err = gpg_error_from_syserror ();
894       goto leave;
895     }
896
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
899      mutex.  */
900   cf->fname = make_filename_try (opt.homedir, SSH_CONTROL_FILE_NAME, NULL);
901   if (!cf->fname)
902     {
903       err = gpg_error_from_syserror ();
904       goto leave;
905     }
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)
910     {
911       estream_t stream = es_fopen (cf->fname, "wx,mode=-rw-r");
912       if (!stream)
913         {
914           err = gpg_error_from_syserror ();
915           log_error (_("can't create '%s': %s\n"),
916                      cf->fname, gpg_strerror (err));
917           goto leave;
918         }
919       es_fputs (sshcontrolblurb, stream);
920       es_fclose (stream);
921       cf->fp = fopen (cf->fname, append? "a+":"r");
922     }
923
924   if (!cf->fp)
925     {
926       err = gpg_error_from_syserror ();
927       log_error (_("can't open '%s': %s\n"),
928                  cf->fname, gpg_strerror (err));
929       goto leave;
930     }
931
932   err = 0;
933
934  leave:
935   if (err && cf)
936     {
937       if (cf->fp)
938         fclose (cf->fp);
939       xfree (cf->fname);
940       xfree (cf);
941     }
942   else
943     *r_cf = cf;
944
945   return err;
946 }
947
948
949 static void
950 rewind_control_file (ssh_control_file_t cf)
951 {
952   fseek (cf->fp, 0, SEEK_SET);
953   cf->lnr = 0;
954   clearerr (cf->fp);
955 }
956
957
958 static void
959 close_control_file (ssh_control_file_t cf)
960 {
961   if (!cf)
962     return;
963   fclose (cf->fp);
964   xfree (cf->fname);
965   xfree (cf);
966 }
967
968
969
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. */
972 static gpg_error_t
973 read_control_file_item (ssh_control_file_t cf)
974 {
975   int c, i, n;
976   char *p, *pend, line[256];
977   long ttl = 0;
978
979   cf->item.valid = 0;
980   clearerr (cf->fp);
981
982   do
983     {
984       if (!fgets (line, DIM(line)-1, cf->fp) )
985         {
986           if (feof (cf->fp))
987             return gpg_error (GPG_ERR_EOF);
988           return gpg_error_from_syserror ();
989         }
990       cf->lnr++;
991
992       if (!*line || line[strlen(line)-1] != '\n')
993         {
994           /* Eat until end of line */
995           while ( (c=getc (cf->fp)) != EOF && c != '\n')
996             ;
997           return gpg_error (*line? GPG_ERR_LINE_TOO_LONG
998                                  : GPG_ERR_INCOMPLETE_LINE);
999         }
1000
1001       /* Allow for empty lines and spaces */
1002       for (p=line; spacep (p); p++)
1003         ;
1004     }
1005   while (!*p || *p == '\n' || *p == '#');
1006
1007   cf->item.disabled = 0;
1008   if (*p == '!')
1009     {
1010       cf->item.disabled = 1;
1011       for (p++; spacep (p); p++)
1012         ;
1013     }
1014
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'))
1019     {
1020       log_error ("%s:%d: invalid formatted line\n", cf->fname, cf->lnr);
1021       return gpg_error (GPG_ERR_BAD_DATA);
1022     }
1023
1024   ttl = strtol (p, &pend, 10);
1025   p = pend;
1026   if (!(spacep (p) || *p == '\n') || (int)ttl < -1)
1027     {
1028       log_error ("%s:%d: invalid TTL value; assuming 0\n", cf->fname, cf->lnr);
1029       cf->item.ttl = 0;
1030     }
1031   cf->item.ttl = ttl;
1032
1033   /* Now check for key-value pairs of the form NAME[=VALUE]. */
1034   cf->item.confirm = 0;
1035   while (*p)
1036     {
1037       for (; spacep (p) && *p != '\n'; p++)
1038         ;
1039       if (!*p || *p == '\n')
1040         break;
1041       n = strcspn (p, "= \t\n");
1042       if (p[n] == '=')
1043         {
1044           log_error ("%s:%d: assigning a value to a flag is not yet supported; "
1045                      "flag ignored\n", cf->fname, cf->lnr);
1046           p++;
1047         }
1048       else if (n == 7 && !memcmp (p, "confirm", 7))
1049         {
1050           cf->item.confirm = 1;
1051         }
1052       else
1053         log_error ("%s:%d: invalid flag '%.*s'; ignored\n",
1054                    cf->fname, cf->lnr, n, p);
1055       p += n;
1056     }
1057
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":""); */
1063
1064   cf->item.valid = 1;
1065   return 0; /* Okay: valid entry found.  */
1066 }
1067
1068
1069
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. */
1075 static gpg_error_t
1076 search_control_file (ssh_control_file_t cf, const char *hexgrip,
1077                      int *r_disabled, int *r_ttl, int *r_confirm)
1078 {
1079   gpg_error_t err;
1080
1081   assert (strlen (hexgrip) == 40 );
1082
1083   if (r_disabled)
1084     *r_disabled = 0;
1085   if (r_ttl)
1086     *r_ttl = 0;
1087   if (r_confirm)
1088     *r_confirm = 0;
1089
1090   rewind_control_file (cf);
1091   while (!(err=read_control_file_item (cf)))
1092     {
1093       if (!cf->item.valid)
1094         continue; /* Should not happen.  */
1095       if (!strcmp (hexgrip, cf->item.hexgrip))
1096         break;
1097     }
1098   if (!err)
1099     {
1100       if (r_disabled)
1101         *r_disabled = cf->item.disabled;
1102       if (r_ttl)
1103         *r_ttl = cf->item.ttl;
1104       if (r_confirm)
1105         *r_confirm = cf->item.confirm;
1106     }
1107   return err;
1108 }
1109
1110
1111
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. */
1117 static gpg_error_t
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)
1121 {
1122   gpg_error_t err;
1123   ssh_control_file_t cf;
1124   int disabled;
1125
1126   (void)ctrl;
1127
1128   err = open_control_file (&cf, 1);
1129   if (err)
1130     return err;
1131
1132   err = search_control_file (cf, hexgrip, &disabled, NULL, NULL);
1133   if (err && gpg_err_code(err) == GPG_ERR_EOF)
1134     {
1135       struct tm *tp;
1136       time_t atime = time (NULL);
1137
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);
1141       fprintf (cf->fp,
1142                ("# %s key added on: %04d-%02d-%02d %02d:%02d:%02d\n"
1143                 "# MD5 Fingerprint:  %s\n"
1144                 "%s %d%s\n"),
1145                spec->name,
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":"");
1149
1150     }
1151   close_control_file (cf);
1152   return 0;
1153 }
1154
1155
1156 /* Scan the sshcontrol file and return the TTL.  */
1157 static int
1158 ttl_from_sshcontrol (const char *hexgrip)
1159 {
1160   ssh_control_file_t cf;
1161   int disabled, ttl;
1162
1163   if (!hexgrip || strlen (hexgrip) != 40)
1164     return 0;  /* Wrong input: Use global default.  */
1165
1166   if (open_control_file (&cf, 0))
1167     return 0; /* Error: Use the global default TTL.  */
1168
1169   if (search_control_file (cf, hexgrip, &disabled, &ttl, NULL)
1170       || disabled)
1171     ttl = 0;  /* Use the global default if not found or disabled.  */
1172
1173   close_control_file (cf);
1174
1175   return ttl;
1176 }
1177
1178
1179 /* Scan the sshcontrol file and return the confirm flag.  */
1180 static int
1181 confirm_flag_from_sshcontrol (const char *hexgrip)
1182 {
1183   ssh_control_file_t cf;
1184   int disabled, confirm;
1185
1186   if (!hexgrip || strlen (hexgrip) != 40)
1187     return 1;  /* Wrong input: Better ask for confirmation.  */
1188
1189   if (open_control_file (&cf, 0))
1190     return 1; /* Error: Better ask for confirmation.  */
1191
1192   if (search_control_file (cf, hexgrip, &disabled, NULL, &confirm)
1193       || disabled)
1194     confirm = 0;  /* If not found or disabled, there is no reason to
1195                      ask for confirmation.  */
1196
1197   close_control_file (cf);
1198
1199   return confirm;
1200 }
1201
1202
1203 \f
1204
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.  */
1208 ssh_control_file_t
1209 ssh_open_control_file (void)
1210 {
1211   ssh_control_file_t cf;
1212
1213   /* Then look at all the registered and non-disabled keys. */
1214   if (open_control_file (&cf, 0))
1215     return NULL;
1216   return cf;
1217 }
1218
1219 /* Close an ssh control file handle.  This is the public version of
1220    close_control_file.  CF may be NULL.  */
1221 void
1222 ssh_close_control_file (ssh_control_file_t cf)
1223 {
1224   close_control_file (cf);
1225 }
1226
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. */
1232 gpg_error_t
1233 ssh_read_control_file (ssh_control_file_t cf,
1234                        char *r_hexgrip,
1235                        int *r_disabled, int *r_ttl, int *r_confirm)
1236 {
1237   gpg_error_t err;
1238
1239   do
1240     err = read_control_file_item (cf);
1241   while (!err && !cf->item.valid);
1242   if (!err)
1243     {
1244       if (r_hexgrip)
1245         strcpy (r_hexgrip, cf->item.hexgrip);
1246       if (r_disabled)
1247         *r_disabled = cf->item.disabled;
1248       if (r_ttl)
1249         *r_ttl = cf->item.ttl;
1250       if (r_confirm)
1251         *r_confirm = cf->item.confirm;
1252     }
1253   return err;
1254 }
1255
1256
1257 /* Search for a key with HEXGRIP in sshcontrol and return all
1258    info.  */
1259 gpg_error_t
1260 ssh_search_control_file (ssh_control_file_t cf,
1261                          const char *hexgrip,
1262                          int *r_disabled, int *r_ttl, int *r_confirm)
1263 {
1264   gpg_error_t err;
1265   int i;
1266   const char *s;
1267   char uphexgrip[41];
1268
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
1271      second buffer. */
1272   for (i=0, s=hexgrip; i < 40 && *s; s++, i++)
1273     uphexgrip[i] = *s >= 'a'? (*s & 0xdf): *s;
1274   uphexgrip[i] = 0;
1275   if (i != 40)
1276     err = gpg_error (GPG_ERR_INV_LENGTH);
1277   else
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);
1281   return err;
1282 }
1283
1284
1285 \f
1286
1287 /*
1288
1289   MPI lists.
1290
1291  */
1292
1293 /* Free the list of MPIs MPI_LIST.  */
1294 static void
1295 mpint_list_free (gcry_mpi_t *mpi_list)
1296 {
1297   if (mpi_list)
1298     {
1299       unsigned int i;
1300
1301       for (i = 0; mpi_list[i]; i++)
1302         gcry_mpi_release (mpi_list[i]);
1303       xfree (mpi_list);
1304     }
1305 }
1306
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
1312    code.  */
1313 static gpg_error_t
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)
1317 {
1318   const char *elems_public;
1319   unsigned int elems_n;
1320   const char *elems;
1321   int elem_is_secret;
1322   gcry_mpi_t *mpis = NULL;
1323   gpg_error_t err = 0;
1324   unsigned int i;
1325
1326   if (secret)
1327     elems = spec->elems_key_secret;
1328   else
1329     elems = spec->elems_key_public;
1330   elems_n = strlen (elems);
1331   elems_public = spec->elems_key_public;
1332
1333   /* Check that either noth, CERT and the WITH_CERT flag, are given or
1334      none of them.  */
1335   if (!(!!(spec->flags & SPEC_FLAG_WITH_CERT) ^ !cert))
1336     {
1337       err = gpg_error (GPG_ERR_INV_CERT_OBJ);
1338       goto out;
1339     }
1340
1341   mpis = xtrycalloc (elems_n + 1, sizeof *mpis );
1342   if (!mpis)
1343     {
1344       err = gpg_error_from_syserror ();
1345       goto out;
1346     }
1347
1348   elem_is_secret = 0;
1349   for (i = 0; i < elems_n; i++)
1350     {
1351       if (secret)
1352         elem_is_secret = !strchr (elems_public, elems[i]);
1353
1354       if (cert && !elem_is_secret)
1355         err = stream_read_mpi (cert, elem_is_secret, &mpis[i]);
1356       else
1357         err = stream_read_mpi (stream, elem_is_secret, &mpis[i]);
1358       if (err)
1359         goto out;
1360     }
1361
1362   *mpi_list = mpis;
1363   mpis = NULL;
1364
1365  out:
1366   if (err)
1367     mpint_list_free (mpis);
1368
1369   return err;
1370 }
1371
1372 \f
1373
1374 /* Key modifier function for RSA.  */
1375 static gpg_error_t
1376 ssh_key_modifier_rsa (const char *elems, gcry_mpi_t *mpis)
1377 {
1378   gcry_mpi_t p;
1379   gcry_mpi_t q;
1380   gcry_mpi_t u;
1381
1382   if (strcmp (elems, "nedupq"))
1383     /* Modifying only necessary for secret keys.  */
1384     goto out;
1385
1386   u = mpis[3];
1387   p = mpis[4];
1388   q = mpis[5];
1389
1390   if (gcry_mpi_cmp (p, q) > 0)
1391     {
1392       /* P shall be smaller then Q!  Swap primes.  iqmp becomes u.  */
1393       gcry_mpi_t tmp;
1394
1395       tmp = mpis[4];
1396       mpis[4] = mpis[5];
1397       mpis[5] = tmp;
1398     }
1399   else
1400     /* U needs to be recomputed.  */
1401     gcry_mpi_invm (u, p, q);
1402
1403  out:
1404
1405   return 0;
1406 }
1407
1408 /* Signature encoder function for RSA.  */
1409 static gpg_error_t
1410 ssh_signature_encoder_rsa (ssh_key_type_spec_t *spec,
1411                            estream_t signature_blob,
1412                            gcry_sexp_t s_signature)
1413 {
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;
1419   const char *elems;
1420   size_t elems_n;
1421   int i;
1422
1423   unsigned char *data;
1424   size_t data_n;
1425   gcry_mpi_t s;
1426
1427   valuelist = gcry_sexp_nth (s_signature, 1);
1428   if (!valuelist)
1429     {
1430       err = gpg_error (GPG_ERR_INV_SEXP);
1431       goto out;
1432     }
1433
1434   elems = spec->elems_signature;
1435   elems_n = strlen (elems);
1436
1437   mpis = xtrycalloc (elems_n + 1, sizeof *mpis);
1438   if (!mpis)
1439     {
1440       err = gpg_error_from_syserror ();
1441       goto out;
1442     }
1443
1444   for (i = 0; i < elems_n; i++)
1445     {
1446       sublist = gcry_sexp_find_token (valuelist, spec->elems_signature + i, 1);
1447       if (!sublist)
1448         {
1449           err = gpg_error (GPG_ERR_INV_SEXP);
1450           break;
1451         }
1452
1453       sig_value = gcry_sexp_nth_mpi (sublist, 1, GCRYMPI_FMT_USG);
1454       if (!sig_value)
1455         {
1456           err = gpg_error (GPG_ERR_INTERNAL); /* FIXME?  */
1457           break;
1458         }
1459       gcry_sexp_release (sublist);
1460       sublist = NULL;
1461
1462       mpis[i] = sig_value;
1463     }
1464   if (err)
1465     goto out;
1466
1467   /* RSA specific */
1468   s = mpis[0];
1469
1470   err = gcry_mpi_aprint (GCRYMPI_FMT_USG, &data, &data_n, s);
1471   if (err)
1472     goto out;
1473
1474   err = stream_write_string (signature_blob, data, data_n);
1475   xfree (data);
1476
1477  out:
1478   gcry_sexp_release (valuelist);
1479   gcry_sexp_release (sublist);
1480   mpint_list_free (mpis);
1481   return err;
1482 }
1483
1484
1485 /* Signature encoder function for DSA.  */
1486 static gpg_error_t
1487 ssh_signature_encoder_dsa (ssh_key_type_spec_t *spec,
1488                            estream_t signature_blob,
1489                            gcry_sexp_t s_signature)
1490 {
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;
1496   const char *elems;
1497   size_t elems_n;
1498   int i;
1499
1500   unsigned char buffer[SSH_DSA_SIGNATURE_PADDING * SSH_DSA_SIGNATURE_ELEMS];
1501   unsigned char *data = NULL;
1502   size_t data_n;
1503
1504   valuelist = gcry_sexp_nth (s_signature, 1);
1505   if (!valuelist)
1506     {
1507       err = gpg_error (GPG_ERR_INV_SEXP);
1508       goto out;
1509     }
1510
1511   elems = spec->elems_signature;
1512   elems_n = strlen (elems);
1513
1514   mpis = xtrycalloc (elems_n + 1, sizeof *mpis);
1515   if (!mpis)
1516     {
1517       err = gpg_error_from_syserror ();
1518       goto out;
1519     }
1520
1521   for (i = 0; i < elems_n; i++)
1522     {
1523       sublist = gcry_sexp_find_token (valuelist, spec->elems_signature + i, 1);
1524       if (!sublist)
1525         {
1526           err = gpg_error (GPG_ERR_INV_SEXP);
1527           break;
1528         }
1529
1530       sig_value = gcry_sexp_nth_mpi (sublist, 1, GCRYMPI_FMT_USG);
1531       if (!sig_value)
1532         {
1533           err = gpg_error (GPG_ERR_INTERNAL); /* FIXME?  */
1534           break;
1535         }
1536       gcry_sexp_release (sublist);
1537       sublist = NULL;
1538
1539       mpis[i] = sig_value;
1540     }
1541   if (err)
1542     goto out;
1543
1544   /* DSA specific code.  */
1545
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++)
1549     {
1550       err = gcry_mpi_aprint (GCRYMPI_FMT_USG, &data, &data_n, mpis[i]);
1551       if (err)
1552         break;
1553
1554       if (data_n > SSH_DSA_SIGNATURE_PADDING)
1555         {
1556           err = gpg_error (GPG_ERR_INTERNAL); /* FIXME?  */
1557           break;
1558         }
1559
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);
1564
1565       xfree (data);
1566       data = NULL;
1567     }
1568   if (err)
1569     goto out;
1570
1571   err = stream_write_string (signature_blob, buffer, sizeof (buffer));
1572
1573  out:
1574   xfree (data);
1575   gcry_sexp_release (valuelist);
1576   gcry_sexp_release (sublist);
1577   mpint_list_free (mpis);
1578   return err;
1579 }
1580
1581
1582 /* Signature encoder function for ECDSA.  */
1583 static gpg_error_t
1584 ssh_signature_encoder_ecdsa (ssh_key_type_spec_t *spec,
1585                              estream_t stream, gcry_sexp_t s_signature)
1586 {
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;
1592   const char *elems;
1593   size_t elems_n;
1594   int i;
1595
1596   unsigned char *data[2] = {NULL, NULL};
1597   size_t data_n[2];
1598   size_t innerlen;
1599
1600   valuelist = gcry_sexp_nth (s_signature, 1);
1601   if (!valuelist)
1602     {
1603       err = gpg_error (GPG_ERR_INV_SEXP);
1604       goto out;
1605     }
1606
1607   elems = spec->elems_signature;
1608   elems_n = strlen (elems);
1609
1610   mpis = xtrycalloc (elems_n + 1, sizeof *mpis);
1611   if (!mpis)
1612     {
1613       err = gpg_error_from_syserror ();
1614       goto out;
1615     }
1616
1617   for (i = 0; i < elems_n; i++)
1618     {
1619       sublist = gcry_sexp_find_token (valuelist, spec->elems_signature + i, 1);
1620       if (!sublist)
1621         {
1622           err = gpg_error (GPG_ERR_INV_SEXP);
1623           break;
1624         }
1625
1626       sig_value = gcry_sexp_nth_mpi (sublist, 1, GCRYMPI_FMT_USG);
1627       if (!sig_value)
1628         {
1629           err = gpg_error (GPG_ERR_INTERNAL); /* FIXME?  */
1630           break;
1631         }
1632       gcry_sexp_release (sublist);
1633       sublist = NULL;
1634
1635       mpis[i] = sig_value;
1636     }
1637   if (err)
1638     goto out;
1639
1640   /* ECDSA specific */
1641
1642   innerlen = 0;
1643   for (i = 0; i < DIM(data); i++)
1644     {
1645       err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &data[i], &data_n[i], mpis[i]);
1646       if (err)
1647         goto out;
1648       innerlen += 4 + data_n[i];
1649     }
1650
1651   err = stream_write_uint32 (stream, innerlen);
1652   if (err)
1653     goto out;
1654
1655   for (i = 0; i < DIM(data); i++)
1656     {
1657       err = stream_write_string (stream, data[i], data_n[i]);
1658       if (err)
1659         goto out;
1660     }
1661
1662  out:
1663   for (i = 0; i < DIM(data); i++)
1664     xfree (data[i]);
1665   gcry_sexp_release (valuelist);
1666   gcry_sexp_release (sublist);
1667   mpint_list_free (mpis);
1668   return err;
1669 }
1670
1671
1672 /* Signature encoder function for EdDSA.  */
1673 static gpg_error_t
1674 ssh_signature_encoder_eddsa (ssh_key_type_spec_t *spec,
1675                              estream_t stream, gcry_sexp_t s_signature)
1676 {
1677   gpg_error_t err = 0;
1678   gcry_sexp_t valuelist = NULL;
1679   gcry_sexp_t sublist = NULL;
1680   const char *elems;
1681   size_t elems_n;
1682   int i;
1683
1684   unsigned char *data[2] = {NULL, NULL};
1685   size_t data_n[2];
1686   size_t totallen = 0;
1687
1688   valuelist = gcry_sexp_nth (s_signature, 1);
1689   if (!valuelist)
1690     {
1691       err = gpg_error (GPG_ERR_INV_SEXP);
1692       goto out;
1693     }
1694
1695   elems = spec->elems_signature;
1696   elems_n = strlen (elems);
1697
1698   if (elems_n != DIM(data))
1699     {
1700       err = gpg_error (GPG_ERR_INV_SEXP);
1701       goto out;
1702     }
1703
1704   for (i = 0; i < DIM(data); i++)
1705     {
1706       sublist = gcry_sexp_find_token (valuelist, spec->elems_signature + i, 1);
1707       if (!sublist)
1708         {
1709           err = gpg_error (GPG_ERR_INV_SEXP);
1710           break;
1711         }
1712
1713       data[i] = gcry_sexp_nth_buffer (sublist, 1, &data_n[i]);
1714       if (!data[i])
1715         {
1716           err = gpg_error (GPG_ERR_INTERNAL); /* FIXME?  */
1717           break;
1718         }
1719       totallen += data_n[i];
1720       gcry_sexp_release (sublist);
1721       sublist = NULL;
1722     }
1723   if (err)
1724     goto out;
1725
1726   err = stream_write_uint32 (stream, totallen);
1727   if (err)
1728     goto out;
1729
1730   for (i = 0; i < DIM(data); i++)
1731     {
1732       err = stream_write_data (stream, data[i], data_n[i]);
1733       if (err)
1734         goto out;
1735     }
1736
1737  out:
1738   for (i = 0; i < DIM(data); i++)
1739     xfree (data[i]);
1740   gcry_sexp_release (valuelist);
1741   gcry_sexp_release (sublist);
1742   return err;
1743 }
1744
1745
1746 /*
1747    S-Expressions.
1748  */
1749
1750
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.  */
1754 static gpg_error_t
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)
1759 {
1760   gpg_error_t err;
1761   gcry_sexp_t sexp_new = NULL;
1762   void *formatbuf = NULL;
1763   void **arg_list = NULL;
1764   estream_t format = NULL;
1765
1766
1767   if ((key_spec.flags & SPEC_FLAG_IS_EdDSA))
1768     {
1769       /* It is much easier and more readable to use a separate code
1770          path for EdDSA.  */
1771       if (!curve_name)
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);
1775       else if (secret
1776                && (!mpis[1]
1777                    || !gcry_mpi_get_flag (mpis[1], GCRYMPI_FLAG_OPAQUE)))
1778         err = gpg_error (GPG_ERR_BAD_SECKEY);
1779       else if (secret)
1780         err = gcry_sexp_build (&sexp_new, NULL,
1781                                "(private-key(ecc(curve %s)"
1782                                "(flags eddsa)(q %m)(d %m))"
1783                                "(comment%s))",
1784                                curve_name,
1785                                mpis[0], mpis[1],
1786                                comment? comment:"");
1787       else
1788         err = gcry_sexp_build (&sexp_new, NULL,
1789                                "(public-key(ecc(curve %s)"
1790                                "(flags eddsa)(q %m))"
1791                                "(comment%s))",
1792                                curve_name,
1793                                mpis[0],
1794                                comment? comment:"");
1795     }
1796   else
1797     {
1798       const char *key_identifier[] = { "public-key", "private-key" };
1799       int arg_idx;
1800       const char *elems;
1801       size_t elems_n;
1802       unsigned int i, j;
1803
1804       if (secret)
1805         elems = key_spec.elems_sexp_order;
1806       else
1807         elems = key_spec.elems_key_public;
1808       elems_n = strlen (elems);
1809
1810       format = es_fopenmem (0, "a+b");
1811       if (!format)
1812         {
1813           err = gpg_error_from_syserror ();
1814           goto out;
1815         }
1816
1817       /* Key identifier, algorithm identifier, mpis, comment, and a NULL
1818          as a safeguard. */
1819       arg_list = xtrymalloc (sizeof (*arg_list) * (2 + 1 + elems_n + 1 + 1));
1820       if (!arg_list)
1821         {
1822           err = gpg_error_from_syserror ();
1823           goto out;
1824         }
1825       arg_idx = 0;
1826
1827       es_fputs ("(%s(%s", format);
1828       arg_list[arg_idx++] = &key_identifier[secret];
1829       arg_list[arg_idx++] = &key_spec.identifier;
1830       if (curve_name)
1831         {
1832           es_fputs ("(curve%s)", format);
1833           arg_list[arg_idx++] = &curve_name;
1834         }
1835
1836       for (i = 0; i < elems_n; i++)
1837         {
1838           es_fprintf (format, "(%c%%m)", elems[i]);
1839           if (secret)
1840             {
1841               for (j = 0; j < elems_n; j++)
1842                 if (key_spec.elems_key_secret[j] == elems[i])
1843                   break;
1844             }
1845           else
1846             j = i;
1847           arg_list[arg_idx++] = &mpis[j];
1848         }
1849       es_fputs (")(comment%s))", format);
1850       arg_list[arg_idx++] = &comment;
1851       arg_list[arg_idx] = NULL;
1852
1853       es_putc (0, format);
1854       if (es_ferror (format))
1855         {
1856           err = gpg_error_from_syserror ();
1857           goto out;
1858         }
1859       if (es_fclose_snatch (format, &formatbuf, NULL))
1860         {
1861           err = gpg_error_from_syserror ();
1862           goto out;
1863         }
1864       format = NULL;
1865
1866       err = gcry_sexp_build_array (&sexp_new, NULL, formatbuf, arg_list);
1867     }
1868
1869   if (!err)
1870     *r_sexp = sexp_new;
1871
1872  out:
1873   es_fclose (format);
1874   xfree (arg_list);
1875   xfree (formatbuf);
1876
1877   return err;
1878 }
1879
1880
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!  */
1886 static gpg_error_t
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)
1890 {
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;
1896   void *blob = NULL;
1897   size_t blob_size;
1898   const char *elems, *p_elems;
1899   const char *data;
1900   size_t datalen;
1901
1902   *r_blob = NULL;
1903   *r_blob_size = 0;
1904
1905   stream = es_fopenmem (0, "r+b");
1906   if (!stream)
1907     {
1908       err = gpg_error_from_syserror ();
1909       goto out;
1910     }
1911
1912   /* Get the type of the key extpression.  */
1913   data = gcry_sexp_nth_data (sexp, 0, &datalen);
1914   if (!data)
1915     {
1916       err = gpg_error (GPG_ERR_INV_SEXP);
1917       goto out;
1918     }
1919
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;
1926   else
1927     {
1928       err = gpg_error (GPG_ERR_INV_SEXP);
1929       goto out;
1930     }
1931
1932   /* Get the algorithm identifier.  */
1933   value_list = gcry_sexp_find_token (sexp, key_spec.identifier, 0);
1934   if (!value_list)
1935     {
1936       err = gpg_error (GPG_ERR_INV_SEXP);
1937       goto out;
1938     }
1939
1940   /* Write the ssh algorithm identifier.  */
1941   if ((key_spec.flags & SPEC_FLAG_IS_ECDSA))
1942     {
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.  */
1947       const char *mapped;
1948       const char *sshname;
1949
1950       gcry_sexp_release (value_pair);
1951       value_pair = gcry_sexp_find_token (value_list, "curve", 5);
1952       if (!value_pair)
1953         {
1954           err = gpg_error (GPG_ERR_INV_CURVE);
1955           goto out;
1956         }
1957       curve_name = gcry_sexp_nth_string (value_pair, 1);
1958       if (!curve_name)
1959         {
1960           err = gpg_error (GPG_ERR_INV_CURVE); /* (Or out of core.)  */
1961           goto out;
1962         }
1963
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";
1972       else
1973         mapped = NULL;
1974       if (mapped)
1975         {
1976           xfree (curve_name);
1977           curve_name = xtrystrdup (mapped);
1978           if (!curve_name)
1979             {
1980               err = gpg_error_from_syserror ();
1981               goto out;
1982             }
1983         }
1984
1985       sshname = ssh_identifier_from_curve_name (curve_name);
1986       if (!sshname)
1987         {
1988           err = gpg_error (GPG_ERR_UNKNOWN_CURVE);
1989           goto out;
1990         }
1991       err = stream_write_cstring (stream, sshname);
1992       if (err)
1993         goto out;
1994       err = stream_write_cstring (stream, curve_name);
1995       if (err)
1996         goto out;
1997     }
1998   else
1999     {
2000       /* Note: This is also used for EdDSA.  */
2001       err = stream_write_cstring (stream, key_spec.ssh_identifier);
2002       if (err)
2003         goto out;
2004     }
2005
2006   /* Write the parameters.  */
2007   for (p_elems = elems; *p_elems; p_elems++)
2008     {
2009       gcry_sexp_release (value_pair);
2010       value_pair = gcry_sexp_find_token (value_list, p_elems, 1);
2011       if (!value_pair)
2012         {
2013           err = gpg_error (GPG_ERR_INV_SEXP);
2014           goto out;
2015         }
2016       if ((key_spec.flags & SPEC_FLAG_IS_EdDSA))
2017         {
2018
2019           data = gcry_sexp_nth_data (value_pair, 1, &datalen);
2020           if (!data)
2021             {
2022               err = gpg_error (GPG_ERR_INV_SEXP);
2023               goto out;
2024             }
2025           if (*p_elems == 'q' && datalen)
2026             { /* Remove the prefix 0x40.  */
2027               data++;
2028               datalen--;
2029             }
2030           err = stream_write_string (stream, data, datalen);
2031           if (err)
2032             goto out;
2033         }
2034       else
2035         {
2036           gcry_mpi_t mpi;
2037
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);
2041           if (!mpi)
2042             {
2043               err = gpg_error (GPG_ERR_INV_SEXP);
2044               goto out;
2045             }
2046           err = stream_write_mpi (stream, mpi);
2047           gcry_mpi_release (mpi);
2048           if (err)
2049             goto out;
2050         }
2051     }
2052
2053   if (es_fclose_snatch (stream, &blob, &blob_size))
2054     {
2055       err = gpg_error_from_syserror ();
2056       goto out;
2057     }
2058   stream = NULL;
2059
2060   *r_blob = blob;
2061   blob = NULL;
2062   *r_blob_size = blob_size;
2063
2064  out:
2065   gcry_sexp_release (value_list);
2066   gcry_sexp_release (value_pair);
2067   xfree (curve_name);
2068   es_fclose (stream);
2069   es_free (blob);
2070
2071   return err;
2072 }
2073
2074 /* Extract the car from SEXP, and create a newly created C-string
2075    which is to be stored in IDENTIFIER.  */
2076 static gpg_error_t
2077 sexp_extract_identifier (gcry_sexp_t sexp, char **identifier)
2078 {
2079   char *identifier_new;
2080   gcry_sexp_t sublist;
2081   const char *data;
2082   size_t data_n;
2083   gpg_error_t err;
2084
2085   identifier_new = NULL;
2086   err = 0;
2087
2088   sublist = gcry_sexp_nth (sexp, 1);
2089   if (! sublist)
2090     {
2091       err = gpg_error (GPG_ERR_INV_SEXP);
2092       goto out;
2093     }
2094
2095   data = gcry_sexp_nth_data (sublist, 0, &data_n);
2096   if (! data)
2097     {
2098       err = gpg_error (GPG_ERR_INV_SEXP);
2099       goto out;
2100     }
2101
2102   identifier_new = make_cstring (data, data_n);
2103   if (! identifier_new)
2104     {
2105       err = gpg_err_code_from_errno (errno);
2106       goto out;
2107     }
2108
2109   *identifier = identifier_new;
2110
2111  out:
2112
2113   gcry_sexp_release (sublist);
2114
2115   return err;
2116 }
2117
2118 \f
2119
2120 /*
2121
2122   Key I/O.
2123
2124 */
2125
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.  */
2130 static gpg_error_t
2131 ssh_key_type_lookup (const char *ssh_name, const char *name,
2132                      ssh_key_type_spec_t *spec)
2133 {
2134   gpg_error_t err;
2135   unsigned int i;
2136
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))))
2145       break;
2146
2147   if (i == DIM (ssh_key_types))
2148     err = gpg_error (GPG_ERR_NOT_FOUND);
2149   else
2150     {
2151       *spec = ssh_key_types[i];
2152       err = 0;
2153     }
2154
2155   return err;
2156 }
2157
2158
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.  */
2164 static gpg_error_t
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)
2167 {
2168   gpg_error_t err;
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;
2175   const char *elems;
2176   char *curve_name = NULL;
2177
2178
2179   err = stream_read_cstring (stream, &key_type);
2180   if (err)
2181     goto out;
2182
2183   err = ssh_key_type_lookup (key_type, NULL, &spec);
2184   if (err)
2185     goto out;
2186
2187   if ((spec.flags & SPEC_FLAG_WITH_CERT))
2188     {
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;
2192       u32 buflen;
2193       char *cert_key_type;
2194
2195       err = stream_read_string (stream, 0, &buffer, &buflen);
2196       if (err)
2197         goto out;
2198       cert = es_fopenmem_init (0, "rb", buffer, buflen);
2199       xfree (buffer);
2200       if (!cert)
2201         {
2202           err = gpg_error_from_syserror ();
2203           goto out;
2204         }
2205
2206       /* Check that the key type matches.  */
2207       err = stream_read_cstring (cert, &cert_key_type);
2208       if (err)
2209         goto out;
2210       if (strcmp (cert_key_type, key_type) )
2211         {
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);
2215           goto out;
2216         }
2217       xfree (cert_key_type);
2218
2219       /* Skip the nonce.  */
2220       err = stream_read_string (cert, 0, NULL, NULL);
2221       if (err)
2222         goto out;
2223     }
2224
2225   if ((spec.flags & SPEC_FLAG_IS_EdDSA))
2226     {
2227       /* The format of an EdDSA key is:
2228        *   string       key_type ("ssh-ed25519")
2229        *   string       public_key
2230        *   string       private_key
2231        *
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
2235        * this.
2236        */
2237       mpi_list = xtrycalloc (3, sizeof *mpi_list);
2238       if (!mpi_list)
2239         {
2240           err = gpg_error_from_syserror ();
2241           goto out;
2242         }
2243
2244       err = stream_read_blob (cert? cert : stream, 0, &mpi_list[0]);
2245       if (err)
2246         goto out;
2247       if (secret)
2248         {
2249           u32 len = 0;
2250           unsigned char *buffer;
2251
2252           /* Read string length.  */
2253           err = stream_read_uint32 (stream, &len);
2254           if (err)
2255             goto out;
2256           if (len != 32 && len != 64)
2257             {
2258               err = gpg_error (GPG_ERR_BAD_SECKEY);
2259               goto out;
2260             }
2261           buffer = xtrymalloc_secure (32);
2262           if (!buffer)
2263             {
2264               err = gpg_error_from_syserror ();
2265               goto out;
2266             }
2267           err = stream_read_data (stream, buffer, 32);
2268           if (err)
2269             {
2270               xfree (buffer);
2271               goto out;
2272             }
2273           mpi_list[1] = gcry_mpi_set_opaque (NULL, buffer, 8*32);
2274           buffer = NULL;
2275           if (len == 64)
2276             {
2277               err = stream_read_skip (stream, 32);
2278               if (err)
2279                 goto out;
2280             }
2281         }
2282     }
2283   else if ((spec.flags & SPEC_FLAG_IS_ECDSA))
2284     {
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
2292        *
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
2296        * certificate.
2297        */
2298       unsigned char *buffer;
2299       const char *mapped;
2300
2301       err = stream_read_string (cert? cert : stream, 0, &buffer, NULL);
2302       if (err)
2303         goto out;
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
2308          native names.  */
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";
2315       else
2316         mapped = NULL;
2317       if (mapped)
2318         {
2319           xfree (curve_name);
2320           curve_name = xtrystrdup (mapped);
2321           if (!curve_name)
2322             {
2323               err = gpg_error_from_syserror ();
2324               goto out;
2325             }
2326         }
2327
2328       err = ssh_receive_mpint_list (stream, secret, &spec, cert, &mpi_list);
2329       if (err)
2330         goto out;
2331     }
2332   else
2333     {
2334       err = ssh_receive_mpint_list (stream, secret, &spec, cert, &mpi_list);
2335       if (err)
2336         goto out;
2337     }
2338
2339   if (read_comment)
2340     {
2341       err = stream_read_cstring (stream, &comment);
2342       if (err)
2343         goto out;
2344     }
2345
2346   if (secret)
2347     elems = spec.elems_key_secret;
2348   else
2349     elems = spec.elems_key_public;
2350
2351   if (spec.key_modifier)
2352     {
2353       err = (*spec.key_modifier) (elems, mpi_list);
2354       if (err)
2355         goto out;
2356     }
2357
2358   if ((spec.flags & SPEC_FLAG_IS_EdDSA))
2359     {
2360       if (secret)
2361         {
2362           err = gcry_sexp_build (&key, NULL,
2363                                  "(private-key(ecc(curve \"Ed25519\")"
2364                                  "(flags eddsa)(q %m)(d %m))"
2365                                  "(comment%s))",
2366                                  mpi_list[0], mpi_list[1],
2367                                  comment? comment:"");
2368         }
2369       else
2370         {
2371           err = gcry_sexp_build (&key, NULL,
2372                                  "(public-key(ecc(curve \"Ed25519\")"
2373                                  "(flags eddsa)(q %m))"
2374                                  "(comment%s))",
2375                                  mpi_list[0],
2376                                  comment? comment:"");
2377         }
2378     }
2379   else
2380     {
2381       err = sexp_key_construct (&key, spec, secret, curve_name, mpi_list,
2382                                 comment? comment:"");
2383       if (err)
2384         goto out;
2385     }
2386
2387   if (key_spec)
2388     *key_spec = spec;
2389   *key_new = key;
2390
2391  out:
2392   es_fclose (cert);
2393   mpint_list_free (mpi_list);
2394   xfree (curve_name);
2395   xfree (key_type);
2396   xfree (comment);
2397
2398   return err;
2399 }
2400
2401
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.  */
2405 static gpg_error_t
2406 ssh_send_key_public (estream_t stream, gcry_sexp_t key,
2407                      const char *override_comment)
2408 {
2409   ssh_key_type_spec_t spec;
2410   char *key_type = NULL;
2411   char *comment = NULL;
2412   void *blob = NULL;
2413   size_t bloblen;
2414   gpg_error_t err;
2415
2416   err = sexp_extract_identifier (key, &key_type);
2417   if (err)
2418     goto out;
2419
2420   err = ssh_key_type_lookup (NULL, key_type, &spec);
2421   if (err)
2422     goto out;
2423
2424   err = ssh_key_to_blob (key, 0, spec, &blob, &bloblen);
2425   if (err)
2426     goto out;
2427
2428   err = stream_write_string (stream, blob, bloblen);
2429   if (err)
2430     goto out;
2431
2432   if (override_comment)
2433     err = stream_write_cstring (stream, override_comment);
2434   else
2435     {
2436       err = ssh_key_extract_comment (key, &comment);
2437       if (err)
2438         err = stream_write_cstring (stream, "(none)");
2439       else
2440         err = stream_write_cstring (stream, comment);
2441     }
2442   if (err)
2443     goto out;
2444
2445  out:
2446   xfree (key_type);
2447   xfree (comment);
2448   es_free (blob);
2449
2450   return err;
2451 }
2452
2453
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.  */
2457 static gpg_error_t
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)
2461 {
2462   gpg_error_t err;
2463   estream_t blob_stream;
2464
2465   blob_stream = es_fopenmem (0, "r+b");
2466   if (!blob_stream)
2467     {
2468       err = gpg_error_from_syserror ();
2469       goto out;
2470     }
2471
2472   err = stream_write_data (blob_stream, blob, blob_size);
2473   if (err)
2474     goto out;
2475
2476   err = es_fseek (blob_stream, 0, SEEK_SET);
2477   if (err)
2478     goto out;
2479
2480   err = ssh_receive_key (blob_stream, key_public, 0, 0, key_spec);
2481
2482  out:
2483   es_fclose (blob_stream);
2484   return err;
2485 }
2486
2487 \f
2488
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.  */
2492 static gpg_error_t
2493 ssh_key_grip (gcry_sexp_t key, unsigned char *buffer)
2494 {
2495   if (!gcry_pk_get_keygrip (key, buffer))
2496     {
2497       gpg_error_t err = gcry_pk_testkey (key);
2498       return err? err : gpg_error (GPG_ERR_INTERNAL);
2499     }
2500
2501   return 0;
2502 }
2503
2504
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. */
2510 static gpg_error_t
2511 card_key_available (ctrl_t ctrl, gcry_sexp_t *r_pk, char **cardsn)
2512 {
2513   gpg_error_t err;
2514   char *authkeyid;
2515   char *serialno = NULL;
2516   unsigned char *pkbuf;
2517   size_t pkbuflen;
2518   gcry_sexp_t s_pk;
2519   unsigned char grip[20];
2520
2521   *r_pk = NULL;
2522   if (cardsn)
2523     *cardsn = NULL;
2524
2525   /* First see whether a card is available and whether the application
2526      is supported.  */
2527   err = agent_card_getattr (ctrl, "$AUTHKEYID", &authkeyid);
2528   if ( gpg_err_code (err) == GPG_ERR_CARD_REMOVED )
2529     {
2530       /* Ask for the serial number to reset the card.  */
2531       err = agent_card_serialno (ctrl, &serialno);
2532       if (err)
2533         {
2534           if (opt.verbose)
2535             log_info (_("error getting serial number of card: %s\n"),
2536                       gpg_strerror (err));
2537           return err;
2538         }
2539       log_info (_("detected card with S/N: %s\n"), serialno);
2540       err = agent_card_getattr (ctrl, "$AUTHKEYID", &authkeyid);
2541     }
2542   if (err)
2543     {
2544       log_error (_("no authentication key for ssh on card: %s\n"),
2545                  gpg_strerror (err));
2546       xfree (serialno);
2547       return err;
2548     }
2549
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)) )
2552     {
2553       log_error (_("error getting serial number of card: %s\n"),
2554                  gpg_strerror (err));
2555       xfree (authkeyid);
2556       return err;
2557     }
2558
2559   /* Read the public key.  */
2560   err = agent_card_readkey (ctrl, authkeyid, &pkbuf);
2561   if (err)
2562     {
2563       if (opt.verbose)
2564         log_info (_("no suitable card key found: %s\n"), gpg_strerror (err));
2565       xfree (serialno);
2566       xfree (authkeyid);
2567       return err;
2568     }
2569
2570   pkbuflen = gcry_sexp_canon_len (pkbuf, 0, NULL, NULL);
2571   err = gcry_sexp_sscan (&s_pk, NULL, (char*)pkbuf, pkbuflen);
2572   if (err)
2573     {
2574       log_error ("failed to build S-Exp from received card key: %s\n",
2575                  gpg_strerror (err));
2576       xfree (pkbuf);
2577       xfree (serialno);
2578       xfree (authkeyid);
2579       return err;
2580     }
2581
2582   err = ssh_key_grip (s_pk, grip);
2583   if (err)
2584     {
2585       log_debug ("error computing keygrip from received card key: %s\n",
2586                  gcry_strerror (err));
2587       xfree (pkbuf);
2588       gcry_sexp_release (s_pk);
2589       xfree (serialno);
2590       xfree (authkeyid);
2591       return err;
2592     }
2593
2594   if ( agent_key_available (grip) )
2595     {
2596       /* (Shadow)-key is not available in our key storage.  */
2597       unsigned char *shadow_info;
2598       unsigned char *tmp;
2599
2600       shadow_info = make_shadow_info (serialno, authkeyid);
2601       if (!shadow_info)
2602         {
2603           err = gpg_error_from_syserror ();
2604           xfree (pkbuf);
2605           gcry_sexp_release (s_pk);
2606           xfree (serialno);
2607           xfree (authkeyid);
2608           return err;
2609         }
2610       err = agent_shadow_key (pkbuf, shadow_info, &tmp);
2611       xfree (shadow_info);
2612       if (err)
2613         {
2614           log_error (_("shadowing the key failed: %s\n"), gpg_strerror (err));
2615           xfree (pkbuf);
2616           gcry_sexp_release (s_pk);
2617           xfree (serialno);
2618           xfree (authkeyid);
2619           return err;
2620         }
2621       xfree (pkbuf);
2622       pkbuf = tmp;
2623       pkbuflen = gcry_sexp_canon_len (pkbuf, 0, NULL, NULL);
2624       assert (pkbuflen);
2625
2626       err = agent_write_private_key (grip, pkbuf, pkbuflen, 0);
2627       if (err)
2628         {
2629           log_error (_("error writing key: %s\n"), gpg_strerror (err));
2630           xfree (pkbuf);
2631           gcry_sexp_release (s_pk);
2632           xfree (serialno);
2633           xfree (authkeyid);
2634           return err;
2635         }
2636     }
2637
2638   if (cardsn)
2639     {
2640       char *dispsn;
2641
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))
2645         {
2646           *cardsn = xtryasprintf ("cardno:%s", dispsn);
2647           xfree (dispsn);
2648         }
2649       else
2650         *cardsn = xtryasprintf ("cardno:%s", serialno);
2651       if (!*cardsn)
2652         {
2653           err = gpg_error_from_syserror ();
2654           xfree (pkbuf);
2655           gcry_sexp_release (s_pk);
2656           xfree (serialno);
2657           xfree (authkeyid);
2658           return err;
2659         }
2660     }
2661
2662   xfree (pkbuf);
2663   xfree (serialno);
2664   xfree (authkeyid);
2665   *r_pk = s_pk;
2666   return 0;
2667 }
2668
2669
2670 \f
2671
2672 /*
2673
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.
2677
2678 */
2679
2680
2681 /* Handler for the "request_identities" command.  */
2682 static gpg_error_t
2683 ssh_handler_request_identities (ctrl_t ctrl,
2684                                 estream_t request, estream_t response)
2685 {
2686   ssh_key_type_spec_t spec;
2687   char *key_fname = NULL;
2688   char *fnameptr;
2689   u32 key_counter;
2690   estream_t key_blobs;
2691   gcry_sexp_t key_secret;
2692   gcry_sexp_t key_public;
2693   gpg_error_t err;
2694   int ret;
2695   ssh_control_file_t cf = NULL;
2696   char *cardsn;
2697   gpg_error_t ret_err;
2698
2699   (void)request;
2700
2701   /* Prepare buffer stream.  */
2702
2703   key_secret = NULL;
2704   key_public = NULL;
2705   key_counter = 0;
2706   err = 0;
2707
2708   key_blobs = es_fopenmem (0, "r+b");
2709   if (! key_blobs)
2710     {
2711       err = gpg_error_from_syserror ();
2712       goto out;
2713     }
2714
2715   /* First check whether a key is currently available in the card
2716      reader - this should be allowed even without being listed in
2717      sshcontrol. */
2718
2719   if (!opt.disable_scdaemon
2720       && !card_key_available (ctrl, &key_public, &cardsn))
2721     {
2722       err = ssh_send_key_public (key_blobs, key_public, cardsn);
2723       gcry_sexp_release (key_public);
2724       key_public = NULL;
2725       xfree (cardsn);
2726       if (err)
2727         goto out;
2728
2729       key_counter++;
2730     }
2731
2732
2733   /* Prepare buffer for key name construction.  */
2734   {
2735     char *dname;
2736
2737     dname = make_filename (opt.homedir, GNUPG_PRIVATE_KEYS_DIR, NULL);
2738     if (!dname)
2739       {
2740         err = gpg_err_code_from_syserror ();
2741         goto out;
2742       }
2743
2744     key_fname = xtrymalloc (strlen (dname) + 1 + 40 + 4 + 1);
2745     if (!key_fname)
2746       {
2747         err = gpg_err_code_from_syserror ();
2748         xfree (dname);
2749         goto out;
2750       }
2751     fnameptr = stpcpy (stpcpy (key_fname, dname), "/");
2752     xfree (dname);
2753   }
2754
2755   /* Then look at all the registered and non-disabled keys. */
2756   err = open_control_file (&cf, 0);
2757   if (err)
2758     goto out;
2759
2760   while (!read_control_file_item (cf))
2761     {
2762       if (!cf->item.valid)
2763         continue; /* Should not happen.  */
2764       if (cf->item.disabled)
2765         continue;
2766       assert (strlen (cf->item.hexgrip) == 40);
2767
2768       stpcpy (stpcpy (fnameptr, cf->item.hexgrip), ".key");
2769
2770       /* Read file content.  */
2771       {
2772         unsigned char *buffer;
2773         size_t buffer_n;
2774
2775         err = file_to_buffer (key_fname, &buffer, &buffer_n);
2776         if (err)
2777           {
2778             log_error ("%s:%d: key '%s' skipped: %s\n",
2779                        cf->fname, cf->lnr, cf->item.hexgrip,
2780                        gpg_strerror (err));
2781             continue;
2782           }
2783
2784         err = gcry_sexp_sscan (&key_secret, NULL, (char*)buffer, buffer_n);
2785         xfree (buffer);
2786         if (err)
2787           goto out;
2788       }
2789
2790       {
2791         char *key_type = NULL;
2792
2793         err = sexp_extract_identifier (key_secret, &key_type);
2794         if (err)
2795           goto out;
2796
2797         err = ssh_key_type_lookup (NULL, key_type, &spec);
2798         xfree (key_type);
2799         if (err)
2800           goto out;
2801       }
2802
2803       err = ssh_send_key_public (key_blobs, key_secret, NULL);
2804       if (err)
2805         goto out;
2806       gcry_sexp_release (key_secret);
2807       key_secret = NULL;
2808
2809       key_counter++;
2810     }
2811   err = 0;
2812
2813   ret = es_fseek (key_blobs, 0, SEEK_SET);
2814   if (ret)
2815     {
2816       err = gpg_error_from_syserror ();
2817       goto out;
2818     }
2819
2820  out:
2821   /* Send response.  */
2822
2823   gcry_sexp_release (key_secret);
2824   gcry_sexp_release (key_public);
2825
2826   if (!err)
2827     {
2828       ret_err = stream_write_byte (response, SSH_RESPONSE_IDENTITIES_ANSWER);
2829       if (!ret_err)
2830         ret_err = stream_write_uint32 (response, key_counter);
2831       if (!ret_err)
2832         ret_err = stream_copy (response, key_blobs);
2833     }
2834   else
2835     {
2836       ret_err = stream_write_byte (response, SSH_RESPONSE_FAILURE);
2837     }
2838
2839   es_fclose (key_blobs);
2840   close_control_file (cf);
2841   xfree (key_fname);
2842
2843   return ret_err;
2844 }
2845
2846
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
2850    for the digest.  */
2851 static gpg_error_t
2852 data_hash (unsigned char *data, size_t data_n,
2853            int md_algorithm, unsigned char *hash)
2854 {
2855   gcry_md_hash_buffer (md_algorithm, hash, data, data_n);
2856
2857   return 0;
2858 }
2859
2860
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.  */
2867 static gpg_error_t
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)
2871 {
2872   gpg_error_t err;
2873   gcry_sexp_t signature_sexp = NULL;
2874   estream_t stream = NULL;
2875   void *blob = NULL;
2876   size_t bloblen;
2877   char hexgrip[40+1];
2878
2879   *r_sig = NULL;
2880   *r_siglen = 0;
2881
2882   /* Quick check to see whether we have a valid keygrip and convert it
2883      to hex.  */
2884   if (!ctrl->have_keygrip)
2885     {
2886       err = gpg_error (GPG_ERR_NO_SECKEY);
2887       goto out;
2888     }
2889   bin2hex (ctrl->keygrip, 20, hexgrip);
2890
2891   /* Ask for confirmation if needed.  */
2892   if (confirm_flag_from_sshcontrol (hexgrip))
2893     {
2894       gcry_sexp_t key;
2895       char *fpr, *prompt;
2896       char *comment = NULL;
2897
2898       err = agent_raw_key_from_file (ctrl, ctrl->keygrip, &key);
2899       if (err)
2900         goto out;
2901       err = ssh_get_fingerprint_string (key, &fpr);
2902       if (!err)
2903         {
2904           gcry_sexp_t tmpsxp = gcry_sexp_find_token (key, "comment", 0);
2905           if (tmpsxp)
2906             comment = gcry_sexp_nth_string (tmpsxp, 1);
2907           gcry_sexp_release (tmpsxp);
2908         }
2909       gcry_sexp_release (key);
2910       if (err)
2911         goto out;
2912       prompt = xtryasprintf (L_("An ssh process requested the use of key%%0A"
2913                                 "  %s%%0A"
2914                                 "  (%s)%%0A"
2915                                 "Do you want to allow this?"),
2916                              fpr, comment? comment:"");
2917       xfree (fpr);
2918       gcry_free (comment);
2919       err = agent_get_confirmation (ctrl, prompt, L_("Allow"), L_("Deny"), 0);
2920       xfree (prompt);
2921       if (err)
2922         goto out;
2923     }
2924
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)"),
2930                          &signature_sexp,
2931                          CACHE_MODE_SSH, ttl_from_sshcontrol,
2932                          hash, hashlen);
2933   ctrl->use_auth_call = 0;
2934   if (err)
2935     goto out;
2936
2937   stream = es_fopenmem (0, "r+b");
2938   if (!stream)
2939     {
2940       err = gpg_error_from_syserror ();
2941       goto out;
2942     }
2943
2944   err = stream_write_cstring (stream, spec->ssh_identifier);
2945   if (err)
2946     goto out;
2947
2948   err = spec->signature_encoder (spec, stream, signature_sexp);
2949   if (err)
2950     goto out;
2951
2952   err = es_fclose_snatch (stream, &blob, &bloblen);
2953   if (err)
2954     goto out;
2955   stream = NULL;
2956
2957   *r_sig = blob; blob = NULL;
2958   *r_siglen = bloblen;
2959
2960  out:
2961   xfree (blob);
2962   es_fclose (stream);
2963   gcry_sexp_release (signature_sexp);
2964
2965   return err;
2966 }
2967
2968
2969 /* Handler for the "sign_request" command.  */
2970 static gpg_error_t
2971 ssh_handler_sign_request (ctrl_t ctrl, estream_t request, estream_t response)
2972 {
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;
2979   u32 key_blob_size;
2980   unsigned char *data = NULL;
2981   unsigned char *sig = NULL;
2982   size_t sig_n;
2983   u32 data_size;
2984   u32 flags;
2985   gpg_error_t err;
2986   gpg_error_t ret_err;
2987   int hash_algo;
2988
2989   /* Receive key.  */
2990
2991   err = stream_read_string (request, 0, &key_blob, &key_blob_size);
2992   if (err)
2993     goto out;
2994
2995   err = ssh_read_key_public_from_blob (key_blob, key_blob_size, &key, &spec);
2996   if (err)
2997     goto out;
2998
2999   /* Receive data to sign.  */
3000   err = stream_read_string (request, 0, &data, &data_size);
3001   if (err)
3002     goto out;
3003
3004   /* FIXME?  */
3005   err = stream_read_uint32 (request, &flags);
3006   if (err)
3007     goto out;
3008
3009   hash_algo = spec.hash_algo;
3010   if (!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;
3015   else
3016     ctrl->digest.raw_value = 1;
3017
3018   /* Calculate key grip.  */
3019   err = ssh_key_grip (key, key_grip);
3020   if (err)
3021     goto out;
3022   ctrl->have_keygrip = 1;
3023   memcpy (ctrl->keygrip, key_grip, 20);
3024
3025   /* Hash data unless we use EdDSA.  */
3026   if ((spec.flags & SPEC_FLAG_IS_EdDSA))
3027     {
3028       ctrl->digest.valuelen = 0;
3029     }
3030   else
3031     {
3032       hash_n = gcry_md_get_algo_dlen (hash_algo);
3033       if (!hash_n)
3034         {
3035           err = gpg_error (GPG_ERR_INTERNAL);
3036           goto out;
3037         }
3038       err = data_hash (data, data_size, hash_algo, hash);
3039       if (err)
3040         goto out;
3041       memcpy (ctrl->digest.value, hash, hash_n);
3042       ctrl->digest.valuelen = hash_n;
3043     }
3044
3045   /* Sign data.  */
3046   if ((spec.flags & SPEC_FLAG_IS_EdDSA))
3047     err = data_sign (ctrl, &spec, data, data_size, &sig, &sig_n);
3048   else
3049     err = data_sign (ctrl, &spec, NULL, 0, &sig, &sig_n);
3050
3051  out:
3052   /* Done.  */
3053   if (!err)
3054     {
3055       ret_err = stream_write_byte (response, SSH_RESPONSE_SIGN_RESPONSE);
3056       if (ret_err)
3057         goto leave;
3058       ret_err = stream_write_string (response, sig, sig_n);
3059       if (ret_err)
3060         goto leave;
3061     }
3062   else
3063     {
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);
3067       if (ret_err)
3068         goto leave;
3069     }
3070
3071  leave:
3072
3073   gcry_sexp_release (key);
3074   xfree (key_blob);
3075   xfree (data);
3076   es_free (sig);
3077
3078   return ret_err;
3079 }
3080
3081
3082 /* This function extracts the comment contained in the key
3083    s-expression KEY and stores a copy in COMMENT.  Returns usual error
3084    code.  */
3085 static gpg_error_t
3086 ssh_key_extract_comment (gcry_sexp_t key, char **r_comment)
3087 {
3088   gcry_sexp_t comment_list;
3089
3090   *r_comment = NULL;
3091
3092   comment_list = gcry_sexp_find_token (key, "comment", 0);
3093   if (!comment_list)
3094     return gpg_error (GPG_ERR_INV_SEXP);
3095
3096   *r_comment = gcry_sexp_nth_string (comment_list, 1);
3097   gcry_sexp_release (comment_list);
3098   if (!*r_comment)
3099     return gpg_error (GPG_ERR_INV_SEXP);
3100
3101   return 0;
3102 }
3103
3104
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.  */
3108 static gpg_error_t
3109 ssh_key_to_protected_buffer (gcry_sexp_t key, const char *passphrase,
3110                              unsigned char **buffer, size_t *buffer_n)
3111 {
3112   unsigned char *buffer_new;
3113   unsigned int buffer_new_n;
3114   gpg_error_t err;
3115
3116   err = 0;
3117   buffer_new_n = gcry_sexp_sprint (key, GCRYSEXP_FMT_CANON, NULL, 0);
3118   buffer_new = xtrymalloc_secure (buffer_new_n);
3119   if (! buffer_new)
3120     {
3121       err = gpg_error_from_syserror ();
3122       goto out;
3123     }
3124
3125   gcry_sexp_sprint (key, GCRYSEXP_FMT_CANON, buffer_new, buffer_new_n);
3126   /* FIXME: guarantee?  */
3127
3128   err = agent_protect (buffer_new, passphrase, buffer, buffer_n, 0);
3129
3130  out:
3131
3132   xfree (buffer_new);
3133
3134   return err;
3135 }
3136
3137
3138
3139 /* Callback function to compare the first entered PIN with the one
3140    currently being entered. */
3141 static gpg_error_t
3142 reenter_compare_cb (struct pin_entry_info_s *pi)
3143 {
3144   const char *pin1 = pi->check_cb_arg;
3145
3146   if (!strcmp (pin1, pi->pin))
3147     return 0; /* okay */
3148   return gpg_error (GPG_ERR_BAD_PASSPHRASE);
3149 }
3150
3151
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.  */
3157 static gpg_error_t
3158 ssh_identity_register (ctrl_t ctrl, ssh_key_type_spec_t *spec,
3159                        gcry_sexp_t key, int ttl, int confirm)
3160 {
3161   gpg_error_t err;
3162   unsigned char key_grip_raw[20];
3163   char key_grip[41];
3164   unsigned char *buffer = NULL;
3165   size_t buffer_n;
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;
3173
3174   err = ssh_key_grip (key, key_grip_raw);
3175   if (err)
3176     goto out;
3177
3178   /* Check whether the key is already in our key storage.  Don't do
3179      anything then.  */
3180   if ( !agent_key_available (key_grip_raw) )
3181     goto out; /* Yes, key is available.  */
3182
3183   err = ssh_get_fingerprint_string (key, &key_fpr);
3184   if (err)
3185     goto out;
3186
3187   err = ssh_key_extract_comment (key, &comment);
3188   if (err)
3189     goto out;
3190
3191   if ( asprintf (&description,
3192                  L_("Please enter a passphrase to protect"
3193                     " the received secret key%%0A"
3194                     "   %s%%0A"
3195                     "   %s%%0A"
3196                     "within gpg-agent's key storage"),
3197                  key_fpr, comment ? comment : "") < 0)
3198     {
3199       err = gpg_error_from_syserror ();
3200       goto out;
3201     }
3202
3203   pi = gcry_calloc_secure (1, sizeof (*pi) + MAX_PASSPHRASE_LEN + 1);
3204   if (!pi)
3205     {
3206       err = gpg_error_from_syserror ();
3207       goto out;
3208     }
3209   pi2 = gcry_calloc_secure (1, sizeof (*pi2) + MAX_PASSPHRASE_LEN + 1);
3210   if (!pi2)
3211     {
3212       err = gpg_error_from_syserror ();
3213       goto out;
3214     }
3215   pi->max_length = MAX_PASSPHRASE_LEN + 1;
3216   pi->max_tries = 1;
3217   pi->with_repeat = 1;
3218   pi2->max_length = MAX_PASSPHRASE_LEN + 1;
3219   pi2->max_tries = 1;
3220   pi2->check_cb = reenter_compare_cb;
3221   pi2->check_cb_arg = pi->pin;
3222
3223  next_try:
3224   err = agent_askpin (ctrl, description, NULL, initial_errtext, pi, NULL, 0);
3225   initial_errtext = NULL;
3226   if (err)
3227     goto out;
3228
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)
3232     {
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
3236              hit cancel. */
3237           initial_errtext = L_("does not match - try again");
3238           goto next_try;
3239         }
3240     }
3241
3242   err = ssh_key_to_protected_buffer (key, pi->pin, &buffer, &buffer_n);
3243   if (err)
3244     goto out;
3245
3246   /* Store this key to our key storage.  */
3247   err = agent_write_private_key (key_grip_raw, buffer, buffer_n, 0);
3248   if (err)
3249     goto out;
3250
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);
3254   if (err)
3255     goto out;
3256
3257   /* And add an entry to the sshcontrol file.  */
3258   err = add_control_entry (ctrl, spec, key_grip, key_fpr, ttl, confirm);
3259
3260
3261  out:
3262   if (pi2 && pi2->max_length)
3263     wipememory (pi2->pin, pi2->max_length);
3264   xfree (pi2);
3265   if (pi && pi->max_length)
3266     wipememory (pi->pin, pi->max_length);
3267   xfree (pi);
3268   xfree (buffer);
3269   xfree (comment);
3270   xfree (key_fpr);
3271   xfree (description);
3272
3273   return err;
3274 }
3275
3276
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.  */
3280 static gpg_error_t
3281 ssh_identity_drop (gcry_sexp_t key)
3282 {
3283   unsigned char key_grip[21] = { 0 };
3284   gpg_error_t err;
3285
3286   err = ssh_key_grip (key, key_grip);
3287   if (err)
3288     goto out;
3289
3290   key_grip[sizeof (key_grip) - 1] = 0;
3291
3292   /* FIXME: What to do here - forgetting the passphrase or deleting
3293      the key from key cache?  */
3294
3295  out:
3296
3297   return err;
3298 }
3299
3300 /* Handler for the "add_identity" command.  */
3301 static gpg_error_t
3302 ssh_handler_add_identity (ctrl_t ctrl, estream_t request, estream_t response)
3303 {
3304   gpg_error_t ret_err;
3305   ssh_key_type_spec_t spec;
3306   gpg_error_t err;
3307   gcry_sexp_t key;
3308   unsigned char b;
3309   int confirm;
3310   int ttl;
3311
3312   confirm = 0;
3313   key = NULL;
3314   ttl = 0;
3315
3316   /* FIXME?  */
3317   err = ssh_receive_key (request, &key, 1, 1, &spec);
3318   if (err)
3319     goto out;
3320
3321   while (1)
3322     {
3323       err = stream_read_byte (request, &b);
3324       if (gpg_err_code (err) == GPG_ERR_EOF)
3325         {
3326           err = 0;
3327           break;
3328         }
3329
3330       switch (b)
3331         {
3332         case SSH_OPT_CONSTRAIN_LIFETIME:
3333           {
3334             u32 n = 0;
3335
3336             err = stream_read_uint32 (request, &n);
3337             if (! err)
3338               ttl = n;
3339             break;
3340           }
3341
3342         case SSH_OPT_CONSTRAIN_CONFIRM:
3343           {
3344             confirm = 1;
3345             break;
3346           }
3347
3348         default:
3349           /* FIXME: log/bad?  */
3350           break;
3351         }
3352     }
3353   if (err)
3354     goto out;
3355
3356   err = ssh_identity_register (ctrl, &spec, key, ttl, confirm);
3357
3358  out:
3359
3360   gcry_sexp_release (key);
3361
3362   if (! err)
3363     ret_err = stream_write_byte (response, SSH_RESPONSE_SUCCESS);
3364   else
3365     ret_err = stream_write_byte (response, SSH_RESPONSE_FAILURE);
3366
3367   return ret_err;
3368 }
3369
3370 /* Handler for the "remove_identity" command.  */
3371 static gpg_error_t
3372 ssh_handler_remove_identity (ctrl_t ctrl,
3373                              estream_t request, estream_t response)
3374 {
3375   unsigned char *key_blob;
3376   u32 key_blob_size;
3377   gcry_sexp_t key;
3378   gpg_error_t ret_err;
3379   gpg_error_t err;
3380
3381   (void)ctrl;
3382
3383   /* Receive key.  */
3384
3385   key_blob = NULL;
3386   key = NULL;
3387
3388   err = stream_read_string (request, 0, &key_blob, &key_blob_size);
3389   if (err)
3390     goto out;
3391
3392   err = ssh_read_key_public_from_blob (key_blob, key_blob_size, &key, NULL);
3393   if (err)
3394     goto out;
3395
3396   err = ssh_identity_drop (key);
3397
3398  out:
3399
3400   xfree (key_blob);
3401   gcry_sexp_release (key);
3402
3403   if (! err)
3404     ret_err = stream_write_byte (response, SSH_RESPONSE_SUCCESS);
3405   else
3406     ret_err = stream_write_byte (response, SSH_RESPONSE_FAILURE);
3407
3408   return ret_err;
3409 }
3410
3411 /* FIXME: stub function.  Actually useful?  */
3412 static gpg_error_t
3413 ssh_identities_remove_all (void)
3414 {
3415   gpg_error_t err;
3416
3417   err = 0;
3418
3419   /* FIXME: shall we remove _all_ cache entries or only those
3420      registered through the ssh emulation?  */
3421
3422   return err;
3423 }
3424
3425 /* Handler for the "remove_all_identities" command.  */
3426 static gpg_error_t
3427 ssh_handler_remove_all_identities (ctrl_t ctrl,
3428                                    estream_t request, estream_t response)
3429 {
3430   gpg_error_t ret_err;
3431   gpg_error_t err;
3432
3433   (void)ctrl;
3434   (void)request;
3435
3436   err = ssh_identities_remove_all ();
3437
3438   if (! err)
3439     ret_err = stream_write_byte (response, SSH_RESPONSE_SUCCESS);
3440   else
3441     ret_err = stream_write_byte (response, SSH_RESPONSE_FAILURE);
3442
3443   return ret_err;
3444 }
3445
3446 /* Lock agent?  FIXME: stub function.  */
3447 static gpg_error_t
3448 ssh_lock (void)
3449 {
3450   gpg_error_t err;
3451
3452   /* FIXME */
3453   log_error ("ssh-agent's lock command is not implemented\n");
3454   err = 0;
3455
3456   return err;
3457 }
3458
3459 /* Unock agent?  FIXME: stub function.  */
3460 static gpg_error_t
3461 ssh_unlock (void)
3462 {
3463   gpg_error_t err;
3464
3465   log_error ("ssh-agent's unlock command is not implemented\n");
3466   err = 0;
3467
3468   return err;
3469 }
3470
3471 /* Handler for the "lock" command.  */
3472 static gpg_error_t
3473 ssh_handler_lock (ctrl_t ctrl, estream_t request, estream_t response)
3474 {
3475   gpg_error_t ret_err;
3476   gpg_error_t err;
3477
3478   (void)ctrl;
3479   (void)request;
3480
3481   err = ssh_lock ();
3482
3483   if (! err)
3484     ret_err = stream_write_byte (response, SSH_RESPONSE_SUCCESS);
3485   else
3486     ret_err = stream_write_byte (response, SSH_RESPONSE_FAILURE);
3487
3488   return ret_err;
3489 }
3490
3491 /* Handler for the "unlock" command.  */
3492 static gpg_error_t
3493 ssh_handler_unlock (ctrl_t ctrl, estream_t request, estream_t response)
3494 {
3495   gpg_error_t ret_err;
3496   gpg_error_t err;
3497
3498   (void)ctrl;
3499   (void)request;
3500
3501   err = ssh_unlock ();
3502
3503   if (! err)
3504     ret_err = stream_write_byte (response, SSH_RESPONSE_SUCCESS);
3505   else
3506     ret_err = stream_write_byte (response, SSH_RESPONSE_FAILURE);
3507
3508   return ret_err;
3509 }
3510
3511 \f
3512
3513 /* Return the request specification for the request identified by TYPE
3514    or NULL in case the requested request specification could not be
3515    found.  */
3516 static ssh_request_spec_t *
3517 request_spec_lookup (int type)
3518 {
3519   ssh_request_spec_t *spec;
3520   unsigned int i;
3521
3522   for (i = 0; i < DIM (request_specs); i++)
3523     if (request_specs[i].type == type)
3524       break;
3525   if (i == DIM (request_specs))
3526     {
3527       if (opt.verbose)
3528         log_info ("ssh request %u is not supported\n", type);
3529       spec = NULL;
3530     }
3531   else
3532     spec = request_specs + i;
3533
3534   return spec;
3535 }
3536
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.  */
3540 static int
3541 ssh_request_process (ctrl_t ctrl, estream_t stream_sock)
3542 {
3543   ssh_request_spec_t *spec;
3544   estream_t response = NULL;
3545   estream_t request = NULL;
3546   unsigned char request_type;
3547   gpg_error_t err;
3548   int send_err = 0;
3549   int ret;
3550   unsigned char *request_data = NULL;
3551   u32 request_data_size;
3552   u32 response_size;
3553
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.
3558
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.
3564      -moritz */
3565
3566   /* Retrieve request.  */
3567   err = stream_read_string (stream_sock, 1, &request_data, &request_data_size);
3568   if (err)
3569     goto out;
3570
3571   if (opt.verbose > 1)
3572     log_info ("received ssh request of length %u\n",
3573               (unsigned int)request_data_size);
3574
3575   if (! request_data_size)
3576     {
3577       send_err = 1;
3578       goto out;
3579       /* Broken request; FIXME.  */
3580     }
3581
3582   request_type = request_data[0];
3583   spec = request_spec_lookup (request_type);
3584   if (! spec)
3585     {
3586       send_err = 1;
3587       goto out;
3588       /* Unknown request; FIXME.  */
3589     }
3590
3591   if (spec->secret_input)
3592     request = es_mopen (NULL, 0, 0, 1, realloc_secure, gcry_free, "r+b");
3593   else
3594     request = es_mopen (NULL, 0, 0, 1, gcry_realloc, gcry_free, "r+b");
3595   if (! request)
3596     {
3597       err = gpg_error_from_syserror ();
3598       goto out;
3599     }
3600   ret = es_setvbuf (request, NULL, _IONBF, 0);
3601   if (ret)
3602     {
3603       err = gpg_error_from_syserror ();
3604       goto out;
3605     }
3606   err = stream_write_data (request, request_data + 1, request_data_size - 1);
3607   if (err)
3608     goto out;
3609   es_rewind (request);
3610
3611   response = es_fopenmem (0, "r+b");
3612   if (! response)
3613     {
3614       err = gpg_error_from_syserror ();
3615       goto out;
3616     }
3617
3618   if (opt.verbose)
3619     log_info ("ssh request handler for %s (%u) started\n",
3620                spec->identifier, spec->type);
3621
3622   err = (*spec->handler) (ctrl, request, response);
3623
3624   if (opt.verbose)
3625     {
3626       if (err)
3627         log_info ("ssh request handler for %s (%u) failed: %s\n",
3628                   spec->identifier, spec->type, gpg_strerror (err));
3629       else
3630         log_info ("ssh request handler for %s (%u) ready\n",
3631                   spec->identifier, spec->type);
3632     }
3633
3634   if (err)
3635     {
3636       send_err = 1;
3637       goto out;
3638     }
3639
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);
3644
3645   err = es_fseek (response, 0, SEEK_SET);
3646   if (err)
3647     {
3648       send_err = 1;
3649       goto out;
3650     }
3651
3652   err = stream_write_uint32 (stream_sock, response_size);
3653   if (err)
3654     {
3655       send_err = 1;
3656       goto out;
3657     }
3658
3659   err = stream_copy (stream_sock, response);
3660   if (err)
3661     goto out;
3662
3663   err = es_fflush (stream_sock);
3664   if (err)
3665     goto out;
3666
3667  out:
3668
3669   if (err && es_feof (stream_sock))
3670     log_error ("error occurred while processing request: %s\n",
3671                gpg_strerror (err));
3672
3673   if (send_err)
3674     {
3675       if (opt.verbose > 1)
3676         log_info ("sending ssh error response\n");
3677       err = stream_write_uint32 (stream_sock, 1);
3678       if (err)
3679         goto leave;
3680       err = stream_write_byte (stream_sock, SSH_RESPONSE_FAILURE);
3681       if (err)
3682         goto leave;
3683     }
3684
3685  leave:
3686
3687   es_fclose (request);
3688   es_fclose (response);
3689   xfree (request_data);
3690
3691   return !!err;
3692 }
3693
3694
3695 /* Start serving client on SOCK_CLIENT.  */
3696 void
3697 start_command_handler_ssh (ctrl_t ctrl, gnupg_fd_t sock_client)
3698 {
3699   estream_t stream_sock = NULL;
3700   gpg_error_t err;
3701   int ret;
3702
3703   err = agent_copy_startup_env (ctrl);
3704   if (err)
3705     goto out;
3706
3707   /* Create stream from socket.  */
3708   stream_sock = es_fdopen (FD2INT(sock_client), "r+");
3709   if (!stream_sock)
3710     {
3711       err = gpg_error_from_syserror ();
3712       log_error (_("failed to create stream from socket: %s\n"),
3713                  gpg_strerror (err));
3714       goto out;
3715     }
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);
3719   if (ret)
3720     {
3721       err = gpg_error_from_syserror ();
3722       log_error ("failed to disable buffering "
3723                  "on socket stream: %s\n", gpg_strerror (err));
3724       goto out;
3725     }
3726
3727   /* Main processing loop. */
3728   while ( !ssh_request_process (ctrl, stream_sock) )
3729     {
3730       /* Check wether we have reached EOF before trying to read
3731          another request.  */
3732       int c;
3733
3734       c = es_fgetc (stream_sock);
3735       if (c == EOF)
3736         break;
3737       es_ungetc (c, stream_sock);
3738     }
3739
3740   /* Reset the SCD in case it has been used. */
3741   agent_reset_scd (ctrl);
3742
3743
3744  out:
3745   if (stream_sock)
3746     es_fclose (stream_sock);
3747 }
3748
3749
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.  */
3755 int
3756 serve_mmapped_ssh_request (ctrl_t ctrl,
3757                            unsigned char *request, size_t maxreqlen)
3758 {
3759   gpg_error_t err;
3760   int send_err = 0;
3761   int valid_response = 0;
3762   ssh_request_spec_t *spec;
3763   u32 msglen;
3764   estream_t request_stream, response_stream;
3765
3766   if (agent_copy_startup_env (ctrl))
3767     goto leave; /* Error setting up the environment.  */
3768
3769   if (maxreqlen < 5)
3770     goto leave; /* Caller error.  */
3771
3772   msglen = uint32_construct (request[0], request[1], request[2], request[3]);
3773   if (msglen < 1 || msglen > maxreqlen - 4)
3774     {
3775       log_error ("ssh message len (%u) out of range", (unsigned int)msglen);
3776       goto leave;
3777     }
3778
3779   spec = request_spec_lookup (request[4]);
3780   if (!spec)
3781     {
3782       send_err = 1;  /* Unknown request type.  */
3783       goto leave;
3784     }
3785
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+");
3789   else
3790     request_stream = es_mopen (NULL, 0, 0, 1, gcry_realloc, gcry_free, "r+");
3791   if (!request_stream)
3792     {
3793       err = gpg_error_from_syserror ();
3794       goto leave;
3795     }
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))
3799     {
3800       err = gpg_error_from_syserror ();
3801       goto leave;
3802     }
3803   /* Copy the request to the stream but omit the request type.  */
3804   err = stream_write_data (request_stream, request + 5, msglen - 1);
3805   if (err)
3806     goto leave;
3807   es_rewind (request_stream);
3808
3809   response_stream = es_fopenmem (0, "r+b");
3810   if (!response_stream)
3811     {
3812       err = gpg_error_from_syserror ();
3813       goto leave;
3814     }
3815
3816   if (opt.verbose)
3817     log_info ("ssh request handler for %s (%u) started\n",
3818                spec->identifier, spec->type);
3819
3820   err = (*spec->handler) (ctrl, request_stream, response_stream);
3821
3822   if (opt.verbose)
3823     {
3824       if (err)
3825         log_info ("ssh request handler for %s (%u) failed: %s\n",
3826                   spec->identifier, spec->type, gpg_strerror (err));
3827       else
3828         log_info ("ssh request handler for %s (%u) ready\n",
3829                   spec->identifier, spec->type);
3830     }
3831
3832   es_fclose (request_stream);
3833   request_stream = NULL;
3834
3835   if (err)
3836     {
3837       send_err = 1;
3838       goto leave;
3839     }
3840
3841   /* Put the response back into the mmapped buffer.  */
3842   {
3843     void *response_data;
3844     size_t response_size;
3845
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))
3849       {
3850         log_error ("snatching ssh response failed: %s",
3851                    gpg_strerror (gpg_error_from_syserror ()));
3852         send_err = 1; /* Ooops.  */
3853         goto leave;
3854       }
3855
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)
3860       {
3861         log_error ("invalid length of the ssh response: %s",
3862                    gpg_strerror (GPG_ERR_INTERNAL));
3863         es_free (response_data);
3864         send_err = 1;
3865         goto leave;
3866       }
3867
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);
3874     valid_response = 1;
3875   }
3876
3877  leave:
3878   if (send_err)
3879     {
3880       request[0] = 0;
3881       request[1] = 0;
3882       request[2] = 0;
3883       request[3] = 1;
3884       request[4] = SSH_RESPONSE_FAILURE;
3885       valid_response = 1;
3886     }
3887
3888   /* Reset the SCD in case it has been used. */
3889   agent_reset_scd (ctrl);
3890
3891   return valid_response? 0 : -1;
3892 }
3893 #endif /*HAVE_W32_SYSTEM*/