Coverage Report

Created: 2026-03-21 06:18

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