Add support for mechanisms with no integrity
[openssh.git] / key.c
1 /* $OpenBSD: key.c,v 1.96 2011/02/04 00:44:21 djm Exp $ */
2 /*
3  * read_bignum():
4  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5  *
6  * As far as I am concerned, the code I have written for this software
7  * can be used freely for any purpose.  Any derived versions of this
8  * software must be clearly marked as such, and if the derived work is
9  * incompatible with the protocol description in the RFC file, it must be
10  * called by a name other than "ssh" or "Secure Shell".
11  *
12  *
13  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
14  * Copyright (c) 2008 Alexander von Gernler.  All rights reserved.
15  *
16  * Redistribution and use in source and binary forms, with or without
17  * modification, are permitted provided that the following conditions
18  * are met:
19  * 1. Redistributions of source code must retain the above copyright
20  *    notice, this list of conditions and the following disclaimer.
21  * 2. Redistributions in binary form must reproduce the above copyright
22  *    notice, this list of conditions and the following disclaimer in the
23  *    documentation and/or other materials provided with the distribution.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
26  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
27  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
28  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
29  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
31  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
32  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
34  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35  */
36
37 #include "includes.h"
38
39 #include <sys/param.h>
40 #include <sys/types.h>
41
42 #include <openssl/evp.h>
43 #include <openbsd-compat/openssl-compat.h>
44
45 #include <stdarg.h>
46 #include <stdio.h>
47 #include <string.h>
48
49 #include "xmalloc.h"
50 #include "key.h"
51 #include "rsa.h"
52 #include "uuencode.h"
53 #include "buffer.h"
54 #include "log.h"
55 #include "misc.h"
56 #include "ssh2.h"
57
58 static struct KeyCert *
59 cert_new(void)
60 {
61         struct KeyCert *cert;
62
63         cert = xcalloc(1, sizeof(*cert));
64         buffer_init(&cert->certblob);
65         buffer_init(&cert->critical);
66         buffer_init(&cert->extensions);
67         cert->key_id = NULL;
68         cert->principals = NULL;
69         cert->signature_key = NULL;
70         return cert;
71 }
72
73 Key *
74 key_new(int type)
75 {
76         Key *k;
77         RSA *rsa;
78         DSA *dsa;
79         k = xcalloc(1, sizeof(*k));
80         k->type = type;
81         k->ecdsa = NULL;
82         k->ecdsa_nid = -1;
83         k->dsa = NULL;
84         k->rsa = NULL;
85         k->cert = NULL;
86         switch (k->type) {
87         case KEY_RSA1:
88         case KEY_RSA:
89         case KEY_RSA_CERT_V00:
90         case KEY_RSA_CERT:
91                 if ((rsa = RSA_new()) == NULL)
92                         fatal("key_new: RSA_new failed");
93                 if ((rsa->n = BN_new()) == NULL)
94                         fatal("key_new: BN_new failed");
95                 if ((rsa->e = BN_new()) == NULL)
96                         fatal("key_new: BN_new failed");
97                 k->rsa = rsa;
98                 break;
99         case KEY_DSA:
100         case KEY_DSA_CERT_V00:
101         case KEY_DSA_CERT:
102                 if ((dsa = DSA_new()) == NULL)
103                         fatal("key_new: DSA_new failed");
104                 if ((dsa->p = BN_new()) == NULL)
105                         fatal("key_new: BN_new failed");
106                 if ((dsa->q = BN_new()) == NULL)
107                         fatal("key_new: BN_new failed");
108                 if ((dsa->g = BN_new()) == NULL)
109                         fatal("key_new: BN_new failed");
110                 if ((dsa->pub_key = BN_new()) == NULL)
111                         fatal("key_new: BN_new failed");
112                 k->dsa = dsa;
113                 break;
114 #ifdef OPENSSL_HAS_ECC
115         case KEY_ECDSA:
116         case KEY_ECDSA_CERT:
117                 /* Cannot do anything until we know the group */
118                 break;
119 #endif
120         case KEY_UNSPEC:
121                 break;
122         default:
123                 fatal("key_new: bad key type %d", k->type);
124                 break;
125         }
126
127         if (key_is_cert(k))
128                 k->cert = cert_new();
129
130         return k;
131 }
132
133 void
134 key_add_private(Key *k)
135 {
136         switch (k->type) {
137         case KEY_RSA1:
138         case KEY_RSA:
139         case KEY_RSA_CERT_V00:
140         case KEY_RSA_CERT:
141                 if ((k->rsa->d = BN_new()) == NULL)
142                         fatal("key_new_private: BN_new failed");
143                 if ((k->rsa->iqmp = BN_new()) == NULL)
144                         fatal("key_new_private: BN_new failed");
145                 if ((k->rsa->q = BN_new()) == NULL)
146                         fatal("key_new_private: BN_new failed");
147                 if ((k->rsa->p = BN_new()) == NULL)
148                         fatal("key_new_private: BN_new failed");
149                 if ((k->rsa->dmq1 = BN_new()) == NULL)
150                         fatal("key_new_private: BN_new failed");
151                 if ((k->rsa->dmp1 = BN_new()) == NULL)
152                         fatal("key_new_private: BN_new failed");
153                 break;
154         case KEY_DSA:
155         case KEY_DSA_CERT_V00:
156         case KEY_DSA_CERT:
157                 if ((k->dsa->priv_key = BN_new()) == NULL)
158                         fatal("key_new_private: BN_new failed");
159                 break;
160         case KEY_ECDSA:
161         case KEY_ECDSA_CERT:
162                 /* Cannot do anything until we know the group */
163                 break;
164         case KEY_UNSPEC:
165                 break;
166         default:
167                 break;
168         }
169 }
170
171 Key *
172 key_new_private(int type)
173 {
174         Key *k = key_new(type);
175
176         key_add_private(k);
177         return k;
178 }
179
180 static void
181 cert_free(struct KeyCert *cert)
182 {
183         u_int i;
184
185         buffer_free(&cert->certblob);
186         buffer_free(&cert->critical);
187         buffer_free(&cert->extensions);
188         if (cert->key_id != NULL)
189                 xfree(cert->key_id);
190         for (i = 0; i < cert->nprincipals; i++)
191                 xfree(cert->principals[i]);
192         if (cert->principals != NULL)
193                 xfree(cert->principals);
194         if (cert->signature_key != NULL)
195                 key_free(cert->signature_key);
196 }
197
198 void
199 key_free(Key *k)
200 {
201         if (k == NULL)
202                 fatal("key_free: key is NULL");
203         switch (k->type) {
204         case KEY_RSA1:
205         case KEY_RSA:
206         case KEY_RSA_CERT_V00:
207         case KEY_RSA_CERT:
208                 if (k->rsa != NULL)
209                         RSA_free(k->rsa);
210                 k->rsa = NULL;
211                 break;
212         case KEY_DSA:
213         case KEY_DSA_CERT_V00:
214         case KEY_DSA_CERT:
215                 if (k->dsa != NULL)
216                         DSA_free(k->dsa);
217                 k->dsa = NULL;
218                 break;
219 #ifdef OPENSSL_HAS_ECC
220         case KEY_ECDSA:
221         case KEY_ECDSA_CERT:
222                 if (k->ecdsa != NULL)
223                         EC_KEY_free(k->ecdsa);
224                 k->ecdsa = NULL;
225                 break;
226 #endif
227         case KEY_UNSPEC:
228                 break;
229         default:
230                 fatal("key_free: bad key type %d", k->type);
231                 break;
232         }
233         if (key_is_cert(k)) {
234                 if (k->cert != NULL)
235                         cert_free(k->cert);
236                 k->cert = NULL;
237         }
238
239         xfree(k);
240 }
241
242 static int
243 cert_compare(struct KeyCert *a, struct KeyCert *b)
244 {
245         if (a == NULL && b == NULL)
246                 return 1;
247         if (a == NULL || b == NULL)
248                 return 0;
249         if (buffer_len(&a->certblob) != buffer_len(&b->certblob))
250                 return 0;
251         if (timingsafe_bcmp(buffer_ptr(&a->certblob), buffer_ptr(&b->certblob),
252             buffer_len(&a->certblob)) != 0)
253                 return 0;
254         return 1;
255 }
256
257 /*
258  * Compare public portions of key only, allowing comparisons between
259  * certificates and plain keys too.
260  */
261 int
262 key_equal_public(const Key *a, const Key *b)
263 {
264 #ifdef OPENSSL_HAS_ECC
265         BN_CTX *bnctx;
266 #endif
267
268         if (a == NULL || b == NULL ||
269             key_type_plain(a->type) != key_type_plain(b->type))
270                 return 0;
271
272         switch (a->type) {
273         case KEY_RSA1:
274         case KEY_RSA_CERT_V00:
275         case KEY_RSA_CERT:
276         case KEY_RSA:
277                 return a->rsa != NULL && b->rsa != NULL &&
278                     BN_cmp(a->rsa->e, b->rsa->e) == 0 &&
279                     BN_cmp(a->rsa->n, b->rsa->n) == 0;
280         case KEY_DSA_CERT_V00:
281         case KEY_DSA_CERT:
282         case KEY_DSA:
283                 return a->dsa != NULL && b->dsa != NULL &&
284                     BN_cmp(a->dsa->p, b->dsa->p) == 0 &&
285                     BN_cmp(a->dsa->q, b->dsa->q) == 0 &&
286                     BN_cmp(a->dsa->g, b->dsa->g) == 0 &&
287                     BN_cmp(a->dsa->pub_key, b->dsa->pub_key) == 0;
288 #ifdef OPENSSL_HAS_ECC
289         case KEY_ECDSA_CERT:
290         case KEY_ECDSA:
291                 if (a->ecdsa == NULL || b->ecdsa == NULL ||
292                     EC_KEY_get0_public_key(a->ecdsa) == NULL ||
293                     EC_KEY_get0_public_key(b->ecdsa) == NULL)
294                         return 0;
295                 if ((bnctx = BN_CTX_new()) == NULL)
296                         fatal("%s: BN_CTX_new failed", __func__);
297                 if (EC_GROUP_cmp(EC_KEY_get0_group(a->ecdsa),
298                     EC_KEY_get0_group(b->ecdsa), bnctx) != 0 ||
299                     EC_POINT_cmp(EC_KEY_get0_group(a->ecdsa),
300                     EC_KEY_get0_public_key(a->ecdsa),
301                     EC_KEY_get0_public_key(b->ecdsa), bnctx) != 0) {
302                         BN_CTX_free(bnctx);
303                         return 0;
304                 }
305                 BN_CTX_free(bnctx);
306                 return 1;
307 #endif /* OPENSSL_HAS_ECC */
308         default:
309                 fatal("key_equal: bad key type %d", a->type);
310         }
311         /* NOTREACHED */
312 }
313
314 int
315 key_equal(const Key *a, const Key *b)
316 {
317         if (a == NULL || b == NULL || a->type != b->type)
318                 return 0;
319         if (key_is_cert(a)) {
320                 if (!cert_compare(a->cert, b->cert))
321                         return 0;
322         }
323         return key_equal_public(a, b);
324 }
325
326 u_char*
327 key_fingerprint_raw(Key *k, enum fp_type dgst_type, u_int *dgst_raw_length)
328 {
329         const EVP_MD *md = NULL;
330         EVP_MD_CTX ctx;
331         u_char *blob = NULL;
332         u_char *retval = NULL;
333         u_int len = 0;
334         int nlen, elen, otype;
335
336         *dgst_raw_length = 0;
337
338         switch (dgst_type) {
339         case SSH_FP_MD5:
340                 md = EVP_md5();
341                 break;
342         case SSH_FP_SHA1:
343                 md = EVP_sha1();
344                 break;
345         default:
346                 fatal("key_fingerprint_raw: bad digest type %d",
347                     dgst_type);
348         }
349         switch (k->type) {
350         case KEY_RSA1:
351                 nlen = BN_num_bytes(k->rsa->n);
352                 elen = BN_num_bytes(k->rsa->e);
353                 len = nlen + elen;
354                 blob = xmalloc(len);
355                 BN_bn2bin(k->rsa->n, blob);
356                 BN_bn2bin(k->rsa->e, blob + nlen);
357                 break;
358         case KEY_DSA:
359         case KEY_ECDSA:
360         case KEY_RSA:
361                 key_to_blob(k, &blob, &len);
362                 break;
363         case KEY_DSA_CERT_V00:
364         case KEY_RSA_CERT_V00:
365         case KEY_DSA_CERT:
366         case KEY_ECDSA_CERT:
367         case KEY_RSA_CERT:
368                 /* We want a fingerprint of the _key_ not of the cert */
369                 otype = k->type;
370                 k->type = key_type_plain(k->type);
371                 key_to_blob(k, &blob, &len);
372                 k->type = otype;
373                 break;
374         case KEY_UNSPEC:
375                 return retval;
376         default:
377                 fatal("key_fingerprint_raw: bad key type %d", k->type);
378                 break;
379         }
380         if (blob != NULL) {
381                 retval = xmalloc(EVP_MAX_MD_SIZE);
382                 EVP_DigestInit(&ctx, md);
383                 EVP_DigestUpdate(&ctx, blob, len);
384                 EVP_DigestFinal(&ctx, retval, dgst_raw_length);
385                 memset(blob, 0, len);
386                 xfree(blob);
387         } else {
388                 fatal("key_fingerprint_raw: blob is null");
389         }
390         return retval;
391 }
392
393 static char *
394 key_fingerprint_hex(u_char *dgst_raw, u_int dgst_raw_len)
395 {
396         char *retval;
397         u_int i;
398
399         retval = xcalloc(1, dgst_raw_len * 3 + 1);
400         for (i = 0; i < dgst_raw_len; i++) {
401                 char hex[4];
402                 snprintf(hex, sizeof(hex), "%02x:", dgst_raw[i]);
403                 strlcat(retval, hex, dgst_raw_len * 3 + 1);
404         }
405
406         /* Remove the trailing ':' character */
407         retval[(dgst_raw_len * 3) - 1] = '\0';
408         return retval;
409 }
410
411 static char *
412 key_fingerprint_bubblebabble(u_char *dgst_raw, u_int dgst_raw_len)
413 {
414         char vowels[] = { 'a', 'e', 'i', 'o', 'u', 'y' };
415         char consonants[] = { 'b', 'c', 'd', 'f', 'g', 'h', 'k', 'l', 'm',
416             'n', 'p', 'r', 's', 't', 'v', 'z', 'x' };
417         u_int i, j = 0, rounds, seed = 1;
418         char *retval;
419
420         rounds = (dgst_raw_len / 2) + 1;
421         retval = xcalloc((rounds * 6), sizeof(char));
422         retval[j++] = 'x';
423         for (i = 0; i < rounds; i++) {
424                 u_int idx0, idx1, idx2, idx3, idx4;
425                 if ((i + 1 < rounds) || (dgst_raw_len % 2 != 0)) {
426                         idx0 = (((((u_int)(dgst_raw[2 * i])) >> 6) & 3) +
427                             seed) % 6;
428                         idx1 = (((u_int)(dgst_raw[2 * i])) >> 2) & 15;
429                         idx2 = ((((u_int)(dgst_raw[2 * i])) & 3) +
430                             (seed / 6)) % 6;
431                         retval[j++] = vowels[idx0];
432                         retval[j++] = consonants[idx1];
433                         retval[j++] = vowels[idx2];
434                         if ((i + 1) < rounds) {
435                                 idx3 = (((u_int)(dgst_raw[(2 * i) + 1])) >> 4) & 15;
436                                 idx4 = (((u_int)(dgst_raw[(2 * i) + 1]))) & 15;
437                                 retval[j++] = consonants[idx3];
438                                 retval[j++] = '-';
439                                 retval[j++] = consonants[idx4];
440                                 seed = ((seed * 5) +
441                                     ((((u_int)(dgst_raw[2 * i])) * 7) +
442                                     ((u_int)(dgst_raw[(2 * i) + 1])))) % 36;
443                         }
444                 } else {
445                         idx0 = seed % 6;
446                         idx1 = 16;
447                         idx2 = seed / 6;
448                         retval[j++] = vowels[idx0];
449                         retval[j++] = consonants[idx1];
450                         retval[j++] = vowels[idx2];
451                 }
452         }
453         retval[j++] = 'x';
454         retval[j++] = '\0';
455         return retval;
456 }
457
458 /*
459  * Draw an ASCII-Art representing the fingerprint so human brain can
460  * profit from its built-in pattern recognition ability.
461  * This technique is called "random art" and can be found in some
462  * scientific publications like this original paper:
463  *
464  * "Hash Visualization: a New Technique to improve Real-World Security",
465  * Perrig A. and Song D., 1999, International Workshop on Cryptographic
466  * Techniques and E-Commerce (CrypTEC '99)
467  * sparrow.ece.cmu.edu/~adrian/projects/validation/validation.pdf
468  *
469  * The subject came up in a talk by Dan Kaminsky, too.
470  *
471  * If you see the picture is different, the key is different.
472  * If the picture looks the same, you still know nothing.
473  *
474  * The algorithm used here is a worm crawling over a discrete plane,
475  * leaving a trace (augmenting the field) everywhere it goes.
476  * Movement is taken from dgst_raw 2bit-wise.  Bumping into walls
477  * makes the respective movement vector be ignored for this turn.
478  * Graphs are not unambiguous, because circles in graphs can be
479  * walked in either direction.
480  */
481
482 /*
483  * Field sizes for the random art.  Have to be odd, so the starting point
484  * can be in the exact middle of the picture, and FLDBASE should be >=8 .
485  * Else pictures would be too dense, and drawing the frame would
486  * fail, too, because the key type would not fit in anymore.
487  */
488 #define FLDBASE         8
489 #define FLDSIZE_Y       (FLDBASE + 1)
490 #define FLDSIZE_X       (FLDBASE * 2 + 1)
491 static char *
492 key_fingerprint_randomart(u_char *dgst_raw, u_int dgst_raw_len, const Key *k)
493 {
494         /*
495          * Chars to be used after each other every time the worm
496          * intersects with itself.  Matter of taste.
497          */
498         char    *augmentation_string = " .o+=*BOX@%&#/^SE";
499         char    *retval, *p;
500         u_char   field[FLDSIZE_X][FLDSIZE_Y];
501         u_int    i, b;
502         int      x, y;
503         size_t   len = strlen(augmentation_string) - 1;
504
505         retval = xcalloc(1, (FLDSIZE_X + 3) * (FLDSIZE_Y + 2));
506
507         /* initialize field */
508         memset(field, 0, FLDSIZE_X * FLDSIZE_Y * sizeof(char));
509         x = FLDSIZE_X / 2;
510         y = FLDSIZE_Y / 2;
511
512         /* process raw key */
513         for (i = 0; i < dgst_raw_len; i++) {
514                 int input;
515                 /* each byte conveys four 2-bit move commands */
516                 input = dgst_raw[i];
517                 for (b = 0; b < 4; b++) {
518                         /* evaluate 2 bit, rest is shifted later */
519                         x += (input & 0x1) ? 1 : -1;
520                         y += (input & 0x2) ? 1 : -1;
521
522                         /* assure we are still in bounds */
523                         x = MAX(x, 0);
524                         y = MAX(y, 0);
525                         x = MIN(x, FLDSIZE_X - 1);
526                         y = MIN(y, FLDSIZE_Y - 1);
527
528                         /* augment the field */
529                         if (field[x][y] < len - 2)
530                                 field[x][y]++;
531                         input = input >> 2;
532                 }
533         }
534
535         /* mark starting point and end point*/
536         field[FLDSIZE_X / 2][FLDSIZE_Y / 2] = len - 1;
537         field[x][y] = len;
538
539         /* fill in retval */
540         snprintf(retval, FLDSIZE_X, "+--[%4s %4u]", key_type(k), key_size(k));
541         p = strchr(retval, '\0');
542
543         /* output upper border */
544         for (i = p - retval - 1; i < FLDSIZE_X; i++)
545                 *p++ = '-';
546         *p++ = '+';
547         *p++ = '\n';
548
549         /* output content */
550         for (y = 0; y < FLDSIZE_Y; y++) {
551                 *p++ = '|';
552                 for (x = 0; x < FLDSIZE_X; x++)
553                         *p++ = augmentation_string[MIN(field[x][y], len)];
554                 *p++ = '|';
555                 *p++ = '\n';
556         }
557
558         /* output lower border */
559         *p++ = '+';
560         for (i = 0; i < FLDSIZE_X; i++)
561                 *p++ = '-';
562         *p++ = '+';
563
564         return retval;
565 }
566
567 char *
568 key_fingerprint(Key *k, enum fp_type dgst_type, enum fp_rep dgst_rep)
569 {
570         char *retval = NULL;
571         u_char *dgst_raw;
572         u_int dgst_raw_len;
573
574         dgst_raw = key_fingerprint_raw(k, dgst_type, &dgst_raw_len);
575         if (!dgst_raw)
576                 fatal("key_fingerprint: null from key_fingerprint_raw()");
577         switch (dgst_rep) {
578         case SSH_FP_HEX:
579                 retval = key_fingerprint_hex(dgst_raw, dgst_raw_len);
580                 break;
581         case SSH_FP_BUBBLEBABBLE:
582                 retval = key_fingerprint_bubblebabble(dgst_raw, dgst_raw_len);
583                 break;
584         case SSH_FP_RANDOMART:
585                 retval = key_fingerprint_randomart(dgst_raw, dgst_raw_len, k);
586                 break;
587         default:
588                 fatal("key_fingerprint: bad digest representation %d",
589                     dgst_rep);
590                 break;
591         }
592         memset(dgst_raw, 0, dgst_raw_len);
593         xfree(dgst_raw);
594         return retval;
595 }
596
597 /*
598  * Reads a multiple-precision integer in decimal from the buffer, and advances
599  * the pointer.  The integer must already be initialized.  This function is
600  * permitted to modify the buffer.  This leaves *cpp to point just beyond the
601  * last processed (and maybe modified) character.  Note that this may modify
602  * the buffer containing the number.
603  */
604 static int
605 read_bignum(char **cpp, BIGNUM * value)
606 {
607         char *cp = *cpp;
608         int old;
609
610         /* Skip any leading whitespace. */
611         for (; *cp == ' ' || *cp == '\t'; cp++)
612                 ;
613
614         /* Check that it begins with a decimal digit. */
615         if (*cp < '0' || *cp > '9')
616                 return 0;
617
618         /* Save starting position. */
619         *cpp = cp;
620
621         /* Move forward until all decimal digits skipped. */
622         for (; *cp >= '0' && *cp <= '9'; cp++)
623                 ;
624
625         /* Save the old terminating character, and replace it by \0. */
626         old = *cp;
627         *cp = 0;
628
629         /* Parse the number. */
630         if (BN_dec2bn(&value, *cpp) == 0)
631                 return 0;
632
633         /* Restore old terminating character. */
634         *cp = old;
635
636         /* Move beyond the number and return success. */
637         *cpp = cp;
638         return 1;
639 }
640
641 static int
642 write_bignum(FILE *f, BIGNUM *num)
643 {
644         char *buf = BN_bn2dec(num);
645         if (buf == NULL) {
646                 error("write_bignum: BN_bn2dec() failed");
647                 return 0;
648         }
649         fprintf(f, " %s", buf);
650         OPENSSL_free(buf);
651         return 1;
652 }
653
654 /* returns 1 ok, -1 error */
655 int
656 key_read(Key *ret, char **cpp)
657 {
658         Key *k;
659         int success = -1;
660         char *cp, *space;
661         int len, n, type;
662         u_int bits;
663         u_char *blob;
664 #ifdef OPENSSL_HAS_ECC
665         int curve_nid = -1;
666 #endif
667
668         cp = *cpp;
669
670         switch (ret->type) {
671         case KEY_RSA1:
672                 /* Get number of bits. */
673                 if (*cp < '0' || *cp > '9')
674                         return -1;      /* Bad bit count... */
675                 for (bits = 0; *cp >= '0' && *cp <= '9'; cp++)
676                         bits = 10 * bits + *cp - '0';
677                 if (bits == 0)
678                         return -1;
679                 *cpp = cp;
680                 /* Get public exponent, public modulus. */
681                 if (!read_bignum(cpp, ret->rsa->e))
682                         return -1;
683                 if (!read_bignum(cpp, ret->rsa->n))
684                         return -1;
685                 /* validate the claimed number of bits */
686                 if ((u_int)BN_num_bits(ret->rsa->n) != bits) {
687                         verbose("key_read: claimed key size %d does not match "
688                            "actual %d", bits, BN_num_bits(ret->rsa->n));
689                         return -1;
690                 }
691                 success = 1;
692                 break;
693         case KEY_UNSPEC:
694         case KEY_RSA:
695         case KEY_DSA:
696         case KEY_ECDSA:
697         case KEY_DSA_CERT_V00:
698         case KEY_RSA_CERT_V00:
699         case KEY_DSA_CERT:
700         case KEY_ECDSA_CERT:
701         case KEY_RSA_CERT:
702                 space = strchr(cp, ' ');
703                 if (space == NULL) {
704                         debug3("key_read: missing whitespace");
705                         return -1;
706                 }
707                 *space = '\0';
708                 type = key_type_from_name(cp);
709 #ifdef OPENSSL_HAS_ECC
710                 if (key_type_plain(type) == KEY_ECDSA &&
711                     (curve_nid = key_ecdsa_nid_from_name(cp)) == -1) {
712                         debug("key_read: invalid curve");
713                         return -1;
714                 }
715 #endif
716                 *space = ' ';
717                 if (type == KEY_UNSPEC) {
718                         debug3("key_read: missing keytype");
719                         return -1;
720                 }
721                 cp = space+1;
722                 if (*cp == '\0') {
723                         debug3("key_read: short string");
724                         return -1;
725                 }
726                 if (ret->type == KEY_UNSPEC) {
727                         ret->type = type;
728                 } else if (ret->type != type) {
729                         /* is a key, but different type */
730                         debug3("key_read: type mismatch");
731                         return -1;
732                 }
733                 len = 2*strlen(cp);
734                 blob = xmalloc(len);
735                 n = uudecode(cp, blob, len);
736                 if (n < 0) {
737                         error("key_read: uudecode %s failed", cp);
738                         xfree(blob);
739                         return -1;
740                 }
741                 k = key_from_blob(blob, (u_int)n);
742                 xfree(blob);
743                 if (k == NULL) {
744                         error("key_read: key_from_blob %s failed", cp);
745                         return -1;
746                 }
747                 if (k->type != type) {
748                         error("key_read: type mismatch: encoding error");
749                         key_free(k);
750                         return -1;
751                 }
752 #ifdef OPENSSL_HAS_ECC
753                 if (key_type_plain(type) == KEY_ECDSA &&
754                     curve_nid != k->ecdsa_nid) {
755                         error("key_read: type mismatch: EC curve mismatch");
756                         key_free(k);
757                         return -1;
758                 }
759 #endif
760 /*XXXX*/
761                 if (key_is_cert(ret)) {
762                         if (!key_is_cert(k)) {
763                                 error("key_read: loaded key is not a cert");
764                                 key_free(k);
765                                 return -1;
766                         }
767                         if (ret->cert != NULL)
768                                 cert_free(ret->cert);
769                         ret->cert = k->cert;
770                         k->cert = NULL;
771                 }
772                 if (key_type_plain(ret->type) == KEY_RSA) {
773                         if (ret->rsa != NULL)
774                                 RSA_free(ret->rsa);
775                         ret->rsa = k->rsa;
776                         k->rsa = NULL;
777 #ifdef DEBUG_PK
778                         RSA_print_fp(stderr, ret->rsa, 8);
779 #endif
780                 }
781                 if (key_type_plain(ret->type) == KEY_DSA) {
782                         if (ret->dsa != NULL)
783                                 DSA_free(ret->dsa);
784                         ret->dsa = k->dsa;
785                         k->dsa = NULL;
786 #ifdef DEBUG_PK
787                         DSA_print_fp(stderr, ret->dsa, 8);
788 #endif
789                 }
790 #ifdef OPENSSL_HAS_ECC
791                 if (key_type_plain(ret->type) == KEY_ECDSA) {
792                         if (ret->ecdsa != NULL)
793                                 EC_KEY_free(ret->ecdsa);
794                         ret->ecdsa = k->ecdsa;
795                         ret->ecdsa_nid = k->ecdsa_nid;
796                         k->ecdsa = NULL;
797                         k->ecdsa_nid = -1;
798 #ifdef DEBUG_PK
799                         key_dump_ec_key(ret->ecdsa);
800 #endif
801                 }
802 #endif
803                 success = 1;
804 /*XXXX*/
805                 key_free(k);
806                 if (success != 1)
807                         break;
808                 /* advance cp: skip whitespace and data */
809                 while (*cp == ' ' || *cp == '\t')
810                         cp++;
811                 while (*cp != '\0' && *cp != ' ' && *cp != '\t')
812                         cp++;
813                 *cpp = cp;
814                 break;
815         default:
816                 fatal("key_read: bad key type: %d", ret->type);
817                 break;
818         }
819         return success;
820 }
821
822 int
823 key_write(const Key *key, FILE *f)
824 {
825         int n, success = 0;
826         u_int len, bits = 0;
827         u_char *blob;
828         char *uu;
829
830         if (key_is_cert(key)) {
831                 if (key->cert == NULL) {
832                         error("%s: no cert data", __func__);
833                         return 0;
834                 }
835                 if (buffer_len(&key->cert->certblob) == 0) {
836                         error("%s: no signed certificate blob", __func__);
837                         return 0;
838                 }
839         }
840
841         switch (key->type) {
842         case KEY_RSA1:
843                 if (key->rsa == NULL)
844                         return 0;
845                 /* size of modulus 'n' */
846                 bits = BN_num_bits(key->rsa->n);
847                 fprintf(f, "%u", bits);
848                 if (write_bignum(f, key->rsa->e) &&
849                     write_bignum(f, key->rsa->n))
850                         return 1;
851                 error("key_write: failed for RSA key");
852                 return 0;
853         case KEY_DSA:
854         case KEY_DSA_CERT_V00:
855         case KEY_DSA_CERT:
856                 if (key->dsa == NULL)
857                         return 0;
858                 break;
859 #ifdef OPENSSL_HAS_ECC
860         case KEY_ECDSA:
861         case KEY_ECDSA_CERT:
862                 if (key->ecdsa == NULL)
863                         return 0;
864                 break;
865 #endif
866         case KEY_RSA:
867         case KEY_RSA_CERT_V00:
868         case KEY_RSA_CERT:
869                 if (key->rsa == NULL)
870                         return 0;
871                 break;
872         default:
873                 return 0;
874         }
875
876         key_to_blob(key, &blob, &len);
877         uu = xmalloc(2*len);
878         n = uuencode(blob, len, uu, 2*len);
879         if (n > 0) {
880                 fprintf(f, "%s %s", key_ssh_name(key), uu);
881                 success = 1;
882         }
883         xfree(blob);
884         xfree(uu);
885
886         return success;
887 }
888
889 const char *
890 key_type(const Key *k)
891 {
892         switch (k->type) {
893         case KEY_RSA1:
894                 return "RSA1";
895         case KEY_RSA:
896                 return "RSA";
897         case KEY_DSA:
898                 return "DSA";
899 #ifdef OPENSSL_HAS_ECC
900         case KEY_ECDSA:
901                 return "ECDSA";
902 #endif
903         case KEY_RSA_CERT_V00:
904                 return "RSA-CERT-V00";
905         case KEY_DSA_CERT_V00:
906                 return "DSA-CERT-V00";
907         case KEY_RSA_CERT:
908                 return "RSA-CERT";
909         case KEY_DSA_CERT:
910                 return "DSA-CERT";
911 #ifdef OPENSSL_HAS_ECC
912         case KEY_ECDSA_CERT:
913                 return "ECDSA-CERT";
914 #endif
915         }
916         return "unknown";
917 }
918
919 const char *
920 key_cert_type(const Key *k)
921 {
922         switch (k->cert->type) {
923         case SSH2_CERT_TYPE_USER:
924                 return "user";
925         case SSH2_CERT_TYPE_HOST:
926                 return "host";
927         default:
928                 return "unknown";
929         }
930 }
931
932 static const char *
933 key_ssh_name_from_type_nid(int type, int nid)
934 {
935         switch (type) {
936         case KEY_RSA:
937                 return "ssh-rsa";
938         case KEY_DSA:
939                 return "ssh-dss";
940         case KEY_RSA_CERT_V00:
941                 return "ssh-rsa-cert-v00@openssh.com";
942         case KEY_DSA_CERT_V00:
943                 return "ssh-dss-cert-v00@openssh.com";
944         case KEY_RSA_CERT:
945                 return "ssh-rsa-cert-v01@openssh.com";
946         case KEY_DSA_CERT:
947                 return "ssh-dss-cert-v01@openssh.com";
948 #ifdef OPENSSL_HAS_ECC
949         case KEY_ECDSA:
950                 switch (nid) {
951                 case NID_X9_62_prime256v1:
952                         return "ecdsa-sha2-nistp256";
953                 case NID_secp384r1:
954                         return "ecdsa-sha2-nistp384";
955                 case NID_secp521r1:
956                         return "ecdsa-sha2-nistp521";
957                 default:
958                         break;
959                 }
960                 break;
961         case KEY_ECDSA_CERT:
962                 switch (nid) {
963                 case NID_X9_62_prime256v1:
964                         return "ecdsa-sha2-nistp256-cert-v01@openssh.com";
965                 case NID_secp384r1:
966                         return "ecdsa-sha2-nistp384-cert-v01@openssh.com";
967                 case NID_secp521r1:
968                         return "ecdsa-sha2-nistp521-cert-v01@openssh.com";
969                 default:
970                         break;
971                 }
972                 break;
973 #endif /* OPENSSL_HAS_ECC */
974         case KEY_NULL:
975                 return "null";
976         }
977         return "ssh-unknown";
978 }
979
980 const char *
981 key_ssh_name(const Key *k)
982 {
983         return key_ssh_name_from_type_nid(k->type, k->ecdsa_nid);
984 }
985
986 const char *
987 key_ssh_name_plain(const Key *k)
988 {
989         return key_ssh_name_from_type_nid(key_type_plain(k->type),
990             k->ecdsa_nid);
991 }
992
993 u_int
994 key_size(const Key *k)
995 {
996         switch (k->type) {
997         case KEY_RSA1:
998         case KEY_RSA:
999         case KEY_RSA_CERT_V00:
1000         case KEY_RSA_CERT:
1001                 return BN_num_bits(k->rsa->n);
1002         case KEY_DSA:
1003         case KEY_DSA_CERT_V00:
1004         case KEY_DSA_CERT:
1005                 return BN_num_bits(k->dsa->p);
1006 #ifdef OPENSSL_HAS_ECC
1007         case KEY_ECDSA:
1008         case KEY_ECDSA_CERT:
1009                 return key_curve_nid_to_bits(k->ecdsa_nid);
1010 #endif
1011         }
1012         return 0;
1013 }
1014
1015 static RSA *
1016 rsa_generate_private_key(u_int bits)
1017 {
1018         RSA *private = RSA_new();
1019         BIGNUM *f4 = BN_new();
1020
1021         if (private == NULL)
1022                 fatal("%s: RSA_new failed", __func__);
1023         if (f4 == NULL)
1024                 fatal("%s: BN_new failed", __func__);
1025         if (!BN_set_word(f4, RSA_F4))
1026                 fatal("%s: BN_new failed", __func__);
1027         if (!RSA_generate_key_ex(private, bits, f4, NULL))
1028                 fatal("%s: key generation failed.", __func__);
1029         BN_free(f4);
1030         return private;
1031 }
1032
1033 static DSA*
1034 dsa_generate_private_key(u_int bits)
1035 {
1036         DSA *private = DSA_new();
1037
1038         if (private == NULL)
1039                 fatal("%s: DSA_new failed", __func__);
1040         if (!DSA_generate_parameters_ex(private, bits, NULL, 0, NULL,
1041             NULL, NULL))
1042                 fatal("%s: DSA_generate_parameters failed", __func__);
1043         if (!DSA_generate_key(private))
1044                 fatal("%s: DSA_generate_key failed.", __func__);
1045         return private;
1046 }
1047
1048 int
1049 key_ecdsa_bits_to_nid(int bits)
1050 {
1051         switch (bits) {
1052 #ifdef OPENSSL_HAS_ECC
1053         case 256:
1054                 return NID_X9_62_prime256v1;
1055         case 384:
1056                 return NID_secp384r1;
1057         case 521:
1058                 return NID_secp521r1;
1059 #endif
1060         default:
1061                 return -1;
1062         }
1063 }
1064
1065 #ifdef OPENSSL_HAS_ECC
1066 int
1067 key_ecdsa_key_to_nid(EC_KEY *k)
1068 {
1069         EC_GROUP *eg;
1070         int nids[] = {
1071                 NID_X9_62_prime256v1,
1072                 NID_secp384r1,
1073                 NID_secp521r1,
1074                 -1
1075         };
1076         int nid;
1077         u_int i;
1078         BN_CTX *bnctx;
1079         const EC_GROUP *g = EC_KEY_get0_group(k);
1080
1081         /*
1082          * The group may be stored in a ASN.1 encoded private key in one of two
1083          * ways: as a "named group", which is reconstituted by ASN.1 object ID
1084          * or explicit group parameters encoded into the key blob. Only the
1085          * "named group" case sets the group NID for us, but we can figure
1086          * it out for the other case by comparing against all the groups that
1087          * are supported.
1088          */
1089         if ((nid = EC_GROUP_get_curve_name(g)) > 0)
1090                 return nid;
1091         if ((bnctx = BN_CTX_new()) == NULL)
1092                 fatal("%s: BN_CTX_new() failed", __func__);
1093         for (i = 0; nids[i] != -1; i++) {
1094                 if ((eg = EC_GROUP_new_by_curve_name(nids[i])) == NULL)
1095                         fatal("%s: EC_GROUP_new_by_curve_name failed",
1096                             __func__);
1097                 if (EC_GROUP_cmp(g, eg, bnctx) == 0)
1098                         break;
1099                 EC_GROUP_free(eg);
1100         }
1101         BN_CTX_free(bnctx);
1102         debug3("%s: nid = %d", __func__, nids[i]);
1103         if (nids[i] != -1) {
1104                 /* Use the group with the NID attached */
1105                 EC_GROUP_set_asn1_flag(eg, OPENSSL_EC_NAMED_CURVE);
1106                 if (EC_KEY_set_group(k, eg) != 1)
1107                         fatal("%s: EC_KEY_set_group", __func__);
1108         }
1109         return nids[i];
1110 }
1111
1112 static EC_KEY*
1113 ecdsa_generate_private_key(u_int bits, int *nid)
1114 {
1115         EC_KEY *private;
1116
1117         if ((*nid = key_ecdsa_bits_to_nid(bits)) == -1)
1118                 fatal("%s: invalid key length", __func__);
1119         if ((private = EC_KEY_new_by_curve_name(*nid)) == NULL)
1120                 fatal("%s: EC_KEY_new_by_curve_name failed", __func__);
1121         if (EC_KEY_generate_key(private) != 1)
1122                 fatal("%s: EC_KEY_generate_key failed", __func__);
1123         EC_KEY_set_asn1_flag(private, OPENSSL_EC_NAMED_CURVE);
1124         return private;
1125 }
1126 #endif /* OPENSSL_HAS_ECC */
1127
1128 Key *
1129 key_generate(int type, u_int bits)
1130 {
1131         Key *k = key_new(KEY_UNSPEC);
1132         switch (type) {
1133         case KEY_DSA:
1134                 k->dsa = dsa_generate_private_key(bits);
1135                 break;
1136 #ifdef OPENSSL_HAS_ECC
1137         case KEY_ECDSA:
1138                 k->ecdsa = ecdsa_generate_private_key(bits, &k->ecdsa_nid);
1139                 break;
1140 #endif
1141         case KEY_RSA:
1142         case KEY_RSA1:
1143                 k->rsa = rsa_generate_private_key(bits);
1144                 break;
1145         case KEY_RSA_CERT_V00:
1146         case KEY_DSA_CERT_V00:
1147         case KEY_RSA_CERT:
1148         case KEY_DSA_CERT:
1149                 fatal("key_generate: cert keys cannot be generated directly");
1150         default:
1151                 fatal("key_generate: unknown type %d", type);
1152         }
1153         k->type = type;
1154         return k;
1155 }
1156
1157 void
1158 key_cert_copy(const Key *from_key, struct Key *to_key)
1159 {
1160         u_int i;
1161         const struct KeyCert *from;
1162         struct KeyCert *to;
1163
1164         if (to_key->cert != NULL) {
1165                 cert_free(to_key->cert);
1166                 to_key->cert = NULL;
1167         }
1168
1169         if ((from = from_key->cert) == NULL)
1170                 return;
1171
1172         to = to_key->cert = cert_new();
1173
1174         buffer_append(&to->certblob, buffer_ptr(&from->certblob),
1175             buffer_len(&from->certblob));
1176
1177         buffer_append(&to->critical,
1178             buffer_ptr(&from->critical), buffer_len(&from->critical));
1179         buffer_append(&to->extensions,
1180             buffer_ptr(&from->extensions), buffer_len(&from->extensions));
1181
1182         to->serial = from->serial;
1183         to->type = from->type;
1184         to->key_id = from->key_id == NULL ? NULL : xstrdup(from->key_id);
1185         to->valid_after = from->valid_after;
1186         to->valid_before = from->valid_before;
1187         to->signature_key = from->signature_key == NULL ?
1188             NULL : key_from_private(from->signature_key);
1189
1190         to->nprincipals = from->nprincipals;
1191         if (to->nprincipals > CERT_MAX_PRINCIPALS)
1192                 fatal("%s: nprincipals (%u) > CERT_MAX_PRINCIPALS (%u)",
1193                     __func__, to->nprincipals, CERT_MAX_PRINCIPALS);
1194         if (to->nprincipals > 0) {
1195                 to->principals = xcalloc(from->nprincipals,
1196                     sizeof(*to->principals));
1197                 for (i = 0; i < to->nprincipals; i++)
1198                         to->principals[i] = xstrdup(from->principals[i]);
1199         }
1200 }
1201
1202 Key *
1203 key_from_private(const Key *k)
1204 {
1205         Key *n = NULL;
1206         switch (k->type) {
1207         case KEY_DSA:
1208         case KEY_DSA_CERT_V00:
1209         case KEY_DSA_CERT:
1210                 n = key_new(k->type);
1211                 if ((BN_copy(n->dsa->p, k->dsa->p) == NULL) ||
1212                     (BN_copy(n->dsa->q, k->dsa->q) == NULL) ||
1213                     (BN_copy(n->dsa->g, k->dsa->g) == NULL) ||
1214                     (BN_copy(n->dsa->pub_key, k->dsa->pub_key) == NULL))
1215                         fatal("key_from_private: BN_copy failed");
1216                 break;
1217 #ifdef OPENSSL_HAS_ECC
1218         case KEY_ECDSA:
1219         case KEY_ECDSA_CERT:
1220                 n = key_new(k->type);
1221                 n->ecdsa_nid = k->ecdsa_nid;
1222                 if ((n->ecdsa = EC_KEY_new_by_curve_name(k->ecdsa_nid)) == NULL)
1223                         fatal("%s: EC_KEY_new_by_curve_name failed", __func__);
1224                 if (EC_KEY_set_public_key(n->ecdsa,
1225                     EC_KEY_get0_public_key(k->ecdsa)) != 1)
1226                         fatal("%s: EC_KEY_set_public_key failed", __func__);
1227                 break;
1228 #endif
1229         case KEY_RSA:
1230         case KEY_RSA1:
1231         case KEY_RSA_CERT_V00:
1232         case KEY_RSA_CERT:
1233                 n = key_new(k->type);
1234                 if ((BN_copy(n->rsa->n, k->rsa->n) == NULL) ||
1235                     (BN_copy(n->rsa->e, k->rsa->e) == NULL))
1236                         fatal("key_from_private: BN_copy failed");
1237                 break;
1238         default:
1239                 fatal("key_from_private: unknown type %d", k->type);
1240                 break;
1241         }
1242         if (key_is_cert(k))
1243                 key_cert_copy(k, n);
1244         return n;
1245 }
1246
1247 int
1248 key_type_from_name(char *name)
1249 {
1250         if (strcmp(name, "rsa1") == 0) {
1251                 return KEY_RSA1;
1252         } else if (strcmp(name, "rsa") == 0) {
1253                 return KEY_RSA;
1254         } else if (strcmp(name, "dsa") == 0) {
1255                 return KEY_DSA;
1256         } else if (strcmp(name, "ssh-rsa") == 0) {
1257                 return KEY_RSA;
1258         } else if (strcmp(name, "ssh-dss") == 0) {
1259                 return KEY_DSA;
1260 #ifdef OPENSSL_HAS_ECC
1261         } else if (strcmp(name, "ecdsa") == 0 ||
1262             strcmp(name, "ecdsa-sha2-nistp256") == 0 ||
1263             strcmp(name, "ecdsa-sha2-nistp384") == 0 ||
1264             strcmp(name, "ecdsa-sha2-nistp521") == 0) {
1265                 return KEY_ECDSA;
1266 #endif
1267         } else if (strcmp(name, "ssh-rsa-cert-v00@openssh.com") == 0) {
1268                 return KEY_RSA_CERT_V00;
1269         } else if (strcmp(name, "ssh-dss-cert-v00@openssh.com") == 0) {
1270                 return KEY_DSA_CERT_V00;
1271         } else if (strcmp(name, "ssh-rsa-cert-v01@openssh.com") == 0) {
1272                 return KEY_RSA_CERT;
1273         } else if (strcmp(name, "ssh-dss-cert-v01@openssh.com") == 0) {
1274                 return KEY_DSA_CERT;
1275 #ifdef OPENSSL_HAS_ECC
1276         } else if (strcmp(name, "ecdsa-sha2-nistp256-cert-v01@openssh.com") == 0 ||
1277             strcmp(name, "ecdsa-sha2-nistp384-cert-v01@openssh.com") == 0 ||
1278             strcmp(name, "ecdsa-sha2-nistp521-cert-v01@openssh.com") == 0) {
1279                 return KEY_ECDSA_CERT;
1280 #endif
1281         } else if (strcmp(name, "null") == 0) {
1282                 return KEY_NULL;
1283         }
1284
1285         debug2("key_type_from_name: unknown key type '%s'", name);
1286         return KEY_UNSPEC;
1287 }
1288
1289 int
1290 key_ecdsa_nid_from_name(const char *name)
1291 {
1292 #ifdef OPENSSL_HAS_ECC
1293         if (strcmp(name, "ecdsa-sha2-nistp256") == 0 ||
1294             strcmp(name, "ecdsa-sha2-nistp256-cert-v01@openssh.com") == 0)
1295                 return NID_X9_62_prime256v1;
1296         if (strcmp(name, "ecdsa-sha2-nistp384") == 0 ||
1297             strcmp(name, "ecdsa-sha2-nistp384-cert-v01@openssh.com") == 0)
1298                 return NID_secp384r1;
1299         if (strcmp(name, "ecdsa-sha2-nistp521") == 0 ||
1300             strcmp(name, "ecdsa-sha2-nistp521-cert-v01@openssh.com") == 0)
1301                 return NID_secp521r1;
1302 #endif /* OPENSSL_HAS_ECC */
1303
1304         debug2("%s: unknown/non-ECDSA key type '%s'", __func__, name);
1305         return -1;
1306 }
1307
1308 int
1309 key_names_valid2(const char *names)
1310 {
1311         char *s, *cp, *p;
1312
1313         if (names == NULL || strcmp(names, "") == 0)
1314                 return 0;
1315         s = cp = xstrdup(names);
1316         for ((p = strsep(&cp, ",")); p && *p != '\0';
1317             (p = strsep(&cp, ","))) {
1318                 switch (key_type_from_name(p)) {
1319                 case KEY_RSA1:
1320                 case KEY_UNSPEC:
1321                         xfree(s);
1322                         return 0;
1323                 }
1324         }
1325         debug3("key names ok: [%s]", names);
1326         xfree(s);
1327         return 1;
1328 }
1329
1330 static int
1331 cert_parse(Buffer *b, Key *key, const u_char *blob, u_int blen)
1332 {
1333         u_char *principals, *critical, *exts, *sig_key, *sig;
1334         u_int signed_len, plen, clen, sklen, slen, kidlen, elen;
1335         Buffer tmp;
1336         char *principal;
1337         int ret = -1;
1338         int v00 = key->type == KEY_DSA_CERT_V00 ||
1339             key->type == KEY_RSA_CERT_V00;
1340
1341         buffer_init(&tmp);
1342
1343         /* Copy the entire key blob for verification and later serialisation */
1344         buffer_append(&key->cert->certblob, blob, blen);
1345
1346         elen = 0; /* Not touched for v00 certs */
1347         principals = exts = critical = sig_key = sig = NULL;
1348         if ((!v00 && buffer_get_int64_ret(&key->cert->serial, b) != 0) ||
1349             buffer_get_int_ret(&key->cert->type, b) != 0 ||
1350             (key->cert->key_id = buffer_get_cstring_ret(b, &kidlen)) == NULL ||
1351             (principals = buffer_get_string_ret(b, &plen)) == NULL ||
1352             buffer_get_int64_ret(&key->cert->valid_after, b) != 0 ||
1353             buffer_get_int64_ret(&key->cert->valid_before, b) != 0 ||
1354             (critical = buffer_get_string_ret(b, &clen)) == NULL ||
1355             (!v00 && (exts = buffer_get_string_ret(b, &elen)) == NULL) ||
1356             (v00 && buffer_get_string_ptr_ret(b, NULL) == NULL) || /* nonce */
1357             buffer_get_string_ptr_ret(b, NULL) == NULL || /* reserved */
1358             (sig_key = buffer_get_string_ret(b, &sklen)) == NULL) {
1359                 error("%s: parse error", __func__);
1360                 goto out;
1361         }
1362
1363         if (kidlen != strlen(key->cert->key_id)) {
1364                 error("%s: key ID contains \\0 character", __func__);
1365                 goto out;
1366         }
1367
1368         /* Signature is left in the buffer so we can calculate this length */
1369         signed_len = buffer_len(&key->cert->certblob) - buffer_len(b);
1370
1371         if ((sig = buffer_get_string_ret(b, &slen)) == NULL) {
1372                 error("%s: parse error", __func__);
1373                 goto out;
1374         }
1375
1376         if (key->cert->type != SSH2_CERT_TYPE_USER &&
1377             key->cert->type != SSH2_CERT_TYPE_HOST) {
1378                 error("Unknown certificate type %u", key->cert->type);
1379                 goto out;
1380         }
1381
1382         buffer_append(&tmp, principals, plen);
1383         while (buffer_len(&tmp) > 0) {
1384                 if (key->cert->nprincipals >= CERT_MAX_PRINCIPALS) {
1385                         error("%s: Too many principals", __func__);
1386                         goto out;
1387                 }
1388                 if ((principal = buffer_get_cstring_ret(&tmp, &plen)) == NULL) {
1389                         error("%s: Principals data invalid", __func__);
1390                         goto out;
1391                 }
1392                 key->cert->principals = xrealloc(key->cert->principals,
1393                     key->cert->nprincipals + 1, sizeof(*key->cert->principals));
1394                 key->cert->principals[key->cert->nprincipals++] = principal;
1395         }
1396
1397         buffer_clear(&tmp);
1398
1399         buffer_append(&key->cert->critical, critical, clen);
1400         buffer_append(&tmp, critical, clen);
1401         /* validate structure */
1402         while (buffer_len(&tmp) != 0) {
1403                 if (buffer_get_string_ptr_ret(&tmp, NULL) == NULL ||
1404                     buffer_get_string_ptr_ret(&tmp, NULL) == NULL) {
1405                         error("%s: critical option data invalid", __func__);
1406                         goto out;
1407                 }
1408         }
1409         buffer_clear(&tmp);
1410
1411         buffer_append(&key->cert->extensions, exts, elen);
1412         buffer_append(&tmp, exts, elen);
1413         /* validate structure */
1414         while (buffer_len(&tmp) != 0) {
1415                 if (buffer_get_string_ptr_ret(&tmp, NULL) == NULL ||
1416                     buffer_get_string_ptr_ret(&tmp, NULL) == NULL) {
1417                         error("%s: extension data invalid", __func__);
1418                         goto out;
1419                 }
1420         }
1421         buffer_clear(&tmp);
1422
1423         if ((key->cert->signature_key = key_from_blob(sig_key,
1424             sklen)) == NULL) {
1425                 error("%s: Signature key invalid", __func__);
1426                 goto out;
1427         }
1428         if (key->cert->signature_key->type != KEY_RSA &&
1429             key->cert->signature_key->type != KEY_DSA &&
1430             key->cert->signature_key->type != KEY_ECDSA) {
1431                 error("%s: Invalid signature key type %s (%d)", __func__,
1432                     key_type(key->cert->signature_key),
1433                     key->cert->signature_key->type);
1434                 goto out;
1435         }
1436
1437         switch (key_verify(key->cert->signature_key, sig, slen, 
1438             buffer_ptr(&key->cert->certblob), signed_len)) {
1439         case 1:
1440                 ret = 0;
1441                 break; /* Good signature */
1442         case 0:
1443                 error("%s: Invalid signature on certificate", __func__);
1444                 goto out;
1445         case -1:
1446                 error("%s: Certificate signature verification failed",
1447                     __func__);
1448                 goto out;
1449         }
1450
1451  out:
1452         buffer_free(&tmp);
1453         if (principals != NULL)
1454                 xfree(principals);
1455         if (critical != NULL)
1456                 xfree(critical);
1457         if (exts != NULL)
1458                 xfree(exts);
1459         if (sig_key != NULL)
1460                 xfree(sig_key);
1461         if (sig != NULL)
1462                 xfree(sig);
1463         return ret;
1464 }
1465
1466 Key *
1467 key_from_blob(const u_char *blob, u_int blen)
1468 {
1469         Buffer b;
1470         int rlen, type;
1471         char *ktype = NULL, *curve = NULL;
1472         Key *key = NULL;
1473 #ifdef OPENSSL_HAS_ECC
1474         EC_POINT *q = NULL;
1475         int nid = -1;
1476 #endif
1477
1478 #ifdef DEBUG_PK
1479         dump_base64(stderr, blob, blen);
1480 #endif
1481         buffer_init(&b);
1482         buffer_append(&b, blob, blen);
1483         if ((ktype = buffer_get_cstring_ret(&b, NULL)) == NULL) {
1484                 error("key_from_blob: can't read key type");
1485                 goto out;
1486         }
1487
1488         type = key_type_from_name(ktype);
1489 #ifdef OPENSSL_HAS_ECC
1490         if (key_type_plain(type) == KEY_ECDSA)
1491                 nid = key_ecdsa_nid_from_name(ktype);
1492 #endif
1493
1494         switch (type) {
1495         case KEY_RSA_CERT:
1496                 (void)buffer_get_string_ptr_ret(&b, NULL); /* Skip nonce */
1497                 /* FALLTHROUGH */
1498         case KEY_RSA:
1499         case KEY_RSA_CERT_V00:
1500                 key = key_new(type);
1501                 if (buffer_get_bignum2_ret(&b, key->rsa->e) == -1 ||
1502                     buffer_get_bignum2_ret(&b, key->rsa->n) == -1) {
1503                         error("key_from_blob: can't read rsa key");
1504  badkey:
1505                         key_free(key);
1506                         key = NULL;
1507                         goto out;
1508                 }
1509 #ifdef DEBUG_PK
1510                 RSA_print_fp(stderr, key->rsa, 8);
1511 #endif
1512                 break;
1513         case KEY_DSA_CERT:
1514                 (void)buffer_get_string_ptr_ret(&b, NULL); /* Skip nonce */
1515                 /* FALLTHROUGH */
1516         case KEY_DSA:
1517         case KEY_DSA_CERT_V00:
1518                 key = key_new(type);
1519                 if (buffer_get_bignum2_ret(&b, key->dsa->p) == -1 ||
1520                     buffer_get_bignum2_ret(&b, key->dsa->q) == -1 ||
1521                     buffer_get_bignum2_ret(&b, key->dsa->g) == -1 ||
1522                     buffer_get_bignum2_ret(&b, key->dsa->pub_key) == -1) {
1523                         error("key_from_blob: can't read dsa key");
1524                         goto badkey;
1525                 }
1526 #ifdef DEBUG_PK
1527                 DSA_print_fp(stderr, key->dsa, 8);
1528 #endif
1529                 break;
1530 #ifdef OPENSSL_HAS_ECC
1531         case KEY_ECDSA_CERT:
1532                 (void)buffer_get_string_ptr_ret(&b, NULL); /* Skip nonce */
1533                 /* FALLTHROUGH */
1534         case KEY_ECDSA:
1535                 key = key_new(type);
1536                 key->ecdsa_nid = nid;
1537                 if ((curve = buffer_get_string_ret(&b, NULL)) == NULL) {
1538                         error("key_from_blob: can't read ecdsa curve");
1539                         goto badkey;
1540                 }
1541                 if (key->ecdsa_nid != key_curve_name_to_nid(curve)) {
1542                         error("key_from_blob: ecdsa curve doesn't match type");
1543                         goto badkey;
1544                 }
1545                 if (key->ecdsa != NULL)
1546                         EC_KEY_free(key->ecdsa);
1547                 if ((key->ecdsa = EC_KEY_new_by_curve_name(key->ecdsa_nid))
1548                     == NULL)
1549                         fatal("key_from_blob: EC_KEY_new_by_curve_name failed");
1550                 if ((q = EC_POINT_new(EC_KEY_get0_group(key->ecdsa))) == NULL)
1551                         fatal("key_from_blob: EC_POINT_new failed");
1552                 if (buffer_get_ecpoint_ret(&b, EC_KEY_get0_group(key->ecdsa),
1553                     q) == -1) {
1554                         error("key_from_blob: can't read ecdsa key point");
1555                         goto badkey;
1556                 }
1557                 if (key_ec_validate_public(EC_KEY_get0_group(key->ecdsa),
1558                     q) != 0)
1559                         goto badkey;
1560                 if (EC_KEY_set_public_key(key->ecdsa, q) != 1)
1561                         fatal("key_from_blob: EC_KEY_set_public_key failed");
1562 #ifdef DEBUG_PK
1563                 key_dump_ec_point(EC_KEY_get0_group(key->ecdsa), q);
1564 #endif
1565                 break;
1566 #endif /* OPENSSL_HAS_ECC */
1567         case KEY_UNSPEC:
1568                 key = key_new(type);
1569                 break;
1570         default:
1571                 error("key_from_blob: cannot handle type %s", ktype);
1572                 goto out;
1573         }
1574         if (key_is_cert(key) && cert_parse(&b, key, blob, blen) == -1) {
1575                 error("key_from_blob: can't parse cert data");
1576                 goto badkey;
1577         }
1578         rlen = buffer_len(&b);
1579         if (key != NULL && rlen != 0)
1580                 error("key_from_blob: remaining bytes in key blob %d", rlen);
1581  out:
1582         if (ktype != NULL)
1583                 xfree(ktype);
1584         if (curve != NULL)
1585                 xfree(curve);
1586 #ifdef OPENSSL_HAS_ECC
1587         if (q != NULL)
1588                 EC_POINT_free(q);
1589 #endif
1590         buffer_free(&b);
1591         return key;
1592 }
1593
1594 int
1595 key_to_blob(const Key *key, u_char **blobp, u_int *lenp)
1596 {
1597         Buffer b;
1598         int len;
1599
1600         if (key == NULL) {
1601                 error("key_to_blob: key == NULL");
1602                 return 0;
1603         }
1604         buffer_init(&b);
1605         switch (key->type) {
1606         case KEY_DSA_CERT_V00:
1607         case KEY_RSA_CERT_V00:
1608         case KEY_DSA_CERT:
1609         case KEY_ECDSA_CERT:
1610         case KEY_RSA_CERT:
1611                 /* Use the existing blob */
1612                 buffer_append(&b, buffer_ptr(&key->cert->certblob),
1613                     buffer_len(&key->cert->certblob));
1614                 break;
1615         case KEY_DSA:
1616                 buffer_put_cstring(&b, key_ssh_name(key));
1617                 buffer_put_bignum2(&b, key->dsa->p);
1618                 buffer_put_bignum2(&b, key->dsa->q);
1619                 buffer_put_bignum2(&b, key->dsa->g);
1620                 buffer_put_bignum2(&b, key->dsa->pub_key);
1621                 break;
1622 #ifdef OPENSSL_HAS_ECC
1623         case KEY_ECDSA:
1624                 buffer_put_cstring(&b, key_ssh_name(key));
1625                 buffer_put_cstring(&b, key_curve_nid_to_name(key->ecdsa_nid));
1626                 buffer_put_ecpoint(&b, EC_KEY_get0_group(key->ecdsa),
1627                     EC_KEY_get0_public_key(key->ecdsa));
1628                 break;
1629 #endif
1630         case KEY_RSA:
1631                 buffer_put_cstring(&b, key_ssh_name(key));
1632                 buffer_put_bignum2(&b, key->rsa->e);
1633                 buffer_put_bignum2(&b, key->rsa->n);
1634                 break;
1635         default:
1636                 error("key_to_blob: unsupported key type %d", key->type);
1637                 buffer_free(&b);
1638                 return 0;
1639         }
1640         len = buffer_len(&b);
1641         if (lenp != NULL)
1642                 *lenp = len;
1643         if (blobp != NULL) {
1644                 *blobp = xmalloc(len);
1645                 memcpy(*blobp, buffer_ptr(&b), len);
1646         }
1647         memset(buffer_ptr(&b), 0, len);
1648         buffer_free(&b);
1649         return len;
1650 }
1651
1652 int
1653 key_sign(
1654     const Key *key,
1655     u_char **sigp, u_int *lenp,
1656     const u_char *data, u_int datalen)
1657 {
1658         switch (key->type) {
1659         case KEY_DSA_CERT_V00:
1660         case KEY_DSA_CERT:
1661         case KEY_DSA:
1662                 return ssh_dss_sign(key, sigp, lenp, data, datalen);
1663 #ifdef OPENSSL_HAS_ECC
1664         case KEY_ECDSA_CERT:
1665         case KEY_ECDSA:
1666                 return ssh_ecdsa_sign(key, sigp, lenp, data, datalen);
1667 #endif
1668         case KEY_RSA_CERT_V00:
1669         case KEY_RSA_CERT:
1670         case KEY_RSA:
1671                 return ssh_rsa_sign(key, sigp, lenp, data, datalen);
1672         default:
1673                 error("key_sign: invalid key type %d", key->type);
1674                 return -1;
1675         }
1676 }
1677
1678 /*
1679  * key_verify returns 1 for a correct signature, 0 for an incorrect signature
1680  * and -1 on error.
1681  */
1682 int
1683 key_verify(
1684     const Key *key,
1685     const u_char *signature, u_int signaturelen,
1686     const u_char *data, u_int datalen)
1687 {
1688         if (signaturelen == 0)
1689                 return -1;
1690
1691         switch (key->type) {
1692         case KEY_DSA_CERT_V00:
1693         case KEY_DSA_CERT:
1694         case KEY_DSA:
1695                 return ssh_dss_verify(key, signature, signaturelen, data, datalen);
1696 #ifdef OPENSSL_HAS_ECC
1697         case KEY_ECDSA_CERT:
1698         case KEY_ECDSA:
1699                 return ssh_ecdsa_verify(key, signature, signaturelen, data, datalen);
1700 #endif
1701         case KEY_RSA_CERT_V00:
1702         case KEY_RSA_CERT:
1703         case KEY_RSA:
1704                 return ssh_rsa_verify(key, signature, signaturelen, data, datalen);
1705         default:
1706                 error("key_verify: invalid key type %d", key->type);
1707                 return -1;
1708         }
1709 }
1710
1711 /* Converts a private to a public key */
1712 Key *
1713 key_demote(const Key *k)
1714 {
1715         Key *pk;
1716
1717         pk = xcalloc(1, sizeof(*pk));
1718         pk->type = k->type;
1719         pk->flags = k->flags;
1720         pk->ecdsa_nid = k->ecdsa_nid;
1721         pk->dsa = NULL;
1722         pk->ecdsa = NULL;
1723         pk->rsa = NULL;
1724
1725         switch (k->type) {
1726         case KEY_RSA_CERT_V00:
1727         case KEY_RSA_CERT:
1728                 key_cert_copy(k, pk);
1729                 /* FALLTHROUGH */
1730         case KEY_RSA1:
1731         case KEY_RSA:
1732                 if ((pk->rsa = RSA_new()) == NULL)
1733                         fatal("key_demote: RSA_new failed");
1734                 if ((pk->rsa->e = BN_dup(k->rsa->e)) == NULL)
1735                         fatal("key_demote: BN_dup failed");
1736                 if ((pk->rsa->n = BN_dup(k->rsa->n)) == NULL)
1737                         fatal("key_demote: BN_dup failed");
1738                 break;
1739         case KEY_DSA_CERT_V00:
1740         case KEY_DSA_CERT:
1741                 key_cert_copy(k, pk);
1742                 /* FALLTHROUGH */
1743         case KEY_DSA:
1744                 if ((pk->dsa = DSA_new()) == NULL)
1745                         fatal("key_demote: DSA_new failed");
1746                 if ((pk->dsa->p = BN_dup(k->dsa->p)) == NULL)
1747                         fatal("key_demote: BN_dup failed");
1748                 if ((pk->dsa->q = BN_dup(k->dsa->q)) == NULL)
1749                         fatal("key_demote: BN_dup failed");
1750                 if ((pk->dsa->g = BN_dup(k->dsa->g)) == NULL)
1751                         fatal("key_demote: BN_dup failed");
1752                 if ((pk->dsa->pub_key = BN_dup(k->dsa->pub_key)) == NULL)
1753                         fatal("key_demote: BN_dup failed");
1754                 break;
1755 #ifdef OPENSSL_HAS_ECC
1756         case KEY_ECDSA_CERT:
1757                 key_cert_copy(k, pk);
1758                 /* FALLTHROUGH */
1759         case KEY_ECDSA:
1760                 if ((pk->ecdsa = EC_KEY_new_by_curve_name(pk->ecdsa_nid)) == NULL)
1761                         fatal("key_demote: EC_KEY_new_by_curve_name failed");
1762                 if (EC_KEY_set_public_key(pk->ecdsa,
1763                     EC_KEY_get0_public_key(k->ecdsa)) != 1)
1764                         fatal("key_demote: EC_KEY_set_public_key failed");
1765                 break;
1766 #endif
1767         default:
1768                 fatal("key_free: bad key type %d", k->type);
1769                 break;
1770         }
1771
1772         return (pk);
1773 }
1774
1775 int
1776 key_is_cert(const Key *k)
1777 {
1778         if (k == NULL)
1779                 return 0;
1780         switch (k->type) {
1781         case KEY_RSA_CERT_V00:
1782         case KEY_DSA_CERT_V00:
1783         case KEY_RSA_CERT:
1784         case KEY_DSA_CERT:
1785         case KEY_ECDSA_CERT:
1786                 return 1;
1787         default:
1788                 return 0;
1789         }
1790 }
1791
1792 /* Return the cert-less equivalent to a certified key type */
1793 int
1794 key_type_plain(int type)
1795 {
1796         switch (type) {
1797         case KEY_RSA_CERT_V00:
1798         case KEY_RSA_CERT:
1799                 return KEY_RSA;
1800         case KEY_DSA_CERT_V00:
1801         case KEY_DSA_CERT:
1802                 return KEY_DSA;
1803         case KEY_ECDSA_CERT:
1804                 return KEY_ECDSA;
1805         default:
1806                 return type;
1807         }
1808 }
1809
1810 /* Convert a KEY_RSA or KEY_DSA to their _CERT equivalent */
1811 int
1812 key_to_certified(Key *k, int legacy)
1813 {
1814         switch (k->type) {
1815         case KEY_RSA:
1816                 k->cert = cert_new();
1817                 k->type = legacy ? KEY_RSA_CERT_V00 : KEY_RSA_CERT;
1818                 return 0;
1819         case KEY_DSA:
1820                 k->cert = cert_new();
1821                 k->type = legacy ? KEY_DSA_CERT_V00 : KEY_DSA_CERT;
1822                 return 0;
1823         case KEY_ECDSA:
1824                 k->cert = cert_new();
1825                 k->type = KEY_ECDSA_CERT;
1826                 return 0;
1827         default:
1828                 error("%s: key has incorrect type %s", __func__, key_type(k));
1829                 return -1;
1830         }
1831 }
1832
1833 /* Convert a KEY_RSA_CERT or KEY_DSA_CERT to their raw key equivalent */
1834 int
1835 key_drop_cert(Key *k)
1836 {
1837         switch (k->type) {
1838         case KEY_RSA_CERT_V00:
1839         case KEY_RSA_CERT:
1840                 cert_free(k->cert);
1841                 k->type = KEY_RSA;
1842                 return 0;
1843         case KEY_DSA_CERT_V00:
1844         case KEY_DSA_CERT:
1845                 cert_free(k->cert);
1846                 k->type = KEY_DSA;
1847                 return 0;
1848         case KEY_ECDSA_CERT:
1849                 cert_free(k->cert);
1850                 k->type = KEY_ECDSA;
1851                 return 0;
1852         default:
1853                 error("%s: key has incorrect type %s", __func__, key_type(k));
1854                 return -1;
1855         }
1856 }
1857
1858 /*
1859  * Sign a KEY_RSA_CERT, KEY_DSA_CERT or KEY_ECDSA_CERT, (re-)generating
1860  * the signed certblob
1861  */
1862 int
1863 key_certify(Key *k, Key *ca)
1864 {
1865         Buffer principals;
1866         u_char *ca_blob, *sig_blob, nonce[32];
1867         u_int i, ca_len, sig_len;
1868
1869         if (k->cert == NULL) {
1870                 error("%s: key lacks cert info", __func__);
1871                 return -1;
1872         }
1873
1874         if (!key_is_cert(k)) {
1875                 error("%s: certificate has unknown type %d", __func__,
1876                     k->cert->type);
1877                 return -1;
1878         }
1879
1880         if (ca->type != KEY_RSA && ca->type != KEY_DSA &&
1881             ca->type != KEY_ECDSA) {
1882                 error("%s: CA key has unsupported type %s", __func__,
1883                     key_type(ca));
1884                 return -1;
1885         }
1886
1887         key_to_blob(ca, &ca_blob, &ca_len);
1888
1889         buffer_clear(&k->cert->certblob);
1890         buffer_put_cstring(&k->cert->certblob, key_ssh_name(k));
1891
1892         /* -v01 certs put nonce first */
1893         arc4random_buf(&nonce, sizeof(nonce));
1894         if (!key_cert_is_legacy(k))
1895                 buffer_put_string(&k->cert->certblob, nonce, sizeof(nonce));
1896
1897         switch (k->type) {
1898         case KEY_DSA_CERT_V00:
1899         case KEY_DSA_CERT:
1900                 buffer_put_bignum2(&k->cert->certblob, k->dsa->p);
1901                 buffer_put_bignum2(&k->cert->certblob, k->dsa->q);
1902                 buffer_put_bignum2(&k->cert->certblob, k->dsa->g);
1903                 buffer_put_bignum2(&k->cert->certblob, k->dsa->pub_key);
1904                 break;
1905 #ifdef OPENSSL_HAS_ECC
1906         case KEY_ECDSA_CERT:
1907                 buffer_put_cstring(&k->cert->certblob,
1908                     key_curve_nid_to_name(k->ecdsa_nid));
1909                 buffer_put_ecpoint(&k->cert->certblob,
1910                     EC_KEY_get0_group(k->ecdsa),
1911                     EC_KEY_get0_public_key(k->ecdsa));
1912                 break;
1913 #endif
1914         case KEY_RSA_CERT_V00:
1915         case KEY_RSA_CERT:
1916                 buffer_put_bignum2(&k->cert->certblob, k->rsa->e);
1917                 buffer_put_bignum2(&k->cert->certblob, k->rsa->n);
1918                 break;
1919         default:
1920                 error("%s: key has incorrect type %s", __func__, key_type(k));
1921                 buffer_clear(&k->cert->certblob);
1922                 xfree(ca_blob);
1923                 return -1;
1924         }
1925
1926         /* -v01 certs have a serial number next */
1927         if (!key_cert_is_legacy(k))
1928                 buffer_put_int64(&k->cert->certblob, k->cert->serial);
1929
1930         buffer_put_int(&k->cert->certblob, k->cert->type);
1931         buffer_put_cstring(&k->cert->certblob, k->cert->key_id);
1932
1933         buffer_init(&principals);
1934         for (i = 0; i < k->cert->nprincipals; i++)
1935                 buffer_put_cstring(&principals, k->cert->principals[i]);
1936         buffer_put_string(&k->cert->certblob, buffer_ptr(&principals),
1937             buffer_len(&principals));
1938         buffer_free(&principals);
1939
1940         buffer_put_int64(&k->cert->certblob, k->cert->valid_after);
1941         buffer_put_int64(&k->cert->certblob, k->cert->valid_before);
1942         buffer_put_string(&k->cert->certblob,
1943             buffer_ptr(&k->cert->critical), buffer_len(&k->cert->critical));
1944
1945         /* -v01 certs have non-critical options here */
1946         if (!key_cert_is_legacy(k)) {
1947                 buffer_put_string(&k->cert->certblob,
1948                     buffer_ptr(&k->cert->extensions),
1949                     buffer_len(&k->cert->extensions));
1950         }
1951
1952         /* -v00 certs put the nonce at the end */
1953         if (key_cert_is_legacy(k))
1954                 buffer_put_string(&k->cert->certblob, nonce, sizeof(nonce));
1955
1956         buffer_put_string(&k->cert->certblob, NULL, 0); /* reserved */
1957         buffer_put_string(&k->cert->certblob, ca_blob, ca_len);
1958         xfree(ca_blob);
1959
1960         /* Sign the whole mess */
1961         if (key_sign(ca, &sig_blob, &sig_len, buffer_ptr(&k->cert->certblob),
1962             buffer_len(&k->cert->certblob)) != 0) {
1963                 error("%s: signature operation failed", __func__);
1964                 buffer_clear(&k->cert->certblob);
1965                 return -1;
1966         }
1967         /* Append signature and we are done */
1968         buffer_put_string(&k->cert->certblob, sig_blob, sig_len);
1969         xfree(sig_blob);
1970
1971         return 0;
1972 }
1973
1974 int
1975 key_cert_check_authority(const Key *k, int want_host, int require_principal,
1976     const char *name, const char **reason)
1977 {
1978         u_int i, principal_matches;
1979         time_t now = time(NULL);
1980
1981         if (want_host) {
1982                 if (k->cert->type != SSH2_CERT_TYPE_HOST) {
1983                         *reason = "Certificate invalid: not a host certificate";
1984                         return -1;
1985                 }
1986         } else {
1987                 if (k->cert->type != SSH2_CERT_TYPE_USER) {
1988                         *reason = "Certificate invalid: not a user certificate";
1989                         return -1;
1990                 }
1991         }
1992         if (now < 0) {
1993                 error("%s: system clock lies before epoch", __func__);
1994                 *reason = "Certificate invalid: not yet valid";
1995                 return -1;
1996         }
1997         if ((u_int64_t)now < k->cert->valid_after) {
1998                 *reason = "Certificate invalid: not yet valid";
1999                 return -1;
2000         }
2001         if ((u_int64_t)now >= k->cert->valid_before) {
2002                 *reason = "Certificate invalid: expired";
2003                 return -1;
2004         }
2005         if (k->cert->nprincipals == 0) {
2006                 if (require_principal) {
2007                         *reason = "Certificate lacks principal list";
2008                         return -1;
2009                 }
2010         } else if (name != NULL) {
2011                 principal_matches = 0;
2012                 for (i = 0; i < k->cert->nprincipals; i++) {
2013                         if (strcmp(name, k->cert->principals[i]) == 0) {
2014                                 principal_matches = 1;
2015                                 break;
2016                         }
2017                 }
2018                 if (!principal_matches) {
2019                         *reason = "Certificate invalid: name is not a listed "
2020                             "principal";
2021                         return -1;
2022                 }
2023         }
2024         return 0;
2025 }
2026
2027 int
2028 key_cert_is_legacy(Key *k)
2029 {
2030         switch (k->type) {
2031         case KEY_DSA_CERT_V00:
2032         case KEY_RSA_CERT_V00:
2033                 return 1;
2034         default:
2035                 return 0;
2036         }
2037 }
2038
2039 /* XXX: these are really begging for a table-driven approach */
2040 int
2041 key_curve_name_to_nid(const char *name)
2042 {
2043 #ifdef OPENSSL_HAS_ECC
2044         if (strcmp(name, "nistp256") == 0)
2045                 return NID_X9_62_prime256v1;
2046         else if (strcmp(name, "nistp384") == 0)
2047                 return NID_secp384r1;
2048         else if (strcmp(name, "nistp521") == 0)
2049                 return NID_secp521r1;
2050 #endif
2051
2052         debug("%s: unsupported EC curve name \"%.100s\"", __func__, name);
2053         return -1;
2054 }
2055
2056 u_int
2057 key_curve_nid_to_bits(int nid)
2058 {
2059         switch (nid) {
2060 #ifdef OPENSSL_HAS_ECC
2061         case NID_X9_62_prime256v1:
2062                 return 256;
2063         case NID_secp384r1:
2064                 return 384;
2065         case NID_secp521r1:
2066                 return 521;
2067 #endif
2068         default:
2069                 error("%s: unsupported EC curve nid %d", __func__, nid);
2070                 return 0;
2071         }
2072 }
2073
2074 const char *
2075 key_curve_nid_to_name(int nid)
2076 {
2077 #ifdef OPENSSL_HAS_ECC
2078         if (nid == NID_X9_62_prime256v1)
2079                 return "nistp256";
2080         else if (nid == NID_secp384r1)
2081                 return "nistp384";
2082         else if (nid == NID_secp521r1)
2083                 return "nistp521";
2084 #endif
2085         error("%s: unsupported EC curve nid %d", __func__, nid);
2086         return NULL;
2087 }
2088
2089 #ifdef OPENSSL_HAS_ECC
2090 const EVP_MD *
2091 key_ec_nid_to_evpmd(int nid)
2092 {
2093         int kbits = key_curve_nid_to_bits(nid);
2094
2095         if (kbits == 0)
2096                 fatal("%s: invalid nid %d", __func__, nid);
2097         /* RFC5656 section 6.2.1 */
2098         if (kbits <= 256)
2099                 return EVP_sha256();
2100         else if (kbits <= 384)
2101                 return EVP_sha384();
2102         else
2103                 return EVP_sha512();
2104 }
2105
2106 int
2107 key_ec_validate_public(const EC_GROUP *group, const EC_POINT *public)
2108 {
2109         BN_CTX *bnctx;
2110         EC_POINT *nq = NULL;
2111         BIGNUM *order, *x, *y, *tmp;
2112         int ret = -1;
2113
2114         if ((bnctx = BN_CTX_new()) == NULL)
2115                 fatal("%s: BN_CTX_new failed", __func__);
2116         BN_CTX_start(bnctx);
2117
2118         /*
2119          * We shouldn't ever hit this case because bignum_get_ecpoint()
2120          * refuses to load GF2m points.
2121          */
2122         if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) !=
2123             NID_X9_62_prime_field) {
2124                 error("%s: group is not a prime field", __func__);
2125                 goto out;
2126         }
2127
2128         /* Q != infinity */
2129         if (EC_POINT_is_at_infinity(group, public)) {
2130                 error("%s: received degenerate public key (infinity)",
2131                     __func__);
2132                 goto out;
2133         }
2134
2135         if ((x = BN_CTX_get(bnctx)) == NULL ||
2136             (y = BN_CTX_get(bnctx)) == NULL ||
2137             (order = BN_CTX_get(bnctx)) == NULL ||
2138             (tmp = BN_CTX_get(bnctx)) == NULL)
2139                 fatal("%s: BN_CTX_get failed", __func__);
2140
2141         /* log2(x) > log2(order)/2, log2(y) > log2(order)/2 */
2142         if (EC_GROUP_get_order(group, order, bnctx) != 1)
2143                 fatal("%s: EC_GROUP_get_order failed", __func__);
2144         if (EC_POINT_get_affine_coordinates_GFp(group, public,
2145             x, y, bnctx) != 1)
2146                 fatal("%s: EC_POINT_get_affine_coordinates_GFp", __func__);
2147         if (BN_num_bits(x) <= BN_num_bits(order) / 2) {
2148                 error("%s: public key x coordinate too small: "
2149                     "bits(x) = %d, bits(order)/2 = %d", __func__,
2150                     BN_num_bits(x), BN_num_bits(order) / 2);
2151                 goto out;
2152         }
2153         if (BN_num_bits(y) <= BN_num_bits(order) / 2) {
2154                 error("%s: public key y coordinate too small: "
2155                     "bits(y) = %d, bits(order)/2 = %d", __func__,
2156                     BN_num_bits(x), BN_num_bits(order) / 2);
2157                 goto out;
2158         }
2159
2160         /* nQ == infinity (n == order of subgroup) */
2161         if ((nq = EC_POINT_new(group)) == NULL)
2162                 fatal("%s: BN_CTX_tmp failed", __func__);
2163         if (EC_POINT_mul(group, nq, NULL, public, order, bnctx) != 1)
2164                 fatal("%s: EC_GROUP_mul failed", __func__);
2165         if (EC_POINT_is_at_infinity(group, nq) != 1) {
2166                 error("%s: received degenerate public key (nQ != infinity)",
2167                     __func__);
2168                 goto out;
2169         }
2170
2171         /* x < order - 1, y < order - 1 */
2172         if (!BN_sub(tmp, order, BN_value_one()))
2173                 fatal("%s: BN_sub failed", __func__);
2174         if (BN_cmp(x, tmp) >= 0) {
2175                 error("%s: public key x coordinate >= group order - 1",
2176                     __func__);
2177                 goto out;
2178         }
2179         if (BN_cmp(y, tmp) >= 0) {
2180                 error("%s: public key y coordinate >= group order - 1",
2181                     __func__);
2182                 goto out;
2183         }
2184         ret = 0;
2185  out:
2186         BN_CTX_free(bnctx);
2187         EC_POINT_free(nq);
2188         return ret;
2189 }
2190
2191 int
2192 key_ec_validate_private(const EC_KEY *key)
2193 {
2194         BN_CTX *bnctx;
2195         BIGNUM *order, *tmp;
2196         int ret = -1;
2197
2198         if ((bnctx = BN_CTX_new()) == NULL)
2199                 fatal("%s: BN_CTX_new failed", __func__);
2200         BN_CTX_start(bnctx);
2201
2202         if ((order = BN_CTX_get(bnctx)) == NULL ||
2203             (tmp = BN_CTX_get(bnctx)) == NULL)
2204                 fatal("%s: BN_CTX_get failed", __func__);
2205
2206         /* log2(private) > log2(order)/2 */
2207         if (EC_GROUP_get_order(EC_KEY_get0_group(key), order, bnctx) != 1)
2208                 fatal("%s: EC_GROUP_get_order failed", __func__);
2209         if (BN_num_bits(EC_KEY_get0_private_key(key)) <=
2210             BN_num_bits(order) / 2) {
2211                 error("%s: private key too small: "
2212                     "bits(y) = %d, bits(order)/2 = %d", __func__,
2213                     BN_num_bits(EC_KEY_get0_private_key(key)),
2214                     BN_num_bits(order) / 2);
2215                 goto out;
2216         }
2217
2218         /* private < order - 1 */
2219         if (!BN_sub(tmp, order, BN_value_one()))
2220                 fatal("%s: BN_sub failed", __func__);
2221         if (BN_cmp(EC_KEY_get0_private_key(key), tmp) >= 0) {
2222                 error("%s: private key >= group order - 1", __func__);
2223                 goto out;
2224         }
2225         ret = 0;
2226  out:
2227         BN_CTX_free(bnctx);
2228         return ret;
2229 }
2230
2231 #if defined(DEBUG_KEXECDH) || defined(DEBUG_PK)
2232 void
2233 key_dump_ec_point(const EC_GROUP *group, const EC_POINT *point)
2234 {
2235         BIGNUM *x, *y;
2236         BN_CTX *bnctx;
2237
2238         if (point == NULL) {
2239                 fputs("point=(NULL)\n", stderr);
2240                 return;
2241         }
2242         if ((bnctx = BN_CTX_new()) == NULL)
2243                 fatal("%s: BN_CTX_new failed", __func__);
2244         BN_CTX_start(bnctx);
2245         if ((x = BN_CTX_get(bnctx)) == NULL || (y = BN_CTX_get(bnctx)) == NULL)
2246                 fatal("%s: BN_CTX_get failed", __func__);
2247         if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) !=
2248             NID_X9_62_prime_field)
2249                 fatal("%s: group is not a prime field", __func__);
2250         if (EC_POINT_get_affine_coordinates_GFp(group, point, x, y, bnctx) != 1)
2251                 fatal("%s: EC_POINT_get_affine_coordinates_GFp", __func__);
2252         fputs("x=", stderr);
2253         BN_print_fp(stderr, x);
2254         fputs("\ny=", stderr);
2255         BN_print_fp(stderr, y);
2256         fputs("\n", stderr);
2257         BN_CTX_free(bnctx);
2258 }
2259
2260 void
2261 key_dump_ec_key(const EC_KEY *key)
2262 {
2263         const BIGNUM *exponent;
2264
2265         key_dump_ec_point(EC_KEY_get0_group(key), EC_KEY_get0_public_key(key));
2266         fputs("exponent=", stderr);
2267         if ((exponent = EC_KEY_get0_private_key(key)) == NULL)
2268                 fputs("(NULL)", stderr);
2269         else
2270                 BN_print_fp(stderr, EC_KEY_get0_private_key(key));
2271         fputs("\n", stderr);
2272 }
2273 #endif /* defined(DEBUG_KEXECDH) || defined(DEBUG_PK) */
2274 #endif /* OPENSSL_HAS_ECC */