1 /* $OpenBSD: key.c,v 1.80 2008/10/10 05:00:12 stevesk Exp $ */
2 /*
3  * read_bignum():
4  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5  *
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".
11  *
12  *
13  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
14  * Copyright (c) 2008 Alexander von Gernler.  All rights reserved.
15  *
16  * Redistribution and use in source and binary forms, with or without
17  * modification, are permitted provided that the following conditions
18  * are met:
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.
24  *
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.
35  */
36 
37 #include <sys/param.h>
38 #include <sys/types.h>
39 
40 #include <openssl/evp.h>
41 #include <openssl/rand.h>
42 
43 #include <stdio.h>
44 #include <string.h>
45 
46 #include "xmalloc.h"
47 #include "key.h"
48 #include "rsa.h"
49 #include "uuencode.h"
50 #include "buffer.h"
51 #include "log.h"
52 
53 __RCSID("$MirOS: src/usr.bin/ssh/key.c,v 1.7 2014/03/13 04:46:47 tg Exp $");
54 
55 static void key_gen_callback(int, int, void *);
56 
57 Key *
key_new(int type)58 key_new(int type)
59 {
60 	Key *k;
61 	RSA *rsa;
62 	DSA *dsa;
63 	k = xcalloc(1, sizeof(*k));
64 	k->type = type;
65 	k->dsa = NULL;
66 	k->rsa = NULL;
67 	switch (k->type) {
68 	case KEY_RSA1:
69 	case KEY_RSA:
70 		if ((rsa = RSA_new()) == NULL)
71 			fatal("key_new: RSA_new failed");
72 		if ((rsa->n = BN_new()) == NULL)
73 			fatal("key_new: BN_new failed");
74 		if ((rsa->e = BN_new()) == NULL)
75 			fatal("key_new: BN_new failed");
76 		k->rsa = rsa;
77 		break;
78 	case KEY_DSA:
79 		if ((dsa = DSA_new()) == NULL)
80 			fatal("key_new: DSA_new failed");
81 		if ((dsa->p = BN_new()) == NULL)
82 			fatal("key_new: BN_new failed");
83 		if ((dsa->q = BN_new()) == NULL)
84 			fatal("key_new: BN_new failed");
85 		if ((dsa->g = BN_new()) == NULL)
86 			fatal("key_new: BN_new failed");
87 		if ((dsa->pub_key = BN_new()) == NULL)
88 			fatal("key_new: BN_new failed");
89 		k->dsa = dsa;
90 		break;
91 	case KEY_UNSPEC:
92 		break;
93 	default:
94 		fatal("key_new: bad key type %d", k->type);
95 		break;
96 	}
97 	return k;
98 }
99 
100 Key *
key_new_private(int type)101 key_new_private(int type)
102 {
103 	Key *k = key_new(type);
104 	switch (k->type) {
105 	case KEY_RSA1:
106 	case KEY_RSA:
107 		if ((k->rsa->d = BN_new()) == NULL)
108 			fatal("key_new_private: BN_new failed");
109 		if ((k->rsa->iqmp = BN_new()) == NULL)
110 			fatal("key_new_private: BN_new failed");
111 		if ((k->rsa->q = BN_new()) == NULL)
112 			fatal("key_new_private: BN_new failed");
113 		if ((k->rsa->p = BN_new()) == NULL)
114 			fatal("key_new_private: BN_new failed");
115 		if ((k->rsa->dmq1 = BN_new()) == NULL)
116 			fatal("key_new_private: BN_new failed");
117 		if ((k->rsa->dmp1 = BN_new()) == NULL)
118 			fatal("key_new_private: BN_new failed");
119 		break;
120 	case KEY_DSA:
121 		if ((k->dsa->priv_key = BN_new()) == NULL)
122 			fatal("key_new_private: BN_new failed");
123 		break;
124 	case KEY_UNSPEC:
125 		break;
126 	default:
127 		break;
128 	}
129 	return k;
130 }
131 
132 void
key_free(Key * k)133 key_free(Key *k)
134 {
135 	if (k == NULL)
136 		fatal("key_free: key is NULL");
137 	switch (k->type) {
138 	case KEY_RSA1:
139 	case KEY_RSA:
140 		if (k->rsa != NULL)
141 			RSA_free(k->rsa);
142 		k->rsa = NULL;
143 		break;
144 	case KEY_DSA:
145 		if (k->dsa != NULL)
146 			DSA_free(k->dsa);
147 		k->dsa = NULL;
148 		break;
149 	case KEY_UNSPEC:
150 		break;
151 	default:
152 		fatal("key_free: bad key type %d", k->type);
153 		break;
154 	}
155 	xfree(k);
156 }
157 
158 int
key_equal(const Key * a,const Key * b)159 key_equal(const Key *a, const Key *b)
160 {
161 	if (a == NULL || b == NULL || a->type != b->type)
162 		return 0;
163 	switch (a->type) {
164 	case KEY_RSA1:
165 	case KEY_RSA:
166 		return a->rsa != NULL && b->rsa != NULL &&
167 		    BN_cmp(a->rsa->e, b->rsa->e) == 0 &&
168 		    BN_cmp(a->rsa->n, b->rsa->n) == 0;
169 	case KEY_DSA:
170 		return a->dsa != NULL && b->dsa != NULL &&
171 		    BN_cmp(a->dsa->p, b->dsa->p) == 0 &&
172 		    BN_cmp(a->dsa->q, b->dsa->q) == 0 &&
173 		    BN_cmp(a->dsa->g, b->dsa->g) == 0 &&
174 		    BN_cmp(a->dsa->pub_key, b->dsa->pub_key) == 0;
175 	default:
176 		fatal("key_equal: bad key type %d", a->type);
177 	}
178 	/* NOTREACHED */
179 }
180 
181 u_char*
key_fingerprint_raw(const Key * k,enum fp_type dgst_type,u_int * dgst_raw_length)182 key_fingerprint_raw(const Key *k, enum fp_type dgst_type,
183     u_int *dgst_raw_length)
184 {
185 	const EVP_MD *md = NULL;
186 	EVP_MD_CTX ctx;
187 	u_char *blob = NULL;
188 	u_char *retval = NULL;
189 	u_int len = 0;
190 	int nlen, elen;
191 
192 	*dgst_raw_length = 0;
193 
194 	switch (dgst_type) {
195 	case SSH_FP_MD5:
196 		md = EVP_md5();
197 		break;
198 	case SSH_FP_SHA1:
199 		md = EVP_sha1();
200 		break;
201 	default:
202 		fatal("key_fingerprint_raw: bad digest type %d",
203 		    dgst_type);
204 	}
205 	switch (k->type) {
206 	case KEY_RSA1:
207 		nlen = BN_num_bytes(k->rsa->n);
208 		elen = BN_num_bytes(k->rsa->e);
209 		len = nlen + elen;
210 		blob = xmalloc(len);
211 		BN_bn2bin(k->rsa->n, blob);
212 		BN_bn2bin(k->rsa->e, blob + nlen);
213 		break;
214 	case KEY_DSA:
215 	case KEY_RSA:
216 		key_to_blob(k, &blob, &len);
217 		break;
218 	case KEY_UNSPEC:
219 		return retval;
220 	default:
221 		fatal("key_fingerprint_raw: bad key type %d", k->type);
222 		break;
223 	}
224 	if (blob != NULL) {
225 		retval = xmalloc(EVP_MAX_MD_SIZE);
226 		EVP_DigestInit(&ctx, md);
227 		EVP_DigestUpdate(&ctx, blob, len);
228 		EVP_DigestFinal(&ctx, retval, dgst_raw_length);
229 		memset(blob, 0, len);
230 		xfree(blob);
231 	} else {
232 		fatal("key_fingerprint_raw: blob is null");
233 	}
234 	return retval;
235 }
236 
237 static char *
key_fingerprint_hex(u_char * dgst_raw,u_int dgst_raw_len)238 key_fingerprint_hex(u_char *dgst_raw, u_int dgst_raw_len)
239 {
240 	char *retval;
241 	u_int i;
242 
243 	retval = xcalloc(1, dgst_raw_len * 3 + 1);
244 	for (i = 0; i < dgst_raw_len; i++) {
245 		char hex[4];
246 		snprintf(hex, sizeof(hex), "%02x:", dgst_raw[i]);
247 		strlcat(retval, hex, dgst_raw_len * 3 + 1);
248 	}
249 
250 	/* Remove the trailing ':' character */
251 	retval[(dgst_raw_len * 3) - 1] = '\0';
252 	return retval;
253 }
254 
255 static char *
key_fingerprint_bubblebabble(u_char * dgst_raw,u_int dgst_raw_len)256 key_fingerprint_bubblebabble(u_char *dgst_raw, u_int dgst_raw_len)
257 {
258 	char vowels[] = { 'a', 'e', 'i', 'o', 'u', 'y' };
259 	char consonants[] = { 'b', 'c', 'd', 'f', 'g', 'h', 'k', 'l', 'm',
260 	    'n', 'p', 'r', 's', 't', 'v', 'z', 'x' };
261 	u_int i, j = 0, rounds, seed = 1;
262 	char *retval;
263 
264 	rounds = (dgst_raw_len / 2) + 1;
265 	retval = xcalloc((rounds * 6), sizeof(char));
266 	retval[j++] = 'x';
267 	for (i = 0; i < rounds; i++) {
268 		u_int idx0, idx1, idx2, idx3, idx4;
269 		if ((i + 1 < rounds) || (dgst_raw_len % 2 != 0)) {
270 			idx0 = (((((u_int)(dgst_raw[2 * i])) >> 6) & 3) +
271 			    seed) % 6;
272 			idx1 = (((u_int)(dgst_raw[2 * i])) >> 2) & 15;
273 			idx2 = ((((u_int)(dgst_raw[2 * i])) & 3) +
274 			    (seed / 6)) % 6;
275 			retval[j++] = vowels[idx0];
276 			retval[j++] = consonants[idx1];
277 			retval[j++] = vowels[idx2];
278 			if ((i + 1) < rounds) {
279 				idx3 = (((u_int)(dgst_raw[(2 * i) + 1])) >> 4) & 15;
280 				idx4 = (((u_int)(dgst_raw[(2 * i) + 1]))) & 15;
281 				retval[j++] = consonants[idx3];
282 				retval[j++] = '-';
283 				retval[j++] = consonants[idx4];
284 				seed = ((seed * 5) +
285 				    ((((u_int)(dgst_raw[2 * i])) * 7) +
286 				    ((u_int)(dgst_raw[(2 * i) + 1])))) % 36;
287 			}
288 		} else {
289 			idx0 = seed % 6;
290 			idx1 = 16;
291 			idx2 = seed / 6;
292 			retval[j++] = vowels[idx0];
293 			retval[j++] = consonants[idx1];
294 			retval[j++] = vowels[idx2];
295 		}
296 	}
297 	retval[j++] = 'x';
298 	retval[j++] = '\0';
299 	return retval;
300 }
301 
302 /*
303  * Draw an ASCII-Art representing the fingerprint so human brain can
304  * profit from its built-in pattern recognition ability.
305  * This technique is called "random art" and can be found in some
306  * scientific publications like this original paper:
307  *
308  * "Hash Visualization: a New Technique to improve Real-World Security",
309  * Perrig A. and Song D., 1999, International Workshop on Cryptographic
310  * Techniques and E-Commerce (CrypTEC '99)
311  * sparrow.ece.cmu.edu/~adrian/projects/validation/validation.pdf
312  *
313  * The subject came up in a talk by Dan Kaminsky, too.
314  *
315  * If you see the picture is different, the key is different.
316  * If the picture looks the same, you still know nothing.
317  *
318  * The algorithm used here is a worm crawling over a discrete plane,
319  * leaving a trace (augmenting the field) everywhere it goes.
320  * Movement is taken from dgst_raw 2bit-wise.  Bumping into walls
321  * makes the respective movement vector be ignored for this turn.
322  * Graphs are not unambiguous, because circles in graphs can be
323  * walked in either direction.
324  */
325 
326 /*
327  * Field sizes for the random art.  Have to be odd, so the starting point
328  * can be in the exact middle of the picture, and FLDBASE should be >=8 .
329  * Else pictures would be too dense, and drawing the frame would
330  * fail, too, because the key type would not fit in anymore.
331  */
332 #define	FLDBASE		8
333 #define	FLDSIZE_Y	(FLDBASE + 1)
334 #define	FLDSIZE_X	(FLDBASE * 2 + 1)
335 static char *
key_fingerprint_randomart(u_char * dgst_raw,u_int dgst_raw_len,const Key * k)336 key_fingerprint_randomart(u_char *dgst_raw, u_int dgst_raw_len, const Key *k)
337 {
338 	/*
339 	 * Chars to be used after each other every time the worm
340 	 * intersects with itself.  Matter of taste.
341 	 */
342 	const char *augmentation_string = " .o+=*BOX@%&#/^SE";
343 	char	*retval, *p;
344 	u_char	 field[FLDSIZE_X][FLDSIZE_Y];
345 	u_int	 i, b;
346 	int	 x, y;
347 	size_t	 len = strlen(augmentation_string) - 1;
348 
349 	retval = xcalloc(1, (FLDSIZE_X + 3) * (FLDSIZE_Y + 2));
350 
351 	/* initialize field */
352 	memset(field, 0, FLDSIZE_X * FLDSIZE_Y * sizeof(char));
353 	x = FLDSIZE_X / 2;
354 	y = FLDSIZE_Y / 2;
355 
356 	/* process raw key */
357 	for (i = 0; i < dgst_raw_len; i++) {
358 		int input;
359 		/* each byte conveys four 2-bit move commands */
360 		input = dgst_raw[i];
361 		for (b = 0; b < 4; b++) {
362 			/* evaluate 2 bit, rest is shifted later */
363 			x += (input & 0x1) ? 1 : -1;
364 			y += (input & 0x2) ? 1 : -1;
365 
366 			/* assure we are still in bounds */
367 			x = MAX(x, 0);
368 			y = MAX(y, 0);
369 			x = MIN(x, FLDSIZE_X - 1);
370 			y = MIN(y, FLDSIZE_Y - 1);
371 
372 			/* augment the field */
373 			if (field[x][y] < len - 2)
374 				field[x][y]++;
375 			input = input >> 2;
376 		}
377 	}
378 
379 	/* mark starting point and end point*/
380 	field[FLDSIZE_X / 2][FLDSIZE_Y / 2] = len - 1;
381 	field[x][y] = len;
382 
383 	/* fill in retval */
384 	snprintf(retval, FLDSIZE_X, "+--[%4s %4u]", key_type(k), key_size(k));
385 	p = strchr(retval, '\0');
386 
387 	/* output upper border */
388 	for (i = p - retval - 1; i < FLDSIZE_X; i++)
389 		*p++ = '-';
390 	*p++ = '+';
391 	*p++ = '\n';
392 
393 	/* output content */
394 	for (y = 0; y < FLDSIZE_Y; y++) {
395 		*p++ = '|';
396 		for (x = 0; x < FLDSIZE_X; x++)
397 			*p++ = augmentation_string[MIN(field[x][y], len)];
398 		*p++ = '|';
399 		*p++ = '\n';
400 	}
401 
402 	/* output lower border */
403 	*p++ = '+';
404 	for (i = 0; i < FLDSIZE_X; i++)
405 		*p++ = '-';
406 	*p++ = '+';
407 
408 	return retval;
409 }
410 
411 char *
key_fingerprint(const Key * k,enum fp_type dgst_type,enum fp_rep dgst_rep)412 key_fingerprint(const Key *k, enum fp_type dgst_type, enum fp_rep dgst_rep)
413 {
414 	char *retval = NULL;
415 	u_char *dgst_raw;
416 	u_int dgst_raw_len;
417 
418 	dgst_raw = key_fingerprint_raw(k, dgst_type, &dgst_raw_len);
419 	if (!dgst_raw)
420 		fatal("key_fingerprint: null from key_fingerprint_raw()");
421 	switch (dgst_rep) {
422 	case SSH_FP_HEX:
423 		retval = key_fingerprint_hex(dgst_raw, dgst_raw_len);
424 		break;
425 	case SSH_FP_BUBBLEBABBLE:
426 		retval = key_fingerprint_bubblebabble(dgst_raw, dgst_raw_len);
427 		break;
428 	case SSH_FP_RANDOMART:
429 		retval = key_fingerprint_randomart(dgst_raw, dgst_raw_len, k);
430 		break;
431 	default:
432 		fatal("key_fingerprint: bad digest representation %d",
433 		    dgst_rep);
434 		break;
435 	}
436 	memset(dgst_raw, 0, dgst_raw_len);
437 	xfree(dgst_raw);
438 	return retval;
439 }
440 
441 /*
442  * Reads a multiple-precision integer in decimal from the buffer, and advances
443  * the pointer.  The integer must already be initialized.  This function is
444  * permitted to modify the buffer.  This leaves *cpp to point just beyond the
445  * last processed (and maybe modified) character.  Note that this may modify
446  * the buffer containing the number.
447  */
448 static int
read_bignum(char ** cpp,BIGNUM * value)449 read_bignum(char **cpp, BIGNUM * value)
450 {
451 	char *cp = *cpp;
452 	int old;
453 
454 	/* Skip any leading whitespace. */
455 	for (; *cp == ' ' || *cp == '\t'; cp++)
456 		;
457 
458 	/* Check that it begins with a decimal digit. */
459 	if (*cp < '0' || *cp > '9')
460 		return 0;
461 
462 	/* Save starting position. */
463 	*cpp = cp;
464 
465 	/* Move forward until all decimal digits skipped. */
466 	for (; *cp >= '0' && *cp <= '9'; cp++)
467 		;
468 
469 	/* Save the old terminating character, and replace it by \0. */
470 	old = *cp;
471 	*cp = 0;
472 
473 	/* Parse the number. */
474 	if (BN_dec2bn(&value, *cpp) == 0)
475 		return 0;
476 
477 	/* Restore old terminating character. */
478 	*cp = old;
479 
480 	/* Move beyond the number and return success. */
481 	*cpp = cp;
482 	return 1;
483 }
484 
485 static int
write_bignum(FILE * f,BIGNUM * num)486 write_bignum(FILE *f, BIGNUM *num)
487 {
488 	char *buf = BN_bn2dec(num);
489 	if (buf == NULL) {
490 		error("write_bignum: BN_bn2dec() failed");
491 		return 0;
492 	}
493 	fprintf(f, " %s", buf);
494 	OPENSSL_free(buf);
495 	return 1;
496 }
497 
498 /* returns 1 ok, -1 error */
499 int
key_read(Key * ret,char ** cpp)500 key_read(Key *ret, char **cpp)
501 {
502 	Key *k;
503 	int success = -1;
504 	char *cp, *space;
505 	int len, n, type;
506 	u_int bits;
507 	u_char *blob;
508 
509 	cp = *cpp;
510 
511 	switch (ret->type) {
512 	case KEY_RSA1:
513 		/* Get number of bits. */
514 		if (*cp < '0' || *cp > '9')
515 			return -1;	/* Bad bit count... */
516 		for (bits = 0; *cp >= '0' && *cp <= '9'; cp++)
517 			bits = 10 * bits + *cp - '0';
518 		if (bits == 0)
519 			return -1;
520 		*cpp = cp;
521 		/* Get public exponent, public modulus. */
522 		if (!read_bignum(cpp, ret->rsa->e))
523 			return -1;
524 		if (!read_bignum(cpp, ret->rsa->n))
525 			return -1;
526 		success = 1;
527 		break;
528 	case KEY_UNSPEC:
529 	case KEY_RSA:
530 	case KEY_DSA:
531 		space = strchr(cp, ' ');
532 		if (space == NULL) {
533 			debug3("key_read: missing whitespace");
534 			return -1;
535 		}
536 		*space = '\0';
537 		type = key_type_from_name(cp);
538 		*space = ' ';
539 		if (type == KEY_UNSPEC) {
540 			debug3("key_read: missing keytype");
541 			return -1;
542 		}
543 		cp = space+1;
544 		if (*cp == '\0') {
545 			debug3("key_read: short string");
546 			return -1;
547 		}
548 		if (ret->type == KEY_UNSPEC) {
549 			ret->type = type;
550 		} else if (ret->type != type) {
551 			/* is a key, but different type */
552 			debug3("key_read: type mismatch");
553 			return -1;
554 		}
555 		len = 2*strlen(cp);
556 		blob = xmalloc(len);
557 		n = uudecode(cp, blob, len);
558 		if (n < 0) {
559 			error("key_read: uudecode %s failed", cp);
560 			xfree(blob);
561 			return -1;
562 		}
563 		k = key_from_blob(blob, (u_int)n);
564 		xfree(blob);
565 		if (k == NULL) {
566 			error("key_read: key_from_blob %s failed", cp);
567 			return -1;
568 		}
569 		if (k->type != type) {
570 			error("key_read: type mismatch: encoding error");
571 			key_free(k);
572 			return -1;
573 		}
574 /*XXXX*/
575 		if (ret->type == KEY_RSA) {
576 			if (ret->rsa != NULL)
577 				RSA_free(ret->rsa);
578 			ret->rsa = k->rsa;
579 			k->rsa = NULL;
580 			success = 1;
581 #ifdef DEBUG_PK
582 			RSA_print_fp(stderr, ret->rsa, 8);
583 #endif
584 		} else {
585 			if (ret->dsa != NULL)
586 				DSA_free(ret->dsa);
587 			ret->dsa = k->dsa;
588 			k->dsa = NULL;
589 			success = 1;
590 #ifdef DEBUG_PK
591 			DSA_print_fp(stderr, ret->dsa, 8);
592 #endif
593 		}
594 /*XXXX*/
595 		key_free(k);
596 		if (success != 1)
597 			break;
598 		/* advance cp: skip whitespace and data */
599 		while (*cp == ' ' || *cp == '\t')
600 			cp++;
601 		while (*cp != '\0' && *cp != ' ' && *cp != '\t')
602 			cp++;
603 		*cpp = cp;
604 		break;
605 	default:
606 		fatal("key_read: bad key type: %d", ret->type);
607 		break;
608 	}
609 	return success;
610 }
611 
612 int
key_write(const Key * key,FILE * f)613 key_write(const Key *key, FILE *f)
614 {
615 	int n, success = 0;
616 	u_int len, bits = 0;
617 	u_char *blob;
618 	char *uu;
619 
620 	if (key->type == KEY_RSA1 && key->rsa != NULL) {
621 		/* size of modulus 'n' */
622 		bits = BN_num_bits(key->rsa->n);
623 		fprintf(f, "%u", bits);
624 		if (write_bignum(f, key->rsa->e) &&
625 		    write_bignum(f, key->rsa->n)) {
626 			success = 1;
627 		} else {
628 			error("key_write: failed for RSA key");
629 		}
630 	} else if ((key->type == KEY_DSA && key->dsa != NULL) ||
631 	    (key->type == KEY_RSA && key->rsa != NULL)) {
632 		key_to_blob(key, &blob, &len);
633 		uu = xmalloc(2*len);
634 		n = uuencode(blob, len, uu, 2*len);
635 		if (n > 0) {
636 			fprintf(f, "%s %s", key_ssh_name(key), uu);
637 			success = 1;
638 		}
639 		xfree(blob);
640 		xfree(uu);
641 	}
642 	return success;
643 }
644 
645 const char *
key_type(const Key * k)646 key_type(const Key *k)
647 {
648 	switch (k->type) {
649 	case KEY_RSA1:
650 		return "RSA1";
651 	case KEY_RSA:
652 		return "RSA";
653 	case KEY_DSA:
654 		return "DSA";
655 	}
656 	return "unknown";
657 }
658 
659 const char *
key_ssh_name(const Key * k)660 key_ssh_name(const Key *k)
661 {
662 	switch (k->type) {
663 	case KEY_RSA:
664 		return "ssh-rsa";
665 	case KEY_DSA:
666 		return "ssh-dss";
667 	}
668 	return "ssh-unknown";
669 }
670 
671 u_int
key_size(const Key * k)672 key_size(const Key *k)
673 {
674 	switch (k->type) {
675 	case KEY_RSA1:
676 	case KEY_RSA:
677 		return BN_num_bits(k->rsa->n);
678 	case KEY_DSA:
679 		return BN_num_bits(k->dsa->p);
680 	}
681 	return 0;
682 }
683 
684 static RSA *
rsa_generate_private_key(u_int bits)685 rsa_generate_private_key(u_int bits)
686 {
687 	RSA *private;
688 
689 	private = RSA_generate_key(bits, 35, key_gen_callback, NULL);
690 	if (private == NULL)
691 		fatal("rsa_generate_private_key: key generation failed.");
692 	return private;
693 }
694 
695 static DSA*
dsa_generate_private_key(u_int bits)696 dsa_generate_private_key(u_int bits)
697 {
698 	DSA *private;
699 
700 	private = DSA_generate_parameters(bits, NULL, 0, NULL, NULL,
701 	    key_gen_callback, NULL);
702 
703 	if (private == NULL)
704 		fatal("dsa_generate_private_key: DSA_generate_parameters failed");
705 	if (!DSA_generate_key(private))
706 		fatal("dsa_generate_private_key: DSA_generate_key failed.");
707 	if (private == NULL)
708 		fatal("dsa_generate_private_key: NULL.");
709 	return private;
710 }
711 
712 Key *
key_generate(int type,u_int bits)713 key_generate(int type, u_int bits)
714 {
715 	Key *k = key_new(KEY_UNSPEC);
716 	switch (type) {
717 	case KEY_DSA:
718 		k->dsa = dsa_generate_private_key(bits);
719 		break;
720 	case KEY_RSA:
721 	case KEY_RSA1:
722 		k->rsa = rsa_generate_private_key(bits);
723 		break;
724 	default:
725 		fatal("key_generate: unknown type %d", type);
726 	}
727 	k->type = type;
728 	return k;
729 }
730 
731 Key *
key_from_private(const Key * k)732 key_from_private(const Key *k)
733 {
734 	Key *n = NULL;
735 	switch (k->type) {
736 	case KEY_DSA:
737 		n = key_new(k->type);
738 		if ((BN_copy(n->dsa->p, k->dsa->p) == NULL) ||
739 		    (BN_copy(n->dsa->q, k->dsa->q) == NULL) ||
740 		    (BN_copy(n->dsa->g, k->dsa->g) == NULL) ||
741 		    (BN_copy(n->dsa->pub_key, k->dsa->pub_key) == NULL))
742 			fatal("key_from_private: BN_copy failed");
743 		break;
744 	case KEY_RSA:
745 	case KEY_RSA1:
746 		n = key_new(k->type);
747 		if ((BN_copy(n->rsa->n, k->rsa->n) == NULL) ||
748 		    (BN_copy(n->rsa->e, k->rsa->e) == NULL))
749 			fatal("key_from_private: BN_copy failed");
750 		break;
751 	default:
752 		fatal("key_from_private: unknown type %d", k->type);
753 		break;
754 	}
755 	return n;
756 }
757 
758 int
key_type_from_name(char * name)759 key_type_from_name(char *name)
760 {
761 	if (strcmp(name, "rsa1") == 0) {
762 		return KEY_RSA1;
763 	} else if (strcmp(name, "rsa") == 0) {
764 		return KEY_RSA;
765 	} else if (strcmp(name, "dsa") == 0) {
766 		return KEY_DSA;
767 	} else if (strcmp(name, "ssh-rsa") == 0) {
768 		return KEY_RSA;
769 	} else if (strcmp(name, "ssh-dss") == 0) {
770 		return KEY_DSA;
771 	}
772 	debug2("key_type_from_name: unknown key type '%s'", name);
773 	return KEY_UNSPEC;
774 }
775 
776 int
key_names_valid2(const char * names)777 key_names_valid2(const char *names)
778 {
779 	char *s, *cp, *p;
780 
781 	if (names == NULL || strcmp(names, "") == 0)
782 		return 0;
783 	s = cp = xstrdup(names);
784 	for ((p = strsep(&cp, ",")); p && *p != '\0';
785 	    (p = strsep(&cp, ","))) {
786 		switch (key_type_from_name(p)) {
787 		case KEY_RSA1:
788 		case KEY_UNSPEC:
789 			xfree(s);
790 			return 0;
791 		}
792 	}
793 	debug3("key names ok: [%s]", names);
794 	xfree(s);
795 	return 1;
796 }
797 
798 Key *
key_from_blob(const u_char * blob,u_int blen)799 key_from_blob(const u_char *blob, u_int blen)
800 {
801 	Buffer b;
802 	int rlen, type;
803 	char *ktype = NULL;
804 	Key *key = NULL;
805 
806 #ifdef DEBUG_PK
807 	dump_base64(stderr, blob, blen);
808 #endif
809 	buffer_init(&b);
810 	buffer_append(&b, blob, blen);
811 	if ((ktype = buffer_get_string_ret(&b, NULL)) == NULL) {
812 		error("key_from_blob: can't read key type");
813 		goto out;
814 	}
815 
816 	type = key_type_from_name(ktype);
817 
818 	switch (type) {
819 	case KEY_RSA:
820 		key = key_new(type);
821 		if (buffer_get_bignum2_ret(&b, key->rsa->e) == -1 ||
822 		    buffer_get_bignum2_ret(&b, key->rsa->n) == -1) {
823 			error("key_from_blob: can't read rsa key");
824 			key_free(key);
825 			key = NULL;
826 			goto out;
827 		}
828 #ifdef DEBUG_PK
829 		RSA_print_fp(stderr, key->rsa, 8);
830 #endif
831 		break;
832 	case KEY_DSA:
833 		key = key_new(type);
834 		if (buffer_get_bignum2_ret(&b, key->dsa->p) == -1 ||
835 		    buffer_get_bignum2_ret(&b, key->dsa->q) == -1 ||
836 		    buffer_get_bignum2_ret(&b, key->dsa->g) == -1 ||
837 		    buffer_get_bignum2_ret(&b, key->dsa->pub_key) == -1) {
838 			error("key_from_blob: can't read dsa key");
839 			key_free(key);
840 			key = NULL;
841 			goto out;
842 		}
843 #ifdef DEBUG_PK
844 		DSA_print_fp(stderr, key->dsa, 8);
845 #endif
846 		break;
847 	case KEY_UNSPEC:
848 		key = key_new(type);
849 		break;
850 	default:
851 		error("key_from_blob: cannot handle type %s", ktype);
852 		goto out;
853 	}
854 	rlen = buffer_len(&b);
855 	if (key != NULL && rlen != 0)
856 		error("key_from_blob: remaining bytes in key blob %d", rlen);
857  out:
858 	if (ktype != NULL)
859 		xfree(ktype);
860 	buffer_free(&b);
861 	return key;
862 }
863 
864 int
key_to_blob(const Key * key,u_char ** blobp,u_int * lenp)865 key_to_blob(const Key *key, u_char **blobp, u_int *lenp)
866 {
867 	Buffer b;
868 	int len;
869 
870 	if (key == NULL) {
871 		error("key_to_blob: key == NULL");
872 		return 0;
873 	}
874 	buffer_init(&b);
875 	switch (key->type) {
876 	case KEY_DSA:
877 		buffer_put_cstring(&b, key_ssh_name(key));
878 		buffer_put_bignum2(&b, key->dsa->p);
879 		buffer_put_bignum2(&b, key->dsa->q);
880 		buffer_put_bignum2(&b, key->dsa->g);
881 		buffer_put_bignum2(&b, key->dsa->pub_key);
882 		break;
883 	case KEY_RSA:
884 		buffer_put_cstring(&b, key_ssh_name(key));
885 		buffer_put_bignum2(&b, key->rsa->e);
886 		buffer_put_bignum2(&b, key->rsa->n);
887 		break;
888 	default:
889 		error("key_to_blob: unsupported key type %d", key->type);
890 		buffer_free(&b);
891 		return 0;
892 	}
893 	len = buffer_len(&b);
894 	if (lenp != NULL)
895 		*lenp = len;
896 	if (blobp != NULL) {
897 		*blobp = xmalloc(len);
898 		memcpy(*blobp, buffer_ptr(&b), len);
899 	}
900 	memset(buffer_ptr(&b), 0, len);
901 	buffer_free(&b);
902 	return len;
903 }
904 
905 int
key_sign(const Key * key,u_char ** sigp,u_int * lenp,const u_char * data,u_int datalen)906 key_sign(
907     const Key *key,
908     u_char **sigp, u_int *lenp,
909     const u_char *data, u_int datalen)
910 {
911 	switch (key->type) {
912 	case KEY_DSA:
913 		return ssh_dss_sign(key, sigp, lenp, data, datalen);
914 	case KEY_RSA:
915 		return ssh_rsa_sign(key, sigp, lenp, data, datalen);
916 	default:
917 		error("key_sign: invalid key type %d", key->type);
918 		return -1;
919 	}
920 }
921 
922 /*
923  * key_verify returns 1 for a correct signature, 0 for an incorrect signature
924  * and -1 on error.
925  */
926 int
key_verify(const Key * key,const u_char * signature,u_int signaturelen,const u_char * data,u_int datalen)927 key_verify(
928     const Key *key,
929     const u_char *signature, u_int signaturelen,
930     const u_char *data, u_int datalen)
931 {
932 	if (signaturelen == 0)
933 		return -1;
934 
935 	switch (key->type) {
936 	case KEY_DSA:
937 		return ssh_dss_verify(key, signature, signaturelen, data, datalen);
938 	case KEY_RSA:
939 		return ssh_rsa_verify(key, signature, signaturelen, data, datalen);
940 	default:
941 		error("key_verify: invalid key type %d", key->type);
942 		return -1;
943 	}
944 }
945 
946 /* Converts a private to a public key */
947 Key *
key_demote(const Key * k)948 key_demote(const Key *k)
949 {
950 	Key *pk;
951 
952 	pk = xcalloc(1, sizeof(*pk));
953 	pk->type = k->type;
954 	pk->flags = k->flags;
955 	pk->dsa = NULL;
956 	pk->rsa = NULL;
957 
958 	switch (k->type) {
959 	case KEY_RSA1:
960 	case KEY_RSA:
961 		if ((pk->rsa = RSA_new()) == NULL)
962 			fatal("key_demote: RSA_new failed");
963 		if ((pk->rsa->e = BN_dup(k->rsa->e)) == NULL)
964 			fatal("key_demote: BN_dup failed");
965 		if ((pk->rsa->n = BN_dup(k->rsa->n)) == NULL)
966 			fatal("key_demote: BN_dup failed");
967 		break;
968 	case KEY_DSA:
969 		if ((pk->dsa = DSA_new()) == NULL)
970 			fatal("key_demote: DSA_new failed");
971 		if ((pk->dsa->p = BN_dup(k->dsa->p)) == NULL)
972 			fatal("key_demote: BN_dup failed");
973 		if ((pk->dsa->q = BN_dup(k->dsa->q)) == NULL)
974 			fatal("key_demote: BN_dup failed");
975 		if ((pk->dsa->g = BN_dup(k->dsa->g)) == NULL)
976 			fatal("key_demote: BN_dup failed");
977 		if ((pk->dsa->pub_key = BN_dup(k->dsa->pub_key)) == NULL)
978 			fatal("key_demote: BN_dup failed");
979 		break;
980 	default:
981 		fatal("key_free: bad key type %d", k->type);
982 		break;
983 	}
984 
985 	return (pk);
986 }
987 
988 static void
key_gen_callback(int p,int n,void * arg)989 key_gen_callback(int p, int n, void *arg)
990 {
991 	struct {
992 		void *arg;
993 		int p;
994 		int n;
995 		int pad;
996 	} x;
997 
998 	RAND_bytes((void *)&x, sizeof(x));
999 	x.arg = arg;
1000 	x.p ^= p;
1001 	x.n ^= n;
1002 	arc4random_pushb_fast(&x, sizeof(x));
1003 	bzero(&x, sizeof(x));
1004 }
1005