Coverage Report

Created: 2026-07-12 07:11

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/hpn-ssh/packet.c
Line
Count
Source
1
/* $OpenBSD: packet.c,v 1.334 2026/03/03 09:57:25 dtucker Exp $ */
2
/*
3
 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4
 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5
 *                    All rights reserved
6
 * This file contains code implementing the packet protocol and communication
7
 * with the other side.  This same code is used both on client and server side.
8
 *
9
 * As far as I am concerned, the code I have written for this software
10
 * can be used freely for any purpose.  Any derived versions of this
11
 * software must be clearly marked as such, and if the derived work is
12
 * incompatible with the protocol description in the RFC file, it must be
13
 * called by a name other than "ssh" or "Secure Shell".
14
 *
15
 *
16
 * SSH2 packet format added by Markus Friedl.
17
 * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
18
 *
19
 * Redistribution and use in source and binary forms, with or without
20
 * modification, are permitted provided that the following conditions
21
 * are met:
22
 * 1. Redistributions of source code must retain the above copyright
23
 *    notice, this list of conditions and the following disclaimer.
24
 * 2. Redistributions in binary form must reproduce the above copyright
25
 *    notice, this list of conditions and the following disclaimer in the
26
 *    documentation and/or other materials provided with the distribution.
27
 *
28
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
29
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
30
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
31
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
32
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
33
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
34
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
35
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
36
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
37
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38
 */
39
40
#include "includes.h"
41
42
#include <sys/types.h>
43
#include <sys/queue.h>
44
#include <sys/socket.h>
45
#include <sys/time.h>
46
47
#include <netinet/in.h>
48
#include <arpa/inet.h>
49
50
#include <errno.h>
51
#include <netdb.h>
52
#include <stdarg.h>
53
#include <stdio.h>
54
#include <stdlib.h>
55
#include <string.h>
56
#include <unistd.h>
57
#include <limits.h>
58
#include <poll.h>
59
#include <signal.h>
60
#include <time.h>
61
#include <util.h>
62
63
/*
64
 * Explicitly include OpenSSL before zlib as some versions of OpenSSL have
65
 * "free_func" in their headers, which zlib typedefs.
66
 */
67
#ifdef WITH_OPENSSL
68
# include <openssl/bn.h>
69
# include <openssl/evp.h>
70
# ifdef OPENSSL_HAS_ECC
71
#  include <openssl/ec.h>
72
# endif
73
#endif
74
75
#ifdef WITH_ZLIB
76
#include <zlib.h>
77
#endif
78
79
#include "xmalloc.h"
80
#include "compat.h"
81
#include "ssh2.h"
82
#include "cipher.h"
83
#include "kex.h"
84
#include "digest.h"
85
#include "mac.h"
86
#include "log.h"
87
#include "canohost.h"
88
#include "channels.h"
89
#include "misc.h"
90
#include "packet.h"
91
#include "ssherr.h"
92
#include "sshbuf.h"
93
94
#ifdef PACKET_DEBUG
95
#define DBG(x) x
96
#else
97
#define DBG(x)
98
#endif
99
100
/* OpenSSH usings 256KB packet size max but that consumes a
101
 * lot of memory with the buffers we are using. However, we need
102
 * a large packet size if the banner that's being sent is large.
103
 * So we need a 256KB packet pre authentication and a smaller one
104
 * in this case SSH_IOBUFSZ + 1KB, afterwards. So we change
105
 * PACKET_MAX_SIZE from a #define to a global. Then, in the function
106
 * ssh_packet_set_authentcated we reduce the size to something
107
 * more memory efficient. -cjr 04/07/23
108
 */
109
u_int packet_max_size = 256 * 1024;
110
111
/* global to support forced rekeying */
112
int rekey_requested = 0;
113
114
115
struct packet_state {
116
  uint32_t seqnr;
117
  uint32_t packets;
118
  uint64_t blocks;
119
  uint64_t bytes;
120
};
121
122
struct packet {
123
  TAILQ_ENTRY(packet) next;
124
  u_char type;
125
  struct sshbuf *payload;
126
};
127
128
struct session_state {
129
  /*
130
   * This variable contains the file descriptors used for
131
   * communicating with the other side.  connection_in is used for
132
   * reading; connection_out for writing.  These can be the same
133
   * descriptor, in which case it is assumed to be a socket.
134
   */
135
  int connection_in;
136
  int connection_out;
137
138
  /* Protocol flags for the remote side. */
139
  u_int remote_protocol_flags;
140
141
  /* Encryption context for receiving data.  Only used for decryption. */
142
  struct sshcipher_ctx *receive_context;
143
144
  /* Encryption context for sending data.  Only used for encryption. */
145
  struct sshcipher_ctx *send_context;
146
147
  /* Buffer for raw input data from the socket. */
148
  struct sshbuf *input;
149
150
  /* Buffer for raw output data going to the socket. */
151
  struct sshbuf *output;
152
153
  /* Buffer for the partial outgoing packet being constructed. */
154
  struct sshbuf *outgoing_packet;
155
156
  /* Buffer for the incoming packet currently being processed. */
157
  struct sshbuf *incoming_packet;
158
159
  /* Scratch buffer for packet compression/decompression. */
160
  struct sshbuf *compression_buffer;
161
162
#ifdef WITH_ZLIB
163
  /* Incoming/outgoing compression dictionaries */
164
  z_stream compression_in_stream;
165
  z_stream compression_out_stream;
166
#endif
167
  int compression_in_started;
168
  int compression_out_started;
169
  int compression_in_failures;
170
  int compression_out_failures;
171
172
  /* default maximum packet size */
173
  u_int max_packet_size;
174
175
  /* Flag indicating whether this module has been initialized. */
176
  int initialized;
177
178
  /* Set to true if the connection is interactive. */
179
  int interactive_mode;
180
181
  /* Set to true if we are the server side. */
182
  int server_side;
183
184
  /* Set to true if we are authenticated. */
185
  int after_authentication;
186
187
  int keep_alive_timeouts;
188
189
  /* The maximum time that we will wait to send or receive a packet */
190
  int packet_timeout_ms;
191
192
  /* Session key information for Encryption and MAC */
193
  struct newkeys *newkeys[MODE_MAX];
194
  struct packet_state p_read, p_send;
195
196
  /* Volume-based rekeying */
197
  uint64_t hard_max_blocks_in, hard_max_blocks_out;
198
  uint64_t max_blocks_in, max_blocks_out, rekey_limit;
199
200
  /* Time-based rekeying */
201
  uint32_t rekey_interval;  /* how often in seconds */
202
  time_t rekey_time;  /* time of last rekeying */
203
204
  /* roundup current message to extra_pad bytes */
205
  u_char extra_pad;
206
207
  /* XXX discard incoming data after MAC error */
208
  u_int packet_discard;
209
  size_t packet_discard_mac_already;
210
  struct sshmac *packet_discard_mac;
211
212
  /* Used in packet_read_poll2() */
213
  u_int packlen;
214
215
  /* Used in packet_send2 */
216
  int rekeying;
217
218
  /* Used in ssh_packet_send_mux() */
219
  int mux;
220
221
  /* QoS handling */
222
  int qos_interactive, qos_other;
223
224
  /* Used in packet_set_maxsize */
225
  int set_maxsize_called;
226
227
  /* One-off warning about weak ciphers */
228
  int cipher_warning_done;
229
230
  /*
231
   * Disconnect in progress. Used to prevent reentry in
232
   * ssh_packet_disconnect()
233
   */
234
  int disconnecting;
235
236
  /* Nagle disabled on socket */
237
  int nodelay_set;
238
239
  /* Hook for fuzzing inbound packets */
240
  ssh_packet_hook_fn *hook_in;
241
  void *hook_in_ctx;
242
243
  TAILQ_HEAD(, packet) outgoing;
244
};
245
246
struct ssh *
247
ssh_alloc_session_state(void)
248
59.2k
{
249
59.2k
  struct ssh *ssh = NULL;
250
59.2k
  struct session_state *state = NULL;
251
252
59.2k
  if ((ssh = calloc(1, sizeof(*ssh))) == NULL ||
253
59.2k
      (state = calloc(1, sizeof(*state))) == NULL ||
254
59.2k
      (ssh->kex = kex_new()) == NULL ||
255
59.2k
      (state->input = sshbuf_new()) == NULL ||
256
59.2k
      (state->output = sshbuf_new()) == NULL ||
257
59.2k
      (state->outgoing_packet = sshbuf_new()) == NULL ||
258
59.2k
      (state->incoming_packet = sshbuf_new()) == NULL)
259
0
    goto fail;
260
  /* these buffers are important in terms of tracking buffer usage
261
   * so we explicitly label and type them with descriptive names */
262
59.2k
  sshbuf_relabel(state->input, "input");
263
59.2k
  sshbuf_type(state->input, BUF_PACKET_INPUT);
264
59.2k
  sshbuf_relabel(state->incoming_packet, "inpacket");
265
59.2k
  sshbuf_type(state->incoming_packet, BUF_PACKET_INCOMING);
266
59.2k
  sshbuf_relabel(state->output, "output");
267
59.2k
  sshbuf_type(state->output, BUF_PACKET_OUTPUT);
268
59.2k
  sshbuf_relabel(state->outgoing_packet, "outpacket");
269
59.2k
  sshbuf_type(state->outgoing_packet, BUF_PACKET_OUTGOING);
270
271
59.2k
  TAILQ_INIT(&state->outgoing);
272
59.2k
  TAILQ_INIT(&ssh->private_keys);
273
59.2k
  TAILQ_INIT(&ssh->public_keys);
274
59.2k
  state->connection_in = -1;
275
59.2k
  state->connection_out = -1;
276
59.2k
  state->max_packet_size = CHAN_SES_PACKET_DEFAULT;
277
59.2k
  state->packet_timeout_ms = -1;
278
59.2k
  state->interactive_mode = 1;
279
59.2k
  state->qos_interactive = state->qos_other = -1;
280
59.2k
  state->p_send.packets = state->p_read.packets = 0;
281
59.2k
  state->initialized = 1;
282
  /*
283
   * ssh_packet_send2() needs to queue packets until
284
   * we've done the initial key exchange.
285
   */
286
59.2k
  state->rekeying = 1;
287
59.2k
  ssh->state = state;
288
59.2k
  return ssh;
289
0
 fail:
290
0
  if (ssh) {
291
0
    kex_free(ssh->kex);
292
0
    free(ssh);
293
0
  }
294
0
  if (state) {
295
0
    sshbuf_free(state->input);
296
0
    sshbuf_free(state->output);
297
0
    sshbuf_free(state->incoming_packet);
298
0
    sshbuf_free(state->outgoing_packet);
299
0
    free(state);
300
0
  }
301
0
  return NULL;
302
59.2k
}
303
304
void
305
ssh_packet_set_input_hook(struct ssh *ssh, ssh_packet_hook_fn *hook, void *ctx)
306
0
{
307
0
  ssh->state->hook_in = hook;
308
0
  ssh->state->hook_in_ctx = ctx;
309
0
}
310
311
/* Returns nonzero if rekeying is in progress */
312
int
313
ssh_packet_is_rekeying(struct ssh *ssh)
314
0
{
315
0
  return ssh->state->rekeying ||
316
0
      (ssh->kex != NULL && ssh->kex->done == 0);
317
0
}
318
319
/*
320
 * Sets the descriptors used for communication.
321
 */
322
struct ssh *
323
ssh_packet_set_connection(struct ssh *ssh, int fd_in, int fd_out)
324
59.2k
{
325
59.2k
  struct session_state *state;
326
59.2k
  struct sshcipher *none = cipher_by_name("none");
327
59.2k
  int r;
328
329
59.2k
  if (none == NULL) {
330
0
    error_f("cannot load cipher 'none'");
331
0
    return NULL;
332
0
  }
333
59.2k
  if (ssh == NULL)
334
59.2k
    ssh = ssh_alloc_session_state();
335
59.2k
  if (ssh == NULL) {
336
0
    error_f("could not allocate state");
337
0
    return NULL;
338
0
  }
339
59.2k
  state = ssh->state;
340
59.2k
  state->connection_in = fd_in;
341
59.2k
  state->connection_out = fd_out;
342
59.2k
  if ((r = cipher_init(&state->send_context, none, (const u_char *)"", 0,
343
59.2k
      NULL, 0, 0, CIPHER_ENCRYPT, state->after_authentication)) != 0 ||
344
59.2k
      (r = cipher_init(&state->receive_context, none, (const u_char *)"",
345
59.2k
      0, NULL, 0, 0, CIPHER_DECRYPT, state->after_authentication)) != 0) {
346
0
    error_fr(r, "cipher_init failed");
347
0
    free(ssh); /* XXX need ssh_free_session_state? */
348
0
    return NULL;
349
0
  }
350
59.2k
  state->newkeys[MODE_IN] = state->newkeys[MODE_OUT] = NULL;
351
  /*
352
   * Cache the IP address of the remote connection for use in error
353
   * messages that might be generated after the connection has closed.
354
   */
355
59.2k
  (void)ssh_remote_ipaddr(ssh);
356
59.2k
  return ssh;
357
59.2k
}
358
359
void
360
ssh_packet_set_timeout(struct ssh *ssh, int timeout, int count)
361
0
{
362
0
  struct session_state *state = ssh->state;
363
364
0
  if (timeout <= 0 || count <= 0) {
365
0
    state->packet_timeout_ms = -1;
366
0
    return;
367
0
  }
368
0
  if ((INT_MAX / 1000) / count < timeout)
369
0
    state->packet_timeout_ms = INT_MAX;
370
0
  else
371
0
    state->packet_timeout_ms = timeout * count * 1000;
372
0
}
373
374
void
375
ssh_packet_set_mux(struct ssh *ssh)
376
0
{
377
0
  ssh->state->mux = 1;
378
0
  ssh->state->rekeying = 0;
379
0
  kex_free(ssh->kex);
380
0
  ssh->kex = NULL;
381
0
}
382
383
int
384
ssh_packet_get_mux(struct ssh *ssh)
385
0
{
386
0
  return ssh->state->mux;
387
0
}
388
389
int
390
ssh_packet_set_log_preamble(struct ssh *ssh, const char *fmt, ...)
391
0
{
392
0
  va_list args;
393
0
  int r;
394
395
0
  free(ssh->log_preamble);
396
0
  if (fmt == NULL)
397
0
    ssh->log_preamble = NULL;
398
0
  else {
399
0
    va_start(args, fmt);
400
0
    r = vasprintf(&ssh->log_preamble, fmt, args);
401
0
    va_end(args);
402
0
    if (r < 0 || ssh->log_preamble == NULL)
403
0
      return SSH_ERR_ALLOC_FAIL;
404
0
  }
405
0
  return 0;
406
0
}
407
408
int
409
ssh_packet_stop_discard(struct ssh *ssh)
410
0
{
411
0
  struct session_state *state = ssh->state;
412
0
  int r;
413
414
0
  if (state->packet_discard_mac) {
415
0
    char buf[1024];
416
0
    size_t dlen = packet_max_size;
417
418
0
    if (dlen > state->packet_discard_mac_already)
419
0
      dlen -= state->packet_discard_mac_already;
420
0
    memset(buf, 'a', sizeof(buf));
421
0
    while (sshbuf_len(state->incoming_packet) < dlen)
422
0
      if ((r = sshbuf_put(state->incoming_packet, buf,
423
0
          sizeof(buf))) != 0)
424
0
        return r;
425
0
    (void) mac_compute(state->packet_discard_mac,
426
0
        state->p_read.seqnr,
427
0
        sshbuf_ptr(state->incoming_packet), dlen,
428
0
        NULL, 0);
429
0
  }
430
0
  logit("Finished discarding for %.200s port %d",
431
0
      ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
432
0
  return SSH_ERR_MAC_INVALID;
433
0
}
434
435
static int
436
ssh_packet_start_discard(struct ssh *ssh, struct sshenc *enc,
437
    struct sshmac *mac, size_t mac_already, u_int discard)
438
7.33k
{
439
7.33k
  struct session_state *state = ssh->state;
440
7.33k
  int r;
441
442
7.33k
  if (enc == NULL || !cipher_is_cbc(enc->cipher) || (mac && mac->etm)) {
443
7.33k
    if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0)
444
0
      return r;
445
7.33k
    return SSH_ERR_MAC_INVALID;
446
7.33k
  }
447
  /*
448
   * Record number of bytes over which the mac has already
449
   * been computed in order to minimize timing attacks.
450
   */
451
0
  if (mac && mac->enabled) {
452
0
    state->packet_discard_mac = mac;
453
0
    state->packet_discard_mac_already = mac_already;
454
0
  }
455
0
  if (sshbuf_len(state->input) >= discard)
456
0
    return ssh_packet_stop_discard(ssh);
457
0
  state->packet_discard = discard - sshbuf_len(state->input);
458
0
  return 0;
459
0
}
460
461
/* Returns 1 if remote host is connected via socket, 0 if not. */
462
463
int
464
ssh_packet_connection_is_on_socket(struct ssh *ssh)
465
59.2k
{
466
59.2k
  struct session_state *state;
467
59.2k
  struct sockaddr_storage from, to;
468
59.2k
  socklen_t fromlen, tolen;
469
470
59.2k
  if (ssh == NULL || ssh->state == NULL)
471
0
    return 0;
472
473
59.2k
  state = ssh->state;
474
59.2k
  if (state->connection_in == -1 || state->connection_out == -1)
475
59.2k
    return 0;
476
  /* filedescriptors in and out are the same, so it's a socket */
477
0
  if (state->connection_in == state->connection_out)
478
0
    return 1;
479
0
  fromlen = sizeof(from);
480
0
  memset(&from, 0, sizeof(from));
481
0
  if (getpeername(state->connection_in, (struct sockaddr *)&from,
482
0
      &fromlen) == -1)
483
0
    return 0;
484
0
  tolen = sizeof(to);
485
0
  memset(&to, 0, sizeof(to));
486
0
  if (getpeername(state->connection_out, (struct sockaddr *)&to,
487
0
      &tolen) == -1)
488
0
    return 0;
489
0
  if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
490
0
    return 0;
491
0
  if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
492
0
    return 0;
493
0
  return 1;
494
0
}
495
496
void
497
ssh_packet_get_bytes(struct ssh *ssh, uint64_t *ibytes, uint64_t *obytes)
498
0
{
499
0
  if (ibytes)
500
0
    *ibytes = ssh->state->p_read.bytes;
501
0
  if (obytes)
502
0
    *obytes = ssh->state->p_send.bytes;
503
0
}
504
505
int
506
ssh_packet_connection_af(struct ssh *ssh)
507
0
{
508
0
  return get_sock_af(ssh->state->connection_out);
509
0
}
510
511
/* Sets the connection into non-blocking mode. */
512
513
void
514
ssh_packet_set_nonblocking(struct ssh *ssh)
515
0
{
516
  /* Set the socket into non-blocking mode. */
517
0
  set_nonblock(ssh->state->connection_in);
518
519
0
  if (ssh->state->connection_out != ssh->state->connection_in)
520
0
    set_nonblock(ssh->state->connection_out);
521
0
}
522
523
/* Returns the socket used for reading. */
524
525
int
526
ssh_packet_get_connection_in(struct ssh *ssh)
527
0
{
528
0
  return ssh->state->connection_in;
529
0
}
530
531
/* Returns the descriptor used for writing. */
532
533
int
534
ssh_packet_get_connection_out(struct ssh *ssh)
535
0
{
536
0
  return ssh->state->connection_out;
537
0
}
538
539
/*
540
 * Returns the IP-address of the remote host as a string.  The returned
541
 * string must not be freed.
542
 */
543
544
const char *
545
ssh_remote_ipaddr(struct ssh *ssh)
546
59.2k
{
547
59.2k
  int sock;
548
549
  /* Check whether we have cached the ipaddr. */
550
59.2k
  if (ssh->remote_ipaddr == NULL) {
551
59.2k
    if (ssh_packet_connection_is_on_socket(ssh)) {
552
0
      sock = ssh->state->connection_in;
553
0
      ssh->remote_ipaddr = get_peer_ipaddr(sock);
554
0
      ssh->remote_port = get_peer_port(sock);
555
0
      ssh->local_ipaddr = get_local_ipaddr(sock);
556
0
      ssh->local_port = get_local_port(sock);
557
59.2k
    } else {
558
59.2k
      ssh->remote_ipaddr = xstrdup("UNKNOWN");
559
59.2k
      ssh->remote_port = 65535;
560
59.2k
      ssh->local_ipaddr = xstrdup("UNKNOWN");
561
59.2k
      ssh->local_port = 65535;
562
59.2k
    }
563
59.2k
  }
564
59.2k
  return ssh->remote_ipaddr;
565
59.2k
}
566
567
/*
568
 * Returns the remote DNS hostname as a string. The returned string must not
569
 * be freed. NB. this will usually trigger a DNS query. Return value is on
570
 * heap and no caching is performed.
571
 * This function does additional checks on the hostname to mitigate some
572
 * attacks based on conflation of hostnames and addresses and will
573
 * fall back to returning an address on error.
574
 */
575
576
char *
577
ssh_remote_hostname(struct ssh *ssh)
578
0
{
579
0
  struct sockaddr_storage from;
580
0
  socklen_t fromlen;
581
0
  struct addrinfo hints, *ai, *aitop;
582
0
  char name[NI_MAXHOST], ntop2[NI_MAXHOST];
583
0
  const char *ntop = ssh_remote_ipaddr(ssh);
584
585
  /* Get IP address of client. */
586
0
  fromlen = sizeof(from);
587
0
  memset(&from, 0, sizeof(from));
588
0
  if (getpeername(ssh_packet_get_connection_in(ssh),
589
0
      (struct sockaddr *)&from, &fromlen) == -1) {
590
0
    debug_f("getpeername failed: %.100s", strerror(errno));
591
0
    return xstrdup(ntop);
592
0
  }
593
594
0
  ipv64_normalise_mapped(&from, &fromlen);
595
0
  if (from.ss_family == AF_INET6)
596
0
    fromlen = sizeof(struct sockaddr_in6);
597
598
0
  debug3("trying to reverse map address %.100s.", ntop);
599
  /* Map the IP address to a host name. */
600
0
  if (getnameinfo((struct sockaddr *)&from, fromlen, name, sizeof(name),
601
0
      NULL, 0, NI_NAMEREQD) != 0) {
602
    /* Host name not found.  Use ip address. */
603
0
    return xstrdup(ntop);
604
0
  }
605
606
  /*
607
   * if reverse lookup result looks like a numeric hostname,
608
   * someone is trying to trick us by PTR record like following:
609
   *  1.1.1.10.in-addr.arpa.  IN PTR  2.3.4.5
610
   */
611
0
  memset(&hints, 0, sizeof(hints));
612
0
  hints.ai_socktype = SOCK_DGRAM; /*dummy*/
613
0
  hints.ai_flags = AI_NUMERICHOST;
614
0
  if (getaddrinfo(name, NULL, &hints, &ai) == 0) {
615
0
    logit("Nasty PTR record \"%s\" is set up for %s, ignoring",
616
0
        name, ntop);
617
0
    freeaddrinfo(ai);
618
0
    return xstrdup(ntop);
619
0
  }
620
621
  /* Names are stored in lowercase. */
622
0
  lowercase(name);
623
624
  /*
625
   * Map it back to an IP address and check that the given
626
   * address actually is an address of this host.  This is
627
   * necessary because anyone with access to a name server can
628
   * define arbitrary names for an IP address. Mapping from
629
   * name to IP address can be trusted better (but can still be
630
   * fooled if the intruder has access to the name server of
631
   * the domain).
632
   */
633
0
  memset(&hints, 0, sizeof(hints));
634
0
  hints.ai_family = from.ss_family;
635
0
  hints.ai_socktype = SOCK_STREAM;
636
0
  if (getaddrinfo(name, NULL, &hints, &aitop) != 0) {
637
0
    logit("reverse mapping checking getaddrinfo for %.700s "
638
0
        "[%s] failed.", name, ntop);
639
0
    return xstrdup(ntop);
640
0
  }
641
  /* Look for the address from the list of addresses. */
642
0
  for (ai = aitop; ai; ai = ai->ai_next) {
643
0
    if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop2,
644
0
        sizeof(ntop2), NULL, 0, NI_NUMERICHOST) == 0 &&
645
0
        (strcmp(ntop, ntop2) == 0))
646
0
        break;
647
0
  }
648
0
  freeaddrinfo(aitop);
649
  /* If we reached the end of the list, the address was not there. */
650
0
  if (ai == NULL) {
651
    /* Address not found for the host name. */
652
0
    logit("Address %.100s maps to %.600s, but this does not "
653
0
        "map back to the address.", ntop, name);
654
0
    return xstrdup(ntop);
655
0
  }
656
0
  return xstrdup(name);
657
0
}
658
659
/* Returns the port number of the remote host. */
660
661
int
662
ssh_remote_port(struct ssh *ssh)
663
0
{
664
0
  (void)ssh_remote_ipaddr(ssh); /* Will lookup and cache. */
665
0
  return ssh->remote_port;
666
0
}
667
668
/*
669
 * Returns the IP-address of the local host as a string.  The returned
670
 * string must not be freed.
671
 */
672
673
const char *
674
ssh_local_ipaddr(struct ssh *ssh)
675
0
{
676
0
  (void)ssh_remote_ipaddr(ssh); /* Will lookup and cache. */
677
0
  return ssh->local_ipaddr;
678
0
}
679
680
/* Returns the port number of the local host. */
681
682
int
683
ssh_local_port(struct ssh *ssh)
684
0
{
685
0
  (void)ssh_remote_ipaddr(ssh); /* Will lookup and cache. */
686
0
  return ssh->local_port;
687
0
}
688
689
/* Returns the routing domain of the input socket, or NULL if unavailable */
690
const char *
691
ssh_packet_rdomain_in(struct ssh *ssh)
692
0
{
693
0
  if (ssh->rdomain_in != NULL)
694
0
    return ssh->rdomain_in;
695
0
  if (!ssh_packet_connection_is_on_socket(ssh))
696
0
    return NULL;
697
0
  ssh->rdomain_in = get_rdomain(ssh->state->connection_in);
698
0
  return ssh->rdomain_in;
699
0
}
700
701
/* Closes the connection and clears and frees internal data structures. */
702
703
static void
704
ssh_packet_close_internal(struct ssh *ssh, int do_close)
705
59.2k
{
706
59.2k
  struct session_state *state = ssh->state;
707
59.2k
  u_int mode;
708
59.2k
  struct packet *p;
709
710
59.2k
  if (!state->initialized)
711
0
    return;
712
59.2k
  state->initialized = 0;
713
59.2k
  if (do_close) {
714
59.2k
    if (state->connection_in == state->connection_out) {
715
59.2k
      close(state->connection_out);
716
59.2k
    } else {
717
0
      close(state->connection_in);
718
0
      close(state->connection_out);
719
0
    }
720
59.2k
  }
721
59.2k
  sshbuf_free(state->input);
722
59.2k
  sshbuf_free(state->output);
723
59.2k
  sshbuf_free(state->outgoing_packet);
724
59.2k
  sshbuf_free(state->incoming_packet);
725
59.2k
  while ((p = TAILQ_FIRST(&state->outgoing))) {
726
0
    sshbuf_free(p->payload);
727
0
    TAILQ_REMOVE(&state->outgoing, p, next);
728
0
    free(p);
729
0
  }
730
177k
  for (mode = 0; mode < MODE_MAX; mode++) {
731
118k
    kex_free_newkeys(state->newkeys[mode]); /* current keys */
732
118k
    state->newkeys[mode] = NULL;
733
118k
    ssh_clear_newkeys(ssh, mode);   /* next keys */
734
118k
  }
735
59.2k
#ifdef WITH_ZLIB
736
  /* compression state is in shared mem, so we can only release it once */
737
59.2k
  if (do_close && state->compression_buffer) {
738
0
    sshbuf_free(state->compression_buffer);
739
0
    if (state->compression_out_started) {
740
0
      z_streamp stream = &state->compression_out_stream;
741
0
      debug("compress outgoing: "
742
0
          "raw data %llu, compressed %llu, factor %.2f",
743
0
        (unsigned long long)stream->total_in,
744
0
        (unsigned long long)stream->total_out,
745
0
        stream->total_in == 0 ? 0.0 :
746
0
        (double) stream->total_out / stream->total_in);
747
0
      if (state->compression_out_failures == 0)
748
0
        deflateEnd(stream);
749
0
    }
750
0
    if (state->compression_in_started) {
751
0
      z_streamp stream = &state->compression_in_stream;
752
0
      debug("compress incoming: "
753
0
          "raw data %llu, compressed %llu, factor %.2f",
754
0
          (unsigned long long)stream->total_out,
755
0
          (unsigned long long)stream->total_in,
756
0
          stream->total_out == 0 ? 0.0 :
757
0
          (double) stream->total_in / stream->total_out);
758
0
      if (state->compression_in_failures == 0)
759
0
        inflateEnd(stream);
760
0
    }
761
0
  }
762
59.2k
#endif  /* WITH_ZLIB */
763
59.2k
  cipher_free(state->send_context);
764
59.2k
  cipher_free(state->receive_context);
765
59.2k
  state->send_context = state->receive_context = NULL;
766
59.2k
  if (do_close) {
767
59.2k
    free(ssh->local_ipaddr);
768
59.2k
    ssh->local_ipaddr = NULL;
769
59.2k
    free(ssh->remote_ipaddr);
770
59.2k
    ssh->remote_ipaddr = NULL;
771
59.2k
    free(ssh->state);
772
59.2k
    ssh->state = NULL;
773
59.2k
    kex_free(ssh->kex);
774
59.2k
    ssh->kex = NULL;
775
59.2k
  }
776
59.2k
}
777
778
void
779
ssh_packet_free(struct ssh *ssh)
780
0
{
781
0
  ssh_packet_close_internal(ssh, 1);
782
0
  freezero(ssh, sizeof(*ssh));
783
0
}
784
785
void
786
ssh_packet_close(struct ssh *ssh)
787
59.2k
{
788
59.2k
  ssh_packet_close_internal(ssh, 1);
789
59.2k
}
790
791
void
792
ssh_packet_clear_keys(struct ssh *ssh)
793
0
{
794
0
  ssh_packet_close_internal(ssh, 0);
795
0
}
796
797
/* Sets remote side protocol flags. */
798
799
void
800
ssh_packet_set_protocol_flags(struct ssh *ssh, u_int protocol_flags)
801
0
{
802
0
  ssh->state->remote_protocol_flags = protocol_flags;
803
0
}
804
805
/* Returns the remote protocol flags set earlier by the above function. */
806
807
u_int
808
ssh_packet_get_protocol_flags(struct ssh *ssh)
809
0
{
810
0
  return ssh->state->remote_protocol_flags;
811
0
}
812
813
/*
814
 * Starts packet compression from the next packet on in both directions.
815
 * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
816
 */
817
818
static int
819
ssh_packet_init_compression(struct ssh *ssh)
820
0
{
821
0
  if (!ssh->state->compression_buffer &&
822
0
      ((ssh->state->compression_buffer = sshbuf_new()) == NULL))
823
0
    return SSH_ERR_ALLOC_FAIL;
824
0
  return 0;
825
0
}
826
827
#ifdef WITH_ZLIB
828
static int
829
start_compression_out(struct ssh *ssh, int level)
830
0
{
831
0
  if (level < 1 || level > 9)
832
0
    return SSH_ERR_INVALID_ARGUMENT;
833
0
  debug("Enabling compression at level %d.", level);
834
0
  if (ssh->state->compression_out_started == 1)
835
0
    deflateEnd(&ssh->state->compression_out_stream);
836
0
  switch (deflateInit(&ssh->state->compression_out_stream, level)) {
837
0
  case Z_OK:
838
0
    ssh->state->compression_out_started = 1;
839
0
    break;
840
0
  case Z_MEM_ERROR:
841
0
    return SSH_ERR_ALLOC_FAIL;
842
0
  default:
843
0
    return SSH_ERR_INTERNAL_ERROR;
844
0
  }
845
0
  return 0;
846
0
}
847
848
static int
849
start_compression_in(struct ssh *ssh)
850
0
{
851
0
  if (ssh->state->compression_in_started == 1)
852
0
    inflateEnd(&ssh->state->compression_in_stream);
853
0
  switch (inflateInit(&ssh->state->compression_in_stream)) {
854
0
  case Z_OK:
855
0
    ssh->state->compression_in_started = 1;
856
0
    break;
857
0
  case Z_MEM_ERROR:
858
0
    return SSH_ERR_ALLOC_FAIL;
859
0
  default:
860
0
    return SSH_ERR_INTERNAL_ERROR;
861
0
  }
862
0
  return 0;
863
0
}
864
865
/* XXX remove need for separate compression buffer */
866
static int
867
compress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
868
0
{
869
0
  u_char buf[4096];
870
0
  int r, status;
871
872
0
  if (ssh->state->compression_out_started != 1)
873
0
    return SSH_ERR_INTERNAL_ERROR;
874
875
  /* This case is not handled below. */
876
0
  if (sshbuf_len(in) == 0)
877
0
    return 0;
878
879
  /* Input is the contents of the input buffer. */
880
0
  if ((ssh->state->compression_out_stream.next_in =
881
0
      sshbuf_mutable_ptr(in)) == NULL)
882
0
    return SSH_ERR_INTERNAL_ERROR;
883
0
  ssh->state->compression_out_stream.avail_in = sshbuf_len(in);
884
885
  /* Loop compressing until deflate() returns with avail_out != 0. */
886
0
  do {
887
    /* Set up fixed-size output buffer. */
888
0
    ssh->state->compression_out_stream.next_out = buf;
889
0
    ssh->state->compression_out_stream.avail_out = sizeof(buf);
890
891
    /* Compress as much data into the buffer as possible. */
892
0
    status = deflate(&ssh->state->compression_out_stream,
893
0
        Z_PARTIAL_FLUSH);
894
0
    switch (status) {
895
0
    case Z_MEM_ERROR:
896
0
      return SSH_ERR_ALLOC_FAIL;
897
0
    case Z_OK:
898
      /* Append compressed data to output_buffer. */
899
0
      if ((r = sshbuf_put(out, buf, sizeof(buf) -
900
0
          ssh->state->compression_out_stream.avail_out)) != 0)
901
0
        return r;
902
0
      break;
903
0
    case Z_STREAM_ERROR:
904
0
    default:
905
0
      ssh->state->compression_out_failures++;
906
0
      return SSH_ERR_INVALID_FORMAT;
907
0
    }
908
0
  } while (ssh->state->compression_out_stream.avail_out == 0);
909
0
  return 0;
910
0
}
911
912
static int
913
uncompress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
914
0
{
915
0
  u_char buf[4096];
916
0
  int r, status;
917
918
0
  if (ssh->state->compression_in_started != 1)
919
0
    return SSH_ERR_INTERNAL_ERROR;
920
921
0
  if ((ssh->state->compression_in_stream.next_in =
922
0
      sshbuf_mutable_ptr(in)) == NULL)
923
0
    return SSH_ERR_INTERNAL_ERROR;
924
0
  ssh->state->compression_in_stream.avail_in = sshbuf_len(in);
925
926
0
  for (;;) {
927
    /* Set up fixed-size output buffer. */
928
0
    ssh->state->compression_in_stream.next_out = buf;
929
0
    ssh->state->compression_in_stream.avail_out = sizeof(buf);
930
931
0
    status = inflate(&ssh->state->compression_in_stream,
932
0
        Z_SYNC_FLUSH);
933
0
    switch (status) {
934
0
    case Z_OK:
935
0
      if ((r = sshbuf_put(out, buf, sizeof(buf) -
936
0
          ssh->state->compression_in_stream.avail_out)) != 0)
937
0
        return r;
938
0
      break;
939
0
    case Z_BUF_ERROR:
940
      /*
941
       * Comments in zlib.h say that we should keep calling
942
       * inflate() until we get an error.  This appears to
943
       * be the error that we get.
944
       */
945
0
      return 0;
946
0
    case Z_DATA_ERROR:
947
0
      return SSH_ERR_INVALID_FORMAT;
948
0
    case Z_MEM_ERROR:
949
0
      return SSH_ERR_ALLOC_FAIL;
950
0
    case Z_STREAM_ERROR:
951
0
    default:
952
0
      ssh->state->compression_in_failures++;
953
0
      return SSH_ERR_INTERNAL_ERROR;
954
0
    }
955
0
  }
956
  /* NOTREACHED */
957
0
}
958
959
#else /* WITH_ZLIB */
960
961
static int
962
start_compression_out(struct ssh *ssh, int level)
963
{
964
  return SSH_ERR_INTERNAL_ERROR;
965
}
966
967
static int
968
start_compression_in(struct ssh *ssh)
969
{
970
  return SSH_ERR_INTERNAL_ERROR;
971
}
972
973
static int
974
compress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
975
{
976
  return SSH_ERR_INTERNAL_ERROR;
977
}
978
979
static int
980
uncompress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
981
{
982
  return SSH_ERR_INTERNAL_ERROR;
983
}
984
#endif  /* WITH_ZLIB */
985
986
void
987
ssh_clear_newkeys(struct ssh *ssh, int mode)
988
118k
{
989
118k
  if (ssh->kex && ssh->kex->newkeys[mode]) {
990
89
    kex_free_newkeys(ssh->kex->newkeys[mode]);
991
89
    ssh->kex->newkeys[mode] = NULL;
992
89
  }
993
118k
}
994
995
int
996
ssh_set_newkeys(struct ssh *ssh, int mode)
997
0
{
998
0
  struct session_state *state = ssh->state;
999
0
  struct sshenc *enc;
1000
0
  struct sshmac *mac;
1001
0
  struct sshcomp *comp;
1002
0
  struct sshcipher_ctx **ccp;
1003
0
  struct packet_state *ps;
1004
0
  uint64_t *max_blocks, *hard_max_blocks;
1005
0
  const char *wmsg;
1006
0
  int r, crypt_type;
1007
0
  const char *dir = mode == MODE_OUT ? "out" : "in";
1008
0
  char blocks_s[FMT_SCALED_STRSIZE], bytes_s[FMT_SCALED_STRSIZE];
1009
1010
0
  debug2_f("mode %d", mode);
1011
1012
0
  if (mode == MODE_OUT) {
1013
0
    ccp = &state->send_context;
1014
0
    crypt_type = CIPHER_ENCRYPT;
1015
0
    ps = &state->p_send;
1016
0
    hard_max_blocks = &state->hard_max_blocks_out;
1017
0
    max_blocks = &state->max_blocks_out;
1018
0
  } else {
1019
0
    ccp = &state->receive_context;
1020
0
    crypt_type = CIPHER_DECRYPT;
1021
0
    ps = &state->p_read;
1022
0
    hard_max_blocks = &state->hard_max_blocks_in;
1023
0
    max_blocks = &state->max_blocks_in;
1024
0
  }
1025
0
  if (state->newkeys[mode] != NULL) {
1026
0
    debug_f("rekeying %s, input %llu bytes %llu blocks, "
1027
0
        "output %llu bytes %llu blocks", dir,
1028
0
        (unsigned long long)state->p_read.bytes,
1029
0
        (unsigned long long)state->p_read.blocks,
1030
0
        (unsigned long long)state->p_send.bytes,
1031
0
        (unsigned long long)state->p_send.blocks);
1032
0
    kex_free_newkeys(state->newkeys[mode]);
1033
0
    state->newkeys[mode] = NULL;
1034
0
  }
1035
  /* note that both bytes and the seqnr are not reset */
1036
0
  ps->packets = ps->blocks = 0;
1037
  /* move newkeys from kex to state */
1038
0
  if ((state->newkeys[mode] = ssh->kex->newkeys[mode]) == NULL)
1039
0
    return SSH_ERR_INTERNAL_ERROR;
1040
0
  ssh->kex->newkeys[mode] = NULL;
1041
0
  enc  = &state->newkeys[mode]->enc;
1042
0
  mac  = &state->newkeys[mode]->mac;
1043
0
  comp = &state->newkeys[mode]->comp;
1044
0
  if (cipher_authlen(enc->cipher) == 0) {
1045
0
    if ((r = mac_init(mac)) != 0)
1046
0
      return r;
1047
0
  }
1048
1049
  /* if we are using NONE MAC then we don't need to enable the
1050
   * mac routines. This disables them and we can claw back some cycles
1051
   * from the CPU -cjr 3/21/2023 */
1052
0
  if (ssh->none_mac != 1)
1053
0
    mac->enabled = 1;
1054
1055
0
  DBG(debug_f("cipher_init: %s", dir));
1056
0
  cipher_free(*ccp);
1057
0
  *ccp = NULL;
1058
0
#ifdef WITH_OPENSSL
1059
0
  if (strcmp(enc->name, "chacha20-poly1305-mt@hpnssh.org") == 0) {
1060
0
    if (state->after_authentication)
1061
0
      enc->cipher = cipher_by_name(
1062
0
          "chacha20-poly1305-mt@hpnssh.org");
1063
0
    else
1064
0
      enc->cipher = cipher_by_name(
1065
0
          "chacha20-poly1305@openssh.com");
1066
0
    if (enc->cipher == NULL)
1067
0
      return r;
1068
0
  }
1069
0
#endif
1070
0
  if ((r = cipher_init(ccp, enc->cipher, enc->key, enc->key_len, enc->iv,
1071
0
      enc->iv_len, crypt_type ? state->p_send.seqnr : state->p_read.seqnr,
1072
0
      crypt_type, state->after_authentication)) != 0)
1073
0
    return r;
1074
0
  if (!state->cipher_warning_done &&
1075
0
      (wmsg = cipher_warning_message(*ccp)) != NULL) {
1076
0
    error("Warning: %s", wmsg);
1077
0
    state->cipher_warning_done = 1;
1078
0
  }
1079
  /* Deleting the keys does not gain extra security */
1080
  /* explicit_bzero(enc->iv,  enc->block_size);
1081
     explicit_bzero(enc->key, enc->key_len);
1082
     explicit_bzero(mac->key, mac->key_len); */
1083
0
  if (((comp->type == COMP_DELAYED && state->after_authentication)) &&
1084
0
      comp->enabled == 0) {
1085
0
    if ((r = ssh_packet_init_compression(ssh)) < 0)
1086
0
      return r;
1087
0
    if (mode == MODE_OUT) {
1088
0
      if ((r = start_compression_out(ssh, 6)) != 0)
1089
0
        return r;
1090
0
    } else {
1091
0
      if ((r = start_compression_in(ssh)) != 0)
1092
0
        return r;
1093
0
    }
1094
0
    comp->enabled = 1;
1095
0
  }
1096
  /* get the maximum number of blocks the cipher can
1097
   * handle safely */
1098
0
  *hard_max_blocks = cipher_rekey_blocks(enc->cipher);
1099
0
  *max_blocks = *hard_max_blocks;
1100
1101
  /* if we have a custom oRekeyLimit use that. */
1102
0
  if (state->rekey_limit) {
1103
0
                *max_blocks = MINIMUM(*max_blocks,
1104
0
                    state->rekey_limit / enc->block_size);
1105
0
  }
1106
1107
  /* these lines support the debug */
1108
0
  strlcpy(blocks_s, "?", sizeof(blocks_s));
1109
0
  strlcpy(bytes_s, "?", sizeof(bytes_s));
1110
0
  if (*max_blocks * enc->block_size < LLONG_MAX) {
1111
0
    fmt_scaled((long long)*max_blocks, blocks_s);
1112
0
    fmt_scaled((long long)*max_blocks * enc->block_size, bytes_s);
1113
0
  }
1114
0
  debug("rekey %s after %s blocks / %sB data", dir, blocks_s, bytes_s);
1115
1116
0
  return 0;
1117
0
}
1118
1119
/* this supports the forced rekeying required for the NONE cipher */
1120
void
1121
packet_request_rekeying(void)
1122
0
{
1123
0
  rekey_requested = 1;
1124
0
}
1125
1126
/* used to determine if pre or post auth when rekeying for aes-ctr
1127
 * and none cipher switch */
1128
int
1129
packet_authentication_state(const struct ssh *ssh)
1130
4.51k
{
1131
4.51k
  struct session_state *state = ssh->state;
1132
1133
4.51k
  return state->after_authentication;
1134
4.51k
}
1135
1136
7.13M
#define MAX_PACKETS (1U<<31)
1137
/*
1138
 * Checks whether the packet- or block- based rekeying limits have been
1139
 * exceeded. If the 'hard' flag is set, the checks are performed against the
1140
 * absolute maximum we're willing to accept for the given cipher. Otherwise
1141
 * the checks are performed against the RekeyLimit volume, which may be lower.
1142
 */
1143
static inline int
1144
ssh_packet_check_rekey_blocklimit(struct ssh *ssh, u_int packet_len, int hard)
1145
2.37M
{
1146
2.37M
  struct session_state *state = ssh->state;
1147
2.37M
  uint32_t out_blocks;
1148
2.37M
  const uint64_t max_blocks_in = hard ?
1149
2.37M
      state->hard_max_blocks_in : state->max_blocks_in;
1150
2.37M
  const uint64_t max_blocks_out = hard ?
1151
2.37M
      state->hard_max_blocks_out : state->max_blocks_out;
1152
1153
  /*
1154
   * Always rekey when MAX_PACKETS sent in either direction
1155
   * As per RFC4344 section 3.1 we do this after 2^31 packets.
1156
   */
1157
2.37M
  if (state->p_send.packets > MAX_PACKETS ||
1158
2.37M
      state->p_read.packets > MAX_PACKETS)
1159
0
    return 1;
1160
1161
2.37M
  if (state->newkeys[MODE_OUT] == NULL)
1162
2.37M
    return 0;
1163
1164
  /* Rekey after (cipher-specific) maximum blocks */
1165
0
  out_blocks = ROUNDUP(packet_len,
1166
0
      state->newkeys[MODE_OUT]->enc.block_size);
1167
0
  return (max_blocks_out &&
1168
0
      (state->p_send.blocks + out_blocks > max_blocks_out)) ||
1169
0
      (max_blocks_in &&
1170
0
      (state->p_read.blocks > max_blocks_in));
1171
2.37M
}
1172
1173
static int
1174
ssh_packet_need_rekeying(struct ssh *ssh, u_int outbound_packet_len)
1175
2.37M
{
1176
2.37M
  struct session_state *state = ssh->state;
1177
1178
  /* Don't attempt rekeying during pre-auth */
1179
2.37M
  if (!state->after_authentication)
1180
2.37M
    return 0;
1181
1182
  /* Haven't keyed yet or KEX in progress. */
1183
0
  if (ssh_packet_is_rekeying(ssh))
1184
0
    return 0;
1185
1186
  /*
1187
   * Permit one packet in or out per rekey - this allows us to
1188
   * make progress when rekey limits are very small.
1189
   */
1190
0
  if (state->p_send.packets == 0 && state->p_read.packets == 0)
1191
0
    return 0;
1192
1193
        /* used to force rekeying when called for by the none
1194
         * cipher switch and aes-mt-ctr methods -cjr */
1195
0
        if (rekey_requested == 1) {
1196
0
    debug_f("Got the rekey request");
1197
0
    rekey_requested = 0;
1198
0
                return 1;
1199
0
        }
1200
1201
  /* Time-based rekeying */
1202
0
  if (state->rekey_interval != 0 &&
1203
0
      (int64_t)state->rekey_time + state->rekey_interval <= monotime())
1204
0
    return 1;
1205
1206
0
  return ssh_packet_check_rekey_blocklimit(ssh, outbound_packet_len, 0);
1207
0
}
1208
1209
/* Checks that the hard rekey limits have not been exceeded during preauth */
1210
static int
1211
ssh_packet_check_rekey_preauth(struct ssh *ssh, u_int outgoing_packet_len)
1212
2.37M
{
1213
2.37M
  if (ssh->state->after_authentication)
1214
0
    return 0;
1215
1216
2.37M
  if (ssh_packet_check_rekey_blocklimit(ssh, 0, 1)) {
1217
0
    error("RekeyLimit exceeded before authentication completed");
1218
0
    return SSH_ERR_NEED_REKEY;
1219
0
  }
1220
2.37M
  return 0;
1221
2.37M
}
1222
1223
int
1224
ssh_packet_check_rekey(struct ssh *ssh)
1225
2.37M
{
1226
2.37M
  int r;
1227
1228
2.37M
  if ((r = ssh_packet_check_rekey_preauth(ssh, 0)) != 0)
1229
0
    return r;
1230
2.37M
  if (!ssh_packet_need_rekeying(ssh, 0))
1231
2.37M
    return 0;
1232
0
  debug3_f("rekex triggered");
1233
0
  return kex_start_rekex(ssh);
1234
2.37M
}
1235
1236
/*
1237
 * Delayed compression for SSH2 is enabled after authentication:
1238
 * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
1239
 * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
1240
 */
1241
static int
1242
ssh_packet_enable_delayed_compress(struct ssh *ssh)
1243
0
{
1244
0
  struct session_state *state = ssh->state;
1245
0
  struct sshcomp *comp = NULL;
1246
0
  int r, mode;
1247
1248
  /*
1249
   * Remember that we are past the authentication step, so rekeying
1250
   * with COMP_DELAYED will turn on compression immediately.
1251
   */
1252
0
  state->after_authentication = 1;
1253
0
  for (mode = 0; mode < MODE_MAX; mode++) {
1254
    /* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
1255
0
    if (state->newkeys[mode] == NULL)
1256
0
      continue;
1257
0
    comp = &state->newkeys[mode]->comp;
1258
0
    if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
1259
0
      if ((r = ssh_packet_init_compression(ssh)) != 0)
1260
0
        return r;
1261
0
      if (mode == MODE_OUT) {
1262
0
        if ((r = start_compression_out(ssh, 6)) != 0)
1263
0
          return r;
1264
0
      } else {
1265
0
        if ((r = start_compression_in(ssh)) != 0)
1266
0
          return r;
1267
0
      }
1268
0
      comp->enabled = 1;
1269
0
    }
1270
0
  }
1271
0
  return 0;
1272
0
}
1273
1274
/* Used to mute debug logging for noisy packet types */
1275
int
1276
ssh_packet_log_type(u_char type)
1277
4.77M
{
1278
4.77M
  switch (type) {
1279
0
  case SSH2_MSG_PING:
1280
0
  case SSH2_MSG_PONG:
1281
0
  case SSH2_MSG_CHANNEL_DATA:
1282
0
  case SSH2_MSG_CHANNEL_EXTENDED_DATA:
1283
0
  case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
1284
0
    return 0;
1285
4.77M
  default:
1286
4.77M
    return 1;
1287
4.77M
  }
1288
4.77M
}
1289
1290
/*
1291
 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
1292
 */
1293
int
1294
ssh_packet_send2_wrapped(struct ssh *ssh)
1295
2.39M
{
1296
2.39M
  struct session_state *state = ssh->state;
1297
2.39M
  u_char type, *cp, macbuf[SSH_DIGEST_MAX_LENGTH];
1298
2.39M
  u_char tmp, padlen, pad = 0;
1299
2.39M
  u_int authlen = 0, aadlen = 0;
1300
2.39M
  u_int len;
1301
2.39M
  struct sshenc *enc   = NULL;
1302
2.39M
  struct sshmac *mac   = NULL;
1303
2.39M
  struct sshcomp *comp = NULL;
1304
2.39M
  int r, block_size;
1305
1306
2.39M
  if (state->newkeys[MODE_OUT] != NULL) {
1307
0
    enc  = &state->newkeys[MODE_OUT]->enc;
1308
0
    mac  = &state->newkeys[MODE_OUT]->mac;
1309
0
    comp = &state->newkeys[MODE_OUT]->comp;
1310
    /* disable mac for authenticated encryption */
1311
0
    if ((authlen = cipher_authlen(enc->cipher)) != 0)
1312
0
      mac = NULL;
1313
0
  }
1314
2.39M
  block_size = enc ? enc->block_size : 8;
1315
2.39M
  aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
1316
1317
2.39M
  type = (sshbuf_ptr(state->outgoing_packet))[5];
1318
2.39M
  if (ssh_packet_log_type(type))
1319
2.39M
    debug3("send packet: type %u", type);
1320
#ifdef PACKET_DEBUG
1321
  fprintf(stderr, "plain:     ");
1322
  sshbuf_dump(state->outgoing_packet, stderr);
1323
#endif
1324
1325
2.39M
  if (comp && comp->enabled) {
1326
0
    len = sshbuf_len(state->outgoing_packet);
1327
    /* skip header, compress only payload */
1328
0
    if ((r = sshbuf_consume(state->outgoing_packet, 5)) != 0)
1329
0
      goto out;
1330
0
    sshbuf_reset(state->compression_buffer);
1331
0
    if ((r = compress_buffer(ssh, state->outgoing_packet,
1332
0
        state->compression_buffer)) != 0)
1333
0
      goto out;
1334
0
    sshbuf_reset(state->outgoing_packet);
1335
0
    if ((r = sshbuf_put(state->outgoing_packet,
1336
0
        "\0\0\0\0\0", 5)) != 0 ||
1337
0
        (r = sshbuf_putb(state->outgoing_packet,
1338
0
        state->compression_buffer)) != 0)
1339
0
      goto out;
1340
0
    DBG(debug("compression: raw %d compressed %zd", len,
1341
0
        sshbuf_len(state->outgoing_packet)));
1342
0
  }
1343
1344
  /* sizeof (packet_len + pad_len + payload) */
1345
2.39M
  len = sshbuf_len(state->outgoing_packet);
1346
1347
  /*
1348
   * calc size of padding, alloc space, get random data,
1349
   * minimum padding is 4 bytes
1350
   */
1351
2.39M
  len -= aadlen; /* packet length is not encrypted for EtM modes */
1352
2.39M
  padlen = block_size - (len % block_size);
1353
2.39M
  if (padlen < 4)
1354
3.17k
    padlen += block_size;
1355
2.39M
  if (state->extra_pad) {
1356
0
    tmp = state->extra_pad;
1357
0
    state->extra_pad =
1358
0
        ROUNDUP(state->extra_pad, block_size);
1359
    /* check if roundup overflowed */
1360
0
    if (state->extra_pad < tmp)
1361
0
      return SSH_ERR_INVALID_ARGUMENT;
1362
0
    tmp = (len + padlen) % state->extra_pad;
1363
    /* Check whether pad calculation below will underflow */
1364
0
    if (tmp > state->extra_pad)
1365
0
      return SSH_ERR_INVALID_ARGUMENT;
1366
0
    pad = state->extra_pad - tmp;
1367
0
    DBG(debug3_f("adding %d (len %d padlen %d extra_pad %d)",
1368
0
        pad, len, padlen, state->extra_pad));
1369
0
    tmp = padlen;
1370
0
    padlen += pad;
1371
    /* Check whether padlen calculation overflowed */
1372
0
    if (padlen < tmp)
1373
0
      return SSH_ERR_INVALID_ARGUMENT; /* overflow */
1374
0
    state->extra_pad = 0;
1375
0
  }
1376
2.39M
  if ((r = sshbuf_reserve(state->outgoing_packet, padlen, &cp)) != 0)
1377
0
    goto out;
1378
2.39M
  if (enc && !cipher_ctx_is_plaintext(state->send_context)) {
1379
    /* random padding */
1380
0
    arc4random_buf(cp, padlen);
1381
2.39M
  } else {
1382
    /* clear padding */
1383
2.39M
    explicit_bzero(cp, padlen);
1384
2.39M
  }
1385
  /* sizeof (packet_len + pad_len + payload + padding) */
1386
2.39M
  len = sshbuf_len(state->outgoing_packet);
1387
2.39M
  cp = sshbuf_mutable_ptr(state->outgoing_packet);
1388
2.39M
  if (cp == NULL) {
1389
0
    r = SSH_ERR_INTERNAL_ERROR;
1390
0
    goto out;
1391
0
  }
1392
  /* packet_length includes payload, padding and padding length field */
1393
2.39M
  POKE_U32(cp, len - 4);
1394
2.39M
  cp[4] = padlen;
1395
2.39M
  DBG(debug("send: len %d (includes padlen %d, aadlen %d)",
1396
2.39M
      len, padlen, aadlen));
1397
1398
  /* compute MAC over seqnr and packet(length fields, payload, padding) */
1399
2.39M
  if (mac && mac->enabled && !mac->etm) {
1400
0
    if ((r = mac_compute(mac, state->p_send.seqnr,
1401
0
        sshbuf_ptr(state->outgoing_packet), len,
1402
0
        macbuf, sizeof(macbuf))) != 0)
1403
0
      goto out;
1404
0
    DBG(debug("done calc MAC out #%d", state->p_send.seqnr));
1405
0
  }
1406
  /* encrypt packet and append to output buffer. */
1407
2.39M
  if ((r = sshbuf_reserve(state->output,
1408
2.39M
      sshbuf_len(state->outgoing_packet) + authlen, &cp)) != 0)
1409
0
    goto out;
1410
2.39M
  if ((r = cipher_crypt(state->send_context, state->p_send.seqnr, cp,
1411
2.39M
      sshbuf_ptr(state->outgoing_packet), len - aadlen, aadlen, authlen))
1412
2.39M
      != 0)
1413
0
    goto out;
1414
  /* append unencrypted MAC */
1415
2.39M
  if (mac && mac->enabled) {
1416
0
    if (mac->etm) {
1417
      /* EtM: compute mac over aadlen + cipher text */
1418
0
      if ((r = mac_compute(mac, state->p_send.seqnr,
1419
0
          cp, len, macbuf, sizeof(macbuf))) != 0)
1420
0
        goto out;
1421
0
      DBG(debug("done calc MAC(EtM) out #%d",
1422
0
          state->p_send.seqnr));
1423
0
    }
1424
0
    if ((r = sshbuf_put(state->output, macbuf, mac->mac_len)) != 0)
1425
0
      goto out;
1426
0
  }
1427
#ifdef PACKET_DEBUG
1428
  fprintf(stderr, "encrypted: ");
1429
  sshbuf_dump(state->output, stderr);
1430
#endif
1431
  /* increment sequence number for outgoing packets */
1432
2.39M
  if (++state->p_send.seqnr == 0) {
1433
0
    if ((ssh->kex->flags & KEX_INITIAL) != 0) {
1434
0
      ssh_packet_disconnect(ssh, "outgoing sequence number "
1435
0
          "wrapped during initial key exchange");
1436
0
    }
1437
0
    logit("outgoing seqnr wraps around");
1438
0
  }
1439
2.39M
  if (++state->p_send.packets == 0)
1440
0
    return SSH_ERR_NEED_REKEY;
1441
2.39M
  state->p_send.blocks += len / block_size;
1442
2.39M
  state->p_send.bytes += len;
1443
2.39M
  sshbuf_reset(state->outgoing_packet);
1444
1445
2.39M
  if (type == SSH2_MSG_NEWKEYS && ssh->kex->kex_strict) {
1446
0
    debug_f("resetting send seqnr %u", state->p_send.seqnr);
1447
0
    state->p_send.seqnr = 0;
1448
0
  }
1449
1450
2.39M
  if (type == SSH2_MSG_NEWKEYS)
1451
0
    r = ssh_set_newkeys(ssh, MODE_OUT);
1452
2.39M
  else if (type == SSH2_MSG_USERAUTH_SUCCESS && state->server_side)
1453
0
    r = ssh_packet_enable_delayed_compress(ssh);
1454
2.39M
  else
1455
2.39M
    r = 0;
1456
2.39M
 out:
1457
2.39M
  return r;
1458
2.39M
}
1459
1460
/* returns non-zero if the specified packet type is usec by KEX */
1461
static int
1462
ssh_packet_type_is_kex(u_char type)
1463
4.79M
{
1464
4.79M
  return
1465
4.79M
      type >= SSH2_MSG_TRANSPORT_MIN &&
1466
4.79M
      type <= SSH2_MSG_TRANSPORT_MAX &&
1467
4.79M
      type != SSH2_MSG_SERVICE_REQUEST &&
1468
4.79M
      type != SSH2_MSG_SERVICE_ACCEPT &&
1469
4.79M
      type != SSH2_MSG_EXT_INFO;
1470
4.79M
}
1471
1472
int
1473
ssh_packet_send2(struct ssh *ssh)
1474
2.39M
{
1475
2.39M
  struct session_state *state = ssh->state;
1476
2.39M
  struct packet *p;
1477
2.39M
  u_char type;
1478
2.39M
  int r, need_rekey;
1479
1480
2.39M
  if (sshbuf_len(state->outgoing_packet) < 6)
1481
0
    return SSH_ERR_INTERNAL_ERROR;
1482
2.39M
  type = sshbuf_ptr(state->outgoing_packet)[5];
1483
2.39M
  need_rekey = !ssh_packet_type_is_kex(type) &&
1484
0
      ssh_packet_need_rekeying(ssh, sshbuf_len(state->outgoing_packet));
1485
1486
  /* Enforce hard rekey limit during pre-auth */
1487
2.39M
  if (!state->rekeying && !ssh_packet_type_is_kex(type) &&
1488
0
      (r = ssh_packet_check_rekey_preauth(ssh, 0)) != 0)
1489
0
    return r;
1490
1491
  /*
1492
   * During rekeying we can only send key exchange messages.
1493
   * Queue everything else.
1494
   */
1495
2.39M
  if ((need_rekey || state->rekeying) && !ssh_packet_type_is_kex(type)) {
1496
0
    if (need_rekey)
1497
0
      debug3_f("rekex triggered");
1498
0
    debug_f("enqueue packet: %u", type);
1499
0
    p = calloc(1, sizeof(*p));
1500
0
    if (p == NULL)
1501
0
      return SSH_ERR_ALLOC_FAIL;
1502
0
    p->type = type;
1503
0
    p->payload = state->outgoing_packet;
1504
0
    TAILQ_INSERT_TAIL(&state->outgoing, p, next);
1505
0
    state->outgoing_packet = sshbuf_new();
1506
0
    if (state->outgoing_packet == NULL)
1507
0
      return SSH_ERR_ALLOC_FAIL;
1508
0
    if (need_rekey) {
1509
      /*
1510
       * This packet triggered a rekey, so send the
1511
       * KEXINIT now.
1512
       * NB. reenters this function via kex_start_rekex().
1513
       */
1514
0
      return kex_start_rekex(ssh);
1515
0
    }
1516
0
    return 0;
1517
0
  }
1518
1519
  /* rekeying starts with sending KEXINIT */
1520
2.39M
  if (type == SSH2_MSG_KEXINIT)
1521
17.8k
    state->rekeying = 1;
1522
1523
2.39M
  if ((r = ssh_packet_send2_wrapped(ssh)) != 0)
1524
0
    return r;
1525
1526
  /* after a NEWKEYS message we can send the complete queue */
1527
2.39M
  if (type == SSH2_MSG_NEWKEYS) {
1528
0
    state->rekeying = 0;
1529
0
    state->rekey_time = monotime();
1530
0
    while ((p = TAILQ_FIRST(&state->outgoing))) {
1531
0
      type = p->type;
1532
      /*
1533
       * If this packet triggers a rekex, then skip the
1534
       * remaining packets in the queue for now.
1535
       * NB. re-enters this function via kex_start_rekex.
1536
       */
1537
0
      if (ssh_packet_need_rekeying(ssh,
1538
0
          sshbuf_len(p->payload))) {
1539
0
        debug3_f("queued packet triggered rekex");
1540
0
        return kex_start_rekex(ssh);
1541
0
      }
1542
0
      debug_f("dequeue packet: %u", type);
1543
0
      sshbuf_free(state->outgoing_packet);
1544
0
      state->outgoing_packet = p->payload;
1545
0
      TAILQ_REMOVE(&state->outgoing, p, next);
1546
0
      memset(p, 0, sizeof(*p));
1547
0
      free(p);
1548
0
      if ((r = ssh_packet_send2_wrapped(ssh)) != 0)
1549
0
        return r;
1550
0
    }
1551
0
  }
1552
2.39M
  return 0;
1553
2.39M
}
1554
1555
/*
1556
 * Waits until a packet has been received, and returns its type.  Note that
1557
 * no other data is processed until this returns, so this function should not
1558
 * be used during the interactive session.
1559
 */
1560
1561
int
1562
ssh_packet_read_seqnr(struct ssh *ssh, u_char *typep, uint32_t *seqnr_p)
1563
0
{
1564
0
  struct session_state *state = ssh->state;
1565
0
  int len, r, ms_remain = 0;
1566
0
  struct pollfd pfd;
1567
0
  char buf[SSH_IOBUFSZ];
1568
0
  struct timeval start;
1569
0
  struct timespec timespec, *timespecp = NULL;
1570
1571
0
  DBG(debug("packet_read()"));
1572
1573
  /*
1574
   * Since we are blocking, ensure that all written packets have
1575
   * been sent.
1576
   */
1577
0
  if ((r = ssh_packet_write_wait(ssh)) != 0)
1578
0
    goto out;
1579
1580
  /* Stay in the loop until we have received a complete packet. */
1581
0
  for (;;) {
1582
    /* Try to read a packet from the buffer. */
1583
0
    if ((r = ssh_packet_read_poll_seqnr(ssh, typep, seqnr_p)) != 0)
1584
0
      break;
1585
    /* If we got a packet, return it. */
1586
0
    if (*typep != SSH_MSG_NONE)
1587
0
      break;
1588
    /*
1589
     * Otherwise, wait for some data to arrive, add it to the
1590
     * buffer, and try again.
1591
     */
1592
0
    pfd.fd = state->connection_in;
1593
0
    pfd.events = POLLIN;
1594
1595
0
    if (state->packet_timeout_ms > 0) {
1596
0
      ms_remain = state->packet_timeout_ms;
1597
0
      timespecp = &timespec;
1598
0
    }
1599
    /* Wait for some data to arrive. */
1600
0
    for (;;) {
1601
0
      if (state->packet_timeout_ms > 0) {
1602
0
        ms_to_timespec(&timespec, ms_remain);
1603
0
        monotime_tv(&start);
1604
0
      }
1605
0
      if ((r = ppoll(&pfd, 1, timespecp, NULL)) >= 0)
1606
0
        break;
1607
0
      if (errno != EAGAIN && errno != EINTR &&
1608
0
          errno != EWOULDBLOCK) {
1609
0
        r = SSH_ERR_SYSTEM_ERROR;
1610
0
        goto out;
1611
0
      }
1612
0
      if (state->packet_timeout_ms <= 0)
1613
0
        continue;
1614
0
      ms_subtract_diff(&start, &ms_remain);
1615
0
      if (ms_remain <= 0) {
1616
0
        r = 0;
1617
0
        break;
1618
0
      }
1619
0
    }
1620
0
    if (r == 0) {
1621
0
      r = SSH_ERR_CONN_TIMEOUT;
1622
0
      goto out;
1623
0
    }
1624
    /* Read data from the socket. */
1625
0
    len = read(state->connection_in, buf, sizeof(buf));
1626
0
    if (len == 0) {
1627
0
      r = SSH_ERR_CONN_CLOSED;
1628
0
      goto out;
1629
0
    }
1630
0
    if (len == -1) {
1631
0
      r = SSH_ERR_SYSTEM_ERROR;
1632
0
      goto out;
1633
0
    }
1634
1635
    /* Append it to the buffer. */
1636
0
    if ((r = ssh_packet_process_incoming(ssh, buf, len)) != 0)
1637
0
      goto out;
1638
0
  }
1639
0
 out:
1640
0
  return r;
1641
0
}
1642
1643
int
1644
ssh_packet_read(struct ssh *ssh)
1645
0
{
1646
0
  u_char type;
1647
0
  int r;
1648
1649
0
  if ((r = ssh_packet_read_seqnr(ssh, &type, NULL)) != 0)
1650
0
    fatal_fr(r, "read");
1651
0
  return type;
1652
0
}
1653
1654
static int
1655
ssh_packet_read_poll2_mux(struct ssh *ssh, u_char *typep, uint32_t *seqnr_p)
1656
0
{
1657
0
  struct session_state *state = ssh->state;
1658
0
  const u_char *cp;
1659
0
  size_t need;
1660
0
  int r;
1661
1662
0
  if (ssh->kex)
1663
0
    return SSH_ERR_INTERNAL_ERROR;
1664
0
  *typep = SSH_MSG_NONE;
1665
0
  cp = sshbuf_ptr(state->input);
1666
0
  if (state->packlen == 0) {
1667
0
    if (sshbuf_len(state->input) < 4 + 1)
1668
0
      return 0; /* packet is incomplete */
1669
0
    state->packlen = PEEK_U32(cp);
1670
0
    if (state->packlen < 4 + 1 ||
1671
0
        state->packlen > packet_max_size)
1672
0
      return SSH_ERR_MESSAGE_INCOMPLETE;
1673
0
  }
1674
0
  need = state->packlen + 4;
1675
0
  if (sshbuf_len(state->input) < need)
1676
0
    return 0; /* packet is incomplete */
1677
0
  sshbuf_reset(state->incoming_packet);
1678
0
  if ((r = sshbuf_put(state->incoming_packet, cp + 4,
1679
0
      state->packlen)) != 0 ||
1680
0
      (r = sshbuf_consume(state->input, need)) != 0 ||
1681
0
      (r = sshbuf_get_u8(state->incoming_packet, NULL)) != 0 ||
1682
0
      (r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
1683
0
    return r;
1684
0
  if (ssh_packet_log_type(*typep))
1685
0
    debug3_f("type %u", *typep);
1686
  /* sshbuf_dump(state->incoming_packet, stderr); */
1687
  /* reset for next packet */
1688
0
  state->packlen = 0;
1689
0
  return r;
1690
0
}
1691
1692
int
1693
ssh_packet_read_poll2(struct ssh *ssh, u_char *typep, uint32_t *seqnr_p)
1694
2.38M
{
1695
2.38M
  struct session_state *state = ssh->state;
1696
2.38M
  u_int padlen, need;
1697
2.38M
  u_char *cp;
1698
2.38M
  u_int maclen, aadlen = 0, authlen = 0, block_size;
1699
2.38M
  struct sshenc *enc   = NULL;
1700
2.38M
  struct sshmac *mac   = NULL;
1701
2.38M
  struct sshcomp *comp = NULL;
1702
2.38M
  int r;
1703
1704
2.38M
  if (state->mux)
1705
0
    return ssh_packet_read_poll2_mux(ssh, typep, seqnr_p);
1706
1707
2.38M
  *typep = SSH_MSG_NONE;
1708
1709
2.38M
  if (state->packet_discard)
1710
0
    return 0;
1711
1712
2.38M
  if (state->newkeys[MODE_IN] != NULL) {
1713
0
    enc  = &state->newkeys[MODE_IN]->enc;
1714
0
    mac  = &state->newkeys[MODE_IN]->mac;
1715
0
    comp = &state->newkeys[MODE_IN]->comp;
1716
    /* disable mac for authenticated encryption */
1717
0
    if ((authlen = cipher_authlen(enc->cipher)) != 0)
1718
0
      mac = NULL;
1719
0
  }
1720
2.38M
  maclen = mac && mac->enabled ? mac->mac_len : 0;
1721
2.38M
  block_size = enc ? enc->block_size : 8;
1722
2.38M
  aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
1723
1724
2.38M
  if (aadlen && state->packlen == 0) {
1725
0
    if (cipher_get_length(state->receive_context, &state->packlen,
1726
0
        state->p_read.seqnr, sshbuf_ptr(state->input),
1727
0
        sshbuf_len(state->input)) != 0)
1728
0
      return 0;
1729
0
    if (state->packlen < 1 + 4 ||
1730
0
        state->packlen > packet_max_size) {
1731
#ifdef PACKET_DEBUG
1732
      sshbuf_dump(state->input, stderr);
1733
#endif
1734
0
      logit("Bad packet length %u.", state->packlen);
1735
0
      if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0)
1736
0
        return r;
1737
0
      return SSH_ERR_CONN_CORRUPT;
1738
0
    }
1739
0
    sshbuf_reset(state->incoming_packet);
1740
2.38M
  } else if (state->packlen == 0) {
1741
    /*
1742
     * check if input size is less than the cipher block size,
1743
     * decrypt first block and extract length of incoming packet
1744
     */
1745
2.38M
    if (sshbuf_len(state->input) < block_size)
1746
0
      return 0;
1747
2.38M
    sshbuf_reset(state->incoming_packet);
1748
2.38M
    if ((r = sshbuf_reserve(state->incoming_packet, block_size,
1749
2.38M
        &cp)) != 0)
1750
0
      goto out;
1751
2.38M
    if ((r = cipher_crypt(state->receive_context,
1752
2.38M
        state->p_send.seqnr, cp, sshbuf_ptr(state->input),
1753
2.38M
        block_size, 0, 0)) != 0)
1754
0
      goto out;
1755
2.38M
    state->packlen = PEEK_U32(sshbuf_ptr(state->incoming_packet));
1756
2.38M
    if (state->packlen < 1 + 4 ||
1757
2.38M
        state->packlen > packet_max_size) {
1758
#ifdef PACKET_DEBUG
1759
      fprintf(stderr, "input: \n");
1760
      sshbuf_dump(state->input, stderr);
1761
      fprintf(stderr, "incoming_packet: \n");
1762
      sshbuf_dump(state->incoming_packet, stderr);
1763
#endif
1764
6.75k
      logit("Bad packet length %u.", state->packlen);
1765
6.75k
      return ssh_packet_start_discard(ssh, enc, mac, 0,
1766
6.75k
          packet_max_size);
1767
6.75k
    }
1768
2.38M
    if ((r = sshbuf_consume(state->input, block_size)) != 0)
1769
0
      goto out;
1770
2.38M
  }
1771
2.38M
  DBG(debug("input: packet len %u", state->packlen+4));
1772
1773
2.38M
  if (aadlen) {
1774
    /* only the payload is encrypted */
1775
0
    need = state->packlen;
1776
2.38M
  } else {
1777
    /*
1778
     * the payload size and the payload are encrypted, but we
1779
     * have a partial packet of block_size bytes
1780
     */
1781
2.38M
    need = 4 + state->packlen - block_size;
1782
2.38M
  }
1783
2.38M
  DBG(debug("partial packet: block %d, need %d, maclen %d, authlen %d,"
1784
2.38M
      " aadlen %d", block_size, need, maclen, authlen, aadlen));
1785
2.38M
  if (need % block_size != 0) {
1786
585
    logit("padding error: need %d block %d mod %d",
1787
585
        need, block_size, need % block_size);
1788
585
    return ssh_packet_start_discard(ssh, enc, mac, 0,
1789
585
        packet_max_size - block_size);
1790
585
  }
1791
  /*
1792
   * check if the entire packet has been received and
1793
   * decrypt into incoming_packet:
1794
   * 'aadlen' bytes are unencrypted, but authenticated.
1795
   * 'need' bytes are encrypted, followed by either
1796
   * 'authlen' bytes of authentication tag or
1797
   * 'maclen' bytes of message authentication code.
1798
   */
1799
2.38M
  if (sshbuf_len(state->input) < aadlen + need + authlen + maclen)
1800
0
    return 0; /* packet is incomplete */
1801
#ifdef PACKET_DEBUG
1802
  fprintf(stderr, "read_poll enc/full: ");
1803
  sshbuf_dump(state->input, stderr);
1804
#endif
1805
  /* EtM: check mac over encrypted input */
1806
2.38M
  if (mac && mac->enabled && mac->etm) {
1807
0
    if ((r = mac_check(mac, state->p_read.seqnr,
1808
0
        sshbuf_ptr(state->input), aadlen + need,
1809
0
        sshbuf_ptr(state->input) + aadlen + need + authlen,
1810
0
        maclen)) != 0) {
1811
0
      if (r == SSH_ERR_MAC_INVALID)
1812
0
        logit("Corrupted MAC on input.");
1813
0
      goto out;
1814
0
    }
1815
0
  }
1816
2.38M
  if ((r = sshbuf_reserve(state->incoming_packet, aadlen + need,
1817
2.38M
      &cp)) != 0)
1818
0
    goto out;
1819
2.38M
  if ((r = cipher_crypt(state->receive_context, state->p_read.seqnr, cp,
1820
2.38M
      sshbuf_ptr(state->input), need, aadlen, authlen)) != 0)
1821
0
    goto out;
1822
2.38M
  if ((r = sshbuf_consume(state->input, aadlen + need + authlen)) != 0)
1823
0
    goto out;
1824
2.38M
  if (mac && mac->enabled) {
1825
    /* Not EtM: check MAC over cleartext */
1826
0
    if (!mac->etm && (r = mac_check(mac, state->p_read.seqnr,
1827
0
        sshbuf_ptr(state->incoming_packet),
1828
0
        sshbuf_len(state->incoming_packet),
1829
0
        sshbuf_ptr(state->input), maclen)) != 0) {
1830
0
      if (r != SSH_ERR_MAC_INVALID)
1831
0
        goto out;
1832
0
      logit("Corrupted MAC on input.");
1833
0
      if (need + block_size > packet_max_size)
1834
0
        return SSH_ERR_INTERNAL_ERROR;
1835
0
      return ssh_packet_start_discard(ssh, enc, mac,
1836
0
          sshbuf_len(state->incoming_packet),
1837
0
          packet_max_size - need - block_size);
1838
0
    }
1839
    /* Remove MAC from input buffer */
1840
0
    DBG(debug("MAC #%d ok", state->p_read.seqnr));
1841
0
    if ((r = sshbuf_consume(state->input, mac->mac_len)) != 0)
1842
0
      goto out;
1843
0
  }
1844
1845
2.38M
  if (seqnr_p != NULL)
1846
2.38M
    *seqnr_p = state->p_read.seqnr;
1847
2.38M
  if (++state->p_read.seqnr == 0) {
1848
0
    if ((ssh->kex->flags & KEX_INITIAL) != 0) {
1849
0
      ssh_packet_disconnect(ssh, "incoming sequence number "
1850
0
          "wrapped during initial key exchange");
1851
0
    }
1852
0
    logit("incoming seqnr wraps around");
1853
0
  }
1854
2.38M
  if (++state->p_read.packets == 0)
1855
0
    return SSH_ERR_NEED_REKEY;
1856
2.38M
  state->p_read.blocks += (state->packlen + 4) / block_size;
1857
2.38M
  state->p_read.bytes += state->packlen + 4;
1858
1859
  /* get padlen */
1860
2.38M
  padlen = sshbuf_ptr(state->incoming_packet)[4];
1861
2.38M
  DBG(debug("input: padlen %d", padlen));
1862
2.38M
  if (padlen < 4)  {
1863
555
    if ((r = sshpkt_disconnect(ssh,
1864
555
        "Corrupted padlen %d on input.", padlen)) != 0 ||
1865
555
        (r = ssh_packet_write_wait(ssh)) != 0)
1866
555
      return r;
1867
0
    return SSH_ERR_CONN_CORRUPT;
1868
555
  }
1869
1870
  /* skip packet size + padlen, discard padding */
1871
2.37M
  if ((r = sshbuf_consume(state->incoming_packet, 4 + 1)) != 0 ||
1872
2.37M
      ((r = sshbuf_consume_end(state->incoming_packet, padlen)) != 0))
1873
570
    goto out;
1874
1875
2.37M
  DBG(debug("input: len before de-compress %zd",
1876
2.37M
      sshbuf_len(state->incoming_packet)));
1877
2.37M
  if (comp && comp->enabled) {
1878
0
    sshbuf_reset(state->compression_buffer);
1879
0
    if ((r = uncompress_buffer(ssh, state->incoming_packet,
1880
0
        state->compression_buffer)) != 0)
1881
0
      goto out;
1882
0
    sshbuf_reset(state->incoming_packet);
1883
0
    if ((r = sshbuf_putb(state->incoming_packet,
1884
0
        state->compression_buffer)) != 0)
1885
0
      goto out;
1886
0
    DBG(debug("input: len after de-compress %zd",
1887
0
        sshbuf_len(state->incoming_packet)));
1888
0
  }
1889
  /*
1890
   * get packet type, implies consume.
1891
   * return length of payload (without type field)
1892
   */
1893
2.37M
  if ((r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
1894
105
    goto out;
1895
2.37M
  if (ssh_packet_log_type(*typep))
1896
2.37M
    debug3("receive packet: type %u", *typep);
1897
2.37M
  if (*typep < SSH2_MSG_MIN) {
1898
240
    if ((r = sshpkt_disconnect(ssh,
1899
240
        "Invalid ssh2 packet type: %d", *typep)) != 0 ||
1900
240
        (r = ssh_packet_write_wait(ssh)) != 0)
1901
240
      return r;
1902
0
    return SSH_ERR_PROTOCOL_ERROR;
1903
240
  }
1904
2.37M
  if (state->hook_in != NULL &&
1905
0
      (r = state->hook_in(ssh, state->incoming_packet, typep,
1906
0
      state->hook_in_ctx)) != 0)
1907
0
    return r;
1908
2.37M
  if (*typep == SSH2_MSG_USERAUTH_SUCCESS && !state->server_side)
1909
0
    r = ssh_packet_enable_delayed_compress(ssh);
1910
2.37M
  else
1911
2.37M
    r = 0;
1912
#ifdef PACKET_DEBUG
1913
  fprintf(stderr, "read/plain[%d]:\r\n", *typep);
1914
  sshbuf_dump(state->incoming_packet, stderr);
1915
#endif
1916
  /* reset for next packet */
1917
2.37M
  state->packlen = 0;
1918
2.37M
  if (*typep == SSH2_MSG_NEWKEYS && ssh->kex->kex_strict) {
1919
0
    debug_f("resetting read seqnr %u", state->p_read.seqnr);
1920
0
    state->p_read.seqnr = 0;
1921
0
  }
1922
1923
2.37M
  if ((r = ssh_packet_check_rekey(ssh)) != 0)
1924
0
    return r;
1925
2.37M
 out:
1926
2.37M
  return r;
1927
2.37M
}
1928
1929
int
1930
ssh_packet_read_poll_seqnr(struct ssh *ssh, u_char *typep, uint32_t *seqnr_p)
1931
0
{
1932
0
  struct session_state *state = ssh->state;
1933
0
  u_int reason, seqnr;
1934
0
  int r;
1935
0
  u_char *msg;
1936
0
  const u_char *d;
1937
0
  size_t len;
1938
1939
0
  for (;;) {
1940
0
    msg = NULL;
1941
0
    r = ssh_packet_read_poll2(ssh, typep, seqnr_p);
1942
0
    if (r != 0)
1943
0
      return r;
1944
0
    if (*typep == 0) {
1945
      /* no message ready */
1946
0
      return 0;
1947
0
    }
1948
0
    state->keep_alive_timeouts = 0;
1949
0
    DBG(debug("received packet type %d", *typep));
1950
1951
    /* Always process disconnect messages */
1952
0
    if (*typep == SSH2_MSG_DISCONNECT) {
1953
0
      if ((r = sshpkt_get_u32(ssh, &reason)) != 0 ||
1954
0
          (r = sshpkt_get_string(ssh, &msg, NULL)) != 0)
1955
0
        return r;
1956
      /* Ignore normal client exit notifications */
1957
0
      do_log2(ssh->state->server_side &&
1958
0
          reason == SSH2_DISCONNECT_BY_APPLICATION ?
1959
0
          SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_ERROR,
1960
0
          "Received disconnect from %s port %d:"
1961
0
          "%u: %.400s", ssh_remote_ipaddr(ssh),
1962
0
          ssh_remote_port(ssh), reason, msg);
1963
0
      free(msg);
1964
0
      return SSH_ERR_DISCONNECTED;
1965
0
    }
1966
1967
    /*
1968
     * Do not implicitly handle any messages here during initial
1969
     * KEX when in strict mode. They will be need to be allowed
1970
     * explicitly by the KEX dispatch table or they will generate
1971
     * protocol errors.
1972
     */
1973
0
    if (ssh->kex != NULL &&
1974
0
        (ssh->kex->flags & KEX_INITIAL) && ssh->kex->kex_strict)
1975
0
      return 0;
1976
    /* Implicitly handle transport-level messages */
1977
0
    switch (*typep) {
1978
0
    case SSH2_MSG_IGNORE:
1979
0
      debug3("Received SSH2_MSG_IGNORE");
1980
0
      break;
1981
0
    case SSH2_MSG_DEBUG:
1982
0
      if ((r = sshpkt_get_u8(ssh, NULL)) != 0 ||
1983
0
          (r = sshpkt_get_string(ssh, &msg, NULL)) != 0 ||
1984
0
          (r = sshpkt_get_string(ssh, NULL, NULL)) != 0) {
1985
0
        free(msg);
1986
0
        return r;
1987
0
      }
1988
0
      debug("Remote: %.900s", msg);
1989
0
      free(msg);
1990
0
      break;
1991
0
    case SSH2_MSG_UNIMPLEMENTED:
1992
0
      if ((r = sshpkt_get_u32(ssh, &seqnr)) != 0)
1993
0
        return r;
1994
0
      debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1995
0
          seqnr);
1996
0
      break;
1997
0
    case SSH2_MSG_PING:
1998
0
      if ((r = sshpkt_get_string_direct(ssh, &d, &len)) != 0)
1999
0
        return r;
2000
0
      DBG(debug("Received SSH2_MSG_PING len %zu", len));
2001
0
      if (!ssh->state->after_authentication) {
2002
0
        DBG(debug("Won't reply to PING in preauth"));
2003
0
        break;
2004
0
      }
2005
0
      if (ssh_packet_is_rekeying(ssh)) {
2006
0
        DBG(debug("Won't reply to PING during KEX"));
2007
0
        break;
2008
0
      }
2009
0
      if ((r = sshpkt_start(ssh, SSH2_MSG_PONG)) != 0 ||
2010
0
          (r = sshpkt_put_string(ssh, d, len)) != 0 ||
2011
0
          (r = sshpkt_send(ssh)) != 0)
2012
0
        return r;
2013
0
      break;
2014
0
    case SSH2_MSG_PONG:
2015
0
      if ((r = sshpkt_get_string_direct(ssh,
2016
0
          NULL, &len)) != 0)
2017
0
        return r;
2018
0
      DBG(debug("Received SSH2_MSG_PONG len %zu", len));
2019
0
      break;
2020
0
    default:
2021
0
      return 0;
2022
0
    }
2023
0
  }
2024
0
}
2025
2026
/*
2027
 * Buffers the supplied input data. This is intended to be used together
2028
 * with packet_read_poll().
2029
 */
2030
int
2031
ssh_packet_process_incoming(struct ssh *ssh, const char *buf, u_int len)
2032
0
{
2033
0
  struct session_state *state = ssh->state;
2034
0
  int r;
2035
2036
0
  if (state->packet_discard) {
2037
0
    state->keep_alive_timeouts = 0; /* ?? */
2038
0
    if (len >= state->packet_discard) {
2039
0
      if ((r = ssh_packet_stop_discard(ssh)) != 0)
2040
0
        return r;
2041
0
    }
2042
0
    state->packet_discard -= len;
2043
0
    return 0;
2044
0
  }
2045
0
  if ((r = sshbuf_put(state->input, buf, len)) != 0)
2046
0
    return r;
2047
2048
0
  return 0;
2049
0
}
2050
2051
/* Reads and buffers data from the specified fd */
2052
int
2053
ssh_packet_process_read(struct ssh *ssh, int fd)
2054
0
{
2055
0
  struct session_state *state = ssh->state;
2056
0
  int r;
2057
0
  size_t rlen;
2058
2059
0
  if ((r = sshbuf_read(fd, state->input, packet_max_size, &rlen)) != 0)
2060
0
    return r;
2061
2062
0
  if (state->packet_discard) {
2063
0
    if ((r = sshbuf_consume_end(state->input, rlen)) != 0)
2064
0
      return r;
2065
0
    state->keep_alive_timeouts = 0; /* ?? */
2066
0
    if (rlen >= state->packet_discard) {
2067
0
      if ((r = ssh_packet_stop_discard(ssh)) != 0)
2068
0
        return r;
2069
0
    }
2070
0
    state->packet_discard -= rlen;
2071
0
    return 0;
2072
0
  }
2073
0
  return 0;
2074
0
}
2075
2076
int
2077
ssh_packet_remaining(struct ssh *ssh)
2078
0
{
2079
0
  return sshbuf_len(ssh->state->incoming_packet);
2080
0
}
2081
2082
/*
2083
 * Sends a diagnostic message from the server to the client.  This message
2084
 * can be sent at any time (but not while constructing another message). The
2085
 * message is printed immediately, but only if the client is being executed
2086
 * in verbose mode.  These messages are primarily intended to ease debugging
2087
 * authentication problems.   The length of the formatted message must not
2088
 * exceed 1024 bytes.  This will automatically call ssh_packet_write_wait.
2089
 */
2090
void
2091
ssh_packet_send_debug(struct ssh *ssh, const char *fmt,...)
2092
0
{
2093
0
  char buf[1024];
2094
0
  va_list args;
2095
0
  int r;
2096
2097
0
  if ((ssh->compat & SSH_BUG_DEBUG))
2098
0
    return;
2099
2100
0
  va_start(args, fmt);
2101
0
  vsnprintf(buf, sizeof(buf), fmt, args);
2102
0
  va_end(args);
2103
2104
0
  debug3("sending debug message: %s", buf);
2105
2106
0
  if ((r = sshpkt_start(ssh, SSH2_MSG_DEBUG)) != 0 ||
2107
0
      (r = sshpkt_put_u8(ssh, 0)) != 0 || /* always display */
2108
0
      (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
2109
0
      (r = sshpkt_put_cstring(ssh, "")) != 0 ||
2110
0
      (r = sshpkt_send(ssh)) != 0 ||
2111
0
      (r = ssh_packet_write_wait(ssh)) != 0)
2112
0
    fatal_fr(r, "send DEBUG");
2113
0
}
2114
2115
void
2116
sshpkt_fmt_connection_id(struct ssh *ssh, char *s, size_t l)
2117
0
{
2118
0
  snprintf(s, l, "%.200s%s%s port %d",
2119
0
      ssh->log_preamble ? ssh->log_preamble : "",
2120
0
      ssh->log_preamble ? " " : "",
2121
0
      ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
2122
0
}
2123
2124
/*
2125
 * Pretty-print connection-terminating errors and exit.
2126
 */
2127
static void
2128
sshpkt_vfatal(struct ssh *ssh, int r, const char *fmt, va_list ap)
2129
0
{
2130
0
  char *tag = NULL, remote_id[512];
2131
0
  int oerrno = errno;
2132
2133
0
  sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id));
2134
2135
0
  switch (r) {
2136
0
  case SSH_ERR_CONN_CLOSED:
2137
0
    ssh_packet_clear_keys(ssh);
2138
0
    sshpkt_final_log_entry(ssh);
2139
0
    logdie("Connection closed by %s", remote_id);
2140
0
  case SSH_ERR_CONN_TIMEOUT:
2141
0
    ssh_packet_clear_keys(ssh);
2142
0
    sshpkt_final_log_entry(ssh);
2143
0
    logdie("Connection %s %s timed out",
2144
0
        ssh->state->server_side ? "from" : "to", remote_id);
2145
0
  case SSH_ERR_DISCONNECTED:
2146
0
    ssh_packet_clear_keys(ssh);
2147
0
    sshpkt_final_log_entry(ssh);
2148
0
    logdie("Disconnected from %s", remote_id);
2149
0
  case SSH_ERR_SYSTEM_ERROR:
2150
0
    if (errno == ECONNRESET) {
2151
0
      ssh_packet_clear_keys(ssh);
2152
0
      sshpkt_final_log_entry(ssh);
2153
0
      logdie("Connection reset by %s", remote_id);
2154
0
    }
2155
    /* FALLTHROUGH */
2156
0
  case SSH_ERR_NO_CIPHER_ALG_MATCH:
2157
0
  case SSH_ERR_NO_MAC_ALG_MATCH:
2158
0
  case SSH_ERR_NO_COMPRESS_ALG_MATCH:
2159
0
  case SSH_ERR_NO_KEX_ALG_MATCH:
2160
0
  case SSH_ERR_NO_HOSTKEY_ALG_MATCH:
2161
0
    if (ssh->kex && ssh->kex->failed_choice) {
2162
0
      ssh_packet_clear_keys(ssh);
2163
0
      errno = oerrno;
2164
0
      logdie("Unable to negotiate with %s: %s. "
2165
0
          "Their offer: %s", remote_id, ssh_err(r),
2166
0
          ssh->kex->failed_choice);
2167
0
    }
2168
    /* FALLTHROUGH */
2169
0
  default:
2170
0
    if (vasprintf(&tag, fmt, ap) == -1) {
2171
0
      ssh_packet_clear_keys(ssh);
2172
0
      logdie_f("could not allocate failure message");
2173
0
    }
2174
0
    ssh_packet_clear_keys(ssh);
2175
0
    errno = oerrno;
2176
0
    logdie_r(r, "%s%sConnection %s %s",
2177
0
        tag != NULL ? tag : "", tag != NULL ? ": " : "",
2178
0
        ssh->state->server_side ? "from" : "to", remote_id);
2179
0
  }
2180
0
}
2181
2182
void
2183
sshpkt_fatal(struct ssh *ssh, int r, const char *fmt, ...)
2184
0
{
2185
0
  va_list ap;
2186
2187
0
  va_start(ap, fmt);
2188
0
  sshpkt_vfatal(ssh, r, fmt, ap);
2189
  /* NOTREACHED */
2190
0
  va_end(ap);
2191
0
  logdie_f("should have exited");
2192
0
}
2193
2194
/* this prints out the final log entry */
2195
void
2196
0
sshpkt_final_log_entry (struct ssh *ssh) {
2197
0
  double total_time;
2198
2199
0
  if (ssh->start_time < 1)
2200
    /* this will produce a NaN in the output. -cjr */
2201
0
    total_time = 0;
2202
0
  else
2203
0
    total_time = monotime_double() - ssh->start_time;
2204
2205
0
  logit("SSH: Server;LType: Throughput;Remote: %s-%d;IN: %lu;OUT: %lu;Duration: %.1f;tPut_in: %.1f;tPut_out: %.1f",
2206
0
        ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
2207
0
        ssh->stdin_bytes, ssh->fdout_bytes, total_time,
2208
0
        ssh->stdin_bytes / total_time,
2209
0
        ssh->fdout_bytes / total_time);
2210
0
}
2211
2212
/*
2213
 * Logs the error plus constructs and sends a disconnect packet, closes the
2214
 * connection, and exits.  This function never returns. The error message
2215
 * should not contain a newline.  The length of the formatted message must
2216
 * not exceed 1024 bytes.
2217
 */
2218
void
2219
ssh_packet_disconnect(struct ssh *ssh, const char *fmt,...)
2220
0
{
2221
0
  char buf[1024], remote_id[512];
2222
0
  va_list args;
2223
0
  int r;
2224
2225
  /* Guard against recursive invocations. */
2226
0
  if (ssh->state->disconnecting)
2227
0
    fatal("packet_disconnect called recursively.");
2228
0
  ssh->state->disconnecting = 1;
2229
2230
  /*
2231
   * Format the message.  Note that the caller must make sure the
2232
   * message is of limited size.
2233
   */
2234
0
  sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id));
2235
0
  va_start(args, fmt);
2236
0
  vsnprintf(buf, sizeof(buf), fmt, args);
2237
0
  va_end(args);
2238
2239
  /* Display the error locally */
2240
0
  logit("Disconnecting %s: %.100s", remote_id, buf);
2241
2242
  /*
2243
   * Send the disconnect message to the other side, and wait
2244
   * for it to get sent.
2245
   */
2246
0
  if ((r = sshpkt_disconnect(ssh, "%s", buf)) != 0)
2247
0
    sshpkt_fatal(ssh, r, "%s", __func__);
2248
2249
0
  if ((r = ssh_packet_write_wait(ssh)) != 0)
2250
0
    sshpkt_fatal(ssh, r, "%s", __func__);
2251
2252
  /* Close the connection. */
2253
0
  ssh_packet_close(ssh);
2254
0
  cleanup_exit(255);
2255
0
}
2256
2257
/*
2258
 * Checks if there is any buffered output, and tries to write some of
2259
 * the output.
2260
 */
2261
int
2262
ssh_packet_write_poll(struct ssh *ssh)
2263
795
{
2264
795
  struct session_state *state = ssh->state;
2265
795
  int len = sshbuf_len(state->output);
2266
795
  int r;
2267
2268
795
  if (len > 0) {
2269
795
    len = write(state->connection_out,
2270
795
        sshbuf_ptr(state->output), len);
2271
795
    if (len == -1) {
2272
795
      if (errno == EINTR || errno == EAGAIN ||
2273
795
          errno == EWOULDBLOCK)
2274
0
        return 0;
2275
795
      return SSH_ERR_SYSTEM_ERROR;
2276
795
    }
2277
0
    if (len == 0)
2278
0
      return SSH_ERR_CONN_CLOSED;
2279
0
    if ((r = sshbuf_consume(state->output, len)) != 0)
2280
0
      return r;
2281
0
  }
2282
0
  return 0;
2283
795
}
2284
2285
/*
2286
 * Calls packet_write_poll repeatedly until all pending output data has been
2287
 * written.
2288
 */
2289
int
2290
ssh_packet_write_wait(struct ssh *ssh)
2291
795
{
2292
795
  int ret, r, ms_remain = 0;
2293
795
  struct timeval start;
2294
795
  struct timespec timespec, *timespecp = NULL;
2295
795
  struct session_state *state = ssh->state;
2296
795
  struct pollfd pfd;
2297
2298
795
  if ((r = ssh_packet_write_poll(ssh)) != 0)
2299
795
    return r;
2300
0
  while (ssh_packet_have_data_to_write(ssh)) {
2301
0
    pfd.fd = state->connection_out;
2302
0
    pfd.events = POLLOUT;
2303
2304
0
    if (state->packet_timeout_ms > 0) {
2305
0
      ms_remain = state->packet_timeout_ms;
2306
0
      timespecp = &timespec;
2307
0
    }
2308
0
    for (;;) {
2309
0
      if (state->packet_timeout_ms > 0) {
2310
0
        ms_to_timespec(&timespec, ms_remain);
2311
0
        monotime_tv(&start);
2312
0
      }
2313
0
      if ((ret = ppoll(&pfd, 1, timespecp, NULL)) >= 0)
2314
0
        break;
2315
0
      if (errno != EAGAIN && errno != EINTR &&
2316
0
          errno != EWOULDBLOCK)
2317
0
        break;
2318
0
      if (state->packet_timeout_ms <= 0)
2319
0
        continue;
2320
0
      ms_subtract_diff(&start, &ms_remain);
2321
0
      if (ms_remain <= 0) {
2322
0
        ret = 0;
2323
0
        break;
2324
0
      }
2325
0
    }
2326
0
    if (ret == 0)
2327
0
      return SSH_ERR_CONN_TIMEOUT;
2328
0
    if ((r = ssh_packet_write_poll(ssh)) != 0)
2329
0
      return r;
2330
0
  }
2331
0
  return 0;
2332
0
}
2333
2334
/* Returns true if there is buffered data to write to the connection. */
2335
2336
int
2337
ssh_packet_have_data_to_write(struct ssh *ssh)
2338
0
{
2339
0
  return sshbuf_len(ssh->state->output) != 0;
2340
0
}
2341
2342
/* Returns true if there is not too much data to write to the connection. */
2343
2344
int
2345
ssh_packet_not_very_much_data_to_write(struct ssh *ssh)
2346
0
{
2347
0
  if (ssh->state->interactive_mode)
2348
0
    return sshbuf_len(ssh->state->output) < 16384;
2349
0
  else
2350
0
    return sshbuf_len(ssh->state->output) < 128 * 1024;
2351
0
}
2352
2353
/*
2354
 * returns true when there are at most a few keystrokes of data to write
2355
 * and the connection is in interactive mode.
2356
 */
2357
2358
int
2359
ssh_packet_interactive_data_to_write(struct ssh *ssh)
2360
0
{
2361
0
  return ssh->state->interactive_mode &&
2362
0
      sshbuf_len(ssh->state->output) < 256;
2363
0
}
2364
2365
static void
2366
apply_qos(struct ssh *ssh)
2367
0
{
2368
0
  struct session_state *state = ssh->state;
2369
0
  int qos = state->interactive_mode ?
2370
0
      state->qos_interactive : state->qos_other;
2371
2372
0
  if (!ssh_packet_connection_is_on_socket(ssh))
2373
0
    return;
2374
0
  if (!state->nodelay_set) {
2375
0
    set_nodelay(state->connection_in);
2376
0
    state->nodelay_set = 1;
2377
0
  }
2378
0
  set_sock_tos(ssh->state->connection_in, qos);
2379
0
}
2380
2381
/* Informs that the current session is interactive. */
2382
void
2383
ssh_packet_set_interactive(struct ssh *ssh, int interactive)
2384
0
{
2385
0
  struct session_state *state = ssh->state;
2386
2387
0
  state->interactive_mode = interactive;
2388
0
  apply_qos(ssh);
2389
0
}
2390
2391
/* Set QoS flags to be used for interactive and non-interactive sessions */
2392
void
2393
ssh_packet_set_qos(struct ssh *ssh, int qos_interactive, int qos_other)
2394
0
{
2395
0
  struct session_state *state = ssh->state;
2396
2397
0
  state->qos_interactive = qos_interactive;
2398
0
  state->qos_other = qos_other;
2399
0
  apply_qos(ssh);
2400
0
}
2401
2402
int
2403
ssh_packet_set_maxsize(struct ssh *ssh, u_int s)
2404
0
{
2405
0
  struct session_state *state = ssh->state;
2406
2407
0
  if (state->set_maxsize_called) {
2408
0
    logit_f("called twice: old %d new %d",
2409
0
        state->max_packet_size, s);
2410
0
    return -1;
2411
0
  }
2412
0
  if (s < 4 * 1024 || s > 1024 * 1024) {
2413
0
    logit_f("bad size %d", s);
2414
0
    return -1;
2415
0
  }
2416
0
  state->set_maxsize_called = 1;
2417
0
  debug_f("setting to %d", s);
2418
0
  state->max_packet_size = s;
2419
0
  return s;
2420
0
}
2421
2422
int
2423
ssh_packet_inc_alive_timeouts(struct ssh *ssh)
2424
0
{
2425
0
  return ++ssh->state->keep_alive_timeouts;
2426
0
}
2427
2428
void
2429
ssh_packet_set_alive_timeouts(struct ssh *ssh, int ka)
2430
0
{
2431
0
  ssh->state->keep_alive_timeouts = ka;
2432
0
}
2433
2434
u_int
2435
ssh_packet_get_maxsize(struct ssh *ssh)
2436
0
{
2437
0
  return ssh->state->max_packet_size;
2438
0
}
2439
2440
void
2441
ssh_packet_set_rekey_limits(struct ssh *ssh, uint64_t bytes, uint32_t seconds)
2442
0
{
2443
0
  debug3("rekey after %llu bytes, %u seconds", (unsigned long long)bytes,
2444
0
      (unsigned int)seconds);
2445
0
  ssh->state->rekey_limit = bytes;
2446
0
  ssh->state->rekey_interval = seconds;
2447
0
}
2448
2449
time_t
2450
ssh_packet_get_rekey_timeout(struct ssh *ssh)
2451
0
{
2452
0
  time_t seconds;
2453
2454
0
  seconds = ssh->state->rekey_time + ssh->state->rekey_interval -
2455
0
      monotime();
2456
0
  return (seconds <= 0 ? 1 : seconds);
2457
0
}
2458
2459
void
2460
ssh_packet_set_server(struct ssh *ssh)
2461
29.6k
{
2462
29.6k
  ssh->state->server_side = 1;
2463
29.6k
  ssh->kex->server = 1; /* XXX unify? */
2464
29.6k
}
2465
2466
/* Set the state of the connection to post auth
2467
 * While we are here also decrease the size of
2468
 * packet_max_size to something more reasonable.
2469
 * In this case thats 33k. Which is the size of
2470
 * the largest packet we expect to see and some space
2471
 * for overhead. This reduces memory usage in high
2472
 * BDP environments without impacting performance
2473
 * -cjr 4/11/23 */
2474
void
2475
ssh_packet_set_authenticated(struct ssh *ssh)
2476
0
{
2477
0
  ssh->state->after_authentication = 1;
2478
0
  packet_max_size = SSH_IOBUFSZ + 1024;
2479
0
}
2480
2481
void *
2482
ssh_packet_get_input(struct ssh *ssh)
2483
106k
{
2484
106k
  return (void *)ssh->state->input;
2485
106k
}
2486
2487
void *
2488
ssh_packet_get_output(struct ssh *ssh)
2489
126k
{
2490
126k
  return (void *)ssh->state->output;
2491
126k
}
2492
2493
/* Reset after_authentication and reset compression in post-auth privsep */
2494
static int
2495
ssh_packet_set_postauth(struct ssh *ssh)
2496
0
{
2497
0
  int r;
2498
2499
0
  debug_f("called");
2500
  /* This was set in net child, but is not visible in user child */
2501
0
  ssh->state->after_authentication = 1;
2502
0
  ssh->state->rekeying = 0;
2503
0
  if ((r = ssh_packet_enable_delayed_compress(ssh)) != 0)
2504
0
    return r;
2505
0
  return 0;
2506
0
}
2507
2508
/* Packet state (de-)serialization for privsep */
2509
2510
/* turn kex into a blob for packet state serialization */
2511
static int
2512
kex_to_blob(struct sshbuf *m, struct kex *kex)
2513
0
{
2514
0
  int r;
2515
2516
0
  if ((r = sshbuf_put_u32(m, kex->we_need)) != 0 ||
2517
0
      (r = sshbuf_put_cstring(m, kex->hostkey_alg)) != 0 ||
2518
0
      (r = sshbuf_put_u32(m, kex->hostkey_type)) != 0 ||
2519
0
      (r = sshbuf_put_u32(m, kex->hostkey_nid)) != 0 ||
2520
0
      (r = sshbuf_put_u32(m, kex->kex_type)) != 0 ||
2521
0
      (r = sshbuf_put_u32(m, kex->kex_strict)) != 0 ||
2522
0
      (r = sshbuf_put_stringb(m, kex->my)) != 0 ||
2523
0
      (r = sshbuf_put_stringb(m, kex->peer)) != 0 ||
2524
0
      (r = sshbuf_put_stringb(m, kex->client_version)) != 0 ||
2525
0
      (r = sshbuf_put_stringb(m, kex->server_version)) != 0 ||
2526
0
      (r = sshbuf_put_stringb(m, kex->session_id)) != 0 ||
2527
0
      (r = sshbuf_put_u32(m, kex->flags)) != 0)
2528
0
    return r;
2529
0
  return 0;
2530
0
}
2531
2532
/* turn key exchange results into a blob for packet state serialization */
2533
static int
2534
newkeys_to_blob(struct sshbuf *m, struct ssh *ssh, int mode)
2535
0
{
2536
0
  struct sshbuf *b;
2537
0
  struct sshcipher_ctx *cc;
2538
0
  struct sshcomp *comp;
2539
0
  struct sshenc *enc;
2540
0
  struct sshmac *mac;
2541
0
  struct newkeys *newkey;
2542
0
  int r;
2543
2544
0
  if ((newkey = ssh->state->newkeys[mode]) == NULL)
2545
0
    return SSH_ERR_INTERNAL_ERROR;
2546
0
  enc = &newkey->enc;
2547
0
  mac = &newkey->mac;
2548
0
  comp = &newkey->comp;
2549
0
  cc = (mode == MODE_OUT) ? ssh->state->send_context :
2550
0
      ssh->state->receive_context;
2551
0
  if ((r = cipher_get_keyiv(cc, enc->iv, enc->iv_len)) != 0)
2552
0
    return r;
2553
0
  if ((b = sshbuf_new()) == NULL)
2554
0
    return SSH_ERR_ALLOC_FAIL;
2555
0
  if ((r = sshbuf_put_cstring(b, enc->name)) != 0 ||
2556
0
      (r = sshbuf_put_u32(b, enc->enabled)) != 0 ||
2557
0
      (r = sshbuf_put_u32(b, enc->block_size)) != 0 ||
2558
0
      (r = sshbuf_put_string(b, enc->key, enc->key_len)) != 0 ||
2559
0
      (r = sshbuf_put_string(b, enc->iv, enc->iv_len)) != 0)
2560
0
    goto out;
2561
0
  if (cipher_authlen(enc->cipher) == 0) {
2562
0
    if ((r = sshbuf_put_cstring(b, mac->name)) != 0 ||
2563
0
        (r = sshbuf_put_u32(b, mac->enabled)) != 0 ||
2564
0
        (r = sshbuf_put_string(b, mac->key, mac->key_len)) != 0)
2565
0
      goto out;
2566
0
  }
2567
0
  if ((r = sshbuf_put_u32(b, comp->type)) != 0 ||
2568
0
      (r = sshbuf_put_cstring(b, comp->name)) != 0)
2569
0
    goto out;
2570
0
  r = sshbuf_put_stringb(m, b);
2571
0
 out:
2572
0
  sshbuf_free(b);
2573
0
  return r;
2574
0
}
2575
2576
/* serialize packet state into a blob */
2577
int
2578
ssh_packet_get_state(struct ssh *ssh, struct sshbuf *m)
2579
0
{
2580
0
  struct session_state *state = ssh->state;
2581
0
  int r;
2582
2583
0
#define ENCODE_INT(v) (((v) < 0) ? 0xFFFFFFFF : (u_int)v)
2584
0
  if ((r = kex_to_blob(m, ssh->kex)) != 0 ||
2585
0
      (r = newkeys_to_blob(m, ssh, MODE_OUT)) != 0 ||
2586
0
      (r = newkeys_to_blob(m, ssh, MODE_IN)) != 0 ||
2587
0
      (r = sshbuf_put_u64(m, state->rekey_limit)) != 0 ||
2588
0
      (r = sshbuf_put_u32(m, state->rekey_interval)) != 0 ||
2589
0
      (r = sshbuf_put_u32(m, state->p_send.seqnr)) != 0 ||
2590
0
      (r = sshbuf_put_u64(m, state->p_send.blocks)) != 0 ||
2591
0
      (r = sshbuf_put_u32(m, state->p_send.packets)) != 0 ||
2592
0
      (r = sshbuf_put_u64(m, state->p_send.bytes)) != 0 ||
2593
0
      (r = sshbuf_put_u32(m, state->p_read.seqnr)) != 0 ||
2594
0
      (r = sshbuf_put_u64(m, state->p_read.blocks)) != 0 ||
2595
0
      (r = sshbuf_put_u32(m, state->p_read.packets)) != 0 ||
2596
0
      (r = sshbuf_put_u64(m, state->p_read.bytes)) != 0 ||
2597
0
      (r = sshbuf_put_stringb(m, state->input)) != 0 ||
2598
0
      (r = sshbuf_put_stringb(m, state->output)) != 0 ||
2599
0
      (r = sshbuf_put_u32(m, ENCODE_INT(state->interactive_mode))) != 0 ||
2600
0
      (r = sshbuf_put_u32(m, ENCODE_INT(state->qos_interactive))) != 0 ||
2601
0
      (r = sshbuf_put_u32(m, ENCODE_INT(state->qos_other))) != 0)
2602
0
    return r;
2603
0
#undef ENCODE_INT
2604
0
  return 0;
2605
0
}
2606
2607
/* restore key exchange results from blob for packet state de-serialization */
2608
static int
2609
newkeys_from_blob(struct sshbuf *m, struct ssh *ssh, int mode)
2610
0
{
2611
0
  struct sshbuf *b = NULL;
2612
0
  struct sshcomp *comp;
2613
0
  struct sshenc *enc;
2614
0
  struct sshmac *mac;
2615
0
  struct newkeys *newkey = NULL;
2616
0
  size_t keylen, ivlen, maclen;
2617
0
  int r;
2618
2619
0
  if ((newkey = calloc(1, sizeof(*newkey))) == NULL) {
2620
0
    r = SSH_ERR_ALLOC_FAIL;
2621
0
    goto out;
2622
0
  }
2623
0
  if ((r = sshbuf_froms(m, &b)) != 0)
2624
0
    goto out;
2625
#ifdef DEBUG_PK
2626
  sshbuf_dump(b, stderr);
2627
#endif
2628
0
  enc = &newkey->enc;
2629
0
  mac = &newkey->mac;
2630
0
  comp = &newkey->comp;
2631
2632
0
  if ((r = sshbuf_get_cstring(b, &enc->name, NULL)) != 0 ||
2633
0
      (r = sshbuf_get_u32(b, (u_int *)&enc->enabled)) != 0 ||
2634
0
      (r = sshbuf_get_u32(b, &enc->block_size)) != 0 ||
2635
0
      (r = sshbuf_get_string(b, &enc->key, &keylen)) != 0 ||
2636
0
      (r = sshbuf_get_string(b, &enc->iv, &ivlen)) != 0)
2637
0
    goto out;
2638
0
  if ((enc->cipher = cipher_by_name(enc->name)) == NULL) {
2639
0
    r = SSH_ERR_INVALID_FORMAT;
2640
0
    goto out;
2641
0
  }
2642
0
  if (cipher_authlen(enc->cipher) == 0) {
2643
0
    if ((r = sshbuf_get_cstring(b, &mac->name, NULL)) != 0)
2644
0
      goto out;
2645
0
    if ((r = mac_setup(mac, mac->name)) != 0)
2646
0
      goto out;
2647
0
    if ((r = sshbuf_get_u32(b, (u_int *)&mac->enabled)) != 0 ||
2648
0
        (r = sshbuf_get_string(b, &mac->key, &maclen)) != 0)
2649
0
      goto out;
2650
0
    if (maclen > mac->key_len) {
2651
0
      r = SSH_ERR_INVALID_FORMAT;
2652
0
      goto out;
2653
0
    }
2654
0
    mac->key_len = maclen;
2655
0
  }
2656
0
  if ((r = sshbuf_get_u32(b, &comp->type)) != 0 ||
2657
0
      (r = sshbuf_get_cstring(b, &comp->name, NULL)) != 0)
2658
0
    goto out;
2659
0
  if (sshbuf_len(b) != 0) {
2660
0
    r = SSH_ERR_INVALID_FORMAT;
2661
0
    goto out;
2662
0
  }
2663
0
  enc->key_len = keylen;
2664
0
  enc->iv_len = ivlen;
2665
0
  ssh->kex->newkeys[mode] = newkey;
2666
0
  newkey = NULL;
2667
0
  r = 0;
2668
0
 out:
2669
0
  free(newkey);
2670
0
  sshbuf_free(b);
2671
0
  return r;
2672
0
}
2673
2674
/* restore kex from blob for packet state de-serialization */
2675
static int
2676
kex_from_blob(struct sshbuf *m, struct kex **kexp)
2677
0
{
2678
0
  struct kex *kex;
2679
0
  int r;
2680
2681
0
  if ((kex = kex_new()) == NULL)
2682
0
    return SSH_ERR_ALLOC_FAIL;
2683
0
  if ((r = sshbuf_get_u32(m, &kex->we_need)) != 0 ||
2684
0
      (r = sshbuf_get_cstring(m, &kex->hostkey_alg, NULL)) != 0 ||
2685
0
      (r = sshbuf_get_u32(m, (u_int *)&kex->hostkey_type)) != 0 ||
2686
0
      (r = sshbuf_get_u32(m, (u_int *)&kex->hostkey_nid)) != 0 ||
2687
0
      (r = sshbuf_get_u32(m, &kex->kex_type)) != 0 ||
2688
0
      (r = sshbuf_get_u32(m, &kex->kex_strict)) != 0 ||
2689
0
      (r = sshbuf_get_stringb(m, kex->my)) != 0 ||
2690
0
      (r = sshbuf_get_stringb(m, kex->peer)) != 0 ||
2691
0
      (r = sshbuf_get_stringb(m, kex->client_version)) != 0 ||
2692
0
      (r = sshbuf_get_stringb(m, kex->server_version)) != 0 ||
2693
0
      (r = sshbuf_get_stringb(m, kex->session_id)) != 0 ||
2694
0
      (r = sshbuf_get_u32(m, &kex->flags)) != 0)
2695
0
    goto out;
2696
0
  kex->server = 1;
2697
0
  kex->done = 1;
2698
0
  r = 0;
2699
0
 out:
2700
0
  if (r != 0 || kexp == NULL) {
2701
0
    kex_free(kex);
2702
0
    if (kexp != NULL)
2703
0
      *kexp = NULL;
2704
0
  } else {
2705
0
    kex_free(*kexp);
2706
0
    *kexp = kex;
2707
0
  }
2708
0
  return r;
2709
0
}
2710
2711
/*
2712
 * Restore packet state from content of blob 'm' (de-serialization).
2713
 * Note that 'm' will be partially consumed on parsing or any other errors.
2714
 */
2715
int
2716
ssh_packet_set_state(struct ssh *ssh, struct sshbuf *m)
2717
0
{
2718
0
  struct session_state *state = ssh->state;
2719
0
  const u_char *input, *output;
2720
0
  size_t ilen, olen;
2721
0
  int r;
2722
0
  u_int interactive, qos_interactive, qos_other;
2723
2724
0
  if ((r = kex_from_blob(m, &ssh->kex)) != 0 ||
2725
0
      (r = newkeys_from_blob(m, ssh, MODE_OUT)) != 0 ||
2726
0
      (r = newkeys_from_blob(m, ssh, MODE_IN)) != 0 ||
2727
0
      (r = sshbuf_get_u64(m, &state->rekey_limit)) != 0 ||
2728
0
      (r = sshbuf_get_u32(m, &state->rekey_interval)) != 0 ||
2729
0
      (r = sshbuf_get_u32(m, &state->p_send.seqnr)) != 0 ||
2730
0
      (r = sshbuf_get_u64(m, &state->p_send.blocks)) != 0 ||
2731
0
      (r = sshbuf_get_u32(m, &state->p_send.packets)) != 0 ||
2732
0
      (r = sshbuf_get_u64(m, &state->p_send.bytes)) != 0 ||
2733
0
      (r = sshbuf_get_u32(m, &state->p_read.seqnr)) != 0 ||
2734
0
      (r = sshbuf_get_u64(m, &state->p_read.blocks)) != 0 ||
2735
0
      (r = sshbuf_get_u32(m, &state->p_read.packets)) != 0 ||
2736
0
      (r = sshbuf_get_u64(m, &state->p_read.bytes)) != 0)
2737
0
    return r;
2738
  /*
2739
   * We set the time here so that in post-auth privsep child we
2740
   * count from the completion of the authentication.
2741
   */
2742
0
  state->rekey_time = monotime();
2743
  /* XXX ssh_set_newkeys overrides p_read.packets? XXX */
2744
0
  if ((r = ssh_set_newkeys(ssh, MODE_IN)) != 0 ||
2745
0
      (r = ssh_set_newkeys(ssh, MODE_OUT)) != 0)
2746
0
    return r;
2747
2748
0
  if ((r = ssh_packet_set_postauth(ssh)) != 0)
2749
0
    return r;
2750
2751
0
  sshbuf_reset(state->input);
2752
0
  sshbuf_reset(state->output);
2753
0
  if ((r = sshbuf_get_string_direct(m, &input, &ilen)) != 0 ||
2754
0
      (r = sshbuf_get_string_direct(m, &output, &olen)) != 0 ||
2755
0
      (r = sshbuf_put(state->input, input, ilen)) != 0 ||
2756
0
      (r = sshbuf_put(state->output, output, olen)) != 0)
2757
0
    return r;
2758
2759
0
  if ((r = sshbuf_get_u32(m, &interactive)) != 0 ||
2760
0
      (r = sshbuf_get_u32(m, &qos_interactive)) != 0 ||
2761
0
      (r = sshbuf_get_u32(m, &qos_other)) != 0)
2762
0
    return r;
2763
0
#define DECODE_INT(v) ((v) > INT_MAX ? -1 : (int)(v))
2764
0
  state->interactive_mode = DECODE_INT(interactive);
2765
0
  state->qos_interactive = DECODE_INT(qos_interactive);
2766
0
  state->qos_other = DECODE_INT(qos_other);
2767
0
#undef DECODE_INT
2768
2769
0
  if (sshbuf_len(m))
2770
0
    return SSH_ERR_INVALID_FORMAT;
2771
0
  debug3_f("done");
2772
0
  return 0;
2773
0
}
2774
2775
/* NEW API */
2776
2777
/* put data to the outgoing packet */
2778
2779
int
2780
sshpkt_put(struct ssh *ssh, const void *v, size_t len)
2781
0
{
2782
0
  return sshbuf_put(ssh->state->outgoing_packet, v, len);
2783
0
}
2784
2785
int
2786
sshpkt_putb(struct ssh *ssh, const struct sshbuf *b)
2787
17.8k
{
2788
17.8k
  return sshbuf_putb(ssh->state->outgoing_packet, b);
2789
17.8k
}
2790
2791
int
2792
sshpkt_put_u8(struct ssh *ssh, u_char val)
2793
0
{
2794
0
  return sshbuf_put_u8(ssh->state->outgoing_packet, val);
2795
0
}
2796
2797
int
2798
sshpkt_put_u32(struct ssh *ssh, uint32_t val)
2799
2.37M
{
2800
2.37M
  return sshbuf_put_u32(ssh->state->outgoing_packet, val);
2801
2.37M
}
2802
2803
int
2804
sshpkt_put_u64(struct ssh *ssh, uint64_t val)
2805
0
{
2806
0
  return sshbuf_put_u64(ssh->state->outgoing_packet, val);
2807
0
}
2808
2809
int
2810
sshpkt_put_string(struct ssh *ssh, const void *v, size_t len)
2811
0
{
2812
0
  return sshbuf_put_string(ssh->state->outgoing_packet, v, len);
2813
0
}
2814
2815
int
2816
sshpkt_put_cstring(struct ssh *ssh, const void *v)
2817
16.2k
{
2818
16.2k
  return sshbuf_put_cstring(ssh->state->outgoing_packet, v);
2819
16.2k
}
2820
2821
int
2822
sshpkt_put_stringb(struct ssh *ssh, const struct sshbuf *v)
2823
0
{
2824
0
  return sshbuf_put_stringb(ssh->state->outgoing_packet, v);
2825
0
}
2826
2827
#ifdef WITH_OPENSSL
2828
#ifdef OPENSSL_HAS_ECC
2829
int
2830
sshpkt_put_ec(struct ssh *ssh, const EC_POINT *v, const EC_GROUP *g)
2831
0
{
2832
0
  return sshbuf_put_ec(ssh->state->outgoing_packet, v, g);
2833
0
}
2834
2835
int
2836
sshpkt_put_ec_pkey(struct ssh *ssh, EVP_PKEY *pkey)
2837
0
{
2838
0
  return sshbuf_put_ec_pkey(ssh->state->outgoing_packet, pkey);
2839
0
}
2840
#endif /* OPENSSL_HAS_ECC */
2841
2842
int
2843
sshpkt_put_bignum2(struct ssh *ssh, const BIGNUM *v)
2844
0
{
2845
0
  return sshbuf_put_bignum2(ssh->state->outgoing_packet, v);
2846
0
}
2847
#endif /* WITH_OPENSSL */
2848
2849
/* fetch data from the incoming packet */
2850
2851
int
2852
sshpkt_get(struct ssh *ssh, void *valp, size_t len)
2853
0
{
2854
0
  return sshbuf_get(ssh->state->incoming_packet, valp, len);
2855
0
}
2856
2857
int
2858
sshpkt_get_u8(struct ssh *ssh, u_char *valp)
2859
145k
{
2860
145k
  return sshbuf_get_u8(ssh->state->incoming_packet, valp);
2861
145k
}
2862
2863
int
2864
sshpkt_get_u32(struct ssh *ssh, uint32_t *valp)
2865
5.19k
{
2866
5.19k
  return sshbuf_get_u32(ssh->state->incoming_packet, valp);
2867
5.19k
}
2868
2869
int
2870
sshpkt_get_u64(struct ssh *ssh, uint64_t *valp)
2871
0
{
2872
0
  return sshbuf_get_u64(ssh->state->incoming_packet, valp);
2873
0
}
2874
2875
int
2876
sshpkt_get_string(struct ssh *ssh, u_char **valp, size_t *lenp)
2877
59.2k
{
2878
59.2k
  return sshbuf_get_string(ssh->state->incoming_packet, valp, lenp);
2879
59.2k
}
2880
2881
int
2882
sshpkt_get_string_direct(struct ssh *ssh, const u_char **valp, size_t *lenp)
2883
0
{
2884
0
  return sshbuf_get_string_direct(ssh->state->incoming_packet, valp, lenp);
2885
0
}
2886
2887
int
2888
sshpkt_peek_string_direct(struct ssh *ssh, const u_char **valp, size_t *lenp)
2889
0
{
2890
0
  return sshbuf_peek_string_direct(ssh->state->incoming_packet, valp, lenp);
2891
0
}
2892
2893
int
2894
sshpkt_get_cstring(struct ssh *ssh, char **valp, size_t *lenp)
2895
0
{
2896
0
  return sshbuf_get_cstring(ssh->state->incoming_packet, valp, lenp);
2897
0
}
2898
2899
int
2900
sshpkt_getb_froms(struct ssh *ssh, struct sshbuf **valp)
2901
0
{
2902
0
  return sshbuf_froms(ssh->state->incoming_packet, valp);
2903
0
}
2904
2905
#ifdef WITH_OPENSSL
2906
#ifdef OPENSSL_HAS_ECC
2907
int
2908
sshpkt_get_ec(struct ssh *ssh, EC_POINT *v, const EC_GROUP *g)
2909
0
{
2910
0
  return sshbuf_get_ec(ssh->state->incoming_packet, v, g);
2911
0
}
2912
#endif /* OPENSSL_HAS_ECC */
2913
2914
int
2915
sshpkt_get_bignum2(struct ssh *ssh, BIGNUM **valp)
2916
0
{
2917
0
  return sshbuf_get_bignum2(ssh->state->incoming_packet, valp);
2918
0
}
2919
#endif /* WITH_OPENSSL */
2920
2921
int
2922
sshpkt_get_end(struct ssh *ssh)
2923
5.14k
{
2924
5.14k
  if (sshbuf_len(ssh->state->incoming_packet) > 0)
2925
630
    return SSH_ERR_UNEXPECTED_TRAILING_DATA;
2926
4.51k
  return 0;
2927
5.14k
}
2928
2929
const u_char *
2930
sshpkt_ptr(struct ssh *ssh, size_t *lenp)
2931
9.03k
{
2932
9.03k
  if (lenp != NULL)
2933
9.03k
    *lenp = sshbuf_len(ssh->state->incoming_packet);
2934
9.03k
  return sshbuf_ptr(ssh->state->incoming_packet);
2935
9.03k
}
2936
2937
/* start a new packet */
2938
2939
int
2940
sshpkt_start(struct ssh *ssh, u_char type)
2941
2.39M
{
2942
2.39M
  u_char buf[6]; /* u32 packet length, u8 pad len, u8 type */
2943
2944
2.39M
  DBG(debug("packet_start[%d]", type));
2945
2.39M
  memset(buf, 0, sizeof(buf));
2946
2.39M
  buf[sizeof(buf) - 1] = type;
2947
2.39M
  sshbuf_reset(ssh->state->outgoing_packet);
2948
2.39M
  return sshbuf_put(ssh->state->outgoing_packet, buf, sizeof(buf));
2949
2.39M
}
2950
2951
static int
2952
ssh_packet_send_mux(struct ssh *ssh)
2953
0
{
2954
0
  struct session_state *state = ssh->state;
2955
0
  u_char type, *cp;
2956
0
  size_t len;
2957
0
  int r;
2958
2959
0
  if (ssh->kex)
2960
0
    return SSH_ERR_INTERNAL_ERROR;
2961
0
  len = sshbuf_len(state->outgoing_packet);
2962
0
  if (len < 6)
2963
0
    return SSH_ERR_INTERNAL_ERROR;
2964
0
  cp = sshbuf_mutable_ptr(state->outgoing_packet);
2965
0
  type = cp[5];
2966
0
  if (ssh_packet_log_type(type))
2967
0
    debug3_f("type %u", type);
2968
  /* drop everything, but the connection protocol */
2969
0
  if (type >= SSH2_MSG_CONNECTION_MIN &&
2970
0
      type <= SSH2_MSG_CONNECTION_MAX) {
2971
0
    POKE_U32(cp, len - 4);
2972
0
    if ((r = sshbuf_putb(state->output,
2973
0
        state->outgoing_packet)) != 0)
2974
0
      return r;
2975
    /* sshbuf_dump(state->output, stderr); */
2976
0
  }
2977
0
  sshbuf_reset(state->outgoing_packet);
2978
0
  return 0;
2979
0
}
2980
2981
/*
2982
 * 9.2.  Ignored Data Message
2983
 *
2984
 *   byte      SSH_MSG_IGNORE
2985
 *   string    data
2986
 *
2987
 * All implementations MUST understand (and ignore) this message at any
2988
 * time (after receiving the protocol version). No implementation is
2989
 * required to send them. This message can be used as an additional
2990
 * protection measure against advanced traffic analysis techniques.
2991
 */
2992
int
2993
sshpkt_msg_ignore(struct ssh *ssh, u_int nbytes)
2994
0
{
2995
0
  uint32_t rnd = 0;
2996
0
  int r;
2997
0
  u_int i;
2998
2999
0
  if ((r = sshpkt_start(ssh, SSH2_MSG_IGNORE)) != 0 ||
3000
0
      (r = sshpkt_put_u32(ssh, nbytes)) != 0)
3001
0
    return r;
3002
0
  for (i = 0; i < nbytes; i++) {
3003
0
    if (i % 4 == 0)
3004
0
      rnd = arc4random();
3005
0
    if ((r = sshpkt_put_u8(ssh, (u_char)rnd & 0xff)) != 0)
3006
0
      return r;
3007
0
    rnd >>= 8;
3008
0
  }
3009
0
  return 0;
3010
0
}
3011
3012
/* send it */
3013
3014
int
3015
sshpkt_send(struct ssh *ssh)
3016
2.39M
{
3017
2.39M
  if (ssh->state && ssh->state->mux)
3018
0
    return ssh_packet_send_mux(ssh);
3019
2.39M
  return ssh_packet_send2(ssh);
3020
2.39M
}
3021
3022
int
3023
sshpkt_disconnect(struct ssh *ssh, const char *fmt,...)
3024
8.13k
{
3025
8.13k
  char buf[1024];
3026
8.13k
  va_list args;
3027
8.13k
  int r;
3028
3029
8.13k
  va_start(args, fmt);
3030
8.13k
  vsnprintf(buf, sizeof(buf), fmt, args);
3031
8.13k
  va_end(args);
3032
3033
8.13k
  debug2_f("sending SSH2_MSG_DISCONNECT: %s", buf);
3034
8.13k
  if ((r = sshpkt_start(ssh, SSH2_MSG_DISCONNECT)) != 0 ||
3035
8.13k
      (r = sshpkt_put_u32(ssh, SSH2_DISCONNECT_PROTOCOL_ERROR)) != 0 ||
3036
8.13k
      (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
3037
8.13k
      (r = sshpkt_put_cstring(ssh, "")) != 0 ||
3038
8.13k
      (r = sshpkt_send(ssh)) != 0)
3039
0
    return r;
3040
8.13k
  return 0;
3041
8.13k
}
3042
3043
/* roundup current message to pad bytes */
3044
int
3045
sshpkt_add_padding(struct ssh *ssh, u_char pad)
3046
0
{
3047
0
  ssh->state->extra_pad = pad;
3048
0
  return 0;
3049
0
}
3050
3051
/* used for cipher switching
3052
 * only called in cipher-swtich.c */
3053
void *
3054
ssh_packet_get_send_context(struct ssh *ssh)
3055
0
{
3056
0
        return ssh->state->send_context;
3057
0
}
3058
3059
void *
3060
ssh_packet_get_receive_context(struct ssh *ssh)
3061
0
{
3062
0
        return ssh->state->receive_context;
3063
0
}
3064
3065
static char *
3066
format_traffic_stats(struct packet_state *ps)
3067
0
{
3068
0
  char *stats = NULL, bytes[FMT_SCALED_STRSIZE];
3069
3070
0
  if (ps->bytes > LLONG_MAX || fmt_scaled(ps->bytes, bytes) != 0)
3071
0
    strlcpy(bytes, "OVERFLOW", sizeof(bytes));
3072
3073
0
  xasprintf(&stats, "%lu pkts %llu blks %sB",
3074
0
      (unsigned long)ps->packets, (unsigned long long)ps->blocks, bytes);
3075
0
  return stats;
3076
0
}
3077
3078
static char *
3079
dedupe_alg_names(const char *in, const char *out)
3080
0
{
3081
0
  char *names = NULL;
3082
3083
0
  if (in == NULL)
3084
0
    in = "<implicit>";
3085
0
  if (out == NULL)
3086
0
    out = "<implicit>";
3087
3088
0
  if (strcmp(in, out) == 0) {
3089
0
    names = xstrdup(in);
3090
0
  } else {
3091
0
    xasprintf(&names, "%s in, %s out", in, out);
3092
0
  }
3093
0
  return names;
3094
0
}
3095
3096
static char *
3097
comp_status_message(struct ssh *ssh)
3098
0
{
3099
0
#ifdef WITH_ZLIB
3100
0
  char *ret = NULL;
3101
0
  struct session_state *state = ssh->state;
3102
0
  unsigned long long iraw = 0, icmp = 0, oraw = 0, ocmp = 0;
3103
0
  char iraw_f[FMT_SCALED_STRSIZE] = "", oraw_f[FMT_SCALED_STRSIZE] = "";
3104
0
  char icmp_f[FMT_SCALED_STRSIZE] = "", ocmp_f[FMT_SCALED_STRSIZE] = "";
3105
3106
0
  if (state->compression_buffer) {
3107
0
    if (state->compression_in_started) {
3108
0
      iraw = state->compression_in_stream.total_out;
3109
0
      icmp = state->compression_in_stream.total_in;
3110
0
      if (fmt_scaled(iraw, iraw_f) != 0)
3111
0
        strlcpy(iraw_f, "OVERFLOW", sizeof(iraw_f));
3112
0
      if (fmt_scaled(icmp, icmp_f) != 0)
3113
0
        strlcpy(icmp_f, "OVERFLOW", sizeof(icmp_f));
3114
0
    }
3115
0
    if (state->compression_out_started) {
3116
0
      oraw = state->compression_out_stream.total_in;
3117
0
      ocmp = state->compression_out_stream.total_out;
3118
0
      if (fmt_scaled(oraw, oraw_f) != 0)
3119
0
        strlcpy(oraw_f, "OVERFLOW", sizeof(oraw_f));
3120
0
      if (fmt_scaled(ocmp, ocmp_f) != 0)
3121
0
        strlcpy(ocmp_f, "OVERFLOW", sizeof(ocmp_f));
3122
0
    }
3123
0
    xasprintf(&ret,
3124
0
        "    compressed %s/%s (*%.3f) in,"
3125
0
        " %s/%s (*%.3f) out\r\n",
3126
0
        icmp_f, iraw_f, iraw == 0 ? 0.0 : (double)icmp / iraw,
3127
0
        ocmp_f, oraw_f, oraw == 0 ? 0.0 : (double)ocmp / oraw);
3128
0
    return ret;
3129
0
  }
3130
0
#endif  /* WITH_ZLIB */
3131
0
  return xstrdup("");
3132
0
}
3133
3134
char *
3135
connection_info_message(struct ssh *ssh)
3136
0
{
3137
0
  char *ret = NULL, *cipher = NULL, *mac = NULL, *comp = NULL;
3138
0
  char *rekey_volume = NULL, *rekey_time = NULL, *comp_info = NULL;
3139
0
  char thishost[NI_MAXHOST] = "unknown", *tcp_info = NULL;
3140
0
  struct kex *kex;
3141
0
  struct session_state *state;
3142
0
  struct newkeys *nk_in, *nk_out;
3143
0
  char *stats_in = NULL, *stats_out = NULL;
3144
0
  uint64_t epoch = (uint64_t)time(NULL) - monotime();
3145
3146
0
  if (ssh == NULL)
3147
0
    return NULL;
3148
0
  state = ssh->state;
3149
0
  kex = ssh->kex;
3150
3151
0
  (void)gethostname(thishost, sizeof(thishost));
3152
3153
0
  if (ssh_local_port(ssh) != 65535 ||
3154
0
       strcmp(ssh_local_ipaddr(ssh), "UNKNOWN") != 0) {
3155
0
    xasprintf(&tcp_info, "  tcp %s:%d -> %s:%d\r\n",
3156
0
        ssh_local_ipaddr(ssh), ssh_local_port(ssh),
3157
0
        ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
3158
0
  } else {
3159
0
    tcp_info = xstrdup("");
3160
0
  }
3161
3162
0
  nk_in = ssh->state->newkeys[MODE_IN];
3163
0
  nk_out = ssh->state->newkeys[MODE_OUT];
3164
0
  stats_in = format_traffic_stats(&ssh->state->p_read);
3165
0
  stats_out = format_traffic_stats(&ssh->state->p_send);
3166
3167
0
  cipher = dedupe_alg_names(nk_in->enc.name, nk_out->enc.name);
3168
0
  mac = dedupe_alg_names(nk_in->mac.name, nk_out->mac.name);
3169
0
  comp = dedupe_alg_names(nk_in->comp.name, nk_out->comp.name);
3170
3171
  /* Volume based rekeying. */
3172
0
  if (state->rekey_limit == 0) {
3173
0
    xasprintf(&rekey_volume, "limit none");
3174
0
  } else {
3175
0
    char *volumes = NULL, in[32], out[32];
3176
3177
0
    snprintf(in, sizeof(in), "%llu",
3178
0
       (unsigned long long)state->max_blocks_in);
3179
0
    snprintf(out, sizeof(out), "%llu",
3180
0
       (unsigned long long)state->max_blocks_out);
3181
0
    volumes = dedupe_alg_names(in, out);
3182
0
    xasprintf(&rekey_volume, "limit blocks %s", volumes);
3183
0
    free(volumes);
3184
0
  }
3185
3186
  /* Time based rekeying. */
3187
0
  if (state->rekey_interval == 0) {
3188
0
    rekey_time = xstrdup("interval none");
3189
0
  } else {
3190
0
    char rekey_next[64];
3191
3192
0
    format_absolute_time(epoch + state->rekey_time +
3193
0
        state->rekey_interval, rekey_next, sizeof(rekey_next));
3194
0
    xasprintf(&rekey_time, "interval %s, next %s",
3195
0
        fmt_timeframe(state->rekey_interval), rekey_next);
3196
0
  }
3197
0
  comp_info = comp_status_message(ssh);
3198
3199
0
  xasprintf(&ret, "Connection information for %s pid %lld\r\n"
3200
0
      "%s"
3201
0
      "  kexalgorithm %s\r\n  hostkeyalgorithm %s\r\n"
3202
0
      "  cipher %s\r\n  mac %s\r\n  compression %s\r\n"
3203
0
      "  rekey %s %s\r\n"
3204
0
      "  traffic %s in, %s out\r\n"
3205
0
      "%s",
3206
0
      thishost, (long long)getpid(),
3207
0
      tcp_info,
3208
0
      kex->name, kex->hostkey_alg,
3209
0
      cipher, mac, comp,
3210
0
      rekey_volume, rekey_time,
3211
0
      stats_in, stats_out,
3212
0
      comp_info
3213
0
  );
3214
0
  free(tcp_info);
3215
0
  free(cipher);
3216
0
  free(mac);
3217
0
  free(comp);
3218
0
  free(stats_in);
3219
0
  free(stats_out);
3220
0
  free(rekey_volume);
3221
0
  free(rekey_time);
3222
0
  free(comp_info);
3223
0
  return ret;
3224
0
}