1 /* $OpenBSD: key.c,v 1.86 2010/03/15 19:40:02 stevesk 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>
57 static struct KeyCert
*
62 cert
= xcalloc(1, sizeof(*cert
));
63 buffer_init(&cert
->certblob
);
64 buffer_init(&cert
->constraints
);
66 cert
->principals
= NULL
;
67 cert
->signature_key
= NULL
;
77 k
= xcalloc(1, sizeof(*k
));
86 if ((rsa
= RSA_new()) == NULL
)
87 fatal("key_new: RSA_new failed");
88 if ((rsa
->n
= BN_new()) == NULL
)
89 fatal("key_new: BN_new failed");
90 if ((rsa
->e
= BN_new()) == NULL
)
91 fatal("key_new: BN_new failed");
96 if ((dsa
= DSA_new()) == NULL
)
97 fatal("key_new: DSA_new failed");
98 if ((dsa
->p
= BN_new()) == NULL
)
99 fatal("key_new: BN_new failed");
100 if ((dsa
->q
= BN_new()) == NULL
)
101 fatal("key_new: BN_new failed");
102 if ((dsa
->g
= BN_new()) == NULL
)
103 fatal("key_new: BN_new failed");
104 if ((dsa
->pub_key
= BN_new()) == NULL
)
105 fatal("key_new: BN_new failed");
111 fatal("key_new: bad key type %d", k
->type
);
116 k
->cert
= cert_new();
122 key_add_private(Key
*k
)
128 if ((k
->rsa
->d
= BN_new()) == NULL
)
129 fatal("key_new_private: BN_new failed");
130 if ((k
->rsa
->iqmp
= BN_new()) == NULL
)
131 fatal("key_new_private: BN_new failed");
132 if ((k
->rsa
->q
= BN_new()) == NULL
)
133 fatal("key_new_private: BN_new failed");
134 if ((k
->rsa
->p
= BN_new()) == NULL
)
135 fatal("key_new_private: BN_new failed");
136 if ((k
->rsa
->dmq1
= BN_new()) == NULL
)
137 fatal("key_new_private: BN_new failed");
138 if ((k
->rsa
->dmp1
= BN_new()) == NULL
)
139 fatal("key_new_private: BN_new failed");
143 if ((k
->dsa
->priv_key
= BN_new()) == NULL
)
144 fatal("key_new_private: BN_new failed");
154 key_new_private(int type
)
156 Key
*k
= key_new(type
);
163 cert_free(struct KeyCert
*cert
)
167 buffer_free(&cert
->certblob
);
168 buffer_free(&cert
->constraints
);
169 if (cert
->key_id
!= NULL
)
171 for (i
= 0; i
< cert
->nprincipals
; i
++)
172 xfree(cert
->principals
[i
]);
173 if (cert
->principals
!= NULL
)
174 xfree(cert
->principals
);
175 if (cert
->signature_key
!= NULL
)
176 key_free(cert
->signature_key
);
183 fatal("key_free: key is NULL");
201 fatal("key_free: bad key type %d", k
->type
);
204 if (key_is_cert(k
)) {
214 cert_compare(struct KeyCert
*a
, struct KeyCert
*b
)
216 if (a
== NULL
&& b
== NULL
)
218 if (a
== NULL
|| b
== NULL
)
220 if (buffer_len(&a
->certblob
) != buffer_len(&b
->certblob
))
222 if (memcmp(buffer_ptr(&a
->certblob
), buffer_ptr(&b
->certblob
),
223 buffer_len(&a
->certblob
)) != 0)
229 * Compare public portions of key only, allowing comparisons between
230 * certificates and plain keys too.
233 key_equal_public(const Key
*a
, const Key
*b
)
235 if (a
== NULL
|| b
== NULL
||
236 key_type_plain(a
->type
) != key_type_plain(b
->type
))
243 return a
->rsa
!= NULL
&& b
->rsa
!= NULL
&&
244 BN_cmp(a
->rsa
->e
, b
->rsa
->e
) == 0 &&
245 BN_cmp(a
->rsa
->n
, b
->rsa
->n
) == 0;
248 return a
->dsa
!= NULL
&& b
->dsa
!= NULL
&&
249 BN_cmp(a
->dsa
->p
, b
->dsa
->p
) == 0 &&
250 BN_cmp(a
->dsa
->q
, b
->dsa
->q
) == 0 &&
251 BN_cmp(a
->dsa
->g
, b
->dsa
->g
) == 0 &&
252 BN_cmp(a
->dsa
->pub_key
, b
->dsa
->pub_key
) == 0;
254 fatal("key_equal: bad key type %d", a
->type
);
260 key_equal(const Key
*a
, const Key
*b
)
262 if (a
== NULL
|| b
== NULL
|| a
->type
!= b
->type
)
264 if (key_is_cert(a
)) {
265 if (!cert_compare(a
->cert
, b
->cert
))
268 return key_equal_public(a
, b
);
272 key_fingerprint_raw(Key
*k
, enum fp_type dgst_type
, u_int
*dgst_raw_length
)
274 const EVP_MD
*md
= NULL
;
277 u_char
*retval
= NULL
;
279 int nlen
, elen
, otype
;
281 *dgst_raw_length
= 0;
291 fatal("key_fingerprint_raw: bad digest type %d",
296 nlen
= BN_num_bytes(k
->rsa
->n
);
297 elen
= BN_num_bytes(k
->rsa
->e
);
300 BN_bn2bin(k
->rsa
->n
, blob
);
301 BN_bn2bin(k
->rsa
->e
, blob
+ nlen
);
305 key_to_blob(k
, &blob
, &len
);
309 /* We want a fingerprint of the _key_ not of the cert */
311 k
->type
= key_type_plain(k
->type
);
312 key_to_blob(k
, &blob
, &len
);
318 fatal("key_fingerprint_raw: bad key type %d", k
->type
);
322 retval
= xmalloc(EVP_MAX_MD_SIZE
);
323 EVP_DigestInit(&ctx
, md
);
324 EVP_DigestUpdate(&ctx
, blob
, len
);
325 EVP_DigestFinal(&ctx
, retval
, dgst_raw_length
);
326 memset(blob
, 0, len
);
329 fatal("key_fingerprint_raw: blob is null");
335 key_fingerprint_hex(u_char
*dgst_raw
, u_int dgst_raw_len
)
340 retval
= xcalloc(1, dgst_raw_len
* 3 + 1);
341 for (i
= 0; i
< dgst_raw_len
; i
++) {
343 snprintf(hex
, sizeof(hex
), "%02x:", dgst_raw
[i
]);
344 strlcat(retval
, hex
, dgst_raw_len
* 3 + 1);
347 /* Remove the trailing ':' character */
348 retval
[(dgst_raw_len
* 3) - 1] = '\0';
353 key_fingerprint_bubblebabble(u_char
*dgst_raw
, u_int dgst_raw_len
)
355 char vowels
[] = { 'a', 'e', 'i', 'o', 'u', 'y' };
356 char consonants
[] = { 'b', 'c', 'd', 'f', 'g', 'h', 'k', 'l', 'm',
357 'n', 'p', 'r', 's', 't', 'v', 'z', 'x' };
358 u_int i
, j
= 0, rounds
, seed
= 1;
361 rounds
= (dgst_raw_len
/ 2) + 1;
362 retval
= xcalloc((rounds
* 6), sizeof(char));
364 for (i
= 0; i
< rounds
; i
++) {
365 u_int idx0
, idx1
, idx2
, idx3
, idx4
;
366 if ((i
+ 1 < rounds
) || (dgst_raw_len
% 2 != 0)) {
367 idx0
= (((((u_int
)(dgst_raw
[2 * i
])) >> 6) & 3) +
369 idx1
= (((u_int
)(dgst_raw
[2 * i
])) >> 2) & 15;
370 idx2
= ((((u_int
)(dgst_raw
[2 * i
])) & 3) +
372 retval
[j
++] = vowels
[idx0
];
373 retval
[j
++] = consonants
[idx1
];
374 retval
[j
++] = vowels
[idx2
];
375 if ((i
+ 1) < rounds
) {
376 idx3
= (((u_int
)(dgst_raw
[(2 * i
) + 1])) >> 4) & 15;
377 idx4
= (((u_int
)(dgst_raw
[(2 * i
) + 1]))) & 15;
378 retval
[j
++] = consonants
[idx3
];
380 retval
[j
++] = consonants
[idx4
];
382 ((((u_int
)(dgst_raw
[2 * i
])) * 7) +
383 ((u_int
)(dgst_raw
[(2 * i
) + 1])))) % 36;
389 retval
[j
++] = vowels
[idx0
];
390 retval
[j
++] = consonants
[idx1
];
391 retval
[j
++] = vowels
[idx2
];
400 * Draw an ASCII-Art representing the fingerprint so human brain can
401 * profit from its built-in pattern recognition ability.
402 * This technique is called "random art" and can be found in some
403 * scientific publications like this original paper:
405 * "Hash Visualization: a New Technique to improve Real-World Security",
406 * Perrig A. and Song D., 1999, International Workshop on Cryptographic
407 * Techniques and E-Commerce (CrypTEC '99)
408 * sparrow.ece.cmu.edu/~adrian/projects/validation/validation.pdf
410 * The subject came up in a talk by Dan Kaminsky, too.
412 * If you see the picture is different, the key is different.
413 * If the picture looks the same, you still know nothing.
415 * The algorithm used here is a worm crawling over a discrete plane,
416 * leaving a trace (augmenting the field) everywhere it goes.
417 * Movement is taken from dgst_raw 2bit-wise. Bumping into walls
418 * makes the respective movement vector be ignored for this turn.
419 * Graphs are not unambiguous, because circles in graphs can be
420 * walked in either direction.
424 * Field sizes for the random art. Have to be odd, so the starting point
425 * can be in the exact middle of the picture, and FLDBASE should be >=8 .
426 * Else pictures would be too dense, and drawing the frame would
427 * fail, too, because the key type would not fit in anymore.
430 #define FLDSIZE_Y (FLDBASE + 1)
431 #define FLDSIZE_X (FLDBASE * 2 + 1)
433 key_fingerprint_randomart(u_char
*dgst_raw
, u_int dgst_raw_len
, const Key
*k
)
436 * Chars to be used after each other every time the worm
437 * intersects with itself. Matter of taste.
439 char *augmentation_string
= " .o+=*BOX@%&#/^SE";
441 u_char field
[FLDSIZE_X
][FLDSIZE_Y
];
444 size_t len
= strlen(augmentation_string
) - 1;
446 retval
= xcalloc(1, (FLDSIZE_X
+ 3) * (FLDSIZE_Y
+ 2));
448 /* initialize field */
449 memset(field
, 0, FLDSIZE_X
* FLDSIZE_Y
* sizeof(char));
453 /* process raw key */
454 for (i
= 0; i
< dgst_raw_len
; i
++) {
456 /* each byte conveys four 2-bit move commands */
458 for (b
= 0; b
< 4; b
++) {
459 /* evaluate 2 bit, rest is shifted later */
460 x
+= (input
& 0x1) ? 1 : -1;
461 y
+= (input
& 0x2) ? 1 : -1;
463 /* assure we are still in bounds */
466 x
= MIN(x
, FLDSIZE_X
- 1);
467 y
= MIN(y
, FLDSIZE_Y
- 1);
469 /* augment the field */
470 if (field
[x
][y
] < len
- 2)
476 /* mark starting point and end point*/
477 field
[FLDSIZE_X
/ 2][FLDSIZE_Y
/ 2] = len
- 1;
481 snprintf(retval
, FLDSIZE_X
, "+--[%4s %4u]", key_type(k
), key_size(k
));
482 p
= strchr(retval
, '\0');
484 /* output upper border */
485 for (i
= p
- retval
- 1; i
< FLDSIZE_X
; i
++)
491 for (y
= 0; y
< FLDSIZE_Y
; y
++) {
493 for (x
= 0; x
< FLDSIZE_X
; x
++)
494 *p
++ = augmentation_string
[MIN(field
[x
][y
], len
)];
499 /* output lower border */
501 for (i
= 0; i
< FLDSIZE_X
; i
++)
509 key_fingerprint(Key
*k
, enum fp_type dgst_type
, enum fp_rep dgst_rep
)
515 dgst_raw
= key_fingerprint_raw(k
, dgst_type
, &dgst_raw_len
);
517 fatal("key_fingerprint: null from key_fingerprint_raw()");
520 retval
= key_fingerprint_hex(dgst_raw
, dgst_raw_len
);
522 case SSH_FP_BUBBLEBABBLE
:
523 retval
= key_fingerprint_bubblebabble(dgst_raw
, dgst_raw_len
);
525 case SSH_FP_RANDOMART
:
526 retval
= key_fingerprint_randomart(dgst_raw
, dgst_raw_len
, k
);
529 fatal("key_fingerprint: bad digest representation %d",
533 memset(dgst_raw
, 0, dgst_raw_len
);
539 * Reads a multiple-precision integer in decimal from the buffer, and advances
540 * the pointer. The integer must already be initialized. This function is
541 * permitted to modify the buffer. This leaves *cpp to point just beyond the
542 * last processed (and maybe modified) character. Note that this may modify
543 * the buffer containing the number.
546 read_bignum(char **cpp
, BIGNUM
* value
)
551 /* Skip any leading whitespace. */
552 for (; *cp
== ' ' || *cp
== '\t'; cp
++)
555 /* Check that it begins with a decimal digit. */
556 if (*cp
< '0' || *cp
> '9')
559 /* Save starting position. */
562 /* Move forward until all decimal digits skipped. */
563 for (; *cp
>= '0' && *cp
<= '9'; cp
++)
566 /* Save the old terminating character, and replace it by \0. */
570 /* Parse the number. */
571 if (BN_dec2bn(&value
, *cpp
) == 0)
574 /* Restore old terminating character. */
577 /* Move beyond the number and return success. */
583 write_bignum(FILE *f
, BIGNUM
*num
)
585 char *buf
= BN_bn2dec(num
);
587 error("write_bignum: BN_bn2dec() failed");
590 fprintf(f
, " %s", buf
);
595 /* returns 1 ok, -1 error */
597 key_read(Key
*ret
, char **cpp
)
610 /* Get number of bits. */
611 if (*cp
< '0' || *cp
> '9')
612 return -1; /* Bad bit count... */
613 for (bits
= 0; *cp
>= '0' && *cp
<= '9'; cp
++)
614 bits
= 10 * bits
+ *cp
- '0';
618 /* Get public exponent, public modulus. */
619 if (!read_bignum(cpp
, ret
->rsa
->e
))
621 if (!read_bignum(cpp
, ret
->rsa
->n
))
623 /* validate the claimed number of bits */
624 if ((u_int
)BN_num_bits(ret
->rsa
->n
) != bits
) {
625 verbose("key_read: claimed key size %d does not match "
626 "actual %d", bits
, BN_num_bits(ret
->rsa
->n
));
636 space
= strchr(cp
, ' ');
638 debug3("key_read: missing whitespace");
642 type
= key_type_from_name(cp
);
644 if (type
== KEY_UNSPEC
) {
645 debug3("key_read: missing keytype");
650 debug3("key_read: short string");
653 if (ret
->type
== KEY_UNSPEC
) {
655 } else if (ret
->type
!= type
) {
656 /* is a key, but different type */
657 debug3("key_read: type mismatch");
662 n
= uudecode(cp
, blob
, len
);
664 error("key_read: uudecode %s failed", cp
);
668 k
= key_from_blob(blob
, (u_int
)n
);
671 error("key_read: key_from_blob %s failed", cp
);
674 if (k
->type
!= type
) {
675 error("key_read: type mismatch: encoding error");
680 if (key_is_cert(ret
)) {
681 if (!key_is_cert(k
)) {
682 error("key_read: loaded key is not a cert");
686 if (ret
->cert
!= NULL
)
687 cert_free(ret
->cert
);
691 if (key_type_plain(ret
->type
) == KEY_RSA
) {
692 if (ret
->rsa
!= NULL
)
697 RSA_print_fp(stderr
, ret
->rsa
, 8);
700 if (key_type_plain(ret
->type
) == KEY_DSA
) {
701 if (ret
->dsa
!= NULL
)
706 DSA_print_fp(stderr
, ret
->dsa
, 8);
714 /* advance cp: skip whitespace and data */
715 while (*cp
== ' ' || *cp
== '\t')
717 while (*cp
!= '\0' && *cp
!= ' ' && *cp
!= '\t')
722 fatal("key_read: bad key type: %d", ret
->type
);
729 key_write(const Key
*key
, FILE *f
)
736 if (key_is_cert(key
)) {
737 if (key
->cert
== NULL
) {
738 error("%s: no cert data", __func__
);
741 if (buffer_len(&key
->cert
->certblob
) == 0) {
742 error("%s: no signed certificate blob", __func__
);
749 if (key
->rsa
== NULL
)
751 /* size of modulus 'n' */
752 bits
= BN_num_bits(key
->rsa
->n
);
753 fprintf(f
, "%u", bits
);
754 if (write_bignum(f
, key
->rsa
->e
) &&
755 write_bignum(f
, key
->rsa
->n
))
757 error("key_write: failed for RSA key");
761 if (key
->dsa
== NULL
)
766 if (key
->rsa
== NULL
)
773 key_to_blob(key
, &blob
, &len
);
775 n
= uuencode(blob
, len
, uu
, 2*len
);
777 fprintf(f
, "%s %s", key_ssh_name(key
), uu
);
787 key_type(const Key
*k
)
805 key_cert_type(const Key
*k
)
807 switch (k
->cert
->type
) {
808 case SSH2_CERT_TYPE_USER
:
810 case SSH2_CERT_TYPE_HOST
:
818 key_ssh_name(const Key
*k
)
826 return "ssh-rsa-cert-v00@openssh.com";
828 return "ssh-dss-cert-v00@openssh.com";
830 return "ssh-unknown";
834 key_size(const Key
*k
)
840 return BN_num_bits(k
->rsa
->n
);
843 return BN_num_bits(k
->dsa
->p
);
849 rsa_generate_private_key(u_int bits
)
853 private = RSA_generate_key(bits
, RSA_F4
, NULL
, NULL
);
855 fatal("rsa_generate_private_key: key generation failed.");
860 dsa_generate_private_key(u_int bits
)
862 DSA
*private = DSA_generate_parameters(bits
, NULL
, 0, NULL
, NULL
, NULL
, NULL
);
865 fatal("dsa_generate_private_key: DSA_generate_parameters failed");
866 if (!DSA_generate_key(private))
867 fatal("dsa_generate_private_key: DSA_generate_key failed.");
869 fatal("dsa_generate_private_key: NULL.");
874 key_generate(int type
, u_int bits
)
876 Key
*k
= key_new(KEY_UNSPEC
);
879 k
->dsa
= dsa_generate_private_key(bits
);
883 k
->rsa
= rsa_generate_private_key(bits
);
887 fatal("key_generate: cert keys cannot be generated directly");
889 fatal("key_generate: unknown type %d", type
);
896 key_cert_copy(const Key
*from_key
, struct Key
*to_key
)
899 const struct KeyCert
*from
;
902 if (to_key
->cert
!= NULL
) {
903 cert_free(to_key
->cert
);
907 if ((from
= from_key
->cert
) == NULL
)
910 to
= to_key
->cert
= cert_new();
912 buffer_append(&to
->certblob
, buffer_ptr(&from
->certblob
),
913 buffer_len(&from
->certblob
));
915 buffer_append(&to
->constraints
, buffer_ptr(&from
->constraints
),
916 buffer_len(&from
->constraints
));
918 to
->type
= from
->type
;
919 to
->key_id
= from
->key_id
== NULL
? NULL
: xstrdup(from
->key_id
);
920 to
->valid_after
= from
->valid_after
;
921 to
->valid_before
= from
->valid_before
;
922 to
->signature_key
= from
->signature_key
== NULL
?
923 NULL
: key_from_private(from
->signature_key
);
925 to
->nprincipals
= from
->nprincipals
;
926 if (to
->nprincipals
> CERT_MAX_PRINCIPALS
)
927 fatal("%s: nprincipals (%u) > CERT_MAX_PRINCIPALS (%u)",
928 __func__
, to
->nprincipals
, CERT_MAX_PRINCIPALS
);
929 if (to
->nprincipals
> 0) {
930 to
->principals
= xcalloc(from
->nprincipals
,
931 sizeof(*to
->principals
));
932 for (i
= 0; i
< to
->nprincipals
; i
++)
933 to
->principals
[i
] = xstrdup(from
->principals
[i
]);
938 key_from_private(const Key
*k
)
944 n
= key_new(k
->type
);
945 if ((BN_copy(n
->dsa
->p
, k
->dsa
->p
) == NULL
) ||
946 (BN_copy(n
->dsa
->q
, k
->dsa
->q
) == NULL
) ||
947 (BN_copy(n
->dsa
->g
, k
->dsa
->g
) == NULL
) ||
948 (BN_copy(n
->dsa
->pub_key
, k
->dsa
->pub_key
) == NULL
))
949 fatal("key_from_private: BN_copy failed");
954 n
= key_new(k
->type
);
955 if ((BN_copy(n
->rsa
->n
, k
->rsa
->n
) == NULL
) ||
956 (BN_copy(n
->rsa
->e
, k
->rsa
->e
) == NULL
))
957 fatal("key_from_private: BN_copy failed");
960 fatal("key_from_private: unknown type %d", k
->type
);
969 key_type_from_name(char *name
)
971 if (strcmp(name
, "rsa1") == 0) {
973 } else if (strcmp(name
, "rsa") == 0) {
975 } else if (strcmp(name
, "dsa") == 0) {
977 } else if (strcmp(name
, "ssh-rsa") == 0) {
979 } else if (strcmp(name
, "ssh-dss") == 0) {
981 } else if (strcmp(name
, "ssh-rsa-cert-v00@openssh.com") == 0) {
983 } else if (strcmp(name
, "ssh-dss-cert-v00@openssh.com") == 0) {
986 debug2("key_type_from_name: unknown key type '%s'", name
);
991 key_names_valid2(const char *names
)
995 if (names
== NULL
|| strcmp(names
, "") == 0)
997 s
= cp
= xstrdup(names
);
998 for ((p
= strsep(&cp
, ",")); p
&& *p
!= '\0';
999 (p
= strsep(&cp
, ","))) {
1000 switch (key_type_from_name(p
)) {
1007 debug3("key names ok: [%s]", names
);
1013 cert_parse(Buffer
*b
, Key
*key
, const u_char
*blob
, u_int blen
)
1015 u_char
*principals
, *constraints
, *sig_key
, *sig
;
1016 u_int signed_len
, plen
, clen
, sklen
, slen
, kidlen
;
1023 /* Copy the entire key blob for verification and later serialisation */
1024 buffer_append(&key
->cert
->certblob
, blob
, blen
);
1026 principals
= constraints
= sig_key
= sig
= NULL
;
1027 if (buffer_get_int_ret(&key
->cert
->type
, b
) != 0 ||
1028 (key
->cert
->key_id
= buffer_get_string_ret(b
, &kidlen
)) == NULL
||
1029 (principals
= buffer_get_string_ret(b
, &plen
)) == NULL
||
1030 buffer_get_int64_ret(&key
->cert
->valid_after
, b
) != 0 ||
1031 buffer_get_int64_ret(&key
->cert
->valid_before
, b
) != 0 ||
1032 (constraints
= buffer_get_string_ret(b
, &clen
)) == NULL
||
1033 /* skip nonce */ buffer_get_string_ptr_ret(b
, NULL
) == NULL
||
1034 /* skip reserved */ buffer_get_string_ptr_ret(b
, NULL
) == NULL
||
1035 (sig_key
= buffer_get_string_ret(b
, &sklen
)) == NULL
) {
1036 error("%s: parse error", __func__
);
1040 if (kidlen
!= strlen(key
->cert
->key_id
)) {
1041 error("%s: key ID contains \\0 character", __func__
);
1045 /* Signature is left in the buffer so we can calculate this length */
1046 signed_len
= buffer_len(&key
->cert
->certblob
) - buffer_len(b
);
1048 if ((sig
= buffer_get_string_ret(b
, &slen
)) == NULL
) {
1049 error("%s: parse error", __func__
);
1053 if (key
->cert
->type
!= SSH2_CERT_TYPE_USER
&&
1054 key
->cert
->type
!= SSH2_CERT_TYPE_HOST
) {
1055 error("Unknown certificate type %u", key
->cert
->type
);
1059 buffer_append(&tmp
, principals
, plen
);
1060 while (buffer_len(&tmp
) > 0) {
1061 if (key
->cert
->nprincipals
>= CERT_MAX_PRINCIPALS
) {
1062 error("%s: Too many principals", __func__
);
1065 if ((principal
= buffer_get_string_ret(&tmp
, &plen
)) == NULL
) {
1066 error("%s: Principals data invalid", __func__
);
1069 if (strlen(principal
) != plen
) {
1070 error("%s: Principal contains \\0 character",
1074 key
->cert
->principals
= xrealloc(key
->cert
->principals
,
1075 key
->cert
->nprincipals
+ 1, sizeof(*key
->cert
->principals
));
1076 key
->cert
->principals
[key
->cert
->nprincipals
++] = principal
;
1081 buffer_append(&key
->cert
->constraints
, constraints
, clen
);
1082 buffer_append(&tmp
, constraints
, clen
);
1083 /* validate structure */
1084 while (buffer_len(&tmp
) != 0) {
1085 if (buffer_get_string_ptr_ret(&tmp
, NULL
) == NULL
||
1086 buffer_get_string_ptr_ret(&tmp
, NULL
) == NULL
) {
1087 error("%s: Constraints data invalid", __func__
);
1093 if ((key
->cert
->signature_key
= key_from_blob(sig_key
,
1095 error("%s: Signature key invalid", __func__
);
1098 if (key
->cert
->signature_key
->type
!= KEY_RSA
&&
1099 key
->cert
->signature_key
->type
!= KEY_DSA
) {
1100 error("%s: Invalid signature key type %s (%d)", __func__
,
1101 key_type(key
->cert
->signature_key
),
1102 key
->cert
->signature_key
->type
);
1106 switch (key_verify(key
->cert
->signature_key
, sig
, slen
,
1107 buffer_ptr(&key
->cert
->certblob
), signed_len
)) {
1110 break; /* Good signature */
1112 error("%s: Invalid signature on certificate", __func__
);
1115 error("%s: Certificate signature verification failed",
1122 if (principals
!= NULL
)
1124 if (constraints
!= NULL
)
1126 if (sig_key
!= NULL
)
1134 key_from_blob(const u_char
*blob
, u_int blen
)
1142 dump_base64(stderr
, blob
, blen
);
1145 buffer_append(&b
, blob
, blen
);
1146 if ((ktype
= buffer_get_string_ret(&b
, NULL
)) == NULL
) {
1147 error("key_from_blob: can't read key type");
1151 type
= key_type_from_name(ktype
);
1156 key
= key_new(type
);
1157 if (buffer_get_bignum2_ret(&b
, key
->rsa
->e
) == -1 ||
1158 buffer_get_bignum2_ret(&b
, key
->rsa
->n
) == -1) {
1159 error("key_from_blob: can't read rsa key");
1166 RSA_print_fp(stderr
, key
->rsa
, 8);
1171 key
= key_new(type
);
1172 if (buffer_get_bignum2_ret(&b
, key
->dsa
->p
) == -1 ||
1173 buffer_get_bignum2_ret(&b
, key
->dsa
->q
) == -1 ||
1174 buffer_get_bignum2_ret(&b
, key
->dsa
->g
) == -1 ||
1175 buffer_get_bignum2_ret(&b
, key
->dsa
->pub_key
) == -1) {
1176 error("key_from_blob: can't read dsa key");
1180 DSA_print_fp(stderr
, key
->dsa
, 8);
1184 key
= key_new(type
);
1187 error("key_from_blob: cannot handle type %s", ktype
);
1190 if (key_is_cert(key
) && cert_parse(&b
, key
, blob
, blen
) == -1) {
1191 error("key_from_blob: can't parse cert data");
1194 rlen
= buffer_len(&b
);
1195 if (key
!= NULL
&& rlen
!= 0)
1196 error("key_from_blob: remaining bytes in key blob %d", rlen
);
1205 key_to_blob(const Key
*key
, u_char
**blobp
, u_int
*lenp
)
1211 error("key_to_blob: key == NULL");
1215 switch (key
->type
) {
1218 /* Use the existing blob */
1219 buffer_append(&b
, buffer_ptr(&key
->cert
->certblob
),
1220 buffer_len(&key
->cert
->certblob
));
1223 buffer_put_cstring(&b
, key_ssh_name(key
));
1224 buffer_put_bignum2(&b
, key
->dsa
->p
);
1225 buffer_put_bignum2(&b
, key
->dsa
->q
);
1226 buffer_put_bignum2(&b
, key
->dsa
->g
);
1227 buffer_put_bignum2(&b
, key
->dsa
->pub_key
);
1230 buffer_put_cstring(&b
, key_ssh_name(key
));
1231 buffer_put_bignum2(&b
, key
->rsa
->e
);
1232 buffer_put_bignum2(&b
, key
->rsa
->n
);
1235 error("key_to_blob: unsupported key type %d", key
->type
);
1239 len
= buffer_len(&b
);
1242 if (blobp
!= NULL
) {
1243 *blobp
= xmalloc(len
);
1244 memcpy(*blobp
, buffer_ptr(&b
), len
);
1246 memset(buffer_ptr(&b
), 0, len
);
1254 u_char
**sigp
, u_int
*lenp
,
1255 const u_char
*data
, u_int datalen
)
1257 switch (key
->type
) {
1260 return ssh_dss_sign(key
, sigp
, lenp
, data
, datalen
);
1263 return ssh_rsa_sign(key
, sigp
, lenp
, data
, datalen
);
1265 error("key_sign: invalid key type %d", key
->type
);
1271 * key_verify returns 1 for a correct signature, 0 for an incorrect signature
1277 const u_char
*signature
, u_int signaturelen
,
1278 const u_char
*data
, u_int datalen
)
1280 if (signaturelen
== 0)
1283 switch (key
->type
) {
1286 return ssh_dss_verify(key
, signature
, signaturelen
, data
, datalen
);
1289 return ssh_rsa_verify(key
, signature
, signaturelen
, data
, datalen
);
1291 error("key_verify: invalid key type %d", key
->type
);
1296 /* Converts a private to a public key */
1298 key_demote(const Key
*k
)
1302 pk
= xcalloc(1, sizeof(*pk
));
1304 pk
->flags
= k
->flags
;
1310 key_cert_copy(k
, pk
);
1314 if ((pk
->rsa
= RSA_new()) == NULL
)
1315 fatal("key_demote: RSA_new failed");
1316 if ((pk
->rsa
->e
= BN_dup(k
->rsa
->e
)) == NULL
)
1317 fatal("key_demote: BN_dup failed");
1318 if ((pk
->rsa
->n
= BN_dup(k
->rsa
->n
)) == NULL
)
1319 fatal("key_demote: BN_dup failed");
1322 key_cert_copy(k
, pk
);
1325 if ((pk
->dsa
= DSA_new()) == NULL
)
1326 fatal("key_demote: DSA_new failed");
1327 if ((pk
->dsa
->p
= BN_dup(k
->dsa
->p
)) == NULL
)
1328 fatal("key_demote: BN_dup failed");
1329 if ((pk
->dsa
->q
= BN_dup(k
->dsa
->q
)) == NULL
)
1330 fatal("key_demote: BN_dup failed");
1331 if ((pk
->dsa
->g
= BN_dup(k
->dsa
->g
)) == NULL
)
1332 fatal("key_demote: BN_dup failed");
1333 if ((pk
->dsa
->pub_key
= BN_dup(k
->dsa
->pub_key
)) == NULL
)
1334 fatal("key_demote: BN_dup failed");
1337 fatal("key_free: bad key type %d", k
->type
);
1345 key_is_cert(const Key
*k
)
1348 (k
->type
== KEY_RSA_CERT
|| k
->type
== KEY_DSA_CERT
);
1351 /* Return the cert-less equivalent to a certified key type */
1353 key_type_plain(int type
)
1365 /* Convert a KEY_RSA or KEY_DSA to their _CERT equivalent */
1367 key_to_certified(Key
*k
)
1371 k
->cert
= cert_new();
1372 k
->type
= KEY_RSA_CERT
;
1375 k
->cert
= cert_new();
1376 k
->type
= KEY_DSA_CERT
;
1379 error("%s: key has incorrect type %s", __func__
, key_type(k
));
1384 /* Convert a KEY_RSA_CERT or KEY_DSA_CERT to their raw key equivalent */
1386 key_drop_cert(Key
*k
)
1398 error("%s: key has incorrect type %s", __func__
, key_type(k
));
1403 /* Sign a KEY_RSA_CERT or KEY_DSA_CERT, (re-)generating the signed certblob */
1405 key_certify(Key
*k
, Key
*ca
)
1408 u_char
*ca_blob
, *sig_blob
, nonce
[32];
1409 u_int i
, ca_len
, sig_len
;
1411 if (k
->cert
== NULL
) {
1412 error("%s: key lacks cert info", __func__
);
1416 if (!key_is_cert(k
)) {
1417 error("%s: certificate has unknown type %d", __func__
,
1422 if (ca
->type
!= KEY_RSA
&& ca
->type
!= KEY_DSA
) {
1423 error("%s: CA key has unsupported type %s", __func__
,
1428 key_to_blob(ca
, &ca_blob
, &ca_len
);
1430 buffer_clear(&k
->cert
->certblob
);
1431 buffer_put_cstring(&k
->cert
->certblob
, key_ssh_name(k
));
1435 buffer_put_bignum2(&k
->cert
->certblob
, k
->dsa
->p
);
1436 buffer_put_bignum2(&k
->cert
->certblob
, k
->dsa
->q
);
1437 buffer_put_bignum2(&k
->cert
->certblob
, k
->dsa
->g
);
1438 buffer_put_bignum2(&k
->cert
->certblob
, k
->dsa
->pub_key
);
1441 buffer_put_bignum2(&k
->cert
->certblob
, k
->rsa
->e
);
1442 buffer_put_bignum2(&k
->cert
->certblob
, k
->rsa
->n
);
1445 error("%s: key has incorrect type %s", __func__
, key_type(k
));
1446 buffer_clear(&k
->cert
->certblob
);
1451 buffer_put_int(&k
->cert
->certblob
, k
->cert
->type
);
1452 buffer_put_cstring(&k
->cert
->certblob
, k
->cert
->key_id
);
1454 buffer_init(&principals
);
1455 for (i
= 0; i
< k
->cert
->nprincipals
; i
++)
1456 buffer_put_cstring(&principals
, k
->cert
->principals
[i
]);
1457 buffer_put_string(&k
->cert
->certblob
, buffer_ptr(&principals
),
1458 buffer_len(&principals
));
1459 buffer_free(&principals
);
1461 buffer_put_int64(&k
->cert
->certblob
, k
->cert
->valid_after
);
1462 buffer_put_int64(&k
->cert
->certblob
, k
->cert
->valid_before
);
1463 buffer_put_string(&k
->cert
->certblob
,
1464 buffer_ptr(&k
->cert
->constraints
),
1465 buffer_len(&k
->cert
->constraints
));
1467 arc4random_buf(&nonce
, sizeof(nonce
));
1468 buffer_put_string(&k
->cert
->certblob
, nonce
, sizeof(nonce
));
1469 buffer_put_string(&k
->cert
->certblob
, NULL
, 0); /* reserved */
1470 buffer_put_string(&k
->cert
->certblob
, ca_blob
, ca_len
);
1473 /* Sign the whole mess */
1474 if (key_sign(ca
, &sig_blob
, &sig_len
, buffer_ptr(&k
->cert
->certblob
),
1475 buffer_len(&k
->cert
->certblob
)) != 0) {
1476 error("%s: signature operation failed", __func__
);
1477 buffer_clear(&k
->cert
->certblob
);
1480 /* Append signature and we are done */
1481 buffer_put_string(&k
->cert
->certblob
, sig_blob
, sig_len
);
1488 key_cert_check_authority(const Key
*k
, int want_host
, int require_principal
,
1489 const char *name
, const char **reason
)
1491 u_int i
, principal_matches
;
1492 time_t now
= time(NULL
);
1495 if (k
->cert
->type
!= SSH2_CERT_TYPE_HOST
) {
1496 *reason
= "Certificate invalid: not a host certificate";
1500 if (k
->cert
->type
!= SSH2_CERT_TYPE_USER
) {
1501 *reason
= "Certificate invalid: not a user certificate";
1506 error("%s: system clock lies before epoch", __func__
);
1507 *reason
= "Certificate invalid: not yet valid";
1510 if ((u_int64_t
)now
< k
->cert
->valid_after
) {
1511 *reason
= "Certificate invalid: not yet valid";
1514 if ((u_int64_t
)now
>= k
->cert
->valid_before
) {
1515 *reason
= "Certificate invalid: expired";
1518 if (k
->cert
->nprincipals
== 0) {
1519 if (require_principal
) {
1520 *reason
= "Certificate lacks principal list";
1524 principal_matches
= 0;
1525 for (i
= 0; i
< k
->cert
->nprincipals
; i
++) {
1526 if (strcmp(name
, k
->cert
->principals
[i
]) == 0) {
1527 principal_matches
= 1;
1531 if (!principal_matches
) {
1532 *reason
= "Certificate invalid: name is not a listed "