Coverage Report

Created: 2026-07-10 07:10

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssh/kex.c
Line
Count
Source
1
/* $OpenBSD: kex.c,v 1.194 2026/05/31 04:44:38 djm Exp $ */
2
/*
3
 * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
4
 *
5
 * Redistribution and use in source and binary forms, with or without
6
 * modification, are permitted provided that the following conditions
7
 * are met:
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.
13
 *
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.
24
 */
25
26
#include "includes.h"
27
28
#include <sys/types.h>
29
#include <errno.h>
30
#include <signal.h>
31
#include <stdarg.h>
32
#include <stdio.h>
33
#include <stdlib.h>
34
#include <string.h>
35
#include <unistd.h>
36
37
#ifdef WITH_OPENSSL
38
#include <openssl/crypto.h>
39
#include <openssl/dh.h>
40
#endif
41
42
#include "ssh.h"
43
#include "ssh2.h"
44
#include "atomicio.h"
45
#include "version.h"
46
#include "packet.h"
47
#include "compat.h"
48
#include "cipher.h"
49
#include "sshkey.h"
50
#include "kex.h"
51
#include "log.h"
52
#include "mac.h"
53
#include "match.h"
54
#include "misc.h"
55
#include "dispatch.h"
56
#include "myproposal.h"
57
58
#include "ssherr.h"
59
#include "sshbuf.h"
60
#include "digest.h"
61
#include "xmalloc.h"
62
63
/* prototype */
64
static int kex_choose_conf(struct ssh *, uint32_t seq);
65
static int kex_input_newkeys(int, uint32_t, struct ssh *);
66
67
static const char * const proposal_names[PROPOSAL_MAX] = {
68
  "KEX algorithms",
69
  "host key algorithms",
70
  "ciphers ctos",
71
  "ciphers stoc",
72
  "MACs ctos",
73
  "MACs stoc",
74
  "compression ctos",
75
  "compression stoc",
76
  "languages ctos",
77
  "languages stoc",
78
};
79
80
/*
81
 * Fill out a proposal array with dynamically allocated values, which may
82
 * be modified as required for compatibility reasons.
83
 * Any of the options may be NULL, in which case the default is used.
84
 * Array contents must be freed by calling kex_proposal_free_entries.
85
 */
86
void
87
kex_proposal_populate_entries(struct ssh *ssh, char *prop[PROPOSAL_MAX],
88
    const char *kexalgos, const char *ciphers, const char *macs,
89
    const char *comp, const char *hkalgs)
90
0
{
91
0
  const char *defpropserver[PROPOSAL_MAX] = { KEX_SERVER };
92
0
  const char *defpropclient[PROPOSAL_MAX] = { KEX_CLIENT };
93
0
  const char **defprop = ssh->kex->server ? defpropserver : defpropclient;
94
0
  u_int i;
95
0
  char *cp;
96
97
0
  if (prop == NULL)
98
0
    fatal_f("proposal missing");
99
100
  /* Append EXT_INFO signalling to KexAlgorithms */
101
0
  if (kexalgos == NULL)
102
0
    kexalgos = defprop[PROPOSAL_KEX_ALGS];
103
0
  if ((cp = kex_names_cat(kexalgos, ssh->kex->server ?
104
0
      "ext-info-s,kex-strict-s-v00@openssh.com" :
105
0
      "ext-info-c,kex-strict-c-v00@openssh.com")) == NULL)
106
0
    fatal_f("kex_names_cat");
107
108
0
  for (i = 0; i < PROPOSAL_MAX; i++) {
109
0
    switch(i) {
110
0
    case PROPOSAL_KEX_ALGS:
111
0
      prop[i] = compat_kex_proposal(ssh, cp);
112
0
      break;
113
0
    case PROPOSAL_ENC_ALGS_CTOS:
114
0
    case PROPOSAL_ENC_ALGS_STOC:
115
0
      prop[i] = xstrdup(ciphers ? ciphers : defprop[i]);
116
0
      break;
117
0
    case PROPOSAL_MAC_ALGS_CTOS:
118
0
    case PROPOSAL_MAC_ALGS_STOC:
119
0
      prop[i]  = xstrdup(macs ? macs : defprop[i]);
120
0
      break;
121
0
    case PROPOSAL_COMP_ALGS_CTOS:
122
0
    case PROPOSAL_COMP_ALGS_STOC:
123
0
      prop[i] = xstrdup(comp ? comp : defprop[i]);
124
0
      break;
125
0
    case PROPOSAL_SERVER_HOST_KEY_ALGS:
126
0
      prop[i] = xstrdup(hkalgs ? hkalgs : defprop[i]);
127
0
      break;
128
0
    default:
129
0
      prop[i] = xstrdup(defprop[i]);
130
0
    }
131
0
  }
132
0
  free(cp);
133
0
}
134
135
void
136
kex_proposal_free_entries(char *prop[PROPOSAL_MAX])
137
0
{
138
0
  u_int i;
139
140
0
  for (i = 0; i < PROPOSAL_MAX; i++)
141
0
    free(prop[i]);
142
0
}
143
144
/* put algorithm proposal into buffer */
145
int
146
kex_prop2buf(struct sshbuf *b, char *proposal[PROPOSAL_MAX])
147
0
{
148
0
  u_int i;
149
0
  int r;
150
151
0
  sshbuf_reset(b);
152
153
  /*
154
   * add a dummy cookie, the cookie will be overwritten by
155
   * kex_send_kexinit(), each time a kexinit is set
156
   */
157
0
  for (i = 0; i < KEX_COOKIE_LEN; i++) {
158
0
    if ((r = sshbuf_put_u8(b, 0)) != 0)
159
0
      return r;
160
0
  }
161
0
  for (i = 0; i < PROPOSAL_MAX; i++) {
162
0
    if ((r = sshbuf_put_cstring(b, proposal[i])) != 0)
163
0
      return r;
164
0
  }
165
0
  if ((r = sshbuf_put_u8(b, 0)) != 0 || /* first_kex_packet_follows */
166
0
      (r = sshbuf_put_u32(b, 0)) != 0) /* uint32 reserved */
167
0
    return r;
168
0
  return 0;
169
0
}
170
171
/* parse buffer and return algorithm proposal */
172
int
173
kex_buf2prop(struct sshbuf *raw, int *first_kex_follows, char ***propp)
174
0
{
175
0
  struct sshbuf *b = NULL;
176
0
  u_char v;
177
0
  u_int i;
178
0
  char **proposal = NULL;
179
0
  int r;
180
181
0
  *propp = NULL;
182
0
  if ((proposal = calloc(PROPOSAL_MAX, sizeof(char *))) == NULL)
183
0
    return SSH_ERR_ALLOC_FAIL;
184
0
  if ((b = sshbuf_fromb(raw)) == NULL) {
185
0
    r = SSH_ERR_ALLOC_FAIL;
186
0
    goto out;
187
0
  }
188
0
  if ((r = sshbuf_consume(b, KEX_COOKIE_LEN)) != 0) { /* skip cookie */
189
0
    error_fr(r, "consume cookie");
190
0
    goto out;
191
0
  }
192
  /* extract kex init proposal strings */
193
0
  for (i = 0; i < PROPOSAL_MAX; i++) {
194
0
    if ((r = sshbuf_get_cstring(b, &(proposal[i]), NULL)) != 0) {
195
0
      error_fr(r, "parse proposal %u", i);
196
0
      goto out;
197
0
    }
198
0
    debug2("%s: %s", proposal_names[i], proposal[i]);
199
0
  }
200
  /* first kex follows / reserved */
201
0
  if ((r = sshbuf_get_u8(b, &v)) != 0 || /* first_kex_follows */
202
0
      (r = sshbuf_get_u32(b, &i)) != 0) { /* reserved */
203
0
    error_fr(r, "parse");
204
0
    goto out;
205
0
  }
206
0
  if (first_kex_follows != NULL)
207
0
    *first_kex_follows = v;
208
0
  debug2("first_kex_follows %d ", v);
209
0
  debug2("reserved %u ", i);
210
0
  r = 0;
211
0
  *propp = proposal;
212
0
 out:
213
0
  if (r != 0 && proposal != NULL)
214
0
    kex_prop_free(proposal);
215
0
  sshbuf_free(b);
216
0
  return r;
217
0
}
218
219
void
220
kex_prop_free(char **proposal)
221
0
{
222
0
  u_int i;
223
224
0
  if (proposal == NULL)
225
0
    return;
226
0
  for (i = 0; i < PROPOSAL_MAX; i++)
227
0
    free(proposal[i]);
228
0
  free(proposal);
229
0
}
230
231
int
232
kex_protocol_error(int type, uint32_t seq, struct ssh *ssh)
233
0
{
234
0
  int r;
235
236
  /* If in strict mode, any unexpected message is an error */
237
0
  if ((ssh->kex->flags & KEX_INITIAL) && ssh->kex->kex_strict) {
238
0
    ssh_packet_disconnect(ssh, "strict KEX violation: "
239
0
        "unexpected packet type %u (seqnr %u)", type, seq);
240
0
  }
241
0
  error_f("type %u seq %u", type, seq);
242
0
  if ((r = sshpkt_start(ssh, SSH2_MSG_UNIMPLEMENTED)) != 0 ||
243
0
      (r = sshpkt_put_u32(ssh, seq)) != 0 ||
244
0
      (r = sshpkt_send(ssh)) != 0)
245
0
    return r;
246
0
  return 0;
247
0
}
248
249
static void
250
kex_reset_dispatch(struct ssh *ssh)
251
0
{
252
0
  ssh_dispatch_range(ssh, SSH2_MSG_TRANSPORT_MIN,
253
0
      SSH2_MSG_TRANSPORT_MAX, &kex_protocol_error);
254
0
}
255
256
void
257
kex_set_server_sig_algs(struct ssh *ssh, const char *allowed_algs)
258
0
{
259
0
  char *alg, *oalgs, *algs, *sigalgs;
260
0
  const char *sigalg;
261
262
  /*
263
   * NB. allowed algorithms may contain certificate algorithms that
264
   * map to a specific plain signature type, e.g.
265
   * rsa-sha2-512-cert-v01@openssh.com => rsa-sha2-512
266
   * We need to be careful here to match these, retain the mapping
267
   * and only add each signature algorithm once.
268
   */
269
0
  if ((sigalgs = sshkey_alg_list(0, 1, 1, ',')) == NULL)
270
0
    fatal_f("sshkey_alg_list failed");
271
0
  oalgs = algs = xstrdup(allowed_algs);
272
0
  free(ssh->kex->server_sig_algs);
273
0
  ssh->kex->server_sig_algs = NULL;
274
0
  for ((alg = strsep(&algs, ",")); alg != NULL && *alg != '\0';
275
0
      (alg = strsep(&algs, ","))) {
276
0
    if ((sigalg = sshkey_sigalg_by_name(alg)) == NULL)
277
0
      continue;
278
0
    if (!kex_has_any_alg(sigalg, sigalgs))
279
0
      continue;
280
    /* Don't add an algorithm twice. */
281
0
    if (ssh->kex->server_sig_algs != NULL &&
282
0
        kex_has_any_alg(sigalg, ssh->kex->server_sig_algs))
283
0
      continue;
284
0
    xextendf(&ssh->kex->server_sig_algs, ",", "%s", sigalg);
285
0
  }
286
0
  free(oalgs);
287
0
  free(sigalgs);
288
0
  if (ssh->kex->server_sig_algs == NULL)
289
0
    ssh->kex->server_sig_algs = xstrdup("");
290
0
}
291
292
static int
293
kex_compose_ext_info_server(struct ssh *ssh, struct sshbuf *m)
294
0
{
295
0
  int r;
296
297
0
  if (ssh->kex->server_sig_algs == NULL &&
298
0
      (ssh->kex->server_sig_algs = sshkey_alg_list(0, 1, 1, ',')) == NULL)
299
0
    return SSH_ERR_ALLOC_FAIL;
300
0
  if ((r = sshbuf_put_u32(m, 4)) != 0 ||
301
0
      (r = sshbuf_put_cstring(m, "server-sig-algs")) != 0 ||
302
0
      (r = sshbuf_put_cstring(m, ssh->kex->server_sig_algs)) != 0 ||
303
0
      (r = sshbuf_put_cstring(m,
304
0
      "publickey-hostbound@openssh.com")) != 0 ||
305
0
      (r = sshbuf_put_cstring(m, "0")) != 0 ||
306
0
      (r = sshbuf_put_cstring(m, "ping@openssh.com")) != 0 ||
307
0
      (r = sshbuf_put_cstring(m, "0")) != 0 ||
308
0
      (r = sshbuf_put_cstring(m, "agent-forward")) != 0 ||
309
0
      (r = sshbuf_put_cstring(m, "0")) != 0) {
310
0
    error_fr(r, "compose");
311
0
    return r;
312
0
  }
313
0
  return 0;
314
0
}
315
316
static int
317
kex_compose_ext_info_client(struct ssh *ssh, struct sshbuf *m)
318
0
{
319
0
  int r;
320
321
0
  if ((r = sshbuf_put_u32(m, 1)) != 0 ||
322
0
      (r = sshbuf_put_cstring(m, "ext-info-in-auth@openssh.com")) != 0 ||
323
0
      (r = sshbuf_put_cstring(m, "0")) != 0) {
324
0
    error_fr(r, "compose");
325
0
    goto out;
326
0
  }
327
  /* success */
328
0
  r = 0;
329
0
 out:
330
0
  return r;
331
0
}
332
333
static int
334
kex_maybe_send_ext_info(struct ssh *ssh)
335
0
{
336
0
  int r;
337
0
  struct sshbuf *m = NULL;
338
339
0
  if ((ssh->kex->flags & KEX_INITIAL) == 0)
340
0
    return 0;
341
0
  if (!ssh->kex->ext_info_c && !ssh->kex->ext_info_s)
342
0
    return 0;
343
344
  /* Compose EXT_INFO packet. */
345
0
  if ((m = sshbuf_new()) == NULL)
346
0
    fatal_f("sshbuf_new failed");
347
0
  if (ssh->kex->ext_info_c &&
348
0
      (r = kex_compose_ext_info_server(ssh, m)) != 0)
349
0
    goto fail;
350
0
  if (ssh->kex->ext_info_s &&
351
0
      (r = kex_compose_ext_info_client(ssh, m)) != 0)
352
0
    goto fail;
353
354
  /* Send the actual KEX_INFO packet */
355
0
  debug("Sending SSH2_MSG_EXT_INFO");
356
0
  if ((r = sshpkt_start(ssh, SSH2_MSG_EXT_INFO)) != 0 ||
357
0
      (r = sshpkt_putb(ssh, m)) != 0 ||
358
0
      (r = sshpkt_send(ssh)) != 0) {
359
0
    error_f("send EXT_INFO");
360
0
    goto fail;
361
0
  }
362
363
0
  r = 0;
364
365
0
 fail:
366
0
  sshbuf_free(m);
367
0
  return r;
368
0
}
369
370
int
371
kex_server_update_ext_info(struct ssh *ssh)
372
0
{
373
0
  int r;
374
375
0
  if ((ssh->kex->flags & KEX_HAS_EXT_INFO_IN_AUTH) == 0)
376
0
    return 0;
377
378
0
  debug_f("Sending SSH2_MSG_EXT_INFO");
379
0
  if ((r = sshpkt_start(ssh, SSH2_MSG_EXT_INFO)) != 0 ||
380
0
      (r = sshpkt_put_u32(ssh, 1)) != 0 ||
381
0
      (r = sshpkt_put_cstring(ssh, "server-sig-algs")) != 0 ||
382
0
      (r = sshpkt_put_cstring(ssh, ssh->kex->server_sig_algs)) != 0 ||
383
0
      (r = sshpkt_send(ssh)) != 0) {
384
0
    error_f("send EXT_INFO");
385
0
    return r;
386
0
  }
387
0
  return 0;
388
0
}
389
390
int
391
kex_send_newkeys(struct ssh *ssh)
392
0
{
393
0
  int r;
394
395
0
  kex_reset_dispatch(ssh);
396
0
  if ((r = sshpkt_start(ssh, SSH2_MSG_NEWKEYS)) != 0 ||
397
0
      (r = sshpkt_send(ssh)) != 0)
398
0
    return r;
399
0
  debug("SSH2_MSG_NEWKEYS sent");
400
0
  ssh_dispatch_set(ssh, SSH2_MSG_NEWKEYS, &kex_input_newkeys);
401
0
  if ((r = kex_maybe_send_ext_info(ssh)) != 0)
402
0
    return r;
403
0
  debug("expecting SSH2_MSG_NEWKEYS");
404
0
  return 0;
405
0
}
406
407
/* Check whether an ext_info value contains the expected version string */
408
static int
409
kex_ext_info_check_ver(struct kex *kex, const char *name,
410
    const u_char *val, size_t len, const char *want_ver, u_int flag)
411
0
{
412
0
  if (memchr(val, '\0', len) != NULL) {
413
0
    error("SSH2_MSG_EXT_INFO: %s value contains nul byte", name);
414
0
    return SSH_ERR_INVALID_FORMAT;
415
0
  }
416
0
  debug_f("%s=<%s>", name, val);
417
0
  if (strcmp(val, want_ver) == 0)
418
0
    kex->flags |= flag;
419
0
  else
420
0
    debug_f("unsupported version of %s extension", name);
421
0
  return 0;
422
0
}
423
424
static int
425
kex_ext_info_client_parse(struct ssh *ssh, const char *name,
426
    const u_char *value, size_t vlen)
427
0
{
428
0
  int r;
429
430
  /* NB. some messages are only accepted in the initial EXT_INFO */
431
0
  if (strcmp(name, "server-sig-algs") == 0) {
432
    /* Ensure no \0 lurking in value */
433
0
    if (memchr(value, '\0', vlen) != NULL) {
434
0
      error_f("nul byte in %s", name);
435
0
      return SSH_ERR_INVALID_FORMAT;
436
0
    }
437
0
    debug_f("%s=<%s>", name, value);
438
0
    free(ssh->kex->server_sig_algs);
439
0
    ssh->kex->server_sig_algs = xstrdup((const char *)value);
440
0
  } else if (ssh->kex->ext_info_received == 1 &&
441
0
      strcmp(name, "publickey-hostbound@openssh.com") == 0) {
442
0
    if ((r = kex_ext_info_check_ver(ssh->kex, name, value, vlen,
443
0
        "0", KEX_HAS_PUBKEY_HOSTBOUND)) != 0) {
444
0
      return r;
445
0
    }
446
0
  } else if (ssh->kex->ext_info_received == 1 &&
447
0
      strcmp(name, "ping@openssh.com") == 0) {
448
0
    if ((r = kex_ext_info_check_ver(ssh->kex, name, value, vlen,
449
0
        "0", KEX_HAS_PING)) != 0) {
450
0
      return r;
451
0
    }
452
0
  } else if (ssh->kex->ext_info_received == 1 &&
453
0
      strcmp(name, "agent-forward") == 0) {
454
0
    if ((r = kex_ext_info_check_ver(ssh->kex, name, value, vlen,
455
0
        "0", KEX_HAS_NEWAGENT)) != 0) {
456
0
      return r;
457
0
    }
458
0
  } else
459
0
    debug_f("%s (unrecognised)", name);
460
461
0
  return 0;
462
0
}
463
464
static int
465
kex_ext_info_server_parse(struct ssh *ssh, const char *name,
466
    const u_char *value, size_t vlen)
467
0
{
468
0
  int r;
469
470
0
  if (strcmp(name, "ext-info-in-auth@openssh.com") == 0) {
471
0
    if ((r = kex_ext_info_check_ver(ssh->kex, name, value, vlen,
472
0
        "0", KEX_HAS_EXT_INFO_IN_AUTH)) != 0) {
473
0
      return r;
474
0
    }
475
0
  } else
476
0
    debug_f("%s (unrecognised)", name);
477
0
  return 0;
478
0
}
479
480
int
481
kex_input_ext_info(int type, uint32_t seq, struct ssh *ssh)
482
0
{
483
0
  struct kex *kex = ssh->kex;
484
0
  const int max_ext_info = kex->server ? 1 : 2;
485
0
  uint32_t i, ninfo;
486
0
  char *name;
487
0
  u_char *val;
488
0
  size_t vlen;
489
0
  int r;
490
491
0
  debug("SSH2_MSG_EXT_INFO received");
492
0
  if (++kex->ext_info_received > max_ext_info) {
493
0
    error("too many SSH2_MSG_EXT_INFO messages sent by peer");
494
0
    return dispatch_protocol_error(type, seq, ssh);
495
0
  }
496
0
  ssh_dispatch_set(ssh, SSH2_MSG_EXT_INFO, &kex_protocol_error);
497
0
  if ((r = sshpkt_get_u32(ssh, &ninfo)) != 0)
498
0
    return r;
499
0
  if (ninfo >= 1024) {
500
0
    error("SSH2_MSG_EXT_INFO with too many entries, expected "
501
0
        "<=1024, received %u", ninfo);
502
0
    return dispatch_protocol_error(type, seq, ssh);
503
0
  }
504
0
  for (i = 0; i < ninfo; i++) {
505
0
    if ((r = sshpkt_get_cstring(ssh, &name, NULL)) != 0)
506
0
      return r;
507
0
    if ((r = sshpkt_get_string(ssh, &val, &vlen)) != 0) {
508
0
      free(name);
509
0
      return r;
510
0
    }
511
0
    debug3_f("extension %s", name);
512
0
    if (kex->server) {
513
0
      if ((r = kex_ext_info_server_parse(ssh, name,
514
0
          val, vlen)) != 0)
515
0
        return r;
516
0
    } else {
517
0
      if ((r = kex_ext_info_client_parse(ssh, name,
518
0
          val, vlen)) != 0)
519
0
        return r;
520
0
    }
521
0
    free(name);
522
0
    free(val);
523
0
  }
524
0
  return sshpkt_get_end(ssh);
525
0
}
526
527
static int
528
kex_input_newkeys(int type, uint32_t seq, struct ssh *ssh)
529
0
{
530
0
  struct kex *kex = ssh->kex;
531
0
  int r, initial = (kex->flags & KEX_INITIAL) != 0;
532
0
  char *cp, **prop;
533
534
0
  debug("SSH2_MSG_NEWKEYS received");
535
0
  if (kex->ext_info_c && initial)
536
0
    ssh_dispatch_set(ssh, SSH2_MSG_EXT_INFO, &kex_input_ext_info);
537
0
  ssh_dispatch_set(ssh, SSH2_MSG_NEWKEYS, &kex_protocol_error);
538
0
  ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, &kex_input_kexinit);
539
0
  if ((r = sshpkt_get_end(ssh)) != 0)
540
0
    return r;
541
0
  if ((r = ssh_set_newkeys(ssh, MODE_IN)) != 0)
542
0
    return r;
543
0
  if (initial) {
544
    /* Remove initial KEX signalling from proposal for rekeying */
545
0
    if ((r = kex_buf2prop(kex->my, NULL, &prop)) != 0)
546
0
      return r;
547
0
    if ((cp = match_filter_denylist(prop[PROPOSAL_KEX_ALGS],
548
0
        kex->server ?
549
0
        "ext-info-s,kex-strict-s-v00@openssh.com" :
550
0
        "ext-info-c,kex-strict-c-v00@openssh.com")) == NULL) {
551
0
      error_f("match_filter_denylist failed");
552
0
      goto fail;
553
0
    }
554
0
    free(prop[PROPOSAL_KEX_ALGS]);
555
0
    prop[PROPOSAL_KEX_ALGS] = cp;
556
0
    if ((r = kex_prop2buf(ssh->kex->my, prop)) != 0) {
557
0
      error_f("kex_prop2buf failed");
558
0
 fail:
559
0
      kex_proposal_free_entries(prop);
560
0
      free(prop);
561
0
      return SSH_ERR_INTERNAL_ERROR;
562
0
    }
563
0
    kex_proposal_free_entries(prop);
564
0
    free(prop);
565
0
  }
566
0
  kex->done = 1;
567
0
  kex->flags &= ~KEX_INITIAL;
568
0
  sshbuf_reset(kex->peer);
569
0
  kex->flags &= ~(KEX_INIT_SENT|KEX_INIT_RECVD);
570
0
  return 0;
571
0
}
572
573
int
574
kex_send_kexinit(struct ssh *ssh)
575
0
{
576
0
  u_char *cookie;
577
0
  struct kex *kex = ssh->kex;
578
0
  int r;
579
580
0
  if (kex == NULL) {
581
0
    error_f("no kex");
582
0
    return SSH_ERR_INTERNAL_ERROR;
583
0
  }
584
0
  if (kex->flags & KEX_INIT_SENT)
585
0
    return 0;
586
0
  kex->done = 0;
587
588
  /* generate a random cookie */
589
0
  if (sshbuf_len(kex->my) < KEX_COOKIE_LEN) {
590
0
    error_f("bad kex length: %zu < %d",
591
0
        sshbuf_len(kex->my), KEX_COOKIE_LEN);
592
0
    return SSH_ERR_INVALID_FORMAT;
593
0
  }
594
0
  if ((cookie = sshbuf_mutable_ptr(kex->my)) == NULL) {
595
0
    error_f("buffer error");
596
0
    return SSH_ERR_INTERNAL_ERROR;
597
0
  }
598
0
  arc4random_buf(cookie, KEX_COOKIE_LEN);
599
600
0
  if ((r = sshpkt_start(ssh, SSH2_MSG_KEXINIT)) != 0 ||
601
0
      (r = sshpkt_putb(ssh, kex->my)) != 0 ||
602
0
      (r = sshpkt_send(ssh)) != 0) {
603
0
    error_fr(r, "compose reply");
604
0
    return r;
605
0
  }
606
0
  debug("SSH2_MSG_KEXINIT sent");
607
0
  kex->flags |= KEX_INIT_SENT;
608
0
  return 0;
609
0
}
610
611
int
612
kex_input_kexinit(int type, uint32_t seq, struct ssh *ssh)
613
0
{
614
0
  struct kex *kex = ssh->kex;
615
0
  const u_char *ptr;
616
0
  u_int i;
617
0
  size_t dlen;
618
0
  int r;
619
620
0
  debug("SSH2_MSG_KEXINIT received");
621
0
  if (kex == NULL) {
622
0
    error_f("no kex");
623
0
    return SSH_ERR_INTERNAL_ERROR;
624
0
  }
625
0
  free(kex->name);
626
0
  kex->name = NULL;
627
0
  if ((kex->flags & KEX_INIT_RECVD) != 0) {
628
0
    ssh_packet_disconnect(ssh,
629
0
        "multiple KEXINIT received from peer");
630
0
  }
631
0
  kex->flags |= KEX_INIT_RECVD;
632
0
  ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, &kex_protocol_error);
633
0
  ptr = sshpkt_ptr(ssh, &dlen);
634
0
  if ((r = sshbuf_put(kex->peer, ptr, dlen)) != 0)
635
0
    return r;
636
637
  /* discard packet */
638
0
  for (i = 0; i < KEX_COOKIE_LEN; i++) {
639
0
    if ((r = sshpkt_get_u8(ssh, NULL)) != 0) {
640
0
      error_fr(r, "discard cookie");
641
0
      return r;
642
0
    }
643
0
  }
644
0
  for (i = 0; i < PROPOSAL_MAX; i++) {
645
0
    if ((r = sshpkt_get_string(ssh, NULL, NULL)) != 0) {
646
0
      error_fr(r, "discard proposal");
647
0
      return r;
648
0
    }
649
0
  }
650
  /*
651
   * XXX RFC4253 sec 7: "each side MAY guess" - currently no supported
652
   * KEX method has the server move first, but a server might be using
653
   * a custom method or one that we otherwise don't support. We should
654
   * be prepared to remember first_kex_follows here so we can eat a
655
   * packet later.
656
   * XXX2 - RFC4253 is kind of ambiguous on what first_kex_follows means
657
   * for cases where the server *doesn't* go first. I guess we should
658
   * ignore it when it is set for these cases, which is what we do now.
659
   */
660
0
  if ((r = sshpkt_get_u8(ssh, NULL)) != 0 || /* first_kex_follows */
661
0
      (r = sshpkt_get_u32(ssh, NULL)) != 0 || /* reserved */
662
0
      (r = sshpkt_get_end(ssh)) != 0)
663
0
      return r;
664
665
0
  if (!(kex->flags & KEX_INIT_SENT))
666
0
    if ((r = kex_send_kexinit(ssh)) != 0)
667
0
      return r;
668
0
  if ((r = kex_choose_conf(ssh, seq)) != 0)
669
0
    return r;
670
671
0
  if (kex->kex_type < KEX_MAX && kex->kex[kex->kex_type] != NULL)
672
0
    return (kex->kex[kex->kex_type])(ssh);
673
674
0
  error_f("unknown kex type %u", kex->kex_type);
675
0
  return SSH_ERR_INTERNAL_ERROR;
676
0
}
677
678
struct kex *
679
kex_new(void)
680
0
{
681
0
  struct kex *kex;
682
683
0
  if ((kex = calloc(1, sizeof(*kex))) == NULL ||
684
0
      (kex->peer = sshbuf_new()) == NULL ||
685
0
      (kex->my = sshbuf_new()) == NULL ||
686
0
      (kex->client_version = sshbuf_new()) == NULL ||
687
0
      (kex->server_version = sshbuf_new()) == NULL ||
688
0
      (kex->session_id = sshbuf_new()) == NULL) {
689
0
    kex_free(kex);
690
0
    return NULL;
691
0
  }
692
0
  return kex;
693
0
}
694
695
void
696
kex_free_newkeys(struct newkeys *newkeys)
697
0
{
698
0
  if (newkeys == NULL)
699
0
    return;
700
0
  if (newkeys->enc.key) {
701
0
    explicit_bzero(newkeys->enc.key, newkeys->enc.key_len);
702
0
    free(newkeys->enc.key);
703
0
    newkeys->enc.key = NULL;
704
0
  }
705
0
  if (newkeys->enc.iv) {
706
0
    explicit_bzero(newkeys->enc.iv, newkeys->enc.iv_len);
707
0
    free(newkeys->enc.iv);
708
0
    newkeys->enc.iv = NULL;
709
0
  }
710
0
  free(newkeys->enc.name);
711
0
  explicit_bzero(&newkeys->enc, sizeof(newkeys->enc));
712
0
  free(newkeys->comp.name);
713
0
  explicit_bzero(&newkeys->comp, sizeof(newkeys->comp));
714
0
  mac_clear(&newkeys->mac);
715
0
  if (newkeys->mac.key) {
716
0
    explicit_bzero(newkeys->mac.key, newkeys->mac.key_len);
717
0
    free(newkeys->mac.key);
718
0
    newkeys->mac.key = NULL;
719
0
  }
720
0
  free(newkeys->mac.name);
721
0
  explicit_bzero(&newkeys->mac, sizeof(newkeys->mac));
722
0
  freezero(newkeys, sizeof(*newkeys));
723
0
}
724
725
void
726
kex_free(struct kex *kex)
727
0
{
728
0
  u_int mode;
729
730
0
  if (kex == NULL)
731
0
    return;
732
733
0
#ifdef WITH_OPENSSL
734
0
  DH_free(kex->dh);
735
0
#ifdef OPENSSL_HAS_ECC
736
0
  EC_KEY_free(kex->ec_client_key);
737
0
#endif /* OPENSSL_HAS_ECC */
738
0
#endif /* WITH_OPENSSL */
739
0
  for (mode = 0; mode < MODE_MAX; mode++) {
740
0
    kex_free_newkeys(kex->newkeys[mode]);
741
0
    kex->newkeys[mode] = NULL;
742
0
  }
743
0
  sshbuf_free(kex->peer);
744
0
  sshbuf_free(kex->my);
745
0
  sshbuf_free(kex->client_version);
746
0
  sshbuf_free(kex->server_version);
747
0
  sshbuf_free(kex->client_pub);
748
0
  sshbuf_free(kex->session_id);
749
0
  sshbuf_free(kex->initial_sig);
750
0
  sshkey_free(kex->initial_hostkey);
751
0
  free(kex->failed_choice);
752
0
  free(kex->hostkey_alg);
753
0
  free(kex->name);
754
0
  free(kex->server_sig_algs);
755
0
  free(kex);
756
0
}
757
758
int
759
kex_ready(struct ssh *ssh, char *proposal[PROPOSAL_MAX])
760
0
{
761
0
  int r;
762
763
0
  if ((r = kex_prop2buf(ssh->kex->my, proposal)) != 0)
764
0
    return r;
765
0
  ssh->kex->flags = KEX_INITIAL;
766
0
  kex_reset_dispatch(ssh);
767
0
  ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, &kex_input_kexinit);
768
0
  return 0;
769
0
}
770
771
int
772
kex_setup(struct ssh *ssh, char *proposal[PROPOSAL_MAX])
773
0
{
774
0
  int r;
775
776
0
  if ((r = kex_ready(ssh, proposal)) != 0)
777
0
    return r;
778
0
  if ((r = kex_send_kexinit(ssh)) != 0) {   /* we start */
779
0
    kex_free(ssh->kex);
780
0
    ssh->kex = NULL;
781
0
    return r;
782
0
  }
783
0
  return 0;
784
0
}
785
786
/*
787
 * Request key re-exchange, returns 0 on success or a ssherr.h error
788
 * code otherwise. Must not be called if KEX is incomplete or in-progress.
789
 */
790
int
791
kex_start_rekex(struct ssh *ssh)
792
0
{
793
0
  if (ssh->kex == NULL) {
794
0
    error_f("no kex");
795
0
    return SSH_ERR_INTERNAL_ERROR;
796
0
  }
797
0
  if (ssh->kex->done == 0) {
798
0
    error_f("requested twice");
799
0
    return SSH_ERR_INTERNAL_ERROR;
800
0
  }
801
0
  ssh->kex->done = 0;
802
0
  return kex_send_kexinit(ssh);
803
0
}
804
805
static int
806
choose_enc(struct sshenc *enc, char *client, char *server)
807
0
{
808
0
  char *name = match_list(client, server, NULL);
809
810
0
  if (name == NULL)
811
0
    return SSH_ERR_NO_CIPHER_ALG_MATCH;
812
0
  if ((enc->cipher = cipher_by_name(name)) == NULL) {
813
0
    error_f("unsupported cipher %s", name);
814
0
    free(name);
815
0
    return SSH_ERR_INTERNAL_ERROR;
816
0
  }
817
0
  enc->name = name;
818
0
  enc->enabled = 0;
819
0
  enc->iv = NULL;
820
0
  enc->iv_len = cipher_ivlen(enc->cipher);
821
0
  enc->key = NULL;
822
0
  enc->key_len = cipher_keylen(enc->cipher);
823
0
  enc->block_size = cipher_blocksize(enc->cipher);
824
0
  return 0;
825
0
}
826
827
static int
828
choose_mac(struct ssh *ssh, struct sshmac *mac, char *client, char *server)
829
0
{
830
0
  char *name = match_list(client, server, NULL);
831
832
0
  if (name == NULL)
833
0
    return SSH_ERR_NO_MAC_ALG_MATCH;
834
0
  if (mac_setup(mac, name) < 0) {
835
0
    error_f("unsupported MAC %s", name);
836
0
    free(name);
837
0
    return SSH_ERR_INTERNAL_ERROR;
838
0
  }
839
0
  mac->name = name;
840
0
  mac->key = NULL;
841
0
  mac->enabled = 0;
842
0
  return 0;
843
0
}
844
845
static int
846
choose_comp(struct sshcomp *comp, char *client, char *server)
847
0
{
848
0
  char *name = match_list(client, server, NULL);
849
850
0
  if (name == NULL)
851
0
    return SSH_ERR_NO_COMPRESS_ALG_MATCH;
852
0
#ifdef WITH_ZLIB
853
0
  if (strcmp(name, "zlib@openssh.com") == 0) {
854
0
    comp->type = COMP_DELAYED;
855
0
  } else
856
0
#endif  /* WITH_ZLIB */
857
0
  if (strcmp(name, "none") == 0) {
858
0
    comp->type = COMP_NONE;
859
0
  } else {
860
0
    error_f("unsupported compression scheme %s", name);
861
0
    free(name);
862
0
    return SSH_ERR_INTERNAL_ERROR;
863
0
  }
864
0
  comp->name = name;
865
0
  return 0;
866
0
}
867
868
static int
869
choose_kex(struct kex *k, char *client, char *server)
870
0
{
871
0
  k->name = match_list(client, server, NULL);
872
873
0
  debug("kex: algorithm: %s", k->name ? k->name : "(no match)");
874
0
  if (k->name == NULL)
875
0
    return SSH_ERR_NO_KEX_ALG_MATCH;
876
0
  if (!kex_name_valid(k->name)) {
877
0
    error_f("unsupported KEX method %s", k->name);
878
0
    return SSH_ERR_INTERNAL_ERROR;
879
0
  }
880
0
  k->kex_type = kex_type_from_name(k->name);
881
0
  k->hash_alg = kex_hash_from_name(k->name);
882
0
  k->ec_nid = kex_nid_from_name(k->name);
883
0
  return 0;
884
0
}
885
886
static int
887
choose_hostkeyalg(struct kex *k, char *client, char *server)
888
0
{
889
0
  free(k->hostkey_alg);
890
0
  k->hostkey_alg = match_list(client, server, NULL);
891
892
0
  debug("kex: host key algorithm: %s",
893
0
      k->hostkey_alg ? k->hostkey_alg : "(no match)");
894
0
  if (k->hostkey_alg == NULL)
895
0
    return SSH_ERR_NO_HOSTKEY_ALG_MATCH;
896
0
  k->hostkey_type = sshkey_type_from_name(k->hostkey_alg);
897
0
  if (k->hostkey_type == KEY_UNSPEC) {
898
0
    error_f("unsupported hostkey algorithm %s", k->hostkey_alg);
899
0
    return SSH_ERR_INTERNAL_ERROR;
900
0
  }
901
0
  k->hostkey_nid = sshkey_ecdsa_nid_from_name(k->hostkey_alg);
902
0
  return 0;
903
0
}
904
905
static int
906
proposals_match(char *my[PROPOSAL_MAX], char *peer[PROPOSAL_MAX])
907
0
{
908
0
  static int check[] = {
909
0
    PROPOSAL_KEX_ALGS, PROPOSAL_SERVER_HOST_KEY_ALGS, -1
910
0
  };
911
0
  int *idx;
912
0
  char *p;
913
914
0
  for (idx = &check[0]; *idx != -1; idx++) {
915
0
    if ((p = strchr(my[*idx], ',')) != NULL)
916
0
      *p = '\0';
917
0
    if ((p = strchr(peer[*idx], ',')) != NULL)
918
0
      *p = '\0';
919
0
    if (strcmp(my[*idx], peer[*idx]) != 0) {
920
0
      debug2("proposal mismatch: my %s peer %s",
921
0
          my[*idx], peer[*idx]);
922
0
      return (0);
923
0
    }
924
0
  }
925
0
  debug2("proposals match");
926
0
  return (1);
927
0
}
928
929
static int
930
kexalgs_contains(char **peer, const char *ext)
931
0
{
932
0
  return kex_has_any_alg(peer[PROPOSAL_KEX_ALGS], ext);
933
0
}
934
935
static int
936
kex_choose_conf(struct ssh *ssh, uint32_t seq)
937
0
{
938
0
  struct kex *kex = ssh->kex;
939
0
  struct newkeys *newkeys;
940
0
  char **my = NULL, **peer = NULL;
941
0
  char **cprop, **sprop;
942
0
  int nenc, nmac, ncomp;
943
0
  u_int mode, ctos, need, dh_need, authlen;
944
0
  int r, first_kex_follows;
945
946
0
  debug2("local %s KEXINIT proposal", kex->server ? "server" : "client");
947
0
  if ((r = kex_buf2prop(kex->my, NULL, &my)) != 0)
948
0
    goto out;
949
0
  debug2("peer %s KEXINIT proposal", kex->server ? "client" : "server");
950
0
  if ((r = kex_buf2prop(kex->peer, &first_kex_follows, &peer)) != 0)
951
0
    goto out;
952
953
0
  if (kex->server) {
954
0
    cprop=peer;
955
0
    sprop=my;
956
0
  } else {
957
0
    cprop=my;
958
0
    sprop=peer;
959
0
  }
960
961
  /* Check whether peer supports ext_info/kex_strict */
962
0
  if ((kex->flags & KEX_INITIAL) != 0) {
963
0
    if (kex->server) {
964
0
      kex->ext_info_c = kexalgs_contains(peer, "ext-info-c");
965
0
      kex->kex_strict = kexalgs_contains(peer,
966
0
          "kex-strict-c-v00@openssh.com");
967
0
    } else {
968
0
      kex->ext_info_s = kexalgs_contains(peer, "ext-info-s");
969
0
      kex->kex_strict = kexalgs_contains(peer,
970
0
          "kex-strict-s-v00@openssh.com");
971
0
    }
972
0
    if (kex->kex_strict) {
973
0
      debug3_f("will use strict KEX ordering");
974
0
      if (seq != 0)
975
0
        ssh_packet_disconnect(ssh,
976
0
            "strict KEX violation: "
977
0
            "KEXINIT was not the first packet");
978
0
    }
979
0
  }
980
981
  /* Check whether client supports rsa-sha2 algorithms */
982
0
  if (kex->server && (kex->flags & KEX_INITIAL)) {
983
0
    if (kex_has_any_alg(peer[PROPOSAL_SERVER_HOST_KEY_ALGS],
984
0
        "rsa-sha2-256,rsa-sha2-256-cert-v01@openssh.com"))
985
0
      kex->flags |= KEX_RSA_SHA2_256_SUPPORTED;
986
0
    if (kex_has_any_alg(peer[PROPOSAL_SERVER_HOST_KEY_ALGS],
987
0
        "rsa-sha2-512,rsa-sha2-512-cert-v01@openssh.com"))
988
0
      kex->flags |= KEX_RSA_SHA2_512_SUPPORTED;
989
0
  }
990
991
  /* Algorithm Negotiation */
992
0
  if ((r = choose_kex(kex, cprop[PROPOSAL_KEX_ALGS],
993
0
      sprop[PROPOSAL_KEX_ALGS])) != 0) {
994
0
    kex->failed_choice = peer[PROPOSAL_KEX_ALGS];
995
0
    peer[PROPOSAL_KEX_ALGS] = NULL;
996
0
    goto out;
997
0
  }
998
0
  if ((r = choose_hostkeyalg(kex, cprop[PROPOSAL_SERVER_HOST_KEY_ALGS],
999
0
      sprop[PROPOSAL_SERVER_HOST_KEY_ALGS])) != 0) {
1000
0
    kex->failed_choice = peer[PROPOSAL_SERVER_HOST_KEY_ALGS];
1001
0
    peer[PROPOSAL_SERVER_HOST_KEY_ALGS] = NULL;
1002
0
    goto out;
1003
0
  }
1004
0
  for (mode = 0; mode < MODE_MAX; mode++) {
1005
0
    if ((newkeys = calloc(1, sizeof(*newkeys))) == NULL) {
1006
0
      r = SSH_ERR_ALLOC_FAIL;
1007
0
      goto out;
1008
0
    }
1009
0
    kex->newkeys[mode] = newkeys;
1010
0
    ctos = (!kex->server && mode == MODE_OUT) ||
1011
0
        (kex->server && mode == MODE_IN);
1012
0
    nenc  = ctos ? PROPOSAL_ENC_ALGS_CTOS  : PROPOSAL_ENC_ALGS_STOC;
1013
0
    nmac  = ctos ? PROPOSAL_MAC_ALGS_CTOS  : PROPOSAL_MAC_ALGS_STOC;
1014
0
    ncomp = ctos ? PROPOSAL_COMP_ALGS_CTOS : PROPOSAL_COMP_ALGS_STOC;
1015
0
    if ((r = choose_enc(&newkeys->enc, cprop[nenc],
1016
0
        sprop[nenc])) != 0) {
1017
0
      kex->failed_choice = peer[nenc];
1018
0
      peer[nenc] = NULL;
1019
0
      goto out;
1020
0
    }
1021
0
    authlen = cipher_authlen(newkeys->enc.cipher);
1022
    /* ignore mac for authenticated encryption */
1023
0
    if (authlen == 0 &&
1024
0
        (r = choose_mac(ssh, &newkeys->mac, cprop[nmac],
1025
0
        sprop[nmac])) != 0) {
1026
0
      kex->failed_choice = peer[nmac];
1027
0
      peer[nmac] = NULL;
1028
0
      goto out;
1029
0
    }
1030
0
    if ((r = choose_comp(&newkeys->comp, cprop[ncomp],
1031
0
        sprop[ncomp])) != 0) {
1032
0
      kex->failed_choice = peer[ncomp];
1033
0
      peer[ncomp] = NULL;
1034
0
      goto out;
1035
0
    }
1036
0
    debug("kex: %s cipher: %s MAC: %s compression: %s",
1037
0
        ctos ? "client->server" : "server->client",
1038
0
        newkeys->enc.name,
1039
0
        authlen == 0 ? newkeys->mac.name : "<implicit>",
1040
0
        newkeys->comp.name);
1041
0
  }
1042
0
  need = dh_need = 0;
1043
0
  for (mode = 0; mode < MODE_MAX; mode++) {
1044
0
    newkeys = kex->newkeys[mode];
1045
0
    need = MAXIMUM(need, newkeys->enc.key_len);
1046
0
    need = MAXIMUM(need, newkeys->enc.block_size);
1047
0
    need = MAXIMUM(need, newkeys->enc.iv_len);
1048
0
    need = MAXIMUM(need, newkeys->mac.key_len);
1049
0
    dh_need = MAXIMUM(dh_need, cipher_seclen(newkeys->enc.cipher));
1050
0
    dh_need = MAXIMUM(dh_need, newkeys->enc.block_size);
1051
0
    dh_need = MAXIMUM(dh_need, newkeys->enc.iv_len);
1052
0
    dh_need = MAXIMUM(dh_need, newkeys->mac.key_len);
1053
0
  }
1054
  /* XXX need runden? */
1055
0
  kex->we_need = need;
1056
0
  kex->dh_need = dh_need;
1057
1058
  /* ignore the next message if the proposals do not match */
1059
0
  if (first_kex_follows && !proposals_match(my, peer))
1060
0
    ssh->dispatch_skip_packets = 1;
1061
0
  r = 0;
1062
0
 out:
1063
0
  kex_prop_free(my);
1064
0
  kex_prop_free(peer);
1065
0
  return r;
1066
0
}
1067
1068
static int
1069
derive_key(struct ssh *ssh, int id, u_int need, u_char *hash, u_int hashlen,
1070
    const struct sshbuf *shared_secret, u_char **keyp)
1071
0
{
1072
0
  struct kex *kex = ssh->kex;
1073
0
  struct ssh_digest_ctx *hashctx = NULL;
1074
0
  char c = id;
1075
0
  u_int have;
1076
0
  size_t mdsz;
1077
0
  u_char *digest;
1078
0
  int r;
1079
1080
0
  if ((mdsz = ssh_digest_bytes(kex->hash_alg)) == 0)
1081
0
    return SSH_ERR_INVALID_ARGUMENT;
1082
0
  if ((digest = calloc(1, ROUNDUP(need, mdsz))) == NULL) {
1083
0
    r = SSH_ERR_ALLOC_FAIL;
1084
0
    goto out;
1085
0
  }
1086
1087
  /* K1 = HASH(K || H || "A" || session_id) */
1088
0
  if ((hashctx = ssh_digest_start(kex->hash_alg)) == NULL ||
1089
0
      ssh_digest_update_buffer(hashctx, shared_secret) != 0 ||
1090
0
      ssh_digest_update(hashctx, hash, hashlen) != 0 ||
1091
0
      ssh_digest_update(hashctx, &c, 1) != 0 ||
1092
0
      ssh_digest_update_buffer(hashctx, kex->session_id) != 0 ||
1093
0
      ssh_digest_final(hashctx, digest, mdsz) != 0) {
1094
0
    r = SSH_ERR_LIBCRYPTO_ERROR;
1095
0
    error_f("KEX hash failed");
1096
0
    goto out;
1097
0
  }
1098
0
  ssh_digest_free(hashctx);
1099
0
  hashctx = NULL;
1100
1101
  /*
1102
   * expand key:
1103
   * Kn = HASH(K || H || K1 || K2 || ... || Kn-1)
1104
   * Key = K1 || K2 || ... || Kn
1105
   */
1106
0
  for (have = mdsz; need > have; have += mdsz) {
1107
0
    if ((hashctx = ssh_digest_start(kex->hash_alg)) == NULL ||
1108
0
        ssh_digest_update_buffer(hashctx, shared_secret) != 0 ||
1109
0
        ssh_digest_update(hashctx, hash, hashlen) != 0 ||
1110
0
        ssh_digest_update(hashctx, digest, have) != 0 ||
1111
0
        ssh_digest_final(hashctx, digest + have, mdsz) != 0) {
1112
0
      error_f("KDF failed");
1113
0
      r = SSH_ERR_LIBCRYPTO_ERROR;
1114
0
      goto out;
1115
0
    }
1116
0
    ssh_digest_free(hashctx);
1117
0
    hashctx = NULL;
1118
0
  }
1119
#ifdef DEBUG_KEX
1120
  fprintf(stderr, "key '%c'== ", c);
1121
  dump_digest("key", digest, need);
1122
#endif
1123
0
  *keyp = digest;
1124
0
  digest = NULL;
1125
0
  r = 0;
1126
0
 out:
1127
0
  free(digest);
1128
0
  ssh_digest_free(hashctx);
1129
0
  return r;
1130
0
}
1131
1132
0
#define NKEYS 6
1133
int
1134
kex_derive_keys(struct ssh *ssh, u_char *hash, u_int hashlen,
1135
    const struct sshbuf *shared_secret)
1136
0
{
1137
0
  struct kex *kex = ssh->kex;
1138
0
  u_char *keys[NKEYS];
1139
0
  u_int i, j, mode, ctos;
1140
0
  int r;
1141
1142
  /* save initial hash as session id */
1143
0
  if ((kex->flags & KEX_INITIAL) != 0) {
1144
0
    if (sshbuf_len(kex->session_id) != 0) {
1145
0
      error_f("already have session ID at kex");
1146
0
      return SSH_ERR_INTERNAL_ERROR;
1147
0
    }
1148
0
    if ((r = sshbuf_put(kex->session_id, hash, hashlen)) != 0)
1149
0
      return r;
1150
0
  } else if (sshbuf_len(kex->session_id) == 0) {
1151
0
    error_f("no session ID in rekex");
1152
0
    return SSH_ERR_INTERNAL_ERROR;
1153
0
  }
1154
0
  for (i = 0; i < NKEYS; i++) {
1155
0
    if ((r = derive_key(ssh, 'A'+i, kex->we_need, hash, hashlen,
1156
0
        shared_secret, &keys[i])) != 0) {
1157
0
      for (j = 0; j < i; j++)
1158
0
        free(keys[j]);
1159
0
      return r;
1160
0
    }
1161
0
  }
1162
0
  for (mode = 0; mode < MODE_MAX; mode++) {
1163
0
    ctos = (!kex->server && mode == MODE_OUT) ||
1164
0
        (kex->server && mode == MODE_IN);
1165
0
    kex->newkeys[mode]->enc.iv  = keys[ctos ? 0 : 1];
1166
0
    kex->newkeys[mode]->enc.key = keys[ctos ? 2 : 3];
1167
0
    kex->newkeys[mode]->mac.key = keys[ctos ? 4 : 5];
1168
0
  }
1169
0
  return 0;
1170
0
}
1171
1172
int
1173
kex_load_hostkey(struct ssh *ssh, struct sshkey **prvp, struct sshkey **pubp)
1174
0
{
1175
0
  struct kex *kex = ssh->kex;
1176
1177
0
  *pubp = NULL;
1178
0
  *prvp = NULL;
1179
0
  if (kex->load_host_public_key == NULL ||
1180
0
      kex->load_host_private_key == NULL) {
1181
0
    error_f("missing hostkey loader");
1182
0
    return SSH_ERR_INVALID_ARGUMENT;
1183
0
  }
1184
0
  *pubp = kex->load_host_public_key(kex->hostkey_type,
1185
0
      kex->hostkey_nid, ssh);
1186
0
  *prvp = kex->load_host_private_key(kex->hostkey_type,
1187
0
      kex->hostkey_nid, ssh);
1188
0
  if (*pubp == NULL)
1189
0
    return SSH_ERR_NO_HOSTKEY_LOADED;
1190
0
  return 0;
1191
0
}
1192
1193
int
1194
kex_verify_host_key(struct ssh *ssh, struct sshkey *server_host_key)
1195
0
{
1196
0
  struct kex *kex = ssh->kex;
1197
1198
0
  if (kex->verify_host_key == NULL) {
1199
0
    error_f("missing hostkey verifier");
1200
0
    return SSH_ERR_INVALID_ARGUMENT;
1201
0
  }
1202
0
  if (server_host_key->type != kex->hostkey_type ||
1203
0
      (kex->hostkey_type == KEY_ECDSA &&
1204
0
      server_host_key->ecdsa_nid != kex->hostkey_nid))
1205
0
    return SSH_ERR_KEY_TYPE_MISMATCH;
1206
0
  if (kex->verify_host_key(server_host_key, ssh) == -1)
1207
0
    return  SSH_ERR_SIGNATURE_INVALID;
1208
0
  return 0;
1209
0
}
1210
1211
#if defined(DEBUG_KEX) || defined(DEBUG_KEXDH) || defined(DEBUG_KEXECDH)
1212
void
1213
dump_digest(const char *msg, const u_char *digest, int len)
1214
{
1215
  fprintf(stderr, "%s\n", msg);
1216
  sshbuf_dump_data(digest, len, stderr);
1217
}
1218
#endif
1219
1220
/*
1221
 * Send a plaintext error message to the peer, suffixed by \r\n.
1222
 * Only used during banner exchange, and there only for the server.
1223
 */
1224
static void
1225
send_error(struct ssh *ssh, char *msg)
1226
0
{
1227
0
  char *crnl = "\r\n";
1228
1229
0
  if (!ssh->kex->server)
1230
0
    return;
1231
1232
0
  if (atomicio(vwrite, ssh_packet_get_connection_out(ssh),
1233
0
      msg, strlen(msg)) != strlen(msg) ||
1234
0
      atomicio(vwrite, ssh_packet_get_connection_out(ssh),
1235
0
      crnl, strlen(crnl)) != strlen(crnl))
1236
0
    error_f("write: %.100s", strerror(errno));
1237
0
}
1238
1239
/*
1240
 * Sends our identification string and waits for the peer's. Will block for
1241
 * up to timeout_ms (or indefinitely if timeout_ms <= 0).
1242
 * Returns on 0 success or a ssherr.h code on failure.
1243
 */
1244
int
1245
kex_exchange_identification(struct ssh *ssh, int timeout_ms,
1246
    const char *version_addendum)
1247
0
{
1248
0
  int remote_major, remote_minor, mismatch, oerrno = 0;
1249
0
  size_t len, n;
1250
0
  int r, expect_nl;
1251
0
  u_char c;
1252
0
  struct sshbuf *our_version = ssh->kex->server ?
1253
0
      ssh->kex->server_version : ssh->kex->client_version;
1254
0
  struct sshbuf *peer_version = ssh->kex->server ?
1255
0
      ssh->kex->client_version : ssh->kex->server_version;
1256
0
  char *our_version_string = NULL, *peer_version_string = NULL;
1257
0
  char *cp, *remote_version = NULL;
1258
1259
  /* Prepare and send our banner */
1260
0
  sshbuf_reset(our_version);
1261
0
  if (version_addendum != NULL && *version_addendum == '\0')
1262
0
    version_addendum = NULL;
1263
0
  if ((r = sshbuf_putf(our_version, "SSH-%d.%d-%s%s%s\r\n",
1264
0
      PROTOCOL_MAJOR_2, PROTOCOL_MINOR_2, SSH_VERSION,
1265
0
      version_addendum == NULL ? "" : " ",
1266
0
      version_addendum == NULL ? "" : version_addendum)) != 0) {
1267
0
    oerrno = errno;
1268
0
    error_fr(r, "sshbuf_putf");
1269
0
    goto out;
1270
0
  }
1271
1272
0
  if (atomicio(vwrite, ssh_packet_get_connection_out(ssh),
1273
0
      sshbuf_mutable_ptr(our_version),
1274
0
      sshbuf_len(our_version)) != sshbuf_len(our_version)) {
1275
0
    oerrno = errno;
1276
0
    debug_f("write: %.100s", strerror(errno));
1277
0
    r = SSH_ERR_SYSTEM_ERROR;
1278
0
    goto out;
1279
0
  }
1280
0
  if ((r = sshbuf_consume_end(our_version, 2)) != 0) { /* trim \r\n */
1281
0
    oerrno = errno;
1282
0
    error_fr(r, "sshbuf_consume_end");
1283
0
    goto out;
1284
0
  }
1285
0
  our_version_string = sshbuf_dup_string(our_version);
1286
0
  if (our_version_string == NULL) {
1287
0
    error_f("sshbuf_dup_string failed");
1288
0
    r = SSH_ERR_ALLOC_FAIL;
1289
0
    goto out;
1290
0
  }
1291
0
  debug("Local version string %.100s", our_version_string);
1292
1293
  /* Read other side's version identification. */
1294
0
  for (n = 0; ; n++) {
1295
0
    if (n >= SSH_MAX_PRE_BANNER_LINES) {
1296
0
      send_error(ssh, "No SSH identification string "
1297
0
          "received.");
1298
0
      error_f("No SSH version received in first %u lines "
1299
0
          "from server", SSH_MAX_PRE_BANNER_LINES);
1300
0
      r = SSH_ERR_INVALID_FORMAT;
1301
0
      goto out;
1302
0
    }
1303
0
    sshbuf_reset(peer_version);
1304
0
    expect_nl = 0;
1305
0
    for (;;) {
1306
0
      if (timeout_ms > 0) {
1307
0
        r = waitrfd(ssh_packet_get_connection_in(ssh),
1308
0
            &timeout_ms, NULL);
1309
0
        if (r == -1 && errno == ETIMEDOUT) {
1310
0
          send_error(ssh, "Timed out waiting "
1311
0
              "for SSH identification string.");
1312
0
          error("Connection timed out during "
1313
0
              "banner exchange");
1314
0
          r = SSH_ERR_CONN_TIMEOUT;
1315
0
          goto out;
1316
0
        } else if (r == -1) {
1317
0
          oerrno = errno;
1318
0
          error_f("%s", strerror(errno));
1319
0
          r = SSH_ERR_SYSTEM_ERROR;
1320
0
          goto out;
1321
0
        }
1322
0
      }
1323
1324
0
      len = atomicio(read, ssh_packet_get_connection_in(ssh),
1325
0
          &c, 1);
1326
0
      if (len != 1 && errno == EPIPE) {
1327
0
        verbose_f("Connection closed by remote host");
1328
0
        r = SSH_ERR_CONN_CLOSED;
1329
0
        goto out;
1330
0
      } else if (len != 1) {
1331
0
        oerrno = errno;
1332
0
        error_f("read: %.100s", strerror(errno));
1333
0
        r = SSH_ERR_SYSTEM_ERROR;
1334
0
        goto out;
1335
0
      }
1336
0
      if (c == '\r') {
1337
0
        expect_nl = 1;
1338
0
        continue;
1339
0
      }
1340
0
      if (c == '\n')
1341
0
        break;
1342
0
      if (c == '\0' || expect_nl) {
1343
0
        verbose_f("banner line contains invalid "
1344
0
            "characters");
1345
0
        goto invalid;
1346
0
      }
1347
0
      if ((r = sshbuf_put_u8(peer_version, c)) != 0) {
1348
0
        oerrno = errno;
1349
0
        error_fr(r, "sshbuf_put");
1350
0
        goto out;
1351
0
      }
1352
0
      if (sshbuf_len(peer_version) > SSH_MAX_BANNER_LEN) {
1353
0
        verbose_f("banner line too long");
1354
0
        goto invalid;
1355
0
      }
1356
0
    }
1357
    /* Is this an actual protocol banner? */
1358
0
    if (sshbuf_len(peer_version) > 4 &&
1359
0
        memcmp(sshbuf_ptr(peer_version), "SSH-", 4) == 0)
1360
0
      break;
1361
    /* If not, then just log the line and continue */
1362
0
    if ((cp = sshbuf_dup_string(peer_version)) == NULL) {
1363
0
      error_f("sshbuf_dup_string failed");
1364
0
      r = SSH_ERR_ALLOC_FAIL;
1365
0
      goto out;
1366
0
    }
1367
    /* Do not accept lines before the SSH ident from a client */
1368
0
    if (ssh->kex->server) {
1369
0
      verbose_f("client sent invalid protocol identifier "
1370
0
          "\"%.256s\"", cp);
1371
0
      free(cp);
1372
0
      goto invalid;
1373
0
    }
1374
0
    debug_f("banner line %zu: %s", n, cp);
1375
0
    free(cp);
1376
0
  }
1377
0
  peer_version_string = sshbuf_dup_string(peer_version);
1378
0
  if (peer_version_string == NULL)
1379
0
    fatal_f("sshbuf_dup_string failed");
1380
  /* XXX must be same size for sscanf */
1381
0
  if ((remote_version = calloc(1, sshbuf_len(peer_version))) == NULL) {
1382
0
    error_f("calloc failed");
1383
0
    r = SSH_ERR_ALLOC_FAIL;
1384
0
    goto out;
1385
0
  }
1386
1387
  /*
1388
   * Check that the versions match.  In future this might accept
1389
   * several versions and set appropriate flags to handle them.
1390
   */
1391
0
  if (sscanf(peer_version_string, "SSH-%d.%d-%[^\n]\n",
1392
0
      &remote_major, &remote_minor, remote_version) != 3) {
1393
0
    error("Bad remote protocol version identification: '%.100s'",
1394
0
        peer_version_string);
1395
0
 invalid:
1396
0
    send_error(ssh, "Invalid SSH identification string.");
1397
0
    r = SSH_ERR_INVALID_FORMAT;
1398
0
    goto out;
1399
0
  }
1400
0
  debug("Remote protocol version %d.%d, remote software version %.100s",
1401
0
      remote_major, remote_minor, remote_version);
1402
0
  compat_banner(ssh, remote_version);
1403
1404
0
  mismatch = 0;
1405
0
  switch (remote_major) {
1406
0
  case 2:
1407
0
    break;
1408
0
  case 1:
1409
0
    if (remote_minor != 99)
1410
0
      mismatch = 1;
1411
0
    break;
1412
0
  default:
1413
0
    mismatch = 1;
1414
0
    break;
1415
0
  }
1416
0
  if (mismatch) {
1417
0
    error("Protocol major versions differ: %d vs. %d",
1418
0
        PROTOCOL_MAJOR_2, remote_major);
1419
0
    send_error(ssh, "Protocol major versions differ.");
1420
0
    r = SSH_ERR_NO_PROTOCOL_VERSION;
1421
0
    goto out;
1422
0
  }
1423
1424
0
  if (ssh->kex->server && (ssh->compat & SSH_BUG_PROBE) != 0) {
1425
0
    logit("probed from %s port %d with %s.  Don't panic.",
1426
0
        ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
1427
0
        peer_version_string);
1428
0
    r = SSH_ERR_CONN_CLOSED; /* XXX */
1429
0
    goto out;
1430
0
  }
1431
0
  if (ssh->kex->server && (ssh->compat & SSH_BUG_SCANNER) != 0) {
1432
0
    logit("scanned from %s port %d with %s.  Don't panic.",
1433
0
        ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
1434
0
        peer_version_string);
1435
0
    r = SSH_ERR_CONN_CLOSED; /* XXX */
1436
0
    goto out;
1437
0
  }
1438
  /* success */
1439
0
  r = 0;
1440
0
 out:
1441
0
  free(our_version_string);
1442
0
  free(peer_version_string);
1443
0
  free(remote_version);
1444
0
  if (r == SSH_ERR_SYSTEM_ERROR)
1445
0
    errno = oerrno;
1446
0
  return r;
1447
0
}
1448