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