1 /* $OpenBSD: sshkey.c,v 1.140 2023/10/16 08:40:00 dtucker Exp $ */
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.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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.
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.
30 #include <sys/types.h>
31 #include <netinet/in.h>
34 #include <openssl/evp.h>
35 #include <openssl/err.h>
36 #include <openssl/pem.h>
39 #include "crypto_api.h"
50 #endif /* HAVE_UTIL_H */
58 #define SSHKEY_INTERNAL
64 #include "sshkey-xmss.h"
65 #include "xmss_fast.h"
68 #include "openbsd-compat/openssl-compat.h"
70 /* openssh private key file format */
71 #define MARK_BEGIN "-----BEGIN OPENSSH PRIVATE KEY-----\n"
72 #define MARK_END "-----END OPENSSH PRIVATE KEY-----\n"
73 #define MARK_BEGIN_LEN (sizeof(MARK_BEGIN) - 1)
74 #define MARK_END_LEN (sizeof(MARK_END) - 1)
75 #define KDFNAME "bcrypt"
76 #define AUTH_MAGIC "openssh-key-v1"
78 #define DEFAULT_CIPHERNAME "aes256-ctr"
79 #define DEFAULT_ROUNDS 24
81 /* Version identification string for SSH v1 identity files. */
82 #define LEGACY_BEGIN "SSH PRIVATE KEY FILE FORMAT 1.1\n"
85 * Constants relating to "shielding" support; protection of keys expected
86 * to remain in memory for long durations
88 #define SSHKEY_SHIELD_PREKEY_LEN (16 * 1024)
89 #define SSHKEY_SHIELD_CIPHER "aes256-ctr" /* XXX want AES-EME* */
90 #define SSHKEY_SHIELD_PREKEY_HASH SSH_DIGEST_SHA512
92 int sshkey_private_serialize_opt(struct sshkey *key,
93 struct sshbuf *buf, enum sshkey_serialize_rep);
94 static int sshkey_from_blob_internal(struct sshbuf *buf,
95 struct sshkey **keyp, int allow_cert);
97 /* Supported key types */
98 extern const struct sshkey_impl sshkey_ed25519_impl;
99 extern const struct sshkey_impl sshkey_ed25519_cert_impl;
100 extern const struct sshkey_impl sshkey_ed25519_sk_impl;
101 extern const struct sshkey_impl sshkey_ed25519_sk_cert_impl;
103 # ifdef OPENSSL_HAS_ECC
105 extern const struct sshkey_impl sshkey_ecdsa_sk_impl;
106 extern const struct sshkey_impl sshkey_ecdsa_sk_cert_impl;
107 extern const struct sshkey_impl sshkey_ecdsa_sk_webauthn_impl;
108 # endif /* ENABLE_SK */
109 extern const struct sshkey_impl sshkey_ecdsa_nistp256_impl;
110 extern const struct sshkey_impl sshkey_ecdsa_nistp256_cert_impl;
111 extern const struct sshkey_impl sshkey_ecdsa_nistp384_impl;
112 extern const struct sshkey_impl sshkey_ecdsa_nistp384_cert_impl;
113 # ifdef OPENSSL_HAS_NISTP521
114 extern const struct sshkey_impl sshkey_ecdsa_nistp521_impl;
115 extern const struct sshkey_impl sshkey_ecdsa_nistp521_cert_impl;
116 # endif /* OPENSSL_HAS_NISTP521 */
117 # endif /* OPENSSL_HAS_ECC */
118 extern const struct sshkey_impl sshkey_rsa_impl;
119 extern const struct sshkey_impl sshkey_rsa_cert_impl;
120 extern const struct sshkey_impl sshkey_rsa_sha256_impl;
121 extern const struct sshkey_impl sshkey_rsa_sha256_cert_impl;
122 extern const struct sshkey_impl sshkey_rsa_sha512_impl;
123 extern const struct sshkey_impl sshkey_rsa_sha512_cert_impl;
124 extern const struct sshkey_impl sshkey_dss_impl;
125 extern const struct sshkey_impl sshkey_dsa_cert_impl;
126 #endif /* WITH_OPENSSL */
128 extern const struct sshkey_impl sshkey_xmss_impl;
129 extern const struct sshkey_impl sshkey_xmss_cert_impl;
132 const struct sshkey_impl * const keyimpls[] = {
133 &sshkey_ed25519_impl,
134 &sshkey_ed25519_cert_impl,
136 &sshkey_ed25519_sk_impl,
137 &sshkey_ed25519_sk_cert_impl,
140 # ifdef OPENSSL_HAS_ECC
141 &sshkey_ecdsa_nistp256_impl,
142 &sshkey_ecdsa_nistp256_cert_impl,
143 &sshkey_ecdsa_nistp384_impl,
144 &sshkey_ecdsa_nistp384_cert_impl,
145 # ifdef OPENSSL_HAS_NISTP521
146 &sshkey_ecdsa_nistp521_impl,
147 &sshkey_ecdsa_nistp521_cert_impl,
148 # endif /* OPENSSL_HAS_NISTP521 */
150 &sshkey_ecdsa_sk_impl,
151 &sshkey_ecdsa_sk_cert_impl,
152 &sshkey_ecdsa_sk_webauthn_impl,
153 # endif /* ENABLE_SK */
154 # endif /* OPENSSL_HAS_ECC */
156 &sshkey_dsa_cert_impl,
158 &sshkey_rsa_cert_impl,
159 &sshkey_rsa_sha256_impl,
160 &sshkey_rsa_sha256_cert_impl,
161 &sshkey_rsa_sha512_impl,
162 &sshkey_rsa_sha512_cert_impl,
163 #endif /* WITH_OPENSSL */
166 &sshkey_xmss_cert_impl,
171 static const struct sshkey_impl *
172 sshkey_impl_from_type(int type)
176 for (i = 0; keyimpls[i] != NULL; i++) {
177 if (keyimpls[i]->type == type)
183 static const struct sshkey_impl *
184 sshkey_impl_from_type_nid(int type, int nid)
188 for (i = 0; keyimpls[i] != NULL; i++) {
189 if (keyimpls[i]->type == type &&
190 (keyimpls[i]->nid == 0 || keyimpls[i]->nid == nid))
196 static const struct sshkey_impl *
197 sshkey_impl_from_key(const struct sshkey *k)
201 return sshkey_impl_from_type_nid(k->type, k->ecdsa_nid);
205 sshkey_type(const struct sshkey *k)
207 const struct sshkey_impl *impl;
209 if ((impl = sshkey_impl_from_key(k)) == NULL)
211 return impl->shortname;
215 sshkey_ssh_name_from_type_nid(int type, int nid)
217 const struct sshkey_impl *impl;
219 if ((impl = sshkey_impl_from_type_nid(type, nid)) == NULL)
220 return "ssh-unknown";
225 sshkey_type_is_cert(int type)
227 const struct sshkey_impl *impl;
229 if ((impl = sshkey_impl_from_type(type)) == NULL)
235 sshkey_ssh_name(const struct sshkey *k)
237 return sshkey_ssh_name_from_type_nid(k->type, k->ecdsa_nid);
241 sshkey_ssh_name_plain(const struct sshkey *k)
243 return sshkey_ssh_name_from_type_nid(sshkey_type_plain(k->type),
248 sshkey_type_from_name(const char *name)
251 const struct sshkey_impl *impl;
253 for (i = 0; keyimpls[i] != NULL; i++) {
255 /* Only allow shortname matches for plain key types */
256 if ((impl->name != NULL && strcmp(name, impl->name) == 0) ||
257 (!impl->cert && strcasecmp(impl->shortname, name) == 0))
264 key_type_is_ecdsa_variant(int type)
270 case KEY_ECDSA_SK_CERT:
277 sshkey_ecdsa_nid_from_name(const char *name)
281 for (i = 0; keyimpls[i] != NULL; i++) {
282 if (!key_type_is_ecdsa_variant(keyimpls[i]->type))
284 if (keyimpls[i]->name != NULL &&
285 strcmp(name, keyimpls[i]->name) == 0)
286 return keyimpls[i]->nid;
292 sshkey_match_keyname_to_sigalgs(const char *keyname, const char *sigalgs)
296 if (sigalgs == NULL || *sigalgs == '\0' ||
297 (ktype = sshkey_type_from_name(keyname)) == KEY_UNSPEC)
299 else if (ktype == KEY_RSA) {
300 return match_pattern_list("ssh-rsa", sigalgs, 0) == 1 ||
301 match_pattern_list("rsa-sha2-256", sigalgs, 0) == 1 ||
302 match_pattern_list("rsa-sha2-512", sigalgs, 0) == 1;
303 } else if (ktype == KEY_RSA_CERT) {
304 return match_pattern_list("ssh-rsa-cert-v01@openssh.com",
306 match_pattern_list("rsa-sha2-256-cert-v01@openssh.com",
308 match_pattern_list("rsa-sha2-512-cert-v01@openssh.com",
311 return match_pattern_list(keyname, sigalgs, 0) == 1;
315 sshkey_alg_list(int certs_only, int plain_only, int include_sigonly, char sep)
317 char *tmp, *ret = NULL;
318 size_t i, nlen, rlen = 0;
319 const struct sshkey_impl *impl;
321 for (i = 0; keyimpls[i] != NULL; i++) {
323 if (impl->name == NULL)
325 if (!include_sigonly && impl->sigonly)
327 if ((certs_only && !impl->cert) || (plain_only && impl->cert))
331 nlen = strlen(impl->name);
332 if ((tmp = realloc(ret, rlen + nlen + 2)) == NULL) {
337 memcpy(ret + rlen, impl->name, nlen + 1);
344 sshkey_names_valid2(const char *names, int allow_wildcard, int plain_only)
347 const struct sshkey_impl *impl;
350 if (names == NULL || strcmp(names, "") == 0)
352 if ((s = cp = strdup(names)) == NULL)
354 for ((p = strsep(&cp, ",")); p && *p != '\0';
355 (p = strsep(&cp, ","))) {
356 type = sshkey_type_from_name(p);
357 if (type == KEY_UNSPEC) {
358 if (allow_wildcard) {
360 * Try matching key types against the string.
361 * If any has a positive or negative match then
362 * the component is accepted.
365 for (i = 0; keyimpls[i] != NULL; i++) {
366 if (match_pattern_list(
367 keyimpls[i]->name, p, 0) != 0) {
377 } else if (plain_only && sshkey_type_is_cert(type)) {
387 sshkey_size(const struct sshkey *k)
389 const struct sshkey_impl *impl;
391 if ((impl = sshkey_impl_from_key(k)) == NULL)
393 if (impl->funcs->size != NULL)
394 return impl->funcs->size(k);
395 return impl->keybits;
399 sshkey_type_is_valid_ca(int type)
401 const struct sshkey_impl *impl;
403 if ((impl = sshkey_impl_from_type(type)) == NULL)
405 /* All non-certificate types may act as CAs */
410 sshkey_is_cert(const struct sshkey *k)
414 return sshkey_type_is_cert(k->type);
418 sshkey_is_sk(const struct sshkey *k)
422 switch (sshkey_type_plain(k->type)) {
431 /* Return the cert-less equivalent to a certified key type */
433 sshkey_type_plain(int type)
442 case KEY_ECDSA_SK_CERT:
444 case KEY_ED25519_CERT:
446 case KEY_ED25519_SK_CERT:
447 return KEY_ED25519_SK;
455 /* Return the cert equivalent to a plain key type */
457 sshkey_type_certified(int type)
465 return KEY_ECDSA_CERT;
467 return KEY_ECDSA_SK_CERT;
469 return KEY_ED25519_CERT;
471 return KEY_ED25519_SK_CERT;
473 return KEY_XMSS_CERT;
480 /* XXX: these are really begging for a table-driven approach */
482 sshkey_curve_name_to_nid(const char *name)
484 if (strcmp(name, "nistp256") == 0)
485 return NID_X9_62_prime256v1;
486 else if (strcmp(name, "nistp384") == 0)
487 return NID_secp384r1;
488 # ifdef OPENSSL_HAS_NISTP521
489 else if (strcmp(name, "nistp521") == 0)
490 return NID_secp521r1;
491 # endif /* OPENSSL_HAS_NISTP521 */
497 sshkey_curve_nid_to_bits(int nid)
500 case NID_X9_62_prime256v1:
504 # ifdef OPENSSL_HAS_NISTP521
507 # endif /* OPENSSL_HAS_NISTP521 */
514 sshkey_ecdsa_bits_to_nid(int bits)
518 return NID_X9_62_prime256v1;
520 return NID_secp384r1;
521 # ifdef OPENSSL_HAS_NISTP521
523 return NID_secp521r1;
524 # endif /* OPENSSL_HAS_NISTP521 */
531 sshkey_curve_nid_to_name(int nid)
534 case NID_X9_62_prime256v1:
538 # ifdef OPENSSL_HAS_NISTP521
541 # endif /* OPENSSL_HAS_NISTP521 */
548 sshkey_ec_nid_to_hash_alg(int nid)
550 int kbits = sshkey_curve_nid_to_bits(nid);
555 /* RFC5656 section 6.2.1 */
557 return SSH_DIGEST_SHA256;
558 else if (kbits <= 384)
559 return SSH_DIGEST_SHA384;
561 return SSH_DIGEST_SHA512;
563 #endif /* WITH_OPENSSL */
566 cert_free(struct sshkey_cert *cert)
572 sshbuf_free(cert->certblob);
573 sshbuf_free(cert->critical);
574 sshbuf_free(cert->extensions);
576 for (i = 0; i < cert->nprincipals; i++)
577 free(cert->principals[i]);
578 free(cert->principals);
579 sshkey_free(cert->signature_key);
580 free(cert->signature_type);
581 freezero(cert, sizeof(*cert));
584 static struct sshkey_cert *
587 struct sshkey_cert *cert;
589 if ((cert = calloc(1, sizeof(*cert))) == NULL)
591 if ((cert->certblob = sshbuf_new()) == NULL ||
592 (cert->critical = sshbuf_new()) == NULL ||
593 (cert->extensions = sshbuf_new()) == NULL) {
598 cert->principals = NULL;
599 cert->signature_key = NULL;
600 cert->signature_type = NULL;
608 const struct sshkey_impl *impl = NULL;
610 if (type != KEY_UNSPEC &&
611 (impl = sshkey_impl_from_type(type)) == NULL)
614 /* All non-certificate types may act as CAs */
615 if ((k = calloc(1, sizeof(*k))) == NULL)
619 if (impl != NULL && impl->funcs->alloc != NULL) {
620 if (impl->funcs->alloc(k) != 0) {
625 if (sshkey_is_cert(k)) {
626 if ((k->cert = cert_new()) == NULL) {
635 /* Frees common FIDO fields */
637 sshkey_sk_cleanup(struct sshkey *k)
639 free(k->sk_application);
640 sshbuf_free(k->sk_key_handle);
641 sshbuf_free(k->sk_reserved);
642 k->sk_application = NULL;
643 k->sk_key_handle = k->sk_reserved = NULL;
647 sshkey_free_contents(struct sshkey *k)
649 const struct sshkey_impl *impl;
653 if ((impl = sshkey_impl_from_type(k->type)) != NULL &&
654 impl->funcs->cleanup != NULL)
655 impl->funcs->cleanup(k);
656 if (sshkey_is_cert(k))
658 freezero(k->shielded_private, k->shielded_len);
659 freezero(k->shield_prekey, k->shield_prekey_len);
663 sshkey_free(struct sshkey *k)
665 sshkey_free_contents(k);
666 freezero(k, sizeof(*k));
670 cert_compare(struct sshkey_cert *a, struct sshkey_cert *b)
672 if (a == NULL && b == NULL)
674 if (a == NULL || b == NULL)
676 if (sshbuf_len(a->certblob) != sshbuf_len(b->certblob))
678 if (timingsafe_bcmp(sshbuf_ptr(a->certblob), sshbuf_ptr(b->certblob),
679 sshbuf_len(a->certblob)) != 0)
684 /* Compares FIDO-specific pubkey fields only */
686 sshkey_sk_fields_equal(const struct sshkey *a, const struct sshkey *b)
688 if (a->sk_application == NULL || b->sk_application == NULL)
690 if (strcmp(a->sk_application, b->sk_application) != 0)
696 * Compare public portions of key only, allowing comparisons between
697 * certificates and plain keys too.
700 sshkey_equal_public(const struct sshkey *a, const struct sshkey *b)
702 const struct sshkey_impl *impl;
704 if (a == NULL || b == NULL ||
705 sshkey_type_plain(a->type) != sshkey_type_plain(b->type))
707 if ((impl = sshkey_impl_from_type(a->type)) == NULL)
709 return impl->funcs->equal(a, b);
713 sshkey_equal(const struct sshkey *a, const struct sshkey *b)
715 if (a == NULL || b == NULL || a->type != b->type)
717 if (sshkey_is_cert(a)) {
718 if (!cert_compare(a->cert, b->cert))
721 return sshkey_equal_public(a, b);
725 /* Serialise common FIDO key parts */
727 sshkey_serialize_sk(const struct sshkey *key, struct sshbuf *b)
731 if ((r = sshbuf_put_cstring(b, key->sk_application)) != 0)
738 to_blob_buf(const struct sshkey *key, struct sshbuf *b, int force_plain,
739 enum sshkey_serialize_rep opts)
741 int type, ret = SSH_ERR_INTERNAL_ERROR;
742 const char *typename;
743 const struct sshkey_impl *impl;
746 return SSH_ERR_INVALID_ARGUMENT;
748 type = force_plain ? sshkey_type_plain(key->type) : key->type;
750 if (sshkey_type_is_cert(type)) {
751 if (key->cert == NULL)
752 return SSH_ERR_EXPECTED_CERT;
753 if (sshbuf_len(key->cert->certblob) == 0)
754 return SSH_ERR_KEY_LACKS_CERTBLOB;
755 /* Use the existing blob */
756 if ((ret = sshbuf_putb(b, key->cert->certblob)) != 0)
760 if ((impl = sshkey_impl_from_type(type)) == NULL)
761 return SSH_ERR_KEY_TYPE_UNKNOWN;
763 typename = sshkey_ssh_name_from_type_nid(type, key->ecdsa_nid);
764 if ((ret = sshbuf_put_cstring(b, typename)) != 0)
766 return impl->funcs->serialize_public(key, b, opts);
770 sshkey_putb(const struct sshkey *key, struct sshbuf *b)
772 return to_blob_buf(key, b, 0, SSHKEY_SERIALIZE_DEFAULT);
776 sshkey_puts_opts(const struct sshkey *key, struct sshbuf *b,
777 enum sshkey_serialize_rep opts)
782 if ((tmp = sshbuf_new()) == NULL)
783 return SSH_ERR_ALLOC_FAIL;
784 r = to_blob_buf(key, tmp, 0, opts);
786 r = sshbuf_put_stringb(b, tmp);
792 sshkey_puts(const struct sshkey *key, struct sshbuf *b)
794 return sshkey_puts_opts(key, b, SSHKEY_SERIALIZE_DEFAULT);
798 sshkey_putb_plain(const struct sshkey *key, struct sshbuf *b)
800 return to_blob_buf(key, b, 1, SSHKEY_SERIALIZE_DEFAULT);
804 to_blob(const struct sshkey *key, u_char **blobp, size_t *lenp, int force_plain,
805 enum sshkey_serialize_rep opts)
807 int ret = SSH_ERR_INTERNAL_ERROR;
809 struct sshbuf *b = NULL;
815 if ((b = sshbuf_new()) == NULL)
816 return SSH_ERR_ALLOC_FAIL;
817 if ((ret = to_blob_buf(key, b, force_plain, opts)) != 0)
823 if ((*blobp = malloc(len)) == NULL) {
824 ret = SSH_ERR_ALLOC_FAIL;
827 memcpy(*blobp, sshbuf_ptr(b), len);
836 sshkey_to_blob(const struct sshkey *key, u_char **blobp, size_t *lenp)
838 return to_blob(key, blobp, lenp, 0, SSHKEY_SERIALIZE_DEFAULT);
842 sshkey_plain_to_blob(const struct sshkey *key, u_char **blobp, size_t *lenp)
844 return to_blob(key, blobp, lenp, 1, SSHKEY_SERIALIZE_DEFAULT);
848 sshkey_fingerprint_raw(const struct sshkey *k, int dgst_alg,
849 u_char **retp, size_t *lenp)
851 u_char *blob = NULL, *ret = NULL;
853 int r = SSH_ERR_INTERNAL_ERROR;
859 if (ssh_digest_bytes(dgst_alg) == 0) {
860 r = SSH_ERR_INVALID_ARGUMENT;
863 if ((r = to_blob(k, &blob, &blob_len, 1, SSHKEY_SERIALIZE_DEFAULT))
866 if ((ret = calloc(1, SSH_DIGEST_MAX_LENGTH)) == NULL) {
867 r = SSH_ERR_ALLOC_FAIL;
870 if ((r = ssh_digest_memory(dgst_alg, blob, blob_len,
871 ret, SSH_DIGEST_MAX_LENGTH)) != 0)
879 *lenp = ssh_digest_bytes(dgst_alg);
884 freezero(blob, blob_len);
889 fingerprint_b64(const char *alg, u_char *dgst_raw, size_t dgst_raw_len)
892 size_t plen = strlen(alg) + 1;
893 size_t rlen = ((dgst_raw_len + 2) / 3) * 4 + plen + 1;
895 if (dgst_raw_len > 65536 || (ret = calloc(1, rlen)) == NULL)
897 strlcpy(ret, alg, rlen);
898 strlcat(ret, ":", rlen);
899 if (dgst_raw_len == 0)
901 if (b64_ntop(dgst_raw, dgst_raw_len, ret + plen, rlen - plen) == -1) {
905 /* Trim padding characters from end */
906 ret[strcspn(ret, "=")] = '\0';
911 fingerprint_hex(const char *alg, u_char *dgst_raw, size_t dgst_raw_len)
913 char *retval, hex[5];
914 size_t i, rlen = dgst_raw_len * 3 + strlen(alg) + 2;
916 if (dgst_raw_len > 65536 || (retval = calloc(1, rlen)) == NULL)
918 strlcpy(retval, alg, rlen);
919 strlcat(retval, ":", rlen);
920 for (i = 0; i < dgst_raw_len; i++) {
921 snprintf(hex, sizeof(hex), "%s%02x",
922 i > 0 ? ":" : "", dgst_raw[i]);
923 strlcat(retval, hex, rlen);
929 fingerprint_bubblebabble(u_char *dgst_raw, size_t dgst_raw_len)
931 char vowels[] = { 'a', 'e', 'i', 'o', 'u', 'y' };
932 char consonants[] = { 'b', 'c', 'd', 'f', 'g', 'h', 'k', 'l', 'm',
933 'n', 'p', 'r', 's', 't', 'v', 'z', 'x' };
934 u_int i, j = 0, rounds, seed = 1;
937 rounds = (dgst_raw_len / 2) + 1;
938 if ((retval = calloc(rounds, 6)) == NULL)
941 for (i = 0; i < rounds; i++) {
942 u_int idx0, idx1, idx2, idx3, idx4;
943 if ((i + 1 < rounds) || (dgst_raw_len % 2 != 0)) {
944 idx0 = (((((u_int)(dgst_raw[2 * i])) >> 6) & 3) +
946 idx1 = (((u_int)(dgst_raw[2 * i])) >> 2) & 15;
947 idx2 = ((((u_int)(dgst_raw[2 * i])) & 3) +
949 retval[j++] = vowels[idx0];
950 retval[j++] = consonants[idx1];
951 retval[j++] = vowels[idx2];
952 if ((i + 1) < rounds) {
953 idx3 = (((u_int)(dgst_raw[(2 * i) + 1])) >> 4) & 15;
954 idx4 = (((u_int)(dgst_raw[(2 * i) + 1]))) & 15;
955 retval[j++] = consonants[idx3];
957 retval[j++] = consonants[idx4];
959 ((((u_int)(dgst_raw[2 * i])) * 7) +
960 ((u_int)(dgst_raw[(2 * i) + 1])))) % 36;
966 retval[j++] = vowels[idx0];
967 retval[j++] = consonants[idx1];
968 retval[j++] = vowels[idx2];
977 * Draw an ASCII-Art representing the fingerprint so human brain can
978 * profit from its built-in pattern recognition ability.
979 * This technique is called "random art" and can be found in some
980 * scientific publications like this original paper:
982 * "Hash Visualization: a New Technique to improve Real-World Security",
983 * Perrig A. and Song D., 1999, International Workshop on Cryptographic
984 * Techniques and E-Commerce (CrypTEC '99)
985 * sparrow.ece.cmu.edu/~adrian/projects/validation/validation.pdf
987 * The subject came up in a talk by Dan Kaminsky, too.
989 * If you see the picture is different, the key is different.
990 * If the picture looks the same, you still know nothing.
992 * The algorithm used here is a worm crawling over a discrete plane,
993 * leaving a trace (augmenting the field) everywhere it goes.
994 * Movement is taken from dgst_raw 2bit-wise. Bumping into walls
995 * makes the respective movement vector be ignored for this turn.
996 * Graphs are not unambiguous, because circles in graphs can be
997 * walked in either direction.
1001 * Field sizes for the random art. Have to be odd, so the starting point
1002 * can be in the exact middle of the picture, and FLDBASE should be >=8 .
1003 * Else pictures would be too dense, and drawing the frame would
1004 * fail, too, because the key type would not fit in anymore.
1007 #define FLDSIZE_Y (FLDBASE + 1)
1008 #define FLDSIZE_X (FLDBASE * 2 + 1)
1010 fingerprint_randomart(const char *alg, u_char *dgst_raw, size_t dgst_raw_len,
1011 const struct sshkey *k)
1014 * Chars to be used after each other every time the worm
1015 * intersects with itself. Matter of taste.
1017 char *augmentation_string = " .o+=*BOX@%&#/^SE";
1018 char *retval, *p, title[FLDSIZE_X], hash[FLDSIZE_X];
1019 u_char field[FLDSIZE_X][FLDSIZE_Y];
1020 size_t i, tlen, hlen;
1023 size_t len = strlen(augmentation_string) - 1;
1025 if ((retval = calloc((FLDSIZE_X + 3), (FLDSIZE_Y + 2))) == NULL)
1028 /* initialize field */
1029 memset(field, 0, FLDSIZE_X * FLDSIZE_Y * sizeof(char));
1033 /* process raw key */
1034 for (i = 0; i < dgst_raw_len; i++) {
1036 /* each byte conveys four 2-bit move commands */
1037 input = dgst_raw[i];
1038 for (b = 0; b < 4; b++) {
1039 /* evaluate 2 bit, rest is shifted later */
1040 x += (input & 0x1) ? 1 : -1;
1041 y += (input & 0x2) ? 1 : -1;
1043 /* assure we are still in bounds */
1046 x = MINIMUM(x, FLDSIZE_X - 1);
1047 y = MINIMUM(y, FLDSIZE_Y - 1);
1049 /* augment the field */
1050 if (field[x][y] < len - 2)
1056 /* mark starting point and end point*/
1057 field[FLDSIZE_X / 2][FLDSIZE_Y / 2] = len - 1;
1060 /* assemble title */
1061 r = snprintf(title, sizeof(title), "[%s %u]",
1062 sshkey_type(k), sshkey_size(k));
1063 /* If [type size] won't fit, then try [type]; fits "[ED25519-CERT]" */
1064 if (r < 0 || r > (int)sizeof(title))
1065 r = snprintf(title, sizeof(title), "[%s]", sshkey_type(k));
1066 tlen = (r <= 0) ? 0 : strlen(title);
1068 /* assemble hash ID. */
1069 r = snprintf(hash, sizeof(hash), "[%s]", alg);
1070 hlen = (r <= 0) ? 0 : strlen(hash);
1072 /* output upper border */
1075 for (i = 0; i < (FLDSIZE_X - tlen) / 2; i++)
1077 memcpy(p, title, tlen);
1079 for (i += tlen; i < FLDSIZE_X; i++)
1084 /* output content */
1085 for (y = 0; y < FLDSIZE_Y; y++) {
1087 for (x = 0; x < FLDSIZE_X; x++)
1088 *p++ = augmentation_string[MINIMUM(field[x][y], len)];
1093 /* output lower border */
1095 for (i = 0; i < (FLDSIZE_X - hlen) / 2; i++)
1097 memcpy(p, hash, hlen);
1099 for (i += hlen; i < FLDSIZE_X; i++)
1107 sshkey_fingerprint(const struct sshkey *k, int dgst_alg,
1108 enum sshkey_fp_rep dgst_rep)
1110 char *retval = NULL;
1112 size_t dgst_raw_len;
1114 if (sshkey_fingerprint_raw(k, dgst_alg, &dgst_raw, &dgst_raw_len) != 0)
1117 case SSH_FP_DEFAULT:
1118 if (dgst_alg == SSH_DIGEST_MD5) {
1119 retval = fingerprint_hex(ssh_digest_alg_name(dgst_alg),
1120 dgst_raw, dgst_raw_len);
1122 retval = fingerprint_b64(ssh_digest_alg_name(dgst_alg),
1123 dgst_raw, dgst_raw_len);
1127 retval = fingerprint_hex(ssh_digest_alg_name(dgst_alg),
1128 dgst_raw, dgst_raw_len);
1131 retval = fingerprint_b64(ssh_digest_alg_name(dgst_alg),
1132 dgst_raw, dgst_raw_len);
1134 case SSH_FP_BUBBLEBABBLE:
1135 retval = fingerprint_bubblebabble(dgst_raw, dgst_raw_len);
1137 case SSH_FP_RANDOMART:
1138 retval = fingerprint_randomart(ssh_digest_alg_name(dgst_alg),
1139 dgst_raw, dgst_raw_len, k);
1142 freezero(dgst_raw, dgst_raw_len);
1145 freezero(dgst_raw, dgst_raw_len);
1150 peek_type_nid(const char *s, size_t l, int *nid)
1152 const struct sshkey_impl *impl;
1155 for (i = 0; keyimpls[i] != NULL; i++) {
1157 if (impl->name == NULL || strlen(impl->name) != l)
1159 if (memcmp(s, impl->name, l) == 0) {
1161 if (key_type_is_ecdsa_variant(impl->type))
1169 /* XXX this can now be made const char * */
1171 sshkey_read(struct sshkey *ret, char **cpp)
1174 char *cp, *blobcopy;
1176 int r, type, curve_nid = -1;
1177 struct sshbuf *blob;
1180 return SSH_ERR_INVALID_ARGUMENT;
1181 if (ret->type != KEY_UNSPEC && sshkey_impl_from_type(ret->type) == NULL)
1182 return SSH_ERR_INVALID_ARGUMENT;
1186 space = strcspn(cp, " \t");
1187 if (space == strlen(cp))
1188 return SSH_ERR_INVALID_FORMAT;
1189 if ((type = peek_type_nid(cp, space, &curve_nid)) == KEY_UNSPEC)
1190 return SSH_ERR_INVALID_FORMAT;
1192 /* skip whitespace */
1193 for (cp += space; *cp == ' ' || *cp == '\t'; cp++)
1196 return SSH_ERR_INVALID_FORMAT;
1197 if (ret->type != KEY_UNSPEC && ret->type != type)
1198 return SSH_ERR_KEY_TYPE_MISMATCH;
1199 if ((blob = sshbuf_new()) == NULL)
1200 return SSH_ERR_ALLOC_FAIL;
1202 /* find end of keyblob and decode */
1203 space = strcspn(cp, " \t");
1204 if ((blobcopy = strndup(cp, space)) == NULL) {
1206 return SSH_ERR_ALLOC_FAIL;
1208 if ((r = sshbuf_b64tod(blob, blobcopy)) != 0) {
1214 if ((r = sshkey_fromb(blob, &k)) != 0) {
1220 /* skip whitespace and leave cp at start of comment */
1221 for (cp += space; *cp == ' ' || *cp == '\t'; cp++)
1224 /* ensure type of blob matches type at start of line */
1225 if (k->type != type) {
1227 return SSH_ERR_KEY_TYPE_MISMATCH;
1229 if (key_type_is_ecdsa_variant(type) && curve_nid != k->ecdsa_nid) {
1231 return SSH_ERR_EC_CURVE_MISMATCH;
1234 /* Fill in ret from parsed key */
1235 sshkey_free_contents(ret);
1237 freezero(k, sizeof(*k));
1245 sshkey_to_base64(const struct sshkey *key, char **b64p)
1247 int r = SSH_ERR_INTERNAL_ERROR;
1248 struct sshbuf *b = NULL;
1253 if ((b = sshbuf_new()) == NULL)
1254 return SSH_ERR_ALLOC_FAIL;
1255 if ((r = sshkey_putb(key, b)) != 0)
1257 if ((uu = sshbuf_dtob64_string(b, 0)) == NULL) {
1258 r = SSH_ERR_ALLOC_FAIL;
1274 sshkey_format_text(const struct sshkey *key, struct sshbuf *b)
1276 int r = SSH_ERR_INTERNAL_ERROR;
1279 if ((r = sshkey_to_base64(key, &uu)) != 0)
1281 if ((r = sshbuf_putf(b, "%s %s",
1282 sshkey_ssh_name(key), uu)) != 0)
1291 sshkey_write(const struct sshkey *key, FILE *f)
1293 struct sshbuf *b = NULL;
1294 int r = SSH_ERR_INTERNAL_ERROR;
1296 if ((b = sshbuf_new()) == NULL)
1297 return SSH_ERR_ALLOC_FAIL;
1298 if ((r = sshkey_format_text(key, b)) != 0)
1300 if (fwrite(sshbuf_ptr(b), sshbuf_len(b), 1, f) != 1) {
1303 r = SSH_ERR_SYSTEM_ERROR;
1314 sshkey_cert_type(const struct sshkey *k)
1316 switch (k->cert->type) {
1317 case SSH2_CERT_TYPE_USER:
1319 case SSH2_CERT_TYPE_HOST:
1327 sshkey_check_rsa_length(const struct sshkey *k, int min_size)
1330 const BIGNUM *rsa_n;
1333 if (k == NULL || k->rsa == NULL ||
1334 (k->type != KEY_RSA && k->type != KEY_RSA_CERT))
1336 RSA_get0_key(k->rsa, &rsa_n, NULL, NULL);
1337 nbits = BN_num_bits(rsa_n);
1338 if (nbits < SSH_RSA_MINIMUM_MODULUS_SIZE ||
1339 (min_size > 0 && nbits < min_size))
1340 return SSH_ERR_KEY_LENGTH;
1341 #endif /* WITH_OPENSSL */
1346 # ifdef OPENSSL_HAS_ECC
1348 sshkey_ecdsa_key_to_nid(EC_KEY *k)
1352 NID_X9_62_prime256v1,
1354 # ifdef OPENSSL_HAS_NISTP521
1356 # endif /* OPENSSL_HAS_NISTP521 */
1361 const EC_GROUP *g = EC_KEY_get0_group(k);
1364 * The group may be stored in a ASN.1 encoded private key in one of two
1365 * ways: as a "named group", which is reconstituted by ASN.1 object ID
1366 * or explicit group parameters encoded into the key blob. Only the
1367 * "named group" case sets the group NID for us, but we can figure
1368 * it out for the other case by comparing against all the groups that
1371 if ((nid = EC_GROUP_get_curve_name(g)) > 0)
1373 for (i = 0; nids[i] != -1; i++) {
1374 if ((eg = EC_GROUP_new_by_curve_name(nids[i])) == NULL)
1376 if (EC_GROUP_cmp(g, eg, NULL) == 0)
1380 if (nids[i] != -1) {
1381 /* Use the group with the NID attached */
1382 EC_GROUP_set_asn1_flag(eg, OPENSSL_EC_NAMED_CURVE);
1383 if (EC_KEY_set_group(k, eg) != 1) {
1390 # endif /* OPENSSL_HAS_ECC */
1391 #endif /* WITH_OPENSSL */
1394 sshkey_generate(int type, u_int bits, struct sshkey **keyp)
1397 int ret = SSH_ERR_INTERNAL_ERROR;
1398 const struct sshkey_impl *impl;
1400 if (keyp == NULL || sshkey_type_is_cert(type))
1401 return SSH_ERR_INVALID_ARGUMENT;
1403 if ((impl = sshkey_impl_from_type(type)) == NULL)
1404 return SSH_ERR_KEY_TYPE_UNKNOWN;
1405 if (impl->funcs->generate == NULL)
1406 return SSH_ERR_FEATURE_UNSUPPORTED;
1407 if ((k = sshkey_new(KEY_UNSPEC)) == NULL)
1408 return SSH_ERR_ALLOC_FAIL;
1410 if ((ret = impl->funcs->generate(k, bits)) != 0) {
1420 sshkey_cert_copy(const struct sshkey *from_key, struct sshkey *to_key)
1423 const struct sshkey_cert *from;
1424 struct sshkey_cert *to;
1425 int r = SSH_ERR_INTERNAL_ERROR;
1427 if (to_key == NULL || (from = from_key->cert) == NULL)
1428 return SSH_ERR_INVALID_ARGUMENT;
1430 if ((to = cert_new()) == NULL)
1431 return SSH_ERR_ALLOC_FAIL;
1433 if ((r = sshbuf_putb(to->certblob, from->certblob)) != 0 ||
1434 (r = sshbuf_putb(to->critical, from->critical)) != 0 ||
1435 (r = sshbuf_putb(to->extensions, from->extensions)) != 0)
1438 to->serial = from->serial;
1439 to->type = from->type;
1440 if (from->key_id == NULL)
1442 else if ((to->key_id = strdup(from->key_id)) == NULL) {
1443 r = SSH_ERR_ALLOC_FAIL;
1446 to->valid_after = from->valid_after;
1447 to->valid_before = from->valid_before;
1448 if (from->signature_key == NULL)
1449 to->signature_key = NULL;
1450 else if ((r = sshkey_from_private(from->signature_key,
1451 &to->signature_key)) != 0)
1453 if (from->signature_type != NULL &&
1454 (to->signature_type = strdup(from->signature_type)) == NULL) {
1455 r = SSH_ERR_ALLOC_FAIL;
1458 if (from->nprincipals > SSHKEY_CERT_MAX_PRINCIPALS) {
1459 r = SSH_ERR_INVALID_ARGUMENT;
1462 if (from->nprincipals > 0) {
1463 if ((to->principals = calloc(from->nprincipals,
1464 sizeof(*to->principals))) == NULL) {
1465 r = SSH_ERR_ALLOC_FAIL;
1468 for (i = 0; i < from->nprincipals; i++) {
1469 to->principals[i] = strdup(from->principals[i]);
1470 if (to->principals[i] == NULL) {
1471 to->nprincipals = i;
1472 r = SSH_ERR_ALLOC_FAIL;
1477 to->nprincipals = from->nprincipals;
1480 cert_free(to_key->cert);
1490 sshkey_copy_public_sk(const struct sshkey *from, struct sshkey *to)
1492 /* Append security-key application string */
1493 if ((to->sk_application = strdup(from->sk_application)) == NULL)
1494 return SSH_ERR_ALLOC_FAIL;
1499 sshkey_from_private(const struct sshkey *k, struct sshkey **pkp)
1501 struct sshkey *n = NULL;
1502 int r = SSH_ERR_INTERNAL_ERROR;
1503 const struct sshkey_impl *impl;
1506 if ((impl = sshkey_impl_from_key(k)) == NULL)
1507 return SSH_ERR_KEY_TYPE_UNKNOWN;
1508 if ((n = sshkey_new(k->type)) == NULL) {
1509 r = SSH_ERR_ALLOC_FAIL;
1512 if ((r = impl->funcs->copy_public(k, n)) != 0)
1514 if (sshkey_is_cert(k) && (r = sshkey_cert_copy(k, n)) != 0)
1526 sshkey_is_shielded(struct sshkey *k)
1528 return k != NULL && k->shielded_private != NULL;
1532 sshkey_shield_private(struct sshkey *k)
1534 struct sshbuf *prvbuf = NULL;
1535 u_char *prekey = NULL, *enc = NULL, keyiv[SSH_DIGEST_MAX_LENGTH];
1536 struct sshcipher_ctx *cctx = NULL;
1537 const struct sshcipher *cipher;
1538 size_t i, enclen = 0;
1539 struct sshkey *kswap = NULL, tmp;
1540 int r = SSH_ERR_INTERNAL_ERROR;
1543 fprintf(stderr, "%s: entering for %s\n", __func__, sshkey_ssh_name(k));
1545 if ((cipher = cipher_by_name(SSHKEY_SHIELD_CIPHER)) == NULL) {
1546 r = SSH_ERR_INVALID_ARGUMENT;
1549 if (cipher_keylen(cipher) + cipher_ivlen(cipher) >
1550 ssh_digest_bytes(SSHKEY_SHIELD_PREKEY_HASH)) {
1551 r = SSH_ERR_INTERNAL_ERROR;
1555 /* Prepare a random pre-key, and from it an ephemeral key */
1556 if ((prekey = malloc(SSHKEY_SHIELD_PREKEY_LEN)) == NULL) {
1557 r = SSH_ERR_ALLOC_FAIL;
1560 arc4random_buf(prekey, SSHKEY_SHIELD_PREKEY_LEN);
1561 if ((r = ssh_digest_memory(SSHKEY_SHIELD_PREKEY_HASH,
1562 prekey, SSHKEY_SHIELD_PREKEY_LEN,
1563 keyiv, SSH_DIGEST_MAX_LENGTH)) != 0)
1566 fprintf(stderr, "%s: key+iv\n", __func__);
1567 sshbuf_dump_data(keyiv, ssh_digest_bytes(SSHKEY_SHIELD_PREKEY_HASH),
1570 if ((r = cipher_init(&cctx, cipher, keyiv, cipher_keylen(cipher),
1571 keyiv + cipher_keylen(cipher), cipher_ivlen(cipher), 1)) != 0)
1574 /* Serialise and encrypt the private key using the ephemeral key */
1575 if ((prvbuf = sshbuf_new()) == NULL) {
1576 r = SSH_ERR_ALLOC_FAIL;
1579 if (sshkey_is_shielded(k) && (r = sshkey_unshield_private(k)) != 0)
1581 if ((r = sshkey_private_serialize_opt(k, prvbuf,
1582 SSHKEY_SERIALIZE_SHIELD)) != 0)
1584 /* pad to cipher blocksize */
1586 while (sshbuf_len(prvbuf) % cipher_blocksize(cipher)) {
1587 if ((r = sshbuf_put_u8(prvbuf, ++i & 0xff)) != 0)
1591 fprintf(stderr, "%s: serialised\n", __func__);
1592 sshbuf_dump(prvbuf, stderr);
1595 enclen = sshbuf_len(prvbuf);
1596 if ((enc = malloc(enclen)) == NULL) {
1597 r = SSH_ERR_ALLOC_FAIL;
1600 if ((r = cipher_crypt(cctx, 0, enc,
1601 sshbuf_ptr(prvbuf), sshbuf_len(prvbuf), 0, 0)) != 0)
1604 fprintf(stderr, "%s: encrypted\n", __func__);
1605 sshbuf_dump_data(enc, enclen, stderr);
1608 /* Make a scrubbed, public-only copy of our private key argument */
1609 if ((r = sshkey_from_private(k, &kswap)) != 0)
1612 /* Swap the private key out (it will be destroyed below) */
1617 /* Insert the shielded key into our argument */
1618 k->shielded_private = enc;
1619 k->shielded_len = enclen;
1620 k->shield_prekey = prekey;
1621 k->shield_prekey_len = SSHKEY_SHIELD_PREKEY_LEN;
1622 enc = prekey = NULL; /* transferred */
1625 /* preserve key fields that are required for correct operation */
1626 k->sk_flags = kswap->sk_flags;
1632 /* XXX behaviour on error - invalidate original private key? */
1634 explicit_bzero(keyiv, sizeof(keyiv));
1635 explicit_bzero(&tmp, sizeof(tmp));
1636 freezero(enc, enclen);
1637 freezero(prekey, SSHKEY_SHIELD_PREKEY_LEN);
1639 sshbuf_free(prvbuf);
1643 /* Check deterministic padding after private key */
1645 private2_check_padding(struct sshbuf *decrypted)
1652 while (sshbuf_len(decrypted)) {
1653 if ((r = sshbuf_get_u8(decrypted, &pad)) != 0)
1655 if (pad != (++i & 0xff)) {
1656 r = SSH_ERR_INVALID_FORMAT;
1663 explicit_bzero(&pad, sizeof(pad));
1664 explicit_bzero(&i, sizeof(i));
1669 sshkey_unshield_private(struct sshkey *k)
1671 struct sshbuf *prvbuf = NULL;
1672 u_char *cp, keyiv[SSH_DIGEST_MAX_LENGTH];
1673 struct sshcipher_ctx *cctx = NULL;
1674 const struct sshcipher *cipher;
1675 struct sshkey *kswap = NULL, tmp;
1676 int r = SSH_ERR_INTERNAL_ERROR;
1679 fprintf(stderr, "%s: entering for %s\n", __func__, sshkey_ssh_name(k));
1681 if (!sshkey_is_shielded(k))
1682 return 0; /* nothing to do */
1684 if ((cipher = cipher_by_name(SSHKEY_SHIELD_CIPHER)) == NULL) {
1685 r = SSH_ERR_INVALID_ARGUMENT;
1688 if (cipher_keylen(cipher) + cipher_ivlen(cipher) >
1689 ssh_digest_bytes(SSHKEY_SHIELD_PREKEY_HASH)) {
1690 r = SSH_ERR_INTERNAL_ERROR;
1693 /* check size of shielded key blob */
1694 if (k->shielded_len < cipher_blocksize(cipher) ||
1695 (k->shielded_len % cipher_blocksize(cipher)) != 0) {
1696 r = SSH_ERR_INVALID_FORMAT;
1700 /* Calculate the ephemeral key from the prekey */
1701 if ((r = ssh_digest_memory(SSHKEY_SHIELD_PREKEY_HASH,
1702 k->shield_prekey, k->shield_prekey_len,
1703 keyiv, SSH_DIGEST_MAX_LENGTH)) != 0)
1705 if ((r = cipher_init(&cctx, cipher, keyiv, cipher_keylen(cipher),
1706 keyiv + cipher_keylen(cipher), cipher_ivlen(cipher), 0)) != 0)
1709 fprintf(stderr, "%s: key+iv\n", __func__);
1710 sshbuf_dump_data(keyiv, ssh_digest_bytes(SSHKEY_SHIELD_PREKEY_HASH),
1714 /* Decrypt and parse the shielded private key using the ephemeral key */
1715 if ((prvbuf = sshbuf_new()) == NULL) {
1716 r = SSH_ERR_ALLOC_FAIL;
1719 if ((r = sshbuf_reserve(prvbuf, k->shielded_len, &cp)) != 0)
1723 fprintf(stderr, "%s: encrypted\n", __func__);
1724 sshbuf_dump_data(k->shielded_private, k->shielded_len, stderr);
1726 if ((r = cipher_crypt(cctx, 0, cp,
1727 k->shielded_private, k->shielded_len, 0, 0)) != 0)
1730 fprintf(stderr, "%s: serialised\n", __func__);
1731 sshbuf_dump(prvbuf, stderr);
1733 /* Parse private key */
1734 if ((r = sshkey_private_deserialize(prvbuf, &kswap)) != 0)
1737 if ((r = private2_check_padding(prvbuf)) != 0)
1740 /* Swap the parsed key back into place */
1750 explicit_bzero(keyiv, sizeof(keyiv));
1751 explicit_bzero(&tmp, sizeof(tmp));
1753 sshbuf_free(prvbuf);
1758 cert_parse(struct sshbuf *b, struct sshkey *key, struct sshbuf *certbuf)
1760 struct sshbuf *principals = NULL, *crit = NULL;
1761 struct sshbuf *exts = NULL, *ca = NULL;
1763 size_t signed_len = 0, slen = 0, kidlen = 0;
1764 int ret = SSH_ERR_INTERNAL_ERROR;
1766 /* Copy the entire key blob for verification and later serialisation */
1767 if ((ret = sshbuf_putb(key->cert->certblob, certbuf)) != 0)
1770 /* Parse body of certificate up to signature */
1771 if ((ret = sshbuf_get_u64(b, &key->cert->serial)) != 0 ||
1772 (ret = sshbuf_get_u32(b, &key->cert->type)) != 0 ||
1773 (ret = sshbuf_get_cstring(b, &key->cert->key_id, &kidlen)) != 0 ||
1774 (ret = sshbuf_froms(b, &principals)) != 0 ||
1775 (ret = sshbuf_get_u64(b, &key->cert->valid_after)) != 0 ||
1776 (ret = sshbuf_get_u64(b, &key->cert->valid_before)) != 0 ||
1777 (ret = sshbuf_froms(b, &crit)) != 0 ||
1778 (ret = sshbuf_froms(b, &exts)) != 0 ||
1779 (ret = sshbuf_get_string_direct(b, NULL, NULL)) != 0 ||
1780 (ret = sshbuf_froms(b, &ca)) != 0) {
1781 /* XXX debug print error for ret */
1782 ret = SSH_ERR_INVALID_FORMAT;
1786 /* Signature is left in the buffer so we can calculate this length */
1787 signed_len = sshbuf_len(key->cert->certblob) - sshbuf_len(b);
1789 if ((ret = sshbuf_get_string(b, &sig, &slen)) != 0) {
1790 ret = SSH_ERR_INVALID_FORMAT;
1794 if (key->cert->type != SSH2_CERT_TYPE_USER &&
1795 key->cert->type != SSH2_CERT_TYPE_HOST) {
1796 ret = SSH_ERR_KEY_CERT_UNKNOWN_TYPE;
1800 /* Parse principals section */
1801 while (sshbuf_len(principals) > 0) {
1802 char *principal = NULL;
1803 char **oprincipals = NULL;
1805 if (key->cert->nprincipals >= SSHKEY_CERT_MAX_PRINCIPALS) {
1806 ret = SSH_ERR_INVALID_FORMAT;
1809 if ((ret = sshbuf_get_cstring(principals, &principal,
1811 ret = SSH_ERR_INVALID_FORMAT;
1814 oprincipals = key->cert->principals;
1815 key->cert->principals = recallocarray(key->cert->principals,
1816 key->cert->nprincipals, key->cert->nprincipals + 1,
1817 sizeof(*key->cert->principals));
1818 if (key->cert->principals == NULL) {
1820 key->cert->principals = oprincipals;
1821 ret = SSH_ERR_ALLOC_FAIL;
1824 key->cert->principals[key->cert->nprincipals++] = principal;
1828 * Stash a copies of the critical options and extensions sections
1831 if ((ret = sshbuf_putb(key->cert->critical, crit)) != 0 ||
1833 (ret = sshbuf_putb(key->cert->extensions, exts)) != 0))
1837 * Validate critical options and extensions sections format.
1839 while (sshbuf_len(crit) != 0) {
1840 if ((ret = sshbuf_get_string_direct(crit, NULL, NULL)) != 0 ||
1841 (ret = sshbuf_get_string_direct(crit, NULL, NULL)) != 0) {
1842 sshbuf_reset(key->cert->critical);
1843 ret = SSH_ERR_INVALID_FORMAT;
1847 while (exts != NULL && sshbuf_len(exts) != 0) {
1848 if ((ret = sshbuf_get_string_direct(exts, NULL, NULL)) != 0 ||
1849 (ret = sshbuf_get_string_direct(exts, NULL, NULL)) != 0) {
1850 sshbuf_reset(key->cert->extensions);
1851 ret = SSH_ERR_INVALID_FORMAT;
1856 /* Parse CA key and check signature */
1857 if (sshkey_from_blob_internal(ca, &key->cert->signature_key, 0) != 0) {
1858 ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
1861 if (!sshkey_type_is_valid_ca(key->cert->signature_key->type)) {
1862 ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
1865 if ((ret = sshkey_verify(key->cert->signature_key, sig, slen,
1866 sshbuf_ptr(key->cert->certblob), signed_len, NULL, 0, NULL)) != 0)
1868 if ((ret = sshkey_get_sigtype(sig, slen,
1869 &key->cert->signature_type)) != 0)
1878 sshbuf_free(principals);
1884 sshkey_deserialize_sk(struct sshbuf *b, struct sshkey *key)
1886 /* Parse additional security-key application string */
1887 if (sshbuf_get_cstring(b, &key->sk_application, NULL) != 0)
1888 return SSH_ERR_INVALID_FORMAT;
1893 sshkey_from_blob_internal(struct sshbuf *b, struct sshkey **keyp,
1896 int type, ret = SSH_ERR_INTERNAL_ERROR;
1898 struct sshkey *key = NULL;
1899 struct sshbuf *copy;
1900 const struct sshkey_impl *impl;
1902 #ifdef DEBUG_PK /* XXX */
1903 sshbuf_dump(b, stderr);
1907 if ((copy = sshbuf_fromb(b)) == NULL) {
1908 ret = SSH_ERR_ALLOC_FAIL;
1911 if (sshbuf_get_cstring(b, &ktype, NULL) != 0) {
1912 ret = SSH_ERR_INVALID_FORMAT;
1916 type = sshkey_type_from_name(ktype);
1917 if (!allow_cert && sshkey_type_is_cert(type)) {
1918 ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
1921 if ((impl = sshkey_impl_from_type(type)) == NULL) {
1922 ret = SSH_ERR_KEY_TYPE_UNKNOWN;
1925 if ((key = sshkey_new(type)) == NULL) {
1926 ret = SSH_ERR_ALLOC_FAIL;
1929 if (sshkey_type_is_cert(type)) {
1930 /* Skip nonce that preceeds all certificates */
1931 if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
1932 ret = SSH_ERR_INVALID_FORMAT;
1936 if ((ret = impl->funcs->deserialize_public(ktype, b, key)) != 0)
1939 /* Parse certificate potion */
1940 if (sshkey_is_cert(key) && (ret = cert_parse(b, key, copy)) != 0)
1943 if (key != NULL && sshbuf_len(b) != 0) {
1944 ret = SSH_ERR_INVALID_FORMAT;
1960 sshkey_from_blob(const u_char *blob, size_t blen, struct sshkey **keyp)
1965 if ((b = sshbuf_from(blob, blen)) == NULL)
1966 return SSH_ERR_ALLOC_FAIL;
1967 r = sshkey_from_blob_internal(b, keyp, 1);
1973 sshkey_fromb(struct sshbuf *b, struct sshkey **keyp)
1975 return sshkey_from_blob_internal(b, keyp, 1);
1979 sshkey_froms(struct sshbuf *buf, struct sshkey **keyp)
1984 if ((r = sshbuf_froms(buf, &b)) != 0)
1986 r = sshkey_from_blob_internal(b, keyp, 1);
1992 sshkey_get_sigtype(const u_char *sig, size_t siglen, char **sigtypep)
1995 struct sshbuf *b = NULL;
1996 char *sigtype = NULL;
1998 if (sigtypep != NULL)
2000 if ((b = sshbuf_from(sig, siglen)) == NULL)
2001 return SSH_ERR_ALLOC_FAIL;
2002 if ((r = sshbuf_get_cstring(b, &sigtype, NULL)) != 0)
2005 if (sigtypep != NULL) {
2006 *sigtypep = sigtype;
2018 * Checks whether a certificate's signature type is allowed.
2019 * Returns 0 (success) if the certificate signature type appears in the
2020 * "allowed" pattern-list, or the key is not a certificate to begin with.
2021 * Otherwise returns a ssherr.h code.
2024 sshkey_check_cert_sigtype(const struct sshkey *key, const char *allowed)
2026 if (key == NULL || allowed == NULL)
2027 return SSH_ERR_INVALID_ARGUMENT;
2028 if (!sshkey_type_is_cert(key->type))
2030 if (key->cert == NULL || key->cert->signature_type == NULL)
2031 return SSH_ERR_INVALID_ARGUMENT;
2032 if (match_pattern_list(key->cert->signature_type, allowed, 0) != 1)
2033 return SSH_ERR_SIGN_ALG_UNSUPPORTED;
2038 * Returns the expected signature algorithm for a given public key algorithm.
2041 sshkey_sigalg_by_name(const char *name)
2043 const struct sshkey_impl *impl;
2046 for (i = 0; keyimpls[i] != NULL; i++) {
2048 if (strcmp(impl->name, name) != 0)
2050 if (impl->sigalg != NULL)
2051 return impl->sigalg;
2054 return sshkey_ssh_name_from_type_nid(
2055 sshkey_type_plain(impl->type), impl->nid);
2061 * Verifies that the signature algorithm appearing inside the signature blob
2062 * matches that which was requested.
2065 sshkey_check_sigtype(const u_char *sig, size_t siglen,
2066 const char *requested_alg)
2068 const char *expected_alg;
2069 char *sigtype = NULL;
2072 if (requested_alg == NULL)
2074 if ((expected_alg = sshkey_sigalg_by_name(requested_alg)) == NULL)
2075 return SSH_ERR_INVALID_ARGUMENT;
2076 if ((r = sshkey_get_sigtype(sig, siglen, &sigtype)) != 0)
2078 r = strcmp(expected_alg, sigtype) == 0;
2080 return r ? 0 : SSH_ERR_SIGN_ALG_UNSUPPORTED;
2084 sshkey_sign(struct sshkey *key,
2085 u_char **sigp, size_t *lenp,
2086 const u_char *data, size_t datalen,
2087 const char *alg, const char *sk_provider, const char *sk_pin, u_int compat)
2089 int was_shielded = sshkey_is_shielded(key);
2090 int r2, r = SSH_ERR_INTERNAL_ERROR;
2091 const struct sshkey_impl *impl;
2097 if (datalen > SSH_KEY_MAX_SIGN_DATA_SIZE)
2098 return SSH_ERR_INVALID_ARGUMENT;
2099 if ((impl = sshkey_impl_from_key(key)) == NULL)
2100 return SSH_ERR_KEY_TYPE_UNKNOWN;
2101 if ((r = sshkey_unshield_private(key)) != 0)
2103 if (sshkey_is_sk(key)) {
2104 r = sshsk_sign(sk_provider, key, sigp, lenp, data,
2105 datalen, compat, sk_pin);
2107 if (impl->funcs->sign == NULL)
2108 r = SSH_ERR_SIGN_ALG_UNSUPPORTED;
2110 r = impl->funcs->sign(key, sigp, lenp, data, datalen,
2111 alg, sk_provider, sk_pin, compat);
2114 if (was_shielded && (r2 = sshkey_shield_private(key)) != 0)
2120 * ssh_key_verify returns 0 for a correct signature and < 0 on error.
2121 * If "alg" specified, then the signature must use that algorithm.
2124 sshkey_verify(const struct sshkey *key,
2125 const u_char *sig, size_t siglen,
2126 const u_char *data, size_t dlen, const char *alg, u_int compat,
2127 struct sshkey_sig_details **detailsp)
2129 const struct sshkey_impl *impl;
2131 if (detailsp != NULL)
2133 if (siglen == 0 || dlen > SSH_KEY_MAX_SIGN_DATA_SIZE)
2134 return SSH_ERR_INVALID_ARGUMENT;
2135 if ((impl = sshkey_impl_from_key(key)) == NULL)
2136 return SSH_ERR_KEY_TYPE_UNKNOWN;
2137 return impl->funcs->verify(key, sig, siglen, data, dlen,
2138 alg, compat, detailsp);
2141 /* Convert a plain key to their _CERT equivalent */
2143 sshkey_to_certified(struct sshkey *k)
2147 if ((newtype = sshkey_type_certified(k->type)) == -1)
2148 return SSH_ERR_INVALID_ARGUMENT;
2149 if ((k->cert = cert_new()) == NULL)
2150 return SSH_ERR_ALLOC_FAIL;
2155 /* Convert a certificate to its raw key equivalent */
2157 sshkey_drop_cert(struct sshkey *k)
2159 if (!sshkey_type_is_cert(k->type))
2160 return SSH_ERR_KEY_TYPE_UNKNOWN;
2163 k->type = sshkey_type_plain(k->type);
2167 /* Sign a certified key, (re-)generating the signed certblob. */
2169 sshkey_certify_custom(struct sshkey *k, struct sshkey *ca, const char *alg,
2170 const char *sk_provider, const char *sk_pin,
2171 sshkey_certify_signer *signer, void *signer_ctx)
2173 const struct sshkey_impl *impl;
2174 struct sshbuf *principals = NULL;
2175 u_char *ca_blob = NULL, *sig_blob = NULL, nonce[32];
2176 size_t i, ca_len, sig_len;
2177 int ret = SSH_ERR_INTERNAL_ERROR;
2178 struct sshbuf *cert = NULL;
2179 char *sigtype = NULL;
2181 if (k == NULL || k->cert == NULL ||
2182 k->cert->certblob == NULL || ca == NULL)
2183 return SSH_ERR_INVALID_ARGUMENT;
2184 if (!sshkey_is_cert(k))
2185 return SSH_ERR_KEY_TYPE_UNKNOWN;
2186 if (!sshkey_type_is_valid_ca(ca->type))
2187 return SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
2188 if ((impl = sshkey_impl_from_key(k)) == NULL)
2189 return SSH_ERR_INTERNAL_ERROR;
2192 * If no alg specified as argument but a signature_type was set,
2193 * then prefer that. If both were specified, then they must match.
2196 alg = k->cert->signature_type;
2197 else if (k->cert->signature_type != NULL &&
2198 strcmp(alg, k->cert->signature_type) != 0)
2199 return SSH_ERR_INVALID_ARGUMENT;
2202 * If no signing algorithm or signature_type was specified and we're
2203 * using a RSA key, then default to a good signature algorithm.
2205 if (alg == NULL && ca->type == KEY_RSA)
2206 alg = "rsa-sha2-512";
2208 if ((ret = sshkey_to_blob(ca, &ca_blob, &ca_len)) != 0)
2209 return SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
2211 cert = k->cert->certblob; /* for readability */
2213 if ((ret = sshbuf_put_cstring(cert, sshkey_ssh_name(k))) != 0)
2216 /* -v01 certs put nonce first */
2217 arc4random_buf(&nonce, sizeof(nonce));
2218 if ((ret = sshbuf_put_string(cert, nonce, sizeof(nonce))) != 0)
2221 /* Public key next */
2222 if ((ret = impl->funcs->serialize_public(k, cert,
2223 SSHKEY_SERIALIZE_DEFAULT)) != 0)
2226 /* Then remaining cert fields */
2227 if ((ret = sshbuf_put_u64(cert, k->cert->serial)) != 0 ||
2228 (ret = sshbuf_put_u32(cert, k->cert->type)) != 0 ||
2229 (ret = sshbuf_put_cstring(cert, k->cert->key_id)) != 0)
2232 if ((principals = sshbuf_new()) == NULL) {
2233 ret = SSH_ERR_ALLOC_FAIL;
2236 for (i = 0; i < k->cert->nprincipals; i++) {
2237 if ((ret = sshbuf_put_cstring(principals,
2238 k->cert->principals[i])) != 0)
2241 if ((ret = sshbuf_put_stringb(cert, principals)) != 0 ||
2242 (ret = sshbuf_put_u64(cert, k->cert->valid_after)) != 0 ||
2243 (ret = sshbuf_put_u64(cert, k->cert->valid_before)) != 0 ||
2244 (ret = sshbuf_put_stringb(cert, k->cert->critical)) != 0 ||
2245 (ret = sshbuf_put_stringb(cert, k->cert->extensions)) != 0 ||
2246 (ret = sshbuf_put_string(cert, NULL, 0)) != 0 || /* Reserved */
2247 (ret = sshbuf_put_string(cert, ca_blob, ca_len)) != 0)
2250 /* Sign the whole mess */
2251 if ((ret = signer(ca, &sig_blob, &sig_len, sshbuf_ptr(cert),
2252 sshbuf_len(cert), alg, sk_provider, sk_pin, 0, signer_ctx)) != 0)
2254 /* Check and update signature_type against what was actually used */
2255 if ((ret = sshkey_get_sigtype(sig_blob, sig_len, &sigtype)) != 0)
2257 if (alg != NULL && strcmp(alg, sigtype) != 0) {
2258 ret = SSH_ERR_SIGN_ALG_UNSUPPORTED;
2261 if (k->cert->signature_type == NULL) {
2262 k->cert->signature_type = sigtype;
2265 /* Append signature and we are done */
2266 if ((ret = sshbuf_put_string(cert, sig_blob, sig_len)) != 0)
2275 sshbuf_free(principals);
2280 default_key_sign(struct sshkey *key, u_char **sigp, size_t *lenp,
2281 const u_char *data, size_t datalen,
2282 const char *alg, const char *sk_provider, const char *sk_pin,
2283 u_int compat, void *ctx)
2286 return SSH_ERR_INVALID_ARGUMENT;
2287 return sshkey_sign(key, sigp, lenp, data, datalen, alg,
2288 sk_provider, sk_pin, compat);
2292 sshkey_certify(struct sshkey *k, struct sshkey *ca, const char *alg,
2293 const char *sk_provider, const char *sk_pin)
2295 return sshkey_certify_custom(k, ca, alg, sk_provider, sk_pin,
2296 default_key_sign, NULL);
2300 sshkey_cert_check_authority(const struct sshkey *k,
2301 int want_host, int require_principal, int wildcard_pattern,
2302 uint64_t verify_time, const char *name, const char **reason)
2304 u_int i, principal_matches;
2307 return SSH_ERR_INVALID_ARGUMENT;
2308 if (!sshkey_is_cert(k)) {
2309 *reason = "Key is not a certificate";
2310 return SSH_ERR_KEY_CERT_INVALID;
2313 if (k->cert->type != SSH2_CERT_TYPE_HOST) {
2314 *reason = "Certificate invalid: not a host certificate";
2315 return SSH_ERR_KEY_CERT_INVALID;
2318 if (k->cert->type != SSH2_CERT_TYPE_USER) {
2319 *reason = "Certificate invalid: not a user certificate";
2320 return SSH_ERR_KEY_CERT_INVALID;
2323 if (verify_time < k->cert->valid_after) {
2324 *reason = "Certificate invalid: not yet valid";
2325 return SSH_ERR_KEY_CERT_INVALID;
2327 if (verify_time >= k->cert->valid_before) {
2328 *reason = "Certificate invalid: expired";
2329 return SSH_ERR_KEY_CERT_INVALID;
2331 if (k->cert->nprincipals == 0) {
2332 if (require_principal) {
2333 *reason = "Certificate lacks principal list";
2334 return SSH_ERR_KEY_CERT_INVALID;
2336 } else if (name != NULL) {
2337 principal_matches = 0;
2338 for (i = 0; i < k->cert->nprincipals; i++) {
2339 if (wildcard_pattern) {
2340 if (match_pattern(k->cert->principals[i],
2342 principal_matches = 1;
2345 } else if (strcmp(name, k->cert->principals[i]) == 0) {
2346 principal_matches = 1;
2350 if (!principal_matches) {
2351 *reason = "Certificate invalid: name is not a listed "
2353 return SSH_ERR_KEY_CERT_INVALID;
2360 sshkey_cert_check_authority_now(const struct sshkey *k,
2361 int want_host, int require_principal, int wildcard_pattern,
2362 const char *name, const char **reason)
2366 if ((now = time(NULL)) < 0) {
2367 /* yikes - system clock before epoch! */
2368 *reason = "Certificate invalid: not yet valid";
2369 return SSH_ERR_KEY_CERT_INVALID;
2371 return sshkey_cert_check_authority(k, want_host, require_principal,
2372 wildcard_pattern, (uint64_t)now, name, reason);
2376 sshkey_cert_check_host(const struct sshkey *key, const char *host,
2377 int wildcard_principals, const char *ca_sign_algorithms,
2378 const char **reason)
2382 if ((r = sshkey_cert_check_authority_now(key, 1, 0, wildcard_principals,
2383 host, reason)) != 0)
2385 if (sshbuf_len(key->cert->critical) != 0) {
2386 *reason = "Certificate contains unsupported critical options";
2387 return SSH_ERR_KEY_CERT_INVALID;
2389 if (ca_sign_algorithms != NULL &&
2390 (r = sshkey_check_cert_sigtype(key, ca_sign_algorithms)) != 0) {
2391 *reason = "Certificate signed with disallowed algorithm";
2392 return SSH_ERR_KEY_CERT_INVALID;
2398 sshkey_format_cert_validity(const struct sshkey_cert *cert, char *s, size_t l)
2400 char from[32], to[32], ret[128];
2403 if (cert->valid_after == 0 &&
2404 cert->valid_before == 0xffffffffffffffffULL)
2405 return strlcpy(s, "forever", l);
2407 if (cert->valid_after != 0)
2408 format_absolute_time(cert->valid_after, from, sizeof(from));
2409 if (cert->valid_before != 0xffffffffffffffffULL)
2410 format_absolute_time(cert->valid_before, to, sizeof(to));
2412 if (cert->valid_after == 0)
2413 snprintf(ret, sizeof(ret), "before %s", to);
2414 else if (cert->valid_before == 0xffffffffffffffffULL)
2415 snprintf(ret, sizeof(ret), "after %s", from);
2417 snprintf(ret, sizeof(ret), "from %s to %s", from, to);
2419 return strlcpy(s, ret, l);
2422 /* Common serialization for FIDO private keys */
2424 sshkey_serialize_private_sk(const struct sshkey *key, struct sshbuf *b)
2428 if ((r = sshbuf_put_cstring(b, key->sk_application)) != 0 ||
2429 (r = sshbuf_put_u8(b, key->sk_flags)) != 0 ||
2430 (r = sshbuf_put_stringb(b, key->sk_key_handle)) != 0 ||
2431 (r = sshbuf_put_stringb(b, key->sk_reserved)) != 0)
2438 sshkey_private_serialize_opt(struct sshkey *key, struct sshbuf *buf,
2439 enum sshkey_serialize_rep opts)
2441 int r = SSH_ERR_INTERNAL_ERROR;
2442 int was_shielded = sshkey_is_shielded(key);
2443 struct sshbuf *b = NULL;
2444 const struct sshkey_impl *impl;
2446 if ((impl = sshkey_impl_from_key(key)) == NULL)
2447 return SSH_ERR_INTERNAL_ERROR;
2448 if ((r = sshkey_unshield_private(key)) != 0)
2450 if ((b = sshbuf_new()) == NULL)
2451 return SSH_ERR_ALLOC_FAIL;
2452 if ((r = sshbuf_put_cstring(b, sshkey_ssh_name(key))) != 0)
2454 if (sshkey_is_cert(key)) {
2455 if (key->cert == NULL ||
2456 sshbuf_len(key->cert->certblob) == 0) {
2457 r = SSH_ERR_INVALID_ARGUMENT;
2460 if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0)
2463 if ((r = impl->funcs->serialize_private(key, b, opts)) != 0)
2467 * success (but we still need to append the output to buf after
2468 * possibly re-shielding the private key)
2473 r = sshkey_shield_private(key);
2475 r = sshbuf_putb(buf, b);
2482 sshkey_private_serialize(struct sshkey *key, struct sshbuf *b)
2484 return sshkey_private_serialize_opt(key, b,
2485 SSHKEY_SERIALIZE_DEFAULT);
2488 /* Shared deserialization of FIDO private key components */
2490 sshkey_private_deserialize_sk(struct sshbuf *buf, struct sshkey *k)
2494 if ((k->sk_key_handle = sshbuf_new()) == NULL ||
2495 (k->sk_reserved = sshbuf_new()) == NULL)
2496 return SSH_ERR_ALLOC_FAIL;
2497 if ((r = sshbuf_get_cstring(buf, &k->sk_application, NULL)) != 0 ||
2498 (r = sshbuf_get_u8(buf, &k->sk_flags)) != 0 ||
2499 (r = sshbuf_get_stringb(buf, k->sk_key_handle)) != 0 ||
2500 (r = sshbuf_get_stringb(buf, k->sk_reserved)) != 0)
2507 sshkey_private_deserialize(struct sshbuf *buf, struct sshkey **kp)
2509 const struct sshkey_impl *impl;
2511 char *expect_sk_application = NULL;
2512 u_char *expect_ed25519_pk = NULL;
2513 struct sshkey *k = NULL;
2514 int type, r = SSH_ERR_INTERNAL_ERROR;
2518 if ((r = sshbuf_get_cstring(buf, &tname, NULL)) != 0)
2520 type = sshkey_type_from_name(tname);
2521 if (sshkey_type_is_cert(type)) {
2523 * Certificate key private keys begin with the certificate
2524 * itself. Make sure this matches the type of the enclosing
2527 if ((r = sshkey_froms(buf, &k)) != 0)
2529 if (k->type != type) {
2530 r = SSH_ERR_KEY_CERT_MISMATCH;
2533 /* For ECDSA keys, the group must match too */
2534 if (k->type == KEY_ECDSA &&
2535 k->ecdsa_nid != sshkey_ecdsa_nid_from_name(tname)) {
2536 r = SSH_ERR_KEY_CERT_MISMATCH;
2540 * Several fields are redundant between certificate and
2541 * private key body, we require these to match.
2543 expect_sk_application = k->sk_application;
2544 expect_ed25519_pk = k->ed25519_pk;
2545 k->sk_application = NULL;
2546 k->ed25519_pk = NULL;
2547 /* XXX xmss too or refactor */
2549 if ((k = sshkey_new(type)) == NULL) {
2550 r = SSH_ERR_ALLOC_FAIL;
2554 if ((impl = sshkey_impl_from_type(type)) == NULL) {
2555 r = SSH_ERR_INTERNAL_ERROR;
2558 if ((r = impl->funcs->deserialize_private(tname, buf, k)) != 0)
2561 /* XXX xmss too or refactor */
2562 if ((expect_sk_application != NULL && (k->sk_application == NULL ||
2563 strcmp(expect_sk_application, k->sk_application) != 0)) ||
2564 (expect_ed25519_pk != NULL && (k->ed25519_pk == NULL ||
2565 memcmp(expect_ed25519_pk, k->ed25519_pk, ED25519_PK_SZ) != 0))) {
2566 r = SSH_ERR_KEY_CERT_MISMATCH;
2578 free(expect_sk_application);
2579 free(expect_ed25519_pk);
2583 #if defined(WITH_OPENSSL) && defined(OPENSSL_HAS_ECC)
2585 sshkey_ec_validate_public(const EC_GROUP *group, const EC_POINT *public)
2587 EC_POINT *nq = NULL;
2588 BIGNUM *order = NULL, *x = NULL, *y = NULL, *tmp = NULL;
2589 int ret = SSH_ERR_KEY_INVALID_EC_VALUE;
2592 * NB. This assumes OpenSSL has already verified that the public
2593 * point lies on the curve. This is done by EC_POINT_oct2point()
2594 * implicitly calling EC_POINT_is_on_curve(). If this code is ever
2595 * reachable with public points not unmarshalled using
2596 * EC_POINT_oct2point then the caller will need to explicitly check.
2600 * We shouldn't ever hit this case because bignum_get_ecpoint()
2601 * refuses to load GF2m points.
2603 if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) !=
2604 NID_X9_62_prime_field)
2608 if (EC_POINT_is_at_infinity(group, public))
2611 if ((x = BN_new()) == NULL ||
2612 (y = BN_new()) == NULL ||
2613 (order = BN_new()) == NULL ||
2614 (tmp = BN_new()) == NULL) {
2615 ret = SSH_ERR_ALLOC_FAIL;
2619 /* log2(x) > log2(order)/2, log2(y) > log2(order)/2 */
2620 if (EC_GROUP_get_order(group, order, NULL) != 1 ||
2621 EC_POINT_get_affine_coordinates_GFp(group, public,
2623 ret = SSH_ERR_LIBCRYPTO_ERROR;
2626 if (BN_num_bits(x) <= BN_num_bits(order) / 2 ||
2627 BN_num_bits(y) <= BN_num_bits(order) / 2)
2630 /* nQ == infinity (n == order of subgroup) */
2631 if ((nq = EC_POINT_new(group)) == NULL) {
2632 ret = SSH_ERR_ALLOC_FAIL;
2635 if (EC_POINT_mul(group, nq, NULL, public, order, NULL) != 1) {
2636 ret = SSH_ERR_LIBCRYPTO_ERROR;
2639 if (EC_POINT_is_at_infinity(group, nq) != 1)
2642 /* x < order - 1, y < order - 1 */
2643 if (!BN_sub(tmp, order, BN_value_one())) {
2644 ret = SSH_ERR_LIBCRYPTO_ERROR;
2647 if (BN_cmp(x, tmp) >= 0 || BN_cmp(y, tmp) >= 0)
2653 BN_clear_free(order);
2660 sshkey_ec_validate_private(const EC_KEY *key)
2662 BIGNUM *order = NULL, *tmp = NULL;
2663 int ret = SSH_ERR_KEY_INVALID_EC_VALUE;
2665 if ((order = BN_new()) == NULL || (tmp = BN_new()) == NULL) {
2666 ret = SSH_ERR_ALLOC_FAIL;
2670 /* log2(private) > log2(order)/2 */
2671 if (EC_GROUP_get_order(EC_KEY_get0_group(key), order, NULL) != 1) {
2672 ret = SSH_ERR_LIBCRYPTO_ERROR;
2675 if (BN_num_bits(EC_KEY_get0_private_key(key)) <=
2676 BN_num_bits(order) / 2)
2679 /* private < order - 1 */
2680 if (!BN_sub(tmp, order, BN_value_one())) {
2681 ret = SSH_ERR_LIBCRYPTO_ERROR;
2684 if (BN_cmp(EC_KEY_get0_private_key(key), tmp) >= 0)
2688 BN_clear_free(order);
2694 sshkey_dump_ec_point(const EC_GROUP *group, const EC_POINT *point)
2696 BIGNUM *x = NULL, *y = NULL;
2698 if (point == NULL) {
2699 fputs("point=(NULL)\n", stderr);
2702 if ((x = BN_new()) == NULL || (y = BN_new()) == NULL) {
2703 fprintf(stderr, "%s: BN_new failed\n", __func__);
2706 if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) !=
2707 NID_X9_62_prime_field) {
2708 fprintf(stderr, "%s: group is not a prime field\n", __func__);
2711 if (EC_POINT_get_affine_coordinates_GFp(group, point,
2713 fprintf(stderr, "%s: EC_POINT_get_affine_coordinates_GFp\n",
2717 fputs("x=", stderr);
2718 BN_print_fp(stderr, x);
2719 fputs("\ny=", stderr);
2720 BN_print_fp(stderr, y);
2721 fputs("\n", stderr);
2728 sshkey_dump_ec_key(const EC_KEY *key)
2730 const BIGNUM *exponent;
2732 sshkey_dump_ec_point(EC_KEY_get0_group(key),
2733 EC_KEY_get0_public_key(key));
2734 fputs("exponent=", stderr);
2735 if ((exponent = EC_KEY_get0_private_key(key)) == NULL)
2736 fputs("(NULL)", stderr);
2738 BN_print_fp(stderr, EC_KEY_get0_private_key(key));
2739 fputs("\n", stderr);
2741 #endif /* WITH_OPENSSL && OPENSSL_HAS_ECC */
2744 sshkey_private_to_blob2(struct sshkey *prv, struct sshbuf *blob,
2745 const char *passphrase, const char *comment, const char *ciphername,
2748 u_char *cp, *key = NULL, *pubkeyblob = NULL;
2749 u_char salt[SALT_LEN];
2750 size_t i, pubkeylen, keylen, ivlen, blocksize, authlen;
2752 int r = SSH_ERR_INTERNAL_ERROR;
2753 struct sshcipher_ctx *ciphercontext = NULL;
2754 const struct sshcipher *cipher;
2755 const char *kdfname = KDFNAME;
2756 struct sshbuf *encoded = NULL, *encrypted = NULL, *kdf = NULL;
2759 rounds = DEFAULT_ROUNDS;
2760 if (passphrase == NULL || !strlen(passphrase)) {
2761 ciphername = "none";
2763 } else if (ciphername == NULL)
2764 ciphername = DEFAULT_CIPHERNAME;
2765 if ((cipher = cipher_by_name(ciphername)) == NULL) {
2766 r = SSH_ERR_INVALID_ARGUMENT;
2770 if ((kdf = sshbuf_new()) == NULL ||
2771 (encoded = sshbuf_new()) == NULL ||
2772 (encrypted = sshbuf_new()) == NULL) {
2773 r = SSH_ERR_ALLOC_FAIL;
2776 blocksize = cipher_blocksize(cipher);
2777 keylen = cipher_keylen(cipher);
2778 ivlen = cipher_ivlen(cipher);
2779 authlen = cipher_authlen(cipher);
2780 if ((key = calloc(1, keylen + ivlen)) == NULL) {
2781 r = SSH_ERR_ALLOC_FAIL;
2784 if (strcmp(kdfname, "bcrypt") == 0) {
2785 arc4random_buf(salt, SALT_LEN);
2786 if (bcrypt_pbkdf(passphrase, strlen(passphrase),
2787 salt, SALT_LEN, key, keylen + ivlen, rounds) < 0) {
2788 r = SSH_ERR_INVALID_ARGUMENT;
2791 if ((r = sshbuf_put_string(kdf, salt, SALT_LEN)) != 0 ||
2792 (r = sshbuf_put_u32(kdf, rounds)) != 0)
2794 } else if (strcmp(kdfname, "none") != 0) {
2795 /* Unsupported KDF type */
2796 r = SSH_ERR_KEY_UNKNOWN_CIPHER;
2799 if ((r = cipher_init(&ciphercontext, cipher, key, keylen,
2800 key + keylen, ivlen, 1)) != 0)
2803 if ((r = sshbuf_put(encoded, AUTH_MAGIC, sizeof(AUTH_MAGIC))) != 0 ||
2804 (r = sshbuf_put_cstring(encoded, ciphername)) != 0 ||
2805 (r = sshbuf_put_cstring(encoded, kdfname)) != 0 ||
2806 (r = sshbuf_put_stringb(encoded, kdf)) != 0 ||
2807 (r = sshbuf_put_u32(encoded, 1)) != 0 || /* number of keys */
2808 (r = sshkey_to_blob(prv, &pubkeyblob, &pubkeylen)) != 0 ||
2809 (r = sshbuf_put_string(encoded, pubkeyblob, pubkeylen)) != 0)
2812 /* set up the buffer that will be encrypted */
2814 /* Random check bytes */
2815 check = arc4random();
2816 if ((r = sshbuf_put_u32(encrypted, check)) != 0 ||
2817 (r = sshbuf_put_u32(encrypted, check)) != 0)
2820 /* append private key and comment*/
2821 if ((r = sshkey_private_serialize_opt(prv, encrypted,
2822 SSHKEY_SERIALIZE_FULL)) != 0 ||
2823 (r = sshbuf_put_cstring(encrypted, comment)) != 0)
2828 while (sshbuf_len(encrypted) % blocksize) {
2829 if ((r = sshbuf_put_u8(encrypted, ++i & 0xff)) != 0)
2833 /* length in destination buffer */
2834 if ((r = sshbuf_put_u32(encoded, sshbuf_len(encrypted))) != 0)
2838 if ((r = sshbuf_reserve(encoded,
2839 sshbuf_len(encrypted) + authlen, &cp)) != 0)
2841 if ((r = cipher_crypt(ciphercontext, 0, cp,
2842 sshbuf_ptr(encrypted), sshbuf_len(encrypted), 0, authlen)) != 0)
2847 /* assemble uuencoded key */
2848 if ((r = sshbuf_put(blob, MARK_BEGIN, MARK_BEGIN_LEN)) != 0 ||
2849 (r = sshbuf_dtob64(encoded, blob, 1)) != 0 ||
2850 (r = sshbuf_put(blob, MARK_END, MARK_END_LEN)) != 0)
2858 sshbuf_free(encoded);
2859 sshbuf_free(encrypted);
2860 cipher_free(ciphercontext);
2861 explicit_bzero(salt, sizeof(salt));
2863 freezero(key, keylen + ivlen);
2864 if (pubkeyblob != NULL)
2865 freezero(pubkeyblob, pubkeylen);
2870 private2_uudecode(struct sshbuf *blob, struct sshbuf **decodedp)
2876 struct sshbuf *encoded = NULL, *decoded = NULL;
2878 if (blob == NULL || decodedp == NULL)
2879 return SSH_ERR_INVALID_ARGUMENT;
2883 if ((encoded = sshbuf_new()) == NULL ||
2884 (decoded = sshbuf_new()) == NULL) {
2885 r = SSH_ERR_ALLOC_FAIL;
2889 /* check preamble */
2890 cp = sshbuf_ptr(blob);
2891 encoded_len = sshbuf_len(blob);
2892 if (encoded_len < (MARK_BEGIN_LEN + MARK_END_LEN) ||
2893 memcmp(cp, MARK_BEGIN, MARK_BEGIN_LEN) != 0) {
2894 r = SSH_ERR_INVALID_FORMAT;
2897 cp += MARK_BEGIN_LEN;
2898 encoded_len -= MARK_BEGIN_LEN;
2900 /* Look for end marker, removing whitespace as we go */
2901 while (encoded_len > 0) {
2902 if (*cp != '\n' && *cp != '\r') {
2903 if ((r = sshbuf_put_u8(encoded, *cp)) != 0)
2910 if (encoded_len >= MARK_END_LEN &&
2911 memcmp(cp, MARK_END, MARK_END_LEN) == 0) {
2913 if ((r = sshbuf_put_u8(encoded, 0)) != 0)
2919 if (encoded_len == 0) {
2920 r = SSH_ERR_INVALID_FORMAT;
2925 if ((r = sshbuf_b64tod(decoded, (char *)sshbuf_ptr(encoded))) != 0)
2929 if (sshbuf_len(decoded) < sizeof(AUTH_MAGIC) ||
2930 memcmp(sshbuf_ptr(decoded), AUTH_MAGIC, sizeof(AUTH_MAGIC))) {
2931 r = SSH_ERR_INVALID_FORMAT;
2935 *decodedp = decoded;
2939 sshbuf_free(encoded);
2940 sshbuf_free(decoded);
2945 private2_decrypt(struct sshbuf *decoded, const char *passphrase,
2946 struct sshbuf **decryptedp, struct sshkey **pubkeyp)
2948 char *ciphername = NULL, *kdfname = NULL;
2949 const struct sshcipher *cipher = NULL;
2950 int r = SSH_ERR_INTERNAL_ERROR;
2951 size_t keylen = 0, ivlen = 0, authlen = 0, slen = 0;
2952 struct sshbuf *kdf = NULL, *decrypted = NULL;
2953 struct sshcipher_ctx *ciphercontext = NULL;
2954 struct sshkey *pubkey = NULL;
2955 u_char *key = NULL, *salt = NULL, *dp;
2956 u_int blocksize, rounds, nkeys, encrypted_len, check1, check2;
2958 if (decoded == NULL || decryptedp == NULL || pubkeyp == NULL)
2959 return SSH_ERR_INVALID_ARGUMENT;
2964 if ((decrypted = sshbuf_new()) == NULL) {
2965 r = SSH_ERR_ALLOC_FAIL;
2969 /* parse public portion of key */
2970 if ((r = sshbuf_consume(decoded, sizeof(AUTH_MAGIC))) != 0 ||
2971 (r = sshbuf_get_cstring(decoded, &ciphername, NULL)) != 0 ||
2972 (r = sshbuf_get_cstring(decoded, &kdfname, NULL)) != 0 ||
2973 (r = sshbuf_froms(decoded, &kdf)) != 0 ||
2974 (r = sshbuf_get_u32(decoded, &nkeys)) != 0)
2978 /* XXX only one key supported at present */
2979 r = SSH_ERR_INVALID_FORMAT;
2983 if ((r = sshkey_froms(decoded, &pubkey)) != 0 ||
2984 (r = sshbuf_get_u32(decoded, &encrypted_len)) != 0)
2987 if ((cipher = cipher_by_name(ciphername)) == NULL) {
2988 r = SSH_ERR_KEY_UNKNOWN_CIPHER;
2991 if (strcmp(kdfname, "none") != 0 && strcmp(kdfname, "bcrypt") != 0) {
2992 r = SSH_ERR_KEY_UNKNOWN_CIPHER;
2995 if (strcmp(kdfname, "none") == 0 && strcmp(ciphername, "none") != 0) {
2996 r = SSH_ERR_INVALID_FORMAT;
2999 if ((passphrase == NULL || strlen(passphrase) == 0) &&
3000 strcmp(kdfname, "none") != 0) {
3001 /* passphrase required */
3002 r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3006 /* check size of encrypted key blob */
3007 blocksize = cipher_blocksize(cipher);
3008 if (encrypted_len < blocksize || (encrypted_len % blocksize) != 0) {
3009 r = SSH_ERR_INVALID_FORMAT;
3014 keylen = cipher_keylen(cipher);
3015 ivlen = cipher_ivlen(cipher);
3016 authlen = cipher_authlen(cipher);
3017 if ((key = calloc(1, keylen + ivlen)) == NULL) {
3018 r = SSH_ERR_ALLOC_FAIL;
3021 if (strcmp(kdfname, "bcrypt") == 0) {
3022 if ((r = sshbuf_get_string(kdf, &salt, &slen)) != 0 ||
3023 (r = sshbuf_get_u32(kdf, &rounds)) != 0)
3025 if (bcrypt_pbkdf(passphrase, strlen(passphrase), salt, slen,
3026 key, keylen + ivlen, rounds) < 0) {
3027 r = SSH_ERR_INVALID_FORMAT;
3032 /* check that an appropriate amount of auth data is present */
3033 if (sshbuf_len(decoded) < authlen ||
3034 sshbuf_len(decoded) - authlen < encrypted_len) {
3035 r = SSH_ERR_INVALID_FORMAT;
3039 /* decrypt private portion of key */
3040 if ((r = sshbuf_reserve(decrypted, encrypted_len, &dp)) != 0 ||
3041 (r = cipher_init(&ciphercontext, cipher, key, keylen,
3042 key + keylen, ivlen, 0)) != 0)
3044 if ((r = cipher_crypt(ciphercontext, 0, dp, sshbuf_ptr(decoded),
3045 encrypted_len, 0, authlen)) != 0) {
3046 /* an integrity error here indicates an incorrect passphrase */
3047 if (r == SSH_ERR_MAC_INVALID)
3048 r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3051 if ((r = sshbuf_consume(decoded, encrypted_len + authlen)) != 0)
3053 /* there should be no trailing data */
3054 if (sshbuf_len(decoded) != 0) {
3055 r = SSH_ERR_INVALID_FORMAT;
3059 /* check check bytes */
3060 if ((r = sshbuf_get_u32(decrypted, &check1)) != 0 ||
3061 (r = sshbuf_get_u32(decrypted, &check2)) != 0)
3063 if (check1 != check2) {
3064 r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3068 *decryptedp = decrypted;
3074 cipher_free(ciphercontext);
3077 sshkey_free(pubkey);
3079 explicit_bzero(salt, slen);
3083 explicit_bzero(key, keylen + ivlen);
3087 sshbuf_free(decrypted);
3092 sshkey_parse_private2(struct sshbuf *blob, int type, const char *passphrase,
3093 struct sshkey **keyp, char **commentp)
3095 char *comment = NULL;
3096 int r = SSH_ERR_INTERNAL_ERROR;
3097 struct sshbuf *decoded = NULL, *decrypted = NULL;
3098 struct sshkey *k = NULL, *pubkey = NULL;
3102 if (commentp != NULL)
3105 /* Undo base64 encoding and decrypt the private section */
3106 if ((r = private2_uudecode(blob, &decoded)) != 0 ||
3107 (r = private2_decrypt(decoded, passphrase,
3108 &decrypted, &pubkey)) != 0)
3111 if (type != KEY_UNSPEC &&
3112 sshkey_type_plain(type) != sshkey_type_plain(pubkey->type)) {
3113 r = SSH_ERR_KEY_TYPE_MISMATCH;
3117 /* Load the private key and comment */
3118 if ((r = sshkey_private_deserialize(decrypted, &k)) != 0 ||
3119 (r = sshbuf_get_cstring(decrypted, &comment, NULL)) != 0)
3122 /* Check deterministic padding after private section */
3123 if ((r = private2_check_padding(decrypted)) != 0)
3126 /* Check that the public key in the envelope matches the private key */
3127 if (!sshkey_equal(pubkey, k)) {
3128 r = SSH_ERR_INVALID_FORMAT;
3138 if (commentp != NULL) {
3139 *commentp = comment;
3144 sshbuf_free(decoded);
3145 sshbuf_free(decrypted);
3147 sshkey_free(pubkey);
3152 sshkey_parse_private2_pubkey(struct sshbuf *blob, int type,
3153 struct sshkey **keyp)
3155 int r = SSH_ERR_INTERNAL_ERROR;
3156 struct sshbuf *decoded = NULL;
3157 struct sshkey *pubkey = NULL;
3163 if ((r = private2_uudecode(blob, &decoded)) != 0)
3165 /* parse public key from unencrypted envelope */
3166 if ((r = sshbuf_consume(decoded, sizeof(AUTH_MAGIC))) != 0 ||
3167 (r = sshbuf_skip_string(decoded)) != 0 || /* cipher */
3168 (r = sshbuf_skip_string(decoded)) != 0 || /* KDF alg */
3169 (r = sshbuf_skip_string(decoded)) != 0 || /* KDF hint */
3170 (r = sshbuf_get_u32(decoded, &nkeys)) != 0)
3174 /* XXX only one key supported at present */
3175 r = SSH_ERR_INVALID_FORMAT;
3179 /* Parse the public key */
3180 if ((r = sshkey_froms(decoded, &pubkey)) != 0)
3183 if (type != KEY_UNSPEC &&
3184 sshkey_type_plain(type) != sshkey_type_plain(pubkey->type)) {
3185 r = SSH_ERR_KEY_TYPE_MISMATCH;
3196 sshbuf_free(decoded);
3197 sshkey_free(pubkey);
3202 /* convert SSH v2 key to PEM or PKCS#8 format */
3204 sshkey_private_to_blob_pem_pkcs8(struct sshkey *key, struct sshbuf *buf,
3205 int format, const char *_passphrase, const char *comment)
3207 int was_shielded = sshkey_is_shielded(key);
3209 int blen, len = strlen(_passphrase);
3210 u_char *passphrase = (len > 0) ? (u_char *)_passphrase : NULL;
3211 const EVP_CIPHER *cipher = (len > 0) ? EVP_aes_128_cbc() : NULL;
3214 struct sshbuf *blob;
3215 EVP_PKEY *pkey = NULL;
3217 if (len > 0 && len <= 4)
3218 return SSH_ERR_PASSPHRASE_TOO_SHORT;
3219 if ((blob = sshbuf_new()) == NULL)
3220 return SSH_ERR_ALLOC_FAIL;
3221 if ((bio = BIO_new(BIO_s_mem())) == NULL) {
3222 r = SSH_ERR_ALLOC_FAIL;
3225 if (format == SSHKEY_PRIVATE_PKCS8 && (pkey = EVP_PKEY_new()) == NULL) {
3226 r = SSH_ERR_ALLOC_FAIL;
3229 if ((r = sshkey_unshield_private(key)) != 0)
3232 switch (key->type) {
3234 if (format == SSHKEY_PRIVATE_PEM) {
3235 success = PEM_write_bio_DSAPrivateKey(bio, key->dsa,
3236 cipher, passphrase, len, NULL, NULL);
3238 success = EVP_PKEY_set1_DSA(pkey, key->dsa);
3241 #ifdef OPENSSL_HAS_ECC
3243 if (format == SSHKEY_PRIVATE_PEM) {
3244 success = PEM_write_bio_ECPrivateKey(bio, key->ecdsa,
3245 cipher, passphrase, len, NULL, NULL);
3247 success = EVP_PKEY_set1_EC_KEY(pkey, key->ecdsa);
3252 if (format == SSHKEY_PRIVATE_PEM) {
3253 success = PEM_write_bio_RSAPrivateKey(bio, key->rsa,
3254 cipher, passphrase, len, NULL, NULL);
3256 success = EVP_PKEY_set1_RSA(pkey, key->rsa);
3264 r = SSH_ERR_LIBCRYPTO_ERROR;
3267 if (format == SSHKEY_PRIVATE_PKCS8) {
3268 if ((success = PEM_write_bio_PrivateKey(bio, pkey, cipher,
3269 passphrase, len, NULL, NULL)) == 0) {
3270 r = SSH_ERR_LIBCRYPTO_ERROR;
3274 if ((blen = BIO_get_mem_data(bio, &bptr)) <= 0) {
3275 r = SSH_ERR_INTERNAL_ERROR;
3278 if ((r = sshbuf_put(blob, bptr, blen)) != 0)
3283 r = sshkey_shield_private(key);
3285 r = sshbuf_putb(buf, blob);
3287 EVP_PKEY_free(pkey);
3292 #endif /* WITH_OPENSSL */
3294 /* Serialise "key" to buffer "blob" */
3296 sshkey_private_to_fileblob(struct sshkey *key, struct sshbuf *blob,
3297 const char *passphrase, const char *comment,
3298 int format, const char *openssh_format_cipher, int openssh_format_rounds)
3300 switch (key->type) {
3305 break; /* see below */
3306 #endif /* WITH_OPENSSL */
3308 case KEY_ED25519_SK:
3311 #endif /* WITH_XMSS */
3314 #endif /* WITH_OPENSSL */
3315 return sshkey_private_to_blob2(key, blob, passphrase,
3316 comment, openssh_format_cipher, openssh_format_rounds);
3318 return SSH_ERR_KEY_TYPE_UNKNOWN;
3323 case SSHKEY_PRIVATE_OPENSSH:
3324 return sshkey_private_to_blob2(key, blob, passphrase,
3325 comment, openssh_format_cipher, openssh_format_rounds);
3326 case SSHKEY_PRIVATE_PEM:
3327 case SSHKEY_PRIVATE_PKCS8:
3328 return sshkey_private_to_blob_pem_pkcs8(key, blob,
3329 format, passphrase, comment);
3331 return SSH_ERR_INVALID_ARGUMENT;
3333 #endif /* WITH_OPENSSL */
3338 translate_libcrypto_error(unsigned long pem_err)
3340 int pem_reason = ERR_GET_REASON(pem_err);
3342 switch (ERR_GET_LIB(pem_err)) {
3344 switch (pem_reason) {
3345 case PEM_R_BAD_PASSWORD_READ:
3346 #ifdef PEM_R_PROBLEMS_GETTING_PASSWORD
3347 case PEM_R_PROBLEMS_GETTING_PASSWORD:
3349 #ifdef PEM_R_BAD_DECRYPT
3350 case PEM_R_BAD_DECRYPT:
3352 return SSH_ERR_KEY_WRONG_PASSPHRASE;
3354 return SSH_ERR_INVALID_FORMAT;
3357 switch (pem_reason) {
3358 #ifdef EVP_R_BAD_DECRYPT
3359 case EVP_R_BAD_DECRYPT:
3360 return SSH_ERR_KEY_WRONG_PASSPHRASE;
3362 #ifdef EVP_R_BN_DECODE_ERROR
3363 case EVP_R_BN_DECODE_ERROR:
3365 case EVP_R_DECODE_ERROR:
3366 #ifdef EVP_R_PRIVATE_KEY_DECODE_ERROR
3367 case EVP_R_PRIVATE_KEY_DECODE_ERROR:
3369 return SSH_ERR_INVALID_FORMAT;
3371 return SSH_ERR_LIBCRYPTO_ERROR;
3374 return SSH_ERR_INVALID_FORMAT;
3376 return SSH_ERR_LIBCRYPTO_ERROR;
3380 clear_libcrypto_errors(void)
3382 while (ERR_get_error() != 0)
3387 * Translate OpenSSL error codes to determine whether
3388 * passphrase is required/incorrect.
3391 convert_libcrypto_error(void)
3394 * Some password errors are reported at the beginning
3395 * of the error queue.
3397 if (translate_libcrypto_error(ERR_peek_error()) ==
3398 SSH_ERR_KEY_WRONG_PASSPHRASE)
3399 return SSH_ERR_KEY_WRONG_PASSPHRASE;
3400 return translate_libcrypto_error(ERR_peek_last_error());
3404 pem_passphrase_cb(char *buf, int size, int rwflag, void *u)
3406 char *p = (char *)u;
3409 if (p == NULL || (len = strlen(p)) == 0)
3411 if (size < 0 || len > (size_t)size)
3413 memcpy(buf, p, len);
3418 sshkey_parse_private_pem_fileblob(struct sshbuf *blob, int type,
3419 const char *passphrase, struct sshkey **keyp)
3421 EVP_PKEY *pk = NULL;
3422 struct sshkey *prv = NULL;
3429 if ((bio = BIO_new(BIO_s_mem())) == NULL || sshbuf_len(blob) > INT_MAX)
3430 return SSH_ERR_ALLOC_FAIL;
3431 if (BIO_write(bio, sshbuf_ptr(blob), sshbuf_len(blob)) !=
3432 (int)sshbuf_len(blob)) {
3433 r = SSH_ERR_ALLOC_FAIL;
3437 clear_libcrypto_errors();
3438 if ((pk = PEM_read_bio_PrivateKey(bio, NULL, pem_passphrase_cb,
3439 (char *)passphrase)) == NULL) {
3441 * libcrypto may return various ASN.1 errors when attempting
3442 * to parse a key with an incorrect passphrase.
3443 * Treat all format errors as "incorrect passphrase" if a
3444 * passphrase was supplied.
3446 if (passphrase != NULL && *passphrase != '\0')
3447 r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3449 r = convert_libcrypto_error();
3452 if (EVP_PKEY_base_id(pk) == EVP_PKEY_RSA &&
3453 (type == KEY_UNSPEC || type == KEY_RSA)) {
3454 if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
3455 r = SSH_ERR_ALLOC_FAIL;
3458 prv->rsa = EVP_PKEY_get1_RSA(pk);
3459 prv->type = KEY_RSA;
3461 RSA_print_fp(stderr, prv->rsa, 8);
3463 if (RSA_blinding_on(prv->rsa, NULL) != 1) {
3464 r = SSH_ERR_LIBCRYPTO_ERROR;
3467 if ((r = sshkey_check_rsa_length(prv, 0)) != 0)
3469 } else if (EVP_PKEY_base_id(pk) == EVP_PKEY_DSA &&
3470 (type == KEY_UNSPEC || type == KEY_DSA)) {
3471 if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
3472 r = SSH_ERR_ALLOC_FAIL;
3475 prv->dsa = EVP_PKEY_get1_DSA(pk);
3476 prv->type = KEY_DSA;
3478 DSA_print_fp(stderr, prv->dsa, 8);
3480 #ifdef OPENSSL_HAS_ECC
3481 } else if (EVP_PKEY_base_id(pk) == EVP_PKEY_EC &&
3482 (type == KEY_UNSPEC || type == KEY_ECDSA)) {
3483 if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
3484 r = SSH_ERR_ALLOC_FAIL;
3487 prv->ecdsa = EVP_PKEY_get1_EC_KEY(pk);
3488 prv->type = KEY_ECDSA;
3489 prv->ecdsa_nid = sshkey_ecdsa_key_to_nid(prv->ecdsa);
3490 if (prv->ecdsa_nid == -1 ||
3491 sshkey_curve_nid_to_name(prv->ecdsa_nid) == NULL ||
3492 sshkey_ec_validate_public(EC_KEY_get0_group(prv->ecdsa),
3493 EC_KEY_get0_public_key(prv->ecdsa)) != 0 ||
3494 sshkey_ec_validate_private(prv->ecdsa) != 0) {
3495 r = SSH_ERR_INVALID_FORMAT;
3499 if (prv != NULL && prv->ecdsa != NULL)
3500 sshkey_dump_ec_key(prv->ecdsa);
3502 #endif /* OPENSSL_HAS_ECC */
3503 #ifdef OPENSSL_HAS_ED25519
3504 } else if (EVP_PKEY_base_id(pk) == EVP_PKEY_ED25519 &&
3505 (type == KEY_UNSPEC || type == KEY_ED25519)) {
3508 if ((prv = sshkey_new(KEY_UNSPEC)) == NULL ||
3509 (prv->ed25519_sk = calloc(1, ED25519_SK_SZ)) == NULL ||
3510 (prv->ed25519_pk = calloc(1, ED25519_PK_SZ)) == NULL) {
3511 r = SSH_ERR_ALLOC_FAIL;
3514 prv->type = KEY_ED25519;
3515 len = ED25519_PK_SZ;
3516 if (!EVP_PKEY_get_raw_public_key(pk, prv->ed25519_pk, &len)) {
3517 r = SSH_ERR_LIBCRYPTO_ERROR;
3520 if (len != ED25519_PK_SZ) {
3521 r = SSH_ERR_INVALID_FORMAT;
3524 len = ED25519_SK_SZ - ED25519_PK_SZ;
3525 if (!EVP_PKEY_get_raw_private_key(pk, prv->ed25519_sk, &len)) {
3526 r = SSH_ERR_LIBCRYPTO_ERROR;
3529 if (len != ED25519_SK_SZ - ED25519_PK_SZ) {
3530 r = SSH_ERR_INVALID_FORMAT;
3533 /* Append the public key to our private key */
3534 memcpy(prv->ed25519_sk + (ED25519_SK_SZ - ED25519_PK_SZ),
3535 prv->ed25519_pk, ED25519_PK_SZ);
3537 sshbuf_dump_data(prv->ed25519_sk, ED25519_SK_SZ, stderr);
3539 #endif /* OPENSSL_HAS_ED25519 */
3541 r = SSH_ERR_INVALID_FORMAT;
3555 #endif /* WITH_OPENSSL */
3558 sshkey_parse_private_fileblob_type(struct sshbuf *blob, int type,
3559 const char *passphrase, struct sshkey **keyp, char **commentp)
3561 int r = SSH_ERR_INTERNAL_ERROR;
3565 if (commentp != NULL)
3570 /* No fallback for new-format-only keys */
3571 return sshkey_parse_private2(blob, type, passphrase,
3574 r = sshkey_parse_private2(blob, type, passphrase, keyp,
3576 /* Only fallback to PEM parser if a format error occurred. */
3577 if (r != SSH_ERR_INVALID_FORMAT)
3580 return sshkey_parse_private_pem_fileblob(blob, type,
3583 return SSH_ERR_INVALID_FORMAT;
3584 #endif /* WITH_OPENSSL */
3589 sshkey_parse_private_fileblob(struct sshbuf *buffer, const char *passphrase,
3590 struct sshkey **keyp, char **commentp)
3594 if (commentp != NULL)
3597 return sshkey_parse_private_fileblob_type(buffer, KEY_UNSPEC,
3598 passphrase, keyp, commentp);
3602 sshkey_sig_details_free(struct sshkey_sig_details *details)
3604 freezero(details, sizeof(*details));
3608 sshkey_parse_pubkey_from_private_fileblob_type(struct sshbuf *blob, int type,
3609 struct sshkey **pubkeyp)
3611 int r = SSH_ERR_INTERNAL_ERROR;
3613 if (pubkeyp != NULL)
3615 /* only new-format private keys bundle a public key inside */
3616 if ((r = sshkey_parse_private2_pubkey(blob, type, pubkeyp)) != 0)
3623 * serialize the key with the current state and forward the state
3627 sshkey_private_serialize_maxsign(struct sshkey *k, struct sshbuf *b,
3628 u_int32_t maxsign, int printerror)
3633 sshkey_type_plain(k->type) != KEY_XMSS)
3634 return sshkey_private_serialize_opt(k, b,
3635 SSHKEY_SERIALIZE_DEFAULT);
3636 if ((r = sshkey_xmss_get_state(k, printerror)) != 0 ||
3637 (r = sshkey_private_serialize_opt(k, b,
3638 SSHKEY_SERIALIZE_STATE)) != 0 ||
3639 (r = sshkey_xmss_forward_state(k, maxsign)) != 0)
3643 if ((rupdate = sshkey_xmss_update_state(k, printerror)) != 0) {
3651 sshkey_signatures_left(const struct sshkey *k)
3653 if (sshkey_type_plain(k->type) == KEY_XMSS)
3654 return sshkey_xmss_signatures_left(k);
3659 sshkey_enable_maxsign(struct sshkey *k, u_int32_t maxsign)
3661 if (sshkey_type_plain(k->type) != KEY_XMSS)
3662 return SSH_ERR_INVALID_ARGUMENT;
3663 return sshkey_xmss_enable_maxsign(k, maxsign);
3667 sshkey_set_filename(struct sshkey *k, const char *filename)
3670 return SSH_ERR_INVALID_ARGUMENT;
3671 if (sshkey_type_plain(k->type) != KEY_XMSS)
3673 if (filename == NULL)
3674 return SSH_ERR_INVALID_ARGUMENT;
3675 if ((k->xmss_filename = strdup(filename)) == NULL)
3676 return SSH_ERR_ALLOC_FAIL;
3681 sshkey_private_serialize_maxsign(struct sshkey *k, struct sshbuf *b,
3682 u_int32_t maxsign, int printerror)
3684 return sshkey_private_serialize_opt(k, b, SSHKEY_SERIALIZE_DEFAULT);
3688 sshkey_signatures_left(const struct sshkey *k)
3694 sshkey_enable_maxsign(struct sshkey *k, u_int32_t maxsign)
3696 return SSH_ERR_INVALID_ARGUMENT;
3700 sshkey_set_filename(struct sshkey *k, const char *filename)
3703 return SSH_ERR_INVALID_ARGUMENT;
3706 #endif /* WITH_XMSS */