]> CyberLeo.Net >> Repos - FreeBSD/releng/8.1.git/blob - crypto/openssh/key.c
Copy stable/8 to releng/8.1 in preparation for 8.1-RC1.
[FreeBSD/releng/8.1.git] / crypto / openssh / key.c
1 /* $OpenBSD: key.c,v 1.85 2010/03/04 01:44:57 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 "ssh2.h"
56
57 static struct KeyCert *
58 cert_new(void)
59 {
60         struct KeyCert *cert;
61
62         cert = xcalloc(1, sizeof(*cert));
63         buffer_init(&cert->certblob);
64         buffer_init(&cert->constraints);
65         cert->key_id = NULL;
66         cert->principals = NULL;
67         cert->signature_key = NULL;
68         return cert;
69 }
70
71 Key *
72 key_new(int type)
73 {
74         Key *k;
75         RSA *rsa;
76         DSA *dsa;
77         k = xcalloc(1, sizeof(*k));
78         k->type = type;
79         k->dsa = NULL;
80         k->rsa = NULL;
81         k->cert = NULL;
82         switch (k->type) {
83         case KEY_RSA1:
84         case KEY_RSA:
85         case KEY_RSA_CERT:
86                 if ((rsa = RSA_new()) == NULL)
87                         fatal("key_new: RSA_new failed");
88                 if ((rsa->n = BN_new()) == NULL)
89                         fatal("key_new: BN_new failed");
90                 if ((rsa->e = BN_new()) == NULL)
91                         fatal("key_new: BN_new failed");
92                 k->rsa = rsa;
93                 break;
94         case KEY_DSA:
95         case KEY_DSA_CERT:
96                 if ((dsa = DSA_new()) == NULL)
97                         fatal("key_new: DSA_new failed");
98                 if ((dsa->p = BN_new()) == NULL)
99                         fatal("key_new: BN_new failed");
100                 if ((dsa->q = BN_new()) == NULL)
101                         fatal("key_new: BN_new failed");
102                 if ((dsa->g = BN_new()) == NULL)
103                         fatal("key_new: BN_new failed");
104                 if ((dsa->pub_key = BN_new()) == NULL)
105                         fatal("key_new: BN_new failed");
106                 k->dsa = dsa;
107                 break;
108         case KEY_UNSPEC:
109                 break;
110         default:
111                 fatal("key_new: bad key type %d", k->type);
112                 break;
113         }
114
115         if (key_is_cert(k))
116                 k->cert = cert_new();
117
118         return k;
119 }
120
121 void
122 key_add_private(Key *k)
123 {
124         switch (k->type) {
125         case KEY_RSA1:
126         case KEY_RSA:
127         case KEY_RSA_CERT:
128                 if ((k->rsa->d = BN_new()) == NULL)
129                         fatal("key_new_private: BN_new failed");
130                 if ((k->rsa->iqmp = BN_new()) == NULL)
131                         fatal("key_new_private: BN_new failed");
132                 if ((k->rsa->q = BN_new()) == NULL)
133                         fatal("key_new_private: BN_new failed");
134                 if ((k->rsa->p = BN_new()) == NULL)
135                         fatal("key_new_private: BN_new failed");
136                 if ((k->rsa->dmq1 = BN_new()) == NULL)
137                         fatal("key_new_private: BN_new failed");
138                 if ((k->rsa->dmp1 = BN_new()) == NULL)
139                         fatal("key_new_private: BN_new failed");
140                 break;
141         case KEY_DSA:
142         case KEY_DSA_CERT:
143                 if ((k->dsa->priv_key = BN_new()) == NULL)
144                         fatal("key_new_private: BN_new failed");
145                 break;
146         case KEY_UNSPEC:
147                 break;
148         default:
149                 break;
150         }
151 }
152
153 Key *
154 key_new_private(int type)
155 {
156         Key *k = key_new(type);
157
158         key_add_private(k);
159         return k;
160 }
161
162 static void
163 cert_free(struct KeyCert *cert)
164 {
165         u_int i;
166
167         buffer_free(&cert->certblob);
168         buffer_free(&cert->constraints);
169         if (cert->key_id != NULL)
170                 xfree(cert->key_id);
171         for (i = 0; i < cert->nprincipals; i++)
172                 xfree(cert->principals[i]);
173         if (cert->principals != NULL)
174                 xfree(cert->principals);
175         if (cert->signature_key != NULL)
176                 key_free(cert->signature_key);
177 }
178
179 void
180 key_free(Key *k)
181 {
182         if (k == NULL)
183                 fatal("key_free: key is NULL");
184         switch (k->type) {
185         case KEY_RSA1:
186         case KEY_RSA:
187         case KEY_RSA_CERT:
188                 if (k->rsa != NULL)
189                         RSA_free(k->rsa);
190                 k->rsa = NULL;
191                 break;
192         case KEY_DSA:
193         case KEY_DSA_CERT:
194                 if (k->dsa != NULL)
195                         DSA_free(k->dsa);
196                 k->dsa = NULL;
197                 break;
198         case KEY_UNSPEC:
199                 break;
200         default:
201                 fatal("key_free: bad key type %d", k->type);
202                 break;
203         }
204         if (key_is_cert(k)) {
205                 if (k->cert != NULL)
206                         cert_free(k->cert);
207                 k->cert = NULL;
208         }
209
210         xfree(k);
211 }
212
213 static int
214 cert_compare(struct KeyCert *a, struct KeyCert *b)
215 {
216         if (a == NULL && b == NULL)
217                 return 1;
218         if (a == NULL || b == NULL)
219                 return 0;
220         if (buffer_len(&a->certblob) != buffer_len(&b->certblob))
221                 return 0;
222         if (memcmp(buffer_ptr(&a->certblob), buffer_ptr(&b->certblob),
223             buffer_len(&a->certblob)) != 0)
224                 return 0;
225         return 1;
226 }
227
228 /*
229  * Compare public portions of key only, allowing comparisons between
230  * certificates and plain keys too.
231  */
232 int
233 key_equal_public(const Key *a, const Key *b)
234 {
235         if (a == NULL || b == NULL ||
236             key_type_plain(a->type) != key_type_plain(b->type))
237                 return 0;
238
239         switch (a->type) {
240         case KEY_RSA1:
241         case KEY_RSA_CERT:
242         case KEY_RSA:
243                 return a->rsa != NULL && b->rsa != NULL &&
244                     BN_cmp(a->rsa->e, b->rsa->e) == 0 &&
245                     BN_cmp(a->rsa->n, b->rsa->n) == 0;
246         case KEY_DSA_CERT:
247         case KEY_DSA:
248                 return a->dsa != NULL && b->dsa != NULL &&
249                     BN_cmp(a->dsa->p, b->dsa->p) == 0 &&
250                     BN_cmp(a->dsa->q, b->dsa->q) == 0 &&
251                     BN_cmp(a->dsa->g, b->dsa->g) == 0 &&
252                     BN_cmp(a->dsa->pub_key, b->dsa->pub_key) == 0;
253         default:
254                 fatal("key_equal: bad key type %d", a->type);
255         }
256         /* NOTREACHED */
257 }
258
259 int
260 key_equal(const Key *a, const Key *b)
261 {
262         if (a == NULL || b == NULL || a->type != b->type)
263                 return 0;
264         if (key_is_cert(a)) {
265                 if (!cert_compare(a->cert, b->cert))
266                         return 0;
267         }
268         return key_equal_public(a, b);
269 }
270
271 u_char*
272 key_fingerprint_raw(Key *k, enum fp_type dgst_type, u_int *dgst_raw_length)
273 {
274         const EVP_MD *md = NULL;
275         EVP_MD_CTX ctx;
276         u_char *blob = NULL;
277         u_char *retval = NULL;
278         u_int len = 0;
279         int nlen, elen, otype;
280
281         *dgst_raw_length = 0;
282
283         switch (dgst_type) {
284         case SSH_FP_MD5:
285                 md = EVP_md5();
286                 break;
287         case SSH_FP_SHA1:
288                 md = EVP_sha1();
289                 break;
290         default:
291                 fatal("key_fingerprint_raw: bad digest type %d",
292                     dgst_type);
293         }
294         switch (k->type) {
295         case KEY_RSA1:
296                 nlen = BN_num_bytes(k->rsa->n);
297                 elen = BN_num_bytes(k->rsa->e);
298                 len = nlen + elen;
299                 blob = xmalloc(len);
300                 BN_bn2bin(k->rsa->n, blob);
301                 BN_bn2bin(k->rsa->e, blob + nlen);
302                 break;
303         case KEY_DSA:
304         case KEY_RSA:
305                 key_to_blob(k, &blob, &len);
306                 break;
307         case KEY_DSA_CERT:
308         case KEY_RSA_CERT:
309                 /* We want a fingerprint of the _key_ not of the cert */
310                 otype = k->type;
311                 k->type = key_type_plain(k->type);
312                 key_to_blob(k, &blob, &len);
313                 k->type = otype;
314                 break;
315         case KEY_UNSPEC:
316                 return retval;
317         default:
318                 fatal("key_fingerprint_raw: bad key type %d", k->type);
319                 break;
320         }
321         if (blob != NULL) {
322                 retval = xmalloc(EVP_MAX_MD_SIZE);
323                 EVP_DigestInit(&ctx, md);
324                 EVP_DigestUpdate(&ctx, blob, len);
325                 EVP_DigestFinal(&ctx, retval, dgst_raw_length);
326                 memset(blob, 0, len);
327                 xfree(blob);
328         } else {
329                 fatal("key_fingerprint_raw: blob is null");
330         }
331         return retval;
332 }
333
334 static char *
335 key_fingerprint_hex(u_char *dgst_raw, u_int dgst_raw_len)
336 {
337         char *retval;
338         u_int i;
339
340         retval = xcalloc(1, dgst_raw_len * 3 + 1);
341         for (i = 0; i < dgst_raw_len; i++) {
342                 char hex[4];
343                 snprintf(hex, sizeof(hex), "%02x:", dgst_raw[i]);
344                 strlcat(retval, hex, dgst_raw_len * 3 + 1);
345         }
346
347         /* Remove the trailing ':' character */
348         retval[(dgst_raw_len * 3) - 1] = '\0';
349         return retval;
350 }
351
352 static char *
353 key_fingerprint_bubblebabble(u_char *dgst_raw, u_int dgst_raw_len)
354 {
355         char vowels[] = { 'a', 'e', 'i', 'o', 'u', 'y' };
356         char consonants[] = { 'b', 'c', 'd', 'f', 'g', 'h', 'k', 'l', 'm',
357             'n', 'p', 'r', 's', 't', 'v', 'z', 'x' };
358         u_int i, j = 0, rounds, seed = 1;
359         char *retval;
360
361         rounds = (dgst_raw_len / 2) + 1;
362         retval = xcalloc((rounds * 6), sizeof(char));
363         retval[j++] = 'x';
364         for (i = 0; i < rounds; i++) {
365                 u_int idx0, idx1, idx2, idx3, idx4;
366                 if ((i + 1 < rounds) || (dgst_raw_len % 2 != 0)) {
367                         idx0 = (((((u_int)(dgst_raw[2 * i])) >> 6) & 3) +
368                             seed) % 6;
369                         idx1 = (((u_int)(dgst_raw[2 * i])) >> 2) & 15;
370                         idx2 = ((((u_int)(dgst_raw[2 * i])) & 3) +
371                             (seed / 6)) % 6;
372                         retval[j++] = vowels[idx0];
373                         retval[j++] = consonants[idx1];
374                         retval[j++] = vowels[idx2];
375                         if ((i + 1) < rounds) {
376                                 idx3 = (((u_int)(dgst_raw[(2 * i) + 1])) >> 4) & 15;
377                                 idx4 = (((u_int)(dgst_raw[(2 * i) + 1]))) & 15;
378                                 retval[j++] = consonants[idx3];
379                                 retval[j++] = '-';
380                                 retval[j++] = consonants[idx4];
381                                 seed = ((seed * 5) +
382                                     ((((u_int)(dgst_raw[2 * i])) * 7) +
383                                     ((u_int)(dgst_raw[(2 * i) + 1])))) % 36;
384                         }
385                 } else {
386                         idx0 = seed % 6;
387                         idx1 = 16;
388                         idx2 = seed / 6;
389                         retval[j++] = vowels[idx0];
390                         retval[j++] = consonants[idx1];
391                         retval[j++] = vowels[idx2];
392                 }
393         }
394         retval[j++] = 'x';
395         retval[j++] = '\0';
396         return retval;
397 }
398
399 /*
400  * Draw an ASCII-Art representing the fingerprint so human brain can
401  * profit from its built-in pattern recognition ability.
402  * This technique is called "random art" and can be found in some
403  * scientific publications like this original paper:
404  *
405  * "Hash Visualization: a New Technique to improve Real-World Security",
406  * Perrig A. and Song D., 1999, International Workshop on Cryptographic
407  * Techniques and E-Commerce (CrypTEC '99)
408  * sparrow.ece.cmu.edu/~adrian/projects/validation/validation.pdf
409  *
410  * The subject came up in a talk by Dan Kaminsky, too.
411  *
412  * If you see the picture is different, the key is different.
413  * If the picture looks the same, you still know nothing.
414  *
415  * The algorithm used here is a worm crawling over a discrete plane,
416  * leaving a trace (augmenting the field) everywhere it goes.
417  * Movement is taken from dgst_raw 2bit-wise.  Bumping into walls
418  * makes the respective movement vector be ignored for this turn.
419  * Graphs are not unambiguous, because circles in graphs can be
420  * walked in either direction.
421  */
422
423 /*
424  * Field sizes for the random art.  Have to be odd, so the starting point
425  * can be in the exact middle of the picture, and FLDBASE should be >=8 .
426  * Else pictures would be too dense, and drawing the frame would
427  * fail, too, because the key type would not fit in anymore.
428  */
429 #define FLDBASE         8
430 #define FLDSIZE_Y       (FLDBASE + 1)
431 #define FLDSIZE_X       (FLDBASE * 2 + 1)
432 static char *
433 key_fingerprint_randomart(u_char *dgst_raw, u_int dgst_raw_len, const Key *k)
434 {
435         /*
436          * Chars to be used after each other every time the worm
437          * intersects with itself.  Matter of taste.
438          */
439         char    *augmentation_string = " .o+=*BOX@%&#/^SE";
440         char    *retval, *p;
441         u_char   field[FLDSIZE_X][FLDSIZE_Y];
442         u_int    i, b;
443         int      x, y;
444         size_t   len = strlen(augmentation_string) - 1;
445
446         retval = xcalloc(1, (FLDSIZE_X + 3) * (FLDSIZE_Y + 2));
447
448         /* initialize field */
449         memset(field, 0, FLDSIZE_X * FLDSIZE_Y * sizeof(char));
450         x = FLDSIZE_X / 2;
451         y = FLDSIZE_Y / 2;
452
453         /* process raw key */
454         for (i = 0; i < dgst_raw_len; i++) {
455                 int input;
456                 /* each byte conveys four 2-bit move commands */
457                 input = dgst_raw[i];
458                 for (b = 0; b < 4; b++) {
459                         /* evaluate 2 bit, rest is shifted later */
460                         x += (input & 0x1) ? 1 : -1;
461                         y += (input & 0x2) ? 1 : -1;
462
463                         /* assure we are still in bounds */
464                         x = MAX(x, 0);
465                         y = MAX(y, 0);
466                         x = MIN(x, FLDSIZE_X - 1);
467                         y = MIN(y, FLDSIZE_Y - 1);
468
469                         /* augment the field */
470                         if (field[x][y] < len - 2)
471                                 field[x][y]++;
472                         input = input >> 2;
473                 }
474         }
475
476         /* mark starting point and end point*/
477         field[FLDSIZE_X / 2][FLDSIZE_Y / 2] = len - 1;
478         field[x][y] = len;
479
480         /* fill in retval */
481         snprintf(retval, FLDSIZE_X, "+--[%4s %4u]", key_type(k), key_size(k));
482         p = strchr(retval, '\0');
483
484         /* output upper border */
485         for (i = p - retval - 1; i < FLDSIZE_X; i++)
486                 *p++ = '-';
487         *p++ = '+';
488         *p++ = '\n';
489
490         /* output content */
491         for (y = 0; y < FLDSIZE_Y; y++) {
492                 *p++ = '|';
493                 for (x = 0; x < FLDSIZE_X; x++)
494                         *p++ = augmentation_string[MIN(field[x][y], len)];
495                 *p++ = '|';
496                 *p++ = '\n';
497         }
498
499         /* output lower border */
500         *p++ = '+';
501         for (i = 0; i < FLDSIZE_X; i++)
502                 *p++ = '-';
503         *p++ = '+';
504
505         return retval;
506 }
507
508 char *
509 key_fingerprint(Key *k, enum fp_type dgst_type, enum fp_rep dgst_rep)
510 {
511         char *retval = NULL;
512         u_char *dgst_raw;
513         u_int dgst_raw_len;
514
515         dgst_raw = key_fingerprint_raw(k, dgst_type, &dgst_raw_len);
516         if (!dgst_raw)
517                 fatal("key_fingerprint: null from key_fingerprint_raw()");
518         switch (dgst_rep) {
519         case SSH_FP_HEX:
520                 retval = key_fingerprint_hex(dgst_raw, dgst_raw_len);
521                 break;
522         case SSH_FP_BUBBLEBABBLE:
523                 retval = key_fingerprint_bubblebabble(dgst_raw, dgst_raw_len);
524                 break;
525         case SSH_FP_RANDOMART:
526                 retval = key_fingerprint_randomart(dgst_raw, dgst_raw_len, k);
527                 break;
528         default:
529                 fatal("key_fingerprint: bad digest representation %d",
530                     dgst_rep);
531                 break;
532         }
533         memset(dgst_raw, 0, dgst_raw_len);
534         xfree(dgst_raw);
535         return retval;
536 }
537
538 /*
539  * Reads a multiple-precision integer in decimal from the buffer, and advances
540  * the pointer.  The integer must already be initialized.  This function is
541  * permitted to modify the buffer.  This leaves *cpp to point just beyond the
542  * last processed (and maybe modified) character.  Note that this may modify
543  * the buffer containing the number.
544  */
545 static int
546 read_bignum(char **cpp, BIGNUM * value)
547 {
548         char *cp = *cpp;
549         int old;
550
551         /* Skip any leading whitespace. */
552         for (; *cp == ' ' || *cp == '\t'; cp++)
553                 ;
554
555         /* Check that it begins with a decimal digit. */
556         if (*cp < '0' || *cp > '9')
557                 return 0;
558
559         /* Save starting position. */
560         *cpp = cp;
561
562         /* Move forward until all decimal digits skipped. */
563         for (; *cp >= '0' && *cp <= '9'; cp++)
564                 ;
565
566         /* Save the old terminating character, and replace it by \0. */
567         old = *cp;
568         *cp = 0;
569
570         /* Parse the number. */
571         if (BN_dec2bn(&value, *cpp) == 0)
572                 return 0;
573
574         /* Restore old terminating character. */
575         *cp = old;
576
577         /* Move beyond the number and return success. */
578         *cpp = cp;
579         return 1;
580 }
581
582 static int
583 write_bignum(FILE *f, BIGNUM *num)
584 {
585         char *buf = BN_bn2dec(num);
586         if (buf == NULL) {
587                 error("write_bignum: BN_bn2dec() failed");
588                 return 0;
589         }
590         fprintf(f, " %s", buf);
591         OPENSSL_free(buf);
592         return 1;
593 }
594
595 /* returns 1 ok, -1 error */
596 int
597 key_read(Key *ret, char **cpp)
598 {
599         Key *k;
600         int success = -1;
601         char *cp, *space;
602         int len, n, type;
603         u_int bits;
604         u_char *blob;
605
606         cp = *cpp;
607
608         switch (ret->type) {
609         case KEY_RSA1:
610                 /* Get number of bits. */
611                 if (*cp < '0' || *cp > '9')
612                         return -1;      /* Bad bit count... */
613                 for (bits = 0; *cp >= '0' && *cp <= '9'; cp++)
614                         bits = 10 * bits + *cp - '0';
615                 if (bits == 0)
616                         return -1;
617                 *cpp = cp;
618                 /* Get public exponent, public modulus. */
619                 if (!read_bignum(cpp, ret->rsa->e))
620                         return -1;
621                 if (!read_bignum(cpp, ret->rsa->n))
622                         return -1;
623                 /* validate the claimed number of bits */
624                 if ((u_int)BN_num_bits(ret->rsa->n) != bits) {
625                         verbose("key_read: claimed key size %d does not match "
626                            "actual %d", bits, BN_num_bits(ret->rsa->n));
627                         return -1;
628                 }
629                 success = 1;
630                 break;
631         case KEY_UNSPEC:
632         case KEY_RSA:
633         case KEY_DSA:
634         case KEY_DSA_CERT:
635         case KEY_RSA_CERT:
636                 space = strchr(cp, ' ');
637                 if (space == NULL) {
638                         debug3("key_read: missing whitespace");
639                         return -1;
640                 }
641                 *space = '\0';
642                 type = key_type_from_name(cp);
643                 *space = ' ';
644                 if (type == KEY_UNSPEC) {
645                         debug3("key_read: missing keytype");
646                         return -1;
647                 }
648                 cp = space+1;
649                 if (*cp == '\0') {
650                         debug3("key_read: short string");
651                         return -1;
652                 }
653                 if (ret->type == KEY_UNSPEC) {
654                         ret->type = type;
655                 } else if (ret->type != type) {
656                         /* is a key, but different type */
657                         debug3("key_read: type mismatch");
658                         return -1;
659                 }
660                 len = 2*strlen(cp);
661                 blob = xmalloc(len);
662                 n = uudecode(cp, blob, len);
663                 if (n < 0) {
664                         error("key_read: uudecode %s failed", cp);
665                         xfree(blob);
666                         return -1;
667                 }
668                 k = key_from_blob(blob, (u_int)n);
669                 xfree(blob);
670                 if (k == NULL) {
671                         error("key_read: key_from_blob %s failed", cp);
672                         return -1;
673                 }
674                 if (k->type != type) {
675                         error("key_read: type mismatch: encoding error");
676                         key_free(k);
677                         return -1;
678                 }
679 /*XXXX*/
680                 if (key_is_cert(ret)) {
681                         if (!key_is_cert(k)) {
682                                 error("key_read: loaded key is not a cert");
683                                 key_free(k);
684                                 return -1;
685                         }
686                         if (ret->cert != NULL)
687                                 cert_free(ret->cert);
688                         ret->cert = k->cert;
689                         k->cert = NULL;
690                 }
691                 if (key_type_plain(ret->type) == KEY_RSA) {
692                         if (ret->rsa != NULL)
693                                 RSA_free(ret->rsa);
694                         ret->rsa = k->rsa;
695                         k->rsa = NULL;
696 #ifdef DEBUG_PK
697                         RSA_print_fp(stderr, ret->rsa, 8);
698 #endif
699                 }
700                 if (key_type_plain(ret->type) == KEY_DSA) {
701                         if (ret->dsa != NULL)
702                                 DSA_free(ret->dsa);
703                         ret->dsa = k->dsa;
704                         k->dsa = NULL;
705 #ifdef DEBUG_PK
706                         DSA_print_fp(stderr, ret->dsa, 8);
707 #endif
708                 }
709                 success = 1;
710 /*XXXX*/
711                 key_free(k);
712                 if (success != 1)
713                         break;
714                 /* advance cp: skip whitespace and data */
715                 while (*cp == ' ' || *cp == '\t')
716                         cp++;
717                 while (*cp != '\0' && *cp != ' ' && *cp != '\t')
718                         cp++;
719                 *cpp = cp;
720                 break;
721         default:
722                 fatal("key_read: bad key type: %d", ret->type);
723                 break;
724         }
725         return success;
726 }
727
728 int
729 key_write(const Key *key, FILE *f)
730 {
731         int n, success = 0;
732         u_int len, bits = 0;
733         u_char *blob;
734         char *uu;
735
736         if (key_is_cert(key)) {
737                 if (key->cert == NULL) {
738                         error("%s: no cert data", __func__);
739                         return 0;
740                 }
741                 if (buffer_len(&key->cert->certblob) == 0) {
742                         error("%s: no signed certificate blob", __func__);
743                         return 0;
744                 }
745         }
746
747         switch (key->type) {
748         case KEY_RSA1:
749                 if (key->rsa == NULL)
750                         return 0;
751                 /* size of modulus 'n' */
752                 bits = BN_num_bits(key->rsa->n);
753                 fprintf(f, "%u", bits);
754                 if (write_bignum(f, key->rsa->e) &&
755                     write_bignum(f, key->rsa->n))
756                         return 1;
757                 error("key_write: failed for RSA key");
758                 return 0;
759         case KEY_DSA:
760         case KEY_DSA_CERT:
761                 if (key->dsa == NULL)
762                         return 0;
763                 break;
764         case KEY_RSA:
765         case KEY_RSA_CERT:
766                 if (key->rsa == NULL)
767                         return 0;
768                 break;
769         default:
770                 return 0;
771         }
772
773         key_to_blob(key, &blob, &len);
774         uu = xmalloc(2*len);
775         n = uuencode(blob, len, uu, 2*len);
776         if (n > 0) {
777                 fprintf(f, "%s %s", key_ssh_name(key), uu);
778                 success = 1;
779         }
780         xfree(blob);
781         xfree(uu);
782
783         return success;
784 }
785
786 const char *
787 key_type(const Key *k)
788 {
789         switch (k->type) {
790         case KEY_RSA1:
791                 return "RSA1";
792         case KEY_RSA:
793                 return "RSA";
794         case KEY_DSA:
795                 return "DSA";
796         case KEY_RSA_CERT:
797                 return "RSA-CERT";
798         case KEY_DSA_CERT:
799                 return "DSA-CERT";
800         }
801         return "unknown";
802 }
803
804 const char *
805 key_ssh_name(const Key *k)
806 {
807         switch (k->type) {
808         case KEY_RSA:
809                 return "ssh-rsa";
810         case KEY_DSA:
811                 return "ssh-dss";
812         case KEY_RSA_CERT:
813                 return "ssh-rsa-cert-v00@openssh.com";
814         case KEY_DSA_CERT:
815                 return "ssh-dss-cert-v00@openssh.com";
816         }
817         return "ssh-unknown";
818 }
819
820 u_int
821 key_size(const Key *k)
822 {
823         switch (k->type) {
824         case KEY_RSA1:
825         case KEY_RSA:
826         case KEY_RSA_CERT:
827                 return BN_num_bits(k->rsa->n);
828         case KEY_DSA:
829         case KEY_DSA_CERT:
830                 return BN_num_bits(k->dsa->p);
831         }
832         return 0;
833 }
834
835 static RSA *
836 rsa_generate_private_key(u_int bits)
837 {
838         RSA *private;
839
840         private = RSA_generate_key(bits, RSA_F4, NULL, NULL);
841         if (private == NULL)
842                 fatal("rsa_generate_private_key: key generation failed.");
843         return private;
844 }
845
846 static DSA*
847 dsa_generate_private_key(u_int bits)
848 {
849         DSA *private = DSA_generate_parameters(bits, NULL, 0, NULL, NULL, NULL, NULL);
850
851         if (private == NULL)
852                 fatal("dsa_generate_private_key: DSA_generate_parameters failed");
853         if (!DSA_generate_key(private))
854                 fatal("dsa_generate_private_key: DSA_generate_key failed.");
855         if (private == NULL)
856                 fatal("dsa_generate_private_key: NULL.");
857         return private;
858 }
859
860 Key *
861 key_generate(int type, u_int bits)
862 {
863         Key *k = key_new(KEY_UNSPEC);
864         switch (type) {
865         case KEY_DSA:
866                 k->dsa = dsa_generate_private_key(bits);
867                 break;
868         case KEY_RSA:
869         case KEY_RSA1:
870                 k->rsa = rsa_generate_private_key(bits);
871                 break;
872         case KEY_RSA_CERT:
873         case KEY_DSA_CERT:
874                 fatal("key_generate: cert keys cannot be generated directly");
875         default:
876                 fatal("key_generate: unknown type %d", type);
877         }
878         k->type = type;
879         return k;
880 }
881
882 void
883 key_cert_copy(const Key *from_key, struct Key *to_key)
884 {
885         u_int i;
886         const struct KeyCert *from;
887         struct KeyCert *to;
888
889         if (to_key->cert != NULL) {
890                 cert_free(to_key->cert);
891                 to_key->cert = NULL;
892         }
893
894         if ((from = from_key->cert) == NULL)
895                 return;
896
897         to = to_key->cert = cert_new();
898
899         buffer_append(&to->certblob, buffer_ptr(&from->certblob),
900             buffer_len(&from->certblob));
901
902         buffer_append(&to->constraints, buffer_ptr(&from->constraints),
903             buffer_len(&from->constraints));
904
905         to->type = from->type;
906         to->key_id = from->key_id == NULL ? NULL : xstrdup(from->key_id);
907         to->valid_after = from->valid_after;
908         to->valid_before = from->valid_before;
909         to->signature_key = from->signature_key == NULL ?
910             NULL : key_from_private(from->signature_key);
911
912         to->nprincipals = from->nprincipals;
913         if (to->nprincipals > CERT_MAX_PRINCIPALS)
914                 fatal("%s: nprincipals (%u) > CERT_MAX_PRINCIPALS (%u)",
915                     __func__, to->nprincipals, CERT_MAX_PRINCIPALS);
916         if (to->nprincipals > 0) {
917                 to->principals = xcalloc(from->nprincipals,
918                     sizeof(*to->principals));
919                 for (i = 0; i < to->nprincipals; i++)
920                         to->principals[i] = xstrdup(from->principals[i]);
921         }
922 }
923
924 Key *
925 key_from_private(const Key *k)
926 {
927         Key *n = NULL;
928         switch (k->type) {
929         case KEY_DSA:
930         case KEY_DSA_CERT:
931                 n = key_new(k->type);
932                 if ((BN_copy(n->dsa->p, k->dsa->p) == NULL) ||
933                     (BN_copy(n->dsa->q, k->dsa->q) == NULL) ||
934                     (BN_copy(n->dsa->g, k->dsa->g) == NULL) ||
935                     (BN_copy(n->dsa->pub_key, k->dsa->pub_key) == NULL))
936                         fatal("key_from_private: BN_copy failed");
937                 break;
938         case KEY_RSA:
939         case KEY_RSA1:
940         case KEY_RSA_CERT:
941                 n = key_new(k->type);
942                 if ((BN_copy(n->rsa->n, k->rsa->n) == NULL) ||
943                     (BN_copy(n->rsa->e, k->rsa->e) == NULL))
944                         fatal("key_from_private: BN_copy failed");
945                 break;
946         default:
947                 fatal("key_from_private: unknown type %d", k->type);
948                 break;
949         }
950         if (key_is_cert(k))
951                 key_cert_copy(k, n);
952         return n;
953 }
954
955 int
956 key_type_from_name(char *name)
957 {
958         if (strcmp(name, "rsa1") == 0) {
959                 return KEY_RSA1;
960         } else if (strcmp(name, "rsa") == 0) {
961                 return KEY_RSA;
962         } else if (strcmp(name, "dsa") == 0) {
963                 return KEY_DSA;
964         } else if (strcmp(name, "ssh-rsa") == 0) {
965                 return KEY_RSA;
966         } else if (strcmp(name, "ssh-dss") == 0) {
967                 return KEY_DSA;
968         } else if (strcmp(name, "ssh-rsa-cert-v00@openssh.com") == 0) {
969                 return KEY_RSA_CERT;
970         } else if (strcmp(name, "ssh-dss-cert-v00@openssh.com") == 0) {
971                 return KEY_DSA_CERT;
972         }
973         debug2("key_type_from_name: unknown key type '%s'", name);
974         return KEY_UNSPEC;
975 }
976
977 int
978 key_names_valid2(const char *names)
979 {
980         char *s, *cp, *p;
981
982         if (names == NULL || strcmp(names, "") == 0)
983                 return 0;
984         s = cp = xstrdup(names);
985         for ((p = strsep(&cp, ",")); p && *p != '\0';
986             (p = strsep(&cp, ","))) {
987                 switch (key_type_from_name(p)) {
988                 case KEY_RSA1:
989                 case KEY_UNSPEC:
990                         xfree(s);
991                         return 0;
992                 }
993         }
994         debug3("key names ok: [%s]", names);
995         xfree(s);
996         return 1;
997 }
998
999 static int
1000 cert_parse(Buffer *b, Key *key, const u_char *blob, u_int blen)
1001 {
1002         u_char *principals, *constraints, *sig_key, *sig;
1003         u_int signed_len, plen, clen, sklen, slen, kidlen;
1004         Buffer tmp;
1005         char *principal;
1006         int ret = -1;
1007
1008         buffer_init(&tmp);
1009
1010         /* Copy the entire key blob for verification and later serialisation */
1011         buffer_append(&key->cert->certblob, blob, blen);
1012
1013         principals = constraints = sig_key = sig = NULL;
1014         if (buffer_get_int_ret(&key->cert->type, b) != 0 ||
1015             (key->cert->key_id = buffer_get_string_ret(b, &kidlen)) == NULL ||
1016             (principals = buffer_get_string_ret(b, &plen)) == NULL ||
1017             buffer_get_int64_ret(&key->cert->valid_after, b) != 0 ||
1018             buffer_get_int64_ret(&key->cert->valid_before, b) != 0 ||
1019             (constraints = buffer_get_string_ret(b, &clen)) == NULL ||
1020             /* skip nonce */ buffer_get_string_ptr_ret(b, NULL) == NULL ||
1021             /* skip reserved */ buffer_get_string_ptr_ret(b, NULL) == NULL ||
1022             (sig_key = buffer_get_string_ret(b, &sklen)) == NULL) {
1023                 error("%s: parse error", __func__);
1024                 goto out;
1025         }
1026
1027         if (kidlen != strlen(key->cert->key_id)) {
1028                 error("%s: key ID contains \\0 character", __func__);
1029                 goto out;
1030         }
1031
1032         /* Signature is left in the buffer so we can calculate this length */
1033         signed_len = buffer_len(&key->cert->certblob) - buffer_len(b);
1034
1035         if ((sig = buffer_get_string_ret(b, &slen)) == NULL) {
1036                 error("%s: parse error", __func__);
1037                 goto out;
1038         }
1039
1040         if (key->cert->type != SSH2_CERT_TYPE_USER &&
1041             key->cert->type != SSH2_CERT_TYPE_HOST) {
1042                 error("Unknown certificate type %u", key->cert->type);
1043                 goto out;
1044         }
1045
1046         buffer_append(&tmp, principals, plen);
1047         while (buffer_len(&tmp) > 0) {
1048                 if (key->cert->nprincipals >= CERT_MAX_PRINCIPALS) {
1049                         error("%s: Too many principals", __func__);
1050                         goto out;
1051                 }
1052                 if ((principal = buffer_get_string_ret(&tmp, &plen)) == NULL) {
1053                         error("%s: Principals data invalid", __func__);
1054                         goto out;
1055                 }
1056                 if (strlen(principal) != plen) {
1057                         error("%s: Principal contains \\0 character",
1058                             __func__);
1059                         goto out;
1060                 }
1061                 key->cert->principals = xrealloc(key->cert->principals,
1062                     key->cert->nprincipals + 1, sizeof(*key->cert->principals));
1063                 key->cert->principals[key->cert->nprincipals++] = principal;
1064         }
1065
1066         buffer_clear(&tmp);
1067
1068         buffer_append(&key->cert->constraints, constraints, clen);
1069         buffer_append(&tmp, constraints, clen);
1070         /* validate structure */
1071         while (buffer_len(&tmp) != 0) {
1072                 if (buffer_get_string_ptr_ret(&tmp, NULL) == NULL ||
1073                     buffer_get_string_ptr_ret(&tmp, NULL) == NULL) {
1074                         error("%s: Constraints data invalid", __func__);
1075                         goto out;
1076                 }
1077         }
1078         buffer_clear(&tmp);
1079
1080         if ((key->cert->signature_key = key_from_blob(sig_key,
1081             sklen)) == NULL) {
1082                 error("%s: Signature key invalid", __func__);
1083                 goto out;
1084         }
1085         if (key->cert->signature_key->type != KEY_RSA &&
1086             key->cert->signature_key->type != KEY_DSA) {
1087                 error("%s: Invalid signature key type %s (%d)", __func__,
1088                     key_type(key->cert->signature_key),
1089                     key->cert->signature_key->type);
1090                 goto out;
1091         }
1092
1093         switch (key_verify(key->cert->signature_key, sig, slen, 
1094             buffer_ptr(&key->cert->certblob), signed_len)) {
1095         case 1:
1096                 ret = 0;
1097                 break; /* Good signature */
1098         case 0:
1099                 error("%s: Invalid signature on certificate", __func__);
1100                 goto out;
1101         case -1:
1102                 error("%s: Certificate signature verification failed",
1103                     __func__);
1104                 goto out;
1105         }
1106
1107  out:
1108         buffer_free(&tmp);
1109         if (principals != NULL)
1110                 xfree(principals);
1111         if (constraints != NULL)
1112                 xfree(constraints);
1113         if (sig_key != NULL)
1114                 xfree(sig_key);
1115         if (sig != NULL)
1116                 xfree(sig);
1117         return ret;
1118 }
1119
1120 Key *
1121 key_from_blob(const u_char *blob, u_int blen)
1122 {
1123         Buffer b;
1124         int rlen, type;
1125         char *ktype = NULL;
1126         Key *key = NULL;
1127
1128 #ifdef DEBUG_PK
1129         dump_base64(stderr, blob, blen);
1130 #endif
1131         buffer_init(&b);
1132         buffer_append(&b, blob, blen);
1133         if ((ktype = buffer_get_string_ret(&b, NULL)) == NULL) {
1134                 error("key_from_blob: can't read key type");
1135                 goto out;
1136         }
1137
1138         type = key_type_from_name(ktype);
1139
1140         switch (type) {
1141         case KEY_RSA:
1142         case KEY_RSA_CERT:
1143                 key = key_new(type);
1144                 if (buffer_get_bignum2_ret(&b, key->rsa->e) == -1 ||
1145                     buffer_get_bignum2_ret(&b, key->rsa->n) == -1) {
1146                         error("key_from_blob: can't read rsa key");
1147  badkey:
1148                         key_free(key);
1149                         key = NULL;
1150                         goto out;
1151                 }
1152 #ifdef DEBUG_PK
1153                 RSA_print_fp(stderr, key->rsa, 8);
1154 #endif
1155                 break;
1156         case KEY_DSA:
1157         case KEY_DSA_CERT:
1158                 key = key_new(type);
1159                 if (buffer_get_bignum2_ret(&b, key->dsa->p) == -1 ||
1160                     buffer_get_bignum2_ret(&b, key->dsa->q) == -1 ||
1161                     buffer_get_bignum2_ret(&b, key->dsa->g) == -1 ||
1162                     buffer_get_bignum2_ret(&b, key->dsa->pub_key) == -1) {
1163                         error("key_from_blob: can't read dsa key");
1164                         goto badkey;
1165                 }
1166 #ifdef DEBUG_PK
1167                 DSA_print_fp(stderr, key->dsa, 8);
1168 #endif
1169                 break;
1170         case KEY_UNSPEC:
1171                 key = key_new(type);
1172                 break;
1173         default:
1174                 error("key_from_blob: cannot handle type %s", ktype);
1175                 goto out;
1176         }
1177         if (key_is_cert(key) && cert_parse(&b, key, blob, blen) == -1) {
1178                 error("key_from_blob: can't parse cert data");
1179                 goto badkey;
1180         }
1181         rlen = buffer_len(&b);
1182         if (key != NULL && rlen != 0)
1183                 error("key_from_blob: remaining bytes in key blob %d", rlen);
1184  out:
1185         if (ktype != NULL)
1186                 xfree(ktype);
1187         buffer_free(&b);
1188         return key;
1189 }
1190
1191 int
1192 key_to_blob(const Key *key, u_char **blobp, u_int *lenp)
1193 {
1194         Buffer b;
1195         int len;
1196
1197         if (key == NULL) {
1198                 error("key_to_blob: key == NULL");
1199                 return 0;
1200         }
1201         buffer_init(&b);
1202         switch (key->type) {
1203         case KEY_DSA_CERT:
1204         case KEY_RSA_CERT:
1205                 /* Use the existing blob */
1206                 buffer_append(&b, buffer_ptr(&key->cert->certblob),
1207                     buffer_len(&key->cert->certblob));
1208                 break;
1209         case KEY_DSA:
1210                 buffer_put_cstring(&b, key_ssh_name(key));
1211                 buffer_put_bignum2(&b, key->dsa->p);
1212                 buffer_put_bignum2(&b, key->dsa->q);
1213                 buffer_put_bignum2(&b, key->dsa->g);
1214                 buffer_put_bignum2(&b, key->dsa->pub_key);
1215                 break;
1216         case KEY_RSA:
1217                 buffer_put_cstring(&b, key_ssh_name(key));
1218                 buffer_put_bignum2(&b, key->rsa->e);
1219                 buffer_put_bignum2(&b, key->rsa->n);
1220                 break;
1221         default:
1222                 error("key_to_blob: unsupported key type %d", key->type);
1223                 buffer_free(&b);
1224                 return 0;
1225         }
1226         len = buffer_len(&b);
1227         if (lenp != NULL)
1228                 *lenp = len;
1229         if (blobp != NULL) {
1230                 *blobp = xmalloc(len);
1231                 memcpy(*blobp, buffer_ptr(&b), len);
1232         }
1233         memset(buffer_ptr(&b), 0, len);
1234         buffer_free(&b);
1235         return len;
1236 }
1237
1238 int
1239 key_sign(
1240     const Key *key,
1241     u_char **sigp, u_int *lenp,
1242     const u_char *data, u_int datalen)
1243 {
1244         switch (key->type) {
1245         case KEY_DSA_CERT:
1246         case KEY_DSA:
1247                 return ssh_dss_sign(key, sigp, lenp, data, datalen);
1248         case KEY_RSA_CERT:
1249         case KEY_RSA:
1250                 return ssh_rsa_sign(key, sigp, lenp, data, datalen);
1251         default:
1252                 error("key_sign: invalid key type %d", key->type);
1253                 return -1;
1254         }
1255 }
1256
1257 /*
1258  * key_verify returns 1 for a correct signature, 0 for an incorrect signature
1259  * and -1 on error.
1260  */
1261 int
1262 key_verify(
1263     const Key *key,
1264     const u_char *signature, u_int signaturelen,
1265     const u_char *data, u_int datalen)
1266 {
1267         if (signaturelen == 0)
1268                 return -1;
1269
1270         switch (key->type) {
1271         case KEY_DSA_CERT:
1272         case KEY_DSA:
1273                 return ssh_dss_verify(key, signature, signaturelen, data, datalen);
1274         case KEY_RSA_CERT:
1275         case KEY_RSA:
1276                 return ssh_rsa_verify(key, signature, signaturelen, data, datalen);
1277         default:
1278                 error("key_verify: invalid key type %d", key->type);
1279                 return -1;
1280         }
1281 }
1282
1283 /* Converts a private to a public key */
1284 Key *
1285 key_demote(const Key *k)
1286 {
1287         Key *pk;
1288
1289         pk = xcalloc(1, sizeof(*pk));
1290         pk->type = k->type;
1291         pk->flags = k->flags;
1292         pk->dsa = NULL;
1293         pk->rsa = NULL;
1294
1295         switch (k->type) {
1296         case KEY_RSA_CERT:
1297                 key_cert_copy(k, pk);
1298                 /* FALLTHROUGH */
1299         case KEY_RSA1:
1300         case KEY_RSA:
1301                 if ((pk->rsa = RSA_new()) == NULL)
1302                         fatal("key_demote: RSA_new failed");
1303                 if ((pk->rsa->e = BN_dup(k->rsa->e)) == NULL)
1304                         fatal("key_demote: BN_dup failed");
1305                 if ((pk->rsa->n = BN_dup(k->rsa->n)) == NULL)
1306                         fatal("key_demote: BN_dup failed");
1307                 break;
1308         case KEY_DSA_CERT:
1309                 key_cert_copy(k, pk);
1310                 /* FALLTHROUGH */
1311         case KEY_DSA:
1312                 if ((pk->dsa = DSA_new()) == NULL)
1313                         fatal("key_demote: DSA_new failed");
1314                 if ((pk->dsa->p = BN_dup(k->dsa->p)) == NULL)
1315                         fatal("key_demote: BN_dup failed");
1316                 if ((pk->dsa->q = BN_dup(k->dsa->q)) == NULL)
1317                         fatal("key_demote: BN_dup failed");
1318                 if ((pk->dsa->g = BN_dup(k->dsa->g)) == NULL)
1319                         fatal("key_demote: BN_dup failed");
1320                 if ((pk->dsa->pub_key = BN_dup(k->dsa->pub_key)) == NULL)
1321                         fatal("key_demote: BN_dup failed");
1322                 break;
1323         default:
1324                 fatal("key_free: bad key type %d", k->type);
1325                 break;
1326         }
1327
1328         return (pk);
1329 }
1330
1331 int
1332 key_is_cert(const Key *k)
1333 {
1334         return k != NULL &&
1335             (k->type == KEY_RSA_CERT || k->type == KEY_DSA_CERT);
1336 }
1337
1338 /* Return the cert-less equivalent to a certified key type */
1339 int
1340 key_type_plain(int type)
1341 {
1342         switch (type) {
1343         case KEY_RSA_CERT:
1344                 return KEY_RSA;
1345         case KEY_DSA_CERT:
1346                 return KEY_DSA;
1347         default:
1348                 return type;
1349         }
1350 }
1351
1352 /* Convert a KEY_RSA or KEY_DSA to their _CERT equivalent */
1353 int
1354 key_to_certified(Key *k)
1355 {
1356         switch (k->type) {
1357         case KEY_RSA:
1358                 k->cert = cert_new();
1359                 k->type = KEY_RSA_CERT;
1360                 return 0;
1361         case KEY_DSA:
1362                 k->cert = cert_new();
1363                 k->type = KEY_DSA_CERT;
1364                 return 0;
1365         default:
1366                 error("%s: key has incorrect type %s", __func__, key_type(k));
1367                 return -1;
1368         }
1369 }
1370
1371 /* Convert a KEY_RSA_CERT or KEY_DSA_CERT to their raw key equivalent */
1372 int
1373 key_drop_cert(Key *k)
1374 {
1375         switch (k->type) {
1376         case KEY_RSA_CERT:
1377                 cert_free(k->cert);
1378                 k->type = KEY_RSA;
1379                 return 0;
1380         case KEY_DSA_CERT:
1381                 cert_free(k->cert);
1382                 k->type = KEY_DSA;
1383                 return 0;
1384         default:
1385                 error("%s: key has incorrect type %s", __func__, key_type(k));
1386                 return -1;
1387         }
1388 }
1389
1390 /* Sign a KEY_RSA_CERT or KEY_DSA_CERT, (re-)generating the signed certblob */
1391 int
1392 key_certify(Key *k, Key *ca)
1393 {
1394         Buffer principals;
1395         u_char *ca_blob, *sig_blob, nonce[32];
1396         u_int i, ca_len, sig_len;
1397
1398         if (k->cert == NULL) {
1399                 error("%s: key lacks cert info", __func__);
1400                 return -1;
1401         }
1402
1403         if (!key_is_cert(k)) {
1404                 error("%s: certificate has unknown type %d", __func__,
1405                     k->cert->type);
1406                 return -1;
1407         }
1408
1409         if (ca->type != KEY_RSA && ca->type != KEY_DSA) {
1410                 error("%s: CA key has unsupported type %s", __func__,
1411                     key_type(ca));
1412                 return -1;
1413         }
1414
1415         key_to_blob(ca, &ca_blob, &ca_len);
1416
1417         buffer_clear(&k->cert->certblob);
1418         buffer_put_cstring(&k->cert->certblob, key_ssh_name(k));
1419
1420         switch (k->type) {
1421         case KEY_DSA_CERT:
1422                 buffer_put_bignum2(&k->cert->certblob, k->dsa->p);
1423                 buffer_put_bignum2(&k->cert->certblob, k->dsa->q);
1424                 buffer_put_bignum2(&k->cert->certblob, k->dsa->g);
1425                 buffer_put_bignum2(&k->cert->certblob, k->dsa->pub_key);
1426                 break;
1427         case KEY_RSA_CERT:
1428                 buffer_put_bignum2(&k->cert->certblob, k->rsa->e);
1429                 buffer_put_bignum2(&k->cert->certblob, k->rsa->n);
1430                 break;
1431         default:
1432                 error("%s: key has incorrect type %s", __func__, key_type(k));
1433                 buffer_clear(&k->cert->certblob);
1434                 xfree(ca_blob);
1435                 return -1;
1436         }
1437
1438         buffer_put_int(&k->cert->certblob, k->cert->type);
1439         buffer_put_cstring(&k->cert->certblob, k->cert->key_id);
1440
1441         buffer_init(&principals);
1442         for (i = 0; i < k->cert->nprincipals; i++)
1443                 buffer_put_cstring(&principals, k->cert->principals[i]);
1444         buffer_put_string(&k->cert->certblob, buffer_ptr(&principals),
1445             buffer_len(&principals));
1446         buffer_free(&principals);
1447
1448         buffer_put_int64(&k->cert->certblob, k->cert->valid_after);
1449         buffer_put_int64(&k->cert->certblob, k->cert->valid_before);
1450         buffer_put_string(&k->cert->certblob,
1451             buffer_ptr(&k->cert->constraints),
1452             buffer_len(&k->cert->constraints));
1453
1454         arc4random_buf(&nonce, sizeof(nonce));
1455         buffer_put_string(&k->cert->certblob, nonce, sizeof(nonce));
1456         buffer_put_string(&k->cert->certblob, NULL, 0); /* reserved */
1457         buffer_put_string(&k->cert->certblob, ca_blob, ca_len);
1458         xfree(ca_blob);
1459
1460         /* Sign the whole mess */
1461         if (key_sign(ca, &sig_blob, &sig_len, buffer_ptr(&k->cert->certblob),
1462             buffer_len(&k->cert->certblob)) != 0) {
1463                 error("%s: signature operation failed", __func__);
1464                 buffer_clear(&k->cert->certblob);
1465                 return -1;
1466         }
1467         /* Append signature and we are done */
1468         buffer_put_string(&k->cert->certblob, sig_blob, sig_len);
1469         xfree(sig_blob);
1470
1471         return 0;
1472 }
1473
1474 int
1475 key_cert_check_authority(const Key *k, int want_host, int require_principal,
1476     const char *name, const char **reason)
1477 {
1478         u_int i, principal_matches;
1479         time_t now = time(NULL);
1480
1481         if (want_host) {
1482                 if (k->cert->type != SSH2_CERT_TYPE_HOST) {
1483                         *reason = "Certificate invalid: not a host certificate";
1484                         return -1;
1485                 }
1486         } else {
1487                 if (k->cert->type != SSH2_CERT_TYPE_USER) {
1488                         *reason = "Certificate invalid: not a user certificate";
1489                         return -1;
1490                 }
1491         }
1492         if (now < 0) {
1493                 error("%s: system clock lies before epoch", __func__);
1494                 *reason = "Certificate invalid: not yet valid";
1495                 return -1;
1496         }
1497         if ((u_int64_t)now < k->cert->valid_after) {
1498                 *reason = "Certificate invalid: not yet valid";
1499                 return -1;
1500         }
1501         if ((u_int64_t)now >= k->cert->valid_before) {
1502                 *reason = "Certificate invalid: expired";
1503                 return -1;
1504         }
1505         if (k->cert->nprincipals == 0) {
1506                 if (require_principal) {
1507                         *reason = "Certificate lacks principal list";
1508                         return -1;
1509                 }
1510         } else {
1511                 principal_matches = 0;
1512                 for (i = 0; i < k->cert->nprincipals; i++) {
1513                         if (strcmp(name, k->cert->principals[i]) == 0) {
1514                                 principal_matches = 1;
1515                                 break;
1516                         }
1517                 }
1518                 if (!principal_matches) {
1519                         *reason = "Certificate invalid: name is not a listed "
1520                             "principal";
1521                         return -1;
1522                 }
1523         }
1524         return 0;
1525 }