1 /* $OpenBSD: key.c,v 1.73 2008/06/12 00:13:13 otto Exp $ */
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.
15 * Redistribution and use in source and binary forms, with or without
16 * modification, are permitted provided that the following conditions
18 * 1. Redistributions of source code must retain the above copyright
19 * notice, this list of conditions and the following disclaimer.
20 * 2. Redistributions in binary form must reproduce the above copyright
21 * notice, this list of conditions and the following disclaimer in the
22 * documentation and/or other materials provided with the distribution.
24 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
25 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
28 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 #include <sys/param.h>
39 #include <sys/types.h>
41 #include <openssl/evp.h>
42 #include <openbsd-compat/openssl-compat.h>
61 k = xcalloc(1, sizeof(*k));
68 if ((rsa = RSA_new()) == NULL)
69 fatal("key_new: RSA_new failed");
70 if ((rsa->n = BN_new()) == NULL)
71 fatal("key_new: BN_new failed");
72 if ((rsa->e = BN_new()) == NULL)
73 fatal("key_new: BN_new failed");
77 if ((dsa = DSA_new()) == NULL)
78 fatal("key_new: DSA_new failed");
79 if ((dsa->p = BN_new()) == NULL)
80 fatal("key_new: BN_new failed");
81 if ((dsa->q = BN_new()) == NULL)
82 fatal("key_new: BN_new failed");
83 if ((dsa->g = BN_new()) == NULL)
84 fatal("key_new: BN_new failed");
85 if ((dsa->pub_key = BN_new()) == NULL)
86 fatal("key_new: BN_new failed");
92 fatal("key_new: bad key type %d", k->type);
99 key_new_private(int type)
101 Key *k = key_new(type);
105 if ((k->rsa->d = BN_new()) == NULL)
106 fatal("key_new_private: BN_new failed");
107 if ((k->rsa->iqmp = BN_new()) == NULL)
108 fatal("key_new_private: BN_new failed");
109 if ((k->rsa->q = BN_new()) == NULL)
110 fatal("key_new_private: BN_new failed");
111 if ((k->rsa->p = BN_new()) == NULL)
112 fatal("key_new_private: BN_new failed");
113 if ((k->rsa->dmq1 = BN_new()) == NULL)
114 fatal("key_new_private: BN_new failed");
115 if ((k->rsa->dmp1 = BN_new()) == NULL)
116 fatal("key_new_private: BN_new failed");
119 if ((k->dsa->priv_key = BN_new()) == NULL)
120 fatal("key_new_private: BN_new failed");
134 fatal("key_free: key is NULL");
150 fatal("key_free: bad key type %d", k->type);
157 key_equal(const Key *a, const Key *b)
159 if (a == NULL || b == NULL || a->type != b->type)
164 return a->rsa != NULL && b->rsa != NULL &&
165 BN_cmp(a->rsa->e, b->rsa->e) == 0 &&
166 BN_cmp(a->rsa->n, b->rsa->n) == 0;
168 return a->dsa != NULL && b->dsa != NULL &&
169 BN_cmp(a->dsa->p, b->dsa->p) == 0 &&
170 BN_cmp(a->dsa->q, b->dsa->q) == 0 &&
171 BN_cmp(a->dsa->g, b->dsa->g) == 0 &&
172 BN_cmp(a->dsa->pub_key, b->dsa->pub_key) == 0;
174 fatal("key_equal: bad key type %d", a->type);
179 key_fingerprint_raw(const Key *k, enum fp_type dgst_type,
180 u_int *dgst_raw_length)
182 const EVP_MD *md = NULL;
185 u_char *retval = NULL;
189 *dgst_raw_length = 0;
199 fatal("key_fingerprint_raw: bad digest type %d",
204 nlen = BN_num_bytes(k->rsa->n);
205 elen = BN_num_bytes(k->rsa->e);
208 BN_bn2bin(k->rsa->n, blob);
209 BN_bn2bin(k->rsa->e, blob + nlen);
213 key_to_blob(k, &blob, &len);
218 fatal("key_fingerprint_raw: bad key type %d", k->type);
222 retval = xmalloc(EVP_MAX_MD_SIZE);
223 EVP_DigestInit(&ctx, md);
224 EVP_DigestUpdate(&ctx, blob, len);
225 EVP_DigestFinal(&ctx, retval, dgst_raw_length);
226 memset(blob, 0, len);
229 fatal("key_fingerprint_raw: blob is null");
235 key_fingerprint_hex(u_char *dgst_raw, u_int dgst_raw_len)
240 retval = xcalloc(1, dgst_raw_len * 3 + 1);
241 for (i = 0; i < dgst_raw_len; i++) {
243 snprintf(hex, sizeof(hex), "%02x:", dgst_raw[i]);
244 strlcat(retval, hex, dgst_raw_len * 3 + 1);
247 /* Remove the trailing ':' character */
248 retval[(dgst_raw_len * 3) - 1] = '\0';
253 key_fingerprint_bubblebabble(u_char *dgst_raw, u_int dgst_raw_len)
255 char vowels[] = { 'a', 'e', 'i', 'o', 'u', 'y' };
256 char consonants[] = { 'b', 'c', 'd', 'f', 'g', 'h', 'k', 'l', 'm',
257 'n', 'p', 'r', 's', 't', 'v', 'z', 'x' };
258 u_int i, j = 0, rounds, seed = 1;
261 rounds = (dgst_raw_len / 2) + 1;
262 retval = xcalloc((rounds * 6), sizeof(char));
264 for (i = 0; i < rounds; i++) {
265 u_int idx0, idx1, idx2, idx3, idx4;
266 if ((i + 1 < rounds) || (dgst_raw_len % 2 != 0)) {
267 idx0 = (((((u_int)(dgst_raw[2 * i])) >> 6) & 3) +
269 idx1 = (((u_int)(dgst_raw[2 * i])) >> 2) & 15;
270 idx2 = ((((u_int)(dgst_raw[2 * i])) & 3) +
272 retval[j++] = vowels[idx0];
273 retval[j++] = consonants[idx1];
274 retval[j++] = vowels[idx2];
275 if ((i + 1) < rounds) {
276 idx3 = (((u_int)(dgst_raw[(2 * i) + 1])) >> 4) & 15;
277 idx4 = (((u_int)(dgst_raw[(2 * i) + 1]))) & 15;
278 retval[j++] = consonants[idx3];
280 retval[j++] = consonants[idx4];
282 ((((u_int)(dgst_raw[2 * i])) * 7) +
283 ((u_int)(dgst_raw[(2 * i) + 1])))) % 36;
289 retval[j++] = vowels[idx0];
290 retval[j++] = consonants[idx1];
291 retval[j++] = vowels[idx2];
300 * Draw an ASCII-Art representing the fingerprint so human brain can
301 * profit from its built-in pattern recognition ability.
302 * This technique is called "random art" and can be found in some
303 * scientific publications like this original paper:
305 * "Hash Visualization: a New Technique to improve Real-World Security",
306 * Perrig A. and Song D., 1999, International Workshop on Cryptographic
307 * Techniques and E-Commerce (CrypTEC '99)
308 * sparrow.ece.cmu.edu/~adrian/projects/validation/validation.pdf
310 * The subject came up in a talk by Dan Kaminsky, too.
312 * If you see the picture is different, the key is different.
313 * If the picture looks the same, you still know nothing.
315 * The algorithm used here is a worm crawling over a discrete plane,
316 * leaving a trace (augmenting the field) everywhere it goes.
317 * Movement is taken from dgst_raw 2bit-wise. Bumping into walls
318 * makes the respective movement vector be ignored for this turn.
319 * Graphs are not unambiguous, because circles in graphs can be
320 * walked in either direction.
322 #define FLDSIZE_Y (8 + 1)
323 #define FLDSIZE_X (8 * 2 + 1)
325 key_fingerprint_randomart(u_char *dgst_raw, u_int dgst_raw_len)
328 * Chars to be used after each other every time the worm
329 * intersects with itself. Matter of taste.
331 char *augmentation_string = " .o+=*BOX@%&#/^S";
333 u_char field[FLDSIZE_X][FLDSIZE_Y];
336 size_t len = strlen(augmentation_string) - 1;
338 retval = xcalloc(1, (FLDSIZE_X + 3) * (FLDSIZE_Y + 2));
340 /* initialize field */
341 memset(field, 0, FLDSIZE_X * FLDSIZE_Y * sizeof(char));
345 /* process raw key */
346 for (i = 0; i < dgst_raw_len; i++) {
348 /* each byte conveys four 2-bit move commands */
350 for (b = 0; b < 4; b++) {
351 /* evaluate 2 bit, rest is shifted later */
352 x += (input & 0x1) ? 1 : -1;
353 y += (input & 0x2) ? 1 : -1;
355 /* assure we are still in bounds */
358 x = MIN(x, FLDSIZE_X - 1);
359 y = MIN(y, FLDSIZE_Y - 1);
361 /* augment the field */
366 field[FLDSIZE_X / 2][FLDSIZE_Y / 2] = len;
371 /* output upper border */
373 for (i = 0; i < FLDSIZE_X; i++)
379 for (y = 0; y < FLDSIZE_Y; y++) {
381 for (x = 0; x < FLDSIZE_X; x++)
382 *p++ = augmentation_string[MIN(field[x][y], len)];
387 /* output lower border */
389 for (i = 0; i < FLDSIZE_X; i++)
397 key_fingerprint(const Key *k, enum fp_type dgst_type, enum fp_rep dgst_rep)
403 dgst_raw = key_fingerprint_raw(k, dgst_type, &dgst_raw_len);
405 fatal("key_fingerprint: null from key_fingerprint_raw()");
408 retval = key_fingerprint_hex(dgst_raw, dgst_raw_len);
410 case SSH_FP_BUBBLEBABBLE:
411 retval = key_fingerprint_bubblebabble(dgst_raw, dgst_raw_len);
413 case SSH_FP_RANDOMART:
414 retval = key_fingerprint_randomart(dgst_raw, dgst_raw_len);
417 fatal("key_fingerprint_ex: bad digest representation %d",
421 memset(dgst_raw, 0, dgst_raw_len);
427 * Reads a multiple-precision integer in decimal from the buffer, and advances
428 * the pointer. The integer must already be initialized. This function is
429 * permitted to modify the buffer. This leaves *cpp to point just beyond the
430 * last processed (and maybe modified) character. Note that this may modify
431 * the buffer containing the number.
434 read_bignum(char **cpp, BIGNUM * value)
439 /* Skip any leading whitespace. */
440 for (; *cp == ' ' || *cp == '\t'; cp++)
443 /* Check that it begins with a decimal digit. */
444 if (*cp < '0' || *cp > '9')
447 /* Save starting position. */
450 /* Move forward until all decimal digits skipped. */
451 for (; *cp >= '0' && *cp <= '9'; cp++)
454 /* Save the old terminating character, and replace it by \0. */
458 /* Parse the number. */
459 if (BN_dec2bn(&value, *cpp) == 0)
462 /* Restore old terminating character. */
465 /* Move beyond the number and return success. */
471 write_bignum(FILE *f, BIGNUM *num)
473 char *buf = BN_bn2dec(num);
475 error("write_bignum: BN_bn2dec() failed");
478 fprintf(f, " %s", buf);
483 /* returns 1 ok, -1 error */
485 key_read(Key *ret, char **cpp)
498 /* Get number of bits. */
499 if (*cp < '0' || *cp > '9')
500 return -1; /* Bad bit count... */
501 for (bits = 0; *cp >= '0' && *cp <= '9'; cp++)
502 bits = 10 * bits + *cp - '0';
506 /* Get public exponent, public modulus. */
507 if (!read_bignum(cpp, ret->rsa->e))
509 if (!read_bignum(cpp, ret->rsa->n))
516 space = strchr(cp, ' ');
518 debug3("key_read: missing whitespace");
522 type = key_type_from_name(cp);
524 if (type == KEY_UNSPEC) {
525 debug3("key_read: missing keytype");
530 debug3("key_read: short string");
533 if (ret->type == KEY_UNSPEC) {
535 } else if (ret->type != type) {
536 /* is a key, but different type */
537 debug3("key_read: type mismatch");
542 n = uudecode(cp, blob, len);
544 error("key_read: uudecode %s failed", cp);
548 k = key_from_blob(blob, (u_int)n);
551 error("key_read: key_from_blob %s failed", cp);
554 if (k->type != type) {
555 error("key_read: type mismatch: encoding error");
560 if (ret->type == KEY_RSA) {
561 if (ret->rsa != NULL)
567 RSA_print_fp(stderr, ret->rsa, 8);
570 if (ret->dsa != NULL)
576 DSA_print_fp(stderr, ret->dsa, 8);
583 /* advance cp: skip whitespace and data */
584 while (*cp == ' ' || *cp == '\t')
586 while (*cp != '\0' && *cp != ' ' && *cp != '\t')
591 fatal("key_read: bad key type: %d", ret->type);
598 key_write(const Key *key, FILE *f)
605 if (key->type == KEY_RSA1 && key->rsa != NULL) {
606 /* size of modulus 'n' */
607 bits = BN_num_bits(key->rsa->n);
608 fprintf(f, "%u", bits);
609 if (write_bignum(f, key->rsa->e) &&
610 write_bignum(f, key->rsa->n)) {
613 error("key_write: failed for RSA key");
615 } else if ((key->type == KEY_DSA && key->dsa != NULL) ||
616 (key->type == KEY_RSA && key->rsa != NULL)) {
617 key_to_blob(key, &blob, &len);
619 n = uuencode(blob, len, uu, 2*len);
621 fprintf(f, "%s %s", key_ssh_name(key), uu);
631 key_type(const Key *k)
645 key_ssh_name(const Key *k)
653 return "ssh-unknown";
657 key_size(const Key *k)
662 return BN_num_bits(k->rsa->n);
664 return BN_num_bits(k->dsa->p);
670 rsa_generate_private_key(u_int bits)
674 private = RSA_generate_key(bits, 35, NULL, NULL);
676 fatal("rsa_generate_private_key: key generation failed.");
681 dsa_generate_private_key(u_int bits)
683 DSA *private = DSA_generate_parameters(bits, NULL, 0, NULL, NULL, NULL, NULL);
686 fatal("dsa_generate_private_key: DSA_generate_parameters failed");
687 if (!DSA_generate_key(private))
688 fatal("dsa_generate_private_key: DSA_generate_key failed.");
690 fatal("dsa_generate_private_key: NULL.");
695 key_generate(int type, u_int bits)
697 Key *k = key_new(KEY_UNSPEC);
700 k->dsa = dsa_generate_private_key(bits);
704 k->rsa = rsa_generate_private_key(bits);
707 fatal("key_generate: unknown type %d", type);
714 key_from_private(const Key *k)
719 n = key_new(k->type);
720 if ((BN_copy(n->dsa->p, k->dsa->p) == NULL) ||
721 (BN_copy(n->dsa->q, k->dsa->q) == NULL) ||
722 (BN_copy(n->dsa->g, k->dsa->g) == NULL) ||
723 (BN_copy(n->dsa->pub_key, k->dsa->pub_key) == NULL))
724 fatal("key_from_private: BN_copy failed");
728 n = key_new(k->type);
729 if ((BN_copy(n->rsa->n, k->rsa->n) == NULL) ||
730 (BN_copy(n->rsa->e, k->rsa->e) == NULL))
731 fatal("key_from_private: BN_copy failed");
734 fatal("key_from_private: unknown type %d", k->type);
741 key_type_from_name(char *name)
743 if (strcmp(name, "rsa1") == 0) {
745 } else if (strcmp(name, "rsa") == 0) {
747 } else if (strcmp(name, "dsa") == 0) {
749 } else if (strcmp(name, "ssh-rsa") == 0) {
751 } else if (strcmp(name, "ssh-dss") == 0) {
754 debug2("key_type_from_name: unknown key type '%s'", name);
759 key_names_valid2(const char *names)
763 if (names == NULL || strcmp(names, "") == 0)
765 s = cp = xstrdup(names);
766 for ((p = strsep(&cp, ",")); p && *p != '\0';
767 (p = strsep(&cp, ","))) {
768 switch (key_type_from_name(p)) {
775 debug3("key names ok: [%s]", names);
781 key_from_blob(const u_char *blob, u_int blen)
789 dump_base64(stderr, blob, blen);
792 buffer_append(&b, blob, blen);
793 if ((ktype = buffer_get_string_ret(&b, NULL)) == NULL) {
794 error("key_from_blob: can't read key type");
798 type = key_type_from_name(ktype);
803 if (buffer_get_bignum2_ret(&b, key->rsa->e) == -1 ||
804 buffer_get_bignum2_ret(&b, key->rsa->n) == -1) {
805 error("key_from_blob: can't read rsa key");
811 RSA_print_fp(stderr, key->rsa, 8);
816 if (buffer_get_bignum2_ret(&b, key->dsa->p) == -1 ||
817 buffer_get_bignum2_ret(&b, key->dsa->q) == -1 ||
818 buffer_get_bignum2_ret(&b, key->dsa->g) == -1 ||
819 buffer_get_bignum2_ret(&b, key->dsa->pub_key) == -1) {
820 error("key_from_blob: can't read dsa key");
826 DSA_print_fp(stderr, key->dsa, 8);
833 error("key_from_blob: cannot handle type %s", ktype);
836 rlen = buffer_len(&b);
837 if (key != NULL && rlen != 0)
838 error("key_from_blob: remaining bytes in key blob %d", rlen);
847 key_to_blob(const Key *key, u_char **blobp, u_int *lenp)
853 error("key_to_blob: key == NULL");
859 buffer_put_cstring(&b, key_ssh_name(key));
860 buffer_put_bignum2(&b, key->dsa->p);
861 buffer_put_bignum2(&b, key->dsa->q);
862 buffer_put_bignum2(&b, key->dsa->g);
863 buffer_put_bignum2(&b, key->dsa->pub_key);
866 buffer_put_cstring(&b, key_ssh_name(key));
867 buffer_put_bignum2(&b, key->rsa->e);
868 buffer_put_bignum2(&b, key->rsa->n);
871 error("key_to_blob: unsupported key type %d", key->type);
875 len = buffer_len(&b);
879 *blobp = xmalloc(len);
880 memcpy(*blobp, buffer_ptr(&b), len);
882 memset(buffer_ptr(&b), 0, len);
890 u_char **sigp, u_int *lenp,
891 const u_char *data, u_int datalen)
895 return ssh_dss_sign(key, sigp, lenp, data, datalen);
897 return ssh_rsa_sign(key, sigp, lenp, data, datalen);
899 error("key_sign: invalid key type %d", key->type);
905 * key_verify returns 1 for a correct signature, 0 for an incorrect signature
911 const u_char *signature, u_int signaturelen,
912 const u_char *data, u_int datalen)
914 if (signaturelen == 0)
919 return ssh_dss_verify(key, signature, signaturelen, data, datalen);
921 return ssh_rsa_verify(key, signature, signaturelen, data, datalen);
923 error("key_verify: invalid key type %d", key->type);
928 /* Converts a private to a public key */
930 key_demote(const Key *k)
934 pk = xcalloc(1, sizeof(*pk));
936 pk->flags = k->flags;
943 if ((pk->rsa = RSA_new()) == NULL)
944 fatal("key_demote: RSA_new failed");
945 if ((pk->rsa->e = BN_dup(k->rsa->e)) == NULL)
946 fatal("key_demote: BN_dup failed");
947 if ((pk->rsa->n = BN_dup(k->rsa->n)) == NULL)
948 fatal("key_demote: BN_dup failed");
951 if ((pk->dsa = DSA_new()) == NULL)
952 fatal("key_demote: DSA_new failed");
953 if ((pk->dsa->p = BN_dup(k->dsa->p)) == NULL)
954 fatal("key_demote: BN_dup failed");
955 if ((pk->dsa->q = BN_dup(k->dsa->q)) == NULL)
956 fatal("key_demote: BN_dup failed");
957 if ((pk->dsa->g = BN_dup(k->dsa->g)) == NULL)
958 fatal("key_demote: BN_dup failed");
959 if ((pk->dsa->pub_key = BN_dup(k->dsa->pub_key)) == NULL)
960 fatal("key_demote: BN_dup failed");
963 fatal("key_free: bad key type %d", k->type);