Coverage Report

Created: 2025-09-04 07:02

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