Coverage Report

Created: 2026-10-13 06:56

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