1 /* $OpenBSD: sshkey.c,v 1.15 2015/03/06 01:40:56 djm 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/param.h> /* MIN MAX */
31 #include <sys/types.h>
32 #include <netinet/in.h>
35 #include <openssl/evp.h>
36 #include <openssl/err.h>
37 #include <openssl/pem.h>
40 #include "crypto_api.h"
49 #endif /* HAVE_UTIL_H */
58 #define SSHKEY_INTERNAL
62 /* openssh private key file format */
63 #define MARK_BEGIN "-----BEGIN OPENSSH PRIVATE KEY-----\n"
64 #define MARK_END "-----END OPENSSH PRIVATE KEY-----\n"
65 #define MARK_BEGIN_LEN (sizeof(MARK_BEGIN) - 1)
66 #define MARK_END_LEN (sizeof(MARK_END) - 1)
67 #define KDFNAME "bcrypt"
68 #define AUTH_MAGIC "openssh-key-v1"
70 #define DEFAULT_CIPHERNAME "aes256-cbc"
71 #define DEFAULT_ROUNDS 16
73 /* Version identification string for SSH v1 identity files. */
74 #define LEGACY_BEGIN "SSH PRIVATE KEY FILE FORMAT 1.1\n"
76 static int sshkey_from_blob_internal(struct sshbuf *buf,
77 struct sshkey **keyp, int allow_cert);
79 /* Supported key types */
82 const char *shortname;
87 static const struct keytype keytypes[] = {
88 { "ssh-ed25519", "ED25519", KEY_ED25519, 0, 0 },
89 { "ssh-ed25519-cert-v01@openssh.com", "ED25519-CERT",
90 KEY_ED25519_CERT, 0, 1 },
92 { NULL, "RSA1", KEY_RSA1, 0, 0 },
93 { "ssh-rsa", "RSA", KEY_RSA, 0, 0 },
94 { "ssh-dss", "DSA", KEY_DSA, 0, 0 },
95 # ifdef OPENSSL_HAS_ECC
96 { "ecdsa-sha2-nistp256", "ECDSA", KEY_ECDSA, NID_X9_62_prime256v1, 0 },
97 { "ecdsa-sha2-nistp384", "ECDSA", KEY_ECDSA, NID_secp384r1, 0 },
98 # ifdef OPENSSL_HAS_NISTP521
99 { "ecdsa-sha2-nistp521", "ECDSA", KEY_ECDSA, NID_secp521r1, 0 },
100 # endif /* OPENSSL_HAS_NISTP521 */
101 # endif /* OPENSSL_HAS_ECC */
102 { "ssh-rsa-cert-v01@openssh.com", "RSA-CERT", KEY_RSA_CERT, 0, 1 },
103 { "ssh-dss-cert-v01@openssh.com", "DSA-CERT", KEY_DSA_CERT, 0, 1 },
104 # ifdef OPENSSL_HAS_ECC
105 { "ecdsa-sha2-nistp256-cert-v01@openssh.com", "ECDSA-CERT",
106 KEY_ECDSA_CERT, NID_X9_62_prime256v1, 1 },
107 { "ecdsa-sha2-nistp384-cert-v01@openssh.com", "ECDSA-CERT",
108 KEY_ECDSA_CERT, NID_secp384r1, 1 },
109 # ifdef OPENSSL_HAS_NISTP521
110 { "ecdsa-sha2-nistp521-cert-v01@openssh.com", "ECDSA-CERT",
111 KEY_ECDSA_CERT, NID_secp521r1, 1 },
112 # endif /* OPENSSL_HAS_NISTP521 */
113 # endif /* OPENSSL_HAS_ECC */
114 { "ssh-rsa-cert-v00@openssh.com", "RSA-CERT-V00",
115 KEY_RSA_CERT_V00, 0, 1 },
116 { "ssh-dss-cert-v00@openssh.com", "DSA-CERT-V00",
117 KEY_DSA_CERT_V00, 0, 1 },
118 #endif /* WITH_OPENSSL */
119 { NULL, NULL, -1, -1, 0 }
123 sshkey_type(const struct sshkey *k)
125 const struct keytype *kt;
127 for (kt = keytypes; kt->type != -1; kt++) {
128 if (kt->type == k->type)
129 return kt->shortname;
135 sshkey_ssh_name_from_type_nid(int type, int nid)
137 const struct keytype *kt;
139 for (kt = keytypes; kt->type != -1; kt++) {
140 if (kt->type == type && (kt->nid == 0 || kt->nid == nid))
143 return "ssh-unknown";
147 sshkey_type_is_cert(int type)
149 const struct keytype *kt;
151 for (kt = keytypes; kt->type != -1; kt++) {
152 if (kt->type == type)
159 sshkey_ssh_name(const struct sshkey *k)
161 return sshkey_ssh_name_from_type_nid(k->type, k->ecdsa_nid);
165 sshkey_ssh_name_plain(const struct sshkey *k)
167 return sshkey_ssh_name_from_type_nid(sshkey_type_plain(k->type),
172 sshkey_type_from_name(const char *name)
174 const struct keytype *kt;
176 for (kt = keytypes; kt->type != -1; kt++) {
177 /* Only allow shortname matches for plain key types */
178 if ((kt->name != NULL && strcmp(name, kt->name) == 0) ||
179 (!kt->cert && strcasecmp(kt->shortname, name) == 0))
186 sshkey_ecdsa_nid_from_name(const char *name)
188 const struct keytype *kt;
190 for (kt = keytypes; kt->type != -1; kt++) {
191 if (kt->type != KEY_ECDSA && kt->type != KEY_ECDSA_CERT)
193 if (kt->name != NULL && strcmp(name, kt->name) == 0)
200 key_alg_list(int certs_only, int plain_only)
202 char *tmp, *ret = NULL;
203 size_t nlen, rlen = 0;
204 const struct keytype *kt;
206 for (kt = keytypes; kt->type != -1; kt++) {
207 if (kt->name == NULL)
209 if ((certs_only && !kt->cert) || (plain_only && kt->cert))
213 nlen = strlen(kt->name);
214 if ((tmp = realloc(ret, rlen + nlen + 2)) == NULL) {
219 memcpy(ret + rlen, kt->name, nlen + 1);
226 sshkey_names_valid2(const char *names, int allow_wildcard)
229 const struct keytype *kt;
232 if (names == NULL || strcmp(names, "") == 0)
234 if ((s = cp = strdup(names)) == NULL)
236 for ((p = strsep(&cp, ",")); p && *p != '\0';
237 (p = strsep(&cp, ","))) {
238 type = sshkey_type_from_name(p);
239 if (type == KEY_RSA1) {
243 if (type == KEY_UNSPEC) {
244 if (allow_wildcard) {
246 * Try matching key types against the string.
247 * If any has a positive or negative match then
248 * the component is accepted.
250 for (kt = keytypes; kt->type != -1; kt++) {
251 if (kt->type == KEY_RSA1)
253 if (match_pattern_list(kt->name,
254 p, strlen(p), 0) != 0)
269 sshkey_size(const struct sshkey *k)
275 case KEY_RSA_CERT_V00:
277 return BN_num_bits(k->rsa->n);
279 case KEY_DSA_CERT_V00:
281 return BN_num_bits(k->dsa->p);
284 return sshkey_curve_nid_to_bits(k->ecdsa_nid);
285 #endif /* WITH_OPENSSL */
287 case KEY_ED25519_CERT:
288 return 256; /* XXX */
294 sshkey_cert_is_legacy(const struct sshkey *k)
297 case KEY_DSA_CERT_V00:
298 case KEY_RSA_CERT_V00:
306 sshkey_type_is_valid_ca(int type)
320 sshkey_is_cert(const struct sshkey *k)
324 return sshkey_type_is_cert(k->type);
327 /* Return the cert-less equivalent to a certified key type */
329 sshkey_type_plain(int type)
332 case KEY_RSA_CERT_V00:
335 case KEY_DSA_CERT_V00:
340 case KEY_ED25519_CERT:
348 /* XXX: these are really begging for a table-driven approach */
350 sshkey_curve_name_to_nid(const char *name)
352 if (strcmp(name, "nistp256") == 0)
353 return NID_X9_62_prime256v1;
354 else if (strcmp(name, "nistp384") == 0)
355 return NID_secp384r1;
356 # ifdef OPENSSL_HAS_NISTP521
357 else if (strcmp(name, "nistp521") == 0)
358 return NID_secp521r1;
359 # endif /* OPENSSL_HAS_NISTP521 */
365 sshkey_curve_nid_to_bits(int nid)
368 case NID_X9_62_prime256v1:
372 # ifdef OPENSSL_HAS_NISTP521
375 # endif /* OPENSSL_HAS_NISTP521 */
382 sshkey_ecdsa_bits_to_nid(int bits)
386 return NID_X9_62_prime256v1;
388 return NID_secp384r1;
389 # ifdef OPENSSL_HAS_NISTP521
391 return NID_secp521r1;
392 # endif /* OPENSSL_HAS_NISTP521 */
399 sshkey_curve_nid_to_name(int nid)
402 case NID_X9_62_prime256v1:
406 # ifdef OPENSSL_HAS_NISTP521
409 # endif /* OPENSSL_HAS_NISTP521 */
416 sshkey_ec_nid_to_hash_alg(int nid)
418 int kbits = sshkey_curve_nid_to_bits(nid);
423 /* RFC5656 section 6.2.1 */
425 return SSH_DIGEST_SHA256;
426 else if (kbits <= 384)
427 return SSH_DIGEST_SHA384;
429 return SSH_DIGEST_SHA512;
431 #endif /* WITH_OPENSSL */
434 cert_free(struct sshkey_cert *cert)
440 if (cert->certblob != NULL)
441 sshbuf_free(cert->certblob);
442 if (cert->critical != NULL)
443 sshbuf_free(cert->critical);
444 if (cert->extensions != NULL)
445 sshbuf_free(cert->extensions);
446 if (cert->key_id != NULL)
448 for (i = 0; i < cert->nprincipals; i++)
449 free(cert->principals[i]);
450 if (cert->principals != NULL)
451 free(cert->principals);
452 if (cert->signature_key != NULL)
453 sshkey_free(cert->signature_key);
454 explicit_bzero(cert, sizeof(*cert));
458 static struct sshkey_cert *
461 struct sshkey_cert *cert;
463 if ((cert = calloc(1, sizeof(*cert))) == NULL)
465 if ((cert->certblob = sshbuf_new()) == NULL ||
466 (cert->critical = sshbuf_new()) == NULL ||
467 (cert->extensions = sshbuf_new()) == NULL) {
472 cert->principals = NULL;
473 cert->signature_key = NULL;
484 #endif /* WITH_OPENSSL */
486 if ((k = calloc(1, sizeof(*k))) == NULL)
494 k->ed25519_sk = NULL;
495 k->ed25519_pk = NULL;
500 case KEY_RSA_CERT_V00:
502 if ((rsa = RSA_new()) == NULL ||
503 (rsa->n = BN_new()) == NULL ||
504 (rsa->e = BN_new()) == NULL) {
513 case KEY_DSA_CERT_V00:
515 if ((dsa = DSA_new()) == NULL ||
516 (dsa->p = BN_new()) == NULL ||
517 (dsa->q = BN_new()) == NULL ||
518 (dsa->g = BN_new()) == NULL ||
519 (dsa->pub_key = BN_new()) == NULL) {
529 /* Cannot do anything until we know the group */
531 #endif /* WITH_OPENSSL */
533 case KEY_ED25519_CERT:
534 /* no need to prealloc */
544 if (sshkey_is_cert(k)) {
545 if ((k->cert = cert_new()) == NULL) {
555 sshkey_add_private(struct sshkey *k)
561 case KEY_RSA_CERT_V00:
563 #define bn_maybe_alloc_failed(p) (p == NULL && (p = BN_new()) == NULL)
564 if (bn_maybe_alloc_failed(k->rsa->d) ||
565 bn_maybe_alloc_failed(k->rsa->iqmp) ||
566 bn_maybe_alloc_failed(k->rsa->q) ||
567 bn_maybe_alloc_failed(k->rsa->p) ||
568 bn_maybe_alloc_failed(k->rsa->dmq1) ||
569 bn_maybe_alloc_failed(k->rsa->dmp1))
570 return SSH_ERR_ALLOC_FAIL;
573 case KEY_DSA_CERT_V00:
575 if (bn_maybe_alloc_failed(k->dsa->priv_key))
576 return SSH_ERR_ALLOC_FAIL;
578 #undef bn_maybe_alloc_failed
581 /* Cannot do anything until we know the group */
583 #endif /* WITH_OPENSSL */
585 case KEY_ED25519_CERT:
586 /* no need to prealloc */
591 return SSH_ERR_INVALID_ARGUMENT;
597 sshkey_new_private(int type)
599 struct sshkey *k = sshkey_new(type);
603 if (sshkey_add_private(k) != 0) {
611 sshkey_free(struct sshkey *k)
619 case KEY_RSA_CERT_V00:
626 case KEY_DSA_CERT_V00:
632 # ifdef OPENSSL_HAS_ECC
635 if (k->ecdsa != NULL)
636 EC_KEY_free(k->ecdsa);
639 # endif /* OPENSSL_HAS_ECC */
640 #endif /* WITH_OPENSSL */
642 case KEY_ED25519_CERT:
644 explicit_bzero(k->ed25519_pk, ED25519_PK_SZ);
646 k->ed25519_pk = NULL;
649 explicit_bzero(k->ed25519_sk, ED25519_SK_SZ);
651 k->ed25519_sk = NULL;
659 if (sshkey_is_cert(k))
661 explicit_bzero(k, sizeof(*k));
666 cert_compare(struct sshkey_cert *a, struct sshkey_cert *b)
668 if (a == NULL && b == NULL)
670 if (a == NULL || b == NULL)
672 if (sshbuf_len(a->certblob) != sshbuf_len(b->certblob))
674 if (timingsafe_bcmp(sshbuf_ptr(a->certblob), sshbuf_ptr(b->certblob),
675 sshbuf_len(a->certblob)) != 0)
681 * Compare public portions of key only, allowing comparisons between
682 * certificates and plain keys too.
685 sshkey_equal_public(const struct sshkey *a, const struct sshkey *b)
687 #if defined(WITH_OPENSSL) && defined(OPENSSL_HAS_ECC)
689 #endif /* WITH_OPENSSL && OPENSSL_HAS_ECC */
691 if (a == NULL || b == NULL ||
692 sshkey_type_plain(a->type) != sshkey_type_plain(b->type))
698 case KEY_RSA_CERT_V00:
701 return a->rsa != NULL && b->rsa != NULL &&
702 BN_cmp(a->rsa->e, b->rsa->e) == 0 &&
703 BN_cmp(a->rsa->n, b->rsa->n) == 0;
704 case KEY_DSA_CERT_V00:
707 return a->dsa != NULL && b->dsa != NULL &&
708 BN_cmp(a->dsa->p, b->dsa->p) == 0 &&
709 BN_cmp(a->dsa->q, b->dsa->q) == 0 &&
710 BN_cmp(a->dsa->g, b->dsa->g) == 0 &&
711 BN_cmp(a->dsa->pub_key, b->dsa->pub_key) == 0;
712 # ifdef OPENSSL_HAS_ECC
715 if (a->ecdsa == NULL || b->ecdsa == NULL ||
716 EC_KEY_get0_public_key(a->ecdsa) == NULL ||
717 EC_KEY_get0_public_key(b->ecdsa) == NULL)
719 if ((bnctx = BN_CTX_new()) == NULL)
721 if (EC_GROUP_cmp(EC_KEY_get0_group(a->ecdsa),
722 EC_KEY_get0_group(b->ecdsa), bnctx) != 0 ||
723 EC_POINT_cmp(EC_KEY_get0_group(a->ecdsa),
724 EC_KEY_get0_public_key(a->ecdsa),
725 EC_KEY_get0_public_key(b->ecdsa), bnctx) != 0) {
731 # endif /* OPENSSL_HAS_ECC */
732 #endif /* WITH_OPENSSL */
734 case KEY_ED25519_CERT:
735 return a->ed25519_pk != NULL && b->ed25519_pk != NULL &&
736 memcmp(a->ed25519_pk, b->ed25519_pk, ED25519_PK_SZ) == 0;
744 sshkey_equal(const struct sshkey *a, const struct sshkey *b)
746 if (a == NULL || b == NULL || a->type != b->type)
748 if (sshkey_is_cert(a)) {
749 if (!cert_compare(a->cert, b->cert))
752 return sshkey_equal_public(a, b);
756 to_blob_buf(const struct sshkey *key, struct sshbuf *b, int force_plain)
758 int type, ret = SSH_ERR_INTERNAL_ERROR;
759 const char *typename;
762 return SSH_ERR_INVALID_ARGUMENT;
764 type = force_plain ? sshkey_type_plain(key->type) : key->type;
765 typename = sshkey_ssh_name_from_type_nid(type, key->ecdsa_nid);
769 case KEY_DSA_CERT_V00:
770 case KEY_RSA_CERT_V00:
774 #endif /* WITH_OPENSSL */
775 case KEY_ED25519_CERT:
776 /* Use the existing blob */
777 /* XXX modified flag? */
778 if ((ret = sshbuf_putb(b, key->cert->certblob)) != 0)
783 if (key->dsa == NULL)
784 return SSH_ERR_INVALID_ARGUMENT;
785 if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
786 (ret = sshbuf_put_bignum2(b, key->dsa->p)) != 0 ||
787 (ret = sshbuf_put_bignum2(b, key->dsa->q)) != 0 ||
788 (ret = sshbuf_put_bignum2(b, key->dsa->g)) != 0 ||
789 (ret = sshbuf_put_bignum2(b, key->dsa->pub_key)) != 0)
792 # ifdef OPENSSL_HAS_ECC
794 if (key->ecdsa == NULL)
795 return SSH_ERR_INVALID_ARGUMENT;
796 if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
797 (ret = sshbuf_put_cstring(b,
798 sshkey_curve_nid_to_name(key->ecdsa_nid))) != 0 ||
799 (ret = sshbuf_put_eckey(b, key->ecdsa)) != 0)
804 if (key->rsa == NULL)
805 return SSH_ERR_INVALID_ARGUMENT;
806 if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
807 (ret = sshbuf_put_bignum2(b, key->rsa->e)) != 0 ||
808 (ret = sshbuf_put_bignum2(b, key->rsa->n)) != 0)
811 #endif /* WITH_OPENSSL */
813 if (key->ed25519_pk == NULL)
814 return SSH_ERR_INVALID_ARGUMENT;
815 if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
816 (ret = sshbuf_put_string(b,
817 key->ed25519_pk, ED25519_PK_SZ)) != 0)
821 return SSH_ERR_KEY_TYPE_UNKNOWN;
827 sshkey_putb(const struct sshkey *key, struct sshbuf *b)
829 return to_blob_buf(key, b, 0);
833 sshkey_puts(const struct sshkey *key, struct sshbuf *b)
838 if ((tmp = sshbuf_new()) == NULL)
839 return SSH_ERR_ALLOC_FAIL;
840 r = to_blob_buf(key, tmp, 0);
842 r = sshbuf_put_stringb(b, tmp);
848 sshkey_putb_plain(const struct sshkey *key, struct sshbuf *b)
850 return to_blob_buf(key, b, 1);
854 to_blob(const struct sshkey *key, u_char **blobp, size_t *lenp, int force_plain)
856 int ret = SSH_ERR_INTERNAL_ERROR;
858 struct sshbuf *b = NULL;
864 if ((b = sshbuf_new()) == NULL)
865 return SSH_ERR_ALLOC_FAIL;
866 if ((ret = to_blob_buf(key, b, force_plain)) != 0)
872 if ((*blobp = malloc(len)) == NULL) {
873 ret = SSH_ERR_ALLOC_FAIL;
876 memcpy(*blobp, sshbuf_ptr(b), len);
885 sshkey_to_blob(const struct sshkey *key, u_char **blobp, size_t *lenp)
887 return to_blob(key, blobp, lenp, 0);
891 sshkey_plain_to_blob(const struct sshkey *key, u_char **blobp, size_t *lenp)
893 return to_blob(key, blobp, lenp, 1);
897 sshkey_fingerprint_raw(const struct sshkey *k, int dgst_alg,
898 u_char **retp, size_t *lenp)
900 u_char *blob = NULL, *ret = NULL;
902 int r = SSH_ERR_INTERNAL_ERROR;
908 if (ssh_digest_bytes(dgst_alg) == 0) {
909 r = SSH_ERR_INVALID_ARGUMENT;
913 if (k->type == KEY_RSA1) {
915 int nlen = BN_num_bytes(k->rsa->n);
916 int elen = BN_num_bytes(k->rsa->e);
918 blob_len = nlen + elen;
919 if (nlen >= INT_MAX - elen ||
920 (blob = malloc(blob_len)) == NULL) {
921 r = SSH_ERR_ALLOC_FAIL;
924 BN_bn2bin(k->rsa->n, blob);
925 BN_bn2bin(k->rsa->e, blob + nlen);
926 #endif /* WITH_OPENSSL */
927 } else if ((r = to_blob(k, &blob, &blob_len, 1)) != 0)
929 if ((ret = calloc(1, SSH_DIGEST_MAX_LENGTH)) == NULL) {
930 r = SSH_ERR_ALLOC_FAIL;
933 if ((r = ssh_digest_memory(dgst_alg, blob, blob_len,
934 ret, SSH_DIGEST_MAX_LENGTH)) != 0)
942 *lenp = ssh_digest_bytes(dgst_alg);
947 explicit_bzero(blob, blob_len);
954 fingerprint_b64(const char *alg, u_char *dgst_raw, size_t dgst_raw_len)
957 size_t plen = strlen(alg) + 1;
958 size_t rlen = ((dgst_raw_len + 2) / 3) * 4 + plen + 1;
961 if (dgst_raw_len > 65536 || (ret = calloc(1, rlen)) == NULL)
963 strlcpy(ret, alg, rlen);
964 strlcat(ret, ":", rlen);
965 if (dgst_raw_len == 0)
967 if ((r = b64_ntop(dgst_raw, dgst_raw_len,
968 ret + plen, rlen - plen)) == -1) {
969 explicit_bzero(ret, rlen);
973 /* Trim padding characters from end */
974 ret[strcspn(ret, "=")] = '\0';
979 fingerprint_hex(const char *alg, u_char *dgst_raw, size_t dgst_raw_len)
981 char *retval, hex[5];
982 size_t i, rlen = dgst_raw_len * 3 + strlen(alg) + 2;
984 if (dgst_raw_len > 65536 || (retval = calloc(1, rlen)) == NULL)
986 strlcpy(retval, alg, rlen);
987 strlcat(retval, ":", rlen);
988 for (i = 0; i < dgst_raw_len; i++) {
989 snprintf(hex, sizeof(hex), "%s%02x",
990 i > 0 ? ":" : "", dgst_raw[i]);
991 strlcat(retval, hex, rlen);
997 fingerprint_bubblebabble(u_char *dgst_raw, size_t dgst_raw_len)
999 char vowels[] = { 'a', 'e', 'i', 'o', 'u', 'y' };
1000 char consonants[] = { 'b', 'c', 'd', 'f', 'g', 'h', 'k', 'l', 'm',
1001 'n', 'p', 'r', 's', 't', 'v', 'z', 'x' };
1002 u_int i, j = 0, rounds, seed = 1;
1005 rounds = (dgst_raw_len / 2) + 1;
1006 if ((retval = calloc(rounds, 6)) == NULL)
1009 for (i = 0; i < rounds; i++) {
1010 u_int idx0, idx1, idx2, idx3, idx4;
1011 if ((i + 1 < rounds) || (dgst_raw_len % 2 != 0)) {
1012 idx0 = (((((u_int)(dgst_raw[2 * i])) >> 6) & 3) +
1014 idx1 = (((u_int)(dgst_raw[2 * i])) >> 2) & 15;
1015 idx2 = ((((u_int)(dgst_raw[2 * i])) & 3) +
1017 retval[j++] = vowels[idx0];
1018 retval[j++] = consonants[idx1];
1019 retval[j++] = vowels[idx2];
1020 if ((i + 1) < rounds) {
1021 idx3 = (((u_int)(dgst_raw[(2 * i) + 1])) >> 4) & 15;
1022 idx4 = (((u_int)(dgst_raw[(2 * i) + 1]))) & 15;
1023 retval[j++] = consonants[idx3];
1025 retval[j++] = consonants[idx4];
1026 seed = ((seed * 5) +
1027 ((((u_int)(dgst_raw[2 * i])) * 7) +
1028 ((u_int)(dgst_raw[(2 * i) + 1])))) % 36;
1034 retval[j++] = vowels[idx0];
1035 retval[j++] = consonants[idx1];
1036 retval[j++] = vowels[idx2];
1045 * Draw an ASCII-Art representing the fingerprint so human brain can
1046 * profit from its built-in pattern recognition ability.
1047 * This technique is called "random art" and can be found in some
1048 * scientific publications like this original paper:
1050 * "Hash Visualization: a New Technique to improve Real-World Security",
1051 * Perrig A. and Song D., 1999, International Workshop on Cryptographic
1052 * Techniques and E-Commerce (CrypTEC '99)
1053 * sparrow.ece.cmu.edu/~adrian/projects/validation/validation.pdf
1055 * The subject came up in a talk by Dan Kaminsky, too.
1057 * If you see the picture is different, the key is different.
1058 * If the picture looks the same, you still know nothing.
1060 * The algorithm used here is a worm crawling over a discrete plane,
1061 * leaving a trace (augmenting the field) everywhere it goes.
1062 * Movement is taken from dgst_raw 2bit-wise. Bumping into walls
1063 * makes the respective movement vector be ignored for this turn.
1064 * Graphs are not unambiguous, because circles in graphs can be
1065 * walked in either direction.
1069 * Field sizes for the random art. Have to be odd, so the starting point
1070 * can be in the exact middle of the picture, and FLDBASE should be >=8 .
1071 * Else pictures would be too dense, and drawing the frame would
1072 * fail, too, because the key type would not fit in anymore.
1075 #define FLDSIZE_Y (FLDBASE + 1)
1076 #define FLDSIZE_X (FLDBASE * 2 + 1)
1078 fingerprint_randomart(const char *alg, u_char *dgst_raw, size_t dgst_raw_len,
1079 const struct sshkey *k)
1082 * Chars to be used after each other every time the worm
1083 * intersects with itself. Matter of taste.
1085 char *augmentation_string = " .o+=*BOX@%&#/^SE";
1086 char *retval, *p, title[FLDSIZE_X], hash[FLDSIZE_X];
1087 u_char field[FLDSIZE_X][FLDSIZE_Y];
1088 size_t i, tlen, hlen;
1091 size_t len = strlen(augmentation_string) - 1;
1093 if ((retval = calloc((FLDSIZE_X + 3), (FLDSIZE_Y + 2))) == NULL)
1096 /* initialize field */
1097 memset(field, 0, FLDSIZE_X * FLDSIZE_Y * sizeof(char));
1101 /* process raw key */
1102 for (i = 0; i < dgst_raw_len; i++) {
1104 /* each byte conveys four 2-bit move commands */
1105 input = dgst_raw[i];
1106 for (b = 0; b < 4; b++) {
1107 /* evaluate 2 bit, rest is shifted later */
1108 x += (input & 0x1) ? 1 : -1;
1109 y += (input & 0x2) ? 1 : -1;
1111 /* assure we are still in bounds */
1114 x = MIN(x, FLDSIZE_X - 1);
1115 y = MIN(y, FLDSIZE_Y - 1);
1117 /* augment the field */
1118 if (field[x][y] < len - 2)
1124 /* mark starting point and end point*/
1125 field[FLDSIZE_X / 2][FLDSIZE_Y / 2] = len - 1;
1128 /* assemble title */
1129 r = snprintf(title, sizeof(title), "[%s %u]",
1130 sshkey_type(k), sshkey_size(k));
1131 /* If [type size] won't fit, then try [type]; fits "[ED25519-CERT]" */
1132 if (r < 0 || r > (int)sizeof(title))
1133 r = snprintf(title, sizeof(title), "[%s]", sshkey_type(k));
1134 tlen = (r <= 0) ? 0 : strlen(title);
1136 /* assemble hash ID. */
1137 r = snprintf(hash, sizeof(hash), "[%s]", alg);
1138 hlen = (r <= 0) ? 0 : strlen(hash);
1140 /* output upper border */
1143 for (i = 0; i < (FLDSIZE_X - tlen) / 2; i++)
1145 memcpy(p, title, tlen);
1147 for (i += tlen; i < FLDSIZE_X; i++)
1152 /* output content */
1153 for (y = 0; y < FLDSIZE_Y; y++) {
1155 for (x = 0; x < FLDSIZE_X; x++)
1156 *p++ = augmentation_string[MIN(field[x][y], len)];
1161 /* output lower border */
1163 for (i = 0; i < (FLDSIZE_X - hlen) / 2; i++)
1165 memcpy(p, hash, hlen);
1167 for (i += hlen; i < FLDSIZE_X; i++)
1175 sshkey_fingerprint(const struct sshkey *k, int dgst_alg,
1176 enum sshkey_fp_rep dgst_rep)
1178 char *retval = NULL;
1180 size_t dgst_raw_len;
1182 if (sshkey_fingerprint_raw(k, dgst_alg, &dgst_raw, &dgst_raw_len) != 0)
1185 case SSH_FP_DEFAULT:
1186 if (dgst_alg == SSH_DIGEST_MD5) {
1187 retval = fingerprint_hex(ssh_digest_alg_name(dgst_alg),
1188 dgst_raw, dgst_raw_len);
1190 retval = fingerprint_b64(ssh_digest_alg_name(dgst_alg),
1191 dgst_raw, dgst_raw_len);
1195 retval = fingerprint_hex(ssh_digest_alg_name(dgst_alg),
1196 dgst_raw, dgst_raw_len);
1199 retval = fingerprint_b64(ssh_digest_alg_name(dgst_alg),
1200 dgst_raw, dgst_raw_len);
1202 case SSH_FP_BUBBLEBABBLE:
1203 retval = fingerprint_bubblebabble(dgst_raw, dgst_raw_len);
1205 case SSH_FP_RANDOMART:
1206 retval = fingerprint_randomart(ssh_digest_alg_name(dgst_alg),
1207 dgst_raw, dgst_raw_len, k);
1210 explicit_bzero(dgst_raw, dgst_raw_len);
1214 explicit_bzero(dgst_raw, dgst_raw_len);
1221 * Reads a multiple-precision integer in decimal from the buffer, and advances
1222 * the pointer. The integer must already be initialized. This function is
1223 * permitted to modify the buffer. This leaves *cpp to point just beyond the
1224 * last processed character.
1227 read_decimal_bignum(char **cpp, BIGNUM *v)
1231 int skip = 1; /* skip white space */
1234 while (*cp == ' ' || *cp == '\t')
1236 e = strspn(cp, "0123456789");
1238 return SSH_ERR_INVALID_FORMAT;
1239 if (e > SSHBUF_MAX_BIGNUM * 3)
1240 return SSH_ERR_BIGNUM_TOO_LARGE;
1243 else if (index(" \t\r\n", cp[e]) == NULL)
1244 return SSH_ERR_INVALID_FORMAT;
1246 if (BN_dec2bn(&v, cp) <= 0)
1247 return SSH_ERR_INVALID_FORMAT;
1248 *cpp = cp + e + skip;
1251 #endif /* WITH_SSH1 */
1253 /* returns 0 ok, and < 0 error */
1255 sshkey_read(struct sshkey *ret, char **cpp)
1258 int retval = SSH_ERR_INVALID_FORMAT;
1260 int r, type, curve_nid = -1;
1261 struct sshbuf *blob;
1265 #endif /* WITH_SSH1 */
1269 switch (ret->type) {
1272 /* Get number of bits. */
1273 bits = strtoul(cp, &ep, 10);
1274 if (*cp == '\0' || index(" \t\r\n", *ep) == NULL ||
1275 bits == 0 || bits > SSHBUF_MAX_BIGNUM * 8)
1276 return SSH_ERR_INVALID_FORMAT; /* Bad bit count... */
1277 /* Get public exponent, public modulus. */
1278 if ((r = read_decimal_bignum(&ep, ret->rsa->e)) < 0)
1280 if ((r = read_decimal_bignum(&ep, ret->rsa->n)) < 0)
1283 /* validate the claimed number of bits */
1284 if (BN_num_bits(ret->rsa->n) != (int)bits)
1285 return SSH_ERR_KEY_BITS_MISMATCH;
1287 #endif /* WITH_SSH1 */
1294 case KEY_DSA_CERT_V00:
1295 case KEY_RSA_CERT_V00:
1297 case KEY_ECDSA_CERT:
1299 case KEY_ED25519_CERT:
1300 space = strchr(cp, ' ');
1302 return SSH_ERR_INVALID_FORMAT;
1304 type = sshkey_type_from_name(cp);
1305 if (sshkey_type_plain(type) == KEY_ECDSA &&
1306 (curve_nid = sshkey_ecdsa_nid_from_name(cp)) == -1)
1307 return SSH_ERR_EC_CURVE_INVALID;
1309 if (type == KEY_UNSPEC)
1310 return SSH_ERR_INVALID_FORMAT;
1313 return SSH_ERR_INVALID_FORMAT;
1314 if (ret->type != KEY_UNSPEC && ret->type != type)
1315 return SSH_ERR_KEY_TYPE_MISMATCH;
1316 if ((blob = sshbuf_new()) == NULL)
1317 return SSH_ERR_ALLOC_FAIL;
1319 space = strchr(cp, ' ');
1321 /* advance 'space': skip whitespace */
1323 while (*space == ' ' || *space == '\t')
1327 *cpp = cp + strlen(cp);
1328 if ((r = sshbuf_b64tod(blob, cp)) != 0) {
1332 if ((r = sshkey_from_blob(sshbuf_ptr(blob),
1333 sshbuf_len(blob), &k)) != 0) {
1338 if (k->type != type) {
1340 return SSH_ERR_KEY_TYPE_MISMATCH;
1342 if (sshkey_type_plain(type) == KEY_ECDSA &&
1343 curve_nid != k->ecdsa_nid) {
1345 return SSH_ERR_EC_CURVE_MISMATCH;
1348 if (sshkey_is_cert(ret)) {
1349 if (!sshkey_is_cert(k)) {
1351 return SSH_ERR_EXPECTED_CERT;
1353 if (ret->cert != NULL)
1354 cert_free(ret->cert);
1355 ret->cert = k->cert;
1359 if (sshkey_type_plain(ret->type) == KEY_RSA) {
1360 if (ret->rsa != NULL)
1365 RSA_print_fp(stderr, ret->rsa, 8);
1368 if (sshkey_type_plain(ret->type) == KEY_DSA) {
1369 if (ret->dsa != NULL)
1374 DSA_print_fp(stderr, ret->dsa, 8);
1377 # ifdef OPENSSL_HAS_ECC
1378 if (sshkey_type_plain(ret->type) == KEY_ECDSA) {
1379 if (ret->ecdsa != NULL)
1380 EC_KEY_free(ret->ecdsa);
1381 ret->ecdsa = k->ecdsa;
1382 ret->ecdsa_nid = k->ecdsa_nid;
1386 sshkey_dump_ec_key(ret->ecdsa);
1389 # endif /* OPENSSL_HAS_ECC */
1390 #endif /* WITH_OPENSSL */
1391 if (sshkey_type_plain(ret->type) == KEY_ED25519) {
1392 free(ret->ed25519_pk);
1393 ret->ed25519_pk = k->ed25519_pk;
1394 k->ed25519_pk = NULL;
1406 return SSH_ERR_INVALID_ARGUMENT;
1412 sshkey_write(const struct sshkey *key, FILE *f)
1414 int ret = SSH_ERR_INTERNAL_ERROR;
1415 struct sshbuf *b = NULL, *bb = NULL;
1419 char *dec_e = NULL, *dec_n = NULL;
1420 #endif /* WITH_SSH1 */
1422 if (sshkey_is_cert(key)) {
1423 if (key->cert == NULL)
1424 return SSH_ERR_EXPECTED_CERT;
1425 if (sshbuf_len(key->cert->certblob) == 0)
1426 return SSH_ERR_KEY_LACKS_CERTBLOB;
1428 if ((b = sshbuf_new()) == NULL)
1429 return SSH_ERR_ALLOC_FAIL;
1430 switch (key->type) {
1433 if (key->rsa == NULL || key->rsa->e == NULL ||
1434 key->rsa->n == NULL) {
1435 ret = SSH_ERR_INVALID_ARGUMENT;
1438 if ((dec_e = BN_bn2dec(key->rsa->e)) == NULL ||
1439 (dec_n = BN_bn2dec(key->rsa->n)) == NULL) {
1440 ret = SSH_ERR_ALLOC_FAIL;
1443 /* size of modulus 'n' */
1444 if ((bits = BN_num_bits(key->rsa->n)) <= 0) {
1445 ret = SSH_ERR_INVALID_ARGUMENT;
1448 if ((ret = sshbuf_putf(b, "%u %s %s", bits, dec_e, dec_n)) != 0)
1450 #endif /* WITH_SSH1 */
1454 case KEY_DSA_CERT_V00:
1457 case KEY_ECDSA_CERT:
1459 case KEY_RSA_CERT_V00:
1461 #endif /* WITH_OPENSSL */
1463 case KEY_ED25519_CERT:
1464 if ((bb = sshbuf_new()) == NULL) {
1465 ret = SSH_ERR_ALLOC_FAIL;
1468 if ((ret = sshkey_putb(key, bb)) != 0)
1470 if ((uu = sshbuf_dtob64(bb)) == NULL) {
1471 ret = SSH_ERR_ALLOC_FAIL;
1474 if ((ret = sshbuf_putf(b, "%s ", sshkey_ssh_name(key))) != 0)
1476 if ((ret = sshbuf_put(b, uu, strlen(uu))) != 0)
1480 ret = SSH_ERR_KEY_TYPE_UNKNOWN;
1483 if (fwrite(sshbuf_ptr(b), sshbuf_len(b), 1, f) != 1) {
1486 ret = SSH_ERR_SYSTEM_ERROR;
1499 OPENSSL_free(dec_e);
1501 OPENSSL_free(dec_n);
1502 #endif /* WITH_SSH1 */
1507 sshkey_cert_type(const struct sshkey *k)
1509 switch (k->cert->type) {
1510 case SSH2_CERT_TYPE_USER:
1512 case SSH2_CERT_TYPE_HOST:
1521 rsa_generate_private_key(u_int bits, RSA **rsap)
1523 RSA *private = NULL;
1525 int ret = SSH_ERR_INTERNAL_ERROR;
1528 bits < SSH_RSA_MINIMUM_MODULUS_SIZE ||
1529 bits > SSHBUF_MAX_BIGNUM * 8)
1530 return SSH_ERR_INVALID_ARGUMENT;
1532 if ((private = RSA_new()) == NULL || (f4 = BN_new()) == NULL) {
1533 ret = SSH_ERR_ALLOC_FAIL;
1536 if (!BN_set_word(f4, RSA_F4) ||
1537 !RSA_generate_key_ex(private, bits, f4, NULL)) {
1538 ret = SSH_ERR_LIBCRYPTO_ERROR;
1545 if (private != NULL)
1553 dsa_generate_private_key(u_int bits, DSA **dsap)
1556 int ret = SSH_ERR_INTERNAL_ERROR;
1558 if (dsap == NULL || bits != 1024)
1559 return SSH_ERR_INVALID_ARGUMENT;
1560 if ((private = DSA_new()) == NULL) {
1561 ret = SSH_ERR_ALLOC_FAIL;
1565 if (!DSA_generate_parameters_ex(private, bits, NULL, 0, NULL,
1566 NULL, NULL) || !DSA_generate_key(private)) {
1568 ret = SSH_ERR_LIBCRYPTO_ERROR;
1575 if (private != NULL)
1580 # ifdef OPENSSL_HAS_ECC
1582 sshkey_ecdsa_key_to_nid(EC_KEY *k)
1586 NID_X9_62_prime256v1,
1588 # ifdef OPENSSL_HAS_NISTP521
1590 # endif /* OPENSSL_HAS_NISTP521 */
1596 const EC_GROUP *g = EC_KEY_get0_group(k);
1599 * The group may be stored in a ASN.1 encoded private key in one of two
1600 * ways: as a "named group", which is reconstituted by ASN.1 object ID
1601 * or explicit group parameters encoded into the key blob. Only the
1602 * "named group" case sets the group NID for us, but we can figure
1603 * it out for the other case by comparing against all the groups that
1606 if ((nid = EC_GROUP_get_curve_name(g)) > 0)
1608 if ((bnctx = BN_CTX_new()) == NULL)
1610 for (i = 0; nids[i] != -1; i++) {
1611 if ((eg = EC_GROUP_new_by_curve_name(nids[i])) == NULL) {
1615 if (EC_GROUP_cmp(g, eg, bnctx) == 0)
1620 if (nids[i] != -1) {
1621 /* Use the group with the NID attached */
1622 EC_GROUP_set_asn1_flag(eg, OPENSSL_EC_NAMED_CURVE);
1623 if (EC_KEY_set_group(k, eg) != 1) {
1632 ecdsa_generate_private_key(u_int bits, int *nid, EC_KEY **ecdsap)
1635 int ret = SSH_ERR_INTERNAL_ERROR;
1637 if (nid == NULL || ecdsap == NULL ||
1638 (*nid = sshkey_ecdsa_bits_to_nid(bits)) == -1)
1639 return SSH_ERR_INVALID_ARGUMENT;
1641 if ((private = EC_KEY_new_by_curve_name(*nid)) == NULL) {
1642 ret = SSH_ERR_ALLOC_FAIL;
1645 if (EC_KEY_generate_key(private) != 1) {
1646 ret = SSH_ERR_LIBCRYPTO_ERROR;
1649 EC_KEY_set_asn1_flag(private, OPENSSL_EC_NAMED_CURVE);
1654 if (private != NULL)
1655 EC_KEY_free(private);
1658 # endif /* OPENSSL_HAS_ECC */
1659 #endif /* WITH_OPENSSL */
1662 sshkey_generate(int type, u_int bits, struct sshkey **keyp)
1665 int ret = SSH_ERR_INTERNAL_ERROR;
1668 return SSH_ERR_INVALID_ARGUMENT;
1670 if ((k = sshkey_new(KEY_UNSPEC)) == NULL)
1671 return SSH_ERR_ALLOC_FAIL;
1674 if ((k->ed25519_pk = malloc(ED25519_PK_SZ)) == NULL ||
1675 (k->ed25519_sk = malloc(ED25519_SK_SZ)) == NULL) {
1676 ret = SSH_ERR_ALLOC_FAIL;
1679 crypto_sign_ed25519_keypair(k->ed25519_pk, k->ed25519_sk);
1684 ret = dsa_generate_private_key(bits, &k->dsa);
1686 # ifdef OPENSSL_HAS_ECC
1688 ret = ecdsa_generate_private_key(bits, &k->ecdsa_nid,
1691 # endif /* OPENSSL_HAS_ECC */
1694 ret = rsa_generate_private_key(bits, &k->rsa);
1696 #endif /* WITH_OPENSSL */
1698 ret = SSH_ERR_INVALID_ARGUMENT;
1709 sshkey_cert_copy(const struct sshkey *from_key, struct sshkey *to_key)
1712 const struct sshkey_cert *from;
1713 struct sshkey_cert *to;
1714 int ret = SSH_ERR_INTERNAL_ERROR;
1716 if (to_key->cert != NULL) {
1717 cert_free(to_key->cert);
1718 to_key->cert = NULL;
1721 if ((from = from_key->cert) == NULL)
1722 return SSH_ERR_INVALID_ARGUMENT;
1724 if ((to = to_key->cert = cert_new()) == NULL)
1725 return SSH_ERR_ALLOC_FAIL;
1727 if ((ret = sshbuf_putb(to->certblob, from->certblob)) != 0 ||
1728 (ret = sshbuf_putb(to->critical, from->critical)) != 0 ||
1729 (ret = sshbuf_putb(to->extensions, from->extensions) != 0))
1732 to->serial = from->serial;
1733 to->type = from->type;
1734 if (from->key_id == NULL)
1736 else if ((to->key_id = strdup(from->key_id)) == NULL)
1737 return SSH_ERR_ALLOC_FAIL;
1738 to->valid_after = from->valid_after;
1739 to->valid_before = from->valid_before;
1740 if (from->signature_key == NULL)
1741 to->signature_key = NULL;
1742 else if ((ret = sshkey_from_private(from->signature_key,
1743 &to->signature_key)) != 0)
1746 if (from->nprincipals > SSHKEY_CERT_MAX_PRINCIPALS)
1747 return SSH_ERR_INVALID_ARGUMENT;
1748 if (from->nprincipals > 0) {
1749 if ((to->principals = calloc(from->nprincipals,
1750 sizeof(*to->principals))) == NULL)
1751 return SSH_ERR_ALLOC_FAIL;
1752 for (i = 0; i < from->nprincipals; i++) {
1753 to->principals[i] = strdup(from->principals[i]);
1754 if (to->principals[i] == NULL) {
1755 to->nprincipals = i;
1756 return SSH_ERR_ALLOC_FAIL;
1760 to->nprincipals = from->nprincipals;
1765 sshkey_from_private(const struct sshkey *k, struct sshkey **pkp)
1767 struct sshkey *n = NULL;
1768 int ret = SSH_ERR_INTERNAL_ERROR;
1776 case KEY_DSA_CERT_V00:
1778 if ((n = sshkey_new(k->type)) == NULL)
1779 return SSH_ERR_ALLOC_FAIL;
1780 if ((BN_copy(n->dsa->p, k->dsa->p) == NULL) ||
1781 (BN_copy(n->dsa->q, k->dsa->q) == NULL) ||
1782 (BN_copy(n->dsa->g, k->dsa->g) == NULL) ||
1783 (BN_copy(n->dsa->pub_key, k->dsa->pub_key) == NULL)) {
1785 return SSH_ERR_ALLOC_FAIL;
1788 # ifdef OPENSSL_HAS_ECC
1790 case KEY_ECDSA_CERT:
1791 if ((n = sshkey_new(k->type)) == NULL)
1792 return SSH_ERR_ALLOC_FAIL;
1793 n->ecdsa_nid = k->ecdsa_nid;
1794 n->ecdsa = EC_KEY_new_by_curve_name(k->ecdsa_nid);
1795 if (n->ecdsa == NULL) {
1797 return SSH_ERR_ALLOC_FAIL;
1799 if (EC_KEY_set_public_key(n->ecdsa,
1800 EC_KEY_get0_public_key(k->ecdsa)) != 1) {
1802 return SSH_ERR_LIBCRYPTO_ERROR;
1805 # endif /* OPENSSL_HAS_ECC */
1808 case KEY_RSA_CERT_V00:
1810 if ((n = sshkey_new(k->type)) == NULL)
1811 return SSH_ERR_ALLOC_FAIL;
1812 if ((BN_copy(n->rsa->n, k->rsa->n) == NULL) ||
1813 (BN_copy(n->rsa->e, k->rsa->e) == NULL)) {
1815 return SSH_ERR_ALLOC_FAIL;
1818 #endif /* WITH_OPENSSL */
1820 case KEY_ED25519_CERT:
1821 if ((n = sshkey_new(k->type)) == NULL)
1822 return SSH_ERR_ALLOC_FAIL;
1823 if (k->ed25519_pk != NULL) {
1824 if ((n->ed25519_pk = malloc(ED25519_PK_SZ)) == NULL) {
1826 return SSH_ERR_ALLOC_FAIL;
1828 memcpy(n->ed25519_pk, k->ed25519_pk, ED25519_PK_SZ);
1832 return SSH_ERR_KEY_TYPE_UNKNOWN;
1834 if (sshkey_is_cert(k)) {
1835 if ((ret = sshkey_cert_copy(k, n)) != 0) {
1845 cert_parse(struct sshbuf *b, struct sshkey *key, struct sshbuf *certbuf)
1847 struct sshbuf *principals = NULL, *crit = NULL;
1848 struct sshbuf *exts = NULL, *ca = NULL;
1850 size_t signed_len = 0, slen = 0, kidlen = 0;
1851 int ret = SSH_ERR_INTERNAL_ERROR;
1852 int v00 = sshkey_cert_is_legacy(key);
1854 /* Copy the entire key blob for verification and later serialisation */
1855 if ((ret = sshbuf_putb(key->cert->certblob, certbuf)) != 0)
1858 if ((!v00 && (ret = sshbuf_get_u64(b, &key->cert->serial)) != 0) ||
1859 (ret = sshbuf_get_u32(b, &key->cert->type)) != 0 ||
1860 (ret = sshbuf_get_cstring(b, &key->cert->key_id, &kidlen)) != 0 ||
1861 (ret = sshbuf_froms(b, &principals)) != 0 ||
1862 (ret = sshbuf_get_u64(b, &key->cert->valid_after)) != 0 ||
1863 (ret = sshbuf_get_u64(b, &key->cert->valid_before)) != 0 ||
1864 (ret = sshbuf_froms(b, &crit)) != 0 ||
1865 (!v00 && (ret = sshbuf_froms(b, &exts)) != 0) ||
1866 (v00 && (ret = sshbuf_get_string_direct(b, NULL, NULL)) != 0) ||
1867 (ret = sshbuf_get_string_direct(b, NULL, NULL)) != 0 ||
1868 (ret = sshbuf_froms(b, &ca)) != 0) {
1869 /* XXX debug print error for ret */
1870 ret = SSH_ERR_INVALID_FORMAT;
1874 /* Signature is left in the buffer so we can calculate this length */
1875 signed_len = sshbuf_len(key->cert->certblob) - sshbuf_len(b);
1877 if ((ret = sshbuf_get_string(b, &sig, &slen)) != 0) {
1878 ret = SSH_ERR_INVALID_FORMAT;
1882 if (key->cert->type != SSH2_CERT_TYPE_USER &&
1883 key->cert->type != SSH2_CERT_TYPE_HOST) {
1884 ret = SSH_ERR_KEY_CERT_UNKNOWN_TYPE;
1888 /* Parse principals section */
1889 while (sshbuf_len(principals) > 0) {
1890 char *principal = NULL;
1891 char **oprincipals = NULL;
1893 if (key->cert->nprincipals >= SSHKEY_CERT_MAX_PRINCIPALS) {
1894 ret = SSH_ERR_INVALID_FORMAT;
1897 if ((ret = sshbuf_get_cstring(principals, &principal,
1899 ret = SSH_ERR_INVALID_FORMAT;
1902 oprincipals = key->cert->principals;
1903 key->cert->principals = realloc(key->cert->principals,
1904 (key->cert->nprincipals + 1) *
1905 sizeof(*key->cert->principals));
1906 if (key->cert->principals == NULL) {
1908 key->cert->principals = oprincipals;
1909 ret = SSH_ERR_ALLOC_FAIL;
1912 key->cert->principals[key->cert->nprincipals++] = principal;
1916 * Stash a copies of the critical options and extensions sections
1919 if ((ret = sshbuf_putb(key->cert->critical, crit)) != 0 ||
1921 (ret = sshbuf_putb(key->cert->extensions, exts)) != 0))
1925 * Validate critical options and extensions sections format.
1926 * NB. extensions are not present in v00 certs.
1928 while (sshbuf_len(crit) != 0) {
1929 if ((ret = sshbuf_get_string_direct(crit, NULL, NULL)) != 0 ||
1930 (ret = sshbuf_get_string_direct(crit, NULL, NULL)) != 0) {
1931 sshbuf_reset(key->cert->critical);
1932 ret = SSH_ERR_INVALID_FORMAT;
1936 while (exts != NULL && sshbuf_len(exts) != 0) {
1937 if ((ret = sshbuf_get_string_direct(exts, NULL, NULL)) != 0 ||
1938 (ret = sshbuf_get_string_direct(exts, NULL, NULL)) != 0) {
1939 sshbuf_reset(key->cert->extensions);
1940 ret = SSH_ERR_INVALID_FORMAT;
1945 /* Parse CA key and check signature */
1946 if (sshkey_from_blob_internal(ca, &key->cert->signature_key, 0) != 0) {
1947 ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
1950 if (!sshkey_type_is_valid_ca(key->cert->signature_key->type)) {
1951 ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
1954 if ((ret = sshkey_verify(key->cert->signature_key, sig, slen,
1955 sshbuf_ptr(key->cert->certblob), signed_len, 0)) != 0)
1964 sshbuf_free(principals);
1970 sshkey_from_blob_internal(struct sshbuf *b, struct sshkey **keyp,
1973 int type, ret = SSH_ERR_INTERNAL_ERROR;
1974 char *ktype = NULL, *curve = NULL;
1975 struct sshkey *key = NULL;
1978 struct sshbuf *copy;
1979 #if defined(WITH_OPENSSL) && defined(OPENSSL_HAS_ECC)
1981 #endif /* WITH_OPENSSL && OPENSSL_HAS_ECC */
1983 #ifdef DEBUG_PK /* XXX */
1984 sshbuf_dump(b, stderr);
1987 if ((copy = sshbuf_fromb(b)) == NULL) {
1988 ret = SSH_ERR_ALLOC_FAIL;
1991 if (sshbuf_get_cstring(b, &ktype, NULL) != 0) {
1992 ret = SSH_ERR_INVALID_FORMAT;
1996 type = sshkey_type_from_name(ktype);
1997 if (!allow_cert && sshkey_type_is_cert(type)) {
1998 ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
2005 if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
2006 ret = SSH_ERR_INVALID_FORMAT;
2011 case KEY_RSA_CERT_V00:
2012 if ((key = sshkey_new(type)) == NULL) {
2013 ret = SSH_ERR_ALLOC_FAIL;
2016 if (sshbuf_get_bignum2(b, key->rsa->e) == -1 ||
2017 sshbuf_get_bignum2(b, key->rsa->n) == -1) {
2018 ret = SSH_ERR_INVALID_FORMAT;
2022 RSA_print_fp(stderr, key->rsa, 8);
2027 if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
2028 ret = SSH_ERR_INVALID_FORMAT;
2033 case KEY_DSA_CERT_V00:
2034 if ((key = sshkey_new(type)) == NULL) {
2035 ret = SSH_ERR_ALLOC_FAIL;
2038 if (sshbuf_get_bignum2(b, key->dsa->p) == -1 ||
2039 sshbuf_get_bignum2(b, key->dsa->q) == -1 ||
2040 sshbuf_get_bignum2(b, key->dsa->g) == -1 ||
2041 sshbuf_get_bignum2(b, key->dsa->pub_key) == -1) {
2042 ret = SSH_ERR_INVALID_FORMAT;
2046 DSA_print_fp(stderr, key->dsa, 8);
2049 case KEY_ECDSA_CERT:
2051 if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
2052 ret = SSH_ERR_INVALID_FORMAT;
2056 # ifdef OPENSSL_HAS_ECC
2058 if ((key = sshkey_new(type)) == NULL) {
2059 ret = SSH_ERR_ALLOC_FAIL;
2062 key->ecdsa_nid = sshkey_ecdsa_nid_from_name(ktype);
2063 if (sshbuf_get_cstring(b, &curve, NULL) != 0) {
2064 ret = SSH_ERR_INVALID_FORMAT;
2067 if (key->ecdsa_nid != sshkey_curve_name_to_nid(curve)) {
2068 ret = SSH_ERR_EC_CURVE_MISMATCH;
2071 if (key->ecdsa != NULL)
2072 EC_KEY_free(key->ecdsa);
2073 if ((key->ecdsa = EC_KEY_new_by_curve_name(key->ecdsa_nid))
2075 ret = SSH_ERR_EC_CURVE_INVALID;
2078 if ((q = EC_POINT_new(EC_KEY_get0_group(key->ecdsa))) == NULL) {
2079 ret = SSH_ERR_ALLOC_FAIL;
2082 if (sshbuf_get_ec(b, q, EC_KEY_get0_group(key->ecdsa)) != 0) {
2083 ret = SSH_ERR_INVALID_FORMAT;
2086 if (sshkey_ec_validate_public(EC_KEY_get0_group(key->ecdsa),
2088 ret = SSH_ERR_KEY_INVALID_EC_VALUE;
2091 if (EC_KEY_set_public_key(key->ecdsa, q) != 1) {
2092 /* XXX assume it is a allocation error */
2093 ret = SSH_ERR_ALLOC_FAIL;
2097 sshkey_dump_ec_point(EC_KEY_get0_group(key->ecdsa), q);
2100 # endif /* OPENSSL_HAS_ECC */
2101 #endif /* WITH_OPENSSL */
2102 case KEY_ED25519_CERT:
2104 if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
2105 ret = SSH_ERR_INVALID_FORMAT;
2110 if ((ret = sshbuf_get_string(b, &pk, &len)) != 0)
2112 if (len != ED25519_PK_SZ) {
2113 ret = SSH_ERR_INVALID_FORMAT;
2116 if ((key = sshkey_new(type)) == NULL) {
2117 ret = SSH_ERR_ALLOC_FAIL;
2120 key->ed25519_pk = pk;
2124 if ((key = sshkey_new(type)) == NULL) {
2125 ret = SSH_ERR_ALLOC_FAIL;
2130 ret = SSH_ERR_KEY_TYPE_UNKNOWN;
2134 /* Parse certificate potion */
2135 if (sshkey_is_cert(key) && (ret = cert_parse(b, key, copy)) != 0)
2138 if (key != NULL && sshbuf_len(b) != 0) {
2139 ret = SSH_ERR_INVALID_FORMAT;
2151 #if defined(WITH_OPENSSL) && defined(OPENSSL_HAS_ECC)
2154 #endif /* WITH_OPENSSL && OPENSSL_HAS_ECC */
2159 sshkey_from_blob(const u_char *blob, size_t blen, struct sshkey **keyp)
2164 if ((b = sshbuf_from(blob, blen)) == NULL)
2165 return SSH_ERR_ALLOC_FAIL;
2166 r = sshkey_from_blob_internal(b, keyp, 1);
2172 sshkey_fromb(struct sshbuf *b, struct sshkey **keyp)
2174 return sshkey_from_blob_internal(b, keyp, 1);
2178 sshkey_froms(struct sshbuf *buf, struct sshkey **keyp)
2183 if ((r = sshbuf_froms(buf, &b)) != 0)
2185 r = sshkey_from_blob_internal(b, keyp, 1);
2191 sshkey_sign(const struct sshkey *key,
2192 u_char **sigp, size_t *lenp,
2193 const u_char *data, size_t datalen, u_int compat)
2199 if (datalen > SSH_KEY_MAX_SIGN_DATA_SIZE)
2200 return SSH_ERR_INVALID_ARGUMENT;
2201 switch (key->type) {
2203 case KEY_DSA_CERT_V00:
2206 return ssh_dss_sign(key, sigp, lenp, data, datalen, compat);
2207 # ifdef OPENSSL_HAS_ECC
2208 case KEY_ECDSA_CERT:
2210 return ssh_ecdsa_sign(key, sigp, lenp, data, datalen, compat);
2211 # endif /* OPENSSL_HAS_ECC */
2212 case KEY_RSA_CERT_V00:
2215 return ssh_rsa_sign(key, sigp, lenp, data, datalen, compat);
2216 #endif /* WITH_OPENSSL */
2218 case KEY_ED25519_CERT:
2219 return ssh_ed25519_sign(key, sigp, lenp, data, datalen, compat);
2221 return SSH_ERR_KEY_TYPE_UNKNOWN;
2226 * ssh_key_verify returns 0 for a correct signature and < 0 on error.
2229 sshkey_verify(const struct sshkey *key,
2230 const u_char *sig, size_t siglen,
2231 const u_char *data, size_t dlen, u_int compat)
2233 if (siglen == 0 || dlen > SSH_KEY_MAX_SIGN_DATA_SIZE)
2234 return SSH_ERR_INVALID_ARGUMENT;
2235 switch (key->type) {
2237 case KEY_DSA_CERT_V00:
2240 return ssh_dss_verify(key, sig, siglen, data, dlen, compat);
2241 # ifdef OPENSSL_HAS_ECC
2242 case KEY_ECDSA_CERT:
2244 return ssh_ecdsa_verify(key, sig, siglen, data, dlen, compat);
2245 # endif /* OPENSSL_HAS_ECC */
2246 case KEY_RSA_CERT_V00:
2249 return ssh_rsa_verify(key, sig, siglen, data, dlen, compat);
2250 #endif /* WITH_OPENSSL */
2252 case KEY_ED25519_CERT:
2253 return ssh_ed25519_verify(key, sig, siglen, data, dlen, compat);
2255 return SSH_ERR_KEY_TYPE_UNKNOWN;
2259 /* Converts a private to a public key */
2261 sshkey_demote(const struct sshkey *k, struct sshkey **dkp)
2264 int ret = SSH_ERR_INTERNAL_ERROR;
2269 if ((pk = calloc(1, sizeof(*pk))) == NULL)
2270 return SSH_ERR_ALLOC_FAIL;
2272 pk->flags = k->flags;
2273 pk->ecdsa_nid = k->ecdsa_nid;
2277 pk->ed25519_pk = NULL;
2278 pk->ed25519_sk = NULL;
2282 case KEY_RSA_CERT_V00:
2284 if ((ret = sshkey_cert_copy(k, pk)) != 0)
2289 if ((pk->rsa = RSA_new()) == NULL ||
2290 (pk->rsa->e = BN_dup(k->rsa->e)) == NULL ||
2291 (pk->rsa->n = BN_dup(k->rsa->n)) == NULL) {
2292 ret = SSH_ERR_ALLOC_FAIL;
2296 case KEY_DSA_CERT_V00:
2298 if ((ret = sshkey_cert_copy(k, pk)) != 0)
2302 if ((pk->dsa = DSA_new()) == NULL ||
2303 (pk->dsa->p = BN_dup(k->dsa->p)) == NULL ||
2304 (pk->dsa->q = BN_dup(k->dsa->q)) == NULL ||
2305 (pk->dsa->g = BN_dup(k->dsa->g)) == NULL ||
2306 (pk->dsa->pub_key = BN_dup(k->dsa->pub_key)) == NULL) {
2307 ret = SSH_ERR_ALLOC_FAIL;
2311 case KEY_ECDSA_CERT:
2312 if ((ret = sshkey_cert_copy(k, pk)) != 0)
2315 # ifdef OPENSSL_HAS_ECC
2317 pk->ecdsa = EC_KEY_new_by_curve_name(pk->ecdsa_nid);
2318 if (pk->ecdsa == NULL) {
2319 ret = SSH_ERR_ALLOC_FAIL;
2322 if (EC_KEY_set_public_key(pk->ecdsa,
2323 EC_KEY_get0_public_key(k->ecdsa)) != 1) {
2324 ret = SSH_ERR_LIBCRYPTO_ERROR;
2328 # endif /* OPENSSL_HAS_ECC */
2329 #endif /* WITH_OPENSSL */
2330 case KEY_ED25519_CERT:
2331 if ((ret = sshkey_cert_copy(k, pk)) != 0)
2335 if (k->ed25519_pk != NULL) {
2336 if ((pk->ed25519_pk = malloc(ED25519_PK_SZ)) == NULL) {
2337 ret = SSH_ERR_ALLOC_FAIL;
2340 memcpy(pk->ed25519_pk, k->ed25519_pk, ED25519_PK_SZ);
2344 ret = SSH_ERR_KEY_TYPE_UNKNOWN;
2353 /* Convert a plain key to their _CERT equivalent */
2355 sshkey_to_certified(struct sshkey *k, int legacy)
2362 newtype = legacy ? KEY_RSA_CERT_V00 : KEY_RSA_CERT;
2365 newtype = legacy ? KEY_DSA_CERT_V00 : KEY_DSA_CERT;
2369 return SSH_ERR_INVALID_ARGUMENT;
2370 newtype = KEY_ECDSA_CERT;
2372 #endif /* WITH_OPENSSL */
2375 return SSH_ERR_INVALID_ARGUMENT;
2376 newtype = KEY_ED25519_CERT;
2379 return SSH_ERR_INVALID_ARGUMENT;
2381 if ((k->cert = cert_new()) == NULL)
2382 return SSH_ERR_ALLOC_FAIL;
2387 /* Convert a certificate to its raw key equivalent */
2389 sshkey_drop_cert(struct sshkey *k)
2391 if (!sshkey_type_is_cert(k->type))
2392 return SSH_ERR_KEY_TYPE_UNKNOWN;
2395 k->type = sshkey_type_plain(k->type);
2399 /* Sign a certified key, (re-)generating the signed certblob. */
2401 sshkey_certify(struct sshkey *k, struct sshkey *ca)
2403 struct sshbuf *principals = NULL;
2404 u_char *ca_blob = NULL, *sig_blob = NULL, nonce[32];
2405 size_t i, ca_len, sig_len;
2406 int ret = SSH_ERR_INTERNAL_ERROR;
2407 struct sshbuf *cert;
2409 if (k == NULL || k->cert == NULL ||
2410 k->cert->certblob == NULL || ca == NULL)
2411 return SSH_ERR_INVALID_ARGUMENT;
2412 if (!sshkey_is_cert(k))
2413 return SSH_ERR_KEY_TYPE_UNKNOWN;
2414 if (!sshkey_type_is_valid_ca(ca->type))
2415 return SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
2417 if ((ret = sshkey_to_blob(ca, &ca_blob, &ca_len)) != 0)
2418 return SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
2420 cert = k->cert->certblob; /* for readability */
2422 if ((ret = sshbuf_put_cstring(cert, sshkey_ssh_name(k))) != 0)
2425 /* -v01 certs put nonce first */
2426 arc4random_buf(&nonce, sizeof(nonce));
2427 if (!sshkey_cert_is_legacy(k)) {
2428 if ((ret = sshbuf_put_string(cert, nonce, sizeof(nonce))) != 0)
2432 /* XXX this substantially duplicates to_blob(); refactor */
2435 case KEY_DSA_CERT_V00:
2437 if ((ret = sshbuf_put_bignum2(cert, k->dsa->p)) != 0 ||
2438 (ret = sshbuf_put_bignum2(cert, k->dsa->q)) != 0 ||
2439 (ret = sshbuf_put_bignum2(cert, k->dsa->g)) != 0 ||
2440 (ret = sshbuf_put_bignum2(cert, k->dsa->pub_key)) != 0)
2443 # ifdef OPENSSL_HAS_ECC
2444 case KEY_ECDSA_CERT:
2445 if ((ret = sshbuf_put_cstring(cert,
2446 sshkey_curve_nid_to_name(k->ecdsa_nid))) != 0 ||
2447 (ret = sshbuf_put_ec(cert,
2448 EC_KEY_get0_public_key(k->ecdsa),
2449 EC_KEY_get0_group(k->ecdsa))) != 0)
2452 # endif /* OPENSSL_HAS_ECC */
2453 case KEY_RSA_CERT_V00:
2455 if ((ret = sshbuf_put_bignum2(cert, k->rsa->e)) != 0 ||
2456 (ret = sshbuf_put_bignum2(cert, k->rsa->n)) != 0)
2459 #endif /* WITH_OPENSSL */
2460 case KEY_ED25519_CERT:
2461 if ((ret = sshbuf_put_string(cert,
2462 k->ed25519_pk, ED25519_PK_SZ)) != 0)
2466 ret = SSH_ERR_INVALID_ARGUMENT;
2470 /* -v01 certs have a serial number next */
2471 if (!sshkey_cert_is_legacy(k)) {
2472 if ((ret = sshbuf_put_u64(cert, k->cert->serial)) != 0)
2476 if ((ret = sshbuf_put_u32(cert, k->cert->type)) != 0 ||
2477 (ret = sshbuf_put_cstring(cert, k->cert->key_id)) != 0)
2480 if ((principals = sshbuf_new()) == NULL) {
2481 ret = SSH_ERR_ALLOC_FAIL;
2484 for (i = 0; i < k->cert->nprincipals; i++) {
2485 if ((ret = sshbuf_put_cstring(principals,
2486 k->cert->principals[i])) != 0)
2489 if ((ret = sshbuf_put_stringb(cert, principals)) != 0 ||
2490 (ret = sshbuf_put_u64(cert, k->cert->valid_after)) != 0 ||
2491 (ret = sshbuf_put_u64(cert, k->cert->valid_before)) != 0 ||
2492 (ret = sshbuf_put_stringb(cert, k->cert->critical)) != 0)
2495 /* -v01 certs have non-critical options here */
2496 if (!sshkey_cert_is_legacy(k)) {
2497 if ((ret = sshbuf_put_stringb(cert, k->cert->extensions)) != 0)
2501 /* -v00 certs put the nonce at the end */
2502 if (sshkey_cert_is_legacy(k)) {
2503 if ((ret = sshbuf_put_string(cert, nonce, sizeof(nonce))) != 0)
2507 if ((ret = sshbuf_put_string(cert, NULL, 0)) != 0 || /* Reserved */
2508 (ret = sshbuf_put_string(cert, ca_blob, ca_len)) != 0)
2511 /* Sign the whole mess */
2512 if ((ret = sshkey_sign(ca, &sig_blob, &sig_len, sshbuf_ptr(cert),
2513 sshbuf_len(cert), 0)) != 0)
2516 /* Append signature and we are done */
2517 if ((ret = sshbuf_put_string(cert, sig_blob, sig_len)) != 0)
2523 if (sig_blob != NULL)
2525 if (ca_blob != NULL)
2527 if (principals != NULL)
2528 sshbuf_free(principals);
2533 sshkey_cert_check_authority(const struct sshkey *k,
2534 int want_host, int require_principal,
2535 const char *name, const char **reason)
2537 u_int i, principal_matches;
2538 time_t now = time(NULL);
2544 if (k->cert->type != SSH2_CERT_TYPE_HOST) {
2545 *reason = "Certificate invalid: not a host certificate";
2546 return SSH_ERR_KEY_CERT_INVALID;
2549 if (k->cert->type != SSH2_CERT_TYPE_USER) {
2550 *reason = "Certificate invalid: not a user certificate";
2551 return SSH_ERR_KEY_CERT_INVALID;
2555 /* yikes - system clock before epoch! */
2556 *reason = "Certificate invalid: not yet valid";
2557 return SSH_ERR_KEY_CERT_INVALID;
2559 if ((u_int64_t)now < k->cert->valid_after) {
2560 *reason = "Certificate invalid: not yet valid";
2561 return SSH_ERR_KEY_CERT_INVALID;
2563 if ((u_int64_t)now >= k->cert->valid_before) {
2564 *reason = "Certificate invalid: expired";
2565 return SSH_ERR_KEY_CERT_INVALID;
2567 if (k->cert->nprincipals == 0) {
2568 if (require_principal) {
2569 *reason = "Certificate lacks principal list";
2570 return SSH_ERR_KEY_CERT_INVALID;
2572 } else if (name != NULL) {
2573 principal_matches = 0;
2574 for (i = 0; i < k->cert->nprincipals; i++) {
2575 if (strcmp(name, k->cert->principals[i]) == 0) {
2576 principal_matches = 1;
2580 if (!principal_matches) {
2581 *reason = "Certificate invalid: name is not a listed "
2583 return SSH_ERR_KEY_CERT_INVALID;
2590 sshkey_private_serialize(const struct sshkey *key, struct sshbuf *b)
2592 int r = SSH_ERR_INTERNAL_ERROR;
2594 if ((r = sshbuf_put_cstring(b, sshkey_ssh_name(key))) != 0)
2596 switch (key->type) {
2599 if ((r = sshbuf_put_bignum2(b, key->rsa->n)) != 0 ||
2600 (r = sshbuf_put_bignum2(b, key->rsa->e)) != 0 ||
2601 (r = sshbuf_put_bignum2(b, key->rsa->d)) != 0 ||
2602 (r = sshbuf_put_bignum2(b, key->rsa->iqmp)) != 0 ||
2603 (r = sshbuf_put_bignum2(b, key->rsa->p)) != 0 ||
2604 (r = sshbuf_put_bignum2(b, key->rsa->q)) != 0)
2607 case KEY_RSA_CERT_V00:
2609 if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
2610 r = SSH_ERR_INVALID_ARGUMENT;
2613 if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
2614 (r = sshbuf_put_bignum2(b, key->rsa->d)) != 0 ||
2615 (r = sshbuf_put_bignum2(b, key->rsa->iqmp)) != 0 ||
2616 (r = sshbuf_put_bignum2(b, key->rsa->p)) != 0 ||
2617 (r = sshbuf_put_bignum2(b, key->rsa->q)) != 0)
2621 if ((r = sshbuf_put_bignum2(b, key->dsa->p)) != 0 ||
2622 (r = sshbuf_put_bignum2(b, key->dsa->q)) != 0 ||
2623 (r = sshbuf_put_bignum2(b, key->dsa->g)) != 0 ||
2624 (r = sshbuf_put_bignum2(b, key->dsa->pub_key)) != 0 ||
2625 (r = sshbuf_put_bignum2(b, key->dsa->priv_key)) != 0)
2628 case KEY_DSA_CERT_V00:
2630 if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
2631 r = SSH_ERR_INVALID_ARGUMENT;
2634 if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
2635 (r = sshbuf_put_bignum2(b, key->dsa->priv_key)) != 0)
2638 # ifdef OPENSSL_HAS_ECC
2640 if ((r = sshbuf_put_cstring(b,
2641 sshkey_curve_nid_to_name(key->ecdsa_nid))) != 0 ||
2642 (r = sshbuf_put_eckey(b, key->ecdsa)) != 0 ||
2643 (r = sshbuf_put_bignum2(b,
2644 EC_KEY_get0_private_key(key->ecdsa))) != 0)
2647 case KEY_ECDSA_CERT:
2648 if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
2649 r = SSH_ERR_INVALID_ARGUMENT;
2652 if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
2653 (r = sshbuf_put_bignum2(b,
2654 EC_KEY_get0_private_key(key->ecdsa))) != 0)
2657 # endif /* OPENSSL_HAS_ECC */
2658 #endif /* WITH_OPENSSL */
2660 if ((r = sshbuf_put_string(b, key->ed25519_pk,
2661 ED25519_PK_SZ)) != 0 ||
2662 (r = sshbuf_put_string(b, key->ed25519_sk,
2663 ED25519_SK_SZ)) != 0)
2666 case KEY_ED25519_CERT:
2667 if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
2668 r = SSH_ERR_INVALID_ARGUMENT;
2671 if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
2672 (r = sshbuf_put_string(b, key->ed25519_pk,
2673 ED25519_PK_SZ)) != 0 ||
2674 (r = sshbuf_put_string(b, key->ed25519_sk,
2675 ED25519_SK_SZ)) != 0)
2679 r = SSH_ERR_INVALID_ARGUMENT;
2689 sshkey_private_deserialize(struct sshbuf *buf, struct sshkey **kp)
2691 char *tname = NULL, *curve = NULL;
2692 struct sshkey *k = NULL;
2693 size_t pklen = 0, sklen = 0;
2694 int type, r = SSH_ERR_INTERNAL_ERROR;
2695 u_char *ed25519_pk = NULL, *ed25519_sk = NULL;
2697 BIGNUM *exponent = NULL;
2698 #endif /* WITH_OPENSSL */
2702 if ((r = sshbuf_get_cstring(buf, &tname, NULL)) != 0)
2704 type = sshkey_type_from_name(tname);
2708 if ((k = sshkey_new_private(type)) == NULL) {
2709 r = SSH_ERR_ALLOC_FAIL;
2712 if ((r = sshbuf_get_bignum2(buf, k->dsa->p)) != 0 ||
2713 (r = sshbuf_get_bignum2(buf, k->dsa->q)) != 0 ||
2714 (r = sshbuf_get_bignum2(buf, k->dsa->g)) != 0 ||
2715 (r = sshbuf_get_bignum2(buf, k->dsa->pub_key)) != 0 ||
2716 (r = sshbuf_get_bignum2(buf, k->dsa->priv_key)) != 0)
2719 case KEY_DSA_CERT_V00:
2721 if ((r = sshkey_froms(buf, &k)) != 0 ||
2722 (r = sshkey_add_private(k)) != 0 ||
2723 (r = sshbuf_get_bignum2(buf, k->dsa->priv_key)) != 0)
2726 # ifdef OPENSSL_HAS_ECC
2728 if ((k = sshkey_new_private(type)) == NULL) {
2729 r = SSH_ERR_ALLOC_FAIL;
2732 if ((k->ecdsa_nid = sshkey_ecdsa_nid_from_name(tname)) == -1) {
2733 r = SSH_ERR_INVALID_ARGUMENT;
2736 if ((r = sshbuf_get_cstring(buf, &curve, NULL)) != 0)
2738 if (k->ecdsa_nid != sshkey_curve_name_to_nid(curve)) {
2739 r = SSH_ERR_EC_CURVE_MISMATCH;
2742 k->ecdsa = EC_KEY_new_by_curve_name(k->ecdsa_nid);
2743 if (k->ecdsa == NULL || (exponent = BN_new()) == NULL) {
2744 r = SSH_ERR_LIBCRYPTO_ERROR;
2747 if ((r = sshbuf_get_eckey(buf, k->ecdsa)) != 0 ||
2748 (r = sshbuf_get_bignum2(buf, exponent)))
2750 if (EC_KEY_set_private_key(k->ecdsa, exponent) != 1) {
2751 r = SSH_ERR_LIBCRYPTO_ERROR;
2754 if ((r = sshkey_ec_validate_public(EC_KEY_get0_group(k->ecdsa),
2755 EC_KEY_get0_public_key(k->ecdsa)) != 0) ||
2756 (r = sshkey_ec_validate_private(k->ecdsa)) != 0)
2759 case KEY_ECDSA_CERT:
2760 if ((exponent = BN_new()) == NULL) {
2761 r = SSH_ERR_LIBCRYPTO_ERROR;
2764 if ((r = sshkey_froms(buf, &k)) != 0 ||
2765 (r = sshkey_add_private(k)) != 0 ||
2766 (r = sshbuf_get_bignum2(buf, exponent)) != 0)
2768 if (EC_KEY_set_private_key(k->ecdsa, exponent) != 1) {
2769 r = SSH_ERR_LIBCRYPTO_ERROR;
2772 if ((r = sshkey_ec_validate_public(EC_KEY_get0_group(k->ecdsa),
2773 EC_KEY_get0_public_key(k->ecdsa)) != 0) ||
2774 (r = sshkey_ec_validate_private(k->ecdsa)) != 0)
2777 # endif /* OPENSSL_HAS_ECC */
2779 if ((k = sshkey_new_private(type)) == NULL) {
2780 r = SSH_ERR_ALLOC_FAIL;
2783 if ((r = sshbuf_get_bignum2(buf, k->rsa->n)) != 0 ||
2784 (r = sshbuf_get_bignum2(buf, k->rsa->e)) != 0 ||
2785 (r = sshbuf_get_bignum2(buf, k->rsa->d)) != 0 ||
2786 (r = sshbuf_get_bignum2(buf, k->rsa->iqmp)) != 0 ||
2787 (r = sshbuf_get_bignum2(buf, k->rsa->p)) != 0 ||
2788 (r = sshbuf_get_bignum2(buf, k->rsa->q)) != 0 ||
2789 (r = rsa_generate_additional_parameters(k->rsa)) != 0)
2792 case KEY_RSA_CERT_V00:
2794 if ((r = sshkey_froms(buf, &k)) != 0 ||
2795 (r = sshkey_add_private(k)) != 0 ||
2796 (r = sshbuf_get_bignum2(buf, k->rsa->d) != 0) ||
2797 (r = sshbuf_get_bignum2(buf, k->rsa->iqmp) != 0) ||
2798 (r = sshbuf_get_bignum2(buf, k->rsa->p) != 0) ||
2799 (r = sshbuf_get_bignum2(buf, k->rsa->q) != 0) ||
2800 (r = rsa_generate_additional_parameters(k->rsa)) != 0)
2803 #endif /* WITH_OPENSSL */
2805 if ((k = sshkey_new_private(type)) == NULL) {
2806 r = SSH_ERR_ALLOC_FAIL;
2809 if ((r = sshbuf_get_string(buf, &ed25519_pk, &pklen)) != 0 ||
2810 (r = sshbuf_get_string(buf, &ed25519_sk, &sklen)) != 0)
2812 if (pklen != ED25519_PK_SZ || sklen != ED25519_SK_SZ) {
2813 r = SSH_ERR_INVALID_FORMAT;
2816 k->ed25519_pk = ed25519_pk;
2817 k->ed25519_sk = ed25519_sk;
2818 ed25519_pk = ed25519_sk = NULL;
2820 case KEY_ED25519_CERT:
2821 if ((r = sshkey_froms(buf, &k)) != 0 ||
2822 (r = sshkey_add_private(k)) != 0 ||
2823 (r = sshbuf_get_string(buf, &ed25519_pk, &pklen)) != 0 ||
2824 (r = sshbuf_get_string(buf, &ed25519_sk, &sklen)) != 0)
2826 if (pklen != ED25519_PK_SZ || sklen != ED25519_SK_SZ) {
2827 r = SSH_ERR_INVALID_FORMAT;
2830 k->ed25519_pk = ed25519_pk;
2831 k->ed25519_sk = ed25519_sk;
2832 ed25519_pk = ed25519_sk = NULL;
2835 r = SSH_ERR_KEY_TYPE_UNKNOWN;
2839 /* enable blinding */
2842 case KEY_RSA_CERT_V00:
2845 if (RSA_blinding_on(k->rsa, NULL) != 1) {
2846 r = SSH_ERR_LIBCRYPTO_ERROR;
2851 #endif /* WITH_OPENSSL */
2862 if (exponent != NULL)
2863 BN_clear_free(exponent);
2864 #endif /* WITH_OPENSSL */
2866 if (ed25519_pk != NULL) {
2867 explicit_bzero(ed25519_pk, pklen);
2870 if (ed25519_sk != NULL) {
2871 explicit_bzero(ed25519_sk, sklen);
2877 #if defined(WITH_OPENSSL) && defined(OPENSSL_HAS_ECC)
2879 sshkey_ec_validate_public(const EC_GROUP *group, const EC_POINT *public)
2882 EC_POINT *nq = NULL;
2883 BIGNUM *order, *x, *y, *tmp;
2884 int ret = SSH_ERR_KEY_INVALID_EC_VALUE;
2886 if ((bnctx = BN_CTX_new()) == NULL)
2887 return SSH_ERR_ALLOC_FAIL;
2888 BN_CTX_start(bnctx);
2891 * We shouldn't ever hit this case because bignum_get_ecpoint()
2892 * refuses to load GF2m points.
2894 if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) !=
2895 NID_X9_62_prime_field)
2899 if (EC_POINT_is_at_infinity(group, public))
2902 if ((x = BN_CTX_get(bnctx)) == NULL ||
2903 (y = BN_CTX_get(bnctx)) == NULL ||
2904 (order = BN_CTX_get(bnctx)) == NULL ||
2905 (tmp = BN_CTX_get(bnctx)) == NULL) {
2906 ret = SSH_ERR_ALLOC_FAIL;
2910 /* log2(x) > log2(order)/2, log2(y) > log2(order)/2 */
2911 if (EC_GROUP_get_order(group, order, bnctx) != 1 ||
2912 EC_POINT_get_affine_coordinates_GFp(group, public,
2913 x, y, bnctx) != 1) {
2914 ret = SSH_ERR_LIBCRYPTO_ERROR;
2917 if (BN_num_bits(x) <= BN_num_bits(order) / 2 ||
2918 BN_num_bits(y) <= BN_num_bits(order) / 2)
2921 /* nQ == infinity (n == order of subgroup) */
2922 if ((nq = EC_POINT_new(group)) == NULL) {
2923 ret = SSH_ERR_ALLOC_FAIL;
2926 if (EC_POINT_mul(group, nq, NULL, public, order, bnctx) != 1) {
2927 ret = SSH_ERR_LIBCRYPTO_ERROR;
2930 if (EC_POINT_is_at_infinity(group, nq) != 1)
2933 /* x < order - 1, y < order - 1 */
2934 if (!BN_sub(tmp, order, BN_value_one())) {
2935 ret = SSH_ERR_LIBCRYPTO_ERROR;
2938 if (BN_cmp(x, tmp) >= 0 || BN_cmp(y, tmp) >= 0)
2949 sshkey_ec_validate_private(const EC_KEY *key)
2952 BIGNUM *order, *tmp;
2953 int ret = SSH_ERR_KEY_INVALID_EC_VALUE;
2955 if ((bnctx = BN_CTX_new()) == NULL)
2956 return SSH_ERR_ALLOC_FAIL;
2957 BN_CTX_start(bnctx);
2959 if ((order = BN_CTX_get(bnctx)) == NULL ||
2960 (tmp = BN_CTX_get(bnctx)) == NULL) {
2961 ret = SSH_ERR_ALLOC_FAIL;
2965 /* log2(private) > log2(order)/2 */
2966 if (EC_GROUP_get_order(EC_KEY_get0_group(key), order, bnctx) != 1) {
2967 ret = SSH_ERR_LIBCRYPTO_ERROR;
2970 if (BN_num_bits(EC_KEY_get0_private_key(key)) <=
2971 BN_num_bits(order) / 2)
2974 /* private < order - 1 */
2975 if (!BN_sub(tmp, order, BN_value_one())) {
2976 ret = SSH_ERR_LIBCRYPTO_ERROR;
2979 if (BN_cmp(EC_KEY_get0_private_key(key), tmp) >= 0)
2988 sshkey_dump_ec_point(const EC_GROUP *group, const EC_POINT *point)
2993 if (point == NULL) {
2994 fputs("point=(NULL)\n", stderr);
2997 if ((bnctx = BN_CTX_new()) == NULL) {
2998 fprintf(stderr, "%s: BN_CTX_new failed\n", __func__);
3001 BN_CTX_start(bnctx);
3002 if ((x = BN_CTX_get(bnctx)) == NULL ||
3003 (y = BN_CTX_get(bnctx)) == NULL) {
3004 fprintf(stderr, "%s: BN_CTX_get failed\n", __func__);
3007 if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) !=
3008 NID_X9_62_prime_field) {
3009 fprintf(stderr, "%s: group is not a prime field\n", __func__);
3012 if (EC_POINT_get_affine_coordinates_GFp(group, point, x, y,
3014 fprintf(stderr, "%s: EC_POINT_get_affine_coordinates_GFp\n",
3018 fputs("x=", stderr);
3019 BN_print_fp(stderr, x);
3020 fputs("\ny=", stderr);
3021 BN_print_fp(stderr, y);
3022 fputs("\n", stderr);
3027 sshkey_dump_ec_key(const EC_KEY *key)
3029 const BIGNUM *exponent;
3031 sshkey_dump_ec_point(EC_KEY_get0_group(key),
3032 EC_KEY_get0_public_key(key));
3033 fputs("exponent=", stderr);
3034 if ((exponent = EC_KEY_get0_private_key(key)) == NULL)
3035 fputs("(NULL)", stderr);
3037 BN_print_fp(stderr, EC_KEY_get0_private_key(key));
3038 fputs("\n", stderr);
3040 #endif /* WITH_OPENSSL && OPENSSL_HAS_ECC */
3043 sshkey_private_to_blob2(const struct sshkey *prv, struct sshbuf *blob,
3044 const char *passphrase, const char *comment, const char *ciphername,
3047 u_char *cp, *key = NULL, *pubkeyblob = NULL;
3048 u_char salt[SALT_LEN];
3050 size_t i, pubkeylen, keylen, ivlen, blocksize, authlen;
3052 int r = SSH_ERR_INTERNAL_ERROR;
3053 struct sshcipher_ctx ciphercontext;
3054 const struct sshcipher *cipher;
3055 const char *kdfname = KDFNAME;
3056 struct sshbuf *encoded = NULL, *encrypted = NULL, *kdf = NULL;
3058 memset(&ciphercontext, 0, sizeof(ciphercontext));
3061 rounds = DEFAULT_ROUNDS;
3062 if (passphrase == NULL || !strlen(passphrase)) {
3063 ciphername = "none";
3065 } else if (ciphername == NULL)
3066 ciphername = DEFAULT_CIPHERNAME;
3067 else if (cipher_number(ciphername) != SSH_CIPHER_SSH2) {
3068 r = SSH_ERR_INVALID_ARGUMENT;
3071 if ((cipher = cipher_by_name(ciphername)) == NULL) {
3072 r = SSH_ERR_INTERNAL_ERROR;
3076 if ((kdf = sshbuf_new()) == NULL ||
3077 (encoded = sshbuf_new()) == NULL ||
3078 (encrypted = sshbuf_new()) == NULL) {
3079 r = SSH_ERR_ALLOC_FAIL;
3082 blocksize = cipher_blocksize(cipher);
3083 keylen = cipher_keylen(cipher);
3084 ivlen = cipher_ivlen(cipher);
3085 authlen = cipher_authlen(cipher);
3086 if ((key = calloc(1, keylen + ivlen)) == NULL) {
3087 r = SSH_ERR_ALLOC_FAIL;
3090 if (strcmp(kdfname, "bcrypt") == 0) {
3091 arc4random_buf(salt, SALT_LEN);
3092 if (bcrypt_pbkdf(passphrase, strlen(passphrase),
3093 salt, SALT_LEN, key, keylen + ivlen, rounds) < 0) {
3094 r = SSH_ERR_INVALID_ARGUMENT;
3097 if ((r = sshbuf_put_string(kdf, salt, SALT_LEN)) != 0 ||
3098 (r = sshbuf_put_u32(kdf, rounds)) != 0)
3100 } else if (strcmp(kdfname, "none") != 0) {
3101 /* Unsupported KDF type */
3102 r = SSH_ERR_KEY_UNKNOWN_CIPHER;
3105 if ((r = cipher_init(&ciphercontext, cipher, key, keylen,
3106 key + keylen, ivlen, 1)) != 0)
3109 if ((r = sshbuf_put(encoded, AUTH_MAGIC, sizeof(AUTH_MAGIC))) != 0 ||
3110 (r = sshbuf_put_cstring(encoded, ciphername)) != 0 ||
3111 (r = sshbuf_put_cstring(encoded, kdfname)) != 0 ||
3112 (r = sshbuf_put_stringb(encoded, kdf)) != 0 ||
3113 (r = sshbuf_put_u32(encoded, 1)) != 0 || /* number of keys */
3114 (r = sshkey_to_blob(prv, &pubkeyblob, &pubkeylen)) != 0 ||
3115 (r = sshbuf_put_string(encoded, pubkeyblob, pubkeylen)) != 0)
3118 /* set up the buffer that will be encrypted */
3120 /* Random check bytes */
3121 check = arc4random();
3122 if ((r = sshbuf_put_u32(encrypted, check)) != 0 ||
3123 (r = sshbuf_put_u32(encrypted, check)) != 0)
3126 /* append private key and comment*/
3127 if ((r = sshkey_private_serialize(prv, encrypted)) != 0 ||
3128 (r = sshbuf_put_cstring(encrypted, comment)) != 0)
3133 while (sshbuf_len(encrypted) % blocksize) {
3134 if ((r = sshbuf_put_u8(encrypted, ++i & 0xff)) != 0)
3138 /* length in destination buffer */
3139 if ((r = sshbuf_put_u32(encoded, sshbuf_len(encrypted))) != 0)
3143 if ((r = sshbuf_reserve(encoded,
3144 sshbuf_len(encrypted) + authlen, &cp)) != 0)
3146 if ((r = cipher_crypt(&ciphercontext, 0, cp,
3147 sshbuf_ptr(encrypted), sshbuf_len(encrypted), 0, authlen)) != 0)
3151 if ((b64 = sshbuf_dtob64(encoded)) == NULL) {
3152 r = SSH_ERR_ALLOC_FAIL;
3157 if ((r = sshbuf_put(blob, MARK_BEGIN, MARK_BEGIN_LEN)) != 0)
3159 for (i = 0; i < strlen(b64); i++) {
3160 if ((r = sshbuf_put_u8(blob, b64[i])) != 0)
3162 /* insert line breaks */
3163 if (i % 70 == 69 && (r = sshbuf_put_u8(blob, '\n')) != 0)
3166 if (i % 70 != 69 && (r = sshbuf_put_u8(blob, '\n')) != 0)
3168 if ((r = sshbuf_put(blob, MARK_END, MARK_END_LEN)) != 0)
3176 sshbuf_free(encoded);
3177 sshbuf_free(encrypted);
3178 cipher_cleanup(&ciphercontext);
3179 explicit_bzero(salt, sizeof(salt));
3181 explicit_bzero(key, keylen + ivlen);
3184 if (pubkeyblob != NULL) {
3185 explicit_bzero(pubkeyblob, pubkeylen);
3189 explicit_bzero(b64, strlen(b64));
3196 sshkey_parse_private2(struct sshbuf *blob, int type, const char *passphrase,
3197 struct sshkey **keyp, char **commentp)
3199 char *comment = NULL, *ciphername = NULL, *kdfname = NULL;
3200 const struct sshcipher *cipher = NULL;
3202 int r = SSH_ERR_INTERNAL_ERROR;
3204 size_t i, keylen = 0, ivlen = 0, slen = 0;
3205 struct sshbuf *encoded = NULL, *decoded = NULL;
3206 struct sshbuf *kdf = NULL, *decrypted = NULL;
3207 struct sshcipher_ctx ciphercontext;
3208 struct sshkey *k = NULL;
3209 u_char *key = NULL, *salt = NULL, *dp, pad, last;
3210 u_int blocksize, rounds, nkeys, encrypted_len, check1, check2;
3212 memset(&ciphercontext, 0, sizeof(ciphercontext));
3215 if (commentp != NULL)
3218 if ((encoded = sshbuf_new()) == NULL ||
3219 (decoded = sshbuf_new()) == NULL ||
3220 (decrypted = sshbuf_new()) == NULL) {
3221 r = SSH_ERR_ALLOC_FAIL;
3225 /* check preamble */
3226 cp = sshbuf_ptr(blob);
3227 encoded_len = sshbuf_len(blob);
3228 if (encoded_len < (MARK_BEGIN_LEN + MARK_END_LEN) ||
3229 memcmp(cp, MARK_BEGIN, MARK_BEGIN_LEN) != 0) {
3230 r = SSH_ERR_INVALID_FORMAT;
3233 cp += MARK_BEGIN_LEN;
3234 encoded_len -= MARK_BEGIN_LEN;
3236 /* Look for end marker, removing whitespace as we go */
3237 while (encoded_len > 0) {
3238 if (*cp != '\n' && *cp != '\r') {
3239 if ((r = sshbuf_put_u8(encoded, *cp)) != 0)
3246 if (encoded_len >= MARK_END_LEN &&
3247 memcmp(cp, MARK_END, MARK_END_LEN) == 0) {
3249 if ((r = sshbuf_put_u8(encoded, 0)) != 0)
3255 if (encoded_len == 0) {
3256 r = SSH_ERR_INVALID_FORMAT;
3261 if ((r = sshbuf_b64tod(decoded, (char *)sshbuf_ptr(encoded))) != 0)
3265 if (sshbuf_len(decoded) < sizeof(AUTH_MAGIC) ||
3266 memcmp(sshbuf_ptr(decoded), AUTH_MAGIC, sizeof(AUTH_MAGIC))) {
3267 r = SSH_ERR_INVALID_FORMAT;
3270 /* parse public portion of key */
3271 if ((r = sshbuf_consume(decoded, sizeof(AUTH_MAGIC))) != 0 ||
3272 (r = sshbuf_get_cstring(decoded, &ciphername, NULL)) != 0 ||
3273 (r = sshbuf_get_cstring(decoded, &kdfname, NULL)) != 0 ||
3274 (r = sshbuf_froms(decoded, &kdf)) != 0 ||
3275 (r = sshbuf_get_u32(decoded, &nkeys)) != 0 ||
3276 (r = sshbuf_skip_string(decoded)) != 0 || /* pubkey */
3277 (r = sshbuf_get_u32(decoded, &encrypted_len)) != 0)
3280 if ((cipher = cipher_by_name(ciphername)) == NULL) {
3281 r = SSH_ERR_KEY_UNKNOWN_CIPHER;
3284 if ((passphrase == NULL || strlen(passphrase) == 0) &&
3285 strcmp(ciphername, "none") != 0) {
3286 /* passphrase required */
3287 r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3290 if (strcmp(kdfname, "none") != 0 && strcmp(kdfname, "bcrypt") != 0) {
3291 r = SSH_ERR_KEY_UNKNOWN_CIPHER;
3294 if (!strcmp(kdfname, "none") && strcmp(ciphername, "none") != 0) {
3295 r = SSH_ERR_INVALID_FORMAT;
3299 /* XXX only one key supported */
3300 r = SSH_ERR_INVALID_FORMAT;
3304 /* check size of encrypted key blob */
3305 blocksize = cipher_blocksize(cipher);
3306 if (encrypted_len < blocksize || (encrypted_len % blocksize) != 0) {
3307 r = SSH_ERR_INVALID_FORMAT;
3312 keylen = cipher_keylen(cipher);
3313 ivlen = cipher_ivlen(cipher);
3314 if ((key = calloc(1, keylen + ivlen)) == NULL) {
3315 r = SSH_ERR_ALLOC_FAIL;
3318 if (strcmp(kdfname, "bcrypt") == 0) {
3319 if ((r = sshbuf_get_string(kdf, &salt, &slen)) != 0 ||
3320 (r = sshbuf_get_u32(kdf, &rounds)) != 0)
3322 if (bcrypt_pbkdf(passphrase, strlen(passphrase), salt, slen,
3323 key, keylen + ivlen, rounds) < 0) {
3324 r = SSH_ERR_INVALID_FORMAT;
3329 /* decrypt private portion of key */
3330 if ((r = sshbuf_reserve(decrypted, encrypted_len, &dp)) != 0 ||
3331 (r = cipher_init(&ciphercontext, cipher, key, keylen,
3332 key + keylen, ivlen, 0)) != 0)
3334 if ((r = cipher_crypt(&ciphercontext, 0, dp, sshbuf_ptr(decoded),
3335 sshbuf_len(decoded), 0, cipher_authlen(cipher))) != 0) {
3336 /* an integrity error here indicates an incorrect passphrase */
3337 if (r == SSH_ERR_MAC_INVALID)
3338 r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3341 if ((r = sshbuf_consume(decoded, encrypted_len)) != 0)
3343 /* there should be no trailing data */
3344 if (sshbuf_len(decoded) != 0) {
3345 r = SSH_ERR_INVALID_FORMAT;
3349 /* check check bytes */
3350 if ((r = sshbuf_get_u32(decrypted, &check1)) != 0 ||
3351 (r = sshbuf_get_u32(decrypted, &check2)) != 0)
3353 if (check1 != check2) {
3354 r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3358 /* Load the private key and comment */
3359 if ((r = sshkey_private_deserialize(decrypted, &k)) != 0 ||
3360 (r = sshbuf_get_cstring(decrypted, &comment, NULL)) != 0)
3363 /* Check deterministic padding */
3365 while (sshbuf_len(decrypted)) {
3366 if ((r = sshbuf_get_u8(decrypted, &pad)) != 0)
3368 if (pad != (++i & 0xff)) {
3369 r = SSH_ERR_INVALID_FORMAT;
3374 /* XXX decode pubkey and check against private */
3382 if (commentp != NULL) {
3383 *commentp = comment;
3388 cipher_cleanup(&ciphercontext);
3393 explicit_bzero(salt, slen);
3397 explicit_bzero(key, keylen + ivlen);
3400 sshbuf_free(encoded);
3401 sshbuf_free(decoded);
3403 sshbuf_free(decrypted);
3410 * Serialises the authentication (private) key to a blob, encrypting it with
3411 * passphrase. The identification of the blob (lowest 64 bits of n) will
3412 * precede the key to provide identification of the key without needing a
3416 sshkey_private_rsa1_to_blob(struct sshkey *key, struct sshbuf *blob,
3417 const char *passphrase, const char *comment)
3419 struct sshbuf *buffer = NULL, *encrypted = NULL;
3422 struct sshcipher_ctx ciphercontext;
3423 const struct sshcipher *cipher;
3427 * If the passphrase is empty, use SSH_CIPHER_NONE to ease converting
3428 * to another cipher; otherwise use SSH_AUTHFILE_CIPHER.
3430 cipher_num = (strcmp(passphrase, "") == 0) ?
3431 SSH_CIPHER_NONE : SSH_CIPHER_3DES;
3432 if ((cipher = cipher_by_number(cipher_num)) == NULL)
3433 return SSH_ERR_INTERNAL_ERROR;
3435 /* This buffer is used to build the secret part of the private key. */
3436 if ((buffer = sshbuf_new()) == NULL)
3437 return SSH_ERR_ALLOC_FAIL;
3439 /* Put checkbytes for checking passphrase validity. */
3440 if ((r = sshbuf_reserve(buffer, 4, &cp)) != 0)
3442 arc4random_buf(cp, 2);
3443 memcpy(cp + 2, cp, 2);
3446 * Store the private key (n and e will not be stored because they
3447 * will be stored in plain text, and storing them also in encrypted
3448 * format would just give known plaintext).
3449 * Note: q and p are stored in reverse order to SSL.
3451 if ((r = sshbuf_put_bignum1(buffer, key->rsa->d)) != 0 ||
3452 (r = sshbuf_put_bignum1(buffer, key->rsa->iqmp)) != 0 ||
3453 (r = sshbuf_put_bignum1(buffer, key->rsa->q)) != 0 ||
3454 (r = sshbuf_put_bignum1(buffer, key->rsa->p)) != 0)
3457 /* Pad the part to be encrypted to a size that is a multiple of 8. */
3458 explicit_bzero(buf, 8);
3459 if ((r = sshbuf_put(buffer, buf, 8 - (sshbuf_len(buffer) % 8))) != 0)
3462 /* This buffer will be used to contain the data in the file. */
3463 if ((encrypted = sshbuf_new()) == NULL) {
3464 r = SSH_ERR_ALLOC_FAIL;
3468 /* First store keyfile id string. */
3469 if ((r = sshbuf_put(encrypted, LEGACY_BEGIN,
3470 sizeof(LEGACY_BEGIN))) != 0)
3473 /* Store cipher type and "reserved" field. */
3474 if ((r = sshbuf_put_u8(encrypted, cipher_num)) != 0 ||
3475 (r = sshbuf_put_u32(encrypted, 0)) != 0)
3478 /* Store public key. This will be in plain text. */
3479 if ((r = sshbuf_put_u32(encrypted, BN_num_bits(key->rsa->n))) != 0 ||
3480 (r = sshbuf_put_bignum1(encrypted, key->rsa->n) != 0) ||
3481 (r = sshbuf_put_bignum1(encrypted, key->rsa->e) != 0) ||
3482 (r = sshbuf_put_cstring(encrypted, comment) != 0))
3485 /* Allocate space for the private part of the key in the buffer. */
3486 if ((r = sshbuf_reserve(encrypted, sshbuf_len(buffer), &cp)) != 0)
3489 if ((r = cipher_set_key_string(&ciphercontext, cipher, passphrase,
3490 CIPHER_ENCRYPT)) != 0)
3492 if ((r = cipher_crypt(&ciphercontext, 0, cp,
3493 sshbuf_ptr(buffer), sshbuf_len(buffer), 0, 0)) != 0)
3495 if ((r = cipher_cleanup(&ciphercontext)) != 0)
3498 r = sshbuf_putb(blob, encrypted);
3501 explicit_bzero(&ciphercontext, sizeof(ciphercontext));
3502 explicit_bzero(buf, sizeof(buf));
3504 sshbuf_free(buffer);
3505 if (encrypted != NULL)
3506 sshbuf_free(encrypted);
3510 #endif /* WITH_SSH1 */
3513 /* convert SSH v2 key in OpenSSL PEM format */
3515 sshkey_private_pem_to_blob(struct sshkey *key, struct sshbuf *blob,
3516 const char *_passphrase, const char *comment)
3519 int blen, len = strlen(_passphrase);
3520 u_char *passphrase = (len > 0) ? (u_char *)_passphrase : NULL;
3521 #if (OPENSSL_VERSION_NUMBER < 0x00907000L)
3522 const EVP_CIPHER *cipher = (len > 0) ? EVP_des_ede3_cbc() : NULL;
3524 const EVP_CIPHER *cipher = (len > 0) ? EVP_aes_128_cbc() : NULL;
3529 if (len > 0 && len <= 4)
3530 return SSH_ERR_PASSPHRASE_TOO_SHORT;
3531 if ((bio = BIO_new(BIO_s_mem())) == NULL)
3532 return SSH_ERR_ALLOC_FAIL;
3534 switch (key->type) {
3536 success = PEM_write_bio_DSAPrivateKey(bio, key->dsa,
3537 cipher, passphrase, len, NULL, NULL);
3539 #ifdef OPENSSL_HAS_ECC
3541 success = PEM_write_bio_ECPrivateKey(bio, key->ecdsa,
3542 cipher, passphrase, len, NULL, NULL);
3546 success = PEM_write_bio_RSAPrivateKey(bio, key->rsa,
3547 cipher, passphrase, len, NULL, NULL);
3554 r = SSH_ERR_LIBCRYPTO_ERROR;
3557 if ((blen = BIO_get_mem_data(bio, &bptr)) <= 0) {
3558 r = SSH_ERR_INTERNAL_ERROR;
3561 if ((r = sshbuf_put(blob, bptr, blen)) != 0)
3568 #endif /* WITH_OPENSSL */
3570 /* Serialise "key" to buffer "blob" */
3572 sshkey_private_to_fileblob(struct sshkey *key, struct sshbuf *blob,
3573 const char *passphrase, const char *comment,
3574 int force_new_format, const char *new_format_cipher, int new_format_rounds)
3576 switch (key->type) {
3579 return sshkey_private_rsa1_to_blob(key, blob,
3580 passphrase, comment);
3581 #endif /* WITH_SSH1 */
3586 if (force_new_format) {
3587 return sshkey_private_to_blob2(key, blob, passphrase,
3588 comment, new_format_cipher, new_format_rounds);
3590 return sshkey_private_pem_to_blob(key, blob,
3591 passphrase, comment);
3592 #endif /* WITH_OPENSSL */
3594 return sshkey_private_to_blob2(key, blob, passphrase,
3595 comment, new_format_cipher, new_format_rounds);
3597 return SSH_ERR_KEY_TYPE_UNKNOWN;
3603 * Parse the public, unencrypted portion of a RSA1 key.
3606 sshkey_parse_public_rsa1_fileblob(struct sshbuf *blob,
3607 struct sshkey **keyp, char **commentp)
3610 struct sshkey *pub = NULL;
3611 struct sshbuf *copy = NULL;
3615 if (commentp != NULL)
3618 /* Check that it is at least big enough to contain the ID string. */
3619 if (sshbuf_len(blob) < sizeof(LEGACY_BEGIN))
3620 return SSH_ERR_INVALID_FORMAT;
3623 * Make sure it begins with the id string. Consume the id string
3626 if (memcmp(sshbuf_ptr(blob), LEGACY_BEGIN, sizeof(LEGACY_BEGIN)) != 0)
3627 return SSH_ERR_INVALID_FORMAT;
3628 /* Make a working copy of the keyblob and skip past the magic */
3629 if ((copy = sshbuf_fromb(blob)) == NULL)
3630 return SSH_ERR_ALLOC_FAIL;
3631 if ((r = sshbuf_consume(copy, sizeof(LEGACY_BEGIN))) != 0)
3634 /* Skip cipher type, reserved data and key bits. */
3635 if ((r = sshbuf_get_u8(copy, NULL)) != 0 || /* cipher type */
3636 (r = sshbuf_get_u32(copy, NULL)) != 0 || /* reserved */
3637 (r = sshbuf_get_u32(copy, NULL)) != 0) /* key bits */
3640 /* Read the public key from the buffer. */
3641 if ((pub = sshkey_new(KEY_RSA1)) == NULL ||
3642 (r = sshbuf_get_bignum1(copy, pub->rsa->n)) != 0 ||
3643 (r = sshbuf_get_bignum1(copy, pub->rsa->e)) != 0)
3646 /* Finally, the comment */
3647 if ((r = sshbuf_get_string(copy, (u_char**)commentp, NULL)) != 0)
3650 /* The encrypted private part is not parsed by this function. */
3668 sshkey_parse_private_rsa1(struct sshbuf *blob, const char *passphrase,
3669 struct sshkey **keyp, char **commentp)
3672 u_int16_t check1, check2;
3673 u_int8_t cipher_type;
3674 struct sshbuf *decrypted = NULL, *copy = NULL;
3676 char *comment = NULL;
3677 struct sshcipher_ctx ciphercontext;
3678 const struct sshcipher *cipher;
3679 struct sshkey *prv = NULL;
3682 if (commentp != NULL)
3685 /* Check that it is at least big enough to contain the ID string. */
3686 if (sshbuf_len(blob) < sizeof(LEGACY_BEGIN))
3687 return SSH_ERR_INVALID_FORMAT;
3690 * Make sure it begins with the id string. Consume the id string
3693 if (memcmp(sshbuf_ptr(blob), LEGACY_BEGIN, sizeof(LEGACY_BEGIN)) != 0)
3694 return SSH_ERR_INVALID_FORMAT;
3696 if ((prv = sshkey_new_private(KEY_RSA1)) == NULL) {
3697 r = SSH_ERR_ALLOC_FAIL;
3700 if ((copy = sshbuf_fromb(blob)) == NULL ||
3701 (decrypted = sshbuf_new()) == NULL) {
3702 r = SSH_ERR_ALLOC_FAIL;
3705 if ((r = sshbuf_consume(copy, sizeof(LEGACY_BEGIN))) != 0)
3708 /* Read cipher type. */
3709 if ((r = sshbuf_get_u8(copy, &cipher_type)) != 0 ||
3710 (r = sshbuf_get_u32(copy, NULL)) != 0) /* reserved */
3713 /* Read the public key and comment from the buffer. */
3714 if ((r = sshbuf_get_u32(copy, NULL)) != 0 || /* key bits */
3715 (r = sshbuf_get_bignum1(copy, prv->rsa->n)) != 0 ||
3716 (r = sshbuf_get_bignum1(copy, prv->rsa->e)) != 0 ||
3717 (r = sshbuf_get_cstring(copy, &comment, NULL)) != 0)
3720 /* Check that it is a supported cipher. */
3721 cipher = cipher_by_number(cipher_type);
3722 if (cipher == NULL) {
3723 r = SSH_ERR_KEY_UNKNOWN_CIPHER;
3726 /* Initialize space for decrypted data. */
3727 if ((r = sshbuf_reserve(decrypted, sshbuf_len(copy), &cp)) != 0)
3730 /* Rest of the buffer is encrypted. Decrypt it using the passphrase. */
3731 if ((r = cipher_set_key_string(&ciphercontext, cipher, passphrase,
3732 CIPHER_DECRYPT)) != 0)
3734 if ((r = cipher_crypt(&ciphercontext, 0, cp,
3735 sshbuf_ptr(copy), sshbuf_len(copy), 0, 0)) != 0) {
3736 cipher_cleanup(&ciphercontext);
3739 if ((r = cipher_cleanup(&ciphercontext)) != 0)
3742 if ((r = sshbuf_get_u16(decrypted, &check1)) != 0 ||
3743 (r = sshbuf_get_u16(decrypted, &check2)) != 0)
3745 if (check1 != check2) {
3746 r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3750 /* Read the rest of the private key. */
3751 if ((r = sshbuf_get_bignum1(decrypted, prv->rsa->d)) != 0 ||
3752 (r = sshbuf_get_bignum1(decrypted, prv->rsa->iqmp)) != 0 ||
3753 (r = sshbuf_get_bignum1(decrypted, prv->rsa->q)) != 0 ||
3754 (r = sshbuf_get_bignum1(decrypted, prv->rsa->p)) != 0)
3757 /* calculate p-1 and q-1 */
3758 if ((r = rsa_generate_additional_parameters(prv->rsa)) != 0)
3761 /* enable blinding */
3762 if (RSA_blinding_on(prv->rsa, NULL) != 1) {
3763 r = SSH_ERR_LIBCRYPTO_ERROR;
3769 if (commentp != NULL) {
3770 *commentp = comment;
3774 explicit_bzero(&ciphercontext, sizeof(ciphercontext));
3775 if (comment != NULL)
3781 if (decrypted != NULL)
3782 sshbuf_free(decrypted);
3785 #endif /* WITH_SSH1 */
3789 sshkey_parse_private_pem_fileblob(struct sshbuf *blob, int type,
3790 const char *passphrase, struct sshkey **keyp)
3792 EVP_PKEY *pk = NULL;
3793 struct sshkey *prv = NULL;
3799 if ((bio = BIO_new(BIO_s_mem())) == NULL || sshbuf_len(blob) > INT_MAX)
3800 return SSH_ERR_ALLOC_FAIL;
3801 if (BIO_write(bio, sshbuf_ptr(blob), sshbuf_len(blob)) !=
3802 (int)sshbuf_len(blob)) {
3803 r = SSH_ERR_ALLOC_FAIL;
3807 if ((pk = PEM_read_bio_PrivateKey(bio, NULL, NULL,
3808 (char *)passphrase)) == NULL) {
3809 r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3812 if (pk->type == EVP_PKEY_RSA &&
3813 (type == KEY_UNSPEC || type == KEY_RSA)) {
3814 if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
3815 r = SSH_ERR_ALLOC_FAIL;
3818 prv->rsa = EVP_PKEY_get1_RSA(pk);
3819 prv->type = KEY_RSA;
3821 RSA_print_fp(stderr, prv->rsa, 8);
3823 if (RSA_blinding_on(prv->rsa, NULL) != 1) {
3824 r = SSH_ERR_LIBCRYPTO_ERROR;
3827 } else if (pk->type == EVP_PKEY_DSA &&
3828 (type == KEY_UNSPEC || type == KEY_DSA)) {
3829 if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
3830 r = SSH_ERR_ALLOC_FAIL;
3833 prv->dsa = EVP_PKEY_get1_DSA(pk);
3834 prv->type = KEY_DSA;
3836 DSA_print_fp(stderr, prv->dsa, 8);
3838 #ifdef OPENSSL_HAS_ECC
3839 } else if (pk->type == EVP_PKEY_EC &&
3840 (type == KEY_UNSPEC || type == KEY_ECDSA)) {
3841 if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
3842 r = SSH_ERR_ALLOC_FAIL;
3845 prv->ecdsa = EVP_PKEY_get1_EC_KEY(pk);
3846 prv->type = KEY_ECDSA;
3847 prv->ecdsa_nid = sshkey_ecdsa_key_to_nid(prv->ecdsa);
3848 if (prv->ecdsa_nid == -1 ||
3849 sshkey_curve_nid_to_name(prv->ecdsa_nid) == NULL ||
3850 sshkey_ec_validate_public(EC_KEY_get0_group(prv->ecdsa),
3851 EC_KEY_get0_public_key(prv->ecdsa)) != 0 ||
3852 sshkey_ec_validate_private(prv->ecdsa) != 0) {
3853 r = SSH_ERR_INVALID_FORMAT;
3857 if (prv != NULL && prv->ecdsa != NULL)
3858 sshkey_dump_ec_key(prv->ecdsa);
3860 #endif /* OPENSSL_HAS_ECC */
3862 r = SSH_ERR_INVALID_FORMAT;
3876 #endif /* WITH_OPENSSL */
3879 sshkey_parse_private_fileblob_type(struct sshbuf *blob, int type,
3880 const char *passphrase, struct sshkey **keyp, char **commentp)
3885 if (commentp != NULL)
3891 return sshkey_parse_private_rsa1(blob, passphrase,
3893 #endif /* WITH_SSH1 */
3898 return sshkey_parse_private_pem_fileblob(blob, type,
3900 #endif /* WITH_OPENSSL */
3902 return sshkey_parse_private2(blob, type, passphrase,
3905 if ((r = sshkey_parse_private2(blob, type, passphrase, keyp,
3909 return sshkey_parse_private_pem_fileblob(blob, type,
3912 return SSH_ERR_INVALID_FORMAT;
3913 #endif /* WITH_OPENSSL */
3915 return SSH_ERR_KEY_TYPE_UNKNOWN;
3920 sshkey_parse_private_fileblob(struct sshbuf *buffer, const char *passphrase,
3921 const char *filename, struct sshkey **keyp, char **commentp)
3927 if (commentp != NULL)
3931 /* it's a SSH v1 key if the public key part is readable */
3932 if ((r = sshkey_parse_public_rsa1_fileblob(buffer, NULL, NULL)) == 0) {
3933 return sshkey_parse_private_fileblob_type(buffer, KEY_RSA1,
3934 passphrase, keyp, commentp);
3936 #endif /* WITH_SSH1 */
3937 if ((r = sshkey_parse_private_fileblob_type(buffer, KEY_UNSPEC,
3938 passphrase, keyp, commentp)) == 0)