1 /* $OpenBSD: key.c,v 1.104 2013/05/19 02:42:42 djm Exp $ */
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * As far as I am concerned, the code I have written for this software
7 * can be used freely for any purpose. Any derived versions of this
8 * software must be clearly marked as such, and if the derived work is
9 * incompatible with the protocol description in the RFC file, it must be
10 * called by a name other than "ssh" or "Secure Shell".
13 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
14 * Copyright (c) 2008 Alexander von Gernler. All rights reserved.
16 * Redistribution and use in source and binary forms, with or without
17 * modification, are permitted provided that the following conditions
19 * 1. Redistributions of source code must retain the above copyright
20 * notice, this list of conditions and the following disclaimer.
21 * 2. Redistributions in binary form must reproduce the above copyright
22 * notice, this list of conditions and the following disclaimer in the
23 * documentation and/or other materials provided with the distribution.
25 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
26 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
27 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
28 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
29 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
31 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
32 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
34 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 #include <sys/param.h>
40 #include <sys/types.h>
42 #include <openssl/evp.h>
43 #include <openbsd-compat/openssl-compat.h>
58 static int to_blob(const Key *, u_char **, u_int *, int);
60 static struct KeyCert *
65 cert = xcalloc(1, sizeof(*cert));
66 buffer_init(&cert->certblob);
67 buffer_init(&cert->critical);
68 buffer_init(&cert->extensions);
70 cert->principals = NULL;
71 cert->signature_key = NULL;
81 k = xcalloc(1, sizeof(*k));
91 case KEY_RSA_CERT_V00:
93 if ((rsa = RSA_new()) == NULL)
94 fatal("key_new: RSA_new failed");
95 if ((rsa->n = BN_new()) == NULL)
96 fatal("key_new: BN_new failed");
97 if ((rsa->e = BN_new()) == NULL)
98 fatal("key_new: BN_new failed");
102 case KEY_DSA_CERT_V00:
104 if ((dsa = DSA_new()) == NULL)
105 fatal("key_new: DSA_new failed");
106 if ((dsa->p = BN_new()) == NULL)
107 fatal("key_new: BN_new failed");
108 if ((dsa->q = BN_new()) == NULL)
109 fatal("key_new: BN_new failed");
110 if ((dsa->g = BN_new()) == NULL)
111 fatal("key_new: BN_new failed");
112 if ((dsa->pub_key = BN_new()) == NULL)
113 fatal("key_new: BN_new failed");
116 #ifdef OPENSSL_HAS_ECC
119 /* Cannot do anything until we know the group */
125 fatal("key_new: bad key type %d", k->type);
130 k->cert = cert_new();
136 key_add_private(Key *k)
141 case KEY_RSA_CERT_V00:
143 if ((k->rsa->d = BN_new()) == NULL)
144 fatal("key_new_private: BN_new failed");
145 if ((k->rsa->iqmp = BN_new()) == NULL)
146 fatal("key_new_private: BN_new failed");
147 if ((k->rsa->q = BN_new()) == NULL)
148 fatal("key_new_private: BN_new failed");
149 if ((k->rsa->p = BN_new()) == NULL)
150 fatal("key_new_private: BN_new failed");
151 if ((k->rsa->dmq1 = BN_new()) == NULL)
152 fatal("key_new_private: BN_new failed");
153 if ((k->rsa->dmp1 = BN_new()) == NULL)
154 fatal("key_new_private: BN_new failed");
157 case KEY_DSA_CERT_V00:
159 if ((k->dsa->priv_key = BN_new()) == NULL)
160 fatal("key_new_private: BN_new failed");
164 /* Cannot do anything until we know the group */
174 key_new_private(int type)
176 Key *k = key_new(type);
183 cert_free(struct KeyCert *cert)
187 buffer_free(&cert->certblob);
188 buffer_free(&cert->critical);
189 buffer_free(&cert->extensions);
191 for (i = 0; i < cert->nprincipals; i++)
192 free(cert->principals[i]);
193 free(cert->principals);
194 if (cert->signature_key != NULL)
195 key_free(cert->signature_key);
203 fatal("key_free: key is NULL");
207 case KEY_RSA_CERT_V00:
214 case KEY_DSA_CERT_V00:
220 #ifdef OPENSSL_HAS_ECC
223 if (k->ecdsa != NULL)
224 EC_KEY_free(k->ecdsa);
231 fatal("key_free: bad key type %d", k->type);
234 if (key_is_cert(k)) {
244 cert_compare(struct KeyCert *a, struct KeyCert *b)
246 if (a == NULL && b == NULL)
248 if (a == NULL || b == NULL)
250 if (buffer_len(&a->certblob) != buffer_len(&b->certblob))
252 if (timingsafe_bcmp(buffer_ptr(&a->certblob), buffer_ptr(&b->certblob),
253 buffer_len(&a->certblob)) != 0)
259 * Compare public portions of key only, allowing comparisons between
260 * certificates and plain keys too.
263 key_equal_public(const Key *a, const Key *b)
265 #ifdef OPENSSL_HAS_ECC
269 if (a == NULL || b == NULL ||
270 key_type_plain(a->type) != key_type_plain(b->type))
275 case KEY_RSA_CERT_V00:
278 return a->rsa != NULL && b->rsa != NULL &&
279 BN_cmp(a->rsa->e, b->rsa->e) == 0 &&
280 BN_cmp(a->rsa->n, b->rsa->n) == 0;
281 case KEY_DSA_CERT_V00:
284 return a->dsa != NULL && b->dsa != NULL &&
285 BN_cmp(a->dsa->p, b->dsa->p) == 0 &&
286 BN_cmp(a->dsa->q, b->dsa->q) == 0 &&
287 BN_cmp(a->dsa->g, b->dsa->g) == 0 &&
288 BN_cmp(a->dsa->pub_key, b->dsa->pub_key) == 0;
289 #ifdef OPENSSL_HAS_ECC
292 if (a->ecdsa == NULL || b->ecdsa == NULL ||
293 EC_KEY_get0_public_key(a->ecdsa) == NULL ||
294 EC_KEY_get0_public_key(b->ecdsa) == NULL)
296 if ((bnctx = BN_CTX_new()) == NULL)
297 fatal("%s: BN_CTX_new failed", __func__);
298 if (EC_GROUP_cmp(EC_KEY_get0_group(a->ecdsa),
299 EC_KEY_get0_group(b->ecdsa), bnctx) != 0 ||
300 EC_POINT_cmp(EC_KEY_get0_group(a->ecdsa),
301 EC_KEY_get0_public_key(a->ecdsa),
302 EC_KEY_get0_public_key(b->ecdsa), bnctx) != 0) {
308 #endif /* OPENSSL_HAS_ECC */
310 fatal("key_equal: bad key type %d", a->type);
316 key_equal(const Key *a, const Key *b)
318 if (a == NULL || b == NULL || a->type != b->type)
320 if (key_is_cert(a)) {
321 if (!cert_compare(a->cert, b->cert))
324 return key_equal_public(a, b);
328 key_fingerprint_raw(const Key *k, enum fp_type dgst_type,
329 u_int *dgst_raw_length)
331 const EVP_MD *md = NULL;
334 u_char *retval = NULL;
338 *dgst_raw_length = 0;
347 #ifdef HAVE_EVP_SHA256
353 fatal("key_fingerprint_raw: bad digest type %d",
358 nlen = BN_num_bytes(k->rsa->n);
359 elen = BN_num_bytes(k->rsa->e);
362 BN_bn2bin(k->rsa->n, blob);
363 BN_bn2bin(k->rsa->e, blob + nlen);
368 key_to_blob(k, &blob, &len);
370 case KEY_DSA_CERT_V00:
371 case KEY_RSA_CERT_V00:
375 /* We want a fingerprint of the _key_ not of the cert */
376 to_blob(k, &blob, &len, 1);
381 fatal("key_fingerprint_raw: bad key type %d", k->type);
385 retval = xmalloc(EVP_MAX_MD_SIZE);
386 EVP_DigestInit(&ctx, md);
387 EVP_DigestUpdate(&ctx, blob, len);
388 EVP_DigestFinal(&ctx, retval, dgst_raw_length);
389 memset(blob, 0, len);
392 fatal("key_fingerprint_raw: blob is null");
398 key_fingerprint_hex(u_char *dgst_raw, u_int dgst_raw_len)
403 retval = xcalloc(1, dgst_raw_len * 3 + 1);
404 for (i = 0; i < dgst_raw_len; i++) {
406 snprintf(hex, sizeof(hex), "%02x:", dgst_raw[i]);
407 strlcat(retval, hex, dgst_raw_len * 3 + 1);
410 /* Remove the trailing ':' character */
411 retval[(dgst_raw_len * 3) - 1] = '\0';
416 key_fingerprint_bubblebabble(u_char *dgst_raw, u_int dgst_raw_len)
418 char vowels[] = { 'a', 'e', 'i', 'o', 'u', 'y' };
419 char consonants[] = { 'b', 'c', 'd', 'f', 'g', 'h', 'k', 'l', 'm',
420 'n', 'p', 'r', 's', 't', 'v', 'z', 'x' };
421 u_int i, j = 0, rounds, seed = 1;
424 rounds = (dgst_raw_len / 2) + 1;
425 retval = xcalloc((rounds * 6), sizeof(char));
427 for (i = 0; i < rounds; i++) {
428 u_int idx0, idx1, idx2, idx3, idx4;
429 if ((i + 1 < rounds) || (dgst_raw_len % 2 != 0)) {
430 idx0 = (((((u_int)(dgst_raw[2 * i])) >> 6) & 3) +
432 idx1 = (((u_int)(dgst_raw[2 * i])) >> 2) & 15;
433 idx2 = ((((u_int)(dgst_raw[2 * i])) & 3) +
435 retval[j++] = vowels[idx0];
436 retval[j++] = consonants[idx1];
437 retval[j++] = vowels[idx2];
438 if ((i + 1) < rounds) {
439 idx3 = (((u_int)(dgst_raw[(2 * i) + 1])) >> 4) & 15;
440 idx4 = (((u_int)(dgst_raw[(2 * i) + 1]))) & 15;
441 retval[j++] = consonants[idx3];
443 retval[j++] = consonants[idx4];
445 ((((u_int)(dgst_raw[2 * i])) * 7) +
446 ((u_int)(dgst_raw[(2 * i) + 1])))) % 36;
452 retval[j++] = vowels[idx0];
453 retval[j++] = consonants[idx1];
454 retval[j++] = vowels[idx2];
463 * Draw an ASCII-Art representing the fingerprint so human brain can
464 * profit from its built-in pattern recognition ability.
465 * This technique is called "random art" and can be found in some
466 * scientific publications like this original paper:
468 * "Hash Visualization: a New Technique to improve Real-World Security",
469 * Perrig A. and Song D., 1999, International Workshop on Cryptographic
470 * Techniques and E-Commerce (CrypTEC '99)
471 * sparrow.ece.cmu.edu/~adrian/projects/validation/validation.pdf
473 * The subject came up in a talk by Dan Kaminsky, too.
475 * If you see the picture is different, the key is different.
476 * If the picture looks the same, you still know nothing.
478 * The algorithm used here is a worm crawling over a discrete plane,
479 * leaving a trace (augmenting the field) everywhere it goes.
480 * Movement is taken from dgst_raw 2bit-wise. Bumping into walls
481 * makes the respective movement vector be ignored for this turn.
482 * Graphs are not unambiguous, because circles in graphs can be
483 * walked in either direction.
487 * Field sizes for the random art. Have to be odd, so the starting point
488 * can be in the exact middle of the picture, and FLDBASE should be >=8 .
489 * Else pictures would be too dense, and drawing the frame would
490 * fail, too, because the key type would not fit in anymore.
493 #define FLDSIZE_Y (FLDBASE + 1)
494 #define FLDSIZE_X (FLDBASE * 2 + 1)
496 key_fingerprint_randomart(u_char *dgst_raw, u_int dgst_raw_len, const Key *k)
499 * Chars to be used after each other every time the worm
500 * intersects with itself. Matter of taste.
502 char *augmentation_string = " .o+=*BOX@%&#/^SE";
504 u_char field[FLDSIZE_X][FLDSIZE_Y];
507 size_t len = strlen(augmentation_string) - 1;
509 retval = xcalloc(1, (FLDSIZE_X + 3) * (FLDSIZE_Y + 2));
511 /* initialize field */
512 memset(field, 0, FLDSIZE_X * FLDSIZE_Y * sizeof(char));
516 /* process raw key */
517 for (i = 0; i < dgst_raw_len; i++) {
519 /* each byte conveys four 2-bit move commands */
521 for (b = 0; b < 4; b++) {
522 /* evaluate 2 bit, rest is shifted later */
523 x += (input & 0x1) ? 1 : -1;
524 y += (input & 0x2) ? 1 : -1;
526 /* assure we are still in bounds */
529 x = MIN(x, FLDSIZE_X - 1);
530 y = MIN(y, FLDSIZE_Y - 1);
532 /* augment the field */
533 if (field[x][y] < len - 2)
539 /* mark starting point and end point*/
540 field[FLDSIZE_X / 2][FLDSIZE_Y / 2] = len - 1;
544 snprintf(retval, FLDSIZE_X, "+--[%4s %4u]", key_type(k), key_size(k));
545 p = strchr(retval, '\0');
547 /* output upper border */
548 for (i = p - retval - 1; i < FLDSIZE_X; i++)
554 for (y = 0; y < FLDSIZE_Y; y++) {
556 for (x = 0; x < FLDSIZE_X; x++)
557 *p++ = augmentation_string[MIN(field[x][y], len)];
562 /* output lower border */
564 for (i = 0; i < FLDSIZE_X; i++)
572 key_fingerprint(const Key *k, enum fp_type dgst_type, enum fp_rep dgst_rep)
578 dgst_raw = key_fingerprint_raw(k, dgst_type, &dgst_raw_len);
580 fatal("key_fingerprint: null from key_fingerprint_raw()");
583 retval = key_fingerprint_hex(dgst_raw, dgst_raw_len);
585 case SSH_FP_BUBBLEBABBLE:
586 retval = key_fingerprint_bubblebabble(dgst_raw, dgst_raw_len);
588 case SSH_FP_RANDOMART:
589 retval = key_fingerprint_randomart(dgst_raw, dgst_raw_len, k);
592 fatal("key_fingerprint: bad digest representation %d",
596 memset(dgst_raw, 0, dgst_raw_len);
602 * Reads a multiple-precision integer in decimal from the buffer, and advances
603 * the pointer. The integer must already be initialized. This function is
604 * permitted to modify the buffer. This leaves *cpp to point just beyond the
605 * last processed (and maybe modified) character. Note that this may modify
606 * the buffer containing the number.
609 read_bignum(char **cpp, BIGNUM * value)
614 /* Skip any leading whitespace. */
615 for (; *cp == ' ' || *cp == '\t'; cp++)
618 /* Check that it begins with a decimal digit. */
619 if (*cp < '0' || *cp > '9')
622 /* Save starting position. */
625 /* Move forward until all decimal digits skipped. */
626 for (; *cp >= '0' && *cp <= '9'; cp++)
629 /* Save the old terminating character, and replace it by \0. */
633 /* Parse the number. */
634 if (BN_dec2bn(&value, *cpp) == 0)
637 /* Restore old terminating character. */
640 /* Move beyond the number and return success. */
646 write_bignum(FILE *f, BIGNUM *num)
648 char *buf = BN_bn2dec(num);
650 error("write_bignum: BN_bn2dec() failed");
653 fprintf(f, " %s", buf);
658 /* returns 1 ok, -1 error */
660 key_read(Key *ret, char **cpp)
668 #ifdef OPENSSL_HAS_ECC
676 /* Get number of bits. */
677 if (*cp < '0' || *cp > '9')
678 return -1; /* Bad bit count... */
679 for (bits = 0; *cp >= '0' && *cp <= '9'; cp++)
680 bits = 10 * bits + *cp - '0';
684 /* Get public exponent, public modulus. */
685 if (!read_bignum(cpp, ret->rsa->e))
687 if (!read_bignum(cpp, ret->rsa->n))
689 /* validate the claimed number of bits */
690 if ((u_int)BN_num_bits(ret->rsa->n) != bits) {
691 verbose("key_read: claimed key size %d does not match "
692 "actual %d", bits, BN_num_bits(ret->rsa->n));
701 case KEY_DSA_CERT_V00:
702 case KEY_RSA_CERT_V00:
706 space = strchr(cp, ' ');
708 debug3("key_read: missing whitespace");
712 type = key_type_from_name(cp);
713 #ifdef OPENSSL_HAS_ECC
714 if (key_type_plain(type) == KEY_ECDSA &&
715 (curve_nid = key_ecdsa_nid_from_name(cp)) == -1) {
716 debug("key_read: invalid curve");
721 if (type == KEY_UNSPEC) {
722 debug3("key_read: missing keytype");
727 debug3("key_read: short string");
730 if (ret->type == KEY_UNSPEC) {
732 } else if (ret->type != type) {
733 /* is a key, but different type */
734 debug3("key_read: type mismatch");
739 n = uudecode(cp, blob, len);
741 error("key_read: uudecode %s failed", cp);
745 k = key_from_blob(blob, (u_int)n);
748 error("key_read: key_from_blob %s failed", cp);
751 if (k->type != type) {
752 error("key_read: type mismatch: encoding error");
756 #ifdef OPENSSL_HAS_ECC
757 if (key_type_plain(type) == KEY_ECDSA &&
758 curve_nid != k->ecdsa_nid) {
759 error("key_read: type mismatch: EC curve mismatch");
765 if (key_is_cert(ret)) {
766 if (!key_is_cert(k)) {
767 error("key_read: loaded key is not a cert");
771 if (ret->cert != NULL)
772 cert_free(ret->cert);
776 if (key_type_plain(ret->type) == KEY_RSA) {
777 if (ret->rsa != NULL)
782 RSA_print_fp(stderr, ret->rsa, 8);
785 if (key_type_plain(ret->type) == KEY_DSA) {
786 if (ret->dsa != NULL)
791 DSA_print_fp(stderr, ret->dsa, 8);
794 #ifdef OPENSSL_HAS_ECC
795 if (key_type_plain(ret->type) == KEY_ECDSA) {
796 if (ret->ecdsa != NULL)
797 EC_KEY_free(ret->ecdsa);
798 ret->ecdsa = k->ecdsa;
799 ret->ecdsa_nid = k->ecdsa_nid;
803 key_dump_ec_key(ret->ecdsa);
812 /* advance cp: skip whitespace and data */
813 while (*cp == ' ' || *cp == '\t')
815 while (*cp != '\0' && *cp != ' ' && *cp != '\t')
820 fatal("key_read: bad key type: %d", ret->type);
827 key_write(const Key *key, FILE *f)
834 if (key_is_cert(key)) {
835 if (key->cert == NULL) {
836 error("%s: no cert data", __func__);
839 if (buffer_len(&key->cert->certblob) == 0) {
840 error("%s: no signed certificate blob", __func__);
847 if (key->rsa == NULL)
849 /* size of modulus 'n' */
850 bits = BN_num_bits(key->rsa->n);
851 fprintf(f, "%u", bits);
852 if (write_bignum(f, key->rsa->e) &&
853 write_bignum(f, key->rsa->n))
855 error("key_write: failed for RSA key");
858 case KEY_DSA_CERT_V00:
860 if (key->dsa == NULL)
863 #ifdef OPENSSL_HAS_ECC
866 if (key->ecdsa == NULL)
871 case KEY_RSA_CERT_V00:
873 if (key->rsa == NULL)
880 key_to_blob(key, &blob, &len);
882 n = uuencode(blob, len, uu, 2*len);
884 fprintf(f, "%s %s", key_ssh_name(key), uu);
894 key_cert_type(const Key *k)
896 switch (k->cert->type) {
897 case SSH2_CERT_TYPE_USER:
899 case SSH2_CERT_TYPE_HOST:
913 static const struct keytype keytypes[] = {
914 { NULL, "RSA1", KEY_RSA1, 0, 0 },
915 { "ssh-rsa", "RSA", KEY_RSA, 0, 0 },
916 { "ssh-dss", "DSA", KEY_DSA, 0, 0 },
917 #ifdef OPENSSL_HAS_ECC
918 { "ecdsa-sha2-nistp256", "ECDSA", KEY_ECDSA, NID_X9_62_prime256v1, 0 },
919 { "ecdsa-sha2-nistp384", "ECDSA", KEY_ECDSA, NID_secp384r1, 0 },
920 { "ecdsa-sha2-nistp521", "ECDSA", KEY_ECDSA, NID_secp521r1, 0 },
921 #endif /* OPENSSL_HAS_ECC */
922 { "ssh-rsa-cert-v01@openssh.com", "RSA-CERT", KEY_RSA_CERT, 0, 1 },
923 { "ssh-dss-cert-v01@openssh.com", "DSA-CERT", KEY_DSA_CERT, 0, 1 },
924 #ifdef OPENSSL_HAS_ECC
925 { "ecdsa-sha2-nistp256-cert-v01@openssh.com", "ECDSA-CERT",
926 KEY_ECDSA_CERT, NID_X9_62_prime256v1, 1 },
927 { "ecdsa-sha2-nistp384-cert-v01@openssh.com", "ECDSA-CERT",
928 KEY_ECDSA_CERT, NID_secp384r1, 1 },
929 { "ecdsa-sha2-nistp521-cert-v01@openssh.com", "ECDSA-CERT",
930 KEY_ECDSA_CERT, NID_secp521r1, 1 },
931 #endif /* OPENSSL_HAS_ECC */
932 { "ssh-rsa-cert-v00@openssh.com", "RSA-CERT-V00",
933 KEY_RSA_CERT_V00, 0, 1 },
934 { "ssh-dss-cert-v00@openssh.com", "DSA-CERT-V00",
935 KEY_DSA_CERT_V00, 0, 1 },
936 { NULL, NULL, -1, -1, 0 }
940 key_type(const Key *k)
942 const struct keytype *kt;
944 for (kt = keytypes; kt->type != -1; kt++) {
945 if (kt->type == k->type)
946 return kt->shortname;
952 key_ssh_name_from_type_nid(int type, int nid)
954 const struct keytype *kt;
956 for (kt = keytypes; kt->type != -1; kt++) {
957 if (kt->type == type && (kt->nid == 0 || kt->nid == nid))
960 return "ssh-unknown";
964 key_ssh_name(const Key *k)
966 return key_ssh_name_from_type_nid(k->type, k->ecdsa_nid);
970 key_ssh_name_plain(const Key *k)
972 return key_ssh_name_from_type_nid(key_type_plain(k->type),
977 key_type_from_name(char *name)
979 const struct keytype *kt;
981 for (kt = keytypes; kt->type != -1; kt++) {
982 /* Only allow shortname matches for plain key types */
983 if ((kt->name != NULL && strcmp(name, kt->name) == 0) ||
984 (!kt->cert && strcasecmp(kt->shortname, name) == 0))
987 debug2("key_type_from_name: unknown key type '%s'", name);
992 key_ecdsa_nid_from_name(const char *name)
994 const struct keytype *kt;
996 for (kt = keytypes; kt->type != -1; kt++) {
997 if (kt->type != KEY_ECDSA && kt->type != KEY_ECDSA_CERT)
999 if (kt->name != NULL && strcmp(name, kt->name) == 0)
1002 debug2("%s: unknown/non-ECDSA key type '%s'", __func__, name);
1010 size_t nlen, rlen = 0;
1011 const struct keytype *kt;
1013 for (kt = keytypes; kt->type != -1; kt++) {
1014 if (kt->name == NULL)
1018 nlen = strlen(kt->name);
1019 ret = xrealloc(ret, 1, rlen + nlen + 2);
1020 memcpy(ret + rlen, kt->name, nlen + 1);
1027 key_size(const Key *k)
1032 case KEY_RSA_CERT_V00:
1034 return BN_num_bits(k->rsa->n);
1036 case KEY_DSA_CERT_V00:
1038 return BN_num_bits(k->dsa->p);
1039 #ifdef OPENSSL_HAS_ECC
1041 case KEY_ECDSA_CERT:
1042 return key_curve_nid_to_bits(k->ecdsa_nid);
1049 rsa_generate_private_key(u_int bits)
1051 RSA *private = RSA_new();
1052 BIGNUM *f4 = BN_new();
1054 if (private == NULL)
1055 fatal("%s: RSA_new failed", __func__);
1057 fatal("%s: BN_new failed", __func__);
1058 if (!BN_set_word(f4, RSA_F4))
1059 fatal("%s: BN_new failed", __func__);
1060 if (!RSA_generate_key_ex(private, bits, f4, NULL))
1061 fatal("%s: key generation failed.", __func__);
1067 dsa_generate_private_key(u_int bits)
1069 DSA *private = DSA_new();
1071 if (private == NULL)
1072 fatal("%s: DSA_new failed", __func__);
1073 if (!DSA_generate_parameters_ex(private, bits, NULL, 0, NULL,
1075 fatal("%s: DSA_generate_parameters failed", __func__);
1076 if (!DSA_generate_key(private))
1077 fatal("%s: DSA_generate_key failed.", __func__);
1082 key_ecdsa_bits_to_nid(int bits)
1085 #ifdef OPENSSL_HAS_ECC
1087 return NID_X9_62_prime256v1;
1089 return NID_secp384r1;
1091 return NID_secp521r1;
1098 #ifdef OPENSSL_HAS_ECC
1100 key_ecdsa_key_to_nid(EC_KEY *k)
1104 NID_X9_62_prime256v1,
1112 const EC_GROUP *g = EC_KEY_get0_group(k);
1115 * The group may be stored in a ASN.1 encoded private key in one of two
1116 * ways: as a "named group", which is reconstituted by ASN.1 object ID
1117 * or explicit group parameters encoded into the key blob. Only the
1118 * "named group" case sets the group NID for us, but we can figure
1119 * it out for the other case by comparing against all the groups that
1122 if ((nid = EC_GROUP_get_curve_name(g)) > 0)
1124 if ((bnctx = BN_CTX_new()) == NULL)
1125 fatal("%s: BN_CTX_new() failed", __func__);
1126 for (i = 0; nids[i] != -1; i++) {
1127 if ((eg = EC_GROUP_new_by_curve_name(nids[i])) == NULL)
1128 fatal("%s: EC_GROUP_new_by_curve_name failed",
1130 if (EC_GROUP_cmp(g, eg, bnctx) == 0)
1135 debug3("%s: nid = %d", __func__, nids[i]);
1136 if (nids[i] != -1) {
1137 /* Use the group with the NID attached */
1138 EC_GROUP_set_asn1_flag(eg, OPENSSL_EC_NAMED_CURVE);
1139 if (EC_KEY_set_group(k, eg) != 1)
1140 fatal("%s: EC_KEY_set_group", __func__);
1146 ecdsa_generate_private_key(u_int bits, int *nid)
1150 if ((*nid = key_ecdsa_bits_to_nid(bits)) == -1)
1151 fatal("%s: invalid key length", __func__);
1152 if ((private = EC_KEY_new_by_curve_name(*nid)) == NULL)
1153 fatal("%s: EC_KEY_new_by_curve_name failed", __func__);
1154 if (EC_KEY_generate_key(private) != 1)
1155 fatal("%s: EC_KEY_generate_key failed", __func__);
1156 EC_KEY_set_asn1_flag(private, OPENSSL_EC_NAMED_CURVE);
1159 #endif /* OPENSSL_HAS_ECC */
1162 key_generate(int type, u_int bits)
1164 Key *k = key_new(KEY_UNSPEC);
1167 k->dsa = dsa_generate_private_key(bits);
1169 #ifdef OPENSSL_HAS_ECC
1171 k->ecdsa = ecdsa_generate_private_key(bits, &k->ecdsa_nid);
1176 k->rsa = rsa_generate_private_key(bits);
1178 case KEY_RSA_CERT_V00:
1179 case KEY_DSA_CERT_V00:
1182 fatal("key_generate: cert keys cannot be generated directly");
1184 fatal("key_generate: unknown type %d", type);
1191 key_cert_copy(const Key *from_key, struct Key *to_key)
1194 const struct KeyCert *from;
1197 if (to_key->cert != NULL) {
1198 cert_free(to_key->cert);
1199 to_key->cert = NULL;
1202 if ((from = from_key->cert) == NULL)
1205 to = to_key->cert = cert_new();
1207 buffer_append(&to->certblob, buffer_ptr(&from->certblob),
1208 buffer_len(&from->certblob));
1210 buffer_append(&to->critical,
1211 buffer_ptr(&from->critical), buffer_len(&from->critical));
1212 buffer_append(&to->extensions,
1213 buffer_ptr(&from->extensions), buffer_len(&from->extensions));
1215 to->serial = from->serial;
1216 to->type = from->type;
1217 to->key_id = from->key_id == NULL ? NULL : xstrdup(from->key_id);
1218 to->valid_after = from->valid_after;
1219 to->valid_before = from->valid_before;
1220 to->signature_key = from->signature_key == NULL ?
1221 NULL : key_from_private(from->signature_key);
1223 to->nprincipals = from->nprincipals;
1224 if (to->nprincipals > CERT_MAX_PRINCIPALS)
1225 fatal("%s: nprincipals (%u) > CERT_MAX_PRINCIPALS (%u)",
1226 __func__, to->nprincipals, CERT_MAX_PRINCIPALS);
1227 if (to->nprincipals > 0) {
1228 to->principals = xcalloc(from->nprincipals,
1229 sizeof(*to->principals));
1230 for (i = 0; i < to->nprincipals; i++)
1231 to->principals[i] = xstrdup(from->principals[i]);
1236 key_from_private(const Key *k)
1241 case KEY_DSA_CERT_V00:
1243 n = key_new(k->type);
1244 if ((BN_copy(n->dsa->p, k->dsa->p) == NULL) ||
1245 (BN_copy(n->dsa->q, k->dsa->q) == NULL) ||
1246 (BN_copy(n->dsa->g, k->dsa->g) == NULL) ||
1247 (BN_copy(n->dsa->pub_key, k->dsa->pub_key) == NULL))
1248 fatal("key_from_private: BN_copy failed");
1250 #ifdef OPENSSL_HAS_ECC
1252 case KEY_ECDSA_CERT:
1253 n = key_new(k->type);
1254 n->ecdsa_nid = k->ecdsa_nid;
1255 if ((n->ecdsa = EC_KEY_new_by_curve_name(k->ecdsa_nid)) == NULL)
1256 fatal("%s: EC_KEY_new_by_curve_name failed", __func__);
1257 if (EC_KEY_set_public_key(n->ecdsa,
1258 EC_KEY_get0_public_key(k->ecdsa)) != 1)
1259 fatal("%s: EC_KEY_set_public_key failed", __func__);
1264 case KEY_RSA_CERT_V00:
1266 n = key_new(k->type);
1267 if ((BN_copy(n->rsa->n, k->rsa->n) == NULL) ||
1268 (BN_copy(n->rsa->e, k->rsa->e) == NULL))
1269 fatal("key_from_private: BN_copy failed");
1272 fatal("key_from_private: unknown type %d", k->type);
1276 key_cert_copy(k, n);
1281 key_names_valid2(const char *names)
1285 if (names == NULL || strcmp(names, "") == 0)
1287 s = cp = xstrdup(names);
1288 for ((p = strsep(&cp, ",")); p && *p != '\0';
1289 (p = strsep(&cp, ","))) {
1290 switch (key_type_from_name(p)) {
1297 debug3("key names ok: [%s]", names);
1303 cert_parse(Buffer *b, Key *key, const u_char *blob, u_int blen)
1305 u_char *principals, *critical, *exts, *sig_key, *sig;
1306 u_int signed_len, plen, clen, sklen, slen, kidlen, elen;
1310 int v00 = key->type == KEY_DSA_CERT_V00 ||
1311 key->type == KEY_RSA_CERT_V00;
1315 /* Copy the entire key blob for verification and later serialisation */
1316 buffer_append(&key->cert->certblob, blob, blen);
1318 elen = 0; /* Not touched for v00 certs */
1319 principals = exts = critical = sig_key = sig = NULL;
1320 if ((!v00 && buffer_get_int64_ret(&key->cert->serial, b) != 0) ||
1321 buffer_get_int_ret(&key->cert->type, b) != 0 ||
1322 (key->cert->key_id = buffer_get_cstring_ret(b, &kidlen)) == NULL ||
1323 (principals = buffer_get_string_ret(b, &plen)) == NULL ||
1324 buffer_get_int64_ret(&key->cert->valid_after, b) != 0 ||
1325 buffer_get_int64_ret(&key->cert->valid_before, b) != 0 ||
1326 (critical = buffer_get_string_ret(b, &clen)) == NULL ||
1327 (!v00 && (exts = buffer_get_string_ret(b, &elen)) == NULL) ||
1328 (v00 && buffer_get_string_ptr_ret(b, NULL) == NULL) || /* nonce */
1329 buffer_get_string_ptr_ret(b, NULL) == NULL || /* reserved */
1330 (sig_key = buffer_get_string_ret(b, &sklen)) == NULL) {
1331 error("%s: parse error", __func__);
1335 /* Signature is left in the buffer so we can calculate this length */
1336 signed_len = buffer_len(&key->cert->certblob) - buffer_len(b);
1338 if ((sig = buffer_get_string_ret(b, &slen)) == NULL) {
1339 error("%s: parse error", __func__);
1343 if (key->cert->type != SSH2_CERT_TYPE_USER &&
1344 key->cert->type != SSH2_CERT_TYPE_HOST) {
1345 error("Unknown certificate type %u", key->cert->type);
1349 buffer_append(&tmp, principals, plen);
1350 while (buffer_len(&tmp) > 0) {
1351 if (key->cert->nprincipals >= CERT_MAX_PRINCIPALS) {
1352 error("%s: Too many principals", __func__);
1355 if ((principal = buffer_get_cstring_ret(&tmp, &plen)) == NULL) {
1356 error("%s: Principals data invalid", __func__);
1359 key->cert->principals = xrealloc(key->cert->principals,
1360 key->cert->nprincipals + 1, sizeof(*key->cert->principals));
1361 key->cert->principals[key->cert->nprincipals++] = principal;
1366 buffer_append(&key->cert->critical, critical, clen);
1367 buffer_append(&tmp, critical, clen);
1368 /* validate structure */
1369 while (buffer_len(&tmp) != 0) {
1370 if (buffer_get_string_ptr_ret(&tmp, NULL) == NULL ||
1371 buffer_get_string_ptr_ret(&tmp, NULL) == NULL) {
1372 error("%s: critical option data invalid", __func__);
1378 buffer_append(&key->cert->extensions, exts, elen);
1379 buffer_append(&tmp, exts, elen);
1380 /* validate structure */
1381 while (buffer_len(&tmp) != 0) {
1382 if (buffer_get_string_ptr_ret(&tmp, NULL) == NULL ||
1383 buffer_get_string_ptr_ret(&tmp, NULL) == NULL) {
1384 error("%s: extension data invalid", __func__);
1390 if ((key->cert->signature_key = key_from_blob(sig_key,
1392 error("%s: Signature key invalid", __func__);
1395 if (key->cert->signature_key->type != KEY_RSA &&
1396 key->cert->signature_key->type != KEY_DSA &&
1397 key->cert->signature_key->type != KEY_ECDSA) {
1398 error("%s: Invalid signature key type %s (%d)", __func__,
1399 key_type(key->cert->signature_key),
1400 key->cert->signature_key->type);
1404 switch (key_verify(key->cert->signature_key, sig, slen,
1405 buffer_ptr(&key->cert->certblob), signed_len)) {
1408 break; /* Good signature */
1410 error("%s: Invalid signature on certificate", __func__);
1413 error("%s: Certificate signature verification failed",
1429 key_from_blob(const u_char *blob, u_int blen)
1433 char *ktype = NULL, *curve = NULL;
1435 #ifdef OPENSSL_HAS_ECC
1441 dump_base64(stderr, blob, blen);
1444 buffer_append(&b, blob, blen);
1445 if ((ktype = buffer_get_cstring_ret(&b, NULL)) == NULL) {
1446 error("key_from_blob: can't read key type");
1450 type = key_type_from_name(ktype);
1451 #ifdef OPENSSL_HAS_ECC
1452 if (key_type_plain(type) == KEY_ECDSA)
1453 nid = key_ecdsa_nid_from_name(ktype);
1458 (void)buffer_get_string_ptr_ret(&b, NULL); /* Skip nonce */
1461 case KEY_RSA_CERT_V00:
1462 key = key_new(type);
1463 if (buffer_get_bignum2_ret(&b, key->rsa->e) == -1 ||
1464 buffer_get_bignum2_ret(&b, key->rsa->n) == -1) {
1465 error("key_from_blob: can't read rsa key");
1472 RSA_print_fp(stderr, key->rsa, 8);
1476 (void)buffer_get_string_ptr_ret(&b, NULL); /* Skip nonce */
1479 case KEY_DSA_CERT_V00:
1480 key = key_new(type);
1481 if (buffer_get_bignum2_ret(&b, key->dsa->p) == -1 ||
1482 buffer_get_bignum2_ret(&b, key->dsa->q) == -1 ||
1483 buffer_get_bignum2_ret(&b, key->dsa->g) == -1 ||
1484 buffer_get_bignum2_ret(&b, key->dsa->pub_key) == -1) {
1485 error("key_from_blob: can't read dsa key");
1489 DSA_print_fp(stderr, key->dsa, 8);
1492 #ifdef OPENSSL_HAS_ECC
1493 case KEY_ECDSA_CERT:
1494 (void)buffer_get_string_ptr_ret(&b, NULL); /* Skip nonce */
1497 key = key_new(type);
1498 key->ecdsa_nid = nid;
1499 if ((curve = buffer_get_string_ret(&b, NULL)) == NULL) {
1500 error("key_from_blob: can't read ecdsa curve");
1503 if (key->ecdsa_nid != key_curve_name_to_nid(curve)) {
1504 error("key_from_blob: ecdsa curve doesn't match type");
1507 if (key->ecdsa != NULL)
1508 EC_KEY_free(key->ecdsa);
1509 if ((key->ecdsa = EC_KEY_new_by_curve_name(key->ecdsa_nid))
1511 fatal("key_from_blob: EC_KEY_new_by_curve_name failed");
1512 if ((q = EC_POINT_new(EC_KEY_get0_group(key->ecdsa))) == NULL)
1513 fatal("key_from_blob: EC_POINT_new failed");
1514 if (buffer_get_ecpoint_ret(&b, EC_KEY_get0_group(key->ecdsa),
1516 error("key_from_blob: can't read ecdsa key point");
1519 if (key_ec_validate_public(EC_KEY_get0_group(key->ecdsa),
1522 if (EC_KEY_set_public_key(key->ecdsa, q) != 1)
1523 fatal("key_from_blob: EC_KEY_set_public_key failed");
1525 key_dump_ec_point(EC_KEY_get0_group(key->ecdsa), q);
1528 #endif /* OPENSSL_HAS_ECC */
1530 key = key_new(type);
1533 error("key_from_blob: cannot handle type %s", ktype);
1536 if (key_is_cert(key) && cert_parse(&b, key, blob, blen) == -1) {
1537 error("key_from_blob: can't parse cert data");
1540 rlen = buffer_len(&b);
1541 if (key != NULL && rlen != 0)
1542 error("key_from_blob: remaining bytes in key blob %d", rlen);
1546 #ifdef OPENSSL_HAS_ECC
1555 to_blob(const Key *key, u_char **blobp, u_int *lenp, int force_plain)
1561 error("key_to_blob: key == NULL");
1565 type = force_plain ? key_type_plain(key->type) : key->type;
1567 case KEY_DSA_CERT_V00:
1568 case KEY_RSA_CERT_V00:
1570 case KEY_ECDSA_CERT:
1572 /* Use the existing blob */
1573 buffer_append(&b, buffer_ptr(&key->cert->certblob),
1574 buffer_len(&key->cert->certblob));
1577 buffer_put_cstring(&b,
1578 key_ssh_name_from_type_nid(type, key->ecdsa_nid));
1579 buffer_put_bignum2(&b, key->dsa->p);
1580 buffer_put_bignum2(&b, key->dsa->q);
1581 buffer_put_bignum2(&b, key->dsa->g);
1582 buffer_put_bignum2(&b, key->dsa->pub_key);
1584 #ifdef OPENSSL_HAS_ECC
1586 buffer_put_cstring(&b,
1587 key_ssh_name_from_type_nid(type, key->ecdsa_nid));
1588 buffer_put_cstring(&b, key_curve_nid_to_name(key->ecdsa_nid));
1589 buffer_put_ecpoint(&b, EC_KEY_get0_group(key->ecdsa),
1590 EC_KEY_get0_public_key(key->ecdsa));
1594 buffer_put_cstring(&b,
1595 key_ssh_name_from_type_nid(type, key->ecdsa_nid));
1596 buffer_put_bignum2(&b, key->rsa->e);
1597 buffer_put_bignum2(&b, key->rsa->n);
1600 error("key_to_blob: unsupported key type %d", key->type);
1604 len = buffer_len(&b);
1607 if (blobp != NULL) {
1608 *blobp = xmalloc(len);
1609 memcpy(*blobp, buffer_ptr(&b), len);
1611 memset(buffer_ptr(&b), 0, len);
1617 key_to_blob(const Key *key, u_char **blobp, u_int *lenp)
1619 return to_blob(key, blobp, lenp, 0);
1625 u_char **sigp, u_int *lenp,
1626 const u_char *data, u_int datalen)
1628 switch (key->type) {
1629 case KEY_DSA_CERT_V00:
1632 return ssh_dss_sign(key, sigp, lenp, data, datalen);
1633 #ifdef OPENSSL_HAS_ECC
1634 case KEY_ECDSA_CERT:
1636 return ssh_ecdsa_sign(key, sigp, lenp, data, datalen);
1638 case KEY_RSA_CERT_V00:
1641 return ssh_rsa_sign(key, sigp, lenp, data, datalen);
1643 error("key_sign: invalid key type %d", key->type);
1649 * key_verify returns 1 for a correct signature, 0 for an incorrect signature
1655 const u_char *signature, u_int signaturelen,
1656 const u_char *data, u_int datalen)
1658 if (signaturelen == 0)
1661 switch (key->type) {
1662 case KEY_DSA_CERT_V00:
1665 return ssh_dss_verify(key, signature, signaturelen, data, datalen);
1666 #ifdef OPENSSL_HAS_ECC
1667 case KEY_ECDSA_CERT:
1669 return ssh_ecdsa_verify(key, signature, signaturelen, data, datalen);
1671 case KEY_RSA_CERT_V00:
1674 return ssh_rsa_verify(key, signature, signaturelen, data, datalen);
1676 error("key_verify: invalid key type %d", key->type);
1681 /* Converts a private to a public key */
1683 key_demote(const Key *k)
1687 pk = xcalloc(1, sizeof(*pk));
1689 pk->flags = k->flags;
1690 pk->ecdsa_nid = k->ecdsa_nid;
1696 case KEY_RSA_CERT_V00:
1698 key_cert_copy(k, pk);
1702 if ((pk->rsa = RSA_new()) == NULL)
1703 fatal("key_demote: RSA_new failed");
1704 if ((pk->rsa->e = BN_dup(k->rsa->e)) == NULL)
1705 fatal("key_demote: BN_dup failed");
1706 if ((pk->rsa->n = BN_dup(k->rsa->n)) == NULL)
1707 fatal("key_demote: BN_dup failed");
1709 case KEY_DSA_CERT_V00:
1711 key_cert_copy(k, pk);
1714 if ((pk->dsa = DSA_new()) == NULL)
1715 fatal("key_demote: DSA_new failed");
1716 if ((pk->dsa->p = BN_dup(k->dsa->p)) == NULL)
1717 fatal("key_demote: BN_dup failed");
1718 if ((pk->dsa->q = BN_dup(k->dsa->q)) == NULL)
1719 fatal("key_demote: BN_dup failed");
1720 if ((pk->dsa->g = BN_dup(k->dsa->g)) == NULL)
1721 fatal("key_demote: BN_dup failed");
1722 if ((pk->dsa->pub_key = BN_dup(k->dsa->pub_key)) == NULL)
1723 fatal("key_demote: BN_dup failed");
1725 #ifdef OPENSSL_HAS_ECC
1726 case KEY_ECDSA_CERT:
1727 key_cert_copy(k, pk);
1730 if ((pk->ecdsa = EC_KEY_new_by_curve_name(pk->ecdsa_nid)) == NULL)
1731 fatal("key_demote: EC_KEY_new_by_curve_name failed");
1732 if (EC_KEY_set_public_key(pk->ecdsa,
1733 EC_KEY_get0_public_key(k->ecdsa)) != 1)
1734 fatal("key_demote: EC_KEY_set_public_key failed");
1738 fatal("key_free: bad key type %d", k->type);
1746 key_is_cert(const Key *k)
1751 case KEY_RSA_CERT_V00:
1752 case KEY_DSA_CERT_V00:
1755 case KEY_ECDSA_CERT:
1762 /* Return the cert-less equivalent to a certified key type */
1764 key_type_plain(int type)
1767 case KEY_RSA_CERT_V00:
1770 case KEY_DSA_CERT_V00:
1773 case KEY_ECDSA_CERT:
1780 /* Convert a KEY_RSA or KEY_DSA to their _CERT equivalent */
1782 key_to_certified(Key *k, int legacy)
1786 k->cert = cert_new();
1787 k->type = legacy ? KEY_RSA_CERT_V00 : KEY_RSA_CERT;
1790 k->cert = cert_new();
1791 k->type = legacy ? KEY_DSA_CERT_V00 : KEY_DSA_CERT;
1795 fatal("%s: legacy ECDSA certificates are not supported",
1797 k->cert = cert_new();
1798 k->type = KEY_ECDSA_CERT;
1801 error("%s: key has incorrect type %s", __func__, key_type(k));
1806 /* Convert a KEY_RSA_CERT or KEY_DSA_CERT to their raw key equivalent */
1808 key_drop_cert(Key *k)
1811 case KEY_RSA_CERT_V00:
1816 case KEY_DSA_CERT_V00:
1821 case KEY_ECDSA_CERT:
1823 k->type = KEY_ECDSA;
1826 error("%s: key has incorrect type %s", __func__, key_type(k));
1832 * Sign a KEY_RSA_CERT, KEY_DSA_CERT or KEY_ECDSA_CERT, (re-)generating
1833 * the signed certblob
1836 key_certify(Key *k, Key *ca)
1839 u_char *ca_blob, *sig_blob, nonce[32];
1840 u_int i, ca_len, sig_len;
1842 if (k->cert == NULL) {
1843 error("%s: key lacks cert info", __func__);
1847 if (!key_is_cert(k)) {
1848 error("%s: certificate has unknown type %d", __func__,
1853 if (ca->type != KEY_RSA && ca->type != KEY_DSA &&
1854 ca->type != KEY_ECDSA) {
1855 error("%s: CA key has unsupported type %s", __func__,
1860 key_to_blob(ca, &ca_blob, &ca_len);
1862 buffer_clear(&k->cert->certblob);
1863 buffer_put_cstring(&k->cert->certblob, key_ssh_name(k));
1865 /* -v01 certs put nonce first */
1866 arc4random_buf(&nonce, sizeof(nonce));
1867 if (!key_cert_is_legacy(k))
1868 buffer_put_string(&k->cert->certblob, nonce, sizeof(nonce));
1871 case KEY_DSA_CERT_V00:
1873 buffer_put_bignum2(&k->cert->certblob, k->dsa->p);
1874 buffer_put_bignum2(&k->cert->certblob, k->dsa->q);
1875 buffer_put_bignum2(&k->cert->certblob, k->dsa->g);
1876 buffer_put_bignum2(&k->cert->certblob, k->dsa->pub_key);
1878 #ifdef OPENSSL_HAS_ECC
1879 case KEY_ECDSA_CERT:
1880 buffer_put_cstring(&k->cert->certblob,
1881 key_curve_nid_to_name(k->ecdsa_nid));
1882 buffer_put_ecpoint(&k->cert->certblob,
1883 EC_KEY_get0_group(k->ecdsa),
1884 EC_KEY_get0_public_key(k->ecdsa));
1887 case KEY_RSA_CERT_V00:
1889 buffer_put_bignum2(&k->cert->certblob, k->rsa->e);
1890 buffer_put_bignum2(&k->cert->certblob, k->rsa->n);
1893 error("%s: key has incorrect type %s", __func__, key_type(k));
1894 buffer_clear(&k->cert->certblob);
1899 /* -v01 certs have a serial number next */
1900 if (!key_cert_is_legacy(k))
1901 buffer_put_int64(&k->cert->certblob, k->cert->serial);
1903 buffer_put_int(&k->cert->certblob, k->cert->type);
1904 buffer_put_cstring(&k->cert->certblob, k->cert->key_id);
1906 buffer_init(&principals);
1907 for (i = 0; i < k->cert->nprincipals; i++)
1908 buffer_put_cstring(&principals, k->cert->principals[i]);
1909 buffer_put_string(&k->cert->certblob, buffer_ptr(&principals),
1910 buffer_len(&principals));
1911 buffer_free(&principals);
1913 buffer_put_int64(&k->cert->certblob, k->cert->valid_after);
1914 buffer_put_int64(&k->cert->certblob, k->cert->valid_before);
1915 buffer_put_string(&k->cert->certblob,
1916 buffer_ptr(&k->cert->critical), buffer_len(&k->cert->critical));
1918 /* -v01 certs have non-critical options here */
1919 if (!key_cert_is_legacy(k)) {
1920 buffer_put_string(&k->cert->certblob,
1921 buffer_ptr(&k->cert->extensions),
1922 buffer_len(&k->cert->extensions));
1925 /* -v00 certs put the nonce at the end */
1926 if (key_cert_is_legacy(k))
1927 buffer_put_string(&k->cert->certblob, nonce, sizeof(nonce));
1929 buffer_put_string(&k->cert->certblob, NULL, 0); /* reserved */
1930 buffer_put_string(&k->cert->certblob, ca_blob, ca_len);
1933 /* Sign the whole mess */
1934 if (key_sign(ca, &sig_blob, &sig_len, buffer_ptr(&k->cert->certblob),
1935 buffer_len(&k->cert->certblob)) != 0) {
1936 error("%s: signature operation failed", __func__);
1937 buffer_clear(&k->cert->certblob);
1940 /* Append signature and we are done */
1941 buffer_put_string(&k->cert->certblob, sig_blob, sig_len);
1948 key_cert_check_authority(const Key *k, int want_host, int require_principal,
1949 const char *name, const char **reason)
1951 u_int i, principal_matches;
1952 time_t now = time(NULL);
1955 if (k->cert->type != SSH2_CERT_TYPE_HOST) {
1956 *reason = "Certificate invalid: not a host certificate";
1960 if (k->cert->type != SSH2_CERT_TYPE_USER) {
1961 *reason = "Certificate invalid: not a user certificate";
1966 error("%s: system clock lies before epoch", __func__);
1967 *reason = "Certificate invalid: not yet valid";
1970 if ((u_int64_t)now < k->cert->valid_after) {
1971 *reason = "Certificate invalid: not yet valid";
1974 if ((u_int64_t)now >= k->cert->valid_before) {
1975 *reason = "Certificate invalid: expired";
1978 if (k->cert->nprincipals == 0) {
1979 if (require_principal) {
1980 *reason = "Certificate lacks principal list";
1983 } else if (name != NULL) {
1984 principal_matches = 0;
1985 for (i = 0; i < k->cert->nprincipals; i++) {
1986 if (strcmp(name, k->cert->principals[i]) == 0) {
1987 principal_matches = 1;
1991 if (!principal_matches) {
1992 *reason = "Certificate invalid: name is not a listed "
2001 key_cert_is_legacy(const Key *k)
2004 case KEY_DSA_CERT_V00:
2005 case KEY_RSA_CERT_V00:
2012 /* XXX: these are really begging for a table-driven approach */
2014 key_curve_name_to_nid(const char *name)
2016 #ifdef OPENSSL_HAS_ECC
2017 if (strcmp(name, "nistp256") == 0)
2018 return NID_X9_62_prime256v1;
2019 else if (strcmp(name, "nistp384") == 0)
2020 return NID_secp384r1;
2021 else if (strcmp(name, "nistp521") == 0)
2022 return NID_secp521r1;
2025 debug("%s: unsupported EC curve name \"%.100s\"", __func__, name);
2030 key_curve_nid_to_bits(int nid)
2033 #ifdef OPENSSL_HAS_ECC
2034 case NID_X9_62_prime256v1:
2042 error("%s: unsupported EC curve nid %d", __func__, nid);
2048 key_curve_nid_to_name(int nid)
2050 #ifdef OPENSSL_HAS_ECC
2051 if (nid == NID_X9_62_prime256v1)
2053 else if (nid == NID_secp384r1)
2055 else if (nid == NID_secp521r1)
2058 error("%s: unsupported EC curve nid %d", __func__, nid);
2062 #ifdef OPENSSL_HAS_ECC
2064 key_ec_nid_to_evpmd(int nid)
2066 int kbits = key_curve_nid_to_bits(nid);
2069 fatal("%s: invalid nid %d", __func__, nid);
2070 /* RFC5656 section 6.2.1 */
2072 return EVP_sha256();
2073 else if (kbits <= 384)
2074 return EVP_sha384();
2076 return EVP_sha512();
2080 key_ec_validate_public(const EC_GROUP *group, const EC_POINT *public)
2083 EC_POINT *nq = NULL;
2084 BIGNUM *order, *x, *y, *tmp;
2087 if ((bnctx = BN_CTX_new()) == NULL)
2088 fatal("%s: BN_CTX_new failed", __func__);
2089 BN_CTX_start(bnctx);
2092 * We shouldn't ever hit this case because bignum_get_ecpoint()
2093 * refuses to load GF2m points.
2095 if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) !=
2096 NID_X9_62_prime_field) {
2097 error("%s: group is not a prime field", __func__);
2102 if (EC_POINT_is_at_infinity(group, public)) {
2103 error("%s: received degenerate public key (infinity)",
2108 if ((x = BN_CTX_get(bnctx)) == NULL ||
2109 (y = BN_CTX_get(bnctx)) == NULL ||
2110 (order = BN_CTX_get(bnctx)) == NULL ||
2111 (tmp = BN_CTX_get(bnctx)) == NULL)
2112 fatal("%s: BN_CTX_get failed", __func__);
2114 /* log2(x) > log2(order)/2, log2(y) > log2(order)/2 */
2115 if (EC_GROUP_get_order(group, order, bnctx) != 1)
2116 fatal("%s: EC_GROUP_get_order failed", __func__);
2117 if (EC_POINT_get_affine_coordinates_GFp(group, public,
2119 fatal("%s: EC_POINT_get_affine_coordinates_GFp", __func__);
2120 if (BN_num_bits(x) <= BN_num_bits(order) / 2) {
2121 error("%s: public key x coordinate too small: "
2122 "bits(x) = %d, bits(order)/2 = %d", __func__,
2123 BN_num_bits(x), BN_num_bits(order) / 2);
2126 if (BN_num_bits(y) <= BN_num_bits(order) / 2) {
2127 error("%s: public key y coordinate too small: "
2128 "bits(y) = %d, bits(order)/2 = %d", __func__,
2129 BN_num_bits(x), BN_num_bits(order) / 2);
2133 /* nQ == infinity (n == order of subgroup) */
2134 if ((nq = EC_POINT_new(group)) == NULL)
2135 fatal("%s: BN_CTX_tmp failed", __func__);
2136 if (EC_POINT_mul(group, nq, NULL, public, order, bnctx) != 1)
2137 fatal("%s: EC_GROUP_mul failed", __func__);
2138 if (EC_POINT_is_at_infinity(group, nq) != 1) {
2139 error("%s: received degenerate public key (nQ != infinity)",
2144 /* x < order - 1, y < order - 1 */
2145 if (!BN_sub(tmp, order, BN_value_one()))
2146 fatal("%s: BN_sub failed", __func__);
2147 if (BN_cmp(x, tmp) >= 0) {
2148 error("%s: public key x coordinate >= group order - 1",
2152 if (BN_cmp(y, tmp) >= 0) {
2153 error("%s: public key y coordinate >= group order - 1",
2165 key_ec_validate_private(const EC_KEY *key)
2168 BIGNUM *order, *tmp;
2171 if ((bnctx = BN_CTX_new()) == NULL)
2172 fatal("%s: BN_CTX_new failed", __func__);
2173 BN_CTX_start(bnctx);
2175 if ((order = BN_CTX_get(bnctx)) == NULL ||
2176 (tmp = BN_CTX_get(bnctx)) == NULL)
2177 fatal("%s: BN_CTX_get failed", __func__);
2179 /* log2(private) > log2(order)/2 */
2180 if (EC_GROUP_get_order(EC_KEY_get0_group(key), order, bnctx) != 1)
2181 fatal("%s: EC_GROUP_get_order failed", __func__);
2182 if (BN_num_bits(EC_KEY_get0_private_key(key)) <=
2183 BN_num_bits(order) / 2) {
2184 error("%s: private key too small: "
2185 "bits(y) = %d, bits(order)/2 = %d", __func__,
2186 BN_num_bits(EC_KEY_get0_private_key(key)),
2187 BN_num_bits(order) / 2);
2191 /* private < order - 1 */
2192 if (!BN_sub(tmp, order, BN_value_one()))
2193 fatal("%s: BN_sub failed", __func__);
2194 if (BN_cmp(EC_KEY_get0_private_key(key), tmp) >= 0) {
2195 error("%s: private key >= group order - 1", __func__);
2204 #if defined(DEBUG_KEXECDH) || defined(DEBUG_PK)
2206 key_dump_ec_point(const EC_GROUP *group, const EC_POINT *point)
2211 if (point == NULL) {
2212 fputs("point=(NULL)\n", stderr);
2215 if ((bnctx = BN_CTX_new()) == NULL)
2216 fatal("%s: BN_CTX_new failed", __func__);
2217 BN_CTX_start(bnctx);
2218 if ((x = BN_CTX_get(bnctx)) == NULL || (y = BN_CTX_get(bnctx)) == NULL)
2219 fatal("%s: BN_CTX_get failed", __func__);
2220 if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) !=
2221 NID_X9_62_prime_field)
2222 fatal("%s: group is not a prime field", __func__);
2223 if (EC_POINT_get_affine_coordinates_GFp(group, point, x, y, bnctx) != 1)
2224 fatal("%s: EC_POINT_get_affine_coordinates_GFp", __func__);
2225 fputs("x=", stderr);
2226 BN_print_fp(stderr, x);
2227 fputs("\ny=", stderr);
2228 BN_print_fp(stderr, y);
2229 fputs("\n", stderr);
2234 key_dump_ec_key(const EC_KEY *key)
2236 const BIGNUM *exponent;
2238 key_dump_ec_point(EC_KEY_get0_group(key), EC_KEY_get0_public_key(key));
2239 fputs("exponent=", stderr);
2240 if ((exponent = EC_KEY_get0_private_key(key)) == NULL)
2241 fputs("(NULL)", stderr);
2243 BN_print_fp(stderr, EC_KEY_get0_private_key(key));
2244 fputs("\n", stderr);
2246 #endif /* defined(DEBUG_KEXECDH) || defined(DEBUG_PK) */
2247 #endif /* OPENSSL_HAS_ECC */