xref: /titanic_44/usr/src/cmd/ssh/libssh/common/key.c (revision ee5416c9d7e449233197d5d20bc6b81e4ff091b2)
1 /*
2  * read_bignum():
3  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
4  *
5  * As far as I am concerned, the code I have written for this software
6  * can be used freely for any purpose.  Any derived versions of this
7  * software must be clearly marked as such, and if the derived work is
8  * incompatible with the protocol description in the RFC file, it must be
9  * called by a name other than "ssh" or "Secure Shell".
10  *
11  *
12  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above copyright
20  *    notice, this list of conditions and the following disclaimer in the
21  *    documentation and/or other materials provided with the distribution.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
24  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
26  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
27  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
28  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
32  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33  */
34 #include "includes.h"
35 RCSID("$OpenBSD: key.c,v 1.49 2002/09/09 14:54:14 markus Exp $");
36 
37 #pragma ident	"%Z%%M%	%I%	%E% SMI"
38 
39 #include <openssl/evp.h>
40 
41 #include "xmalloc.h"
42 #include "key.h"
43 #include "rsa.h"
44 #include "ssh-dss.h"
45 #include "ssh-rsa.h"
46 #include "uuencode.h"
47 #include "buffer.h"
48 #include "bufaux.h"
49 #include "log.h"
50 
51 Key *
52 key_new(int type)
53 {
54 	Key *k;
55 	RSA *rsa;
56 	DSA *dsa;
57 	k = xmalloc(sizeof(*k));
58 	k->type = type;
59 	k->flags = 0;
60 	k->dsa = NULL;
61 	k->rsa = NULL;
62 	switch (k->type) {
63 	case KEY_RSA1:
64 	case KEY_RSA:
65 		if ((rsa = RSA_new()) == NULL)
66 			fatal("key_new: RSA_new failed");
67 		if ((rsa->n = BN_new()) == NULL)
68 			fatal("key_new: BN_new failed");
69 		if ((rsa->e = BN_new()) == NULL)
70 			fatal("key_new: BN_new failed");
71 		k->rsa = rsa;
72 		break;
73 	case KEY_DSA:
74 		if ((dsa = DSA_new()) == NULL)
75 			fatal("key_new: DSA_new failed");
76 		if ((dsa->p = BN_new()) == NULL)
77 			fatal("key_new: BN_new failed");
78 		if ((dsa->q = BN_new()) == NULL)
79 			fatal("key_new: BN_new failed");
80 		if ((dsa->g = BN_new()) == NULL)
81 			fatal("key_new: BN_new failed");
82 		if ((dsa->pub_key = BN_new()) == NULL)
83 			fatal("key_new: BN_new failed");
84 		k->dsa = dsa;
85 		break;
86 	case KEY_UNSPEC:
87 		break;
88 	default:
89 		fatal("key_new: bad key type %d", k->type);
90 		break;
91 	}
92 	return k;
93 }
94 
95 Key *
96 key_new_private(int type)
97 {
98 	Key *k = key_new(type);
99 	switch (k->type) {
100 	case KEY_RSA1:
101 	case KEY_RSA:
102 		if ((k->rsa->d = BN_new()) == NULL)
103 			fatal("key_new_private: BN_new failed");
104 		if ((k->rsa->iqmp = BN_new()) == NULL)
105 			fatal("key_new_private: BN_new failed");
106 		if ((k->rsa->q = BN_new()) == NULL)
107 			fatal("key_new_private: BN_new failed");
108 		if ((k->rsa->p = BN_new()) == NULL)
109 			fatal("key_new_private: BN_new failed");
110 		if ((k->rsa->dmq1 = BN_new()) == NULL)
111 			fatal("key_new_private: BN_new failed");
112 		if ((k->rsa->dmp1 = BN_new()) == NULL)
113 			fatal("key_new_private: BN_new failed");
114 		break;
115 	case KEY_DSA:
116 		if ((k->dsa->priv_key = BN_new()) == NULL)
117 			fatal("key_new_private: BN_new failed");
118 		break;
119 	case KEY_UNSPEC:
120 		break;
121 	default:
122 		break;
123 	}
124 	return k;
125 }
126 
127 void
128 key_free(Key *k)
129 {
130 	switch (k->type) {
131 	case KEY_RSA1:
132 	case KEY_RSA:
133 		if (k->rsa != NULL)
134 			RSA_free(k->rsa);
135 		k->rsa = NULL;
136 		break;
137 	case KEY_DSA:
138 		if (k->dsa != NULL)
139 			DSA_free(k->dsa);
140 		k->dsa = NULL;
141 		break;
142 	case KEY_UNSPEC:
143 		break;
144 	default:
145 		fatal("key_free: bad key type %d", k->type);
146 		break;
147 	}
148 	xfree(k);
149 }
150 int
151 key_equal(Key *a, Key *b)
152 {
153 	if (a == NULL || b == NULL || a->type != b->type)
154 		return 0;
155 	switch (a->type) {
156 	case KEY_RSA1:
157 	case KEY_RSA:
158 		return a->rsa != NULL && b->rsa != NULL &&
159 		    BN_cmp(a->rsa->e, b->rsa->e) == 0 &&
160 		    BN_cmp(a->rsa->n, b->rsa->n) == 0;
161 		break;
162 	case KEY_DSA:
163 		return a->dsa != NULL && b->dsa != NULL &&
164 		    BN_cmp(a->dsa->p, b->dsa->p) == 0 &&
165 		    BN_cmp(a->dsa->q, b->dsa->q) == 0 &&
166 		    BN_cmp(a->dsa->g, b->dsa->g) == 0 &&
167 		    BN_cmp(a->dsa->pub_key, b->dsa->pub_key) == 0;
168 		break;
169 	default:
170 		fatal("key_equal: bad key type %d", a->type);
171 		break;
172 	}
173 	return 0;
174 }
175 
176 static u_char *
177 key_fingerprint_raw(Key *k, enum fp_type dgst_type, u_int *dgst_raw_length)
178 {
179 	const EVP_MD *md = NULL;
180 	EVP_MD_CTX ctx;
181 	u_char *blob = NULL;
182 	u_char *retval = NULL;
183 	u_int len = 0;
184 	int nlen, elen;
185 
186 	*dgst_raw_length = 0;
187 
188 	switch (dgst_type) {
189 	case SSH_FP_MD5:
190 		md = EVP_md5();
191 		break;
192 	case SSH_FP_SHA1:
193 		md = EVP_sha1();
194 		break;
195 	default:
196 		fatal("key_fingerprint_raw: bad digest type %d",
197 		    dgst_type);
198 	}
199 	switch (k->type) {
200 	case KEY_RSA1:
201 		nlen = BN_num_bytes(k->rsa->n);
202 		elen = BN_num_bytes(k->rsa->e);
203 		len = nlen + elen;
204 		blob = xmalloc(len);
205 		BN_bn2bin(k->rsa->n, blob);
206 		BN_bn2bin(k->rsa->e, blob + nlen);
207 		break;
208 	case KEY_DSA:
209 	case KEY_RSA:
210 		key_to_blob(k, &blob, &len);
211 		break;
212 	case KEY_UNSPEC:
213 		return retval;
214 		break;
215 	default:
216 		fatal("key_fingerprint_raw: bad key type %d", k->type);
217 		break;
218 	}
219 	if (blob != NULL) {
220 		retval = xmalloc(EVP_MAX_MD_SIZE);
221 		EVP_DigestInit(&ctx, md);
222 		EVP_DigestUpdate(&ctx, blob, len);
223 		EVP_DigestFinal(&ctx, retval, dgst_raw_length);
224 		memset(blob, 0, len);
225 		xfree(blob);
226 	} else {
227 		fatal("key_fingerprint_raw: blob is null");
228 	}
229 	return retval;
230 }
231 
232 static char *
233 key_fingerprint_hex(u_char *dgst_raw, u_int dgst_raw_len)
234 {
235 	char *retval;
236 	int i;
237 
238 	retval = xmalloc(dgst_raw_len * 3 + 1);
239 	retval[0] = '\0';
240 	for (i = 0; i < dgst_raw_len; i++) {
241 		char hex[4];
242 		snprintf(hex, sizeof(hex), "%02x:", dgst_raw[i]);
243 		strlcat(retval, hex, dgst_raw_len * 3);
244 	}
245 	retval[(dgst_raw_len * 3) - 1] = '\0';
246 	return retval;
247 }
248 
249 static char *
250 key_fingerprint_bubblebabble(u_char *dgst_raw, u_int dgst_raw_len)
251 {
252 	char vowels[] = { 'a', 'e', 'i', 'o', 'u', 'y' };
253 	char consonants[] = { 'b', 'c', 'd', 'f', 'g', 'h', 'k', 'l', 'm',
254 	    'n', 'p', 'r', 's', 't', 'v', 'z', 'x' };
255 	u_int i, j = 0, rounds, seed = 1;
256 	char *retval;
257 
258 	rounds = (dgst_raw_len / 2) + 1;
259 	retval = xmalloc(sizeof(char) * (rounds*6));
260 	retval[j++] = 'x';
261 	for (i = 0; i < rounds; i++) {
262 		u_int idx0, idx1, idx2, idx3, idx4;
263 		if ((i + 1 < rounds) || (dgst_raw_len % 2 != 0)) {
264 			idx0 = (((((u_int)(dgst_raw[2 * i])) >> 6) & 3) +
265 			    seed) % 6;
266 			idx1 = (((u_int)(dgst_raw[2 * i])) >> 2) & 15;
267 			idx2 = ((((u_int)(dgst_raw[2 * i])) & 3) +
268 			    (seed / 6)) % 6;
269 			retval[j++] = vowels[idx0];
270 			retval[j++] = consonants[idx1];
271 			retval[j++] = vowels[idx2];
272 			if ((i + 1) < rounds) {
273 				idx3 = (((u_int)(dgst_raw[(2 * i) + 1])) >> 4) & 15;
274 				idx4 = (((u_int)(dgst_raw[(2 * i) + 1]))) & 15;
275 				retval[j++] = consonants[idx3];
276 				retval[j++] = '-';
277 				retval[j++] = consonants[idx4];
278 				seed = ((seed * 5) +
279 				    ((((u_int)(dgst_raw[2 * i])) * 7) +
280 				    ((u_int)(dgst_raw[(2 * i) + 1])))) % 36;
281 			}
282 		} else {
283 			idx0 = seed % 6;
284 			idx1 = 16;
285 			idx2 = seed / 6;
286 			retval[j++] = vowels[idx0];
287 			retval[j++] = consonants[idx1];
288 			retval[j++] = vowels[idx2];
289 		}
290 	}
291 	retval[j++] = 'x';
292 	retval[j++] = '\0';
293 	return retval;
294 }
295 
296 char *
297 key_fingerprint(Key *k, enum fp_type dgst_type, enum fp_rep dgst_rep)
298 {
299 	char *retval = NULL;
300 	u_char *dgst_raw;
301 	u_int dgst_raw_len;
302 
303 	dgst_raw = key_fingerprint_raw(k, dgst_type, &dgst_raw_len);
304 	if (!dgst_raw)
305 		fatal("key_fingerprint: null from key_fingerprint_raw()");
306 	switch (dgst_rep) {
307 	case SSH_FP_HEX:
308 		retval = key_fingerprint_hex(dgst_raw, dgst_raw_len);
309 		break;
310 	case SSH_FP_BUBBLEBABBLE:
311 		retval = key_fingerprint_bubblebabble(dgst_raw, dgst_raw_len);
312 		break;
313 	default:
314 		fatal("key_fingerprint_ex: bad digest representation %d",
315 		    dgst_rep);
316 		break;
317 	}
318 	memset(dgst_raw, 0, dgst_raw_len);
319 	xfree(dgst_raw);
320 	return retval;
321 }
322 
323 /*
324  * Reads a multiple-precision integer in decimal from the buffer, and advances
325  * the pointer.  The integer must already be initialized.  This function is
326  * permitted to modify the buffer.  This leaves *cpp to point just beyond the
327  * last processed (and maybe modified) character.  Note that this may modify
328  * the buffer containing the number.
329  */
330 static int
331 read_bignum(char **cpp, BIGNUM * value)
332 {
333 	char *cp = *cpp;
334 	int old;
335 
336 	/* Skip any leading whitespace. */
337 	for (; *cp == ' ' || *cp == '\t'; cp++)
338 		;
339 
340 	/* Check that it begins with a decimal digit. */
341 	if (*cp < '0' || *cp > '9')
342 		return 0;
343 
344 	/* Save starting position. */
345 	*cpp = cp;
346 
347 	/* Move forward until all decimal digits skipped. */
348 	for (; *cp >= '0' && *cp <= '9'; cp++)
349 		;
350 
351 	/* Save the old terminating character, and replace it by \0. */
352 	old = *cp;
353 	*cp = 0;
354 
355 	/* Parse the number. */
356 	if (BN_dec2bn(&value, *cpp) == 0)
357 		return 0;
358 
359 	/* Restore old terminating character. */
360 	*cp = old;
361 
362 	/* Move beyond the number and return success. */
363 	*cpp = cp;
364 	return 1;
365 }
366 
367 static int
368 write_bignum(FILE *f, BIGNUM *num)
369 {
370 	char *buf = BN_bn2dec(num);
371 	if (buf == NULL) {
372 		error("write_bignum: BN_bn2dec() failed");
373 		return 0;
374 	}
375 	fprintf(f, " %s", buf);
376 	OPENSSL_free(buf);
377 	return 1;
378 }
379 
380 /* returns 1 ok, -1 error */
381 int
382 key_read(Key *ret, char **cpp)
383 {
384 	Key *k;
385 	int success = -1;
386 	char *cp, *space;
387 	int len, n, type;
388 	u_int bits;
389 	u_char *blob;
390 
391 	cp = *cpp;
392 
393 	switch (ret->type) {
394 	case KEY_RSA1:
395 		/* Get number of bits. */
396 		if (*cp < '0' || *cp > '9')
397 			return -1;	/* Bad bit count... */
398 		for (bits = 0; *cp >= '0' && *cp <= '9'; cp++)
399 			bits = 10 * bits + *cp - '0';
400 		if (bits == 0)
401 			return -1;
402 		*cpp = cp;
403 		/* Get public exponent, public modulus. */
404 		if (!read_bignum(cpp, ret->rsa->e))
405 			return -1;
406 		if (!read_bignum(cpp, ret->rsa->n))
407 			return -1;
408 		success = 1;
409 		break;
410 	case KEY_UNSPEC:
411 	case KEY_RSA:
412 	case KEY_DSA:
413 		space = strchr(cp, ' ');
414 		if (space == NULL) {
415 			debug3("key_read: no space");
416 			return -1;
417 		}
418 		*space = '\0';
419 		type = key_type_from_name(cp);
420 		*space = ' ';
421 		if (type == KEY_UNSPEC) {
422 			debug3("key_read: no key found");
423 			return -1;
424 		}
425 		cp = space+1;
426 		if (*cp == '\0') {
427 			debug3("key_read: short string");
428 			return -1;
429 		}
430 		if (ret->type == KEY_UNSPEC) {
431 			ret->type = type;
432 		} else if (ret->type != type) {
433 			/* is a key, but different type */
434 			debug3("key_read: type mismatch");
435 			return -1;
436 		}
437 		len = 2*strlen(cp);
438 		blob = xmalloc(len);
439 		n = uudecode(cp, blob, len);
440 		if (n < 0) {
441 			error("key_read: uudecode %s failed", cp);
442 			xfree(blob);
443 			return -1;
444 		}
445 		k = key_from_blob(blob, n);
446 		xfree(blob);
447 		if (k == NULL) {
448 			error("key_read: key_from_blob %s failed", cp);
449 			return -1;
450 		}
451 		if (k->type != type) {
452 			error("key_read: type mismatch: encoding error");
453 			key_free(k);
454 			return -1;
455 		}
456 /*XXXX*/
457 		if (ret->type == KEY_RSA) {
458 			if (ret->rsa != NULL)
459 				RSA_free(ret->rsa);
460 			ret->rsa = k->rsa;
461 			k->rsa = NULL;
462 			success = 1;
463 #ifdef DEBUG_PK
464 			RSA_print_fp(stderr, ret->rsa, 8);
465 #endif
466 		} else {
467 			if (ret->dsa != NULL)
468 				DSA_free(ret->dsa);
469 			ret->dsa = k->dsa;
470 			k->dsa = NULL;
471 			success = 1;
472 #ifdef DEBUG_PK
473 			DSA_print_fp(stderr, ret->dsa, 8);
474 #endif
475 		}
476 /*XXXX*/
477 		key_free(k);
478 		if (success != 1)
479 			break;
480 		/* advance cp: skip whitespace and data */
481 		while (*cp == ' ' || *cp == '\t')
482 			cp++;
483 		while (*cp != '\0' && *cp != ' ' && *cp != '\t')
484 			cp++;
485 		*cpp = cp;
486 		break;
487 	default:
488 		fatal("key_read: bad key type: %d", ret->type);
489 		break;
490 	}
491 	return success;
492 }
493 
494 int
495 key_write(Key *key, FILE *f)
496 {
497 	int n, success = 0;
498 	u_int len, bits = 0;
499 	u_char *blob;
500 	char *uu;
501 
502 	if (key->type == KEY_RSA1 && key->rsa != NULL) {
503 		/* size of modulus 'n' */
504 		bits = BN_num_bits(key->rsa->n);
505 		fprintf(f, "%u", bits);
506 		if (write_bignum(f, key->rsa->e) &&
507 		    write_bignum(f, key->rsa->n)) {
508 			success = 1;
509 		} else {
510 			error("key_write: failed for RSA key");
511 		}
512 	} else if ((key->type == KEY_DSA && key->dsa != NULL) ||
513 	    (key->type == KEY_RSA && key->rsa != NULL)) {
514 		key_to_blob(key, &blob, &len);
515 		uu = xmalloc(2*len);
516 		n = uuencode(blob, len, uu, 2*len);
517 		if (n > 0) {
518 			fprintf(f, "%s %s", key_ssh_name(key), uu);
519 			success = 1;
520 		}
521 		xfree(blob);
522 		xfree(uu);
523 	}
524 	return success;
525 }
526 
527 char *
528 key_type(Key *k)
529 {
530 	switch (k->type) {
531 	case KEY_RSA1:
532 		return "RSA1";
533 		break;
534 	case KEY_RSA:
535 		return "RSA";
536 		break;
537 	case KEY_DSA:
538 		return "DSA";
539 		break;
540 	}
541 	return "unknown";
542 }
543 
544 char *
545 key_ssh_name(Key *k)
546 {
547 	switch (k->type) {
548 	case KEY_RSA:
549 		return "ssh-rsa";
550 		break;
551 	case KEY_DSA:
552 		return "ssh-dss";
553 		break;
554 	}
555 	return "ssh-unknown";
556 }
557 
558 u_int
559 key_size(Key *k)
560 {
561 	switch (k->type) {
562 	case KEY_RSA1:
563 	case KEY_RSA:
564 		return BN_num_bits(k->rsa->n);
565 		break;
566 	case KEY_DSA:
567 		return BN_num_bits(k->dsa->p);
568 		break;
569 	}
570 	return 0;
571 }
572 
573 static RSA *
574 rsa_generate_private_key(u_int bits)
575 {
576 	RSA *private;
577 	private = RSA_generate_key(bits, 35, NULL, NULL);
578 	if (private == NULL)
579 		fatal("rsa_generate_private_key: key generation failed.");
580 	return private;
581 }
582 
583 static DSA*
584 dsa_generate_private_key(u_int bits)
585 {
586 	DSA *private = DSA_generate_parameters(bits, NULL, 0, NULL, NULL, NULL, NULL);
587 	if (private == NULL)
588 		fatal("dsa_generate_private_key: DSA_generate_parameters failed");
589 	if (!DSA_generate_key(private))
590 		fatal("dsa_generate_private_key: DSA_generate_key failed.");
591 	if (private == NULL)
592 		fatal("dsa_generate_private_key: NULL.");
593 	return private;
594 }
595 
596 Key *
597 key_generate(int type, u_int bits)
598 {
599 	Key *k = key_new(KEY_UNSPEC);
600 	switch (type) {
601 	case KEY_DSA:
602 		k->dsa = dsa_generate_private_key(bits);
603 		break;
604 	case KEY_RSA:
605 	case KEY_RSA1:
606 		k->rsa = rsa_generate_private_key(bits);
607 		break;
608 	default:
609 		fatal("key_generate: unknown type %d", type);
610 	}
611 	k->type = type;
612 	return k;
613 }
614 
615 Key *
616 key_from_private(Key *k)
617 {
618 	Key *n = NULL;
619 	switch (k->type) {
620 	case KEY_DSA:
621 		n = key_new(k->type);
622 		BN_copy(n->dsa->p, k->dsa->p);
623 		BN_copy(n->dsa->q, k->dsa->q);
624 		BN_copy(n->dsa->g, k->dsa->g);
625 		BN_copy(n->dsa->pub_key, k->dsa->pub_key);
626 		break;
627 	case KEY_RSA:
628 	case KEY_RSA1:
629 		n = key_new(k->type);
630 		BN_copy(n->rsa->n, k->rsa->n);
631 		BN_copy(n->rsa->e, k->rsa->e);
632 		break;
633 	default:
634 		fatal("key_from_private: unknown type %d", k->type);
635 		break;
636 	}
637 	return n;
638 }
639 
640 int
641 key_type_from_name(char *name)
642 {
643 	if (strcmp(name, "rsa1") == 0) {
644 		return KEY_RSA1;
645 	} else if (strcmp(name, "rsa") == 0) {
646 		return KEY_RSA;
647 	} else if (strcmp(name, "dsa") == 0) {
648 		return KEY_DSA;
649 	} else if (strcmp(name, "ssh-rsa") == 0) {
650 		return KEY_RSA;
651 	} else if (strcmp(name, "ssh-dss") == 0) {
652 		return KEY_DSA;
653 	} else if (strcmp(name, "null") == 0){
654 		return KEY_NULL;
655 	}
656 	debug2("key_type_from_name: unknown key type '%s'", name);
657 	return KEY_UNSPEC;
658 }
659 
660 int
661 key_names_valid2(const char *names)
662 {
663 	char *s, *cp, *p;
664 
665 	if (names == NULL || strcmp(names, "") == 0)
666 		return 0;
667 	s = cp = xstrdup(names);
668 	for ((p = strsep(&cp, ",")); p && *p != '\0';
669 	    (p = strsep(&cp, ","))) {
670 		switch (key_type_from_name(p)) {
671 		case KEY_RSA1:
672 		case KEY_UNSPEC:
673 			xfree(s);
674 			return 0;
675 		}
676 	}
677 	debug3("key names ok: [%s]", names);
678 	xfree(s);
679 	return 1;
680 }
681 
682 Key *
683 key_from_blob(u_char *blob, int blen)
684 {
685 	Buffer b;
686 	char *ktype;
687 	int rlen, type;
688 	Key *key = NULL;
689 
690 #ifdef DEBUG_PK
691 	dump_base64(stderr, blob, blen);
692 #endif
693 	buffer_init(&b);
694 	buffer_append(&b, blob, blen);
695 	if ((ktype = buffer_get_string_ret(&b, NULL)) == NULL) {
696 		error("key_from_blob: can't read key type");
697 		goto out;
698 	}
699 
700 	type = key_type_from_name(ktype);
701 
702 	switch (type) {
703 	case KEY_RSA:
704 		key = key_new(type);
705 		if (buffer_get_bignum2_ret(&b, key->rsa->e) == -1 ||
706 		    buffer_get_bignum2_ret(&b, key->rsa->n) == -1) {
707 			error("key_from_blob: can't read rsa key");
708 			key_free(key);
709 			key = NULL;
710 			goto out;
711 		}
712 #ifdef DEBUG_PK
713 		RSA_print_fp(stderr, key->rsa, 8);
714 #endif
715 		break;
716 	case KEY_DSA:
717 		key = key_new(type);
718 		if (buffer_get_bignum2_ret(&b, key->dsa->p) == -1 ||
719 		    buffer_get_bignum2_ret(&b, key->dsa->q) == -1 ||
720 		    buffer_get_bignum2_ret(&b, key->dsa->g) == -1 ||
721 		    buffer_get_bignum2_ret(&b, key->dsa->pub_key) == -1) {
722 			error("key_from_blob: can't read dsa key");
723 			key_free(key);
724 			key = NULL;
725 			goto out;
726 		}
727 #ifdef DEBUG_PK
728 		DSA_print_fp(stderr, key->dsa, 8);
729 #endif
730 		break;
731 	case KEY_UNSPEC:
732 		key = key_new(type);
733 		break;
734 	default:
735 		error("key_from_blob: cannot handle type %s", ktype);
736 		goto out;
737 	}
738 	rlen = buffer_len(&b);
739 	if (key != NULL && rlen != 0)
740 		error("key_from_blob: remaining bytes in key blob %d", rlen);
741  out:
742 	if (ktype != NULL)
743 		xfree(ktype);
744 	buffer_free(&b);
745 	return key;
746 }
747 
748 int
749 key_to_blob(Key *key, u_char **blobp, u_int *lenp)
750 {
751 	Buffer b;
752 	int len;
753 
754 	if (key == NULL) {
755 		error("key_to_blob: key == NULL");
756 		return 0;
757 	}
758 	buffer_init(&b);
759 	switch (key->type) {
760 	case KEY_DSA:
761 		buffer_put_cstring(&b, key_ssh_name(key));
762 		buffer_put_bignum2(&b, key->dsa->p);
763 		buffer_put_bignum2(&b, key->dsa->q);
764 		buffer_put_bignum2(&b, key->dsa->g);
765 		buffer_put_bignum2(&b, key->dsa->pub_key);
766 		break;
767 	case KEY_RSA:
768 		buffer_put_cstring(&b, key_ssh_name(key));
769 		buffer_put_bignum2(&b, key->rsa->e);
770 		buffer_put_bignum2(&b, key->rsa->n);
771 		break;
772 	default:
773 		error("key_to_blob: unsupported key type %d", key->type);
774 		buffer_free(&b);
775 		return 0;
776 	}
777 	len = buffer_len(&b);
778 	if (lenp != NULL)
779 		*lenp = len;
780 	if (blobp != NULL) {
781 		*blobp = xmalloc(len);
782 		memcpy(*blobp, buffer_ptr(&b), len);
783 	}
784 	memset(buffer_ptr(&b), 0, len);
785 	buffer_free(&b);
786 	return len;
787 }
788 
789 int
790 key_sign(
791     Key *key,
792     u_char **sigp, u_int *lenp,
793     u_char *data, u_int datalen)
794 {
795 	switch (key->type) {
796 	case KEY_DSA:
797 		return ssh_dss_sign(key, sigp, lenp, data, datalen);
798 		break;
799 	case KEY_RSA:
800 		return ssh_rsa_sign(key, sigp, lenp, data, datalen);
801 		break;
802 	default:
803 		error("key_sign: illegal key type %d", key->type);
804 		return -1;
805 		break;
806 	}
807 }
808 
809 /*
810  * key_verify returns 1 for a correct signature, 0 for an incorrect signature
811  * and -1 on error.
812  */
813 int
814 key_verify(
815     Key *key,
816     u_char *signature, u_int signaturelen,
817     u_char *data, u_int datalen)
818 {
819 	if (signaturelen == 0)
820 		return -1;
821 
822 	switch (key->type) {
823 	case KEY_DSA:
824 		return ssh_dss_verify(key, signature, signaturelen, data, datalen);
825 		break;
826 	case KEY_RSA:
827 		return ssh_rsa_verify(key, signature, signaturelen, data, datalen);
828 		break;
829 	default:
830 		error("key_verify: illegal key type %d", key->type);
831 		return -1;
832 		break;
833 	}
834 }
835 
836 /* Converts a private to a public key */
837 Key *
838 key_demote(Key *k)
839 {
840 	Key *pk;
841 
842 	pk = xmalloc(sizeof(*pk));
843 	pk->type = k->type;
844 	pk->flags = k->flags;
845 	pk->dsa = NULL;
846 	pk->rsa = NULL;
847 
848 	switch (k->type) {
849 	case KEY_RSA1:
850 	case KEY_RSA:
851 		if ((pk->rsa = RSA_new()) == NULL)
852 			fatal("key_demote: RSA_new failed");
853 		if ((pk->rsa->e = BN_dup(k->rsa->e)) == NULL)
854 			fatal("key_demote: BN_dup failed");
855 		if ((pk->rsa->n = BN_dup(k->rsa->n)) == NULL)
856 			fatal("key_demote: BN_dup failed");
857 		break;
858 	case KEY_DSA:
859 		if ((pk->dsa = DSA_new()) == NULL)
860 			fatal("key_demote: DSA_new failed");
861 		if ((pk->dsa->p = BN_dup(k->dsa->p)) == NULL)
862 			fatal("key_demote: BN_dup failed");
863 		if ((pk->dsa->q = BN_dup(k->dsa->q)) == NULL)
864 			fatal("key_demote: BN_dup failed");
865 		if ((pk->dsa->g = BN_dup(k->dsa->g)) == NULL)
866 			fatal("key_demote: BN_dup failed");
867 		if ((pk->dsa->pub_key = BN_dup(k->dsa->pub_key)) == NULL)
868 			fatal("key_demote: BN_dup failed");
869 		break;
870 	default:
871 		fatal("key_free: bad key type %d", k->type);
872 		break;
873 	}
874 
875 	return (pk);
876 }
877