1 /* $OpenBSD: sshkey.c,v 1.41 2016/10/24 01:09:17 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"
48 #endif /* HAVE_UTIL_H */
57 #define SSHKEY_INTERNAL
61 /* openssh private key file format */
62 #define MARK_BEGIN "-----BEGIN OPENSSH PRIVATE KEY-----\n"
63 #define MARK_END "-----END OPENSSH PRIVATE KEY-----\n"
64 #define MARK_BEGIN_LEN (sizeof(MARK_BEGIN) - 1)
65 #define MARK_END_LEN (sizeof(MARK_END) - 1)
66 #define KDFNAME "bcrypt"
67 #define AUTH_MAGIC "openssh-key-v1"
69 #define DEFAULT_CIPHERNAME "aes256-cbc"
70 #define DEFAULT_ROUNDS 16
72 /* Version identification string for SSH v1 identity files. */
73 #define LEGACY_BEGIN "SSH PRIVATE KEY FILE FORMAT 1.1\n"
75 static int sshkey_from_blob_internal(struct sshbuf *buf,
76 struct sshkey **keyp, int allow_cert);
78 /* Supported key types */
81 const char *shortname;
87 static const struct keytype keytypes[] = {
88 { "ssh-ed25519", "ED25519", KEY_ED25519, 0, 0, 0 },
89 { "ssh-ed25519-cert-v01@openssh.com", "ED25519-CERT",
90 KEY_ED25519_CERT, 0, 1, 0 },
92 { NULL, "RSA1", KEY_RSA1, 0, 0, 0 },
93 { "ssh-rsa", "RSA", KEY_RSA, 0, 0, 0 },
94 { "rsa-sha2-256", "RSA", KEY_RSA, 0, 0, 1 },
95 { "rsa-sha2-512", "RSA", KEY_RSA, 0, 0, 1 },
96 { "ssh-dss", "DSA", KEY_DSA, 0, 0, 0 },
97 # ifdef OPENSSL_HAS_ECC
98 { "ecdsa-sha2-nistp256", "ECDSA", KEY_ECDSA, NID_X9_62_prime256v1, 0, 0 },
99 { "ecdsa-sha2-nistp384", "ECDSA", KEY_ECDSA, NID_secp384r1, 0, 0 },
100 # ifdef OPENSSL_HAS_NISTP521
101 { "ecdsa-sha2-nistp521", "ECDSA", KEY_ECDSA, NID_secp521r1, 0, 0 },
102 # endif /* OPENSSL_HAS_NISTP521 */
103 # endif /* OPENSSL_HAS_ECC */
104 { "ssh-rsa-cert-v01@openssh.com", "RSA-CERT", KEY_RSA_CERT, 0, 1, 0 },
105 { "ssh-dss-cert-v01@openssh.com", "DSA-CERT", KEY_DSA_CERT, 0, 1, 0 },
106 # ifdef OPENSSL_HAS_ECC
107 { "ecdsa-sha2-nistp256-cert-v01@openssh.com", "ECDSA-CERT",
108 KEY_ECDSA_CERT, NID_X9_62_prime256v1, 1, 0 },
109 { "ecdsa-sha2-nistp384-cert-v01@openssh.com", "ECDSA-CERT",
110 KEY_ECDSA_CERT, NID_secp384r1, 1, 0 },
111 # ifdef OPENSSL_HAS_NISTP521
112 { "ecdsa-sha2-nistp521-cert-v01@openssh.com", "ECDSA-CERT",
113 KEY_ECDSA_CERT, NID_secp521r1, 1, 0 },
114 # endif /* OPENSSL_HAS_NISTP521 */
115 # endif /* OPENSSL_HAS_ECC */
116 #endif /* WITH_OPENSSL */
117 { NULL, NULL, -1, -1, 0, 0 }
121 sshkey_type(const struct sshkey *k)
123 const struct keytype *kt;
125 for (kt = keytypes; kt->type != -1; kt++) {
126 if (kt->type == k->type)
127 return kt->shortname;
133 sshkey_ssh_name_from_type_nid(int type, int nid)
135 const struct keytype *kt;
137 for (kt = keytypes; kt->type != -1; kt++) {
138 if (kt->type == type && (kt->nid == 0 || kt->nid == nid))
141 return "ssh-unknown";
145 sshkey_type_is_cert(int type)
147 const struct keytype *kt;
149 for (kt = keytypes; kt->type != -1; kt++) {
150 if (kt->type == type)
157 sshkey_ssh_name(const struct sshkey *k)
159 return sshkey_ssh_name_from_type_nid(k->type, k->ecdsa_nid);
163 sshkey_ssh_name_plain(const struct sshkey *k)
165 return sshkey_ssh_name_from_type_nid(sshkey_type_plain(k->type),
170 sshkey_type_from_name(const char *name)
172 const struct keytype *kt;
174 for (kt = keytypes; kt->type != -1; kt++) {
175 /* Only allow shortname matches for plain key types */
176 if ((kt->name != NULL && strcmp(name, kt->name) == 0) ||
177 (!kt->cert && strcasecmp(kt->shortname, name) == 0))
184 sshkey_ecdsa_nid_from_name(const char *name)
186 const struct keytype *kt;
188 for (kt = keytypes; kt->type != -1; kt++) {
189 if (kt->type != KEY_ECDSA && kt->type != KEY_ECDSA_CERT)
191 if (kt->name != NULL && strcmp(name, kt->name) == 0)
198 sshkey_alg_list(int certs_only, int plain_only, char sep)
200 char *tmp, *ret = NULL;
201 size_t nlen, rlen = 0;
202 const struct keytype *kt;
204 for (kt = keytypes; kt->type != -1; kt++) {
205 if (kt->name == NULL || kt->sigonly)
207 if ((certs_only && !kt->cert) || (plain_only && kt->cert))
211 nlen = strlen(kt->name);
212 if ((tmp = realloc(ret, rlen + nlen + 2)) == NULL) {
217 memcpy(ret + rlen, kt->name, nlen + 1);
224 sshkey_names_valid2(const char *names, int allow_wildcard)
227 const struct keytype *kt;
230 if (names == NULL || strcmp(names, "") == 0)
232 if ((s = cp = strdup(names)) == NULL)
234 for ((p = strsep(&cp, ",")); p && *p != '\0';
235 (p = strsep(&cp, ","))) {
236 type = sshkey_type_from_name(p);
237 if (type == KEY_RSA1) {
241 if (type == KEY_UNSPEC) {
242 if (allow_wildcard) {
244 * Try matching key types against the string.
245 * If any has a positive or negative match then
246 * the component is accepted.
248 for (kt = keytypes; kt->type != -1; kt++) {
249 if (kt->type == KEY_RSA1)
251 if (match_pattern_list(kt->name,
267 sshkey_size(const struct sshkey *k)
274 return BN_num_bits(k->rsa->n);
277 return BN_num_bits(k->dsa->p);
280 return sshkey_curve_nid_to_bits(k->ecdsa_nid);
281 #endif /* WITH_OPENSSL */
283 case KEY_ED25519_CERT:
284 return 256; /* XXX */
290 sshkey_type_is_valid_ca(int type)
304 sshkey_is_cert(const struct sshkey *k)
308 return sshkey_type_is_cert(k->type);
311 /* Return the cert-less equivalent to a certified key type */
313 sshkey_type_plain(int type)
322 case KEY_ED25519_CERT:
330 /* XXX: these are really begging for a table-driven approach */
332 sshkey_curve_name_to_nid(const char *name)
334 if (strcmp(name, "nistp256") == 0)
335 return NID_X9_62_prime256v1;
336 else if (strcmp(name, "nistp384") == 0)
337 return NID_secp384r1;
338 # ifdef OPENSSL_HAS_NISTP521
339 else if (strcmp(name, "nistp521") == 0)
340 return NID_secp521r1;
341 # endif /* OPENSSL_HAS_NISTP521 */
347 sshkey_curve_nid_to_bits(int nid)
350 case NID_X9_62_prime256v1:
354 # ifdef OPENSSL_HAS_NISTP521
357 # endif /* OPENSSL_HAS_NISTP521 */
364 sshkey_ecdsa_bits_to_nid(int bits)
368 return NID_X9_62_prime256v1;
370 return NID_secp384r1;
371 # ifdef OPENSSL_HAS_NISTP521
373 return NID_secp521r1;
374 # endif /* OPENSSL_HAS_NISTP521 */
381 sshkey_curve_nid_to_name(int nid)
384 case NID_X9_62_prime256v1:
388 # ifdef OPENSSL_HAS_NISTP521
391 # endif /* OPENSSL_HAS_NISTP521 */
398 sshkey_ec_nid_to_hash_alg(int nid)
400 int kbits = sshkey_curve_nid_to_bits(nid);
405 /* RFC5656 section 6.2.1 */
407 return SSH_DIGEST_SHA256;
408 else if (kbits <= 384)
409 return SSH_DIGEST_SHA384;
411 return SSH_DIGEST_SHA512;
413 #endif /* WITH_OPENSSL */
416 cert_free(struct sshkey_cert *cert)
422 sshbuf_free(cert->certblob);
423 sshbuf_free(cert->critical);
424 sshbuf_free(cert->extensions);
426 for (i = 0; i < cert->nprincipals; i++)
427 free(cert->principals[i]);
428 free(cert->principals);
429 sshkey_free(cert->signature_key);
430 explicit_bzero(cert, sizeof(*cert));
434 static struct sshkey_cert *
437 struct sshkey_cert *cert;
439 if ((cert = calloc(1, sizeof(*cert))) == NULL)
441 if ((cert->certblob = sshbuf_new()) == NULL ||
442 (cert->critical = sshbuf_new()) == NULL ||
443 (cert->extensions = sshbuf_new()) == NULL) {
448 cert->principals = NULL;
449 cert->signature_key = NULL;
460 #endif /* WITH_OPENSSL */
462 if ((k = calloc(1, sizeof(*k))) == NULL)
470 k->ed25519_sk = NULL;
471 k->ed25519_pk = NULL;
477 if ((rsa = RSA_new()) == NULL ||
478 (rsa->n = BN_new()) == NULL ||
479 (rsa->e = BN_new()) == NULL) {
489 if ((dsa = DSA_new()) == NULL ||
490 (dsa->p = BN_new()) == NULL ||
491 (dsa->q = BN_new()) == NULL ||
492 (dsa->g = BN_new()) == NULL ||
493 (dsa->pub_key = BN_new()) == NULL) {
503 /* Cannot do anything until we know the group */
505 #endif /* WITH_OPENSSL */
507 case KEY_ED25519_CERT:
508 /* no need to prealloc */
517 if (sshkey_is_cert(k)) {
518 if ((k->cert = cert_new()) == NULL) {
528 sshkey_add_private(struct sshkey *k)
535 #define bn_maybe_alloc_failed(p) (p == NULL && (p = BN_new()) == NULL)
536 if (bn_maybe_alloc_failed(k->rsa->d) ||
537 bn_maybe_alloc_failed(k->rsa->iqmp) ||
538 bn_maybe_alloc_failed(k->rsa->q) ||
539 bn_maybe_alloc_failed(k->rsa->p) ||
540 bn_maybe_alloc_failed(k->rsa->dmq1) ||
541 bn_maybe_alloc_failed(k->rsa->dmp1))
542 return SSH_ERR_ALLOC_FAIL;
546 if (bn_maybe_alloc_failed(k->dsa->priv_key))
547 return SSH_ERR_ALLOC_FAIL;
549 #undef bn_maybe_alloc_failed
552 /* Cannot do anything until we know the group */
554 #endif /* WITH_OPENSSL */
556 case KEY_ED25519_CERT:
557 /* no need to prealloc */
562 return SSH_ERR_INVALID_ARGUMENT;
568 sshkey_new_private(int type)
570 struct sshkey *k = sshkey_new(type);
574 if (sshkey_add_private(k) != 0) {
582 sshkey_free(struct sshkey *k)
601 # ifdef OPENSSL_HAS_ECC
604 if (k->ecdsa != NULL)
605 EC_KEY_free(k->ecdsa);
608 # endif /* OPENSSL_HAS_ECC */
609 #endif /* WITH_OPENSSL */
611 case KEY_ED25519_CERT:
613 explicit_bzero(k->ed25519_pk, ED25519_PK_SZ);
615 k->ed25519_pk = NULL;
618 explicit_bzero(k->ed25519_sk, ED25519_SK_SZ);
620 k->ed25519_sk = NULL;
628 if (sshkey_is_cert(k))
630 explicit_bzero(k, sizeof(*k));
635 cert_compare(struct sshkey_cert *a, struct sshkey_cert *b)
637 if (a == NULL && b == NULL)
639 if (a == NULL || b == NULL)
641 if (sshbuf_len(a->certblob) != sshbuf_len(b->certblob))
643 if (timingsafe_bcmp(sshbuf_ptr(a->certblob), sshbuf_ptr(b->certblob),
644 sshbuf_len(a->certblob)) != 0)
650 * Compare public portions of key only, allowing comparisons between
651 * certificates and plain keys too.
654 sshkey_equal_public(const struct sshkey *a, const struct sshkey *b)
656 #if defined(WITH_OPENSSL) && defined(OPENSSL_HAS_ECC)
658 #endif /* WITH_OPENSSL && OPENSSL_HAS_ECC */
660 if (a == NULL || b == NULL ||
661 sshkey_type_plain(a->type) != sshkey_type_plain(b->type))
669 return a->rsa != NULL && b->rsa != NULL &&
670 BN_cmp(a->rsa->e, b->rsa->e) == 0 &&
671 BN_cmp(a->rsa->n, b->rsa->n) == 0;
674 return a->dsa != NULL && b->dsa != NULL &&
675 BN_cmp(a->dsa->p, b->dsa->p) == 0 &&
676 BN_cmp(a->dsa->q, b->dsa->q) == 0 &&
677 BN_cmp(a->dsa->g, b->dsa->g) == 0 &&
678 BN_cmp(a->dsa->pub_key, b->dsa->pub_key) == 0;
679 # ifdef OPENSSL_HAS_ECC
682 if (a->ecdsa == NULL || b->ecdsa == NULL ||
683 EC_KEY_get0_public_key(a->ecdsa) == NULL ||
684 EC_KEY_get0_public_key(b->ecdsa) == NULL)
686 if ((bnctx = BN_CTX_new()) == NULL)
688 if (EC_GROUP_cmp(EC_KEY_get0_group(a->ecdsa),
689 EC_KEY_get0_group(b->ecdsa), bnctx) != 0 ||
690 EC_POINT_cmp(EC_KEY_get0_group(a->ecdsa),
691 EC_KEY_get0_public_key(a->ecdsa),
692 EC_KEY_get0_public_key(b->ecdsa), bnctx) != 0) {
698 # endif /* OPENSSL_HAS_ECC */
699 #endif /* WITH_OPENSSL */
701 case KEY_ED25519_CERT:
702 return a->ed25519_pk != NULL && b->ed25519_pk != NULL &&
703 memcmp(a->ed25519_pk, b->ed25519_pk, ED25519_PK_SZ) == 0;
711 sshkey_equal(const struct sshkey *a, const struct sshkey *b)
713 if (a == NULL || b == NULL || a->type != b->type)
715 if (sshkey_is_cert(a)) {
716 if (!cert_compare(a->cert, b->cert))
719 return sshkey_equal_public(a, b);
723 to_blob_buf(const struct sshkey *key, struct sshbuf *b, int force_plain)
725 int type, ret = SSH_ERR_INTERNAL_ERROR;
726 const char *typename;
729 return SSH_ERR_INVALID_ARGUMENT;
731 if (sshkey_is_cert(key)) {
732 if (key->cert == NULL)
733 return SSH_ERR_EXPECTED_CERT;
734 if (sshbuf_len(key->cert->certblob) == 0)
735 return SSH_ERR_KEY_LACKS_CERTBLOB;
737 type = force_plain ? sshkey_type_plain(key->type) : key->type;
738 typename = sshkey_ssh_name_from_type_nid(type, key->ecdsa_nid);
745 #endif /* WITH_OPENSSL */
746 case KEY_ED25519_CERT:
747 /* Use the existing blob */
748 /* XXX modified flag? */
749 if ((ret = sshbuf_putb(b, key->cert->certblob)) != 0)
754 if (key->dsa == NULL)
755 return SSH_ERR_INVALID_ARGUMENT;
756 if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
757 (ret = sshbuf_put_bignum2(b, key->dsa->p)) != 0 ||
758 (ret = sshbuf_put_bignum2(b, key->dsa->q)) != 0 ||
759 (ret = sshbuf_put_bignum2(b, key->dsa->g)) != 0 ||
760 (ret = sshbuf_put_bignum2(b, key->dsa->pub_key)) != 0)
763 # ifdef OPENSSL_HAS_ECC
765 if (key->ecdsa == NULL)
766 return SSH_ERR_INVALID_ARGUMENT;
767 if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
768 (ret = sshbuf_put_cstring(b,
769 sshkey_curve_nid_to_name(key->ecdsa_nid))) != 0 ||
770 (ret = sshbuf_put_eckey(b, key->ecdsa)) != 0)
775 if (key->rsa == NULL)
776 return SSH_ERR_INVALID_ARGUMENT;
777 if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
778 (ret = sshbuf_put_bignum2(b, key->rsa->e)) != 0 ||
779 (ret = sshbuf_put_bignum2(b, key->rsa->n)) != 0)
782 #endif /* WITH_OPENSSL */
784 if (key->ed25519_pk == NULL)
785 return SSH_ERR_INVALID_ARGUMENT;
786 if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
787 (ret = sshbuf_put_string(b,
788 key->ed25519_pk, ED25519_PK_SZ)) != 0)
792 return SSH_ERR_KEY_TYPE_UNKNOWN;
798 sshkey_putb(const struct sshkey *key, struct sshbuf *b)
800 return to_blob_buf(key, b, 0);
804 sshkey_puts(const struct sshkey *key, struct sshbuf *b)
809 if ((tmp = sshbuf_new()) == NULL)
810 return SSH_ERR_ALLOC_FAIL;
811 r = to_blob_buf(key, tmp, 0);
813 r = sshbuf_put_stringb(b, tmp);
819 sshkey_putb_plain(const struct sshkey *key, struct sshbuf *b)
821 return to_blob_buf(key, b, 1);
825 to_blob(const struct sshkey *key, u_char **blobp, size_t *lenp, int force_plain)
827 int ret = SSH_ERR_INTERNAL_ERROR;
829 struct sshbuf *b = NULL;
835 if ((b = sshbuf_new()) == NULL)
836 return SSH_ERR_ALLOC_FAIL;
837 if ((ret = to_blob_buf(key, b, force_plain)) != 0)
843 if ((*blobp = malloc(len)) == NULL) {
844 ret = SSH_ERR_ALLOC_FAIL;
847 memcpy(*blobp, sshbuf_ptr(b), len);
856 sshkey_to_blob(const struct sshkey *key, u_char **blobp, size_t *lenp)
858 return to_blob(key, blobp, lenp, 0);
862 sshkey_plain_to_blob(const struct sshkey *key, u_char **blobp, size_t *lenp)
864 return to_blob(key, blobp, lenp, 1);
868 sshkey_fingerprint_raw(const struct sshkey *k, int dgst_alg,
869 u_char **retp, size_t *lenp)
871 u_char *blob = NULL, *ret = NULL;
873 int r = SSH_ERR_INTERNAL_ERROR;
879 if (ssh_digest_bytes(dgst_alg) == 0) {
880 r = SSH_ERR_INVALID_ARGUMENT;
884 if (k->type == KEY_RSA1) {
886 int nlen = BN_num_bytes(k->rsa->n);
887 int elen = BN_num_bytes(k->rsa->e);
889 if (nlen < 0 || elen < 0 || nlen >= INT_MAX - elen) {
890 r = SSH_ERR_INVALID_FORMAT;
893 blob_len = nlen + elen;
894 if ((blob = malloc(blob_len)) == NULL) {
895 r = SSH_ERR_ALLOC_FAIL;
898 BN_bn2bin(k->rsa->n, blob);
899 BN_bn2bin(k->rsa->e, blob + nlen);
900 #endif /* WITH_OPENSSL */
901 } else if ((r = to_blob(k, &blob, &blob_len, 1)) != 0)
903 if ((ret = calloc(1, SSH_DIGEST_MAX_LENGTH)) == NULL) {
904 r = SSH_ERR_ALLOC_FAIL;
907 if ((r = ssh_digest_memory(dgst_alg, blob, blob_len,
908 ret, SSH_DIGEST_MAX_LENGTH)) != 0)
916 *lenp = ssh_digest_bytes(dgst_alg);
921 explicit_bzero(blob, blob_len);
928 fingerprint_b64(const char *alg, u_char *dgst_raw, size_t dgst_raw_len)
931 size_t plen = strlen(alg) + 1;
932 size_t rlen = ((dgst_raw_len + 2) / 3) * 4 + plen + 1;
935 if (dgst_raw_len > 65536 || (ret = calloc(1, rlen)) == NULL)
937 strlcpy(ret, alg, rlen);
938 strlcat(ret, ":", rlen);
939 if (dgst_raw_len == 0)
941 if ((r = b64_ntop(dgst_raw, dgst_raw_len,
942 ret + plen, rlen - plen)) == -1) {
943 explicit_bzero(ret, rlen);
947 /* Trim padding characters from end */
948 ret[strcspn(ret, "=")] = '\0';
953 fingerprint_hex(const char *alg, u_char *dgst_raw, size_t dgst_raw_len)
955 char *retval, hex[5];
956 size_t i, rlen = dgst_raw_len * 3 + strlen(alg) + 2;
958 if (dgst_raw_len > 65536 || (retval = calloc(1, rlen)) == NULL)
960 strlcpy(retval, alg, rlen);
961 strlcat(retval, ":", rlen);
962 for (i = 0; i < dgst_raw_len; i++) {
963 snprintf(hex, sizeof(hex), "%s%02x",
964 i > 0 ? ":" : "", dgst_raw[i]);
965 strlcat(retval, hex, rlen);
971 fingerprint_bubblebabble(u_char *dgst_raw, size_t dgst_raw_len)
973 char vowels[] = { 'a', 'e', 'i', 'o', 'u', 'y' };
974 char consonants[] = { 'b', 'c', 'd', 'f', 'g', 'h', 'k', 'l', 'm',
975 'n', 'p', 'r', 's', 't', 'v', 'z', 'x' };
976 u_int i, j = 0, rounds, seed = 1;
979 rounds = (dgst_raw_len / 2) + 1;
980 if ((retval = calloc(rounds, 6)) == NULL)
983 for (i = 0; i < rounds; i++) {
984 u_int idx0, idx1, idx2, idx3, idx4;
985 if ((i + 1 < rounds) || (dgst_raw_len % 2 != 0)) {
986 idx0 = (((((u_int)(dgst_raw[2 * i])) >> 6) & 3) +
988 idx1 = (((u_int)(dgst_raw[2 * i])) >> 2) & 15;
989 idx2 = ((((u_int)(dgst_raw[2 * i])) & 3) +
991 retval[j++] = vowels[idx0];
992 retval[j++] = consonants[idx1];
993 retval[j++] = vowels[idx2];
994 if ((i + 1) < rounds) {
995 idx3 = (((u_int)(dgst_raw[(2 * i) + 1])) >> 4) & 15;
996 idx4 = (((u_int)(dgst_raw[(2 * i) + 1]))) & 15;
997 retval[j++] = consonants[idx3];
999 retval[j++] = consonants[idx4];
1000 seed = ((seed * 5) +
1001 ((((u_int)(dgst_raw[2 * i])) * 7) +
1002 ((u_int)(dgst_raw[(2 * i) + 1])))) % 36;
1008 retval[j++] = vowels[idx0];
1009 retval[j++] = consonants[idx1];
1010 retval[j++] = vowels[idx2];
1019 * Draw an ASCII-Art representing the fingerprint so human brain can
1020 * profit from its built-in pattern recognition ability.
1021 * This technique is called "random art" and can be found in some
1022 * scientific publications like this original paper:
1024 * "Hash Visualization: a New Technique to improve Real-World Security",
1025 * Perrig A. and Song D., 1999, International Workshop on Cryptographic
1026 * Techniques and E-Commerce (CrypTEC '99)
1027 * sparrow.ece.cmu.edu/~adrian/projects/validation/validation.pdf
1029 * The subject came up in a talk by Dan Kaminsky, too.
1031 * If you see the picture is different, the key is different.
1032 * If the picture looks the same, you still know nothing.
1034 * The algorithm used here is a worm crawling over a discrete plane,
1035 * leaving a trace (augmenting the field) everywhere it goes.
1036 * Movement is taken from dgst_raw 2bit-wise. Bumping into walls
1037 * makes the respective movement vector be ignored for this turn.
1038 * Graphs are not unambiguous, because circles in graphs can be
1039 * walked in either direction.
1043 * Field sizes for the random art. Have to be odd, so the starting point
1044 * can be in the exact middle of the picture, and FLDBASE should be >=8 .
1045 * Else pictures would be too dense, and drawing the frame would
1046 * fail, too, because the key type would not fit in anymore.
1049 #define FLDSIZE_Y (FLDBASE + 1)
1050 #define FLDSIZE_X (FLDBASE * 2 + 1)
1052 fingerprint_randomart(const char *alg, u_char *dgst_raw, size_t dgst_raw_len,
1053 const struct sshkey *k)
1056 * Chars to be used after each other every time the worm
1057 * intersects with itself. Matter of taste.
1059 char *augmentation_string = " .o+=*BOX@%&#/^SE";
1060 char *retval, *p, title[FLDSIZE_X], hash[FLDSIZE_X];
1061 u_char field[FLDSIZE_X][FLDSIZE_Y];
1062 size_t i, tlen, hlen;
1065 size_t len = strlen(augmentation_string) - 1;
1067 if ((retval = calloc((FLDSIZE_X + 3), (FLDSIZE_Y + 2))) == NULL)
1070 /* initialize field */
1071 memset(field, 0, FLDSIZE_X * FLDSIZE_Y * sizeof(char));
1075 /* process raw key */
1076 for (i = 0; i < dgst_raw_len; i++) {
1078 /* each byte conveys four 2-bit move commands */
1079 input = dgst_raw[i];
1080 for (b = 0; b < 4; b++) {
1081 /* evaluate 2 bit, rest is shifted later */
1082 x += (input & 0x1) ? 1 : -1;
1083 y += (input & 0x2) ? 1 : -1;
1085 /* assure we are still in bounds */
1088 x = MINIMUM(x, FLDSIZE_X - 1);
1089 y = MINIMUM(y, FLDSIZE_Y - 1);
1091 /* augment the field */
1092 if (field[x][y] < len - 2)
1098 /* mark starting point and end point*/
1099 field[FLDSIZE_X / 2][FLDSIZE_Y / 2] = len - 1;
1102 /* assemble title */
1103 r = snprintf(title, sizeof(title), "[%s %u]",
1104 sshkey_type(k), sshkey_size(k));
1105 /* If [type size] won't fit, then try [type]; fits "[ED25519-CERT]" */
1106 if (r < 0 || r > (int)sizeof(title))
1107 r = snprintf(title, sizeof(title), "[%s]", sshkey_type(k));
1108 tlen = (r <= 0) ? 0 : strlen(title);
1110 /* assemble hash ID. */
1111 r = snprintf(hash, sizeof(hash), "[%s]", alg);
1112 hlen = (r <= 0) ? 0 : strlen(hash);
1114 /* output upper border */
1117 for (i = 0; i < (FLDSIZE_X - tlen) / 2; i++)
1119 memcpy(p, title, tlen);
1121 for (i += tlen; i < FLDSIZE_X; i++)
1126 /* output content */
1127 for (y = 0; y < FLDSIZE_Y; y++) {
1129 for (x = 0; x < FLDSIZE_X; x++)
1130 *p++ = augmentation_string[MINIMUM(field[x][y], len)];
1135 /* output lower border */
1137 for (i = 0; i < (FLDSIZE_X - hlen) / 2; i++)
1139 memcpy(p, hash, hlen);
1141 for (i += hlen; i < FLDSIZE_X; i++)
1149 sshkey_fingerprint(const struct sshkey *k, int dgst_alg,
1150 enum sshkey_fp_rep dgst_rep)
1152 char *retval = NULL;
1154 size_t dgst_raw_len;
1156 if (sshkey_fingerprint_raw(k, dgst_alg, &dgst_raw, &dgst_raw_len) != 0)
1159 case SSH_FP_DEFAULT:
1160 if (dgst_alg == SSH_DIGEST_MD5) {
1161 retval = fingerprint_hex(ssh_digest_alg_name(dgst_alg),
1162 dgst_raw, dgst_raw_len);
1164 retval = fingerprint_b64(ssh_digest_alg_name(dgst_alg),
1165 dgst_raw, dgst_raw_len);
1169 retval = fingerprint_hex(ssh_digest_alg_name(dgst_alg),
1170 dgst_raw, dgst_raw_len);
1173 retval = fingerprint_b64(ssh_digest_alg_name(dgst_alg),
1174 dgst_raw, dgst_raw_len);
1176 case SSH_FP_BUBBLEBABBLE:
1177 retval = fingerprint_bubblebabble(dgst_raw, dgst_raw_len);
1179 case SSH_FP_RANDOMART:
1180 retval = fingerprint_randomart(ssh_digest_alg_name(dgst_alg),
1181 dgst_raw, dgst_raw_len, k);
1184 explicit_bzero(dgst_raw, dgst_raw_len);
1188 explicit_bzero(dgst_raw, dgst_raw_len);
1195 * Reads a multiple-precision integer in decimal from the buffer, and advances
1196 * the pointer. The integer must already be initialized. This function is
1197 * permitted to modify the buffer. This leaves *cpp to point just beyond the
1198 * last processed character.
1201 read_decimal_bignum(char **cpp, BIGNUM *v)
1205 int skip = 1; /* skip white space */
1208 while (*cp == ' ' || *cp == '\t')
1210 e = strspn(cp, "0123456789");
1212 return SSH_ERR_INVALID_FORMAT;
1213 if (e > SSHBUF_MAX_BIGNUM * 3)
1214 return SSH_ERR_BIGNUM_TOO_LARGE;
1217 else if (strchr(" \t\r\n", cp[e]) == NULL)
1218 return SSH_ERR_INVALID_FORMAT;
1220 if (BN_dec2bn(&v, cp) <= 0)
1221 return SSH_ERR_INVALID_FORMAT;
1222 *cpp = cp + e + skip;
1225 #endif /* WITH_SSH1 */
1227 /* returns 0 ok, and < 0 error */
1229 sshkey_read(struct sshkey *ret, char **cpp)
1232 int retval = SSH_ERR_INVALID_FORMAT;
1233 char *ep, *cp, *space;
1234 int r, type, curve_nid = -1;
1235 struct sshbuf *blob;
1238 #endif /* WITH_SSH1 */
1242 switch (ret->type) {
1245 /* Get number of bits. */
1246 bits = strtoul(cp, &ep, 10);
1247 if (*cp == '\0' || strchr(" \t\r\n", *ep) == NULL ||
1248 bits == 0 || bits > SSHBUF_MAX_BIGNUM * 8)
1249 return SSH_ERR_INVALID_FORMAT; /* Bad bit count... */
1250 /* Get public exponent, public modulus. */
1251 if ((r = read_decimal_bignum(&ep, ret->rsa->e)) < 0)
1253 if ((r = read_decimal_bignum(&ep, ret->rsa->n)) < 0)
1255 /* validate the claimed number of bits */
1256 if (BN_num_bits(ret->rsa->n) != (int)bits)
1257 return SSH_ERR_KEY_BITS_MISMATCH;
1260 #endif /* WITH_SSH1 */
1268 case KEY_ECDSA_CERT:
1270 case KEY_ED25519_CERT:
1271 space = strchr(cp, ' ');
1273 return SSH_ERR_INVALID_FORMAT;
1275 type = sshkey_type_from_name(cp);
1276 if (sshkey_type_plain(type) == KEY_ECDSA &&
1277 (curve_nid = sshkey_ecdsa_nid_from_name(cp)) == -1)
1278 return SSH_ERR_EC_CURVE_INVALID;
1280 if (type == KEY_UNSPEC)
1281 return SSH_ERR_INVALID_FORMAT;
1284 return SSH_ERR_INVALID_FORMAT;
1285 if (ret->type != KEY_UNSPEC && ret->type != type)
1286 return SSH_ERR_KEY_TYPE_MISMATCH;
1287 if ((blob = sshbuf_new()) == NULL)
1288 return SSH_ERR_ALLOC_FAIL;
1290 space = strchr(cp, ' ');
1292 /* advance 'space': skip whitespace */
1294 while (*space == ' ' || *space == '\t')
1298 ep = cp + strlen(cp);
1299 if ((r = sshbuf_b64tod(blob, cp)) != 0) {
1303 if ((r = sshkey_from_blob(sshbuf_ptr(blob),
1304 sshbuf_len(blob), &k)) != 0) {
1309 if (k->type != type) {
1311 return SSH_ERR_KEY_TYPE_MISMATCH;
1313 if (sshkey_type_plain(type) == KEY_ECDSA &&
1314 curve_nid != k->ecdsa_nid) {
1316 return SSH_ERR_EC_CURVE_MISMATCH;
1319 if (sshkey_is_cert(ret)) {
1320 if (!sshkey_is_cert(k)) {
1322 return SSH_ERR_EXPECTED_CERT;
1324 if (ret->cert != NULL)
1325 cert_free(ret->cert);
1326 ret->cert = k->cert;
1329 switch (sshkey_type_plain(ret->type)) {
1332 if (ret->rsa != NULL)
1337 RSA_print_fp(stderr, ret->rsa, 8);
1341 if (ret->dsa != NULL)
1346 DSA_print_fp(stderr, ret->dsa, 8);
1349 # ifdef OPENSSL_HAS_ECC
1351 if (ret->ecdsa != NULL)
1352 EC_KEY_free(ret->ecdsa);
1353 ret->ecdsa = k->ecdsa;
1354 ret->ecdsa_nid = k->ecdsa_nid;
1358 sshkey_dump_ec_key(ret->ecdsa);
1361 # endif /* OPENSSL_HAS_ECC */
1362 #endif /* WITH_OPENSSL */
1364 free(ret->ed25519_pk);
1365 ret->ed25519_pk = k->ed25519_pk;
1366 k->ed25519_pk = NULL;
1380 return SSH_ERR_INVALID_ARGUMENT;
1386 sshkey_to_base64(const struct sshkey *key, char **b64p)
1388 int r = SSH_ERR_INTERNAL_ERROR;
1389 struct sshbuf *b = NULL;
1394 if ((b = sshbuf_new()) == NULL)
1395 return SSH_ERR_ALLOC_FAIL;
1396 if ((r = sshkey_putb(key, b)) != 0)
1398 if ((uu = sshbuf_dtob64(b)) == NULL) {
1399 r = SSH_ERR_ALLOC_FAIL;
1415 sshkey_format_rsa1(const struct sshkey *key, struct sshbuf *b)
1417 int r = SSH_ERR_INTERNAL_ERROR;
1420 char *dec_e = NULL, *dec_n = NULL;
1422 if (key->rsa == NULL || key->rsa->e == NULL ||
1423 key->rsa->n == NULL) {
1424 r = SSH_ERR_INVALID_ARGUMENT;
1427 if ((dec_e = BN_bn2dec(key->rsa->e)) == NULL ||
1428 (dec_n = BN_bn2dec(key->rsa->n)) == NULL) {
1429 r = SSH_ERR_ALLOC_FAIL;
1432 /* size of modulus 'n' */
1433 if ((bits = BN_num_bits(key->rsa->n)) <= 0) {
1434 r = SSH_ERR_INVALID_ARGUMENT;
1437 if ((r = sshbuf_putf(b, "%u %s %s", bits, dec_e, dec_n)) != 0)
1444 OPENSSL_free(dec_e);
1446 OPENSSL_free(dec_n);
1447 #endif /* WITH_SSH1 */
1453 sshkey_format_text(const struct sshkey *key, struct sshbuf *b)
1455 int r = SSH_ERR_INTERNAL_ERROR;
1458 if (key->type == KEY_RSA1) {
1459 if ((r = sshkey_format_rsa1(key, b)) != 0)
1462 /* Unsupported key types handled in sshkey_to_base64() */
1463 if ((r = sshkey_to_base64(key, &uu)) != 0)
1465 if ((r = sshbuf_putf(b, "%s %s",
1466 sshkey_ssh_name(key), uu)) != 0)
1476 sshkey_write(const struct sshkey *key, FILE *f)
1478 struct sshbuf *b = NULL;
1479 int r = SSH_ERR_INTERNAL_ERROR;
1481 if ((b = sshbuf_new()) == NULL)
1482 return SSH_ERR_ALLOC_FAIL;
1483 if ((r = sshkey_format_text(key, b)) != 0)
1485 if (fwrite(sshbuf_ptr(b), sshbuf_len(b), 1, f) != 1) {
1488 r = SSH_ERR_SYSTEM_ERROR;
1499 sshkey_cert_type(const struct sshkey *k)
1501 switch (k->cert->type) {
1502 case SSH2_CERT_TYPE_USER:
1504 case SSH2_CERT_TYPE_HOST:
1513 rsa_generate_private_key(u_int bits, RSA **rsap)
1515 RSA *private = NULL;
1517 int ret = SSH_ERR_INTERNAL_ERROR;
1520 bits < SSH_RSA_MINIMUM_MODULUS_SIZE ||
1521 bits > SSHBUF_MAX_BIGNUM * 8)
1522 return SSH_ERR_INVALID_ARGUMENT;
1524 if ((private = RSA_new()) == NULL || (f4 = BN_new()) == NULL) {
1525 ret = SSH_ERR_ALLOC_FAIL;
1528 if (!BN_set_word(f4, RSA_F4) ||
1529 !RSA_generate_key_ex(private, bits, f4, NULL)) {
1530 ret = SSH_ERR_LIBCRYPTO_ERROR;
1537 if (private != NULL)
1545 dsa_generate_private_key(u_int bits, DSA **dsap)
1548 int ret = SSH_ERR_INTERNAL_ERROR;
1550 if (dsap == NULL || bits != 1024)
1551 return SSH_ERR_INVALID_ARGUMENT;
1552 if ((private = DSA_new()) == NULL) {
1553 ret = SSH_ERR_ALLOC_FAIL;
1557 if (!DSA_generate_parameters_ex(private, bits, NULL, 0, NULL,
1558 NULL, NULL) || !DSA_generate_key(private)) {
1559 ret = SSH_ERR_LIBCRYPTO_ERROR;
1566 if (private != NULL)
1571 # ifdef OPENSSL_HAS_ECC
1573 sshkey_ecdsa_key_to_nid(EC_KEY *k)
1577 NID_X9_62_prime256v1,
1579 # ifdef OPENSSL_HAS_NISTP521
1581 # endif /* OPENSSL_HAS_NISTP521 */
1587 const EC_GROUP *g = EC_KEY_get0_group(k);
1590 * The group may be stored in a ASN.1 encoded private key in one of two
1591 * ways: as a "named group", which is reconstituted by ASN.1 object ID
1592 * or explicit group parameters encoded into the key blob. Only the
1593 * "named group" case sets the group NID for us, but we can figure
1594 * it out for the other case by comparing against all the groups that
1597 if ((nid = EC_GROUP_get_curve_name(g)) > 0)
1599 if ((bnctx = BN_CTX_new()) == NULL)
1601 for (i = 0; nids[i] != -1; i++) {
1602 if ((eg = EC_GROUP_new_by_curve_name(nids[i])) == NULL) {
1606 if (EC_GROUP_cmp(g, eg, bnctx) == 0)
1611 if (nids[i] != -1) {
1612 /* Use the group with the NID attached */
1613 EC_GROUP_set_asn1_flag(eg, OPENSSL_EC_NAMED_CURVE);
1614 if (EC_KEY_set_group(k, eg) != 1) {
1623 ecdsa_generate_private_key(u_int bits, int *nid, EC_KEY **ecdsap)
1626 int ret = SSH_ERR_INTERNAL_ERROR;
1628 if (nid == NULL || ecdsap == NULL ||
1629 (*nid = sshkey_ecdsa_bits_to_nid(bits)) == -1)
1630 return SSH_ERR_INVALID_ARGUMENT;
1632 if ((private = EC_KEY_new_by_curve_name(*nid)) == NULL) {
1633 ret = SSH_ERR_ALLOC_FAIL;
1636 if (EC_KEY_generate_key(private) != 1) {
1637 ret = SSH_ERR_LIBCRYPTO_ERROR;
1640 EC_KEY_set_asn1_flag(private, OPENSSL_EC_NAMED_CURVE);
1645 if (private != NULL)
1646 EC_KEY_free(private);
1649 # endif /* OPENSSL_HAS_ECC */
1650 #endif /* WITH_OPENSSL */
1653 sshkey_generate(int type, u_int bits, struct sshkey **keyp)
1656 int ret = SSH_ERR_INTERNAL_ERROR;
1659 return SSH_ERR_INVALID_ARGUMENT;
1661 if ((k = sshkey_new(KEY_UNSPEC)) == NULL)
1662 return SSH_ERR_ALLOC_FAIL;
1665 if ((k->ed25519_pk = malloc(ED25519_PK_SZ)) == NULL ||
1666 (k->ed25519_sk = malloc(ED25519_SK_SZ)) == NULL) {
1667 ret = SSH_ERR_ALLOC_FAIL;
1670 crypto_sign_ed25519_keypair(k->ed25519_pk, k->ed25519_sk);
1675 ret = dsa_generate_private_key(bits, &k->dsa);
1677 # ifdef OPENSSL_HAS_ECC
1679 ret = ecdsa_generate_private_key(bits, &k->ecdsa_nid,
1682 # endif /* OPENSSL_HAS_ECC */
1685 ret = rsa_generate_private_key(bits, &k->rsa);
1687 #endif /* WITH_OPENSSL */
1689 ret = SSH_ERR_INVALID_ARGUMENT;
1700 sshkey_cert_copy(const struct sshkey *from_key, struct sshkey *to_key)
1703 const struct sshkey_cert *from;
1704 struct sshkey_cert *to;
1705 int ret = SSH_ERR_INTERNAL_ERROR;
1707 if (to_key->cert != NULL) {
1708 cert_free(to_key->cert);
1709 to_key->cert = NULL;
1712 if ((from = from_key->cert) == NULL)
1713 return SSH_ERR_INVALID_ARGUMENT;
1715 if ((to = to_key->cert = cert_new()) == NULL)
1716 return SSH_ERR_ALLOC_FAIL;
1718 if ((ret = sshbuf_putb(to->certblob, from->certblob)) != 0 ||
1719 (ret = sshbuf_putb(to->critical, from->critical)) != 0 ||
1720 (ret = sshbuf_putb(to->extensions, from->extensions)) != 0)
1723 to->serial = from->serial;
1724 to->type = from->type;
1725 if (from->key_id == NULL)
1727 else if ((to->key_id = strdup(from->key_id)) == NULL)
1728 return SSH_ERR_ALLOC_FAIL;
1729 to->valid_after = from->valid_after;
1730 to->valid_before = from->valid_before;
1731 if (from->signature_key == NULL)
1732 to->signature_key = NULL;
1733 else if ((ret = sshkey_from_private(from->signature_key,
1734 &to->signature_key)) != 0)
1737 if (from->nprincipals > SSHKEY_CERT_MAX_PRINCIPALS)
1738 return SSH_ERR_INVALID_ARGUMENT;
1739 if (from->nprincipals > 0) {
1740 if ((to->principals = calloc(from->nprincipals,
1741 sizeof(*to->principals))) == NULL)
1742 return SSH_ERR_ALLOC_FAIL;
1743 for (i = 0; i < from->nprincipals; i++) {
1744 to->principals[i] = strdup(from->principals[i]);
1745 if (to->principals[i] == NULL) {
1746 to->nprincipals = i;
1747 return SSH_ERR_ALLOC_FAIL;
1751 to->nprincipals = from->nprincipals;
1756 sshkey_from_private(const struct sshkey *k, struct sshkey **pkp)
1758 struct sshkey *n = NULL;
1759 int ret = SSH_ERR_INTERNAL_ERROR;
1766 if ((n = sshkey_new(k->type)) == NULL)
1767 return SSH_ERR_ALLOC_FAIL;
1768 if ((BN_copy(n->dsa->p, k->dsa->p) == NULL) ||
1769 (BN_copy(n->dsa->q, k->dsa->q) == NULL) ||
1770 (BN_copy(n->dsa->g, k->dsa->g) == NULL) ||
1771 (BN_copy(n->dsa->pub_key, k->dsa->pub_key) == NULL)) {
1773 return SSH_ERR_ALLOC_FAIL;
1776 # ifdef OPENSSL_HAS_ECC
1778 case KEY_ECDSA_CERT:
1779 if ((n = sshkey_new(k->type)) == NULL)
1780 return SSH_ERR_ALLOC_FAIL;
1781 n->ecdsa_nid = k->ecdsa_nid;
1782 n->ecdsa = EC_KEY_new_by_curve_name(k->ecdsa_nid);
1783 if (n->ecdsa == NULL) {
1785 return SSH_ERR_ALLOC_FAIL;
1787 if (EC_KEY_set_public_key(n->ecdsa,
1788 EC_KEY_get0_public_key(k->ecdsa)) != 1) {
1790 return SSH_ERR_LIBCRYPTO_ERROR;
1793 # endif /* OPENSSL_HAS_ECC */
1797 if ((n = sshkey_new(k->type)) == NULL)
1798 return SSH_ERR_ALLOC_FAIL;
1799 if ((BN_copy(n->rsa->n, k->rsa->n) == NULL) ||
1800 (BN_copy(n->rsa->e, k->rsa->e) == NULL)) {
1802 return SSH_ERR_ALLOC_FAIL;
1805 #endif /* WITH_OPENSSL */
1807 case KEY_ED25519_CERT:
1808 if ((n = sshkey_new(k->type)) == NULL)
1809 return SSH_ERR_ALLOC_FAIL;
1810 if (k->ed25519_pk != NULL) {
1811 if ((n->ed25519_pk = malloc(ED25519_PK_SZ)) == NULL) {
1813 return SSH_ERR_ALLOC_FAIL;
1815 memcpy(n->ed25519_pk, k->ed25519_pk, ED25519_PK_SZ);
1819 return SSH_ERR_KEY_TYPE_UNKNOWN;
1821 if (sshkey_is_cert(k)) {
1822 if ((ret = sshkey_cert_copy(k, n)) != 0) {
1832 cert_parse(struct sshbuf *b, struct sshkey *key, struct sshbuf *certbuf)
1834 struct sshbuf *principals = NULL, *crit = NULL;
1835 struct sshbuf *exts = NULL, *ca = NULL;
1837 size_t signed_len = 0, slen = 0, kidlen = 0;
1838 int ret = SSH_ERR_INTERNAL_ERROR;
1840 /* Copy the entire key blob for verification and later serialisation */
1841 if ((ret = sshbuf_putb(key->cert->certblob, certbuf)) != 0)
1844 /* Parse body of certificate up to signature */
1845 if ((ret = sshbuf_get_u64(b, &key->cert->serial)) != 0 ||
1846 (ret = sshbuf_get_u32(b, &key->cert->type)) != 0 ||
1847 (ret = sshbuf_get_cstring(b, &key->cert->key_id, &kidlen)) != 0 ||
1848 (ret = sshbuf_froms(b, &principals)) != 0 ||
1849 (ret = sshbuf_get_u64(b, &key->cert->valid_after)) != 0 ||
1850 (ret = sshbuf_get_u64(b, &key->cert->valid_before)) != 0 ||
1851 (ret = sshbuf_froms(b, &crit)) != 0 ||
1852 (ret = sshbuf_froms(b, &exts)) != 0 ||
1853 (ret = sshbuf_get_string_direct(b, NULL, NULL)) != 0 ||
1854 (ret = sshbuf_froms(b, &ca)) != 0) {
1855 /* XXX debug print error for ret */
1856 ret = SSH_ERR_INVALID_FORMAT;
1860 /* Signature is left in the buffer so we can calculate this length */
1861 signed_len = sshbuf_len(key->cert->certblob) - sshbuf_len(b);
1863 if ((ret = sshbuf_get_string(b, &sig, &slen)) != 0) {
1864 ret = SSH_ERR_INVALID_FORMAT;
1868 if (key->cert->type != SSH2_CERT_TYPE_USER &&
1869 key->cert->type != SSH2_CERT_TYPE_HOST) {
1870 ret = SSH_ERR_KEY_CERT_UNKNOWN_TYPE;
1874 /* Parse principals section */
1875 while (sshbuf_len(principals) > 0) {
1876 char *principal = NULL;
1877 char **oprincipals = NULL;
1879 if (key->cert->nprincipals >= SSHKEY_CERT_MAX_PRINCIPALS) {
1880 ret = SSH_ERR_INVALID_FORMAT;
1883 if ((ret = sshbuf_get_cstring(principals, &principal,
1885 ret = SSH_ERR_INVALID_FORMAT;
1888 oprincipals = key->cert->principals;
1889 key->cert->principals = reallocarray(key->cert->principals,
1890 key->cert->nprincipals + 1, sizeof(*key->cert->principals));
1891 if (key->cert->principals == NULL) {
1893 key->cert->principals = oprincipals;
1894 ret = SSH_ERR_ALLOC_FAIL;
1897 key->cert->principals[key->cert->nprincipals++] = principal;
1901 * Stash a copies of the critical options and extensions sections
1904 if ((ret = sshbuf_putb(key->cert->critical, crit)) != 0 ||
1906 (ret = sshbuf_putb(key->cert->extensions, exts)) != 0))
1910 * Validate critical options and extensions sections format.
1912 while (sshbuf_len(crit) != 0) {
1913 if ((ret = sshbuf_get_string_direct(crit, NULL, NULL)) != 0 ||
1914 (ret = sshbuf_get_string_direct(crit, NULL, NULL)) != 0) {
1915 sshbuf_reset(key->cert->critical);
1916 ret = SSH_ERR_INVALID_FORMAT;
1920 while (exts != NULL && sshbuf_len(exts) != 0) {
1921 if ((ret = sshbuf_get_string_direct(exts, NULL, NULL)) != 0 ||
1922 (ret = sshbuf_get_string_direct(exts, NULL, NULL)) != 0) {
1923 sshbuf_reset(key->cert->extensions);
1924 ret = SSH_ERR_INVALID_FORMAT;
1929 /* Parse CA key and check signature */
1930 if (sshkey_from_blob_internal(ca, &key->cert->signature_key, 0) != 0) {
1931 ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
1934 if (!sshkey_type_is_valid_ca(key->cert->signature_key->type)) {
1935 ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
1938 if ((ret = sshkey_verify(key->cert->signature_key, sig, slen,
1939 sshbuf_ptr(key->cert->certblob), signed_len, 0)) != 0)
1948 sshbuf_free(principals);
1954 sshkey_from_blob_internal(struct sshbuf *b, struct sshkey **keyp,
1957 int type, ret = SSH_ERR_INTERNAL_ERROR;
1958 char *ktype = NULL, *curve = NULL;
1959 struct sshkey *key = NULL;
1962 struct sshbuf *copy;
1963 #if defined(WITH_OPENSSL) && defined(OPENSSL_HAS_ECC)
1965 #endif /* WITH_OPENSSL && OPENSSL_HAS_ECC */
1967 #ifdef DEBUG_PK /* XXX */
1968 sshbuf_dump(b, stderr);
1972 if ((copy = sshbuf_fromb(b)) == NULL) {
1973 ret = SSH_ERR_ALLOC_FAIL;
1976 if (sshbuf_get_cstring(b, &ktype, NULL) != 0) {
1977 ret = SSH_ERR_INVALID_FORMAT;
1981 type = sshkey_type_from_name(ktype);
1982 if (!allow_cert && sshkey_type_is_cert(type)) {
1983 ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
1990 if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
1991 ret = SSH_ERR_INVALID_FORMAT;
1996 if ((key = sshkey_new(type)) == NULL) {
1997 ret = SSH_ERR_ALLOC_FAIL;
2000 if (sshbuf_get_bignum2(b, key->rsa->e) != 0 ||
2001 sshbuf_get_bignum2(b, key->rsa->n) != 0) {
2002 ret = SSH_ERR_INVALID_FORMAT;
2006 RSA_print_fp(stderr, key->rsa, 8);
2011 if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
2012 ret = SSH_ERR_INVALID_FORMAT;
2017 if ((key = sshkey_new(type)) == NULL) {
2018 ret = SSH_ERR_ALLOC_FAIL;
2021 if (sshbuf_get_bignum2(b, key->dsa->p) != 0 ||
2022 sshbuf_get_bignum2(b, key->dsa->q) != 0 ||
2023 sshbuf_get_bignum2(b, key->dsa->g) != 0 ||
2024 sshbuf_get_bignum2(b, key->dsa->pub_key) != 0) {
2025 ret = SSH_ERR_INVALID_FORMAT;
2029 DSA_print_fp(stderr, key->dsa, 8);
2032 case KEY_ECDSA_CERT:
2034 if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
2035 ret = SSH_ERR_INVALID_FORMAT;
2039 # ifdef OPENSSL_HAS_ECC
2041 if ((key = sshkey_new(type)) == NULL) {
2042 ret = SSH_ERR_ALLOC_FAIL;
2045 key->ecdsa_nid = sshkey_ecdsa_nid_from_name(ktype);
2046 if (sshbuf_get_cstring(b, &curve, NULL) != 0) {
2047 ret = SSH_ERR_INVALID_FORMAT;
2050 if (key->ecdsa_nid != sshkey_curve_name_to_nid(curve)) {
2051 ret = SSH_ERR_EC_CURVE_MISMATCH;
2054 if (key->ecdsa != NULL)
2055 EC_KEY_free(key->ecdsa);
2056 if ((key->ecdsa = EC_KEY_new_by_curve_name(key->ecdsa_nid))
2058 ret = SSH_ERR_EC_CURVE_INVALID;
2061 if ((q = EC_POINT_new(EC_KEY_get0_group(key->ecdsa))) == NULL) {
2062 ret = SSH_ERR_ALLOC_FAIL;
2065 if (sshbuf_get_ec(b, q, EC_KEY_get0_group(key->ecdsa)) != 0) {
2066 ret = SSH_ERR_INVALID_FORMAT;
2069 if (sshkey_ec_validate_public(EC_KEY_get0_group(key->ecdsa),
2071 ret = SSH_ERR_KEY_INVALID_EC_VALUE;
2074 if (EC_KEY_set_public_key(key->ecdsa, q) != 1) {
2075 /* XXX assume it is a allocation error */
2076 ret = SSH_ERR_ALLOC_FAIL;
2080 sshkey_dump_ec_point(EC_KEY_get0_group(key->ecdsa), q);
2083 # endif /* OPENSSL_HAS_ECC */
2084 #endif /* WITH_OPENSSL */
2085 case KEY_ED25519_CERT:
2087 if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
2088 ret = SSH_ERR_INVALID_FORMAT;
2093 if ((ret = sshbuf_get_string(b, &pk, &len)) != 0)
2095 if (len != ED25519_PK_SZ) {
2096 ret = SSH_ERR_INVALID_FORMAT;
2099 if ((key = sshkey_new(type)) == NULL) {
2100 ret = SSH_ERR_ALLOC_FAIL;
2103 key->ed25519_pk = pk;
2107 if ((key = sshkey_new(type)) == NULL) {
2108 ret = SSH_ERR_ALLOC_FAIL;
2113 ret = SSH_ERR_KEY_TYPE_UNKNOWN;
2117 /* Parse certificate potion */
2118 if (sshkey_is_cert(key) && (ret = cert_parse(b, key, copy)) != 0)
2121 if (key != NULL && sshbuf_len(b) != 0) {
2122 ret = SSH_ERR_INVALID_FORMAT;
2136 #if defined(WITH_OPENSSL) && defined(OPENSSL_HAS_ECC)
2139 #endif /* WITH_OPENSSL && OPENSSL_HAS_ECC */
2144 sshkey_from_blob(const u_char *blob, size_t blen, struct sshkey **keyp)
2149 if ((b = sshbuf_from(blob, blen)) == NULL)
2150 return SSH_ERR_ALLOC_FAIL;
2151 r = sshkey_from_blob_internal(b, keyp, 1);
2157 sshkey_fromb(struct sshbuf *b, struct sshkey **keyp)
2159 return sshkey_from_blob_internal(b, keyp, 1);
2163 sshkey_froms(struct sshbuf *buf, struct sshkey **keyp)
2168 if ((r = sshbuf_froms(buf, &b)) != 0)
2170 r = sshkey_from_blob_internal(b, keyp, 1);
2176 sshkey_sign(const struct sshkey *key,
2177 u_char **sigp, size_t *lenp,
2178 const u_char *data, size_t datalen, const char *alg, u_int compat)
2184 if (datalen > SSH_KEY_MAX_SIGN_DATA_SIZE)
2185 return SSH_ERR_INVALID_ARGUMENT;
2186 switch (key->type) {
2190 return ssh_dss_sign(key, sigp, lenp, data, datalen, compat);
2191 # ifdef OPENSSL_HAS_ECC
2192 case KEY_ECDSA_CERT:
2194 return ssh_ecdsa_sign(key, sigp, lenp, data, datalen, compat);
2195 # endif /* OPENSSL_HAS_ECC */
2198 return ssh_rsa_sign(key, sigp, lenp, data, datalen, alg);
2199 #endif /* WITH_OPENSSL */
2201 case KEY_ED25519_CERT:
2202 return ssh_ed25519_sign(key, sigp, lenp, data, datalen, compat);
2204 return SSH_ERR_KEY_TYPE_UNKNOWN;
2209 * ssh_key_verify returns 0 for a correct signature and < 0 on error.
2212 sshkey_verify(const struct sshkey *key,
2213 const u_char *sig, size_t siglen,
2214 const u_char *data, size_t dlen, u_int compat)
2216 if (siglen == 0 || dlen > SSH_KEY_MAX_SIGN_DATA_SIZE)
2217 return SSH_ERR_INVALID_ARGUMENT;
2218 switch (key->type) {
2222 return ssh_dss_verify(key, sig, siglen, data, dlen, compat);
2223 # ifdef OPENSSL_HAS_ECC
2224 case KEY_ECDSA_CERT:
2226 return ssh_ecdsa_verify(key, sig, siglen, data, dlen, compat);
2227 # endif /* OPENSSL_HAS_ECC */
2230 return ssh_rsa_verify(key, sig, siglen, data, dlen);
2231 #endif /* WITH_OPENSSL */
2233 case KEY_ED25519_CERT:
2234 return ssh_ed25519_verify(key, sig, siglen, data, dlen, compat);
2236 return SSH_ERR_KEY_TYPE_UNKNOWN;
2240 /* Converts a private to a public key */
2242 sshkey_demote(const struct sshkey *k, struct sshkey **dkp)
2245 int ret = SSH_ERR_INTERNAL_ERROR;
2248 if ((pk = calloc(1, sizeof(*pk))) == NULL)
2249 return SSH_ERR_ALLOC_FAIL;
2251 pk->flags = k->flags;
2252 pk->ecdsa_nid = k->ecdsa_nid;
2256 pk->ed25519_pk = NULL;
2257 pk->ed25519_sk = NULL;
2262 if ((ret = sshkey_cert_copy(k, pk)) != 0)
2267 if ((pk->rsa = RSA_new()) == NULL ||
2268 (pk->rsa->e = BN_dup(k->rsa->e)) == NULL ||
2269 (pk->rsa->n = BN_dup(k->rsa->n)) == NULL) {
2270 ret = SSH_ERR_ALLOC_FAIL;
2275 if ((ret = sshkey_cert_copy(k, pk)) != 0)
2279 if ((pk->dsa = DSA_new()) == NULL ||
2280 (pk->dsa->p = BN_dup(k->dsa->p)) == NULL ||
2281 (pk->dsa->q = BN_dup(k->dsa->q)) == NULL ||
2282 (pk->dsa->g = BN_dup(k->dsa->g)) == NULL ||
2283 (pk->dsa->pub_key = BN_dup(k->dsa->pub_key)) == NULL) {
2284 ret = SSH_ERR_ALLOC_FAIL;
2288 case KEY_ECDSA_CERT:
2289 if ((ret = sshkey_cert_copy(k, pk)) != 0)
2292 # ifdef OPENSSL_HAS_ECC
2294 pk->ecdsa = EC_KEY_new_by_curve_name(pk->ecdsa_nid);
2295 if (pk->ecdsa == NULL) {
2296 ret = SSH_ERR_ALLOC_FAIL;
2299 if (EC_KEY_set_public_key(pk->ecdsa,
2300 EC_KEY_get0_public_key(k->ecdsa)) != 1) {
2301 ret = SSH_ERR_LIBCRYPTO_ERROR;
2305 # endif /* OPENSSL_HAS_ECC */
2306 #endif /* WITH_OPENSSL */
2307 case KEY_ED25519_CERT:
2308 if ((ret = sshkey_cert_copy(k, pk)) != 0)
2312 if (k->ed25519_pk != NULL) {
2313 if ((pk->ed25519_pk = malloc(ED25519_PK_SZ)) == NULL) {
2314 ret = SSH_ERR_ALLOC_FAIL;
2317 memcpy(pk->ed25519_pk, k->ed25519_pk, ED25519_PK_SZ);
2321 ret = SSH_ERR_KEY_TYPE_UNKNOWN;
2330 /* Convert a plain key to their _CERT equivalent */
2332 sshkey_to_certified(struct sshkey *k)
2339 newtype = KEY_RSA_CERT;
2342 newtype = KEY_DSA_CERT;
2345 newtype = KEY_ECDSA_CERT;
2347 #endif /* WITH_OPENSSL */
2349 newtype = KEY_ED25519_CERT;
2352 return SSH_ERR_INVALID_ARGUMENT;
2354 if ((k->cert = cert_new()) == NULL)
2355 return SSH_ERR_ALLOC_FAIL;
2360 /* Convert a certificate to its raw key equivalent */
2362 sshkey_drop_cert(struct sshkey *k)
2364 if (!sshkey_type_is_cert(k->type))
2365 return SSH_ERR_KEY_TYPE_UNKNOWN;
2368 k->type = sshkey_type_plain(k->type);
2372 /* Sign a certified key, (re-)generating the signed certblob. */
2374 sshkey_certify(struct sshkey *k, struct sshkey *ca, const char *alg)
2376 struct sshbuf *principals = NULL;
2377 u_char *ca_blob = NULL, *sig_blob = NULL, nonce[32];
2378 size_t i, ca_len, sig_len;
2379 int ret = SSH_ERR_INTERNAL_ERROR;
2380 struct sshbuf *cert;
2382 if (k == NULL || k->cert == NULL ||
2383 k->cert->certblob == NULL || ca == NULL)
2384 return SSH_ERR_INVALID_ARGUMENT;
2385 if (!sshkey_is_cert(k))
2386 return SSH_ERR_KEY_TYPE_UNKNOWN;
2387 if (!sshkey_type_is_valid_ca(ca->type))
2388 return SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
2390 if ((ret = sshkey_to_blob(ca, &ca_blob, &ca_len)) != 0)
2391 return SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
2393 cert = k->cert->certblob; /* for readability */
2395 if ((ret = sshbuf_put_cstring(cert, sshkey_ssh_name(k))) != 0)
2398 /* -v01 certs put nonce first */
2399 arc4random_buf(&nonce, sizeof(nonce));
2400 if ((ret = sshbuf_put_string(cert, nonce, sizeof(nonce))) != 0)
2403 /* XXX this substantially duplicates to_blob(); refactor */
2407 if ((ret = sshbuf_put_bignum2(cert, k->dsa->p)) != 0 ||
2408 (ret = sshbuf_put_bignum2(cert, k->dsa->q)) != 0 ||
2409 (ret = sshbuf_put_bignum2(cert, k->dsa->g)) != 0 ||
2410 (ret = sshbuf_put_bignum2(cert, k->dsa->pub_key)) != 0)
2413 # ifdef OPENSSL_HAS_ECC
2414 case KEY_ECDSA_CERT:
2415 if ((ret = sshbuf_put_cstring(cert,
2416 sshkey_curve_nid_to_name(k->ecdsa_nid))) != 0 ||
2417 (ret = sshbuf_put_ec(cert,
2418 EC_KEY_get0_public_key(k->ecdsa),
2419 EC_KEY_get0_group(k->ecdsa))) != 0)
2422 # endif /* OPENSSL_HAS_ECC */
2424 if ((ret = sshbuf_put_bignum2(cert, k->rsa->e)) != 0 ||
2425 (ret = sshbuf_put_bignum2(cert, k->rsa->n)) != 0)
2428 #endif /* WITH_OPENSSL */
2429 case KEY_ED25519_CERT:
2430 if ((ret = sshbuf_put_string(cert,
2431 k->ed25519_pk, ED25519_PK_SZ)) != 0)
2435 ret = SSH_ERR_INVALID_ARGUMENT;
2439 if ((ret = sshbuf_put_u64(cert, k->cert->serial)) != 0 ||
2440 (ret = sshbuf_put_u32(cert, k->cert->type)) != 0 ||
2441 (ret = sshbuf_put_cstring(cert, k->cert->key_id)) != 0)
2444 if ((principals = sshbuf_new()) == NULL) {
2445 ret = SSH_ERR_ALLOC_FAIL;
2448 for (i = 0; i < k->cert->nprincipals; i++) {
2449 if ((ret = sshbuf_put_cstring(principals,
2450 k->cert->principals[i])) != 0)
2453 if ((ret = sshbuf_put_stringb(cert, principals)) != 0 ||
2454 (ret = sshbuf_put_u64(cert, k->cert->valid_after)) != 0 ||
2455 (ret = sshbuf_put_u64(cert, k->cert->valid_before)) != 0 ||
2456 (ret = sshbuf_put_stringb(cert, k->cert->critical)) != 0 ||
2457 (ret = sshbuf_put_stringb(cert, k->cert->extensions)) != 0 ||
2458 (ret = sshbuf_put_string(cert, NULL, 0)) != 0 || /* Reserved */
2459 (ret = sshbuf_put_string(cert, ca_blob, ca_len)) != 0)
2462 /* Sign the whole mess */
2463 if ((ret = sshkey_sign(ca, &sig_blob, &sig_len, sshbuf_ptr(cert),
2464 sshbuf_len(cert), alg, 0)) != 0)
2467 /* Append signature and we are done */
2468 if ((ret = sshbuf_put_string(cert, sig_blob, sig_len)) != 0)
2476 sshbuf_free(principals);
2481 sshkey_cert_check_authority(const struct sshkey *k,
2482 int want_host, int require_principal,
2483 const char *name, const char **reason)
2485 u_int i, principal_matches;
2486 time_t now = time(NULL);
2492 if (k->cert->type != SSH2_CERT_TYPE_HOST) {
2493 *reason = "Certificate invalid: not a host certificate";
2494 return SSH_ERR_KEY_CERT_INVALID;
2497 if (k->cert->type != SSH2_CERT_TYPE_USER) {
2498 *reason = "Certificate invalid: not a user certificate";
2499 return SSH_ERR_KEY_CERT_INVALID;
2503 /* yikes - system clock before epoch! */
2504 *reason = "Certificate invalid: not yet valid";
2505 return SSH_ERR_KEY_CERT_INVALID;
2507 if ((u_int64_t)now < k->cert->valid_after) {
2508 *reason = "Certificate invalid: not yet valid";
2509 return SSH_ERR_KEY_CERT_INVALID;
2511 if ((u_int64_t)now >= k->cert->valid_before) {
2512 *reason = "Certificate invalid: expired";
2513 return SSH_ERR_KEY_CERT_INVALID;
2515 if (k->cert->nprincipals == 0) {
2516 if (require_principal) {
2517 *reason = "Certificate lacks principal list";
2518 return SSH_ERR_KEY_CERT_INVALID;
2520 } else if (name != NULL) {
2521 principal_matches = 0;
2522 for (i = 0; i < k->cert->nprincipals; i++) {
2523 if (strcmp(name, k->cert->principals[i]) == 0) {
2524 principal_matches = 1;
2528 if (!principal_matches) {
2529 *reason = "Certificate invalid: name is not a listed "
2531 return SSH_ERR_KEY_CERT_INVALID;
2538 sshkey_format_cert_validity(const struct sshkey_cert *cert, char *s, size_t l)
2540 char from[32], to[32], ret[64];
2545 if (cert->valid_after == 0 &&
2546 cert->valid_before == 0xffffffffffffffffULL)
2547 return strlcpy(s, "forever", l);
2549 if (cert->valid_after != 0) {
2550 /* XXX revisit INT_MAX in 2038 :) */
2551 tt = cert->valid_after > INT_MAX ?
2552 INT_MAX : cert->valid_after;
2553 tm = localtime(&tt);
2554 strftime(from, sizeof(from), "%Y-%m-%dT%H:%M:%S", tm);
2556 if (cert->valid_before != 0xffffffffffffffffULL) {
2557 /* XXX revisit INT_MAX in 2038 :) */
2558 tt = cert->valid_before > INT_MAX ?
2559 INT_MAX : cert->valid_before;
2560 tm = localtime(&tt);
2561 strftime(to, sizeof(to), "%Y-%m-%dT%H:%M:%S", tm);
2564 if (cert->valid_after == 0)
2565 snprintf(ret, sizeof(ret), "before %s", to);
2566 else if (cert->valid_before == 0xffffffffffffffffULL)
2567 snprintf(ret, sizeof(ret), "after %s", from);
2569 snprintf(ret, sizeof(ret), "from %s to %s", from, to);
2571 return strlcpy(s, ret, l);
2575 sshkey_private_serialize(const struct sshkey *key, struct sshbuf *b)
2577 int r = SSH_ERR_INTERNAL_ERROR;
2579 if ((r = sshbuf_put_cstring(b, sshkey_ssh_name(key))) != 0)
2581 switch (key->type) {
2584 if ((r = sshbuf_put_bignum2(b, key->rsa->n)) != 0 ||
2585 (r = sshbuf_put_bignum2(b, key->rsa->e)) != 0 ||
2586 (r = sshbuf_put_bignum2(b, key->rsa->d)) != 0 ||
2587 (r = sshbuf_put_bignum2(b, key->rsa->iqmp)) != 0 ||
2588 (r = sshbuf_put_bignum2(b, key->rsa->p)) != 0 ||
2589 (r = sshbuf_put_bignum2(b, key->rsa->q)) != 0)
2593 if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
2594 r = SSH_ERR_INVALID_ARGUMENT;
2597 if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
2598 (r = sshbuf_put_bignum2(b, key->rsa->d)) != 0 ||
2599 (r = sshbuf_put_bignum2(b, key->rsa->iqmp)) != 0 ||
2600 (r = sshbuf_put_bignum2(b, key->rsa->p)) != 0 ||
2601 (r = sshbuf_put_bignum2(b, key->rsa->q)) != 0)
2605 if ((r = sshbuf_put_bignum2(b, key->dsa->p)) != 0 ||
2606 (r = sshbuf_put_bignum2(b, key->dsa->q)) != 0 ||
2607 (r = sshbuf_put_bignum2(b, key->dsa->g)) != 0 ||
2608 (r = sshbuf_put_bignum2(b, key->dsa->pub_key)) != 0 ||
2609 (r = sshbuf_put_bignum2(b, key->dsa->priv_key)) != 0)
2613 if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
2614 r = SSH_ERR_INVALID_ARGUMENT;
2617 if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
2618 (r = sshbuf_put_bignum2(b, key->dsa->priv_key)) != 0)
2621 # ifdef OPENSSL_HAS_ECC
2623 if ((r = sshbuf_put_cstring(b,
2624 sshkey_curve_nid_to_name(key->ecdsa_nid))) != 0 ||
2625 (r = sshbuf_put_eckey(b, key->ecdsa)) != 0 ||
2626 (r = sshbuf_put_bignum2(b,
2627 EC_KEY_get0_private_key(key->ecdsa))) != 0)
2630 case KEY_ECDSA_CERT:
2631 if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
2632 r = SSH_ERR_INVALID_ARGUMENT;
2635 if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
2636 (r = sshbuf_put_bignum2(b,
2637 EC_KEY_get0_private_key(key->ecdsa))) != 0)
2640 # endif /* OPENSSL_HAS_ECC */
2641 #endif /* WITH_OPENSSL */
2643 if ((r = sshbuf_put_string(b, key->ed25519_pk,
2644 ED25519_PK_SZ)) != 0 ||
2645 (r = sshbuf_put_string(b, key->ed25519_sk,
2646 ED25519_SK_SZ)) != 0)
2649 case KEY_ED25519_CERT:
2650 if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
2651 r = SSH_ERR_INVALID_ARGUMENT;
2654 if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
2655 (r = sshbuf_put_string(b, key->ed25519_pk,
2656 ED25519_PK_SZ)) != 0 ||
2657 (r = sshbuf_put_string(b, key->ed25519_sk,
2658 ED25519_SK_SZ)) != 0)
2662 r = SSH_ERR_INVALID_ARGUMENT;
2672 sshkey_private_deserialize(struct sshbuf *buf, struct sshkey **kp)
2674 char *tname = NULL, *curve = NULL;
2675 struct sshkey *k = NULL;
2676 size_t pklen = 0, sklen = 0;
2677 int type, r = SSH_ERR_INTERNAL_ERROR;
2678 u_char *ed25519_pk = NULL, *ed25519_sk = NULL;
2680 BIGNUM *exponent = NULL;
2681 #endif /* WITH_OPENSSL */
2685 if ((r = sshbuf_get_cstring(buf, &tname, NULL)) != 0)
2687 type = sshkey_type_from_name(tname);
2691 if ((k = sshkey_new_private(type)) == NULL) {
2692 r = SSH_ERR_ALLOC_FAIL;
2695 if ((r = sshbuf_get_bignum2(buf, k->dsa->p)) != 0 ||
2696 (r = sshbuf_get_bignum2(buf, k->dsa->q)) != 0 ||
2697 (r = sshbuf_get_bignum2(buf, k->dsa->g)) != 0 ||
2698 (r = sshbuf_get_bignum2(buf, k->dsa->pub_key)) != 0 ||
2699 (r = sshbuf_get_bignum2(buf, k->dsa->priv_key)) != 0)
2703 if ((r = sshkey_froms(buf, &k)) != 0 ||
2704 (r = sshkey_add_private(k)) != 0 ||
2705 (r = sshbuf_get_bignum2(buf, k->dsa->priv_key)) != 0)
2708 # ifdef OPENSSL_HAS_ECC
2710 if ((k = sshkey_new_private(type)) == NULL) {
2711 r = SSH_ERR_ALLOC_FAIL;
2714 if ((k->ecdsa_nid = sshkey_ecdsa_nid_from_name(tname)) == -1) {
2715 r = SSH_ERR_INVALID_ARGUMENT;
2718 if ((r = sshbuf_get_cstring(buf, &curve, NULL)) != 0)
2720 if (k->ecdsa_nid != sshkey_curve_name_to_nid(curve)) {
2721 r = SSH_ERR_EC_CURVE_MISMATCH;
2724 k->ecdsa = EC_KEY_new_by_curve_name(k->ecdsa_nid);
2725 if (k->ecdsa == NULL || (exponent = BN_new()) == NULL) {
2726 r = SSH_ERR_LIBCRYPTO_ERROR;
2729 if ((r = sshbuf_get_eckey(buf, k->ecdsa)) != 0 ||
2730 (r = sshbuf_get_bignum2(buf, exponent)))
2732 if (EC_KEY_set_private_key(k->ecdsa, exponent) != 1) {
2733 r = SSH_ERR_LIBCRYPTO_ERROR;
2736 if ((r = sshkey_ec_validate_public(EC_KEY_get0_group(k->ecdsa),
2737 EC_KEY_get0_public_key(k->ecdsa))) != 0 ||
2738 (r = sshkey_ec_validate_private(k->ecdsa)) != 0)
2741 case KEY_ECDSA_CERT:
2742 if ((exponent = BN_new()) == NULL) {
2743 r = SSH_ERR_LIBCRYPTO_ERROR;
2746 if ((r = sshkey_froms(buf, &k)) != 0 ||
2747 (r = sshkey_add_private(k)) != 0 ||
2748 (r = sshbuf_get_bignum2(buf, exponent)) != 0)
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 # endif /* OPENSSL_HAS_ECC */
2761 if ((k = sshkey_new_private(type)) == NULL) {
2762 r = SSH_ERR_ALLOC_FAIL;
2765 if ((r = sshbuf_get_bignum2(buf, k->rsa->n)) != 0 ||
2766 (r = sshbuf_get_bignum2(buf, k->rsa->e)) != 0 ||
2767 (r = sshbuf_get_bignum2(buf, k->rsa->d)) != 0 ||
2768 (r = sshbuf_get_bignum2(buf, k->rsa->iqmp)) != 0 ||
2769 (r = sshbuf_get_bignum2(buf, k->rsa->p)) != 0 ||
2770 (r = sshbuf_get_bignum2(buf, k->rsa->q)) != 0 ||
2771 (r = rsa_generate_additional_parameters(k->rsa)) != 0)
2775 if ((r = sshkey_froms(buf, &k)) != 0 ||
2776 (r = sshkey_add_private(k)) != 0 ||
2777 (r = sshbuf_get_bignum2(buf, k->rsa->d)) != 0 ||
2778 (r = sshbuf_get_bignum2(buf, k->rsa->iqmp)) != 0 ||
2779 (r = sshbuf_get_bignum2(buf, k->rsa->p)) != 0 ||
2780 (r = sshbuf_get_bignum2(buf, k->rsa->q)) != 0 ||
2781 (r = rsa_generate_additional_parameters(k->rsa)) != 0)
2784 #endif /* WITH_OPENSSL */
2786 if ((k = sshkey_new_private(type)) == NULL) {
2787 r = SSH_ERR_ALLOC_FAIL;
2790 if ((r = sshbuf_get_string(buf, &ed25519_pk, &pklen)) != 0 ||
2791 (r = sshbuf_get_string(buf, &ed25519_sk, &sklen)) != 0)
2793 if (pklen != ED25519_PK_SZ || sklen != ED25519_SK_SZ) {
2794 r = SSH_ERR_INVALID_FORMAT;
2797 k->ed25519_pk = ed25519_pk;
2798 k->ed25519_sk = ed25519_sk;
2799 ed25519_pk = ed25519_sk = NULL;
2801 case KEY_ED25519_CERT:
2802 if ((r = sshkey_froms(buf, &k)) != 0 ||
2803 (r = sshkey_add_private(k)) != 0 ||
2804 (r = sshbuf_get_string(buf, &ed25519_pk, &pklen)) != 0 ||
2805 (r = sshbuf_get_string(buf, &ed25519_sk, &sklen)) != 0)
2807 if (pklen != ED25519_PK_SZ || sklen != ED25519_SK_SZ) {
2808 r = SSH_ERR_INVALID_FORMAT;
2811 k->ed25519_pk = ed25519_pk;
2812 k->ed25519_sk = ed25519_sk;
2813 ed25519_pk = ed25519_sk = NULL;
2816 r = SSH_ERR_KEY_TYPE_UNKNOWN;
2820 /* enable blinding */
2825 if (RSA_blinding_on(k->rsa, NULL) != 1) {
2826 r = SSH_ERR_LIBCRYPTO_ERROR;
2831 #endif /* WITH_OPENSSL */
2842 if (exponent != NULL)
2843 BN_clear_free(exponent);
2844 #endif /* WITH_OPENSSL */
2846 if (ed25519_pk != NULL) {
2847 explicit_bzero(ed25519_pk, pklen);
2850 if (ed25519_sk != NULL) {
2851 explicit_bzero(ed25519_sk, sklen);
2857 #if defined(WITH_OPENSSL) && defined(OPENSSL_HAS_ECC)
2859 sshkey_ec_validate_public(const EC_GROUP *group, const EC_POINT *public)
2862 EC_POINT *nq = NULL;
2863 BIGNUM *order, *x, *y, *tmp;
2864 int ret = SSH_ERR_KEY_INVALID_EC_VALUE;
2867 * NB. This assumes OpenSSL has already verified that the public
2868 * point lies on the curve. This is done by EC_POINT_oct2point()
2869 * implicitly calling EC_POINT_is_on_curve(). If this code is ever
2870 * reachable with public points not unmarshalled using
2871 * EC_POINT_oct2point then the caller will need to explicitly check.
2874 if ((bnctx = BN_CTX_new()) == NULL)
2875 return SSH_ERR_ALLOC_FAIL;
2876 BN_CTX_start(bnctx);
2879 * We shouldn't ever hit this case because bignum_get_ecpoint()
2880 * refuses to load GF2m points.
2882 if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) !=
2883 NID_X9_62_prime_field)
2887 if (EC_POINT_is_at_infinity(group, public))
2890 if ((x = BN_CTX_get(bnctx)) == NULL ||
2891 (y = BN_CTX_get(bnctx)) == NULL ||
2892 (order = BN_CTX_get(bnctx)) == NULL ||
2893 (tmp = BN_CTX_get(bnctx)) == NULL) {
2894 ret = SSH_ERR_ALLOC_FAIL;
2898 /* log2(x) > log2(order)/2, log2(y) > log2(order)/2 */
2899 if (EC_GROUP_get_order(group, order, bnctx) != 1 ||
2900 EC_POINT_get_affine_coordinates_GFp(group, public,
2901 x, y, bnctx) != 1) {
2902 ret = SSH_ERR_LIBCRYPTO_ERROR;
2905 if (BN_num_bits(x) <= BN_num_bits(order) / 2 ||
2906 BN_num_bits(y) <= BN_num_bits(order) / 2)
2909 /* nQ == infinity (n == order of subgroup) */
2910 if ((nq = EC_POINT_new(group)) == NULL) {
2911 ret = SSH_ERR_ALLOC_FAIL;
2914 if (EC_POINT_mul(group, nq, NULL, public, order, bnctx) != 1) {
2915 ret = SSH_ERR_LIBCRYPTO_ERROR;
2918 if (EC_POINT_is_at_infinity(group, nq) != 1)
2921 /* x < order - 1, y < order - 1 */
2922 if (!BN_sub(tmp, order, BN_value_one())) {
2923 ret = SSH_ERR_LIBCRYPTO_ERROR;
2926 if (BN_cmp(x, tmp) >= 0 || BN_cmp(y, tmp) >= 0)
2937 sshkey_ec_validate_private(const EC_KEY *key)
2940 BIGNUM *order, *tmp;
2941 int ret = SSH_ERR_KEY_INVALID_EC_VALUE;
2943 if ((bnctx = BN_CTX_new()) == NULL)
2944 return SSH_ERR_ALLOC_FAIL;
2945 BN_CTX_start(bnctx);
2947 if ((order = BN_CTX_get(bnctx)) == NULL ||
2948 (tmp = BN_CTX_get(bnctx)) == NULL) {
2949 ret = SSH_ERR_ALLOC_FAIL;
2953 /* log2(private) > log2(order)/2 */
2954 if (EC_GROUP_get_order(EC_KEY_get0_group(key), order, bnctx) != 1) {
2955 ret = SSH_ERR_LIBCRYPTO_ERROR;
2958 if (BN_num_bits(EC_KEY_get0_private_key(key)) <=
2959 BN_num_bits(order) / 2)
2962 /* private < order - 1 */
2963 if (!BN_sub(tmp, order, BN_value_one())) {
2964 ret = SSH_ERR_LIBCRYPTO_ERROR;
2967 if (BN_cmp(EC_KEY_get0_private_key(key), tmp) >= 0)
2976 sshkey_dump_ec_point(const EC_GROUP *group, const EC_POINT *point)
2981 if (point == NULL) {
2982 fputs("point=(NULL)\n", stderr);
2985 if ((bnctx = BN_CTX_new()) == NULL) {
2986 fprintf(stderr, "%s: BN_CTX_new failed\n", __func__);
2989 BN_CTX_start(bnctx);
2990 if ((x = BN_CTX_get(bnctx)) == NULL ||
2991 (y = BN_CTX_get(bnctx)) == NULL) {
2992 fprintf(stderr, "%s: BN_CTX_get failed\n", __func__);
2995 if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) !=
2996 NID_X9_62_prime_field) {
2997 fprintf(stderr, "%s: group is not a prime field\n", __func__);
3000 if (EC_POINT_get_affine_coordinates_GFp(group, point, x, y,
3002 fprintf(stderr, "%s: EC_POINT_get_affine_coordinates_GFp\n",
3006 fputs("x=", stderr);
3007 BN_print_fp(stderr, x);
3008 fputs("\ny=", stderr);
3009 BN_print_fp(stderr, y);
3010 fputs("\n", stderr);
3015 sshkey_dump_ec_key(const EC_KEY *key)
3017 const BIGNUM *exponent;
3019 sshkey_dump_ec_point(EC_KEY_get0_group(key),
3020 EC_KEY_get0_public_key(key));
3021 fputs("exponent=", stderr);
3022 if ((exponent = EC_KEY_get0_private_key(key)) == NULL)
3023 fputs("(NULL)", stderr);
3025 BN_print_fp(stderr, EC_KEY_get0_private_key(key));
3026 fputs("\n", stderr);
3028 #endif /* WITH_OPENSSL && OPENSSL_HAS_ECC */
3031 sshkey_private_to_blob2(const struct sshkey *prv, struct sshbuf *blob,
3032 const char *passphrase, const char *comment, const char *ciphername,
3035 u_char *cp, *key = NULL, *pubkeyblob = NULL;
3036 u_char salt[SALT_LEN];
3038 size_t i, pubkeylen, keylen, ivlen, blocksize, authlen;
3040 int r = SSH_ERR_INTERNAL_ERROR;
3041 struct sshcipher_ctx *ciphercontext = NULL;
3042 const struct sshcipher *cipher;
3043 const char *kdfname = KDFNAME;
3044 struct sshbuf *encoded = NULL, *encrypted = NULL, *kdf = NULL;
3047 rounds = DEFAULT_ROUNDS;
3048 if (passphrase == NULL || !strlen(passphrase)) {
3049 ciphername = "none";
3051 } else if (ciphername == NULL)
3052 ciphername = DEFAULT_CIPHERNAME;
3053 else if (cipher_number(ciphername) != SSH_CIPHER_SSH2) {
3054 r = SSH_ERR_INVALID_ARGUMENT;
3057 if ((cipher = cipher_by_name(ciphername)) == NULL) {
3058 r = SSH_ERR_INTERNAL_ERROR;
3062 if ((kdf = sshbuf_new()) == NULL ||
3063 (encoded = sshbuf_new()) == NULL ||
3064 (encrypted = sshbuf_new()) == NULL) {
3065 r = SSH_ERR_ALLOC_FAIL;
3068 blocksize = cipher_blocksize(cipher);
3069 keylen = cipher_keylen(cipher);
3070 ivlen = cipher_ivlen(cipher);
3071 authlen = cipher_authlen(cipher);
3072 if ((key = calloc(1, keylen + ivlen)) == NULL) {
3073 r = SSH_ERR_ALLOC_FAIL;
3076 if (strcmp(kdfname, "bcrypt") == 0) {
3077 arc4random_buf(salt, SALT_LEN);
3078 if (bcrypt_pbkdf(passphrase, strlen(passphrase),
3079 salt, SALT_LEN, key, keylen + ivlen, rounds) < 0) {
3080 r = SSH_ERR_INVALID_ARGUMENT;
3083 if ((r = sshbuf_put_string(kdf, salt, SALT_LEN)) != 0 ||
3084 (r = sshbuf_put_u32(kdf, rounds)) != 0)
3086 } else if (strcmp(kdfname, "none") != 0) {
3087 /* Unsupported KDF type */
3088 r = SSH_ERR_KEY_UNKNOWN_CIPHER;
3091 if ((r = cipher_init(&ciphercontext, cipher, key, keylen,
3092 key + keylen, ivlen, 1)) != 0)
3095 if ((r = sshbuf_put(encoded, AUTH_MAGIC, sizeof(AUTH_MAGIC))) != 0 ||
3096 (r = sshbuf_put_cstring(encoded, ciphername)) != 0 ||
3097 (r = sshbuf_put_cstring(encoded, kdfname)) != 0 ||
3098 (r = sshbuf_put_stringb(encoded, kdf)) != 0 ||
3099 (r = sshbuf_put_u32(encoded, 1)) != 0 || /* number of keys */
3100 (r = sshkey_to_blob(prv, &pubkeyblob, &pubkeylen)) != 0 ||
3101 (r = sshbuf_put_string(encoded, pubkeyblob, pubkeylen)) != 0)
3104 /* set up the buffer that will be encrypted */
3106 /* Random check bytes */
3107 check = arc4random();
3108 if ((r = sshbuf_put_u32(encrypted, check)) != 0 ||
3109 (r = sshbuf_put_u32(encrypted, check)) != 0)
3112 /* append private key and comment*/
3113 if ((r = sshkey_private_serialize(prv, encrypted)) != 0 ||
3114 (r = sshbuf_put_cstring(encrypted, comment)) != 0)
3119 while (sshbuf_len(encrypted) % blocksize) {
3120 if ((r = sshbuf_put_u8(encrypted, ++i & 0xff)) != 0)
3124 /* length in destination buffer */
3125 if ((r = sshbuf_put_u32(encoded, sshbuf_len(encrypted))) != 0)
3129 if ((r = sshbuf_reserve(encoded,
3130 sshbuf_len(encrypted) + authlen, &cp)) != 0)
3132 if ((r = cipher_crypt(ciphercontext, 0, cp,
3133 sshbuf_ptr(encrypted), sshbuf_len(encrypted), 0, authlen)) != 0)
3137 if ((b64 = sshbuf_dtob64(encoded)) == NULL) {
3138 r = SSH_ERR_ALLOC_FAIL;
3143 if ((r = sshbuf_put(blob, MARK_BEGIN, MARK_BEGIN_LEN)) != 0)
3145 for (i = 0; i < strlen(b64); i++) {
3146 if ((r = sshbuf_put_u8(blob, b64[i])) != 0)
3148 /* insert line breaks */
3149 if (i % 70 == 69 && (r = sshbuf_put_u8(blob, '\n')) != 0)
3152 if (i % 70 != 69 && (r = sshbuf_put_u8(blob, '\n')) != 0)
3154 if ((r = sshbuf_put(blob, MARK_END, MARK_END_LEN)) != 0)
3162 sshbuf_free(encoded);
3163 sshbuf_free(encrypted);
3164 cipher_free(ciphercontext);
3165 explicit_bzero(salt, sizeof(salt));
3167 explicit_bzero(key, keylen + ivlen);
3170 if (pubkeyblob != NULL) {
3171 explicit_bzero(pubkeyblob, pubkeylen);
3175 explicit_bzero(b64, strlen(b64));
3182 sshkey_parse_private2(struct sshbuf *blob, int type, const char *passphrase,
3183 struct sshkey **keyp, char **commentp)
3185 char *comment = NULL, *ciphername = NULL, *kdfname = NULL;
3186 const struct sshcipher *cipher = NULL;
3188 int r = SSH_ERR_INTERNAL_ERROR;
3190 size_t i, keylen = 0, ivlen = 0, authlen = 0, slen = 0;
3191 struct sshbuf *encoded = NULL, *decoded = NULL;
3192 struct sshbuf *kdf = NULL, *decrypted = NULL;
3193 struct sshcipher_ctx *ciphercontext = NULL;
3194 struct sshkey *k = NULL;
3195 u_char *key = NULL, *salt = NULL, *dp, pad, last;
3196 u_int blocksize, rounds, nkeys, encrypted_len, check1, check2;
3200 if (commentp != NULL)
3203 if ((encoded = sshbuf_new()) == NULL ||
3204 (decoded = sshbuf_new()) == NULL ||
3205 (decrypted = sshbuf_new()) == NULL) {
3206 r = SSH_ERR_ALLOC_FAIL;
3210 /* check preamble */
3211 cp = sshbuf_ptr(blob);
3212 encoded_len = sshbuf_len(blob);
3213 if (encoded_len < (MARK_BEGIN_LEN + MARK_END_LEN) ||
3214 memcmp(cp, MARK_BEGIN, MARK_BEGIN_LEN) != 0) {
3215 r = SSH_ERR_INVALID_FORMAT;
3218 cp += MARK_BEGIN_LEN;
3219 encoded_len -= MARK_BEGIN_LEN;
3221 /* Look for end marker, removing whitespace as we go */
3222 while (encoded_len > 0) {
3223 if (*cp != '\n' && *cp != '\r') {
3224 if ((r = sshbuf_put_u8(encoded, *cp)) != 0)
3231 if (encoded_len >= MARK_END_LEN &&
3232 memcmp(cp, MARK_END, MARK_END_LEN) == 0) {
3234 if ((r = sshbuf_put_u8(encoded, 0)) != 0)
3240 if (encoded_len == 0) {
3241 r = SSH_ERR_INVALID_FORMAT;
3246 if ((r = sshbuf_b64tod(decoded, (char *)sshbuf_ptr(encoded))) != 0)
3250 if (sshbuf_len(decoded) < sizeof(AUTH_MAGIC) ||
3251 memcmp(sshbuf_ptr(decoded), AUTH_MAGIC, sizeof(AUTH_MAGIC))) {
3252 r = SSH_ERR_INVALID_FORMAT;
3255 /* parse public portion of key */
3256 if ((r = sshbuf_consume(decoded, sizeof(AUTH_MAGIC))) != 0 ||
3257 (r = sshbuf_get_cstring(decoded, &ciphername, NULL)) != 0 ||
3258 (r = sshbuf_get_cstring(decoded, &kdfname, NULL)) != 0 ||
3259 (r = sshbuf_froms(decoded, &kdf)) != 0 ||
3260 (r = sshbuf_get_u32(decoded, &nkeys)) != 0 ||
3261 (r = sshbuf_skip_string(decoded)) != 0 || /* pubkey */
3262 (r = sshbuf_get_u32(decoded, &encrypted_len)) != 0)
3265 if ((cipher = cipher_by_name(ciphername)) == NULL) {
3266 r = SSH_ERR_KEY_UNKNOWN_CIPHER;
3269 if ((passphrase == NULL || strlen(passphrase) == 0) &&
3270 strcmp(ciphername, "none") != 0) {
3271 /* passphrase required */
3272 r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3275 if (strcmp(kdfname, "none") != 0 && strcmp(kdfname, "bcrypt") != 0) {
3276 r = SSH_ERR_KEY_UNKNOWN_CIPHER;
3279 if (!strcmp(kdfname, "none") && strcmp(ciphername, "none") != 0) {
3280 r = SSH_ERR_INVALID_FORMAT;
3284 /* XXX only one key supported */
3285 r = SSH_ERR_INVALID_FORMAT;
3289 /* check size of encrypted key blob */
3290 blocksize = cipher_blocksize(cipher);
3291 if (encrypted_len < blocksize || (encrypted_len % blocksize) != 0) {
3292 r = SSH_ERR_INVALID_FORMAT;
3297 keylen = cipher_keylen(cipher);
3298 ivlen = cipher_ivlen(cipher);
3299 authlen = cipher_authlen(cipher);
3300 if ((key = calloc(1, keylen + ivlen)) == NULL) {
3301 r = SSH_ERR_ALLOC_FAIL;
3304 if (strcmp(kdfname, "bcrypt") == 0) {
3305 if ((r = sshbuf_get_string(kdf, &salt, &slen)) != 0 ||
3306 (r = sshbuf_get_u32(kdf, &rounds)) != 0)
3308 if (bcrypt_pbkdf(passphrase, strlen(passphrase), salt, slen,
3309 key, keylen + ivlen, rounds) < 0) {
3310 r = SSH_ERR_INVALID_FORMAT;
3315 /* check that an appropriate amount of auth data is present */
3316 if (sshbuf_len(decoded) < encrypted_len + authlen) {
3317 r = SSH_ERR_INVALID_FORMAT;
3321 /* decrypt private portion of key */
3322 if ((r = sshbuf_reserve(decrypted, encrypted_len, &dp)) != 0 ||
3323 (r = cipher_init(&ciphercontext, cipher, key, keylen,
3324 key + keylen, ivlen, 0)) != 0)
3326 if ((r = cipher_crypt(ciphercontext, 0, dp, sshbuf_ptr(decoded),
3327 encrypted_len, 0, authlen)) != 0) {
3328 /* an integrity error here indicates an incorrect passphrase */
3329 if (r == SSH_ERR_MAC_INVALID)
3330 r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3333 if ((r = sshbuf_consume(decoded, encrypted_len + authlen)) != 0)
3335 /* there should be no trailing data */
3336 if (sshbuf_len(decoded) != 0) {
3337 r = SSH_ERR_INVALID_FORMAT;
3341 /* check check bytes */
3342 if ((r = sshbuf_get_u32(decrypted, &check1)) != 0 ||
3343 (r = sshbuf_get_u32(decrypted, &check2)) != 0)
3345 if (check1 != check2) {
3346 r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3350 /* Load the private key and comment */
3351 if ((r = sshkey_private_deserialize(decrypted, &k)) != 0 ||
3352 (r = sshbuf_get_cstring(decrypted, &comment, NULL)) != 0)
3355 /* Check deterministic padding */
3357 while (sshbuf_len(decrypted)) {
3358 if ((r = sshbuf_get_u8(decrypted, &pad)) != 0)
3360 if (pad != (++i & 0xff)) {
3361 r = SSH_ERR_INVALID_FORMAT;
3366 /* XXX decode pubkey and check against private */
3374 if (commentp != NULL) {
3375 *commentp = comment;
3380 cipher_free(ciphercontext);
3385 explicit_bzero(salt, slen);
3389 explicit_bzero(key, keylen + ivlen);
3392 sshbuf_free(encoded);
3393 sshbuf_free(decoded);
3395 sshbuf_free(decrypted);
3402 * Serialises the authentication (private) key to a blob, encrypting it with
3403 * passphrase. The identification of the blob (lowest 64 bits of n) will
3404 * precede the key to provide identification of the key without needing a
3408 sshkey_private_rsa1_to_blob(struct sshkey *key, struct sshbuf *blob,
3409 const char *passphrase, const char *comment)
3411 struct sshbuf *buffer = NULL, *encrypted = NULL;
3414 struct sshcipher_ctx *ciphercontext = NULL;
3415 const struct sshcipher *cipher;
3419 * If the passphrase is empty, use SSH_CIPHER_NONE to ease converting
3420 * to another cipher; otherwise use SSH_AUTHFILE_CIPHER.
3422 cipher_num = (strcmp(passphrase, "") == 0) ?
3423 SSH_CIPHER_NONE : SSH_CIPHER_3DES;
3424 if ((cipher = cipher_by_number(cipher_num)) == NULL)
3425 return SSH_ERR_INTERNAL_ERROR;
3427 /* This buffer is used to build the secret part of the private key. */
3428 if ((buffer = sshbuf_new()) == NULL)
3429 return SSH_ERR_ALLOC_FAIL;
3431 /* Put checkbytes for checking passphrase validity. */
3432 if ((r = sshbuf_reserve(buffer, 4, &cp)) != 0)
3434 arc4random_buf(cp, 2);
3435 memcpy(cp + 2, cp, 2);
3438 * Store the private key (n and e will not be stored because they
3439 * will be stored in plain text, and storing them also in encrypted
3440 * format would just give known plaintext).
3441 * Note: q and p are stored in reverse order to SSL.
3443 if ((r = sshbuf_put_bignum1(buffer, key->rsa->d)) != 0 ||
3444 (r = sshbuf_put_bignum1(buffer, key->rsa->iqmp)) != 0 ||
3445 (r = sshbuf_put_bignum1(buffer, key->rsa->q)) != 0 ||
3446 (r = sshbuf_put_bignum1(buffer, key->rsa->p)) != 0)
3449 /* Pad the part to be encrypted to a size that is a multiple of 8. */
3450 explicit_bzero(buf, 8);
3451 if ((r = sshbuf_put(buffer, buf, 8 - (sshbuf_len(buffer) % 8))) != 0)
3454 /* This buffer will be used to contain the data in the file. */
3455 if ((encrypted = sshbuf_new()) == NULL) {
3456 r = SSH_ERR_ALLOC_FAIL;
3460 /* First store keyfile id string. */
3461 if ((r = sshbuf_put(encrypted, LEGACY_BEGIN,
3462 sizeof(LEGACY_BEGIN))) != 0)
3465 /* Store cipher type and "reserved" field. */
3466 if ((r = sshbuf_put_u8(encrypted, cipher_num)) != 0 ||
3467 (r = sshbuf_put_u32(encrypted, 0)) != 0)
3470 /* Store public key. This will be in plain text. */
3471 if ((r = sshbuf_put_u32(encrypted, BN_num_bits(key->rsa->n))) != 0 ||
3472 (r = sshbuf_put_bignum1(encrypted, key->rsa->n)) != 0 ||
3473 (r = sshbuf_put_bignum1(encrypted, key->rsa->e)) != 0 ||
3474 (r = sshbuf_put_cstring(encrypted, comment)) != 0)
3477 /* Allocate space for the private part of the key in the buffer. */
3478 if ((r = sshbuf_reserve(encrypted, sshbuf_len(buffer), &cp)) != 0)
3481 if ((r = cipher_set_key_string(&ciphercontext, cipher, passphrase,
3482 CIPHER_ENCRYPT)) != 0)
3484 if ((r = cipher_crypt(ciphercontext, 0, cp,
3485 sshbuf_ptr(buffer), sshbuf_len(buffer), 0, 0)) != 0)
3488 r = sshbuf_putb(blob, encrypted);
3491 cipher_free(ciphercontext);
3492 explicit_bzero(buf, sizeof(buf));
3493 sshbuf_free(buffer);
3494 sshbuf_free(encrypted);
3498 #endif /* WITH_SSH1 */
3501 /* convert SSH v2 key in OpenSSL PEM format */
3503 sshkey_private_pem_to_blob(struct sshkey *key, struct sshbuf *blob,
3504 const char *_passphrase, const char *comment)
3507 int blen, len = strlen(_passphrase);
3508 u_char *passphrase = (len > 0) ? (u_char *)_passphrase : NULL;
3509 #if (OPENSSL_VERSION_NUMBER < 0x00907000L)
3510 const EVP_CIPHER *cipher = (len > 0) ? EVP_des_ede3_cbc() : NULL;
3512 const EVP_CIPHER *cipher = (len > 0) ? EVP_aes_128_cbc() : NULL;
3517 if (len > 0 && len <= 4)
3518 return SSH_ERR_PASSPHRASE_TOO_SHORT;
3519 if ((bio = BIO_new(BIO_s_mem())) == NULL)
3520 return SSH_ERR_ALLOC_FAIL;
3522 switch (key->type) {
3524 success = PEM_write_bio_DSAPrivateKey(bio, key->dsa,
3525 cipher, passphrase, len, NULL, NULL);
3527 #ifdef OPENSSL_HAS_ECC
3529 success = PEM_write_bio_ECPrivateKey(bio, key->ecdsa,
3530 cipher, passphrase, len, NULL, NULL);
3534 success = PEM_write_bio_RSAPrivateKey(bio, key->rsa,
3535 cipher, passphrase, len, NULL, NULL);
3542 r = SSH_ERR_LIBCRYPTO_ERROR;
3545 if ((blen = BIO_get_mem_data(bio, &bptr)) <= 0) {
3546 r = SSH_ERR_INTERNAL_ERROR;
3549 if ((r = sshbuf_put(blob, bptr, blen)) != 0)
3556 #endif /* WITH_OPENSSL */
3558 /* Serialise "key" to buffer "blob" */
3560 sshkey_private_to_fileblob(struct sshkey *key, struct sshbuf *blob,
3561 const char *passphrase, const char *comment,
3562 int force_new_format, const char *new_format_cipher, int new_format_rounds)
3564 switch (key->type) {
3567 return sshkey_private_rsa1_to_blob(key, blob,
3568 passphrase, comment);
3569 #endif /* WITH_SSH1 */
3574 if (force_new_format) {
3575 return sshkey_private_to_blob2(key, blob, passphrase,
3576 comment, new_format_cipher, new_format_rounds);
3578 return sshkey_private_pem_to_blob(key, blob,
3579 passphrase, comment);
3580 #endif /* WITH_OPENSSL */
3582 return sshkey_private_to_blob2(key, blob, passphrase,
3583 comment, new_format_cipher, new_format_rounds);
3585 return SSH_ERR_KEY_TYPE_UNKNOWN;
3591 * Parse the public, unencrypted portion of a RSA1 key.
3594 sshkey_parse_public_rsa1_fileblob(struct sshbuf *blob,
3595 struct sshkey **keyp, char **commentp)
3598 struct sshkey *pub = NULL;
3599 struct sshbuf *copy = NULL;
3603 if (commentp != NULL)
3606 /* Check that it is at least big enough to contain the ID string. */
3607 if (sshbuf_len(blob) < sizeof(LEGACY_BEGIN))
3608 return SSH_ERR_INVALID_FORMAT;
3611 * Make sure it begins with the id string. Consume the id string
3614 if (memcmp(sshbuf_ptr(blob), LEGACY_BEGIN, sizeof(LEGACY_BEGIN)) != 0)
3615 return SSH_ERR_INVALID_FORMAT;
3616 /* Make a working copy of the keyblob and skip past the magic */
3617 if ((copy = sshbuf_fromb(blob)) == NULL)
3618 return SSH_ERR_ALLOC_FAIL;
3619 if ((r = sshbuf_consume(copy, sizeof(LEGACY_BEGIN))) != 0)
3622 /* Skip cipher type, reserved data and key bits. */
3623 if ((r = sshbuf_get_u8(copy, NULL)) != 0 || /* cipher type */
3624 (r = sshbuf_get_u32(copy, NULL)) != 0 || /* reserved */
3625 (r = sshbuf_get_u32(copy, NULL)) != 0) /* key bits */
3628 /* Read the public key from the buffer. */
3629 if ((pub = sshkey_new(KEY_RSA1)) == NULL ||
3630 (r = sshbuf_get_bignum1(copy, pub->rsa->n)) != 0 ||
3631 (r = sshbuf_get_bignum1(copy, pub->rsa->e)) != 0)
3634 /* Finally, the comment */
3635 if ((r = sshbuf_get_string(copy, (u_char**)commentp, NULL)) != 0)
3638 /* The encrypted private part is not parsed by this function. */
3652 sshkey_parse_private_rsa1(struct sshbuf *blob, const char *passphrase,
3653 struct sshkey **keyp, char **commentp)
3656 u_int16_t check1, check2;
3657 u_int8_t cipher_type;
3658 struct sshbuf *decrypted = NULL, *copy = NULL;
3660 char *comment = NULL;
3661 struct sshcipher_ctx *ciphercontext = NULL;
3662 const struct sshcipher *cipher;
3663 struct sshkey *prv = NULL;
3667 if (commentp != NULL)
3670 /* Check that it is at least big enough to contain the ID string. */
3671 if (sshbuf_len(blob) < sizeof(LEGACY_BEGIN))
3672 return SSH_ERR_INVALID_FORMAT;
3675 * Make sure it begins with the id string. Consume the id string
3678 if (memcmp(sshbuf_ptr(blob), LEGACY_BEGIN, sizeof(LEGACY_BEGIN)) != 0)
3679 return SSH_ERR_INVALID_FORMAT;
3681 if ((prv = sshkey_new_private(KEY_RSA1)) == NULL) {
3682 r = SSH_ERR_ALLOC_FAIL;
3685 if ((copy = sshbuf_fromb(blob)) == NULL ||
3686 (decrypted = sshbuf_new()) == NULL) {
3687 r = SSH_ERR_ALLOC_FAIL;
3690 if ((r = sshbuf_consume(copy, sizeof(LEGACY_BEGIN))) != 0)
3693 /* Read cipher type. */
3694 if ((r = sshbuf_get_u8(copy, &cipher_type)) != 0 ||
3695 (r = sshbuf_get_u32(copy, NULL)) != 0) /* reserved */
3698 /* Read the public key and comment from the buffer. */
3699 if ((r = sshbuf_get_u32(copy, NULL)) != 0 || /* key bits */
3700 (r = sshbuf_get_bignum1(copy, prv->rsa->n)) != 0 ||
3701 (r = sshbuf_get_bignum1(copy, prv->rsa->e)) != 0 ||
3702 (r = sshbuf_get_cstring(copy, &comment, NULL)) != 0)
3705 /* Check that it is a supported cipher. */
3706 cipher = cipher_by_number(cipher_type);
3707 if (cipher == NULL) {
3708 r = SSH_ERR_KEY_UNKNOWN_CIPHER;
3711 /* Initialize space for decrypted data. */
3712 if ((r = sshbuf_reserve(decrypted, sshbuf_len(copy), &cp)) != 0)
3715 /* Rest of the buffer is encrypted. Decrypt it using the passphrase. */
3716 if ((r = cipher_set_key_string(&ciphercontext, cipher, passphrase,
3717 CIPHER_DECRYPT)) != 0)
3719 if ((r = cipher_crypt(ciphercontext, 0, cp,
3720 sshbuf_ptr(copy), sshbuf_len(copy), 0, 0)) != 0)
3723 if ((r = sshbuf_get_u16(decrypted, &check1)) != 0 ||
3724 (r = sshbuf_get_u16(decrypted, &check2)) != 0)
3726 if (check1 != check2) {
3727 r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3731 /* Read the rest of the private key. */
3732 if ((r = sshbuf_get_bignum1(decrypted, prv->rsa->d)) != 0 ||
3733 (r = sshbuf_get_bignum1(decrypted, prv->rsa->iqmp)) != 0 ||
3734 (r = sshbuf_get_bignum1(decrypted, prv->rsa->q)) != 0 ||
3735 (r = sshbuf_get_bignum1(decrypted, prv->rsa->p)) != 0)
3738 /* calculate p-1 and q-1 */
3739 if ((r = rsa_generate_additional_parameters(prv->rsa)) != 0)
3742 /* enable blinding */
3743 if (RSA_blinding_on(prv->rsa, NULL) != 1) {
3744 r = SSH_ERR_LIBCRYPTO_ERROR;
3752 if (commentp != NULL) {
3753 *commentp = comment;
3757 cipher_free(ciphercontext);
3761 sshbuf_free(decrypted);
3764 #endif /* WITH_SSH1 */
3768 sshkey_parse_private_pem_fileblob(struct sshbuf *blob, int type,
3769 const char *passphrase, struct sshkey **keyp)
3771 EVP_PKEY *pk = NULL;
3772 struct sshkey *prv = NULL;
3779 if ((bio = BIO_new(BIO_s_mem())) == NULL || sshbuf_len(blob) > INT_MAX)
3780 return SSH_ERR_ALLOC_FAIL;
3781 if (BIO_write(bio, sshbuf_ptr(blob), sshbuf_len(blob)) !=
3782 (int)sshbuf_len(blob)) {
3783 r = SSH_ERR_ALLOC_FAIL;
3787 if ((pk = PEM_read_bio_PrivateKey(bio, NULL, NULL,
3788 (char *)passphrase)) == NULL) {
3789 r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3792 if (pk->type == EVP_PKEY_RSA &&
3793 (type == KEY_UNSPEC || type == KEY_RSA)) {
3794 if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
3795 r = SSH_ERR_ALLOC_FAIL;
3798 prv->rsa = EVP_PKEY_get1_RSA(pk);
3799 prv->type = KEY_RSA;
3801 RSA_print_fp(stderr, prv->rsa, 8);
3803 if (RSA_blinding_on(prv->rsa, NULL) != 1) {
3804 r = SSH_ERR_LIBCRYPTO_ERROR;
3807 } else if (pk->type == EVP_PKEY_DSA &&
3808 (type == KEY_UNSPEC || type == KEY_DSA)) {
3809 if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
3810 r = SSH_ERR_ALLOC_FAIL;
3813 prv->dsa = EVP_PKEY_get1_DSA(pk);
3814 prv->type = KEY_DSA;
3816 DSA_print_fp(stderr, prv->dsa, 8);
3818 #ifdef OPENSSL_HAS_ECC
3819 } else if (pk->type == EVP_PKEY_EC &&
3820 (type == KEY_UNSPEC || type == KEY_ECDSA)) {
3821 if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
3822 r = SSH_ERR_ALLOC_FAIL;
3825 prv->ecdsa = EVP_PKEY_get1_EC_KEY(pk);
3826 prv->type = KEY_ECDSA;
3827 prv->ecdsa_nid = sshkey_ecdsa_key_to_nid(prv->ecdsa);
3828 if (prv->ecdsa_nid == -1 ||
3829 sshkey_curve_nid_to_name(prv->ecdsa_nid) == NULL ||
3830 sshkey_ec_validate_public(EC_KEY_get0_group(prv->ecdsa),
3831 EC_KEY_get0_public_key(prv->ecdsa)) != 0 ||
3832 sshkey_ec_validate_private(prv->ecdsa) != 0) {
3833 r = SSH_ERR_INVALID_FORMAT;
3837 if (prv != NULL && prv->ecdsa != NULL)
3838 sshkey_dump_ec_key(prv->ecdsa);
3840 #endif /* OPENSSL_HAS_ECC */
3842 r = SSH_ERR_INVALID_FORMAT;
3857 #endif /* WITH_OPENSSL */
3860 sshkey_parse_private_fileblob_type(struct sshbuf *blob, int type,
3861 const char *passphrase, struct sshkey **keyp, char **commentp)
3865 if (commentp != NULL)
3871 return sshkey_parse_private_rsa1(blob, passphrase,
3873 #endif /* WITH_SSH1 */
3878 return sshkey_parse_private_pem_fileblob(blob, type,
3880 #endif /* WITH_OPENSSL */
3882 return sshkey_parse_private2(blob, type, passphrase,
3885 if (sshkey_parse_private2(blob, type, passphrase, keyp,
3889 return sshkey_parse_private_pem_fileblob(blob, type,
3892 return SSH_ERR_INVALID_FORMAT;
3893 #endif /* WITH_OPENSSL */
3895 return SSH_ERR_KEY_TYPE_UNKNOWN;
3900 sshkey_parse_private_fileblob(struct sshbuf *buffer, const char *passphrase,
3901 struct sshkey **keyp, char **commentp)
3905 if (commentp != NULL)
3909 /* it's a SSH v1 key if the public key part is readable */
3910 if (sshkey_parse_public_rsa1_fileblob(buffer, NULL, NULL) == 0) {
3911 return sshkey_parse_private_fileblob_type(buffer, KEY_RSA1,
3912 passphrase, keyp, commentp);
3914 #endif /* WITH_SSH1 */
3915 return sshkey_parse_private_fileblob_type(buffer, KEY_UNSPEC,
3916 passphrase, keyp, commentp);