• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* $OpenBSD: sshkey.c,v 1.108 2020/04/11 10:16:11 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/types.h>
31 #include <netinet/in.h>
32 
33 #ifdef WITH_OPENSSL
34 #include <openssl/evp.h>
35 #include <openssl/err.h>
36 #include <openssl/pem.h>
37 #endif
38 
39 #include "crypto_api.h"
40 
41 #include <errno.h>
42 #include <limits.h>
43 #include <stdio.h>
44 #include <string.h>
45 #include <resolv.h>
46 #include <time.h>
47 #ifdef HAVE_UTIL_H
48 #include <util.h>
49 #endif /* HAVE_UTIL_H */
50 
51 #include "ssh2.h"
52 #include "ssherr.h"
53 #include "misc.h"
54 #include "sshbuf.h"
55 #include "cipher.h"
56 #include "digest.h"
57 #define SSHKEY_INTERNAL
58 #include "sshkey.h"
59 #include "match.h"
60 #include "ssh-sk.h"
61 
62 #ifdef WITH_XMSS
63 #include "sshkey-xmss.h"
64 #include "xmss_fast.h"
65 #endif
66 
67 #include "openbsd-compat/openssl-compat.h"
68 
69 /* openssh private key file format */
70 #define MARK_BEGIN		"-----BEGIN OPENSSH PRIVATE KEY-----\n"
71 #define MARK_END		"-----END OPENSSH PRIVATE KEY-----\n"
72 #define MARK_BEGIN_LEN		(sizeof(MARK_BEGIN) - 1)
73 #define MARK_END_LEN		(sizeof(MARK_END) - 1)
74 #define KDFNAME			"bcrypt"
75 #define AUTH_MAGIC		"openssh-key-v1"
76 #define SALT_LEN		16
77 #define DEFAULT_CIPHERNAME	"aes256-ctr"
78 #define	DEFAULT_ROUNDS		16
79 
80 /* Version identification string for SSH v1 identity files. */
81 #define LEGACY_BEGIN		"SSH PRIVATE KEY FILE FORMAT 1.1\n"
82 
83 /*
84  * Constants relating to "shielding" support; protection of keys expected
85  * to remain in memory for long durations
86  */
87 #define SSHKEY_SHIELD_PREKEY_LEN	(16 * 1024)
88 #define SSHKEY_SHIELD_CIPHER		"aes256-ctr" /* XXX want AES-EME* */
89 #define SSHKEY_SHIELD_PREKEY_HASH	SSH_DIGEST_SHA512
90 
91 int	sshkey_private_serialize_opt(struct sshkey *key,
92     struct sshbuf *buf, enum sshkey_serialize_rep);
93 static int sshkey_from_blob_internal(struct sshbuf *buf,
94     struct sshkey **keyp, int allow_cert);
95 
96 /* Supported key types */
97 struct keytype {
98 	const char *name;
99 	const char *shortname;
100 	const char *sigalg;
101 	int type;
102 	int nid;
103 	int cert;
104 	int sigonly;
105 };
106 static const struct keytype keytypes[] = {
107 	{ "ssh-ed25519", "ED25519", NULL, KEY_ED25519, 0, 0, 0 },
108 	{ "ssh-ed25519-cert-v01@openssh.com", "ED25519-CERT", NULL,
109 	    KEY_ED25519_CERT, 0, 1, 0 },
110 	{ "sk-ssh-ed25519@openssh.com", "ED25519-SK", NULL,
111 	    KEY_ED25519_SK, 0, 0, 0 },
112 	{ "sk-ssh-ed25519-cert-v01@openssh.com", "ED25519-SK-CERT", NULL,
113 	    KEY_ED25519_SK_CERT, 0, 1, 0 },
114 #ifdef WITH_XMSS
115 	{ "ssh-xmss@openssh.com", "XMSS", NULL, KEY_XMSS, 0, 0, 0 },
116 	{ "ssh-xmss-cert-v01@openssh.com", "XMSS-CERT", NULL,
117 	    KEY_XMSS_CERT, 0, 1, 0 },
118 #endif /* WITH_XMSS */
119 #ifdef WITH_OPENSSL
120 	{ "ssh-rsa", "RSA", NULL, KEY_RSA, 0, 0, 0 },
121 	{ "rsa-sha2-256", "RSA", NULL, KEY_RSA, 0, 0, 1 },
122 	{ "rsa-sha2-512", "RSA", NULL, KEY_RSA, 0, 0, 1 },
123 	{ "ssh-dss", "DSA", NULL, KEY_DSA, 0, 0, 0 },
124 # ifdef OPENSSL_HAS_ECC
125 	{ "ecdsa-sha2-nistp256", "ECDSA", NULL,
126 	    KEY_ECDSA, NID_X9_62_prime256v1, 0, 0 },
127 	{ "ecdsa-sha2-nistp384", "ECDSA", NULL,
128 	    KEY_ECDSA, NID_secp384r1, 0, 0 },
129 #  ifdef OPENSSL_HAS_NISTP521
130 	{ "ecdsa-sha2-nistp521", "ECDSA", NULL,
131 	    KEY_ECDSA, NID_secp521r1, 0, 0 },
132 #  endif /* OPENSSL_HAS_NISTP521 */
133 	{ "sk-ecdsa-sha2-nistp256@openssh.com", "ECDSA-SK", NULL,
134 	    KEY_ECDSA_SK, NID_X9_62_prime256v1, 0, 0 },
135 # endif /* OPENSSL_HAS_ECC */
136 	{ "ssh-rsa-cert-v01@openssh.com", "RSA-CERT", NULL,
137 	    KEY_RSA_CERT, 0, 1, 0 },
138 	{ "rsa-sha2-256-cert-v01@openssh.com", "RSA-CERT",
139 	    "rsa-sha2-256", KEY_RSA_CERT, 0, 1, 1 },
140 	{ "rsa-sha2-512-cert-v01@openssh.com", "RSA-CERT",
141 	    "rsa-sha2-512", KEY_RSA_CERT, 0, 1, 1 },
142 	{ "ssh-dss-cert-v01@openssh.com", "DSA-CERT", NULL,
143 	    KEY_DSA_CERT, 0, 1, 0 },
144 # ifdef OPENSSL_HAS_ECC
145 	{ "ecdsa-sha2-nistp256-cert-v01@openssh.com", "ECDSA-CERT", NULL,
146 	    KEY_ECDSA_CERT, NID_X9_62_prime256v1, 1, 0 },
147 	{ "ecdsa-sha2-nistp384-cert-v01@openssh.com", "ECDSA-CERT", NULL,
148 	    KEY_ECDSA_CERT, NID_secp384r1, 1, 0 },
149 #  ifdef OPENSSL_HAS_NISTP521
150 	{ "ecdsa-sha2-nistp521-cert-v01@openssh.com", "ECDSA-CERT", NULL,
151 	   KEY_ECDSA_CERT, NID_secp521r1, 1, 0 },
152 #  endif /* OPENSSL_HAS_NISTP521 */
153 	{ "sk-ecdsa-sha2-nistp256-cert-v01@openssh.com", "ECDSA-SK-CERT", NULL,
154 	    KEY_ECDSA_SK_CERT, NID_X9_62_prime256v1, 1, 0 },
155 # endif /* OPENSSL_HAS_ECC */
156 #endif /* WITH_OPENSSL */
157 	{ NULL, NULL, NULL, -1, -1, 0, 0 }
158 };
159 
160 const char *
sshkey_type(const struct sshkey * k)161 sshkey_type(const struct sshkey *k)
162 {
163 	const struct keytype *kt;
164 
165 	for (kt = keytypes; kt->type != -1; kt++) {
166 		if (kt->type == k->type)
167 			return kt->shortname;
168 	}
169 	return "unknown";
170 }
171 
172 static const char *
sshkey_ssh_name_from_type_nid(int type,int nid)173 sshkey_ssh_name_from_type_nid(int type, int nid)
174 {
175 	const struct keytype *kt;
176 
177 	for (kt = keytypes; kt->type != -1; kt++) {
178 		if (kt->type == type && (kt->nid == 0 || kt->nid == nid))
179 			return kt->name;
180 	}
181 	return "ssh-unknown";
182 }
183 
184 int
sshkey_type_is_cert(int type)185 sshkey_type_is_cert(int type)
186 {
187 	const struct keytype *kt;
188 
189 	for (kt = keytypes; kt->type != -1; kt++) {
190 		if (kt->type == type)
191 			return kt->cert;
192 	}
193 	return 0;
194 }
195 
196 const char *
sshkey_ssh_name(const struct sshkey * k)197 sshkey_ssh_name(const struct sshkey *k)
198 {
199 	return sshkey_ssh_name_from_type_nid(k->type, k->ecdsa_nid);
200 }
201 
202 const char *
sshkey_ssh_name_plain(const struct sshkey * k)203 sshkey_ssh_name_plain(const struct sshkey *k)
204 {
205 	return sshkey_ssh_name_from_type_nid(sshkey_type_plain(k->type),
206 	    k->ecdsa_nid);
207 }
208 
209 int
sshkey_type_from_name(const char * name)210 sshkey_type_from_name(const char *name)
211 {
212 	const struct keytype *kt;
213 
214 	for (kt = keytypes; kt->type != -1; kt++) {
215 		/* Only allow shortname matches for plain key types */
216 		if ((kt->name != NULL && strcmp(name, kt->name) == 0) ||
217 		    (!kt->cert && strcasecmp(kt->shortname, name) == 0))
218 			return kt->type;
219 	}
220 	return KEY_UNSPEC;
221 }
222 
223 static int
key_type_is_ecdsa_variant(int type)224 key_type_is_ecdsa_variant(int type)
225 {
226 	switch (type) {
227 	case KEY_ECDSA:
228 	case KEY_ECDSA_CERT:
229 	case KEY_ECDSA_SK:
230 	case KEY_ECDSA_SK_CERT:
231 		return 1;
232 	}
233 	return 0;
234 }
235 
236 int
sshkey_ecdsa_nid_from_name(const char * name)237 sshkey_ecdsa_nid_from_name(const char *name)
238 {
239 	const struct keytype *kt;
240 
241 	for (kt = keytypes; kt->type != -1; kt++) {
242 		if (!key_type_is_ecdsa_variant(kt->type))
243 			continue;
244 		if (kt->name != NULL && strcmp(name, kt->name) == 0)
245 			return kt->nid;
246 	}
247 	return -1;
248 }
249 
250 char *
sshkey_alg_list(int certs_only,int plain_only,int include_sigonly,char sep)251 sshkey_alg_list(int certs_only, int plain_only, int include_sigonly, char sep)
252 {
253 	char *tmp, *ret = NULL;
254 	size_t nlen, rlen = 0;
255 	const struct keytype *kt;
256 
257 	for (kt = keytypes; kt->type != -1; kt++) {
258 		if (kt->name == NULL)
259 			continue;
260 		if (!include_sigonly && kt->sigonly)
261 			continue;
262 		if ((certs_only && !kt->cert) || (plain_only && kt->cert))
263 			continue;
264 		if (ret != NULL)
265 			ret[rlen++] = sep;
266 		nlen = strlen(kt->name);
267 		if ((tmp = realloc(ret, rlen + nlen + 2)) == NULL) {
268 			free(ret);
269 			return NULL;
270 		}
271 		ret = tmp;
272 		memcpy(ret + rlen, kt->name, nlen + 1);
273 		rlen += nlen;
274 	}
275 	return ret;
276 }
277 
278 int
sshkey_names_valid2(const char * names,int allow_wildcard)279 sshkey_names_valid2(const char *names, int allow_wildcard)
280 {
281 	char *s, *cp, *p;
282 	const struct keytype *kt;
283 	int type;
284 
285 	if (names == NULL || strcmp(names, "") == 0)
286 		return 0;
287 	if ((s = cp = strdup(names)) == NULL)
288 		return 0;
289 	for ((p = strsep(&cp, ",")); p && *p != '\0';
290 	    (p = strsep(&cp, ","))) {
291 		type = sshkey_type_from_name(p);
292 		if (type == KEY_UNSPEC) {
293 			if (allow_wildcard) {
294 				/*
295 				 * Try matching key types against the string.
296 				 * If any has a positive or negative match then
297 				 * the component is accepted.
298 				 */
299 				for (kt = keytypes; kt->type != -1; kt++) {
300 					if (match_pattern_list(kt->name,
301 					    p, 0) != 0)
302 						break;
303 				}
304 				if (kt->type != -1)
305 					continue;
306 			}
307 			free(s);
308 			return 0;
309 		}
310 	}
311 	free(s);
312 	return 1;
313 }
314 
315 u_int
sshkey_size(const struct sshkey * k)316 sshkey_size(const struct sshkey *k)
317 {
318 #ifdef WITH_OPENSSL
319 	const BIGNUM *rsa_n, *dsa_p;
320 #endif /* WITH_OPENSSL */
321 
322 	switch (k->type) {
323 #ifdef WITH_OPENSSL
324 	case KEY_RSA:
325 	case KEY_RSA_CERT:
326 		if (k->rsa == NULL)
327 			return 0;
328 		RSA_get0_key(k->rsa, &rsa_n, NULL, NULL);
329 		return BN_num_bits(rsa_n);
330 	case KEY_DSA:
331 	case KEY_DSA_CERT:
332 		if (k->dsa == NULL)
333 			return 0;
334 		DSA_get0_pqg(k->dsa, &dsa_p, NULL, NULL);
335 		return BN_num_bits(dsa_p);
336 	case KEY_ECDSA:
337 	case KEY_ECDSA_CERT:
338 	case KEY_ECDSA_SK:
339 	case KEY_ECDSA_SK_CERT:
340 		return sshkey_curve_nid_to_bits(k->ecdsa_nid);
341 #endif /* WITH_OPENSSL */
342 	case KEY_ED25519:
343 	case KEY_ED25519_CERT:
344 	case KEY_ED25519_SK:
345 	case KEY_ED25519_SK_CERT:
346 	case KEY_XMSS:
347 	case KEY_XMSS_CERT:
348 		return 256;	/* XXX */
349 	}
350 	return 0;
351 }
352 
353 static int
sshkey_type_is_valid_ca(int type)354 sshkey_type_is_valid_ca(int type)
355 {
356 	switch (type) {
357 	case KEY_RSA:
358 	case KEY_DSA:
359 	case KEY_ECDSA:
360 	case KEY_ECDSA_SK:
361 	case KEY_ED25519:
362 	case KEY_ED25519_SK:
363 	case KEY_XMSS:
364 		return 1;
365 	default:
366 		return 0;
367 	}
368 }
369 
370 int
sshkey_is_cert(const struct sshkey * k)371 sshkey_is_cert(const struct sshkey *k)
372 {
373 	if (k == NULL)
374 		return 0;
375 	return sshkey_type_is_cert(k->type);
376 }
377 
378 int
sshkey_is_sk(const struct sshkey * k)379 sshkey_is_sk(const struct sshkey *k)
380 {
381 	if (k == NULL)
382 		return 0;
383 	switch (sshkey_type_plain(k->type)) {
384 	case KEY_ECDSA_SK:
385 	case KEY_ED25519_SK:
386 		return 1;
387 	default:
388 		return 0;
389 	}
390 }
391 
392 /* Return the cert-less equivalent to a certified key type */
393 int
sshkey_type_plain(int type)394 sshkey_type_plain(int type)
395 {
396 	switch (type) {
397 	case KEY_RSA_CERT:
398 		return KEY_RSA;
399 	case KEY_DSA_CERT:
400 		return KEY_DSA;
401 	case KEY_ECDSA_CERT:
402 		return KEY_ECDSA;
403 	case KEY_ECDSA_SK_CERT:
404 		return KEY_ECDSA_SK;
405 	case KEY_ED25519_CERT:
406 		return KEY_ED25519;
407 	case KEY_ED25519_SK_CERT:
408 		return KEY_ED25519_SK;
409 	case KEY_XMSS_CERT:
410 		return KEY_XMSS;
411 	default:
412 		return type;
413 	}
414 }
415 
416 #ifdef WITH_OPENSSL
417 /* XXX: these are really begging for a table-driven approach */
418 int
sshkey_curve_name_to_nid(const char * name)419 sshkey_curve_name_to_nid(const char *name)
420 {
421 	if (strcmp(name, "nistp256") == 0)
422 		return NID_X9_62_prime256v1;
423 	else if (strcmp(name, "nistp384") == 0)
424 		return NID_secp384r1;
425 # ifdef OPENSSL_HAS_NISTP521
426 	else if (strcmp(name, "nistp521") == 0)
427 		return NID_secp521r1;
428 # endif /* OPENSSL_HAS_NISTP521 */
429 	else
430 		return -1;
431 }
432 
433 u_int
sshkey_curve_nid_to_bits(int nid)434 sshkey_curve_nid_to_bits(int nid)
435 {
436 	switch (nid) {
437 	case NID_X9_62_prime256v1:
438 		return 256;
439 	case NID_secp384r1:
440 		return 384;
441 # ifdef OPENSSL_HAS_NISTP521
442 	case NID_secp521r1:
443 		return 521;
444 # endif /* OPENSSL_HAS_NISTP521 */
445 	default:
446 		return 0;
447 	}
448 }
449 
450 int
sshkey_ecdsa_bits_to_nid(int bits)451 sshkey_ecdsa_bits_to_nid(int bits)
452 {
453 	switch (bits) {
454 	case 256:
455 		return NID_X9_62_prime256v1;
456 	case 384:
457 		return NID_secp384r1;
458 # ifdef OPENSSL_HAS_NISTP521
459 	case 521:
460 		return NID_secp521r1;
461 # endif /* OPENSSL_HAS_NISTP521 */
462 	default:
463 		return -1;
464 	}
465 }
466 
467 const char *
sshkey_curve_nid_to_name(int nid)468 sshkey_curve_nid_to_name(int nid)
469 {
470 	switch (nid) {
471 	case NID_X9_62_prime256v1:
472 		return "nistp256";
473 	case NID_secp384r1:
474 		return "nistp384";
475 # ifdef OPENSSL_HAS_NISTP521
476 	case NID_secp521r1:
477 		return "nistp521";
478 # endif /* OPENSSL_HAS_NISTP521 */
479 	default:
480 		return NULL;
481 	}
482 }
483 
484 int
sshkey_ec_nid_to_hash_alg(int nid)485 sshkey_ec_nid_to_hash_alg(int nid)
486 {
487 	int kbits = sshkey_curve_nid_to_bits(nid);
488 
489 	if (kbits <= 0)
490 		return -1;
491 
492 	/* RFC5656 section 6.2.1 */
493 	if (kbits <= 256)
494 		return SSH_DIGEST_SHA256;
495 	else if (kbits <= 384)
496 		return SSH_DIGEST_SHA384;
497 	else
498 		return SSH_DIGEST_SHA512;
499 }
500 #endif /* WITH_OPENSSL */
501 
502 static void
cert_free(struct sshkey_cert * cert)503 cert_free(struct sshkey_cert *cert)
504 {
505 	u_int i;
506 
507 	if (cert == NULL)
508 		return;
509 	sshbuf_free(cert->certblob);
510 	sshbuf_free(cert->critical);
511 	sshbuf_free(cert->extensions);
512 	free(cert->key_id);
513 	for (i = 0; i < cert->nprincipals; i++)
514 		free(cert->principals[i]);
515 	free(cert->principals);
516 	sshkey_free(cert->signature_key);
517 	free(cert->signature_type);
518 	freezero(cert, sizeof(*cert));
519 }
520 
521 static struct sshkey_cert *
cert_new(void)522 cert_new(void)
523 {
524 	struct sshkey_cert *cert;
525 
526 	if ((cert = calloc(1, sizeof(*cert))) == NULL)
527 		return NULL;
528 	if ((cert->certblob = sshbuf_new()) == NULL ||
529 	    (cert->critical = sshbuf_new()) == NULL ||
530 	    (cert->extensions = sshbuf_new()) == NULL) {
531 		cert_free(cert);
532 		return NULL;
533 	}
534 	cert->key_id = NULL;
535 	cert->principals = NULL;
536 	cert->signature_key = NULL;
537 	cert->signature_type = NULL;
538 	return cert;
539 }
540 
541 struct sshkey *
sshkey_new(int type)542 sshkey_new(int type)
543 {
544 	struct sshkey *k;
545 #ifdef WITH_OPENSSL
546 	RSA *rsa;
547 	DSA *dsa;
548 #endif /* WITH_OPENSSL */
549 
550 	if ((k = calloc(1, sizeof(*k))) == NULL)
551 		return NULL;
552 	k->type = type;
553 	k->ecdsa = NULL;
554 	k->ecdsa_nid = -1;
555 	k->dsa = NULL;
556 	k->rsa = NULL;
557 	k->cert = NULL;
558 	k->ed25519_sk = NULL;
559 	k->ed25519_pk = NULL;
560 	k->xmss_sk = NULL;
561 	k->xmss_pk = NULL;
562 	switch (k->type) {
563 #ifdef WITH_OPENSSL
564 	case KEY_RSA:
565 	case KEY_RSA_CERT:
566 		if ((rsa = RSA_new()) == NULL) {
567 			free(k);
568 			return NULL;
569 		}
570 		k->rsa = rsa;
571 		break;
572 	case KEY_DSA:
573 	case KEY_DSA_CERT:
574 		if ((dsa = DSA_new()) == NULL) {
575 			free(k);
576 			return NULL;
577 		}
578 		k->dsa = dsa;
579 		break;
580 	case KEY_ECDSA:
581 	case KEY_ECDSA_CERT:
582 	case KEY_ECDSA_SK:
583 	case KEY_ECDSA_SK_CERT:
584 		/* Cannot do anything until we know the group */
585 		break;
586 #endif /* WITH_OPENSSL */
587 	case KEY_ED25519:
588 	case KEY_ED25519_CERT:
589 	case KEY_ED25519_SK:
590 	case KEY_ED25519_SK_CERT:
591 	case KEY_XMSS:
592 	case KEY_XMSS_CERT:
593 		/* no need to prealloc */
594 		break;
595 	case KEY_UNSPEC:
596 		break;
597 	default:
598 		free(k);
599 		return NULL;
600 	}
601 
602 	if (sshkey_is_cert(k)) {
603 		if ((k->cert = cert_new()) == NULL) {
604 			sshkey_free(k);
605 			return NULL;
606 		}
607 	}
608 
609 	return k;
610 }
611 
612 void
sshkey_free(struct sshkey * k)613 sshkey_free(struct sshkey *k)
614 {
615 	if (k == NULL)
616 		return;
617 	switch (k->type) {
618 #ifdef WITH_OPENSSL
619 	case KEY_RSA:
620 	case KEY_RSA_CERT:
621 		RSA_free(k->rsa);
622 		k->rsa = NULL;
623 		break;
624 	case KEY_DSA:
625 	case KEY_DSA_CERT:
626 		DSA_free(k->dsa);
627 		k->dsa = NULL;
628 		break;
629 # ifdef OPENSSL_HAS_ECC
630 	case KEY_ECDSA_SK:
631 	case KEY_ECDSA_SK_CERT:
632 		free(k->sk_application);
633 		sshbuf_free(k->sk_key_handle);
634 		sshbuf_free(k->sk_reserved);
635 		/* FALLTHROUGH */
636 	case KEY_ECDSA:
637 	case KEY_ECDSA_CERT:
638 		EC_KEY_free(k->ecdsa);
639 		k->ecdsa = NULL;
640 		break;
641 # endif /* OPENSSL_HAS_ECC */
642 #endif /* WITH_OPENSSL */
643 	case KEY_ED25519_SK:
644 	case KEY_ED25519_SK_CERT:
645 		free(k->sk_application);
646 		sshbuf_free(k->sk_key_handle);
647 		sshbuf_free(k->sk_reserved);
648 		/* FALLTHROUGH */
649 	case KEY_ED25519:
650 	case KEY_ED25519_CERT:
651 		freezero(k->ed25519_pk, ED25519_PK_SZ);
652 		k->ed25519_pk = NULL;
653 		freezero(k->ed25519_sk, ED25519_SK_SZ);
654 		k->ed25519_sk = NULL;
655 		break;
656 #ifdef WITH_XMSS
657 	case KEY_XMSS:
658 	case KEY_XMSS_CERT:
659 		freezero(k->xmss_pk, sshkey_xmss_pklen(k));
660 		k->xmss_pk = NULL;
661 		freezero(k->xmss_sk, sshkey_xmss_sklen(k));
662 		k->xmss_sk = NULL;
663 		sshkey_xmss_free_state(k);
664 		free(k->xmss_name);
665 		k->xmss_name = NULL;
666 		free(k->xmss_filename);
667 		k->xmss_filename = NULL;
668 		break;
669 #endif /* WITH_XMSS */
670 	case KEY_UNSPEC:
671 		break;
672 	default:
673 		break;
674 	}
675 	if (sshkey_is_cert(k))
676 		cert_free(k->cert);
677 	freezero(k->shielded_private, k->shielded_len);
678 	freezero(k->shield_prekey, k->shield_prekey_len);
679 	freezero(k, sizeof(*k));
680 }
681 
682 static int
cert_compare(struct sshkey_cert * a,struct sshkey_cert * b)683 cert_compare(struct sshkey_cert *a, struct sshkey_cert *b)
684 {
685 	if (a == NULL && b == NULL)
686 		return 1;
687 	if (a == NULL || b == NULL)
688 		return 0;
689 	if (sshbuf_len(a->certblob) != sshbuf_len(b->certblob))
690 		return 0;
691 	if (timingsafe_bcmp(sshbuf_ptr(a->certblob), sshbuf_ptr(b->certblob),
692 	    sshbuf_len(a->certblob)) != 0)
693 		return 0;
694 	return 1;
695 }
696 
697 /*
698  * Compare public portions of key only, allowing comparisons between
699  * certificates and plain keys too.
700  */
701 int
sshkey_equal_public(const struct sshkey * a,const struct sshkey * b)702 sshkey_equal_public(const struct sshkey *a, const struct sshkey *b)
703 {
704 #if defined(WITH_OPENSSL)
705 	const BIGNUM *rsa_e_a, *rsa_n_a;
706 	const BIGNUM *rsa_e_b, *rsa_n_b;
707 	const BIGNUM *dsa_p_a, *dsa_q_a, *dsa_g_a, *dsa_pub_key_a;
708 	const BIGNUM *dsa_p_b, *dsa_q_b, *dsa_g_b, *dsa_pub_key_b;
709 #endif /* WITH_OPENSSL */
710 
711 	if (a == NULL || b == NULL ||
712 	    sshkey_type_plain(a->type) != sshkey_type_plain(b->type))
713 		return 0;
714 
715 	switch (a->type) {
716 #ifdef WITH_OPENSSL
717 	case KEY_RSA_CERT:
718 	case KEY_RSA:
719 		if (a->rsa == NULL || b->rsa == NULL)
720 			return 0;
721 		RSA_get0_key(a->rsa, &rsa_n_a, &rsa_e_a, NULL);
722 		RSA_get0_key(b->rsa, &rsa_n_b, &rsa_e_b, NULL);
723 		return BN_cmp(rsa_e_a, rsa_e_b) == 0 &&
724 		    BN_cmp(rsa_n_a, rsa_n_b) == 0;
725 	case KEY_DSA_CERT:
726 	case KEY_DSA:
727 		if (a->dsa == NULL || b->dsa == NULL)
728 			return 0;
729 		DSA_get0_pqg(a->dsa, &dsa_p_a, &dsa_q_a, &dsa_g_a);
730 		DSA_get0_pqg(b->dsa, &dsa_p_b, &dsa_q_b, &dsa_g_b);
731 		DSA_get0_key(a->dsa, &dsa_pub_key_a, NULL);
732 		DSA_get0_key(b->dsa, &dsa_pub_key_b, NULL);
733 		return BN_cmp(dsa_p_a, dsa_p_b) == 0 &&
734 		    BN_cmp(dsa_q_a, dsa_q_b) == 0 &&
735 		    BN_cmp(dsa_g_a, dsa_g_b) == 0 &&
736 		    BN_cmp(dsa_pub_key_a, dsa_pub_key_b) == 0;
737 # ifdef OPENSSL_HAS_ECC
738 	case KEY_ECDSA_SK:
739 	case KEY_ECDSA_SK_CERT:
740 		if (a->sk_application == NULL || b->sk_application == NULL)
741 			return 0;
742 		if (strcmp(a->sk_application, b->sk_application) != 0)
743 			return 0;
744 		/* FALLTHROUGH */
745 	case KEY_ECDSA_CERT:
746 	case KEY_ECDSA:
747 		if (a->ecdsa == NULL || b->ecdsa == NULL ||
748 		    EC_KEY_get0_public_key(a->ecdsa) == NULL ||
749 		    EC_KEY_get0_public_key(b->ecdsa) == NULL)
750 			return 0;
751 		if (EC_GROUP_cmp(EC_KEY_get0_group(a->ecdsa),
752 		    EC_KEY_get0_group(b->ecdsa), NULL) != 0 ||
753 		    EC_POINT_cmp(EC_KEY_get0_group(a->ecdsa),
754 		    EC_KEY_get0_public_key(a->ecdsa),
755 		    EC_KEY_get0_public_key(b->ecdsa), NULL) != 0)
756 			return 0;
757 		return 1;
758 # endif /* OPENSSL_HAS_ECC */
759 #endif /* WITH_OPENSSL */
760 	case KEY_ED25519_SK:
761 	case KEY_ED25519_SK_CERT:
762 		if (a->sk_application == NULL || b->sk_application == NULL)
763 			return 0;
764 		if (strcmp(a->sk_application, b->sk_application) != 0)
765 			return 0;
766 		/* FALLTHROUGH */
767 	case KEY_ED25519:
768 	case KEY_ED25519_CERT:
769 		return a->ed25519_pk != NULL && b->ed25519_pk != NULL &&
770 		    memcmp(a->ed25519_pk, b->ed25519_pk, ED25519_PK_SZ) == 0;
771 #ifdef WITH_XMSS
772 	case KEY_XMSS:
773 	case KEY_XMSS_CERT:
774 		return a->xmss_pk != NULL && b->xmss_pk != NULL &&
775 		    sshkey_xmss_pklen(a) == sshkey_xmss_pklen(b) &&
776 		    memcmp(a->xmss_pk, b->xmss_pk, sshkey_xmss_pklen(a)) == 0;
777 #endif /* WITH_XMSS */
778 	default:
779 		return 0;
780 	}
781 	/* NOTREACHED */
782 }
783 
784 int
sshkey_equal(const struct sshkey * a,const struct sshkey * b)785 sshkey_equal(const struct sshkey *a, const struct sshkey *b)
786 {
787 	if (a == NULL || b == NULL || a->type != b->type)
788 		return 0;
789 	if (sshkey_is_cert(a)) {
790 		if (!cert_compare(a->cert, b->cert))
791 			return 0;
792 	}
793 	return sshkey_equal_public(a, b);
794 }
795 
796 static int
to_blob_buf(const struct sshkey * key,struct sshbuf * b,int force_plain,enum sshkey_serialize_rep opts)797 to_blob_buf(const struct sshkey *key, struct sshbuf *b, int force_plain,
798   enum sshkey_serialize_rep opts)
799 {
800 	int type, ret = SSH_ERR_INTERNAL_ERROR;
801 	const char *typename;
802 #ifdef WITH_OPENSSL
803 	const BIGNUM *rsa_n, *rsa_e, *dsa_p, *dsa_q, *dsa_g, *dsa_pub_key;
804 #endif /* WITH_OPENSSL */
805 
806 	if (key == NULL)
807 		return SSH_ERR_INVALID_ARGUMENT;
808 
809 	if (sshkey_is_cert(key)) {
810 		if (key->cert == NULL)
811 			return SSH_ERR_EXPECTED_CERT;
812 		if (sshbuf_len(key->cert->certblob) == 0)
813 			return SSH_ERR_KEY_LACKS_CERTBLOB;
814 	}
815 	type = force_plain ? sshkey_type_plain(key->type) : key->type;
816 	typename = sshkey_ssh_name_from_type_nid(type, key->ecdsa_nid);
817 
818 	switch (type) {
819 #ifdef WITH_OPENSSL
820 	case KEY_DSA_CERT:
821 	case KEY_ECDSA_CERT:
822 	case KEY_ECDSA_SK_CERT:
823 	case KEY_RSA_CERT:
824 #endif /* WITH_OPENSSL */
825 	case KEY_ED25519_CERT:
826 	case KEY_ED25519_SK_CERT:
827 #ifdef WITH_XMSS
828 	case KEY_XMSS_CERT:
829 #endif /* WITH_XMSS */
830 		/* Use the existing blob */
831 		/* XXX modified flag? */
832 		if ((ret = sshbuf_putb(b, key->cert->certblob)) != 0)
833 			return ret;
834 		break;
835 #ifdef WITH_OPENSSL
836 	case KEY_DSA:
837 		if (key->dsa == NULL)
838 			return SSH_ERR_INVALID_ARGUMENT;
839 		DSA_get0_pqg(key->dsa, &dsa_p, &dsa_q, &dsa_g);
840 		DSA_get0_key(key->dsa, &dsa_pub_key, NULL);
841 		if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
842 		    (ret = sshbuf_put_bignum2(b, dsa_p)) != 0 ||
843 		    (ret = sshbuf_put_bignum2(b, dsa_q)) != 0 ||
844 		    (ret = sshbuf_put_bignum2(b, dsa_g)) != 0 ||
845 		    (ret = sshbuf_put_bignum2(b, dsa_pub_key)) != 0)
846 			return ret;
847 		break;
848 # ifdef OPENSSL_HAS_ECC
849 	case KEY_ECDSA:
850 	case KEY_ECDSA_SK:
851 		if (key->ecdsa == NULL)
852 			return SSH_ERR_INVALID_ARGUMENT;
853 		if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
854 		    (ret = sshbuf_put_cstring(b,
855 		    sshkey_curve_nid_to_name(key->ecdsa_nid))) != 0 ||
856 		    (ret = sshbuf_put_eckey(b, key->ecdsa)) != 0)
857 			return ret;
858 		if (type == KEY_ECDSA_SK) {
859 			if ((ret = sshbuf_put_cstring(b,
860 			    key->sk_application)) != 0)
861 				return ret;
862 		}
863 		break;
864 # endif
865 	case KEY_RSA:
866 		if (key->rsa == NULL)
867 			return SSH_ERR_INVALID_ARGUMENT;
868 		RSA_get0_key(key->rsa, &rsa_n, &rsa_e, NULL);
869 		if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
870 		    (ret = sshbuf_put_bignum2(b, rsa_e)) != 0 ||
871 		    (ret = sshbuf_put_bignum2(b, rsa_n)) != 0)
872 			return ret;
873 		break;
874 #endif /* WITH_OPENSSL */
875 	case KEY_ED25519:
876 	case KEY_ED25519_SK:
877 		if (key->ed25519_pk == NULL)
878 			return SSH_ERR_INVALID_ARGUMENT;
879 		if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
880 		    (ret = sshbuf_put_string(b,
881 		    key->ed25519_pk, ED25519_PK_SZ)) != 0)
882 			return ret;
883 		if (type == KEY_ED25519_SK) {
884 			if ((ret = sshbuf_put_cstring(b,
885 			    key->sk_application)) != 0)
886 				return ret;
887 		}
888 		break;
889 #ifdef WITH_XMSS
890 	case KEY_XMSS:
891 		if (key->xmss_name == NULL || key->xmss_pk == NULL ||
892 		    sshkey_xmss_pklen(key) == 0)
893 			return SSH_ERR_INVALID_ARGUMENT;
894 		if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
895 		    (ret = sshbuf_put_cstring(b, key->xmss_name)) != 0 ||
896 		    (ret = sshbuf_put_string(b,
897 		    key->xmss_pk, sshkey_xmss_pklen(key))) != 0 ||
898 		    (ret = sshkey_xmss_serialize_pk_info(key, b, opts)) != 0)
899 			return ret;
900 		break;
901 #endif /* WITH_XMSS */
902 	default:
903 		return SSH_ERR_KEY_TYPE_UNKNOWN;
904 	}
905 	return 0;
906 }
907 
908 int
sshkey_putb(const struct sshkey * key,struct sshbuf * b)909 sshkey_putb(const struct sshkey *key, struct sshbuf *b)
910 {
911 	return to_blob_buf(key, b, 0, SSHKEY_SERIALIZE_DEFAULT);
912 }
913 
914 int
sshkey_puts_opts(const struct sshkey * key,struct sshbuf * b,enum sshkey_serialize_rep opts)915 sshkey_puts_opts(const struct sshkey *key, struct sshbuf *b,
916     enum sshkey_serialize_rep opts)
917 {
918 	struct sshbuf *tmp;
919 	int r;
920 
921 	if ((tmp = sshbuf_new()) == NULL)
922 		return SSH_ERR_ALLOC_FAIL;
923 	r = to_blob_buf(key, tmp, 0, opts);
924 	if (r == 0)
925 		r = sshbuf_put_stringb(b, tmp);
926 	sshbuf_free(tmp);
927 	return r;
928 }
929 
930 int
sshkey_puts(const struct sshkey * key,struct sshbuf * b)931 sshkey_puts(const struct sshkey *key, struct sshbuf *b)
932 {
933 	return sshkey_puts_opts(key, b, SSHKEY_SERIALIZE_DEFAULT);
934 }
935 
936 int
sshkey_putb_plain(const struct sshkey * key,struct sshbuf * b)937 sshkey_putb_plain(const struct sshkey *key, struct sshbuf *b)
938 {
939 	return to_blob_buf(key, b, 1, SSHKEY_SERIALIZE_DEFAULT);
940 }
941 
942 static int
to_blob(const struct sshkey * key,u_char ** blobp,size_t * lenp,int force_plain,enum sshkey_serialize_rep opts)943 to_blob(const struct sshkey *key, u_char **blobp, size_t *lenp, int force_plain,
944     enum sshkey_serialize_rep opts)
945 {
946 	int ret = SSH_ERR_INTERNAL_ERROR;
947 	size_t len;
948 	struct sshbuf *b = NULL;
949 
950 	if (lenp != NULL)
951 		*lenp = 0;
952 	if (blobp != NULL)
953 		*blobp = NULL;
954 	if ((b = sshbuf_new()) == NULL)
955 		return SSH_ERR_ALLOC_FAIL;
956 	if ((ret = to_blob_buf(key, b, force_plain, opts)) != 0)
957 		goto out;
958 	len = sshbuf_len(b);
959 	if (lenp != NULL)
960 		*lenp = len;
961 	if (blobp != NULL) {
962 		if ((*blobp = malloc(len)) == NULL) {
963 			ret = SSH_ERR_ALLOC_FAIL;
964 			goto out;
965 		}
966 		memcpy(*blobp, sshbuf_ptr(b), len);
967 	}
968 	ret = 0;
969  out:
970 	sshbuf_free(b);
971 	return ret;
972 }
973 
974 int
sshkey_to_blob(const struct sshkey * key,u_char ** blobp,size_t * lenp)975 sshkey_to_blob(const struct sshkey *key, u_char **blobp, size_t *lenp)
976 {
977 	return to_blob(key, blobp, lenp, 0, SSHKEY_SERIALIZE_DEFAULT);
978 }
979 
980 int
sshkey_plain_to_blob(const struct sshkey * key,u_char ** blobp,size_t * lenp)981 sshkey_plain_to_blob(const struct sshkey *key, u_char **blobp, size_t *lenp)
982 {
983 	return to_blob(key, blobp, lenp, 1, SSHKEY_SERIALIZE_DEFAULT);
984 }
985 
986 int
sshkey_fingerprint_raw(const struct sshkey * k,int dgst_alg,u_char ** retp,size_t * lenp)987 sshkey_fingerprint_raw(const struct sshkey *k, int dgst_alg,
988     u_char **retp, size_t *lenp)
989 {
990 	u_char *blob = NULL, *ret = NULL;
991 	size_t blob_len = 0;
992 	int r = SSH_ERR_INTERNAL_ERROR;
993 
994 	if (retp != NULL)
995 		*retp = NULL;
996 	if (lenp != NULL)
997 		*lenp = 0;
998 	if (ssh_digest_bytes(dgst_alg) == 0) {
999 		r = SSH_ERR_INVALID_ARGUMENT;
1000 		goto out;
1001 	}
1002 	if ((r = to_blob(k, &blob, &blob_len, 1, SSHKEY_SERIALIZE_DEFAULT))
1003 	    != 0)
1004 		goto out;
1005 	if ((ret = calloc(1, SSH_DIGEST_MAX_LENGTH)) == NULL) {
1006 		r = SSH_ERR_ALLOC_FAIL;
1007 		goto out;
1008 	}
1009 	if ((r = ssh_digest_memory(dgst_alg, blob, blob_len,
1010 	    ret, SSH_DIGEST_MAX_LENGTH)) != 0)
1011 		goto out;
1012 	/* success */
1013 	if (retp != NULL) {
1014 		*retp = ret;
1015 		ret = NULL;
1016 	}
1017 	if (lenp != NULL)
1018 		*lenp = ssh_digest_bytes(dgst_alg);
1019 	r = 0;
1020  out:
1021 	free(ret);
1022 	if (blob != NULL)
1023 		freezero(blob, blob_len);
1024 	return r;
1025 }
1026 
1027 static char *
fingerprint_b64(const char * alg,u_char * dgst_raw,size_t dgst_raw_len)1028 fingerprint_b64(const char *alg, u_char *dgst_raw, size_t dgst_raw_len)
1029 {
1030 	char *ret;
1031 	size_t plen = strlen(alg) + 1;
1032 	size_t rlen = ((dgst_raw_len + 2) / 3) * 4 + plen + 1;
1033 
1034 	if (dgst_raw_len > 65536 || (ret = calloc(1, rlen)) == NULL)
1035 		return NULL;
1036 	strlcpy(ret, alg, rlen);
1037 	strlcat(ret, ":", rlen);
1038 	if (dgst_raw_len == 0)
1039 		return ret;
1040 	if (b64_ntop(dgst_raw, dgst_raw_len, ret + plen, rlen - plen) == -1) {
1041 		freezero(ret, rlen);
1042 		return NULL;
1043 	}
1044 	/* Trim padding characters from end */
1045 	ret[strcspn(ret, "=")] = '\0';
1046 	return ret;
1047 }
1048 
1049 static char *
fingerprint_hex(const char * alg,u_char * dgst_raw,size_t dgst_raw_len)1050 fingerprint_hex(const char *alg, u_char *dgst_raw, size_t dgst_raw_len)
1051 {
1052 	char *retval, hex[5];
1053 	size_t i, rlen = dgst_raw_len * 3 + strlen(alg) + 2;
1054 
1055 	if (dgst_raw_len > 65536 || (retval = calloc(1, rlen)) == NULL)
1056 		return NULL;
1057 	strlcpy(retval, alg, rlen);
1058 	strlcat(retval, ":", rlen);
1059 	for (i = 0; i < dgst_raw_len; i++) {
1060 		snprintf(hex, sizeof(hex), "%s%02x",
1061 		    i > 0 ? ":" : "", dgst_raw[i]);
1062 		strlcat(retval, hex, rlen);
1063 	}
1064 	return retval;
1065 }
1066 
1067 static char *
fingerprint_bubblebabble(u_char * dgst_raw,size_t dgst_raw_len)1068 fingerprint_bubblebabble(u_char *dgst_raw, size_t dgst_raw_len)
1069 {
1070 	char vowels[] = { 'a', 'e', 'i', 'o', 'u', 'y' };
1071 	char consonants[] = { 'b', 'c', 'd', 'f', 'g', 'h', 'k', 'l', 'm',
1072 	    'n', 'p', 'r', 's', 't', 'v', 'z', 'x' };
1073 	u_int i, j = 0, rounds, seed = 1;
1074 	char *retval;
1075 
1076 	rounds = (dgst_raw_len / 2) + 1;
1077 	if ((retval = calloc(rounds, 6)) == NULL)
1078 		return NULL;
1079 	retval[j++] = 'x';
1080 	for (i = 0; i < rounds; i++) {
1081 		u_int idx0, idx1, idx2, idx3, idx4;
1082 		if ((i + 1 < rounds) || (dgst_raw_len % 2 != 0)) {
1083 			idx0 = (((((u_int)(dgst_raw[2 * i])) >> 6) & 3) +
1084 			    seed) % 6;
1085 			idx1 = (((u_int)(dgst_raw[2 * i])) >> 2) & 15;
1086 			idx2 = ((((u_int)(dgst_raw[2 * i])) & 3) +
1087 			    (seed / 6)) % 6;
1088 			retval[j++] = vowels[idx0];
1089 			retval[j++] = consonants[idx1];
1090 			retval[j++] = vowels[idx2];
1091 			if ((i + 1) < rounds) {
1092 				idx3 = (((u_int)(dgst_raw[(2 * i) + 1])) >> 4) & 15;
1093 				idx4 = (((u_int)(dgst_raw[(2 * i) + 1]))) & 15;
1094 				retval[j++] = consonants[idx3];
1095 				retval[j++] = '-';
1096 				retval[j++] = consonants[idx4];
1097 				seed = ((seed * 5) +
1098 				    ((((u_int)(dgst_raw[2 * i])) * 7) +
1099 				    ((u_int)(dgst_raw[(2 * i) + 1])))) % 36;
1100 			}
1101 		} else {
1102 			idx0 = seed % 6;
1103 			idx1 = 16;
1104 			idx2 = seed / 6;
1105 			retval[j++] = vowels[idx0];
1106 			retval[j++] = consonants[idx1];
1107 			retval[j++] = vowels[idx2];
1108 		}
1109 	}
1110 	retval[j++] = 'x';
1111 	retval[j++] = '\0';
1112 	return retval;
1113 }
1114 
1115 /*
1116  * Draw an ASCII-Art representing the fingerprint so human brain can
1117  * profit from its built-in pattern recognition ability.
1118  * This technique is called "random art" and can be found in some
1119  * scientific publications like this original paper:
1120  *
1121  * "Hash Visualization: a New Technique to improve Real-World Security",
1122  * Perrig A. and Song D., 1999, International Workshop on Cryptographic
1123  * Techniques and E-Commerce (CrypTEC '99)
1124  * sparrow.ece.cmu.edu/~adrian/projects/validation/validation.pdf
1125  *
1126  * The subject came up in a talk by Dan Kaminsky, too.
1127  *
1128  * If you see the picture is different, the key is different.
1129  * If the picture looks the same, you still know nothing.
1130  *
1131  * The algorithm used here is a worm crawling over a discrete plane,
1132  * leaving a trace (augmenting the field) everywhere it goes.
1133  * Movement is taken from dgst_raw 2bit-wise.  Bumping into walls
1134  * makes the respective movement vector be ignored for this turn.
1135  * Graphs are not unambiguous, because circles in graphs can be
1136  * walked in either direction.
1137  */
1138 
1139 /*
1140  * Field sizes for the random art.  Have to be odd, so the starting point
1141  * can be in the exact middle of the picture, and FLDBASE should be >=8 .
1142  * Else pictures would be too dense, and drawing the frame would
1143  * fail, too, because the key type would not fit in anymore.
1144  */
1145 #define	FLDBASE		8
1146 #define	FLDSIZE_Y	(FLDBASE + 1)
1147 #define	FLDSIZE_X	(FLDBASE * 2 + 1)
1148 static char *
fingerprint_randomart(const char * alg,u_char * dgst_raw,size_t dgst_raw_len,const struct sshkey * k)1149 fingerprint_randomart(const char *alg, u_char *dgst_raw, size_t dgst_raw_len,
1150     const struct sshkey *k)
1151 {
1152 	/*
1153 	 * Chars to be used after each other every time the worm
1154 	 * intersects with itself.  Matter of taste.
1155 	 */
1156 	char	*augmentation_string = " .o+=*BOX@%&#/^SE";
1157 	char	*retval, *p, title[FLDSIZE_X], hash[FLDSIZE_X];
1158 	u_char	 field[FLDSIZE_X][FLDSIZE_Y];
1159 	size_t	 i, tlen, hlen;
1160 	u_int	 b;
1161 	int	 x, y, r;
1162 	size_t	 len = strlen(augmentation_string) - 1;
1163 
1164 	if ((retval = calloc((FLDSIZE_X + 3), (FLDSIZE_Y + 2))) == NULL)
1165 		return NULL;
1166 
1167 	/* initialize field */
1168 	memset(field, 0, FLDSIZE_X * FLDSIZE_Y * sizeof(char));
1169 	x = FLDSIZE_X / 2;
1170 	y = FLDSIZE_Y / 2;
1171 
1172 	/* process raw key */
1173 	for (i = 0; i < dgst_raw_len; i++) {
1174 		int input;
1175 		/* each byte conveys four 2-bit move commands */
1176 		input = dgst_raw[i];
1177 		for (b = 0; b < 4; b++) {
1178 			/* evaluate 2 bit, rest is shifted later */
1179 			x += (input & 0x1) ? 1 : -1;
1180 			y += (input & 0x2) ? 1 : -1;
1181 
1182 			/* assure we are still in bounds */
1183 			x = MAXIMUM(x, 0);
1184 			y = MAXIMUM(y, 0);
1185 			x = MINIMUM(x, FLDSIZE_X - 1);
1186 			y = MINIMUM(y, FLDSIZE_Y - 1);
1187 
1188 			/* augment the field */
1189 			if (field[x][y] < len - 2)
1190 				field[x][y]++;
1191 			input = input >> 2;
1192 		}
1193 	}
1194 
1195 	/* mark starting point and end point*/
1196 	field[FLDSIZE_X / 2][FLDSIZE_Y / 2] = len - 1;
1197 	field[x][y] = len;
1198 
1199 	/* assemble title */
1200 	r = snprintf(title, sizeof(title), "[%s %u]",
1201 		sshkey_type(k), sshkey_size(k));
1202 	/* If [type size] won't fit, then try [type]; fits "[ED25519-CERT]" */
1203 	if (r < 0 || r > (int)sizeof(title))
1204 		r = snprintf(title, sizeof(title), "[%s]", sshkey_type(k));
1205 	tlen = (r <= 0) ? 0 : strlen(title);
1206 
1207 	/* assemble hash ID. */
1208 	r = snprintf(hash, sizeof(hash), "[%s]", alg);
1209 	hlen = (r <= 0) ? 0 : strlen(hash);
1210 
1211 	/* output upper border */
1212 	p = retval;
1213 	*p++ = '+';
1214 	for (i = 0; i < (FLDSIZE_X - tlen) / 2; i++)
1215 		*p++ = '-';
1216 	memcpy(p, title, tlen);
1217 	p += tlen;
1218 	for (i += tlen; i < FLDSIZE_X; i++)
1219 		*p++ = '-';
1220 	*p++ = '+';
1221 	*p++ = '\n';
1222 
1223 	/* output content */
1224 	for (y = 0; y < FLDSIZE_Y; y++) {
1225 		*p++ = '|';
1226 		for (x = 0; x < FLDSIZE_X; x++)
1227 			*p++ = augmentation_string[MINIMUM(field[x][y], len)];
1228 		*p++ = '|';
1229 		*p++ = '\n';
1230 	}
1231 
1232 	/* output lower border */
1233 	*p++ = '+';
1234 	for (i = 0; i < (FLDSIZE_X - hlen) / 2; i++)
1235 		*p++ = '-';
1236 	memcpy(p, hash, hlen);
1237 	p += hlen;
1238 	for (i += hlen; i < FLDSIZE_X; i++)
1239 		*p++ = '-';
1240 	*p++ = '+';
1241 
1242 	return retval;
1243 }
1244 
1245 char *
sshkey_fingerprint(const struct sshkey * k,int dgst_alg,enum sshkey_fp_rep dgst_rep)1246 sshkey_fingerprint(const struct sshkey *k, int dgst_alg,
1247     enum sshkey_fp_rep dgst_rep)
1248 {
1249 	char *retval = NULL;
1250 	u_char *dgst_raw;
1251 	size_t dgst_raw_len;
1252 
1253 	if (sshkey_fingerprint_raw(k, dgst_alg, &dgst_raw, &dgst_raw_len) != 0)
1254 		return NULL;
1255 	switch (dgst_rep) {
1256 	case SSH_FP_DEFAULT:
1257 		if (dgst_alg == SSH_DIGEST_MD5) {
1258 			retval = fingerprint_hex(ssh_digest_alg_name(dgst_alg),
1259 			    dgst_raw, dgst_raw_len);
1260 		} else {
1261 			retval = fingerprint_b64(ssh_digest_alg_name(dgst_alg),
1262 			    dgst_raw, dgst_raw_len);
1263 		}
1264 		break;
1265 	case SSH_FP_HEX:
1266 		retval = fingerprint_hex(ssh_digest_alg_name(dgst_alg),
1267 		    dgst_raw, dgst_raw_len);
1268 		break;
1269 	case SSH_FP_BASE64:
1270 		retval = fingerprint_b64(ssh_digest_alg_name(dgst_alg),
1271 		    dgst_raw, dgst_raw_len);
1272 		break;
1273 	case SSH_FP_BUBBLEBABBLE:
1274 		retval = fingerprint_bubblebabble(dgst_raw, dgst_raw_len);
1275 		break;
1276 	case SSH_FP_RANDOMART:
1277 		retval = fingerprint_randomart(ssh_digest_alg_name(dgst_alg),
1278 		    dgst_raw, dgst_raw_len, k);
1279 		break;
1280 	default:
1281 		freezero(dgst_raw, dgst_raw_len);
1282 		return NULL;
1283 	}
1284 	freezero(dgst_raw, dgst_raw_len);
1285 	return retval;
1286 }
1287 
1288 static int
peek_type_nid(const char * s,size_t l,int * nid)1289 peek_type_nid(const char *s, size_t l, int *nid)
1290 {
1291 	const struct keytype *kt;
1292 
1293 	for (kt = keytypes; kt->type != -1; kt++) {
1294 		if (kt->name == NULL || strlen(kt->name) != l)
1295 			continue;
1296 		if (memcmp(s, kt->name, l) == 0) {
1297 			*nid = -1;
1298 			if (key_type_is_ecdsa_variant(kt->type))
1299 				*nid = kt->nid;
1300 			return kt->type;
1301 		}
1302 	}
1303 	return KEY_UNSPEC;
1304 }
1305 
1306 /* XXX this can now be made const char * */
1307 int
sshkey_read(struct sshkey * ret,char ** cpp)1308 sshkey_read(struct sshkey *ret, char **cpp)
1309 {
1310 	struct sshkey *k;
1311 	char *cp, *blobcopy;
1312 	size_t space;
1313 	int r, type, curve_nid = -1;
1314 	struct sshbuf *blob;
1315 
1316 	if (ret == NULL)
1317 		return SSH_ERR_INVALID_ARGUMENT;
1318 
1319 	switch (ret->type) {
1320 	case KEY_UNSPEC:
1321 	case KEY_RSA:
1322 	case KEY_DSA:
1323 	case KEY_ECDSA:
1324 	case KEY_ECDSA_SK:
1325 	case KEY_ED25519:
1326 	case KEY_ED25519_SK:
1327 	case KEY_DSA_CERT:
1328 	case KEY_ECDSA_CERT:
1329 	case KEY_ECDSA_SK_CERT:
1330 	case KEY_RSA_CERT:
1331 	case KEY_ED25519_CERT:
1332 	case KEY_ED25519_SK_CERT:
1333 #ifdef WITH_XMSS
1334 	case KEY_XMSS:
1335 	case KEY_XMSS_CERT:
1336 #endif /* WITH_XMSS */
1337 		break; /* ok */
1338 	default:
1339 		return SSH_ERR_INVALID_ARGUMENT;
1340 	}
1341 
1342 	/* Decode type */
1343 	cp = *cpp;
1344 	space = strcspn(cp, " \t");
1345 	if (space == strlen(cp))
1346 		return SSH_ERR_INVALID_FORMAT;
1347 	if ((type = peek_type_nid(cp, space, &curve_nid)) == KEY_UNSPEC)
1348 		return SSH_ERR_INVALID_FORMAT;
1349 
1350 	/* skip whitespace */
1351 	for (cp += space; *cp == ' ' || *cp == '\t'; cp++)
1352 		;
1353 	if (*cp == '\0')
1354 		return SSH_ERR_INVALID_FORMAT;
1355 	if (ret->type != KEY_UNSPEC && ret->type != type)
1356 		return SSH_ERR_KEY_TYPE_MISMATCH;
1357 	if ((blob = sshbuf_new()) == NULL)
1358 		return SSH_ERR_ALLOC_FAIL;
1359 
1360 	/* find end of keyblob and decode */
1361 	space = strcspn(cp, " \t");
1362 	if ((blobcopy = strndup(cp, space)) == NULL) {
1363 		sshbuf_free(blob);
1364 		return SSH_ERR_ALLOC_FAIL;
1365 	}
1366 	if ((r = sshbuf_b64tod(blob, blobcopy)) != 0) {
1367 		free(blobcopy);
1368 		sshbuf_free(blob);
1369 		return r;
1370 	}
1371 	free(blobcopy);
1372 	if ((r = sshkey_fromb(blob, &k)) != 0) {
1373 		sshbuf_free(blob);
1374 		return r;
1375 	}
1376 	sshbuf_free(blob);
1377 
1378 	/* skip whitespace and leave cp at start of comment */
1379 	for (cp += space; *cp == ' ' || *cp == '\t'; cp++)
1380 		;
1381 
1382 	/* ensure type of blob matches type at start of line */
1383 	if (k->type != type) {
1384 		sshkey_free(k);
1385 		return SSH_ERR_KEY_TYPE_MISMATCH;
1386 	}
1387 	if (key_type_is_ecdsa_variant(type) && curve_nid != k->ecdsa_nid) {
1388 		sshkey_free(k);
1389 		return SSH_ERR_EC_CURVE_MISMATCH;
1390 	}
1391 
1392 	/* Fill in ret from parsed key */
1393 	ret->type = type;
1394 	if (sshkey_is_cert(ret)) {
1395 		if (!sshkey_is_cert(k)) {
1396 			sshkey_free(k);
1397 			return SSH_ERR_EXPECTED_CERT;
1398 		}
1399 		if (ret->cert != NULL)
1400 			cert_free(ret->cert);
1401 		ret->cert = k->cert;
1402 		k->cert = NULL;
1403 	}
1404 	switch (sshkey_type_plain(ret->type)) {
1405 #ifdef WITH_OPENSSL
1406 	case KEY_RSA:
1407 		RSA_free(ret->rsa);
1408 		ret->rsa = k->rsa;
1409 		k->rsa = NULL;
1410 #ifdef DEBUG_PK
1411 		RSA_print_fp(stderr, ret->rsa, 8);
1412 #endif
1413 		break;
1414 	case KEY_DSA:
1415 		DSA_free(ret->dsa);
1416 		ret->dsa = k->dsa;
1417 		k->dsa = NULL;
1418 #ifdef DEBUG_PK
1419 		DSA_print_fp(stderr, ret->dsa, 8);
1420 #endif
1421 		break;
1422 # ifdef OPENSSL_HAS_ECC
1423 	case KEY_ECDSA:
1424 		EC_KEY_free(ret->ecdsa);
1425 		ret->ecdsa = k->ecdsa;
1426 		ret->ecdsa_nid = k->ecdsa_nid;
1427 		k->ecdsa = NULL;
1428 		k->ecdsa_nid = -1;
1429 #ifdef DEBUG_PK
1430 		sshkey_dump_ec_key(ret->ecdsa);
1431 #endif
1432 		break;
1433 	case KEY_ECDSA_SK:
1434 		EC_KEY_free(ret->ecdsa);
1435 		ret->ecdsa = k->ecdsa;
1436 		ret->ecdsa_nid = k->ecdsa_nid;
1437 		ret->sk_application = k->sk_application;
1438 		k->ecdsa = NULL;
1439 		k->ecdsa_nid = -1;
1440 		k->sk_application = NULL;
1441 #ifdef DEBUG_PK
1442 		sshkey_dump_ec_key(ret->ecdsa);
1443 		fprintf(stderr, "App: %s\n", ret->sk_application);
1444 #endif
1445 		break;
1446 # endif /* OPENSSL_HAS_ECC */
1447 #endif /* WITH_OPENSSL */
1448 	case KEY_ED25519:
1449 		freezero(ret->ed25519_pk, ED25519_PK_SZ);
1450 		ret->ed25519_pk = k->ed25519_pk;
1451 		k->ed25519_pk = NULL;
1452 #ifdef DEBUG_PK
1453 		/* XXX */
1454 #endif
1455 		break;
1456 	case KEY_ED25519_SK:
1457 		freezero(ret->ed25519_pk, ED25519_PK_SZ);
1458 		ret->ed25519_pk = k->ed25519_pk;
1459 		ret->sk_application = k->sk_application;
1460 		k->ed25519_pk = NULL;
1461 		k->sk_application = NULL;
1462 		break;
1463 #ifdef WITH_XMSS
1464 	case KEY_XMSS:
1465 		free(ret->xmss_pk);
1466 		ret->xmss_pk = k->xmss_pk;
1467 		k->xmss_pk = NULL;
1468 		free(ret->xmss_state);
1469 		ret->xmss_state = k->xmss_state;
1470 		k->xmss_state = NULL;
1471 		free(ret->xmss_name);
1472 		ret->xmss_name = k->xmss_name;
1473 		k->xmss_name = NULL;
1474 		free(ret->xmss_filename);
1475 		ret->xmss_filename = k->xmss_filename;
1476 		k->xmss_filename = NULL;
1477 #ifdef DEBUG_PK
1478 		/* XXX */
1479 #endif
1480 		break;
1481 #endif /* WITH_XMSS */
1482 	default:
1483 		sshkey_free(k);
1484 		return SSH_ERR_INTERNAL_ERROR;
1485 	}
1486 	sshkey_free(k);
1487 
1488 	/* success */
1489 	*cpp = cp;
1490 	return 0;
1491 }
1492 
1493 
1494 int
sshkey_to_base64(const struct sshkey * key,char ** b64p)1495 sshkey_to_base64(const struct sshkey *key, char **b64p)
1496 {
1497 	int r = SSH_ERR_INTERNAL_ERROR;
1498 	struct sshbuf *b = NULL;
1499 	char *uu = NULL;
1500 
1501 	if (b64p != NULL)
1502 		*b64p = NULL;
1503 	if ((b = sshbuf_new()) == NULL)
1504 		return SSH_ERR_ALLOC_FAIL;
1505 	if ((r = sshkey_putb(key, b)) != 0)
1506 		goto out;
1507 	if ((uu = sshbuf_dtob64_string(b, 0)) == NULL) {
1508 		r = SSH_ERR_ALLOC_FAIL;
1509 		goto out;
1510 	}
1511 	/* Success */
1512 	if (b64p != NULL) {
1513 		*b64p = uu;
1514 		uu = NULL;
1515 	}
1516 	r = 0;
1517  out:
1518 	sshbuf_free(b);
1519 	free(uu);
1520 	return r;
1521 }
1522 
1523 int
sshkey_format_text(const struct sshkey * key,struct sshbuf * b)1524 sshkey_format_text(const struct sshkey *key, struct sshbuf *b)
1525 {
1526 	int r = SSH_ERR_INTERNAL_ERROR;
1527 	char *uu = NULL;
1528 
1529 	if ((r = sshkey_to_base64(key, &uu)) != 0)
1530 		goto out;
1531 	if ((r = sshbuf_putf(b, "%s %s",
1532 	    sshkey_ssh_name(key), uu)) != 0)
1533 		goto out;
1534 	r = 0;
1535  out:
1536 	free(uu);
1537 	return r;
1538 }
1539 
1540 int
sshkey_write(const struct sshkey * key,FILE * f)1541 sshkey_write(const struct sshkey *key, FILE *f)
1542 {
1543 	struct sshbuf *b = NULL;
1544 	int r = SSH_ERR_INTERNAL_ERROR;
1545 
1546 	if ((b = sshbuf_new()) == NULL)
1547 		return SSH_ERR_ALLOC_FAIL;
1548 	if ((r = sshkey_format_text(key, b)) != 0)
1549 		goto out;
1550 	if (fwrite(sshbuf_ptr(b), sshbuf_len(b), 1, f) != 1) {
1551 		if (feof(f))
1552 			errno = EPIPE;
1553 		r = SSH_ERR_SYSTEM_ERROR;
1554 		goto out;
1555 	}
1556 	/* Success */
1557 	r = 0;
1558  out:
1559 	sshbuf_free(b);
1560 	return r;
1561 }
1562 
1563 const char *
sshkey_cert_type(const struct sshkey * k)1564 sshkey_cert_type(const struct sshkey *k)
1565 {
1566 	switch (k->cert->type) {
1567 	case SSH2_CERT_TYPE_USER:
1568 		return "user";
1569 	case SSH2_CERT_TYPE_HOST:
1570 		return "host";
1571 	default:
1572 		return "unknown";
1573 	}
1574 }
1575 
1576 #ifdef WITH_OPENSSL
1577 static int
rsa_generate_private_key(u_int bits,RSA ** rsap)1578 rsa_generate_private_key(u_int bits, RSA **rsap)
1579 {
1580 	RSA *private = NULL;
1581 	BIGNUM *f4 = NULL;
1582 	int ret = SSH_ERR_INTERNAL_ERROR;
1583 
1584 	if (rsap == NULL)
1585 		return SSH_ERR_INVALID_ARGUMENT;
1586 	if (bits < SSH_RSA_MINIMUM_MODULUS_SIZE ||
1587 	    bits > SSHBUF_MAX_BIGNUM * 8)
1588 		return SSH_ERR_KEY_LENGTH;
1589 	*rsap = NULL;
1590 	if ((private = RSA_new()) == NULL || (f4 = BN_new()) == NULL) {
1591 		ret = SSH_ERR_ALLOC_FAIL;
1592 		goto out;
1593 	}
1594 	if (!BN_set_word(f4, RSA_F4) ||
1595 	    !RSA_generate_key_ex(private, bits, f4, NULL)) {
1596 		ret = SSH_ERR_LIBCRYPTO_ERROR;
1597 		goto out;
1598 	}
1599 	*rsap = private;
1600 	private = NULL;
1601 	ret = 0;
1602  out:
1603 	RSA_free(private);
1604 	BN_free(f4);
1605 	return ret;
1606 }
1607 
1608 static int
dsa_generate_private_key(u_int bits,DSA ** dsap)1609 dsa_generate_private_key(u_int bits, DSA **dsap)
1610 {
1611 	DSA *private;
1612 	int ret = SSH_ERR_INTERNAL_ERROR;
1613 
1614 	if (dsap == NULL)
1615 		return SSH_ERR_INVALID_ARGUMENT;
1616 	if (bits != 1024)
1617 		return SSH_ERR_KEY_LENGTH;
1618 	if ((private = DSA_new()) == NULL) {
1619 		ret = SSH_ERR_ALLOC_FAIL;
1620 		goto out;
1621 	}
1622 	*dsap = NULL;
1623 	if (!DSA_generate_parameters_ex(private, bits, NULL, 0, NULL,
1624 	    NULL, NULL) || !DSA_generate_key(private)) {
1625 		ret = SSH_ERR_LIBCRYPTO_ERROR;
1626 		goto out;
1627 	}
1628 	*dsap = private;
1629 	private = NULL;
1630 	ret = 0;
1631  out:
1632 	DSA_free(private);
1633 	return ret;
1634 }
1635 
1636 # ifdef OPENSSL_HAS_ECC
1637 int
sshkey_ecdsa_key_to_nid(EC_KEY * k)1638 sshkey_ecdsa_key_to_nid(EC_KEY *k)
1639 {
1640 	EC_GROUP *eg;
1641 	int nids[] = {
1642 		NID_X9_62_prime256v1,
1643 		NID_secp384r1,
1644 #  ifdef OPENSSL_HAS_NISTP521
1645 		NID_secp521r1,
1646 #  endif /* OPENSSL_HAS_NISTP521 */
1647 		-1
1648 	};
1649 	int nid;
1650 	u_int i;
1651 	const EC_GROUP *g = EC_KEY_get0_group(k);
1652 
1653 	/*
1654 	 * The group may be stored in a ASN.1 encoded private key in one of two
1655 	 * ways: as a "named group", which is reconstituted by ASN.1 object ID
1656 	 * or explicit group parameters encoded into the key blob. Only the
1657 	 * "named group" case sets the group NID for us, but we can figure
1658 	 * it out for the other case by comparing against all the groups that
1659 	 * are supported.
1660 	 */
1661 	if ((nid = EC_GROUP_get_curve_name(g)) > 0)
1662 		return nid;
1663 	for (i = 0; nids[i] != -1; i++) {
1664 		if ((eg = EC_GROUP_new_by_curve_name(nids[i])) == NULL)
1665 			return -1;
1666 		if (EC_GROUP_cmp(g, eg, NULL) == 0)
1667 			break;
1668 		EC_GROUP_free(eg);
1669 	}
1670 	if (nids[i] != -1) {
1671 		/* Use the group with the NID attached */
1672 		EC_GROUP_set_asn1_flag(eg, OPENSSL_EC_NAMED_CURVE);
1673 		if (EC_KEY_set_group(k, eg) != 1) {
1674 			EC_GROUP_free(eg);
1675 			return -1;
1676 		}
1677 	}
1678 	return nids[i];
1679 }
1680 
1681 static int
ecdsa_generate_private_key(u_int bits,int * nid,EC_KEY ** ecdsap)1682 ecdsa_generate_private_key(u_int bits, int *nid, EC_KEY **ecdsap)
1683 {
1684 	EC_KEY *private;
1685 	int ret = SSH_ERR_INTERNAL_ERROR;
1686 
1687 	if (nid == NULL || ecdsap == NULL)
1688 		return SSH_ERR_INVALID_ARGUMENT;
1689 	if ((*nid = sshkey_ecdsa_bits_to_nid(bits)) == -1)
1690 		return SSH_ERR_KEY_LENGTH;
1691 	*ecdsap = NULL;
1692 	if ((private = EC_KEY_new_by_curve_name(*nid)) == NULL) {
1693 		ret = SSH_ERR_ALLOC_FAIL;
1694 		goto out;
1695 	}
1696 	if (EC_KEY_generate_key(private) != 1) {
1697 		ret = SSH_ERR_LIBCRYPTO_ERROR;
1698 		goto out;
1699 	}
1700 	EC_KEY_set_asn1_flag(private, OPENSSL_EC_NAMED_CURVE);
1701 	*ecdsap = private;
1702 	private = NULL;
1703 	ret = 0;
1704  out:
1705 	EC_KEY_free(private);
1706 	return ret;
1707 }
1708 # endif /* OPENSSL_HAS_ECC */
1709 #endif /* WITH_OPENSSL */
1710 
1711 int
sshkey_generate(int type,u_int bits,struct sshkey ** keyp)1712 sshkey_generate(int type, u_int bits, struct sshkey **keyp)
1713 {
1714 	struct sshkey *k;
1715 	int ret = SSH_ERR_INTERNAL_ERROR;
1716 
1717 	if (keyp == NULL)
1718 		return SSH_ERR_INVALID_ARGUMENT;
1719 	*keyp = NULL;
1720 	if ((k = sshkey_new(KEY_UNSPEC)) == NULL)
1721 		return SSH_ERR_ALLOC_FAIL;
1722 	switch (type) {
1723 	case KEY_ED25519:
1724 		if ((k->ed25519_pk = malloc(ED25519_PK_SZ)) == NULL ||
1725 		    (k->ed25519_sk = malloc(ED25519_SK_SZ)) == NULL) {
1726 			ret = SSH_ERR_ALLOC_FAIL;
1727 			break;
1728 		}
1729 		crypto_sign_ed25519_keypair(k->ed25519_pk, k->ed25519_sk);
1730 		ret = 0;
1731 		break;
1732 #ifdef WITH_XMSS
1733 	case KEY_XMSS:
1734 		ret = sshkey_xmss_generate_private_key(k, bits);
1735 		break;
1736 #endif /* WITH_XMSS */
1737 #ifdef WITH_OPENSSL
1738 	case KEY_DSA:
1739 		ret = dsa_generate_private_key(bits, &k->dsa);
1740 		break;
1741 # ifdef OPENSSL_HAS_ECC
1742 	case KEY_ECDSA:
1743 		ret = ecdsa_generate_private_key(bits, &k->ecdsa_nid,
1744 		    &k->ecdsa);
1745 		break;
1746 # endif /* OPENSSL_HAS_ECC */
1747 	case KEY_RSA:
1748 		ret = rsa_generate_private_key(bits, &k->rsa);
1749 		break;
1750 #endif /* WITH_OPENSSL */
1751 	default:
1752 		ret = SSH_ERR_INVALID_ARGUMENT;
1753 	}
1754 	if (ret == 0) {
1755 		k->type = type;
1756 		*keyp = k;
1757 	} else
1758 		sshkey_free(k);
1759 	return ret;
1760 }
1761 
1762 int
sshkey_cert_copy(const struct sshkey * from_key,struct sshkey * to_key)1763 sshkey_cert_copy(const struct sshkey *from_key, struct sshkey *to_key)
1764 {
1765 	u_int i;
1766 	const struct sshkey_cert *from;
1767 	struct sshkey_cert *to;
1768 	int r = SSH_ERR_INTERNAL_ERROR;
1769 
1770 	if (to_key == NULL || (from = from_key->cert) == NULL)
1771 		return SSH_ERR_INVALID_ARGUMENT;
1772 
1773 	if ((to = cert_new()) == NULL)
1774 		return SSH_ERR_ALLOC_FAIL;
1775 
1776 	if ((r = sshbuf_putb(to->certblob, from->certblob)) != 0 ||
1777 	    (r = sshbuf_putb(to->critical, from->critical)) != 0 ||
1778 	    (r = sshbuf_putb(to->extensions, from->extensions)) != 0)
1779 		goto out;
1780 
1781 	to->serial = from->serial;
1782 	to->type = from->type;
1783 	if (from->key_id == NULL)
1784 		to->key_id = NULL;
1785 	else if ((to->key_id = strdup(from->key_id)) == NULL) {
1786 		r = SSH_ERR_ALLOC_FAIL;
1787 		goto out;
1788 	}
1789 	to->valid_after = from->valid_after;
1790 	to->valid_before = from->valid_before;
1791 	if (from->signature_key == NULL)
1792 		to->signature_key = NULL;
1793 	else if ((r = sshkey_from_private(from->signature_key,
1794 	    &to->signature_key)) != 0)
1795 		goto out;
1796 	if (from->signature_type != NULL &&
1797 	    (to->signature_type = strdup(from->signature_type)) == NULL) {
1798 		r = SSH_ERR_ALLOC_FAIL;
1799 		goto out;
1800 	}
1801 	if (from->nprincipals > SSHKEY_CERT_MAX_PRINCIPALS) {
1802 		r = SSH_ERR_INVALID_ARGUMENT;
1803 		goto out;
1804 	}
1805 	if (from->nprincipals > 0) {
1806 		if ((to->principals = calloc(from->nprincipals,
1807 		    sizeof(*to->principals))) == NULL) {
1808 			r = SSH_ERR_ALLOC_FAIL;
1809 			goto out;
1810 		}
1811 		for (i = 0; i < from->nprincipals; i++) {
1812 			to->principals[i] = strdup(from->principals[i]);
1813 			if (to->principals[i] == NULL) {
1814 				to->nprincipals = i;
1815 				r = SSH_ERR_ALLOC_FAIL;
1816 				goto out;
1817 			}
1818 		}
1819 	}
1820 	to->nprincipals = from->nprincipals;
1821 
1822 	/* success */
1823 	cert_free(to_key->cert);
1824 	to_key->cert = to;
1825 	to = NULL;
1826 	r = 0;
1827  out:
1828 	cert_free(to);
1829 	return r;
1830 }
1831 
1832 int
sshkey_from_private(const struct sshkey * k,struct sshkey ** pkp)1833 sshkey_from_private(const struct sshkey *k, struct sshkey **pkp)
1834 {
1835 	struct sshkey *n = NULL;
1836 	int r = SSH_ERR_INTERNAL_ERROR;
1837 #ifdef WITH_OPENSSL
1838 	const BIGNUM *rsa_n, *rsa_e;
1839 	BIGNUM *rsa_n_dup = NULL, *rsa_e_dup = NULL;
1840 	const BIGNUM *dsa_p, *dsa_q, *dsa_g, *dsa_pub_key;
1841 	BIGNUM *dsa_p_dup = NULL, *dsa_q_dup = NULL, *dsa_g_dup = NULL;
1842 	BIGNUM *dsa_pub_key_dup = NULL;
1843 #endif /* WITH_OPENSSL */
1844 
1845 	*pkp = NULL;
1846 	if ((n = sshkey_new(k->type)) == NULL) {
1847 		r = SSH_ERR_ALLOC_FAIL;
1848 		goto out;
1849 	}
1850 	switch (k->type) {
1851 #ifdef WITH_OPENSSL
1852 	case KEY_DSA:
1853 	case KEY_DSA_CERT:
1854 		DSA_get0_pqg(k->dsa, &dsa_p, &dsa_q, &dsa_g);
1855 		DSA_get0_key(k->dsa, &dsa_pub_key, NULL);
1856 		if ((dsa_p_dup = BN_dup(dsa_p)) == NULL ||
1857 		    (dsa_q_dup = BN_dup(dsa_q)) == NULL ||
1858 		    (dsa_g_dup = BN_dup(dsa_g)) == NULL ||
1859 		    (dsa_pub_key_dup = BN_dup(dsa_pub_key)) == NULL) {
1860 			r = SSH_ERR_ALLOC_FAIL;
1861 			goto out;
1862 		}
1863 		if (!DSA_set0_pqg(n->dsa, dsa_p_dup, dsa_q_dup, dsa_g_dup)) {
1864 			r = SSH_ERR_LIBCRYPTO_ERROR;
1865 			goto out;
1866 		}
1867 		dsa_p_dup = dsa_q_dup = dsa_g_dup = NULL; /* transferred */
1868 		if (!DSA_set0_key(n->dsa, dsa_pub_key_dup, NULL)) {
1869 			r = SSH_ERR_LIBCRYPTO_ERROR;
1870 			goto out;
1871 		}
1872 		dsa_pub_key_dup = NULL; /* transferred */
1873 
1874 		break;
1875 # ifdef OPENSSL_HAS_ECC
1876 	case KEY_ECDSA:
1877 	case KEY_ECDSA_CERT:
1878 	case KEY_ECDSA_SK:
1879 	case KEY_ECDSA_SK_CERT:
1880 		n->ecdsa_nid = k->ecdsa_nid;
1881 		n->ecdsa = EC_KEY_new_by_curve_name(k->ecdsa_nid);
1882 		if (n->ecdsa == NULL) {
1883 			r = SSH_ERR_ALLOC_FAIL;
1884 			goto out;
1885 		}
1886 		if (EC_KEY_set_public_key(n->ecdsa,
1887 		    EC_KEY_get0_public_key(k->ecdsa)) != 1) {
1888 			r = SSH_ERR_LIBCRYPTO_ERROR;
1889 			goto out;
1890 		}
1891 		if (k->type != KEY_ECDSA_SK && k->type != KEY_ECDSA_SK_CERT)
1892 			break;
1893 		/* Append security-key application string */
1894 		if ((n->sk_application = strdup(k->sk_application)) == NULL)
1895 			goto out;
1896 		break;
1897 # endif /* OPENSSL_HAS_ECC */
1898 	case KEY_RSA:
1899 	case KEY_RSA_CERT:
1900 		RSA_get0_key(k->rsa, &rsa_n, &rsa_e, NULL);
1901 		if ((rsa_n_dup = BN_dup(rsa_n)) == NULL ||
1902 		    (rsa_e_dup = BN_dup(rsa_e)) == NULL) {
1903 			r = SSH_ERR_ALLOC_FAIL;
1904 			goto out;
1905 		}
1906 		if (!RSA_set0_key(n->rsa, rsa_n_dup, rsa_e_dup, NULL)) {
1907 			r = SSH_ERR_LIBCRYPTO_ERROR;
1908 			goto out;
1909 		}
1910 		rsa_n_dup = rsa_e_dup = NULL; /* transferred */
1911 		break;
1912 #endif /* WITH_OPENSSL */
1913 	case KEY_ED25519:
1914 	case KEY_ED25519_CERT:
1915 	case KEY_ED25519_SK:
1916 	case KEY_ED25519_SK_CERT:
1917 		if (k->ed25519_pk != NULL) {
1918 			if ((n->ed25519_pk = malloc(ED25519_PK_SZ)) == NULL) {
1919 				r = SSH_ERR_ALLOC_FAIL;
1920 				goto out;
1921 			}
1922 			memcpy(n->ed25519_pk, k->ed25519_pk, ED25519_PK_SZ);
1923 		}
1924 		if (k->type != KEY_ED25519_SK &&
1925 		    k->type != KEY_ED25519_SK_CERT)
1926 			break;
1927 		/* Append security-key application string */
1928 		if ((n->sk_application = strdup(k->sk_application)) == NULL)
1929 			goto out;
1930 		break;
1931 #ifdef WITH_XMSS
1932 	case KEY_XMSS:
1933 	case KEY_XMSS_CERT:
1934 		if ((r = sshkey_xmss_init(n, k->xmss_name)) != 0)
1935 			goto out;
1936 		if (k->xmss_pk != NULL) {
1937 			u_int32_t left;
1938 			size_t pklen = sshkey_xmss_pklen(k);
1939 			if (pklen == 0 || sshkey_xmss_pklen(n) != pklen) {
1940 				r = SSH_ERR_INTERNAL_ERROR;
1941 				goto out;
1942 			}
1943 			if ((n->xmss_pk = malloc(pklen)) == NULL) {
1944 				r = SSH_ERR_ALLOC_FAIL;
1945 				goto out;
1946 			}
1947 			memcpy(n->xmss_pk, k->xmss_pk, pklen);
1948 			/* simulate number of signatures left on pubkey */
1949 			left = sshkey_xmss_signatures_left(k);
1950 			if (left)
1951 				sshkey_xmss_enable_maxsign(n, left);
1952 		}
1953 		break;
1954 #endif /* WITH_XMSS */
1955 	default:
1956 		r = SSH_ERR_KEY_TYPE_UNKNOWN;
1957 		goto out;
1958 	}
1959 	if (sshkey_is_cert(k) && (r = sshkey_cert_copy(k, n)) != 0)
1960 		goto out;
1961 	/* success */
1962 	*pkp = n;
1963 	n = NULL;
1964 	r = 0;
1965  out:
1966 	sshkey_free(n);
1967 #ifdef WITH_OPENSSL
1968 	BN_clear_free(rsa_n_dup);
1969 	BN_clear_free(rsa_e_dup);
1970 	BN_clear_free(dsa_p_dup);
1971 	BN_clear_free(dsa_q_dup);
1972 	BN_clear_free(dsa_g_dup);
1973 	BN_clear_free(dsa_pub_key_dup);
1974 #endif
1975 
1976 	return r;
1977 }
1978 
1979 int
sshkey_is_shielded(struct sshkey * k)1980 sshkey_is_shielded(struct sshkey *k)
1981 {
1982 	return k != NULL && k->shielded_private != NULL;
1983 }
1984 
1985 int
sshkey_shield_private(struct sshkey * k)1986 sshkey_shield_private(struct sshkey *k)
1987 {
1988 	struct sshbuf *prvbuf = NULL;
1989 	u_char *prekey = NULL, *enc = NULL, keyiv[SSH_DIGEST_MAX_LENGTH];
1990 	struct sshcipher_ctx *cctx = NULL;
1991 	const struct sshcipher *cipher;
1992 	size_t i, enclen = 0;
1993 	struct sshkey *kswap = NULL, tmp;
1994 	int r = SSH_ERR_INTERNAL_ERROR;
1995 
1996 #ifdef DEBUG_PK
1997 	fprintf(stderr, "%s: entering for %s\n", __func__, sshkey_ssh_name(k));
1998 #endif
1999 	if ((cipher = cipher_by_name(SSHKEY_SHIELD_CIPHER)) == NULL) {
2000 		r = SSH_ERR_INVALID_ARGUMENT;
2001 		goto out;
2002 	}
2003 	if (cipher_keylen(cipher) + cipher_ivlen(cipher) >
2004 	    ssh_digest_bytes(SSHKEY_SHIELD_PREKEY_HASH)) {
2005 		r = SSH_ERR_INTERNAL_ERROR;
2006 		goto out;
2007 	}
2008 
2009 	/* Prepare a random pre-key, and from it an ephemeral key */
2010 	if ((prekey = malloc(SSHKEY_SHIELD_PREKEY_LEN)) == NULL) {
2011 		r = SSH_ERR_ALLOC_FAIL;
2012 		goto out;
2013 	}
2014 	arc4random_buf(prekey, SSHKEY_SHIELD_PREKEY_LEN);
2015 	if ((r = ssh_digest_memory(SSHKEY_SHIELD_PREKEY_HASH,
2016 	    prekey, SSHKEY_SHIELD_PREKEY_LEN,
2017 	    keyiv, SSH_DIGEST_MAX_LENGTH)) != 0)
2018 		goto out;
2019 #ifdef DEBUG_PK
2020 	fprintf(stderr, "%s: key+iv\n", __func__);
2021 	sshbuf_dump_data(keyiv, ssh_digest_bytes(SSHKEY_SHIELD_PREKEY_HASH),
2022 	    stderr);
2023 #endif
2024 	if ((r = cipher_init(&cctx, cipher, keyiv, cipher_keylen(cipher),
2025 	    keyiv + cipher_keylen(cipher), cipher_ivlen(cipher), 1)) != 0)
2026 		goto out;
2027 
2028 	/* Serialise and encrypt the private key using the ephemeral key */
2029 	if ((prvbuf = sshbuf_new()) == NULL) {
2030 		r = SSH_ERR_ALLOC_FAIL;
2031 		goto out;
2032 	}
2033 	if (sshkey_is_shielded(k) && (r = sshkey_unshield_private(k)) != 0)
2034 		goto out;
2035 	if ((r = sshkey_private_serialize_opt(k, prvbuf,
2036 	     SSHKEY_SERIALIZE_SHIELD)) != 0)
2037 		goto out;
2038 	/* pad to cipher blocksize */
2039 	i = 0;
2040 	while (sshbuf_len(prvbuf) % cipher_blocksize(cipher)) {
2041 		if ((r = sshbuf_put_u8(prvbuf, ++i & 0xff)) != 0)
2042 			goto out;
2043 	}
2044 #ifdef DEBUG_PK
2045 	fprintf(stderr, "%s: serialised\n", __func__);
2046 	sshbuf_dump(prvbuf, stderr);
2047 #endif
2048 	/* encrypt */
2049 	enclen = sshbuf_len(prvbuf);
2050 	if ((enc = malloc(enclen)) == NULL) {
2051 		r = SSH_ERR_ALLOC_FAIL;
2052 		goto out;
2053 	}
2054 	if ((r = cipher_crypt(cctx, 0, enc,
2055 	    sshbuf_ptr(prvbuf), sshbuf_len(prvbuf), 0, 0)) != 0)
2056 		goto out;
2057 #ifdef DEBUG_PK
2058 	fprintf(stderr, "%s: encrypted\n", __func__);
2059 	sshbuf_dump_data(enc, enclen, stderr);
2060 #endif
2061 
2062 	/* Make a scrubbed, public-only copy of our private key argument */
2063 	if ((r = sshkey_from_private(k, &kswap)) != 0)
2064 		goto out;
2065 
2066 	/* Swap the private key out (it will be destroyed below) */
2067 	tmp = *kswap;
2068 	*kswap = *k;
2069 	*k = tmp;
2070 
2071 	/* Insert the shielded key into our argument */
2072 	k->shielded_private = enc;
2073 	k->shielded_len = enclen;
2074 	k->shield_prekey = prekey;
2075 	k->shield_prekey_len = SSHKEY_SHIELD_PREKEY_LEN;
2076 	enc = prekey = NULL; /* transferred */
2077 	enclen = 0;
2078 
2079 	/* preserve key fields that are required for correct operation */
2080 	k->sk_flags = kswap->sk_flags;
2081 
2082 	/* success */
2083 	r = 0;
2084 
2085  out:
2086 	/* XXX behaviour on error - invalidate original private key? */
2087 	cipher_free(cctx);
2088 	explicit_bzero(keyiv, sizeof(keyiv));
2089 	explicit_bzero(&tmp, sizeof(tmp));
2090 	freezero(enc, enclen);
2091 	freezero(prekey, SSHKEY_SHIELD_PREKEY_LEN);
2092 	sshkey_free(kswap);
2093 	sshbuf_free(prvbuf);
2094 	return r;
2095 }
2096 
2097 int
sshkey_unshield_private(struct sshkey * k)2098 sshkey_unshield_private(struct sshkey *k)
2099 {
2100 	struct sshbuf *prvbuf = NULL;
2101 	u_char pad, *cp, keyiv[SSH_DIGEST_MAX_LENGTH];
2102 	struct sshcipher_ctx *cctx = NULL;
2103 	const struct sshcipher *cipher;
2104 	size_t i;
2105 	struct sshkey *kswap = NULL, tmp;
2106 	int r = SSH_ERR_INTERNAL_ERROR;
2107 
2108 #ifdef DEBUG_PK
2109 	fprintf(stderr, "%s: entering for %s\n", __func__, sshkey_ssh_name(k));
2110 #endif
2111 	if (!sshkey_is_shielded(k))
2112 		return 0; /* nothing to do */
2113 
2114 	if ((cipher = cipher_by_name(SSHKEY_SHIELD_CIPHER)) == NULL) {
2115 		r = SSH_ERR_INVALID_ARGUMENT;
2116 		goto out;
2117 	}
2118 	if (cipher_keylen(cipher) + cipher_ivlen(cipher) >
2119 	    ssh_digest_bytes(SSHKEY_SHIELD_PREKEY_HASH)) {
2120 		r = SSH_ERR_INTERNAL_ERROR;
2121 		goto out;
2122 	}
2123 	/* check size of shielded key blob */
2124 	if (k->shielded_len < cipher_blocksize(cipher) ||
2125 	    (k->shielded_len % cipher_blocksize(cipher)) != 0) {
2126 		r = SSH_ERR_INVALID_FORMAT;
2127 		goto out;
2128 	}
2129 
2130 	/* Calculate the ephemeral key from the prekey */
2131 	if ((r = ssh_digest_memory(SSHKEY_SHIELD_PREKEY_HASH,
2132 	    k->shield_prekey, k->shield_prekey_len,
2133 	    keyiv, SSH_DIGEST_MAX_LENGTH)) != 0)
2134 		goto out;
2135 	if ((r = cipher_init(&cctx, cipher, keyiv, cipher_keylen(cipher),
2136 	    keyiv + cipher_keylen(cipher), cipher_ivlen(cipher), 0)) != 0)
2137 		goto out;
2138 #ifdef DEBUG_PK
2139 	fprintf(stderr, "%s: key+iv\n", __func__);
2140 	sshbuf_dump_data(keyiv, ssh_digest_bytes(SSHKEY_SHIELD_PREKEY_HASH),
2141 	    stderr);
2142 #endif
2143 
2144 	/* Decrypt and parse the shielded private key using the ephemeral key */
2145 	if ((prvbuf = sshbuf_new()) == NULL) {
2146 		r = SSH_ERR_ALLOC_FAIL;
2147 		goto out;
2148 	}
2149 	if ((r = sshbuf_reserve(prvbuf, k->shielded_len, &cp)) != 0)
2150 		goto out;
2151 	/* decrypt */
2152 #ifdef DEBUG_PK
2153 	fprintf(stderr, "%s: encrypted\n", __func__);
2154 	sshbuf_dump_data(k->shielded_private, k->shielded_len, stderr);
2155 #endif
2156 	if ((r = cipher_crypt(cctx, 0, cp,
2157 	    k->shielded_private, k->shielded_len, 0, 0)) != 0)
2158 		goto out;
2159 #ifdef DEBUG_PK
2160 	fprintf(stderr, "%s: serialised\n", __func__);
2161 	sshbuf_dump(prvbuf, stderr);
2162 #endif
2163 	/* Parse private key */
2164 	if ((r = sshkey_private_deserialize(prvbuf, &kswap)) != 0)
2165 		goto out;
2166 	/* Check deterministic padding */
2167 	i = 0;
2168 	while (sshbuf_len(prvbuf)) {
2169 		if ((r = sshbuf_get_u8(prvbuf, &pad)) != 0)
2170 			goto out;
2171 		if (pad != (++i & 0xff)) {
2172 			r = SSH_ERR_INVALID_FORMAT;
2173 			goto out;
2174 		}
2175 	}
2176 
2177 	/* Swap the parsed key back into place */
2178 	tmp = *kswap;
2179 	*kswap = *k;
2180 	*k = tmp;
2181 
2182 	/* success */
2183 	r = 0;
2184 
2185  out:
2186 	cipher_free(cctx);
2187 	explicit_bzero(keyiv, sizeof(keyiv));
2188 	explicit_bzero(&tmp, sizeof(tmp));
2189 	sshkey_free(kswap);
2190 	sshbuf_free(prvbuf);
2191 	return r;
2192 }
2193 
2194 static int
cert_parse(struct sshbuf * b,struct sshkey * key,struct sshbuf * certbuf)2195 cert_parse(struct sshbuf *b, struct sshkey *key, struct sshbuf *certbuf)
2196 {
2197 	struct sshbuf *principals = NULL, *crit = NULL;
2198 	struct sshbuf *exts = NULL, *ca = NULL;
2199 	u_char *sig = NULL;
2200 	size_t signed_len = 0, slen = 0, kidlen = 0;
2201 	int ret = SSH_ERR_INTERNAL_ERROR;
2202 
2203 	/* Copy the entire key blob for verification and later serialisation */
2204 	if ((ret = sshbuf_putb(key->cert->certblob, certbuf)) != 0)
2205 		return ret;
2206 
2207 	/* Parse body of certificate up to signature */
2208 	if ((ret = sshbuf_get_u64(b, &key->cert->serial)) != 0 ||
2209 	    (ret = sshbuf_get_u32(b, &key->cert->type)) != 0 ||
2210 	    (ret = sshbuf_get_cstring(b, &key->cert->key_id, &kidlen)) != 0 ||
2211 	    (ret = sshbuf_froms(b, &principals)) != 0 ||
2212 	    (ret = sshbuf_get_u64(b, &key->cert->valid_after)) != 0 ||
2213 	    (ret = sshbuf_get_u64(b, &key->cert->valid_before)) != 0 ||
2214 	    (ret = sshbuf_froms(b, &crit)) != 0 ||
2215 	    (ret = sshbuf_froms(b, &exts)) != 0 ||
2216 	    (ret = sshbuf_get_string_direct(b, NULL, NULL)) != 0 ||
2217 	    (ret = sshbuf_froms(b, &ca)) != 0) {
2218 		/* XXX debug print error for ret */
2219 		ret = SSH_ERR_INVALID_FORMAT;
2220 		goto out;
2221 	}
2222 
2223 	/* Signature is left in the buffer so we can calculate this length */
2224 	signed_len = sshbuf_len(key->cert->certblob) - sshbuf_len(b);
2225 
2226 	if ((ret = sshbuf_get_string(b, &sig, &slen)) != 0) {
2227 		ret = SSH_ERR_INVALID_FORMAT;
2228 		goto out;
2229 	}
2230 
2231 	if (key->cert->type != SSH2_CERT_TYPE_USER &&
2232 	    key->cert->type != SSH2_CERT_TYPE_HOST) {
2233 		ret = SSH_ERR_KEY_CERT_UNKNOWN_TYPE;
2234 		goto out;
2235 	}
2236 
2237 	/* Parse principals section */
2238 	while (sshbuf_len(principals) > 0) {
2239 		char *principal = NULL;
2240 		char **oprincipals = NULL;
2241 
2242 		if (key->cert->nprincipals >= SSHKEY_CERT_MAX_PRINCIPALS) {
2243 			ret = SSH_ERR_INVALID_FORMAT;
2244 			goto out;
2245 		}
2246 		if ((ret = sshbuf_get_cstring(principals, &principal,
2247 		    NULL)) != 0) {
2248 			ret = SSH_ERR_INVALID_FORMAT;
2249 			goto out;
2250 		}
2251 		oprincipals = key->cert->principals;
2252 		key->cert->principals = recallocarray(key->cert->principals,
2253 		    key->cert->nprincipals, key->cert->nprincipals + 1,
2254 		    sizeof(*key->cert->principals));
2255 		if (key->cert->principals == NULL) {
2256 			free(principal);
2257 			key->cert->principals = oprincipals;
2258 			ret = SSH_ERR_ALLOC_FAIL;
2259 			goto out;
2260 		}
2261 		key->cert->principals[key->cert->nprincipals++] = principal;
2262 	}
2263 
2264 	/*
2265 	 * Stash a copies of the critical options and extensions sections
2266 	 * for later use.
2267 	 */
2268 	if ((ret = sshbuf_putb(key->cert->critical, crit)) != 0 ||
2269 	    (exts != NULL &&
2270 	    (ret = sshbuf_putb(key->cert->extensions, exts)) != 0))
2271 		goto out;
2272 
2273 	/*
2274 	 * Validate critical options and extensions sections format.
2275 	 */
2276 	while (sshbuf_len(crit) != 0) {
2277 		if ((ret = sshbuf_get_string_direct(crit, NULL, NULL)) != 0 ||
2278 		    (ret = sshbuf_get_string_direct(crit, NULL, NULL)) != 0) {
2279 			sshbuf_reset(key->cert->critical);
2280 			ret = SSH_ERR_INVALID_FORMAT;
2281 			goto out;
2282 		}
2283 	}
2284 	while (exts != NULL && sshbuf_len(exts) != 0) {
2285 		if ((ret = sshbuf_get_string_direct(exts, NULL, NULL)) != 0 ||
2286 		    (ret = sshbuf_get_string_direct(exts, NULL, NULL)) != 0) {
2287 			sshbuf_reset(key->cert->extensions);
2288 			ret = SSH_ERR_INVALID_FORMAT;
2289 			goto out;
2290 		}
2291 	}
2292 
2293 	/* Parse CA key and check signature */
2294 	if (sshkey_from_blob_internal(ca, &key->cert->signature_key, 0) != 0) {
2295 		ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
2296 		goto out;
2297 	}
2298 	if (!sshkey_type_is_valid_ca(key->cert->signature_key->type)) {
2299 		ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
2300 		goto out;
2301 	}
2302 	if ((ret = sshkey_verify(key->cert->signature_key, sig, slen,
2303 	    sshbuf_ptr(key->cert->certblob), signed_len, NULL, 0, NULL)) != 0)
2304 		goto out;
2305 	if ((ret = sshkey_get_sigtype(sig, slen,
2306 	    &key->cert->signature_type)) != 0)
2307 		goto out;
2308 
2309 	/* Success */
2310 	ret = 0;
2311  out:
2312 	sshbuf_free(ca);
2313 	sshbuf_free(crit);
2314 	sshbuf_free(exts);
2315 	sshbuf_free(principals);
2316 	free(sig);
2317 	return ret;
2318 }
2319 
2320 #ifdef WITH_OPENSSL
2321 static int
check_rsa_length(const RSA * rsa)2322 check_rsa_length(const RSA *rsa)
2323 {
2324 	const BIGNUM *rsa_n;
2325 
2326 	RSA_get0_key(rsa, &rsa_n, NULL, NULL);
2327 	if (BN_num_bits(rsa_n) < SSH_RSA_MINIMUM_MODULUS_SIZE)
2328 		return SSH_ERR_KEY_LENGTH;
2329 	return 0;
2330 }
2331 #endif
2332 
2333 static int
sshkey_from_blob_internal(struct sshbuf * b,struct sshkey ** keyp,int allow_cert)2334 sshkey_from_blob_internal(struct sshbuf *b, struct sshkey **keyp,
2335     int allow_cert)
2336 {
2337 	int type, ret = SSH_ERR_INTERNAL_ERROR;
2338 	char *ktype = NULL, *curve = NULL, *xmss_name = NULL;
2339 	struct sshkey *key = NULL;
2340 	size_t len;
2341 	u_char *pk = NULL;
2342 	struct sshbuf *copy;
2343 #if defined(WITH_OPENSSL)
2344 	BIGNUM *rsa_n = NULL, *rsa_e = NULL;
2345 	BIGNUM *dsa_p = NULL, *dsa_q = NULL, *dsa_g = NULL, *dsa_pub_key = NULL;
2346 # if defined(OPENSSL_HAS_ECC)
2347 	EC_POINT *q = NULL;
2348 # endif /* OPENSSL_HAS_ECC */
2349 #endif /* WITH_OPENSSL */
2350 
2351 #ifdef DEBUG_PK /* XXX */
2352 	sshbuf_dump(b, stderr);
2353 #endif
2354 	if (keyp != NULL)
2355 		*keyp = NULL;
2356 	if ((copy = sshbuf_fromb(b)) == NULL) {
2357 		ret = SSH_ERR_ALLOC_FAIL;
2358 		goto out;
2359 	}
2360 	if (sshbuf_get_cstring(b, &ktype, NULL) != 0) {
2361 		ret = SSH_ERR_INVALID_FORMAT;
2362 		goto out;
2363 	}
2364 
2365 	type = sshkey_type_from_name(ktype);
2366 	if (!allow_cert && sshkey_type_is_cert(type)) {
2367 		ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
2368 		goto out;
2369 	}
2370 	switch (type) {
2371 #ifdef WITH_OPENSSL
2372 	case KEY_RSA_CERT:
2373 		/* Skip nonce */
2374 		if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
2375 			ret = SSH_ERR_INVALID_FORMAT;
2376 			goto out;
2377 		}
2378 		/* FALLTHROUGH */
2379 	case KEY_RSA:
2380 		if ((key = sshkey_new(type)) == NULL) {
2381 			ret = SSH_ERR_ALLOC_FAIL;
2382 			goto out;
2383 		}
2384 		if (sshbuf_get_bignum2(b, &rsa_e) != 0 ||
2385 		    sshbuf_get_bignum2(b, &rsa_n) != 0) {
2386 			ret = SSH_ERR_INVALID_FORMAT;
2387 			goto out;
2388 		}
2389 		if (!RSA_set0_key(key->rsa, rsa_n, rsa_e, NULL)) {
2390 			ret = SSH_ERR_LIBCRYPTO_ERROR;
2391 			goto out;
2392 		}
2393 		rsa_n = rsa_e = NULL; /* transferred */
2394 		if ((ret = check_rsa_length(key->rsa)) != 0)
2395 			goto out;
2396 #ifdef DEBUG_PK
2397 		RSA_print_fp(stderr, key->rsa, 8);
2398 #endif
2399 		break;
2400 	case KEY_DSA_CERT:
2401 		/* Skip nonce */
2402 		if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
2403 			ret = SSH_ERR_INVALID_FORMAT;
2404 			goto out;
2405 		}
2406 		/* FALLTHROUGH */
2407 	case KEY_DSA:
2408 		if ((key = sshkey_new(type)) == NULL) {
2409 			ret = SSH_ERR_ALLOC_FAIL;
2410 			goto out;
2411 		}
2412 		if (sshbuf_get_bignum2(b, &dsa_p) != 0 ||
2413 		    sshbuf_get_bignum2(b, &dsa_q) != 0 ||
2414 		    sshbuf_get_bignum2(b, &dsa_g) != 0 ||
2415 		    sshbuf_get_bignum2(b, &dsa_pub_key) != 0) {
2416 			ret = SSH_ERR_INVALID_FORMAT;
2417 			goto out;
2418 		}
2419 		if (!DSA_set0_pqg(key->dsa, dsa_p, dsa_q, dsa_g)) {
2420 			ret = SSH_ERR_LIBCRYPTO_ERROR;
2421 			goto out;
2422 		}
2423 		dsa_p = dsa_q = dsa_g = NULL; /* transferred */
2424 		if (!DSA_set0_key(key->dsa, dsa_pub_key, NULL)) {
2425 			ret = SSH_ERR_LIBCRYPTO_ERROR;
2426 			goto out;
2427 		}
2428 		dsa_pub_key = NULL; /* transferred */
2429 #ifdef DEBUG_PK
2430 		DSA_print_fp(stderr, key->dsa, 8);
2431 #endif
2432 		break;
2433 # ifdef OPENSSL_HAS_ECC
2434 	case KEY_ECDSA_CERT:
2435 	case KEY_ECDSA_SK_CERT:
2436 		/* Skip nonce */
2437 		if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
2438 			ret = SSH_ERR_INVALID_FORMAT;
2439 			goto out;
2440 		}
2441 		/* FALLTHROUGH */
2442 	case KEY_ECDSA:
2443 	case KEY_ECDSA_SK:
2444 		if ((key = sshkey_new(type)) == NULL) {
2445 			ret = SSH_ERR_ALLOC_FAIL;
2446 			goto out;
2447 		}
2448 		key->ecdsa_nid = sshkey_ecdsa_nid_from_name(ktype);
2449 		if (sshbuf_get_cstring(b, &curve, NULL) != 0) {
2450 			ret = SSH_ERR_INVALID_FORMAT;
2451 			goto out;
2452 		}
2453 		if (key->ecdsa_nid != sshkey_curve_name_to_nid(curve)) {
2454 			ret = SSH_ERR_EC_CURVE_MISMATCH;
2455 			goto out;
2456 		}
2457 		EC_KEY_free(key->ecdsa);
2458 		if ((key->ecdsa = EC_KEY_new_by_curve_name(key->ecdsa_nid))
2459 		    == NULL) {
2460 			ret = SSH_ERR_EC_CURVE_INVALID;
2461 			goto out;
2462 		}
2463 		if ((q = EC_POINT_new(EC_KEY_get0_group(key->ecdsa))) == NULL) {
2464 			ret = SSH_ERR_ALLOC_FAIL;
2465 			goto out;
2466 		}
2467 		if (sshbuf_get_ec(b, q, EC_KEY_get0_group(key->ecdsa)) != 0) {
2468 			ret = SSH_ERR_INVALID_FORMAT;
2469 			goto out;
2470 		}
2471 		if (sshkey_ec_validate_public(EC_KEY_get0_group(key->ecdsa),
2472 		    q) != 0) {
2473 			ret = SSH_ERR_KEY_INVALID_EC_VALUE;
2474 			goto out;
2475 		}
2476 		if (EC_KEY_set_public_key(key->ecdsa, q) != 1) {
2477 			/* XXX assume it is a allocation error */
2478 			ret = SSH_ERR_ALLOC_FAIL;
2479 			goto out;
2480 		}
2481 #ifdef DEBUG_PK
2482 		sshkey_dump_ec_point(EC_KEY_get0_group(key->ecdsa), q);
2483 #endif
2484 		if (type == KEY_ECDSA_SK || type == KEY_ECDSA_SK_CERT) {
2485 			/* Parse additional security-key application string */
2486 			if (sshbuf_get_cstring(b, &key->sk_application,
2487 			    NULL) != 0) {
2488 				ret = SSH_ERR_INVALID_FORMAT;
2489 				goto out;
2490 			}
2491 #ifdef DEBUG_PK
2492 			fprintf(stderr, "App: %s\n", key->sk_application);
2493 #endif
2494 		}
2495 		break;
2496 # endif /* OPENSSL_HAS_ECC */
2497 #endif /* WITH_OPENSSL */
2498 	case KEY_ED25519_CERT:
2499 	case KEY_ED25519_SK_CERT:
2500 		/* Skip nonce */
2501 		if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
2502 			ret = SSH_ERR_INVALID_FORMAT;
2503 			goto out;
2504 		}
2505 		/* FALLTHROUGH */
2506 	case KEY_ED25519:
2507 	case KEY_ED25519_SK:
2508 		if ((ret = sshbuf_get_string(b, &pk, &len)) != 0)
2509 			goto out;
2510 		if (len != ED25519_PK_SZ) {
2511 			ret = SSH_ERR_INVALID_FORMAT;
2512 			goto out;
2513 		}
2514 		if ((key = sshkey_new(type)) == NULL) {
2515 			ret = SSH_ERR_ALLOC_FAIL;
2516 			goto out;
2517 		}
2518 		if (type == KEY_ED25519_SK || type == KEY_ED25519_SK_CERT) {
2519 			/* Parse additional security-key application string */
2520 			if (sshbuf_get_cstring(b, &key->sk_application,
2521 			    NULL) != 0) {
2522 				ret = SSH_ERR_INVALID_FORMAT;
2523 				goto out;
2524 			}
2525 #ifdef DEBUG_PK
2526 			fprintf(stderr, "App: %s\n", key->sk_application);
2527 #endif
2528 		}
2529 		key->ed25519_pk = pk;
2530 		pk = NULL;
2531 		break;
2532 #ifdef WITH_XMSS
2533 	case KEY_XMSS_CERT:
2534 		/* Skip nonce */
2535 		if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
2536 			ret = SSH_ERR_INVALID_FORMAT;
2537 			goto out;
2538 		}
2539 		/* FALLTHROUGH */
2540 	case KEY_XMSS:
2541 		if ((ret = sshbuf_get_cstring(b, &xmss_name, NULL)) != 0)
2542 			goto out;
2543 		if ((key = sshkey_new(type)) == NULL) {
2544 			ret = SSH_ERR_ALLOC_FAIL;
2545 			goto out;
2546 		}
2547 		if ((ret = sshkey_xmss_init(key, xmss_name)) != 0)
2548 			goto out;
2549 		if ((ret = sshbuf_get_string(b, &pk, &len)) != 0)
2550 			goto out;
2551 		if (len == 0 || len != sshkey_xmss_pklen(key)) {
2552 			ret = SSH_ERR_INVALID_FORMAT;
2553 			goto out;
2554 		}
2555 		key->xmss_pk = pk;
2556 		pk = NULL;
2557 		if (type != KEY_XMSS_CERT &&
2558 		    (ret = sshkey_xmss_deserialize_pk_info(key, b)) != 0)
2559 			goto out;
2560 		break;
2561 #endif /* WITH_XMSS */
2562 	case KEY_UNSPEC:
2563 	default:
2564 		ret = SSH_ERR_KEY_TYPE_UNKNOWN;
2565 		goto out;
2566 	}
2567 
2568 	/* Parse certificate potion */
2569 	if (sshkey_is_cert(key) && (ret = cert_parse(b, key, copy)) != 0)
2570 		goto out;
2571 
2572 	if (key != NULL && sshbuf_len(b) != 0) {
2573 		ret = SSH_ERR_INVALID_FORMAT;
2574 		goto out;
2575 	}
2576 	ret = 0;
2577 	if (keyp != NULL) {
2578 		*keyp = key;
2579 		key = NULL;
2580 	}
2581  out:
2582 	sshbuf_free(copy);
2583 	sshkey_free(key);
2584 	free(xmss_name);
2585 	free(ktype);
2586 	free(curve);
2587 	free(pk);
2588 #if defined(WITH_OPENSSL)
2589 	BN_clear_free(rsa_n);
2590 	BN_clear_free(rsa_e);
2591 	BN_clear_free(dsa_p);
2592 	BN_clear_free(dsa_q);
2593 	BN_clear_free(dsa_g);
2594 	BN_clear_free(dsa_pub_key);
2595 # if defined(OPENSSL_HAS_ECC)
2596 	EC_POINT_free(q);
2597 # endif /* OPENSSL_HAS_ECC */
2598 #endif /* WITH_OPENSSL */
2599 	return ret;
2600 }
2601 
2602 int
sshkey_from_blob(const u_char * blob,size_t blen,struct sshkey ** keyp)2603 sshkey_from_blob(const u_char *blob, size_t blen, struct sshkey **keyp)
2604 {
2605 	struct sshbuf *b;
2606 	int r;
2607 
2608 	if ((b = sshbuf_from(blob, blen)) == NULL)
2609 		return SSH_ERR_ALLOC_FAIL;
2610 	r = sshkey_from_blob_internal(b, keyp, 1);
2611 	sshbuf_free(b);
2612 	return r;
2613 }
2614 
2615 int
sshkey_fromb(struct sshbuf * b,struct sshkey ** keyp)2616 sshkey_fromb(struct sshbuf *b, struct sshkey **keyp)
2617 {
2618 	return sshkey_from_blob_internal(b, keyp, 1);
2619 }
2620 
2621 int
sshkey_froms(struct sshbuf * buf,struct sshkey ** keyp)2622 sshkey_froms(struct sshbuf *buf, struct sshkey **keyp)
2623 {
2624 	struct sshbuf *b;
2625 	int r;
2626 
2627 	if ((r = sshbuf_froms(buf, &b)) != 0)
2628 		return r;
2629 	r = sshkey_from_blob_internal(b, keyp, 1);
2630 	sshbuf_free(b);
2631 	return r;
2632 }
2633 
2634 int
sshkey_get_sigtype(const u_char * sig,size_t siglen,char ** sigtypep)2635 sshkey_get_sigtype(const u_char *sig, size_t siglen, char **sigtypep)
2636 {
2637 	int r;
2638 	struct sshbuf *b = NULL;
2639 	char *sigtype = NULL;
2640 
2641 	if (sigtypep != NULL)
2642 		*sigtypep = NULL;
2643 	if ((b = sshbuf_from(sig, siglen)) == NULL)
2644 		return SSH_ERR_ALLOC_FAIL;
2645 	if ((r = sshbuf_get_cstring(b, &sigtype, NULL)) != 0)
2646 		goto out;
2647 	/* success */
2648 	if (sigtypep != NULL) {
2649 		*sigtypep = sigtype;
2650 		sigtype = NULL;
2651 	}
2652 	r = 0;
2653  out:
2654 	free(sigtype);
2655 	sshbuf_free(b);
2656 	return r;
2657 }
2658 
2659 /*
2660  *
2661  * Checks whether a certificate's signature type is allowed.
2662  * Returns 0 (success) if the certificate signature type appears in the
2663  * "allowed" pattern-list, or the key is not a certificate to begin with.
2664  * Otherwise returns a ssherr.h code.
2665  */
2666 int
sshkey_check_cert_sigtype(const struct sshkey * key,const char * allowed)2667 sshkey_check_cert_sigtype(const struct sshkey *key, const char *allowed)
2668 {
2669 	if (key == NULL || allowed == NULL)
2670 		return SSH_ERR_INVALID_ARGUMENT;
2671 	if (!sshkey_type_is_cert(key->type))
2672 		return 0;
2673 	if (key->cert == NULL || key->cert->signature_type == NULL)
2674 		return SSH_ERR_INVALID_ARGUMENT;
2675 	if (match_pattern_list(key->cert->signature_type, allowed, 0) != 1)
2676 		return SSH_ERR_SIGN_ALG_UNSUPPORTED;
2677 	return 0;
2678 }
2679 
2680 /*
2681  * Returns the expected signature algorithm for a given public key algorithm.
2682  */
2683 const char *
sshkey_sigalg_by_name(const char * name)2684 sshkey_sigalg_by_name(const char *name)
2685 {
2686 	const struct keytype *kt;
2687 
2688 	for (kt = keytypes; kt->type != -1; kt++) {
2689 		if (strcmp(kt->name, name) != 0)
2690 			continue;
2691 		if (kt->sigalg != NULL)
2692 			return kt->sigalg;
2693 		if (!kt->cert)
2694 			return kt->name;
2695 		return sshkey_ssh_name_from_type_nid(
2696 		    sshkey_type_plain(kt->type), kt->nid);
2697 	}
2698 	return NULL;
2699 }
2700 
2701 /*
2702  * Verifies that the signature algorithm appearing inside the signature blob
2703  * matches that which was requested.
2704  */
2705 int
sshkey_check_sigtype(const u_char * sig,size_t siglen,const char * requested_alg)2706 sshkey_check_sigtype(const u_char *sig, size_t siglen,
2707     const char *requested_alg)
2708 {
2709 	const char *expected_alg;
2710 	char *sigtype = NULL;
2711 	int r;
2712 
2713 	if (requested_alg == NULL)
2714 		return 0;
2715 	if ((expected_alg = sshkey_sigalg_by_name(requested_alg)) == NULL)
2716 		return SSH_ERR_INVALID_ARGUMENT;
2717 	if ((r = sshkey_get_sigtype(sig, siglen, &sigtype)) != 0)
2718 		return r;
2719 	r = strcmp(expected_alg, sigtype) == 0;
2720 	free(sigtype);
2721 	return r ? 0 : SSH_ERR_SIGN_ALG_UNSUPPORTED;
2722 }
2723 
2724 int
sshkey_sign(struct sshkey * key,u_char ** sigp,size_t * lenp,const u_char * data,size_t datalen,const char * alg,const char * sk_provider,u_int compat)2725 sshkey_sign(struct sshkey *key,
2726     u_char **sigp, size_t *lenp,
2727     const u_char *data, size_t datalen,
2728     const char *alg, const char *sk_provider, u_int compat)
2729 {
2730 	int was_shielded = sshkey_is_shielded(key);
2731 	int r2, r = SSH_ERR_INTERNAL_ERROR;
2732 
2733 	if (sigp != NULL)
2734 		*sigp = NULL;
2735 	if (lenp != NULL)
2736 		*lenp = 0;
2737 	if (datalen > SSH_KEY_MAX_SIGN_DATA_SIZE)
2738 		return SSH_ERR_INVALID_ARGUMENT;
2739 	if ((r = sshkey_unshield_private(key)) != 0)
2740 		return r;
2741 	switch (key->type) {
2742 #ifdef WITH_OPENSSL
2743 	case KEY_DSA_CERT:
2744 	case KEY_DSA:
2745 		r = ssh_dss_sign(key, sigp, lenp, data, datalen, compat);
2746 		break;
2747 # ifdef OPENSSL_HAS_ECC
2748 	case KEY_ECDSA_CERT:
2749 	case KEY_ECDSA:
2750 		r = ssh_ecdsa_sign(key, sigp, lenp, data, datalen, compat);
2751 		break;
2752 # endif /* OPENSSL_HAS_ECC */
2753 	case KEY_RSA_CERT:
2754 	case KEY_RSA:
2755 		r = ssh_rsa_sign(key, sigp, lenp, data, datalen, alg);
2756 		break;
2757 #endif /* WITH_OPENSSL */
2758 	case KEY_ED25519:
2759 	case KEY_ED25519_CERT:
2760 		r = ssh_ed25519_sign(key, sigp, lenp, data, datalen, compat);
2761 		break;
2762 	case KEY_ED25519_SK:
2763 	case KEY_ED25519_SK_CERT:
2764 	case KEY_ECDSA_SK_CERT:
2765 	case KEY_ECDSA_SK:
2766 		r = sshsk_sign(sk_provider, key, sigp, lenp, data,
2767 		    datalen, compat, /* XXX PIN */ NULL);
2768 		break;
2769 #ifdef WITH_XMSS
2770 	case KEY_XMSS:
2771 	case KEY_XMSS_CERT:
2772 		r = ssh_xmss_sign(key, sigp, lenp, data, datalen, compat);
2773 		break;
2774 #endif /* WITH_XMSS */
2775 	default:
2776 		r = SSH_ERR_KEY_TYPE_UNKNOWN;
2777 		break;
2778 	}
2779 	if (was_shielded && (r2 = sshkey_shield_private(key)) != 0)
2780 		return r2;
2781 	return r;
2782 }
2783 
2784 /*
2785  * ssh_key_verify returns 0 for a correct signature  and < 0 on error.
2786  * If "alg" specified, then the signature must use that algorithm.
2787  */
2788 int
sshkey_verify(const struct sshkey * key,const u_char * sig,size_t siglen,const u_char * data,size_t dlen,const char * alg,u_int compat,struct sshkey_sig_details ** detailsp)2789 sshkey_verify(const struct sshkey *key,
2790     const u_char *sig, size_t siglen,
2791     const u_char *data, size_t dlen, const char *alg, u_int compat,
2792     struct sshkey_sig_details **detailsp)
2793 {
2794 	if (detailsp != NULL)
2795 		*detailsp = NULL;
2796 	if (siglen == 0 || dlen > SSH_KEY_MAX_SIGN_DATA_SIZE)
2797 		return SSH_ERR_INVALID_ARGUMENT;
2798 	switch (key->type) {
2799 #ifdef WITH_OPENSSL
2800 	case KEY_DSA_CERT:
2801 	case KEY_DSA:
2802 		return ssh_dss_verify(key, sig, siglen, data, dlen, compat);
2803 # ifdef OPENSSL_HAS_ECC
2804 	case KEY_ECDSA_CERT:
2805 	case KEY_ECDSA:
2806 		return ssh_ecdsa_verify(key, sig, siglen, data, dlen, compat);
2807 	case KEY_ECDSA_SK_CERT:
2808 	case KEY_ECDSA_SK:
2809 		return ssh_ecdsa_sk_verify(key, sig, siglen, data, dlen,
2810 		    compat, detailsp);
2811 # endif /* OPENSSL_HAS_ECC */
2812 	case KEY_RSA_CERT:
2813 	case KEY_RSA:
2814 		return ssh_rsa_verify(key, sig, siglen, data, dlen, alg);
2815 #endif /* WITH_OPENSSL */
2816 	case KEY_ED25519:
2817 	case KEY_ED25519_CERT:
2818 		return ssh_ed25519_verify(key, sig, siglen, data, dlen, compat);
2819 	case KEY_ED25519_SK:
2820 	case KEY_ED25519_SK_CERT:
2821 		return ssh_ed25519_sk_verify(key, sig, siglen, data, dlen,
2822 		    compat, detailsp);
2823 #ifdef WITH_XMSS
2824 	case KEY_XMSS:
2825 	case KEY_XMSS_CERT:
2826 		return ssh_xmss_verify(key, sig, siglen, data, dlen, compat);
2827 #endif /* WITH_XMSS */
2828 	default:
2829 		return SSH_ERR_KEY_TYPE_UNKNOWN;
2830 	}
2831 }
2832 
2833 /* Convert a plain key to their _CERT equivalent */
2834 int
sshkey_to_certified(struct sshkey * k)2835 sshkey_to_certified(struct sshkey *k)
2836 {
2837 	int newtype;
2838 
2839 	switch (k->type) {
2840 #ifdef WITH_OPENSSL
2841 	case KEY_RSA:
2842 		newtype = KEY_RSA_CERT;
2843 		break;
2844 	case KEY_DSA:
2845 		newtype = KEY_DSA_CERT;
2846 		break;
2847 	case KEY_ECDSA:
2848 		newtype = KEY_ECDSA_CERT;
2849 		break;
2850 	case KEY_ECDSA_SK:
2851 		newtype = KEY_ECDSA_SK_CERT;
2852 		break;
2853 #endif /* WITH_OPENSSL */
2854 	case KEY_ED25519_SK:
2855 		newtype = KEY_ED25519_SK_CERT;
2856 		break;
2857 	case KEY_ED25519:
2858 		newtype = KEY_ED25519_CERT;
2859 		break;
2860 #ifdef WITH_XMSS
2861 	case KEY_XMSS:
2862 		newtype = KEY_XMSS_CERT;
2863 		break;
2864 #endif /* WITH_XMSS */
2865 	default:
2866 		return SSH_ERR_INVALID_ARGUMENT;
2867 	}
2868 	if ((k->cert = cert_new()) == NULL)
2869 		return SSH_ERR_ALLOC_FAIL;
2870 	k->type = newtype;
2871 	return 0;
2872 }
2873 
2874 /* Convert a certificate to its raw key equivalent */
2875 int
sshkey_drop_cert(struct sshkey * k)2876 sshkey_drop_cert(struct sshkey *k)
2877 {
2878 	if (!sshkey_type_is_cert(k->type))
2879 		return SSH_ERR_KEY_TYPE_UNKNOWN;
2880 	cert_free(k->cert);
2881 	k->cert = NULL;
2882 	k->type = sshkey_type_plain(k->type);
2883 	return 0;
2884 }
2885 
2886 /* Sign a certified key, (re-)generating the signed certblob. */
2887 int
sshkey_certify_custom(struct sshkey * k,struct sshkey * ca,const char * alg,const char * sk_provider,sshkey_certify_signer * signer,void * signer_ctx)2888 sshkey_certify_custom(struct sshkey *k, struct sshkey *ca, const char *alg,
2889     const char *sk_provider, sshkey_certify_signer *signer, void *signer_ctx)
2890 {
2891 	struct sshbuf *principals = NULL;
2892 	u_char *ca_blob = NULL, *sig_blob = NULL, nonce[32];
2893 	size_t i, ca_len, sig_len;
2894 	int ret = SSH_ERR_INTERNAL_ERROR;
2895 	struct sshbuf *cert = NULL;
2896 	char *sigtype = NULL;
2897 #ifdef WITH_OPENSSL
2898 	const BIGNUM *rsa_n, *rsa_e, *dsa_p, *dsa_q, *dsa_g, *dsa_pub_key;
2899 #endif /* WITH_OPENSSL */
2900 
2901 	if (k == NULL || k->cert == NULL ||
2902 	    k->cert->certblob == NULL || ca == NULL)
2903 		return SSH_ERR_INVALID_ARGUMENT;
2904 	if (!sshkey_is_cert(k))
2905 		return SSH_ERR_KEY_TYPE_UNKNOWN;
2906 	if (!sshkey_type_is_valid_ca(ca->type))
2907 		return SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
2908 
2909 	/*
2910 	 * If no alg specified as argument but a signature_type was set,
2911 	 * then prefer that. If both were specified, then they must match.
2912 	 */
2913 	if (alg == NULL)
2914 		alg = k->cert->signature_type;
2915 	else if (k->cert->signature_type != NULL &&
2916 	    strcmp(alg, k->cert->signature_type) != 0)
2917 		return SSH_ERR_INVALID_ARGUMENT;
2918 
2919 	/*
2920 	 * If no signing algorithm or signature_type was specified and we're
2921 	 * using a RSA key, then default to a good signature algorithm.
2922 	 */
2923 	if (alg == NULL && ca->type == KEY_RSA)
2924 		alg = "rsa-sha2-512";
2925 
2926 	if ((ret = sshkey_to_blob(ca, &ca_blob, &ca_len)) != 0)
2927 		return SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
2928 
2929 	cert = k->cert->certblob; /* for readability */
2930 	sshbuf_reset(cert);
2931 	if ((ret = sshbuf_put_cstring(cert, sshkey_ssh_name(k))) != 0)
2932 		goto out;
2933 
2934 	/* -v01 certs put nonce first */
2935 	arc4random_buf(&nonce, sizeof(nonce));
2936 	if ((ret = sshbuf_put_string(cert, nonce, sizeof(nonce))) != 0)
2937 		goto out;
2938 
2939 	/* XXX this substantially duplicates to_blob(); refactor */
2940 	switch (k->type) {
2941 #ifdef WITH_OPENSSL
2942 	case KEY_DSA_CERT:
2943 		DSA_get0_pqg(k->dsa, &dsa_p, &dsa_q, &dsa_g);
2944 		DSA_get0_key(k->dsa, &dsa_pub_key, NULL);
2945 		if ((ret = sshbuf_put_bignum2(cert, dsa_p)) != 0 ||
2946 		    (ret = sshbuf_put_bignum2(cert, dsa_q)) != 0 ||
2947 		    (ret = sshbuf_put_bignum2(cert, dsa_g)) != 0 ||
2948 		    (ret = sshbuf_put_bignum2(cert, dsa_pub_key)) != 0)
2949 			goto out;
2950 		break;
2951 # ifdef OPENSSL_HAS_ECC
2952 	case KEY_ECDSA_CERT:
2953 	case KEY_ECDSA_SK_CERT:
2954 		if ((ret = sshbuf_put_cstring(cert,
2955 		    sshkey_curve_nid_to_name(k->ecdsa_nid))) != 0 ||
2956 		    (ret = sshbuf_put_ec(cert,
2957 		    EC_KEY_get0_public_key(k->ecdsa),
2958 		    EC_KEY_get0_group(k->ecdsa))) != 0)
2959 			goto out;
2960 		if (k->type == KEY_ECDSA_SK_CERT) {
2961 			if ((ret = sshbuf_put_cstring(cert,
2962 			    k->sk_application)) != 0)
2963 				goto out;
2964 		}
2965 		break;
2966 # endif /* OPENSSL_HAS_ECC */
2967 	case KEY_RSA_CERT:
2968 		RSA_get0_key(k->rsa, &rsa_n, &rsa_e, NULL);
2969 		if ((ret = sshbuf_put_bignum2(cert, rsa_e)) != 0 ||
2970 		    (ret = sshbuf_put_bignum2(cert, rsa_n)) != 0)
2971 			goto out;
2972 		break;
2973 #endif /* WITH_OPENSSL */
2974 	case KEY_ED25519_CERT:
2975 	case KEY_ED25519_SK_CERT:
2976 		if ((ret = sshbuf_put_string(cert,
2977 		    k->ed25519_pk, ED25519_PK_SZ)) != 0)
2978 			goto out;
2979 		if (k->type == KEY_ED25519_SK_CERT) {
2980 			if ((ret = sshbuf_put_cstring(cert,
2981 			    k->sk_application)) != 0)
2982 				goto out;
2983 		}
2984 		break;
2985 #ifdef WITH_XMSS
2986 	case KEY_XMSS_CERT:
2987 		if (k->xmss_name == NULL) {
2988 			ret = SSH_ERR_INVALID_ARGUMENT;
2989 			goto out;
2990 		}
2991 		if ((ret = sshbuf_put_cstring(cert, k->xmss_name)) ||
2992 		    (ret = sshbuf_put_string(cert,
2993 		    k->xmss_pk, sshkey_xmss_pklen(k))) != 0)
2994 			goto out;
2995 		break;
2996 #endif /* WITH_XMSS */
2997 	default:
2998 		ret = SSH_ERR_INVALID_ARGUMENT;
2999 		goto out;
3000 	}
3001 
3002 	if ((ret = sshbuf_put_u64(cert, k->cert->serial)) != 0 ||
3003 	    (ret = sshbuf_put_u32(cert, k->cert->type)) != 0 ||
3004 	    (ret = sshbuf_put_cstring(cert, k->cert->key_id)) != 0)
3005 		goto out;
3006 
3007 	if ((principals = sshbuf_new()) == NULL) {
3008 		ret = SSH_ERR_ALLOC_FAIL;
3009 		goto out;
3010 	}
3011 	for (i = 0; i < k->cert->nprincipals; i++) {
3012 		if ((ret = sshbuf_put_cstring(principals,
3013 		    k->cert->principals[i])) != 0)
3014 			goto out;
3015 	}
3016 	if ((ret = sshbuf_put_stringb(cert, principals)) != 0 ||
3017 	    (ret = sshbuf_put_u64(cert, k->cert->valid_after)) != 0 ||
3018 	    (ret = sshbuf_put_u64(cert, k->cert->valid_before)) != 0 ||
3019 	    (ret = sshbuf_put_stringb(cert, k->cert->critical)) != 0 ||
3020 	    (ret = sshbuf_put_stringb(cert, k->cert->extensions)) != 0 ||
3021 	    (ret = sshbuf_put_string(cert, NULL, 0)) != 0 || /* Reserved */
3022 	    (ret = sshbuf_put_string(cert, ca_blob, ca_len)) != 0)
3023 		goto out;
3024 
3025 	/* Sign the whole mess */
3026 	if ((ret = signer(ca, &sig_blob, &sig_len, sshbuf_ptr(cert),
3027 	    sshbuf_len(cert), alg, sk_provider, 0, signer_ctx)) != 0)
3028 		goto out;
3029 	/* Check and update signature_type against what was actually used */
3030 	if ((ret = sshkey_get_sigtype(sig_blob, sig_len, &sigtype)) != 0)
3031 		goto out;
3032 	if (alg != NULL && strcmp(alg, sigtype) != 0) {
3033 		ret = SSH_ERR_SIGN_ALG_UNSUPPORTED;
3034 		goto out;
3035 	}
3036 	if (k->cert->signature_type == NULL) {
3037 		k->cert->signature_type = sigtype;
3038 		sigtype = NULL;
3039 	}
3040 	/* Append signature and we are done */
3041 	if ((ret = sshbuf_put_string(cert, sig_blob, sig_len)) != 0)
3042 		goto out;
3043 	ret = 0;
3044  out:
3045 	if (ret != 0)
3046 		sshbuf_reset(cert);
3047 	free(sig_blob);
3048 	free(ca_blob);
3049 	free(sigtype);
3050 	sshbuf_free(principals);
3051 	return ret;
3052 }
3053 
3054 static int
default_key_sign(struct sshkey * key,u_char ** sigp,size_t * lenp,const u_char * data,size_t datalen,const char * alg,const char * sk_provider,u_int compat,void * ctx)3055 default_key_sign(struct sshkey *key, u_char **sigp, size_t *lenp,
3056     const u_char *data, size_t datalen,
3057     const char *alg, const char *sk_provider, u_int compat, void *ctx)
3058 {
3059 	if (ctx != NULL)
3060 		return SSH_ERR_INVALID_ARGUMENT;
3061 	return sshkey_sign(key, sigp, lenp, data, datalen, alg,
3062 	    sk_provider, compat);
3063 }
3064 
3065 int
sshkey_certify(struct sshkey * k,struct sshkey * ca,const char * alg,const char * sk_provider)3066 sshkey_certify(struct sshkey *k, struct sshkey *ca, const char *alg,
3067     const char *sk_provider)
3068 {
3069 	return sshkey_certify_custom(k, ca, alg, sk_provider,
3070 	    default_key_sign, NULL);
3071 }
3072 
3073 int
sshkey_cert_check_authority(const struct sshkey * k,int want_host,int require_principal,const char * name,const char ** reason)3074 sshkey_cert_check_authority(const struct sshkey *k,
3075     int want_host, int require_principal,
3076     const char *name, const char **reason)
3077 {
3078 	u_int i, principal_matches;
3079 	time_t now = time(NULL);
3080 
3081 	if (reason == NULL)
3082 		return SSH_ERR_INVALID_ARGUMENT;
3083 
3084 	if (want_host) {
3085 		if (k->cert->type != SSH2_CERT_TYPE_HOST) {
3086 			*reason = "Certificate invalid: not a host certificate";
3087 			return SSH_ERR_KEY_CERT_INVALID;
3088 		}
3089 	} else {
3090 		if (k->cert->type != SSH2_CERT_TYPE_USER) {
3091 			*reason = "Certificate invalid: not a user certificate";
3092 			return SSH_ERR_KEY_CERT_INVALID;
3093 		}
3094 	}
3095 	if (now < 0) {
3096 		/* yikes - system clock before epoch! */
3097 		*reason = "Certificate invalid: not yet valid";
3098 		return SSH_ERR_KEY_CERT_INVALID;
3099 	}
3100 	if ((u_int64_t)now < k->cert->valid_after) {
3101 		*reason = "Certificate invalid: not yet valid";
3102 		return SSH_ERR_KEY_CERT_INVALID;
3103 	}
3104 	if ((u_int64_t)now >= k->cert->valid_before) {
3105 		*reason = "Certificate invalid: expired";
3106 		return SSH_ERR_KEY_CERT_INVALID;
3107 	}
3108 	if (k->cert->nprincipals == 0) {
3109 		if (require_principal) {
3110 			*reason = "Certificate lacks principal list";
3111 			return SSH_ERR_KEY_CERT_INVALID;
3112 		}
3113 	} else if (name != NULL) {
3114 		principal_matches = 0;
3115 		for (i = 0; i < k->cert->nprincipals; i++) {
3116 			if (strcmp(name, k->cert->principals[i]) == 0) {
3117 				principal_matches = 1;
3118 				break;
3119 			}
3120 		}
3121 		if (!principal_matches) {
3122 			*reason = "Certificate invalid: name is not a listed "
3123 			    "principal";
3124 			return SSH_ERR_KEY_CERT_INVALID;
3125 		}
3126 	}
3127 	return 0;
3128 }
3129 
3130 size_t
sshkey_format_cert_validity(const struct sshkey_cert * cert,char * s,size_t l)3131 sshkey_format_cert_validity(const struct sshkey_cert *cert, char *s, size_t l)
3132 {
3133 	char from[32], to[32], ret[64];
3134 	time_t tt;
3135 	struct tm *tm;
3136 
3137 	*from = *to = '\0';
3138 	if (cert->valid_after == 0 &&
3139 	    cert->valid_before == 0xffffffffffffffffULL)
3140 		return strlcpy(s, "forever", l);
3141 
3142 	if (cert->valid_after != 0) {
3143 		/* XXX revisit INT_MAX in 2038 :) */
3144 		tt = cert->valid_after > INT_MAX ?
3145 		    INT_MAX : cert->valid_after;
3146 		tm = localtime(&tt);
3147 		strftime(from, sizeof(from), "%Y-%m-%dT%H:%M:%S", tm);
3148 	}
3149 	if (cert->valid_before != 0xffffffffffffffffULL) {
3150 		/* XXX revisit INT_MAX in 2038 :) */
3151 		tt = cert->valid_before > INT_MAX ?
3152 		    INT_MAX : cert->valid_before;
3153 		tm = localtime(&tt);
3154 		strftime(to, sizeof(to), "%Y-%m-%dT%H:%M:%S", tm);
3155 	}
3156 
3157 	if (cert->valid_after == 0)
3158 		snprintf(ret, sizeof(ret), "before %s", to);
3159 	else if (cert->valid_before == 0xffffffffffffffffULL)
3160 		snprintf(ret, sizeof(ret), "after %s", from);
3161 	else
3162 		snprintf(ret, sizeof(ret), "from %s to %s", from, to);
3163 
3164 	return strlcpy(s, ret, l);
3165 }
3166 
3167 int
sshkey_private_serialize_opt(struct sshkey * key,struct sshbuf * buf,enum sshkey_serialize_rep opts)3168 sshkey_private_serialize_opt(struct sshkey *key, struct sshbuf *buf,
3169     enum sshkey_serialize_rep opts)
3170 {
3171 	int r = SSH_ERR_INTERNAL_ERROR;
3172 	int was_shielded = sshkey_is_shielded(key);
3173 	struct sshbuf *b = NULL;
3174 #ifdef WITH_OPENSSL
3175 	const BIGNUM *rsa_n, *rsa_e, *rsa_d, *rsa_iqmp, *rsa_p, *rsa_q;
3176 	const BIGNUM *dsa_p, *dsa_q, *dsa_g, *dsa_pub_key, *dsa_priv_key;
3177 #endif /* WITH_OPENSSL */
3178 
3179 	if ((r = sshkey_unshield_private(key)) != 0)
3180 		return r;
3181 	if ((b = sshbuf_new()) == NULL)
3182 		return SSH_ERR_ALLOC_FAIL;
3183 	if ((r = sshbuf_put_cstring(b, sshkey_ssh_name(key))) != 0)
3184 		goto out;
3185 	switch (key->type) {
3186 #ifdef WITH_OPENSSL
3187 	case KEY_RSA:
3188 		RSA_get0_key(key->rsa, &rsa_n, &rsa_e, &rsa_d);
3189 		RSA_get0_factors(key->rsa, &rsa_p, &rsa_q);
3190 		RSA_get0_crt_params(key->rsa, NULL, NULL, &rsa_iqmp);
3191 		if ((r = sshbuf_put_bignum2(b, rsa_n)) != 0 ||
3192 		    (r = sshbuf_put_bignum2(b, rsa_e)) != 0 ||
3193 		    (r = sshbuf_put_bignum2(b, rsa_d)) != 0 ||
3194 		    (r = sshbuf_put_bignum2(b, rsa_iqmp)) != 0 ||
3195 		    (r = sshbuf_put_bignum2(b, rsa_p)) != 0 ||
3196 		    (r = sshbuf_put_bignum2(b, rsa_q)) != 0)
3197 			goto out;
3198 		break;
3199 	case KEY_RSA_CERT:
3200 		if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
3201 			r = SSH_ERR_INVALID_ARGUMENT;
3202 			goto out;
3203 		}
3204 		RSA_get0_key(key->rsa, NULL, NULL, &rsa_d);
3205 		RSA_get0_factors(key->rsa, &rsa_p, &rsa_q);
3206 		RSA_get0_crt_params(key->rsa, NULL, NULL, &rsa_iqmp);
3207 		if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
3208 		    (r = sshbuf_put_bignum2(b, rsa_d)) != 0 ||
3209 		    (r = sshbuf_put_bignum2(b, rsa_iqmp)) != 0 ||
3210 		    (r = sshbuf_put_bignum2(b, rsa_p)) != 0 ||
3211 		    (r = sshbuf_put_bignum2(b, rsa_q)) != 0)
3212 			goto out;
3213 		break;
3214 	case KEY_DSA:
3215 		DSA_get0_pqg(key->dsa, &dsa_p, &dsa_q, &dsa_g);
3216 		DSA_get0_key(key->dsa, &dsa_pub_key, &dsa_priv_key);
3217 		if ((r = sshbuf_put_bignum2(b, dsa_p)) != 0 ||
3218 		    (r = sshbuf_put_bignum2(b, dsa_q)) != 0 ||
3219 		    (r = sshbuf_put_bignum2(b, dsa_g)) != 0 ||
3220 		    (r = sshbuf_put_bignum2(b, dsa_pub_key)) != 0 ||
3221 		    (r = sshbuf_put_bignum2(b, dsa_priv_key)) != 0)
3222 			goto out;
3223 		break;
3224 	case KEY_DSA_CERT:
3225 		if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
3226 			r = SSH_ERR_INVALID_ARGUMENT;
3227 			goto out;
3228 		}
3229 		DSA_get0_key(key->dsa, NULL, &dsa_priv_key);
3230 		if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
3231 		    (r = sshbuf_put_bignum2(b, dsa_priv_key)) != 0)
3232 			goto out;
3233 		break;
3234 # ifdef OPENSSL_HAS_ECC
3235 	case KEY_ECDSA:
3236 		if ((r = sshbuf_put_cstring(b,
3237 		    sshkey_curve_nid_to_name(key->ecdsa_nid))) != 0 ||
3238 		    (r = sshbuf_put_eckey(b, key->ecdsa)) != 0 ||
3239 		    (r = sshbuf_put_bignum2(b,
3240 		    EC_KEY_get0_private_key(key->ecdsa))) != 0)
3241 			goto out;
3242 		break;
3243 	case KEY_ECDSA_CERT:
3244 		if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
3245 			r = SSH_ERR_INVALID_ARGUMENT;
3246 			goto out;
3247 		}
3248 		if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
3249 		    (r = sshbuf_put_bignum2(b,
3250 		    EC_KEY_get0_private_key(key->ecdsa))) != 0)
3251 			goto out;
3252 		break;
3253 	case KEY_ECDSA_SK:
3254 		if ((r = sshbuf_put_cstring(b,
3255 		    sshkey_curve_nid_to_name(key->ecdsa_nid))) != 0 ||
3256 		    (r = sshbuf_put_eckey(b, key->ecdsa)) != 0 ||
3257 		    (r = sshbuf_put_cstring(b, key->sk_application)) != 0 ||
3258 		    (r = sshbuf_put_u8(b, key->sk_flags)) != 0 ||
3259 		    (r = sshbuf_put_stringb(b, key->sk_key_handle)) != 0 ||
3260 		    (r = sshbuf_put_stringb(b, key->sk_reserved)) != 0)
3261 			goto out;
3262 		break;
3263 	case KEY_ECDSA_SK_CERT:
3264 		if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
3265 			r = SSH_ERR_INVALID_ARGUMENT;
3266 			goto out;
3267 		}
3268 		if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
3269 		    (r = sshbuf_put_cstring(b, key->sk_application)) != 0 ||
3270 		    (r = sshbuf_put_u8(b, key->sk_flags)) != 0 ||
3271 		    (r = sshbuf_put_stringb(b, key->sk_key_handle)) != 0 ||
3272 		    (r = sshbuf_put_stringb(b, key->sk_reserved)) != 0)
3273 			goto out;
3274 		break;
3275 # endif /* OPENSSL_HAS_ECC */
3276 #endif /* WITH_OPENSSL */
3277 	case KEY_ED25519:
3278 		if ((r = sshbuf_put_string(b, key->ed25519_pk,
3279 		    ED25519_PK_SZ)) != 0 ||
3280 		    (r = sshbuf_put_string(b, key->ed25519_sk,
3281 		    ED25519_SK_SZ)) != 0)
3282 			goto out;
3283 		break;
3284 	case KEY_ED25519_CERT:
3285 		if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
3286 			r = SSH_ERR_INVALID_ARGUMENT;
3287 			goto out;
3288 		}
3289 		if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
3290 		    (r = sshbuf_put_string(b, key->ed25519_pk,
3291 		    ED25519_PK_SZ)) != 0 ||
3292 		    (r = sshbuf_put_string(b, key->ed25519_sk,
3293 		    ED25519_SK_SZ)) != 0)
3294 			goto out;
3295 		break;
3296 	case KEY_ED25519_SK:
3297 		if ((r = sshbuf_put_string(b, key->ed25519_pk,
3298 		    ED25519_PK_SZ)) != 0 ||
3299 		    (r = sshbuf_put_cstring(b, key->sk_application)) != 0 ||
3300 		    (r = sshbuf_put_u8(b, key->sk_flags)) != 0 ||
3301 		    (r = sshbuf_put_stringb(b, key->sk_key_handle)) != 0 ||
3302 		    (r = sshbuf_put_stringb(b, key->sk_reserved)) != 0)
3303 			goto out;
3304 		break;
3305 	case KEY_ED25519_SK_CERT:
3306 		if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
3307 			r = SSH_ERR_INVALID_ARGUMENT;
3308 			goto out;
3309 		}
3310 		if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
3311 		    (r = sshbuf_put_string(b, key->ed25519_pk,
3312 		    ED25519_PK_SZ)) != 0 ||
3313 		    (r = sshbuf_put_cstring(b, key->sk_application)) != 0 ||
3314 		    (r = sshbuf_put_u8(b, key->sk_flags)) != 0 ||
3315 		    (r = sshbuf_put_stringb(b, key->sk_key_handle)) != 0 ||
3316 		    (r = sshbuf_put_stringb(b, key->sk_reserved)) != 0)
3317 			goto out;
3318 		break;
3319 #ifdef WITH_XMSS
3320 	case KEY_XMSS:
3321 		if (key->xmss_name == NULL) {
3322 			r = SSH_ERR_INVALID_ARGUMENT;
3323 			goto out;
3324 		}
3325 		if ((r = sshbuf_put_cstring(b, key->xmss_name)) != 0 ||
3326 		    (r = sshbuf_put_string(b, key->xmss_pk,
3327 		    sshkey_xmss_pklen(key))) != 0 ||
3328 		    (r = sshbuf_put_string(b, key->xmss_sk,
3329 		    sshkey_xmss_sklen(key))) != 0 ||
3330 		    (r = sshkey_xmss_serialize_state_opt(key, b, opts)) != 0)
3331 			goto out;
3332 		break;
3333 	case KEY_XMSS_CERT:
3334 		if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0 ||
3335 		    key->xmss_name == NULL) {
3336 			r = SSH_ERR_INVALID_ARGUMENT;
3337 			goto out;
3338 		}
3339 		if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
3340 		    (r = sshbuf_put_cstring(b, key->xmss_name)) != 0 ||
3341 		    (r = sshbuf_put_string(b, key->xmss_pk,
3342 		    sshkey_xmss_pklen(key))) != 0 ||
3343 		    (r = sshbuf_put_string(b, key->xmss_sk,
3344 		    sshkey_xmss_sklen(key))) != 0 ||
3345 		    (r = sshkey_xmss_serialize_state_opt(key, b, opts)) != 0)
3346 			goto out;
3347 		break;
3348 #endif /* WITH_XMSS */
3349 	default:
3350 		r = SSH_ERR_INVALID_ARGUMENT;
3351 		goto out;
3352 	}
3353 	/*
3354 	 * success (but we still need to append the output to buf after
3355 	 * possibly re-shielding the private key)
3356 	 */
3357 	r = 0;
3358  out:
3359 	if (was_shielded)
3360 		r = sshkey_shield_private(key);
3361 	if (r == 0)
3362 		r = sshbuf_putb(buf, b);
3363 	sshbuf_free(b);
3364 
3365 	return r;
3366 }
3367 
3368 int
sshkey_private_serialize(struct sshkey * key,struct sshbuf * b)3369 sshkey_private_serialize(struct sshkey *key, struct sshbuf *b)
3370 {
3371 	return sshkey_private_serialize_opt(key, b,
3372 	    SSHKEY_SERIALIZE_DEFAULT);
3373 }
3374 
3375 int
sshkey_private_deserialize(struct sshbuf * buf,struct sshkey ** kp)3376 sshkey_private_deserialize(struct sshbuf *buf, struct sshkey **kp)
3377 {
3378 	char *tname = NULL, *curve = NULL, *xmss_name = NULL;
3379 	struct sshkey *k = NULL;
3380 	size_t pklen = 0, sklen = 0;
3381 	int type, r = SSH_ERR_INTERNAL_ERROR;
3382 	u_char *ed25519_pk = NULL, *ed25519_sk = NULL;
3383 	u_char *xmss_pk = NULL, *xmss_sk = NULL;
3384 #ifdef WITH_OPENSSL
3385 	BIGNUM *exponent = NULL;
3386 	BIGNUM *rsa_n = NULL, *rsa_e = NULL, *rsa_d = NULL;
3387 	BIGNUM *rsa_iqmp = NULL, *rsa_p = NULL, *rsa_q = NULL;
3388 	BIGNUM *dsa_p = NULL, *dsa_q = NULL, *dsa_g = NULL;
3389 	BIGNUM *dsa_pub_key = NULL, *dsa_priv_key = NULL;
3390 #endif /* WITH_OPENSSL */
3391 
3392 	if (kp != NULL)
3393 		*kp = NULL;
3394 	if ((r = sshbuf_get_cstring(buf, &tname, NULL)) != 0)
3395 		goto out;
3396 	type = sshkey_type_from_name(tname);
3397 	if (sshkey_type_is_cert(type)) {
3398 		/*
3399 		 * Certificate key private keys begin with the certificate
3400 		 * itself. Make sure this matches the type of the enclosing
3401 		 * private key.
3402 		 */
3403 		if ((r = sshkey_froms(buf, &k)) != 0)
3404 			goto out;
3405 		if (k->type != type) {
3406 			r = SSH_ERR_KEY_CERT_MISMATCH;
3407 			goto out;
3408 		}
3409 		/* For ECDSA keys, the group must match too */
3410 		if (k->type == KEY_ECDSA &&
3411 		    k->ecdsa_nid != sshkey_ecdsa_nid_from_name(tname)) {
3412 			r = SSH_ERR_KEY_CERT_MISMATCH;
3413 			goto out;
3414 		}
3415 	} else {
3416 		if ((k = sshkey_new(type)) == NULL) {
3417 			r = SSH_ERR_ALLOC_FAIL;
3418 			goto out;
3419 		}
3420 	}
3421 	switch (type) {
3422 #ifdef WITH_OPENSSL
3423 	case KEY_DSA:
3424 		if ((r = sshbuf_get_bignum2(buf, &dsa_p)) != 0 ||
3425 		    (r = sshbuf_get_bignum2(buf, &dsa_q)) != 0 ||
3426 		    (r = sshbuf_get_bignum2(buf, &dsa_g)) != 0 ||
3427 		    (r = sshbuf_get_bignum2(buf, &dsa_pub_key)) != 0)
3428 			goto out;
3429 		if (!DSA_set0_pqg(k->dsa, dsa_p, dsa_q, dsa_g)) {
3430 			r = SSH_ERR_LIBCRYPTO_ERROR;
3431 			goto out;
3432 		}
3433 		dsa_p = dsa_q = dsa_g = NULL; /* transferred */
3434 		if (!DSA_set0_key(k->dsa, dsa_pub_key, NULL)) {
3435 			r = SSH_ERR_LIBCRYPTO_ERROR;
3436 			goto out;
3437 		}
3438 		dsa_pub_key = NULL; /* transferred */
3439 		/* FALLTHROUGH */
3440 	case KEY_DSA_CERT:
3441 		if ((r = sshbuf_get_bignum2(buf, &dsa_priv_key)) != 0)
3442 			goto out;
3443 		if (!DSA_set0_key(k->dsa, NULL, dsa_priv_key)) {
3444 			r = SSH_ERR_LIBCRYPTO_ERROR;
3445 			goto out;
3446 		}
3447 		dsa_priv_key = NULL; /* transferred */
3448 		break;
3449 # ifdef OPENSSL_HAS_ECC
3450 	case KEY_ECDSA:
3451 		if ((k->ecdsa_nid = sshkey_ecdsa_nid_from_name(tname)) == -1) {
3452 			r = SSH_ERR_INVALID_ARGUMENT;
3453 			goto out;
3454 		}
3455 		if ((r = sshbuf_get_cstring(buf, &curve, NULL)) != 0)
3456 			goto out;
3457 		if (k->ecdsa_nid != sshkey_curve_name_to_nid(curve)) {
3458 			r = SSH_ERR_EC_CURVE_MISMATCH;
3459 			goto out;
3460 		}
3461 		k->ecdsa = EC_KEY_new_by_curve_name(k->ecdsa_nid);
3462 		if (k->ecdsa  == NULL) {
3463 			r = SSH_ERR_LIBCRYPTO_ERROR;
3464 			goto out;
3465 		}
3466 		if ((r = sshbuf_get_eckey(buf, k->ecdsa)) != 0)
3467 			goto out;
3468 		/* FALLTHROUGH */
3469 	case KEY_ECDSA_CERT:
3470 		if ((r = sshbuf_get_bignum2(buf, &exponent)) != 0)
3471 			goto out;
3472 		if (EC_KEY_set_private_key(k->ecdsa, exponent) != 1) {
3473 			r = SSH_ERR_LIBCRYPTO_ERROR;
3474 			goto out;
3475 		}
3476 		if ((r = sshkey_ec_validate_public(EC_KEY_get0_group(k->ecdsa),
3477 		    EC_KEY_get0_public_key(k->ecdsa))) != 0 ||
3478 		    (r = sshkey_ec_validate_private(k->ecdsa)) != 0)
3479 			goto out;
3480 		break;
3481 	case KEY_ECDSA_SK:
3482 		if ((k->ecdsa_nid = sshkey_ecdsa_nid_from_name(tname)) == -1) {
3483 			r = SSH_ERR_INVALID_ARGUMENT;
3484 			goto out;
3485 		}
3486 		if ((r = sshbuf_get_cstring(buf, &curve, NULL)) != 0)
3487 			goto out;
3488 		if (k->ecdsa_nid != sshkey_curve_name_to_nid(curve)) {
3489 			r = SSH_ERR_EC_CURVE_MISMATCH;
3490 			goto out;
3491 		}
3492 		if ((k->sk_key_handle = sshbuf_new()) == NULL ||
3493 		    (k->sk_reserved = sshbuf_new()) == NULL) {
3494 			r = SSH_ERR_ALLOC_FAIL;
3495 			goto out;
3496 		}
3497 		k->ecdsa = EC_KEY_new_by_curve_name(k->ecdsa_nid);
3498 		if (k->ecdsa  == NULL) {
3499 			r = SSH_ERR_LIBCRYPTO_ERROR;
3500 			goto out;
3501 		}
3502 		if ((r = sshbuf_get_eckey(buf, k->ecdsa)) != 0 ||
3503 		    (r = sshbuf_get_cstring(buf, &k->sk_application,
3504 		    NULL)) != 0 ||
3505 		    (r = sshbuf_get_u8(buf, &k->sk_flags)) != 0 ||
3506 		    (r = sshbuf_get_stringb(buf, k->sk_key_handle)) != 0 ||
3507 		    (r = sshbuf_get_stringb(buf, k->sk_reserved)) != 0)
3508 			goto out;
3509 		if ((r = sshkey_ec_validate_public(EC_KEY_get0_group(k->ecdsa),
3510 		    EC_KEY_get0_public_key(k->ecdsa))) != 0)
3511 			goto out;
3512 		break;
3513 	case KEY_ECDSA_SK_CERT:
3514 		if ((k->sk_key_handle = sshbuf_new()) == NULL ||
3515 		    (k->sk_reserved = sshbuf_new()) == NULL) {
3516 			r = SSH_ERR_ALLOC_FAIL;
3517 			goto out;
3518 		}
3519 		if ((r = sshbuf_get_cstring(buf, &k->sk_application,
3520 		    NULL)) != 0 ||
3521 		    (r = sshbuf_get_u8(buf, &k->sk_flags)) != 0 ||
3522 		    (r = sshbuf_get_stringb(buf, k->sk_key_handle)) != 0 ||
3523 		    (r = sshbuf_get_stringb(buf, k->sk_reserved)) != 0)
3524 			goto out;
3525 		if ((r = sshkey_ec_validate_public(EC_KEY_get0_group(k->ecdsa),
3526 		    EC_KEY_get0_public_key(k->ecdsa))) != 0)
3527 			goto out;
3528 		break;
3529 # endif /* OPENSSL_HAS_ECC */
3530 	case KEY_RSA:
3531 		if ((r = sshbuf_get_bignum2(buf, &rsa_n)) != 0 ||
3532 		    (r = sshbuf_get_bignum2(buf, &rsa_e)) != 0)
3533 			goto out;
3534 		if (!RSA_set0_key(k->rsa, rsa_n, rsa_e, NULL)) {
3535 			r = SSH_ERR_LIBCRYPTO_ERROR;
3536 			goto out;
3537 		}
3538 		rsa_n = rsa_e = NULL; /* transferred */
3539 		/* FALLTHROUGH */
3540 	case KEY_RSA_CERT:
3541 		if ((r = sshbuf_get_bignum2(buf, &rsa_d)) != 0 ||
3542 		    (r = sshbuf_get_bignum2(buf, &rsa_iqmp)) != 0 ||
3543 		    (r = sshbuf_get_bignum2(buf, &rsa_p)) != 0 ||
3544 		    (r = sshbuf_get_bignum2(buf, &rsa_q)) != 0)
3545 			goto out;
3546 		if (!RSA_set0_key(k->rsa, NULL, NULL, rsa_d)) {
3547 			r = SSH_ERR_LIBCRYPTO_ERROR;
3548 			goto out;
3549 		}
3550 		rsa_d = NULL; /* transferred */
3551 		if (!RSA_set0_factors(k->rsa, rsa_p, rsa_q)) {
3552 			r = SSH_ERR_LIBCRYPTO_ERROR;
3553 			goto out;
3554 		}
3555 		rsa_p = rsa_q = NULL; /* transferred */
3556 		if ((r = check_rsa_length(k->rsa)) != 0)
3557 			goto out;
3558 		if ((r = ssh_rsa_complete_crt_parameters(k, rsa_iqmp)) != 0)
3559 			goto out;
3560 		break;
3561 #endif /* WITH_OPENSSL */
3562 	case KEY_ED25519:
3563 	case KEY_ED25519_CERT:
3564 		if ((r = sshbuf_get_string(buf, &ed25519_pk, &pklen)) != 0 ||
3565 		    (r = sshbuf_get_string(buf, &ed25519_sk, &sklen)) != 0)
3566 			goto out;
3567 		if (pklen != ED25519_PK_SZ || sklen != ED25519_SK_SZ) {
3568 			r = SSH_ERR_INVALID_FORMAT;
3569 			goto out;
3570 		}
3571 		k->ed25519_pk = ed25519_pk;
3572 		k->ed25519_sk = ed25519_sk;
3573 		ed25519_pk = ed25519_sk = NULL; /* transferred */
3574 		break;
3575 	case KEY_ED25519_SK:
3576 	case KEY_ED25519_SK_CERT:
3577 		if ((r = sshbuf_get_string(buf, &ed25519_pk, &pklen)) != 0)
3578 			goto out;
3579 		if (pklen != ED25519_PK_SZ) {
3580 			r = SSH_ERR_INVALID_FORMAT;
3581 			goto out;
3582 		}
3583 		if ((k->sk_key_handle = sshbuf_new()) == NULL ||
3584 		    (k->sk_reserved = sshbuf_new()) == NULL) {
3585 			r = SSH_ERR_ALLOC_FAIL;
3586 			goto out;
3587 		}
3588 		if ((r = sshbuf_get_cstring(buf, &k->sk_application,
3589 		    NULL)) != 0 ||
3590 		    (r = sshbuf_get_u8(buf, &k->sk_flags)) != 0 ||
3591 		    (r = sshbuf_get_stringb(buf, k->sk_key_handle)) != 0 ||
3592 		    (r = sshbuf_get_stringb(buf, k->sk_reserved)) != 0)
3593 			goto out;
3594 		k->ed25519_pk = ed25519_pk;
3595 		ed25519_pk = NULL; /* transferred */
3596 		break;
3597 #ifdef WITH_XMSS
3598 	case KEY_XMSS:
3599 	case KEY_XMSS_CERT:
3600 		if ((r = sshbuf_get_cstring(buf, &xmss_name, NULL)) != 0 ||
3601 		    (r = sshkey_xmss_init(k, xmss_name)) != 0 ||
3602 		    (r = sshbuf_get_string(buf, &xmss_pk, &pklen)) != 0 ||
3603 		    (r = sshbuf_get_string(buf, &xmss_sk, &sklen)) != 0)
3604 			goto out;
3605 		if (pklen != sshkey_xmss_pklen(k) ||
3606 		    sklen != sshkey_xmss_sklen(k)) {
3607 			r = SSH_ERR_INVALID_FORMAT;
3608 			goto out;
3609 		}
3610 		k->xmss_pk = xmss_pk;
3611 		k->xmss_sk = xmss_sk;
3612 		xmss_pk = xmss_sk = NULL;
3613 		/* optional internal state */
3614 		if ((r = sshkey_xmss_deserialize_state_opt(k, buf)) != 0)
3615 			goto out;
3616 		break;
3617 #endif /* WITH_XMSS */
3618 	default:
3619 		r = SSH_ERR_KEY_TYPE_UNKNOWN;
3620 		goto out;
3621 	}
3622 #ifdef WITH_OPENSSL
3623 	/* enable blinding */
3624 	switch (k->type) {
3625 	case KEY_RSA:
3626 	case KEY_RSA_CERT:
3627 		if (RSA_blinding_on(k->rsa, NULL) != 1) {
3628 			r = SSH_ERR_LIBCRYPTO_ERROR;
3629 			goto out;
3630 		}
3631 		break;
3632 	}
3633 #endif /* WITH_OPENSSL */
3634 	/* success */
3635 	r = 0;
3636 	if (kp != NULL) {
3637 		*kp = k;
3638 		k = NULL;
3639 	}
3640  out:
3641 	free(tname);
3642 	free(curve);
3643 #ifdef WITH_OPENSSL
3644 	BN_clear_free(exponent);
3645 	BN_clear_free(dsa_p);
3646 	BN_clear_free(dsa_q);
3647 	BN_clear_free(dsa_g);
3648 	BN_clear_free(dsa_pub_key);
3649 	BN_clear_free(dsa_priv_key);
3650 	BN_clear_free(rsa_n);
3651 	BN_clear_free(rsa_e);
3652 	BN_clear_free(rsa_d);
3653 	BN_clear_free(rsa_p);
3654 	BN_clear_free(rsa_q);
3655 	BN_clear_free(rsa_iqmp);
3656 #endif /* WITH_OPENSSL */
3657 	sshkey_free(k);
3658 	freezero(ed25519_pk, pklen);
3659 	freezero(ed25519_sk, sklen);
3660 	free(xmss_name);
3661 	freezero(xmss_pk, pklen);
3662 	freezero(xmss_sk, sklen);
3663 	return r;
3664 }
3665 
3666 #if defined(WITH_OPENSSL) && defined(OPENSSL_HAS_ECC)
3667 int
sshkey_ec_validate_public(const EC_GROUP * group,const EC_POINT * public)3668 sshkey_ec_validate_public(const EC_GROUP *group, const EC_POINT *public)
3669 {
3670 	EC_POINT *nq = NULL;
3671 	BIGNUM *order = NULL, *x = NULL, *y = NULL, *tmp = NULL;
3672 	int ret = SSH_ERR_KEY_INVALID_EC_VALUE;
3673 
3674 	/*
3675 	 * NB. This assumes OpenSSL has already verified that the public
3676 	 * point lies on the curve. This is done by EC_POINT_oct2point()
3677 	 * implicitly calling EC_POINT_is_on_curve(). If this code is ever
3678 	 * reachable with public points not unmarshalled using
3679 	 * EC_POINT_oct2point then the caller will need to explicitly check.
3680 	 */
3681 
3682 	/*
3683 	 * We shouldn't ever hit this case because bignum_get_ecpoint()
3684 	 * refuses to load GF2m points.
3685 	 */
3686 	if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) !=
3687 	    NID_X9_62_prime_field)
3688 		goto out;
3689 
3690 	/* Q != infinity */
3691 	if (EC_POINT_is_at_infinity(group, public))
3692 		goto out;
3693 
3694 	if ((x = BN_new()) == NULL ||
3695 	    (y = BN_new()) == NULL ||
3696 	    (order = BN_new()) == NULL ||
3697 	    (tmp = BN_new()) == NULL) {
3698 		ret = SSH_ERR_ALLOC_FAIL;
3699 		goto out;
3700 	}
3701 
3702 	/* log2(x) > log2(order)/2, log2(y) > log2(order)/2 */
3703 	if (EC_GROUP_get_order(group, order, NULL) != 1 ||
3704 	    EC_POINT_get_affine_coordinates_GFp(group, public,
3705 	    x, y, NULL) != 1) {
3706 		ret = SSH_ERR_LIBCRYPTO_ERROR;
3707 		goto out;
3708 	}
3709 	if (BN_num_bits(x) <= BN_num_bits(order) / 2 ||
3710 	    BN_num_bits(y) <= BN_num_bits(order) / 2)
3711 		goto out;
3712 
3713 	/* nQ == infinity (n == order of subgroup) */
3714 	if ((nq = EC_POINT_new(group)) == NULL) {
3715 		ret = SSH_ERR_ALLOC_FAIL;
3716 		goto out;
3717 	}
3718 	if (EC_POINT_mul(group, nq, NULL, public, order, NULL) != 1) {
3719 		ret = SSH_ERR_LIBCRYPTO_ERROR;
3720 		goto out;
3721 	}
3722 	if (EC_POINT_is_at_infinity(group, nq) != 1)
3723 		goto out;
3724 
3725 	/* x < order - 1, y < order - 1 */
3726 	if (!BN_sub(tmp, order, BN_value_one())) {
3727 		ret = SSH_ERR_LIBCRYPTO_ERROR;
3728 		goto out;
3729 	}
3730 	if (BN_cmp(x, tmp) >= 0 || BN_cmp(y, tmp) >= 0)
3731 		goto out;
3732 	ret = 0;
3733  out:
3734 	BN_clear_free(x);
3735 	BN_clear_free(y);
3736 	BN_clear_free(order);
3737 	BN_clear_free(tmp);
3738 	EC_POINT_free(nq);
3739 	return ret;
3740 }
3741 
3742 int
sshkey_ec_validate_private(const EC_KEY * key)3743 sshkey_ec_validate_private(const EC_KEY *key)
3744 {
3745 	BIGNUM *order = NULL, *tmp = NULL;
3746 	int ret = SSH_ERR_KEY_INVALID_EC_VALUE;
3747 
3748 	if ((order = BN_new()) == NULL || (tmp = BN_new()) == NULL) {
3749 		ret = SSH_ERR_ALLOC_FAIL;
3750 		goto out;
3751 	}
3752 
3753 	/* log2(private) > log2(order)/2 */
3754 	if (EC_GROUP_get_order(EC_KEY_get0_group(key), order, NULL) != 1) {
3755 		ret = SSH_ERR_LIBCRYPTO_ERROR;
3756 		goto out;
3757 	}
3758 	if (BN_num_bits(EC_KEY_get0_private_key(key)) <=
3759 	    BN_num_bits(order) / 2)
3760 		goto out;
3761 
3762 	/* private < order - 1 */
3763 	if (!BN_sub(tmp, order, BN_value_one())) {
3764 		ret = SSH_ERR_LIBCRYPTO_ERROR;
3765 		goto out;
3766 	}
3767 	if (BN_cmp(EC_KEY_get0_private_key(key), tmp) >= 0)
3768 		goto out;
3769 	ret = 0;
3770  out:
3771 	BN_clear_free(order);
3772 	BN_clear_free(tmp);
3773 	return ret;
3774 }
3775 
3776 void
sshkey_dump_ec_point(const EC_GROUP * group,const EC_POINT * point)3777 sshkey_dump_ec_point(const EC_GROUP *group, const EC_POINT *point)
3778 {
3779 	BIGNUM *x = NULL, *y = NULL;
3780 
3781 	if (point == NULL) {
3782 		fputs("point=(NULL)\n", stderr);
3783 		return;
3784 	}
3785 	if ((x = BN_new()) == NULL || (y = BN_new()) == NULL) {
3786 		fprintf(stderr, "%s: BN_new failed\n", __func__);
3787 		goto out;
3788 	}
3789 	if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) !=
3790 	    NID_X9_62_prime_field) {
3791 		fprintf(stderr, "%s: group is not a prime field\n", __func__);
3792 		goto out;
3793 	}
3794 	if (EC_POINT_get_affine_coordinates_GFp(group, point,
3795 	    x, y, NULL) != 1) {
3796 		fprintf(stderr, "%s: EC_POINT_get_affine_coordinates_GFp\n",
3797 		    __func__);
3798 		goto out;
3799 	}
3800 	fputs("x=", stderr);
3801 	BN_print_fp(stderr, x);
3802 	fputs("\ny=", stderr);
3803 	BN_print_fp(stderr, y);
3804 	fputs("\n", stderr);
3805  out:
3806 	BN_clear_free(x);
3807 	BN_clear_free(y);
3808 }
3809 
3810 void
sshkey_dump_ec_key(const EC_KEY * key)3811 sshkey_dump_ec_key(const EC_KEY *key)
3812 {
3813 	const BIGNUM *exponent;
3814 
3815 	sshkey_dump_ec_point(EC_KEY_get0_group(key),
3816 	    EC_KEY_get0_public_key(key));
3817 	fputs("exponent=", stderr);
3818 	if ((exponent = EC_KEY_get0_private_key(key)) == NULL)
3819 		fputs("(NULL)", stderr);
3820 	else
3821 		BN_print_fp(stderr, EC_KEY_get0_private_key(key));
3822 	fputs("\n", stderr);
3823 }
3824 #endif /* WITH_OPENSSL && OPENSSL_HAS_ECC */
3825 
3826 static int
sshkey_private_to_blob2(struct sshkey * prv,struct sshbuf * blob,const char * passphrase,const char * comment,const char * ciphername,int rounds)3827 sshkey_private_to_blob2(struct sshkey *prv, struct sshbuf *blob,
3828     const char *passphrase, const char *comment, const char *ciphername,
3829     int rounds)
3830 {
3831 	u_char *cp, *key = NULL, *pubkeyblob = NULL;
3832 	u_char salt[SALT_LEN];
3833 	char *b64 = NULL;
3834 	size_t i, pubkeylen, keylen, ivlen, blocksize, authlen;
3835 	u_int check;
3836 	int r = SSH_ERR_INTERNAL_ERROR;
3837 	struct sshcipher_ctx *ciphercontext = NULL;
3838 	const struct sshcipher *cipher;
3839 	const char *kdfname = KDFNAME;
3840 	struct sshbuf *encoded = NULL, *encrypted = NULL, *kdf = NULL;
3841 
3842 	if (rounds <= 0)
3843 		rounds = DEFAULT_ROUNDS;
3844 	if (passphrase == NULL || !strlen(passphrase)) {
3845 		ciphername = "none";
3846 		kdfname = "none";
3847 	} else if (ciphername == NULL)
3848 		ciphername = DEFAULT_CIPHERNAME;
3849 	if ((cipher = cipher_by_name(ciphername)) == NULL) {
3850 		r = SSH_ERR_INVALID_ARGUMENT;
3851 		goto out;
3852 	}
3853 
3854 	if ((kdf = sshbuf_new()) == NULL ||
3855 	    (encoded = sshbuf_new()) == NULL ||
3856 	    (encrypted = sshbuf_new()) == NULL) {
3857 		r = SSH_ERR_ALLOC_FAIL;
3858 		goto out;
3859 	}
3860 	blocksize = cipher_blocksize(cipher);
3861 	keylen = cipher_keylen(cipher);
3862 	ivlen = cipher_ivlen(cipher);
3863 	authlen = cipher_authlen(cipher);
3864 	if ((key = calloc(1, keylen + ivlen)) == NULL) {
3865 		r = SSH_ERR_ALLOC_FAIL;
3866 		goto out;
3867 	}
3868 	if (strcmp(kdfname, "bcrypt") == 0) {
3869 		arc4random_buf(salt, SALT_LEN);
3870 		if (bcrypt_pbkdf(passphrase, strlen(passphrase),
3871 		    salt, SALT_LEN, key, keylen + ivlen, rounds) < 0) {
3872 			r = SSH_ERR_INVALID_ARGUMENT;
3873 			goto out;
3874 		}
3875 		if ((r = sshbuf_put_string(kdf, salt, SALT_LEN)) != 0 ||
3876 		    (r = sshbuf_put_u32(kdf, rounds)) != 0)
3877 			goto out;
3878 	} else if (strcmp(kdfname, "none") != 0) {
3879 		/* Unsupported KDF type */
3880 		r = SSH_ERR_KEY_UNKNOWN_CIPHER;
3881 		goto out;
3882 	}
3883 	if ((r = cipher_init(&ciphercontext, cipher, key, keylen,
3884 	    key + keylen, ivlen, 1)) != 0)
3885 		goto out;
3886 
3887 	if ((r = sshbuf_put(encoded, AUTH_MAGIC, sizeof(AUTH_MAGIC))) != 0 ||
3888 	    (r = sshbuf_put_cstring(encoded, ciphername)) != 0 ||
3889 	    (r = sshbuf_put_cstring(encoded, kdfname)) != 0 ||
3890 	    (r = sshbuf_put_stringb(encoded, kdf)) != 0 ||
3891 	    (r = sshbuf_put_u32(encoded, 1)) != 0 ||	/* number of keys */
3892 	    (r = sshkey_to_blob(prv, &pubkeyblob, &pubkeylen)) != 0 ||
3893 	    (r = sshbuf_put_string(encoded, pubkeyblob, pubkeylen)) != 0)
3894 		goto out;
3895 
3896 	/* set up the buffer that will be encrypted */
3897 
3898 	/* Random check bytes */
3899 	check = arc4random();
3900 	if ((r = sshbuf_put_u32(encrypted, check)) != 0 ||
3901 	    (r = sshbuf_put_u32(encrypted, check)) != 0)
3902 		goto out;
3903 
3904 	/* append private key and comment*/
3905 	if ((r = sshkey_private_serialize_opt(prv, encrypted,
3906 	     SSHKEY_SERIALIZE_FULL)) != 0 ||
3907 	    (r = sshbuf_put_cstring(encrypted, comment)) != 0)
3908 		goto out;
3909 
3910 	/* padding */
3911 	i = 0;
3912 	while (sshbuf_len(encrypted) % blocksize) {
3913 		if ((r = sshbuf_put_u8(encrypted, ++i & 0xff)) != 0)
3914 			goto out;
3915 	}
3916 
3917 	/* length in destination buffer */
3918 	if ((r = sshbuf_put_u32(encoded, sshbuf_len(encrypted))) != 0)
3919 		goto out;
3920 
3921 	/* encrypt */
3922 	if ((r = sshbuf_reserve(encoded,
3923 	    sshbuf_len(encrypted) + authlen, &cp)) != 0)
3924 		goto out;
3925 	if ((r = cipher_crypt(ciphercontext, 0, cp,
3926 	    sshbuf_ptr(encrypted), sshbuf_len(encrypted), 0, authlen)) != 0)
3927 		goto out;
3928 
3929 	sshbuf_reset(blob);
3930 
3931 	/* assemble uuencoded key */
3932 	if ((r = sshbuf_put(blob, MARK_BEGIN, MARK_BEGIN_LEN)) != 0 ||
3933 	    (r = sshbuf_dtob64(encoded, blob, 1)) != 0 ||
3934 	    (r = sshbuf_put(blob, MARK_END, MARK_END_LEN)) != 0)
3935 		goto out;
3936 
3937 	/* success */
3938 	r = 0;
3939 
3940  out:
3941 	sshbuf_free(kdf);
3942 	sshbuf_free(encoded);
3943 	sshbuf_free(encrypted);
3944 	cipher_free(ciphercontext);
3945 	explicit_bzero(salt, sizeof(salt));
3946 	if (key != NULL)
3947 		freezero(key, keylen + ivlen);
3948 	if (pubkeyblob != NULL)
3949 		freezero(pubkeyblob, pubkeylen);
3950 	if (b64 != NULL)
3951 		freezero(b64, strlen(b64));
3952 	return r;
3953 }
3954 
3955 static int
private2_uudecode(struct sshbuf * blob,struct sshbuf ** decodedp)3956 private2_uudecode(struct sshbuf *blob, struct sshbuf **decodedp)
3957 {
3958 	const u_char *cp;
3959 	size_t encoded_len;
3960 	int r;
3961 	u_char last;
3962 	struct sshbuf *encoded = NULL, *decoded = NULL;
3963 
3964 	if (blob == NULL || decodedp == NULL)
3965 		return SSH_ERR_INVALID_ARGUMENT;
3966 
3967 	*decodedp = NULL;
3968 
3969 	if ((encoded = sshbuf_new()) == NULL ||
3970 	    (decoded = sshbuf_new()) == NULL) {
3971 		r = SSH_ERR_ALLOC_FAIL;
3972 		goto out;
3973 	}
3974 
3975 	/* check preamble */
3976 	cp = sshbuf_ptr(blob);
3977 	encoded_len = sshbuf_len(blob);
3978 	if (encoded_len < (MARK_BEGIN_LEN + MARK_END_LEN) ||
3979 	    memcmp(cp, MARK_BEGIN, MARK_BEGIN_LEN) != 0) {
3980 		r = SSH_ERR_INVALID_FORMAT;
3981 		goto out;
3982 	}
3983 	cp += MARK_BEGIN_LEN;
3984 	encoded_len -= MARK_BEGIN_LEN;
3985 
3986 	/* Look for end marker, removing whitespace as we go */
3987 	while (encoded_len > 0) {
3988 		if (*cp != '\n' && *cp != '\r') {
3989 			if ((r = sshbuf_put_u8(encoded, *cp)) != 0)
3990 				goto out;
3991 		}
3992 		last = *cp;
3993 		encoded_len--;
3994 		cp++;
3995 		if (last == '\n') {
3996 			if (encoded_len >= MARK_END_LEN &&
3997 			    memcmp(cp, MARK_END, MARK_END_LEN) == 0) {
3998 				/* \0 terminate */
3999 				if ((r = sshbuf_put_u8(encoded, 0)) != 0)
4000 					goto out;
4001 				break;
4002 			}
4003 		}
4004 	}
4005 	if (encoded_len == 0) {
4006 		r = SSH_ERR_INVALID_FORMAT;
4007 		goto out;
4008 	}
4009 
4010 	/* decode base64 */
4011 	if ((r = sshbuf_b64tod(decoded, (char *)sshbuf_ptr(encoded))) != 0)
4012 		goto out;
4013 
4014 	/* check magic */
4015 	if (sshbuf_len(decoded) < sizeof(AUTH_MAGIC) ||
4016 	    memcmp(sshbuf_ptr(decoded), AUTH_MAGIC, sizeof(AUTH_MAGIC))) {
4017 		r = SSH_ERR_INVALID_FORMAT;
4018 		goto out;
4019 	}
4020 	/* success */
4021 	*decodedp = decoded;
4022 	decoded = NULL;
4023 	r = 0;
4024  out:
4025 	sshbuf_free(encoded);
4026 	sshbuf_free(decoded);
4027 	return r;
4028 }
4029 
4030 static int
private2_decrypt(struct sshbuf * decoded,const char * passphrase,struct sshbuf ** decryptedp,struct sshkey ** pubkeyp)4031 private2_decrypt(struct sshbuf *decoded, const char *passphrase,
4032     struct sshbuf **decryptedp, struct sshkey **pubkeyp)
4033 {
4034 	char *ciphername = NULL, *kdfname = NULL;
4035 	const struct sshcipher *cipher = NULL;
4036 	int r = SSH_ERR_INTERNAL_ERROR;
4037 	size_t keylen = 0, ivlen = 0, authlen = 0, slen = 0;
4038 	struct sshbuf *kdf = NULL, *decrypted = NULL;
4039 	struct sshcipher_ctx *ciphercontext = NULL;
4040 	struct sshkey *pubkey = NULL;
4041 	u_char *key = NULL, *salt = NULL, *dp;
4042 	u_int blocksize, rounds, nkeys, encrypted_len, check1, check2;
4043 
4044 	if (decoded == NULL || decryptedp == NULL || pubkeyp == NULL)
4045 		return SSH_ERR_INVALID_ARGUMENT;
4046 
4047 	*decryptedp = NULL;
4048 	*pubkeyp = NULL;
4049 
4050 	if ((decrypted = sshbuf_new()) == NULL) {
4051 		r = SSH_ERR_ALLOC_FAIL;
4052 		goto out;
4053 	}
4054 
4055 	/* parse public portion of key */
4056 	if ((r = sshbuf_consume(decoded, sizeof(AUTH_MAGIC))) != 0 ||
4057 	    (r = sshbuf_get_cstring(decoded, &ciphername, NULL)) != 0 ||
4058 	    (r = sshbuf_get_cstring(decoded, &kdfname, NULL)) != 0 ||
4059 	    (r = sshbuf_froms(decoded, &kdf)) != 0 ||
4060 	    (r = sshbuf_get_u32(decoded, &nkeys)) != 0)
4061 		goto out;
4062 
4063 	if (nkeys != 1) {
4064 		/* XXX only one key supported at present */
4065 		r = SSH_ERR_INVALID_FORMAT;
4066 		goto out;
4067 	}
4068 
4069 	if ((r = sshkey_froms(decoded, &pubkey)) != 0 ||
4070 	    (r = sshbuf_get_u32(decoded, &encrypted_len)) != 0)
4071 		goto out;
4072 
4073 	if ((cipher = cipher_by_name(ciphername)) == NULL) {
4074 		r = SSH_ERR_KEY_UNKNOWN_CIPHER;
4075 		goto out;
4076 	}
4077 	if (strcmp(kdfname, "none") != 0 && strcmp(kdfname, "bcrypt") != 0) {
4078 		r = SSH_ERR_KEY_UNKNOWN_CIPHER;
4079 		goto out;
4080 	}
4081 	if (strcmp(kdfname, "none") == 0 && strcmp(ciphername, "none") != 0) {
4082 		r = SSH_ERR_INVALID_FORMAT;
4083 		goto out;
4084 	}
4085 	if ((passphrase == NULL || strlen(passphrase) == 0) &&
4086 	    strcmp(kdfname, "none") != 0) {
4087 		/* passphrase required */
4088 		r = SSH_ERR_KEY_WRONG_PASSPHRASE;
4089 		goto out;
4090 	}
4091 
4092 	/* check size of encrypted key blob */
4093 	blocksize = cipher_blocksize(cipher);
4094 	if (encrypted_len < blocksize || (encrypted_len % blocksize) != 0) {
4095 		r = SSH_ERR_INVALID_FORMAT;
4096 		goto out;
4097 	}
4098 
4099 	/* setup key */
4100 	keylen = cipher_keylen(cipher);
4101 	ivlen = cipher_ivlen(cipher);
4102 	authlen = cipher_authlen(cipher);
4103 	if ((key = calloc(1, keylen + ivlen)) == NULL) {
4104 		r = SSH_ERR_ALLOC_FAIL;
4105 		goto out;
4106 	}
4107 	if (strcmp(kdfname, "bcrypt") == 0) {
4108 		if ((r = sshbuf_get_string(kdf, &salt, &slen)) != 0 ||
4109 		    (r = sshbuf_get_u32(kdf, &rounds)) != 0)
4110 			goto out;
4111 		if (bcrypt_pbkdf(passphrase, strlen(passphrase), salt, slen,
4112 		    key, keylen + ivlen, rounds) < 0) {
4113 			r = SSH_ERR_INVALID_FORMAT;
4114 			goto out;
4115 		}
4116 	}
4117 
4118 	/* check that an appropriate amount of auth data is present */
4119 	if (sshbuf_len(decoded) < authlen ||
4120 	    sshbuf_len(decoded) - authlen < encrypted_len) {
4121 		r = SSH_ERR_INVALID_FORMAT;
4122 		goto out;
4123 	}
4124 
4125 	/* decrypt private portion of key */
4126 	if ((r = sshbuf_reserve(decrypted, encrypted_len, &dp)) != 0 ||
4127 	    (r = cipher_init(&ciphercontext, cipher, key, keylen,
4128 	    key + keylen, ivlen, 0)) != 0)
4129 		goto out;
4130 	if ((r = cipher_crypt(ciphercontext, 0, dp, sshbuf_ptr(decoded),
4131 	    encrypted_len, 0, authlen)) != 0) {
4132 		/* an integrity error here indicates an incorrect passphrase */
4133 		if (r == SSH_ERR_MAC_INVALID)
4134 			r = SSH_ERR_KEY_WRONG_PASSPHRASE;
4135 		goto out;
4136 	}
4137 	if ((r = sshbuf_consume(decoded, encrypted_len + authlen)) != 0)
4138 		goto out;
4139 	/* there should be no trailing data */
4140 	if (sshbuf_len(decoded) != 0) {
4141 		r = SSH_ERR_INVALID_FORMAT;
4142 		goto out;
4143 	}
4144 
4145 	/* check check bytes */
4146 	if ((r = sshbuf_get_u32(decrypted, &check1)) != 0 ||
4147 	    (r = sshbuf_get_u32(decrypted, &check2)) != 0)
4148 		goto out;
4149 	if (check1 != check2) {
4150 		r = SSH_ERR_KEY_WRONG_PASSPHRASE;
4151 		goto out;
4152 	}
4153 	/* success */
4154 	*decryptedp = decrypted;
4155 	decrypted = NULL;
4156 	*pubkeyp = pubkey;
4157 	pubkey = NULL;
4158 	r = 0;
4159  out:
4160 	cipher_free(ciphercontext);
4161 	free(ciphername);
4162 	free(kdfname);
4163 	sshkey_free(pubkey);
4164 	if (salt != NULL) {
4165 		explicit_bzero(salt, slen);
4166 		free(salt);
4167 	}
4168 	if (key != NULL) {
4169 		explicit_bzero(key, keylen + ivlen);
4170 		free(key);
4171 	}
4172 	sshbuf_free(kdf);
4173 	sshbuf_free(decrypted);
4174 	return r;
4175 }
4176 
4177 /* Check deterministic padding after private key */
4178 static int
private2_check_padding(struct sshbuf * decrypted)4179 private2_check_padding(struct sshbuf *decrypted)
4180 {
4181 	u_char pad;
4182 	size_t i;
4183 	int r = SSH_ERR_INTERNAL_ERROR;
4184 
4185 	i = 0;
4186 	while (sshbuf_len(decrypted)) {
4187 		if ((r = sshbuf_get_u8(decrypted, &pad)) != 0)
4188 			goto out;
4189 		if (pad != (++i & 0xff)) {
4190 			r = SSH_ERR_INVALID_FORMAT;
4191 			goto out;
4192 		}
4193 	}
4194 	/* success */
4195 	r = 0;
4196  out:
4197 	explicit_bzero(&pad, sizeof(pad));
4198 	explicit_bzero(&i, sizeof(i));
4199 	return r;
4200 }
4201 
4202 static int
sshkey_parse_private2(struct sshbuf * blob,int type,const char * passphrase,struct sshkey ** keyp,char ** commentp)4203 sshkey_parse_private2(struct sshbuf *blob, int type, const char *passphrase,
4204     struct sshkey **keyp, char **commentp)
4205 {
4206 	char *comment = NULL;
4207 	int r = SSH_ERR_INTERNAL_ERROR;
4208 	struct sshbuf *decoded = NULL, *decrypted = NULL;
4209 	struct sshkey *k = NULL, *pubkey = NULL;
4210 
4211 	if (keyp != NULL)
4212 		*keyp = NULL;
4213 	if (commentp != NULL)
4214 		*commentp = NULL;
4215 
4216 	/* Undo base64 encoding and decrypt the private section */
4217 	if ((r = private2_uudecode(blob, &decoded)) != 0 ||
4218 	    (r = private2_decrypt(decoded, passphrase,
4219 	    &decrypted, &pubkey)) != 0)
4220 		goto out;
4221 
4222 	if (type != KEY_UNSPEC &&
4223 	    sshkey_type_plain(type) != sshkey_type_plain(pubkey->type)) {
4224 		r = SSH_ERR_KEY_TYPE_MISMATCH;
4225 		goto out;
4226 	}
4227 
4228 	/* Load the private key and comment */
4229 	if ((r = sshkey_private_deserialize(decrypted, &k)) != 0 ||
4230 	    (r = sshbuf_get_cstring(decrypted, &comment, NULL)) != 0)
4231 		goto out;
4232 
4233 	/* Check deterministic padding after private section */
4234 	if ((r = private2_check_padding(decrypted)) != 0)
4235 		goto out;
4236 
4237 	/* Check that the public key in the envelope matches the private key */
4238 	if (!sshkey_equal(pubkey, k)) {
4239 		r = SSH_ERR_INVALID_FORMAT;
4240 		goto out;
4241 	}
4242 
4243 	/* success */
4244 	r = 0;
4245 	if (keyp != NULL) {
4246 		*keyp = k;
4247 		k = NULL;
4248 	}
4249 	if (commentp != NULL) {
4250 		*commentp = comment;
4251 		comment = NULL;
4252 	}
4253  out:
4254 	free(comment);
4255 	sshbuf_free(decoded);
4256 	sshbuf_free(decrypted);
4257 	sshkey_free(k);
4258 	sshkey_free(pubkey);
4259 	return r;
4260 }
4261 
4262 static int
sshkey_parse_private2_pubkey(struct sshbuf * blob,int type,struct sshkey ** keyp)4263 sshkey_parse_private2_pubkey(struct sshbuf *blob, int type,
4264     struct sshkey **keyp)
4265 {
4266 	int r = SSH_ERR_INTERNAL_ERROR;
4267 	struct sshbuf *decoded = NULL;
4268 	struct sshkey *pubkey = NULL;
4269 	u_int nkeys = 0;
4270 
4271 	if (keyp != NULL)
4272 		*keyp = NULL;
4273 
4274 	if ((r = private2_uudecode(blob, &decoded)) != 0)
4275 		goto out;
4276 	/* parse public key from unencrypted envelope */
4277 	if ((r = sshbuf_consume(decoded, sizeof(AUTH_MAGIC))) != 0 ||
4278 	    (r = sshbuf_skip_string(decoded)) != 0 || /* cipher */
4279 	    (r = sshbuf_skip_string(decoded)) != 0 || /* KDF alg */
4280 	    (r = sshbuf_skip_string(decoded)) != 0 || /* KDF hint */
4281 	    (r = sshbuf_get_u32(decoded, &nkeys)) != 0)
4282 		goto out;
4283 
4284 	if (nkeys != 1) {
4285 		/* XXX only one key supported at present */
4286 		r = SSH_ERR_INVALID_FORMAT;
4287 		goto out;
4288 	}
4289 
4290 	/* Parse the public key */
4291 	if ((r = sshkey_froms(decoded, &pubkey)) != 0)
4292 		goto out;
4293 
4294 	if (type != KEY_UNSPEC &&
4295 	    sshkey_type_plain(type) != sshkey_type_plain(pubkey->type)) {
4296 		r = SSH_ERR_KEY_TYPE_MISMATCH;
4297 		goto out;
4298 	}
4299 
4300 	/* success */
4301 	r = 0;
4302 	if (keyp != NULL) {
4303 		*keyp = pubkey;
4304 		pubkey = NULL;
4305 	}
4306  out:
4307 	sshbuf_free(decoded);
4308 	sshkey_free(pubkey);
4309 	return r;
4310 }
4311 
4312 #ifdef WITH_OPENSSL
4313 /* convert SSH v2 key to PEM or PKCS#8 format */
4314 static int
sshkey_private_to_blob_pem_pkcs8(struct sshkey * key,struct sshbuf * buf,int format,const char * _passphrase,const char * comment)4315 sshkey_private_to_blob_pem_pkcs8(struct sshkey *key, struct sshbuf *buf,
4316     int format, const char *_passphrase, const char *comment)
4317 {
4318 	int was_shielded = sshkey_is_shielded(key);
4319 	int success, r;
4320 	int blen, len = strlen(_passphrase);
4321 	u_char *passphrase = (len > 0) ? (u_char *)_passphrase : NULL;
4322 	const EVP_CIPHER *cipher = (len > 0) ? EVP_aes_128_cbc() : NULL;
4323 	char *bptr;
4324 	BIO *bio = NULL;
4325 	struct sshbuf *blob;
4326 	EVP_PKEY *pkey = NULL;
4327 
4328 	if (len > 0 && len <= 4)
4329 		return SSH_ERR_PASSPHRASE_TOO_SHORT;
4330 	if ((blob = sshbuf_new()) == NULL)
4331 		return SSH_ERR_ALLOC_FAIL;
4332  	if ((bio = BIO_new(BIO_s_mem())) == NULL) {
4333 		r = SSH_ERR_ALLOC_FAIL;
4334 		goto out;
4335 	}
4336 	if (format == SSHKEY_PRIVATE_PKCS8 && (pkey = EVP_PKEY_new()) == NULL) {
4337 		r = SSH_ERR_ALLOC_FAIL;
4338 		goto out;
4339  	}
4340 	if ((r = sshkey_unshield_private(key)) != 0)
4341 		goto out;
4342 
4343 	switch (key->type) {
4344 	case KEY_DSA:
4345 		if (format == SSHKEY_PRIVATE_PEM) {
4346 			success = PEM_write_bio_DSAPrivateKey(bio, key->dsa,
4347 			    cipher, passphrase, len, NULL, NULL);
4348 		} else {
4349 			success = EVP_PKEY_set1_DSA(pkey, key->dsa);
4350 		}
4351 		break;
4352 #ifdef OPENSSL_HAS_ECC
4353 	case KEY_ECDSA:
4354 		if (format == SSHKEY_PRIVATE_PEM) {
4355 			success = PEM_write_bio_ECPrivateKey(bio, key->ecdsa,
4356 			    cipher, passphrase, len, NULL, NULL);
4357 		} else {
4358 			success = EVP_PKEY_set1_EC_KEY(pkey, key->ecdsa);
4359 		}
4360 		break;
4361 #endif
4362 	case KEY_RSA:
4363 		if (format == SSHKEY_PRIVATE_PEM) {
4364 			success = PEM_write_bio_RSAPrivateKey(bio, key->rsa,
4365 			    cipher, passphrase, len, NULL, NULL);
4366 		} else {
4367 			success = EVP_PKEY_set1_RSA(pkey, key->rsa);
4368 		}
4369 		break;
4370 	default:
4371 		success = 0;
4372 		break;
4373 	}
4374 	if (success == 0) {
4375 		r = SSH_ERR_LIBCRYPTO_ERROR;
4376 		goto out;
4377 	}
4378 	if (format == SSHKEY_PRIVATE_PKCS8) {
4379 		if ((success = PEM_write_bio_PrivateKey(bio, pkey, cipher,
4380 		    passphrase, len, NULL, NULL)) == 0) {
4381 			r = SSH_ERR_LIBCRYPTO_ERROR;
4382 			goto out;
4383 		}
4384 	}
4385 	if ((blen = BIO_get_mem_data(bio, &bptr)) <= 0) {
4386 		r = SSH_ERR_INTERNAL_ERROR;
4387 		goto out;
4388 	}
4389 	if ((r = sshbuf_put(blob, bptr, blen)) != 0)
4390 		goto out;
4391 	r = 0;
4392  out:
4393 	if (was_shielded)
4394 		r = sshkey_shield_private(key);
4395 	if (r == 0)
4396 		r = sshbuf_putb(buf, blob);
4397 
4398 	EVP_PKEY_free(pkey);
4399 	sshbuf_free(blob);
4400 	BIO_free(bio);
4401 	return r;
4402 }
4403 #endif /* WITH_OPENSSL */
4404 
4405 /* Serialise "key" to buffer "blob" */
4406 int
sshkey_private_to_fileblob(struct sshkey * key,struct sshbuf * blob,const char * passphrase,const char * comment,int format,const char * openssh_format_cipher,int openssh_format_rounds)4407 sshkey_private_to_fileblob(struct sshkey *key, struct sshbuf *blob,
4408     const char *passphrase, const char *comment,
4409     int format, const char *openssh_format_cipher, int openssh_format_rounds)
4410 {
4411 	switch (key->type) {
4412 #ifdef WITH_OPENSSL
4413 	case KEY_DSA:
4414 	case KEY_ECDSA:
4415 	case KEY_RSA:
4416 		break; /* see below */
4417 #endif /* WITH_OPENSSL */
4418 	case KEY_ED25519:
4419 	case KEY_ED25519_SK:
4420 #ifdef WITH_XMSS
4421 	case KEY_XMSS:
4422 #endif /* WITH_XMSS */
4423 #ifdef WITH_OPENSSL
4424 	case KEY_ECDSA_SK:
4425 #endif /* WITH_OPENSSL */
4426 		return sshkey_private_to_blob2(key, blob, passphrase,
4427 		    comment, openssh_format_cipher, openssh_format_rounds);
4428 	default:
4429 		return SSH_ERR_KEY_TYPE_UNKNOWN;
4430 	}
4431 
4432 #ifdef WITH_OPENSSL
4433 	switch (format) {
4434 	case SSHKEY_PRIVATE_OPENSSH:
4435 		return sshkey_private_to_blob2(key, blob, passphrase,
4436 		    comment, openssh_format_cipher, openssh_format_rounds);
4437 	case SSHKEY_PRIVATE_PEM:
4438 	case SSHKEY_PRIVATE_PKCS8:
4439 		return sshkey_private_to_blob_pem_pkcs8(key, blob,
4440 		    format, passphrase, comment);
4441 	default:
4442 		return SSH_ERR_INVALID_ARGUMENT;
4443 	}
4444 #endif /* WITH_OPENSSL */
4445 }
4446 
4447 #ifdef WITH_OPENSSL
4448 static int
translate_libcrypto_error(unsigned long pem_err)4449 translate_libcrypto_error(unsigned long pem_err)
4450 {
4451 	int pem_reason = ERR_GET_REASON(pem_err);
4452 
4453 	switch (ERR_GET_LIB(pem_err)) {
4454 	case ERR_LIB_PEM:
4455 		switch (pem_reason) {
4456 		case PEM_R_BAD_PASSWORD_READ:
4457 #ifdef PEM_R_PROBLEMS_GETTING_PASSWORD
4458 		case PEM_R_PROBLEMS_GETTING_PASSWORD:
4459 #endif
4460 		case PEM_R_BAD_DECRYPT:
4461 			return SSH_ERR_KEY_WRONG_PASSPHRASE;
4462 		default:
4463 			return SSH_ERR_INVALID_FORMAT;
4464 		}
4465 	case ERR_LIB_EVP:
4466 		switch (pem_reason) {
4467 #ifdef EVP_R_BAD_DECRYPT
4468 		case EVP_R_BAD_DECRYPT:
4469 			return SSH_ERR_KEY_WRONG_PASSPHRASE;
4470 #endif
4471 #ifdef EVP_R_BN_DECODE_ERROR
4472 		case EVP_R_BN_DECODE_ERROR:
4473 #endif
4474 		case EVP_R_DECODE_ERROR:
4475 #ifdef EVP_R_PRIVATE_KEY_DECODE_ERROR
4476 		case EVP_R_PRIVATE_KEY_DECODE_ERROR:
4477 #endif
4478 			return SSH_ERR_INVALID_FORMAT;
4479 		default:
4480 			return SSH_ERR_LIBCRYPTO_ERROR;
4481 		}
4482 	case ERR_LIB_ASN1:
4483 		return SSH_ERR_INVALID_FORMAT;
4484 	}
4485 	return SSH_ERR_LIBCRYPTO_ERROR;
4486 }
4487 
4488 static void
clear_libcrypto_errors(void)4489 clear_libcrypto_errors(void)
4490 {
4491 	while (ERR_get_error() != 0)
4492 		;
4493 }
4494 
4495 /*
4496  * Translate OpenSSL error codes to determine whether
4497  * passphrase is required/incorrect.
4498  */
4499 static int
convert_libcrypto_error(void)4500 convert_libcrypto_error(void)
4501 {
4502 	/*
4503 	 * Some password errors are reported at the beginning
4504 	 * of the error queue.
4505 	 */
4506 	if (translate_libcrypto_error(ERR_peek_error()) ==
4507 	    SSH_ERR_KEY_WRONG_PASSPHRASE)
4508 		return SSH_ERR_KEY_WRONG_PASSPHRASE;
4509 	return translate_libcrypto_error(ERR_peek_last_error());
4510 }
4511 
4512 static int
pem_passphrase_cb(char * buf,int size,int rwflag,void * u)4513 pem_passphrase_cb(char *buf, int size, int rwflag, void *u)
4514 {
4515 	char *p = (char *)u;
4516 	size_t len;
4517 
4518 	if (p == NULL || (len = strlen(p)) == 0)
4519 		return -1;
4520 	if (size < 0 || len > (size_t)size)
4521 		return -1;
4522 	memcpy(buf, p, len);
4523 	return (int)len;
4524 }
4525 
4526 static int
sshkey_parse_private_pem_fileblob(struct sshbuf * blob,int type,const char * passphrase,struct sshkey ** keyp)4527 sshkey_parse_private_pem_fileblob(struct sshbuf *blob, int type,
4528     const char *passphrase, struct sshkey **keyp)
4529 {
4530 	EVP_PKEY *pk = NULL;
4531 	struct sshkey *prv = NULL;
4532 	BIO *bio = NULL;
4533 	int r;
4534 
4535 	if (keyp != NULL)
4536 		*keyp = NULL;
4537 
4538 	if ((bio = BIO_new(BIO_s_mem())) == NULL || sshbuf_len(blob) > INT_MAX)
4539 		return SSH_ERR_ALLOC_FAIL;
4540 	if (BIO_write(bio, sshbuf_ptr(blob), sshbuf_len(blob)) !=
4541 	    (int)sshbuf_len(blob)) {
4542 		r = SSH_ERR_ALLOC_FAIL;
4543 		goto out;
4544 	}
4545 
4546 	clear_libcrypto_errors();
4547 	if ((pk = PEM_read_bio_PrivateKey(bio, NULL, pem_passphrase_cb,
4548 	    (char *)passphrase)) == NULL) {
4549 	       /*
4550 		* libcrypto may return various ASN.1 errors when attempting
4551 		* to parse a key with an incorrect passphrase.
4552 		* Treat all format errors as "incorrect passphrase" if a
4553 		* passphrase was supplied.
4554 		*/
4555 		if (passphrase != NULL && *passphrase != '\0')
4556 			r = SSH_ERR_KEY_WRONG_PASSPHRASE;
4557 		else
4558 			r = convert_libcrypto_error();
4559 		goto out;
4560 	}
4561 	if (EVP_PKEY_base_id(pk) == EVP_PKEY_RSA &&
4562 	    (type == KEY_UNSPEC || type == KEY_RSA)) {
4563 		if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
4564 			r = SSH_ERR_ALLOC_FAIL;
4565 			goto out;
4566 		}
4567 		prv->rsa = EVP_PKEY_get1_RSA(pk);
4568 		prv->type = KEY_RSA;
4569 #ifdef DEBUG_PK
4570 		RSA_print_fp(stderr, prv->rsa, 8);
4571 #endif
4572 		if (RSA_blinding_on(prv->rsa, NULL) != 1) {
4573 			r = SSH_ERR_LIBCRYPTO_ERROR;
4574 			goto out;
4575 		}
4576 		if ((r = check_rsa_length(prv->rsa)) != 0)
4577 			goto out;
4578 	} else if (EVP_PKEY_base_id(pk) == EVP_PKEY_DSA &&
4579 	    (type == KEY_UNSPEC || type == KEY_DSA)) {
4580 		if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
4581 			r = SSH_ERR_ALLOC_FAIL;
4582 			goto out;
4583 		}
4584 		prv->dsa = EVP_PKEY_get1_DSA(pk);
4585 		prv->type = KEY_DSA;
4586 #ifdef DEBUG_PK
4587 		DSA_print_fp(stderr, prv->dsa, 8);
4588 #endif
4589 #ifdef OPENSSL_HAS_ECC
4590 	} else if (EVP_PKEY_base_id(pk) == EVP_PKEY_EC &&
4591 	    (type == KEY_UNSPEC || type == KEY_ECDSA)) {
4592 		if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
4593 			r = SSH_ERR_ALLOC_FAIL;
4594 			goto out;
4595 		}
4596 		prv->ecdsa = EVP_PKEY_get1_EC_KEY(pk);
4597 		prv->type = KEY_ECDSA;
4598 		prv->ecdsa_nid = sshkey_ecdsa_key_to_nid(prv->ecdsa);
4599 		if (prv->ecdsa_nid == -1 ||
4600 		    sshkey_curve_nid_to_name(prv->ecdsa_nid) == NULL ||
4601 		    sshkey_ec_validate_public(EC_KEY_get0_group(prv->ecdsa),
4602 		    EC_KEY_get0_public_key(prv->ecdsa)) != 0 ||
4603 		    sshkey_ec_validate_private(prv->ecdsa) != 0) {
4604 			r = SSH_ERR_INVALID_FORMAT;
4605 			goto out;
4606 		}
4607 # ifdef DEBUG_PK
4608 		if (prv != NULL && prv->ecdsa != NULL)
4609 			sshkey_dump_ec_key(prv->ecdsa);
4610 # endif
4611 #endif /* OPENSSL_HAS_ECC */
4612 	} else {
4613 		r = SSH_ERR_INVALID_FORMAT;
4614 		goto out;
4615 	}
4616 	r = 0;
4617 	if (keyp != NULL) {
4618 		*keyp = prv;
4619 		prv = NULL;
4620 	}
4621  out:
4622 	BIO_free(bio);
4623 	EVP_PKEY_free(pk);
4624 	sshkey_free(prv);
4625 	return r;
4626 }
4627 #endif /* WITH_OPENSSL */
4628 
4629 int
sshkey_parse_private_fileblob_type(struct sshbuf * blob,int type,const char * passphrase,struct sshkey ** keyp,char ** commentp)4630 sshkey_parse_private_fileblob_type(struct sshbuf *blob, int type,
4631     const char *passphrase, struct sshkey **keyp, char **commentp)
4632 {
4633 	int r = SSH_ERR_INTERNAL_ERROR;
4634 
4635 	if (keyp != NULL)
4636 		*keyp = NULL;
4637 	if (commentp != NULL)
4638 		*commentp = NULL;
4639 
4640 	switch (type) {
4641 	case KEY_ED25519:
4642 	case KEY_XMSS:
4643 		/* No fallback for new-format-only keys */
4644 		return sshkey_parse_private2(blob, type, passphrase,
4645 		    keyp, commentp);
4646 	default:
4647 		r = sshkey_parse_private2(blob, type, passphrase, keyp,
4648 		    commentp);
4649 		/* Only fallback to PEM parser if a format error occurred. */
4650 		if (r != SSH_ERR_INVALID_FORMAT)
4651 			return r;
4652 #ifdef WITH_OPENSSL
4653 		return sshkey_parse_private_pem_fileblob(blob, type,
4654 		    passphrase, keyp);
4655 #else
4656 		return SSH_ERR_INVALID_FORMAT;
4657 #endif /* WITH_OPENSSL */
4658 	}
4659 }
4660 
4661 int
sshkey_parse_private_fileblob(struct sshbuf * buffer,const char * passphrase,struct sshkey ** keyp,char ** commentp)4662 sshkey_parse_private_fileblob(struct sshbuf *buffer, const char *passphrase,
4663     struct sshkey **keyp, char **commentp)
4664 {
4665 	if (keyp != NULL)
4666 		*keyp = NULL;
4667 	if (commentp != NULL)
4668 		*commentp = NULL;
4669 
4670 	return sshkey_parse_private_fileblob_type(buffer, KEY_UNSPEC,
4671 	    passphrase, keyp, commentp);
4672 }
4673 
4674 void
sshkey_sig_details_free(struct sshkey_sig_details * details)4675 sshkey_sig_details_free(struct sshkey_sig_details *details)
4676 {
4677 	freezero(details, sizeof(*details));
4678 }
4679 
4680 int
sshkey_parse_pubkey_from_private_fileblob_type(struct sshbuf * blob,int type,struct sshkey ** pubkeyp)4681 sshkey_parse_pubkey_from_private_fileblob_type(struct sshbuf *blob, int type,
4682     struct sshkey **pubkeyp)
4683 {
4684 	int r = SSH_ERR_INTERNAL_ERROR;
4685 
4686 	if (pubkeyp != NULL)
4687 		*pubkeyp = NULL;
4688 	/* only new-format private keys bundle a public key inside */
4689 	if ((r = sshkey_parse_private2_pubkey(blob, type, pubkeyp)) != 0)
4690 		return r;
4691 	return 0;
4692 }
4693 
4694 #ifdef WITH_XMSS
4695 /*
4696  * serialize the key with the current state and forward the state
4697  * maxsign times.
4698  */
4699 int
sshkey_private_serialize_maxsign(struct sshkey * k,struct sshbuf * b,u_int32_t maxsign,sshkey_printfn * pr)4700 sshkey_private_serialize_maxsign(struct sshkey *k, struct sshbuf *b,
4701     u_int32_t maxsign, sshkey_printfn *pr)
4702 {
4703 	int r, rupdate;
4704 
4705 	if (maxsign == 0 ||
4706 	    sshkey_type_plain(k->type) != KEY_XMSS)
4707 		return sshkey_private_serialize_opt(k, b,
4708 		    SSHKEY_SERIALIZE_DEFAULT);
4709 	if ((r = sshkey_xmss_get_state(k, pr)) != 0 ||
4710 	    (r = sshkey_private_serialize_opt(k, b,
4711 	    SSHKEY_SERIALIZE_STATE)) != 0 ||
4712 	    (r = sshkey_xmss_forward_state(k, maxsign)) != 0)
4713 		goto out;
4714 	r = 0;
4715 out:
4716 	if ((rupdate = sshkey_xmss_update_state(k, pr)) != 0) {
4717 		if (r == 0)
4718 			r = rupdate;
4719 	}
4720 	return r;
4721 }
4722 
4723 u_int32_t
sshkey_signatures_left(const struct sshkey * k)4724 sshkey_signatures_left(const struct sshkey *k)
4725 {
4726 	if (sshkey_type_plain(k->type) == KEY_XMSS)
4727 		return sshkey_xmss_signatures_left(k);
4728 	return 0;
4729 }
4730 
4731 int
sshkey_enable_maxsign(struct sshkey * k,u_int32_t maxsign)4732 sshkey_enable_maxsign(struct sshkey *k, u_int32_t maxsign)
4733 {
4734 	if (sshkey_type_plain(k->type) != KEY_XMSS)
4735 		return SSH_ERR_INVALID_ARGUMENT;
4736 	return sshkey_xmss_enable_maxsign(k, maxsign);
4737 }
4738 
4739 int
sshkey_set_filename(struct sshkey * k,const char * filename)4740 sshkey_set_filename(struct sshkey *k, const char *filename)
4741 {
4742 	if (k == NULL)
4743 		return SSH_ERR_INVALID_ARGUMENT;
4744 	if (sshkey_type_plain(k->type) != KEY_XMSS)
4745 		return 0;
4746 	if (filename == NULL)
4747 		return SSH_ERR_INVALID_ARGUMENT;
4748 	if ((k->xmss_filename = strdup(filename)) == NULL)
4749 		return SSH_ERR_ALLOC_FAIL;
4750 	return 0;
4751 }
4752 #else
4753 int
sshkey_private_serialize_maxsign(struct sshkey * k,struct sshbuf * b,u_int32_t maxsign,sshkey_printfn * pr)4754 sshkey_private_serialize_maxsign(struct sshkey *k, struct sshbuf *b,
4755     u_int32_t maxsign, sshkey_printfn *pr)
4756 {
4757 	return sshkey_private_serialize_opt(k, b, SSHKEY_SERIALIZE_DEFAULT);
4758 }
4759 
4760 u_int32_t
sshkey_signatures_left(const struct sshkey * k)4761 sshkey_signatures_left(const struct sshkey *k)
4762 {
4763 	return 0;
4764 }
4765 
4766 int
sshkey_enable_maxsign(struct sshkey * k,u_int32_t maxsign)4767 sshkey_enable_maxsign(struct sshkey *k, u_int32_t maxsign)
4768 {
4769 	return SSH_ERR_INVALID_ARGUMENT;
4770 }
4771 
4772 int
sshkey_set_filename(struct sshkey * k,const char * filename)4773 sshkey_set_filename(struct sshkey *k, const char *filename)
4774 {
4775 	if (k == NULL)
4776 		return SSH_ERR_INVALID_ARGUMENT;
4777 	return 0;
4778 }
4779 #endif /* WITH_XMSS */
4780