xref: /openbsd-src/usr.bin/ssh/sshkey.c (revision 0b7734b3d77bb9b21afec6f4621cae6c805dbd45)
1 /* $OpenBSD: sshkey.c,v 1.35 2016/06/19 07:48:02 djm Exp $ */
2 /*
3  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
4  * Copyright (c) 2008 Alexander von Gernler.  All rights reserved.
5  * Copyright (c) 2010,2011 Damien Miller.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 #include <sys/param.h>	/* MIN MAX */
29 #include <sys/types.h>
30 #include <netinet/in.h>
31 
32 #ifdef WITH_OPENSSL
33 #include <openssl/evp.h>
34 #include <openssl/err.h>
35 #include <openssl/pem.h>
36 #endif
37 
38 #include "crypto_api.h"
39 
40 #include <errno.h>
41 #include <stdio.h>
42 #include <string.h>
43 #include <util.h>
44 #include <limits.h>
45 #include <resolv.h>
46 
47 #include "ssh2.h"
48 #include "ssherr.h"
49 #include "misc.h"
50 #include "sshbuf.h"
51 #include "rsa.h"
52 #include "cipher.h"
53 #include "digest.h"
54 #define SSHKEY_INTERNAL
55 #include "sshkey.h"
56 #include "match.h"
57 
58 /* openssh private key file format */
59 #define MARK_BEGIN		"-----BEGIN OPENSSH PRIVATE KEY-----\n"
60 #define MARK_END		"-----END OPENSSH PRIVATE KEY-----\n"
61 #define MARK_BEGIN_LEN		(sizeof(MARK_BEGIN) - 1)
62 #define MARK_END_LEN		(sizeof(MARK_END) - 1)
63 #define KDFNAME			"bcrypt"
64 #define AUTH_MAGIC		"openssh-key-v1"
65 #define SALT_LEN		16
66 #define DEFAULT_CIPHERNAME	"aes256-cbc"
67 #define	DEFAULT_ROUNDS		16
68 
69 /* Version identification string for SSH v1 identity files. */
70 #define LEGACY_BEGIN		"SSH PRIVATE KEY FILE FORMAT 1.1\n"
71 
72 static int sshkey_from_blob_internal(struct sshbuf *buf,
73     struct sshkey **keyp, int allow_cert);
74 
75 /* Supported key types */
76 struct keytype {
77 	const char *name;
78 	const char *shortname;
79 	int type;
80 	int nid;
81 	int cert;
82 	int sigonly;
83 };
84 static const struct keytype keytypes[] = {
85 	{ "ssh-ed25519", "ED25519", KEY_ED25519, 0, 0, 0 },
86 	{ "ssh-ed25519-cert-v01@openssh.com", "ED25519-CERT",
87 	    KEY_ED25519_CERT, 0, 1, 0 },
88 #ifdef WITH_OPENSSL
89 	{ NULL, "RSA1", KEY_RSA1, 0, 0, 0 },
90 	{ "ssh-rsa", "RSA", KEY_RSA, 0, 0, 0 },
91 	{ "rsa-sha2-256", "RSA", KEY_RSA, 0, 0, 1 },
92 	{ "rsa-sha2-512", "RSA", KEY_RSA, 0, 0, 1 },
93 	{ "ssh-dss", "DSA", KEY_DSA, 0, 0, 0 },
94 	{ "ecdsa-sha2-nistp256", "ECDSA", KEY_ECDSA, NID_X9_62_prime256v1, 0, 0 },
95 	{ "ecdsa-sha2-nistp384", "ECDSA", KEY_ECDSA, NID_secp384r1, 0, 0 },
96 	{ "ecdsa-sha2-nistp521", "ECDSA", KEY_ECDSA, NID_secp521r1, 0, 0 },
97 	{ "ssh-rsa-cert-v01@openssh.com", "RSA-CERT", KEY_RSA_CERT, 0, 1, 0 },
98 	{ "ssh-dss-cert-v01@openssh.com", "DSA-CERT", KEY_DSA_CERT, 0, 1, 0 },
99 	{ "ecdsa-sha2-nistp256-cert-v01@openssh.com", "ECDSA-CERT",
100 	    KEY_ECDSA_CERT, NID_X9_62_prime256v1, 1, 0 },
101 	{ "ecdsa-sha2-nistp384-cert-v01@openssh.com", "ECDSA-CERT",
102 	    KEY_ECDSA_CERT, NID_secp384r1, 1, 0 },
103 	{ "ecdsa-sha2-nistp521-cert-v01@openssh.com", "ECDSA-CERT",
104 	    KEY_ECDSA_CERT, NID_secp521r1, 1, 0 },
105 #endif /* WITH_OPENSSL */
106 	{ NULL, NULL, -1, -1, 0, 0 }
107 };
108 
109 const char *
110 sshkey_type(const struct sshkey *k)
111 {
112 	const struct keytype *kt;
113 
114 	for (kt = keytypes; kt->type != -1; kt++) {
115 		if (kt->type == k->type)
116 			return kt->shortname;
117 	}
118 	return "unknown";
119 }
120 
121 static const char *
122 sshkey_ssh_name_from_type_nid(int type, int nid)
123 {
124 	const struct keytype *kt;
125 
126 	for (kt = keytypes; kt->type != -1; kt++) {
127 		if (kt->type == type && (kt->nid == 0 || kt->nid == nid))
128 			return kt->name;
129 	}
130 	return "ssh-unknown";
131 }
132 
133 int
134 sshkey_type_is_cert(int type)
135 {
136 	const struct keytype *kt;
137 
138 	for (kt = keytypes; kt->type != -1; kt++) {
139 		if (kt->type == type)
140 			return kt->cert;
141 	}
142 	return 0;
143 }
144 
145 const char *
146 sshkey_ssh_name(const struct sshkey *k)
147 {
148 	return sshkey_ssh_name_from_type_nid(k->type, k->ecdsa_nid);
149 }
150 
151 const char *
152 sshkey_ssh_name_plain(const struct sshkey *k)
153 {
154 	return sshkey_ssh_name_from_type_nid(sshkey_type_plain(k->type),
155 	    k->ecdsa_nid);
156 }
157 
158 int
159 sshkey_type_from_name(const char *name)
160 {
161 	const struct keytype *kt;
162 
163 	for (kt = keytypes; kt->type != -1; kt++) {
164 		/* Only allow shortname matches for plain key types */
165 		if ((kt->name != NULL && strcmp(name, kt->name) == 0) ||
166 		    (!kt->cert && strcasecmp(kt->shortname, name) == 0))
167 			return kt->type;
168 	}
169 	return KEY_UNSPEC;
170 }
171 
172 int
173 sshkey_ecdsa_nid_from_name(const char *name)
174 {
175 	const struct keytype *kt;
176 
177 	for (kt = keytypes; kt->type != -1; kt++) {
178 		if (kt->type != KEY_ECDSA && kt->type != KEY_ECDSA_CERT)
179 			continue;
180 		if (kt->name != NULL && strcmp(name, kt->name) == 0)
181 			return kt->nid;
182 	}
183 	return -1;
184 }
185 
186 char *
187 key_alg_list(int certs_only, int plain_only)
188 {
189 	char *tmp, *ret = NULL;
190 	size_t nlen, rlen = 0;
191 	const struct keytype *kt;
192 
193 	for (kt = keytypes; kt->type != -1; kt++) {
194 		if (kt->name == NULL || kt->sigonly)
195 			continue;
196 		if ((certs_only && !kt->cert) || (plain_only && kt->cert))
197 			continue;
198 		if (ret != NULL)
199 			ret[rlen++] = '\n';
200 		nlen = strlen(kt->name);
201 		if ((tmp = realloc(ret, rlen + nlen + 2)) == NULL) {
202 			free(ret);
203 			return NULL;
204 		}
205 		ret = tmp;
206 		memcpy(ret + rlen, kt->name, nlen + 1);
207 		rlen += nlen;
208 	}
209 	return ret;
210 }
211 
212 int
213 sshkey_names_valid2(const char *names, int allow_wildcard)
214 {
215 	char *s, *cp, *p;
216 	const struct keytype *kt;
217 	int type;
218 
219 	if (names == NULL || strcmp(names, "") == 0)
220 		return 0;
221 	if ((s = cp = strdup(names)) == NULL)
222 		return 0;
223 	for ((p = strsep(&cp, ",")); p && *p != '\0';
224 	    (p = strsep(&cp, ","))) {
225 		type = sshkey_type_from_name(p);
226 		if (type == KEY_RSA1) {
227 			free(s);
228 			return 0;
229 		}
230 		if (type == KEY_UNSPEC) {
231 			if (allow_wildcard) {
232 				/*
233 				 * Try matching key types against the string.
234 				 * If any has a positive or negative match then
235 				 * the component is accepted.
236 				 */
237 				for (kt = keytypes; kt->type != -1; kt++) {
238 					if (kt->type == KEY_RSA1)
239 						continue;
240 					if (match_pattern_list(kt->name,
241 					    p, 0) != 0)
242 						break;
243 				}
244 				if (kt->type != -1)
245 					continue;
246 			}
247 			free(s);
248 			return 0;
249 		}
250 	}
251 	free(s);
252 	return 1;
253 }
254 
255 u_int
256 sshkey_size(const struct sshkey *k)
257 {
258 	switch (k->type) {
259 #ifdef WITH_OPENSSL
260 	case KEY_RSA1:
261 	case KEY_RSA:
262 	case KEY_RSA_CERT:
263 		return BN_num_bits(k->rsa->n);
264 	case KEY_DSA:
265 	case KEY_DSA_CERT:
266 		return BN_num_bits(k->dsa->p);
267 	case KEY_ECDSA:
268 	case KEY_ECDSA_CERT:
269 		return sshkey_curve_nid_to_bits(k->ecdsa_nid);
270 #endif /* WITH_OPENSSL */
271 	case KEY_ED25519:
272 	case KEY_ED25519_CERT:
273 		return 256;	/* XXX */
274 	}
275 	return 0;
276 }
277 
278 static int
279 sshkey_type_is_valid_ca(int type)
280 {
281 	switch (type) {
282 	case KEY_RSA:
283 	case KEY_DSA:
284 	case KEY_ECDSA:
285 	case KEY_ED25519:
286 		return 1;
287 	default:
288 		return 0;
289 	}
290 }
291 
292 int
293 sshkey_is_cert(const struct sshkey *k)
294 {
295 	if (k == NULL)
296 		return 0;
297 	return sshkey_type_is_cert(k->type);
298 }
299 
300 /* Return the cert-less equivalent to a certified key type */
301 int
302 sshkey_type_plain(int type)
303 {
304 	switch (type) {
305 	case KEY_RSA_CERT:
306 		return KEY_RSA;
307 	case KEY_DSA_CERT:
308 		return KEY_DSA;
309 	case KEY_ECDSA_CERT:
310 		return KEY_ECDSA;
311 	case KEY_ED25519_CERT:
312 		return KEY_ED25519;
313 	default:
314 		return type;
315 	}
316 }
317 
318 #ifdef WITH_OPENSSL
319 /* XXX: these are really begging for a table-driven approach */
320 int
321 sshkey_curve_name_to_nid(const char *name)
322 {
323 	if (strcmp(name, "nistp256") == 0)
324 		return NID_X9_62_prime256v1;
325 	else if (strcmp(name, "nistp384") == 0)
326 		return NID_secp384r1;
327 	else if (strcmp(name, "nistp521") == 0)
328 		return NID_secp521r1;
329 	else
330 		return -1;
331 }
332 
333 u_int
334 sshkey_curve_nid_to_bits(int nid)
335 {
336 	switch (nid) {
337 	case NID_X9_62_prime256v1:
338 		return 256;
339 	case NID_secp384r1:
340 		return 384;
341 	case NID_secp521r1:
342 		return 521;
343 	default:
344 		return 0;
345 	}
346 }
347 
348 int
349 sshkey_ecdsa_bits_to_nid(int bits)
350 {
351 	switch (bits) {
352 	case 256:
353 		return NID_X9_62_prime256v1;
354 	case 384:
355 		return NID_secp384r1;
356 	case 521:
357 		return NID_secp521r1;
358 	default:
359 		return -1;
360 	}
361 }
362 
363 const char *
364 sshkey_curve_nid_to_name(int nid)
365 {
366 	switch (nid) {
367 	case NID_X9_62_prime256v1:
368 		return "nistp256";
369 	case NID_secp384r1:
370 		return "nistp384";
371 	case NID_secp521r1:
372 		return "nistp521";
373 	default:
374 		return NULL;
375 	}
376 }
377 
378 int
379 sshkey_ec_nid_to_hash_alg(int nid)
380 {
381 	int kbits = sshkey_curve_nid_to_bits(nid);
382 
383 	if (kbits <= 0)
384 		return -1;
385 
386 	/* RFC5656 section 6.2.1 */
387 	if (kbits <= 256)
388 		return SSH_DIGEST_SHA256;
389 	else if (kbits <= 384)
390 		return SSH_DIGEST_SHA384;
391 	else
392 		return SSH_DIGEST_SHA512;
393 }
394 #endif /* WITH_OPENSSL */
395 
396 static void
397 cert_free(struct sshkey_cert *cert)
398 {
399 	u_int i;
400 
401 	if (cert == NULL)
402 		return;
403 	sshbuf_free(cert->certblob);
404 	sshbuf_free(cert->critical);
405 	sshbuf_free(cert->extensions);
406 	free(cert->key_id);
407 	for (i = 0; i < cert->nprincipals; i++)
408 		free(cert->principals[i]);
409 	free(cert->principals);
410 	sshkey_free(cert->signature_key);
411 	explicit_bzero(cert, sizeof(*cert));
412 	free(cert);
413 }
414 
415 static struct sshkey_cert *
416 cert_new(void)
417 {
418 	struct sshkey_cert *cert;
419 
420 	if ((cert = calloc(1, sizeof(*cert))) == NULL)
421 		return NULL;
422 	if ((cert->certblob = sshbuf_new()) == NULL ||
423 	    (cert->critical = sshbuf_new()) == NULL ||
424 	    (cert->extensions = sshbuf_new()) == NULL) {
425 		cert_free(cert);
426 		return NULL;
427 	}
428 	cert->key_id = NULL;
429 	cert->principals = NULL;
430 	cert->signature_key = NULL;
431 	return cert;
432 }
433 
434 struct sshkey *
435 sshkey_new(int type)
436 {
437 	struct sshkey *k;
438 #ifdef WITH_OPENSSL
439 	RSA *rsa;
440 	DSA *dsa;
441 #endif /* WITH_OPENSSL */
442 
443 	if ((k = calloc(1, sizeof(*k))) == NULL)
444 		return NULL;
445 	k->type = type;
446 	k->ecdsa = NULL;
447 	k->ecdsa_nid = -1;
448 	k->dsa = NULL;
449 	k->rsa = NULL;
450 	k->cert = NULL;
451 	k->ed25519_sk = NULL;
452 	k->ed25519_pk = NULL;
453 	switch (k->type) {
454 #ifdef WITH_OPENSSL
455 	case KEY_RSA1:
456 	case KEY_RSA:
457 	case KEY_RSA_CERT:
458 		if ((rsa = RSA_new()) == NULL ||
459 		    (rsa->n = BN_new()) == NULL ||
460 		    (rsa->e = BN_new()) == NULL) {
461 			if (rsa != NULL)
462 				RSA_free(rsa);
463 			free(k);
464 			return NULL;
465 		}
466 		k->rsa = rsa;
467 		break;
468 	case KEY_DSA:
469 	case KEY_DSA_CERT:
470 		if ((dsa = DSA_new()) == NULL ||
471 		    (dsa->p = BN_new()) == NULL ||
472 		    (dsa->q = BN_new()) == NULL ||
473 		    (dsa->g = BN_new()) == NULL ||
474 		    (dsa->pub_key = BN_new()) == NULL) {
475 			if (dsa != NULL)
476 				DSA_free(dsa);
477 			free(k);
478 			return NULL;
479 		}
480 		k->dsa = dsa;
481 		break;
482 	case KEY_ECDSA:
483 	case KEY_ECDSA_CERT:
484 		/* Cannot do anything until we know the group */
485 		break;
486 #endif /* WITH_OPENSSL */
487 	case KEY_ED25519:
488 	case KEY_ED25519_CERT:
489 		/* no need to prealloc */
490 		break;
491 	case KEY_UNSPEC:
492 		break;
493 	default:
494 		free(k);
495 		return NULL;
496 		break;
497 	}
498 
499 	if (sshkey_is_cert(k)) {
500 		if ((k->cert = cert_new()) == NULL) {
501 			sshkey_free(k);
502 			return NULL;
503 		}
504 	}
505 
506 	return k;
507 }
508 
509 int
510 sshkey_add_private(struct sshkey *k)
511 {
512 	switch (k->type) {
513 #ifdef WITH_OPENSSL
514 	case KEY_RSA1:
515 	case KEY_RSA:
516 	case KEY_RSA_CERT:
517 #define bn_maybe_alloc_failed(p) (p == NULL && (p = BN_new()) == NULL)
518 		if (bn_maybe_alloc_failed(k->rsa->d) ||
519 		    bn_maybe_alloc_failed(k->rsa->iqmp) ||
520 		    bn_maybe_alloc_failed(k->rsa->q) ||
521 		    bn_maybe_alloc_failed(k->rsa->p) ||
522 		    bn_maybe_alloc_failed(k->rsa->dmq1) ||
523 		    bn_maybe_alloc_failed(k->rsa->dmp1))
524 			return SSH_ERR_ALLOC_FAIL;
525 		break;
526 	case KEY_DSA:
527 	case KEY_DSA_CERT:
528 		if (bn_maybe_alloc_failed(k->dsa->priv_key))
529 			return SSH_ERR_ALLOC_FAIL;
530 		break;
531 #undef bn_maybe_alloc_failed
532 	case KEY_ECDSA:
533 	case KEY_ECDSA_CERT:
534 		/* Cannot do anything until we know the group */
535 		break;
536 #endif /* WITH_OPENSSL */
537 	case KEY_ED25519:
538 	case KEY_ED25519_CERT:
539 		/* no need to prealloc */
540 		break;
541 	case KEY_UNSPEC:
542 		break;
543 	default:
544 		return SSH_ERR_INVALID_ARGUMENT;
545 	}
546 	return 0;
547 }
548 
549 struct sshkey *
550 sshkey_new_private(int type)
551 {
552 	struct sshkey *k = sshkey_new(type);
553 
554 	if (k == NULL)
555 		return NULL;
556 	if (sshkey_add_private(k) != 0) {
557 		sshkey_free(k);
558 		return NULL;
559 	}
560 	return k;
561 }
562 
563 void
564 sshkey_free(struct sshkey *k)
565 {
566 	if (k == NULL)
567 		return;
568 	switch (k->type) {
569 #ifdef WITH_OPENSSL
570 	case KEY_RSA1:
571 	case KEY_RSA:
572 	case KEY_RSA_CERT:
573 		if (k->rsa != NULL)
574 			RSA_free(k->rsa);
575 		k->rsa = NULL;
576 		break;
577 	case KEY_DSA:
578 	case KEY_DSA_CERT:
579 		if (k->dsa != NULL)
580 			DSA_free(k->dsa);
581 		k->dsa = NULL;
582 		break;
583 	case KEY_ECDSA:
584 	case KEY_ECDSA_CERT:
585 		if (k->ecdsa != NULL)
586 			EC_KEY_free(k->ecdsa);
587 		k->ecdsa = NULL;
588 		break;
589 #endif /* WITH_OPENSSL */
590 	case KEY_ED25519:
591 	case KEY_ED25519_CERT:
592 		if (k->ed25519_pk) {
593 			explicit_bzero(k->ed25519_pk, ED25519_PK_SZ);
594 			free(k->ed25519_pk);
595 			k->ed25519_pk = NULL;
596 		}
597 		if (k->ed25519_sk) {
598 			explicit_bzero(k->ed25519_sk, ED25519_SK_SZ);
599 			free(k->ed25519_sk);
600 			k->ed25519_sk = NULL;
601 		}
602 		break;
603 	case KEY_UNSPEC:
604 		break;
605 	default:
606 		break;
607 	}
608 	if (sshkey_is_cert(k))
609 		cert_free(k->cert);
610 	explicit_bzero(k, sizeof(*k));
611 	free(k);
612 }
613 
614 static int
615 cert_compare(struct sshkey_cert *a, struct sshkey_cert *b)
616 {
617 	if (a == NULL && b == NULL)
618 		return 1;
619 	if (a == NULL || b == NULL)
620 		return 0;
621 	if (sshbuf_len(a->certblob) != sshbuf_len(b->certblob))
622 		return 0;
623 	if (timingsafe_bcmp(sshbuf_ptr(a->certblob), sshbuf_ptr(b->certblob),
624 	    sshbuf_len(a->certblob)) != 0)
625 		return 0;
626 	return 1;
627 }
628 
629 /*
630  * Compare public portions of key only, allowing comparisons between
631  * certificates and plain keys too.
632  */
633 int
634 sshkey_equal_public(const struct sshkey *a, const struct sshkey *b)
635 {
636 #ifdef WITH_OPENSSL
637 	BN_CTX *bnctx;
638 #endif /* WITH_OPENSSL */
639 
640 	if (a == NULL || b == NULL ||
641 	    sshkey_type_plain(a->type) != sshkey_type_plain(b->type))
642 		return 0;
643 
644 	switch (a->type) {
645 #ifdef WITH_OPENSSL
646 	case KEY_RSA1:
647 	case KEY_RSA_CERT:
648 	case KEY_RSA:
649 		return a->rsa != NULL && b->rsa != NULL &&
650 		    BN_cmp(a->rsa->e, b->rsa->e) == 0 &&
651 		    BN_cmp(a->rsa->n, b->rsa->n) == 0;
652 	case KEY_DSA_CERT:
653 	case KEY_DSA:
654 		return a->dsa != NULL && b->dsa != NULL &&
655 		    BN_cmp(a->dsa->p, b->dsa->p) == 0 &&
656 		    BN_cmp(a->dsa->q, b->dsa->q) == 0 &&
657 		    BN_cmp(a->dsa->g, b->dsa->g) == 0 &&
658 		    BN_cmp(a->dsa->pub_key, b->dsa->pub_key) == 0;
659 	case KEY_ECDSA_CERT:
660 	case KEY_ECDSA:
661 		if (a->ecdsa == NULL || b->ecdsa == NULL ||
662 		    EC_KEY_get0_public_key(a->ecdsa) == NULL ||
663 		    EC_KEY_get0_public_key(b->ecdsa) == NULL)
664 			return 0;
665 		if ((bnctx = BN_CTX_new()) == NULL)
666 			return 0;
667 		if (EC_GROUP_cmp(EC_KEY_get0_group(a->ecdsa),
668 		    EC_KEY_get0_group(b->ecdsa), bnctx) != 0 ||
669 		    EC_POINT_cmp(EC_KEY_get0_group(a->ecdsa),
670 		    EC_KEY_get0_public_key(a->ecdsa),
671 		    EC_KEY_get0_public_key(b->ecdsa), bnctx) != 0) {
672 			BN_CTX_free(bnctx);
673 			return 0;
674 		}
675 		BN_CTX_free(bnctx);
676 		return 1;
677 #endif /* WITH_OPENSSL */
678 	case KEY_ED25519:
679 	case KEY_ED25519_CERT:
680 		return a->ed25519_pk != NULL && b->ed25519_pk != NULL &&
681 		    memcmp(a->ed25519_pk, b->ed25519_pk, ED25519_PK_SZ) == 0;
682 	default:
683 		return 0;
684 	}
685 	/* NOTREACHED */
686 }
687 
688 int
689 sshkey_equal(const struct sshkey *a, const struct sshkey *b)
690 {
691 	if (a == NULL || b == NULL || a->type != b->type)
692 		return 0;
693 	if (sshkey_is_cert(a)) {
694 		if (!cert_compare(a->cert, b->cert))
695 			return 0;
696 	}
697 	return sshkey_equal_public(a, b);
698 }
699 
700 static int
701 to_blob_buf(const struct sshkey *key, struct sshbuf *b, int force_plain)
702 {
703 	int type, ret = SSH_ERR_INTERNAL_ERROR;
704 	const char *typename;
705 
706 	if (key == NULL)
707 		return SSH_ERR_INVALID_ARGUMENT;
708 
709 	if (sshkey_is_cert(key)) {
710 		if (key->cert == NULL)
711 			return SSH_ERR_EXPECTED_CERT;
712 		if (sshbuf_len(key->cert->certblob) == 0)
713 			return SSH_ERR_KEY_LACKS_CERTBLOB;
714 	}
715 	type = force_plain ? sshkey_type_plain(key->type) : key->type;
716 	typename = sshkey_ssh_name_from_type_nid(type, key->ecdsa_nid);
717 
718 	switch (type) {
719 #ifdef WITH_OPENSSL
720 	case KEY_DSA_CERT:
721 	case KEY_ECDSA_CERT:
722 	case KEY_RSA_CERT:
723 #endif /* WITH_OPENSSL */
724 	case KEY_ED25519_CERT:
725 		/* Use the existing blob */
726 		/* XXX modified flag? */
727 		if ((ret = sshbuf_putb(b, key->cert->certblob)) != 0)
728 			return ret;
729 		break;
730 #ifdef WITH_OPENSSL
731 	case KEY_DSA:
732 		if (key->dsa == NULL)
733 			return SSH_ERR_INVALID_ARGUMENT;
734 		if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
735 		    (ret = sshbuf_put_bignum2(b, key->dsa->p)) != 0 ||
736 		    (ret = sshbuf_put_bignum2(b, key->dsa->q)) != 0 ||
737 		    (ret = sshbuf_put_bignum2(b, key->dsa->g)) != 0 ||
738 		    (ret = sshbuf_put_bignum2(b, key->dsa->pub_key)) != 0)
739 			return ret;
740 		break;
741 	case KEY_ECDSA:
742 		if (key->ecdsa == NULL)
743 			return SSH_ERR_INVALID_ARGUMENT;
744 		if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
745 		    (ret = sshbuf_put_cstring(b,
746 		    sshkey_curve_nid_to_name(key->ecdsa_nid))) != 0 ||
747 		    (ret = sshbuf_put_eckey(b, key->ecdsa)) != 0)
748 			return ret;
749 		break;
750 	case KEY_RSA:
751 		if (key->rsa == NULL)
752 			return SSH_ERR_INVALID_ARGUMENT;
753 		if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
754 		    (ret = sshbuf_put_bignum2(b, key->rsa->e)) != 0 ||
755 		    (ret = sshbuf_put_bignum2(b, key->rsa->n)) != 0)
756 			return ret;
757 		break;
758 #endif /* WITH_OPENSSL */
759 	case KEY_ED25519:
760 		if (key->ed25519_pk == NULL)
761 			return SSH_ERR_INVALID_ARGUMENT;
762 		if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
763 		    (ret = sshbuf_put_string(b,
764 		    key->ed25519_pk, ED25519_PK_SZ)) != 0)
765 			return ret;
766 		break;
767 	default:
768 		return SSH_ERR_KEY_TYPE_UNKNOWN;
769 	}
770 	return 0;
771 }
772 
773 int
774 sshkey_putb(const struct sshkey *key, struct sshbuf *b)
775 {
776 	return to_blob_buf(key, b, 0);
777 }
778 
779 int
780 sshkey_puts(const struct sshkey *key, struct sshbuf *b)
781 {
782 	struct sshbuf *tmp;
783 	int r;
784 
785 	if ((tmp = sshbuf_new()) == NULL)
786 		return SSH_ERR_ALLOC_FAIL;
787 	r = to_blob_buf(key, tmp, 0);
788 	if (r == 0)
789 		r = sshbuf_put_stringb(b, tmp);
790 	sshbuf_free(tmp);
791 	return r;
792 }
793 
794 int
795 sshkey_putb_plain(const struct sshkey *key, struct sshbuf *b)
796 {
797 	return to_blob_buf(key, b, 1);
798 }
799 
800 static int
801 to_blob(const struct sshkey *key, u_char **blobp, size_t *lenp, int force_plain)
802 {
803 	int ret = SSH_ERR_INTERNAL_ERROR;
804 	size_t len;
805 	struct sshbuf *b = NULL;
806 
807 	if (lenp != NULL)
808 		*lenp = 0;
809 	if (blobp != NULL)
810 		*blobp = NULL;
811 	if ((b = sshbuf_new()) == NULL)
812 		return SSH_ERR_ALLOC_FAIL;
813 	if ((ret = to_blob_buf(key, b, force_plain)) != 0)
814 		goto out;
815 	len = sshbuf_len(b);
816 	if (lenp != NULL)
817 		*lenp = len;
818 	if (blobp != NULL) {
819 		if ((*blobp = malloc(len)) == NULL) {
820 			ret = SSH_ERR_ALLOC_FAIL;
821 			goto out;
822 		}
823 		memcpy(*blobp, sshbuf_ptr(b), len);
824 	}
825 	ret = 0;
826  out:
827 	sshbuf_free(b);
828 	return ret;
829 }
830 
831 int
832 sshkey_to_blob(const struct sshkey *key, u_char **blobp, size_t *lenp)
833 {
834 	return to_blob(key, blobp, lenp, 0);
835 }
836 
837 int
838 sshkey_plain_to_blob(const struct sshkey *key, u_char **blobp, size_t *lenp)
839 {
840 	return to_blob(key, blobp, lenp, 1);
841 }
842 
843 int
844 sshkey_fingerprint_raw(const struct sshkey *k, int dgst_alg,
845     u_char **retp, size_t *lenp)
846 {
847 	u_char *blob = NULL, *ret = NULL;
848 	size_t blob_len = 0;
849 	int r = SSH_ERR_INTERNAL_ERROR;
850 
851 	if (retp != NULL)
852 		*retp = NULL;
853 	if (lenp != NULL)
854 		*lenp = 0;
855 	if (ssh_digest_bytes(dgst_alg) == 0) {
856 		r = SSH_ERR_INVALID_ARGUMENT;
857 		goto out;
858 	}
859 
860 	if (k->type == KEY_RSA1) {
861 #ifdef WITH_OPENSSL
862 		int nlen = BN_num_bytes(k->rsa->n);
863 		int elen = BN_num_bytes(k->rsa->e);
864 
865 		blob_len = nlen + elen;
866 		if (nlen >= INT_MAX - elen ||
867 		    (blob = malloc(blob_len)) == NULL) {
868 			r = SSH_ERR_ALLOC_FAIL;
869 			goto out;
870 		}
871 		BN_bn2bin(k->rsa->n, blob);
872 		BN_bn2bin(k->rsa->e, blob + nlen);
873 #endif /* WITH_OPENSSL */
874 	} else if ((r = to_blob(k, &blob, &blob_len, 1)) != 0)
875 		goto out;
876 	if ((ret = calloc(1, SSH_DIGEST_MAX_LENGTH)) == NULL) {
877 		r = SSH_ERR_ALLOC_FAIL;
878 		goto out;
879 	}
880 	if ((r = ssh_digest_memory(dgst_alg, blob, blob_len,
881 	    ret, SSH_DIGEST_MAX_LENGTH)) != 0)
882 		goto out;
883 	/* success */
884 	if (retp != NULL) {
885 		*retp = ret;
886 		ret = NULL;
887 	}
888 	if (lenp != NULL)
889 		*lenp = ssh_digest_bytes(dgst_alg);
890 	r = 0;
891  out:
892 	free(ret);
893 	if (blob != NULL) {
894 		explicit_bzero(blob, blob_len);
895 		free(blob);
896 	}
897 	return r;
898 }
899 
900 static char *
901 fingerprint_b64(const char *alg, u_char *dgst_raw, size_t dgst_raw_len)
902 {
903 	char *ret;
904 	size_t plen = strlen(alg) + 1;
905 	size_t rlen = ((dgst_raw_len + 2) / 3) * 4 + plen + 1;
906 	int r;
907 
908 	if (dgst_raw_len > 65536 || (ret = calloc(1, rlen)) == NULL)
909 		return NULL;
910 	strlcpy(ret, alg, rlen);
911 	strlcat(ret, ":", rlen);
912 	if (dgst_raw_len == 0)
913 		return ret;
914 	if ((r = b64_ntop(dgst_raw, dgst_raw_len,
915 	    ret + plen, rlen - plen)) == -1) {
916 		explicit_bzero(ret, rlen);
917 		free(ret);
918 		return NULL;
919 	}
920 	/* Trim padding characters from end */
921 	ret[strcspn(ret, "=")] = '\0';
922 	return ret;
923 }
924 
925 static char *
926 fingerprint_hex(const char *alg, u_char *dgst_raw, size_t dgst_raw_len)
927 {
928 	char *retval, hex[5];
929 	size_t i, rlen = dgst_raw_len * 3 + strlen(alg) + 2;
930 
931 	if (dgst_raw_len > 65536 || (retval = calloc(1, rlen)) == NULL)
932 		return NULL;
933 	strlcpy(retval, alg, rlen);
934 	strlcat(retval, ":", rlen);
935 	for (i = 0; i < dgst_raw_len; i++) {
936 		snprintf(hex, sizeof(hex), "%s%02x",
937 		    i > 0 ? ":" : "", dgst_raw[i]);
938 		strlcat(retval, hex, rlen);
939 	}
940 	return retval;
941 }
942 
943 static char *
944 fingerprint_bubblebabble(u_char *dgst_raw, size_t dgst_raw_len)
945 {
946 	char vowels[] = { 'a', 'e', 'i', 'o', 'u', 'y' };
947 	char consonants[] = { 'b', 'c', 'd', 'f', 'g', 'h', 'k', 'l', 'm',
948 	    'n', 'p', 'r', 's', 't', 'v', 'z', 'x' };
949 	u_int i, j = 0, rounds, seed = 1;
950 	char *retval;
951 
952 	rounds = (dgst_raw_len / 2) + 1;
953 	if ((retval = calloc(rounds, 6)) == NULL)
954 		return NULL;
955 	retval[j++] = 'x';
956 	for (i = 0; i < rounds; i++) {
957 		u_int idx0, idx1, idx2, idx3, idx4;
958 		if ((i + 1 < rounds) || (dgst_raw_len % 2 != 0)) {
959 			idx0 = (((((u_int)(dgst_raw[2 * i])) >> 6) & 3) +
960 			    seed) % 6;
961 			idx1 = (((u_int)(dgst_raw[2 * i])) >> 2) & 15;
962 			idx2 = ((((u_int)(dgst_raw[2 * i])) & 3) +
963 			    (seed / 6)) % 6;
964 			retval[j++] = vowels[idx0];
965 			retval[j++] = consonants[idx1];
966 			retval[j++] = vowels[idx2];
967 			if ((i + 1) < rounds) {
968 				idx3 = (((u_int)(dgst_raw[(2 * i) + 1])) >> 4) & 15;
969 				idx4 = (((u_int)(dgst_raw[(2 * i) + 1]))) & 15;
970 				retval[j++] = consonants[idx3];
971 				retval[j++] = '-';
972 				retval[j++] = consonants[idx4];
973 				seed = ((seed * 5) +
974 				    ((((u_int)(dgst_raw[2 * i])) * 7) +
975 				    ((u_int)(dgst_raw[(2 * i) + 1])))) % 36;
976 			}
977 		} else {
978 			idx0 = seed % 6;
979 			idx1 = 16;
980 			idx2 = seed / 6;
981 			retval[j++] = vowels[idx0];
982 			retval[j++] = consonants[idx1];
983 			retval[j++] = vowels[idx2];
984 		}
985 	}
986 	retval[j++] = 'x';
987 	retval[j++] = '\0';
988 	return retval;
989 }
990 
991 /*
992  * Draw an ASCII-Art representing the fingerprint so human brain can
993  * profit from its built-in pattern recognition ability.
994  * This technique is called "random art" and can be found in some
995  * scientific publications like this original paper:
996  *
997  * "Hash Visualization: a New Technique to improve Real-World Security",
998  * Perrig A. and Song D., 1999, International Workshop on Cryptographic
999  * Techniques and E-Commerce (CrypTEC '99)
1000  * sparrow.ece.cmu.edu/~adrian/projects/validation/validation.pdf
1001  *
1002  * The subject came up in a talk by Dan Kaminsky, too.
1003  *
1004  * If you see the picture is different, the key is different.
1005  * If the picture looks the same, you still know nothing.
1006  *
1007  * The algorithm used here is a worm crawling over a discrete plane,
1008  * leaving a trace (augmenting the field) everywhere it goes.
1009  * Movement is taken from dgst_raw 2bit-wise.  Bumping into walls
1010  * makes the respective movement vector be ignored for this turn.
1011  * Graphs are not unambiguous, because circles in graphs can be
1012  * walked in either direction.
1013  */
1014 
1015 /*
1016  * Field sizes for the random art.  Have to be odd, so the starting point
1017  * can be in the exact middle of the picture, and FLDBASE should be >=8 .
1018  * Else pictures would be too dense, and drawing the frame would
1019  * fail, too, because the key type would not fit in anymore.
1020  */
1021 #define	FLDBASE		8
1022 #define	FLDSIZE_Y	(FLDBASE + 1)
1023 #define	FLDSIZE_X	(FLDBASE * 2 + 1)
1024 static char *
1025 fingerprint_randomart(const char *alg, u_char *dgst_raw, size_t dgst_raw_len,
1026     const struct sshkey *k)
1027 {
1028 	/*
1029 	 * Chars to be used after each other every time the worm
1030 	 * intersects with itself.  Matter of taste.
1031 	 */
1032 	char	*augmentation_string = " .o+=*BOX@%&#/^SE";
1033 	char	*retval, *p, title[FLDSIZE_X], hash[FLDSIZE_X];
1034 	u_char	 field[FLDSIZE_X][FLDSIZE_Y];
1035 	size_t	 i, tlen, hlen;
1036 	u_int	 b;
1037 	int	 x, y, r;
1038 	size_t	 len = strlen(augmentation_string) - 1;
1039 
1040 	if ((retval = calloc((FLDSIZE_X + 3), (FLDSIZE_Y + 2))) == NULL)
1041 		return NULL;
1042 
1043 	/* initialize field */
1044 	memset(field, 0, FLDSIZE_X * FLDSIZE_Y * sizeof(char));
1045 	x = FLDSIZE_X / 2;
1046 	y = FLDSIZE_Y / 2;
1047 
1048 	/* process raw key */
1049 	for (i = 0; i < dgst_raw_len; i++) {
1050 		int input;
1051 		/* each byte conveys four 2-bit move commands */
1052 		input = dgst_raw[i];
1053 		for (b = 0; b < 4; b++) {
1054 			/* evaluate 2 bit, rest is shifted later */
1055 			x += (input & 0x1) ? 1 : -1;
1056 			y += (input & 0x2) ? 1 : -1;
1057 
1058 			/* assure we are still in bounds */
1059 			x = MAX(x, 0);
1060 			y = MAX(y, 0);
1061 			x = MIN(x, FLDSIZE_X - 1);
1062 			y = MIN(y, FLDSIZE_Y - 1);
1063 
1064 			/* augment the field */
1065 			if (field[x][y] < len - 2)
1066 				field[x][y]++;
1067 			input = input >> 2;
1068 		}
1069 	}
1070 
1071 	/* mark starting point and end point*/
1072 	field[FLDSIZE_X / 2][FLDSIZE_Y / 2] = len - 1;
1073 	field[x][y] = len;
1074 
1075 	/* assemble title */
1076 	r = snprintf(title, sizeof(title), "[%s %u]",
1077 		sshkey_type(k), sshkey_size(k));
1078 	/* If [type size] won't fit, then try [type]; fits "[ED25519-CERT]" */
1079 	if (r < 0 || r > (int)sizeof(title))
1080 		r = snprintf(title, sizeof(title), "[%s]", sshkey_type(k));
1081 	tlen = (r <= 0) ? 0 : strlen(title);
1082 
1083 	/* assemble hash ID. */
1084 	r = snprintf(hash, sizeof(hash), "[%s]", alg);
1085 	hlen = (r <= 0) ? 0 : strlen(hash);
1086 
1087 	/* output upper border */
1088 	p = retval;
1089 	*p++ = '+';
1090 	for (i = 0; i < (FLDSIZE_X - tlen) / 2; i++)
1091 		*p++ = '-';
1092 	memcpy(p, title, tlen);
1093 	p += tlen;
1094 	for (i += tlen; i < FLDSIZE_X; i++)
1095 		*p++ = '-';
1096 	*p++ = '+';
1097 	*p++ = '\n';
1098 
1099 	/* output content */
1100 	for (y = 0; y < FLDSIZE_Y; y++) {
1101 		*p++ = '|';
1102 		for (x = 0; x < FLDSIZE_X; x++)
1103 			*p++ = augmentation_string[MIN(field[x][y], len)];
1104 		*p++ = '|';
1105 		*p++ = '\n';
1106 	}
1107 
1108 	/* output lower border */
1109 	*p++ = '+';
1110 	for (i = 0; i < (FLDSIZE_X - hlen) / 2; i++)
1111 		*p++ = '-';
1112 	memcpy(p, hash, hlen);
1113 	p += hlen;
1114 	for (i += hlen; i < FLDSIZE_X; i++)
1115 		*p++ = '-';
1116 	*p++ = '+';
1117 
1118 	return retval;
1119 }
1120 
1121 char *
1122 sshkey_fingerprint(const struct sshkey *k, int dgst_alg,
1123     enum sshkey_fp_rep dgst_rep)
1124 {
1125 	char *retval = NULL;
1126 	u_char *dgst_raw;
1127 	size_t dgst_raw_len;
1128 
1129 	if (sshkey_fingerprint_raw(k, dgst_alg, &dgst_raw, &dgst_raw_len) != 0)
1130 		return NULL;
1131 	switch (dgst_rep) {
1132 	case SSH_FP_DEFAULT:
1133 		if (dgst_alg == SSH_DIGEST_MD5) {
1134 			retval = fingerprint_hex(ssh_digest_alg_name(dgst_alg),
1135 			    dgst_raw, dgst_raw_len);
1136 		} else {
1137 			retval = fingerprint_b64(ssh_digest_alg_name(dgst_alg),
1138 			    dgst_raw, dgst_raw_len);
1139 		}
1140 		break;
1141 	case SSH_FP_HEX:
1142 		retval = fingerprint_hex(ssh_digest_alg_name(dgst_alg),
1143 		    dgst_raw, dgst_raw_len);
1144 		break;
1145 	case SSH_FP_BASE64:
1146 		retval = fingerprint_b64(ssh_digest_alg_name(dgst_alg),
1147 		    dgst_raw, dgst_raw_len);
1148 		break;
1149 	case SSH_FP_BUBBLEBABBLE:
1150 		retval = fingerprint_bubblebabble(dgst_raw, dgst_raw_len);
1151 		break;
1152 	case SSH_FP_RANDOMART:
1153 		retval = fingerprint_randomart(ssh_digest_alg_name(dgst_alg),
1154 		    dgst_raw, dgst_raw_len, k);
1155 		break;
1156 	default:
1157 		explicit_bzero(dgst_raw, dgst_raw_len);
1158 		free(dgst_raw);
1159 		return NULL;
1160 	}
1161 	explicit_bzero(dgst_raw, dgst_raw_len);
1162 	free(dgst_raw);
1163 	return retval;
1164 }
1165 
1166 #ifdef WITH_SSH1
1167 /*
1168  * Reads a multiple-precision integer in decimal from the buffer, and advances
1169  * the pointer.  The integer must already be initialized.  This function is
1170  * permitted to modify the buffer.  This leaves *cpp to point just beyond the
1171  * last processed character.
1172  */
1173 static int
1174 read_decimal_bignum(char **cpp, BIGNUM *v)
1175 {
1176 	char *cp;
1177 	size_t e;
1178 	int skip = 1;	/* skip white space */
1179 
1180 	cp = *cpp;
1181 	while (*cp == ' ' || *cp == '\t')
1182 		cp++;
1183 	e = strspn(cp, "0123456789");
1184 	if (e == 0)
1185 		return SSH_ERR_INVALID_FORMAT;
1186 	if (e > SSHBUF_MAX_BIGNUM * 3)
1187 		return SSH_ERR_BIGNUM_TOO_LARGE;
1188 	if (cp[e] == '\0')
1189 		skip = 0;
1190 	else if (strchr(" \t\r\n", cp[e]) == NULL)
1191 		return SSH_ERR_INVALID_FORMAT;
1192 	cp[e] = '\0';
1193 	if (BN_dec2bn(&v, cp) <= 0)
1194 		return SSH_ERR_INVALID_FORMAT;
1195 	*cpp = cp + e + skip;
1196 	return 0;
1197 }
1198 #endif /* WITH_SSH1 */
1199 
1200 /* returns 0 ok, and < 0 error */
1201 int
1202 sshkey_read(struct sshkey *ret, char **cpp)
1203 {
1204 	struct sshkey *k;
1205 	int retval = SSH_ERR_INVALID_FORMAT;
1206 	char *ep, *cp, *space;
1207 	int r, type, curve_nid = -1;
1208 	struct sshbuf *blob;
1209 #ifdef WITH_SSH1
1210 	u_long bits;
1211 #endif /* WITH_SSH1 */
1212 
1213 	cp = *cpp;
1214 
1215 	switch (ret->type) {
1216 	case KEY_RSA1:
1217 #ifdef WITH_SSH1
1218 		/* Get number of bits. */
1219 		bits = strtoul(cp, &ep, 10);
1220 		if (*cp == '\0' || strchr(" \t\r\n", *ep) == NULL ||
1221 		    bits == 0 || bits > SSHBUF_MAX_BIGNUM * 8)
1222 			return SSH_ERR_INVALID_FORMAT;	/* Bad bit count... */
1223 		/* Get public exponent, public modulus. */
1224 		if ((r = read_decimal_bignum(&ep, ret->rsa->e)) < 0)
1225 			return r;
1226 		if ((r = read_decimal_bignum(&ep, ret->rsa->n)) < 0)
1227 			return r;
1228 		/* validate the claimed number of bits */
1229 		if (BN_num_bits(ret->rsa->n) != (int)bits)
1230 			return SSH_ERR_KEY_BITS_MISMATCH;
1231 		*cpp = ep;
1232 		retval = 0;
1233 #endif /* WITH_SSH1 */
1234 		break;
1235 	case KEY_UNSPEC:
1236 	case KEY_RSA:
1237 	case KEY_DSA:
1238 	case KEY_ECDSA:
1239 	case KEY_ED25519:
1240 	case KEY_DSA_CERT:
1241 	case KEY_ECDSA_CERT:
1242 	case KEY_RSA_CERT:
1243 	case KEY_ED25519_CERT:
1244 		space = strchr(cp, ' ');
1245 		if (space == NULL)
1246 			return SSH_ERR_INVALID_FORMAT;
1247 		*space = '\0';
1248 		type = sshkey_type_from_name(cp);
1249 		if (sshkey_type_plain(type) == KEY_ECDSA &&
1250 		    (curve_nid = sshkey_ecdsa_nid_from_name(cp)) == -1)
1251 			return SSH_ERR_EC_CURVE_INVALID;
1252 		*space = ' ';
1253 		if (type == KEY_UNSPEC)
1254 			return SSH_ERR_INVALID_FORMAT;
1255 		cp = space+1;
1256 		if (*cp == '\0')
1257 			return SSH_ERR_INVALID_FORMAT;
1258 		if (ret->type != KEY_UNSPEC && ret->type != type)
1259 			return SSH_ERR_KEY_TYPE_MISMATCH;
1260 		if ((blob = sshbuf_new()) == NULL)
1261 			return SSH_ERR_ALLOC_FAIL;
1262 		/* trim comment */
1263 		space = strchr(cp, ' ');
1264 		if (space) {
1265 			/* advance 'space': skip whitespace */
1266 			*space++ = '\0';
1267 			while (*space == ' ' || *space == '\t')
1268 				space++;
1269 			ep = space;
1270 		} else
1271 			ep = cp + strlen(cp);
1272 		if ((r = sshbuf_b64tod(blob, cp)) != 0) {
1273 			sshbuf_free(blob);
1274 			return r;
1275 		}
1276 		if ((r = sshkey_from_blob(sshbuf_ptr(blob),
1277 		    sshbuf_len(blob), &k)) != 0) {
1278 			sshbuf_free(blob);
1279 			return r;
1280 		}
1281 		sshbuf_free(blob);
1282 		if (k->type != type) {
1283 			sshkey_free(k);
1284 			return SSH_ERR_KEY_TYPE_MISMATCH;
1285 		}
1286 		if (sshkey_type_plain(type) == KEY_ECDSA &&
1287 		    curve_nid != k->ecdsa_nid) {
1288 			sshkey_free(k);
1289 			return SSH_ERR_EC_CURVE_MISMATCH;
1290 		}
1291 		ret->type = type;
1292 		if (sshkey_is_cert(ret)) {
1293 			if (!sshkey_is_cert(k)) {
1294 				sshkey_free(k);
1295 				return SSH_ERR_EXPECTED_CERT;
1296 			}
1297 			if (ret->cert != NULL)
1298 				cert_free(ret->cert);
1299 			ret->cert = k->cert;
1300 			k->cert = NULL;
1301 		}
1302 		switch (sshkey_type_plain(ret->type)) {
1303 #ifdef WITH_OPENSSL
1304 		case KEY_RSA:
1305 			if (ret->rsa != NULL)
1306 				RSA_free(ret->rsa);
1307 			ret->rsa = k->rsa;
1308 			k->rsa = NULL;
1309 #ifdef DEBUG_PK
1310 			RSA_print_fp(stderr, ret->rsa, 8);
1311 #endif
1312 			break;
1313 		case KEY_DSA:
1314 			if (ret->dsa != NULL)
1315 				DSA_free(ret->dsa);
1316 			ret->dsa = k->dsa;
1317 			k->dsa = NULL;
1318 #ifdef DEBUG_PK
1319 			DSA_print_fp(stderr, ret->dsa, 8);
1320 #endif
1321 			break;
1322 		case KEY_ECDSA:
1323 			if (ret->ecdsa != NULL)
1324 				EC_KEY_free(ret->ecdsa);
1325 			ret->ecdsa = k->ecdsa;
1326 			ret->ecdsa_nid = k->ecdsa_nid;
1327 			k->ecdsa = NULL;
1328 			k->ecdsa_nid = -1;
1329 #ifdef DEBUG_PK
1330 			sshkey_dump_ec_key(ret->ecdsa);
1331 #endif
1332 			break;
1333 #endif /* WITH_OPENSSL */
1334 		case KEY_ED25519:
1335 			free(ret->ed25519_pk);
1336 			ret->ed25519_pk = k->ed25519_pk;
1337 			k->ed25519_pk = NULL;
1338 #ifdef DEBUG_PK
1339 			/* XXX */
1340 #endif
1341 			break;
1342 		}
1343 		*cpp = ep;
1344 		retval = 0;
1345 /*XXXX*/
1346 		sshkey_free(k);
1347 		if (retval != 0)
1348 			break;
1349 		break;
1350 	default:
1351 		return SSH_ERR_INVALID_ARGUMENT;
1352 	}
1353 	return retval;
1354 }
1355 
1356 int
1357 sshkey_to_base64(const struct sshkey *key, char **b64p)
1358 {
1359 	int r = SSH_ERR_INTERNAL_ERROR;
1360 	struct sshbuf *b = NULL;
1361 	char *uu = NULL;
1362 
1363 	if (b64p != NULL)
1364 		*b64p = NULL;
1365 	if ((b = sshbuf_new()) == NULL)
1366 		return SSH_ERR_ALLOC_FAIL;
1367 	if ((r = sshkey_putb(key, b)) != 0)
1368 		goto out;
1369 	if ((uu = sshbuf_dtob64(b)) == NULL) {
1370 		r = SSH_ERR_ALLOC_FAIL;
1371 		goto out;
1372 	}
1373 	/* Success */
1374 	if (b64p != NULL) {
1375 		*b64p = uu;
1376 		uu = NULL;
1377 	}
1378 	r = 0;
1379  out:
1380 	sshbuf_free(b);
1381 	free(uu);
1382 	return r;
1383 }
1384 
1385 static int
1386 sshkey_format_rsa1(const struct sshkey *key, struct sshbuf *b)
1387 {
1388 	int r = SSH_ERR_INTERNAL_ERROR;
1389 #ifdef WITH_SSH1
1390 	u_int bits = 0;
1391 	char *dec_e = NULL, *dec_n = NULL;
1392 
1393 	if (key->rsa == NULL || key->rsa->e == NULL ||
1394 	    key->rsa->n == NULL) {
1395 		r = SSH_ERR_INVALID_ARGUMENT;
1396 		goto out;
1397 	}
1398 	if ((dec_e = BN_bn2dec(key->rsa->e)) == NULL ||
1399 	    (dec_n = BN_bn2dec(key->rsa->n)) == NULL) {
1400 		r = SSH_ERR_ALLOC_FAIL;
1401 		goto out;
1402 	}
1403 	/* size of modulus 'n' */
1404 	if ((bits = BN_num_bits(key->rsa->n)) <= 0) {
1405 		r = SSH_ERR_INVALID_ARGUMENT;
1406 		goto out;
1407 	}
1408 	if ((r = sshbuf_putf(b, "%u %s %s", bits, dec_e, dec_n)) != 0)
1409 		goto out;
1410 
1411 	/* Success */
1412 	r = 0;
1413  out:
1414 	if (dec_e != NULL)
1415 		OPENSSL_free(dec_e);
1416 	if (dec_n != NULL)
1417 		OPENSSL_free(dec_n);
1418 #endif /* WITH_SSH1 */
1419 
1420 	return r;
1421 }
1422 
1423 static int
1424 sshkey_format_text(const struct sshkey *key, struct sshbuf *b)
1425 {
1426 	int r = SSH_ERR_INTERNAL_ERROR;
1427 	char *uu = NULL;
1428 
1429 	if (key->type == KEY_RSA1) {
1430 		if ((r = sshkey_format_rsa1(key, b)) != 0)
1431 			goto out;
1432 	} else {
1433 		/* Unsupported key types handled in sshkey_to_base64() */
1434 		if ((r = sshkey_to_base64(key, &uu)) != 0)
1435 			goto out;
1436 		if ((r = sshbuf_putf(b, "%s %s",
1437 		    sshkey_ssh_name(key), uu)) != 0)
1438 			goto out;
1439 	}
1440 	r = 0;
1441  out:
1442 	free(uu);
1443 	return r;
1444 }
1445 
1446 int
1447 sshkey_write(const struct sshkey *key, FILE *f)
1448 {
1449 	struct sshbuf *b = NULL;
1450 	int r = SSH_ERR_INTERNAL_ERROR;
1451 
1452 	if ((b = sshbuf_new()) == NULL)
1453 		return SSH_ERR_ALLOC_FAIL;
1454 	if ((r = sshkey_format_text(key, b)) != 0)
1455 		goto out;
1456 	if (fwrite(sshbuf_ptr(b), sshbuf_len(b), 1, f) != 1) {
1457 		if (feof(f))
1458 			errno = EPIPE;
1459 		r = SSH_ERR_SYSTEM_ERROR;
1460 		goto out;
1461 	}
1462 	/* Success */
1463 	r = 0;
1464  out:
1465 	sshbuf_free(b);
1466 	return r;
1467 }
1468 
1469 const char *
1470 sshkey_cert_type(const struct sshkey *k)
1471 {
1472 	switch (k->cert->type) {
1473 	case SSH2_CERT_TYPE_USER:
1474 		return "user";
1475 	case SSH2_CERT_TYPE_HOST:
1476 		return "host";
1477 	default:
1478 		return "unknown";
1479 	}
1480 }
1481 
1482 #ifdef WITH_OPENSSL
1483 static int
1484 rsa_generate_private_key(u_int bits, RSA **rsap)
1485 {
1486 	RSA *private = NULL;
1487 	BIGNUM *f4 = NULL;
1488 	int ret = SSH_ERR_INTERNAL_ERROR;
1489 
1490 	if (rsap == NULL ||
1491 	    bits < SSH_RSA_MINIMUM_MODULUS_SIZE ||
1492 	    bits > SSHBUF_MAX_BIGNUM * 8)
1493 		return SSH_ERR_INVALID_ARGUMENT;
1494 	*rsap = NULL;
1495 	if ((private = RSA_new()) == NULL || (f4 = BN_new()) == NULL) {
1496 		ret = SSH_ERR_ALLOC_FAIL;
1497 		goto out;
1498 	}
1499 	if (!BN_set_word(f4, RSA_F4) ||
1500 	    !RSA_generate_key_ex(private, bits, f4, NULL)) {
1501 		ret = SSH_ERR_LIBCRYPTO_ERROR;
1502 		goto out;
1503 	}
1504 	*rsap = private;
1505 	private = NULL;
1506 	ret = 0;
1507  out:
1508 	if (private != NULL)
1509 		RSA_free(private);
1510 	if (f4 != NULL)
1511 		BN_free(f4);
1512 	return ret;
1513 }
1514 
1515 static int
1516 dsa_generate_private_key(u_int bits, DSA **dsap)
1517 {
1518 	DSA *private;
1519 	int ret = SSH_ERR_INTERNAL_ERROR;
1520 
1521 	if (dsap == NULL || bits != 1024)
1522 		return SSH_ERR_INVALID_ARGUMENT;
1523 	if ((private = DSA_new()) == NULL) {
1524 		ret = SSH_ERR_ALLOC_FAIL;
1525 		goto out;
1526 	}
1527 	*dsap = NULL;
1528 	if (!DSA_generate_parameters_ex(private, bits, NULL, 0, NULL,
1529 	    NULL, NULL) || !DSA_generate_key(private)) {
1530 		ret = SSH_ERR_LIBCRYPTO_ERROR;
1531 		goto out;
1532 	}
1533 	*dsap = private;
1534 	private = NULL;
1535 	ret = 0;
1536  out:
1537 	if (private != NULL)
1538 		DSA_free(private);
1539 	return ret;
1540 }
1541 
1542 int
1543 sshkey_ecdsa_key_to_nid(EC_KEY *k)
1544 {
1545 	EC_GROUP *eg;
1546 	int nids[] = {
1547 		NID_X9_62_prime256v1,
1548 		NID_secp384r1,
1549 		NID_secp521r1,
1550 		-1
1551 	};
1552 	int nid;
1553 	u_int i;
1554 	BN_CTX *bnctx;
1555 	const EC_GROUP *g = EC_KEY_get0_group(k);
1556 
1557 	/*
1558 	 * The group may be stored in a ASN.1 encoded private key in one of two
1559 	 * ways: as a "named group", which is reconstituted by ASN.1 object ID
1560 	 * or explicit group parameters encoded into the key blob. Only the
1561 	 * "named group" case sets the group NID for us, but we can figure
1562 	 * it out for the other case by comparing against all the groups that
1563 	 * are supported.
1564 	 */
1565 	if ((nid = EC_GROUP_get_curve_name(g)) > 0)
1566 		return nid;
1567 	if ((bnctx = BN_CTX_new()) == NULL)
1568 		return -1;
1569 	for (i = 0; nids[i] != -1; i++) {
1570 		if ((eg = EC_GROUP_new_by_curve_name(nids[i])) == NULL) {
1571 			BN_CTX_free(bnctx);
1572 			return -1;
1573 		}
1574 		if (EC_GROUP_cmp(g, eg, bnctx) == 0)
1575 			break;
1576 		EC_GROUP_free(eg);
1577 	}
1578 	BN_CTX_free(bnctx);
1579 	if (nids[i] != -1) {
1580 		/* Use the group with the NID attached */
1581 		EC_GROUP_set_asn1_flag(eg, OPENSSL_EC_NAMED_CURVE);
1582 		if (EC_KEY_set_group(k, eg) != 1) {
1583 			EC_GROUP_free(eg);
1584 			return -1;
1585 		}
1586 	}
1587 	return nids[i];
1588 }
1589 
1590 static int
1591 ecdsa_generate_private_key(u_int bits, int *nid, EC_KEY **ecdsap)
1592 {
1593 	EC_KEY *private;
1594 	int ret = SSH_ERR_INTERNAL_ERROR;
1595 
1596 	if (nid == NULL || ecdsap == NULL ||
1597 	    (*nid = sshkey_ecdsa_bits_to_nid(bits)) == -1)
1598 		return SSH_ERR_INVALID_ARGUMENT;
1599 	*ecdsap = NULL;
1600 	if ((private = EC_KEY_new_by_curve_name(*nid)) == NULL) {
1601 		ret = SSH_ERR_ALLOC_FAIL;
1602 		goto out;
1603 	}
1604 	if (EC_KEY_generate_key(private) != 1) {
1605 		ret = SSH_ERR_LIBCRYPTO_ERROR;
1606 		goto out;
1607 	}
1608 	EC_KEY_set_asn1_flag(private, OPENSSL_EC_NAMED_CURVE);
1609 	*ecdsap = private;
1610 	private = NULL;
1611 	ret = 0;
1612  out:
1613 	if (private != NULL)
1614 		EC_KEY_free(private);
1615 	return ret;
1616 }
1617 #endif /* WITH_OPENSSL */
1618 
1619 int
1620 sshkey_generate(int type, u_int bits, struct sshkey **keyp)
1621 {
1622 	struct sshkey *k;
1623 	int ret = SSH_ERR_INTERNAL_ERROR;
1624 
1625 	if (keyp == NULL)
1626 		return SSH_ERR_INVALID_ARGUMENT;
1627 	*keyp = NULL;
1628 	if ((k = sshkey_new(KEY_UNSPEC)) == NULL)
1629 		return SSH_ERR_ALLOC_FAIL;
1630 	switch (type) {
1631 	case KEY_ED25519:
1632 		if ((k->ed25519_pk = malloc(ED25519_PK_SZ)) == NULL ||
1633 		    (k->ed25519_sk = malloc(ED25519_SK_SZ)) == NULL) {
1634 			ret = SSH_ERR_ALLOC_FAIL;
1635 			break;
1636 		}
1637 		crypto_sign_ed25519_keypair(k->ed25519_pk, k->ed25519_sk);
1638 		ret = 0;
1639 		break;
1640 #ifdef WITH_OPENSSL
1641 	case KEY_DSA:
1642 		ret = dsa_generate_private_key(bits, &k->dsa);
1643 		break;
1644 	case KEY_ECDSA:
1645 		ret = ecdsa_generate_private_key(bits, &k->ecdsa_nid,
1646 		    &k->ecdsa);
1647 		break;
1648 	case KEY_RSA:
1649 	case KEY_RSA1:
1650 		ret = rsa_generate_private_key(bits, &k->rsa);
1651 		break;
1652 #endif /* WITH_OPENSSL */
1653 	default:
1654 		ret = SSH_ERR_INVALID_ARGUMENT;
1655 	}
1656 	if (ret == 0) {
1657 		k->type = type;
1658 		*keyp = k;
1659 	} else
1660 		sshkey_free(k);
1661 	return ret;
1662 }
1663 
1664 int
1665 sshkey_cert_copy(const struct sshkey *from_key, struct sshkey *to_key)
1666 {
1667 	u_int i;
1668 	const struct sshkey_cert *from;
1669 	struct sshkey_cert *to;
1670 	int ret = SSH_ERR_INTERNAL_ERROR;
1671 
1672 	if (to_key->cert != NULL) {
1673 		cert_free(to_key->cert);
1674 		to_key->cert = NULL;
1675 	}
1676 
1677 	if ((from = from_key->cert) == NULL)
1678 		return SSH_ERR_INVALID_ARGUMENT;
1679 
1680 	if ((to = to_key->cert = cert_new()) == NULL)
1681 		return SSH_ERR_ALLOC_FAIL;
1682 
1683 	if ((ret = sshbuf_putb(to->certblob, from->certblob)) != 0 ||
1684 	    (ret = sshbuf_putb(to->critical, from->critical)) != 0 ||
1685 	    (ret = sshbuf_putb(to->extensions, from->extensions)) != 0)
1686 		return ret;
1687 
1688 	to->serial = from->serial;
1689 	to->type = from->type;
1690 	if (from->key_id == NULL)
1691 		to->key_id = NULL;
1692 	else if ((to->key_id = strdup(from->key_id)) == NULL)
1693 		return SSH_ERR_ALLOC_FAIL;
1694 	to->valid_after = from->valid_after;
1695 	to->valid_before = from->valid_before;
1696 	if (from->signature_key == NULL)
1697 		to->signature_key = NULL;
1698 	else if ((ret = sshkey_from_private(from->signature_key,
1699 	    &to->signature_key)) != 0)
1700 		return ret;
1701 
1702 	if (from->nprincipals > SSHKEY_CERT_MAX_PRINCIPALS)
1703 		return SSH_ERR_INVALID_ARGUMENT;
1704 	if (from->nprincipals > 0) {
1705 		if ((to->principals = calloc(from->nprincipals,
1706 		    sizeof(*to->principals))) == NULL)
1707 			return SSH_ERR_ALLOC_FAIL;
1708 		for (i = 0; i < from->nprincipals; i++) {
1709 			to->principals[i] = strdup(from->principals[i]);
1710 			if (to->principals[i] == NULL) {
1711 				to->nprincipals = i;
1712 				return SSH_ERR_ALLOC_FAIL;
1713 			}
1714 		}
1715 	}
1716 	to->nprincipals = from->nprincipals;
1717 	return 0;
1718 }
1719 
1720 int
1721 sshkey_from_private(const struct sshkey *k, struct sshkey **pkp)
1722 {
1723 	struct sshkey *n = NULL;
1724 	int ret = SSH_ERR_INTERNAL_ERROR;
1725 
1726 	*pkp = NULL;
1727 	switch (k->type) {
1728 #ifdef WITH_OPENSSL
1729 	case KEY_DSA:
1730 	case KEY_DSA_CERT:
1731 		if ((n = sshkey_new(k->type)) == NULL)
1732 			return SSH_ERR_ALLOC_FAIL;
1733 		if ((BN_copy(n->dsa->p, k->dsa->p) == NULL) ||
1734 		    (BN_copy(n->dsa->q, k->dsa->q) == NULL) ||
1735 		    (BN_copy(n->dsa->g, k->dsa->g) == NULL) ||
1736 		    (BN_copy(n->dsa->pub_key, k->dsa->pub_key) == NULL)) {
1737 			sshkey_free(n);
1738 			return SSH_ERR_ALLOC_FAIL;
1739 		}
1740 		break;
1741 	case KEY_ECDSA:
1742 	case KEY_ECDSA_CERT:
1743 		if ((n = sshkey_new(k->type)) == NULL)
1744 			return SSH_ERR_ALLOC_FAIL;
1745 		n->ecdsa_nid = k->ecdsa_nid;
1746 		n->ecdsa = EC_KEY_new_by_curve_name(k->ecdsa_nid);
1747 		if (n->ecdsa == NULL) {
1748 			sshkey_free(n);
1749 			return SSH_ERR_ALLOC_FAIL;
1750 		}
1751 		if (EC_KEY_set_public_key(n->ecdsa,
1752 		    EC_KEY_get0_public_key(k->ecdsa)) != 1) {
1753 			sshkey_free(n);
1754 			return SSH_ERR_LIBCRYPTO_ERROR;
1755 		}
1756 		break;
1757 	case KEY_RSA:
1758 	case KEY_RSA1:
1759 	case KEY_RSA_CERT:
1760 		if ((n = sshkey_new(k->type)) == NULL)
1761 			return SSH_ERR_ALLOC_FAIL;
1762 		if ((BN_copy(n->rsa->n, k->rsa->n) == NULL) ||
1763 		    (BN_copy(n->rsa->e, k->rsa->e) == NULL)) {
1764 			sshkey_free(n);
1765 			return SSH_ERR_ALLOC_FAIL;
1766 		}
1767 		break;
1768 #endif /* WITH_OPENSSL */
1769 	case KEY_ED25519:
1770 	case KEY_ED25519_CERT:
1771 		if ((n = sshkey_new(k->type)) == NULL)
1772 			return SSH_ERR_ALLOC_FAIL;
1773 		if (k->ed25519_pk != NULL) {
1774 			if ((n->ed25519_pk = malloc(ED25519_PK_SZ)) == NULL) {
1775 				sshkey_free(n);
1776 				return SSH_ERR_ALLOC_FAIL;
1777 			}
1778 			memcpy(n->ed25519_pk, k->ed25519_pk, ED25519_PK_SZ);
1779 		}
1780 		break;
1781 	default:
1782 		return SSH_ERR_KEY_TYPE_UNKNOWN;
1783 	}
1784 	if (sshkey_is_cert(k)) {
1785 		if ((ret = sshkey_cert_copy(k, n)) != 0) {
1786 			sshkey_free(n);
1787 			return ret;
1788 		}
1789 	}
1790 	*pkp = n;
1791 	return 0;
1792 }
1793 
1794 static int
1795 cert_parse(struct sshbuf *b, struct sshkey *key, struct sshbuf *certbuf)
1796 {
1797 	struct sshbuf *principals = NULL, *crit = NULL;
1798 	struct sshbuf *exts = NULL, *ca = NULL;
1799 	u_char *sig = NULL;
1800 	size_t signed_len = 0, slen = 0, kidlen = 0;
1801 	int ret = SSH_ERR_INTERNAL_ERROR;
1802 
1803 	/* Copy the entire key blob for verification and later serialisation */
1804 	if ((ret = sshbuf_putb(key->cert->certblob, certbuf)) != 0)
1805 		return ret;
1806 
1807 	/* Parse body of certificate up to signature */
1808 	if ((ret = sshbuf_get_u64(b, &key->cert->serial)) != 0 ||
1809 	    (ret = sshbuf_get_u32(b, &key->cert->type)) != 0 ||
1810 	    (ret = sshbuf_get_cstring(b, &key->cert->key_id, &kidlen)) != 0 ||
1811 	    (ret = sshbuf_froms(b, &principals)) != 0 ||
1812 	    (ret = sshbuf_get_u64(b, &key->cert->valid_after)) != 0 ||
1813 	    (ret = sshbuf_get_u64(b, &key->cert->valid_before)) != 0 ||
1814 	    (ret = sshbuf_froms(b, &crit)) != 0 ||
1815 	    (ret = sshbuf_froms(b, &exts)) != 0 ||
1816 	    (ret = sshbuf_get_string_direct(b, NULL, NULL)) != 0 ||
1817 	    (ret = sshbuf_froms(b, &ca)) != 0) {
1818 		/* XXX debug print error for ret */
1819 		ret = SSH_ERR_INVALID_FORMAT;
1820 		goto out;
1821 	}
1822 
1823 	/* Signature is left in the buffer so we can calculate this length */
1824 	signed_len = sshbuf_len(key->cert->certblob) - sshbuf_len(b);
1825 
1826 	if ((ret = sshbuf_get_string(b, &sig, &slen)) != 0) {
1827 		ret = SSH_ERR_INVALID_FORMAT;
1828 		goto out;
1829 	}
1830 
1831 	if (key->cert->type != SSH2_CERT_TYPE_USER &&
1832 	    key->cert->type != SSH2_CERT_TYPE_HOST) {
1833 		ret = SSH_ERR_KEY_CERT_UNKNOWN_TYPE;
1834 		goto out;
1835 	}
1836 
1837 	/* Parse principals section */
1838 	while (sshbuf_len(principals) > 0) {
1839 		char *principal = NULL;
1840 		char **oprincipals = NULL;
1841 
1842 		if (key->cert->nprincipals >= SSHKEY_CERT_MAX_PRINCIPALS) {
1843 			ret = SSH_ERR_INVALID_FORMAT;
1844 			goto out;
1845 		}
1846 		if ((ret = sshbuf_get_cstring(principals, &principal,
1847 		    NULL)) != 0) {
1848 			ret = SSH_ERR_INVALID_FORMAT;
1849 			goto out;
1850 		}
1851 		oprincipals = key->cert->principals;
1852 		key->cert->principals = reallocarray(key->cert->principals,
1853 		    key->cert->nprincipals + 1, sizeof(*key->cert->principals));
1854 		if (key->cert->principals == NULL) {
1855 			free(principal);
1856 			key->cert->principals = oprincipals;
1857 			ret = SSH_ERR_ALLOC_FAIL;
1858 			goto out;
1859 		}
1860 		key->cert->principals[key->cert->nprincipals++] = principal;
1861 	}
1862 
1863 	/*
1864 	 * Stash a copies of the critical options and extensions sections
1865 	 * for later use.
1866 	 */
1867 	if ((ret = sshbuf_putb(key->cert->critical, crit)) != 0 ||
1868 	    (exts != NULL &&
1869 	    (ret = sshbuf_putb(key->cert->extensions, exts)) != 0))
1870 		goto out;
1871 
1872 	/*
1873 	 * Validate critical options and extensions sections format.
1874 	 */
1875 	while (sshbuf_len(crit) != 0) {
1876 		if ((ret = sshbuf_get_string_direct(crit, NULL, NULL)) != 0 ||
1877 		    (ret = sshbuf_get_string_direct(crit, NULL, NULL)) != 0) {
1878 			sshbuf_reset(key->cert->critical);
1879 			ret = SSH_ERR_INVALID_FORMAT;
1880 			goto out;
1881 		}
1882 	}
1883 	while (exts != NULL && sshbuf_len(exts) != 0) {
1884 		if ((ret = sshbuf_get_string_direct(exts, NULL, NULL)) != 0 ||
1885 		    (ret = sshbuf_get_string_direct(exts, NULL, NULL)) != 0) {
1886 			sshbuf_reset(key->cert->extensions);
1887 			ret = SSH_ERR_INVALID_FORMAT;
1888 			goto out;
1889 		}
1890 	}
1891 
1892 	/* Parse CA key and check signature */
1893 	if (sshkey_from_blob_internal(ca, &key->cert->signature_key, 0) != 0) {
1894 		ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
1895 		goto out;
1896 	}
1897 	if (!sshkey_type_is_valid_ca(key->cert->signature_key->type)) {
1898 		ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
1899 		goto out;
1900 	}
1901 	if ((ret = sshkey_verify(key->cert->signature_key, sig, slen,
1902 	    sshbuf_ptr(key->cert->certblob), signed_len, 0)) != 0)
1903 		goto out;
1904 
1905 	/* Success */
1906 	ret = 0;
1907  out:
1908 	sshbuf_free(ca);
1909 	sshbuf_free(crit);
1910 	sshbuf_free(exts);
1911 	sshbuf_free(principals);
1912 	free(sig);
1913 	return ret;
1914 }
1915 
1916 static int
1917 sshkey_from_blob_internal(struct sshbuf *b, struct sshkey **keyp,
1918     int allow_cert)
1919 {
1920 	int type, ret = SSH_ERR_INTERNAL_ERROR;
1921 	char *ktype = NULL, *curve = NULL;
1922 	struct sshkey *key = NULL;
1923 	size_t len;
1924 	u_char *pk = NULL;
1925 	struct sshbuf *copy;
1926 #ifdef WITH_OPENSSL
1927 	EC_POINT *q = NULL;
1928 #endif /* WITH_OPENSSL */
1929 
1930 #ifdef DEBUG_PK /* XXX */
1931 	sshbuf_dump(b, stderr);
1932 #endif
1933 	if (keyp != NULL)
1934 		*keyp = NULL;
1935 	if ((copy = sshbuf_fromb(b)) == NULL) {
1936 		ret = SSH_ERR_ALLOC_FAIL;
1937 		goto out;
1938 	}
1939 	if (sshbuf_get_cstring(b, &ktype, NULL) != 0) {
1940 		ret = SSH_ERR_INVALID_FORMAT;
1941 		goto out;
1942 	}
1943 
1944 	type = sshkey_type_from_name(ktype);
1945 	if (!allow_cert && sshkey_type_is_cert(type)) {
1946 		ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
1947 		goto out;
1948 	}
1949 	switch (type) {
1950 #ifdef WITH_OPENSSL
1951 	case KEY_RSA_CERT:
1952 		/* Skip nonce */
1953 		if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
1954 			ret = SSH_ERR_INVALID_FORMAT;
1955 			goto out;
1956 		}
1957 		/* FALLTHROUGH */
1958 	case KEY_RSA:
1959 		if ((key = sshkey_new(type)) == NULL) {
1960 			ret = SSH_ERR_ALLOC_FAIL;
1961 			goto out;
1962 		}
1963 		if (sshbuf_get_bignum2(b, key->rsa->e) != 0 ||
1964 		    sshbuf_get_bignum2(b, key->rsa->n) != 0) {
1965 			ret = SSH_ERR_INVALID_FORMAT;
1966 			goto out;
1967 		}
1968 #ifdef DEBUG_PK
1969 		RSA_print_fp(stderr, key->rsa, 8);
1970 #endif
1971 		break;
1972 	case KEY_DSA_CERT:
1973 		/* Skip nonce */
1974 		if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
1975 			ret = SSH_ERR_INVALID_FORMAT;
1976 			goto out;
1977 		}
1978 		/* FALLTHROUGH */
1979 	case KEY_DSA:
1980 		if ((key = sshkey_new(type)) == NULL) {
1981 			ret = SSH_ERR_ALLOC_FAIL;
1982 			goto out;
1983 		}
1984 		if (sshbuf_get_bignum2(b, key->dsa->p) != 0 ||
1985 		    sshbuf_get_bignum2(b, key->dsa->q) != 0 ||
1986 		    sshbuf_get_bignum2(b, key->dsa->g) != 0 ||
1987 		    sshbuf_get_bignum2(b, key->dsa->pub_key) != 0) {
1988 			ret = SSH_ERR_INVALID_FORMAT;
1989 			goto out;
1990 		}
1991 #ifdef DEBUG_PK
1992 		DSA_print_fp(stderr, key->dsa, 8);
1993 #endif
1994 		break;
1995 	case KEY_ECDSA_CERT:
1996 		/* Skip nonce */
1997 		if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
1998 			ret = SSH_ERR_INVALID_FORMAT;
1999 			goto out;
2000 		}
2001 		/* FALLTHROUGH */
2002 	case KEY_ECDSA:
2003 		if ((key = sshkey_new(type)) == NULL) {
2004 			ret = SSH_ERR_ALLOC_FAIL;
2005 			goto out;
2006 		}
2007 		key->ecdsa_nid = sshkey_ecdsa_nid_from_name(ktype);
2008 		if (sshbuf_get_cstring(b, &curve, NULL) != 0) {
2009 			ret = SSH_ERR_INVALID_FORMAT;
2010 			goto out;
2011 		}
2012 		if (key->ecdsa_nid != sshkey_curve_name_to_nid(curve)) {
2013 			ret = SSH_ERR_EC_CURVE_MISMATCH;
2014 			goto out;
2015 		}
2016 		if (key->ecdsa != NULL)
2017 			EC_KEY_free(key->ecdsa);
2018 		if ((key->ecdsa = EC_KEY_new_by_curve_name(key->ecdsa_nid))
2019 		    == NULL) {
2020 			ret = SSH_ERR_EC_CURVE_INVALID;
2021 			goto out;
2022 		}
2023 		if ((q = EC_POINT_new(EC_KEY_get0_group(key->ecdsa))) == NULL) {
2024 			ret = SSH_ERR_ALLOC_FAIL;
2025 			goto out;
2026 		}
2027 		if (sshbuf_get_ec(b, q, EC_KEY_get0_group(key->ecdsa)) != 0) {
2028 			ret = SSH_ERR_INVALID_FORMAT;
2029 			goto out;
2030 		}
2031 		if (sshkey_ec_validate_public(EC_KEY_get0_group(key->ecdsa),
2032 		    q) != 0) {
2033 			ret = SSH_ERR_KEY_INVALID_EC_VALUE;
2034 			goto out;
2035 		}
2036 		if (EC_KEY_set_public_key(key->ecdsa, q) != 1) {
2037 			/* XXX assume it is a allocation error */
2038 			ret = SSH_ERR_ALLOC_FAIL;
2039 			goto out;
2040 		}
2041 #ifdef DEBUG_PK
2042 		sshkey_dump_ec_point(EC_KEY_get0_group(key->ecdsa), q);
2043 #endif
2044 		break;
2045 #endif /* WITH_OPENSSL */
2046 	case KEY_ED25519_CERT:
2047 		/* Skip nonce */
2048 		if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
2049 			ret = SSH_ERR_INVALID_FORMAT;
2050 			goto out;
2051 		}
2052 		/* FALLTHROUGH */
2053 	case KEY_ED25519:
2054 		if ((ret = sshbuf_get_string(b, &pk, &len)) != 0)
2055 			goto out;
2056 		if (len != ED25519_PK_SZ) {
2057 			ret = SSH_ERR_INVALID_FORMAT;
2058 			goto out;
2059 		}
2060 		if ((key = sshkey_new(type)) == NULL) {
2061 			ret = SSH_ERR_ALLOC_FAIL;
2062 			goto out;
2063 		}
2064 		key->ed25519_pk = pk;
2065 		pk = NULL;
2066 		break;
2067 	case KEY_UNSPEC:
2068 		if ((key = sshkey_new(type)) == NULL) {
2069 			ret = SSH_ERR_ALLOC_FAIL;
2070 			goto out;
2071 		}
2072 		break;
2073 	default:
2074 		ret = SSH_ERR_KEY_TYPE_UNKNOWN;
2075 		goto out;
2076 	}
2077 
2078 	/* Parse certificate potion */
2079 	if (sshkey_is_cert(key) && (ret = cert_parse(b, key, copy)) != 0)
2080 		goto out;
2081 
2082 	if (key != NULL && sshbuf_len(b) != 0) {
2083 		ret = SSH_ERR_INVALID_FORMAT;
2084 		goto out;
2085 	}
2086 	ret = 0;
2087 	if (keyp != NULL) {
2088 		*keyp = key;
2089 		key = NULL;
2090 	}
2091  out:
2092 	sshbuf_free(copy);
2093 	sshkey_free(key);
2094 	free(ktype);
2095 	free(curve);
2096 	free(pk);
2097 #ifdef WITH_OPENSSL
2098 	if (q != NULL)
2099 		EC_POINT_free(q);
2100 #endif /* WITH_OPENSSL */
2101 	return ret;
2102 }
2103 
2104 int
2105 sshkey_from_blob(const u_char *blob, size_t blen, struct sshkey **keyp)
2106 {
2107 	struct sshbuf *b;
2108 	int r;
2109 
2110 	if ((b = sshbuf_from(blob, blen)) == NULL)
2111 		return SSH_ERR_ALLOC_FAIL;
2112 	r = sshkey_from_blob_internal(b, keyp, 1);
2113 	sshbuf_free(b);
2114 	return r;
2115 }
2116 
2117 int
2118 sshkey_fromb(struct sshbuf *b, struct sshkey **keyp)
2119 {
2120 	return sshkey_from_blob_internal(b, keyp, 1);
2121 }
2122 
2123 int
2124 sshkey_froms(struct sshbuf *buf, struct sshkey **keyp)
2125 {
2126 	struct sshbuf *b;
2127 	int r;
2128 
2129 	if ((r = sshbuf_froms(buf, &b)) != 0)
2130 		return r;
2131 	r = sshkey_from_blob_internal(b, keyp, 1);
2132 	sshbuf_free(b);
2133 	return r;
2134 }
2135 
2136 int
2137 sshkey_sign(const struct sshkey *key,
2138     u_char **sigp, size_t *lenp,
2139     const u_char *data, size_t datalen, const char *alg, u_int compat)
2140 {
2141 	if (sigp != NULL)
2142 		*sigp = NULL;
2143 	if (lenp != NULL)
2144 		*lenp = 0;
2145 	if (datalen > SSH_KEY_MAX_SIGN_DATA_SIZE)
2146 		return SSH_ERR_INVALID_ARGUMENT;
2147 	switch (key->type) {
2148 #ifdef WITH_OPENSSL
2149 	case KEY_DSA_CERT:
2150 	case KEY_DSA:
2151 		return ssh_dss_sign(key, sigp, lenp, data, datalen, compat);
2152 	case KEY_ECDSA_CERT:
2153 	case KEY_ECDSA:
2154 		return ssh_ecdsa_sign(key, sigp, lenp, data, datalen, compat);
2155 	case KEY_RSA_CERT:
2156 	case KEY_RSA:
2157 		return ssh_rsa_sign(key, sigp, lenp, data, datalen, alg);
2158 #endif /* WITH_OPENSSL */
2159 	case KEY_ED25519:
2160 	case KEY_ED25519_CERT:
2161 		return ssh_ed25519_sign(key, sigp, lenp, data, datalen, compat);
2162 	default:
2163 		return SSH_ERR_KEY_TYPE_UNKNOWN;
2164 	}
2165 }
2166 
2167 /*
2168  * ssh_key_verify returns 0 for a correct signature  and < 0 on error.
2169  */
2170 int
2171 sshkey_verify(const struct sshkey *key,
2172     const u_char *sig, size_t siglen,
2173     const u_char *data, size_t dlen, u_int compat)
2174 {
2175 	if (siglen == 0 || dlen > SSH_KEY_MAX_SIGN_DATA_SIZE)
2176 		return SSH_ERR_INVALID_ARGUMENT;
2177 	switch (key->type) {
2178 #ifdef WITH_OPENSSL
2179 	case KEY_DSA_CERT:
2180 	case KEY_DSA:
2181 		return ssh_dss_verify(key, sig, siglen, data, dlen, compat);
2182 	case KEY_ECDSA_CERT:
2183 	case KEY_ECDSA:
2184 		return ssh_ecdsa_verify(key, sig, siglen, data, dlen, compat);
2185 	case KEY_RSA_CERT:
2186 	case KEY_RSA:
2187 		return ssh_rsa_verify(key, sig, siglen, data, dlen);
2188 #endif /* WITH_OPENSSL */
2189 	case KEY_ED25519:
2190 	case KEY_ED25519_CERT:
2191 		return ssh_ed25519_verify(key, sig, siglen, data, dlen, compat);
2192 	default:
2193 		return SSH_ERR_KEY_TYPE_UNKNOWN;
2194 	}
2195 }
2196 
2197 /* Converts a private to a public key */
2198 int
2199 sshkey_demote(const struct sshkey *k, struct sshkey **dkp)
2200 {
2201 	struct sshkey *pk;
2202 	int ret = SSH_ERR_INTERNAL_ERROR;
2203 
2204 	*dkp = NULL;
2205 	if ((pk = calloc(1, sizeof(*pk))) == NULL)
2206 		return SSH_ERR_ALLOC_FAIL;
2207 	pk->type = k->type;
2208 	pk->flags = k->flags;
2209 	pk->ecdsa_nid = k->ecdsa_nid;
2210 	pk->dsa = NULL;
2211 	pk->ecdsa = NULL;
2212 	pk->rsa = NULL;
2213 	pk->ed25519_pk = NULL;
2214 	pk->ed25519_sk = NULL;
2215 
2216 	switch (k->type) {
2217 #ifdef WITH_OPENSSL
2218 	case KEY_RSA_CERT:
2219 		if ((ret = sshkey_cert_copy(k, pk)) != 0)
2220 			goto fail;
2221 		/* FALLTHROUGH */
2222 	case KEY_RSA1:
2223 	case KEY_RSA:
2224 		if ((pk->rsa = RSA_new()) == NULL ||
2225 		    (pk->rsa->e = BN_dup(k->rsa->e)) == NULL ||
2226 		    (pk->rsa->n = BN_dup(k->rsa->n)) == NULL) {
2227 			ret = SSH_ERR_ALLOC_FAIL;
2228 			goto fail;
2229 			}
2230 		break;
2231 	case KEY_DSA_CERT:
2232 		if ((ret = sshkey_cert_copy(k, pk)) != 0)
2233 			goto fail;
2234 		/* FALLTHROUGH */
2235 	case KEY_DSA:
2236 		if ((pk->dsa = DSA_new()) == NULL ||
2237 		    (pk->dsa->p = BN_dup(k->dsa->p)) == NULL ||
2238 		    (pk->dsa->q = BN_dup(k->dsa->q)) == NULL ||
2239 		    (pk->dsa->g = BN_dup(k->dsa->g)) == NULL ||
2240 		    (pk->dsa->pub_key = BN_dup(k->dsa->pub_key)) == NULL) {
2241 			ret = SSH_ERR_ALLOC_FAIL;
2242 			goto fail;
2243 		}
2244 		break;
2245 	case KEY_ECDSA_CERT:
2246 		if ((ret = sshkey_cert_copy(k, pk)) != 0)
2247 			goto fail;
2248 		/* FALLTHROUGH */
2249 	case KEY_ECDSA:
2250 		pk->ecdsa = EC_KEY_new_by_curve_name(pk->ecdsa_nid);
2251 		if (pk->ecdsa == NULL) {
2252 			ret = SSH_ERR_ALLOC_FAIL;
2253 			goto fail;
2254 		}
2255 		if (EC_KEY_set_public_key(pk->ecdsa,
2256 		    EC_KEY_get0_public_key(k->ecdsa)) != 1) {
2257 			ret = SSH_ERR_LIBCRYPTO_ERROR;
2258 			goto fail;
2259 		}
2260 		break;
2261 #endif /* WITH_OPENSSL */
2262 	case KEY_ED25519_CERT:
2263 		if ((ret = sshkey_cert_copy(k, pk)) != 0)
2264 			goto fail;
2265 		/* FALLTHROUGH */
2266 	case KEY_ED25519:
2267 		if (k->ed25519_pk != NULL) {
2268 			if ((pk->ed25519_pk = malloc(ED25519_PK_SZ)) == NULL) {
2269 				ret = SSH_ERR_ALLOC_FAIL;
2270 				goto fail;
2271 			}
2272 			memcpy(pk->ed25519_pk, k->ed25519_pk, ED25519_PK_SZ);
2273 		}
2274 		break;
2275 	default:
2276 		ret = SSH_ERR_KEY_TYPE_UNKNOWN;
2277  fail:
2278 		sshkey_free(pk);
2279 		return ret;
2280 	}
2281 	*dkp = pk;
2282 	return 0;
2283 }
2284 
2285 /* Convert a plain key to their _CERT equivalent */
2286 int
2287 sshkey_to_certified(struct sshkey *k)
2288 {
2289 	int newtype;
2290 
2291 	switch (k->type) {
2292 #ifdef WITH_OPENSSL
2293 	case KEY_RSA:
2294 		newtype = KEY_RSA_CERT;
2295 		break;
2296 	case KEY_DSA:
2297 		newtype = KEY_DSA_CERT;
2298 		break;
2299 	case KEY_ECDSA:
2300 		newtype = KEY_ECDSA_CERT;
2301 		break;
2302 #endif /* WITH_OPENSSL */
2303 	case KEY_ED25519:
2304 		newtype = KEY_ED25519_CERT;
2305 		break;
2306 	default:
2307 		return SSH_ERR_INVALID_ARGUMENT;
2308 	}
2309 	if ((k->cert = cert_new()) == NULL)
2310 		return SSH_ERR_ALLOC_FAIL;
2311 	k->type = newtype;
2312 	return 0;
2313 }
2314 
2315 /* Convert a certificate to its raw key equivalent */
2316 int
2317 sshkey_drop_cert(struct sshkey *k)
2318 {
2319 	if (!sshkey_type_is_cert(k->type))
2320 		return SSH_ERR_KEY_TYPE_UNKNOWN;
2321 	cert_free(k->cert);
2322 	k->cert = NULL;
2323 	k->type = sshkey_type_plain(k->type);
2324 	return 0;
2325 }
2326 
2327 /* Sign a certified key, (re-)generating the signed certblob. */
2328 int
2329 sshkey_certify(struct sshkey *k, struct sshkey *ca, const char *alg)
2330 {
2331 	struct sshbuf *principals = NULL;
2332 	u_char *ca_blob = NULL, *sig_blob = NULL, nonce[32];
2333 	size_t i, ca_len, sig_len;
2334 	int ret = SSH_ERR_INTERNAL_ERROR;
2335 	struct sshbuf *cert;
2336 
2337 	if (k == NULL || k->cert == NULL ||
2338 	    k->cert->certblob == NULL || ca == NULL)
2339 		return SSH_ERR_INVALID_ARGUMENT;
2340 	if (!sshkey_is_cert(k))
2341 		return SSH_ERR_KEY_TYPE_UNKNOWN;
2342 	if (!sshkey_type_is_valid_ca(ca->type))
2343 		return SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
2344 
2345 	if ((ret = sshkey_to_blob(ca, &ca_blob, &ca_len)) != 0)
2346 		return SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
2347 
2348 	cert = k->cert->certblob; /* for readability */
2349 	sshbuf_reset(cert);
2350 	if ((ret = sshbuf_put_cstring(cert, sshkey_ssh_name(k))) != 0)
2351 		goto out;
2352 
2353 	/* -v01 certs put nonce first */
2354 	arc4random_buf(&nonce, sizeof(nonce));
2355 	if ((ret = sshbuf_put_string(cert, nonce, sizeof(nonce))) != 0)
2356 		goto out;
2357 
2358 	/* XXX this substantially duplicates to_blob(); refactor */
2359 	switch (k->type) {
2360 #ifdef WITH_OPENSSL
2361 	case KEY_DSA_CERT:
2362 		if ((ret = sshbuf_put_bignum2(cert, k->dsa->p)) != 0 ||
2363 		    (ret = sshbuf_put_bignum2(cert, k->dsa->q)) != 0 ||
2364 		    (ret = sshbuf_put_bignum2(cert, k->dsa->g)) != 0 ||
2365 		    (ret = sshbuf_put_bignum2(cert, k->dsa->pub_key)) != 0)
2366 			goto out;
2367 		break;
2368 	case KEY_ECDSA_CERT:
2369 		if ((ret = sshbuf_put_cstring(cert,
2370 		    sshkey_curve_nid_to_name(k->ecdsa_nid))) != 0 ||
2371 		    (ret = sshbuf_put_ec(cert,
2372 		    EC_KEY_get0_public_key(k->ecdsa),
2373 		    EC_KEY_get0_group(k->ecdsa))) != 0)
2374 			goto out;
2375 		break;
2376 	case KEY_RSA_CERT:
2377 		if ((ret = sshbuf_put_bignum2(cert, k->rsa->e)) != 0 ||
2378 		    (ret = sshbuf_put_bignum2(cert, k->rsa->n)) != 0)
2379 			goto out;
2380 		break;
2381 #endif /* WITH_OPENSSL */
2382 	case KEY_ED25519_CERT:
2383 		if ((ret = sshbuf_put_string(cert,
2384 		    k->ed25519_pk, ED25519_PK_SZ)) != 0)
2385 			goto out;
2386 		break;
2387 	default:
2388 		ret = SSH_ERR_INVALID_ARGUMENT;
2389 		goto out;
2390 	}
2391 
2392 	if ((ret = sshbuf_put_u64(cert, k->cert->serial)) != 0 ||
2393 	    (ret = sshbuf_put_u32(cert, k->cert->type)) != 0 ||
2394 	    (ret = sshbuf_put_cstring(cert, k->cert->key_id)) != 0)
2395 		goto out;
2396 
2397 	if ((principals = sshbuf_new()) == NULL) {
2398 		ret = SSH_ERR_ALLOC_FAIL;
2399 		goto out;
2400 	}
2401 	for (i = 0; i < k->cert->nprincipals; i++) {
2402 		if ((ret = sshbuf_put_cstring(principals,
2403 		    k->cert->principals[i])) != 0)
2404 			goto out;
2405 	}
2406 	if ((ret = sshbuf_put_stringb(cert, principals)) != 0 ||
2407 	    (ret = sshbuf_put_u64(cert, k->cert->valid_after)) != 0 ||
2408 	    (ret = sshbuf_put_u64(cert, k->cert->valid_before)) != 0 ||
2409 	    (ret = sshbuf_put_stringb(cert, k->cert->critical)) != 0 ||
2410 	    (ret = sshbuf_put_stringb(cert, k->cert->extensions)) != 0 ||
2411 	    (ret = sshbuf_put_string(cert, NULL, 0)) != 0 || /* Reserved */
2412 	    (ret = sshbuf_put_string(cert, ca_blob, ca_len)) != 0)
2413 		goto out;
2414 
2415 	/* Sign the whole mess */
2416 	if ((ret = sshkey_sign(ca, &sig_blob, &sig_len, sshbuf_ptr(cert),
2417 	    sshbuf_len(cert), alg, 0)) != 0)
2418 		goto out;
2419 
2420 	/* Append signature and we are done */
2421 	if ((ret = sshbuf_put_string(cert, sig_blob, sig_len)) != 0)
2422 		goto out;
2423 	ret = 0;
2424  out:
2425 	if (ret != 0)
2426 		sshbuf_reset(cert);
2427 	free(sig_blob);
2428 	free(ca_blob);
2429 	sshbuf_free(principals);
2430 	return ret;
2431 }
2432 
2433 int
2434 sshkey_cert_check_authority(const struct sshkey *k,
2435     int want_host, int require_principal,
2436     const char *name, const char **reason)
2437 {
2438 	u_int i, principal_matches;
2439 	time_t now = time(NULL);
2440 
2441 	if (reason != NULL)
2442 		*reason = NULL;
2443 
2444 	if (want_host) {
2445 		if (k->cert->type != SSH2_CERT_TYPE_HOST) {
2446 			*reason = "Certificate invalid: not a host certificate";
2447 			return SSH_ERR_KEY_CERT_INVALID;
2448 		}
2449 	} else {
2450 		if (k->cert->type != SSH2_CERT_TYPE_USER) {
2451 			*reason = "Certificate invalid: not a user certificate";
2452 			return SSH_ERR_KEY_CERT_INVALID;
2453 		}
2454 	}
2455 	if (now < 0) {
2456 		/* yikes - system clock before epoch! */
2457 		*reason = "Certificate invalid: not yet valid";
2458 		return SSH_ERR_KEY_CERT_INVALID;
2459 	}
2460 	if ((u_int64_t)now < k->cert->valid_after) {
2461 		*reason = "Certificate invalid: not yet valid";
2462 		return SSH_ERR_KEY_CERT_INVALID;
2463 	}
2464 	if ((u_int64_t)now >= k->cert->valid_before) {
2465 		*reason = "Certificate invalid: expired";
2466 		return SSH_ERR_KEY_CERT_INVALID;
2467 	}
2468 	if (k->cert->nprincipals == 0) {
2469 		if (require_principal) {
2470 			*reason = "Certificate lacks principal list";
2471 			return SSH_ERR_KEY_CERT_INVALID;
2472 		}
2473 	} else if (name != NULL) {
2474 		principal_matches = 0;
2475 		for (i = 0; i < k->cert->nprincipals; i++) {
2476 			if (strcmp(name, k->cert->principals[i]) == 0) {
2477 				principal_matches = 1;
2478 				break;
2479 			}
2480 		}
2481 		if (!principal_matches) {
2482 			*reason = "Certificate invalid: name is not a listed "
2483 			    "principal";
2484 			return SSH_ERR_KEY_CERT_INVALID;
2485 		}
2486 	}
2487 	return 0;
2488 }
2489 
2490 size_t
2491 sshkey_format_cert_validity(const struct sshkey_cert *cert, char *s, size_t l)
2492 {
2493 	char from[32], to[32], ret[64];
2494 	time_t tt;
2495 	struct tm *tm;
2496 
2497 	*from = *to = '\0';
2498 	if (cert->valid_after == 0 &&
2499 	    cert->valid_before == 0xffffffffffffffffULL)
2500 		return strlcpy(s, "forever", l);
2501 
2502 	if (cert->valid_after != 0) {
2503 		/* XXX revisit INT_MAX in 2038 :) */
2504 		tt = cert->valid_after > INT_MAX ?
2505 		    INT_MAX : cert->valid_after;
2506 		tm = localtime(&tt);
2507 		strftime(from, sizeof(from), "%Y-%m-%dT%H:%M:%S", tm);
2508 	}
2509 	if (cert->valid_before != 0xffffffffffffffffULL) {
2510 		/* XXX revisit INT_MAX in 2038 :) */
2511 		tt = cert->valid_before > INT_MAX ?
2512 		    INT_MAX : cert->valid_before;
2513 		tm = localtime(&tt);
2514 		strftime(to, sizeof(to), "%Y-%m-%dT%H:%M:%S", tm);
2515 	}
2516 
2517 	if (cert->valid_after == 0)
2518 		snprintf(ret, sizeof(ret), "before %s", to);
2519 	else if (cert->valid_before == 0xffffffffffffffffULL)
2520 		snprintf(ret, sizeof(ret), "after %s", from);
2521 	else
2522 		snprintf(ret, sizeof(ret), "from %s to %s", from, to);
2523 
2524 	return strlcpy(s, ret, l);
2525 }
2526 
2527 int
2528 sshkey_private_serialize(const struct sshkey *key, struct sshbuf *b)
2529 {
2530 	int r = SSH_ERR_INTERNAL_ERROR;
2531 
2532 	if ((r = sshbuf_put_cstring(b, sshkey_ssh_name(key))) != 0)
2533 		goto out;
2534 	switch (key->type) {
2535 #ifdef WITH_OPENSSL
2536 	case KEY_RSA:
2537 		if ((r = sshbuf_put_bignum2(b, key->rsa->n)) != 0 ||
2538 		    (r = sshbuf_put_bignum2(b, key->rsa->e)) != 0 ||
2539 		    (r = sshbuf_put_bignum2(b, key->rsa->d)) != 0 ||
2540 		    (r = sshbuf_put_bignum2(b, key->rsa->iqmp)) != 0 ||
2541 		    (r = sshbuf_put_bignum2(b, key->rsa->p)) != 0 ||
2542 		    (r = sshbuf_put_bignum2(b, key->rsa->q)) != 0)
2543 			goto out;
2544 		break;
2545 	case KEY_RSA_CERT:
2546 		if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
2547 			r = SSH_ERR_INVALID_ARGUMENT;
2548 			goto out;
2549 		}
2550 		if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
2551 		    (r = sshbuf_put_bignum2(b, key->rsa->d)) != 0 ||
2552 		    (r = sshbuf_put_bignum2(b, key->rsa->iqmp)) != 0 ||
2553 		    (r = sshbuf_put_bignum2(b, key->rsa->p)) != 0 ||
2554 		    (r = sshbuf_put_bignum2(b, key->rsa->q)) != 0)
2555 			goto out;
2556 		break;
2557 	case KEY_DSA:
2558 		if ((r = sshbuf_put_bignum2(b, key->dsa->p)) != 0 ||
2559 		    (r = sshbuf_put_bignum2(b, key->dsa->q)) != 0 ||
2560 		    (r = sshbuf_put_bignum2(b, key->dsa->g)) != 0 ||
2561 		    (r = sshbuf_put_bignum2(b, key->dsa->pub_key)) != 0 ||
2562 		    (r = sshbuf_put_bignum2(b, key->dsa->priv_key)) != 0)
2563 			goto out;
2564 		break;
2565 	case KEY_DSA_CERT:
2566 		if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
2567 			r = SSH_ERR_INVALID_ARGUMENT;
2568 			goto out;
2569 		}
2570 		if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
2571 		    (r = sshbuf_put_bignum2(b, key->dsa->priv_key)) != 0)
2572 			goto out;
2573 		break;
2574 	case KEY_ECDSA:
2575 		if ((r = sshbuf_put_cstring(b,
2576 		    sshkey_curve_nid_to_name(key->ecdsa_nid))) != 0 ||
2577 		    (r = sshbuf_put_eckey(b, key->ecdsa)) != 0 ||
2578 		    (r = sshbuf_put_bignum2(b,
2579 		    EC_KEY_get0_private_key(key->ecdsa))) != 0)
2580 			goto out;
2581 		break;
2582 	case KEY_ECDSA_CERT:
2583 		if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
2584 			r = SSH_ERR_INVALID_ARGUMENT;
2585 			goto out;
2586 		}
2587 		if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
2588 		    (r = sshbuf_put_bignum2(b,
2589 		    EC_KEY_get0_private_key(key->ecdsa))) != 0)
2590 			goto out;
2591 		break;
2592 #endif /* WITH_OPENSSL */
2593 	case KEY_ED25519:
2594 		if ((r = sshbuf_put_string(b, key->ed25519_pk,
2595 		    ED25519_PK_SZ)) != 0 ||
2596 		    (r = sshbuf_put_string(b, key->ed25519_sk,
2597 		    ED25519_SK_SZ)) != 0)
2598 			goto out;
2599 		break;
2600 	case KEY_ED25519_CERT:
2601 		if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
2602 			r = SSH_ERR_INVALID_ARGUMENT;
2603 			goto out;
2604 		}
2605 		if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
2606 		    (r = sshbuf_put_string(b, key->ed25519_pk,
2607 		    ED25519_PK_SZ)) != 0 ||
2608 		    (r = sshbuf_put_string(b, key->ed25519_sk,
2609 		    ED25519_SK_SZ)) != 0)
2610 			goto out;
2611 		break;
2612 	default:
2613 		r = SSH_ERR_INVALID_ARGUMENT;
2614 		goto out;
2615 	}
2616 	/* success */
2617 	r = 0;
2618  out:
2619 	return r;
2620 }
2621 
2622 int
2623 sshkey_private_deserialize(struct sshbuf *buf, struct sshkey **kp)
2624 {
2625 	char *tname = NULL, *curve = NULL;
2626 	struct sshkey *k = NULL;
2627 	size_t pklen = 0, sklen = 0;
2628 	int type, r = SSH_ERR_INTERNAL_ERROR;
2629 	u_char *ed25519_pk = NULL, *ed25519_sk = NULL;
2630 #ifdef WITH_OPENSSL
2631 	BIGNUM *exponent = NULL;
2632 #endif /* WITH_OPENSSL */
2633 
2634 	if (kp != NULL)
2635 		*kp = NULL;
2636 	if ((r = sshbuf_get_cstring(buf, &tname, NULL)) != 0)
2637 		goto out;
2638 	type = sshkey_type_from_name(tname);
2639 	switch (type) {
2640 #ifdef WITH_OPENSSL
2641 	case KEY_DSA:
2642 		if ((k = sshkey_new_private(type)) == NULL) {
2643 			r = SSH_ERR_ALLOC_FAIL;
2644 			goto out;
2645 		}
2646 		if ((r = sshbuf_get_bignum2(buf, k->dsa->p)) != 0 ||
2647 		    (r = sshbuf_get_bignum2(buf, k->dsa->q)) != 0 ||
2648 		    (r = sshbuf_get_bignum2(buf, k->dsa->g)) != 0 ||
2649 		    (r = sshbuf_get_bignum2(buf, k->dsa->pub_key)) != 0 ||
2650 		    (r = sshbuf_get_bignum2(buf, k->dsa->priv_key)) != 0)
2651 			goto out;
2652 		break;
2653 	case KEY_DSA_CERT:
2654 		if ((r = sshkey_froms(buf, &k)) != 0 ||
2655 		    (r = sshkey_add_private(k)) != 0 ||
2656 		    (r = sshbuf_get_bignum2(buf, k->dsa->priv_key)) != 0)
2657 			goto out;
2658 		break;
2659 	case KEY_ECDSA:
2660 		if ((k = sshkey_new_private(type)) == NULL) {
2661 			r = SSH_ERR_ALLOC_FAIL;
2662 			goto out;
2663 		}
2664 		if ((k->ecdsa_nid = sshkey_ecdsa_nid_from_name(tname)) == -1) {
2665 			r = SSH_ERR_INVALID_ARGUMENT;
2666 			goto out;
2667 		}
2668 		if ((r = sshbuf_get_cstring(buf, &curve, NULL)) != 0)
2669 			goto out;
2670 		if (k->ecdsa_nid != sshkey_curve_name_to_nid(curve)) {
2671 			r = SSH_ERR_EC_CURVE_MISMATCH;
2672 			goto out;
2673 		}
2674 		k->ecdsa = EC_KEY_new_by_curve_name(k->ecdsa_nid);
2675 		if (k->ecdsa  == NULL || (exponent = BN_new()) == NULL) {
2676 			r = SSH_ERR_LIBCRYPTO_ERROR;
2677 			goto out;
2678 		}
2679 		if ((r = sshbuf_get_eckey(buf, k->ecdsa)) != 0 ||
2680 		    (r = sshbuf_get_bignum2(buf, exponent)))
2681 			goto out;
2682 		if (EC_KEY_set_private_key(k->ecdsa, exponent) != 1) {
2683 			r = SSH_ERR_LIBCRYPTO_ERROR;
2684 			goto out;
2685 		}
2686 		if ((r = sshkey_ec_validate_public(EC_KEY_get0_group(k->ecdsa),
2687 		    EC_KEY_get0_public_key(k->ecdsa))) != 0 ||
2688 		    (r = sshkey_ec_validate_private(k->ecdsa)) != 0)
2689 			goto out;
2690 		break;
2691 	case KEY_ECDSA_CERT:
2692 		if ((exponent = BN_new()) == NULL) {
2693 			r = SSH_ERR_LIBCRYPTO_ERROR;
2694 			goto out;
2695 		}
2696 		if ((r = sshkey_froms(buf, &k)) != 0 ||
2697 		    (r = sshkey_add_private(k)) != 0 ||
2698 		    (r = sshbuf_get_bignum2(buf, exponent)) != 0)
2699 			goto out;
2700 		if (EC_KEY_set_private_key(k->ecdsa, exponent) != 1) {
2701 			r = SSH_ERR_LIBCRYPTO_ERROR;
2702 			goto out;
2703 		}
2704 		if ((r = sshkey_ec_validate_public(EC_KEY_get0_group(k->ecdsa),
2705 		    EC_KEY_get0_public_key(k->ecdsa))) != 0 ||
2706 		    (r = sshkey_ec_validate_private(k->ecdsa)) != 0)
2707 			goto out;
2708 		break;
2709 	case KEY_RSA:
2710 		if ((k = sshkey_new_private(type)) == NULL) {
2711 			r = SSH_ERR_ALLOC_FAIL;
2712 			goto out;
2713 		}
2714 		if ((r = sshbuf_get_bignum2(buf, k->rsa->n)) != 0 ||
2715 		    (r = sshbuf_get_bignum2(buf, k->rsa->e)) != 0 ||
2716 		    (r = sshbuf_get_bignum2(buf, k->rsa->d)) != 0 ||
2717 		    (r = sshbuf_get_bignum2(buf, k->rsa->iqmp)) != 0 ||
2718 		    (r = sshbuf_get_bignum2(buf, k->rsa->p)) != 0 ||
2719 		    (r = sshbuf_get_bignum2(buf, k->rsa->q)) != 0 ||
2720 		    (r = rsa_generate_additional_parameters(k->rsa)) != 0)
2721 			goto out;
2722 		break;
2723 	case KEY_RSA_CERT:
2724 		if ((r = sshkey_froms(buf, &k)) != 0 ||
2725 		    (r = sshkey_add_private(k)) != 0 ||
2726 		    (r = sshbuf_get_bignum2(buf, k->rsa->d)) != 0 ||
2727 		    (r = sshbuf_get_bignum2(buf, k->rsa->iqmp)) != 0 ||
2728 		    (r = sshbuf_get_bignum2(buf, k->rsa->p)) != 0 ||
2729 		    (r = sshbuf_get_bignum2(buf, k->rsa->q)) != 0 ||
2730 		    (r = rsa_generate_additional_parameters(k->rsa)) != 0)
2731 			goto out;
2732 		break;
2733 #endif /* WITH_OPENSSL */
2734 	case KEY_ED25519:
2735 		if ((k = sshkey_new_private(type)) == NULL) {
2736 			r = SSH_ERR_ALLOC_FAIL;
2737 			goto out;
2738 		}
2739 		if ((r = sshbuf_get_string(buf, &ed25519_pk, &pklen)) != 0 ||
2740 		    (r = sshbuf_get_string(buf, &ed25519_sk, &sklen)) != 0)
2741 			goto out;
2742 		if (pklen != ED25519_PK_SZ || sklen != ED25519_SK_SZ) {
2743 			r = SSH_ERR_INVALID_FORMAT;
2744 			goto out;
2745 		}
2746 		k->ed25519_pk = ed25519_pk;
2747 		k->ed25519_sk = ed25519_sk;
2748 		ed25519_pk = ed25519_sk = NULL;
2749 		break;
2750 	case KEY_ED25519_CERT:
2751 		if ((r = sshkey_froms(buf, &k)) != 0 ||
2752 		    (r = sshkey_add_private(k)) != 0 ||
2753 		    (r = sshbuf_get_string(buf, &ed25519_pk, &pklen)) != 0 ||
2754 		    (r = sshbuf_get_string(buf, &ed25519_sk, &sklen)) != 0)
2755 			goto out;
2756 		if (pklen != ED25519_PK_SZ || sklen != ED25519_SK_SZ) {
2757 			r = SSH_ERR_INVALID_FORMAT;
2758 			goto out;
2759 		}
2760 		k->ed25519_pk = ed25519_pk;
2761 		k->ed25519_sk = ed25519_sk;
2762 		ed25519_pk = ed25519_sk = NULL;
2763 		break;
2764 	default:
2765 		r = SSH_ERR_KEY_TYPE_UNKNOWN;
2766 		goto out;
2767 	}
2768 #ifdef WITH_OPENSSL
2769 	/* enable blinding */
2770 	switch (k->type) {
2771 	case KEY_RSA:
2772 	case KEY_RSA_CERT:
2773 	case KEY_RSA1:
2774 		if (RSA_blinding_on(k->rsa, NULL) != 1) {
2775 			r = SSH_ERR_LIBCRYPTO_ERROR;
2776 			goto out;
2777 		}
2778 		break;
2779 	}
2780 #endif /* WITH_OPENSSL */
2781 	/* success */
2782 	r = 0;
2783 	if (kp != NULL) {
2784 		*kp = k;
2785 		k = NULL;
2786 	}
2787  out:
2788 	free(tname);
2789 	free(curve);
2790 #ifdef WITH_OPENSSL
2791 	if (exponent != NULL)
2792 		BN_clear_free(exponent);
2793 #endif /* WITH_OPENSSL */
2794 	sshkey_free(k);
2795 	if (ed25519_pk != NULL) {
2796 		explicit_bzero(ed25519_pk, pklen);
2797 		free(ed25519_pk);
2798 	}
2799 	if (ed25519_sk != NULL) {
2800 		explicit_bzero(ed25519_sk, sklen);
2801 		free(ed25519_sk);
2802 	}
2803 	return r;
2804 }
2805 
2806 #ifdef WITH_OPENSSL
2807 int
2808 sshkey_ec_validate_public(const EC_GROUP *group, const EC_POINT *public)
2809 {
2810 	BN_CTX *bnctx;
2811 	EC_POINT *nq = NULL;
2812 	BIGNUM *order, *x, *y, *tmp;
2813 	int ret = SSH_ERR_KEY_INVALID_EC_VALUE;
2814 
2815 	if ((bnctx = BN_CTX_new()) == NULL)
2816 		return SSH_ERR_ALLOC_FAIL;
2817 	BN_CTX_start(bnctx);
2818 
2819 	/*
2820 	 * We shouldn't ever hit this case because bignum_get_ecpoint()
2821 	 * refuses to load GF2m points.
2822 	 */
2823 	if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) !=
2824 	    NID_X9_62_prime_field)
2825 		goto out;
2826 
2827 	/* Q != infinity */
2828 	if (EC_POINT_is_at_infinity(group, public))
2829 		goto out;
2830 
2831 	if ((x = BN_CTX_get(bnctx)) == NULL ||
2832 	    (y = BN_CTX_get(bnctx)) == NULL ||
2833 	    (order = BN_CTX_get(bnctx)) == NULL ||
2834 	    (tmp = BN_CTX_get(bnctx)) == NULL) {
2835 		ret = SSH_ERR_ALLOC_FAIL;
2836 		goto out;
2837 	}
2838 
2839 	/* log2(x) > log2(order)/2, log2(y) > log2(order)/2 */
2840 	if (EC_GROUP_get_order(group, order, bnctx) != 1 ||
2841 	    EC_POINT_get_affine_coordinates_GFp(group, public,
2842 	    x, y, bnctx) != 1) {
2843 		ret = SSH_ERR_LIBCRYPTO_ERROR;
2844 		goto out;
2845 	}
2846 	if (BN_num_bits(x) <= BN_num_bits(order) / 2 ||
2847 	    BN_num_bits(y) <= BN_num_bits(order) / 2)
2848 		goto out;
2849 
2850 	/* nQ == infinity (n == order of subgroup) */
2851 	if ((nq = EC_POINT_new(group)) == NULL) {
2852 		ret = SSH_ERR_ALLOC_FAIL;
2853 		goto out;
2854 	}
2855 	if (EC_POINT_mul(group, nq, NULL, public, order, bnctx) != 1) {
2856 		ret = SSH_ERR_LIBCRYPTO_ERROR;
2857 		goto out;
2858 	}
2859 	if (EC_POINT_is_at_infinity(group, nq) != 1)
2860 		goto out;
2861 
2862 	/* x < order - 1, y < order - 1 */
2863 	if (!BN_sub(tmp, order, BN_value_one())) {
2864 		ret = SSH_ERR_LIBCRYPTO_ERROR;
2865 		goto out;
2866 	}
2867 	if (BN_cmp(x, tmp) >= 0 || BN_cmp(y, tmp) >= 0)
2868 		goto out;
2869 	ret = 0;
2870  out:
2871 	BN_CTX_free(bnctx);
2872 	if (nq != NULL)
2873 		EC_POINT_free(nq);
2874 	return ret;
2875 }
2876 
2877 int
2878 sshkey_ec_validate_private(const EC_KEY *key)
2879 {
2880 	BN_CTX *bnctx;
2881 	BIGNUM *order, *tmp;
2882 	int ret = SSH_ERR_KEY_INVALID_EC_VALUE;
2883 
2884 	if ((bnctx = BN_CTX_new()) == NULL)
2885 		return SSH_ERR_ALLOC_FAIL;
2886 	BN_CTX_start(bnctx);
2887 
2888 	if ((order = BN_CTX_get(bnctx)) == NULL ||
2889 	    (tmp = BN_CTX_get(bnctx)) == NULL) {
2890 		ret = SSH_ERR_ALLOC_FAIL;
2891 		goto out;
2892 	}
2893 
2894 	/* log2(private) > log2(order)/2 */
2895 	if (EC_GROUP_get_order(EC_KEY_get0_group(key), order, bnctx) != 1) {
2896 		ret = SSH_ERR_LIBCRYPTO_ERROR;
2897 		goto out;
2898 	}
2899 	if (BN_num_bits(EC_KEY_get0_private_key(key)) <=
2900 	    BN_num_bits(order) / 2)
2901 		goto out;
2902 
2903 	/* private < order - 1 */
2904 	if (!BN_sub(tmp, order, BN_value_one())) {
2905 		ret = SSH_ERR_LIBCRYPTO_ERROR;
2906 		goto out;
2907 	}
2908 	if (BN_cmp(EC_KEY_get0_private_key(key), tmp) >= 0)
2909 		goto out;
2910 	ret = 0;
2911  out:
2912 	BN_CTX_free(bnctx);
2913 	return ret;
2914 }
2915 
2916 void
2917 sshkey_dump_ec_point(const EC_GROUP *group, const EC_POINT *point)
2918 {
2919 	BIGNUM *x, *y;
2920 	BN_CTX *bnctx;
2921 
2922 	if (point == NULL) {
2923 		fputs("point=(NULL)\n", stderr);
2924 		return;
2925 	}
2926 	if ((bnctx = BN_CTX_new()) == NULL) {
2927 		fprintf(stderr, "%s: BN_CTX_new failed\n", __func__);
2928 		return;
2929 	}
2930 	BN_CTX_start(bnctx);
2931 	if ((x = BN_CTX_get(bnctx)) == NULL ||
2932 	    (y = BN_CTX_get(bnctx)) == NULL) {
2933 		fprintf(stderr, "%s: BN_CTX_get failed\n", __func__);
2934 		return;
2935 	}
2936 	if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) !=
2937 	    NID_X9_62_prime_field) {
2938 		fprintf(stderr, "%s: group is not a prime field\n", __func__);
2939 		return;
2940 	}
2941 	if (EC_POINT_get_affine_coordinates_GFp(group, point, x, y,
2942 	    bnctx) != 1) {
2943 		fprintf(stderr, "%s: EC_POINT_get_affine_coordinates_GFp\n",
2944 		    __func__);
2945 		return;
2946 	}
2947 	fputs("x=", stderr);
2948 	BN_print_fp(stderr, x);
2949 	fputs("\ny=", stderr);
2950 	BN_print_fp(stderr, y);
2951 	fputs("\n", stderr);
2952 	BN_CTX_free(bnctx);
2953 }
2954 
2955 void
2956 sshkey_dump_ec_key(const EC_KEY *key)
2957 {
2958 	const BIGNUM *exponent;
2959 
2960 	sshkey_dump_ec_point(EC_KEY_get0_group(key),
2961 	    EC_KEY_get0_public_key(key));
2962 	fputs("exponent=", stderr);
2963 	if ((exponent = EC_KEY_get0_private_key(key)) == NULL)
2964 		fputs("(NULL)", stderr);
2965 	else
2966 		BN_print_fp(stderr, EC_KEY_get0_private_key(key));
2967 	fputs("\n", stderr);
2968 }
2969 #endif /* WITH_OPENSSL */
2970 
2971 static int
2972 sshkey_private_to_blob2(const struct sshkey *prv, struct sshbuf *blob,
2973     const char *passphrase, const char *comment, const char *ciphername,
2974     int rounds)
2975 {
2976 	u_char *cp, *key = NULL, *pubkeyblob = NULL;
2977 	u_char salt[SALT_LEN];
2978 	char *b64 = NULL;
2979 	size_t i, pubkeylen, keylen, ivlen, blocksize, authlen;
2980 	u_int check;
2981 	int r = SSH_ERR_INTERNAL_ERROR;
2982 	struct sshcipher_ctx ciphercontext;
2983 	const struct sshcipher *cipher;
2984 	const char *kdfname = KDFNAME;
2985 	struct sshbuf *encoded = NULL, *encrypted = NULL, *kdf = NULL;
2986 
2987 	memset(&ciphercontext, 0, sizeof(ciphercontext));
2988 
2989 	if (rounds <= 0)
2990 		rounds = DEFAULT_ROUNDS;
2991 	if (passphrase == NULL || !strlen(passphrase)) {
2992 		ciphername = "none";
2993 		kdfname = "none";
2994 	} else if (ciphername == NULL)
2995 		ciphername = DEFAULT_CIPHERNAME;
2996 	else if (cipher_number(ciphername) != SSH_CIPHER_SSH2) {
2997 		r = SSH_ERR_INVALID_ARGUMENT;
2998 		goto out;
2999 	}
3000 	if ((cipher = cipher_by_name(ciphername)) == NULL) {
3001 		r = SSH_ERR_INTERNAL_ERROR;
3002 		goto out;
3003 	}
3004 
3005 	if ((kdf = sshbuf_new()) == NULL ||
3006 	    (encoded = sshbuf_new()) == NULL ||
3007 	    (encrypted = sshbuf_new()) == NULL) {
3008 		r = SSH_ERR_ALLOC_FAIL;
3009 		goto out;
3010 	}
3011 	blocksize = cipher_blocksize(cipher);
3012 	keylen = cipher_keylen(cipher);
3013 	ivlen = cipher_ivlen(cipher);
3014 	authlen = cipher_authlen(cipher);
3015 	if ((key = calloc(1, keylen + ivlen)) == NULL) {
3016 		r = SSH_ERR_ALLOC_FAIL;
3017 		goto out;
3018 	}
3019 	if (strcmp(kdfname, "bcrypt") == 0) {
3020 		arc4random_buf(salt, SALT_LEN);
3021 		if (bcrypt_pbkdf(passphrase, strlen(passphrase),
3022 		    salt, SALT_LEN, key, keylen + ivlen, rounds) < 0) {
3023 			r = SSH_ERR_INVALID_ARGUMENT;
3024 			goto out;
3025 		}
3026 		if ((r = sshbuf_put_string(kdf, salt, SALT_LEN)) != 0 ||
3027 		    (r = sshbuf_put_u32(kdf, rounds)) != 0)
3028 			goto out;
3029 	} else if (strcmp(kdfname, "none") != 0) {
3030 		/* Unsupported KDF type */
3031 		r = SSH_ERR_KEY_UNKNOWN_CIPHER;
3032 		goto out;
3033 	}
3034 	if ((r = cipher_init(&ciphercontext, cipher, key, keylen,
3035 	    key + keylen, ivlen, 1)) != 0)
3036 		goto out;
3037 
3038 	if ((r = sshbuf_put(encoded, AUTH_MAGIC, sizeof(AUTH_MAGIC))) != 0 ||
3039 	    (r = sshbuf_put_cstring(encoded, ciphername)) != 0 ||
3040 	    (r = sshbuf_put_cstring(encoded, kdfname)) != 0 ||
3041 	    (r = sshbuf_put_stringb(encoded, kdf)) != 0 ||
3042 	    (r = sshbuf_put_u32(encoded, 1)) != 0 ||	/* number of keys */
3043 	    (r = sshkey_to_blob(prv, &pubkeyblob, &pubkeylen)) != 0 ||
3044 	    (r = sshbuf_put_string(encoded, pubkeyblob, pubkeylen)) != 0)
3045 		goto out;
3046 
3047 	/* set up the buffer that will be encrypted */
3048 
3049 	/* Random check bytes */
3050 	check = arc4random();
3051 	if ((r = sshbuf_put_u32(encrypted, check)) != 0 ||
3052 	    (r = sshbuf_put_u32(encrypted, check)) != 0)
3053 		goto out;
3054 
3055 	/* append private key and comment*/
3056 	if ((r = sshkey_private_serialize(prv, encrypted)) != 0 ||
3057 	    (r = sshbuf_put_cstring(encrypted, comment)) != 0)
3058 		goto out;
3059 
3060 	/* padding */
3061 	i = 0;
3062 	while (sshbuf_len(encrypted) % blocksize) {
3063 		if ((r = sshbuf_put_u8(encrypted, ++i & 0xff)) != 0)
3064 			goto out;
3065 	}
3066 
3067 	/* length in destination buffer */
3068 	if ((r = sshbuf_put_u32(encoded, sshbuf_len(encrypted))) != 0)
3069 		goto out;
3070 
3071 	/* encrypt */
3072 	if ((r = sshbuf_reserve(encoded,
3073 	    sshbuf_len(encrypted) + authlen, &cp)) != 0)
3074 		goto out;
3075 	if ((r = cipher_crypt(&ciphercontext, 0, cp,
3076 	    sshbuf_ptr(encrypted), sshbuf_len(encrypted), 0, authlen)) != 0)
3077 		goto out;
3078 
3079 	/* uuencode */
3080 	if ((b64 = sshbuf_dtob64(encoded)) == NULL) {
3081 		r = SSH_ERR_ALLOC_FAIL;
3082 		goto out;
3083 	}
3084 
3085 	sshbuf_reset(blob);
3086 	if ((r = sshbuf_put(blob, MARK_BEGIN, MARK_BEGIN_LEN)) != 0)
3087 		goto out;
3088 	for (i = 0; i < strlen(b64); i++) {
3089 		if ((r = sshbuf_put_u8(blob, b64[i])) != 0)
3090 			goto out;
3091 		/* insert line breaks */
3092 		if (i % 70 == 69 && (r = sshbuf_put_u8(blob, '\n')) != 0)
3093 			goto out;
3094 	}
3095 	if (i % 70 != 69 && (r = sshbuf_put_u8(blob, '\n')) != 0)
3096 		goto out;
3097 	if ((r = sshbuf_put(blob, MARK_END, MARK_END_LEN)) != 0)
3098 		goto out;
3099 
3100 	/* success */
3101 	r = 0;
3102 
3103  out:
3104 	sshbuf_free(kdf);
3105 	sshbuf_free(encoded);
3106 	sshbuf_free(encrypted);
3107 	cipher_cleanup(&ciphercontext);
3108 	explicit_bzero(salt, sizeof(salt));
3109 	if (key != NULL) {
3110 		explicit_bzero(key, keylen + ivlen);
3111 		free(key);
3112 	}
3113 	if (pubkeyblob != NULL) {
3114 		explicit_bzero(pubkeyblob, pubkeylen);
3115 		free(pubkeyblob);
3116 	}
3117 	if (b64 != NULL) {
3118 		explicit_bzero(b64, strlen(b64));
3119 		free(b64);
3120 	}
3121 	return r;
3122 }
3123 
3124 static int
3125 sshkey_parse_private2(struct sshbuf *blob, int type, const char *passphrase,
3126     struct sshkey **keyp, char **commentp)
3127 {
3128 	char *comment = NULL, *ciphername = NULL, *kdfname = NULL;
3129 	const struct sshcipher *cipher = NULL;
3130 	const u_char *cp;
3131 	int r = SSH_ERR_INTERNAL_ERROR;
3132 	size_t encoded_len;
3133 	size_t i, keylen = 0, ivlen = 0, authlen = 0, slen = 0;
3134 	struct sshbuf *encoded = NULL, *decoded = NULL;
3135 	struct sshbuf *kdf = NULL, *decrypted = NULL;
3136 	struct sshcipher_ctx ciphercontext;
3137 	struct sshkey *k = NULL;
3138 	u_char *key = NULL, *salt = NULL, *dp, pad, last;
3139 	u_int blocksize, rounds, nkeys, encrypted_len, check1, check2;
3140 
3141 	memset(&ciphercontext, 0, sizeof(ciphercontext));
3142 	if (keyp != NULL)
3143 		*keyp = NULL;
3144 	if (commentp != NULL)
3145 		*commentp = NULL;
3146 
3147 	if ((encoded = sshbuf_new()) == NULL ||
3148 	    (decoded = sshbuf_new()) == NULL ||
3149 	    (decrypted = sshbuf_new()) == NULL) {
3150 		r = SSH_ERR_ALLOC_FAIL;
3151 		goto out;
3152 	}
3153 
3154 	/* check preamble */
3155 	cp = sshbuf_ptr(blob);
3156 	encoded_len = sshbuf_len(blob);
3157 	if (encoded_len < (MARK_BEGIN_LEN + MARK_END_LEN) ||
3158 	    memcmp(cp, MARK_BEGIN, MARK_BEGIN_LEN) != 0) {
3159 		r = SSH_ERR_INVALID_FORMAT;
3160 		goto out;
3161 	}
3162 	cp += MARK_BEGIN_LEN;
3163 	encoded_len -= MARK_BEGIN_LEN;
3164 
3165 	/* Look for end marker, removing whitespace as we go */
3166 	while (encoded_len > 0) {
3167 		if (*cp != '\n' && *cp != '\r') {
3168 			if ((r = sshbuf_put_u8(encoded, *cp)) != 0)
3169 				goto out;
3170 		}
3171 		last = *cp;
3172 		encoded_len--;
3173 		cp++;
3174 		if (last == '\n') {
3175 			if (encoded_len >= MARK_END_LEN &&
3176 			    memcmp(cp, MARK_END, MARK_END_LEN) == 0) {
3177 				/* \0 terminate */
3178 				if ((r = sshbuf_put_u8(encoded, 0)) != 0)
3179 					goto out;
3180 				break;
3181 			}
3182 		}
3183 	}
3184 	if (encoded_len == 0) {
3185 		r = SSH_ERR_INVALID_FORMAT;
3186 		goto out;
3187 	}
3188 
3189 	/* decode base64 */
3190 	if ((r = sshbuf_b64tod(decoded, (char *)sshbuf_ptr(encoded))) != 0)
3191 		goto out;
3192 
3193 	/* check magic */
3194 	if (sshbuf_len(decoded) < sizeof(AUTH_MAGIC) ||
3195 	    memcmp(sshbuf_ptr(decoded), AUTH_MAGIC, sizeof(AUTH_MAGIC))) {
3196 		r = SSH_ERR_INVALID_FORMAT;
3197 		goto out;
3198 	}
3199 	/* parse public portion of key */
3200 	if ((r = sshbuf_consume(decoded, sizeof(AUTH_MAGIC))) != 0 ||
3201 	    (r = sshbuf_get_cstring(decoded, &ciphername, NULL)) != 0 ||
3202 	    (r = sshbuf_get_cstring(decoded, &kdfname, NULL)) != 0 ||
3203 	    (r = sshbuf_froms(decoded, &kdf)) != 0 ||
3204 	    (r = sshbuf_get_u32(decoded, &nkeys)) != 0 ||
3205 	    (r = sshbuf_skip_string(decoded)) != 0 || /* pubkey */
3206 	    (r = sshbuf_get_u32(decoded, &encrypted_len)) != 0)
3207 		goto out;
3208 
3209 	if ((cipher = cipher_by_name(ciphername)) == NULL) {
3210 		r = SSH_ERR_KEY_UNKNOWN_CIPHER;
3211 		goto out;
3212 	}
3213 	if ((passphrase == NULL || strlen(passphrase) == 0) &&
3214 	    strcmp(ciphername, "none") != 0) {
3215 		/* passphrase required */
3216 		r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3217 		goto out;
3218 	}
3219 	if (strcmp(kdfname, "none") != 0 && strcmp(kdfname, "bcrypt") != 0) {
3220 		r = SSH_ERR_KEY_UNKNOWN_CIPHER;
3221 		goto out;
3222 	}
3223 	if (!strcmp(kdfname, "none") && strcmp(ciphername, "none") != 0) {
3224 		r = SSH_ERR_INVALID_FORMAT;
3225 		goto out;
3226 	}
3227 	if (nkeys != 1) {
3228 		/* XXX only one key supported */
3229 		r = SSH_ERR_INVALID_FORMAT;
3230 		goto out;
3231 	}
3232 
3233 	/* check size of encrypted key blob */
3234 	blocksize = cipher_blocksize(cipher);
3235 	if (encrypted_len < blocksize || (encrypted_len % blocksize) != 0) {
3236 		r = SSH_ERR_INVALID_FORMAT;
3237 		goto out;
3238 	}
3239 
3240 	/* setup key */
3241 	keylen = cipher_keylen(cipher);
3242 	ivlen = cipher_ivlen(cipher);
3243 	authlen = cipher_authlen(cipher);
3244 	if ((key = calloc(1, keylen + ivlen)) == NULL) {
3245 		r = SSH_ERR_ALLOC_FAIL;
3246 		goto out;
3247 	}
3248 	if (strcmp(kdfname, "bcrypt") == 0) {
3249 		if ((r = sshbuf_get_string(kdf, &salt, &slen)) != 0 ||
3250 		    (r = sshbuf_get_u32(kdf, &rounds)) != 0)
3251 			goto out;
3252 		if (bcrypt_pbkdf(passphrase, strlen(passphrase), salt, slen,
3253 		    key, keylen + ivlen, rounds) < 0) {
3254 			r = SSH_ERR_INVALID_FORMAT;
3255 			goto out;
3256 		}
3257 	}
3258 
3259 	/* check that an appropriate amount of auth data is present */
3260 	if (sshbuf_len(decoded) < encrypted_len + authlen) {
3261 		r = SSH_ERR_INVALID_FORMAT;
3262 		goto out;
3263 	}
3264 
3265 	/* decrypt private portion of key */
3266 	if ((r = sshbuf_reserve(decrypted, encrypted_len, &dp)) != 0 ||
3267 	    (r = cipher_init(&ciphercontext, cipher, key, keylen,
3268 	    key + keylen, ivlen, 0)) != 0)
3269 		goto out;
3270 	if ((r = cipher_crypt(&ciphercontext, 0, dp, sshbuf_ptr(decoded),
3271 	    encrypted_len, 0, authlen)) != 0) {
3272 		/* an integrity error here indicates an incorrect passphrase */
3273 		if (r == SSH_ERR_MAC_INVALID)
3274 			r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3275 		goto out;
3276 	}
3277 	if ((r = sshbuf_consume(decoded, encrypted_len + authlen)) != 0)
3278 		goto out;
3279 	/* there should be no trailing data */
3280 	if (sshbuf_len(decoded) != 0) {
3281 		r = SSH_ERR_INVALID_FORMAT;
3282 		goto out;
3283 	}
3284 
3285 	/* check check bytes */
3286 	if ((r = sshbuf_get_u32(decrypted, &check1)) != 0 ||
3287 	    (r = sshbuf_get_u32(decrypted, &check2)) != 0)
3288 		goto out;
3289 	if (check1 != check2) {
3290 		r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3291 		goto out;
3292 	}
3293 
3294 	/* Load the private key and comment */
3295 	if ((r = sshkey_private_deserialize(decrypted, &k)) != 0 ||
3296 	    (r = sshbuf_get_cstring(decrypted, &comment, NULL)) != 0)
3297 		goto out;
3298 
3299 	/* Check deterministic padding */
3300 	i = 0;
3301 	while (sshbuf_len(decrypted)) {
3302 		if ((r = sshbuf_get_u8(decrypted, &pad)) != 0)
3303 			goto out;
3304 		if (pad != (++i & 0xff)) {
3305 			r = SSH_ERR_INVALID_FORMAT;
3306 			goto out;
3307 		}
3308 	}
3309 
3310 	/* XXX decode pubkey and check against private */
3311 
3312 	/* success */
3313 	r = 0;
3314 	if (keyp != NULL) {
3315 		*keyp = k;
3316 		k = NULL;
3317 	}
3318 	if (commentp != NULL) {
3319 		*commentp = comment;
3320 		comment = NULL;
3321 	}
3322  out:
3323 	pad = 0;
3324 	cipher_cleanup(&ciphercontext);
3325 	free(ciphername);
3326 	free(kdfname);
3327 	free(comment);
3328 	if (salt != NULL) {
3329 		explicit_bzero(salt, slen);
3330 		free(salt);
3331 	}
3332 	if (key != NULL) {
3333 		explicit_bzero(key, keylen + ivlen);
3334 		free(key);
3335 	}
3336 	sshbuf_free(encoded);
3337 	sshbuf_free(decoded);
3338 	sshbuf_free(kdf);
3339 	sshbuf_free(decrypted);
3340 	sshkey_free(k);
3341 	return r;
3342 }
3343 
3344 #if WITH_SSH1
3345 /*
3346  * Serialises the authentication (private) key to a blob, encrypting it with
3347  * passphrase.  The identification of the blob (lowest 64 bits of n) will
3348  * precede the key to provide identification of the key without needing a
3349  * passphrase.
3350  */
3351 static int
3352 sshkey_private_rsa1_to_blob(struct sshkey *key, struct sshbuf *blob,
3353     const char *passphrase, const char *comment)
3354 {
3355 	struct sshbuf *buffer = NULL, *encrypted = NULL;
3356 	u_char buf[8];
3357 	int r, cipher_num;
3358 	struct sshcipher_ctx ciphercontext;
3359 	const struct sshcipher *cipher;
3360 	u_char *cp;
3361 
3362 	/*
3363 	 * If the passphrase is empty, use SSH_CIPHER_NONE to ease converting
3364 	 * to another cipher; otherwise use SSH_AUTHFILE_CIPHER.
3365 	 */
3366 	cipher_num = (strcmp(passphrase, "") == 0) ?
3367 	    SSH_CIPHER_NONE : SSH_CIPHER_3DES;
3368 	if ((cipher = cipher_by_number(cipher_num)) == NULL)
3369 		return SSH_ERR_INTERNAL_ERROR;
3370 
3371 	/* This buffer is used to build the secret part of the private key. */
3372 	if ((buffer = sshbuf_new()) == NULL)
3373 		return SSH_ERR_ALLOC_FAIL;
3374 
3375 	/* Put checkbytes for checking passphrase validity. */
3376 	if ((r = sshbuf_reserve(buffer, 4, &cp)) != 0)
3377 		goto out;
3378 	arc4random_buf(cp, 2);
3379 	memcpy(cp + 2, cp, 2);
3380 
3381 	/*
3382 	 * Store the private key (n and e will not be stored because they
3383 	 * will be stored in plain text, and storing them also in encrypted
3384 	 * format would just give known plaintext).
3385 	 * Note: q and p are stored in reverse order to SSL.
3386 	 */
3387 	if ((r = sshbuf_put_bignum1(buffer, key->rsa->d)) != 0 ||
3388 	    (r = sshbuf_put_bignum1(buffer, key->rsa->iqmp)) != 0 ||
3389 	    (r = sshbuf_put_bignum1(buffer, key->rsa->q)) != 0 ||
3390 	    (r = sshbuf_put_bignum1(buffer, key->rsa->p)) != 0)
3391 		goto out;
3392 
3393 	/* Pad the part to be encrypted to a size that is a multiple of 8. */
3394 	explicit_bzero(buf, 8);
3395 	if ((r = sshbuf_put(buffer, buf, 8 - (sshbuf_len(buffer) % 8))) != 0)
3396 		goto out;
3397 
3398 	/* This buffer will be used to contain the data in the file. */
3399 	if ((encrypted = sshbuf_new()) == NULL) {
3400 		r = SSH_ERR_ALLOC_FAIL;
3401 		goto out;
3402 	}
3403 
3404 	/* First store keyfile id string. */
3405 	if ((r = sshbuf_put(encrypted, LEGACY_BEGIN,
3406 	    sizeof(LEGACY_BEGIN))) != 0)
3407 		goto out;
3408 
3409 	/* Store cipher type and "reserved" field. */
3410 	if ((r = sshbuf_put_u8(encrypted, cipher_num)) != 0 ||
3411 	    (r = sshbuf_put_u32(encrypted, 0)) != 0)
3412 		goto out;
3413 
3414 	/* Store public key.  This will be in plain text. */
3415 	if ((r = sshbuf_put_u32(encrypted, BN_num_bits(key->rsa->n))) != 0 ||
3416 	    (r = sshbuf_put_bignum1(encrypted, key->rsa->n)) != 0 ||
3417 	    (r = sshbuf_put_bignum1(encrypted, key->rsa->e)) != 0 ||
3418 	    (r = sshbuf_put_cstring(encrypted, comment)) != 0)
3419 		goto out;
3420 
3421 	/* Allocate space for the private part of the key in the buffer. */
3422 	if ((r = sshbuf_reserve(encrypted, sshbuf_len(buffer), &cp)) != 0)
3423 		goto out;
3424 
3425 	if ((r = cipher_set_key_string(&ciphercontext, cipher, passphrase,
3426 	    CIPHER_ENCRYPT)) != 0)
3427 		goto out;
3428 	if ((r = cipher_crypt(&ciphercontext, 0, cp,
3429 	    sshbuf_ptr(buffer), sshbuf_len(buffer), 0, 0)) != 0)
3430 		goto out;
3431 	if ((r = cipher_cleanup(&ciphercontext)) != 0)
3432 		goto out;
3433 
3434 	r = sshbuf_putb(blob, encrypted);
3435 
3436  out:
3437 	explicit_bzero(&ciphercontext, sizeof(ciphercontext));
3438 	explicit_bzero(buf, sizeof(buf));
3439 	sshbuf_free(buffer);
3440 	sshbuf_free(encrypted);
3441 
3442 	return r;
3443 }
3444 #endif /* WITH_SSH1 */
3445 
3446 #ifdef WITH_OPENSSL
3447 /* convert SSH v2 key in OpenSSL PEM format */
3448 static int
3449 sshkey_private_pem_to_blob(struct sshkey *key, struct sshbuf *blob,
3450     const char *_passphrase, const char *comment)
3451 {
3452 	int success, r;
3453 	int blen, len = strlen(_passphrase);
3454 	u_char *passphrase = (len > 0) ? (u_char *)_passphrase : NULL;
3455 	const EVP_CIPHER *cipher = (len > 0) ? EVP_aes_128_cbc() : NULL;
3456 	const u_char *bptr;
3457 	BIO *bio = NULL;
3458 
3459 	if (len > 0 && len <= 4)
3460 		return SSH_ERR_PASSPHRASE_TOO_SHORT;
3461 	if ((bio = BIO_new(BIO_s_mem())) == NULL)
3462 		return SSH_ERR_ALLOC_FAIL;
3463 
3464 	switch (key->type) {
3465 	case KEY_DSA:
3466 		success = PEM_write_bio_DSAPrivateKey(bio, key->dsa,
3467 		    cipher, passphrase, len, NULL, NULL);
3468 		break;
3469 	case KEY_ECDSA:
3470 		success = PEM_write_bio_ECPrivateKey(bio, key->ecdsa,
3471 		    cipher, passphrase, len, NULL, NULL);
3472 		break;
3473 	case KEY_RSA:
3474 		success = PEM_write_bio_RSAPrivateKey(bio, key->rsa,
3475 		    cipher, passphrase, len, NULL, NULL);
3476 		break;
3477 	default:
3478 		success = 0;
3479 		break;
3480 	}
3481 	if (success == 0) {
3482 		r = SSH_ERR_LIBCRYPTO_ERROR;
3483 		goto out;
3484 	}
3485 	if ((blen = BIO_get_mem_data(bio, &bptr)) <= 0) {
3486 		r = SSH_ERR_INTERNAL_ERROR;
3487 		goto out;
3488 	}
3489 	if ((r = sshbuf_put(blob, bptr, blen)) != 0)
3490 		goto out;
3491 	r = 0;
3492  out:
3493 	BIO_free(bio);
3494 	return r;
3495 }
3496 #endif /* WITH_OPENSSL */
3497 
3498 /* Serialise "key" to buffer "blob" */
3499 int
3500 sshkey_private_to_fileblob(struct sshkey *key, struct sshbuf *blob,
3501     const char *passphrase, const char *comment,
3502     int force_new_format, const char *new_format_cipher, int new_format_rounds)
3503 {
3504 	switch (key->type) {
3505 #ifdef WITH_SSH1
3506 	case KEY_RSA1:
3507 		return sshkey_private_rsa1_to_blob(key, blob,
3508 		    passphrase, comment);
3509 #endif /* WITH_SSH1 */
3510 #ifdef WITH_OPENSSL
3511 	case KEY_DSA:
3512 	case KEY_ECDSA:
3513 	case KEY_RSA:
3514 		if (force_new_format) {
3515 			return sshkey_private_to_blob2(key, blob, passphrase,
3516 			    comment, new_format_cipher, new_format_rounds);
3517 		}
3518 		return sshkey_private_pem_to_blob(key, blob,
3519 		    passphrase, comment);
3520 #endif /* WITH_OPENSSL */
3521 	case KEY_ED25519:
3522 		return sshkey_private_to_blob2(key, blob, passphrase,
3523 		    comment, new_format_cipher, new_format_rounds);
3524 	default:
3525 		return SSH_ERR_KEY_TYPE_UNKNOWN;
3526 	}
3527 }
3528 
3529 #ifdef WITH_SSH1
3530 /*
3531  * Parse the public, unencrypted portion of a RSA1 key.
3532  */
3533 int
3534 sshkey_parse_public_rsa1_fileblob(struct sshbuf *blob,
3535     struct sshkey **keyp, char **commentp)
3536 {
3537 	int r;
3538 	struct sshkey *pub = NULL;
3539 	struct sshbuf *copy = NULL;
3540 
3541 	if (keyp != NULL)
3542 		*keyp = NULL;
3543 	if (commentp != NULL)
3544 		*commentp = NULL;
3545 
3546 	/* Check that it is at least big enough to contain the ID string. */
3547 	if (sshbuf_len(blob) < sizeof(LEGACY_BEGIN))
3548 		return SSH_ERR_INVALID_FORMAT;
3549 
3550 	/*
3551 	 * Make sure it begins with the id string.  Consume the id string
3552 	 * from the buffer.
3553 	 */
3554 	if (memcmp(sshbuf_ptr(blob), LEGACY_BEGIN, sizeof(LEGACY_BEGIN)) != 0)
3555 		return SSH_ERR_INVALID_FORMAT;
3556 	/* Make a working copy of the keyblob and skip past the magic */
3557 	if ((copy = sshbuf_fromb(blob)) == NULL)
3558 		return SSH_ERR_ALLOC_FAIL;
3559 	if ((r = sshbuf_consume(copy, sizeof(LEGACY_BEGIN))) != 0)
3560 		goto out;
3561 
3562 	/* Skip cipher type, reserved data and key bits. */
3563 	if ((r = sshbuf_get_u8(copy, NULL)) != 0 ||	/* cipher type */
3564 	    (r = sshbuf_get_u32(copy, NULL)) != 0 ||	/* reserved */
3565 	    (r = sshbuf_get_u32(copy, NULL)) != 0)	/* key bits */
3566 		goto out;
3567 
3568 	/* Read the public key from the buffer. */
3569 	if ((pub = sshkey_new(KEY_RSA1)) == NULL ||
3570 	    (r = sshbuf_get_bignum1(copy, pub->rsa->n)) != 0 ||
3571 	    (r = sshbuf_get_bignum1(copy, pub->rsa->e)) != 0)
3572 		goto out;
3573 
3574 	/* Finally, the comment */
3575 	if ((r = sshbuf_get_string(copy, (u_char**)commentp, NULL)) != 0)
3576 		goto out;
3577 
3578 	/* The encrypted private part is not parsed by this function. */
3579 
3580 	r = 0;
3581 	if (keyp != NULL) {
3582 		*keyp = pub;
3583 		pub = NULL;
3584 	}
3585  out:
3586 	sshbuf_free(copy);
3587 	sshkey_free(pub);
3588 	return r;
3589 }
3590 
3591 static int
3592 sshkey_parse_private_rsa1(struct sshbuf *blob, const char *passphrase,
3593     struct sshkey **keyp, char **commentp)
3594 {
3595 	int r;
3596 	u_int16_t check1, check2;
3597 	u_int8_t cipher_type;
3598 	struct sshbuf *decrypted = NULL, *copy = NULL;
3599 	u_char *cp;
3600 	char *comment = NULL;
3601 	struct sshcipher_ctx ciphercontext;
3602 	const struct sshcipher *cipher;
3603 	struct sshkey *prv = NULL;
3604 
3605 	if (keyp != NULL)
3606 		*keyp = NULL;
3607 	if (commentp != NULL)
3608 		*commentp = NULL;
3609 
3610 	/* Check that it is at least big enough to contain the ID string. */
3611 	if (sshbuf_len(blob) < sizeof(LEGACY_BEGIN))
3612 		return SSH_ERR_INVALID_FORMAT;
3613 
3614 	/*
3615 	 * Make sure it begins with the id string.  Consume the id string
3616 	 * from the buffer.
3617 	 */
3618 	if (memcmp(sshbuf_ptr(blob), LEGACY_BEGIN, sizeof(LEGACY_BEGIN)) != 0)
3619 		return SSH_ERR_INVALID_FORMAT;
3620 
3621 	if ((prv = sshkey_new_private(KEY_RSA1)) == NULL) {
3622 		r = SSH_ERR_ALLOC_FAIL;
3623 		goto out;
3624 	}
3625 	if ((copy = sshbuf_fromb(blob)) == NULL ||
3626 	    (decrypted = sshbuf_new()) == NULL) {
3627 		r = SSH_ERR_ALLOC_FAIL;
3628 		goto out;
3629 	}
3630 	if ((r = sshbuf_consume(copy, sizeof(LEGACY_BEGIN))) != 0)
3631 		goto out;
3632 
3633 	/* Read cipher type. */
3634 	if ((r = sshbuf_get_u8(copy, &cipher_type)) != 0 ||
3635 	    (r = sshbuf_get_u32(copy, NULL)) != 0)	/* reserved */
3636 		goto out;
3637 
3638 	/* Read the public key and comment from the buffer. */
3639 	if ((r = sshbuf_get_u32(copy, NULL)) != 0 ||	/* key bits */
3640 	    (r = sshbuf_get_bignum1(copy, prv->rsa->n)) != 0 ||
3641 	    (r = sshbuf_get_bignum1(copy, prv->rsa->e)) != 0 ||
3642 	    (r = sshbuf_get_cstring(copy, &comment, NULL)) != 0)
3643 		goto out;
3644 
3645 	/* Check that it is a supported cipher. */
3646 	cipher = cipher_by_number(cipher_type);
3647 	if (cipher == NULL) {
3648 		r = SSH_ERR_KEY_UNKNOWN_CIPHER;
3649 		goto out;
3650 	}
3651 	/* Initialize space for decrypted data. */
3652 	if ((r = sshbuf_reserve(decrypted, sshbuf_len(copy), &cp)) != 0)
3653 		goto out;
3654 
3655 	/* Rest of the buffer is encrypted.  Decrypt it using the passphrase. */
3656 	if ((r = cipher_set_key_string(&ciphercontext, cipher, passphrase,
3657 	    CIPHER_DECRYPT)) != 0)
3658 		goto out;
3659 	if ((r = cipher_crypt(&ciphercontext, 0, cp,
3660 	    sshbuf_ptr(copy), sshbuf_len(copy), 0, 0)) != 0) {
3661 		cipher_cleanup(&ciphercontext);
3662 		goto out;
3663 	}
3664 	if ((r = cipher_cleanup(&ciphercontext)) != 0)
3665 		goto out;
3666 
3667 	if ((r = sshbuf_get_u16(decrypted, &check1)) != 0 ||
3668 	    (r = sshbuf_get_u16(decrypted, &check2)) != 0)
3669 		goto out;
3670 	if (check1 != check2) {
3671 		r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3672 		goto out;
3673 	}
3674 
3675 	/* Read the rest of the private key. */
3676 	if ((r = sshbuf_get_bignum1(decrypted, prv->rsa->d)) != 0 ||
3677 	    (r = sshbuf_get_bignum1(decrypted, prv->rsa->iqmp)) != 0 ||
3678 	    (r = sshbuf_get_bignum1(decrypted, prv->rsa->q)) != 0 ||
3679 	    (r = sshbuf_get_bignum1(decrypted, prv->rsa->p)) != 0)
3680 		goto out;
3681 
3682 	/* calculate p-1 and q-1 */
3683 	if ((r = rsa_generate_additional_parameters(prv->rsa)) != 0)
3684 		goto out;
3685 
3686 	/* enable blinding */
3687 	if (RSA_blinding_on(prv->rsa, NULL) != 1) {
3688 		r = SSH_ERR_LIBCRYPTO_ERROR;
3689 		goto out;
3690 	}
3691 	r = 0;
3692 	if (keyp != NULL) {
3693 		*keyp = prv;
3694 		prv = NULL;
3695 	}
3696 	if (commentp != NULL) {
3697 		*commentp = comment;
3698 		comment = NULL;
3699 	}
3700  out:
3701 	explicit_bzero(&ciphercontext, sizeof(ciphercontext));
3702 	free(comment);
3703 	sshkey_free(prv);
3704 	sshbuf_free(copy);
3705 	sshbuf_free(decrypted);
3706 	return r;
3707 }
3708 #endif /* WITH_SSH1 */
3709 
3710 #ifdef WITH_OPENSSL
3711 static int
3712 sshkey_parse_private_pem_fileblob(struct sshbuf *blob, int type,
3713     const char *passphrase, struct sshkey **keyp)
3714 {
3715 	EVP_PKEY *pk = NULL;
3716 	struct sshkey *prv = NULL;
3717 	BIO *bio = NULL;
3718 	int r;
3719 
3720 	if (keyp != NULL)
3721 		*keyp = NULL;
3722 
3723 	if ((bio = BIO_new(BIO_s_mem())) == NULL || sshbuf_len(blob) > INT_MAX)
3724 		return SSH_ERR_ALLOC_FAIL;
3725 	if (BIO_write(bio, sshbuf_ptr(blob), sshbuf_len(blob)) !=
3726 	    (int)sshbuf_len(blob)) {
3727 		r = SSH_ERR_ALLOC_FAIL;
3728 		goto out;
3729 	}
3730 
3731 	if ((pk = PEM_read_bio_PrivateKey(bio, NULL, NULL,
3732 	    (char *)passphrase)) == NULL) {
3733 		r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3734 		goto out;
3735 	}
3736 	if (pk->type == EVP_PKEY_RSA &&
3737 	    (type == KEY_UNSPEC || type == KEY_RSA)) {
3738 		if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
3739 			r = SSH_ERR_ALLOC_FAIL;
3740 			goto out;
3741 		}
3742 		prv->rsa = EVP_PKEY_get1_RSA(pk);
3743 		prv->type = KEY_RSA;
3744 #ifdef DEBUG_PK
3745 		RSA_print_fp(stderr, prv->rsa, 8);
3746 #endif
3747 		if (RSA_blinding_on(prv->rsa, NULL) != 1) {
3748 			r = SSH_ERR_LIBCRYPTO_ERROR;
3749 			goto out;
3750 		}
3751 	} else if (pk->type == EVP_PKEY_DSA &&
3752 	    (type == KEY_UNSPEC || type == KEY_DSA)) {
3753 		if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
3754 			r = SSH_ERR_ALLOC_FAIL;
3755 			goto out;
3756 		}
3757 		prv->dsa = EVP_PKEY_get1_DSA(pk);
3758 		prv->type = KEY_DSA;
3759 #ifdef DEBUG_PK
3760 		DSA_print_fp(stderr, prv->dsa, 8);
3761 #endif
3762 	} else if (pk->type == EVP_PKEY_EC &&
3763 	    (type == KEY_UNSPEC || type == KEY_ECDSA)) {
3764 		if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
3765 			r = SSH_ERR_ALLOC_FAIL;
3766 			goto out;
3767 		}
3768 		prv->ecdsa = EVP_PKEY_get1_EC_KEY(pk);
3769 		prv->type = KEY_ECDSA;
3770 		prv->ecdsa_nid = sshkey_ecdsa_key_to_nid(prv->ecdsa);
3771 		if (prv->ecdsa_nid == -1 ||
3772 		    sshkey_curve_nid_to_name(prv->ecdsa_nid) == NULL ||
3773 		    sshkey_ec_validate_public(EC_KEY_get0_group(prv->ecdsa),
3774 		    EC_KEY_get0_public_key(prv->ecdsa)) != 0 ||
3775 		    sshkey_ec_validate_private(prv->ecdsa) != 0) {
3776 			r = SSH_ERR_INVALID_FORMAT;
3777 			goto out;
3778 		}
3779 #ifdef DEBUG_PK
3780 		if (prv != NULL && prv->ecdsa != NULL)
3781 			sshkey_dump_ec_key(prv->ecdsa);
3782 #endif
3783 	} else {
3784 		r = SSH_ERR_INVALID_FORMAT;
3785 		goto out;
3786 	}
3787 	r = 0;
3788 	if (keyp != NULL) {
3789 		*keyp = prv;
3790 		prv = NULL;
3791 	}
3792  out:
3793 	BIO_free(bio);
3794 	if (pk != NULL)
3795 		EVP_PKEY_free(pk);
3796 	sshkey_free(prv);
3797 	return r;
3798 }
3799 #endif /* WITH_OPENSSL */
3800 
3801 int
3802 sshkey_parse_private_fileblob_type(struct sshbuf *blob, int type,
3803     const char *passphrase, struct sshkey **keyp, char **commentp)
3804 {
3805 	if (keyp != NULL)
3806 		*keyp = NULL;
3807 	if (commentp != NULL)
3808 		*commentp = NULL;
3809 
3810 	switch (type) {
3811 #ifdef WITH_SSH1
3812 	case KEY_RSA1:
3813 		return sshkey_parse_private_rsa1(blob, passphrase,
3814 		    keyp, commentp);
3815 #endif /* WITH_SSH1 */
3816 #ifdef WITH_OPENSSL
3817 	case KEY_DSA:
3818 	case KEY_ECDSA:
3819 	case KEY_RSA:
3820 		return sshkey_parse_private_pem_fileblob(blob, type,
3821 		    passphrase, keyp);
3822 #endif /* WITH_OPENSSL */
3823 	case KEY_ED25519:
3824 		return sshkey_parse_private2(blob, type, passphrase,
3825 		    keyp, commentp);
3826 	case KEY_UNSPEC:
3827 		if (sshkey_parse_private2(blob, type, passphrase, keyp,
3828 		    commentp) == 0)
3829 			return 0;
3830 #ifdef WITH_OPENSSL
3831 		return sshkey_parse_private_pem_fileblob(blob, type,
3832 		    passphrase, keyp);
3833 #else
3834 		return SSH_ERR_INVALID_FORMAT;
3835 #endif /* WITH_OPENSSL */
3836 	default:
3837 		return SSH_ERR_KEY_TYPE_UNKNOWN;
3838 	}
3839 }
3840 
3841 int
3842 sshkey_parse_private_fileblob(struct sshbuf *buffer, const char *passphrase,
3843     struct sshkey **keyp, char **commentp)
3844 {
3845 	if (keyp != NULL)
3846 		*keyp = NULL;
3847 	if (commentp != NULL)
3848 		*commentp = NULL;
3849 
3850 #ifdef WITH_SSH1
3851 	/* it's a SSH v1 key if the public key part is readable */
3852 	if (sshkey_parse_public_rsa1_fileblob(buffer, NULL, NULL) == 0) {
3853 		return sshkey_parse_private_fileblob_type(buffer, KEY_RSA1,
3854 		    passphrase, keyp, commentp);
3855 	}
3856 #endif /* WITH_SSH1 */
3857 	return sshkey_parse_private_fileblob_type(buffer, KEY_UNSPEC,
3858 	    passphrase, keyp, commentp);
3859 }
3860