1 /* $OpenBSD: key.c,v 1.64 2006/03/25 13:17:02 djm 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.
37 #include <openssl/evp.h>
53 k = xcalloc(1, sizeof(*k));
60 if ((rsa = RSA_new()) == NULL)
61 fatal("key_new: RSA_new failed");
62 if ((rsa->n = BN_new()) == NULL)
63 fatal("key_new: BN_new failed");
64 if ((rsa->e = BN_new()) == NULL)
65 fatal("key_new: BN_new failed");
69 if ((dsa = DSA_new()) == NULL)
70 fatal("key_new: DSA_new failed");
71 if ((dsa->p = BN_new()) == NULL)
72 fatal("key_new: BN_new failed");
73 if ((dsa->q = BN_new()) == NULL)
74 fatal("key_new: BN_new failed");
75 if ((dsa->g = BN_new()) == NULL)
76 fatal("key_new: BN_new failed");
77 if ((dsa->pub_key = BN_new()) == NULL)
78 fatal("key_new: BN_new failed");
84 fatal("key_new: bad key type %d", k->type);
91 key_new_private(int type)
93 Key *k = key_new(type);
97 if ((k->rsa->d = BN_new()) == NULL)
98 fatal("key_new_private: BN_new failed");
99 if ((k->rsa->iqmp = BN_new()) == NULL)
100 fatal("key_new_private: BN_new failed");
101 if ((k->rsa->q = BN_new()) == NULL)
102 fatal("key_new_private: BN_new failed");
103 if ((k->rsa->p = BN_new()) == NULL)
104 fatal("key_new_private: BN_new failed");
105 if ((k->rsa->dmq1 = BN_new()) == NULL)
106 fatal("key_new_private: BN_new failed");
107 if ((k->rsa->dmp1 = BN_new()) == NULL)
108 fatal("key_new_private: BN_new failed");
111 if ((k->dsa->priv_key = BN_new()) == NULL)
112 fatal("key_new_private: BN_new failed");
126 fatal("key_free: key is NULL");
142 fatal("key_free: bad key type %d", k->type);
149 key_equal(const Key *a, const Key *b)
151 if (a == NULL || b == NULL || a->type != b->type)
156 return a->rsa != NULL && b->rsa != NULL &&
157 BN_cmp(a->rsa->e, b->rsa->e) == 0 &&
158 BN_cmp(a->rsa->n, b->rsa->n) == 0;
160 return a->dsa != NULL && b->dsa != NULL &&
161 BN_cmp(a->dsa->p, b->dsa->p) == 0 &&
162 BN_cmp(a->dsa->q, b->dsa->q) == 0 &&
163 BN_cmp(a->dsa->g, b->dsa->g) == 0 &&
164 BN_cmp(a->dsa->pub_key, b->dsa->pub_key) == 0;
166 fatal("key_equal: bad key type %d", a->type);
173 key_fingerprint_raw(const Key *k, enum fp_type dgst_type,
174 u_int *dgst_raw_length)
176 const EVP_MD *md = NULL;
179 u_char *retval = NULL;
183 *dgst_raw_length = 0;
193 fatal("key_fingerprint_raw: bad digest type %d",
198 nlen = BN_num_bytes(k->rsa->n);
199 elen = BN_num_bytes(k->rsa->e);
202 BN_bn2bin(k->rsa->n, blob);
203 BN_bn2bin(k->rsa->e, blob + nlen);
207 key_to_blob(k, &blob, &len);
212 fatal("key_fingerprint_raw: bad key type %d", k->type);
216 retval = xmalloc(EVP_MAX_MD_SIZE);
217 EVP_DigestInit(&ctx, md);
218 EVP_DigestUpdate(&ctx, blob, len);
219 EVP_DigestFinal(&ctx, retval, dgst_raw_length);
220 memset(blob, 0, len);
223 fatal("key_fingerprint_raw: blob is null");
229 key_fingerprint_hex(u_char *dgst_raw, u_int dgst_raw_len)
234 retval = xcalloc(1, dgst_raw_len * 3 + 1);
235 for (i = 0; i < dgst_raw_len; i++) {
237 snprintf(hex, sizeof(hex), "%02x:", dgst_raw[i]);
238 strlcat(retval, hex, dgst_raw_len * 3 + 1);
241 /* Remove the trailing ':' character */
242 retval[(dgst_raw_len * 3) - 1] = '\0';
247 key_fingerprint_bubblebabble(u_char *dgst_raw, u_int dgst_raw_len)
249 char vowels[] = { 'a', 'e', 'i', 'o', 'u', 'y' };
250 char consonants[] = { 'b', 'c', 'd', 'f', 'g', 'h', 'k', 'l', 'm',
251 'n', 'p', 'r', 's', 't', 'v', 'z', 'x' };
252 u_int i, j = 0, rounds, seed = 1;
255 rounds = (dgst_raw_len / 2) + 1;
256 retval = xcalloc((rounds * 6), sizeof(char));
258 for (i = 0; i < rounds; i++) {
259 u_int idx0, idx1, idx2, idx3, idx4;
260 if ((i + 1 < rounds) || (dgst_raw_len % 2 != 0)) {
261 idx0 = (((((u_int)(dgst_raw[2 * i])) >> 6) & 3) +
263 idx1 = (((u_int)(dgst_raw[2 * i])) >> 2) & 15;
264 idx2 = ((((u_int)(dgst_raw[2 * i])) & 3) +
266 retval[j++] = vowels[idx0];
267 retval[j++] = consonants[idx1];
268 retval[j++] = vowels[idx2];
269 if ((i + 1) < rounds) {
270 idx3 = (((u_int)(dgst_raw[(2 * i) + 1])) >> 4) & 15;
271 idx4 = (((u_int)(dgst_raw[(2 * i) + 1]))) & 15;
272 retval[j++] = consonants[idx3];
274 retval[j++] = consonants[idx4];
276 ((((u_int)(dgst_raw[2 * i])) * 7) +
277 ((u_int)(dgst_raw[(2 * i) + 1])))) % 36;
283 retval[j++] = vowels[idx0];
284 retval[j++] = consonants[idx1];
285 retval[j++] = vowels[idx2];
294 key_fingerprint(const Key *k, enum fp_type dgst_type, enum fp_rep dgst_rep)
300 dgst_raw = key_fingerprint_raw(k, dgst_type, &dgst_raw_len);
302 fatal("key_fingerprint: null from key_fingerprint_raw()");
305 retval = key_fingerprint_hex(dgst_raw, dgst_raw_len);
307 case SSH_FP_BUBBLEBABBLE:
308 retval = key_fingerprint_bubblebabble(dgst_raw, dgst_raw_len);
311 fatal("key_fingerprint_ex: bad digest representation %d",
315 memset(dgst_raw, 0, dgst_raw_len);
321 * Reads a multiple-precision integer in decimal from the buffer, and advances
322 * the pointer. The integer must already be initialized. This function is
323 * permitted to modify the buffer. This leaves *cpp to point just beyond the
324 * last processed (and maybe modified) character. Note that this may modify
325 * the buffer containing the number.
328 read_bignum(char **cpp, BIGNUM * value)
333 /* Skip any leading whitespace. */
334 for (; *cp == ' ' || *cp == '\t'; cp++)
337 /* Check that it begins with a decimal digit. */
338 if (*cp < '0' || *cp > '9')
341 /* Save starting position. */
344 /* Move forward until all decimal digits skipped. */
345 for (; *cp >= '0' && *cp <= '9'; cp++)
348 /* Save the old terminating character, and replace it by \0. */
352 /* Parse the number. */
353 if (BN_dec2bn(&value, *cpp) == 0)
356 /* Restore old terminating character. */
359 /* Move beyond the number and return success. */
365 write_bignum(FILE *f, BIGNUM *num)
367 char *buf = BN_bn2dec(num);
369 error("write_bignum: BN_bn2dec() failed");
372 fprintf(f, " %s", buf);
377 /* returns 1 ok, -1 error */
379 key_read(Key *ret, char **cpp)
392 /* Get number of bits. */
393 if (*cp < '0' || *cp > '9')
394 return -1; /* Bad bit count... */
395 for (bits = 0; *cp >= '0' && *cp <= '9'; cp++)
396 bits = 10 * bits + *cp - '0';
400 /* Get public exponent, public modulus. */
401 if (!read_bignum(cpp, ret->rsa->e))
403 if (!read_bignum(cpp, ret->rsa->n))
410 space = strchr(cp, ' ');
412 debug3("key_read: missing whitespace");
416 type = key_type_from_name(cp);
418 if (type == KEY_UNSPEC) {
419 debug3("key_read: missing keytype");
424 debug3("key_read: short string");
427 if (ret->type == KEY_UNSPEC) {
429 } else if (ret->type != type) {
430 /* is a key, but different type */
431 debug3("key_read: type mismatch");
436 n = uudecode(cp, blob, len);
438 error("key_read: uudecode %s failed", cp);
442 k = key_from_blob(blob, (u_int)n);
445 error("key_read: key_from_blob %s failed", cp);
448 if (k->type != type) {
449 error("key_read: type mismatch: encoding error");
454 if (ret->type == KEY_RSA) {
455 if (ret->rsa != NULL)
461 RSA_print_fp(stderr, ret->rsa, 8);
464 if (ret->dsa != NULL)
470 DSA_print_fp(stderr, ret->dsa, 8);
477 /* advance cp: skip whitespace and data */
478 while (*cp == ' ' || *cp == '\t')
480 while (*cp != '\0' && *cp != ' ' && *cp != '\t')
485 fatal("key_read: bad key type: %d", ret->type);
492 key_write(const Key *key, FILE *f)
499 if (key->type == KEY_RSA1 && key->rsa != NULL) {
500 /* size of modulus 'n' */
501 bits = BN_num_bits(key->rsa->n);
502 fprintf(f, "%u", bits);
503 if (write_bignum(f, key->rsa->e) &&
504 write_bignum(f, key->rsa->n)) {
507 error("key_write: failed for RSA key");
509 } else if ((key->type == KEY_DSA && key->dsa != NULL) ||
510 (key->type == KEY_RSA && key->rsa != NULL)) {
511 key_to_blob(key, &blob, &len);
513 n = uuencode(blob, len, uu, 2*len);
515 fprintf(f, "%s %s", key_ssh_name(key), uu);
525 key_type(const Key *k)
539 key_ssh_name(const Key *k)
547 return "ssh-unknown";
551 key_size(const Key *k)
556 return BN_num_bits(k->rsa->n);
558 return BN_num_bits(k->dsa->p);
564 rsa_generate_private_key(u_int bits)
568 private = RSA_generate_key(bits, 35, NULL, NULL);
570 fatal("rsa_generate_private_key: key generation failed.");
575 dsa_generate_private_key(u_int bits)
577 DSA *private = DSA_generate_parameters(bits, NULL, 0, NULL, NULL, NULL, NULL);
580 fatal("dsa_generate_private_key: DSA_generate_parameters failed");
581 if (!DSA_generate_key(private))
582 fatal("dsa_generate_private_key: DSA_generate_key failed.");
584 fatal("dsa_generate_private_key: NULL.");
589 key_generate(int type, u_int bits)
591 Key *k = key_new(KEY_UNSPEC);
594 k->dsa = dsa_generate_private_key(bits);
598 k->rsa = rsa_generate_private_key(bits);
601 fatal("key_generate: unknown type %d", type);
608 key_from_private(const Key *k)
613 n = key_new(k->type);
614 BN_copy(n->dsa->p, k->dsa->p);
615 BN_copy(n->dsa->q, k->dsa->q);
616 BN_copy(n->dsa->g, k->dsa->g);
617 BN_copy(n->dsa->pub_key, k->dsa->pub_key);
621 n = key_new(k->type);
622 BN_copy(n->rsa->n, k->rsa->n);
623 BN_copy(n->rsa->e, k->rsa->e);
626 fatal("key_from_private: unknown type %d", k->type);
633 key_type_from_name(char *name)
635 if (strcmp(name, "rsa1") == 0) {
637 } else if (strcmp(name, "rsa") == 0) {
639 } else if (strcmp(name, "dsa") == 0) {
641 } else if (strcmp(name, "ssh-rsa") == 0) {
643 } else if (strcmp(name, "ssh-dss") == 0) {
646 debug2("key_type_from_name: unknown key type '%s'", name);
651 key_names_valid2(const char *names)
655 if (names == NULL || strcmp(names, "") == 0)
657 s = cp = xstrdup(names);
658 for ((p = strsep(&cp, ",")); p && *p != '\0';
659 (p = strsep(&cp, ","))) {
660 switch (key_type_from_name(p)) {
667 debug3("key names ok: [%s]", names);
673 key_from_blob(const u_char *blob, u_int blen)
681 dump_base64(stderr, blob, blen);
684 buffer_append(&b, blob, blen);
685 if ((ktype = buffer_get_string_ret(&b, NULL)) == NULL) {
686 error("key_from_blob: can't read key type");
690 type = key_type_from_name(ktype);
695 if (buffer_get_bignum2_ret(&b, key->rsa->e) == -1 ||
696 buffer_get_bignum2_ret(&b, key->rsa->n) == -1) {
697 error("key_from_blob: can't read rsa key");
703 RSA_print_fp(stderr, key->rsa, 8);
708 if (buffer_get_bignum2_ret(&b, key->dsa->p) == -1 ||
709 buffer_get_bignum2_ret(&b, key->dsa->q) == -1 ||
710 buffer_get_bignum2_ret(&b, key->dsa->g) == -1 ||
711 buffer_get_bignum2_ret(&b, key->dsa->pub_key) == -1) {
712 error("key_from_blob: can't read dsa key");
718 DSA_print_fp(stderr, key->dsa, 8);
725 error("key_from_blob: cannot handle type %s", ktype);
728 rlen = buffer_len(&b);
729 if (key != NULL && rlen != 0)
730 error("key_from_blob: remaining bytes in key blob %d", rlen);
739 key_to_blob(const Key *key, u_char **blobp, u_int *lenp)
745 error("key_to_blob: key == NULL");
751 buffer_put_cstring(&b, key_ssh_name(key));
752 buffer_put_bignum2(&b, key->dsa->p);
753 buffer_put_bignum2(&b, key->dsa->q);
754 buffer_put_bignum2(&b, key->dsa->g);
755 buffer_put_bignum2(&b, key->dsa->pub_key);
758 buffer_put_cstring(&b, key_ssh_name(key));
759 buffer_put_bignum2(&b, key->rsa->e);
760 buffer_put_bignum2(&b, key->rsa->n);
763 error("key_to_blob: unsupported key type %d", key->type);
767 len = buffer_len(&b);
771 *blobp = xmalloc(len);
772 memcpy(*blobp, buffer_ptr(&b), len);
774 memset(buffer_ptr(&b), 0, len);
782 u_char **sigp, u_int *lenp,
783 const u_char *data, u_int datalen)
787 return ssh_dss_sign(key, sigp, lenp, data, datalen);
789 return ssh_rsa_sign(key, sigp, lenp, data, datalen);
791 error("key_sign: invalid key type %d", key->type);
797 * key_verify returns 1 for a correct signature, 0 for an incorrect signature
803 const u_char *signature, u_int signaturelen,
804 const u_char *data, u_int datalen)
806 if (signaturelen == 0)
811 return ssh_dss_verify(key, signature, signaturelen, data, datalen);
813 return ssh_rsa_verify(key, signature, signaturelen, data, datalen);
815 error("key_verify: invalid key type %d", key->type);
820 /* Converts a private to a public key */
822 key_demote(const Key *k)
826 pk = xcalloc(1, sizeof(*pk));
828 pk->flags = k->flags;
835 if ((pk->rsa = RSA_new()) == NULL)
836 fatal("key_demote: RSA_new failed");
837 if ((pk->rsa->e = BN_dup(k->rsa->e)) == NULL)
838 fatal("key_demote: BN_dup failed");
839 if ((pk->rsa->n = BN_dup(k->rsa->n)) == NULL)
840 fatal("key_demote: BN_dup failed");
843 if ((pk->dsa = DSA_new()) == NULL)
844 fatal("key_demote: DSA_new failed");
845 if ((pk->dsa->p = BN_dup(k->dsa->p)) == NULL)
846 fatal("key_demote: BN_dup failed");
847 if ((pk->dsa->q = BN_dup(k->dsa->q)) == NULL)
848 fatal("key_demote: BN_dup failed");
849 if ((pk->dsa->g = BN_dup(k->dsa->g)) == NULL)
850 fatal("key_demote: BN_dup failed");
851 if ((pk->dsa->pub_key = BN_dup(k->dsa->pub_key)) == NULL)
852 fatal("key_demote: BN_dup failed");
855 fatal("key_free: bad key type %d", k->type);