1 /* $OpenBSD: kex.c,v 1.99 2014/04/29 18:01:49 markus Exp $ */
3 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
18 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 #include <sys/param.h>
37 #include <openssl/crypto.h>
57 #if OPENSSL_VERSION_NUMBER >= 0x00907000L
58 # if defined(HAVE_EVP_SHA256)
59 # define evp_ssh_sha256 EVP_sha256
61 extern const EVP_MD
*evp_ssh_sha256(void);
66 static void kex_kexinit_finish(Kex
*);
67 static void kex_choose_conf(Kex
*);
75 static const struct kexalg kexalgs
[] = {
77 { KEX_DH1
, KEX_DH_GRP1_SHA1
, 0, SSH_DIGEST_SHA1
},
78 { KEX_DH14
, KEX_DH_GRP14_SHA1
, 0, SSH_DIGEST_SHA1
},
79 { KEX_DHGEX_SHA1
, KEX_DH_GEX_SHA1
, 0, SSH_DIGEST_SHA1
},
80 #ifdef HAVE_EVP_SHA256
81 { KEX_DHGEX_SHA256
, KEX_DH_GEX_SHA256
, 0, SSH_DIGEST_SHA256
},
82 #endif /* HAVE_EVP_SHA256 */
83 #ifdef OPENSSL_HAS_ECC
84 { KEX_ECDH_SHA2_NISTP256
, KEX_ECDH_SHA2
,
85 NID_X9_62_prime256v1
, SSH_DIGEST_SHA256
},
86 { KEX_ECDH_SHA2_NISTP384
, KEX_ECDH_SHA2
, NID_secp384r1
,
88 # ifdef OPENSSL_HAS_NISTP521
89 { KEX_ECDH_SHA2_NISTP521
, KEX_ECDH_SHA2
, NID_secp521r1
,
91 # endif /* OPENSSL_HAS_NISTP521 */
92 #endif /* OPENSSL_HAS_ECC */
93 { KEX_DH1
, KEX_DH_GRP1_SHA1
, 0, SSH_DIGEST_SHA1
},
94 #endif /* WITH_OPENSSL */
95 #ifdef HAVE_EVP_SHA256
96 { KEX_CURVE25519_SHA256
, KEX_C25519_SHA256
, 0, SSH_DIGEST_SHA256
},
97 #endif /* HAVE_EVP_SHA256 */
102 kex_alg_list(char sep
)
105 size_t nlen
, rlen
= 0;
106 const struct kexalg
*k
;
108 for (k
= kexalgs
; k
->name
!= NULL
; k
++) {
111 nlen
= strlen(k
->name
);
112 ret
= xrealloc(ret
, 1, rlen
+ nlen
+ 2);
113 memcpy(ret
+ rlen
, k
->name
, nlen
+ 1);
119 static const struct kexalg
*
120 kex_alg_by_name(const char *name
)
122 const struct kexalg
*k
;
124 for (k
= kexalgs
; k
->name
!= NULL
; k
++) {
125 if (strcmp(k
->name
, name
) == 0)
131 /* Validate KEX method name list */
133 kex_names_valid(const char *names
)
137 if (names
== NULL
|| strcmp(names
, "") == 0)
139 s
= cp
= xstrdup(names
);
140 for ((p
= strsep(&cp
, ",")); p
&& *p
!= '\0';
141 (p
= strsep(&cp
, ","))) {
142 if (kex_alg_by_name(p
) == NULL
) {
143 error("Unsupported KEX algorithm \"%.100s\"", p
);
148 debug3("kex names ok: [%s]", names
);
153 /* put algorithm proposal into buffer */
154 /* used in sshconnect.c as well as kex.c */
156 kex_prop2buf(Buffer
*b
, char *proposal
[PROPOSAL_MAX
])
162 * add a dummy cookie, the cookie will be overwritten by
163 * kex_send_kexinit(), each time a kexinit is set
165 for (i
= 0; i
< KEX_COOKIE_LEN
; i
++)
166 buffer_put_char(b
, 0);
167 for (i
= 0; i
< PROPOSAL_MAX
; i
++)
168 buffer_put_cstring(b
, proposal
[i
]);
169 buffer_put_char(b
, 0); /* first_kex_packet_follows */
170 buffer_put_int(b
, 0); /* uint32 reserved */
173 /* parse buffer and return algorithm proposal */
175 kex_buf2prop(Buffer
*raw
, int *first_kex_follows
)
181 proposal
= xcalloc(PROPOSAL_MAX
, sizeof(char *));
184 buffer_append(&b
, buffer_ptr(raw
), buffer_len(raw
));
186 for (i
= 0; i
< KEX_COOKIE_LEN
; i
++)
188 /* extract kex init proposal strings */
189 for (i
= 0; i
< PROPOSAL_MAX
; i
++) {
190 proposal
[i
] = buffer_get_cstring(&b
,NULL
);
191 debug2("kex_parse_kexinit: %s", proposal
[i
]);
193 /* first kex follows / reserved */
194 i
= buffer_get_char(&b
);
195 if (first_kex_follows
!= NULL
)
196 *first_kex_follows
= i
;
197 debug2("kex_parse_kexinit: first_kex_follows %d ", i
);
198 i
= buffer_get_int(&b
);
199 debug2("kex_parse_kexinit: reserved %u ", i
);
205 kex_prop_free(char **proposal
)
209 for (i
= 0; i
< PROPOSAL_MAX
; i
++)
216 kex_protocol_error(int type
, u_int32_t seq
, void *ctxt
)
218 error("Hm, kex protocol error: type %d seq %u", type
, seq
);
222 kex_reset_dispatch(void)
224 dispatch_range(SSH2_MSG_TRANSPORT_MIN
,
225 SSH2_MSG_TRANSPORT_MAX
, &kex_protocol_error
);
226 dispatch_set(SSH2_MSG_KEXINIT
, &kex_input_kexinit
);
232 kex_reset_dispatch();
234 packet_start(SSH2_MSG_NEWKEYS
);
236 /* packet_write_wait(); */
237 debug("SSH2_MSG_NEWKEYS sent");
239 debug("expecting SSH2_MSG_NEWKEYS");
240 packet_read_expect(SSH2_MSG_NEWKEYS
);
242 debug("SSH2_MSG_NEWKEYS received");
245 buffer_clear(&kex
->peer
);
246 /* buffer_clear(&kex->my); */
247 kex
->flags
&= ~KEX_INIT_SENT
;
253 kex_send_kexinit(Kex
*kex
)
260 error("kex_send_kexinit: no kex, cannot rekey");
263 if (kex
->flags
& KEX_INIT_SENT
) {
264 debug("KEX_INIT_SENT");
269 /* generate a random cookie */
270 if (buffer_len(&kex
->my
) < KEX_COOKIE_LEN
)
271 fatal("kex_send_kexinit: kex proposal too short");
272 cookie
= buffer_ptr(&kex
->my
);
273 for (i
= 0; i
< KEX_COOKIE_LEN
; i
++) {
279 packet_start(SSH2_MSG_KEXINIT
);
280 packet_put_raw(buffer_ptr(&kex
->my
), buffer_len(&kex
->my
));
282 debug("SSH2_MSG_KEXINIT sent");
283 kex
->flags
|= KEX_INIT_SENT
;
288 kex_input_kexinit(int type
, u_int32_t seq
, void *ctxt
)
292 Kex
*kex
= (Kex
*)ctxt
;
294 debug("SSH2_MSG_KEXINIT received");
296 fatal("kex_input_kexinit: no kex, cannot rekey");
298 ptr
= packet_get_raw(&dlen
);
299 buffer_append(&kex
->peer
, ptr
, dlen
);
302 for (i
= 0; i
< KEX_COOKIE_LEN
; i
++)
304 for (i
= 0; i
< PROPOSAL_MAX
; i
++)
305 free(packet_get_string(NULL
));
307 * XXX RFC4253 sec 7: "each side MAY guess" - currently no supported
308 * KEX method has the server move first, but a server might be using
309 * a custom method or one that we otherwise don't support. We should
310 * be prepared to remember first_kex_follows here so we can eat a
312 * XXX2 - RFC4253 is kind of ambiguous on what first_kex_follows means
313 * for cases where the server *doesn't* go first. I guess we should
314 * ignore it when it is set for these cases, which is what we do now.
316 (void) packet_get_char(); /* first_kex_follows */
317 (void) packet_get_int(); /* reserved */
320 kex_kexinit_finish(kex
);
324 kex_setup(char *proposal
[PROPOSAL_MAX
])
328 kex
= xcalloc(1, sizeof(*kex
));
329 buffer_init(&kex
->peer
);
330 buffer_init(&kex
->my
);
331 kex_prop2buf(&kex
->my
, proposal
);
334 kex_send_kexinit(kex
); /* we start */
335 kex_reset_dispatch();
341 kex_kexinit_finish(Kex
*kex
)
343 if (!(kex
->flags
& KEX_INIT_SENT
))
344 kex_send_kexinit(kex
);
346 kex_choose_conf(kex
);
348 if (kex
->kex_type
>= 0 && kex
->kex_type
< KEX_MAX
&&
349 kex
->kex
[kex
->kex_type
] != NULL
) {
350 (kex
->kex
[kex
->kex_type
])(kex
);
352 fatal("Unsupported key exchange %d", kex
->kex_type
);
357 choose_enc(Enc
*enc
, char *client
, char *server
)
359 char *name
= match_list(client
, server
, NULL
);
361 fatal("no matching cipher found: client %s server %s",
363 if ((enc
->cipher
= cipher_by_name(name
)) == NULL
)
364 fatal("matching cipher is not supported: %s", name
);
368 enc
->iv_len
= cipher_ivlen(enc
->cipher
);
370 enc
->key_len
= cipher_keylen(enc
->cipher
);
371 enc
->block_size
= cipher_blocksize(enc
->cipher
);
375 choose_mac(Mac
*mac
, char *client
, char *server
)
377 char *name
= match_list(client
, server
, NULL
);
379 fatal("no matching mac found: client %s server %s",
381 if (mac_setup(mac
, name
) < 0)
382 fatal("unsupported mac %s", name
);
383 /* truncate the key */
384 if (datafellows
& SSH_BUG_HMAC
)
392 choose_comp(Comp
*comp
, char *client
, char *server
)
394 char *name
= match_list(client
, server
, NULL
);
396 fatal("no matching comp found: client %s server %s", client
, server
);
397 if (strcmp(name
, "zlib@openssh.com") == 0) {
398 comp
->type
= COMP_DELAYED
;
399 } else if (strcmp(name
, "zlib") == 0) {
400 comp
->type
= COMP_ZLIB
;
401 } else if (strcmp(name
, "none") == 0) {
402 comp
->type
= COMP_NONE
;
404 fatal("unsupported comp %s", name
);
410 choose_kex(Kex
*k
, char *client
, char *server
)
412 const struct kexalg
*kexalg
;
414 k
->name
= match_list(client
, server
, NULL
);
416 fatal("Unable to negotiate a key exchange method");
417 if ((kexalg
= kex_alg_by_name(k
->name
)) == NULL
)
418 fatal("unsupported kex alg %s", k
->name
);
419 k
->kex_type
= kexalg
->type
;
420 k
->hash_alg
= kexalg
->hash_alg
;
421 k
->ec_nid
= kexalg
->ec_nid
;
425 choose_hostkeyalg(Kex
*k
, char *client
, char *server
)
427 char *hostkeyalg
= match_list(client
, server
, NULL
);
428 if (hostkeyalg
== NULL
)
429 fatal("no hostkey alg");
430 k
->hostkey_type
= key_type_from_name(hostkeyalg
);
431 if (k
->hostkey_type
== KEY_UNSPEC
)
432 fatal("bad hostkey alg '%s'", hostkeyalg
);
437 proposals_match(char *my
[PROPOSAL_MAX
], char *peer
[PROPOSAL_MAX
])
439 static int check
[] = {
440 PROPOSAL_KEX_ALGS
, PROPOSAL_SERVER_HOST_KEY_ALGS
, -1
445 for (idx
= &check
[0]; *idx
!= -1; idx
++) {
446 if ((p
= strchr(my
[*idx
], ',')) != NULL
)
448 if ((p
= strchr(peer
[*idx
], ',')) != NULL
)
450 if (strcmp(my
[*idx
], peer
[*idx
]) != 0) {
451 debug2("proposal mismatch: my %s peer %s",
452 my
[*idx
], peer
[*idx
]);
456 debug2("proposals match");
461 kex_choose_conf(Kex
*kex
)
465 char **cprop
, **sprop
;
466 int nenc
, nmac
, ncomp
;
467 u_int mode
, ctos
, need
, dh_need
, authlen
;
468 int first_kex_follows
, type
;
472 auth_flag
= packet_authentication_state();
473 debug ("AUTH STATE IS %d", auth_flag
);
475 my
= kex_buf2prop(&kex
->my
, NULL
);
476 peer
= kex_buf2prop(&kex
->peer
, &first_kex_follows
);
486 /* Check whether server offers roaming */
489 roaming
= match_list(KEX_RESUME
, peer
[PROPOSAL_KEX_ALGS
], NULL
);
496 /* Algorithm Negotiation */
497 for (mode
= 0; mode
< MODE_MAX
; mode
++) {
498 newkeys
= xcalloc(1, sizeof(*newkeys
));
499 kex
->newkeys
[mode
] = newkeys
;
500 ctos
= (!kex
->server
&& mode
== MODE_OUT
) ||
501 (kex
->server
&& mode
== MODE_IN
);
502 nenc
= ctos
? PROPOSAL_ENC_ALGS_CTOS
: PROPOSAL_ENC_ALGS_STOC
;
503 nmac
= ctos
? PROPOSAL_MAC_ALGS_CTOS
: PROPOSAL_MAC_ALGS_STOC
;
504 ncomp
= ctos
? PROPOSAL_COMP_ALGS_CTOS
: PROPOSAL_COMP_ALGS_STOC
;
505 choose_enc(&newkeys
->enc
, cprop
[nenc
], sprop
[nenc
]);
506 /* ignore mac for authenticated encryption */
507 authlen
= cipher_authlen(newkeys
->enc
.cipher
);
509 choose_mac(&newkeys
->mac
, cprop
[nmac
], sprop
[nmac
]);
510 choose_comp(&newkeys
->comp
, cprop
[ncomp
], sprop
[ncomp
]);
511 debug("REQUESTED ENC.NAME is '%s'", newkeys
->enc
.name
);
512 if (strcmp(newkeys
->enc
.name
, "none") == 0) {
513 debug("Requesting NONE. Authflag is %d", auth_flag
);
514 if (auth_flag
== 1) {
515 debug("None requested post authentication.");
517 fatal("Pre-authentication none cipher requests are not allowed.");
520 debug("kex: %s %s %s %s",
521 ctos
? "client->server" : "server->client",
523 authlen
== 0 ? newkeys
->mac
.name
: "<implicit>",
525 /* client starts withctos = 0 && log flag = 0 and no log*/
526 /* 2nd client pass ctos=1 and flag = 1 so no log*/
527 /* server starts with ctos =1 && log_flag = 0 so log */
528 /* 2nd sever pass ctos = 1 && log flag = 1 so no log*/
530 if (ctos
&& !log_flag
) {
531 logit("SSH: Server;Ltype: Kex;Remote: %s-%d;Enc: %s;MAC: %s;Comp: %s",
540 choose_kex(kex
, cprop
[PROPOSAL_KEX_ALGS
], sprop
[PROPOSAL_KEX_ALGS
]);
541 choose_hostkeyalg(kex
, cprop
[PROPOSAL_SERVER_HOST_KEY_ALGS
],
542 sprop
[PROPOSAL_SERVER_HOST_KEY_ALGS
]);
544 for (mode
= 0; mode
< MODE_MAX
; mode
++) {
545 newkeys
= kex
->newkeys
[mode
];
546 need
= MAX(need
, newkeys
->enc
.key_len
);
547 need
= MAX(need
, newkeys
->enc
.block_size
);
548 need
= MAX(need
, newkeys
->enc
.iv_len
);
549 need
= MAX(need
, newkeys
->mac
.key_len
);
550 dh_need
= MAX(dh_need
, cipher_seclen(newkeys
->enc
.cipher
));
551 dh_need
= MAX(dh_need
, newkeys
->enc
.block_size
);
552 dh_need
= MAX(dh_need
, newkeys
->enc
.iv_len
);
553 dh_need
= MAX(dh_need
, newkeys
->mac
.key_len
);
555 /* XXX need runden? */
557 kex
->dh_need
= dh_need
;
559 /* ignore the next message if the proposals do not match */
560 if (first_kex_follows
&& !proposals_match(my
, peer
) &&
561 !(datafellows
& SSH_BUG_FIRSTKEX
)) {
562 type
= packet_read();
563 debug2("skipping next packet (type %u)", type
);
571 derive_key(Kex
*kex
, int id
, u_int need
, u_char
*hash
, u_int hashlen
,
572 const u_char
*shared_secret
, u_int slen
)
575 struct ssh_digest_ctx
*hashctx
;
581 if ((mdsz
= ssh_digest_bytes(kex
->hash_alg
)) == 0)
582 fatal("bad kex md size %zu", mdsz
);
583 digest
= xmalloc(roundup(need
, mdsz
));
586 buffer_append(&b
, shared_secret
, slen
);
588 /* K1 = HASH(K || H || "A" || session_id) */
589 if ((hashctx
= ssh_digest_start(kex
->hash_alg
)) == NULL
)
590 fatal("%s: ssh_digest_start failed", __func__
);
591 if (ssh_digest_update_buffer(hashctx
, &b
) != 0 ||
592 ssh_digest_update(hashctx
, hash
, hashlen
) != 0 ||
593 ssh_digest_update(hashctx
, &c
, 1) != 0 ||
594 ssh_digest_update(hashctx
, kex
->session_id
,
595 kex
->session_id_len
) != 0)
596 fatal("%s: ssh_digest_update failed", __func__
);
597 if (ssh_digest_final(hashctx
, digest
, mdsz
) != 0)
598 fatal("%s: ssh_digest_final failed", __func__
);
599 ssh_digest_free(hashctx
);
603 * Kn = HASH(K || H || K1 || K2 || ... || Kn-1)
604 * Key = K1 || K2 || ... || Kn
606 for (have
= mdsz
; need
> have
; have
+= mdsz
) {
607 if ((hashctx
= ssh_digest_start(kex
->hash_alg
)) == NULL
)
608 fatal("%s: ssh_digest_start failed", __func__
);
609 if (ssh_digest_update_buffer(hashctx
, &b
) != 0 ||
610 ssh_digest_update(hashctx
, hash
, hashlen
) != 0 ||
611 ssh_digest_update(hashctx
, digest
, have
) != 0)
612 fatal("%s: ssh_digest_update failed", __func__
);
613 if (ssh_digest_final(hashctx
, digest
+ have
, mdsz
) != 0)
614 fatal("%s: ssh_digest_final failed", __func__
);
615 ssh_digest_free(hashctx
);
619 fprintf(stderr
, "key '%c'== ", c
);
620 dump_digest("key", digest
, need
);
625 Newkeys
*current_keys
[MODE_MAX
];
629 kex_derive_keys(Kex
*kex
, u_char
*hash
, u_int hashlen
,
630 const u_char
*shared_secret
, u_int slen
)
635 for (i
= 0; i
< NKEYS
; i
++) {
636 keys
[i
] = derive_key(kex
, 'A'+i
, kex
->we_need
, hash
, hashlen
,
637 shared_secret
, slen
);
640 debug2("kex_derive_keys");
641 for (mode
= 0; mode
< MODE_MAX
; mode
++) {
642 current_keys
[mode
] = kex
->newkeys
[mode
];
643 kex
->newkeys
[mode
] = NULL
;
644 ctos
= (!kex
->server
&& mode
== MODE_OUT
) ||
645 (kex
->server
&& mode
== MODE_IN
);
646 current_keys
[mode
]->enc
.iv
= keys
[ctos
? 0 : 1];
647 current_keys
[mode
]->enc
.key
= keys
[ctos
? 2 : 3];
648 current_keys
[mode
]->mac
.key
= keys
[ctos
? 4 : 5];
654 kex_derive_keys_bn(Kex
*kex
, u_char
*hash
, u_int hashlen
, const BIGNUM
*secret
)
656 Buffer shared_secret
;
658 buffer_init(&shared_secret
);
659 buffer_put_bignum2(&shared_secret
, secret
);
660 kex_derive_keys(kex
, hash
, hashlen
,
661 buffer_ptr(&shared_secret
), buffer_len(&shared_secret
));
662 buffer_free(&shared_secret
);
667 kex_get_newkeys(int mode
)
671 ret
= current_keys
[mode
];
672 current_keys
[mode
] = NULL
;
678 derive_ssh1_session_id(BIGNUM
*host_modulus
, BIGNUM
*server_modulus
,
679 u_int8_t cookie
[8], u_int8_t id
[16])
681 u_int8_t nbuf
[2048], obuf
[SSH_DIGEST_MAX_LENGTH
];
683 struct ssh_digest_ctx
*hashctx
;
685 if ((hashctx
= ssh_digest_start(SSH_DIGEST_MD5
)) == NULL
)
686 fatal("%s: ssh_digest_start", __func__
);
688 len
= BN_num_bytes(host_modulus
);
689 if (len
< (512 / 8) || (u_int
)len
> sizeof(nbuf
))
690 fatal("%s: bad host modulus (len %d)", __func__
, len
);
691 BN_bn2bin(host_modulus
, nbuf
);
692 if (ssh_digest_update(hashctx
, nbuf
, len
) != 0)
693 fatal("%s: ssh_digest_update failed", __func__
);
695 len
= BN_num_bytes(server_modulus
);
696 if (len
< (512 / 8) || (u_int
)len
> sizeof(nbuf
))
697 fatal("%s: bad server modulus (len %d)", __func__
, len
);
698 BN_bn2bin(server_modulus
, nbuf
);
699 if (ssh_digest_update(hashctx
, nbuf
, len
) != 0 ||
700 ssh_digest_update(hashctx
, cookie
, 8) != 0)
701 fatal("%s: ssh_digest_update failed", __func__
);
702 if (ssh_digest_final(hashctx
, obuf
, sizeof(obuf
)) != 0)
703 fatal("%s: ssh_digest_final failed", __func__
);
704 memcpy(id
, obuf
, ssh_digest_bytes(SSH_DIGEST_MD5
));
706 explicit_bzero(nbuf
, sizeof(nbuf
));
707 explicit_bzero(obuf
, sizeof(obuf
));
711 #if defined(DEBUG_KEX) || defined(DEBUG_KEXDH) || defined(DEBUG_KEXECDH)
713 dump_digest(char *msg
, u_char
*digest
, int len
)
717 fprintf(stderr
, "%s\n", msg
);
718 for (i
= 0; i
< len
; i
++) {
719 fprintf(stderr
, "%02x", digest
[i
]);
721 fprintf(stderr
, "\n");
723 fprintf(stderr
, " ");
725 fprintf(stderr
, "\n");