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