1 /* $OpenBSD: sshkey.c,v 1.45 2017/03/10 04:07:20 djm Exp $ */
3 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
4 * Copyright (c) 2008 Alexander von Gernler. All rights reserved.
5 * Copyright (c) 2010,2011 Damien Miller. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 #include <sys/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 },
93 { NULL, "RSA1", KEY_RSA1, 0, 0, 0 },
95 { "ssh-rsa", "RSA", KEY_RSA, 0, 0, 0 },
96 { "rsa-sha2-256", "RSA", KEY_RSA, 0, 0, 1 },
97 { "rsa-sha2-512", "RSA", KEY_RSA, 0, 0, 1 },
98 { "ssh-dss", "DSA", KEY_DSA, 0, 0, 0 },
99 # ifdef OPENSSL_HAS_ECC
100 { "ecdsa-sha2-nistp256", "ECDSA", KEY_ECDSA, NID_X9_62_prime256v1, 0, 0 },
101 { "ecdsa-sha2-nistp384", "ECDSA", KEY_ECDSA, NID_secp384r1, 0, 0 },
102 # ifdef OPENSSL_HAS_NISTP521
103 { "ecdsa-sha2-nistp521", "ECDSA", KEY_ECDSA, NID_secp521r1, 0, 0 },
104 # endif /* OPENSSL_HAS_NISTP521 */
105 # endif /* OPENSSL_HAS_ECC */
106 { "ssh-rsa-cert-v01@openssh.com", "RSA-CERT", KEY_RSA_CERT, 0, 1, 0 },
107 { "ssh-dss-cert-v01@openssh.com", "DSA-CERT", KEY_DSA_CERT, 0, 1, 0 },
108 # ifdef OPENSSL_HAS_ECC
109 { "ecdsa-sha2-nistp256-cert-v01@openssh.com", "ECDSA-CERT",
110 KEY_ECDSA_CERT, NID_X9_62_prime256v1, 1, 0 },
111 { "ecdsa-sha2-nistp384-cert-v01@openssh.com", "ECDSA-CERT",
112 KEY_ECDSA_CERT, NID_secp384r1, 1, 0 },
113 # ifdef OPENSSL_HAS_NISTP521
114 { "ecdsa-sha2-nistp521-cert-v01@openssh.com", "ECDSA-CERT",
115 KEY_ECDSA_CERT, NID_secp521r1, 1, 0 },
116 # endif /* OPENSSL_HAS_NISTP521 */
117 # endif /* OPENSSL_HAS_ECC */
118 #endif /* WITH_OPENSSL */
119 { NULL, NULL, -1, -1, 0, 0 }
123 sshkey_type(const struct sshkey *k)
125 const struct keytype *kt;
127 for (kt = keytypes; kt->type != -1; kt++) {
128 if (kt->type == k->type)
129 return kt->shortname;
135 sshkey_ssh_name_from_type_nid(int type, int nid)
137 const struct keytype *kt;
139 for (kt = keytypes; kt->type != -1; kt++) {
140 if (kt->type == type && (kt->nid == 0 || kt->nid == nid))
143 return "ssh-unknown";
147 sshkey_type_is_cert(int type)
149 const struct keytype *kt;
151 for (kt = keytypes; kt->type != -1; kt++) {
152 if (kt->type == type)
159 sshkey_ssh_name(const struct sshkey *k)
161 return sshkey_ssh_name_from_type_nid(k->type, k->ecdsa_nid);
165 sshkey_ssh_name_plain(const struct sshkey *k)
167 return sshkey_ssh_name_from_type_nid(sshkey_type_plain(k->type),
172 sshkey_type_from_name(const char *name)
174 const struct keytype *kt;
176 for (kt = keytypes; kt->type != -1; kt++) {
177 /* Only allow shortname matches for plain key types */
178 if ((kt->name != NULL && strcmp(name, kt->name) == 0) ||
179 (!kt->cert && strcasecmp(kt->shortname, name) == 0))
186 sshkey_ecdsa_nid_from_name(const char *name)
188 const struct keytype *kt;
190 for (kt = keytypes; kt->type != -1; kt++) {
191 if (kt->type != KEY_ECDSA && kt->type != KEY_ECDSA_CERT)
193 if (kt->name != NULL && strcmp(name, kt->name) == 0)
200 sshkey_alg_list(int certs_only, int plain_only, int include_sigonly, char sep)
202 char *tmp, *ret = NULL;
203 size_t nlen, rlen = 0;
204 const struct keytype *kt;
206 for (kt = keytypes; kt->type != -1; kt++) {
207 if (kt->name == NULL)
209 if (!include_sigonly && kt->sigonly)
211 if ((certs_only && !kt->cert) || (plain_only && kt->cert))
215 nlen = strlen(kt->name);
216 if ((tmp = realloc(ret, rlen + nlen + 2)) == NULL) {
221 memcpy(ret + rlen, kt->name, nlen + 1);
228 sshkey_names_valid2(const char *names, int allow_wildcard)
231 const struct keytype *kt;
234 if (names == NULL || strcmp(names, "") == 0)
236 if ((s = cp = strdup(names)) == NULL)
238 for ((p = strsep(&cp, ",")); p && *p != '\0';
239 (p = strsep(&cp, ","))) {
240 type = sshkey_type_from_name(p);
241 if (type == KEY_RSA1) {
245 if (type == KEY_UNSPEC) {
246 if (allow_wildcard) {
248 * Try matching key types against the string.
249 * If any has a positive or negative match then
250 * the component is accepted.
252 for (kt = keytypes; kt->type != -1; kt++) {
253 if (kt->type == KEY_RSA1)
255 if (match_pattern_list(kt->name,
271 sshkey_size(const struct sshkey *k)
278 return BN_num_bits(k->rsa->n);
281 return BN_num_bits(k->dsa->p);
284 return sshkey_curve_nid_to_bits(k->ecdsa_nid);
285 #endif /* WITH_OPENSSL */
287 case KEY_ED25519_CERT:
288 return 256; /* XXX */
294 sshkey_type_is_valid_ca(int type)
308 sshkey_is_cert(const struct sshkey *k)
312 return sshkey_type_is_cert(k->type);
315 /* Return the cert-less equivalent to a certified key type */
317 sshkey_type_plain(int type)
326 case KEY_ED25519_CERT:
334 /* XXX: these are really begging for a table-driven approach */
336 sshkey_curve_name_to_nid(const char *name)
338 if (strcmp(name, "nistp256") == 0)
339 return NID_X9_62_prime256v1;
340 else if (strcmp(name, "nistp384") == 0)
341 return NID_secp384r1;
342 # ifdef OPENSSL_HAS_NISTP521
343 else if (strcmp(name, "nistp521") == 0)
344 return NID_secp521r1;
345 # endif /* OPENSSL_HAS_NISTP521 */
351 sshkey_curve_nid_to_bits(int nid)
354 case NID_X9_62_prime256v1:
358 # ifdef OPENSSL_HAS_NISTP521
361 # endif /* OPENSSL_HAS_NISTP521 */
368 sshkey_ecdsa_bits_to_nid(int bits)
372 return NID_X9_62_prime256v1;
374 return NID_secp384r1;
375 # ifdef OPENSSL_HAS_NISTP521
377 return NID_secp521r1;
378 # endif /* OPENSSL_HAS_NISTP521 */
385 sshkey_curve_nid_to_name(int nid)
388 case NID_X9_62_prime256v1:
392 # ifdef OPENSSL_HAS_NISTP521
395 # endif /* OPENSSL_HAS_NISTP521 */
402 sshkey_ec_nid_to_hash_alg(int nid)
404 int kbits = sshkey_curve_nid_to_bits(nid);
409 /* RFC5656 section 6.2.1 */
411 return SSH_DIGEST_SHA256;
412 else if (kbits <= 384)
413 return SSH_DIGEST_SHA384;
415 return SSH_DIGEST_SHA512;
417 #endif /* WITH_OPENSSL */
420 cert_free(struct sshkey_cert *cert)
426 sshbuf_free(cert->certblob);
427 sshbuf_free(cert->critical);
428 sshbuf_free(cert->extensions);
430 for (i = 0; i < cert->nprincipals; i++)
431 free(cert->principals[i]);
432 free(cert->principals);
433 sshkey_free(cert->signature_key);
434 explicit_bzero(cert, sizeof(*cert));
438 static struct sshkey_cert *
441 struct sshkey_cert *cert;
443 if ((cert = calloc(1, sizeof(*cert))) == NULL)
445 if ((cert->certblob = sshbuf_new()) == NULL ||
446 (cert->critical = sshbuf_new()) == NULL ||
447 (cert->extensions = sshbuf_new()) == NULL) {
452 cert->principals = NULL;
453 cert->signature_key = NULL;
464 #endif /* WITH_OPENSSL */
466 if ((k = calloc(1, sizeof(*k))) == NULL)
474 k->ed25519_sk = NULL;
475 k->ed25519_pk = NULL;
481 if ((rsa = RSA_new()) == NULL ||
482 (rsa->n = BN_new()) == NULL ||
483 (rsa->e = BN_new()) == NULL) {
493 if ((dsa = DSA_new()) == NULL ||
494 (dsa->p = BN_new()) == NULL ||
495 (dsa->q = BN_new()) == NULL ||
496 (dsa->g = BN_new()) == NULL ||
497 (dsa->pub_key = BN_new()) == NULL) {
507 /* Cannot do anything until we know the group */
509 #endif /* WITH_OPENSSL */
511 case KEY_ED25519_CERT:
512 /* no need to prealloc */
521 if (sshkey_is_cert(k)) {
522 if ((k->cert = cert_new()) == NULL) {
532 sshkey_add_private(struct sshkey *k)
539 #define bn_maybe_alloc_failed(p) (p == NULL && (p = BN_new()) == NULL)
540 if (bn_maybe_alloc_failed(k->rsa->d) ||
541 bn_maybe_alloc_failed(k->rsa->iqmp) ||
542 bn_maybe_alloc_failed(k->rsa->q) ||
543 bn_maybe_alloc_failed(k->rsa->p) ||
544 bn_maybe_alloc_failed(k->rsa->dmq1) ||
545 bn_maybe_alloc_failed(k->rsa->dmp1))
546 return SSH_ERR_ALLOC_FAIL;
550 if (bn_maybe_alloc_failed(k->dsa->priv_key))
551 return SSH_ERR_ALLOC_FAIL;
553 #undef bn_maybe_alloc_failed
556 /* Cannot do anything until we know the group */
558 #endif /* WITH_OPENSSL */
560 case KEY_ED25519_CERT:
561 /* no need to prealloc */
566 return SSH_ERR_INVALID_ARGUMENT;
572 sshkey_new_private(int type)
574 struct sshkey *k = sshkey_new(type);
578 if (sshkey_add_private(k) != 0) {
586 sshkey_free(struct sshkey *k)
605 # ifdef OPENSSL_HAS_ECC
608 if (k->ecdsa != NULL)
609 EC_KEY_free(k->ecdsa);
612 # endif /* OPENSSL_HAS_ECC */
613 #endif /* WITH_OPENSSL */
615 case KEY_ED25519_CERT:
617 explicit_bzero(k->ed25519_pk, ED25519_PK_SZ);
619 k->ed25519_pk = NULL;
622 explicit_bzero(k->ed25519_sk, ED25519_SK_SZ);
624 k->ed25519_sk = NULL;
632 if (sshkey_is_cert(k))
634 explicit_bzero(k, sizeof(*k));
639 cert_compare(struct sshkey_cert *a, struct sshkey_cert *b)
641 if (a == NULL && b == NULL)
643 if (a == NULL || b == NULL)
645 if (sshbuf_len(a->certblob) != sshbuf_len(b->certblob))
647 if (timingsafe_bcmp(sshbuf_ptr(a->certblob), sshbuf_ptr(b->certblob),
648 sshbuf_len(a->certblob)) != 0)
654 * Compare public portions of key only, allowing comparisons between
655 * certificates and plain keys too.
658 sshkey_equal_public(const struct sshkey *a, const struct sshkey *b)
660 #if defined(WITH_OPENSSL) && defined(OPENSSL_HAS_ECC)
662 #endif /* WITH_OPENSSL && OPENSSL_HAS_ECC */
664 if (a == NULL || b == NULL ||
665 sshkey_type_plain(a->type) != sshkey_type_plain(b->type))
673 return a->rsa != NULL && b->rsa != NULL &&
674 BN_cmp(a->rsa->e, b->rsa->e) == 0 &&
675 BN_cmp(a->rsa->n, b->rsa->n) == 0;
678 return a->dsa != NULL && b->dsa != NULL &&
679 BN_cmp(a->dsa->p, b->dsa->p) == 0 &&
680 BN_cmp(a->dsa->q, b->dsa->q) == 0 &&
681 BN_cmp(a->dsa->g, b->dsa->g) == 0 &&
682 BN_cmp(a->dsa->pub_key, b->dsa->pub_key) == 0;
683 # ifdef OPENSSL_HAS_ECC
686 if (a->ecdsa == NULL || b->ecdsa == NULL ||
687 EC_KEY_get0_public_key(a->ecdsa) == NULL ||
688 EC_KEY_get0_public_key(b->ecdsa) == NULL)
690 if ((bnctx = BN_CTX_new()) == NULL)
692 if (EC_GROUP_cmp(EC_KEY_get0_group(a->ecdsa),
693 EC_KEY_get0_group(b->ecdsa), bnctx) != 0 ||
694 EC_POINT_cmp(EC_KEY_get0_group(a->ecdsa),
695 EC_KEY_get0_public_key(a->ecdsa),
696 EC_KEY_get0_public_key(b->ecdsa), bnctx) != 0) {
702 # endif /* OPENSSL_HAS_ECC */
703 #endif /* WITH_OPENSSL */
705 case KEY_ED25519_CERT:
706 return a->ed25519_pk != NULL && b->ed25519_pk != NULL &&
707 memcmp(a->ed25519_pk, b->ed25519_pk, ED25519_PK_SZ) == 0;
715 sshkey_equal(const struct sshkey *a, const struct sshkey *b)
717 if (a == NULL || b == NULL || a->type != b->type)
719 if (sshkey_is_cert(a)) {
720 if (!cert_compare(a->cert, b->cert))
723 return sshkey_equal_public(a, b);
727 to_blob_buf(const struct sshkey *key, struct sshbuf *b, int force_plain)
729 int type, ret = SSH_ERR_INTERNAL_ERROR;
730 const char *typename;
733 return SSH_ERR_INVALID_ARGUMENT;
735 if (sshkey_is_cert(key)) {
736 if (key->cert == NULL)
737 return SSH_ERR_EXPECTED_CERT;
738 if (sshbuf_len(key->cert->certblob) == 0)
739 return SSH_ERR_KEY_LACKS_CERTBLOB;
741 type = force_plain ? sshkey_type_plain(key->type) : key->type;
742 typename = sshkey_ssh_name_from_type_nid(type, key->ecdsa_nid);
749 #endif /* WITH_OPENSSL */
750 case KEY_ED25519_CERT:
751 /* Use the existing blob */
752 /* XXX modified flag? */
753 if ((ret = sshbuf_putb(b, key->cert->certblob)) != 0)
758 if (key->dsa == NULL)
759 return SSH_ERR_INVALID_ARGUMENT;
760 if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
761 (ret = sshbuf_put_bignum2(b, key->dsa->p)) != 0 ||
762 (ret = sshbuf_put_bignum2(b, key->dsa->q)) != 0 ||
763 (ret = sshbuf_put_bignum2(b, key->dsa->g)) != 0 ||
764 (ret = sshbuf_put_bignum2(b, key->dsa->pub_key)) != 0)
767 # ifdef OPENSSL_HAS_ECC
769 if (key->ecdsa == NULL)
770 return SSH_ERR_INVALID_ARGUMENT;
771 if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
772 (ret = sshbuf_put_cstring(b,
773 sshkey_curve_nid_to_name(key->ecdsa_nid))) != 0 ||
774 (ret = sshbuf_put_eckey(b, key->ecdsa)) != 0)
779 if (key->rsa == NULL)
780 return SSH_ERR_INVALID_ARGUMENT;
781 if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
782 (ret = sshbuf_put_bignum2(b, key->rsa->e)) != 0 ||
783 (ret = sshbuf_put_bignum2(b, key->rsa->n)) != 0)
786 #endif /* WITH_OPENSSL */
788 if (key->ed25519_pk == NULL)
789 return SSH_ERR_INVALID_ARGUMENT;
790 if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
791 (ret = sshbuf_put_string(b,
792 key->ed25519_pk, ED25519_PK_SZ)) != 0)
796 return SSH_ERR_KEY_TYPE_UNKNOWN;
802 sshkey_putb(const struct sshkey *key, struct sshbuf *b)
804 return to_blob_buf(key, b, 0);
808 sshkey_puts(const struct sshkey *key, struct sshbuf *b)
813 if ((tmp = sshbuf_new()) == NULL)
814 return SSH_ERR_ALLOC_FAIL;
815 r = to_blob_buf(key, tmp, 0);
817 r = sshbuf_put_stringb(b, tmp);
823 sshkey_putb_plain(const struct sshkey *key, struct sshbuf *b)
825 return to_blob_buf(key, b, 1);
829 to_blob(const struct sshkey *key, u_char **blobp, size_t *lenp, int force_plain)
831 int ret = SSH_ERR_INTERNAL_ERROR;
833 struct sshbuf *b = NULL;
839 if ((b = sshbuf_new()) == NULL)
840 return SSH_ERR_ALLOC_FAIL;
841 if ((ret = to_blob_buf(key, b, force_plain)) != 0)
847 if ((*blobp = malloc(len)) == NULL) {
848 ret = SSH_ERR_ALLOC_FAIL;
851 memcpy(*blobp, sshbuf_ptr(b), len);
860 sshkey_to_blob(const struct sshkey *key, u_char **blobp, size_t *lenp)
862 return to_blob(key, blobp, lenp, 0);
866 sshkey_plain_to_blob(const struct sshkey *key, u_char **blobp, size_t *lenp)
868 return to_blob(key, blobp, lenp, 1);
872 sshkey_fingerprint_raw(const struct sshkey *k, int dgst_alg,
873 u_char **retp, size_t *lenp)
875 u_char *blob = NULL, *ret = NULL;
877 int r = SSH_ERR_INTERNAL_ERROR;
883 if (ssh_digest_bytes(dgst_alg) == 0) {
884 r = SSH_ERR_INVALID_ARGUMENT;
888 if (k->type == KEY_RSA1) {
890 int nlen = BN_num_bytes(k->rsa->n);
891 int elen = BN_num_bytes(k->rsa->e);
893 if (nlen < 0 || elen < 0 || nlen >= INT_MAX - elen) {
894 r = SSH_ERR_INVALID_FORMAT;
897 blob_len = nlen + elen;
898 if ((blob = malloc(blob_len)) == NULL) {
899 r = SSH_ERR_ALLOC_FAIL;
902 BN_bn2bin(k->rsa->n, blob);
903 BN_bn2bin(k->rsa->e, blob + nlen);
904 #endif /* WITH_OPENSSL */
905 } else if ((r = to_blob(k, &blob, &blob_len, 1)) != 0)
907 if ((ret = calloc(1, SSH_DIGEST_MAX_LENGTH)) == NULL) {
908 r = SSH_ERR_ALLOC_FAIL;
911 if ((r = ssh_digest_memory(dgst_alg, blob, blob_len,
912 ret, SSH_DIGEST_MAX_LENGTH)) != 0)
920 *lenp = ssh_digest_bytes(dgst_alg);
925 explicit_bzero(blob, blob_len);
932 fingerprint_b64(const char *alg, u_char *dgst_raw, size_t dgst_raw_len)
935 size_t plen = strlen(alg) + 1;
936 size_t rlen = ((dgst_raw_len + 2) / 3) * 4 + plen + 1;
939 if (dgst_raw_len > 65536 || (ret = calloc(1, rlen)) == NULL)
941 strlcpy(ret, alg, rlen);
942 strlcat(ret, ":", rlen);
943 if (dgst_raw_len == 0)
945 if ((r = b64_ntop(dgst_raw, dgst_raw_len,
946 ret + plen, rlen - plen)) == -1) {
947 explicit_bzero(ret, rlen);
951 /* Trim padding characters from end */
952 ret[strcspn(ret, "=")] = '\0';
957 fingerprint_hex(const char *alg, u_char *dgst_raw, size_t dgst_raw_len)
959 char *retval, hex[5];
960 size_t i, rlen = dgst_raw_len * 3 + strlen(alg) + 2;
962 if (dgst_raw_len > 65536 || (retval = calloc(1, rlen)) == NULL)
964 strlcpy(retval, alg, rlen);
965 strlcat(retval, ":", rlen);
966 for (i = 0; i < dgst_raw_len; i++) {
967 snprintf(hex, sizeof(hex), "%s%02x",
968 i > 0 ? ":" : "", dgst_raw[i]);
969 strlcat(retval, hex, rlen);
975 fingerprint_bubblebabble(u_char *dgst_raw, size_t dgst_raw_len)
977 char vowels[] = { 'a', 'e', 'i', 'o', 'u', 'y' };
978 char consonants[] = { 'b', 'c', 'd', 'f', 'g', 'h', 'k', 'l', 'm',
979 'n', 'p', 'r', 's', 't', 'v', 'z', 'x' };
980 u_int i, j = 0, rounds, seed = 1;
983 rounds = (dgst_raw_len / 2) + 1;
984 if ((retval = calloc(rounds, 6)) == NULL)
987 for (i = 0; i < rounds; i++) {
988 u_int idx0, idx1, idx2, idx3, idx4;
989 if ((i + 1 < rounds) || (dgst_raw_len % 2 != 0)) {
990 idx0 = (((((u_int)(dgst_raw[2 * i])) >> 6) & 3) +
992 idx1 = (((u_int)(dgst_raw[2 * i])) >> 2) & 15;
993 idx2 = ((((u_int)(dgst_raw[2 * i])) & 3) +
995 retval[j++] = vowels[idx0];
996 retval[j++] = consonants[idx1];
997 retval[j++] = vowels[idx2];
998 if ((i + 1) < rounds) {
999 idx3 = (((u_int)(dgst_raw[(2 * i) + 1])) >> 4) & 15;
1000 idx4 = (((u_int)(dgst_raw[(2 * i) + 1]))) & 15;
1001 retval[j++] = consonants[idx3];
1003 retval[j++] = consonants[idx4];
1004 seed = ((seed * 5) +
1005 ((((u_int)(dgst_raw[2 * i])) * 7) +
1006 ((u_int)(dgst_raw[(2 * i) + 1])))) % 36;
1012 retval[j++] = vowels[idx0];
1013 retval[j++] = consonants[idx1];
1014 retval[j++] = vowels[idx2];
1023 * Draw an ASCII-Art representing the fingerprint so human brain can
1024 * profit from its built-in pattern recognition ability.
1025 * This technique is called "random art" and can be found in some
1026 * scientific publications like this original paper:
1028 * "Hash Visualization: a New Technique to improve Real-World Security",
1029 * Perrig A. and Song D., 1999, International Workshop on Cryptographic
1030 * Techniques and E-Commerce (CrypTEC '99)
1031 * sparrow.ece.cmu.edu/~adrian/projects/validation/validation.pdf
1033 * The subject came up in a talk by Dan Kaminsky, too.
1035 * If you see the picture is different, the key is different.
1036 * If the picture looks the same, you still know nothing.
1038 * The algorithm used here is a worm crawling over a discrete plane,
1039 * leaving a trace (augmenting the field) everywhere it goes.
1040 * Movement is taken from dgst_raw 2bit-wise. Bumping into walls
1041 * makes the respective movement vector be ignored for this turn.
1042 * Graphs are not unambiguous, because circles in graphs can be
1043 * walked in either direction.
1047 * Field sizes for the random art. Have to be odd, so the starting point
1048 * can be in the exact middle of the picture, and FLDBASE should be >=8 .
1049 * Else pictures would be too dense, and drawing the frame would
1050 * fail, too, because the key type would not fit in anymore.
1053 #define FLDSIZE_Y (FLDBASE + 1)
1054 #define FLDSIZE_X (FLDBASE * 2 + 1)
1056 fingerprint_randomart(const char *alg, u_char *dgst_raw, size_t dgst_raw_len,
1057 const struct sshkey *k)
1060 * Chars to be used after each other every time the worm
1061 * intersects with itself. Matter of taste.
1063 char *augmentation_string = " .o+=*BOX@%&#/^SE";
1064 char *retval, *p, title[FLDSIZE_X], hash[FLDSIZE_X];
1065 u_char field[FLDSIZE_X][FLDSIZE_Y];
1066 size_t i, tlen, hlen;
1069 size_t len = strlen(augmentation_string) - 1;
1071 if ((retval = calloc((FLDSIZE_X + 3), (FLDSIZE_Y + 2))) == NULL)
1074 /* initialize field */
1075 memset(field, 0, FLDSIZE_X * FLDSIZE_Y * sizeof(char));
1079 /* process raw key */
1080 for (i = 0; i < dgst_raw_len; i++) {
1082 /* each byte conveys four 2-bit move commands */
1083 input = dgst_raw[i];
1084 for (b = 0; b < 4; b++) {
1085 /* evaluate 2 bit, rest is shifted later */
1086 x += (input & 0x1) ? 1 : -1;
1087 y += (input & 0x2) ? 1 : -1;
1089 /* assure we are still in bounds */
1092 x = MINIMUM(x, FLDSIZE_X - 1);
1093 y = MINIMUM(y, FLDSIZE_Y - 1);
1095 /* augment the field */
1096 if (field[x][y] < len - 2)
1102 /* mark starting point and end point*/
1103 field[FLDSIZE_X / 2][FLDSIZE_Y / 2] = len - 1;
1106 /* assemble title */
1107 r = snprintf(title, sizeof(title), "[%s %u]",
1108 sshkey_type(k), sshkey_size(k));
1109 /* If [type size] won't fit, then try [type]; fits "[ED25519-CERT]" */
1110 if (r < 0 || r > (int)sizeof(title))
1111 r = snprintf(title, sizeof(title), "[%s]", sshkey_type(k));
1112 tlen = (r <= 0) ? 0 : strlen(title);
1114 /* assemble hash ID. */
1115 r = snprintf(hash, sizeof(hash), "[%s]", alg);
1116 hlen = (r <= 0) ? 0 : strlen(hash);
1118 /* output upper border */
1121 for (i = 0; i < (FLDSIZE_X - tlen) / 2; i++)
1123 memcpy(p, title, tlen);
1125 for (i += tlen; i < FLDSIZE_X; i++)
1130 /* output content */
1131 for (y = 0; y < FLDSIZE_Y; y++) {
1133 for (x = 0; x < FLDSIZE_X; x++)
1134 *p++ = augmentation_string[MINIMUM(field[x][y], len)];
1139 /* output lower border */
1141 for (i = 0; i < (FLDSIZE_X - hlen) / 2; i++)
1143 memcpy(p, hash, hlen);
1145 for (i += hlen; i < FLDSIZE_X; i++)
1153 sshkey_fingerprint(const struct sshkey *k, int dgst_alg,
1154 enum sshkey_fp_rep dgst_rep)
1156 char *retval = NULL;
1158 size_t dgst_raw_len;
1160 if (sshkey_fingerprint_raw(k, dgst_alg, &dgst_raw, &dgst_raw_len) != 0)
1163 case SSH_FP_DEFAULT:
1164 if (dgst_alg == SSH_DIGEST_MD5) {
1165 retval = fingerprint_hex(ssh_digest_alg_name(dgst_alg),
1166 dgst_raw, dgst_raw_len);
1168 retval = fingerprint_b64(ssh_digest_alg_name(dgst_alg),
1169 dgst_raw, dgst_raw_len);
1173 retval = fingerprint_hex(ssh_digest_alg_name(dgst_alg),
1174 dgst_raw, dgst_raw_len);
1177 retval = fingerprint_b64(ssh_digest_alg_name(dgst_alg),
1178 dgst_raw, dgst_raw_len);
1180 case SSH_FP_BUBBLEBABBLE:
1181 retval = fingerprint_bubblebabble(dgst_raw, dgst_raw_len);
1183 case SSH_FP_RANDOMART:
1184 retval = fingerprint_randomart(ssh_digest_alg_name(dgst_alg),
1185 dgst_raw, dgst_raw_len, k);
1188 explicit_bzero(dgst_raw, dgst_raw_len);
1192 explicit_bzero(dgst_raw, dgst_raw_len);
1199 * Reads a multiple-precision integer in decimal from the buffer, and advances
1200 * the pointer. The integer must already be initialized. This function is
1201 * permitted to modify the buffer. This leaves *cpp to point just beyond the
1202 * last processed character.
1205 read_decimal_bignum(char **cpp, BIGNUM *v)
1209 int skip = 1; /* skip white space */
1212 while (*cp == ' ' || *cp == '\t')
1214 e = strspn(cp, "0123456789");
1216 return SSH_ERR_INVALID_FORMAT;
1217 if (e > SSHBUF_MAX_BIGNUM * 3)
1218 return SSH_ERR_BIGNUM_TOO_LARGE;
1221 else if (strchr(" \t\r\n", cp[e]) == NULL)
1222 return SSH_ERR_INVALID_FORMAT;
1224 if (BN_dec2bn(&v, cp) <= 0)
1225 return SSH_ERR_INVALID_FORMAT;
1226 *cpp = cp + e + skip;
1229 #endif /* WITH_SSH1 */
1231 /* returns 0 ok, and < 0 error */
1233 sshkey_read(struct sshkey *ret, char **cpp)
1236 int retval = SSH_ERR_INVALID_FORMAT;
1237 char *ep, *cp, *space;
1238 int r, type, curve_nid = -1;
1239 struct sshbuf *blob;
1242 #endif /* WITH_SSH1 */
1245 return SSH_ERR_INVALID_ARGUMENT;
1249 switch (ret->type) {
1252 /* Get number of bits. */
1253 bits = strtoul(cp, &ep, 10);
1254 if (*cp == '\0' || strchr(" \t\r\n", *ep) == NULL ||
1255 bits == 0 || bits > SSHBUF_MAX_BIGNUM * 8)
1256 return SSH_ERR_INVALID_FORMAT; /* Bad bit count... */
1257 /* Get public exponent, public modulus. */
1258 if ((r = read_decimal_bignum(&ep, ret->rsa->e)) < 0)
1260 if ((r = read_decimal_bignum(&ep, ret->rsa->n)) < 0)
1262 /* validate the claimed number of bits */
1263 if (BN_num_bits(ret->rsa->n) != (int)bits)
1264 return SSH_ERR_KEY_BITS_MISMATCH;
1267 #endif /* WITH_SSH1 */
1275 case KEY_ECDSA_CERT:
1277 case KEY_ED25519_CERT:
1278 space = strchr(cp, ' ');
1280 return SSH_ERR_INVALID_FORMAT;
1282 type = sshkey_type_from_name(cp);
1283 if (sshkey_type_plain(type) == KEY_ECDSA &&
1284 (curve_nid = sshkey_ecdsa_nid_from_name(cp)) == -1)
1285 return SSH_ERR_EC_CURVE_INVALID;
1287 if (type == KEY_UNSPEC)
1288 return SSH_ERR_INVALID_FORMAT;
1291 return SSH_ERR_INVALID_FORMAT;
1292 if (ret->type != KEY_UNSPEC && ret->type != type)
1293 return SSH_ERR_KEY_TYPE_MISMATCH;
1294 if ((blob = sshbuf_new()) == NULL)
1295 return SSH_ERR_ALLOC_FAIL;
1297 space = strchr(cp, ' ');
1299 /* advance 'space': skip whitespace */
1301 while (*space == ' ' || *space == '\t')
1305 ep = cp + strlen(cp);
1306 if ((r = sshbuf_b64tod(blob, cp)) != 0) {
1310 if ((r = sshkey_from_blob(sshbuf_ptr(blob),
1311 sshbuf_len(blob), &k)) != 0) {
1316 if (k->type != type) {
1318 return SSH_ERR_KEY_TYPE_MISMATCH;
1320 if (sshkey_type_plain(type) == KEY_ECDSA &&
1321 curve_nid != k->ecdsa_nid) {
1323 return SSH_ERR_EC_CURVE_MISMATCH;
1326 if (sshkey_is_cert(ret)) {
1327 if (!sshkey_is_cert(k)) {
1329 return SSH_ERR_EXPECTED_CERT;
1331 if (ret->cert != NULL)
1332 cert_free(ret->cert);
1333 ret->cert = k->cert;
1336 switch (sshkey_type_plain(ret->type)) {
1339 if (ret->rsa != NULL)
1344 RSA_print_fp(stderr, ret->rsa, 8);
1348 if (ret->dsa != NULL)
1353 DSA_print_fp(stderr, ret->dsa, 8);
1356 # ifdef OPENSSL_HAS_ECC
1358 if (ret->ecdsa != NULL)
1359 EC_KEY_free(ret->ecdsa);
1360 ret->ecdsa = k->ecdsa;
1361 ret->ecdsa_nid = k->ecdsa_nid;
1365 sshkey_dump_ec_key(ret->ecdsa);
1368 # endif /* OPENSSL_HAS_ECC */
1369 #endif /* WITH_OPENSSL */
1371 free(ret->ed25519_pk);
1372 ret->ed25519_pk = k->ed25519_pk;
1373 k->ed25519_pk = NULL;
1387 return SSH_ERR_INVALID_ARGUMENT;
1393 sshkey_to_base64(const struct sshkey *key, char **b64p)
1395 int r = SSH_ERR_INTERNAL_ERROR;
1396 struct sshbuf *b = NULL;
1401 if ((b = sshbuf_new()) == NULL)
1402 return SSH_ERR_ALLOC_FAIL;
1403 if ((r = sshkey_putb(key, b)) != 0)
1405 if ((uu = sshbuf_dtob64(b)) == NULL) {
1406 r = SSH_ERR_ALLOC_FAIL;
1422 sshkey_format_rsa1(const struct sshkey *key, struct sshbuf *b)
1424 int r = SSH_ERR_INTERNAL_ERROR;
1427 char *dec_e = NULL, *dec_n = NULL;
1429 if (key->rsa == NULL || key->rsa->e == NULL ||
1430 key->rsa->n == NULL) {
1431 r = SSH_ERR_INVALID_ARGUMENT;
1434 if ((dec_e = BN_bn2dec(key->rsa->e)) == NULL ||
1435 (dec_n = BN_bn2dec(key->rsa->n)) == NULL) {
1436 r = SSH_ERR_ALLOC_FAIL;
1439 /* size of modulus 'n' */
1440 if ((bits = BN_num_bits(key->rsa->n)) <= 0) {
1441 r = SSH_ERR_INVALID_ARGUMENT;
1444 if ((r = sshbuf_putf(b, "%u %s %s", bits, dec_e, dec_n)) != 0)
1451 OPENSSL_free(dec_e);
1453 OPENSSL_free(dec_n);
1454 #endif /* WITH_SSH1 */
1460 sshkey_format_text(const struct sshkey *key, struct sshbuf *b)
1462 int r = SSH_ERR_INTERNAL_ERROR;
1465 if (key->type == KEY_RSA1) {
1466 if ((r = sshkey_format_rsa1(key, b)) != 0)
1469 /* Unsupported key types handled in sshkey_to_base64() */
1470 if ((r = sshkey_to_base64(key, &uu)) != 0)
1472 if ((r = sshbuf_putf(b, "%s %s",
1473 sshkey_ssh_name(key), uu)) != 0)
1483 sshkey_write(const struct sshkey *key, FILE *f)
1485 struct sshbuf *b = NULL;
1486 int r = SSH_ERR_INTERNAL_ERROR;
1488 if ((b = sshbuf_new()) == NULL)
1489 return SSH_ERR_ALLOC_FAIL;
1490 if ((r = sshkey_format_text(key, b)) != 0)
1492 if (fwrite(sshbuf_ptr(b), sshbuf_len(b), 1, f) != 1) {
1495 r = SSH_ERR_SYSTEM_ERROR;
1506 sshkey_cert_type(const struct sshkey *k)
1508 switch (k->cert->type) {
1509 case SSH2_CERT_TYPE_USER:
1511 case SSH2_CERT_TYPE_HOST:
1520 rsa_generate_private_key(u_int bits, RSA **rsap)
1522 RSA *private = NULL;
1524 int ret = SSH_ERR_INTERNAL_ERROR;
1527 bits < SSH_RSA_MINIMUM_MODULUS_SIZE ||
1528 bits > SSHBUF_MAX_BIGNUM * 8)
1529 return SSH_ERR_INVALID_ARGUMENT;
1531 if ((private = RSA_new()) == NULL || (f4 = BN_new()) == NULL) {
1532 ret = SSH_ERR_ALLOC_FAIL;
1535 if (!BN_set_word(f4, RSA_F4) ||
1536 !RSA_generate_key_ex(private, bits, f4, NULL)) {
1537 ret = SSH_ERR_LIBCRYPTO_ERROR;
1544 if (private != NULL)
1552 dsa_generate_private_key(u_int bits, DSA **dsap)
1555 int ret = SSH_ERR_INTERNAL_ERROR;
1557 if (dsap == NULL || bits != 1024)
1558 return SSH_ERR_INVALID_ARGUMENT;
1559 if ((private = DSA_new()) == NULL) {
1560 ret = SSH_ERR_ALLOC_FAIL;
1564 if (!DSA_generate_parameters_ex(private, bits, NULL, 0, NULL,
1565 NULL, NULL) || !DSA_generate_key(private)) {
1566 ret = SSH_ERR_LIBCRYPTO_ERROR;
1573 if (private != NULL)
1578 # ifdef OPENSSL_HAS_ECC
1580 sshkey_ecdsa_key_to_nid(EC_KEY *k)
1584 NID_X9_62_prime256v1,
1586 # ifdef OPENSSL_HAS_NISTP521
1588 # endif /* OPENSSL_HAS_NISTP521 */
1594 const EC_GROUP *g = EC_KEY_get0_group(k);
1597 * The group may be stored in a ASN.1 encoded private key in one of two
1598 * ways: as a "named group", which is reconstituted by ASN.1 object ID
1599 * or explicit group parameters encoded into the key blob. Only the
1600 * "named group" case sets the group NID for us, but we can figure
1601 * it out for the other case by comparing against all the groups that
1604 if ((nid = EC_GROUP_get_curve_name(g)) > 0)
1606 if ((bnctx = BN_CTX_new()) == NULL)
1608 for (i = 0; nids[i] != -1; i++) {
1609 if ((eg = EC_GROUP_new_by_curve_name(nids[i])) == NULL) {
1613 if (EC_GROUP_cmp(g, eg, bnctx) == 0)
1618 if (nids[i] != -1) {
1619 /* Use the group with the NID attached */
1620 EC_GROUP_set_asn1_flag(eg, OPENSSL_EC_NAMED_CURVE);
1621 if (EC_KEY_set_group(k, eg) != 1) {
1630 ecdsa_generate_private_key(u_int bits, int *nid, EC_KEY **ecdsap)
1633 int ret = SSH_ERR_INTERNAL_ERROR;
1635 if (nid == NULL || ecdsap == NULL ||
1636 (*nid = sshkey_ecdsa_bits_to_nid(bits)) == -1)
1637 return SSH_ERR_INVALID_ARGUMENT;
1639 if ((private = EC_KEY_new_by_curve_name(*nid)) == NULL) {
1640 ret = SSH_ERR_ALLOC_FAIL;
1643 if (EC_KEY_generate_key(private) != 1) {
1644 ret = SSH_ERR_LIBCRYPTO_ERROR;
1647 EC_KEY_set_asn1_flag(private, OPENSSL_EC_NAMED_CURVE);
1652 if (private != NULL)
1653 EC_KEY_free(private);
1656 # endif /* OPENSSL_HAS_ECC */
1657 #endif /* WITH_OPENSSL */
1660 sshkey_generate(int type, u_int bits, struct sshkey **keyp)
1663 int ret = SSH_ERR_INTERNAL_ERROR;
1666 return SSH_ERR_INVALID_ARGUMENT;
1668 if ((k = sshkey_new(KEY_UNSPEC)) == NULL)
1669 return SSH_ERR_ALLOC_FAIL;
1672 if ((k->ed25519_pk = malloc(ED25519_PK_SZ)) == NULL ||
1673 (k->ed25519_sk = malloc(ED25519_SK_SZ)) == NULL) {
1674 ret = SSH_ERR_ALLOC_FAIL;
1677 crypto_sign_ed25519_keypair(k->ed25519_pk, k->ed25519_sk);
1682 ret = dsa_generate_private_key(bits, &k->dsa);
1684 # ifdef OPENSSL_HAS_ECC
1686 ret = ecdsa_generate_private_key(bits, &k->ecdsa_nid,
1689 # endif /* OPENSSL_HAS_ECC */
1692 ret = rsa_generate_private_key(bits, &k->rsa);
1694 #endif /* WITH_OPENSSL */
1696 ret = SSH_ERR_INVALID_ARGUMENT;
1707 sshkey_cert_copy(const struct sshkey *from_key, struct sshkey *to_key)
1710 const struct sshkey_cert *from;
1711 struct sshkey_cert *to;
1712 int ret = SSH_ERR_INTERNAL_ERROR;
1714 if (to_key->cert != NULL) {
1715 cert_free(to_key->cert);
1716 to_key->cert = NULL;
1719 if ((from = from_key->cert) == NULL)
1720 return SSH_ERR_INVALID_ARGUMENT;
1722 if ((to = to_key->cert = cert_new()) == NULL)
1723 return SSH_ERR_ALLOC_FAIL;
1725 if ((ret = sshbuf_putb(to->certblob, from->certblob)) != 0 ||
1726 (ret = sshbuf_putb(to->critical, from->critical)) != 0 ||
1727 (ret = sshbuf_putb(to->extensions, from->extensions)) != 0)
1730 to->serial = from->serial;
1731 to->type = from->type;
1732 if (from->key_id == NULL)
1734 else if ((to->key_id = strdup(from->key_id)) == NULL)
1735 return SSH_ERR_ALLOC_FAIL;
1736 to->valid_after = from->valid_after;
1737 to->valid_before = from->valid_before;
1738 if (from->signature_key == NULL)
1739 to->signature_key = NULL;
1740 else if ((ret = sshkey_from_private(from->signature_key,
1741 &to->signature_key)) != 0)
1744 if (from->nprincipals > SSHKEY_CERT_MAX_PRINCIPALS)
1745 return SSH_ERR_INVALID_ARGUMENT;
1746 if (from->nprincipals > 0) {
1747 if ((to->principals = calloc(from->nprincipals,
1748 sizeof(*to->principals))) == NULL)
1749 return SSH_ERR_ALLOC_FAIL;
1750 for (i = 0; i < from->nprincipals; i++) {
1751 to->principals[i] = strdup(from->principals[i]);
1752 if (to->principals[i] == NULL) {
1753 to->nprincipals = i;
1754 return SSH_ERR_ALLOC_FAIL;
1758 to->nprincipals = from->nprincipals;
1763 sshkey_from_private(const struct sshkey *k, struct sshkey **pkp)
1765 struct sshkey *n = NULL;
1766 int ret = SSH_ERR_INTERNAL_ERROR;
1773 if ((n = sshkey_new(k->type)) == NULL)
1774 return SSH_ERR_ALLOC_FAIL;
1775 if ((BN_copy(n->dsa->p, k->dsa->p) == NULL) ||
1776 (BN_copy(n->dsa->q, k->dsa->q) == NULL) ||
1777 (BN_copy(n->dsa->g, k->dsa->g) == NULL) ||
1778 (BN_copy(n->dsa->pub_key, k->dsa->pub_key) == NULL)) {
1780 return SSH_ERR_ALLOC_FAIL;
1783 # ifdef OPENSSL_HAS_ECC
1785 case KEY_ECDSA_CERT:
1786 if ((n = sshkey_new(k->type)) == NULL)
1787 return SSH_ERR_ALLOC_FAIL;
1788 n->ecdsa_nid = k->ecdsa_nid;
1789 n->ecdsa = EC_KEY_new_by_curve_name(k->ecdsa_nid);
1790 if (n->ecdsa == NULL) {
1792 return SSH_ERR_ALLOC_FAIL;
1794 if (EC_KEY_set_public_key(n->ecdsa,
1795 EC_KEY_get0_public_key(k->ecdsa)) != 1) {
1797 return SSH_ERR_LIBCRYPTO_ERROR;
1800 # endif /* OPENSSL_HAS_ECC */
1804 if ((n = sshkey_new(k->type)) == NULL)
1805 return SSH_ERR_ALLOC_FAIL;
1806 if ((BN_copy(n->rsa->n, k->rsa->n) == NULL) ||
1807 (BN_copy(n->rsa->e, k->rsa->e) == NULL)) {
1809 return SSH_ERR_ALLOC_FAIL;
1812 #endif /* WITH_OPENSSL */
1814 case KEY_ED25519_CERT:
1815 if ((n = sshkey_new(k->type)) == NULL)
1816 return SSH_ERR_ALLOC_FAIL;
1817 if (k->ed25519_pk != NULL) {
1818 if ((n->ed25519_pk = malloc(ED25519_PK_SZ)) == NULL) {
1820 return SSH_ERR_ALLOC_FAIL;
1822 memcpy(n->ed25519_pk, k->ed25519_pk, ED25519_PK_SZ);
1826 return SSH_ERR_KEY_TYPE_UNKNOWN;
1828 if (sshkey_is_cert(k)) {
1829 if ((ret = sshkey_cert_copy(k, n)) != 0) {
1839 cert_parse(struct sshbuf *b, struct sshkey *key, struct sshbuf *certbuf)
1841 struct sshbuf *principals = NULL, *crit = NULL;
1842 struct sshbuf *exts = NULL, *ca = NULL;
1844 size_t signed_len = 0, slen = 0, kidlen = 0;
1845 int ret = SSH_ERR_INTERNAL_ERROR;
1847 /* Copy the entire key blob for verification and later serialisation */
1848 if ((ret = sshbuf_putb(key->cert->certblob, certbuf)) != 0)
1851 /* Parse body of certificate up to signature */
1852 if ((ret = sshbuf_get_u64(b, &key->cert->serial)) != 0 ||
1853 (ret = sshbuf_get_u32(b, &key->cert->type)) != 0 ||
1854 (ret = sshbuf_get_cstring(b, &key->cert->key_id, &kidlen)) != 0 ||
1855 (ret = sshbuf_froms(b, &principals)) != 0 ||
1856 (ret = sshbuf_get_u64(b, &key->cert->valid_after)) != 0 ||
1857 (ret = sshbuf_get_u64(b, &key->cert->valid_before)) != 0 ||
1858 (ret = sshbuf_froms(b, &crit)) != 0 ||
1859 (ret = sshbuf_froms(b, &exts)) != 0 ||
1860 (ret = sshbuf_get_string_direct(b, NULL, NULL)) != 0 ||
1861 (ret = sshbuf_froms(b, &ca)) != 0) {
1862 /* XXX debug print error for ret */
1863 ret = SSH_ERR_INVALID_FORMAT;
1867 /* Signature is left in the buffer so we can calculate this length */
1868 signed_len = sshbuf_len(key->cert->certblob) - sshbuf_len(b);
1870 if ((ret = sshbuf_get_string(b, &sig, &slen)) != 0) {
1871 ret = SSH_ERR_INVALID_FORMAT;
1875 if (key->cert->type != SSH2_CERT_TYPE_USER &&
1876 key->cert->type != SSH2_CERT_TYPE_HOST) {
1877 ret = SSH_ERR_KEY_CERT_UNKNOWN_TYPE;
1881 /* Parse principals section */
1882 while (sshbuf_len(principals) > 0) {
1883 char *principal = NULL;
1884 char **oprincipals = NULL;
1886 if (key->cert->nprincipals >= SSHKEY_CERT_MAX_PRINCIPALS) {
1887 ret = SSH_ERR_INVALID_FORMAT;
1890 if ((ret = sshbuf_get_cstring(principals, &principal,
1892 ret = SSH_ERR_INVALID_FORMAT;
1895 oprincipals = key->cert->principals;
1896 key->cert->principals = reallocarray(key->cert->principals,
1897 key->cert->nprincipals + 1, sizeof(*key->cert->principals));
1898 if (key->cert->principals == NULL) {
1900 key->cert->principals = oprincipals;
1901 ret = SSH_ERR_ALLOC_FAIL;
1904 key->cert->principals[key->cert->nprincipals++] = principal;
1908 * Stash a copies of the critical options and extensions sections
1911 if ((ret = sshbuf_putb(key->cert->critical, crit)) != 0 ||
1913 (ret = sshbuf_putb(key->cert->extensions, exts)) != 0))
1917 * Validate critical options and extensions sections format.
1919 while (sshbuf_len(crit) != 0) {
1920 if ((ret = sshbuf_get_string_direct(crit, NULL, NULL)) != 0 ||
1921 (ret = sshbuf_get_string_direct(crit, NULL, NULL)) != 0) {
1922 sshbuf_reset(key->cert->critical);
1923 ret = SSH_ERR_INVALID_FORMAT;
1927 while (exts != NULL && sshbuf_len(exts) != 0) {
1928 if ((ret = sshbuf_get_string_direct(exts, NULL, NULL)) != 0 ||
1929 (ret = sshbuf_get_string_direct(exts, NULL, NULL)) != 0) {
1930 sshbuf_reset(key->cert->extensions);
1931 ret = SSH_ERR_INVALID_FORMAT;
1936 /* Parse CA key and check signature */
1937 if (sshkey_from_blob_internal(ca, &key->cert->signature_key, 0) != 0) {
1938 ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
1941 if (!sshkey_type_is_valid_ca(key->cert->signature_key->type)) {
1942 ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
1945 if ((ret = sshkey_verify(key->cert->signature_key, sig, slen,
1946 sshbuf_ptr(key->cert->certblob), signed_len, 0)) != 0)
1955 sshbuf_free(principals);
1961 sshkey_from_blob_internal(struct sshbuf *b, struct sshkey **keyp,
1964 int type, ret = SSH_ERR_INTERNAL_ERROR;
1965 char *ktype = NULL, *curve = NULL;
1966 struct sshkey *key = NULL;
1969 struct sshbuf *copy;
1970 #if defined(WITH_OPENSSL) && defined(OPENSSL_HAS_ECC)
1972 #endif /* WITH_OPENSSL && OPENSSL_HAS_ECC */
1974 #ifdef DEBUG_PK /* XXX */
1975 sshbuf_dump(b, stderr);
1979 if ((copy = sshbuf_fromb(b)) == NULL) {
1980 ret = SSH_ERR_ALLOC_FAIL;
1983 if (sshbuf_get_cstring(b, &ktype, NULL) != 0) {
1984 ret = SSH_ERR_INVALID_FORMAT;
1988 type = sshkey_type_from_name(ktype);
1989 if (!allow_cert && sshkey_type_is_cert(type)) {
1990 ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
1997 if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
1998 ret = SSH_ERR_INVALID_FORMAT;
2003 if ((key = sshkey_new(type)) == NULL) {
2004 ret = SSH_ERR_ALLOC_FAIL;
2007 if (sshbuf_get_bignum2(b, key->rsa->e) != 0 ||
2008 sshbuf_get_bignum2(b, key->rsa->n) != 0) {
2009 ret = SSH_ERR_INVALID_FORMAT;
2013 RSA_print_fp(stderr, key->rsa, 8);
2018 if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
2019 ret = SSH_ERR_INVALID_FORMAT;
2024 if ((key = sshkey_new(type)) == NULL) {
2025 ret = SSH_ERR_ALLOC_FAIL;
2028 if (sshbuf_get_bignum2(b, key->dsa->p) != 0 ||
2029 sshbuf_get_bignum2(b, key->dsa->q) != 0 ||
2030 sshbuf_get_bignum2(b, key->dsa->g) != 0 ||
2031 sshbuf_get_bignum2(b, key->dsa->pub_key) != 0) {
2032 ret = SSH_ERR_INVALID_FORMAT;
2036 DSA_print_fp(stderr, key->dsa, 8);
2039 case KEY_ECDSA_CERT:
2041 if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
2042 ret = SSH_ERR_INVALID_FORMAT;
2046 # ifdef OPENSSL_HAS_ECC
2048 if ((key = sshkey_new(type)) == NULL) {
2049 ret = SSH_ERR_ALLOC_FAIL;
2052 key->ecdsa_nid = sshkey_ecdsa_nid_from_name(ktype);
2053 if (sshbuf_get_cstring(b, &curve, NULL) != 0) {
2054 ret = SSH_ERR_INVALID_FORMAT;
2057 if (key->ecdsa_nid != sshkey_curve_name_to_nid(curve)) {
2058 ret = SSH_ERR_EC_CURVE_MISMATCH;
2061 if (key->ecdsa != NULL)
2062 EC_KEY_free(key->ecdsa);
2063 if ((key->ecdsa = EC_KEY_new_by_curve_name(key->ecdsa_nid))
2065 ret = SSH_ERR_EC_CURVE_INVALID;
2068 if ((q = EC_POINT_new(EC_KEY_get0_group(key->ecdsa))) == NULL) {
2069 ret = SSH_ERR_ALLOC_FAIL;
2072 if (sshbuf_get_ec(b, q, EC_KEY_get0_group(key->ecdsa)) != 0) {
2073 ret = SSH_ERR_INVALID_FORMAT;
2076 if (sshkey_ec_validate_public(EC_KEY_get0_group(key->ecdsa),
2078 ret = SSH_ERR_KEY_INVALID_EC_VALUE;
2081 if (EC_KEY_set_public_key(key->ecdsa, q) != 1) {
2082 /* XXX assume it is a allocation error */
2083 ret = SSH_ERR_ALLOC_FAIL;
2087 sshkey_dump_ec_point(EC_KEY_get0_group(key->ecdsa), q);
2090 # endif /* OPENSSL_HAS_ECC */
2091 #endif /* WITH_OPENSSL */
2092 case KEY_ED25519_CERT:
2094 if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
2095 ret = SSH_ERR_INVALID_FORMAT;
2100 if ((ret = sshbuf_get_string(b, &pk, &len)) != 0)
2102 if (len != ED25519_PK_SZ) {
2103 ret = SSH_ERR_INVALID_FORMAT;
2106 if ((key = sshkey_new(type)) == NULL) {
2107 ret = SSH_ERR_ALLOC_FAIL;
2110 key->ed25519_pk = pk;
2114 if ((key = sshkey_new(type)) == NULL) {
2115 ret = SSH_ERR_ALLOC_FAIL;
2120 ret = SSH_ERR_KEY_TYPE_UNKNOWN;
2124 /* Parse certificate potion */
2125 if (sshkey_is_cert(key) && (ret = cert_parse(b, key, copy)) != 0)
2128 if (key != NULL && sshbuf_len(b) != 0) {
2129 ret = SSH_ERR_INVALID_FORMAT;
2143 #if defined(WITH_OPENSSL) && defined(OPENSSL_HAS_ECC)
2146 #endif /* WITH_OPENSSL && OPENSSL_HAS_ECC */
2151 sshkey_from_blob(const u_char *blob, size_t blen, struct sshkey **keyp)
2156 if ((b = sshbuf_from(blob, blen)) == NULL)
2157 return SSH_ERR_ALLOC_FAIL;
2158 r = sshkey_from_blob_internal(b, keyp, 1);
2164 sshkey_fromb(struct sshbuf *b, struct sshkey **keyp)
2166 return sshkey_from_blob_internal(b, keyp, 1);
2170 sshkey_froms(struct sshbuf *buf, struct sshkey **keyp)
2175 if ((r = sshbuf_froms(buf, &b)) != 0)
2177 r = sshkey_from_blob_internal(b, keyp, 1);
2183 sshkey_sign(const struct sshkey *key,
2184 u_char **sigp, size_t *lenp,
2185 const u_char *data, size_t datalen, const char *alg, u_int compat)
2191 if (datalen > SSH_KEY_MAX_SIGN_DATA_SIZE)
2192 return SSH_ERR_INVALID_ARGUMENT;
2193 switch (key->type) {
2197 return ssh_dss_sign(key, sigp, lenp, data, datalen, compat);
2198 # ifdef OPENSSL_HAS_ECC
2199 case KEY_ECDSA_CERT:
2201 return ssh_ecdsa_sign(key, sigp, lenp, data, datalen, compat);
2202 # endif /* OPENSSL_HAS_ECC */
2205 return ssh_rsa_sign(key, sigp, lenp, data, datalen, alg);
2206 #endif /* WITH_OPENSSL */
2208 case KEY_ED25519_CERT:
2209 return ssh_ed25519_sign(key, sigp, lenp, data, datalen, compat);
2211 return SSH_ERR_KEY_TYPE_UNKNOWN;
2216 * ssh_key_verify returns 0 for a correct signature and < 0 on error.
2219 sshkey_verify(const struct sshkey *key,
2220 const u_char *sig, size_t siglen,
2221 const u_char *data, size_t dlen, u_int compat)
2223 if (siglen == 0 || dlen > SSH_KEY_MAX_SIGN_DATA_SIZE)
2224 return SSH_ERR_INVALID_ARGUMENT;
2225 switch (key->type) {
2229 return ssh_dss_verify(key, sig, siglen, data, dlen, compat);
2230 # ifdef OPENSSL_HAS_ECC
2231 case KEY_ECDSA_CERT:
2233 return ssh_ecdsa_verify(key, sig, siglen, data, dlen, compat);
2234 # endif /* OPENSSL_HAS_ECC */
2237 return ssh_rsa_verify(key, sig, siglen, data, dlen);
2238 #endif /* WITH_OPENSSL */
2240 case KEY_ED25519_CERT:
2241 return ssh_ed25519_verify(key, sig, siglen, data, dlen, compat);
2243 return SSH_ERR_KEY_TYPE_UNKNOWN;
2247 /* Converts a private to a public key */
2249 sshkey_demote(const struct sshkey *k, struct sshkey **dkp)
2252 int ret = SSH_ERR_INTERNAL_ERROR;
2255 if ((pk = calloc(1, sizeof(*pk))) == NULL)
2256 return SSH_ERR_ALLOC_FAIL;
2258 pk->flags = k->flags;
2259 pk->ecdsa_nid = k->ecdsa_nid;
2263 pk->ed25519_pk = NULL;
2264 pk->ed25519_sk = NULL;
2269 if ((ret = sshkey_cert_copy(k, pk)) != 0)
2274 if ((pk->rsa = RSA_new()) == NULL ||
2275 (pk->rsa->e = BN_dup(k->rsa->e)) == NULL ||
2276 (pk->rsa->n = BN_dup(k->rsa->n)) == NULL) {
2277 ret = SSH_ERR_ALLOC_FAIL;
2282 if ((ret = sshkey_cert_copy(k, pk)) != 0)
2286 if ((pk->dsa = DSA_new()) == NULL ||
2287 (pk->dsa->p = BN_dup(k->dsa->p)) == NULL ||
2288 (pk->dsa->q = BN_dup(k->dsa->q)) == NULL ||
2289 (pk->dsa->g = BN_dup(k->dsa->g)) == NULL ||
2290 (pk->dsa->pub_key = BN_dup(k->dsa->pub_key)) == NULL) {
2291 ret = SSH_ERR_ALLOC_FAIL;
2295 case KEY_ECDSA_CERT:
2296 if ((ret = sshkey_cert_copy(k, pk)) != 0)
2299 # ifdef OPENSSL_HAS_ECC
2301 pk->ecdsa = EC_KEY_new_by_curve_name(pk->ecdsa_nid);
2302 if (pk->ecdsa == NULL) {
2303 ret = SSH_ERR_ALLOC_FAIL;
2306 if (EC_KEY_set_public_key(pk->ecdsa,
2307 EC_KEY_get0_public_key(k->ecdsa)) != 1) {
2308 ret = SSH_ERR_LIBCRYPTO_ERROR;
2312 # endif /* OPENSSL_HAS_ECC */
2313 #endif /* WITH_OPENSSL */
2314 case KEY_ED25519_CERT:
2315 if ((ret = sshkey_cert_copy(k, pk)) != 0)
2319 if (k->ed25519_pk != NULL) {
2320 if ((pk->ed25519_pk = malloc(ED25519_PK_SZ)) == NULL) {
2321 ret = SSH_ERR_ALLOC_FAIL;
2324 memcpy(pk->ed25519_pk, k->ed25519_pk, ED25519_PK_SZ);
2328 ret = SSH_ERR_KEY_TYPE_UNKNOWN;
2337 /* Convert a plain key to their _CERT equivalent */
2339 sshkey_to_certified(struct sshkey *k)
2346 newtype = KEY_RSA_CERT;
2349 newtype = KEY_DSA_CERT;
2352 newtype = KEY_ECDSA_CERT;
2354 #endif /* WITH_OPENSSL */
2356 newtype = KEY_ED25519_CERT;
2359 return SSH_ERR_INVALID_ARGUMENT;
2361 if ((k->cert = cert_new()) == NULL)
2362 return SSH_ERR_ALLOC_FAIL;
2367 /* Convert a certificate to its raw key equivalent */
2369 sshkey_drop_cert(struct sshkey *k)
2371 if (!sshkey_type_is_cert(k->type))
2372 return SSH_ERR_KEY_TYPE_UNKNOWN;
2375 k->type = sshkey_type_plain(k->type);
2379 /* Sign a certified key, (re-)generating the signed certblob. */
2381 sshkey_certify(struct sshkey *k, struct sshkey *ca, const char *alg)
2383 struct sshbuf *principals = NULL;
2384 u_char *ca_blob = NULL, *sig_blob = NULL, nonce[32];
2385 size_t i, ca_len, sig_len;
2386 int ret = SSH_ERR_INTERNAL_ERROR;
2387 struct sshbuf *cert;
2389 if (k == NULL || k->cert == NULL ||
2390 k->cert->certblob == NULL || ca == NULL)
2391 return SSH_ERR_INVALID_ARGUMENT;
2392 if (!sshkey_is_cert(k))
2393 return SSH_ERR_KEY_TYPE_UNKNOWN;
2394 if (!sshkey_type_is_valid_ca(ca->type))
2395 return SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
2397 if ((ret = sshkey_to_blob(ca, &ca_blob, &ca_len)) != 0)
2398 return SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
2400 cert = k->cert->certblob; /* for readability */
2402 if ((ret = sshbuf_put_cstring(cert, sshkey_ssh_name(k))) != 0)
2405 /* -v01 certs put nonce first */
2406 arc4random_buf(&nonce, sizeof(nonce));
2407 if ((ret = sshbuf_put_string(cert, nonce, sizeof(nonce))) != 0)
2410 /* XXX this substantially duplicates to_blob(); refactor */
2414 if ((ret = sshbuf_put_bignum2(cert, k->dsa->p)) != 0 ||
2415 (ret = sshbuf_put_bignum2(cert, k->dsa->q)) != 0 ||
2416 (ret = sshbuf_put_bignum2(cert, k->dsa->g)) != 0 ||
2417 (ret = sshbuf_put_bignum2(cert, k->dsa->pub_key)) != 0)
2420 # ifdef OPENSSL_HAS_ECC
2421 case KEY_ECDSA_CERT:
2422 if ((ret = sshbuf_put_cstring(cert,
2423 sshkey_curve_nid_to_name(k->ecdsa_nid))) != 0 ||
2424 (ret = sshbuf_put_ec(cert,
2425 EC_KEY_get0_public_key(k->ecdsa),
2426 EC_KEY_get0_group(k->ecdsa))) != 0)
2429 # endif /* OPENSSL_HAS_ECC */
2431 if ((ret = sshbuf_put_bignum2(cert, k->rsa->e)) != 0 ||
2432 (ret = sshbuf_put_bignum2(cert, k->rsa->n)) != 0)
2435 #endif /* WITH_OPENSSL */
2436 case KEY_ED25519_CERT:
2437 if ((ret = sshbuf_put_string(cert,
2438 k->ed25519_pk, ED25519_PK_SZ)) != 0)
2442 ret = SSH_ERR_INVALID_ARGUMENT;
2446 if ((ret = sshbuf_put_u64(cert, k->cert->serial)) != 0 ||
2447 (ret = sshbuf_put_u32(cert, k->cert->type)) != 0 ||
2448 (ret = sshbuf_put_cstring(cert, k->cert->key_id)) != 0)
2451 if ((principals = sshbuf_new()) == NULL) {
2452 ret = SSH_ERR_ALLOC_FAIL;
2455 for (i = 0; i < k->cert->nprincipals; i++) {
2456 if ((ret = sshbuf_put_cstring(principals,
2457 k->cert->principals[i])) != 0)
2460 if ((ret = sshbuf_put_stringb(cert, principals)) != 0 ||
2461 (ret = sshbuf_put_u64(cert, k->cert->valid_after)) != 0 ||
2462 (ret = sshbuf_put_u64(cert, k->cert->valid_before)) != 0 ||
2463 (ret = sshbuf_put_stringb(cert, k->cert->critical)) != 0 ||
2464 (ret = sshbuf_put_stringb(cert, k->cert->extensions)) != 0 ||
2465 (ret = sshbuf_put_string(cert, NULL, 0)) != 0 || /* Reserved */
2466 (ret = sshbuf_put_string(cert, ca_blob, ca_len)) != 0)
2469 /* Sign the whole mess */
2470 if ((ret = sshkey_sign(ca, &sig_blob, &sig_len, sshbuf_ptr(cert),
2471 sshbuf_len(cert), alg, 0)) != 0)
2474 /* Append signature and we are done */
2475 if ((ret = sshbuf_put_string(cert, sig_blob, sig_len)) != 0)
2483 sshbuf_free(principals);
2488 sshkey_cert_check_authority(const struct sshkey *k,
2489 int want_host, int require_principal,
2490 const char *name, const char **reason)
2492 u_int i, principal_matches;
2493 time_t now = time(NULL);
2499 if (k->cert->type != SSH2_CERT_TYPE_HOST) {
2500 *reason = "Certificate invalid: not a host certificate";
2501 return SSH_ERR_KEY_CERT_INVALID;
2504 if (k->cert->type != SSH2_CERT_TYPE_USER) {
2505 *reason = "Certificate invalid: not a user certificate";
2506 return SSH_ERR_KEY_CERT_INVALID;
2510 /* yikes - system clock before epoch! */
2511 *reason = "Certificate invalid: not yet valid";
2512 return SSH_ERR_KEY_CERT_INVALID;
2514 if ((u_int64_t)now < k->cert->valid_after) {
2515 *reason = "Certificate invalid: not yet valid";
2516 return SSH_ERR_KEY_CERT_INVALID;
2518 if ((u_int64_t)now >= k->cert->valid_before) {
2519 *reason = "Certificate invalid: expired";
2520 return SSH_ERR_KEY_CERT_INVALID;
2522 if (k->cert->nprincipals == 0) {
2523 if (require_principal) {
2524 *reason = "Certificate lacks principal list";
2525 return SSH_ERR_KEY_CERT_INVALID;
2527 } else if (name != NULL) {
2528 principal_matches = 0;
2529 for (i = 0; i < k->cert->nprincipals; i++) {
2530 if (strcmp(name, k->cert->principals[i]) == 0) {
2531 principal_matches = 1;
2535 if (!principal_matches) {
2536 *reason = "Certificate invalid: name is not a listed "
2538 return SSH_ERR_KEY_CERT_INVALID;
2545 sshkey_format_cert_validity(const struct sshkey_cert *cert, char *s, size_t l)
2547 char from[32], to[32], ret[64];
2552 if (cert->valid_after == 0 &&
2553 cert->valid_before == 0xffffffffffffffffULL)
2554 return strlcpy(s, "forever", l);
2556 if (cert->valid_after != 0) {
2557 /* XXX revisit INT_MAX in 2038 :) */
2558 tt = cert->valid_after > INT_MAX ?
2559 INT_MAX : cert->valid_after;
2560 tm = localtime(&tt);
2561 strftime(from, sizeof(from), "%Y-%m-%dT%H:%M:%S", tm);
2563 if (cert->valid_before != 0xffffffffffffffffULL) {
2564 /* XXX revisit INT_MAX in 2038 :) */
2565 tt = cert->valid_before > INT_MAX ?
2566 INT_MAX : cert->valid_before;
2567 tm = localtime(&tt);
2568 strftime(to, sizeof(to), "%Y-%m-%dT%H:%M:%S", tm);
2571 if (cert->valid_after == 0)
2572 snprintf(ret, sizeof(ret), "before %s", to);
2573 else if (cert->valid_before == 0xffffffffffffffffULL)
2574 snprintf(ret, sizeof(ret), "after %s", from);
2576 snprintf(ret, sizeof(ret), "from %s to %s", from, to);
2578 return strlcpy(s, ret, l);
2582 sshkey_private_serialize(const struct sshkey *key, struct sshbuf *b)
2584 int r = SSH_ERR_INTERNAL_ERROR;
2586 if ((r = sshbuf_put_cstring(b, sshkey_ssh_name(key))) != 0)
2588 switch (key->type) {
2591 if ((r = sshbuf_put_bignum2(b, key->rsa->n)) != 0 ||
2592 (r = sshbuf_put_bignum2(b, key->rsa->e)) != 0 ||
2593 (r = sshbuf_put_bignum2(b, key->rsa->d)) != 0 ||
2594 (r = sshbuf_put_bignum2(b, key->rsa->iqmp)) != 0 ||
2595 (r = sshbuf_put_bignum2(b, key->rsa->p)) != 0 ||
2596 (r = sshbuf_put_bignum2(b, key->rsa->q)) != 0)
2600 if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
2601 r = SSH_ERR_INVALID_ARGUMENT;
2604 if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
2605 (r = sshbuf_put_bignum2(b, key->rsa->d)) != 0 ||
2606 (r = sshbuf_put_bignum2(b, key->rsa->iqmp)) != 0 ||
2607 (r = sshbuf_put_bignum2(b, key->rsa->p)) != 0 ||
2608 (r = sshbuf_put_bignum2(b, key->rsa->q)) != 0)
2612 if ((r = sshbuf_put_bignum2(b, key->dsa->p)) != 0 ||
2613 (r = sshbuf_put_bignum2(b, key->dsa->q)) != 0 ||
2614 (r = sshbuf_put_bignum2(b, key->dsa->g)) != 0 ||
2615 (r = sshbuf_put_bignum2(b, key->dsa->pub_key)) != 0 ||
2616 (r = sshbuf_put_bignum2(b, key->dsa->priv_key)) != 0)
2620 if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
2621 r = SSH_ERR_INVALID_ARGUMENT;
2624 if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
2625 (r = sshbuf_put_bignum2(b, key->dsa->priv_key)) != 0)
2628 # ifdef OPENSSL_HAS_ECC
2630 if ((r = sshbuf_put_cstring(b,
2631 sshkey_curve_nid_to_name(key->ecdsa_nid))) != 0 ||
2632 (r = sshbuf_put_eckey(b, key->ecdsa)) != 0 ||
2633 (r = sshbuf_put_bignum2(b,
2634 EC_KEY_get0_private_key(key->ecdsa))) != 0)
2637 case KEY_ECDSA_CERT:
2638 if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
2639 r = SSH_ERR_INVALID_ARGUMENT;
2642 if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
2643 (r = sshbuf_put_bignum2(b,
2644 EC_KEY_get0_private_key(key->ecdsa))) != 0)
2647 # endif /* OPENSSL_HAS_ECC */
2648 #endif /* WITH_OPENSSL */
2650 if ((r = sshbuf_put_string(b, key->ed25519_pk,
2651 ED25519_PK_SZ)) != 0 ||
2652 (r = sshbuf_put_string(b, key->ed25519_sk,
2653 ED25519_SK_SZ)) != 0)
2656 case KEY_ED25519_CERT:
2657 if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
2658 r = SSH_ERR_INVALID_ARGUMENT;
2661 if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
2662 (r = sshbuf_put_string(b, key->ed25519_pk,
2663 ED25519_PK_SZ)) != 0 ||
2664 (r = sshbuf_put_string(b, key->ed25519_sk,
2665 ED25519_SK_SZ)) != 0)
2669 r = SSH_ERR_INVALID_ARGUMENT;
2679 sshkey_private_deserialize(struct sshbuf *buf, struct sshkey **kp)
2681 char *tname = NULL, *curve = NULL;
2682 struct sshkey *k = NULL;
2683 size_t pklen = 0, sklen = 0;
2684 int type, r = SSH_ERR_INTERNAL_ERROR;
2685 u_char *ed25519_pk = NULL, *ed25519_sk = NULL;
2687 BIGNUM *exponent = NULL;
2688 #endif /* WITH_OPENSSL */
2692 if ((r = sshbuf_get_cstring(buf, &tname, NULL)) != 0)
2694 type = sshkey_type_from_name(tname);
2698 if ((k = sshkey_new_private(type)) == NULL) {
2699 r = SSH_ERR_ALLOC_FAIL;
2702 if ((r = sshbuf_get_bignum2(buf, k->dsa->p)) != 0 ||
2703 (r = sshbuf_get_bignum2(buf, k->dsa->q)) != 0 ||
2704 (r = sshbuf_get_bignum2(buf, k->dsa->g)) != 0 ||
2705 (r = sshbuf_get_bignum2(buf, k->dsa->pub_key)) != 0 ||
2706 (r = sshbuf_get_bignum2(buf, k->dsa->priv_key)) != 0)
2710 if ((r = sshkey_froms(buf, &k)) != 0 ||
2711 (r = sshkey_add_private(k)) != 0 ||
2712 (r = sshbuf_get_bignum2(buf, k->dsa->priv_key)) != 0)
2715 # ifdef OPENSSL_HAS_ECC
2717 if ((k = sshkey_new_private(type)) == NULL) {
2718 r = SSH_ERR_ALLOC_FAIL;
2721 if ((k->ecdsa_nid = sshkey_ecdsa_nid_from_name(tname)) == -1) {
2722 r = SSH_ERR_INVALID_ARGUMENT;
2725 if ((r = sshbuf_get_cstring(buf, &curve, NULL)) != 0)
2727 if (k->ecdsa_nid != sshkey_curve_name_to_nid(curve)) {
2728 r = SSH_ERR_EC_CURVE_MISMATCH;
2731 k->ecdsa = EC_KEY_new_by_curve_name(k->ecdsa_nid);
2732 if (k->ecdsa == NULL || (exponent = BN_new()) == NULL) {
2733 r = SSH_ERR_LIBCRYPTO_ERROR;
2736 if ((r = sshbuf_get_eckey(buf, k->ecdsa)) != 0 ||
2737 (r = sshbuf_get_bignum2(buf, exponent)))
2739 if (EC_KEY_set_private_key(k->ecdsa, exponent) != 1) {
2740 r = SSH_ERR_LIBCRYPTO_ERROR;
2743 if ((r = sshkey_ec_validate_public(EC_KEY_get0_group(k->ecdsa),
2744 EC_KEY_get0_public_key(k->ecdsa))) != 0 ||
2745 (r = sshkey_ec_validate_private(k->ecdsa)) != 0)
2748 case KEY_ECDSA_CERT:
2749 if ((exponent = BN_new()) == NULL) {
2750 r = SSH_ERR_LIBCRYPTO_ERROR;
2753 if ((r = sshkey_froms(buf, &k)) != 0 ||
2754 (r = sshkey_add_private(k)) != 0 ||
2755 (r = sshbuf_get_bignum2(buf, exponent)) != 0)
2757 if (EC_KEY_set_private_key(k->ecdsa, exponent) != 1) {
2758 r = SSH_ERR_LIBCRYPTO_ERROR;
2761 if ((r = sshkey_ec_validate_public(EC_KEY_get0_group(k->ecdsa),
2762 EC_KEY_get0_public_key(k->ecdsa))) != 0 ||
2763 (r = sshkey_ec_validate_private(k->ecdsa)) != 0)
2766 # endif /* OPENSSL_HAS_ECC */
2768 if ((k = sshkey_new_private(type)) == NULL) {
2769 r = SSH_ERR_ALLOC_FAIL;
2772 if ((r = sshbuf_get_bignum2(buf, k->rsa->n)) != 0 ||
2773 (r = sshbuf_get_bignum2(buf, k->rsa->e)) != 0 ||
2774 (r = sshbuf_get_bignum2(buf, k->rsa->d)) != 0 ||
2775 (r = sshbuf_get_bignum2(buf, k->rsa->iqmp)) != 0 ||
2776 (r = sshbuf_get_bignum2(buf, k->rsa->p)) != 0 ||
2777 (r = sshbuf_get_bignum2(buf, k->rsa->q)) != 0 ||
2778 (r = rsa_generate_additional_parameters(k->rsa)) != 0)
2782 if ((r = sshkey_froms(buf, &k)) != 0 ||
2783 (r = sshkey_add_private(k)) != 0 ||
2784 (r = sshbuf_get_bignum2(buf, k->rsa->d)) != 0 ||
2785 (r = sshbuf_get_bignum2(buf, k->rsa->iqmp)) != 0 ||
2786 (r = sshbuf_get_bignum2(buf, k->rsa->p)) != 0 ||
2787 (r = sshbuf_get_bignum2(buf, k->rsa->q)) != 0 ||
2788 (r = rsa_generate_additional_parameters(k->rsa)) != 0)
2791 #endif /* WITH_OPENSSL */
2793 if ((k = sshkey_new_private(type)) == NULL) {
2794 r = SSH_ERR_ALLOC_FAIL;
2797 if ((r = sshbuf_get_string(buf, &ed25519_pk, &pklen)) != 0 ||
2798 (r = sshbuf_get_string(buf, &ed25519_sk, &sklen)) != 0)
2800 if (pklen != ED25519_PK_SZ || sklen != ED25519_SK_SZ) {
2801 r = SSH_ERR_INVALID_FORMAT;
2804 k->ed25519_pk = ed25519_pk;
2805 k->ed25519_sk = ed25519_sk;
2806 ed25519_pk = ed25519_sk = NULL;
2808 case KEY_ED25519_CERT:
2809 if ((r = sshkey_froms(buf, &k)) != 0 ||
2810 (r = sshkey_add_private(k)) != 0 ||
2811 (r = sshbuf_get_string(buf, &ed25519_pk, &pklen)) != 0 ||
2812 (r = sshbuf_get_string(buf, &ed25519_sk, &sklen)) != 0)
2814 if (pklen != ED25519_PK_SZ || sklen != ED25519_SK_SZ) {
2815 r = SSH_ERR_INVALID_FORMAT;
2818 k->ed25519_pk = ed25519_pk;
2819 k->ed25519_sk = ed25519_sk;
2820 ed25519_pk = ed25519_sk = NULL;
2823 r = SSH_ERR_KEY_TYPE_UNKNOWN;
2827 /* enable blinding */
2832 if (RSA_blinding_on(k->rsa, NULL) != 1) {
2833 r = SSH_ERR_LIBCRYPTO_ERROR;
2838 #endif /* WITH_OPENSSL */
2849 if (exponent != NULL)
2850 BN_clear_free(exponent);
2851 #endif /* WITH_OPENSSL */
2853 if (ed25519_pk != NULL) {
2854 explicit_bzero(ed25519_pk, pklen);
2857 if (ed25519_sk != NULL) {
2858 explicit_bzero(ed25519_sk, sklen);
2864 #if defined(WITH_OPENSSL) && defined(OPENSSL_HAS_ECC)
2866 sshkey_ec_validate_public(const EC_GROUP *group, const EC_POINT *public)
2869 EC_POINT *nq = NULL;
2870 BIGNUM *order, *x, *y, *tmp;
2871 int ret = SSH_ERR_KEY_INVALID_EC_VALUE;
2874 * NB. This assumes OpenSSL has already verified that the public
2875 * point lies on the curve. This is done by EC_POINT_oct2point()
2876 * implicitly calling EC_POINT_is_on_curve(). If this code is ever
2877 * reachable with public points not unmarshalled using
2878 * EC_POINT_oct2point then the caller will need to explicitly check.
2881 if ((bnctx = BN_CTX_new()) == NULL)
2882 return SSH_ERR_ALLOC_FAIL;
2883 BN_CTX_start(bnctx);
2886 * We shouldn't ever hit this case because bignum_get_ecpoint()
2887 * refuses to load GF2m points.
2889 if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) !=
2890 NID_X9_62_prime_field)
2894 if (EC_POINT_is_at_infinity(group, public))
2897 if ((x = BN_CTX_get(bnctx)) == NULL ||
2898 (y = BN_CTX_get(bnctx)) == NULL ||
2899 (order = BN_CTX_get(bnctx)) == NULL ||
2900 (tmp = BN_CTX_get(bnctx)) == NULL) {
2901 ret = SSH_ERR_ALLOC_FAIL;
2905 /* log2(x) > log2(order)/2, log2(y) > log2(order)/2 */
2906 if (EC_GROUP_get_order(group, order, bnctx) != 1 ||
2907 EC_POINT_get_affine_coordinates_GFp(group, public,
2908 x, y, bnctx) != 1) {
2909 ret = SSH_ERR_LIBCRYPTO_ERROR;
2912 if (BN_num_bits(x) <= BN_num_bits(order) / 2 ||
2913 BN_num_bits(y) <= BN_num_bits(order) / 2)
2916 /* nQ == infinity (n == order of subgroup) */
2917 if ((nq = EC_POINT_new(group)) == NULL) {
2918 ret = SSH_ERR_ALLOC_FAIL;
2921 if (EC_POINT_mul(group, nq, NULL, public, order, bnctx) != 1) {
2922 ret = SSH_ERR_LIBCRYPTO_ERROR;
2925 if (EC_POINT_is_at_infinity(group, nq) != 1)
2928 /* x < order - 1, y < order - 1 */
2929 if (!BN_sub(tmp, order, BN_value_one())) {
2930 ret = SSH_ERR_LIBCRYPTO_ERROR;
2933 if (BN_cmp(x, tmp) >= 0 || BN_cmp(y, tmp) >= 0)
2944 sshkey_ec_validate_private(const EC_KEY *key)
2947 BIGNUM *order, *tmp;
2948 int ret = SSH_ERR_KEY_INVALID_EC_VALUE;
2950 if ((bnctx = BN_CTX_new()) == NULL)
2951 return SSH_ERR_ALLOC_FAIL;
2952 BN_CTX_start(bnctx);
2954 if ((order = BN_CTX_get(bnctx)) == NULL ||
2955 (tmp = BN_CTX_get(bnctx)) == NULL) {
2956 ret = SSH_ERR_ALLOC_FAIL;
2960 /* log2(private) > log2(order)/2 */
2961 if (EC_GROUP_get_order(EC_KEY_get0_group(key), order, bnctx) != 1) {
2962 ret = SSH_ERR_LIBCRYPTO_ERROR;
2965 if (BN_num_bits(EC_KEY_get0_private_key(key)) <=
2966 BN_num_bits(order) / 2)
2969 /* private < order - 1 */
2970 if (!BN_sub(tmp, order, BN_value_one())) {
2971 ret = SSH_ERR_LIBCRYPTO_ERROR;
2974 if (BN_cmp(EC_KEY_get0_private_key(key), tmp) >= 0)
2983 sshkey_dump_ec_point(const EC_GROUP *group, const EC_POINT *point)
2988 if (point == NULL) {
2989 fputs("point=(NULL)\n", stderr);
2992 if ((bnctx = BN_CTX_new()) == NULL) {
2993 fprintf(stderr, "%s: BN_CTX_new failed\n", __func__);
2996 BN_CTX_start(bnctx);
2997 if ((x = BN_CTX_get(bnctx)) == NULL ||
2998 (y = BN_CTX_get(bnctx)) == NULL) {
2999 fprintf(stderr, "%s: BN_CTX_get failed\n", __func__);
3002 if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) !=
3003 NID_X9_62_prime_field) {
3004 fprintf(stderr, "%s: group is not a prime field\n", __func__);
3007 if (EC_POINT_get_affine_coordinates_GFp(group, point, x, y,
3009 fprintf(stderr, "%s: EC_POINT_get_affine_coordinates_GFp\n",
3013 fputs("x=", stderr);
3014 BN_print_fp(stderr, x);
3015 fputs("\ny=", stderr);
3016 BN_print_fp(stderr, y);
3017 fputs("\n", stderr);
3022 sshkey_dump_ec_key(const EC_KEY *key)
3024 const BIGNUM *exponent;
3026 sshkey_dump_ec_point(EC_KEY_get0_group(key),
3027 EC_KEY_get0_public_key(key));
3028 fputs("exponent=", stderr);
3029 if ((exponent = EC_KEY_get0_private_key(key)) == NULL)
3030 fputs("(NULL)", stderr);
3032 BN_print_fp(stderr, EC_KEY_get0_private_key(key));
3033 fputs("\n", stderr);
3035 #endif /* WITH_OPENSSL && OPENSSL_HAS_ECC */
3038 sshkey_private_to_blob2(const struct sshkey *prv, struct sshbuf *blob,
3039 const char *passphrase, const char *comment, const char *ciphername,
3042 u_char *cp, *key = NULL, *pubkeyblob = NULL;
3043 u_char salt[SALT_LEN];
3045 size_t i, pubkeylen, keylen, ivlen, blocksize, authlen;
3047 int r = SSH_ERR_INTERNAL_ERROR;
3048 struct sshcipher_ctx *ciphercontext = NULL;
3049 const struct sshcipher *cipher;
3050 const char *kdfname = KDFNAME;
3051 struct sshbuf *encoded = NULL, *encrypted = NULL, *kdf = NULL;
3054 rounds = DEFAULT_ROUNDS;
3055 if (passphrase == NULL || !strlen(passphrase)) {
3056 ciphername = "none";
3058 } else if (ciphername == NULL)
3059 ciphername = DEFAULT_CIPHERNAME;
3060 else if (cipher_number(ciphername) != SSH_CIPHER_SSH2) {
3061 r = SSH_ERR_INVALID_ARGUMENT;
3064 if ((cipher = cipher_by_name(ciphername)) == NULL) {
3065 r = SSH_ERR_INTERNAL_ERROR;
3069 if ((kdf = sshbuf_new()) == NULL ||
3070 (encoded = sshbuf_new()) == NULL ||
3071 (encrypted = sshbuf_new()) == NULL) {
3072 r = SSH_ERR_ALLOC_FAIL;
3075 blocksize = cipher_blocksize(cipher);
3076 keylen = cipher_keylen(cipher);
3077 ivlen = cipher_ivlen(cipher);
3078 authlen = cipher_authlen(cipher);
3079 if ((key = calloc(1, keylen + ivlen)) == NULL) {
3080 r = SSH_ERR_ALLOC_FAIL;
3083 if (strcmp(kdfname, "bcrypt") == 0) {
3084 arc4random_buf(salt, SALT_LEN);
3085 if (bcrypt_pbkdf(passphrase, strlen(passphrase),
3086 salt, SALT_LEN, key, keylen + ivlen, rounds) < 0) {
3087 r = SSH_ERR_INVALID_ARGUMENT;
3090 if ((r = sshbuf_put_string(kdf, salt, SALT_LEN)) != 0 ||
3091 (r = sshbuf_put_u32(kdf, rounds)) != 0)
3093 } else if (strcmp(kdfname, "none") != 0) {
3094 /* Unsupported KDF type */
3095 r = SSH_ERR_KEY_UNKNOWN_CIPHER;
3098 if ((r = cipher_init(&ciphercontext, cipher, key, keylen,
3099 key + keylen, ivlen, 1)) != 0)
3102 if ((r = sshbuf_put(encoded, AUTH_MAGIC, sizeof(AUTH_MAGIC))) != 0 ||
3103 (r = sshbuf_put_cstring(encoded, ciphername)) != 0 ||
3104 (r = sshbuf_put_cstring(encoded, kdfname)) != 0 ||
3105 (r = sshbuf_put_stringb(encoded, kdf)) != 0 ||
3106 (r = sshbuf_put_u32(encoded, 1)) != 0 || /* number of keys */
3107 (r = sshkey_to_blob(prv, &pubkeyblob, &pubkeylen)) != 0 ||
3108 (r = sshbuf_put_string(encoded, pubkeyblob, pubkeylen)) != 0)
3111 /* set up the buffer that will be encrypted */
3113 /* Random check bytes */
3114 check = arc4random();
3115 if ((r = sshbuf_put_u32(encrypted, check)) != 0 ||
3116 (r = sshbuf_put_u32(encrypted, check)) != 0)
3119 /* append private key and comment*/
3120 if ((r = sshkey_private_serialize(prv, encrypted)) != 0 ||
3121 (r = sshbuf_put_cstring(encrypted, comment)) != 0)
3126 while (sshbuf_len(encrypted) % blocksize) {
3127 if ((r = sshbuf_put_u8(encrypted, ++i & 0xff)) != 0)
3131 /* length in destination buffer */
3132 if ((r = sshbuf_put_u32(encoded, sshbuf_len(encrypted))) != 0)
3136 if ((r = sshbuf_reserve(encoded,
3137 sshbuf_len(encrypted) + authlen, &cp)) != 0)
3139 if ((r = cipher_crypt(ciphercontext, 0, cp,
3140 sshbuf_ptr(encrypted), sshbuf_len(encrypted), 0, authlen)) != 0)
3144 if ((b64 = sshbuf_dtob64(encoded)) == NULL) {
3145 r = SSH_ERR_ALLOC_FAIL;
3150 if ((r = sshbuf_put(blob, MARK_BEGIN, MARK_BEGIN_LEN)) != 0)
3152 for (i = 0; i < strlen(b64); i++) {
3153 if ((r = sshbuf_put_u8(blob, b64[i])) != 0)
3155 /* insert line breaks */
3156 if (i % 70 == 69 && (r = sshbuf_put_u8(blob, '\n')) != 0)
3159 if (i % 70 != 69 && (r = sshbuf_put_u8(blob, '\n')) != 0)
3161 if ((r = sshbuf_put(blob, MARK_END, MARK_END_LEN)) != 0)
3169 sshbuf_free(encoded);
3170 sshbuf_free(encrypted);
3171 cipher_free(ciphercontext);
3172 explicit_bzero(salt, sizeof(salt));
3174 explicit_bzero(key, keylen + ivlen);
3177 if (pubkeyblob != NULL) {
3178 explicit_bzero(pubkeyblob, pubkeylen);
3182 explicit_bzero(b64, strlen(b64));
3189 sshkey_parse_private2(struct sshbuf *blob, int type, const char *passphrase,
3190 struct sshkey **keyp, char **commentp)
3192 char *comment = NULL, *ciphername = NULL, *kdfname = NULL;
3193 const struct sshcipher *cipher = NULL;
3195 int r = SSH_ERR_INTERNAL_ERROR;
3197 size_t i, keylen = 0, ivlen = 0, authlen = 0, slen = 0;
3198 struct sshbuf *encoded = NULL, *decoded = NULL;
3199 struct sshbuf *kdf = NULL, *decrypted = NULL;
3200 struct sshcipher_ctx *ciphercontext = NULL;
3201 struct sshkey *k = NULL;
3202 u_char *key = NULL, *salt = NULL, *dp, pad, last;
3203 u_int blocksize, rounds, nkeys, encrypted_len, check1, check2;
3207 if (commentp != NULL)
3210 if ((encoded = sshbuf_new()) == NULL ||
3211 (decoded = sshbuf_new()) == NULL ||
3212 (decrypted = sshbuf_new()) == NULL) {
3213 r = SSH_ERR_ALLOC_FAIL;
3217 /* check preamble */
3218 cp = sshbuf_ptr(blob);
3219 encoded_len = sshbuf_len(blob);
3220 if (encoded_len < (MARK_BEGIN_LEN + MARK_END_LEN) ||
3221 memcmp(cp, MARK_BEGIN, MARK_BEGIN_LEN) != 0) {
3222 r = SSH_ERR_INVALID_FORMAT;
3225 cp += MARK_BEGIN_LEN;
3226 encoded_len -= MARK_BEGIN_LEN;
3228 /* Look for end marker, removing whitespace as we go */
3229 while (encoded_len > 0) {
3230 if (*cp != '\n' && *cp != '\r') {
3231 if ((r = sshbuf_put_u8(encoded, *cp)) != 0)
3238 if (encoded_len >= MARK_END_LEN &&
3239 memcmp(cp, MARK_END, MARK_END_LEN) == 0) {
3241 if ((r = sshbuf_put_u8(encoded, 0)) != 0)
3247 if (encoded_len == 0) {
3248 r = SSH_ERR_INVALID_FORMAT;
3253 if ((r = sshbuf_b64tod(decoded, (char *)sshbuf_ptr(encoded))) != 0)
3257 if (sshbuf_len(decoded) < sizeof(AUTH_MAGIC) ||
3258 memcmp(sshbuf_ptr(decoded), AUTH_MAGIC, sizeof(AUTH_MAGIC))) {
3259 r = SSH_ERR_INVALID_FORMAT;
3262 /* parse public portion of key */
3263 if ((r = sshbuf_consume(decoded, sizeof(AUTH_MAGIC))) != 0 ||
3264 (r = sshbuf_get_cstring(decoded, &ciphername, NULL)) != 0 ||
3265 (r = sshbuf_get_cstring(decoded, &kdfname, NULL)) != 0 ||
3266 (r = sshbuf_froms(decoded, &kdf)) != 0 ||
3267 (r = sshbuf_get_u32(decoded, &nkeys)) != 0 ||
3268 (r = sshbuf_skip_string(decoded)) != 0 || /* pubkey */
3269 (r = sshbuf_get_u32(decoded, &encrypted_len)) != 0)
3272 if ((cipher = cipher_by_name(ciphername)) == NULL) {
3273 r = SSH_ERR_KEY_UNKNOWN_CIPHER;
3276 if ((passphrase == NULL || strlen(passphrase) == 0) &&
3277 strcmp(ciphername, "none") != 0) {
3278 /* passphrase required */
3279 r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3282 if (strcmp(kdfname, "none") != 0 && strcmp(kdfname, "bcrypt") != 0) {
3283 r = SSH_ERR_KEY_UNKNOWN_CIPHER;
3286 if (!strcmp(kdfname, "none") && strcmp(ciphername, "none") != 0) {
3287 r = SSH_ERR_INVALID_FORMAT;
3291 /* XXX only one key supported */
3292 r = SSH_ERR_INVALID_FORMAT;
3296 /* check size of encrypted key blob */
3297 blocksize = cipher_blocksize(cipher);
3298 if (encrypted_len < blocksize || (encrypted_len % blocksize) != 0) {
3299 r = SSH_ERR_INVALID_FORMAT;
3304 keylen = cipher_keylen(cipher);
3305 ivlen = cipher_ivlen(cipher);
3306 authlen = cipher_authlen(cipher);
3307 if ((key = calloc(1, keylen + ivlen)) == NULL) {
3308 r = SSH_ERR_ALLOC_FAIL;
3311 if (strcmp(kdfname, "bcrypt") == 0) {
3312 if ((r = sshbuf_get_string(kdf, &salt, &slen)) != 0 ||
3313 (r = sshbuf_get_u32(kdf, &rounds)) != 0)
3315 if (bcrypt_pbkdf(passphrase, strlen(passphrase), salt, slen,
3316 key, keylen + ivlen, rounds) < 0) {
3317 r = SSH_ERR_INVALID_FORMAT;
3322 /* check that an appropriate amount of auth data is present */
3323 if (sshbuf_len(decoded) < encrypted_len + authlen) {
3324 r = SSH_ERR_INVALID_FORMAT;
3328 /* decrypt private portion of key */
3329 if ((r = sshbuf_reserve(decrypted, encrypted_len, &dp)) != 0 ||
3330 (r = cipher_init(&ciphercontext, cipher, key, keylen,
3331 key + keylen, ivlen, 0)) != 0)
3333 if ((r = cipher_crypt(ciphercontext, 0, dp, sshbuf_ptr(decoded),
3334 encrypted_len, 0, authlen)) != 0) {
3335 /* an integrity error here indicates an incorrect passphrase */
3336 if (r == SSH_ERR_MAC_INVALID)
3337 r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3340 if ((r = sshbuf_consume(decoded, encrypted_len + authlen)) != 0)
3342 /* there should be no trailing data */
3343 if (sshbuf_len(decoded) != 0) {
3344 r = SSH_ERR_INVALID_FORMAT;
3348 /* check check bytes */
3349 if ((r = sshbuf_get_u32(decrypted, &check1)) != 0 ||
3350 (r = sshbuf_get_u32(decrypted, &check2)) != 0)
3352 if (check1 != check2) {
3353 r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3357 /* Load the private key and comment */
3358 if ((r = sshkey_private_deserialize(decrypted, &k)) != 0 ||
3359 (r = sshbuf_get_cstring(decrypted, &comment, NULL)) != 0)
3362 /* Check deterministic padding */
3364 while (sshbuf_len(decrypted)) {
3365 if ((r = sshbuf_get_u8(decrypted, &pad)) != 0)
3367 if (pad != (++i & 0xff)) {
3368 r = SSH_ERR_INVALID_FORMAT;
3373 /* XXX decode pubkey and check against private */
3381 if (commentp != NULL) {
3382 *commentp = comment;
3387 cipher_free(ciphercontext);
3392 explicit_bzero(salt, slen);
3396 explicit_bzero(key, keylen + ivlen);
3399 sshbuf_free(encoded);
3400 sshbuf_free(decoded);
3402 sshbuf_free(decrypted);
3409 * Serialises the authentication (private) key to a blob, encrypting it with
3410 * passphrase. The identification of the blob (lowest 64 bits of n) will
3411 * precede the key to provide identification of the key without needing a
3415 sshkey_private_rsa1_to_blob(struct sshkey *key, struct sshbuf *blob,
3416 const char *passphrase, const char *comment)
3418 struct sshbuf *buffer = NULL, *encrypted = NULL;
3421 struct sshcipher_ctx *ciphercontext = NULL;
3422 const struct sshcipher *cipher;
3426 * If the passphrase is empty, use SSH_CIPHER_NONE to ease converting
3427 * to another cipher; otherwise use SSH_AUTHFILE_CIPHER.
3429 cipher_num = (strcmp(passphrase, "") == 0) ?
3430 SSH_CIPHER_NONE : SSH_CIPHER_3DES;
3431 if ((cipher = cipher_by_number(cipher_num)) == NULL)
3432 return SSH_ERR_INTERNAL_ERROR;
3434 /* This buffer is used to build the secret part of the private key. */
3435 if ((buffer = sshbuf_new()) == NULL)
3436 return SSH_ERR_ALLOC_FAIL;
3438 /* Put checkbytes for checking passphrase validity. */
3439 if ((r = sshbuf_reserve(buffer, 4, &cp)) != 0)
3441 arc4random_buf(cp, 2);
3442 memcpy(cp + 2, cp, 2);
3445 * Store the private key (n and e will not be stored because they
3446 * will be stored in plain text, and storing them also in encrypted
3447 * format would just give known plaintext).
3448 * Note: q and p are stored in reverse order to SSL.
3450 if ((r = sshbuf_put_bignum1(buffer, key->rsa->d)) != 0 ||
3451 (r = sshbuf_put_bignum1(buffer, key->rsa->iqmp)) != 0 ||
3452 (r = sshbuf_put_bignum1(buffer, key->rsa->q)) != 0 ||
3453 (r = sshbuf_put_bignum1(buffer, key->rsa->p)) != 0)
3456 /* Pad the part to be encrypted to a size that is a multiple of 8. */
3457 explicit_bzero(buf, 8);
3458 if ((r = sshbuf_put(buffer, buf, 8 - (sshbuf_len(buffer) % 8))) != 0)
3461 /* This buffer will be used to contain the data in the file. */
3462 if ((encrypted = sshbuf_new()) == NULL) {
3463 r = SSH_ERR_ALLOC_FAIL;
3467 /* First store keyfile id string. */
3468 if ((r = sshbuf_put(encrypted, LEGACY_BEGIN,
3469 sizeof(LEGACY_BEGIN))) != 0)
3472 /* Store cipher type and "reserved" field. */
3473 if ((r = sshbuf_put_u8(encrypted, cipher_num)) != 0 ||
3474 (r = sshbuf_put_u32(encrypted, 0)) != 0)
3477 /* Store public key. This will be in plain text. */
3478 if ((r = sshbuf_put_u32(encrypted, BN_num_bits(key->rsa->n))) != 0 ||
3479 (r = sshbuf_put_bignum1(encrypted, key->rsa->n)) != 0 ||
3480 (r = sshbuf_put_bignum1(encrypted, key->rsa->e)) != 0 ||
3481 (r = sshbuf_put_cstring(encrypted, comment)) != 0)
3484 /* Allocate space for the private part of the key in the buffer. */
3485 if ((r = sshbuf_reserve(encrypted, sshbuf_len(buffer), &cp)) != 0)
3488 if ((r = cipher_set_key_string(&ciphercontext, cipher, passphrase,
3489 CIPHER_ENCRYPT)) != 0)
3491 if ((r = cipher_crypt(ciphercontext, 0, cp,
3492 sshbuf_ptr(buffer), sshbuf_len(buffer), 0, 0)) != 0)
3495 r = sshbuf_putb(blob, encrypted);
3498 cipher_free(ciphercontext);
3499 explicit_bzero(buf, sizeof(buf));
3500 sshbuf_free(buffer);
3501 sshbuf_free(encrypted);
3505 #endif /* WITH_SSH1 */
3508 /* convert SSH v2 key in OpenSSL PEM format */
3510 sshkey_private_pem_to_blob(struct sshkey *key, struct sshbuf *blob,
3511 const char *_passphrase, const char *comment)
3514 int blen, len = strlen(_passphrase);
3515 u_char *passphrase = (len > 0) ? (u_char *)_passphrase : NULL;
3516 #if (OPENSSL_VERSION_NUMBER < 0x00907000L)
3517 const EVP_CIPHER *cipher = (len > 0) ? EVP_des_ede3_cbc() : NULL;
3519 const EVP_CIPHER *cipher = (len > 0) ? EVP_aes_128_cbc() : NULL;
3524 if (len > 0 && len <= 4)
3525 return SSH_ERR_PASSPHRASE_TOO_SHORT;
3526 if ((bio = BIO_new(BIO_s_mem())) == NULL)
3527 return SSH_ERR_ALLOC_FAIL;
3529 switch (key->type) {
3531 success = PEM_write_bio_DSAPrivateKey(bio, key->dsa,
3532 cipher, passphrase, len, NULL, NULL);
3534 #ifdef OPENSSL_HAS_ECC
3536 success = PEM_write_bio_ECPrivateKey(bio, key->ecdsa,
3537 cipher, passphrase, len, NULL, NULL);
3541 success = PEM_write_bio_RSAPrivateKey(bio, key->rsa,
3542 cipher, passphrase, len, NULL, NULL);
3549 r = SSH_ERR_LIBCRYPTO_ERROR;
3552 if ((blen = BIO_get_mem_data(bio, &bptr)) <= 0) {
3553 r = SSH_ERR_INTERNAL_ERROR;
3556 if ((r = sshbuf_put(blob, bptr, blen)) != 0)
3563 #endif /* WITH_OPENSSL */
3565 /* Serialise "key" to buffer "blob" */
3567 sshkey_private_to_fileblob(struct sshkey *key, struct sshbuf *blob,
3568 const char *passphrase, const char *comment,
3569 int force_new_format, const char *new_format_cipher, int new_format_rounds)
3571 switch (key->type) {
3574 return sshkey_private_rsa1_to_blob(key, blob,
3575 passphrase, comment);
3576 #endif /* WITH_SSH1 */
3581 if (force_new_format) {
3582 return sshkey_private_to_blob2(key, blob, passphrase,
3583 comment, new_format_cipher, new_format_rounds);
3585 return sshkey_private_pem_to_blob(key, blob,
3586 passphrase, comment);
3587 #endif /* WITH_OPENSSL */
3589 return sshkey_private_to_blob2(key, blob, passphrase,
3590 comment, new_format_cipher, new_format_rounds);
3592 return SSH_ERR_KEY_TYPE_UNKNOWN;
3598 * Parse the public, unencrypted portion of a RSA1 key.
3601 sshkey_parse_public_rsa1_fileblob(struct sshbuf *blob,
3602 struct sshkey **keyp, char **commentp)
3605 struct sshkey *pub = NULL;
3606 struct sshbuf *copy = NULL;
3610 if (commentp != NULL)
3613 /* Check that it is at least big enough to contain the ID string. */
3614 if (sshbuf_len(blob) < sizeof(LEGACY_BEGIN))
3615 return SSH_ERR_INVALID_FORMAT;
3618 * Make sure it begins with the id string. Consume the id string
3621 if (memcmp(sshbuf_ptr(blob), LEGACY_BEGIN, sizeof(LEGACY_BEGIN)) != 0)
3622 return SSH_ERR_INVALID_FORMAT;
3623 /* Make a working copy of the keyblob and skip past the magic */
3624 if ((copy = sshbuf_fromb(blob)) == NULL)
3625 return SSH_ERR_ALLOC_FAIL;
3626 if ((r = sshbuf_consume(copy, sizeof(LEGACY_BEGIN))) != 0)
3629 /* Skip cipher type, reserved data and key bits. */
3630 if ((r = sshbuf_get_u8(copy, NULL)) != 0 || /* cipher type */
3631 (r = sshbuf_get_u32(copy, NULL)) != 0 || /* reserved */
3632 (r = sshbuf_get_u32(copy, NULL)) != 0) /* key bits */
3635 /* Read the public key from the buffer. */
3636 if ((pub = sshkey_new(KEY_RSA1)) == NULL ||
3637 (r = sshbuf_get_bignum1(copy, pub->rsa->n)) != 0 ||
3638 (r = sshbuf_get_bignum1(copy, pub->rsa->e)) != 0)
3641 /* Finally, the comment */
3642 if ((r = sshbuf_get_string(copy, (u_char**)commentp, NULL)) != 0)
3645 /* The encrypted private part is not parsed by this function. */
3659 sshkey_parse_private_rsa1(struct sshbuf *blob, const char *passphrase,
3660 struct sshkey **keyp, char **commentp)
3663 u_int16_t check1, check2;
3664 u_int8_t cipher_type;
3665 struct sshbuf *decrypted = NULL, *copy = NULL;
3667 char *comment = NULL;
3668 struct sshcipher_ctx *ciphercontext = NULL;
3669 const struct sshcipher *cipher;
3670 struct sshkey *prv = NULL;
3674 if (commentp != NULL)
3677 /* Check that it is at least big enough to contain the ID string. */
3678 if (sshbuf_len(blob) < sizeof(LEGACY_BEGIN))
3679 return SSH_ERR_INVALID_FORMAT;
3682 * Make sure it begins with the id string. Consume the id string
3685 if (memcmp(sshbuf_ptr(blob), LEGACY_BEGIN, sizeof(LEGACY_BEGIN)) != 0)
3686 return SSH_ERR_INVALID_FORMAT;
3688 if ((prv = sshkey_new_private(KEY_RSA1)) == NULL) {
3689 r = SSH_ERR_ALLOC_FAIL;
3692 if ((copy = sshbuf_fromb(blob)) == NULL ||
3693 (decrypted = sshbuf_new()) == NULL) {
3694 r = SSH_ERR_ALLOC_FAIL;
3697 if ((r = sshbuf_consume(copy, sizeof(LEGACY_BEGIN))) != 0)
3700 /* Read cipher type. */
3701 if ((r = sshbuf_get_u8(copy, &cipher_type)) != 0 ||
3702 (r = sshbuf_get_u32(copy, NULL)) != 0) /* reserved */
3705 /* Read the public key and comment from the buffer. */
3706 if ((r = sshbuf_get_u32(copy, NULL)) != 0 || /* key bits */
3707 (r = sshbuf_get_bignum1(copy, prv->rsa->n)) != 0 ||
3708 (r = sshbuf_get_bignum1(copy, prv->rsa->e)) != 0 ||
3709 (r = sshbuf_get_cstring(copy, &comment, NULL)) != 0)
3712 /* Check that it is a supported cipher. */
3713 cipher = cipher_by_number(cipher_type);
3714 if (cipher == NULL) {
3715 r = SSH_ERR_KEY_UNKNOWN_CIPHER;
3718 /* Initialize space for decrypted data. */
3719 if ((r = sshbuf_reserve(decrypted, sshbuf_len(copy), &cp)) != 0)
3722 /* Rest of the buffer is encrypted. Decrypt it using the passphrase. */
3723 if ((r = cipher_set_key_string(&ciphercontext, cipher, passphrase,
3724 CIPHER_DECRYPT)) != 0)
3726 if ((r = cipher_crypt(ciphercontext, 0, cp,
3727 sshbuf_ptr(copy), sshbuf_len(copy), 0, 0)) != 0)
3730 if ((r = sshbuf_get_u16(decrypted, &check1)) != 0 ||
3731 (r = sshbuf_get_u16(decrypted, &check2)) != 0)
3733 if (check1 != check2) {
3734 r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3738 /* Read the rest of the private key. */
3739 if ((r = sshbuf_get_bignum1(decrypted, prv->rsa->d)) != 0 ||
3740 (r = sshbuf_get_bignum1(decrypted, prv->rsa->iqmp)) != 0 ||
3741 (r = sshbuf_get_bignum1(decrypted, prv->rsa->q)) != 0 ||
3742 (r = sshbuf_get_bignum1(decrypted, prv->rsa->p)) != 0)
3745 /* calculate p-1 and q-1 */
3746 if ((r = rsa_generate_additional_parameters(prv->rsa)) != 0)
3749 /* enable blinding */
3750 if (RSA_blinding_on(prv->rsa, NULL) != 1) {
3751 r = SSH_ERR_LIBCRYPTO_ERROR;
3759 if (commentp != NULL) {
3760 *commentp = comment;
3764 cipher_free(ciphercontext);
3768 sshbuf_free(decrypted);
3771 #endif /* WITH_SSH1 */
3775 sshkey_parse_private_pem_fileblob(struct sshbuf *blob, int type,
3776 const char *passphrase, struct sshkey **keyp)
3778 EVP_PKEY *pk = NULL;
3779 struct sshkey *prv = NULL;
3786 if ((bio = BIO_new(BIO_s_mem())) == NULL || sshbuf_len(blob) > INT_MAX)
3787 return SSH_ERR_ALLOC_FAIL;
3788 if (BIO_write(bio, sshbuf_ptr(blob), sshbuf_len(blob)) !=
3789 (int)sshbuf_len(blob)) {
3790 r = SSH_ERR_ALLOC_FAIL;
3794 if ((pk = PEM_read_bio_PrivateKey(bio, NULL, NULL,
3795 (char *)passphrase)) == NULL) {
3796 unsigned long pem_err = ERR_peek_last_error();
3797 int pem_reason = ERR_GET_REASON(pem_err);
3800 * Translate OpenSSL error codes to determine whether
3801 * passphrase is required/incorrect.
3803 switch (ERR_GET_LIB(pem_err)) {
3805 switch (pem_reason) {
3806 case PEM_R_BAD_PASSWORD_READ:
3807 case PEM_R_PROBLEMS_GETTING_PASSWORD:
3808 case PEM_R_BAD_DECRYPT:
3809 r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3812 r = SSH_ERR_INVALID_FORMAT;
3816 switch (pem_reason) {
3817 case EVP_R_BAD_DECRYPT:
3818 r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3820 case EVP_R_BN_DECODE_ERROR:
3821 case EVP_R_DECODE_ERROR:
3822 #ifdef EVP_R_PRIVATE_KEY_DECODE_ERROR
3823 case EVP_R_PRIVATE_KEY_DECODE_ERROR:
3825 r = SSH_ERR_INVALID_FORMAT;
3828 r = SSH_ERR_LIBCRYPTO_ERROR;
3832 r = SSH_ERR_INVALID_FORMAT;
3835 r = SSH_ERR_LIBCRYPTO_ERROR;
3838 if (pk->type == EVP_PKEY_RSA &&
3839 (type == KEY_UNSPEC || type == KEY_RSA)) {
3840 if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
3841 r = SSH_ERR_ALLOC_FAIL;
3844 prv->rsa = EVP_PKEY_get1_RSA(pk);
3845 prv->type = KEY_RSA;
3847 RSA_print_fp(stderr, prv->rsa, 8);
3849 if (RSA_blinding_on(prv->rsa, NULL) != 1) {
3850 r = SSH_ERR_LIBCRYPTO_ERROR;
3853 } else if (pk->type == EVP_PKEY_DSA &&
3854 (type == KEY_UNSPEC || type == KEY_DSA)) {
3855 if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
3856 r = SSH_ERR_ALLOC_FAIL;
3859 prv->dsa = EVP_PKEY_get1_DSA(pk);
3860 prv->type = KEY_DSA;
3862 DSA_print_fp(stderr, prv->dsa, 8);
3864 #ifdef OPENSSL_HAS_ECC
3865 } else if (pk->type == EVP_PKEY_EC &&
3866 (type == KEY_UNSPEC || type == KEY_ECDSA)) {
3867 if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
3868 r = SSH_ERR_ALLOC_FAIL;
3871 prv->ecdsa = EVP_PKEY_get1_EC_KEY(pk);
3872 prv->type = KEY_ECDSA;
3873 prv->ecdsa_nid = sshkey_ecdsa_key_to_nid(prv->ecdsa);
3874 if (prv->ecdsa_nid == -1 ||
3875 sshkey_curve_nid_to_name(prv->ecdsa_nid) == NULL ||
3876 sshkey_ec_validate_public(EC_KEY_get0_group(prv->ecdsa),
3877 EC_KEY_get0_public_key(prv->ecdsa)) != 0 ||
3878 sshkey_ec_validate_private(prv->ecdsa) != 0) {
3879 r = SSH_ERR_INVALID_FORMAT;
3883 if (prv != NULL && prv->ecdsa != NULL)
3884 sshkey_dump_ec_key(prv->ecdsa);
3886 #endif /* OPENSSL_HAS_ECC */
3888 r = SSH_ERR_INVALID_FORMAT;
3903 #endif /* WITH_OPENSSL */
3906 sshkey_parse_private_fileblob_type(struct sshbuf *blob, int type,
3907 const char *passphrase, struct sshkey **keyp, char **commentp)
3909 int r = SSH_ERR_INTERNAL_ERROR;
3913 if (commentp != NULL)
3919 return sshkey_parse_private_rsa1(blob, passphrase,
3921 #endif /* WITH_SSH1 */
3926 return sshkey_parse_private_pem_fileblob(blob, type,
3928 #endif /* WITH_OPENSSL */
3930 return sshkey_parse_private2(blob, type, passphrase,
3933 r = sshkey_parse_private2(blob, type, passphrase, keyp,
3935 /* Do not fallback to PEM parser if only passphrase is wrong. */
3936 if (r == 0 || r == SSH_ERR_KEY_WRONG_PASSPHRASE)
3939 return sshkey_parse_private_pem_fileblob(blob, type,
3942 return SSH_ERR_INVALID_FORMAT;
3943 #endif /* WITH_OPENSSL */
3945 return SSH_ERR_KEY_TYPE_UNKNOWN;
3950 sshkey_parse_private_fileblob(struct sshbuf *buffer, const char *passphrase,
3951 struct sshkey **keyp, char **commentp)
3955 if (commentp != NULL)
3959 /* it's a SSH v1 key if the public key part is readable */
3960 if (sshkey_parse_public_rsa1_fileblob(buffer, NULL, NULL) == 0) {
3961 return sshkey_parse_private_fileblob_type(buffer, KEY_RSA1,
3962 passphrase, keyp, commentp);
3964 #endif /* WITH_SSH1 */
3965 return sshkey_parse_private_fileblob_type(buffer, KEY_UNSPEC,
3966 passphrase, keyp, commentp);