- (dtucker) [contrib/aix/buildbff.sh] Fix creation of ssh_prng_cmds.default
[openssh-git.git] / key.c
blob34f678b38be846582723344be1fb711a40452123
1 /* $OpenBSD: key.c,v 1.87 2010/04/16 01:47:26 djm Exp $ */
2 /*
3 * read_bignum():
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
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".
13 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
14 * Copyright (c) 2008 Alexander von Gernler. All rights reserved.
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.
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.
37 #include "includes.h"
39 #include <sys/param.h>
40 #include <sys/types.h>
42 #include <openssl/evp.h>
43 #include <openbsd-compat/openssl-compat.h>
45 #include <stdarg.h>
46 #include <stdio.h>
47 #include <string.h>
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"
57 static struct KeyCert *
58 cert_new(void)
60 struct KeyCert *cert;
62 cert = xcalloc(1, sizeof(*cert));
63 buffer_init(&cert->certblob);
64 buffer_init(&cert->critical);
65 buffer_init(&cert->extensions);
66 cert->key_id = NULL;
67 cert->principals = NULL;
68 cert->signature_key = NULL;
69 return cert;
72 Key *
73 key_new(int type)
75 Key *k;
76 RSA *rsa;
77 DSA *dsa;
78 k = xcalloc(1, sizeof(*k));
79 k->type = type;
80 k->dsa = NULL;
81 k->rsa = NULL;
82 k->cert = NULL;
83 switch (k->type) {
84 case KEY_RSA1:
85 case KEY_RSA:
86 case KEY_RSA_CERT_V00:
87 case KEY_RSA_CERT:
88 if ((rsa = RSA_new()) == NULL)
89 fatal("key_new: RSA_new failed");
90 if ((rsa->n = BN_new()) == NULL)
91 fatal("key_new: BN_new failed");
92 if ((rsa->e = BN_new()) == NULL)
93 fatal("key_new: BN_new failed");
94 k->rsa = rsa;
95 break;
96 case KEY_DSA:
97 case KEY_DSA_CERT_V00:
98 case KEY_DSA_CERT:
99 if ((dsa = DSA_new()) == NULL)
100 fatal("key_new: DSA_new failed");
101 if ((dsa->p = BN_new()) == NULL)
102 fatal("key_new: BN_new failed");
103 if ((dsa->q = BN_new()) == NULL)
104 fatal("key_new: BN_new failed");
105 if ((dsa->g = BN_new()) == NULL)
106 fatal("key_new: BN_new failed");
107 if ((dsa->pub_key = BN_new()) == NULL)
108 fatal("key_new: BN_new failed");
109 k->dsa = dsa;
110 break;
111 case KEY_UNSPEC:
112 break;
113 default:
114 fatal("key_new: bad key type %d", k->type);
115 break;
118 if (key_is_cert(k))
119 k->cert = cert_new();
121 return k;
124 void
125 key_add_private(Key *k)
127 switch (k->type) {
128 case KEY_RSA1:
129 case KEY_RSA:
130 case KEY_RSA_CERT_V00:
131 case KEY_RSA_CERT:
132 if ((k->rsa->d = BN_new()) == NULL)
133 fatal("key_new_private: BN_new failed");
134 if ((k->rsa->iqmp = BN_new()) == NULL)
135 fatal("key_new_private: BN_new failed");
136 if ((k->rsa->q = BN_new()) == NULL)
137 fatal("key_new_private: BN_new failed");
138 if ((k->rsa->p = BN_new()) == NULL)
139 fatal("key_new_private: BN_new failed");
140 if ((k->rsa->dmq1 = BN_new()) == NULL)
141 fatal("key_new_private: BN_new failed");
142 if ((k->rsa->dmp1 = BN_new()) == NULL)
143 fatal("key_new_private: BN_new failed");
144 break;
145 case KEY_DSA:
146 case KEY_DSA_CERT_V00:
147 case KEY_DSA_CERT:
148 if ((k->dsa->priv_key = BN_new()) == NULL)
149 fatal("key_new_private: BN_new failed");
150 break;
151 case KEY_UNSPEC:
152 break;
153 default:
154 break;
158 Key *
159 key_new_private(int type)
161 Key *k = key_new(type);
163 key_add_private(k);
164 return k;
167 static void
168 cert_free(struct KeyCert *cert)
170 u_int i;
172 buffer_free(&cert->certblob);
173 buffer_free(&cert->critical);
174 buffer_free(&cert->extensions);
175 if (cert->key_id != NULL)
176 xfree(cert->key_id);
177 for (i = 0; i < cert->nprincipals; i++)
178 xfree(cert->principals[i]);
179 if (cert->principals != NULL)
180 xfree(cert->principals);
181 if (cert->signature_key != NULL)
182 key_free(cert->signature_key);
185 void
186 key_free(Key *k)
188 if (k == NULL)
189 fatal("key_free: key is NULL");
190 switch (k->type) {
191 case KEY_RSA1:
192 case KEY_RSA:
193 case KEY_RSA_CERT_V00:
194 case KEY_RSA_CERT:
195 if (k->rsa != NULL)
196 RSA_free(k->rsa);
197 k->rsa = NULL;
198 break;
199 case KEY_DSA:
200 case KEY_DSA_CERT_V00:
201 case KEY_DSA_CERT:
202 if (k->dsa != NULL)
203 DSA_free(k->dsa);
204 k->dsa = NULL;
205 break;
206 case KEY_UNSPEC:
207 break;
208 default:
209 fatal("key_free: bad key type %d", k->type);
210 break;
212 if (key_is_cert(k)) {
213 if (k->cert != NULL)
214 cert_free(k->cert);
215 k->cert = NULL;
218 xfree(k);
221 static int
222 cert_compare(struct KeyCert *a, struct KeyCert *b)
224 if (a == NULL && b == NULL)
225 return 1;
226 if (a == NULL || b == NULL)
227 return 0;
228 if (buffer_len(&a->certblob) != buffer_len(&b->certblob))
229 return 0;
230 if (memcmp(buffer_ptr(&a->certblob), buffer_ptr(&b->certblob),
231 buffer_len(&a->certblob)) != 0)
232 return 0;
233 return 1;
237 * Compare public portions of key only, allowing comparisons between
238 * certificates and plain keys too.
241 key_equal_public(const Key *a, const Key *b)
243 if (a == NULL || b == NULL ||
244 key_type_plain(a->type) != key_type_plain(b->type))
245 return 0;
247 switch (a->type) {
248 case KEY_RSA1:
249 case KEY_RSA_CERT_V00:
250 case KEY_RSA_CERT:
251 case KEY_RSA:
252 return a->rsa != NULL && b->rsa != NULL &&
253 BN_cmp(a->rsa->e, b->rsa->e) == 0 &&
254 BN_cmp(a->rsa->n, b->rsa->n) == 0;
255 case KEY_DSA_CERT_V00:
256 case KEY_DSA_CERT:
257 case KEY_DSA:
258 return a->dsa != NULL && b->dsa != NULL &&
259 BN_cmp(a->dsa->p, b->dsa->p) == 0 &&
260 BN_cmp(a->dsa->q, b->dsa->q) == 0 &&
261 BN_cmp(a->dsa->g, b->dsa->g) == 0 &&
262 BN_cmp(a->dsa->pub_key, b->dsa->pub_key) == 0;
263 default:
264 fatal("key_equal: bad key type %d", a->type);
266 /* NOTREACHED */
270 key_equal(const Key *a, const Key *b)
272 if (a == NULL || b == NULL || a->type != b->type)
273 return 0;
274 if (key_is_cert(a)) {
275 if (!cert_compare(a->cert, b->cert))
276 return 0;
278 return key_equal_public(a, b);
281 u_char*
282 key_fingerprint_raw(Key *k, enum fp_type dgst_type, u_int *dgst_raw_length)
284 const EVP_MD *md = NULL;
285 EVP_MD_CTX ctx;
286 u_char *blob = NULL;
287 u_char *retval = NULL;
288 u_int len = 0;
289 int nlen, elen, otype;
291 *dgst_raw_length = 0;
293 switch (dgst_type) {
294 case SSH_FP_MD5:
295 md = EVP_md5();
296 break;
297 case SSH_FP_SHA1:
298 md = EVP_sha1();
299 break;
300 default:
301 fatal("key_fingerprint_raw: bad digest type %d",
302 dgst_type);
304 switch (k->type) {
305 case KEY_RSA1:
306 nlen = BN_num_bytes(k->rsa->n);
307 elen = BN_num_bytes(k->rsa->e);
308 len = nlen + elen;
309 blob = xmalloc(len);
310 BN_bn2bin(k->rsa->n, blob);
311 BN_bn2bin(k->rsa->e, blob + nlen);
312 break;
313 case KEY_DSA:
314 case KEY_RSA:
315 key_to_blob(k, &blob, &len);
316 break;
317 case KEY_DSA_CERT_V00:
318 case KEY_RSA_CERT_V00:
319 case KEY_DSA_CERT:
320 case KEY_RSA_CERT:
321 /* We want a fingerprint of the _key_ not of the cert */
322 otype = k->type;
323 k->type = key_type_plain(k->type);
324 key_to_blob(k, &blob, &len);
325 k->type = otype;
326 break;
327 case KEY_UNSPEC:
328 return retval;
329 default:
330 fatal("key_fingerprint_raw: bad key type %d", k->type);
331 break;
333 if (blob != NULL) {
334 retval = xmalloc(EVP_MAX_MD_SIZE);
335 EVP_DigestInit(&ctx, md);
336 EVP_DigestUpdate(&ctx, blob, len);
337 EVP_DigestFinal(&ctx, retval, dgst_raw_length);
338 memset(blob, 0, len);
339 xfree(blob);
340 } else {
341 fatal("key_fingerprint_raw: blob is null");
343 return retval;
346 static char *
347 key_fingerprint_hex(u_char *dgst_raw, u_int dgst_raw_len)
349 char *retval;
350 u_int i;
352 retval = xcalloc(1, dgst_raw_len * 3 + 1);
353 for (i = 0; i < dgst_raw_len; i++) {
354 char hex[4];
355 snprintf(hex, sizeof(hex), "%02x:", dgst_raw[i]);
356 strlcat(retval, hex, dgst_raw_len * 3 + 1);
359 /* Remove the trailing ':' character */
360 retval[(dgst_raw_len * 3) - 1] = '\0';
361 return retval;
364 static char *
365 key_fingerprint_bubblebabble(u_char *dgst_raw, u_int dgst_raw_len)
367 char vowels[] = { 'a', 'e', 'i', 'o', 'u', 'y' };
368 char consonants[] = { 'b', 'c', 'd', 'f', 'g', 'h', 'k', 'l', 'm',
369 'n', 'p', 'r', 's', 't', 'v', 'z', 'x' };
370 u_int i, j = 0, rounds, seed = 1;
371 char *retval;
373 rounds = (dgst_raw_len / 2) + 1;
374 retval = xcalloc((rounds * 6), sizeof(char));
375 retval[j++] = 'x';
376 for (i = 0; i < rounds; i++) {
377 u_int idx0, idx1, idx2, idx3, idx4;
378 if ((i + 1 < rounds) || (dgst_raw_len % 2 != 0)) {
379 idx0 = (((((u_int)(dgst_raw[2 * i])) >> 6) & 3) +
380 seed) % 6;
381 idx1 = (((u_int)(dgst_raw[2 * i])) >> 2) & 15;
382 idx2 = ((((u_int)(dgst_raw[2 * i])) & 3) +
383 (seed / 6)) % 6;
384 retval[j++] = vowels[idx0];
385 retval[j++] = consonants[idx1];
386 retval[j++] = vowels[idx2];
387 if ((i + 1) < rounds) {
388 idx3 = (((u_int)(dgst_raw[(2 * i) + 1])) >> 4) & 15;
389 idx4 = (((u_int)(dgst_raw[(2 * i) + 1]))) & 15;
390 retval[j++] = consonants[idx3];
391 retval[j++] = '-';
392 retval[j++] = consonants[idx4];
393 seed = ((seed * 5) +
394 ((((u_int)(dgst_raw[2 * i])) * 7) +
395 ((u_int)(dgst_raw[(2 * i) + 1])))) % 36;
397 } else {
398 idx0 = seed % 6;
399 idx1 = 16;
400 idx2 = seed / 6;
401 retval[j++] = vowels[idx0];
402 retval[j++] = consonants[idx1];
403 retval[j++] = vowels[idx2];
406 retval[j++] = 'x';
407 retval[j++] = '\0';
408 return retval;
412 * Draw an ASCII-Art representing the fingerprint so human brain can
413 * profit from its built-in pattern recognition ability.
414 * This technique is called "random art" and can be found in some
415 * scientific publications like this original paper:
417 * "Hash Visualization: a New Technique to improve Real-World Security",
418 * Perrig A. and Song D., 1999, International Workshop on Cryptographic
419 * Techniques and E-Commerce (CrypTEC '99)
420 * sparrow.ece.cmu.edu/~adrian/projects/validation/validation.pdf
422 * The subject came up in a talk by Dan Kaminsky, too.
424 * If you see the picture is different, the key is different.
425 * If the picture looks the same, you still know nothing.
427 * The algorithm used here is a worm crawling over a discrete plane,
428 * leaving a trace (augmenting the field) everywhere it goes.
429 * Movement is taken from dgst_raw 2bit-wise. Bumping into walls
430 * makes the respective movement vector be ignored for this turn.
431 * Graphs are not unambiguous, because circles in graphs can be
432 * walked in either direction.
436 * Field sizes for the random art. Have to be odd, so the starting point
437 * can be in the exact middle of the picture, and FLDBASE should be >=8 .
438 * Else pictures would be too dense, and drawing the frame would
439 * fail, too, because the key type would not fit in anymore.
441 #define FLDBASE 8
442 #define FLDSIZE_Y (FLDBASE + 1)
443 #define FLDSIZE_X (FLDBASE * 2 + 1)
444 static char *
445 key_fingerprint_randomart(u_char *dgst_raw, u_int dgst_raw_len, const Key *k)
448 * Chars to be used after each other every time the worm
449 * intersects with itself. Matter of taste.
451 char *augmentation_string = " .o+=*BOX@%&#/^SE";
452 char *retval, *p;
453 u_char field[FLDSIZE_X][FLDSIZE_Y];
454 u_int i, b;
455 int x, y;
456 size_t len = strlen(augmentation_string) - 1;
458 retval = xcalloc(1, (FLDSIZE_X + 3) * (FLDSIZE_Y + 2));
460 /* initialize field */
461 memset(field, 0, FLDSIZE_X * FLDSIZE_Y * sizeof(char));
462 x = FLDSIZE_X / 2;
463 y = FLDSIZE_Y / 2;
465 /* process raw key */
466 for (i = 0; i < dgst_raw_len; i++) {
467 int input;
468 /* each byte conveys four 2-bit move commands */
469 input = dgst_raw[i];
470 for (b = 0; b < 4; b++) {
471 /* evaluate 2 bit, rest is shifted later */
472 x += (input & 0x1) ? 1 : -1;
473 y += (input & 0x2) ? 1 : -1;
475 /* assure we are still in bounds */
476 x = MAX(x, 0);
477 y = MAX(y, 0);
478 x = MIN(x, FLDSIZE_X - 1);
479 y = MIN(y, FLDSIZE_Y - 1);
481 /* augment the field */
482 if (field[x][y] < len - 2)
483 field[x][y]++;
484 input = input >> 2;
488 /* mark starting point and end point*/
489 field[FLDSIZE_X / 2][FLDSIZE_Y / 2] = len - 1;
490 field[x][y] = len;
492 /* fill in retval */
493 snprintf(retval, FLDSIZE_X, "+--[%4s %4u]", key_type(k), key_size(k));
494 p = strchr(retval, '\0');
496 /* output upper border */
497 for (i = p - retval - 1; i < FLDSIZE_X; i++)
498 *p++ = '-';
499 *p++ = '+';
500 *p++ = '\n';
502 /* output content */
503 for (y = 0; y < FLDSIZE_Y; y++) {
504 *p++ = '|';
505 for (x = 0; x < FLDSIZE_X; x++)
506 *p++ = augmentation_string[MIN(field[x][y], len)];
507 *p++ = '|';
508 *p++ = '\n';
511 /* output lower border */
512 *p++ = '+';
513 for (i = 0; i < FLDSIZE_X; i++)
514 *p++ = '-';
515 *p++ = '+';
517 return retval;
520 char *
521 key_fingerprint(Key *k, enum fp_type dgst_type, enum fp_rep dgst_rep)
523 char *retval = NULL;
524 u_char *dgst_raw;
525 u_int dgst_raw_len;
527 dgst_raw = key_fingerprint_raw(k, dgst_type, &dgst_raw_len);
528 if (!dgst_raw)
529 fatal("key_fingerprint: null from key_fingerprint_raw()");
530 switch (dgst_rep) {
531 case SSH_FP_HEX:
532 retval = key_fingerprint_hex(dgst_raw, dgst_raw_len);
533 break;
534 case SSH_FP_BUBBLEBABBLE:
535 retval = key_fingerprint_bubblebabble(dgst_raw, dgst_raw_len);
536 break;
537 case SSH_FP_RANDOMART:
538 retval = key_fingerprint_randomart(dgst_raw, dgst_raw_len, k);
539 break;
540 default:
541 fatal("key_fingerprint: bad digest representation %d",
542 dgst_rep);
543 break;
545 memset(dgst_raw, 0, dgst_raw_len);
546 xfree(dgst_raw);
547 return retval;
551 * Reads a multiple-precision integer in decimal from the buffer, and advances
552 * the pointer. The integer must already be initialized. This function is
553 * permitted to modify the buffer. This leaves *cpp to point just beyond the
554 * last processed (and maybe modified) character. Note that this may modify
555 * the buffer containing the number.
557 static int
558 read_bignum(char **cpp, BIGNUM * value)
560 char *cp = *cpp;
561 int old;
563 /* Skip any leading whitespace. */
564 for (; *cp == ' ' || *cp == '\t'; cp++)
567 /* Check that it begins with a decimal digit. */
568 if (*cp < '0' || *cp > '9')
569 return 0;
571 /* Save starting position. */
572 *cpp = cp;
574 /* Move forward until all decimal digits skipped. */
575 for (; *cp >= '0' && *cp <= '9'; cp++)
578 /* Save the old terminating character, and replace it by \0. */
579 old = *cp;
580 *cp = 0;
582 /* Parse the number. */
583 if (BN_dec2bn(&value, *cpp) == 0)
584 return 0;
586 /* Restore old terminating character. */
587 *cp = old;
589 /* Move beyond the number and return success. */
590 *cpp = cp;
591 return 1;
594 static int
595 write_bignum(FILE *f, BIGNUM *num)
597 char *buf = BN_bn2dec(num);
598 if (buf == NULL) {
599 error("write_bignum: BN_bn2dec() failed");
600 return 0;
602 fprintf(f, " %s", buf);
603 OPENSSL_free(buf);
604 return 1;
607 /* returns 1 ok, -1 error */
609 key_read(Key *ret, char **cpp)
611 Key *k;
612 int success = -1;
613 char *cp, *space;
614 int len, n, type;
615 u_int bits;
616 u_char *blob;
618 cp = *cpp;
620 switch (ret->type) {
621 case KEY_RSA1:
622 /* Get number of bits. */
623 if (*cp < '0' || *cp > '9')
624 return -1; /* Bad bit count... */
625 for (bits = 0; *cp >= '0' && *cp <= '9'; cp++)
626 bits = 10 * bits + *cp - '0';
627 if (bits == 0)
628 return -1;
629 *cpp = cp;
630 /* Get public exponent, public modulus. */
631 if (!read_bignum(cpp, ret->rsa->e))
632 return -1;
633 if (!read_bignum(cpp, ret->rsa->n))
634 return -1;
635 /* validate the claimed number of bits */
636 if ((u_int)BN_num_bits(ret->rsa->n) != bits) {
637 verbose("key_read: claimed key size %d does not match "
638 "actual %d", bits, BN_num_bits(ret->rsa->n));
639 return -1;
641 success = 1;
642 break;
643 case KEY_UNSPEC:
644 case KEY_RSA:
645 case KEY_DSA:
646 case KEY_DSA_CERT_V00:
647 case KEY_RSA_CERT_V00:
648 case KEY_DSA_CERT:
649 case KEY_RSA_CERT:
650 space = strchr(cp, ' ');
651 if (space == NULL) {
652 debug3("key_read: missing whitespace");
653 return -1;
655 *space = '\0';
656 type = key_type_from_name(cp);
657 *space = ' ';
658 if (type == KEY_UNSPEC) {
659 debug3("key_read: missing keytype");
660 return -1;
662 cp = space+1;
663 if (*cp == '\0') {
664 debug3("key_read: short string");
665 return -1;
667 if (ret->type == KEY_UNSPEC) {
668 ret->type = type;
669 } else if (ret->type != type) {
670 /* is a key, but different type */
671 debug3("key_read: type mismatch");
672 return -1;
674 len = 2*strlen(cp);
675 blob = xmalloc(len);
676 n = uudecode(cp, blob, len);
677 if (n < 0) {
678 error("key_read: uudecode %s failed", cp);
679 xfree(blob);
680 return -1;
682 k = key_from_blob(blob, (u_int)n);
683 xfree(blob);
684 if (k == NULL) {
685 error("key_read: key_from_blob %s failed", cp);
686 return -1;
688 if (k->type != type) {
689 error("key_read: type mismatch: encoding error");
690 key_free(k);
691 return -1;
693 /*XXXX*/
694 if (key_is_cert(ret)) {
695 if (!key_is_cert(k)) {
696 error("key_read: loaded key is not a cert");
697 key_free(k);
698 return -1;
700 if (ret->cert != NULL)
701 cert_free(ret->cert);
702 ret->cert = k->cert;
703 k->cert = NULL;
705 if (key_type_plain(ret->type) == KEY_RSA) {
706 if (ret->rsa != NULL)
707 RSA_free(ret->rsa);
708 ret->rsa = k->rsa;
709 k->rsa = NULL;
710 #ifdef DEBUG_PK
711 RSA_print_fp(stderr, ret->rsa, 8);
712 #endif
714 if (key_type_plain(ret->type) == KEY_DSA) {
715 if (ret->dsa != NULL)
716 DSA_free(ret->dsa);
717 ret->dsa = k->dsa;
718 k->dsa = NULL;
719 #ifdef DEBUG_PK
720 DSA_print_fp(stderr, ret->dsa, 8);
721 #endif
723 success = 1;
724 /*XXXX*/
725 key_free(k);
726 if (success != 1)
727 break;
728 /* advance cp: skip whitespace and data */
729 while (*cp == ' ' || *cp == '\t')
730 cp++;
731 while (*cp != '\0' && *cp != ' ' && *cp != '\t')
732 cp++;
733 *cpp = cp;
734 break;
735 default:
736 fatal("key_read: bad key type: %d", ret->type);
737 break;
739 return success;
743 key_write(const Key *key, FILE *f)
745 int n, success = 0;
746 u_int len, bits = 0;
747 u_char *blob;
748 char *uu;
750 if (key_is_cert(key)) {
751 if (key->cert == NULL) {
752 error("%s: no cert data", __func__);
753 return 0;
755 if (buffer_len(&key->cert->certblob) == 0) {
756 error("%s: no signed certificate blob", __func__);
757 return 0;
761 switch (key->type) {
762 case KEY_RSA1:
763 if (key->rsa == NULL)
764 return 0;
765 /* size of modulus 'n' */
766 bits = BN_num_bits(key->rsa->n);
767 fprintf(f, "%u", bits);
768 if (write_bignum(f, key->rsa->e) &&
769 write_bignum(f, key->rsa->n))
770 return 1;
771 error("key_write: failed for RSA key");
772 return 0;
773 case KEY_DSA:
774 case KEY_DSA_CERT_V00:
775 case KEY_DSA_CERT:
776 if (key->dsa == NULL)
777 return 0;
778 break;
779 case KEY_RSA:
780 case KEY_RSA_CERT_V00:
781 case KEY_RSA_CERT:
782 if (key->rsa == NULL)
783 return 0;
784 break;
785 default:
786 return 0;
789 key_to_blob(key, &blob, &len);
790 uu = xmalloc(2*len);
791 n = uuencode(blob, len, uu, 2*len);
792 if (n > 0) {
793 fprintf(f, "%s %s", key_ssh_name(key), uu);
794 success = 1;
796 xfree(blob);
797 xfree(uu);
799 return success;
802 const char *
803 key_type(const Key *k)
805 switch (k->type) {
806 case KEY_RSA1:
807 return "RSA1";
808 case KEY_RSA:
809 return "RSA";
810 case KEY_DSA:
811 return "DSA";
812 case KEY_RSA_CERT_V00:
813 return "RSA-CERT-V00";
814 case KEY_DSA_CERT_V00:
815 return "DSA-CERT-V00";
816 case KEY_RSA_CERT:
817 return "RSA-CERT";
818 case KEY_DSA_CERT:
819 return "DSA-CERT";
821 return "unknown";
824 const char *
825 key_cert_type(const Key *k)
827 switch (k->cert->type) {
828 case SSH2_CERT_TYPE_USER:
829 return "user";
830 case SSH2_CERT_TYPE_HOST:
831 return "host";
832 default:
833 return "unknown";
837 const char *
838 key_ssh_name(const Key *k)
840 switch (k->type) {
841 case KEY_RSA:
842 return "ssh-rsa";
843 case KEY_DSA:
844 return "ssh-dss";
845 case KEY_RSA_CERT_V00:
846 return "ssh-rsa-cert-v00@openssh.com";
847 case KEY_DSA_CERT_V00:
848 return "ssh-dss-cert-v00@openssh.com";
849 case KEY_RSA_CERT:
850 return "ssh-rsa-cert-v01@openssh.com";
851 case KEY_DSA_CERT:
852 return "ssh-dss-cert-v01@openssh.com";
854 return "ssh-unknown";
857 u_int
858 key_size(const Key *k)
860 switch (k->type) {
861 case KEY_RSA1:
862 case KEY_RSA:
863 case KEY_RSA_CERT_V00:
864 case KEY_RSA_CERT:
865 return BN_num_bits(k->rsa->n);
866 case KEY_DSA:
867 case KEY_DSA_CERT_V00:
868 case KEY_DSA_CERT:
869 return BN_num_bits(k->dsa->p);
871 return 0;
874 static RSA *
875 rsa_generate_private_key(u_int bits)
877 RSA *private;
879 private = RSA_generate_key(bits, RSA_F4, NULL, NULL);
880 if (private == NULL)
881 fatal("rsa_generate_private_key: key generation failed.");
882 return private;
885 static DSA*
886 dsa_generate_private_key(u_int bits)
888 DSA *private = DSA_generate_parameters(bits, NULL, 0, NULL, NULL, NULL, NULL);
890 if (private == NULL)
891 fatal("dsa_generate_private_key: DSA_generate_parameters failed");
892 if (!DSA_generate_key(private))
893 fatal("dsa_generate_private_key: DSA_generate_key failed.");
894 if (private == NULL)
895 fatal("dsa_generate_private_key: NULL.");
896 return private;
899 Key *
900 key_generate(int type, u_int bits)
902 Key *k = key_new(KEY_UNSPEC);
903 switch (type) {
904 case KEY_DSA:
905 k->dsa = dsa_generate_private_key(bits);
906 break;
907 case KEY_RSA:
908 case KEY_RSA1:
909 k->rsa = rsa_generate_private_key(bits);
910 break;
911 case KEY_RSA_CERT_V00:
912 case KEY_DSA_CERT_V00:
913 case KEY_RSA_CERT:
914 case KEY_DSA_CERT:
915 fatal("key_generate: cert keys cannot be generated directly");
916 default:
917 fatal("key_generate: unknown type %d", type);
919 k->type = type;
920 return k;
923 void
924 key_cert_copy(const Key *from_key, struct Key *to_key)
926 u_int i;
927 const struct KeyCert *from;
928 struct KeyCert *to;
930 if (to_key->cert != NULL) {
931 cert_free(to_key->cert);
932 to_key->cert = NULL;
935 if ((from = from_key->cert) == NULL)
936 return;
938 to = to_key->cert = cert_new();
940 buffer_append(&to->certblob, buffer_ptr(&from->certblob),
941 buffer_len(&from->certblob));
943 buffer_append(&to->critical,
944 buffer_ptr(&from->critical), buffer_len(&from->critical));
945 buffer_append(&to->extensions,
946 buffer_ptr(&from->extensions), buffer_len(&from->extensions));
948 to->serial = from->serial;
949 to->type = from->type;
950 to->key_id = from->key_id == NULL ? NULL : xstrdup(from->key_id);
951 to->valid_after = from->valid_after;
952 to->valid_before = from->valid_before;
953 to->signature_key = from->signature_key == NULL ?
954 NULL : key_from_private(from->signature_key);
956 to->nprincipals = from->nprincipals;
957 if (to->nprincipals > CERT_MAX_PRINCIPALS)
958 fatal("%s: nprincipals (%u) > CERT_MAX_PRINCIPALS (%u)",
959 __func__, to->nprincipals, CERT_MAX_PRINCIPALS);
960 if (to->nprincipals > 0) {
961 to->principals = xcalloc(from->nprincipals,
962 sizeof(*to->principals));
963 for (i = 0; i < to->nprincipals; i++)
964 to->principals[i] = xstrdup(from->principals[i]);
968 Key *
969 key_from_private(const Key *k)
971 Key *n = NULL;
972 switch (k->type) {
973 case KEY_DSA:
974 case KEY_DSA_CERT_V00:
975 case KEY_DSA_CERT:
976 n = key_new(k->type);
977 if ((BN_copy(n->dsa->p, k->dsa->p) == NULL) ||
978 (BN_copy(n->dsa->q, k->dsa->q) == NULL) ||
979 (BN_copy(n->dsa->g, k->dsa->g) == NULL) ||
980 (BN_copy(n->dsa->pub_key, k->dsa->pub_key) == NULL))
981 fatal("key_from_private: BN_copy failed");
982 break;
983 case KEY_RSA:
984 case KEY_RSA1:
985 case KEY_RSA_CERT_V00:
986 case KEY_RSA_CERT:
987 n = key_new(k->type);
988 if ((BN_copy(n->rsa->n, k->rsa->n) == NULL) ||
989 (BN_copy(n->rsa->e, k->rsa->e) == NULL))
990 fatal("key_from_private: BN_copy failed");
991 break;
992 default:
993 fatal("key_from_private: unknown type %d", k->type);
994 break;
996 if (key_is_cert(k))
997 key_cert_copy(k, n);
998 return n;
1002 key_type_from_name(char *name)
1004 if (strcmp(name, "rsa1") == 0) {
1005 return KEY_RSA1;
1006 } else if (strcmp(name, "rsa") == 0) {
1007 return KEY_RSA;
1008 } else if (strcmp(name, "dsa") == 0) {
1009 return KEY_DSA;
1010 } else if (strcmp(name, "ssh-rsa") == 0) {
1011 return KEY_RSA;
1012 } else if (strcmp(name, "ssh-dss") == 0) {
1013 return KEY_DSA;
1014 } else if (strcmp(name, "ssh-rsa-cert-v00@openssh.com") == 0) {
1015 return KEY_RSA_CERT_V00;
1016 } else if (strcmp(name, "ssh-dss-cert-v00@openssh.com") == 0) {
1017 return KEY_DSA_CERT_V00;
1018 } else if (strcmp(name, "ssh-rsa-cert-v01@openssh.com") == 0) {
1019 return KEY_RSA_CERT;
1020 } else if (strcmp(name, "ssh-dss-cert-v01@openssh.com") == 0) {
1021 return KEY_DSA_CERT;
1023 debug2("key_type_from_name: unknown key type '%s'", name);
1024 return KEY_UNSPEC;
1028 key_names_valid2(const char *names)
1030 char *s, *cp, *p;
1032 if (names == NULL || strcmp(names, "") == 0)
1033 return 0;
1034 s = cp = xstrdup(names);
1035 for ((p = strsep(&cp, ",")); p && *p != '\0';
1036 (p = strsep(&cp, ","))) {
1037 switch (key_type_from_name(p)) {
1038 case KEY_RSA1:
1039 case KEY_UNSPEC:
1040 xfree(s);
1041 return 0;
1044 debug3("key names ok: [%s]", names);
1045 xfree(s);
1046 return 1;
1049 static int
1050 cert_parse(Buffer *b, Key *key, const u_char *blob, u_int blen)
1052 u_char *principals, *critical, *exts, *sig_key, *sig;
1053 u_int signed_len, plen, clen, sklen, slen, kidlen, elen;
1054 Buffer tmp;
1055 char *principal;
1056 int ret = -1;
1057 int v00 = key->type == KEY_DSA_CERT_V00 ||
1058 key->type == KEY_RSA_CERT_V00;
1060 buffer_init(&tmp);
1062 /* Copy the entire key blob for verification and later serialisation */
1063 buffer_append(&key->cert->certblob, blob, blen);
1065 elen = 0; /* Not touched for v00 certs */
1066 principals = exts = critical = sig_key = sig = NULL;
1067 if ((!v00 && buffer_get_int64_ret(&key->cert->serial, b) != 0) ||
1068 buffer_get_int_ret(&key->cert->type, b) != 0 ||
1069 (key->cert->key_id = buffer_get_string_ret(b, &kidlen)) == NULL ||
1070 (principals = buffer_get_string_ret(b, &plen)) == NULL ||
1071 buffer_get_int64_ret(&key->cert->valid_after, b) != 0 ||
1072 buffer_get_int64_ret(&key->cert->valid_before, b) != 0 ||
1073 (critical = buffer_get_string_ret(b, &clen)) == NULL ||
1074 (!v00 && (exts = buffer_get_string_ret(b, &elen)) == NULL) ||
1075 (v00 && buffer_get_string_ptr_ret(b, NULL) == NULL) || /* nonce */
1076 buffer_get_string_ptr_ret(b, NULL) == NULL || /* reserved */
1077 (sig_key = buffer_get_string_ret(b, &sklen)) == NULL) {
1078 error("%s: parse error", __func__);
1079 goto out;
1082 if (kidlen != strlen(key->cert->key_id)) {
1083 error("%s: key ID contains \\0 character", __func__);
1084 goto out;
1087 /* Signature is left in the buffer so we can calculate this length */
1088 signed_len = buffer_len(&key->cert->certblob) - buffer_len(b);
1090 if ((sig = buffer_get_string_ret(b, &slen)) == NULL) {
1091 error("%s: parse error", __func__);
1092 goto out;
1095 if (key->cert->type != SSH2_CERT_TYPE_USER &&
1096 key->cert->type != SSH2_CERT_TYPE_HOST) {
1097 error("Unknown certificate type %u", key->cert->type);
1098 goto out;
1101 buffer_append(&tmp, principals, plen);
1102 while (buffer_len(&tmp) > 0) {
1103 if (key->cert->nprincipals >= CERT_MAX_PRINCIPALS) {
1104 error("%s: Too many principals", __func__);
1105 goto out;
1107 if ((principal = buffer_get_string_ret(&tmp, &plen)) == NULL) {
1108 error("%s: Principals data invalid", __func__);
1109 goto out;
1111 if (strlen(principal) != plen) {
1112 error("%s: Principal contains \\0 character",
1113 __func__);
1114 goto out;
1116 key->cert->principals = xrealloc(key->cert->principals,
1117 key->cert->nprincipals + 1, sizeof(*key->cert->principals));
1118 key->cert->principals[key->cert->nprincipals++] = principal;
1121 buffer_clear(&tmp);
1123 buffer_append(&key->cert->critical, critical, clen);
1124 buffer_append(&tmp, critical, clen);
1125 /* validate structure */
1126 while (buffer_len(&tmp) != 0) {
1127 if (buffer_get_string_ptr_ret(&tmp, NULL) == NULL ||
1128 buffer_get_string_ptr_ret(&tmp, NULL) == NULL) {
1129 error("%s: critical option data invalid", __func__);
1130 goto out;
1133 buffer_clear(&tmp);
1135 buffer_append(&key->cert->extensions, exts, elen);
1136 buffer_append(&tmp, exts, elen);
1137 /* validate structure */
1138 while (buffer_len(&tmp) != 0) {
1139 if (buffer_get_string_ptr_ret(&tmp, NULL) == NULL ||
1140 buffer_get_string_ptr_ret(&tmp, NULL) == NULL) {
1141 error("%s: extension data invalid", __func__);
1142 goto out;
1145 buffer_clear(&tmp);
1147 if ((key->cert->signature_key = key_from_blob(sig_key,
1148 sklen)) == NULL) {
1149 error("%s: Signature key invalid", __func__);
1150 goto out;
1152 if (key->cert->signature_key->type != KEY_RSA &&
1153 key->cert->signature_key->type != KEY_DSA) {
1154 error("%s: Invalid signature key type %s (%d)", __func__,
1155 key_type(key->cert->signature_key),
1156 key->cert->signature_key->type);
1157 goto out;
1160 switch (key_verify(key->cert->signature_key, sig, slen,
1161 buffer_ptr(&key->cert->certblob), signed_len)) {
1162 case 1:
1163 ret = 0;
1164 break; /* Good signature */
1165 case 0:
1166 error("%s: Invalid signature on certificate", __func__);
1167 goto out;
1168 case -1:
1169 error("%s: Certificate signature verification failed",
1170 __func__);
1171 goto out;
1174 out:
1175 buffer_free(&tmp);
1176 if (principals != NULL)
1177 xfree(principals);
1178 if (critical != NULL)
1179 xfree(critical);
1180 if (exts != NULL)
1181 xfree(exts);
1182 if (sig_key != NULL)
1183 xfree(sig_key);
1184 if (sig != NULL)
1185 xfree(sig);
1186 return ret;
1189 Key *
1190 key_from_blob(const u_char *blob, u_int blen)
1192 Buffer b;
1193 int rlen, type;
1194 char *ktype = NULL;
1195 Key *key = NULL;
1197 #ifdef DEBUG_PK
1198 dump_base64(stderr, blob, blen);
1199 #endif
1200 buffer_init(&b);
1201 buffer_append(&b, blob, blen);
1202 if ((ktype = buffer_get_string_ret(&b, NULL)) == NULL) {
1203 error("key_from_blob: can't read key type");
1204 goto out;
1207 type = key_type_from_name(ktype);
1209 switch (type) {
1210 case KEY_RSA_CERT:
1211 (void)buffer_get_string_ptr_ret(&b, NULL); /* Skip nonce */
1212 /* FALLTHROUGH */
1213 case KEY_RSA:
1214 case KEY_RSA_CERT_V00:
1215 key = key_new(type);
1216 if (buffer_get_bignum2_ret(&b, key->rsa->e) == -1 ||
1217 buffer_get_bignum2_ret(&b, key->rsa->n) == -1) {
1218 error("key_from_blob: can't read rsa key");
1219 badkey:
1220 key_free(key);
1221 key = NULL;
1222 goto out;
1224 #ifdef DEBUG_PK
1225 RSA_print_fp(stderr, key->rsa, 8);
1226 #endif
1227 break;
1228 case KEY_DSA_CERT:
1229 (void)buffer_get_string_ptr_ret(&b, NULL); /* Skip nonce */
1230 /* FALLTHROUGH */
1231 case KEY_DSA:
1232 case KEY_DSA_CERT_V00:
1233 key = key_new(type);
1234 if (buffer_get_bignum2_ret(&b, key->dsa->p) == -1 ||
1235 buffer_get_bignum2_ret(&b, key->dsa->q) == -1 ||
1236 buffer_get_bignum2_ret(&b, key->dsa->g) == -1 ||
1237 buffer_get_bignum2_ret(&b, key->dsa->pub_key) == -1) {
1238 error("key_from_blob: can't read dsa key");
1239 goto badkey;
1241 #ifdef DEBUG_PK
1242 DSA_print_fp(stderr, key->dsa, 8);
1243 #endif
1244 break;
1245 case KEY_UNSPEC:
1246 key = key_new(type);
1247 break;
1248 default:
1249 error("key_from_blob: cannot handle type %s", ktype);
1250 goto out;
1252 if (key_is_cert(key) && cert_parse(&b, key, blob, blen) == -1) {
1253 error("key_from_blob: can't parse cert data");
1254 goto badkey;
1256 rlen = buffer_len(&b);
1257 if (key != NULL && rlen != 0)
1258 error("key_from_blob: remaining bytes in key blob %d", rlen);
1259 out:
1260 if (ktype != NULL)
1261 xfree(ktype);
1262 buffer_free(&b);
1263 return key;
1267 key_to_blob(const Key *key, u_char **blobp, u_int *lenp)
1269 Buffer b;
1270 int len;
1272 if (key == NULL) {
1273 error("key_to_blob: key == NULL");
1274 return 0;
1276 buffer_init(&b);
1277 switch (key->type) {
1278 case KEY_DSA_CERT_V00:
1279 case KEY_RSA_CERT_V00:
1280 case KEY_DSA_CERT:
1281 case KEY_RSA_CERT:
1282 /* Use the existing blob */
1283 buffer_append(&b, buffer_ptr(&key->cert->certblob),
1284 buffer_len(&key->cert->certblob));
1285 break;
1286 case KEY_DSA:
1287 buffer_put_cstring(&b, key_ssh_name(key));
1288 buffer_put_bignum2(&b, key->dsa->p);
1289 buffer_put_bignum2(&b, key->dsa->q);
1290 buffer_put_bignum2(&b, key->dsa->g);
1291 buffer_put_bignum2(&b, key->dsa->pub_key);
1292 break;
1293 case KEY_RSA:
1294 buffer_put_cstring(&b, key_ssh_name(key));
1295 buffer_put_bignum2(&b, key->rsa->e);
1296 buffer_put_bignum2(&b, key->rsa->n);
1297 break;
1298 default:
1299 error("key_to_blob: unsupported key type %d", key->type);
1300 buffer_free(&b);
1301 return 0;
1303 len = buffer_len(&b);
1304 if (lenp != NULL)
1305 *lenp = len;
1306 if (blobp != NULL) {
1307 *blobp = xmalloc(len);
1308 memcpy(*blobp, buffer_ptr(&b), len);
1310 memset(buffer_ptr(&b), 0, len);
1311 buffer_free(&b);
1312 return len;
1316 key_sign(
1317 const Key *key,
1318 u_char **sigp, u_int *lenp,
1319 const u_char *data, u_int datalen)
1321 switch (key->type) {
1322 case KEY_DSA_CERT_V00:
1323 case KEY_DSA_CERT:
1324 case KEY_DSA:
1325 return ssh_dss_sign(key, sigp, lenp, data, datalen);
1326 case KEY_RSA_CERT_V00:
1327 case KEY_RSA_CERT:
1328 case KEY_RSA:
1329 return ssh_rsa_sign(key, sigp, lenp, data, datalen);
1330 default:
1331 error("key_sign: invalid key type %d", key->type);
1332 return -1;
1337 * key_verify returns 1 for a correct signature, 0 for an incorrect signature
1338 * and -1 on error.
1341 key_verify(
1342 const Key *key,
1343 const u_char *signature, u_int signaturelen,
1344 const u_char *data, u_int datalen)
1346 if (signaturelen == 0)
1347 return -1;
1349 switch (key->type) {
1350 case KEY_DSA_CERT_V00:
1351 case KEY_DSA_CERT:
1352 case KEY_DSA:
1353 return ssh_dss_verify(key, signature, signaturelen, data, datalen);
1354 case KEY_RSA_CERT_V00:
1355 case KEY_RSA_CERT:
1356 case KEY_RSA:
1357 return ssh_rsa_verify(key, signature, signaturelen, data, datalen);
1358 default:
1359 error("key_verify: invalid key type %d", key->type);
1360 return -1;
1364 /* Converts a private to a public key */
1365 Key *
1366 key_demote(const Key *k)
1368 Key *pk;
1370 pk = xcalloc(1, sizeof(*pk));
1371 pk->type = k->type;
1372 pk->flags = k->flags;
1373 pk->dsa = NULL;
1374 pk->rsa = NULL;
1376 switch (k->type) {
1377 case KEY_RSA_CERT_V00:
1378 case KEY_RSA_CERT:
1379 key_cert_copy(k, pk);
1380 /* FALLTHROUGH */
1381 case KEY_RSA1:
1382 case KEY_RSA:
1383 if ((pk->rsa = RSA_new()) == NULL)
1384 fatal("key_demote: RSA_new failed");
1385 if ((pk->rsa->e = BN_dup(k->rsa->e)) == NULL)
1386 fatal("key_demote: BN_dup failed");
1387 if ((pk->rsa->n = BN_dup(k->rsa->n)) == NULL)
1388 fatal("key_demote: BN_dup failed");
1389 break;
1390 case KEY_DSA_CERT_V00:
1391 case KEY_DSA_CERT:
1392 key_cert_copy(k, pk);
1393 /* FALLTHROUGH */
1394 case KEY_DSA:
1395 if ((pk->dsa = DSA_new()) == NULL)
1396 fatal("key_demote: DSA_new failed");
1397 if ((pk->dsa->p = BN_dup(k->dsa->p)) == NULL)
1398 fatal("key_demote: BN_dup failed");
1399 if ((pk->dsa->q = BN_dup(k->dsa->q)) == NULL)
1400 fatal("key_demote: BN_dup failed");
1401 if ((pk->dsa->g = BN_dup(k->dsa->g)) == NULL)
1402 fatal("key_demote: BN_dup failed");
1403 if ((pk->dsa->pub_key = BN_dup(k->dsa->pub_key)) == NULL)
1404 fatal("key_demote: BN_dup failed");
1405 break;
1406 default:
1407 fatal("key_free: bad key type %d", k->type);
1408 break;
1411 return (pk);
1415 key_is_cert(const Key *k)
1417 if (k == NULL)
1418 return 0;
1419 switch (k->type) {
1420 case KEY_RSA_CERT_V00:
1421 case KEY_DSA_CERT_V00:
1422 case KEY_RSA_CERT:
1423 case KEY_DSA_CERT:
1424 return 1;
1425 default:
1426 return 0;
1430 /* Return the cert-less equivalent to a certified key type */
1432 key_type_plain(int type)
1434 switch (type) {
1435 case KEY_RSA_CERT_V00:
1436 case KEY_RSA_CERT:
1437 return KEY_RSA;
1438 case KEY_DSA_CERT_V00:
1439 case KEY_DSA_CERT:
1440 return KEY_DSA;
1441 default:
1442 return type;
1446 /* Convert a KEY_RSA or KEY_DSA to their _CERT equivalent */
1448 key_to_certified(Key *k, int legacy)
1450 switch (k->type) {
1451 case KEY_RSA:
1452 k->cert = cert_new();
1453 k->type = legacy ? KEY_RSA_CERT_V00 : KEY_RSA_CERT;
1454 return 0;
1455 case KEY_DSA:
1456 k->cert = cert_new();
1457 k->type = legacy ? KEY_DSA_CERT_V00 : KEY_DSA_CERT;
1458 return 0;
1459 default:
1460 error("%s: key has incorrect type %s", __func__, key_type(k));
1461 return -1;
1465 /* Convert a KEY_RSA_CERT or KEY_DSA_CERT to their raw key equivalent */
1467 key_drop_cert(Key *k)
1469 switch (k->type) {
1470 case KEY_RSA_CERT_V00:
1471 case KEY_RSA_CERT:
1472 cert_free(k->cert);
1473 k->type = KEY_RSA;
1474 return 0;
1475 case KEY_DSA_CERT_V00:
1476 case KEY_DSA_CERT:
1477 cert_free(k->cert);
1478 k->type = KEY_DSA;
1479 return 0;
1480 default:
1481 error("%s: key has incorrect type %s", __func__, key_type(k));
1482 return -1;
1486 /* Sign a KEY_RSA_CERT or KEY_DSA_CERT, (re-)generating the signed certblob */
1488 key_certify(Key *k, Key *ca)
1490 Buffer principals;
1491 u_char *ca_blob, *sig_blob, nonce[32];
1492 u_int i, ca_len, sig_len;
1494 if (k->cert == NULL) {
1495 error("%s: key lacks cert info", __func__);
1496 return -1;
1499 if (!key_is_cert(k)) {
1500 error("%s: certificate has unknown type %d", __func__,
1501 k->cert->type);
1502 return -1;
1505 if (ca->type != KEY_RSA && ca->type != KEY_DSA) {
1506 error("%s: CA key has unsupported type %s", __func__,
1507 key_type(ca));
1508 return -1;
1511 key_to_blob(ca, &ca_blob, &ca_len);
1513 buffer_clear(&k->cert->certblob);
1514 buffer_put_cstring(&k->cert->certblob, key_ssh_name(k));
1516 /* -v01 certs put nonce first */
1517 if (k->type == KEY_DSA_CERT || k->type == KEY_RSA_CERT) {
1518 arc4random_buf(&nonce, sizeof(nonce));
1519 buffer_put_string(&k->cert->certblob, nonce, sizeof(nonce));
1522 switch (k->type) {
1523 case KEY_DSA_CERT_V00:
1524 case KEY_DSA_CERT:
1525 buffer_put_bignum2(&k->cert->certblob, k->dsa->p);
1526 buffer_put_bignum2(&k->cert->certblob, k->dsa->q);
1527 buffer_put_bignum2(&k->cert->certblob, k->dsa->g);
1528 buffer_put_bignum2(&k->cert->certblob, k->dsa->pub_key);
1529 break;
1530 case KEY_RSA_CERT_V00:
1531 case KEY_RSA_CERT:
1532 buffer_put_bignum2(&k->cert->certblob, k->rsa->e);
1533 buffer_put_bignum2(&k->cert->certblob, k->rsa->n);
1534 break;
1535 default:
1536 error("%s: key has incorrect type %s", __func__, key_type(k));
1537 buffer_clear(&k->cert->certblob);
1538 xfree(ca_blob);
1539 return -1;
1542 /* -v01 certs have a serial number next */
1543 if (k->type == KEY_DSA_CERT || k->type == KEY_RSA_CERT)
1544 buffer_put_int64(&k->cert->certblob, k->cert->serial);
1546 buffer_put_int(&k->cert->certblob, k->cert->type);
1547 buffer_put_cstring(&k->cert->certblob, k->cert->key_id);
1549 buffer_init(&principals);
1550 for (i = 0; i < k->cert->nprincipals; i++)
1551 buffer_put_cstring(&principals, k->cert->principals[i]);
1552 buffer_put_string(&k->cert->certblob, buffer_ptr(&principals),
1553 buffer_len(&principals));
1554 buffer_free(&principals);
1556 buffer_put_int64(&k->cert->certblob, k->cert->valid_after);
1557 buffer_put_int64(&k->cert->certblob, k->cert->valid_before);
1558 buffer_put_string(&k->cert->certblob,
1559 buffer_ptr(&k->cert->critical), buffer_len(&k->cert->critical));
1561 /* -v01 certs have non-critical options here */
1562 if (k->type == KEY_DSA_CERT || k->type == KEY_RSA_CERT) {
1563 buffer_put_string(&k->cert->certblob,
1564 buffer_ptr(&k->cert->extensions),
1565 buffer_len(&k->cert->extensions));
1568 /* -v00 certs put the nonce at the end */
1569 if (k->type == KEY_DSA_CERT_V00 || k->type == KEY_RSA_CERT_V00)
1570 buffer_put_string(&k->cert->certblob, nonce, sizeof(nonce));
1572 buffer_put_string(&k->cert->certblob, NULL, 0); /* reserved */
1573 buffer_put_string(&k->cert->certblob, ca_blob, ca_len);
1574 xfree(ca_blob);
1576 /* Sign the whole mess */
1577 if (key_sign(ca, &sig_blob, &sig_len, buffer_ptr(&k->cert->certblob),
1578 buffer_len(&k->cert->certblob)) != 0) {
1579 error("%s: signature operation failed", __func__);
1580 buffer_clear(&k->cert->certblob);
1581 return -1;
1583 /* Append signature and we are done */
1584 buffer_put_string(&k->cert->certblob, sig_blob, sig_len);
1585 xfree(sig_blob);
1587 return 0;
1591 key_cert_check_authority(const Key *k, int want_host, int require_principal,
1592 const char *name, const char **reason)
1594 u_int i, principal_matches;
1595 time_t now = time(NULL);
1597 if (want_host) {
1598 if (k->cert->type != SSH2_CERT_TYPE_HOST) {
1599 *reason = "Certificate invalid: not a host certificate";
1600 return -1;
1602 } else {
1603 if (k->cert->type != SSH2_CERT_TYPE_USER) {
1604 *reason = "Certificate invalid: not a user certificate";
1605 return -1;
1608 if (now < 0) {
1609 error("%s: system clock lies before epoch", __func__);
1610 *reason = "Certificate invalid: not yet valid";
1611 return -1;
1613 if ((u_int64_t)now < k->cert->valid_after) {
1614 *reason = "Certificate invalid: not yet valid";
1615 return -1;
1617 if ((u_int64_t)now >= k->cert->valid_before) {
1618 *reason = "Certificate invalid: expired";
1619 return -1;
1621 if (k->cert->nprincipals == 0) {
1622 if (require_principal) {
1623 *reason = "Certificate lacks principal list";
1624 return -1;
1626 } else {
1627 principal_matches = 0;
1628 for (i = 0; i < k->cert->nprincipals; i++) {
1629 if (strcmp(name, k->cert->principals[i]) == 0) {
1630 principal_matches = 1;
1631 break;
1634 if (!principal_matches) {
1635 *reason = "Certificate invalid: name is not a listed "
1636 "principal";
1637 return -1;
1640 return 0;
1644 key_cert_is_legacy(Key *k)
1646 switch (k->type) {
1647 case KEY_DSA_CERT_V00:
1648 case KEY_RSA_CERT_V00:
1649 return 1;
1650 default:
1651 return 0;