1 /* $OpenBSD: sshkey.c,v 1.31 2015/12/11 04:21:12 mmcc 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;
88 static const struct keytype keytypes[] = {
89 { "ssh-ed25519", "ED25519", KEY_ED25519, 0, 0, 0 },
90 { "ssh-ed25519-cert-v01@openssh.com", "ED25519-CERT",
91 KEY_ED25519_CERT, 0, 1, 0 },
93 { NULL, "RSA1", KEY_RSA1, 0, 0, 0 },
94 { "ssh-rsa", "RSA", KEY_RSA, 0, 0, 0 },
95 { "rsa-sha2-256", "RSA", KEY_RSA, 0, 0, 1 },
96 { "rsa-sha2-512", "RSA", KEY_RSA, 0, 0, 1 },
97 { "ssh-dss", "DSA", KEY_DSA, 0, 0, 0 },
98 # ifdef OPENSSL_HAS_ECC
99 { "ecdsa-sha2-nistp256", "ECDSA", KEY_ECDSA, NID_X9_62_prime256v1, 0, 0 },
100 { "ecdsa-sha2-nistp384", "ECDSA", KEY_ECDSA, NID_secp384r1, 0, 0 },
101 # ifdef OPENSSL_HAS_NISTP521
102 { "ecdsa-sha2-nistp521", "ECDSA", KEY_ECDSA, NID_secp521r1, 0, 0 },
103 # endif /* OPENSSL_HAS_NISTP521 */
104 # endif /* OPENSSL_HAS_ECC */
105 { "ssh-rsa-cert-v01@openssh.com", "RSA-CERT", KEY_RSA_CERT, 0, 1, 0 },
106 { "ssh-dss-cert-v01@openssh.com", "DSA-CERT", KEY_DSA_CERT, 0, 1, 0 },
107 # ifdef OPENSSL_HAS_ECC
108 { "ecdsa-sha2-nistp256-cert-v01@openssh.com", "ECDSA-CERT",
109 KEY_ECDSA_CERT, NID_X9_62_prime256v1, 1, 0 },
110 { "ecdsa-sha2-nistp384-cert-v01@openssh.com", "ECDSA-CERT",
111 KEY_ECDSA_CERT, NID_secp384r1, 1, 0 },
112 # ifdef OPENSSL_HAS_NISTP521
113 { "ecdsa-sha2-nistp521-cert-v01@openssh.com", "ECDSA-CERT",
114 KEY_ECDSA_CERT, NID_secp521r1, 1, 0 },
115 # endif /* OPENSSL_HAS_NISTP521 */
116 # endif /* OPENSSL_HAS_ECC */
117 #endif /* WITH_OPENSSL */
118 { NULL, NULL, -1, -1, 0, 0 }
122 sshkey_type(const struct sshkey *k)
124 const struct keytype *kt;
126 for (kt = keytypes; kt->type != -1; kt++) {
127 if (kt->type == k->type)
128 return kt->shortname;
134 sshkey_ssh_name_from_type_nid(int type, int nid)
136 const struct keytype *kt;
138 for (kt = keytypes; kt->type != -1; kt++) {
139 if (kt->type == type && (kt->nid == 0 || kt->nid == nid))
142 return "ssh-unknown";
146 sshkey_type_is_cert(int type)
148 const struct keytype *kt;
150 for (kt = keytypes; kt->type != -1; kt++) {
151 if (kt->type == type)
158 sshkey_ssh_name(const struct sshkey *k)
160 return sshkey_ssh_name_from_type_nid(k->type, k->ecdsa_nid);
164 sshkey_ssh_name_plain(const struct sshkey *k)
166 return sshkey_ssh_name_from_type_nid(sshkey_type_plain(k->type),
171 sshkey_type_from_name(const char *name)
173 const struct keytype *kt;
175 for (kt = keytypes; kt->type != -1; kt++) {
176 /* Only allow shortname matches for plain key types */
177 if ((kt->name != NULL && strcmp(name, kt->name) == 0) ||
178 (!kt->cert && strcasecmp(kt->shortname, name) == 0))
185 sshkey_ecdsa_nid_from_name(const char *name)
187 const struct keytype *kt;
189 for (kt = keytypes; kt->type != -1; kt++) {
190 if (kt->type != KEY_ECDSA && kt->type != KEY_ECDSA_CERT)
192 if (kt->name != NULL && strcmp(name, kt->name) == 0)
199 key_alg_list(int certs_only, int plain_only)
201 char *tmp, *ret = NULL;
202 size_t nlen, rlen = 0;
203 const struct keytype *kt;
205 for (kt = keytypes; kt->type != -1; kt++) {
206 if (kt->name == NULL || kt->sigonly)
208 if ((certs_only && !kt->cert) || (plain_only && kt->cert))
212 nlen = strlen(kt->name);
213 if ((tmp = realloc(ret, rlen + nlen + 2)) == NULL) {
218 memcpy(ret + rlen, kt->name, nlen + 1);
225 sshkey_names_valid2(const char *names, int allow_wildcard)
228 const struct keytype *kt;
231 if (names == NULL || strcmp(names, "") == 0)
233 if ((s = cp = strdup(names)) == NULL)
235 for ((p = strsep(&cp, ",")); p && *p != '\0';
236 (p = strsep(&cp, ","))) {
237 type = sshkey_type_from_name(p);
238 if (type == KEY_RSA1) {
242 if (type == KEY_UNSPEC) {
243 if (allow_wildcard) {
245 * Try matching key types against the string.
246 * If any has a positive or negative match then
247 * the component is accepted.
249 for (kt = keytypes; kt->type != -1; kt++) {
250 if (kt->type == KEY_RSA1)
252 if (match_pattern_list(kt->name,
268 sshkey_size(const struct sshkey *k)
275 return BN_num_bits(k->rsa->n);
278 return BN_num_bits(k->dsa->p);
281 return sshkey_curve_nid_to_bits(k->ecdsa_nid);
282 #endif /* WITH_OPENSSL */
284 case KEY_ED25519_CERT:
285 return 256; /* XXX */
291 sshkey_type_is_valid_ca(int type)
305 sshkey_is_cert(const struct sshkey *k)
309 return sshkey_type_is_cert(k->type);
312 /* Return the cert-less equivalent to a certified key type */
314 sshkey_type_plain(int type)
323 case KEY_ED25519_CERT:
331 /* XXX: these are really begging for a table-driven approach */
333 sshkey_curve_name_to_nid(const char *name)
335 if (strcmp(name, "nistp256") == 0)
336 return NID_X9_62_prime256v1;
337 else if (strcmp(name, "nistp384") == 0)
338 return NID_secp384r1;
339 # ifdef OPENSSL_HAS_NISTP521
340 else if (strcmp(name, "nistp521") == 0)
341 return NID_secp521r1;
342 # endif /* OPENSSL_HAS_NISTP521 */
348 sshkey_curve_nid_to_bits(int nid)
351 case NID_X9_62_prime256v1:
355 # ifdef OPENSSL_HAS_NISTP521
358 # endif /* OPENSSL_HAS_NISTP521 */
365 sshkey_ecdsa_bits_to_nid(int bits)
369 return NID_X9_62_prime256v1;
371 return NID_secp384r1;
372 # ifdef OPENSSL_HAS_NISTP521
374 return NID_secp521r1;
375 # endif /* OPENSSL_HAS_NISTP521 */
382 sshkey_curve_nid_to_name(int nid)
385 case NID_X9_62_prime256v1:
389 # ifdef OPENSSL_HAS_NISTP521
392 # endif /* OPENSSL_HAS_NISTP521 */
399 sshkey_ec_nid_to_hash_alg(int nid)
401 int kbits = sshkey_curve_nid_to_bits(nid);
406 /* RFC5656 section 6.2.1 */
408 return SSH_DIGEST_SHA256;
409 else if (kbits <= 384)
410 return SSH_DIGEST_SHA384;
412 return SSH_DIGEST_SHA512;
414 #endif /* WITH_OPENSSL */
417 cert_free(struct sshkey_cert *cert)
423 sshbuf_free(cert->certblob);
424 sshbuf_free(cert->critical);
425 sshbuf_free(cert->extensions);
427 for (i = 0; i < cert->nprincipals; i++)
428 free(cert->principals[i]);
429 free(cert->principals);
430 sshkey_free(cert->signature_key);
431 explicit_bzero(cert, sizeof(*cert));
435 static struct sshkey_cert *
438 struct sshkey_cert *cert;
440 if ((cert = calloc(1, sizeof(*cert))) == NULL)
442 if ((cert->certblob = sshbuf_new()) == NULL ||
443 (cert->critical = sshbuf_new()) == NULL ||
444 (cert->extensions = sshbuf_new()) == NULL) {
449 cert->principals = NULL;
450 cert->signature_key = NULL;
461 #endif /* WITH_OPENSSL */
463 if ((k = calloc(1, sizeof(*k))) == NULL)
471 k->ed25519_sk = NULL;
472 k->ed25519_pk = NULL;
478 if ((rsa = RSA_new()) == NULL ||
479 (rsa->n = BN_new()) == NULL ||
480 (rsa->e = BN_new()) == NULL) {
490 if ((dsa = DSA_new()) == NULL ||
491 (dsa->p = BN_new()) == NULL ||
492 (dsa->q = BN_new()) == NULL ||
493 (dsa->g = BN_new()) == NULL ||
494 (dsa->pub_key = BN_new()) == NULL) {
504 /* Cannot do anything until we know the group */
506 #endif /* WITH_OPENSSL */
508 case KEY_ED25519_CERT:
509 /* no need to prealloc */
519 if (sshkey_is_cert(k)) {
520 if ((k->cert = cert_new()) == NULL) {
530 sshkey_add_private(struct sshkey *k)
537 #define bn_maybe_alloc_failed(p) (p == NULL && (p = BN_new()) == NULL)
538 if (bn_maybe_alloc_failed(k->rsa->d) ||
539 bn_maybe_alloc_failed(k->rsa->iqmp) ||
540 bn_maybe_alloc_failed(k->rsa->q) ||
541 bn_maybe_alloc_failed(k->rsa->p) ||
542 bn_maybe_alloc_failed(k->rsa->dmq1) ||
543 bn_maybe_alloc_failed(k->rsa->dmp1))
544 return SSH_ERR_ALLOC_FAIL;
548 if (bn_maybe_alloc_failed(k->dsa->priv_key))
549 return SSH_ERR_ALLOC_FAIL;
551 #undef bn_maybe_alloc_failed
554 /* Cannot do anything until we know the group */
556 #endif /* WITH_OPENSSL */
558 case KEY_ED25519_CERT:
559 /* no need to prealloc */
564 return SSH_ERR_INVALID_ARGUMENT;
570 sshkey_new_private(int type)
572 struct sshkey *k = sshkey_new(type);
576 if (sshkey_add_private(k) != 0) {
584 sshkey_free(struct sshkey *k)
603 # ifdef OPENSSL_HAS_ECC
606 if (k->ecdsa != NULL)
607 EC_KEY_free(k->ecdsa);
610 # endif /* OPENSSL_HAS_ECC */
611 #endif /* WITH_OPENSSL */
613 case KEY_ED25519_CERT:
615 explicit_bzero(k->ed25519_pk, ED25519_PK_SZ);
617 k->ed25519_pk = NULL;
620 explicit_bzero(k->ed25519_sk, ED25519_SK_SZ);
622 k->ed25519_sk = NULL;
630 if (sshkey_is_cert(k))
632 explicit_bzero(k, sizeof(*k));
637 cert_compare(struct sshkey_cert *a, struct sshkey_cert *b)
639 if (a == NULL && b == NULL)
641 if (a == NULL || b == NULL)
643 if (sshbuf_len(a->certblob) != sshbuf_len(b->certblob))
645 if (timingsafe_bcmp(sshbuf_ptr(a->certblob), sshbuf_ptr(b->certblob),
646 sshbuf_len(a->certblob)) != 0)
652 * Compare public portions of key only, allowing comparisons between
653 * certificates and plain keys too.
656 sshkey_equal_public(const struct sshkey *a, const struct sshkey *b)
658 #if defined(WITH_OPENSSL) && defined(OPENSSL_HAS_ECC)
660 #endif /* WITH_OPENSSL && OPENSSL_HAS_ECC */
662 if (a == NULL || b == NULL ||
663 sshkey_type_plain(a->type) != sshkey_type_plain(b->type))
671 return a->rsa != NULL && b->rsa != NULL &&
672 BN_cmp(a->rsa->e, b->rsa->e) == 0 &&
673 BN_cmp(a->rsa->n, b->rsa->n) == 0;
676 return a->dsa != NULL && b->dsa != NULL &&
677 BN_cmp(a->dsa->p, b->dsa->p) == 0 &&
678 BN_cmp(a->dsa->q, b->dsa->q) == 0 &&
679 BN_cmp(a->dsa->g, b->dsa->g) == 0 &&
680 BN_cmp(a->dsa->pub_key, b->dsa->pub_key) == 0;
681 # ifdef OPENSSL_HAS_ECC
684 if (a->ecdsa == NULL || b->ecdsa == NULL ||
685 EC_KEY_get0_public_key(a->ecdsa) == NULL ||
686 EC_KEY_get0_public_key(b->ecdsa) == NULL)
688 if ((bnctx = BN_CTX_new()) == NULL)
690 if (EC_GROUP_cmp(EC_KEY_get0_group(a->ecdsa),
691 EC_KEY_get0_group(b->ecdsa), bnctx) != 0 ||
692 EC_POINT_cmp(EC_KEY_get0_group(a->ecdsa),
693 EC_KEY_get0_public_key(a->ecdsa),
694 EC_KEY_get0_public_key(b->ecdsa), bnctx) != 0) {
700 # endif /* OPENSSL_HAS_ECC */
701 #endif /* WITH_OPENSSL */
703 case KEY_ED25519_CERT:
704 return a->ed25519_pk != NULL && b->ed25519_pk != NULL &&
705 memcmp(a->ed25519_pk, b->ed25519_pk, ED25519_PK_SZ) == 0;
713 sshkey_equal(const struct sshkey *a, const struct sshkey *b)
715 if (a == NULL || b == NULL || a->type != b->type)
717 if (sshkey_is_cert(a)) {
718 if (!cert_compare(a->cert, b->cert))
721 return sshkey_equal_public(a, b);
725 to_blob_buf(const struct sshkey *key, struct sshbuf *b, int force_plain)
727 int type, ret = SSH_ERR_INTERNAL_ERROR;
728 const char *typename;
731 return SSH_ERR_INVALID_ARGUMENT;
733 if (sshkey_is_cert(key)) {
734 if (key->cert == NULL)
735 return SSH_ERR_EXPECTED_CERT;
736 if (sshbuf_len(key->cert->certblob) == 0)
737 return SSH_ERR_KEY_LACKS_CERTBLOB;
739 type = force_plain ? sshkey_type_plain(key->type) : key->type;
740 typename = sshkey_ssh_name_from_type_nid(type, key->ecdsa_nid);
747 #endif /* WITH_OPENSSL */
748 case KEY_ED25519_CERT:
749 /* Use the existing blob */
750 /* XXX modified flag? */
751 if ((ret = sshbuf_putb(b, key->cert->certblob)) != 0)
756 if (key->dsa == NULL)
757 return SSH_ERR_INVALID_ARGUMENT;
758 if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
759 (ret = sshbuf_put_bignum2(b, key->dsa->p)) != 0 ||
760 (ret = sshbuf_put_bignum2(b, key->dsa->q)) != 0 ||
761 (ret = sshbuf_put_bignum2(b, key->dsa->g)) != 0 ||
762 (ret = sshbuf_put_bignum2(b, key->dsa->pub_key)) != 0)
765 # ifdef OPENSSL_HAS_ECC
767 if (key->ecdsa == NULL)
768 return SSH_ERR_INVALID_ARGUMENT;
769 if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
770 (ret = sshbuf_put_cstring(b,
771 sshkey_curve_nid_to_name(key->ecdsa_nid))) != 0 ||
772 (ret = sshbuf_put_eckey(b, key->ecdsa)) != 0)
777 if (key->rsa == NULL)
778 return SSH_ERR_INVALID_ARGUMENT;
779 if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
780 (ret = sshbuf_put_bignum2(b, key->rsa->e)) != 0 ||
781 (ret = sshbuf_put_bignum2(b, key->rsa->n)) != 0)
784 #endif /* WITH_OPENSSL */
786 if (key->ed25519_pk == NULL)
787 return SSH_ERR_INVALID_ARGUMENT;
788 if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
789 (ret = sshbuf_put_string(b,
790 key->ed25519_pk, ED25519_PK_SZ)) != 0)
794 return SSH_ERR_KEY_TYPE_UNKNOWN;
800 sshkey_putb(const struct sshkey *key, struct sshbuf *b)
802 return to_blob_buf(key, b, 0);
806 sshkey_puts(const struct sshkey *key, struct sshbuf *b)
811 if ((tmp = sshbuf_new()) == NULL)
812 return SSH_ERR_ALLOC_FAIL;
813 r = to_blob_buf(key, tmp, 0);
815 r = sshbuf_put_stringb(b, tmp);
821 sshkey_putb_plain(const struct sshkey *key, struct sshbuf *b)
823 return to_blob_buf(key, b, 1);
827 to_blob(const struct sshkey *key, u_char **blobp, size_t *lenp, int force_plain)
829 int ret = SSH_ERR_INTERNAL_ERROR;
831 struct sshbuf *b = NULL;
837 if ((b = sshbuf_new()) == NULL)
838 return SSH_ERR_ALLOC_FAIL;
839 if ((ret = to_blob_buf(key, b, force_plain)) != 0)
845 if ((*blobp = malloc(len)) == NULL) {
846 ret = SSH_ERR_ALLOC_FAIL;
849 memcpy(*blobp, sshbuf_ptr(b), len);
858 sshkey_to_blob(const struct sshkey *key, u_char **blobp, size_t *lenp)
860 return to_blob(key, blobp, lenp, 0);
864 sshkey_plain_to_blob(const struct sshkey *key, u_char **blobp, size_t *lenp)
866 return to_blob(key, blobp, lenp, 1);
870 sshkey_fingerprint_raw(const struct sshkey *k, int dgst_alg,
871 u_char **retp, size_t *lenp)
873 u_char *blob = NULL, *ret = NULL;
875 int r = SSH_ERR_INTERNAL_ERROR;
881 if (ssh_digest_bytes(dgst_alg) == 0) {
882 r = SSH_ERR_INVALID_ARGUMENT;
886 if (k->type == KEY_RSA1) {
888 int nlen = BN_num_bytes(k->rsa->n);
889 int elen = BN_num_bytes(k->rsa->e);
891 blob_len = nlen + elen;
892 if (nlen >= INT_MAX - elen ||
893 (blob = malloc(blob_len)) == NULL) {
894 r = SSH_ERR_ALLOC_FAIL;
897 BN_bn2bin(k->rsa->n, blob);
898 BN_bn2bin(k->rsa->e, blob + nlen);
899 #endif /* WITH_OPENSSL */
900 } else if ((r = to_blob(k, &blob, &blob_len, 1)) != 0)
902 if ((ret = calloc(1, SSH_DIGEST_MAX_LENGTH)) == NULL) {
903 r = SSH_ERR_ALLOC_FAIL;
906 if ((r = ssh_digest_memory(dgst_alg, blob, blob_len,
907 ret, SSH_DIGEST_MAX_LENGTH)) != 0)
915 *lenp = ssh_digest_bytes(dgst_alg);
920 explicit_bzero(blob, blob_len);
927 fingerprint_b64(const char *alg, u_char *dgst_raw, size_t dgst_raw_len)
930 size_t plen = strlen(alg) + 1;
931 size_t rlen = ((dgst_raw_len + 2) / 3) * 4 + plen + 1;
934 if (dgst_raw_len > 65536 || (ret = calloc(1, rlen)) == NULL)
936 strlcpy(ret, alg, rlen);
937 strlcat(ret, ":", rlen);
938 if (dgst_raw_len == 0)
940 if ((r = b64_ntop(dgst_raw, dgst_raw_len,
941 ret + plen, rlen - plen)) == -1) {
942 explicit_bzero(ret, rlen);
946 /* Trim padding characters from end */
947 ret[strcspn(ret, "=")] = '\0';
952 fingerprint_hex(const char *alg, u_char *dgst_raw, size_t dgst_raw_len)
954 char *retval, hex[5];
955 size_t i, rlen = dgst_raw_len * 3 + strlen(alg) + 2;
957 if (dgst_raw_len > 65536 || (retval = calloc(1, rlen)) == NULL)
959 strlcpy(retval, alg, rlen);
960 strlcat(retval, ":", rlen);
961 for (i = 0; i < dgst_raw_len; i++) {
962 snprintf(hex, sizeof(hex), "%s%02x",
963 i > 0 ? ":" : "", dgst_raw[i]);
964 strlcat(retval, hex, rlen);
970 fingerprint_bubblebabble(u_char *dgst_raw, size_t dgst_raw_len)
972 char vowels[] = { 'a', 'e', 'i', 'o', 'u', 'y' };
973 char consonants[] = { 'b', 'c', 'd', 'f', 'g', 'h', 'k', 'l', 'm',
974 'n', 'p', 'r', 's', 't', 'v', 'z', 'x' };
975 u_int i, j = 0, rounds, seed = 1;
978 rounds = (dgst_raw_len / 2) + 1;
979 if ((retval = calloc(rounds, 6)) == NULL)
982 for (i = 0; i < rounds; i++) {
983 u_int idx0, idx1, idx2, idx3, idx4;
984 if ((i + 1 < rounds) || (dgst_raw_len % 2 != 0)) {
985 idx0 = (((((u_int)(dgst_raw[2 * i])) >> 6) & 3) +
987 idx1 = (((u_int)(dgst_raw[2 * i])) >> 2) & 15;
988 idx2 = ((((u_int)(dgst_raw[2 * i])) & 3) +
990 retval[j++] = vowels[idx0];
991 retval[j++] = consonants[idx1];
992 retval[j++] = vowels[idx2];
993 if ((i + 1) < rounds) {
994 idx3 = (((u_int)(dgst_raw[(2 * i) + 1])) >> 4) & 15;
995 idx4 = (((u_int)(dgst_raw[(2 * i) + 1]))) & 15;
996 retval[j++] = consonants[idx3];
998 retval[j++] = consonants[idx4];
1000 ((((u_int)(dgst_raw[2 * i])) * 7) +
1001 ((u_int)(dgst_raw[(2 * i) + 1])))) % 36;
1007 retval[j++] = vowels[idx0];
1008 retval[j++] = consonants[idx1];
1009 retval[j++] = vowels[idx2];
1018 * Draw an ASCII-Art representing the fingerprint so human brain can
1019 * profit from its built-in pattern recognition ability.
1020 * This technique is called "random art" and can be found in some
1021 * scientific publications like this original paper:
1023 * "Hash Visualization: a New Technique to improve Real-World Security",
1024 * Perrig A. and Song D., 1999, International Workshop on Cryptographic
1025 * Techniques and E-Commerce (CrypTEC '99)
1026 * sparrow.ece.cmu.edu/~adrian/projects/validation/validation.pdf
1028 * The subject came up in a talk by Dan Kaminsky, too.
1030 * If you see the picture is different, the key is different.
1031 * If the picture looks the same, you still know nothing.
1033 * The algorithm used here is a worm crawling over a discrete plane,
1034 * leaving a trace (augmenting the field) everywhere it goes.
1035 * Movement is taken from dgst_raw 2bit-wise. Bumping into walls
1036 * makes the respective movement vector be ignored for this turn.
1037 * Graphs are not unambiguous, because circles in graphs can be
1038 * walked in either direction.
1042 * Field sizes for the random art. Have to be odd, so the starting point
1043 * can be in the exact middle of the picture, and FLDBASE should be >=8 .
1044 * Else pictures would be too dense, and drawing the frame would
1045 * fail, too, because the key type would not fit in anymore.
1048 #define FLDSIZE_Y (FLDBASE + 1)
1049 #define FLDSIZE_X (FLDBASE * 2 + 1)
1051 fingerprint_randomart(const char *alg, u_char *dgst_raw, size_t dgst_raw_len,
1052 const struct sshkey *k)
1055 * Chars to be used after each other every time the worm
1056 * intersects with itself. Matter of taste.
1058 char *augmentation_string = " .o+=*BOX@%&#/^SE";
1059 char *retval, *p, title[FLDSIZE_X], hash[FLDSIZE_X];
1060 u_char field[FLDSIZE_X][FLDSIZE_Y];
1061 size_t i, tlen, hlen;
1064 size_t len = strlen(augmentation_string) - 1;
1066 if ((retval = calloc((FLDSIZE_X + 3), (FLDSIZE_Y + 2))) == NULL)
1069 /* initialize field */
1070 memset(field, 0, FLDSIZE_X * FLDSIZE_Y * sizeof(char));
1074 /* process raw key */
1075 for (i = 0; i < dgst_raw_len; i++) {
1077 /* each byte conveys four 2-bit move commands */
1078 input = dgst_raw[i];
1079 for (b = 0; b < 4; b++) {
1080 /* evaluate 2 bit, rest is shifted later */
1081 x += (input & 0x1) ? 1 : -1;
1082 y += (input & 0x2) ? 1 : -1;
1084 /* assure we are still in bounds */
1087 x = MIN(x, FLDSIZE_X - 1);
1088 y = MIN(y, FLDSIZE_Y - 1);
1090 /* augment the field */
1091 if (field[x][y] < len - 2)
1097 /* mark starting point and end point*/
1098 field[FLDSIZE_X / 2][FLDSIZE_Y / 2] = len - 1;
1101 /* assemble title */
1102 r = snprintf(title, sizeof(title), "[%s %u]",
1103 sshkey_type(k), sshkey_size(k));
1104 /* If [type size] won't fit, then try [type]; fits "[ED25519-CERT]" */
1105 if (r < 0 || r > (int)sizeof(title))
1106 r = snprintf(title, sizeof(title), "[%s]", sshkey_type(k));
1107 tlen = (r <= 0) ? 0 : strlen(title);
1109 /* assemble hash ID. */
1110 r = snprintf(hash, sizeof(hash), "[%s]", alg);
1111 hlen = (r <= 0) ? 0 : strlen(hash);
1113 /* output upper border */
1116 for (i = 0; i < (FLDSIZE_X - tlen) / 2; i++)
1118 memcpy(p, title, tlen);
1120 for (i += tlen; i < FLDSIZE_X; i++)
1125 /* output content */
1126 for (y = 0; y < FLDSIZE_Y; y++) {
1128 for (x = 0; x < FLDSIZE_X; x++)
1129 *p++ = augmentation_string[MIN(field[x][y], len)];
1134 /* output lower border */
1136 for (i = 0; i < (FLDSIZE_X - hlen) / 2; i++)
1138 memcpy(p, hash, hlen);
1140 for (i += hlen; i < FLDSIZE_X; i++)
1148 sshkey_fingerprint(const struct sshkey *k, int dgst_alg,
1149 enum sshkey_fp_rep dgst_rep)
1151 char *retval = NULL;
1153 size_t dgst_raw_len;
1155 if (sshkey_fingerprint_raw(k, dgst_alg, &dgst_raw, &dgst_raw_len) != 0)
1158 case SSH_FP_DEFAULT:
1159 if (dgst_alg == SSH_DIGEST_MD5) {
1160 retval = fingerprint_hex(ssh_digest_alg_name(dgst_alg),
1161 dgst_raw, dgst_raw_len);
1163 retval = fingerprint_b64(ssh_digest_alg_name(dgst_alg),
1164 dgst_raw, dgst_raw_len);
1168 retval = fingerprint_hex(ssh_digest_alg_name(dgst_alg),
1169 dgst_raw, dgst_raw_len);
1172 retval = fingerprint_b64(ssh_digest_alg_name(dgst_alg),
1173 dgst_raw, dgst_raw_len);
1175 case SSH_FP_BUBBLEBABBLE:
1176 retval = fingerprint_bubblebabble(dgst_raw, dgst_raw_len);
1178 case SSH_FP_RANDOMART:
1179 retval = fingerprint_randomart(ssh_digest_alg_name(dgst_alg),
1180 dgst_raw, dgst_raw_len, k);
1183 explicit_bzero(dgst_raw, dgst_raw_len);
1187 explicit_bzero(dgst_raw, dgst_raw_len);
1194 * Reads a multiple-precision integer in decimal from the buffer, and advances
1195 * the pointer. The integer must already be initialized. This function is
1196 * permitted to modify the buffer. This leaves *cpp to point just beyond the
1197 * last processed character.
1200 read_decimal_bignum(char **cpp, BIGNUM *v)
1204 int skip = 1; /* skip white space */
1207 while (*cp == ' ' || *cp == '\t')
1209 e = strspn(cp, "0123456789");
1211 return SSH_ERR_INVALID_FORMAT;
1212 if (e > SSHBUF_MAX_BIGNUM * 3)
1213 return SSH_ERR_BIGNUM_TOO_LARGE;
1216 else if (strchr(" \t\r\n", cp[e]) == NULL)
1217 return SSH_ERR_INVALID_FORMAT;
1219 if (BN_dec2bn(&v, cp) <= 0)
1220 return SSH_ERR_INVALID_FORMAT;
1221 *cpp = cp + e + skip;
1224 #endif /* WITH_SSH1 */
1226 /* returns 0 ok, and < 0 error */
1228 sshkey_read(struct sshkey *ret, char **cpp)
1231 int retval = SSH_ERR_INVALID_FORMAT;
1232 char *ep, *cp, *space;
1233 int r, type, curve_nid = -1;
1234 struct sshbuf *blob;
1237 #endif /* WITH_SSH1 */
1241 switch (ret->type) {
1244 /* Get number of bits. */
1245 bits = strtoul(cp, &ep, 10);
1246 if (*cp == '\0' || strchr(" \t\r\n", *ep) == NULL ||
1247 bits == 0 || bits > SSHBUF_MAX_BIGNUM * 8)
1248 return SSH_ERR_INVALID_FORMAT; /* Bad bit count... */
1249 /* Get public exponent, public modulus. */
1250 if ((r = read_decimal_bignum(&ep, ret->rsa->e)) < 0)
1252 if ((r = read_decimal_bignum(&ep, ret->rsa->n)) < 0)
1254 /* validate the claimed number of bits */
1255 if (BN_num_bits(ret->rsa->n) != (int)bits)
1256 return SSH_ERR_KEY_BITS_MISMATCH;
1259 #endif /* WITH_SSH1 */
1267 case KEY_ECDSA_CERT:
1269 case KEY_ED25519_CERT:
1270 space = strchr(cp, ' ');
1272 return SSH_ERR_INVALID_FORMAT;
1274 type = sshkey_type_from_name(cp);
1275 if (sshkey_type_plain(type) == KEY_ECDSA &&
1276 (curve_nid = sshkey_ecdsa_nid_from_name(cp)) == -1)
1277 return SSH_ERR_EC_CURVE_INVALID;
1279 if (type == KEY_UNSPEC)
1280 return SSH_ERR_INVALID_FORMAT;
1283 return SSH_ERR_INVALID_FORMAT;
1284 if (ret->type != KEY_UNSPEC && ret->type != type)
1285 return SSH_ERR_KEY_TYPE_MISMATCH;
1286 if ((blob = sshbuf_new()) == NULL)
1287 return SSH_ERR_ALLOC_FAIL;
1289 space = strchr(cp, ' ');
1291 /* advance 'space': skip whitespace */
1293 while (*space == ' ' || *space == '\t')
1297 ep = cp + strlen(cp);
1298 if ((r = sshbuf_b64tod(blob, cp)) != 0) {
1302 if ((r = sshkey_from_blob(sshbuf_ptr(blob),
1303 sshbuf_len(blob), &k)) != 0) {
1308 if (k->type != type) {
1310 return SSH_ERR_KEY_TYPE_MISMATCH;
1312 if (sshkey_type_plain(type) == KEY_ECDSA &&
1313 curve_nid != k->ecdsa_nid) {
1315 return SSH_ERR_EC_CURVE_MISMATCH;
1318 if (sshkey_is_cert(ret)) {
1319 if (!sshkey_is_cert(k)) {
1321 return SSH_ERR_EXPECTED_CERT;
1323 if (ret->cert != NULL)
1324 cert_free(ret->cert);
1325 ret->cert = k->cert;
1328 switch (sshkey_type_plain(ret->type)) {
1331 if (ret->rsa != NULL)
1336 RSA_print_fp(stderr, ret->rsa, 8);
1340 if (ret->dsa != NULL)
1345 DSA_print_fp(stderr, ret->dsa, 8);
1348 # ifdef OPENSSL_HAS_ECC
1350 if (ret->ecdsa != NULL)
1351 EC_KEY_free(ret->ecdsa);
1352 ret->ecdsa = k->ecdsa;
1353 ret->ecdsa_nid = k->ecdsa_nid;
1357 sshkey_dump_ec_key(ret->ecdsa);
1360 # endif /* OPENSSL_HAS_ECC */
1361 #endif /* WITH_OPENSSL */
1363 free(ret->ed25519_pk);
1364 ret->ed25519_pk = k->ed25519_pk;
1365 k->ed25519_pk = NULL;
1379 return SSH_ERR_INVALID_ARGUMENT;
1385 sshkey_to_base64(const struct sshkey *key, char **b64p)
1387 int r = SSH_ERR_INTERNAL_ERROR;
1388 struct sshbuf *b = NULL;
1393 if ((b = sshbuf_new()) == NULL)
1394 return SSH_ERR_ALLOC_FAIL;
1395 if ((r = sshkey_putb(key, b)) != 0)
1397 if ((uu = sshbuf_dtob64(b)) == NULL) {
1398 r = SSH_ERR_ALLOC_FAIL;
1414 sshkey_format_rsa1(const struct sshkey *key, struct sshbuf *b)
1416 int r = SSH_ERR_INTERNAL_ERROR;
1419 char *dec_e = NULL, *dec_n = NULL;
1421 if (key->rsa == NULL || key->rsa->e == NULL ||
1422 key->rsa->n == NULL) {
1423 r = SSH_ERR_INVALID_ARGUMENT;
1426 if ((dec_e = BN_bn2dec(key->rsa->e)) == NULL ||
1427 (dec_n = BN_bn2dec(key->rsa->n)) == NULL) {
1428 r = SSH_ERR_ALLOC_FAIL;
1431 /* size of modulus 'n' */
1432 if ((bits = BN_num_bits(key->rsa->n)) <= 0) {
1433 r = SSH_ERR_INVALID_ARGUMENT;
1436 if ((r = sshbuf_putf(b, "%u %s %s", bits, dec_e, dec_n)) != 0)
1443 OPENSSL_free(dec_e);
1445 OPENSSL_free(dec_n);
1446 #endif /* WITH_SSH1 */
1452 sshkey_format_text(const struct sshkey *key, struct sshbuf *b)
1454 int r = SSH_ERR_INTERNAL_ERROR;
1457 if (key->type == KEY_RSA1) {
1458 if ((r = sshkey_format_rsa1(key, b)) != 0)
1461 /* Unsupported key types handled in sshkey_to_base64() */
1462 if ((r = sshkey_to_base64(key, &uu)) != 0)
1464 if ((r = sshbuf_putf(b, "%s %s",
1465 sshkey_ssh_name(key), uu)) != 0)
1475 sshkey_write(const struct sshkey *key, FILE *f)
1477 struct sshbuf *b = NULL;
1478 int r = SSH_ERR_INTERNAL_ERROR;
1480 if ((b = sshbuf_new()) == NULL)
1481 return SSH_ERR_ALLOC_FAIL;
1482 if ((r = sshkey_format_text(key, b)) != 0)
1484 if (fwrite(sshbuf_ptr(b), sshbuf_len(b), 1, f) != 1) {
1487 r = SSH_ERR_SYSTEM_ERROR;
1498 sshkey_cert_type(const struct sshkey *k)
1500 switch (k->cert->type) {
1501 case SSH2_CERT_TYPE_USER:
1503 case SSH2_CERT_TYPE_HOST:
1512 rsa_generate_private_key(u_int bits, RSA **rsap)
1514 RSA *private = NULL;
1516 int ret = SSH_ERR_INTERNAL_ERROR;
1519 bits < SSH_RSA_MINIMUM_MODULUS_SIZE ||
1520 bits > SSHBUF_MAX_BIGNUM * 8)
1521 return SSH_ERR_INVALID_ARGUMENT;
1523 if ((private = RSA_new()) == NULL || (f4 = BN_new()) == NULL) {
1524 ret = SSH_ERR_ALLOC_FAIL;
1527 if (!BN_set_word(f4, RSA_F4) ||
1528 !RSA_generate_key_ex(private, bits, f4, NULL)) {
1529 ret = SSH_ERR_LIBCRYPTO_ERROR;
1536 if (private != NULL)
1544 dsa_generate_private_key(u_int bits, DSA **dsap)
1547 int ret = SSH_ERR_INTERNAL_ERROR;
1549 if (dsap == NULL || bits != 1024)
1550 return SSH_ERR_INVALID_ARGUMENT;
1551 if ((private = DSA_new()) == NULL) {
1552 ret = SSH_ERR_ALLOC_FAIL;
1556 if (!DSA_generate_parameters_ex(private, bits, NULL, 0, NULL,
1557 NULL, NULL) || !DSA_generate_key(private)) {
1558 ret = SSH_ERR_LIBCRYPTO_ERROR;
1565 if (private != NULL)
1570 # ifdef OPENSSL_HAS_ECC
1572 sshkey_ecdsa_key_to_nid(EC_KEY *k)
1576 NID_X9_62_prime256v1,
1578 # ifdef OPENSSL_HAS_NISTP521
1580 # endif /* OPENSSL_HAS_NISTP521 */
1586 const EC_GROUP *g = EC_KEY_get0_group(k);
1589 * The group may be stored in a ASN.1 encoded private key in one of two
1590 * ways: as a "named group", which is reconstituted by ASN.1 object ID
1591 * or explicit group parameters encoded into the key blob. Only the
1592 * "named group" case sets the group NID for us, but we can figure
1593 * it out for the other case by comparing against all the groups that
1596 if ((nid = EC_GROUP_get_curve_name(g)) > 0)
1598 if ((bnctx = BN_CTX_new()) == NULL)
1600 for (i = 0; nids[i] != -1; i++) {
1601 if ((eg = EC_GROUP_new_by_curve_name(nids[i])) == NULL) {
1605 if (EC_GROUP_cmp(g, eg, bnctx) == 0)
1610 if (nids[i] != -1) {
1611 /* Use the group with the NID attached */
1612 EC_GROUP_set_asn1_flag(eg, OPENSSL_EC_NAMED_CURVE);
1613 if (EC_KEY_set_group(k, eg) != 1) {
1622 ecdsa_generate_private_key(u_int bits, int *nid, EC_KEY **ecdsap)
1625 int ret = SSH_ERR_INTERNAL_ERROR;
1627 if (nid == NULL || ecdsap == NULL ||
1628 (*nid = sshkey_ecdsa_bits_to_nid(bits)) == -1)
1629 return SSH_ERR_INVALID_ARGUMENT;
1631 if ((private = EC_KEY_new_by_curve_name(*nid)) == NULL) {
1632 ret = SSH_ERR_ALLOC_FAIL;
1635 if (EC_KEY_generate_key(private) != 1) {
1636 ret = SSH_ERR_LIBCRYPTO_ERROR;
1639 EC_KEY_set_asn1_flag(private, OPENSSL_EC_NAMED_CURVE);
1644 if (private != NULL)
1645 EC_KEY_free(private);
1648 # endif /* OPENSSL_HAS_ECC */
1649 #endif /* WITH_OPENSSL */
1652 sshkey_generate(int type, u_int bits, struct sshkey **keyp)
1655 int ret = SSH_ERR_INTERNAL_ERROR;
1658 return SSH_ERR_INVALID_ARGUMENT;
1660 if ((k = sshkey_new(KEY_UNSPEC)) == NULL)
1661 return SSH_ERR_ALLOC_FAIL;
1664 if ((k->ed25519_pk = malloc(ED25519_PK_SZ)) == NULL ||
1665 (k->ed25519_sk = malloc(ED25519_SK_SZ)) == NULL) {
1666 ret = SSH_ERR_ALLOC_FAIL;
1669 crypto_sign_ed25519_keypair(k->ed25519_pk, k->ed25519_sk);
1674 ret = dsa_generate_private_key(bits, &k->dsa);
1676 # ifdef OPENSSL_HAS_ECC
1678 ret = ecdsa_generate_private_key(bits, &k->ecdsa_nid,
1681 # endif /* OPENSSL_HAS_ECC */
1684 ret = rsa_generate_private_key(bits, &k->rsa);
1686 #endif /* WITH_OPENSSL */
1688 ret = SSH_ERR_INVALID_ARGUMENT;
1699 sshkey_cert_copy(const struct sshkey *from_key, struct sshkey *to_key)
1702 const struct sshkey_cert *from;
1703 struct sshkey_cert *to;
1704 int ret = SSH_ERR_INTERNAL_ERROR;
1706 if (to_key->cert != NULL) {
1707 cert_free(to_key->cert);
1708 to_key->cert = NULL;
1711 if ((from = from_key->cert) == NULL)
1712 return SSH_ERR_INVALID_ARGUMENT;
1714 if ((to = to_key->cert = cert_new()) == NULL)
1715 return SSH_ERR_ALLOC_FAIL;
1717 if ((ret = sshbuf_putb(to->certblob, from->certblob)) != 0 ||
1718 (ret = sshbuf_putb(to->critical, from->critical)) != 0 ||
1719 (ret = sshbuf_putb(to->extensions, from->extensions)) != 0)
1722 to->serial = from->serial;
1723 to->type = from->type;
1724 if (from->key_id == NULL)
1726 else if ((to->key_id = strdup(from->key_id)) == NULL)
1727 return SSH_ERR_ALLOC_FAIL;
1728 to->valid_after = from->valid_after;
1729 to->valid_before = from->valid_before;
1730 if (from->signature_key == NULL)
1731 to->signature_key = NULL;
1732 else if ((ret = sshkey_from_private(from->signature_key,
1733 &to->signature_key)) != 0)
1736 if (from->nprincipals > SSHKEY_CERT_MAX_PRINCIPALS)
1737 return SSH_ERR_INVALID_ARGUMENT;
1738 if (from->nprincipals > 0) {
1739 if ((to->principals = calloc(from->nprincipals,
1740 sizeof(*to->principals))) == NULL)
1741 return SSH_ERR_ALLOC_FAIL;
1742 for (i = 0; i < from->nprincipals; i++) {
1743 to->principals[i] = strdup(from->principals[i]);
1744 if (to->principals[i] == NULL) {
1745 to->nprincipals = i;
1746 return SSH_ERR_ALLOC_FAIL;
1750 to->nprincipals = from->nprincipals;
1755 sshkey_from_private(const struct sshkey *k, struct sshkey **pkp)
1757 struct sshkey *n = NULL;
1758 int ret = SSH_ERR_INTERNAL_ERROR;
1765 if ((n = sshkey_new(k->type)) == NULL)
1766 return SSH_ERR_ALLOC_FAIL;
1767 if ((BN_copy(n->dsa->p, k->dsa->p) == NULL) ||
1768 (BN_copy(n->dsa->q, k->dsa->q) == NULL) ||
1769 (BN_copy(n->dsa->g, k->dsa->g) == NULL) ||
1770 (BN_copy(n->dsa->pub_key, k->dsa->pub_key) == NULL)) {
1772 return SSH_ERR_ALLOC_FAIL;
1775 # ifdef OPENSSL_HAS_ECC
1777 case KEY_ECDSA_CERT:
1778 if ((n = sshkey_new(k->type)) == NULL)
1779 return SSH_ERR_ALLOC_FAIL;
1780 n->ecdsa_nid = k->ecdsa_nid;
1781 n->ecdsa = EC_KEY_new_by_curve_name(k->ecdsa_nid);
1782 if (n->ecdsa == NULL) {
1784 return SSH_ERR_ALLOC_FAIL;
1786 if (EC_KEY_set_public_key(n->ecdsa,
1787 EC_KEY_get0_public_key(k->ecdsa)) != 1) {
1789 return SSH_ERR_LIBCRYPTO_ERROR;
1792 # endif /* OPENSSL_HAS_ECC */
1796 if ((n = sshkey_new(k->type)) == NULL)
1797 return SSH_ERR_ALLOC_FAIL;
1798 if ((BN_copy(n->rsa->n, k->rsa->n) == NULL) ||
1799 (BN_copy(n->rsa->e, k->rsa->e) == NULL)) {
1801 return SSH_ERR_ALLOC_FAIL;
1804 #endif /* WITH_OPENSSL */
1806 case KEY_ED25519_CERT:
1807 if ((n = sshkey_new(k->type)) == NULL)
1808 return SSH_ERR_ALLOC_FAIL;
1809 if (k->ed25519_pk != NULL) {
1810 if ((n->ed25519_pk = malloc(ED25519_PK_SZ)) == NULL) {
1812 return SSH_ERR_ALLOC_FAIL;
1814 memcpy(n->ed25519_pk, k->ed25519_pk, ED25519_PK_SZ);
1818 return SSH_ERR_KEY_TYPE_UNKNOWN;
1820 if (sshkey_is_cert(k)) {
1821 if ((ret = sshkey_cert_copy(k, n)) != 0) {
1831 cert_parse(struct sshbuf *b, struct sshkey *key, struct sshbuf *certbuf)
1833 struct sshbuf *principals = NULL, *crit = NULL;
1834 struct sshbuf *exts = NULL, *ca = NULL;
1836 size_t signed_len = 0, slen = 0, kidlen = 0;
1837 int ret = SSH_ERR_INTERNAL_ERROR;
1839 /* Copy the entire key blob for verification and later serialisation */
1840 if ((ret = sshbuf_putb(key->cert->certblob, certbuf)) != 0)
1843 /* Parse body of certificate up to signature */
1844 if ((ret = sshbuf_get_u64(b, &key->cert->serial)) != 0 ||
1845 (ret = sshbuf_get_u32(b, &key->cert->type)) != 0 ||
1846 (ret = sshbuf_get_cstring(b, &key->cert->key_id, &kidlen)) != 0 ||
1847 (ret = sshbuf_froms(b, &principals)) != 0 ||
1848 (ret = sshbuf_get_u64(b, &key->cert->valid_after)) != 0 ||
1849 (ret = sshbuf_get_u64(b, &key->cert->valid_before)) != 0 ||
1850 (ret = sshbuf_froms(b, &crit)) != 0 ||
1851 (ret = sshbuf_froms(b, &exts)) != 0 ||
1852 (ret = sshbuf_get_string_direct(b, NULL, NULL)) != 0 ||
1853 (ret = sshbuf_froms(b, &ca)) != 0) {
1854 /* XXX debug print error for ret */
1855 ret = SSH_ERR_INVALID_FORMAT;
1859 /* Signature is left in the buffer so we can calculate this length */
1860 signed_len = sshbuf_len(key->cert->certblob) - sshbuf_len(b);
1862 if ((ret = sshbuf_get_string(b, &sig, &slen)) != 0) {
1863 ret = SSH_ERR_INVALID_FORMAT;
1867 if (key->cert->type != SSH2_CERT_TYPE_USER &&
1868 key->cert->type != SSH2_CERT_TYPE_HOST) {
1869 ret = SSH_ERR_KEY_CERT_UNKNOWN_TYPE;
1873 /* Parse principals section */
1874 while (sshbuf_len(principals) > 0) {
1875 char *principal = NULL;
1876 char **oprincipals = NULL;
1878 if (key->cert->nprincipals >= SSHKEY_CERT_MAX_PRINCIPALS) {
1879 ret = SSH_ERR_INVALID_FORMAT;
1882 if ((ret = sshbuf_get_cstring(principals, &principal,
1884 ret = SSH_ERR_INVALID_FORMAT;
1887 oprincipals = key->cert->principals;
1888 key->cert->principals = reallocarray(key->cert->principals,
1889 key->cert->nprincipals + 1, sizeof(*key->cert->principals));
1890 if (key->cert->principals == NULL) {
1892 key->cert->principals = oprincipals;
1893 ret = SSH_ERR_ALLOC_FAIL;
1896 key->cert->principals[key->cert->nprincipals++] = principal;
1900 * Stash a copies of the critical options and extensions sections
1903 if ((ret = sshbuf_putb(key->cert->critical, crit)) != 0 ||
1905 (ret = sshbuf_putb(key->cert->extensions, exts)) != 0))
1909 * Validate critical options and extensions sections format.
1911 while (sshbuf_len(crit) != 0) {
1912 if ((ret = sshbuf_get_string_direct(crit, NULL, NULL)) != 0 ||
1913 (ret = sshbuf_get_string_direct(crit, NULL, NULL)) != 0) {
1914 sshbuf_reset(key->cert->critical);
1915 ret = SSH_ERR_INVALID_FORMAT;
1919 while (exts != NULL && sshbuf_len(exts) != 0) {
1920 if ((ret = sshbuf_get_string_direct(exts, NULL, NULL)) != 0 ||
1921 (ret = sshbuf_get_string_direct(exts, NULL, NULL)) != 0) {
1922 sshbuf_reset(key->cert->extensions);
1923 ret = SSH_ERR_INVALID_FORMAT;
1928 /* Parse CA key and check signature */
1929 if (sshkey_from_blob_internal(ca, &key->cert->signature_key, 0) != 0) {
1930 ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
1933 if (!sshkey_type_is_valid_ca(key->cert->signature_key->type)) {
1934 ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
1937 if ((ret = sshkey_verify(key->cert->signature_key, sig, slen,
1938 sshbuf_ptr(key->cert->certblob), signed_len, 0)) != 0)
1947 sshbuf_free(principals);
1953 sshkey_from_blob_internal(struct sshbuf *b, struct sshkey **keyp,
1956 int type, ret = SSH_ERR_INTERNAL_ERROR;
1957 char *ktype = NULL, *curve = NULL;
1958 struct sshkey *key = NULL;
1961 struct sshbuf *copy;
1962 #if defined(WITH_OPENSSL) && defined(OPENSSL_HAS_ECC)
1964 #endif /* WITH_OPENSSL && OPENSSL_HAS_ECC */
1966 #ifdef DEBUG_PK /* XXX */
1967 sshbuf_dump(b, stderr);
1970 if ((copy = sshbuf_fromb(b)) == NULL) {
1971 ret = SSH_ERR_ALLOC_FAIL;
1974 if (sshbuf_get_cstring(b, &ktype, NULL) != 0) {
1975 ret = SSH_ERR_INVALID_FORMAT;
1979 type = sshkey_type_from_name(ktype);
1980 if (!allow_cert && sshkey_type_is_cert(type)) {
1981 ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
1988 if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
1989 ret = SSH_ERR_INVALID_FORMAT;
1994 if ((key = sshkey_new(type)) == NULL) {
1995 ret = SSH_ERR_ALLOC_FAIL;
1998 if (sshbuf_get_bignum2(b, key->rsa->e) != 0 ||
1999 sshbuf_get_bignum2(b, key->rsa->n) != 0) {
2000 ret = SSH_ERR_INVALID_FORMAT;
2004 RSA_print_fp(stderr, key->rsa, 8);
2009 if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
2010 ret = SSH_ERR_INVALID_FORMAT;
2015 if ((key = sshkey_new(type)) == NULL) {
2016 ret = SSH_ERR_ALLOC_FAIL;
2019 if (sshbuf_get_bignum2(b, key->dsa->p) != 0 ||
2020 sshbuf_get_bignum2(b, key->dsa->q) != 0 ||
2021 sshbuf_get_bignum2(b, key->dsa->g) != 0 ||
2022 sshbuf_get_bignum2(b, key->dsa->pub_key) != 0) {
2023 ret = SSH_ERR_INVALID_FORMAT;
2027 DSA_print_fp(stderr, key->dsa, 8);
2030 case KEY_ECDSA_CERT:
2032 if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
2033 ret = SSH_ERR_INVALID_FORMAT;
2037 # ifdef OPENSSL_HAS_ECC
2039 if ((key = sshkey_new(type)) == NULL) {
2040 ret = SSH_ERR_ALLOC_FAIL;
2043 key->ecdsa_nid = sshkey_ecdsa_nid_from_name(ktype);
2044 if (sshbuf_get_cstring(b, &curve, NULL) != 0) {
2045 ret = SSH_ERR_INVALID_FORMAT;
2048 if (key->ecdsa_nid != sshkey_curve_name_to_nid(curve)) {
2049 ret = SSH_ERR_EC_CURVE_MISMATCH;
2052 if (key->ecdsa != NULL)
2053 EC_KEY_free(key->ecdsa);
2054 if ((key->ecdsa = EC_KEY_new_by_curve_name(key->ecdsa_nid))
2056 ret = SSH_ERR_EC_CURVE_INVALID;
2059 if ((q = EC_POINT_new(EC_KEY_get0_group(key->ecdsa))) == NULL) {
2060 ret = SSH_ERR_ALLOC_FAIL;
2063 if (sshbuf_get_ec(b, q, EC_KEY_get0_group(key->ecdsa)) != 0) {
2064 ret = SSH_ERR_INVALID_FORMAT;
2067 if (sshkey_ec_validate_public(EC_KEY_get0_group(key->ecdsa),
2069 ret = SSH_ERR_KEY_INVALID_EC_VALUE;
2072 if (EC_KEY_set_public_key(key->ecdsa, q) != 1) {
2073 /* XXX assume it is a allocation error */
2074 ret = SSH_ERR_ALLOC_FAIL;
2078 sshkey_dump_ec_point(EC_KEY_get0_group(key->ecdsa), q);
2081 # endif /* OPENSSL_HAS_ECC */
2082 #endif /* WITH_OPENSSL */
2083 case KEY_ED25519_CERT:
2085 if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
2086 ret = SSH_ERR_INVALID_FORMAT;
2091 if ((ret = sshbuf_get_string(b, &pk, &len)) != 0)
2093 if (len != ED25519_PK_SZ) {
2094 ret = SSH_ERR_INVALID_FORMAT;
2097 if ((key = sshkey_new(type)) == NULL) {
2098 ret = SSH_ERR_ALLOC_FAIL;
2101 key->ed25519_pk = pk;
2105 if ((key = sshkey_new(type)) == NULL) {
2106 ret = SSH_ERR_ALLOC_FAIL;
2111 ret = SSH_ERR_KEY_TYPE_UNKNOWN;
2115 /* Parse certificate potion */
2116 if (sshkey_is_cert(key) && (ret = cert_parse(b, key, copy)) != 0)
2119 if (key != NULL && sshbuf_len(b) != 0) {
2120 ret = SSH_ERR_INVALID_FORMAT;
2132 #if defined(WITH_OPENSSL) && defined(OPENSSL_HAS_ECC)
2135 #endif /* WITH_OPENSSL && OPENSSL_HAS_ECC */
2140 sshkey_from_blob(const u_char *blob, size_t blen, struct sshkey **keyp)
2145 if ((b = sshbuf_from(blob, blen)) == NULL)
2146 return SSH_ERR_ALLOC_FAIL;
2147 r = sshkey_from_blob_internal(b, keyp, 1);
2153 sshkey_fromb(struct sshbuf *b, struct sshkey **keyp)
2155 return sshkey_from_blob_internal(b, keyp, 1);
2159 sshkey_froms(struct sshbuf *buf, struct sshkey **keyp)
2164 if ((r = sshbuf_froms(buf, &b)) != 0)
2166 r = sshkey_from_blob_internal(b, keyp, 1);
2172 sshkey_sign(const struct sshkey *key,
2173 u_char **sigp, size_t *lenp,
2174 const u_char *data, size_t datalen, const char *alg, u_int compat)
2180 if (datalen > SSH_KEY_MAX_SIGN_DATA_SIZE)
2181 return SSH_ERR_INVALID_ARGUMENT;
2182 switch (key->type) {
2186 return ssh_dss_sign(key, sigp, lenp, data, datalen, compat);
2187 # ifdef OPENSSL_HAS_ECC
2188 case KEY_ECDSA_CERT:
2190 return ssh_ecdsa_sign(key, sigp, lenp, data, datalen, compat);
2191 # endif /* OPENSSL_HAS_ECC */
2194 return ssh_rsa_sign(key, sigp, lenp, data, datalen, alg);
2195 #endif /* WITH_OPENSSL */
2197 case KEY_ED25519_CERT:
2198 return ssh_ed25519_sign(key, sigp, lenp, data, datalen, compat);
2200 return SSH_ERR_KEY_TYPE_UNKNOWN;
2205 * ssh_key_verify returns 0 for a correct signature and < 0 on error.
2208 sshkey_verify(const struct sshkey *key,
2209 const u_char *sig, size_t siglen,
2210 const u_char *data, size_t dlen, u_int compat)
2212 if (siglen == 0 || dlen > SSH_KEY_MAX_SIGN_DATA_SIZE)
2213 return SSH_ERR_INVALID_ARGUMENT;
2214 switch (key->type) {
2218 return ssh_dss_verify(key, sig, siglen, data, dlen, compat);
2219 # ifdef OPENSSL_HAS_ECC
2220 case KEY_ECDSA_CERT:
2222 return ssh_ecdsa_verify(key, sig, siglen, data, dlen, compat);
2223 # endif /* OPENSSL_HAS_ECC */
2226 return ssh_rsa_verify(key, sig, siglen, data, dlen);
2227 #endif /* WITH_OPENSSL */
2229 case KEY_ED25519_CERT:
2230 return ssh_ed25519_verify(key, sig, siglen, data, dlen, compat);
2232 return SSH_ERR_KEY_TYPE_UNKNOWN;
2236 /* Converts a private to a public key */
2238 sshkey_demote(const struct sshkey *k, struct sshkey **dkp)
2241 int ret = SSH_ERR_INTERNAL_ERROR;
2244 if ((pk = calloc(1, sizeof(*pk))) == NULL)
2245 return SSH_ERR_ALLOC_FAIL;
2247 pk->flags = k->flags;
2248 pk->ecdsa_nid = k->ecdsa_nid;
2252 pk->ed25519_pk = NULL;
2253 pk->ed25519_sk = NULL;
2258 if ((ret = sshkey_cert_copy(k, pk)) != 0)
2263 if ((pk->rsa = RSA_new()) == NULL ||
2264 (pk->rsa->e = BN_dup(k->rsa->e)) == NULL ||
2265 (pk->rsa->n = BN_dup(k->rsa->n)) == NULL) {
2266 ret = SSH_ERR_ALLOC_FAIL;
2271 if ((ret = sshkey_cert_copy(k, pk)) != 0)
2275 if ((pk->dsa = DSA_new()) == NULL ||
2276 (pk->dsa->p = BN_dup(k->dsa->p)) == NULL ||
2277 (pk->dsa->q = BN_dup(k->dsa->q)) == NULL ||
2278 (pk->dsa->g = BN_dup(k->dsa->g)) == NULL ||
2279 (pk->dsa->pub_key = BN_dup(k->dsa->pub_key)) == NULL) {
2280 ret = SSH_ERR_ALLOC_FAIL;
2284 case KEY_ECDSA_CERT:
2285 if ((ret = sshkey_cert_copy(k, pk)) != 0)
2288 # ifdef OPENSSL_HAS_ECC
2290 pk->ecdsa = EC_KEY_new_by_curve_name(pk->ecdsa_nid);
2291 if (pk->ecdsa == NULL) {
2292 ret = SSH_ERR_ALLOC_FAIL;
2295 if (EC_KEY_set_public_key(pk->ecdsa,
2296 EC_KEY_get0_public_key(k->ecdsa)) != 1) {
2297 ret = SSH_ERR_LIBCRYPTO_ERROR;
2301 # endif /* OPENSSL_HAS_ECC */
2302 #endif /* WITH_OPENSSL */
2303 case KEY_ED25519_CERT:
2304 if ((ret = sshkey_cert_copy(k, pk)) != 0)
2308 if (k->ed25519_pk != NULL) {
2309 if ((pk->ed25519_pk = malloc(ED25519_PK_SZ)) == NULL) {
2310 ret = SSH_ERR_ALLOC_FAIL;
2313 memcpy(pk->ed25519_pk, k->ed25519_pk, ED25519_PK_SZ);
2317 ret = SSH_ERR_KEY_TYPE_UNKNOWN;
2326 /* Convert a plain key to their _CERT equivalent */
2328 sshkey_to_certified(struct sshkey *k)
2335 newtype = KEY_RSA_CERT;
2338 newtype = KEY_DSA_CERT;
2341 newtype = KEY_ECDSA_CERT;
2343 #endif /* WITH_OPENSSL */
2345 newtype = KEY_ED25519_CERT;
2348 return SSH_ERR_INVALID_ARGUMENT;
2350 if ((k->cert = cert_new()) == NULL)
2351 return SSH_ERR_ALLOC_FAIL;
2356 /* Convert a certificate to its raw key equivalent */
2358 sshkey_drop_cert(struct sshkey *k)
2360 if (!sshkey_type_is_cert(k->type))
2361 return SSH_ERR_KEY_TYPE_UNKNOWN;
2364 k->type = sshkey_type_plain(k->type);
2368 /* Sign a certified key, (re-)generating the signed certblob. */
2370 sshkey_certify(struct sshkey *k, struct sshkey *ca)
2372 struct sshbuf *principals = NULL;
2373 u_char *ca_blob = NULL, *sig_blob = NULL, nonce[32];
2374 size_t i, ca_len, sig_len;
2375 int ret = SSH_ERR_INTERNAL_ERROR;
2376 struct sshbuf *cert;
2378 if (k == NULL || k->cert == NULL ||
2379 k->cert->certblob == NULL || ca == NULL)
2380 return SSH_ERR_INVALID_ARGUMENT;
2381 if (!sshkey_is_cert(k))
2382 return SSH_ERR_KEY_TYPE_UNKNOWN;
2383 if (!sshkey_type_is_valid_ca(ca->type))
2384 return SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
2386 if ((ret = sshkey_to_blob(ca, &ca_blob, &ca_len)) != 0)
2387 return SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
2389 cert = k->cert->certblob; /* for readability */
2391 if ((ret = sshbuf_put_cstring(cert, sshkey_ssh_name(k))) != 0)
2394 /* -v01 certs put nonce first */
2395 arc4random_buf(&nonce, sizeof(nonce));
2396 if ((ret = sshbuf_put_string(cert, nonce, sizeof(nonce))) != 0)
2399 /* XXX this substantially duplicates to_blob(); refactor */
2403 if ((ret = sshbuf_put_bignum2(cert, k->dsa->p)) != 0 ||
2404 (ret = sshbuf_put_bignum2(cert, k->dsa->q)) != 0 ||
2405 (ret = sshbuf_put_bignum2(cert, k->dsa->g)) != 0 ||
2406 (ret = sshbuf_put_bignum2(cert, k->dsa->pub_key)) != 0)
2409 # ifdef OPENSSL_HAS_ECC
2410 case KEY_ECDSA_CERT:
2411 if ((ret = sshbuf_put_cstring(cert,
2412 sshkey_curve_nid_to_name(k->ecdsa_nid))) != 0 ||
2413 (ret = sshbuf_put_ec(cert,
2414 EC_KEY_get0_public_key(k->ecdsa),
2415 EC_KEY_get0_group(k->ecdsa))) != 0)
2418 # endif /* OPENSSL_HAS_ECC */
2420 if ((ret = sshbuf_put_bignum2(cert, k->rsa->e)) != 0 ||
2421 (ret = sshbuf_put_bignum2(cert, k->rsa->n)) != 0)
2424 #endif /* WITH_OPENSSL */
2425 case KEY_ED25519_CERT:
2426 if ((ret = sshbuf_put_string(cert,
2427 k->ed25519_pk, ED25519_PK_SZ)) != 0)
2431 ret = SSH_ERR_INVALID_ARGUMENT;
2435 if ((ret = sshbuf_put_u64(cert, k->cert->serial)) != 0 ||
2436 (ret = sshbuf_put_u32(cert, k->cert->type)) != 0 ||
2437 (ret = sshbuf_put_cstring(cert, k->cert->key_id)) != 0)
2440 if ((principals = sshbuf_new()) == NULL) {
2441 ret = SSH_ERR_ALLOC_FAIL;
2444 for (i = 0; i < k->cert->nprincipals; i++) {
2445 if ((ret = sshbuf_put_cstring(principals,
2446 k->cert->principals[i])) != 0)
2449 if ((ret = sshbuf_put_stringb(cert, principals)) != 0 ||
2450 (ret = sshbuf_put_u64(cert, k->cert->valid_after)) != 0 ||
2451 (ret = sshbuf_put_u64(cert, k->cert->valid_before)) != 0 ||
2452 (ret = sshbuf_put_stringb(cert, k->cert->critical)) != 0 ||
2453 (ret = sshbuf_put_stringb(cert, k->cert->extensions)) != 0 ||
2454 (ret = sshbuf_put_string(cert, NULL, 0)) != 0 || /* Reserved */
2455 (ret = sshbuf_put_string(cert, ca_blob, ca_len)) != 0)
2458 /* Sign the whole mess */
2459 if ((ret = sshkey_sign(ca, &sig_blob, &sig_len, sshbuf_ptr(cert),
2460 sshbuf_len(cert), NULL, 0)) != 0)
2463 /* Append signature and we are done */
2464 if ((ret = sshbuf_put_string(cert, sig_blob, sig_len)) != 0)
2472 sshbuf_free(principals);
2477 sshkey_cert_check_authority(const struct sshkey *k,
2478 int want_host, int require_principal,
2479 const char *name, const char **reason)
2481 u_int i, principal_matches;
2482 time_t now = time(NULL);
2488 if (k->cert->type != SSH2_CERT_TYPE_HOST) {
2489 *reason = "Certificate invalid: not a host certificate";
2490 return SSH_ERR_KEY_CERT_INVALID;
2493 if (k->cert->type != SSH2_CERT_TYPE_USER) {
2494 *reason = "Certificate invalid: not a user certificate";
2495 return SSH_ERR_KEY_CERT_INVALID;
2499 /* yikes - system clock before epoch! */
2500 *reason = "Certificate invalid: not yet valid";
2501 return SSH_ERR_KEY_CERT_INVALID;
2503 if ((u_int64_t)now < k->cert->valid_after) {
2504 *reason = "Certificate invalid: not yet valid";
2505 return SSH_ERR_KEY_CERT_INVALID;
2507 if ((u_int64_t)now >= k->cert->valid_before) {
2508 *reason = "Certificate invalid: expired";
2509 return SSH_ERR_KEY_CERT_INVALID;
2511 if (k->cert->nprincipals == 0) {
2512 if (require_principal) {
2513 *reason = "Certificate lacks principal list";
2514 return SSH_ERR_KEY_CERT_INVALID;
2516 } else if (name != NULL) {
2517 principal_matches = 0;
2518 for (i = 0; i < k->cert->nprincipals; i++) {
2519 if (strcmp(name, k->cert->principals[i]) == 0) {
2520 principal_matches = 1;
2524 if (!principal_matches) {
2525 *reason = "Certificate invalid: name is not a listed "
2527 return SSH_ERR_KEY_CERT_INVALID;
2534 sshkey_format_cert_validity(const struct sshkey_cert *cert, char *s, size_t l)
2536 char from[32], to[32], ret[64];
2541 if (cert->valid_after == 0 &&
2542 cert->valid_before == 0xffffffffffffffffULL)
2543 return strlcpy(s, "forever", l);
2545 if (cert->valid_after != 0) {
2546 /* XXX revisit INT_MAX in 2038 :) */
2547 tt = cert->valid_after > INT_MAX ?
2548 INT_MAX : cert->valid_after;
2549 tm = localtime(&tt);
2550 strftime(from, sizeof(from), "%Y-%m-%dT%H:%M:%S", tm);
2552 if (cert->valid_before != 0xffffffffffffffffULL) {
2553 /* XXX revisit INT_MAX in 2038 :) */
2554 tt = cert->valid_before > INT_MAX ?
2555 INT_MAX : cert->valid_before;
2556 tm = localtime(&tt);
2557 strftime(to, sizeof(to), "%Y-%m-%dT%H:%M:%S", tm);
2560 if (cert->valid_after == 0)
2561 snprintf(ret, sizeof(ret), "before %s", to);
2562 else if (cert->valid_before == 0xffffffffffffffffULL)
2563 snprintf(ret, sizeof(ret), "after %s", from);
2565 snprintf(ret, sizeof(ret), "from %s to %s", from, to);
2567 return strlcpy(s, ret, l);
2571 sshkey_private_serialize(const struct sshkey *key, struct sshbuf *b)
2573 int r = SSH_ERR_INTERNAL_ERROR;
2575 if ((r = sshbuf_put_cstring(b, sshkey_ssh_name(key))) != 0)
2577 switch (key->type) {
2580 if ((r = sshbuf_put_bignum2(b, key->rsa->n)) != 0 ||
2581 (r = sshbuf_put_bignum2(b, key->rsa->e)) != 0 ||
2582 (r = sshbuf_put_bignum2(b, key->rsa->d)) != 0 ||
2583 (r = sshbuf_put_bignum2(b, key->rsa->iqmp)) != 0 ||
2584 (r = sshbuf_put_bignum2(b, key->rsa->p)) != 0 ||
2585 (r = sshbuf_put_bignum2(b, key->rsa->q)) != 0)
2589 if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
2590 r = SSH_ERR_INVALID_ARGUMENT;
2593 if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
2594 (r = sshbuf_put_bignum2(b, key->rsa->d)) != 0 ||
2595 (r = sshbuf_put_bignum2(b, key->rsa->iqmp)) != 0 ||
2596 (r = sshbuf_put_bignum2(b, key->rsa->p)) != 0 ||
2597 (r = sshbuf_put_bignum2(b, key->rsa->q)) != 0)
2601 if ((r = sshbuf_put_bignum2(b, key->dsa->p)) != 0 ||
2602 (r = sshbuf_put_bignum2(b, key->dsa->q)) != 0 ||
2603 (r = sshbuf_put_bignum2(b, key->dsa->g)) != 0 ||
2604 (r = sshbuf_put_bignum2(b, key->dsa->pub_key)) != 0 ||
2605 (r = sshbuf_put_bignum2(b, key->dsa->priv_key)) != 0)
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->dsa->priv_key)) != 0)
2617 # ifdef OPENSSL_HAS_ECC
2619 if ((r = sshbuf_put_cstring(b,
2620 sshkey_curve_nid_to_name(key->ecdsa_nid))) != 0 ||
2621 (r = sshbuf_put_eckey(b, key->ecdsa)) != 0 ||
2622 (r = sshbuf_put_bignum2(b,
2623 EC_KEY_get0_private_key(key->ecdsa))) != 0)
2626 case KEY_ECDSA_CERT:
2627 if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
2628 r = SSH_ERR_INVALID_ARGUMENT;
2631 if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
2632 (r = sshbuf_put_bignum2(b,
2633 EC_KEY_get0_private_key(key->ecdsa))) != 0)
2636 # endif /* OPENSSL_HAS_ECC */
2637 #endif /* WITH_OPENSSL */
2639 if ((r = sshbuf_put_string(b, key->ed25519_pk,
2640 ED25519_PK_SZ)) != 0 ||
2641 (r = sshbuf_put_string(b, key->ed25519_sk,
2642 ED25519_SK_SZ)) != 0)
2645 case KEY_ED25519_CERT:
2646 if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
2647 r = SSH_ERR_INVALID_ARGUMENT;
2650 if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
2651 (r = sshbuf_put_string(b, key->ed25519_pk,
2652 ED25519_PK_SZ)) != 0 ||
2653 (r = sshbuf_put_string(b, key->ed25519_sk,
2654 ED25519_SK_SZ)) != 0)
2658 r = SSH_ERR_INVALID_ARGUMENT;
2668 sshkey_private_deserialize(struct sshbuf *buf, struct sshkey **kp)
2670 char *tname = NULL, *curve = NULL;
2671 struct sshkey *k = NULL;
2672 size_t pklen = 0, sklen = 0;
2673 int type, r = SSH_ERR_INTERNAL_ERROR;
2674 u_char *ed25519_pk = NULL, *ed25519_sk = NULL;
2676 BIGNUM *exponent = NULL;
2677 #endif /* WITH_OPENSSL */
2681 if ((r = sshbuf_get_cstring(buf, &tname, NULL)) != 0)
2683 type = sshkey_type_from_name(tname);
2687 if ((k = sshkey_new_private(type)) == NULL) {
2688 r = SSH_ERR_ALLOC_FAIL;
2691 if ((r = sshbuf_get_bignum2(buf, k->dsa->p)) != 0 ||
2692 (r = sshbuf_get_bignum2(buf, k->dsa->q)) != 0 ||
2693 (r = sshbuf_get_bignum2(buf, k->dsa->g)) != 0 ||
2694 (r = sshbuf_get_bignum2(buf, k->dsa->pub_key)) != 0 ||
2695 (r = sshbuf_get_bignum2(buf, k->dsa->priv_key)) != 0)
2699 if ((r = sshkey_froms(buf, &k)) != 0 ||
2700 (r = sshkey_add_private(k)) != 0 ||
2701 (r = sshbuf_get_bignum2(buf, k->dsa->priv_key)) != 0)
2704 # ifdef OPENSSL_HAS_ECC
2706 if ((k = sshkey_new_private(type)) == NULL) {
2707 r = SSH_ERR_ALLOC_FAIL;
2710 if ((k->ecdsa_nid = sshkey_ecdsa_nid_from_name(tname)) == -1) {
2711 r = SSH_ERR_INVALID_ARGUMENT;
2714 if ((r = sshbuf_get_cstring(buf, &curve, NULL)) != 0)
2716 if (k->ecdsa_nid != sshkey_curve_name_to_nid(curve)) {
2717 r = SSH_ERR_EC_CURVE_MISMATCH;
2720 k->ecdsa = EC_KEY_new_by_curve_name(k->ecdsa_nid);
2721 if (k->ecdsa == NULL || (exponent = BN_new()) == NULL) {
2722 r = SSH_ERR_LIBCRYPTO_ERROR;
2725 if ((r = sshbuf_get_eckey(buf, k->ecdsa)) != 0 ||
2726 (r = sshbuf_get_bignum2(buf, exponent)))
2728 if (EC_KEY_set_private_key(k->ecdsa, exponent) != 1) {
2729 r = SSH_ERR_LIBCRYPTO_ERROR;
2732 if ((r = sshkey_ec_validate_public(EC_KEY_get0_group(k->ecdsa),
2733 EC_KEY_get0_public_key(k->ecdsa))) != 0 ||
2734 (r = sshkey_ec_validate_private(k->ecdsa)) != 0)
2737 case KEY_ECDSA_CERT:
2738 if ((exponent = BN_new()) == NULL) {
2739 r = SSH_ERR_LIBCRYPTO_ERROR;
2742 if ((r = sshkey_froms(buf, &k)) != 0 ||
2743 (r = sshkey_add_private(k)) != 0 ||
2744 (r = sshbuf_get_bignum2(buf, exponent)) != 0)
2746 if (EC_KEY_set_private_key(k->ecdsa, exponent) != 1) {
2747 r = SSH_ERR_LIBCRYPTO_ERROR;
2750 if ((r = sshkey_ec_validate_public(EC_KEY_get0_group(k->ecdsa),
2751 EC_KEY_get0_public_key(k->ecdsa))) != 0 ||
2752 (r = sshkey_ec_validate_private(k->ecdsa)) != 0)
2755 # endif /* OPENSSL_HAS_ECC */
2757 if ((k = sshkey_new_private(type)) == NULL) {
2758 r = SSH_ERR_ALLOC_FAIL;
2761 if ((r = sshbuf_get_bignum2(buf, k->rsa->n)) != 0 ||
2762 (r = sshbuf_get_bignum2(buf, k->rsa->e)) != 0 ||
2763 (r = sshbuf_get_bignum2(buf, k->rsa->d)) != 0 ||
2764 (r = sshbuf_get_bignum2(buf, k->rsa->iqmp)) != 0 ||
2765 (r = sshbuf_get_bignum2(buf, k->rsa->p)) != 0 ||
2766 (r = sshbuf_get_bignum2(buf, k->rsa->q)) != 0 ||
2767 (r = rsa_generate_additional_parameters(k->rsa)) != 0)
2771 if ((r = sshkey_froms(buf, &k)) != 0 ||
2772 (r = sshkey_add_private(k)) != 0 ||
2773 (r = sshbuf_get_bignum2(buf, k->rsa->d)) != 0 ||
2774 (r = sshbuf_get_bignum2(buf, k->rsa->iqmp)) != 0 ||
2775 (r = sshbuf_get_bignum2(buf, k->rsa->p)) != 0 ||
2776 (r = sshbuf_get_bignum2(buf, k->rsa->q)) != 0 ||
2777 (r = rsa_generate_additional_parameters(k->rsa)) != 0)
2780 #endif /* WITH_OPENSSL */
2782 if ((k = sshkey_new_private(type)) == NULL) {
2783 r = SSH_ERR_ALLOC_FAIL;
2786 if ((r = sshbuf_get_string(buf, &ed25519_pk, &pklen)) != 0 ||
2787 (r = sshbuf_get_string(buf, &ed25519_sk, &sklen)) != 0)
2789 if (pklen != ED25519_PK_SZ || sklen != ED25519_SK_SZ) {
2790 r = SSH_ERR_INVALID_FORMAT;
2793 k->ed25519_pk = ed25519_pk;
2794 k->ed25519_sk = ed25519_sk;
2795 ed25519_pk = ed25519_sk = NULL;
2797 case KEY_ED25519_CERT:
2798 if ((r = sshkey_froms(buf, &k)) != 0 ||
2799 (r = sshkey_add_private(k)) != 0 ||
2800 (r = sshbuf_get_string(buf, &ed25519_pk, &pklen)) != 0 ||
2801 (r = sshbuf_get_string(buf, &ed25519_sk, &sklen)) != 0)
2803 if (pklen != ED25519_PK_SZ || sklen != ED25519_SK_SZ) {
2804 r = SSH_ERR_INVALID_FORMAT;
2807 k->ed25519_pk = ed25519_pk;
2808 k->ed25519_sk = ed25519_sk;
2809 ed25519_pk = ed25519_sk = NULL;
2812 r = SSH_ERR_KEY_TYPE_UNKNOWN;
2816 /* enable blinding */
2821 if (RSA_blinding_on(k->rsa, NULL) != 1) {
2822 r = SSH_ERR_LIBCRYPTO_ERROR;
2827 #endif /* WITH_OPENSSL */
2838 if (exponent != NULL)
2839 BN_clear_free(exponent);
2840 #endif /* WITH_OPENSSL */
2842 if (ed25519_pk != NULL) {
2843 explicit_bzero(ed25519_pk, pklen);
2846 if (ed25519_sk != NULL) {
2847 explicit_bzero(ed25519_sk, sklen);
2853 #if defined(WITH_OPENSSL) && defined(OPENSSL_HAS_ECC)
2855 sshkey_ec_validate_public(const EC_GROUP *group, const EC_POINT *public)
2858 EC_POINT *nq = NULL;
2859 BIGNUM *order, *x, *y, *tmp;
2860 int ret = SSH_ERR_KEY_INVALID_EC_VALUE;
2862 if ((bnctx = BN_CTX_new()) == NULL)
2863 return SSH_ERR_ALLOC_FAIL;
2864 BN_CTX_start(bnctx);
2867 * We shouldn't ever hit this case because bignum_get_ecpoint()
2868 * refuses to load GF2m points.
2870 if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) !=
2871 NID_X9_62_prime_field)
2875 if (EC_POINT_is_at_infinity(group, public))
2878 if ((x = BN_CTX_get(bnctx)) == NULL ||
2879 (y = BN_CTX_get(bnctx)) == NULL ||
2880 (order = BN_CTX_get(bnctx)) == NULL ||
2881 (tmp = BN_CTX_get(bnctx)) == NULL) {
2882 ret = SSH_ERR_ALLOC_FAIL;
2886 /* log2(x) > log2(order)/2, log2(y) > log2(order)/2 */
2887 if (EC_GROUP_get_order(group, order, bnctx) != 1 ||
2888 EC_POINT_get_affine_coordinates_GFp(group, public,
2889 x, y, bnctx) != 1) {
2890 ret = SSH_ERR_LIBCRYPTO_ERROR;
2893 if (BN_num_bits(x) <= BN_num_bits(order) / 2 ||
2894 BN_num_bits(y) <= BN_num_bits(order) / 2)
2897 /* nQ == infinity (n == order of subgroup) */
2898 if ((nq = EC_POINT_new(group)) == NULL) {
2899 ret = SSH_ERR_ALLOC_FAIL;
2902 if (EC_POINT_mul(group, nq, NULL, public, order, bnctx) != 1) {
2903 ret = SSH_ERR_LIBCRYPTO_ERROR;
2906 if (EC_POINT_is_at_infinity(group, nq) != 1)
2909 /* x < order - 1, y < order - 1 */
2910 if (!BN_sub(tmp, order, BN_value_one())) {
2911 ret = SSH_ERR_LIBCRYPTO_ERROR;
2914 if (BN_cmp(x, tmp) >= 0 || BN_cmp(y, tmp) >= 0)
2925 sshkey_ec_validate_private(const EC_KEY *key)
2928 BIGNUM *order, *tmp;
2929 int ret = SSH_ERR_KEY_INVALID_EC_VALUE;
2931 if ((bnctx = BN_CTX_new()) == NULL)
2932 return SSH_ERR_ALLOC_FAIL;
2933 BN_CTX_start(bnctx);
2935 if ((order = BN_CTX_get(bnctx)) == NULL ||
2936 (tmp = BN_CTX_get(bnctx)) == NULL) {
2937 ret = SSH_ERR_ALLOC_FAIL;
2941 /* log2(private) > log2(order)/2 */
2942 if (EC_GROUP_get_order(EC_KEY_get0_group(key), order, bnctx) != 1) {
2943 ret = SSH_ERR_LIBCRYPTO_ERROR;
2946 if (BN_num_bits(EC_KEY_get0_private_key(key)) <=
2947 BN_num_bits(order) / 2)
2950 /* private < order - 1 */
2951 if (!BN_sub(tmp, order, BN_value_one())) {
2952 ret = SSH_ERR_LIBCRYPTO_ERROR;
2955 if (BN_cmp(EC_KEY_get0_private_key(key), tmp) >= 0)
2964 sshkey_dump_ec_point(const EC_GROUP *group, const EC_POINT *point)
2969 if (point == NULL) {
2970 fputs("point=(NULL)\n", stderr);
2973 if ((bnctx = BN_CTX_new()) == NULL) {
2974 fprintf(stderr, "%s: BN_CTX_new failed\n", __func__);
2977 BN_CTX_start(bnctx);
2978 if ((x = BN_CTX_get(bnctx)) == NULL ||
2979 (y = BN_CTX_get(bnctx)) == NULL) {
2980 fprintf(stderr, "%s: BN_CTX_get failed\n", __func__);
2983 if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) !=
2984 NID_X9_62_prime_field) {
2985 fprintf(stderr, "%s: group is not a prime field\n", __func__);
2988 if (EC_POINT_get_affine_coordinates_GFp(group, point, x, y,
2990 fprintf(stderr, "%s: EC_POINT_get_affine_coordinates_GFp\n",
2994 fputs("x=", stderr);
2995 BN_print_fp(stderr, x);
2996 fputs("\ny=", stderr);
2997 BN_print_fp(stderr, y);
2998 fputs("\n", stderr);
3003 sshkey_dump_ec_key(const EC_KEY *key)
3005 const BIGNUM *exponent;
3007 sshkey_dump_ec_point(EC_KEY_get0_group(key),
3008 EC_KEY_get0_public_key(key));
3009 fputs("exponent=", stderr);
3010 if ((exponent = EC_KEY_get0_private_key(key)) == NULL)
3011 fputs("(NULL)", stderr);
3013 BN_print_fp(stderr, EC_KEY_get0_private_key(key));
3014 fputs("\n", stderr);
3016 #endif /* WITH_OPENSSL && OPENSSL_HAS_ECC */
3019 sshkey_private_to_blob2(const struct sshkey *prv, struct sshbuf *blob,
3020 const char *passphrase, const char *comment, const char *ciphername,
3023 u_char *cp, *key = NULL, *pubkeyblob = NULL;
3024 u_char salt[SALT_LEN];
3026 size_t i, pubkeylen, keylen, ivlen, blocksize, authlen;
3028 int r = SSH_ERR_INTERNAL_ERROR;
3029 struct sshcipher_ctx ciphercontext;
3030 const struct sshcipher *cipher;
3031 const char *kdfname = KDFNAME;
3032 struct sshbuf *encoded = NULL, *encrypted = NULL, *kdf = NULL;
3034 memset(&ciphercontext, 0, sizeof(ciphercontext));
3037 rounds = DEFAULT_ROUNDS;
3038 if (passphrase == NULL || !strlen(passphrase)) {
3039 ciphername = "none";
3041 } else if (ciphername == NULL)
3042 ciphername = DEFAULT_CIPHERNAME;
3043 else if (cipher_number(ciphername) != SSH_CIPHER_SSH2) {
3044 r = SSH_ERR_INVALID_ARGUMENT;
3047 if ((cipher = cipher_by_name(ciphername)) == NULL) {
3048 r = SSH_ERR_INTERNAL_ERROR;
3052 if ((kdf = sshbuf_new()) == NULL ||
3053 (encoded = sshbuf_new()) == NULL ||
3054 (encrypted = sshbuf_new()) == NULL) {
3055 r = SSH_ERR_ALLOC_FAIL;
3058 blocksize = cipher_blocksize(cipher);
3059 keylen = cipher_keylen(cipher);
3060 ivlen = cipher_ivlen(cipher);
3061 authlen = cipher_authlen(cipher);
3062 if ((key = calloc(1, keylen + ivlen)) == NULL) {
3063 r = SSH_ERR_ALLOC_FAIL;
3066 if (strcmp(kdfname, "bcrypt") == 0) {
3067 arc4random_buf(salt, SALT_LEN);
3068 if (bcrypt_pbkdf(passphrase, strlen(passphrase),
3069 salt, SALT_LEN, key, keylen + ivlen, rounds) < 0) {
3070 r = SSH_ERR_INVALID_ARGUMENT;
3073 if ((r = sshbuf_put_string(kdf, salt, SALT_LEN)) != 0 ||
3074 (r = sshbuf_put_u32(kdf, rounds)) != 0)
3076 } else if (strcmp(kdfname, "none") != 0) {
3077 /* Unsupported KDF type */
3078 r = SSH_ERR_KEY_UNKNOWN_CIPHER;
3081 if ((r = cipher_init(&ciphercontext, cipher, key, keylen,
3082 key + keylen, ivlen, 1)) != 0)
3085 if ((r = sshbuf_put(encoded, AUTH_MAGIC, sizeof(AUTH_MAGIC))) != 0 ||
3086 (r = sshbuf_put_cstring(encoded, ciphername)) != 0 ||
3087 (r = sshbuf_put_cstring(encoded, kdfname)) != 0 ||
3088 (r = sshbuf_put_stringb(encoded, kdf)) != 0 ||
3089 (r = sshbuf_put_u32(encoded, 1)) != 0 || /* number of keys */
3090 (r = sshkey_to_blob(prv, &pubkeyblob, &pubkeylen)) != 0 ||
3091 (r = sshbuf_put_string(encoded, pubkeyblob, pubkeylen)) != 0)
3094 /* set up the buffer that will be encrypted */
3096 /* Random check bytes */
3097 check = arc4random();
3098 if ((r = sshbuf_put_u32(encrypted, check)) != 0 ||
3099 (r = sshbuf_put_u32(encrypted, check)) != 0)
3102 /* append private key and comment*/
3103 if ((r = sshkey_private_serialize(prv, encrypted)) != 0 ||
3104 (r = sshbuf_put_cstring(encrypted, comment)) != 0)
3109 while (sshbuf_len(encrypted) % blocksize) {
3110 if ((r = sshbuf_put_u8(encrypted, ++i & 0xff)) != 0)
3114 /* length in destination buffer */
3115 if ((r = sshbuf_put_u32(encoded, sshbuf_len(encrypted))) != 0)
3119 if ((r = sshbuf_reserve(encoded,
3120 sshbuf_len(encrypted) + authlen, &cp)) != 0)
3122 if ((r = cipher_crypt(&ciphercontext, 0, cp,
3123 sshbuf_ptr(encrypted), sshbuf_len(encrypted), 0, authlen)) != 0)
3127 if ((b64 = sshbuf_dtob64(encoded)) == NULL) {
3128 r = SSH_ERR_ALLOC_FAIL;
3133 if ((r = sshbuf_put(blob, MARK_BEGIN, MARK_BEGIN_LEN)) != 0)
3135 for (i = 0; i < strlen(b64); i++) {
3136 if ((r = sshbuf_put_u8(blob, b64[i])) != 0)
3138 /* insert line breaks */
3139 if (i % 70 == 69 && (r = sshbuf_put_u8(blob, '\n')) != 0)
3142 if (i % 70 != 69 && (r = sshbuf_put_u8(blob, '\n')) != 0)
3144 if ((r = sshbuf_put(blob, MARK_END, MARK_END_LEN)) != 0)
3152 sshbuf_free(encoded);
3153 sshbuf_free(encrypted);
3154 cipher_cleanup(&ciphercontext);
3155 explicit_bzero(salt, sizeof(salt));
3157 explicit_bzero(key, keylen + ivlen);
3160 if (pubkeyblob != NULL) {
3161 explicit_bzero(pubkeyblob, pubkeylen);
3165 explicit_bzero(b64, strlen(b64));
3172 sshkey_parse_private2(struct sshbuf *blob, int type, const char *passphrase,
3173 struct sshkey **keyp, char **commentp)
3175 char *comment = NULL, *ciphername = NULL, *kdfname = NULL;
3176 const struct sshcipher *cipher = NULL;
3178 int r = SSH_ERR_INTERNAL_ERROR;
3180 size_t i, keylen = 0, ivlen = 0, authlen = 0, slen = 0;
3181 struct sshbuf *encoded = NULL, *decoded = NULL;
3182 struct sshbuf *kdf = NULL, *decrypted = NULL;
3183 struct sshcipher_ctx ciphercontext;
3184 struct sshkey *k = NULL;
3185 u_char *key = NULL, *salt = NULL, *dp, pad, last;
3186 u_int blocksize, rounds, nkeys, encrypted_len, check1, check2;
3188 memset(&ciphercontext, 0, sizeof(ciphercontext));
3191 if (commentp != NULL)
3194 if ((encoded = sshbuf_new()) == NULL ||
3195 (decoded = sshbuf_new()) == NULL ||
3196 (decrypted = sshbuf_new()) == NULL) {
3197 r = SSH_ERR_ALLOC_FAIL;
3201 /* check preamble */
3202 cp = sshbuf_ptr(blob);
3203 encoded_len = sshbuf_len(blob);
3204 if (encoded_len < (MARK_BEGIN_LEN + MARK_END_LEN) ||
3205 memcmp(cp, MARK_BEGIN, MARK_BEGIN_LEN) != 0) {
3206 r = SSH_ERR_INVALID_FORMAT;
3209 cp += MARK_BEGIN_LEN;
3210 encoded_len -= MARK_BEGIN_LEN;
3212 /* Look for end marker, removing whitespace as we go */
3213 while (encoded_len > 0) {
3214 if (*cp != '\n' && *cp != '\r') {
3215 if ((r = sshbuf_put_u8(encoded, *cp)) != 0)
3222 if (encoded_len >= MARK_END_LEN &&
3223 memcmp(cp, MARK_END, MARK_END_LEN) == 0) {
3225 if ((r = sshbuf_put_u8(encoded, 0)) != 0)
3231 if (encoded_len == 0) {
3232 r = SSH_ERR_INVALID_FORMAT;
3237 if ((r = sshbuf_b64tod(decoded, (char *)sshbuf_ptr(encoded))) != 0)
3241 if (sshbuf_len(decoded) < sizeof(AUTH_MAGIC) ||
3242 memcmp(sshbuf_ptr(decoded), AUTH_MAGIC, sizeof(AUTH_MAGIC))) {
3243 r = SSH_ERR_INVALID_FORMAT;
3246 /* parse public portion of key */
3247 if ((r = sshbuf_consume(decoded, sizeof(AUTH_MAGIC))) != 0 ||
3248 (r = sshbuf_get_cstring(decoded, &ciphername, NULL)) != 0 ||
3249 (r = sshbuf_get_cstring(decoded, &kdfname, NULL)) != 0 ||
3250 (r = sshbuf_froms(decoded, &kdf)) != 0 ||
3251 (r = sshbuf_get_u32(decoded, &nkeys)) != 0 ||
3252 (r = sshbuf_skip_string(decoded)) != 0 || /* pubkey */
3253 (r = sshbuf_get_u32(decoded, &encrypted_len)) != 0)
3256 if ((cipher = cipher_by_name(ciphername)) == NULL) {
3257 r = SSH_ERR_KEY_UNKNOWN_CIPHER;
3260 if ((passphrase == NULL || strlen(passphrase) == 0) &&
3261 strcmp(ciphername, "none") != 0) {
3262 /* passphrase required */
3263 r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3266 if (strcmp(kdfname, "none") != 0 && strcmp(kdfname, "bcrypt") != 0) {
3267 r = SSH_ERR_KEY_UNKNOWN_CIPHER;
3270 if (!strcmp(kdfname, "none") && strcmp(ciphername, "none") != 0) {
3271 r = SSH_ERR_INVALID_FORMAT;
3275 /* XXX only one key supported */
3276 r = SSH_ERR_INVALID_FORMAT;
3280 /* check size of encrypted key blob */
3281 blocksize = cipher_blocksize(cipher);
3282 if (encrypted_len < blocksize || (encrypted_len % blocksize) != 0) {
3283 r = SSH_ERR_INVALID_FORMAT;
3288 keylen = cipher_keylen(cipher);
3289 ivlen = cipher_ivlen(cipher);
3290 authlen = cipher_authlen(cipher);
3291 if ((key = calloc(1, keylen + ivlen)) == NULL) {
3292 r = SSH_ERR_ALLOC_FAIL;
3295 if (strcmp(kdfname, "bcrypt") == 0) {
3296 if ((r = sshbuf_get_string(kdf, &salt, &slen)) != 0 ||
3297 (r = sshbuf_get_u32(kdf, &rounds)) != 0)
3299 if (bcrypt_pbkdf(passphrase, strlen(passphrase), salt, slen,
3300 key, keylen + ivlen, rounds) < 0) {
3301 r = SSH_ERR_INVALID_FORMAT;
3306 /* check that an appropriate amount of auth data is present */
3307 if (sshbuf_len(decoded) < encrypted_len + authlen) {
3308 r = SSH_ERR_INVALID_FORMAT;
3312 /* decrypt private portion of key */
3313 if ((r = sshbuf_reserve(decrypted, encrypted_len, &dp)) != 0 ||
3314 (r = cipher_init(&ciphercontext, cipher, key, keylen,
3315 key + keylen, ivlen, 0)) != 0)
3317 if ((r = cipher_crypt(&ciphercontext, 0, dp, sshbuf_ptr(decoded),
3318 encrypted_len, 0, authlen)) != 0) {
3319 /* an integrity error here indicates an incorrect passphrase */
3320 if (r == SSH_ERR_MAC_INVALID)
3321 r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3324 if ((r = sshbuf_consume(decoded, encrypted_len + authlen)) != 0)
3326 /* there should be no trailing data */
3327 if (sshbuf_len(decoded) != 0) {
3328 r = SSH_ERR_INVALID_FORMAT;
3332 /* check check bytes */
3333 if ((r = sshbuf_get_u32(decrypted, &check1)) != 0 ||
3334 (r = sshbuf_get_u32(decrypted, &check2)) != 0)
3336 if (check1 != check2) {
3337 r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3341 /* Load the private key and comment */
3342 if ((r = sshkey_private_deserialize(decrypted, &k)) != 0 ||
3343 (r = sshbuf_get_cstring(decrypted, &comment, NULL)) != 0)
3346 /* Check deterministic padding */
3348 while (sshbuf_len(decrypted)) {
3349 if ((r = sshbuf_get_u8(decrypted, &pad)) != 0)
3351 if (pad != (++i & 0xff)) {
3352 r = SSH_ERR_INVALID_FORMAT;
3357 /* XXX decode pubkey and check against private */
3365 if (commentp != NULL) {
3366 *commentp = comment;
3371 cipher_cleanup(&ciphercontext);
3376 explicit_bzero(salt, slen);
3380 explicit_bzero(key, keylen + ivlen);
3383 sshbuf_free(encoded);
3384 sshbuf_free(decoded);
3386 sshbuf_free(decrypted);
3393 * Serialises the authentication (private) key to a blob, encrypting it with
3394 * passphrase. The identification of the blob (lowest 64 bits of n) will
3395 * precede the key to provide identification of the key without needing a
3399 sshkey_private_rsa1_to_blob(struct sshkey *key, struct sshbuf *blob,
3400 const char *passphrase, const char *comment)
3402 struct sshbuf *buffer = NULL, *encrypted = NULL;
3405 struct sshcipher_ctx ciphercontext;
3406 const struct sshcipher *cipher;
3410 * If the passphrase is empty, use SSH_CIPHER_NONE to ease converting
3411 * to another cipher; otherwise use SSH_AUTHFILE_CIPHER.
3413 cipher_num = (strcmp(passphrase, "") == 0) ?
3414 SSH_CIPHER_NONE : SSH_CIPHER_3DES;
3415 if ((cipher = cipher_by_number(cipher_num)) == NULL)
3416 return SSH_ERR_INTERNAL_ERROR;
3418 /* This buffer is used to build the secret part of the private key. */
3419 if ((buffer = sshbuf_new()) == NULL)
3420 return SSH_ERR_ALLOC_FAIL;
3422 /* Put checkbytes for checking passphrase validity. */
3423 if ((r = sshbuf_reserve(buffer, 4, &cp)) != 0)
3425 arc4random_buf(cp, 2);
3426 memcpy(cp + 2, cp, 2);
3429 * Store the private key (n and e will not be stored because they
3430 * will be stored in plain text, and storing them also in encrypted
3431 * format would just give known plaintext).
3432 * Note: q and p are stored in reverse order to SSL.
3434 if ((r = sshbuf_put_bignum1(buffer, key->rsa->d)) != 0 ||
3435 (r = sshbuf_put_bignum1(buffer, key->rsa->iqmp)) != 0 ||
3436 (r = sshbuf_put_bignum1(buffer, key->rsa->q)) != 0 ||
3437 (r = sshbuf_put_bignum1(buffer, key->rsa->p)) != 0)
3440 /* Pad the part to be encrypted to a size that is a multiple of 8. */
3441 explicit_bzero(buf, 8);
3442 if ((r = sshbuf_put(buffer, buf, 8 - (sshbuf_len(buffer) % 8))) != 0)
3445 /* This buffer will be used to contain the data in the file. */
3446 if ((encrypted = sshbuf_new()) == NULL) {
3447 r = SSH_ERR_ALLOC_FAIL;
3451 /* First store keyfile id string. */
3452 if ((r = sshbuf_put(encrypted, LEGACY_BEGIN,
3453 sizeof(LEGACY_BEGIN))) != 0)
3456 /* Store cipher type and "reserved" field. */
3457 if ((r = sshbuf_put_u8(encrypted, cipher_num)) != 0 ||
3458 (r = sshbuf_put_u32(encrypted, 0)) != 0)
3461 /* Store public key. This will be in plain text. */
3462 if ((r = sshbuf_put_u32(encrypted, BN_num_bits(key->rsa->n))) != 0 ||
3463 (r = sshbuf_put_bignum1(encrypted, key->rsa->n)) != 0 ||
3464 (r = sshbuf_put_bignum1(encrypted, key->rsa->e)) != 0 ||
3465 (r = sshbuf_put_cstring(encrypted, comment)) != 0)
3468 /* Allocate space for the private part of the key in the buffer. */
3469 if ((r = sshbuf_reserve(encrypted, sshbuf_len(buffer), &cp)) != 0)
3472 if ((r = cipher_set_key_string(&ciphercontext, cipher, passphrase,
3473 CIPHER_ENCRYPT)) != 0)
3475 if ((r = cipher_crypt(&ciphercontext, 0, cp,
3476 sshbuf_ptr(buffer), sshbuf_len(buffer), 0, 0)) != 0)
3478 if ((r = cipher_cleanup(&ciphercontext)) != 0)
3481 r = sshbuf_putb(blob, encrypted);
3484 explicit_bzero(&ciphercontext, sizeof(ciphercontext));
3485 explicit_bzero(buf, sizeof(buf));
3486 sshbuf_free(buffer);
3487 sshbuf_free(encrypted);
3491 #endif /* WITH_SSH1 */
3494 /* convert SSH v2 key in OpenSSL PEM format */
3496 sshkey_private_pem_to_blob(struct sshkey *key, struct sshbuf *blob,
3497 const char *_passphrase, const char *comment)
3500 int blen, len = strlen(_passphrase);
3501 u_char *passphrase = (len > 0) ? (u_char *)_passphrase : NULL;
3502 #if (OPENSSL_VERSION_NUMBER < 0x00907000L)
3503 const EVP_CIPHER *cipher = (len > 0) ? EVP_des_ede3_cbc() : NULL;
3505 const EVP_CIPHER *cipher = (len > 0) ? EVP_aes_128_cbc() : NULL;
3510 if (len > 0 && len <= 4)
3511 return SSH_ERR_PASSPHRASE_TOO_SHORT;
3512 if ((bio = BIO_new(BIO_s_mem())) == NULL)
3513 return SSH_ERR_ALLOC_FAIL;
3515 switch (key->type) {
3517 success = PEM_write_bio_DSAPrivateKey(bio, key->dsa,
3518 cipher, passphrase, len, NULL, NULL);
3520 #ifdef OPENSSL_HAS_ECC
3522 success = PEM_write_bio_ECPrivateKey(bio, key->ecdsa,
3523 cipher, passphrase, len, NULL, NULL);
3527 success = PEM_write_bio_RSAPrivateKey(bio, key->rsa,
3528 cipher, passphrase, len, NULL, NULL);
3535 r = SSH_ERR_LIBCRYPTO_ERROR;
3538 if ((blen = BIO_get_mem_data(bio, &bptr)) <= 0) {
3539 r = SSH_ERR_INTERNAL_ERROR;
3542 if ((r = sshbuf_put(blob, bptr, blen)) != 0)
3549 #endif /* WITH_OPENSSL */
3551 /* Serialise "key" to buffer "blob" */
3553 sshkey_private_to_fileblob(struct sshkey *key, struct sshbuf *blob,
3554 const char *passphrase, const char *comment,
3555 int force_new_format, const char *new_format_cipher, int new_format_rounds)
3557 switch (key->type) {
3560 return sshkey_private_rsa1_to_blob(key, blob,
3561 passphrase, comment);
3562 #endif /* WITH_SSH1 */
3567 if (force_new_format) {
3568 return sshkey_private_to_blob2(key, blob, passphrase,
3569 comment, new_format_cipher, new_format_rounds);
3571 return sshkey_private_pem_to_blob(key, blob,
3572 passphrase, comment);
3573 #endif /* WITH_OPENSSL */
3575 return sshkey_private_to_blob2(key, blob, passphrase,
3576 comment, new_format_cipher, new_format_rounds);
3578 return SSH_ERR_KEY_TYPE_UNKNOWN;
3584 * Parse the public, unencrypted portion of a RSA1 key.
3587 sshkey_parse_public_rsa1_fileblob(struct sshbuf *blob,
3588 struct sshkey **keyp, char **commentp)
3591 struct sshkey *pub = NULL;
3592 struct sshbuf *copy = NULL;
3596 if (commentp != NULL)
3599 /* Check that it is at least big enough to contain the ID string. */
3600 if (sshbuf_len(blob) < sizeof(LEGACY_BEGIN))
3601 return SSH_ERR_INVALID_FORMAT;
3604 * Make sure it begins with the id string. Consume the id string
3607 if (memcmp(sshbuf_ptr(blob), LEGACY_BEGIN, sizeof(LEGACY_BEGIN)) != 0)
3608 return SSH_ERR_INVALID_FORMAT;
3609 /* Make a working copy of the keyblob and skip past the magic */
3610 if ((copy = sshbuf_fromb(blob)) == NULL)
3611 return SSH_ERR_ALLOC_FAIL;
3612 if ((r = sshbuf_consume(copy, sizeof(LEGACY_BEGIN))) != 0)
3615 /* Skip cipher type, reserved data and key bits. */
3616 if ((r = sshbuf_get_u8(copy, NULL)) != 0 || /* cipher type */
3617 (r = sshbuf_get_u32(copy, NULL)) != 0 || /* reserved */
3618 (r = sshbuf_get_u32(copy, NULL)) != 0) /* key bits */
3621 /* Read the public key from the buffer. */
3622 if ((pub = sshkey_new(KEY_RSA1)) == NULL ||
3623 (r = sshbuf_get_bignum1(copy, pub->rsa->n)) != 0 ||
3624 (r = sshbuf_get_bignum1(copy, pub->rsa->e)) != 0)
3627 /* Finally, the comment */
3628 if ((r = sshbuf_get_string(copy, (u_char**)commentp, NULL)) != 0)
3631 /* The encrypted private part is not parsed by this function. */
3647 sshkey_parse_private_rsa1(struct sshbuf *blob, const char *passphrase,
3648 struct sshkey **keyp, char **commentp)
3651 u_int16_t check1, check2;
3652 u_int8_t cipher_type;
3653 struct sshbuf *decrypted = NULL, *copy = NULL;
3655 char *comment = NULL;
3656 struct sshcipher_ctx ciphercontext;
3657 const struct sshcipher *cipher;
3658 struct sshkey *prv = NULL;
3661 if (commentp != NULL)
3664 /* Check that it is at least big enough to contain the ID string. */
3665 if (sshbuf_len(blob) < sizeof(LEGACY_BEGIN))
3666 return SSH_ERR_INVALID_FORMAT;
3669 * Make sure it begins with the id string. Consume the id string
3672 if (memcmp(sshbuf_ptr(blob), LEGACY_BEGIN, sizeof(LEGACY_BEGIN)) != 0)
3673 return SSH_ERR_INVALID_FORMAT;
3675 if ((prv = sshkey_new_private(KEY_RSA1)) == NULL) {
3676 r = SSH_ERR_ALLOC_FAIL;
3679 if ((copy = sshbuf_fromb(blob)) == NULL ||
3680 (decrypted = sshbuf_new()) == NULL) {
3681 r = SSH_ERR_ALLOC_FAIL;
3684 if ((r = sshbuf_consume(copy, sizeof(LEGACY_BEGIN))) != 0)
3687 /* Read cipher type. */
3688 if ((r = sshbuf_get_u8(copy, &cipher_type)) != 0 ||
3689 (r = sshbuf_get_u32(copy, NULL)) != 0) /* reserved */
3692 /* Read the public key and comment from the buffer. */
3693 if ((r = sshbuf_get_u32(copy, NULL)) != 0 || /* key bits */
3694 (r = sshbuf_get_bignum1(copy, prv->rsa->n)) != 0 ||
3695 (r = sshbuf_get_bignum1(copy, prv->rsa->e)) != 0 ||
3696 (r = sshbuf_get_cstring(copy, &comment, NULL)) != 0)
3699 /* Check that it is a supported cipher. */
3700 cipher = cipher_by_number(cipher_type);
3701 if (cipher == NULL) {
3702 r = SSH_ERR_KEY_UNKNOWN_CIPHER;
3705 /* Initialize space for decrypted data. */
3706 if ((r = sshbuf_reserve(decrypted, sshbuf_len(copy), &cp)) != 0)
3709 /* Rest of the buffer is encrypted. Decrypt it using the passphrase. */
3710 if ((r = cipher_set_key_string(&ciphercontext, cipher, passphrase,
3711 CIPHER_DECRYPT)) != 0)
3713 if ((r = cipher_crypt(&ciphercontext, 0, cp,
3714 sshbuf_ptr(copy), sshbuf_len(copy), 0, 0)) != 0) {
3715 cipher_cleanup(&ciphercontext);
3718 if ((r = cipher_cleanup(&ciphercontext)) != 0)
3721 if ((r = sshbuf_get_u16(decrypted, &check1)) != 0 ||
3722 (r = sshbuf_get_u16(decrypted, &check2)) != 0)
3724 if (check1 != check2) {
3725 r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3729 /* Read the rest of the private key. */
3730 if ((r = sshbuf_get_bignum1(decrypted, prv->rsa->d)) != 0 ||
3731 (r = sshbuf_get_bignum1(decrypted, prv->rsa->iqmp)) != 0 ||
3732 (r = sshbuf_get_bignum1(decrypted, prv->rsa->q)) != 0 ||
3733 (r = sshbuf_get_bignum1(decrypted, prv->rsa->p)) != 0)
3736 /* calculate p-1 and q-1 */
3737 if ((r = rsa_generate_additional_parameters(prv->rsa)) != 0)
3740 /* enable blinding */
3741 if (RSA_blinding_on(prv->rsa, NULL) != 1) {
3742 r = SSH_ERR_LIBCRYPTO_ERROR;
3748 if (commentp != NULL) {
3749 *commentp = comment;
3753 explicit_bzero(&ciphercontext, sizeof(ciphercontext));
3757 sshbuf_free(decrypted);
3760 #endif /* WITH_SSH1 */
3764 sshkey_parse_private_pem_fileblob(struct sshbuf *blob, int type,
3765 const char *passphrase, struct sshkey **keyp)
3767 EVP_PKEY *pk = NULL;
3768 struct sshkey *prv = NULL;
3774 if ((bio = BIO_new(BIO_s_mem())) == NULL || sshbuf_len(blob) > INT_MAX)
3775 return SSH_ERR_ALLOC_FAIL;
3776 if (BIO_write(bio, sshbuf_ptr(blob), sshbuf_len(blob)) !=
3777 (int)sshbuf_len(blob)) {
3778 r = SSH_ERR_ALLOC_FAIL;
3782 if ((pk = PEM_read_bio_PrivateKey(bio, NULL, NULL,
3783 (char *)passphrase)) == NULL) {
3784 r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3787 if (pk->type == EVP_PKEY_RSA &&
3788 (type == KEY_UNSPEC || type == KEY_RSA)) {
3789 if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
3790 r = SSH_ERR_ALLOC_FAIL;
3793 prv->rsa = EVP_PKEY_get1_RSA(pk);
3794 prv->type = KEY_RSA;
3796 RSA_print_fp(stderr, prv->rsa, 8);
3798 if (RSA_blinding_on(prv->rsa, NULL) != 1) {
3799 r = SSH_ERR_LIBCRYPTO_ERROR;
3802 } else if (pk->type == EVP_PKEY_DSA &&
3803 (type == KEY_UNSPEC || type == KEY_DSA)) {
3804 if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
3805 r = SSH_ERR_ALLOC_FAIL;
3808 prv->dsa = EVP_PKEY_get1_DSA(pk);
3809 prv->type = KEY_DSA;
3811 DSA_print_fp(stderr, prv->dsa, 8);
3813 #ifdef OPENSSL_HAS_ECC
3814 } else if (pk->type == EVP_PKEY_EC &&
3815 (type == KEY_UNSPEC || type == KEY_ECDSA)) {
3816 if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
3817 r = SSH_ERR_ALLOC_FAIL;
3820 prv->ecdsa = EVP_PKEY_get1_EC_KEY(pk);
3821 prv->type = KEY_ECDSA;
3822 prv->ecdsa_nid = sshkey_ecdsa_key_to_nid(prv->ecdsa);
3823 if (prv->ecdsa_nid == -1 ||
3824 sshkey_curve_nid_to_name(prv->ecdsa_nid) == NULL ||
3825 sshkey_ec_validate_public(EC_KEY_get0_group(prv->ecdsa),
3826 EC_KEY_get0_public_key(prv->ecdsa)) != 0 ||
3827 sshkey_ec_validate_private(prv->ecdsa) != 0) {
3828 r = SSH_ERR_INVALID_FORMAT;
3832 if (prv != NULL && prv->ecdsa != NULL)
3833 sshkey_dump_ec_key(prv->ecdsa);
3835 #endif /* OPENSSL_HAS_ECC */
3837 r = SSH_ERR_INVALID_FORMAT;
3850 #endif /* WITH_OPENSSL */
3853 sshkey_parse_private_fileblob_type(struct sshbuf *blob, int type,
3854 const char *passphrase, struct sshkey **keyp, char **commentp)
3857 if (commentp != NULL)
3863 return sshkey_parse_private_rsa1(blob, passphrase,
3865 #endif /* WITH_SSH1 */
3870 return sshkey_parse_private_pem_fileblob(blob, type,
3872 #endif /* WITH_OPENSSL */
3874 return sshkey_parse_private2(blob, type, passphrase,
3877 if (sshkey_parse_private2(blob, type, passphrase, keyp,
3881 return sshkey_parse_private_pem_fileblob(blob, type,
3884 return SSH_ERR_INVALID_FORMAT;
3885 #endif /* WITH_OPENSSL */
3887 return SSH_ERR_KEY_TYPE_UNKNOWN;
3892 sshkey_parse_private_fileblob(struct sshbuf *buffer, const char *passphrase,
3893 struct sshkey **keyp, char **commentp)
3897 if (commentp != NULL)
3901 /* it's a SSH v1 key if the public key part is readable */
3902 if (sshkey_parse_public_rsa1_fileblob(buffer, NULL, NULL) == 0) {
3903 return sshkey_parse_private_fileblob_type(buffer, KEY_RSA1,
3904 passphrase, keyp, commentp);
3906 #endif /* WITH_SSH1 */
3907 return sshkey_parse_private_fileblob_type(buffer, KEY_UNSPEC,
3908 passphrase, keyp, commentp);