Coverage Report

Created: 2025-10-10 06:39

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