Coverage Report

Created: 2025-07-11 06:18

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