No empty .Rs/.Re
[netbsd-mini2440.git] / crypto / external / bsd / openssh / dist / key.c
blob4115b3bbb32281e64f8b0cac5b6f0ba6046ef5c5
1 /* $NetBSD$ */
2 /* $OpenBSD: key.c,v 1.80 2008/10/10 05:00:12 stevesk Exp $ */
3 /*
4 * read_bignum():
5 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
7 * As far as I am concerned, the code I have written for this software
8 * can be used freely for any purpose. Any derived versions of this
9 * software must be clearly marked as such, and if the derived work is
10 * incompatible with the protocol description in the RFC file, it must be
11 * called by a name other than "ssh" or "Secure Shell".
14 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
15 * Copyright (c) 2008 Alexander von Gernler. All rights reserved.
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions
19 * are met:
20 * 1. Redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer.
22 * 2. Redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution.
26 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
27 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
28 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
29 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
30 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
31 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
35 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 #include "includes.h"
39 __RCSID("$NetBSD: key.c,v 1.27 2009/02/16 20:53:54 christos Exp $");
40 #include <sys/param.h>
41 #include <sys/types.h>
43 #include <openssl/evp.h>
45 #include <stdio.h>
46 #include <string.h>
48 #include "xmalloc.h"
49 #include "key.h"
50 #include "rsa.h"
51 #include "uuencode.h"
52 #include "buffer.h"
53 #include "log.h"
55 Key *
56 key_new(int type)
58 Key *k;
59 RSA *rsa;
60 DSA *dsa;
61 k = xcalloc(1, sizeof(*k));
62 k->type = type;
63 k->dsa = NULL;
64 k->rsa = NULL;
65 switch (k->type) {
66 case KEY_RSA1:
67 case KEY_RSA:
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");
74 k->rsa = rsa;
75 break;
76 case KEY_DSA:
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");
87 k->dsa = dsa;
88 break;
89 case KEY_UNSPEC:
90 break;
91 default:
92 fatal("key_new: bad key type %d", k->type);
93 break;
95 return k;
98 Key *
99 key_new_private(int type)
101 Key *k = key_new(type);
102 switch (k->type) {
103 case KEY_RSA1:
104 case KEY_RSA:
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");
117 break;
118 case KEY_DSA:
119 if ((k->dsa->priv_key = BN_new()) == NULL)
120 fatal("key_new_private: BN_new failed");
121 break;
122 case KEY_UNSPEC:
123 break;
124 default:
125 break;
127 return k;
130 void
131 key_free(Key *k)
133 if (k == NULL)
134 fatal("key_free: key is NULL");
135 switch (k->type) {
136 case KEY_RSA1:
137 case KEY_RSA:
138 if (k->rsa != NULL)
139 RSA_free(k->rsa);
140 k->rsa = NULL;
141 break;
142 case KEY_DSA:
143 if (k->dsa != NULL)
144 DSA_free(k->dsa);
145 k->dsa = NULL;
146 break;
147 case KEY_UNSPEC:
148 break;
149 default:
150 fatal("key_free: bad key type %d", k->type);
151 break;
153 xfree(k);
157 key_equal(const Key *a, const Key *b)
159 if (a == NULL || b == NULL || a->type != b->type)
160 return 0;
161 switch (a->type) {
162 case KEY_RSA1:
163 case KEY_RSA:
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;
167 case KEY_DSA:
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;
173 default:
174 fatal("key_equal: bad key type %d", a->type);
176 /* NOTREACHED */
179 u_char*
180 key_fingerprint_raw(const Key *k, enum fp_type dgst_type,
181 u_int *dgst_raw_length)
183 const EVP_MD *md = NULL;
184 EVP_MD_CTX ctx;
185 u_char *blob = NULL;
186 u_char *retval = NULL;
187 u_int len = 0;
188 int nlen, elen;
190 *dgst_raw_length = 0;
192 switch (dgst_type) {
193 case SSH_FP_MD5:
194 md = EVP_md5();
195 break;
196 case SSH_FP_SHA1:
197 md = EVP_sha1();
198 break;
199 default:
200 fatal("key_fingerprint_raw: bad digest type %d",
201 dgst_type);
203 switch (k->type) {
204 case KEY_RSA1:
205 nlen = BN_num_bytes(k->rsa->n);
206 elen = BN_num_bytes(k->rsa->e);
207 len = nlen + elen;
208 blob = xmalloc(len);
209 BN_bn2bin(k->rsa->n, blob);
210 BN_bn2bin(k->rsa->e, blob + nlen);
211 break;
212 case KEY_DSA:
213 case KEY_RSA:
214 key_to_blob(k, &blob, &len);
215 break;
216 case KEY_UNSPEC:
217 return retval;
218 default:
219 fatal("key_fingerprint_raw: bad key type %d", k->type);
220 break;
222 if (blob != NULL) {
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);
228 xfree(blob);
229 } else {
230 fatal("key_fingerprint_raw: blob is null");
232 return retval;
235 static char *
236 key_fingerprint_hex(u_char *dgst_raw, u_int dgst_raw_len)
238 char *retval;
239 u_int i;
241 retval = xcalloc(1, dgst_raw_len * 3 + 1);
242 for (i = 0; i < dgst_raw_len; i++) {
243 char hex[4];
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';
250 return retval;
253 static char *
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;
260 char *retval;
262 rounds = (dgst_raw_len / 2) + 1;
263 retval = xcalloc((rounds * 6), sizeof(char));
264 retval[j++] = 'x';
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) +
269 seed) % 6;
270 idx1 = (((u_int)(dgst_raw[2 * i])) >> 2) & 15;
271 idx2 = ((((u_int)(dgst_raw[2 * i])) & 3) +
272 (seed / 6)) % 6;
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];
280 retval[j++] = '-';
281 retval[j++] = consonants[idx4];
282 seed = ((seed * 5) +
283 ((((u_int)(dgst_raw[2 * i])) * 7) +
284 ((u_int)(dgst_raw[(2 * i) + 1])))) % 36;
286 } else {
287 idx0 = seed % 6;
288 idx1 = 16;
289 idx2 = seed / 6;
290 retval[j++] = vowels[idx0];
291 retval[j++] = consonants[idx1];
292 retval[j++] = vowels[idx2];
295 retval[j++] = 'x';
296 retval[j++] = '\0';
297 return retval;
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.
330 #define FLDBASE 8
331 #define FLDSIZE_Y (FLDBASE + 1)
332 #define FLDSIZE_X (FLDBASE * 2 + 1)
333 static char *
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";
341 char *retval, *p;
342 u_char field[FLDSIZE_X][FLDSIZE_Y];
343 u_int i, b;
344 int x, 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));
351 x = FLDSIZE_X / 2;
352 y = FLDSIZE_Y / 2;
354 /* process raw key */
355 for (i = 0; i < dgst_raw_len; i++) {
356 int input;
357 /* each byte conveys four 2-bit move commands */
358 input = dgst_raw[i];
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 */
365 x = MAX(x, 0);
366 y = MAX(y, 0);
367 x = MIN(x, FLDSIZE_X - 1);
368 y = MIN(y, FLDSIZE_Y - 1);
370 /* augment the field */
371 if (field[x][y] < len - 2)
372 field[x][y]++;
373 input = input >> 2;
377 /* mark starting point and end point*/
378 field[FLDSIZE_X / 2][FLDSIZE_Y / 2] = len - 1;
379 field[x][y] = len;
381 /* fill in retval */
382 snprintf(retval, FLDSIZE_X, "+--[%4s %4u]", key_type(k), key_size(k));
383 p = strchr(retval, '\0');
385 /* output upper border */
386 for (i = p - retval - 1; i < FLDSIZE_X; i++)
387 *p++ = '-';
388 *p++ = '+';
389 *p++ = '\n';
391 /* output content */
392 for (y = 0; y < FLDSIZE_Y; y++) {
393 *p++ = '|';
394 for (x = 0; x < FLDSIZE_X; x++)
395 *p++ = augmentation_string[MIN(field[x][y], len)];
396 *p++ = '|';
397 *p++ = '\n';
400 /* output lower border */
401 *p++ = '+';
402 for (i = 0; i < FLDSIZE_X; i++)
403 *p++ = '-';
404 *p++ = '+';
406 return retval;
409 char *
410 key_fingerprint(const Key *k, enum fp_type dgst_type, enum fp_rep dgst_rep)
412 char *retval = NULL;
413 u_char *dgst_raw;
414 u_int dgst_raw_len;
416 dgst_raw = key_fingerprint_raw(k, dgst_type, &dgst_raw_len);
417 if (!dgst_raw)
418 fatal("key_fingerprint: null from key_fingerprint_raw()");
419 switch (dgst_rep) {
420 case SSH_FP_HEX:
421 retval = key_fingerprint_hex(dgst_raw, dgst_raw_len);
422 break;
423 case SSH_FP_BUBBLEBABBLE:
424 retval = key_fingerprint_bubblebabble(dgst_raw, dgst_raw_len);
425 break;
426 case SSH_FP_RANDOMART:
427 retval = key_fingerprint_randomart(dgst_raw, dgst_raw_len, k);
428 break;
429 default:
430 fatal("key_fingerprint: bad digest representation %d",
431 dgst_rep);
432 break;
434 memset(dgst_raw, 0, dgst_raw_len);
435 xfree(dgst_raw);
436 return retval;
440 * Reads a multiple-precision integer in decimal from the buffer, and advances
441 * the pointer. The integer must already be initialized. This function is
442 * permitted to modify the buffer. This leaves *cpp to point just beyond the
443 * last processed (and maybe modified) character. Note that this may modify
444 * the buffer containing the number.
446 static int
447 read_bignum(char **cpp, BIGNUM * value)
449 char *cp = *cpp;
450 int old;
452 /* Skip any leading whitespace. */
453 for (; *cp == ' ' || *cp == '\t'; cp++)
456 /* Check that it begins with a decimal digit. */
457 if (*cp < '0' || *cp > '9')
458 return 0;
460 /* Save starting position. */
461 *cpp = cp;
463 /* Move forward until all decimal digits skipped. */
464 for (; *cp >= '0' && *cp <= '9'; cp++)
467 /* Save the old terminating character, and replace it by \0. */
468 old = *cp;
469 *cp = 0;
471 /* Parse the number. */
472 if (BN_dec2bn(&value, *cpp) == 0)
473 return 0;
475 /* Restore old terminating character. */
476 *cp = old;
478 /* Move beyond the number and return success. */
479 *cpp = cp;
480 return 1;
483 static int
484 write_bignum(FILE *f, BIGNUM *num)
486 char *buf = BN_bn2dec(num);
487 if (buf == NULL) {
488 error("write_bignum: BN_bn2dec() failed");
489 return 0;
491 fprintf(f, " %s", buf);
492 OPENSSL_free(buf);
493 return 1;
496 /* returns 1 ok, -1 error */
498 key_read(Key *ret, char **cpp)
500 Key *k;
501 int success = -1;
502 char *cp, *space;
503 int len, n, type;
504 u_int bits;
505 u_char *blob;
507 cp = *cpp;
509 switch (ret->type) {
510 case KEY_RSA1:
511 /* Get number of bits. */
512 if (*cp < '0' || *cp > '9')
513 return -1; /* Bad bit count... */
514 for (bits = 0; *cp >= '0' && *cp <= '9'; cp++)
515 bits = 10 * bits + *cp - '0';
516 if (bits == 0)
517 return -1;
518 *cpp = cp;
519 /* Get public exponent, public modulus. */
520 if (!read_bignum(cpp, ret->rsa->e))
521 return -1;
522 if (!read_bignum(cpp, ret->rsa->n))
523 return -1;
524 success = 1;
525 break;
526 case KEY_UNSPEC:
527 case KEY_RSA:
528 case KEY_DSA:
529 space = strchr(cp, ' ');
530 if (space == NULL) {
531 debug3("key_read: missing whitespace");
532 return -1;
534 *space = '\0';
535 type = key_type_from_name(cp);
536 *space = ' ';
537 if (type == KEY_UNSPEC) {
538 debug3("key_read: missing keytype");
539 return -1;
541 cp = space+1;
542 if (*cp == '\0') {
543 debug3("key_read: short string");
544 return -1;
546 if (ret->type == KEY_UNSPEC) {
547 ret->type = type;
548 } else if (ret->type != type) {
549 /* is a key, but different type */
550 debug3("key_read: type mismatch");
551 return -1;
553 len = 2*strlen(cp);
554 blob = xmalloc(len);
555 n = uudecode(cp, blob, len);
556 if (n < 0) {
557 error("key_read: uudecode %s failed", cp);
558 xfree(blob);
559 return -1;
561 k = key_from_blob(blob, (u_int)n);
562 xfree(blob);
563 if (k == NULL) {
564 error("key_read: key_from_blob %s failed", cp);
565 return -1;
567 if (k->type != type) {
568 error("key_read: type mismatch: encoding error");
569 key_free(k);
570 return -1;
572 /*XXXX*/
573 if (ret->type == KEY_RSA) {
574 if (ret->rsa != NULL)
575 RSA_free(ret->rsa);
576 ret->rsa = k->rsa;
577 k->rsa = NULL;
578 success = 1;
579 #ifdef DEBUG_PK
580 RSA_print_fp(stderr, ret->rsa, 8);
581 #endif
582 } else {
583 if (ret->dsa != NULL)
584 DSA_free(ret->dsa);
585 ret->dsa = k->dsa;
586 k->dsa = NULL;
587 success = 1;
588 #ifdef DEBUG_PK
589 DSA_print_fp(stderr, ret->dsa, 8);
590 #endif
592 /*XXXX*/
593 key_free(k);
594 if (success != 1)
595 break;
596 /* advance cp: skip whitespace and data */
597 while (*cp == ' ' || *cp == '\t')
598 cp++;
599 while (*cp != '\0' && *cp != ' ' && *cp != '\t')
600 cp++;
601 *cpp = cp;
602 break;
603 default:
604 fatal("key_read: bad key type: %d", ret->type);
605 break;
607 return success;
611 key_write(const Key *key, FILE *f)
613 int n, success = 0;
614 u_int len, bits = 0;
615 u_char *blob;
616 char *uu;
618 if (key->type == KEY_RSA1 && key->rsa != NULL) {
619 /* size of modulus 'n' */
620 bits = BN_num_bits(key->rsa->n);
621 fprintf(f, "%u", bits);
622 if (write_bignum(f, key->rsa->e) &&
623 write_bignum(f, key->rsa->n)) {
624 success = 1;
625 } else {
626 error("key_write: failed for RSA key");
628 } else if ((key->type == KEY_DSA && key->dsa != NULL) ||
629 (key->type == KEY_RSA && key->rsa != NULL)) {
630 key_to_blob(key, &blob, &len);
631 uu = xmalloc(2*len);
632 n = uuencode(blob, len, uu, 2*len);
633 if (n > 0) {
634 fprintf(f, "%s %s", key_ssh_name(key), uu);
635 success = 1;
637 xfree(blob);
638 xfree(uu);
640 return success;
643 const char *
644 key_type(const Key *k)
646 switch (k->type) {
647 case KEY_RSA1:
648 return "RSA1";
649 case KEY_RSA:
650 return "RSA";
651 case KEY_DSA:
652 return "DSA";
654 return "unknown";
657 const char *
658 key_ssh_name(const Key *k)
660 switch (k->type) {
661 case KEY_RSA:
662 return "ssh-rsa";
663 case KEY_DSA:
664 return "ssh-dss";
666 return "ssh-unknown";
669 u_int
670 key_size(const Key *k)
672 switch (k->type) {
673 case KEY_RSA1:
674 case KEY_RSA:
675 return BN_num_bits(k->rsa->n);
676 case KEY_DSA:
677 return BN_num_bits(k->dsa->p);
679 return 0;
682 static RSA *
683 rsa_generate_private_key(u_int bits)
685 RSA *private;
687 private = RSA_generate_key(bits, 35, NULL, NULL);
688 if (private == NULL)
689 fatal("rsa_generate_private_key: key generation failed.");
690 return private;
693 static DSA*
694 dsa_generate_private_key(u_int bits)
696 DSA *private = DSA_generate_parameters(bits, NULL, 0, NULL, NULL, NULL, NULL);
698 if (private == NULL)
699 fatal("dsa_generate_private_key: DSA_generate_parameters failed");
700 if (!DSA_generate_key(private))
701 fatal("dsa_generate_private_key: DSA_generate_key failed.");
702 if (private == NULL)
703 fatal("dsa_generate_private_key: NULL.");
704 return private;
707 Key *
708 key_generate(int type, u_int bits)
710 Key *k = key_new(KEY_UNSPEC);
711 switch (type) {
712 case KEY_DSA:
713 k->dsa = dsa_generate_private_key(bits);
714 break;
715 case KEY_RSA:
716 case KEY_RSA1:
717 k->rsa = rsa_generate_private_key(bits);
718 break;
719 default:
720 fatal("key_generate: unknown type %d", type);
722 k->type = type;
723 return k;
726 Key *
727 key_from_private(const Key *k)
729 Key *n = NULL;
730 switch (k->type) {
731 case KEY_DSA:
732 n = key_new(k->type);
733 if ((BN_copy(n->dsa->p, k->dsa->p) == NULL) ||
734 (BN_copy(n->dsa->q, k->dsa->q) == NULL) ||
735 (BN_copy(n->dsa->g, k->dsa->g) == NULL) ||
736 (BN_copy(n->dsa->pub_key, k->dsa->pub_key) == NULL))
737 fatal("key_from_private: BN_copy failed");
738 break;
739 case KEY_RSA:
740 case KEY_RSA1:
741 n = key_new(k->type);
742 if ((BN_copy(n->rsa->n, k->rsa->n) == NULL) ||
743 (BN_copy(n->rsa->e, k->rsa->e) == NULL))
744 fatal("key_from_private: BN_copy failed");
745 break;
746 default:
747 fatal("key_from_private: unknown type %d", k->type);
748 break;
750 return n;
754 key_type_from_name(char *name)
756 if (strcmp(name, "rsa1") == 0) {
757 return KEY_RSA1;
758 } else if (strcmp(name, "rsa") == 0) {
759 return KEY_RSA;
760 } else if (strcmp(name, "dsa") == 0) {
761 return KEY_DSA;
762 } else if (strcmp(name, "ssh-rsa") == 0) {
763 return KEY_RSA;
764 } else if (strcmp(name, "ssh-dss") == 0) {
765 return KEY_DSA;
767 debug2("key_type_from_name: unknown key type '%s'", name);
768 return KEY_UNSPEC;
772 key_names_valid2(const char *names)
774 char *s, *cp, *p;
776 if (names == NULL || strcmp(names, "") == 0)
777 return 0;
778 s = cp = xstrdup(names);
779 for ((p = strsep(&cp, ",")); p && *p != '\0';
780 (p = strsep(&cp, ","))) {
781 switch (key_type_from_name(p)) {
782 case KEY_RSA1:
783 case KEY_UNSPEC:
784 xfree(s);
785 return 0;
788 debug3("key names ok: [%s]", names);
789 xfree(s);
790 return 1;
793 Key *
794 key_from_blob(const u_char *blob, u_int blen)
796 Buffer b;
797 int rlen, type;
798 char *ktype = NULL;
799 Key *key = NULL;
801 #ifdef DEBUG_PK
802 dump_base64(stderr, blob, blen);
803 #endif
804 buffer_init(&b);
805 buffer_append(&b, blob, blen);
806 if ((ktype = buffer_get_string_ret(&b, NULL)) == NULL) {
807 error("key_from_blob: can't read key type");
808 goto out;
811 type = key_type_from_name(ktype);
813 switch (type) {
814 case KEY_RSA:
815 key = key_new(type);
816 if (buffer_get_bignum2_ret(&b, key->rsa->e) == -1 ||
817 buffer_get_bignum2_ret(&b, key->rsa->n) == -1) {
818 error("key_from_blob: can't read rsa key");
819 key_free(key);
820 key = NULL;
821 goto out;
823 #ifdef DEBUG_PK
824 RSA_print_fp(stderr, key->rsa, 8);
825 #endif
826 break;
827 case KEY_DSA:
828 key = key_new(type);
829 if (buffer_get_bignum2_ret(&b, key->dsa->p) == -1 ||
830 buffer_get_bignum2_ret(&b, key->dsa->q) == -1 ||
831 buffer_get_bignum2_ret(&b, key->dsa->g) == -1 ||
832 buffer_get_bignum2_ret(&b, key->dsa->pub_key) == -1) {
833 error("key_from_blob: can't read dsa key");
834 key_free(key);
835 key = NULL;
836 goto out;
838 #ifdef DEBUG_PK
839 DSA_print_fp(stderr, key->dsa, 8);
840 #endif
841 break;
842 case KEY_UNSPEC:
843 key = key_new(type);
844 break;
845 default:
846 error("key_from_blob: cannot handle type %s", ktype);
847 goto out;
849 rlen = buffer_len(&b);
850 if (key != NULL && rlen != 0)
851 error("key_from_blob: remaining bytes in key blob %d", rlen);
852 out:
853 if (ktype != NULL)
854 xfree(ktype);
855 buffer_free(&b);
856 return key;
860 key_to_blob(const Key *key, u_char **blobp, u_int *lenp)
862 Buffer b;
863 int len;
865 if (key == NULL) {
866 error("key_to_blob: key == NULL");
867 return 0;
869 buffer_init(&b);
870 switch (key->type) {
871 case KEY_DSA:
872 buffer_put_cstring(&b, key_ssh_name(key));
873 buffer_put_bignum2(&b, key->dsa->p);
874 buffer_put_bignum2(&b, key->dsa->q);
875 buffer_put_bignum2(&b, key->dsa->g);
876 buffer_put_bignum2(&b, key->dsa->pub_key);
877 break;
878 case KEY_RSA:
879 buffer_put_cstring(&b, key_ssh_name(key));
880 buffer_put_bignum2(&b, key->rsa->e);
881 buffer_put_bignum2(&b, key->rsa->n);
882 break;
883 default:
884 error("key_to_blob: unsupported key type %d", key->type);
885 buffer_free(&b);
886 return 0;
888 len = buffer_len(&b);
889 if (lenp != NULL)
890 *lenp = len;
891 if (blobp != NULL) {
892 *blobp = xmalloc(len);
893 memcpy(*blobp, buffer_ptr(&b), len);
895 memset(buffer_ptr(&b), 0, len);
896 buffer_free(&b);
897 return len;
901 key_sign(
902 const Key *key,
903 u_char **sigp, u_int *lenp,
904 const u_char *data, u_int datalen)
906 switch (key->type) {
907 case KEY_DSA:
908 return ssh_dss_sign(key, sigp, lenp, data, datalen);
909 case KEY_RSA:
910 return ssh_rsa_sign(key, sigp, lenp, data, datalen);
911 default:
912 error("key_sign: invalid key type %d", key->type);
913 return -1;
918 * key_verify returns 1 for a correct signature, 0 for an incorrect signature
919 * and -1 on error.
922 key_verify(
923 const Key *key,
924 const u_char *signature, u_int signaturelen,
925 const u_char *data, u_int datalen)
927 if (signaturelen == 0)
928 return -1;
930 switch (key->type) {
931 case KEY_DSA:
932 return ssh_dss_verify(key, signature, signaturelen, data, datalen);
933 case KEY_RSA:
934 return ssh_rsa_verify(key, signature, signaturelen, data, datalen);
935 default:
936 error("key_verify: invalid key type %d", key->type);
937 return -1;
941 /* Converts a private to a public key */
942 Key *
943 key_demote(const Key *k)
945 Key *pk;
947 pk = xcalloc(1, sizeof(*pk));
948 pk->type = k->type;
949 pk->flags = k->flags;
950 pk->dsa = NULL;
951 pk->rsa = NULL;
953 switch (k->type) {
954 case KEY_RSA1:
955 case KEY_RSA:
956 if ((pk->rsa = RSA_new()) == NULL)
957 fatal("key_demote: RSA_new failed");
958 if ((pk->rsa->e = BN_dup(k->rsa->e)) == NULL)
959 fatal("key_demote: BN_dup failed");
960 if ((pk->rsa->n = BN_dup(k->rsa->n)) == NULL)
961 fatal("key_demote: BN_dup failed");
962 break;
963 case KEY_DSA:
964 if ((pk->dsa = DSA_new()) == NULL)
965 fatal("key_demote: DSA_new failed");
966 if ((pk->dsa->p = BN_dup(k->dsa->p)) == NULL)
967 fatal("key_demote: BN_dup failed");
968 if ((pk->dsa->q = BN_dup(k->dsa->q)) == NULL)
969 fatal("key_demote: BN_dup failed");
970 if ((pk->dsa->g = BN_dup(k->dsa->g)) == NULL)
971 fatal("key_demote: BN_dup failed");
972 if ((pk->dsa->pub_key = BN_dup(k->dsa->pub_key)) == NULL)
973 fatal("key_demote: BN_dup failed");
974 break;
975 default:
976 fatal("key_free: bad key type %d", k->type);
977 break;
980 return (pk);