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