1 /* $OpenBSD: key.c,v 1.100 2013/01/17 23:00:01 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);
190 if (cert->key_id != NULL)
192 for (i = 0; i < cert->nprincipals; i++)
193 xfree(cert->principals[i]);
194 if (cert->principals != NULL)
195 xfree(cert->principals);
196 if (cert->signature_key != NULL)
197 key_free(cert->signature_key);
204 fatal("key_free: key is NULL");
208 case KEY_RSA_CERT_V00:
215 case KEY_DSA_CERT_V00:
221 #ifdef OPENSSL_HAS_ECC
224 if (k->ecdsa != NULL)
225 EC_KEY_free(k->ecdsa);
232 fatal("key_free: bad key type %d", k->type);
235 if (key_is_cert(k)) {
245 cert_compare(struct KeyCert *a, struct KeyCert *b)
247 if (a == NULL && b == NULL)
249 if (a == NULL || b == NULL)
251 if (buffer_len(&a->certblob) != buffer_len(&b->certblob))
253 if (timingsafe_bcmp(buffer_ptr(&a->certblob), buffer_ptr(&b->certblob),
254 buffer_len(&a->certblob)) != 0)
260 * Compare public portions of key only, allowing comparisons between
261 * certificates and plain keys too.
264 key_equal_public(const Key *a, const Key *b)
266 #ifdef OPENSSL_HAS_ECC
270 if (a == NULL || b == NULL ||
271 key_type_plain(a->type) != key_type_plain(b->type))
276 case KEY_RSA_CERT_V00:
279 return a->rsa != NULL && b->rsa != NULL &&
280 BN_cmp(a->rsa->e, b->rsa->e) == 0 &&
281 BN_cmp(a->rsa->n, b->rsa->n) == 0;
282 case KEY_DSA_CERT_V00:
285 return a->dsa != NULL && b->dsa != NULL &&
286 BN_cmp(a->dsa->p, b->dsa->p) == 0 &&
287 BN_cmp(a->dsa->q, b->dsa->q) == 0 &&
288 BN_cmp(a->dsa->g, b->dsa->g) == 0 &&
289 BN_cmp(a->dsa->pub_key, b->dsa->pub_key) == 0;
290 #ifdef OPENSSL_HAS_ECC
293 if (a->ecdsa == NULL || b->ecdsa == NULL ||
294 EC_KEY_get0_public_key(a->ecdsa) == NULL ||
295 EC_KEY_get0_public_key(b->ecdsa) == NULL)
297 if ((bnctx = BN_CTX_new()) == NULL)
298 fatal("%s: BN_CTX_new failed", __func__);
299 if (EC_GROUP_cmp(EC_KEY_get0_group(a->ecdsa),
300 EC_KEY_get0_group(b->ecdsa), bnctx) != 0 ||
301 EC_POINT_cmp(EC_KEY_get0_group(a->ecdsa),
302 EC_KEY_get0_public_key(a->ecdsa),
303 EC_KEY_get0_public_key(b->ecdsa), bnctx) != 0) {
309 #endif /* OPENSSL_HAS_ECC */
311 fatal("key_equal: bad key type %d", a->type);
317 key_equal(const Key *a, const Key *b)
319 if (a == NULL || b == NULL || a->type != b->type)
321 if (key_is_cert(a)) {
322 if (!cert_compare(a->cert, b->cert))
325 return key_equal_public(a, b);
329 key_fingerprint_raw(const Key *k, enum fp_type dgst_type,
330 u_int *dgst_raw_length)
332 const EVP_MD *md = NULL;
335 u_char *retval = NULL;
339 *dgst_raw_length = 0;
348 #ifdef HAVE_EVP_SHA256
354 fatal("key_fingerprint_raw: bad digest type %d",
359 nlen = BN_num_bytes(k->rsa->n);
360 elen = BN_num_bytes(k->rsa->e);
363 BN_bn2bin(k->rsa->n, blob);
364 BN_bn2bin(k->rsa->e, blob + nlen);
369 key_to_blob(k, &blob, &len);
371 case KEY_DSA_CERT_V00:
372 case KEY_RSA_CERT_V00:
376 /* We want a fingerprint of the _key_ not of the cert */
377 to_blob(k, &blob, &len, 1);
382 fatal("key_fingerprint_raw: bad key type %d", k->type);
386 retval = xmalloc(EVP_MAX_MD_SIZE);
387 EVP_DigestInit(&ctx, md);
388 EVP_DigestUpdate(&ctx, blob, len);
389 EVP_DigestFinal(&ctx, retval, dgst_raw_length);
390 memset(blob, 0, len);
393 fatal("key_fingerprint_raw: blob is null");
399 key_fingerprint_hex(u_char *dgst_raw, u_int dgst_raw_len)
404 retval = xcalloc(1, dgst_raw_len * 3 + 1);
405 for (i = 0; i < dgst_raw_len; i++) {
407 snprintf(hex, sizeof(hex), "%02x:", dgst_raw[i]);
408 strlcat(retval, hex, dgst_raw_len * 3 + 1);
411 /* Remove the trailing ':' character */
412 retval[(dgst_raw_len * 3) - 1] = '\0';
417 key_fingerprint_bubblebabble(u_char *dgst_raw, u_int dgst_raw_len)
419 char vowels[] = { 'a', 'e', 'i', 'o', 'u', 'y' };
420 char consonants[] = { 'b', 'c', 'd', 'f', 'g', 'h', 'k', 'l', 'm',
421 'n', 'p', 'r', 's', 't', 'v', 'z', 'x' };
422 u_int i, j = 0, rounds, seed = 1;
425 rounds = (dgst_raw_len / 2) + 1;
426 retval = xcalloc((rounds * 6), sizeof(char));
428 for (i = 0; i < rounds; i++) {
429 u_int idx0, idx1, idx2, idx3, idx4;
430 if ((i + 1 < rounds) || (dgst_raw_len % 2 != 0)) {
431 idx0 = (((((u_int)(dgst_raw[2 * i])) >> 6) & 3) +
433 idx1 = (((u_int)(dgst_raw[2 * i])) >> 2) & 15;
434 idx2 = ((((u_int)(dgst_raw[2 * i])) & 3) +
436 retval[j++] = vowels[idx0];
437 retval[j++] = consonants[idx1];
438 retval[j++] = vowels[idx2];
439 if ((i + 1) < rounds) {
440 idx3 = (((u_int)(dgst_raw[(2 * i) + 1])) >> 4) & 15;
441 idx4 = (((u_int)(dgst_raw[(2 * i) + 1]))) & 15;
442 retval[j++] = consonants[idx3];
444 retval[j++] = consonants[idx4];
446 ((((u_int)(dgst_raw[2 * i])) * 7) +
447 ((u_int)(dgst_raw[(2 * i) + 1])))) % 36;
453 retval[j++] = vowels[idx0];
454 retval[j++] = consonants[idx1];
455 retval[j++] = vowels[idx2];
464 * Draw an ASCII-Art representing the fingerprint so human brain can
465 * profit from its built-in pattern recognition ability.
466 * This technique is called "random art" and can be found in some
467 * scientific publications like this original paper:
469 * "Hash Visualization: a New Technique to improve Real-World Security",
470 * Perrig A. and Song D., 1999, International Workshop on Cryptographic
471 * Techniques and E-Commerce (CrypTEC '99)
472 * sparrow.ece.cmu.edu/~adrian/projects/validation/validation.pdf
474 * The subject came up in a talk by Dan Kaminsky, too.
476 * If you see the picture is different, the key is different.
477 * If the picture looks the same, you still know nothing.
479 * The algorithm used here is a worm crawling over a discrete plane,
480 * leaving a trace (augmenting the field) everywhere it goes.
481 * Movement is taken from dgst_raw 2bit-wise. Bumping into walls
482 * makes the respective movement vector be ignored for this turn.
483 * Graphs are not unambiguous, because circles in graphs can be
484 * walked in either direction.
488 * Field sizes for the random art. Have to be odd, so the starting point
489 * can be in the exact middle of the picture, and FLDBASE should be >=8 .
490 * Else pictures would be too dense, and drawing the frame would
491 * fail, too, because the key type would not fit in anymore.
494 #define FLDSIZE_Y (FLDBASE + 1)
495 #define FLDSIZE_X (FLDBASE * 2 + 1)
497 key_fingerprint_randomart(u_char *dgst_raw, u_int dgst_raw_len, const Key *k)
500 * Chars to be used after each other every time the worm
501 * intersects with itself. Matter of taste.
503 char *augmentation_string = " .o+=*BOX@%&#/^SE";
505 u_char field[FLDSIZE_X][FLDSIZE_Y];
508 size_t len = strlen(augmentation_string) - 1;
510 retval = xcalloc(1, (FLDSIZE_X + 3) * (FLDSIZE_Y + 2));
512 /* initialize field */
513 memset(field, 0, FLDSIZE_X * FLDSIZE_Y * sizeof(char));
517 /* process raw key */
518 for (i = 0; i < dgst_raw_len; i++) {
520 /* each byte conveys four 2-bit move commands */
522 for (b = 0; b < 4; b++) {
523 /* evaluate 2 bit, rest is shifted later */
524 x += (input & 0x1) ? 1 : -1;
525 y += (input & 0x2) ? 1 : -1;
527 /* assure we are still in bounds */
530 x = MIN(x, FLDSIZE_X - 1);
531 y = MIN(y, FLDSIZE_Y - 1);
533 /* augment the field */
534 if (field[x][y] < len - 2)
540 /* mark starting point and end point*/
541 field[FLDSIZE_X / 2][FLDSIZE_Y / 2] = len - 1;
545 snprintf(retval, FLDSIZE_X, "+--[%4s %4u]", key_type(k), key_size(k));
546 p = strchr(retval, '\0');
548 /* output upper border */
549 for (i = p - retval - 1; i < FLDSIZE_X; i++)
555 for (y = 0; y < FLDSIZE_Y; y++) {
557 for (x = 0; x < FLDSIZE_X; x++)
558 *p++ = augmentation_string[MIN(field[x][y], len)];
563 /* output lower border */
565 for (i = 0; i < FLDSIZE_X; i++)
573 key_fingerprint(Key *k, enum fp_type dgst_type, enum fp_rep dgst_rep)
579 dgst_raw = key_fingerprint_raw(k, dgst_type, &dgst_raw_len);
581 fatal("key_fingerprint: null from key_fingerprint_raw()");
584 retval = key_fingerprint_hex(dgst_raw, dgst_raw_len);
586 case SSH_FP_BUBBLEBABBLE:
587 retval = key_fingerprint_bubblebabble(dgst_raw, dgst_raw_len);
589 case SSH_FP_RANDOMART:
590 retval = key_fingerprint_randomart(dgst_raw, dgst_raw_len, k);
593 fatal("key_fingerprint: bad digest representation %d",
597 memset(dgst_raw, 0, dgst_raw_len);
603 * Reads a multiple-precision integer in decimal from the buffer, and advances
604 * the pointer. The integer must already be initialized. This function is
605 * permitted to modify the buffer. This leaves *cpp to point just beyond the
606 * last processed (and maybe modified) character. Note that this may modify
607 * the buffer containing the number.
610 read_bignum(char **cpp, BIGNUM * value)
615 /* Skip any leading whitespace. */
616 for (; *cp == ' ' || *cp == '\t'; cp++)
619 /* Check that it begins with a decimal digit. */
620 if (*cp < '0' || *cp > '9')
623 /* Save starting position. */
626 /* Move forward until all decimal digits skipped. */
627 for (; *cp >= '0' && *cp <= '9'; cp++)
630 /* Save the old terminating character, and replace it by \0. */
634 /* Parse the number. */
635 if (BN_dec2bn(&value, *cpp) == 0)
638 /* Restore old terminating character. */
641 /* Move beyond the number and return success. */
647 write_bignum(FILE *f, BIGNUM *num)
649 char *buf = BN_bn2dec(num);
651 error("write_bignum: BN_bn2dec() failed");
654 fprintf(f, " %s", buf);
659 /* returns 1 ok, -1 error */
661 key_read(Key *ret, char **cpp)
669 #ifdef OPENSSL_HAS_ECC
677 /* Get number of bits. */
678 if (*cp < '0' || *cp > '9')
679 return -1; /* Bad bit count... */
680 for (bits = 0; *cp >= '0' && *cp <= '9'; cp++)
681 bits = 10 * bits + *cp - '0';
685 /* Get public exponent, public modulus. */
686 if (!read_bignum(cpp, ret->rsa->e))
688 if (!read_bignum(cpp, ret->rsa->n))
690 /* validate the claimed number of bits */
691 if ((u_int)BN_num_bits(ret->rsa->n) != bits) {
692 verbose("key_read: claimed key size %d does not match "
693 "actual %d", bits, BN_num_bits(ret->rsa->n));
702 case KEY_DSA_CERT_V00:
703 case KEY_RSA_CERT_V00:
707 space = strchr(cp, ' ');
709 debug3("key_read: missing whitespace");
713 type = key_type_from_name(cp);
714 #ifdef OPENSSL_HAS_ECC
715 if (key_type_plain(type) == KEY_ECDSA &&
716 (curve_nid = key_ecdsa_nid_from_name(cp)) == -1) {
717 debug("key_read: invalid curve");
722 if (type == KEY_UNSPEC) {
723 debug3("key_read: missing keytype");
728 debug3("key_read: short string");
731 if (ret->type == KEY_UNSPEC) {
733 } else if (ret->type != type) {
734 /* is a key, but different type */
735 debug3("key_read: type mismatch");
740 n = uudecode(cp, blob, len);
742 error("key_read: uudecode %s failed", cp);
746 k = key_from_blob(blob, (u_int)n);
749 error("key_read: key_from_blob %s failed", cp);
752 if (k->type != type) {
753 error("key_read: type mismatch: encoding error");
757 #ifdef OPENSSL_HAS_ECC
758 if (key_type_plain(type) == KEY_ECDSA &&
759 curve_nid != k->ecdsa_nid) {
760 error("key_read: type mismatch: EC curve mismatch");
766 if (key_is_cert(ret)) {
767 if (!key_is_cert(k)) {
768 error("key_read: loaded key is not a cert");
772 if (ret->cert != NULL)
773 cert_free(ret->cert);
777 if (key_type_plain(ret->type) == KEY_RSA) {
778 if (ret->rsa != NULL)
783 RSA_print_fp(stderr, ret->rsa, 8);
786 if (key_type_plain(ret->type) == KEY_DSA) {
787 if (ret->dsa != NULL)
792 DSA_print_fp(stderr, ret->dsa, 8);
795 #ifdef OPENSSL_HAS_ECC
796 if (key_type_plain(ret->type) == KEY_ECDSA) {
797 if (ret->ecdsa != NULL)
798 EC_KEY_free(ret->ecdsa);
799 ret->ecdsa = k->ecdsa;
800 ret->ecdsa_nid = k->ecdsa_nid;
804 key_dump_ec_key(ret->ecdsa);
813 /* advance cp: skip whitespace and data */
814 while (*cp == ' ' || *cp == '\t')
816 while (*cp != '\0' && *cp != ' ' && *cp != '\t')
821 fatal("key_read: bad key type: %d", ret->type);
828 key_write(const Key *key, FILE *f)
835 if (key_is_cert(key)) {
836 if (key->cert == NULL) {
837 error("%s: no cert data", __func__);
840 if (buffer_len(&key->cert->certblob) == 0) {
841 error("%s: no signed certificate blob", __func__);
848 if (key->rsa == NULL)
850 /* size of modulus 'n' */
851 bits = BN_num_bits(key->rsa->n);
852 fprintf(f, "%u", bits);
853 if (write_bignum(f, key->rsa->e) &&
854 write_bignum(f, key->rsa->n))
856 error("key_write: failed for RSA key");
859 case KEY_DSA_CERT_V00:
861 if (key->dsa == NULL)
864 #ifdef OPENSSL_HAS_ECC
867 if (key->ecdsa == NULL)
872 case KEY_RSA_CERT_V00:
874 if (key->rsa == NULL)
881 key_to_blob(key, &blob, &len);
883 n = uuencode(blob, len, uu, 2*len);
885 fprintf(f, "%s %s", key_ssh_name(key), uu);
895 key_type(const Key *k)
904 #ifdef OPENSSL_HAS_ECC
908 case KEY_RSA_CERT_V00:
909 return "RSA-CERT-V00";
910 case KEY_DSA_CERT_V00:
911 return "DSA-CERT-V00";
916 #ifdef OPENSSL_HAS_ECC
925 key_cert_type(const Key *k)
927 switch (k->cert->type) {
928 case SSH2_CERT_TYPE_USER:
930 case SSH2_CERT_TYPE_HOST:
938 key_ssh_name_from_type_nid(int type, int nid)
945 case KEY_RSA_CERT_V00:
946 return "ssh-rsa-cert-v00@openssh.com";
947 case KEY_DSA_CERT_V00:
948 return "ssh-dss-cert-v00@openssh.com";
950 return "ssh-rsa-cert-v01@openssh.com";
952 return "ssh-dss-cert-v01@openssh.com";
953 #ifdef OPENSSL_HAS_ECC
956 case NID_X9_62_prime256v1:
957 return "ecdsa-sha2-nistp256";
959 return "ecdsa-sha2-nistp384";
961 return "ecdsa-sha2-nistp521";
968 case NID_X9_62_prime256v1:
969 return "ecdsa-sha2-nistp256-cert-v01@openssh.com";
971 return "ecdsa-sha2-nistp384-cert-v01@openssh.com";
973 return "ecdsa-sha2-nistp521-cert-v01@openssh.com";
978 #endif /* OPENSSL_HAS_ECC */
980 return "ssh-unknown";
984 key_ssh_name(const Key *k)
986 return key_ssh_name_from_type_nid(k->type, k->ecdsa_nid);
990 key_ssh_name_plain(const Key *k)
992 return key_ssh_name_from_type_nid(key_type_plain(k->type),
997 key_size(const Key *k)
1002 case KEY_RSA_CERT_V00:
1004 return BN_num_bits(k->rsa->n);
1006 case KEY_DSA_CERT_V00:
1008 return BN_num_bits(k->dsa->p);
1009 #ifdef OPENSSL_HAS_ECC
1011 case KEY_ECDSA_CERT:
1012 return key_curve_nid_to_bits(k->ecdsa_nid);
1019 rsa_generate_private_key(u_int bits)
1021 RSA *private = RSA_new();
1022 BIGNUM *f4 = BN_new();
1024 if (private == NULL)
1025 fatal("%s: RSA_new failed", __func__);
1027 fatal("%s: BN_new failed", __func__);
1028 if (!BN_set_word(f4, RSA_F4))
1029 fatal("%s: BN_new failed", __func__);
1030 if (!RSA_generate_key_ex(private, bits, f4, NULL))
1031 fatal("%s: key generation failed.", __func__);
1037 dsa_generate_private_key(u_int bits)
1039 DSA *private = DSA_new();
1041 if (private == NULL)
1042 fatal("%s: DSA_new failed", __func__);
1043 if (!DSA_generate_parameters_ex(private, bits, NULL, 0, NULL,
1045 fatal("%s: DSA_generate_parameters failed", __func__);
1046 if (!DSA_generate_key(private))
1047 fatal("%s: DSA_generate_key failed.", __func__);
1052 key_ecdsa_bits_to_nid(int bits)
1055 #ifdef OPENSSL_HAS_ECC
1057 return NID_X9_62_prime256v1;
1059 return NID_secp384r1;
1061 return NID_secp521r1;
1068 #ifdef OPENSSL_HAS_ECC
1070 key_ecdsa_key_to_nid(EC_KEY *k)
1074 NID_X9_62_prime256v1,
1082 const EC_GROUP *g = EC_KEY_get0_group(k);
1085 * The group may be stored in a ASN.1 encoded private key in one of two
1086 * ways: as a "named group", which is reconstituted by ASN.1 object ID
1087 * or explicit group parameters encoded into the key blob. Only the
1088 * "named group" case sets the group NID for us, but we can figure
1089 * it out for the other case by comparing against all the groups that
1092 if ((nid = EC_GROUP_get_curve_name(g)) > 0)
1094 if ((bnctx = BN_CTX_new()) == NULL)
1095 fatal("%s: BN_CTX_new() failed", __func__);
1096 for (i = 0; nids[i] != -1; i++) {
1097 if ((eg = EC_GROUP_new_by_curve_name(nids[i])) == NULL)
1098 fatal("%s: EC_GROUP_new_by_curve_name failed",
1100 if (EC_GROUP_cmp(g, eg, bnctx) == 0)
1105 debug3("%s: nid = %d", __func__, nids[i]);
1106 if (nids[i] != -1) {
1107 /* Use the group with the NID attached */
1108 EC_GROUP_set_asn1_flag(eg, OPENSSL_EC_NAMED_CURVE);
1109 if (EC_KEY_set_group(k, eg) != 1)
1110 fatal("%s: EC_KEY_set_group", __func__);
1116 ecdsa_generate_private_key(u_int bits, int *nid)
1120 if ((*nid = key_ecdsa_bits_to_nid(bits)) == -1)
1121 fatal("%s: invalid key length", __func__);
1122 if ((private = EC_KEY_new_by_curve_name(*nid)) == NULL)
1123 fatal("%s: EC_KEY_new_by_curve_name failed", __func__);
1124 if (EC_KEY_generate_key(private) != 1)
1125 fatal("%s: EC_KEY_generate_key failed", __func__);
1126 EC_KEY_set_asn1_flag(private, OPENSSL_EC_NAMED_CURVE);
1129 #endif /* OPENSSL_HAS_ECC */
1132 key_generate(int type, u_int bits)
1134 Key *k = key_new(KEY_UNSPEC);
1137 k->dsa = dsa_generate_private_key(bits);
1139 #ifdef OPENSSL_HAS_ECC
1141 k->ecdsa = ecdsa_generate_private_key(bits, &k->ecdsa_nid);
1146 k->rsa = rsa_generate_private_key(bits);
1148 case KEY_RSA_CERT_V00:
1149 case KEY_DSA_CERT_V00:
1152 fatal("key_generate: cert keys cannot be generated directly");
1154 fatal("key_generate: unknown type %d", type);
1161 key_cert_copy(const Key *from_key, struct Key *to_key)
1164 const struct KeyCert *from;
1167 if (to_key->cert != NULL) {
1168 cert_free(to_key->cert);
1169 to_key->cert = NULL;
1172 if ((from = from_key->cert) == NULL)
1175 to = to_key->cert = cert_new();
1177 buffer_append(&to->certblob, buffer_ptr(&from->certblob),
1178 buffer_len(&from->certblob));
1180 buffer_append(&to->critical,
1181 buffer_ptr(&from->critical), buffer_len(&from->critical));
1182 buffer_append(&to->extensions,
1183 buffer_ptr(&from->extensions), buffer_len(&from->extensions));
1185 to->serial = from->serial;
1186 to->type = from->type;
1187 to->key_id = from->key_id == NULL ? NULL : xstrdup(from->key_id);
1188 to->valid_after = from->valid_after;
1189 to->valid_before = from->valid_before;
1190 to->signature_key = from->signature_key == NULL ?
1191 NULL : key_from_private(from->signature_key);
1193 to->nprincipals = from->nprincipals;
1194 if (to->nprincipals > CERT_MAX_PRINCIPALS)
1195 fatal("%s: nprincipals (%u) > CERT_MAX_PRINCIPALS (%u)",
1196 __func__, to->nprincipals, CERT_MAX_PRINCIPALS);
1197 if (to->nprincipals > 0) {
1198 to->principals = xcalloc(from->nprincipals,
1199 sizeof(*to->principals));
1200 for (i = 0; i < to->nprincipals; i++)
1201 to->principals[i] = xstrdup(from->principals[i]);
1206 key_from_private(const Key *k)
1211 case KEY_DSA_CERT_V00:
1213 n = key_new(k->type);
1214 if ((BN_copy(n->dsa->p, k->dsa->p) == NULL) ||
1215 (BN_copy(n->dsa->q, k->dsa->q) == NULL) ||
1216 (BN_copy(n->dsa->g, k->dsa->g) == NULL) ||
1217 (BN_copy(n->dsa->pub_key, k->dsa->pub_key) == NULL))
1218 fatal("key_from_private: BN_copy failed");
1220 #ifdef OPENSSL_HAS_ECC
1222 case KEY_ECDSA_CERT:
1223 n = key_new(k->type);
1224 n->ecdsa_nid = k->ecdsa_nid;
1225 if ((n->ecdsa = EC_KEY_new_by_curve_name(k->ecdsa_nid)) == NULL)
1226 fatal("%s: EC_KEY_new_by_curve_name failed", __func__);
1227 if (EC_KEY_set_public_key(n->ecdsa,
1228 EC_KEY_get0_public_key(k->ecdsa)) != 1)
1229 fatal("%s: EC_KEY_set_public_key failed", __func__);
1234 case KEY_RSA_CERT_V00:
1236 n = key_new(k->type);
1237 if ((BN_copy(n->rsa->n, k->rsa->n) == NULL) ||
1238 (BN_copy(n->rsa->e, k->rsa->e) == NULL))
1239 fatal("key_from_private: BN_copy failed");
1242 fatal("key_from_private: unknown type %d", k->type);
1246 key_cert_copy(k, n);
1251 key_type_from_name(char *name)
1253 if (strcmp(name, "rsa1") == 0) {
1255 } else if (strcmp(name, "rsa") == 0) {
1257 } else if (strcmp(name, "dsa") == 0) {
1259 } else if (strcmp(name, "ssh-rsa") == 0) {
1261 } else if (strcmp(name, "ssh-dss") == 0) {
1263 #ifdef OPENSSL_HAS_ECC
1264 } else if (strcmp(name, "ecdsa") == 0 ||
1265 strcmp(name, "ecdsa-sha2-nistp256") == 0 ||
1266 strcmp(name, "ecdsa-sha2-nistp384") == 0 ||
1267 strcmp(name, "ecdsa-sha2-nistp521") == 0) {
1270 } else if (strcmp(name, "ssh-rsa-cert-v00@openssh.com") == 0) {
1271 return KEY_RSA_CERT_V00;
1272 } else if (strcmp(name, "ssh-dss-cert-v00@openssh.com") == 0) {
1273 return KEY_DSA_CERT_V00;
1274 } else if (strcmp(name, "ssh-rsa-cert-v01@openssh.com") == 0) {
1275 return KEY_RSA_CERT;
1276 } else if (strcmp(name, "ssh-dss-cert-v01@openssh.com") == 0) {
1277 return KEY_DSA_CERT;
1278 #ifdef OPENSSL_HAS_ECC
1279 } else if (strcmp(name, "ecdsa-sha2-nistp256-cert-v01@openssh.com") == 0 ||
1280 strcmp(name, "ecdsa-sha2-nistp384-cert-v01@openssh.com") == 0 ||
1281 strcmp(name, "ecdsa-sha2-nistp521-cert-v01@openssh.com") == 0) {
1282 return KEY_ECDSA_CERT;
1286 debug2("key_type_from_name: unknown key type '%s'", name);
1291 key_ecdsa_nid_from_name(const char *name)
1293 #ifdef OPENSSL_HAS_ECC
1294 if (strcmp(name, "ecdsa-sha2-nistp256") == 0 ||
1295 strcmp(name, "ecdsa-sha2-nistp256-cert-v01@openssh.com") == 0)
1296 return NID_X9_62_prime256v1;
1297 if (strcmp(name, "ecdsa-sha2-nistp384") == 0 ||
1298 strcmp(name, "ecdsa-sha2-nistp384-cert-v01@openssh.com") == 0)
1299 return NID_secp384r1;
1300 if (strcmp(name, "ecdsa-sha2-nistp521") == 0 ||
1301 strcmp(name, "ecdsa-sha2-nistp521-cert-v01@openssh.com") == 0)
1302 return NID_secp521r1;
1303 #endif /* OPENSSL_HAS_ECC */
1305 debug2("%s: unknown/non-ECDSA key type '%s'", __func__, name);
1310 key_names_valid2(const char *names)
1314 if (names == NULL || strcmp(names, "") == 0)
1316 s = cp = xstrdup(names);
1317 for ((p = strsep(&cp, ",")); p && *p != '\0';
1318 (p = strsep(&cp, ","))) {
1319 switch (key_type_from_name(p)) {
1326 debug3("key names ok: [%s]", names);
1332 cert_parse(Buffer *b, Key *key, const u_char *blob, u_int blen)
1334 u_char *principals, *critical, *exts, *sig_key, *sig;
1335 u_int signed_len, plen, clen, sklen, slen, kidlen, elen;
1339 int v00 = key->type == KEY_DSA_CERT_V00 ||
1340 key->type == KEY_RSA_CERT_V00;
1344 /* Copy the entire key blob for verification and later serialisation */
1345 buffer_append(&key->cert->certblob, blob, blen);
1347 elen = 0; /* Not touched for v00 certs */
1348 principals = exts = critical = sig_key = sig = NULL;
1349 if ((!v00 && buffer_get_int64_ret(&key->cert->serial, b) != 0) ||
1350 buffer_get_int_ret(&key->cert->type, b) != 0 ||
1351 (key->cert->key_id = buffer_get_cstring_ret(b, &kidlen)) == NULL ||
1352 (principals = buffer_get_string_ret(b, &plen)) == NULL ||
1353 buffer_get_int64_ret(&key->cert->valid_after, b) != 0 ||
1354 buffer_get_int64_ret(&key->cert->valid_before, b) != 0 ||
1355 (critical = buffer_get_string_ret(b, &clen)) == NULL ||
1356 (!v00 && (exts = buffer_get_string_ret(b, &elen)) == NULL) ||
1357 (v00 && buffer_get_string_ptr_ret(b, NULL) == NULL) || /* nonce */
1358 buffer_get_string_ptr_ret(b, NULL) == NULL || /* reserved */
1359 (sig_key = buffer_get_string_ret(b, &sklen)) == NULL) {
1360 error("%s: parse error", __func__);
1364 /* Signature is left in the buffer so we can calculate this length */
1365 signed_len = buffer_len(&key->cert->certblob) - buffer_len(b);
1367 if ((sig = buffer_get_string_ret(b, &slen)) == NULL) {
1368 error("%s: parse error", __func__);
1372 if (key->cert->type != SSH2_CERT_TYPE_USER &&
1373 key->cert->type != SSH2_CERT_TYPE_HOST) {
1374 error("Unknown certificate type %u", key->cert->type);
1378 buffer_append(&tmp, principals, plen);
1379 while (buffer_len(&tmp) > 0) {
1380 if (key->cert->nprincipals >= CERT_MAX_PRINCIPALS) {
1381 error("%s: Too many principals", __func__);
1384 if ((principal = buffer_get_cstring_ret(&tmp, &plen)) == NULL) {
1385 error("%s: Principals data invalid", __func__);
1388 key->cert->principals = xrealloc(key->cert->principals,
1389 key->cert->nprincipals + 1, sizeof(*key->cert->principals));
1390 key->cert->principals[key->cert->nprincipals++] = principal;
1395 buffer_append(&key->cert->critical, critical, clen);
1396 buffer_append(&tmp, critical, clen);
1397 /* validate structure */
1398 while (buffer_len(&tmp) != 0) {
1399 if (buffer_get_string_ptr_ret(&tmp, NULL) == NULL ||
1400 buffer_get_string_ptr_ret(&tmp, NULL) == NULL) {
1401 error("%s: critical option data invalid", __func__);
1407 buffer_append(&key->cert->extensions, exts, elen);
1408 buffer_append(&tmp, exts, elen);
1409 /* validate structure */
1410 while (buffer_len(&tmp) != 0) {
1411 if (buffer_get_string_ptr_ret(&tmp, NULL) == NULL ||
1412 buffer_get_string_ptr_ret(&tmp, NULL) == NULL) {
1413 error("%s: extension data invalid", __func__);
1419 if ((key->cert->signature_key = key_from_blob(sig_key,
1421 error("%s: Signature key invalid", __func__);
1424 if (key->cert->signature_key->type != KEY_RSA &&
1425 key->cert->signature_key->type != KEY_DSA &&
1426 key->cert->signature_key->type != KEY_ECDSA) {
1427 error("%s: Invalid signature key type %s (%d)", __func__,
1428 key_type(key->cert->signature_key),
1429 key->cert->signature_key->type);
1433 switch (key_verify(key->cert->signature_key, sig, slen,
1434 buffer_ptr(&key->cert->certblob), signed_len)) {
1437 break; /* Good signature */
1439 error("%s: Invalid signature on certificate", __func__);
1442 error("%s: Certificate signature verification failed",
1449 if (principals != NULL)
1451 if (critical != NULL)
1455 if (sig_key != NULL)
1463 key_from_blob(const u_char *blob, u_int blen)
1467 char *ktype = NULL, *curve = NULL;
1469 #ifdef OPENSSL_HAS_ECC
1475 dump_base64(stderr, blob, blen);
1478 buffer_append(&b, blob, blen);
1479 if ((ktype = buffer_get_cstring_ret(&b, NULL)) == NULL) {
1480 error("key_from_blob: can't read key type");
1484 type = key_type_from_name(ktype);
1485 #ifdef OPENSSL_HAS_ECC
1486 if (key_type_plain(type) == KEY_ECDSA)
1487 nid = key_ecdsa_nid_from_name(ktype);
1492 (void)buffer_get_string_ptr_ret(&b, NULL); /* Skip nonce */
1495 case KEY_RSA_CERT_V00:
1496 key = key_new(type);
1497 if (buffer_get_bignum2_ret(&b, key->rsa->e) == -1 ||
1498 buffer_get_bignum2_ret(&b, key->rsa->n) == -1) {
1499 error("key_from_blob: can't read rsa key");
1506 RSA_print_fp(stderr, key->rsa, 8);
1510 (void)buffer_get_string_ptr_ret(&b, NULL); /* Skip nonce */
1513 case KEY_DSA_CERT_V00:
1514 key = key_new(type);
1515 if (buffer_get_bignum2_ret(&b, key->dsa->p) == -1 ||
1516 buffer_get_bignum2_ret(&b, key->dsa->q) == -1 ||
1517 buffer_get_bignum2_ret(&b, key->dsa->g) == -1 ||
1518 buffer_get_bignum2_ret(&b, key->dsa->pub_key) == -1) {
1519 error("key_from_blob: can't read dsa key");
1523 DSA_print_fp(stderr, key->dsa, 8);
1526 #ifdef OPENSSL_HAS_ECC
1527 case KEY_ECDSA_CERT:
1528 (void)buffer_get_string_ptr_ret(&b, NULL); /* Skip nonce */
1531 key = key_new(type);
1532 key->ecdsa_nid = nid;
1533 if ((curve = buffer_get_string_ret(&b, NULL)) == NULL) {
1534 error("key_from_blob: can't read ecdsa curve");
1537 if (key->ecdsa_nid != key_curve_name_to_nid(curve)) {
1538 error("key_from_blob: ecdsa curve doesn't match type");
1541 if (key->ecdsa != NULL)
1542 EC_KEY_free(key->ecdsa);
1543 if ((key->ecdsa = EC_KEY_new_by_curve_name(key->ecdsa_nid))
1545 fatal("key_from_blob: EC_KEY_new_by_curve_name failed");
1546 if ((q = EC_POINT_new(EC_KEY_get0_group(key->ecdsa))) == NULL)
1547 fatal("key_from_blob: EC_POINT_new failed");
1548 if (buffer_get_ecpoint_ret(&b, EC_KEY_get0_group(key->ecdsa),
1550 error("key_from_blob: can't read ecdsa key point");
1553 if (key_ec_validate_public(EC_KEY_get0_group(key->ecdsa),
1556 if (EC_KEY_set_public_key(key->ecdsa, q) != 1)
1557 fatal("key_from_blob: EC_KEY_set_public_key failed");
1559 key_dump_ec_point(EC_KEY_get0_group(key->ecdsa), q);
1562 #endif /* OPENSSL_HAS_ECC */
1564 key = key_new(type);
1567 error("key_from_blob: cannot handle type %s", ktype);
1570 if (key_is_cert(key) && cert_parse(&b, key, blob, blen) == -1) {
1571 error("key_from_blob: can't parse cert data");
1574 rlen = buffer_len(&b);
1575 if (key != NULL && rlen != 0)
1576 error("key_from_blob: remaining bytes in key blob %d", rlen);
1582 #ifdef OPENSSL_HAS_ECC
1591 to_blob(const Key *key, u_char **blobp, u_int *lenp, int force_plain)
1597 error("key_to_blob: key == NULL");
1601 type = force_plain ? key_type_plain(key->type) : key->type;
1603 case KEY_DSA_CERT_V00:
1604 case KEY_RSA_CERT_V00:
1606 case KEY_ECDSA_CERT:
1608 /* Use the existing blob */
1609 buffer_append(&b, buffer_ptr(&key->cert->certblob),
1610 buffer_len(&key->cert->certblob));
1613 buffer_put_cstring(&b,
1614 key_ssh_name_from_type_nid(type, key->ecdsa_nid));
1615 buffer_put_bignum2(&b, key->dsa->p);
1616 buffer_put_bignum2(&b, key->dsa->q);
1617 buffer_put_bignum2(&b, key->dsa->g);
1618 buffer_put_bignum2(&b, key->dsa->pub_key);
1620 #ifdef OPENSSL_HAS_ECC
1622 buffer_put_cstring(&b,
1623 key_ssh_name_from_type_nid(type, key->ecdsa_nid));
1624 buffer_put_cstring(&b, key_curve_nid_to_name(key->ecdsa_nid));
1625 buffer_put_ecpoint(&b, EC_KEY_get0_group(key->ecdsa),
1626 EC_KEY_get0_public_key(key->ecdsa));
1630 buffer_put_cstring(&b,
1631 key_ssh_name_from_type_nid(type, key->ecdsa_nid));
1632 buffer_put_bignum2(&b, key->rsa->e);
1633 buffer_put_bignum2(&b, key->rsa->n);
1636 error("key_to_blob: unsupported key type %d", key->type);
1640 len = buffer_len(&b);
1643 if (blobp != NULL) {
1644 *blobp = xmalloc(len);
1645 memcpy(*blobp, buffer_ptr(&b), len);
1647 memset(buffer_ptr(&b), 0, len);
1653 key_to_blob(const Key *key, u_char **blobp, u_int *lenp)
1655 return to_blob(key, blobp, lenp, 0);
1661 u_char **sigp, u_int *lenp,
1662 const u_char *data, u_int datalen)
1664 switch (key->type) {
1665 case KEY_DSA_CERT_V00:
1668 return ssh_dss_sign(key, sigp, lenp, data, datalen);
1669 #ifdef OPENSSL_HAS_ECC
1670 case KEY_ECDSA_CERT:
1672 return ssh_ecdsa_sign(key, sigp, lenp, data, datalen);
1674 case KEY_RSA_CERT_V00:
1677 return ssh_rsa_sign(key, sigp, lenp, data, datalen);
1679 error("key_sign: invalid key type %d", key->type);
1685 * key_verify returns 1 for a correct signature, 0 for an incorrect signature
1691 const u_char *signature, u_int signaturelen,
1692 const u_char *data, u_int datalen)
1694 if (signaturelen == 0)
1697 switch (key->type) {
1698 case KEY_DSA_CERT_V00:
1701 return ssh_dss_verify(key, signature, signaturelen, data, datalen);
1702 #ifdef OPENSSL_HAS_ECC
1703 case KEY_ECDSA_CERT:
1705 return ssh_ecdsa_verify(key, signature, signaturelen, data, datalen);
1707 case KEY_RSA_CERT_V00:
1710 return ssh_rsa_verify(key, signature, signaturelen, data, datalen);
1712 error("key_verify: invalid key type %d", key->type);
1717 /* Converts a private to a public key */
1719 key_demote(const Key *k)
1723 pk = xcalloc(1, sizeof(*pk));
1725 pk->flags = k->flags;
1726 pk->ecdsa_nid = k->ecdsa_nid;
1732 case KEY_RSA_CERT_V00:
1734 key_cert_copy(k, pk);
1738 if ((pk->rsa = RSA_new()) == NULL)
1739 fatal("key_demote: RSA_new failed");
1740 if ((pk->rsa->e = BN_dup(k->rsa->e)) == NULL)
1741 fatal("key_demote: BN_dup failed");
1742 if ((pk->rsa->n = BN_dup(k->rsa->n)) == NULL)
1743 fatal("key_demote: BN_dup failed");
1745 case KEY_DSA_CERT_V00:
1747 key_cert_copy(k, pk);
1750 if ((pk->dsa = DSA_new()) == NULL)
1751 fatal("key_demote: DSA_new failed");
1752 if ((pk->dsa->p = BN_dup(k->dsa->p)) == NULL)
1753 fatal("key_demote: BN_dup failed");
1754 if ((pk->dsa->q = BN_dup(k->dsa->q)) == NULL)
1755 fatal("key_demote: BN_dup failed");
1756 if ((pk->dsa->g = BN_dup(k->dsa->g)) == NULL)
1757 fatal("key_demote: BN_dup failed");
1758 if ((pk->dsa->pub_key = BN_dup(k->dsa->pub_key)) == NULL)
1759 fatal("key_demote: BN_dup failed");
1761 #ifdef OPENSSL_HAS_ECC
1762 case KEY_ECDSA_CERT:
1763 key_cert_copy(k, pk);
1766 if ((pk->ecdsa = EC_KEY_new_by_curve_name(pk->ecdsa_nid)) == NULL)
1767 fatal("key_demote: EC_KEY_new_by_curve_name failed");
1768 if (EC_KEY_set_public_key(pk->ecdsa,
1769 EC_KEY_get0_public_key(k->ecdsa)) != 1)
1770 fatal("key_demote: EC_KEY_set_public_key failed");
1774 fatal("key_free: bad key type %d", k->type);
1782 key_is_cert(const Key *k)
1787 case KEY_RSA_CERT_V00:
1788 case KEY_DSA_CERT_V00:
1791 case KEY_ECDSA_CERT:
1798 /* Return the cert-less equivalent to a certified key type */
1800 key_type_plain(int type)
1803 case KEY_RSA_CERT_V00:
1806 case KEY_DSA_CERT_V00:
1809 case KEY_ECDSA_CERT:
1816 /* Convert a KEY_RSA or KEY_DSA to their _CERT equivalent */
1818 key_to_certified(Key *k, int legacy)
1822 k->cert = cert_new();
1823 k->type = legacy ? KEY_RSA_CERT_V00 : KEY_RSA_CERT;
1826 k->cert = cert_new();
1827 k->type = legacy ? KEY_DSA_CERT_V00 : KEY_DSA_CERT;
1831 fatal("%s: legacy ECDSA certificates are not supported",
1833 k->cert = cert_new();
1834 k->type = KEY_ECDSA_CERT;
1837 error("%s: key has incorrect type %s", __func__, key_type(k));
1842 /* Convert a KEY_RSA_CERT or KEY_DSA_CERT to their raw key equivalent */
1844 key_drop_cert(Key *k)
1847 case KEY_RSA_CERT_V00:
1852 case KEY_DSA_CERT_V00:
1857 case KEY_ECDSA_CERT:
1859 k->type = KEY_ECDSA;
1862 error("%s: key has incorrect type %s", __func__, key_type(k));
1868 * Sign a KEY_RSA_CERT, KEY_DSA_CERT or KEY_ECDSA_CERT, (re-)generating
1869 * the signed certblob
1872 key_certify(Key *k, Key *ca)
1875 u_char *ca_blob, *sig_blob, nonce[32];
1876 u_int i, ca_len, sig_len;
1878 if (k->cert == NULL) {
1879 error("%s: key lacks cert info", __func__);
1883 if (!key_is_cert(k)) {
1884 error("%s: certificate has unknown type %d", __func__,
1889 if (ca->type != KEY_RSA && ca->type != KEY_DSA &&
1890 ca->type != KEY_ECDSA) {
1891 error("%s: CA key has unsupported type %s", __func__,
1896 key_to_blob(ca, &ca_blob, &ca_len);
1898 buffer_clear(&k->cert->certblob);
1899 buffer_put_cstring(&k->cert->certblob, key_ssh_name(k));
1901 /* -v01 certs put nonce first */
1902 arc4random_buf(&nonce, sizeof(nonce));
1903 if (!key_cert_is_legacy(k))
1904 buffer_put_string(&k->cert->certblob, nonce, sizeof(nonce));
1907 case KEY_DSA_CERT_V00:
1909 buffer_put_bignum2(&k->cert->certblob, k->dsa->p);
1910 buffer_put_bignum2(&k->cert->certblob, k->dsa->q);
1911 buffer_put_bignum2(&k->cert->certblob, k->dsa->g);
1912 buffer_put_bignum2(&k->cert->certblob, k->dsa->pub_key);
1914 #ifdef OPENSSL_HAS_ECC
1915 case KEY_ECDSA_CERT:
1916 buffer_put_cstring(&k->cert->certblob,
1917 key_curve_nid_to_name(k->ecdsa_nid));
1918 buffer_put_ecpoint(&k->cert->certblob,
1919 EC_KEY_get0_group(k->ecdsa),
1920 EC_KEY_get0_public_key(k->ecdsa));
1923 case KEY_RSA_CERT_V00:
1925 buffer_put_bignum2(&k->cert->certblob, k->rsa->e);
1926 buffer_put_bignum2(&k->cert->certblob, k->rsa->n);
1929 error("%s: key has incorrect type %s", __func__, key_type(k));
1930 buffer_clear(&k->cert->certblob);
1935 /* -v01 certs have a serial number next */
1936 if (!key_cert_is_legacy(k))
1937 buffer_put_int64(&k->cert->certblob, k->cert->serial);
1939 buffer_put_int(&k->cert->certblob, k->cert->type);
1940 buffer_put_cstring(&k->cert->certblob, k->cert->key_id);
1942 buffer_init(&principals);
1943 for (i = 0; i < k->cert->nprincipals; i++)
1944 buffer_put_cstring(&principals, k->cert->principals[i]);
1945 buffer_put_string(&k->cert->certblob, buffer_ptr(&principals),
1946 buffer_len(&principals));
1947 buffer_free(&principals);
1949 buffer_put_int64(&k->cert->certblob, k->cert->valid_after);
1950 buffer_put_int64(&k->cert->certblob, k->cert->valid_before);
1951 buffer_put_string(&k->cert->certblob,
1952 buffer_ptr(&k->cert->critical), buffer_len(&k->cert->critical));
1954 /* -v01 certs have non-critical options here */
1955 if (!key_cert_is_legacy(k)) {
1956 buffer_put_string(&k->cert->certblob,
1957 buffer_ptr(&k->cert->extensions),
1958 buffer_len(&k->cert->extensions));
1961 /* -v00 certs put the nonce at the end */
1962 if (key_cert_is_legacy(k))
1963 buffer_put_string(&k->cert->certblob, nonce, sizeof(nonce));
1965 buffer_put_string(&k->cert->certblob, NULL, 0); /* reserved */
1966 buffer_put_string(&k->cert->certblob, ca_blob, ca_len);
1969 /* Sign the whole mess */
1970 if (key_sign(ca, &sig_blob, &sig_len, buffer_ptr(&k->cert->certblob),
1971 buffer_len(&k->cert->certblob)) != 0) {
1972 error("%s: signature operation failed", __func__);
1973 buffer_clear(&k->cert->certblob);
1976 /* Append signature and we are done */
1977 buffer_put_string(&k->cert->certblob, sig_blob, sig_len);
1984 key_cert_check_authority(const Key *k, int want_host, int require_principal,
1985 const char *name, const char **reason)
1987 u_int i, principal_matches;
1988 time_t now = time(NULL);
1991 if (k->cert->type != SSH2_CERT_TYPE_HOST) {
1992 *reason = "Certificate invalid: not a host certificate";
1996 if (k->cert->type != SSH2_CERT_TYPE_USER) {
1997 *reason = "Certificate invalid: not a user certificate";
2002 error("%s: system clock lies before epoch", __func__);
2003 *reason = "Certificate invalid: not yet valid";
2006 if ((u_int64_t)now < k->cert->valid_after) {
2007 *reason = "Certificate invalid: not yet valid";
2010 if ((u_int64_t)now >= k->cert->valid_before) {
2011 *reason = "Certificate invalid: expired";
2014 if (k->cert->nprincipals == 0) {
2015 if (require_principal) {
2016 *reason = "Certificate lacks principal list";
2019 } else if (name != NULL) {
2020 principal_matches = 0;
2021 for (i = 0; i < k->cert->nprincipals; i++) {
2022 if (strcmp(name, k->cert->principals[i]) == 0) {
2023 principal_matches = 1;
2027 if (!principal_matches) {
2028 *reason = "Certificate invalid: name is not a listed "
2037 key_cert_is_legacy(const Key *k)
2040 case KEY_DSA_CERT_V00:
2041 case KEY_RSA_CERT_V00:
2048 /* XXX: these are really begging for a table-driven approach */
2050 key_curve_name_to_nid(const char *name)
2052 #ifdef OPENSSL_HAS_ECC
2053 if (strcmp(name, "nistp256") == 0)
2054 return NID_X9_62_prime256v1;
2055 else if (strcmp(name, "nistp384") == 0)
2056 return NID_secp384r1;
2057 else if (strcmp(name, "nistp521") == 0)
2058 return NID_secp521r1;
2061 debug("%s: unsupported EC curve name \"%.100s\"", __func__, name);
2066 key_curve_nid_to_bits(int nid)
2069 #ifdef OPENSSL_HAS_ECC
2070 case NID_X9_62_prime256v1:
2078 error("%s: unsupported EC curve nid %d", __func__, nid);
2084 key_curve_nid_to_name(int nid)
2086 #ifdef OPENSSL_HAS_ECC
2087 if (nid == NID_X9_62_prime256v1)
2089 else if (nid == NID_secp384r1)
2091 else if (nid == NID_secp521r1)
2094 error("%s: unsupported EC curve nid %d", __func__, nid);
2098 #ifdef OPENSSL_HAS_ECC
2100 key_ec_nid_to_evpmd(int nid)
2102 int kbits = key_curve_nid_to_bits(nid);
2105 fatal("%s: invalid nid %d", __func__, nid);
2106 /* RFC5656 section 6.2.1 */
2108 return EVP_sha256();
2109 else if (kbits <= 384)
2110 return EVP_sha384();
2112 return EVP_sha512();
2116 key_ec_validate_public(const EC_GROUP *group, const EC_POINT *public)
2119 EC_POINT *nq = NULL;
2120 BIGNUM *order, *x, *y, *tmp;
2123 if ((bnctx = BN_CTX_new()) == NULL)
2124 fatal("%s: BN_CTX_new failed", __func__);
2125 BN_CTX_start(bnctx);
2128 * We shouldn't ever hit this case because bignum_get_ecpoint()
2129 * refuses to load GF2m points.
2131 if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) !=
2132 NID_X9_62_prime_field) {
2133 error("%s: group is not a prime field", __func__);
2138 if (EC_POINT_is_at_infinity(group, public)) {
2139 error("%s: received degenerate public key (infinity)",
2144 if ((x = BN_CTX_get(bnctx)) == NULL ||
2145 (y = BN_CTX_get(bnctx)) == NULL ||
2146 (order = BN_CTX_get(bnctx)) == NULL ||
2147 (tmp = BN_CTX_get(bnctx)) == NULL)
2148 fatal("%s: BN_CTX_get failed", __func__);
2150 /* log2(x) > log2(order)/2, log2(y) > log2(order)/2 */
2151 if (EC_GROUP_get_order(group, order, bnctx) != 1)
2152 fatal("%s: EC_GROUP_get_order failed", __func__);
2153 if (EC_POINT_get_affine_coordinates_GFp(group, public,
2155 fatal("%s: EC_POINT_get_affine_coordinates_GFp", __func__);
2156 if (BN_num_bits(x) <= BN_num_bits(order) / 2) {
2157 error("%s: public key x coordinate too small: "
2158 "bits(x) = %d, bits(order)/2 = %d", __func__,
2159 BN_num_bits(x), BN_num_bits(order) / 2);
2162 if (BN_num_bits(y) <= BN_num_bits(order) / 2) {
2163 error("%s: public key y coordinate too small: "
2164 "bits(y) = %d, bits(order)/2 = %d", __func__,
2165 BN_num_bits(x), BN_num_bits(order) / 2);
2169 /* nQ == infinity (n == order of subgroup) */
2170 if ((nq = EC_POINT_new(group)) == NULL)
2171 fatal("%s: BN_CTX_tmp failed", __func__);
2172 if (EC_POINT_mul(group, nq, NULL, public, order, bnctx) != 1)
2173 fatal("%s: EC_GROUP_mul failed", __func__);
2174 if (EC_POINT_is_at_infinity(group, nq) != 1) {
2175 error("%s: received degenerate public key (nQ != infinity)",
2180 /* x < order - 1, y < order - 1 */
2181 if (!BN_sub(tmp, order, BN_value_one()))
2182 fatal("%s: BN_sub failed", __func__);
2183 if (BN_cmp(x, tmp) >= 0) {
2184 error("%s: public key x coordinate >= group order - 1",
2188 if (BN_cmp(y, tmp) >= 0) {
2189 error("%s: public key y coordinate >= group order - 1",
2201 key_ec_validate_private(const EC_KEY *key)
2204 BIGNUM *order, *tmp;
2207 if ((bnctx = BN_CTX_new()) == NULL)
2208 fatal("%s: BN_CTX_new failed", __func__);
2209 BN_CTX_start(bnctx);
2211 if ((order = BN_CTX_get(bnctx)) == NULL ||
2212 (tmp = BN_CTX_get(bnctx)) == NULL)
2213 fatal("%s: BN_CTX_get failed", __func__);
2215 /* log2(private) > log2(order)/2 */
2216 if (EC_GROUP_get_order(EC_KEY_get0_group(key), order, bnctx) != 1)
2217 fatal("%s: EC_GROUP_get_order failed", __func__);
2218 if (BN_num_bits(EC_KEY_get0_private_key(key)) <=
2219 BN_num_bits(order) / 2) {
2220 error("%s: private key too small: "
2221 "bits(y) = %d, bits(order)/2 = %d", __func__,
2222 BN_num_bits(EC_KEY_get0_private_key(key)),
2223 BN_num_bits(order) / 2);
2227 /* private < order - 1 */
2228 if (!BN_sub(tmp, order, BN_value_one()))
2229 fatal("%s: BN_sub failed", __func__);
2230 if (BN_cmp(EC_KEY_get0_private_key(key), tmp) >= 0) {
2231 error("%s: private key >= group order - 1", __func__);
2240 #if defined(DEBUG_KEXECDH) || defined(DEBUG_PK)
2242 key_dump_ec_point(const EC_GROUP *group, const EC_POINT *point)
2247 if (point == NULL) {
2248 fputs("point=(NULL)\n", stderr);
2251 if ((bnctx = BN_CTX_new()) == NULL)
2252 fatal("%s: BN_CTX_new failed", __func__);
2253 BN_CTX_start(bnctx);
2254 if ((x = BN_CTX_get(bnctx)) == NULL || (y = BN_CTX_get(bnctx)) == NULL)
2255 fatal("%s: BN_CTX_get failed", __func__);
2256 if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) !=
2257 NID_X9_62_prime_field)
2258 fatal("%s: group is not a prime field", __func__);
2259 if (EC_POINT_get_affine_coordinates_GFp(group, point, x, y, bnctx) != 1)
2260 fatal("%s: EC_POINT_get_affine_coordinates_GFp", __func__);
2261 fputs("x=", stderr);
2262 BN_print_fp(stderr, x);
2263 fputs("\ny=", stderr);
2264 BN_print_fp(stderr, y);
2265 fputs("\n", stderr);
2270 key_dump_ec_key(const EC_KEY *key)
2272 const BIGNUM *exponent;
2274 key_dump_ec_point(EC_KEY_get0_group(key), EC_KEY_get0_public_key(key));
2275 fputs("exponent=", stderr);
2276 if ((exponent = EC_KEY_get0_private_key(key)) == NULL)
2277 fputs("(NULL)", stderr);
2279 BN_print_fp(stderr, EC_KEY_get0_private_key(key));
2280 fputs("\n", stderr);
2282 #endif /* defined(DEBUG_KEXECDH) || defined(DEBUG_PK) */
2283 #endif /* OPENSSL_HAS_ECC */