1 /* $OpenBSD: key.c,v 1.76 2008/06/12 22:03:36 grunk 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.
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
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.
39 #include <sys/param.h>
40 #include <sys/types.h>
42 #include <openssl/evp.h>
43 #include <openbsd-compat/openssl-compat.h>
62 k = xcalloc(1, sizeof(*k));
69 if ((rsa = RSA_new()) == NULL)
70 fatal("key_new: RSA_new failed");
71 if ((rsa->n = BN_new()) == NULL)
72 fatal("key_new: BN_new failed");
73 if ((rsa->e = BN_new()) == NULL)
74 fatal("key_new: BN_new failed");
78 if ((dsa = DSA_new()) == NULL)
79 fatal("key_new: DSA_new failed");
80 if ((dsa->p = BN_new()) == NULL)
81 fatal("key_new: BN_new failed");
82 if ((dsa->q = BN_new()) == NULL)
83 fatal("key_new: BN_new failed");
84 if ((dsa->g = BN_new()) == NULL)
85 fatal("key_new: BN_new failed");
86 if ((dsa->pub_key = BN_new()) == NULL)
87 fatal("key_new: BN_new failed");
93 fatal("key_new: bad key type %d", k->type);
100 key_new_private(int type)
102 Key *k = key_new(type);
106 if ((k->rsa->d = BN_new()) == NULL)
107 fatal("key_new_private: BN_new failed");
108 if ((k->rsa->iqmp = BN_new()) == NULL)
109 fatal("key_new_private: BN_new failed");
110 if ((k->rsa->q = BN_new()) == NULL)
111 fatal("key_new_private: BN_new failed");
112 if ((k->rsa->p = BN_new()) == NULL)
113 fatal("key_new_private: BN_new failed");
114 if ((k->rsa->dmq1 = BN_new()) == NULL)
115 fatal("key_new_private: BN_new failed");
116 if ((k->rsa->dmp1 = BN_new()) == NULL)
117 fatal("key_new_private: BN_new failed");
120 if ((k->dsa->priv_key = BN_new()) == NULL)
121 fatal("key_new_private: BN_new failed");
135 fatal("key_free: key is NULL");
151 fatal("key_free: bad key type %d", k->type);
158 key_equal(const Key *a, const Key *b)
160 if (a == NULL || b == NULL || a->type != b->type)
165 return a->rsa != NULL && b->rsa != NULL &&
166 BN_cmp(a->rsa->e, b->rsa->e) == 0 &&
167 BN_cmp(a->rsa->n, b->rsa->n) == 0;
169 return a->dsa != NULL && b->dsa != NULL &&
170 BN_cmp(a->dsa->p, b->dsa->p) == 0 &&
171 BN_cmp(a->dsa->q, b->dsa->q) == 0 &&
172 BN_cmp(a->dsa->g, b->dsa->g) == 0 &&
173 BN_cmp(a->dsa->pub_key, b->dsa->pub_key) == 0;
175 fatal("key_equal: bad key type %d", a->type);
180 key_fingerprint_raw(const Key *k, enum fp_type dgst_type,
181 u_int *dgst_raw_length)
183 const EVP_MD *md = NULL;
186 u_char *retval = NULL;
190 *dgst_raw_length = 0;
200 fatal("key_fingerprint_raw: bad digest type %d",
205 nlen = BN_num_bytes(k->rsa->n);
206 elen = BN_num_bytes(k->rsa->e);
209 BN_bn2bin(k->rsa->n, blob);
210 BN_bn2bin(k->rsa->e, blob + nlen);
214 key_to_blob(k, &blob, &len);
219 fatal("key_fingerprint_raw: bad key type %d", k->type);
223 retval = xmalloc(EVP_MAX_MD_SIZE);
224 EVP_DigestInit(&ctx, md);
225 EVP_DigestUpdate(&ctx, blob, len);
226 EVP_DigestFinal(&ctx, retval, dgst_raw_length);
227 memset(blob, 0, len);
230 fatal("key_fingerprint_raw: blob is null");
236 key_fingerprint_hex(u_char *dgst_raw, u_int dgst_raw_len)
241 retval = xcalloc(1, dgst_raw_len * 3 + 1);
242 for (i = 0; i < dgst_raw_len; i++) {
244 snprintf(hex, sizeof(hex), "%02x:", dgst_raw[i]);
245 strlcat(retval, hex, dgst_raw_len * 3 + 1);
248 /* Remove the trailing ':' character */
249 retval[(dgst_raw_len * 3) - 1] = '\0';
254 key_fingerprint_bubblebabble(u_char *dgst_raw, u_int dgst_raw_len)
256 char vowels[] = { 'a', 'e', 'i', 'o', 'u', 'y' };
257 char consonants[] = { 'b', 'c', 'd', 'f', 'g', 'h', 'k', 'l', 'm',
258 'n', 'p', 'r', 's', 't', 'v', 'z', 'x' };
259 u_int i, j = 0, rounds, seed = 1;
262 rounds = (dgst_raw_len / 2) + 1;
263 retval = xcalloc((rounds * 6), sizeof(char));
265 for (i = 0; i < rounds; i++) {
266 u_int idx0, idx1, idx2, idx3, idx4;
267 if ((i + 1 < rounds) || (dgst_raw_len % 2 != 0)) {
268 idx0 = (((((u_int)(dgst_raw[2 * i])) >> 6) & 3) +
270 idx1 = (((u_int)(dgst_raw[2 * i])) >> 2) & 15;
271 idx2 = ((((u_int)(dgst_raw[2 * i])) & 3) +
273 retval[j++] = vowels[idx0];
274 retval[j++] = consonants[idx1];
275 retval[j++] = vowels[idx2];
276 if ((i + 1) < rounds) {
277 idx3 = (((u_int)(dgst_raw[(2 * i) + 1])) >> 4) & 15;
278 idx4 = (((u_int)(dgst_raw[(2 * i) + 1]))) & 15;
279 retval[j++] = consonants[idx3];
281 retval[j++] = consonants[idx4];
283 ((((u_int)(dgst_raw[2 * i])) * 7) +
284 ((u_int)(dgst_raw[(2 * i) + 1])))) % 36;
290 retval[j++] = vowels[idx0];
291 retval[j++] = consonants[idx1];
292 retval[j++] = vowels[idx2];
301 * Draw an ASCII-Art representing the fingerprint so human brain can
302 * profit from its built-in pattern recognition ability.
303 * This technique is called "random art" and can be found in some
304 * scientific publications like this original paper:
306 * "Hash Visualization: a New Technique to improve Real-World Security",
307 * Perrig A. and Song D., 1999, International Workshop on Cryptographic
308 * Techniques and E-Commerce (CrypTEC '99)
309 * sparrow.ece.cmu.edu/~adrian/projects/validation/validation.pdf
311 * The subject came up in a talk by Dan Kaminsky, too.
313 * If you see the picture is different, the key is different.
314 * If the picture looks the same, you still know nothing.
316 * The algorithm used here is a worm crawling over a discrete plane,
317 * leaving a trace (augmenting the field) everywhere it goes.
318 * Movement is taken from dgst_raw 2bit-wise. Bumping into walls
319 * makes the respective movement vector be ignored for this turn.
320 * Graphs are not unambiguous, because circles in graphs can be
321 * walked in either direction.
325 * Field sizes for the random art. Have to be odd, so the starting point
326 * can be in the exact middle of the picture, and FLDBASE should be >=8 .
327 * Else pictures would be too dense, and drawing the frame would
328 * fail, too, because the key type would not fit in anymore.
331 #define FLDSIZE_Y (FLDBASE + 1)
332 #define FLDSIZE_X (FLDBASE * 2 + 1)
334 key_fingerprint_randomart(u_char *dgst_raw, u_int dgst_raw_len, const Key *k)
337 * Chars to be used after each other every time the worm
338 * intersects with itself. Matter of taste.
340 char *augmentation_string = " .o+=*BOX@%&#/^SE";
342 u_char field[FLDSIZE_X][FLDSIZE_Y];
345 size_t len = strlen(augmentation_string) - 1;
347 retval = xcalloc(1, (FLDSIZE_X + 3) * (FLDSIZE_Y + 2));
349 /* initialize field */
350 memset(field, 0, FLDSIZE_X * FLDSIZE_Y * sizeof(char));
354 /* process raw key */
355 for (i = 0; i < dgst_raw_len; i++) {
357 /* each byte conveys four 2-bit move commands */
359 for (b = 0; b < 4; b++) {
360 /* evaluate 2 bit, rest is shifted later */
361 x += (input & 0x1) ? 1 : -1;
362 y += (input & 0x2) ? 1 : -1;
364 /* assure we are still in bounds */
367 x = MIN(x, FLDSIZE_X - 1);
368 y = MIN(y, FLDSIZE_Y - 1);
370 /* augment the field */
376 /* mark starting point and end point*/
377 field[FLDSIZE_X / 2][FLDSIZE_Y / 2] = len - 1;
381 snprintf(retval, 10, "+--[%4s]", key_type(k));
382 p = strchr(retval, '\0');
384 /* output upper border */
385 for (i = 0; i < FLDSIZE_X - 8; i++)
391 for (y = 0; y < FLDSIZE_Y; y++) {
393 for (x = 0; x < FLDSIZE_X; x++)
394 *p++ = augmentation_string[MIN(field[x][y], len)];
399 /* output lower border */
401 for (i = 0; i < FLDSIZE_X; i++)
409 key_fingerprint(const Key *k, enum fp_type dgst_type, enum fp_rep dgst_rep)
415 dgst_raw = key_fingerprint_raw(k, dgst_type, &dgst_raw_len);
417 fatal("key_fingerprint: null from key_fingerprint_raw()");
420 retval = key_fingerprint_hex(dgst_raw, dgst_raw_len);
422 case SSH_FP_BUBBLEBABBLE:
423 retval = key_fingerprint_bubblebabble(dgst_raw, dgst_raw_len);
425 case SSH_FP_RANDOMART:
426 retval = key_fingerprint_randomart(dgst_raw, dgst_raw_len, k);
429 fatal("key_fingerprint_ex: bad digest representation %d",
433 memset(dgst_raw, 0, dgst_raw_len);
439 * Reads a multiple-precision integer in decimal from the buffer, and advances
440 * the pointer. The integer must already be initialized. This function is
441 * permitted to modify the buffer. This leaves *cpp to point just beyond the
442 * last processed (and maybe modified) character. Note that this may modify
443 * the buffer containing the number.
446 read_bignum(char **cpp, BIGNUM * value)
451 /* Skip any leading whitespace. */
452 for (; *cp == ' ' || *cp == '\t'; cp++)
455 /* Check that it begins with a decimal digit. */
456 if (*cp < '0' || *cp > '9')
459 /* Save starting position. */
462 /* Move forward until all decimal digits skipped. */
463 for (; *cp >= '0' && *cp <= '9'; cp++)
466 /* Save the old terminating character, and replace it by \0. */
470 /* Parse the number. */
471 if (BN_dec2bn(&value, *cpp) == 0)
474 /* Restore old terminating character. */
477 /* Move beyond the number and return success. */
483 write_bignum(FILE *f, BIGNUM *num)
485 char *buf = BN_bn2dec(num);
487 error("write_bignum: BN_bn2dec() failed");
490 fprintf(f, " %s", buf);
495 /* returns 1 ok, -1 error */
497 key_read(Key *ret, char **cpp)
510 /* Get number of bits. */
511 if (*cp < '0' || *cp > '9')
512 return -1; /* Bad bit count... */
513 for (bits = 0; *cp >= '0' && *cp <= '9'; cp++)
514 bits = 10 * bits + *cp - '0';
518 /* Get public exponent, public modulus. */
519 if (!read_bignum(cpp, ret->rsa->e))
521 if (!read_bignum(cpp, ret->rsa->n))
528 space = strchr(cp, ' ');
530 debug3("key_read: missing whitespace");
534 type = key_type_from_name(cp);
536 if (type == KEY_UNSPEC) {
537 debug3("key_read: missing keytype");
542 debug3("key_read: short string");
545 if (ret->type == KEY_UNSPEC) {
547 } else if (ret->type != type) {
548 /* is a key, but different type */
549 debug3("key_read: type mismatch");
554 n = uudecode(cp, blob, len);
556 error("key_read: uudecode %s failed", cp);
560 k = key_from_blob(blob, (u_int)n);
563 error("key_read: key_from_blob %s failed", cp);
566 if (k->type != type) {
567 error("key_read: type mismatch: encoding error");
572 if (ret->type == KEY_RSA) {
573 if (ret->rsa != NULL)
579 RSA_print_fp(stderr, ret->rsa, 8);
582 if (ret->dsa != NULL)
588 DSA_print_fp(stderr, ret->dsa, 8);
595 /* advance cp: skip whitespace and data */
596 while (*cp == ' ' || *cp == '\t')
598 while (*cp != '\0' && *cp != ' ' && *cp != '\t')
603 fatal("key_read: bad key type: %d", ret->type);
610 key_write(const Key *key, FILE *f)
617 if (key->type == KEY_RSA1 && key->rsa != NULL) {
618 /* size of modulus 'n' */
619 bits = BN_num_bits(key->rsa->n);
620 fprintf(f, "%u", bits);
621 if (write_bignum(f, key->rsa->e) &&
622 write_bignum(f, key->rsa->n)) {
625 error("key_write: failed for RSA key");
627 } else if ((key->type == KEY_DSA && key->dsa != NULL) ||
628 (key->type == KEY_RSA && key->rsa != NULL)) {
629 key_to_blob(key, &blob, &len);
631 n = uuencode(blob, len, uu, 2*len);
633 fprintf(f, "%s %s", key_ssh_name(key), uu);
643 key_type(const Key *k)
657 key_ssh_name(const Key *k)
665 return "ssh-unknown";
669 key_size(const Key *k)
674 return BN_num_bits(k->rsa->n);
676 return BN_num_bits(k->dsa->p);
682 rsa_generate_private_key(u_int bits)
686 private = RSA_generate_key(bits, 35, NULL, NULL);
688 fatal("rsa_generate_private_key: key generation failed.");
693 dsa_generate_private_key(u_int bits)
695 DSA *private = DSA_generate_parameters(bits, NULL, 0, NULL, NULL, NULL, NULL);
698 fatal("dsa_generate_private_key: DSA_generate_parameters failed");
699 if (!DSA_generate_key(private))
700 fatal("dsa_generate_private_key: DSA_generate_key failed.");
702 fatal("dsa_generate_private_key: NULL.");
707 key_generate(int type, u_int bits)
709 Key *k = key_new(KEY_UNSPEC);
712 k->dsa = dsa_generate_private_key(bits);
716 k->rsa = rsa_generate_private_key(bits);
719 fatal("key_generate: unknown type %d", type);
726 key_from_private(const Key *k)
731 n = key_new(k->type);
732 if ((BN_copy(n->dsa->p, k->dsa->p) == NULL) ||
733 (BN_copy(n->dsa->q, k->dsa->q) == NULL) ||
734 (BN_copy(n->dsa->g, k->dsa->g) == NULL) ||
735 (BN_copy(n->dsa->pub_key, k->dsa->pub_key) == NULL))
736 fatal("key_from_private: BN_copy failed");
740 n = key_new(k->type);
741 if ((BN_copy(n->rsa->n, k->rsa->n) == NULL) ||
742 (BN_copy(n->rsa->e, k->rsa->e) == NULL))
743 fatal("key_from_private: BN_copy failed");
746 fatal("key_from_private: unknown type %d", k->type);
753 key_type_from_name(char *name)
755 if (strcmp(name, "rsa1") == 0) {
757 } else if (strcmp(name, "rsa") == 0) {
759 } else if (strcmp(name, "dsa") == 0) {
761 } else if (strcmp(name, "ssh-rsa") == 0) {
763 } else if (strcmp(name, "ssh-dss") == 0) {
766 debug2("key_type_from_name: unknown key type '%s'", name);
771 key_names_valid2(const char *names)
775 if (names == NULL || strcmp(names, "") == 0)
777 s = cp = xstrdup(names);
778 for ((p = strsep(&cp, ",")); p && *p != '\0';
779 (p = strsep(&cp, ","))) {
780 switch (key_type_from_name(p)) {
787 debug3("key names ok: [%s]", names);
793 key_from_blob(const u_char *blob, u_int blen)
801 dump_base64(stderr, blob, blen);
804 buffer_append(&b, blob, blen);
805 if ((ktype = buffer_get_string_ret(&b, NULL)) == NULL) {
806 error("key_from_blob: can't read key type");
810 type = key_type_from_name(ktype);
815 if (buffer_get_bignum2_ret(&b, key->rsa->e) == -1 ||
816 buffer_get_bignum2_ret(&b, key->rsa->n) == -1) {
817 error("key_from_blob: can't read rsa key");
823 RSA_print_fp(stderr, key->rsa, 8);
828 if (buffer_get_bignum2_ret(&b, key->dsa->p) == -1 ||
829 buffer_get_bignum2_ret(&b, key->dsa->q) == -1 ||
830 buffer_get_bignum2_ret(&b, key->dsa->g) == -1 ||
831 buffer_get_bignum2_ret(&b, key->dsa->pub_key) == -1) {
832 error("key_from_blob: can't read dsa key");
838 DSA_print_fp(stderr, key->dsa, 8);
845 error("key_from_blob: cannot handle type %s", ktype);
848 rlen = buffer_len(&b);
849 if (key != NULL && rlen != 0)
850 error("key_from_blob: remaining bytes in key blob %d", rlen);
859 key_to_blob(const Key *key, u_char **blobp, u_int *lenp)
865 error("key_to_blob: key == NULL");
871 buffer_put_cstring(&b, key_ssh_name(key));
872 buffer_put_bignum2(&b, key->dsa->p);
873 buffer_put_bignum2(&b, key->dsa->q);
874 buffer_put_bignum2(&b, key->dsa->g);
875 buffer_put_bignum2(&b, key->dsa->pub_key);
878 buffer_put_cstring(&b, key_ssh_name(key));
879 buffer_put_bignum2(&b, key->rsa->e);
880 buffer_put_bignum2(&b, key->rsa->n);
883 error("key_to_blob: unsupported key type %d", key->type);
887 len = buffer_len(&b);
891 *blobp = xmalloc(len);
892 memcpy(*blobp, buffer_ptr(&b), len);
894 memset(buffer_ptr(&b), 0, len);
902 u_char **sigp, u_int *lenp,
903 const u_char *data, u_int datalen)
907 return ssh_dss_sign(key, sigp, lenp, data, datalen);
909 return ssh_rsa_sign(key, sigp, lenp, data, datalen);
911 error("key_sign: invalid key type %d", key->type);
917 * key_verify returns 1 for a correct signature, 0 for an incorrect signature
923 const u_char *signature, u_int signaturelen,
924 const u_char *data, u_int datalen)
926 if (signaturelen == 0)
931 return ssh_dss_verify(key, signature, signaturelen, data, datalen);
933 return ssh_rsa_verify(key, signature, signaturelen, data, datalen);
935 error("key_verify: invalid key type %d", key->type);
940 /* Converts a private to a public key */
942 key_demote(const Key *k)
946 pk = xcalloc(1, sizeof(*pk));
948 pk->flags = k->flags;
955 if ((pk->rsa = RSA_new()) == NULL)
956 fatal("key_demote: RSA_new failed");
957 if ((pk->rsa->e = BN_dup(k->rsa->e)) == NULL)
958 fatal("key_demote: BN_dup failed");
959 if ((pk->rsa->n = BN_dup(k->rsa->n)) == NULL)
960 fatal("key_demote: BN_dup failed");
963 if ((pk->dsa = DSA_new()) == NULL)
964 fatal("key_demote: DSA_new failed");
965 if ((pk->dsa->p = BN_dup(k->dsa->p)) == NULL)
966 fatal("key_demote: BN_dup failed");
967 if ((pk->dsa->q = BN_dup(k->dsa->q)) == NULL)
968 fatal("key_demote: BN_dup failed");
969 if ((pk->dsa->g = BN_dup(k->dsa->g)) == NULL)
970 fatal("key_demote: BN_dup failed");
971 if ((pk->dsa->pub_key = BN_dup(k->dsa->pub_key)) == NULL)
972 fatal("key_demote: BN_dup failed");
975 fatal("key_free: bad key type %d", k->type);