Coverage Report

Created: 2026-06-10 06:24

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