1 /* $OpenBSD: packet.c,v 1.310 2023/04/06 03:21:31 djm Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
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.
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".
16 * SSH2 packet format added by Markus Friedl.
17 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
19 * Redistribution and use in source and binary forms, with or without
20 * modification, are permitted provided that the following conditions
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.
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.
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>
49 #include <netinet/in.h>
50 #include <netinet/ip.h>
51 #include <arpa/inet.h>
68 * Explicitly include OpenSSL before zlib as some versions of OpenSSL have
69 * "free_func" in their headers, which zlib typedefs.
72 # include <openssl/bn.h>
73 # include <openssl/evp.h>
74 # ifdef OPENSSL_HAS_ECC
75 # include <openssl/ec.h>
99 #include "blacklist_client.h"
107 #define PACKET_MAX_SIZE (256 * 1024)
109 struct packet_state {
117 TAILQ_ENTRY(packet) next;
119 struct sshbuf *payload;
122 struct session_state {
124 * This variable contains the file descriptors used for
125 * communicating with the other side. connection_in is used for
126 * reading; connection_out for writing. These can be the same
127 * descriptor, in which case it is assumed to be a socket.
132 /* Protocol flags for the remote side. */
133 u_int remote_protocol_flags;
135 /* Encryption context for receiving data. Only used for decryption. */
136 struct sshcipher_ctx *receive_context;
138 /* Encryption context for sending data. Only used for encryption. */
139 struct sshcipher_ctx *send_context;
141 /* Buffer for raw input data from the socket. */
142 struct sshbuf *input;
144 /* Buffer for raw output data going to the socket. */
145 struct sshbuf *output;
147 /* Buffer for the partial outgoing packet being constructed. */
148 struct sshbuf *outgoing_packet;
150 /* Buffer for the incoming packet currently being processed. */
151 struct sshbuf *incoming_packet;
153 /* Scratch buffer for packet compression/decompression. */
154 struct sshbuf *compression_buffer;
157 /* Incoming/outgoing compression dictionaries */
158 z_stream compression_in_stream;
159 z_stream compression_out_stream;
161 int compression_in_started;
162 int compression_out_started;
163 int compression_in_failures;
164 int compression_out_failures;
166 /* default maximum packet size */
167 u_int max_packet_size;
169 /* Flag indicating whether this module has been initialized. */
172 /* Set to true if the connection is interactive. */
173 int interactive_mode;
175 /* Set to true if we are the server side. */
178 /* Set to true if we are authenticated. */
179 int after_authentication;
181 int keep_alive_timeouts;
183 /* The maximum time that we will wait to send or receive a packet */
184 int packet_timeout_ms;
186 /* Session key information for Encryption and MAC */
187 struct newkeys *newkeys[MODE_MAX];
188 struct packet_state p_read, p_send;
190 /* Volume-based rekeying */
191 u_int64_t max_blocks_in, max_blocks_out, rekey_limit;
193 /* Time-based rekeying */
194 u_int32_t rekey_interval; /* how often in seconds */
195 time_t rekey_time; /* time of last rekeying */
197 /* roundup current message to extra_pad bytes */
200 /* XXX discard incoming data after MAC error */
201 u_int packet_discard;
202 size_t packet_discard_mac_already;
203 struct sshmac *packet_discard_mac;
205 /* Used in packet_read_poll2() */
208 /* Used in packet_send2 */
211 /* Used in ssh_packet_send_mux() */
214 /* Used in packet_set_interactive */
215 int set_interactive_called;
217 /* Used in packet_set_maxsize */
218 int set_maxsize_called;
220 /* One-off warning about weak ciphers */
221 int cipher_warning_done;
223 /* Hook for fuzzing inbound packets */
224 ssh_packet_hook_fn *hook_in;
227 TAILQ_HEAD(, packet) outgoing;
231 ssh_alloc_session_state(void)
233 struct ssh *ssh = NULL;
234 struct session_state *state = NULL;
236 if ((ssh = calloc(1, sizeof(*ssh))) == NULL ||
237 (state = calloc(1, sizeof(*state))) == NULL ||
238 (ssh->kex = kex_new()) == NULL ||
239 (state->input = sshbuf_new()) == NULL ||
240 (state->output = sshbuf_new()) == NULL ||
241 (state->outgoing_packet = sshbuf_new()) == NULL ||
242 (state->incoming_packet = sshbuf_new()) == NULL)
244 TAILQ_INIT(&state->outgoing);
245 TAILQ_INIT(&ssh->private_keys);
246 TAILQ_INIT(&ssh->public_keys);
247 state->connection_in = -1;
248 state->connection_out = -1;
249 state->max_packet_size = 32768;
250 state->packet_timeout_ms = -1;
251 state->p_send.packets = state->p_read.packets = 0;
252 state->initialized = 1;
254 * ssh_packet_send2() needs to queue packets until
255 * we've done the initial key exchange.
266 sshbuf_free(state->input);
267 sshbuf_free(state->output);
268 sshbuf_free(state->incoming_packet);
269 sshbuf_free(state->outgoing_packet);
276 ssh_packet_set_input_hook(struct ssh *ssh, ssh_packet_hook_fn *hook, void *ctx)
278 ssh->state->hook_in = hook;
279 ssh->state->hook_in_ctx = ctx;
282 /* Returns nonzero if rekeying is in progress */
284 ssh_packet_is_rekeying(struct ssh *ssh)
286 return ssh->state->rekeying ||
287 (ssh->kex != NULL && ssh->kex->done == 0);
291 * Sets the descriptors used for communication.
294 ssh_packet_set_connection(struct ssh *ssh, int fd_in, int fd_out)
296 struct session_state *state;
297 const struct sshcipher *none = cipher_by_name("none");
301 error_f("cannot load cipher 'none'");
305 ssh = ssh_alloc_session_state();
307 error_f("could not allocate state");
311 state->connection_in = fd_in;
312 state->connection_out = fd_out;
313 if ((r = cipher_init(&state->send_context, none,
314 (const u_char *)"", 0, NULL, 0, CIPHER_ENCRYPT)) != 0 ||
315 (r = cipher_init(&state->receive_context, none,
316 (const u_char *)"", 0, NULL, 0, CIPHER_DECRYPT)) != 0) {
317 error_fr(r, "cipher_init failed");
318 free(ssh); /* XXX need ssh_free_session_state? */
321 state->newkeys[MODE_IN] = state->newkeys[MODE_OUT] = NULL;
323 * Cache the IP address of the remote connection for use in error
324 * messages that might be generated after the connection has closed.
326 (void)ssh_remote_ipaddr(ssh);
331 ssh_packet_set_timeout(struct ssh *ssh, int timeout, int count)
333 struct session_state *state = ssh->state;
335 if (timeout <= 0 || count <= 0) {
336 state->packet_timeout_ms = -1;
339 if ((INT_MAX / 1000) / count < timeout)
340 state->packet_timeout_ms = INT_MAX;
342 state->packet_timeout_ms = timeout * count * 1000;
346 ssh_packet_set_mux(struct ssh *ssh)
349 ssh->state->rekeying = 0;
355 ssh_packet_get_mux(struct ssh *ssh)
357 return ssh->state->mux;
361 ssh_packet_set_log_preamble(struct ssh *ssh, const char *fmt, ...)
366 free(ssh->log_preamble);
368 ssh->log_preamble = NULL;
371 r = vasprintf(&ssh->log_preamble, fmt, args);
373 if (r < 0 || ssh->log_preamble == NULL)
374 return SSH_ERR_ALLOC_FAIL;
380 ssh_packet_stop_discard(struct ssh *ssh)
382 struct session_state *state = ssh->state;
385 if (state->packet_discard_mac) {
387 size_t dlen = PACKET_MAX_SIZE;
389 if (dlen > state->packet_discard_mac_already)
390 dlen -= state->packet_discard_mac_already;
391 memset(buf, 'a', sizeof(buf));
392 while (sshbuf_len(state->incoming_packet) < dlen)
393 if ((r = sshbuf_put(state->incoming_packet, buf,
396 (void) mac_compute(state->packet_discard_mac,
398 sshbuf_ptr(state->incoming_packet), dlen,
401 logit("Finished discarding for %.200s port %d",
402 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
403 return SSH_ERR_MAC_INVALID;
407 ssh_packet_start_discard(struct ssh *ssh, struct sshenc *enc,
408 struct sshmac *mac, size_t mac_already, u_int discard)
410 struct session_state *state = ssh->state;
413 if (enc == NULL || !cipher_is_cbc(enc->cipher) || (mac && mac->etm)) {
414 if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0)
416 return SSH_ERR_MAC_INVALID;
419 * Record number of bytes over which the mac has already
420 * been computed in order to minimize timing attacks.
422 if (mac && mac->enabled) {
423 state->packet_discard_mac = mac;
424 state->packet_discard_mac_already = mac_already;
426 if (sshbuf_len(state->input) >= discard)
427 return ssh_packet_stop_discard(ssh);
428 state->packet_discard = discard - sshbuf_len(state->input);
432 /* Returns 1 if remote host is connected via socket, 0 if not. */
435 ssh_packet_connection_is_on_socket(struct ssh *ssh)
437 struct session_state *state;
438 struct sockaddr_storage from, to;
439 socklen_t fromlen, tolen;
441 if (ssh == NULL || ssh->state == NULL)
445 if (state->connection_in == -1 || state->connection_out == -1)
447 /* filedescriptors in and out are the same, so it's a socket */
448 if (state->connection_in == state->connection_out)
450 fromlen = sizeof(from);
451 memset(&from, 0, sizeof(from));
452 if (getpeername(state->connection_in, (struct sockaddr *)&from,
456 memset(&to, 0, sizeof(to));
457 if (getpeername(state->connection_out, (struct sockaddr *)&to,
460 if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
462 if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
468 ssh_packet_get_bytes(struct ssh *ssh, u_int64_t *ibytes, u_int64_t *obytes)
471 *ibytes = ssh->state->p_read.bytes;
473 *obytes = ssh->state->p_send.bytes;
477 ssh_packet_connection_af(struct ssh *ssh)
479 return get_sock_af(ssh->state->connection_out);
482 /* Sets the connection into non-blocking mode. */
485 ssh_packet_set_nonblocking(struct ssh *ssh)
487 /* Set the socket into non-blocking mode. */
488 set_nonblock(ssh->state->connection_in);
490 if (ssh->state->connection_out != ssh->state->connection_in)
491 set_nonblock(ssh->state->connection_out);
494 /* Returns the socket used for reading. */
497 ssh_packet_get_connection_in(struct ssh *ssh)
499 return ssh->state->connection_in;
502 /* Returns the descriptor used for writing. */
505 ssh_packet_get_connection_out(struct ssh *ssh)
507 return ssh->state->connection_out;
511 * Returns the IP-address of the remote host as a string. The returned
512 * string must not be freed.
516 ssh_remote_ipaddr(struct ssh *ssh)
520 /* Check whether we have cached the ipaddr. */
521 if (ssh->remote_ipaddr == NULL) {
522 if (ssh_packet_connection_is_on_socket(ssh)) {
523 sock = ssh->state->connection_in;
524 ssh->remote_ipaddr = get_peer_ipaddr(sock);
525 ssh->remote_port = get_peer_port(sock);
526 ssh->local_ipaddr = get_local_ipaddr(sock);
527 ssh->local_port = get_local_port(sock);
529 ssh->remote_ipaddr = xstrdup("UNKNOWN");
530 ssh->remote_port = 65535;
531 ssh->local_ipaddr = xstrdup("UNKNOWN");
532 ssh->local_port = 65535;
535 return ssh->remote_ipaddr;
538 /* Returns the port number of the remote host. */
541 ssh_remote_port(struct ssh *ssh)
543 (void)ssh_remote_ipaddr(ssh); /* Will lookup and cache. */
544 return ssh->remote_port;
548 * Returns the IP-address of the local host as a string. The returned
549 * string must not be freed.
553 ssh_local_ipaddr(struct ssh *ssh)
555 (void)ssh_remote_ipaddr(ssh); /* Will lookup and cache. */
556 return ssh->local_ipaddr;
559 /* Returns the port number of the local host. */
562 ssh_local_port(struct ssh *ssh)
564 (void)ssh_remote_ipaddr(ssh); /* Will lookup and cache. */
565 return ssh->local_port;
568 /* Returns the routing domain of the input socket, or NULL if unavailable */
570 ssh_packet_rdomain_in(struct ssh *ssh)
572 if (ssh->rdomain_in != NULL)
573 return ssh->rdomain_in;
574 if (!ssh_packet_connection_is_on_socket(ssh))
576 ssh->rdomain_in = get_rdomain(ssh->state->connection_in);
577 return ssh->rdomain_in;
580 /* Closes the connection and clears and frees internal data structures. */
583 ssh_packet_close_internal(struct ssh *ssh, int do_close)
585 struct session_state *state = ssh->state;
588 if (!state->initialized)
590 state->initialized = 0;
592 if (state->connection_in == state->connection_out) {
593 close(state->connection_out);
595 close(state->connection_in);
596 close(state->connection_out);
599 sshbuf_free(state->input);
600 sshbuf_free(state->output);
601 sshbuf_free(state->outgoing_packet);
602 sshbuf_free(state->incoming_packet);
603 for (mode = 0; mode < MODE_MAX; mode++) {
604 kex_free_newkeys(state->newkeys[mode]); /* current keys */
605 state->newkeys[mode] = NULL;
606 ssh_clear_newkeys(ssh, mode); /* next keys */
609 /* compression state is in shared mem, so we can only release it once */
610 if (do_close && state->compression_buffer) {
611 sshbuf_free(state->compression_buffer);
612 if (state->compression_out_started) {
613 z_streamp stream = &state->compression_out_stream;
614 debug("compress outgoing: "
615 "raw data %llu, compressed %llu, factor %.2f",
616 (unsigned long long)stream->total_in,
617 (unsigned long long)stream->total_out,
618 stream->total_in == 0 ? 0.0 :
619 (double) stream->total_out / stream->total_in);
620 if (state->compression_out_failures == 0)
623 if (state->compression_in_started) {
624 z_streamp stream = &state->compression_in_stream;
625 debug("compress incoming: "
626 "raw data %llu, compressed %llu, factor %.2f",
627 (unsigned long long)stream->total_out,
628 (unsigned long long)stream->total_in,
629 stream->total_out == 0 ? 0.0 :
630 (double) stream->total_in / stream->total_out);
631 if (state->compression_in_failures == 0)
635 #endif /* WITH_ZLIB */
636 cipher_free(state->send_context);
637 cipher_free(state->receive_context);
638 state->send_context = state->receive_context = NULL;
640 free(ssh->local_ipaddr);
641 ssh->local_ipaddr = NULL;
642 free(ssh->remote_ipaddr);
643 ssh->remote_ipaddr = NULL;
652 ssh_packet_close(struct ssh *ssh)
654 ssh_packet_close_internal(ssh, 1);
658 ssh_packet_clear_keys(struct ssh *ssh)
660 ssh_packet_close_internal(ssh, 0);
663 /* Sets remote side protocol flags. */
666 ssh_packet_set_protocol_flags(struct ssh *ssh, u_int protocol_flags)
668 ssh->state->remote_protocol_flags = protocol_flags;
671 /* Returns the remote protocol flags set earlier by the above function. */
674 ssh_packet_get_protocol_flags(struct ssh *ssh)
676 return ssh->state->remote_protocol_flags;
680 * Starts packet compression from the next packet on in both directions.
681 * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
685 ssh_packet_init_compression(struct ssh *ssh)
687 if (!ssh->state->compression_buffer &&
688 ((ssh->state->compression_buffer = sshbuf_new()) == NULL))
689 return SSH_ERR_ALLOC_FAIL;
695 start_compression_out(struct ssh *ssh, int level)
697 if (level < 1 || level > 9)
698 return SSH_ERR_INVALID_ARGUMENT;
699 debug("Enabling compression at level %d.", level);
700 if (ssh->state->compression_out_started == 1)
701 deflateEnd(&ssh->state->compression_out_stream);
702 switch (deflateInit(&ssh->state->compression_out_stream, level)) {
704 ssh->state->compression_out_started = 1;
707 return SSH_ERR_ALLOC_FAIL;
709 return SSH_ERR_INTERNAL_ERROR;
715 start_compression_in(struct ssh *ssh)
717 if (ssh->state->compression_in_started == 1)
718 inflateEnd(&ssh->state->compression_in_stream);
719 switch (inflateInit(&ssh->state->compression_in_stream)) {
721 ssh->state->compression_in_started = 1;
724 return SSH_ERR_ALLOC_FAIL;
726 return SSH_ERR_INTERNAL_ERROR;
731 /* XXX remove need for separate compression buffer */
733 compress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
738 if (ssh->state->compression_out_started != 1)
739 return SSH_ERR_INTERNAL_ERROR;
741 /* This case is not handled below. */
742 if (sshbuf_len(in) == 0)
745 /* Input is the contents of the input buffer. */
746 if ((ssh->state->compression_out_stream.next_in =
747 sshbuf_mutable_ptr(in)) == NULL)
748 return SSH_ERR_INTERNAL_ERROR;
749 ssh->state->compression_out_stream.avail_in = sshbuf_len(in);
751 /* Loop compressing until deflate() returns with avail_out != 0. */
753 /* Set up fixed-size output buffer. */
754 ssh->state->compression_out_stream.next_out = buf;
755 ssh->state->compression_out_stream.avail_out = sizeof(buf);
757 /* Compress as much data into the buffer as possible. */
758 status = deflate(&ssh->state->compression_out_stream,
762 return SSH_ERR_ALLOC_FAIL;
764 /* Append compressed data to output_buffer. */
765 if ((r = sshbuf_put(out, buf, sizeof(buf) -
766 ssh->state->compression_out_stream.avail_out)) != 0)
771 ssh->state->compression_out_failures++;
772 return SSH_ERR_INVALID_FORMAT;
774 } while (ssh->state->compression_out_stream.avail_out == 0);
779 uncompress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
784 if (ssh->state->compression_in_started != 1)
785 return SSH_ERR_INTERNAL_ERROR;
787 if ((ssh->state->compression_in_stream.next_in =
788 sshbuf_mutable_ptr(in)) == NULL)
789 return SSH_ERR_INTERNAL_ERROR;
790 ssh->state->compression_in_stream.avail_in = sshbuf_len(in);
793 /* Set up fixed-size output buffer. */
794 ssh->state->compression_in_stream.next_out = buf;
795 ssh->state->compression_in_stream.avail_out = sizeof(buf);
797 status = inflate(&ssh->state->compression_in_stream,
801 if ((r = sshbuf_put(out, buf, sizeof(buf) -
802 ssh->state->compression_in_stream.avail_out)) != 0)
807 * Comments in zlib.h say that we should keep calling
808 * inflate() until we get an error. This appears to
809 * be the error that we get.
813 return SSH_ERR_INVALID_FORMAT;
815 return SSH_ERR_ALLOC_FAIL;
818 ssh->state->compression_in_failures++;
819 return SSH_ERR_INTERNAL_ERROR;
825 #else /* WITH_ZLIB */
828 start_compression_out(struct ssh *ssh, int level)
830 return SSH_ERR_INTERNAL_ERROR;
834 start_compression_in(struct ssh *ssh)
836 return SSH_ERR_INTERNAL_ERROR;
840 compress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
842 return SSH_ERR_INTERNAL_ERROR;
846 uncompress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
848 return SSH_ERR_INTERNAL_ERROR;
850 #endif /* WITH_ZLIB */
853 ssh_clear_newkeys(struct ssh *ssh, int mode)
855 if (ssh->kex && ssh->kex->newkeys[mode]) {
856 kex_free_newkeys(ssh->kex->newkeys[mode]);
857 ssh->kex->newkeys[mode] = NULL;
862 ssh_set_newkeys(struct ssh *ssh, int mode)
864 struct session_state *state = ssh->state;
867 struct sshcomp *comp;
868 struct sshcipher_ctx **ccp;
869 struct packet_state *ps;
870 u_int64_t *max_blocks;
873 const char *dir = mode == MODE_OUT ? "out" : "in";
875 debug2_f("mode %d", mode);
877 if (mode == MODE_OUT) {
878 ccp = &state->send_context;
879 crypt_type = CIPHER_ENCRYPT;
881 max_blocks = &state->max_blocks_out;
883 ccp = &state->receive_context;
884 crypt_type = CIPHER_DECRYPT;
886 max_blocks = &state->max_blocks_in;
888 if (state->newkeys[mode] != NULL) {
889 debug_f("rekeying %s, input %llu bytes %llu blocks, "
890 "output %llu bytes %llu blocks", dir,
891 (unsigned long long)state->p_read.bytes,
892 (unsigned long long)state->p_read.blocks,
893 (unsigned long long)state->p_send.bytes,
894 (unsigned long long)state->p_send.blocks);
895 kex_free_newkeys(state->newkeys[mode]);
896 state->newkeys[mode] = NULL;
898 /* note that both bytes and the seqnr are not reset */
899 ps->packets = ps->blocks = 0;
900 /* move newkeys from kex to state */
901 if ((state->newkeys[mode] = ssh->kex->newkeys[mode]) == NULL)
902 return SSH_ERR_INTERNAL_ERROR;
903 ssh->kex->newkeys[mode] = NULL;
904 enc = &state->newkeys[mode]->enc;
905 mac = &state->newkeys[mode]->mac;
906 comp = &state->newkeys[mode]->comp;
907 if (cipher_authlen(enc->cipher) == 0) {
908 if ((r = mac_init(mac)) != 0)
912 DBG(debug_f("cipher_init: %s", dir));
915 if ((r = cipher_init(ccp, enc->cipher, enc->key, enc->key_len,
916 enc->iv, enc->iv_len, crypt_type)) != 0)
918 if (!state->cipher_warning_done &&
919 (wmsg = cipher_warning_message(*ccp)) != NULL) {
920 error("Warning: %s", wmsg);
921 state->cipher_warning_done = 1;
923 /* Deleting the keys does not gain extra security */
924 /* explicit_bzero(enc->iv, enc->block_size);
925 explicit_bzero(enc->key, enc->key_len);
926 explicit_bzero(mac->key, mac->key_len); */
927 if ((comp->type == COMP_ZLIB ||
928 (comp->type == COMP_DELAYED &&
929 state->after_authentication)) && comp->enabled == 0) {
930 if ((r = ssh_packet_init_compression(ssh)) < 0)
932 if (mode == MODE_OUT) {
933 if ((r = start_compression_out(ssh, 6)) != 0)
936 if ((r = start_compression_in(ssh)) != 0)
942 * The 2^(blocksize*2) limit is too expensive for 3DES,
943 * so enforce a 1GB limit for small blocksizes.
944 * See RFC4344 section 3.2.
946 if (enc->block_size >= 16)
947 *max_blocks = (u_int64_t)1 << (enc->block_size*2);
949 *max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
950 if (state->rekey_limit)
951 *max_blocks = MINIMUM(*max_blocks,
952 state->rekey_limit / enc->block_size);
953 debug("rekey %s after %llu blocks", dir,
954 (unsigned long long)*max_blocks);
958 #define MAX_PACKETS (1U<<31)
960 ssh_packet_need_rekeying(struct ssh *ssh, u_int outbound_packet_len)
962 struct session_state *state = ssh->state;
963 u_int32_t out_blocks;
965 /* XXX client can't cope with rekeying pre-auth */
966 if (!state->after_authentication)
969 /* Haven't keyed yet or KEX in progress. */
970 if (ssh_packet_is_rekeying(ssh))
973 /* Peer can't rekey */
974 if (ssh->compat & SSH_BUG_NOREKEY)
978 * Permit one packet in or out per rekey - this allows us to
979 * make progress when rekey limits are very small.
981 if (state->p_send.packets == 0 && state->p_read.packets == 0)
984 /* Time-based rekeying */
985 if (state->rekey_interval != 0 &&
986 (int64_t)state->rekey_time + state->rekey_interval <= monotime())
990 * Always rekey when MAX_PACKETS sent in either direction
991 * As per RFC4344 section 3.1 we do this after 2^31 packets.
993 if (state->p_send.packets > MAX_PACKETS ||
994 state->p_read.packets > MAX_PACKETS)
997 /* Rekey after (cipher-specific) maximum blocks */
998 out_blocks = ROUNDUP(outbound_packet_len,
999 state->newkeys[MODE_OUT]->enc.block_size);
1000 return (state->max_blocks_out &&
1001 (state->p_send.blocks + out_blocks > state->max_blocks_out)) ||
1002 (state->max_blocks_in &&
1003 (state->p_read.blocks > state->max_blocks_in));
1007 ssh_packet_check_rekey(struct ssh *ssh)
1009 if (!ssh_packet_need_rekeying(ssh, 0))
1011 debug3_f("rekex triggered");
1012 return kex_start_rekex(ssh);
1016 * Delayed compression for SSH2 is enabled after authentication:
1017 * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
1018 * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
1021 ssh_packet_enable_delayed_compress(struct ssh *ssh)
1023 struct session_state *state = ssh->state;
1024 struct sshcomp *comp = NULL;
1028 * Remember that we are past the authentication step, so rekeying
1029 * with COMP_DELAYED will turn on compression immediately.
1031 state->after_authentication = 1;
1032 for (mode = 0; mode < MODE_MAX; mode++) {
1033 /* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
1034 if (state->newkeys[mode] == NULL)
1036 comp = &state->newkeys[mode]->comp;
1037 if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
1038 if ((r = ssh_packet_init_compression(ssh)) != 0)
1040 if (mode == MODE_OUT) {
1041 if ((r = start_compression_out(ssh, 6)) != 0)
1044 if ((r = start_compression_in(ssh)) != 0)
1053 /* Used to mute debug logging for noisy packet types */
1055 ssh_packet_log_type(u_char type)
1058 case SSH2_MSG_CHANNEL_DATA:
1059 case SSH2_MSG_CHANNEL_EXTENDED_DATA:
1060 case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
1068 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
1071 ssh_packet_send2_wrapped(struct ssh *ssh)
1073 struct session_state *state = ssh->state;
1074 u_char type, *cp, macbuf[SSH_DIGEST_MAX_LENGTH];
1075 u_char tmp, padlen, pad = 0;
1076 u_int authlen = 0, aadlen = 0;
1078 struct sshenc *enc = NULL;
1079 struct sshmac *mac = NULL;
1080 struct sshcomp *comp = NULL;
1083 if (state->newkeys[MODE_OUT] != NULL) {
1084 enc = &state->newkeys[MODE_OUT]->enc;
1085 mac = &state->newkeys[MODE_OUT]->mac;
1086 comp = &state->newkeys[MODE_OUT]->comp;
1087 /* disable mac for authenticated encryption */
1088 if ((authlen = cipher_authlen(enc->cipher)) != 0)
1091 block_size = enc ? enc->block_size : 8;
1092 aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
1094 type = (sshbuf_ptr(state->outgoing_packet))[5];
1095 if (ssh_packet_log_type(type))
1096 debug3("send packet: type %u", type);
1098 fprintf(stderr, "plain: ");
1099 sshbuf_dump(state->outgoing_packet, stderr);
1102 if (comp && comp->enabled) {
1103 len = sshbuf_len(state->outgoing_packet);
1104 /* skip header, compress only payload */
1105 if ((r = sshbuf_consume(state->outgoing_packet, 5)) != 0)
1107 sshbuf_reset(state->compression_buffer);
1108 if ((r = compress_buffer(ssh, state->outgoing_packet,
1109 state->compression_buffer)) != 0)
1111 sshbuf_reset(state->outgoing_packet);
1112 if ((r = sshbuf_put(state->outgoing_packet,
1113 "\0\0\0\0\0", 5)) != 0 ||
1114 (r = sshbuf_putb(state->outgoing_packet,
1115 state->compression_buffer)) != 0)
1117 DBG(debug("compression: raw %d compressed %zd", len,
1118 sshbuf_len(state->outgoing_packet)));
1121 /* sizeof (packet_len + pad_len + payload) */
1122 len = sshbuf_len(state->outgoing_packet);
1125 * calc size of padding, alloc space, get random data,
1126 * minimum padding is 4 bytes
1128 len -= aadlen; /* packet length is not encrypted for EtM modes */
1129 padlen = block_size - (len % block_size);
1131 padlen += block_size;
1132 if (state->extra_pad) {
1133 tmp = state->extra_pad;
1135 ROUNDUP(state->extra_pad, block_size);
1136 /* check if roundup overflowed */
1137 if (state->extra_pad < tmp)
1138 return SSH_ERR_INVALID_ARGUMENT;
1139 tmp = (len + padlen) % state->extra_pad;
1140 /* Check whether pad calculation below will underflow */
1141 if (tmp > state->extra_pad)
1142 return SSH_ERR_INVALID_ARGUMENT;
1143 pad = state->extra_pad - tmp;
1144 DBG(debug3_f("adding %d (len %d padlen %d extra_pad %d)",
1145 pad, len, padlen, state->extra_pad));
1148 /* Check whether padlen calculation overflowed */
1150 return SSH_ERR_INVALID_ARGUMENT; /* overflow */
1151 state->extra_pad = 0;
1153 if ((r = sshbuf_reserve(state->outgoing_packet, padlen, &cp)) != 0)
1155 if (enc && !cipher_ctx_is_plaintext(state->send_context)) {
1156 /* random padding */
1157 arc4random_buf(cp, padlen);
1160 explicit_bzero(cp, padlen);
1162 /* sizeof (packet_len + pad_len + payload + padding) */
1163 len = sshbuf_len(state->outgoing_packet);
1164 cp = sshbuf_mutable_ptr(state->outgoing_packet);
1166 r = SSH_ERR_INTERNAL_ERROR;
1169 /* packet_length includes payload, padding and padding length field */
1170 POKE_U32(cp, len - 4);
1172 DBG(debug("send: len %d (includes padlen %d, aadlen %d)",
1173 len, padlen, aadlen));
1175 /* compute MAC over seqnr and packet(length fields, payload, padding) */
1176 if (mac && mac->enabled && !mac->etm) {
1177 if ((r = mac_compute(mac, state->p_send.seqnr,
1178 sshbuf_ptr(state->outgoing_packet), len,
1179 macbuf, sizeof(macbuf))) != 0)
1181 DBG(debug("done calc MAC out #%d", state->p_send.seqnr));
1183 /* encrypt packet and append to output buffer. */
1184 if ((r = sshbuf_reserve(state->output,
1185 sshbuf_len(state->outgoing_packet) + authlen, &cp)) != 0)
1187 if ((r = cipher_crypt(state->send_context, state->p_send.seqnr, cp,
1188 sshbuf_ptr(state->outgoing_packet),
1189 len - aadlen, aadlen, authlen)) != 0)
1191 /* append unencrypted MAC */
1192 if (mac && mac->enabled) {
1194 /* EtM: compute mac over aadlen + cipher text */
1195 if ((r = mac_compute(mac, state->p_send.seqnr,
1196 cp, len, macbuf, sizeof(macbuf))) != 0)
1198 DBG(debug("done calc MAC(EtM) out #%d",
1199 state->p_send.seqnr));
1201 if ((r = sshbuf_put(state->output, macbuf, mac->mac_len)) != 0)
1205 fprintf(stderr, "encrypted: ");
1206 sshbuf_dump(state->output, stderr);
1208 /* increment sequence number for outgoing packets */
1209 if (++state->p_send.seqnr == 0)
1210 logit("outgoing seqnr wraps around");
1211 if (++state->p_send.packets == 0)
1212 if (!(ssh->compat & SSH_BUG_NOREKEY))
1213 return SSH_ERR_NEED_REKEY;
1214 state->p_send.blocks += len / block_size;
1215 state->p_send.bytes += len;
1216 sshbuf_reset(state->outgoing_packet);
1218 if (type == SSH2_MSG_NEWKEYS)
1219 r = ssh_set_newkeys(ssh, MODE_OUT);
1220 else if (type == SSH2_MSG_USERAUTH_SUCCESS && state->server_side)
1221 r = ssh_packet_enable_delayed_compress(ssh);
1228 /* returns non-zero if the specified packet type is usec by KEX */
1230 ssh_packet_type_is_kex(u_char type)
1233 type >= SSH2_MSG_TRANSPORT_MIN &&
1234 type <= SSH2_MSG_TRANSPORT_MAX &&
1235 type != SSH2_MSG_SERVICE_REQUEST &&
1236 type != SSH2_MSG_SERVICE_ACCEPT &&
1237 type != SSH2_MSG_EXT_INFO;
1241 ssh_packet_send2(struct ssh *ssh)
1243 struct session_state *state = ssh->state;
1248 if (sshbuf_len(state->outgoing_packet) < 6)
1249 return SSH_ERR_INTERNAL_ERROR;
1250 type = sshbuf_ptr(state->outgoing_packet)[5];
1251 need_rekey = !ssh_packet_type_is_kex(type) &&
1252 ssh_packet_need_rekeying(ssh, sshbuf_len(state->outgoing_packet));
1255 * During rekeying we can only send key exchange messages.
1256 * Queue everything else.
1258 if ((need_rekey || state->rekeying) && !ssh_packet_type_is_kex(type)) {
1260 debug3_f("rekex triggered");
1261 debug("enqueue packet: %u", type);
1262 p = calloc(1, sizeof(*p));
1264 return SSH_ERR_ALLOC_FAIL;
1266 p->payload = state->outgoing_packet;
1267 TAILQ_INSERT_TAIL(&state->outgoing, p, next);
1268 state->outgoing_packet = sshbuf_new();
1269 if (state->outgoing_packet == NULL)
1270 return SSH_ERR_ALLOC_FAIL;
1273 * This packet triggered a rekey, so send the
1275 * NB. reenters this function via kex_start_rekex().
1277 return kex_start_rekex(ssh);
1282 /* rekeying starts with sending KEXINIT */
1283 if (type == SSH2_MSG_KEXINIT)
1284 state->rekeying = 1;
1286 if ((r = ssh_packet_send2_wrapped(ssh)) != 0)
1289 /* after a NEWKEYS message we can send the complete queue */
1290 if (type == SSH2_MSG_NEWKEYS) {
1291 state->rekeying = 0;
1292 state->rekey_time = monotime();
1293 while ((p = TAILQ_FIRST(&state->outgoing))) {
1296 * If this packet triggers a rekex, then skip the
1297 * remaining packets in the queue for now.
1298 * NB. re-enters this function via kex_start_rekex.
1300 if (ssh_packet_need_rekeying(ssh,
1301 sshbuf_len(p->payload))) {
1302 debug3_f("queued packet triggered rekex");
1303 return kex_start_rekex(ssh);
1305 debug("dequeue packet: %u", type);
1306 sshbuf_free(state->outgoing_packet);
1307 state->outgoing_packet = p->payload;
1308 TAILQ_REMOVE(&state->outgoing, p, next);
1309 memset(p, 0, sizeof(*p));
1311 if ((r = ssh_packet_send2_wrapped(ssh)) != 0)
1319 * Waits until a packet has been received, and returns its type. Note that
1320 * no other data is processed until this returns, so this function should not
1321 * be used during the interactive session.
1325 ssh_packet_read_seqnr(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1327 struct session_state *state = ssh->state;
1328 int len, r, ms_remain = 0;
1331 struct timeval start;
1332 struct timespec timespec, *timespecp = NULL;
1334 DBG(debug("packet_read()"));
1337 * Since we are blocking, ensure that all written packets have
1340 if ((r = ssh_packet_write_wait(ssh)) != 0)
1343 /* Stay in the loop until we have received a complete packet. */
1345 /* Try to read a packet from the buffer. */
1346 r = ssh_packet_read_poll_seqnr(ssh, typep, seqnr_p);
1349 /* If we got a packet, return it. */
1350 if (*typep != SSH_MSG_NONE)
1353 * Otherwise, wait for some data to arrive, add it to the
1354 * buffer, and try again.
1356 pfd.fd = state->connection_in;
1357 pfd.events = POLLIN;
1359 if (state->packet_timeout_ms > 0) {
1360 ms_remain = state->packet_timeout_ms;
1361 timespecp = ×pec;
1363 /* Wait for some data to arrive. */
1365 if (state->packet_timeout_ms > 0) {
1366 ms_to_timespec(×pec, ms_remain);
1367 monotime_tv(&start);
1369 if ((r = ppoll(&pfd, 1, timespecp, NULL)) >= 0)
1371 if (errno != EAGAIN && errno != EINTR &&
1372 errno != EWOULDBLOCK) {
1373 r = SSH_ERR_SYSTEM_ERROR;
1376 if (state->packet_timeout_ms <= 0)
1378 ms_subtract_diff(&start, &ms_remain);
1379 if (ms_remain <= 0) {
1385 r = SSH_ERR_CONN_TIMEOUT;
1388 /* Read data from the socket. */
1389 len = read(state->connection_in, buf, sizeof(buf));
1391 r = SSH_ERR_CONN_CLOSED;
1395 r = SSH_ERR_SYSTEM_ERROR;
1399 /* Append it to the buffer. */
1400 if ((r = ssh_packet_process_incoming(ssh, buf, len)) != 0)
1408 ssh_packet_read(struct ssh *ssh)
1413 if ((r = ssh_packet_read_seqnr(ssh, &type, NULL)) != 0)
1414 fatal_fr(r, "read");
1419 * Waits until a packet has been received, verifies that its type matches
1420 * that given, and gives a fatal error and exits if there is a mismatch.
1424 ssh_packet_read_expect(struct ssh *ssh, u_int expected_type)
1429 if ((r = ssh_packet_read_seqnr(ssh, &type, NULL)) != 0)
1431 if (type != expected_type) {
1432 if ((r = sshpkt_disconnect(ssh,
1433 "Protocol error: expected packet type %d, got %d",
1434 expected_type, type)) != 0)
1436 return SSH_ERR_PROTOCOL_ERROR;
1442 ssh_packet_read_poll2_mux(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1444 struct session_state *state = ssh->state;
1450 return SSH_ERR_INTERNAL_ERROR;
1451 *typep = SSH_MSG_NONE;
1452 cp = sshbuf_ptr(state->input);
1453 if (state->packlen == 0) {
1454 if (sshbuf_len(state->input) < 4 + 1)
1455 return 0; /* packet is incomplete */
1456 state->packlen = PEEK_U32(cp);
1457 if (state->packlen < 4 + 1 ||
1458 state->packlen > PACKET_MAX_SIZE)
1459 return SSH_ERR_MESSAGE_INCOMPLETE;
1461 need = state->packlen + 4;
1462 if (sshbuf_len(state->input) < need)
1463 return 0; /* packet is incomplete */
1464 sshbuf_reset(state->incoming_packet);
1465 if ((r = sshbuf_put(state->incoming_packet, cp + 4,
1466 state->packlen)) != 0 ||
1467 (r = sshbuf_consume(state->input, need)) != 0 ||
1468 (r = sshbuf_get_u8(state->incoming_packet, NULL)) != 0 ||
1469 (r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
1471 if (ssh_packet_log_type(*typep))
1472 debug3_f("type %u", *typep);
1473 /* sshbuf_dump(state->incoming_packet, stderr); */
1474 /* reset for next packet */
1480 ssh_packet_read_poll2(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1482 struct session_state *state = ssh->state;
1485 u_int maclen, aadlen = 0, authlen = 0, block_size;
1486 struct sshenc *enc = NULL;
1487 struct sshmac *mac = NULL;
1488 struct sshcomp *comp = NULL;
1492 return ssh_packet_read_poll2_mux(ssh, typep, seqnr_p);
1494 *typep = SSH_MSG_NONE;
1496 if (state->packet_discard)
1499 if (state->newkeys[MODE_IN] != NULL) {
1500 enc = &state->newkeys[MODE_IN]->enc;
1501 mac = &state->newkeys[MODE_IN]->mac;
1502 comp = &state->newkeys[MODE_IN]->comp;
1503 /* disable mac for authenticated encryption */
1504 if ((authlen = cipher_authlen(enc->cipher)) != 0)
1507 maclen = mac && mac->enabled ? mac->mac_len : 0;
1508 block_size = enc ? enc->block_size : 8;
1509 aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
1511 if (aadlen && state->packlen == 0) {
1512 if (cipher_get_length(state->receive_context,
1513 &state->packlen, state->p_read.seqnr,
1514 sshbuf_ptr(state->input), sshbuf_len(state->input)) != 0)
1516 if (state->packlen < 1 + 4 ||
1517 state->packlen > PACKET_MAX_SIZE) {
1519 sshbuf_dump(state->input, stderr);
1521 logit("Bad packet length %u.", state->packlen);
1522 if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0)
1524 return SSH_ERR_CONN_CORRUPT;
1526 sshbuf_reset(state->incoming_packet);
1527 } else if (state->packlen == 0) {
1529 * check if input size is less than the cipher block size,
1530 * decrypt first block and extract length of incoming packet
1532 if (sshbuf_len(state->input) < block_size)
1534 sshbuf_reset(state->incoming_packet);
1535 if ((r = sshbuf_reserve(state->incoming_packet, block_size,
1538 if ((r = cipher_crypt(state->receive_context,
1539 state->p_send.seqnr, cp, sshbuf_ptr(state->input),
1540 block_size, 0, 0)) != 0)
1542 state->packlen = PEEK_U32(sshbuf_ptr(state->incoming_packet));
1543 if (state->packlen < 1 + 4 ||
1544 state->packlen > PACKET_MAX_SIZE) {
1546 fprintf(stderr, "input: \n");
1547 sshbuf_dump(state->input, stderr);
1548 fprintf(stderr, "incoming_packet: \n");
1549 sshbuf_dump(state->incoming_packet, stderr);
1551 logit("Bad packet length %u.", state->packlen);
1552 return ssh_packet_start_discard(ssh, enc, mac, 0,
1555 if ((r = sshbuf_consume(state->input, block_size)) != 0)
1558 DBG(debug("input: packet len %u", state->packlen+4));
1561 /* only the payload is encrypted */
1562 need = state->packlen;
1565 * the payload size and the payload are encrypted, but we
1566 * have a partial packet of block_size bytes
1568 need = 4 + state->packlen - block_size;
1570 DBG(debug("partial packet: block %d, need %d, maclen %d, authlen %d,"
1571 " aadlen %d", block_size, need, maclen, authlen, aadlen));
1572 if (need % block_size != 0) {
1573 logit("padding error: need %d block %d mod %d",
1574 need, block_size, need % block_size);
1575 return ssh_packet_start_discard(ssh, enc, mac, 0,
1576 PACKET_MAX_SIZE - block_size);
1579 * check if the entire packet has been received and
1580 * decrypt into incoming_packet:
1581 * 'aadlen' bytes are unencrypted, but authenticated.
1582 * 'need' bytes are encrypted, followed by either
1583 * 'authlen' bytes of authentication tag or
1584 * 'maclen' bytes of message authentication code.
1586 if (sshbuf_len(state->input) < aadlen + need + authlen + maclen)
1587 return 0; /* packet is incomplete */
1589 fprintf(stderr, "read_poll enc/full: ");
1590 sshbuf_dump(state->input, stderr);
1592 /* EtM: check mac over encrypted input */
1593 if (mac && mac->enabled && mac->etm) {
1594 if ((r = mac_check(mac, state->p_read.seqnr,
1595 sshbuf_ptr(state->input), aadlen + need,
1596 sshbuf_ptr(state->input) + aadlen + need + authlen,
1598 if (r == SSH_ERR_MAC_INVALID)
1599 logit("Corrupted MAC on input.");
1603 if ((r = sshbuf_reserve(state->incoming_packet, aadlen + need,
1606 if ((r = cipher_crypt(state->receive_context, state->p_read.seqnr, cp,
1607 sshbuf_ptr(state->input), need, aadlen, authlen)) != 0)
1609 if ((r = sshbuf_consume(state->input, aadlen + need + authlen)) != 0)
1611 if (mac && mac->enabled) {
1612 /* Not EtM: check MAC over cleartext */
1613 if (!mac->etm && (r = mac_check(mac, state->p_read.seqnr,
1614 sshbuf_ptr(state->incoming_packet),
1615 sshbuf_len(state->incoming_packet),
1616 sshbuf_ptr(state->input), maclen)) != 0) {
1617 if (r != SSH_ERR_MAC_INVALID)
1619 logit("Corrupted MAC on input.");
1620 if (need + block_size > PACKET_MAX_SIZE)
1621 return SSH_ERR_INTERNAL_ERROR;
1622 return ssh_packet_start_discard(ssh, enc, mac,
1623 sshbuf_len(state->incoming_packet),
1624 PACKET_MAX_SIZE - need - block_size);
1626 /* Remove MAC from input buffer */
1627 DBG(debug("MAC #%d ok", state->p_read.seqnr));
1628 if ((r = sshbuf_consume(state->input, mac->mac_len)) != 0)
1631 if (seqnr_p != NULL)
1632 *seqnr_p = state->p_read.seqnr;
1633 if (++state->p_read.seqnr == 0)
1634 logit("incoming seqnr wraps around");
1635 if (++state->p_read.packets == 0)
1636 if (!(ssh->compat & SSH_BUG_NOREKEY))
1637 return SSH_ERR_NEED_REKEY;
1638 state->p_read.blocks += (state->packlen + 4) / block_size;
1639 state->p_read.bytes += state->packlen + 4;
1642 padlen = sshbuf_ptr(state->incoming_packet)[4];
1643 DBG(debug("input: padlen %d", padlen));
1645 if ((r = sshpkt_disconnect(ssh,
1646 "Corrupted padlen %d on input.", padlen)) != 0 ||
1647 (r = ssh_packet_write_wait(ssh)) != 0)
1649 return SSH_ERR_CONN_CORRUPT;
1652 /* skip packet size + padlen, discard padding */
1653 if ((r = sshbuf_consume(state->incoming_packet, 4 + 1)) != 0 ||
1654 ((r = sshbuf_consume_end(state->incoming_packet, padlen)) != 0))
1657 DBG(debug("input: len before de-compress %zd",
1658 sshbuf_len(state->incoming_packet)));
1659 if (comp && comp->enabled) {
1660 sshbuf_reset(state->compression_buffer);
1661 if ((r = uncompress_buffer(ssh, state->incoming_packet,
1662 state->compression_buffer)) != 0)
1664 sshbuf_reset(state->incoming_packet);
1665 if ((r = sshbuf_putb(state->incoming_packet,
1666 state->compression_buffer)) != 0)
1668 DBG(debug("input: len after de-compress %zd",
1669 sshbuf_len(state->incoming_packet)));
1672 * get packet type, implies consume.
1673 * return length of payload (without type field)
1675 if ((r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
1677 if (ssh_packet_log_type(*typep))
1678 debug3("receive packet: type %u", *typep);
1679 if (*typep < SSH2_MSG_MIN || *typep >= SSH2_MSG_LOCAL_MIN) {
1680 if ((r = sshpkt_disconnect(ssh,
1681 "Invalid ssh2 packet type: %d", *typep)) != 0 ||
1682 (r = ssh_packet_write_wait(ssh)) != 0)
1684 return SSH_ERR_PROTOCOL_ERROR;
1686 if (state->hook_in != NULL &&
1687 (r = state->hook_in(ssh, state->incoming_packet, typep,
1688 state->hook_in_ctx)) != 0)
1690 if (*typep == SSH2_MSG_USERAUTH_SUCCESS && !state->server_side)
1691 r = ssh_packet_enable_delayed_compress(ssh);
1695 fprintf(stderr, "read/plain[%d]:\r\n", *typep);
1696 sshbuf_dump(state->incoming_packet, stderr);
1698 /* reset for next packet */
1701 if ((r = ssh_packet_check_rekey(ssh)) != 0)
1708 ssh_packet_read_poll_seqnr(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1710 struct session_state *state = ssh->state;
1711 u_int reason, seqnr;
1717 r = ssh_packet_read_poll2(ssh, typep, seqnr_p);
1721 state->keep_alive_timeouts = 0;
1722 DBG(debug("received packet type %d", *typep));
1725 case SSH2_MSG_IGNORE:
1726 debug3("Received SSH2_MSG_IGNORE");
1728 case SSH2_MSG_DEBUG:
1729 if ((r = sshpkt_get_u8(ssh, NULL)) != 0 ||
1730 (r = sshpkt_get_string(ssh, &msg, NULL)) != 0 ||
1731 (r = sshpkt_get_string(ssh, NULL, NULL)) != 0) {
1735 debug("Remote: %.900s", msg);
1738 case SSH2_MSG_DISCONNECT:
1739 if ((r = sshpkt_get_u32(ssh, &reason)) != 0 ||
1740 (r = sshpkt_get_string(ssh, &msg, NULL)) != 0)
1742 /* Ignore normal client exit notifications */
1743 do_log2(ssh->state->server_side &&
1744 reason == SSH2_DISCONNECT_BY_APPLICATION ?
1745 SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_ERROR,
1746 "Received disconnect from %s port %d:"
1747 "%u: %.400s", ssh_remote_ipaddr(ssh),
1748 ssh_remote_port(ssh), reason, msg);
1750 return SSH_ERR_DISCONNECTED;
1751 case SSH2_MSG_UNIMPLEMENTED:
1752 if ((r = sshpkt_get_u32(ssh, &seqnr)) != 0)
1754 debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1764 * Buffers the supplied input data. This is intended to be used together
1765 * with packet_read_poll().
1768 ssh_packet_process_incoming(struct ssh *ssh, const char *buf, u_int len)
1770 struct session_state *state = ssh->state;
1773 if (state->packet_discard) {
1774 state->keep_alive_timeouts = 0; /* ?? */
1775 if (len >= state->packet_discard) {
1776 if ((r = ssh_packet_stop_discard(ssh)) != 0)
1779 state->packet_discard -= len;
1782 if ((r = sshbuf_put(state->input, buf, len)) != 0)
1788 /* Reads and buffers data from the specified fd */
1790 ssh_packet_process_read(struct ssh *ssh, int fd)
1792 struct session_state *state = ssh->state;
1796 if ((r = sshbuf_read(fd, state->input, PACKET_MAX_SIZE, &rlen)) != 0)
1799 if (state->packet_discard) {
1800 if ((r = sshbuf_consume_end(state->input, rlen)) != 0)
1802 state->keep_alive_timeouts = 0; /* ?? */
1803 if (rlen >= state->packet_discard) {
1804 if ((r = ssh_packet_stop_discard(ssh)) != 0)
1807 state->packet_discard -= rlen;
1814 ssh_packet_remaining(struct ssh *ssh)
1816 return sshbuf_len(ssh->state->incoming_packet);
1820 * Sends a diagnostic message from the server to the client. This message
1821 * can be sent at any time (but not while constructing another message). The
1822 * message is printed immediately, but only if the client is being executed
1823 * in verbose mode. These messages are primarily intended to ease debugging
1824 * authentication problems. The length of the formatted message must not
1825 * exceed 1024 bytes. This will automatically call ssh_packet_write_wait.
1828 ssh_packet_send_debug(struct ssh *ssh, const char *fmt,...)
1834 if ((ssh->compat & SSH_BUG_DEBUG))
1837 va_start(args, fmt);
1838 vsnprintf(buf, sizeof(buf), fmt, args);
1841 debug3("sending debug message: %s", buf);
1843 if ((r = sshpkt_start(ssh, SSH2_MSG_DEBUG)) != 0 ||
1844 (r = sshpkt_put_u8(ssh, 0)) != 0 || /* always display */
1845 (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
1846 (r = sshpkt_put_cstring(ssh, "")) != 0 ||
1847 (r = sshpkt_send(ssh)) != 0 ||
1848 (r = ssh_packet_write_wait(ssh)) != 0)
1849 fatal_fr(r, "send DEBUG");
1853 sshpkt_fmt_connection_id(struct ssh *ssh, char *s, size_t l)
1855 snprintf(s, l, "%.200s%s%s port %d",
1856 ssh->log_preamble ? ssh->log_preamble : "",
1857 ssh->log_preamble ? " " : "",
1858 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
1862 * Pretty-print connection-terminating errors and exit.
1865 sshpkt_vfatal(struct ssh *ssh, int r, const char *fmt, va_list ap)
1867 char *tag = NULL, remote_id[512];
1870 sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id));
1873 case SSH_ERR_CONN_CLOSED:
1874 ssh_packet_clear_keys(ssh);
1875 logdie("Connection closed by %s", remote_id);
1876 case SSH_ERR_CONN_TIMEOUT:
1877 ssh_packet_clear_keys(ssh);
1878 logdie("Connection %s %s timed out",
1879 ssh->state->server_side ? "from" : "to", remote_id);
1880 case SSH_ERR_DISCONNECTED:
1881 ssh_packet_clear_keys(ssh);
1882 logdie("Disconnected from %s", remote_id);
1883 case SSH_ERR_SYSTEM_ERROR:
1884 if (errno == ECONNRESET) {
1885 ssh_packet_clear_keys(ssh);
1886 logdie("Connection reset by %s", remote_id);
1889 case SSH_ERR_NO_CIPHER_ALG_MATCH:
1890 case SSH_ERR_NO_MAC_ALG_MATCH:
1891 case SSH_ERR_NO_COMPRESS_ALG_MATCH:
1892 case SSH_ERR_NO_KEX_ALG_MATCH:
1893 case SSH_ERR_NO_HOSTKEY_ALG_MATCH:
1894 if (ssh->kex && ssh->kex->failed_choice) {
1895 BLACKLIST_NOTIFY(ssh, BLACKLIST_AUTH_FAIL, "ssh");
1896 ssh_packet_clear_keys(ssh);
1898 logdie("Unable to negotiate with %s: %s. "
1899 "Their offer: %s", remote_id, ssh_err(r),
1900 ssh->kex->failed_choice);
1904 if (vasprintf(&tag, fmt, ap) == -1) {
1905 ssh_packet_clear_keys(ssh);
1906 logdie_f("could not allocate failure message");
1908 ssh_packet_clear_keys(ssh);
1910 logdie_r(r, "%s%sConnection %s %s",
1911 tag != NULL ? tag : "", tag != NULL ? ": " : "",
1912 ssh->state->server_side ? "from" : "to", remote_id);
1917 sshpkt_fatal(struct ssh *ssh, int r, const char *fmt, ...)
1922 sshpkt_vfatal(ssh, r, fmt, ap);
1925 logdie_f("should have exited");
1929 * Logs the error plus constructs and sends a disconnect packet, closes the
1930 * connection, and exits. This function never returns. The error message
1931 * should not contain a newline. The length of the formatted message must
1932 * not exceed 1024 bytes.
1935 ssh_packet_disconnect(struct ssh *ssh, const char *fmt,...)
1937 char buf[1024], remote_id[512];
1939 static int disconnecting = 0;
1942 if (disconnecting) /* Guard against recursive invocations. */
1943 fatal("packet_disconnect called recursively.");
1947 * Format the message. Note that the caller must make sure the
1948 * message is of limited size.
1950 sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id));
1951 va_start(args, fmt);
1952 vsnprintf(buf, sizeof(buf), fmt, args);
1955 /* Display the error locally */
1956 logit("Disconnecting %s: %.100s", remote_id, buf);
1959 * Send the disconnect message to the other side, and wait
1960 * for it to get sent.
1962 if ((r = sshpkt_disconnect(ssh, "%s", buf)) != 0)
1963 sshpkt_fatal(ssh, r, "%s", __func__);
1965 if ((r = ssh_packet_write_wait(ssh)) != 0)
1966 sshpkt_fatal(ssh, r, "%s", __func__);
1968 /* Close the connection. */
1969 ssh_packet_close(ssh);
1974 * Checks if there is any buffered output, and tries to write some of
1978 ssh_packet_write_poll(struct ssh *ssh)
1980 struct session_state *state = ssh->state;
1981 int len = sshbuf_len(state->output);
1985 len = write(state->connection_out,
1986 sshbuf_ptr(state->output), len);
1988 if (errno == EINTR || errno == EAGAIN ||
1989 errno == EWOULDBLOCK)
1991 return SSH_ERR_SYSTEM_ERROR;
1994 return SSH_ERR_CONN_CLOSED;
1995 if ((r = sshbuf_consume(state->output, len)) != 0)
2002 * Calls packet_write_poll repeatedly until all pending output data has been
2006 ssh_packet_write_wait(struct ssh *ssh)
2008 int ret, r, ms_remain = 0;
2009 struct timeval start;
2010 struct timespec timespec, *timespecp = NULL;
2011 struct session_state *state = ssh->state;
2014 if ((r = ssh_packet_write_poll(ssh)) != 0)
2016 while (ssh_packet_have_data_to_write(ssh)) {
2017 pfd.fd = state->connection_out;
2018 pfd.events = POLLOUT;
2020 if (state->packet_timeout_ms > 0) {
2021 ms_remain = state->packet_timeout_ms;
2022 timespecp = ×pec;
2025 if (state->packet_timeout_ms > 0) {
2026 ms_to_timespec(×pec, ms_remain);
2027 monotime_tv(&start);
2029 if ((ret = ppoll(&pfd, 1, timespecp, NULL)) >= 0)
2031 if (errno != EAGAIN && errno != EINTR &&
2032 errno != EWOULDBLOCK)
2034 if (state->packet_timeout_ms <= 0)
2036 ms_subtract_diff(&start, &ms_remain);
2037 if (ms_remain <= 0) {
2043 return SSH_ERR_CONN_TIMEOUT;
2044 if ((r = ssh_packet_write_poll(ssh)) != 0)
2050 /* Returns true if there is buffered data to write to the connection. */
2053 ssh_packet_have_data_to_write(struct ssh *ssh)
2055 return sshbuf_len(ssh->state->output) != 0;
2058 /* Returns true if there is not too much data to write to the connection. */
2061 ssh_packet_not_very_much_data_to_write(struct ssh *ssh)
2063 if (ssh->state->interactive_mode)
2064 return sshbuf_len(ssh->state->output) < 16384;
2066 return sshbuf_len(ssh->state->output) < 128 * 1024;
2070 ssh_packet_set_tos(struct ssh *ssh, int tos)
2072 if (!ssh_packet_connection_is_on_socket(ssh) || tos == INT_MAX)
2074 set_sock_tos(ssh->state->connection_in, tos);
2077 /* Informs that the current session is interactive. Sets IP flags for that. */
2080 ssh_packet_set_interactive(struct ssh *ssh, int interactive, int qos_interactive, int qos_bulk)
2082 struct session_state *state = ssh->state;
2084 if (state->set_interactive_called)
2086 state->set_interactive_called = 1;
2088 /* Record that we are in interactive mode. */
2089 state->interactive_mode = interactive;
2091 /* Only set socket options if using a socket. */
2092 if (!ssh_packet_connection_is_on_socket(ssh))
2094 set_nodelay(state->connection_in);
2095 ssh_packet_set_tos(ssh, interactive ? qos_interactive : qos_bulk);
2098 /* Returns true if the current connection is interactive. */
2101 ssh_packet_is_interactive(struct ssh *ssh)
2103 return ssh->state->interactive_mode;
2107 ssh_packet_set_maxsize(struct ssh *ssh, u_int s)
2109 struct session_state *state = ssh->state;
2111 if (state->set_maxsize_called) {
2112 logit_f("called twice: old %d new %d",
2113 state->max_packet_size, s);
2116 if (s < 4 * 1024 || s > 1024 * 1024) {
2117 logit_f("bad size %d", s);
2120 state->set_maxsize_called = 1;
2121 debug_f("setting to %d", s);
2122 state->max_packet_size = s;
2127 ssh_packet_inc_alive_timeouts(struct ssh *ssh)
2129 return ++ssh->state->keep_alive_timeouts;
2133 ssh_packet_set_alive_timeouts(struct ssh *ssh, int ka)
2135 ssh->state->keep_alive_timeouts = ka;
2139 ssh_packet_get_maxsize(struct ssh *ssh)
2141 return ssh->state->max_packet_size;
2145 ssh_packet_set_rekey_limits(struct ssh *ssh, u_int64_t bytes, u_int32_t seconds)
2147 debug3("rekey after %llu bytes, %u seconds", (unsigned long long)bytes,
2148 (unsigned int)seconds);
2149 ssh->state->rekey_limit = bytes;
2150 ssh->state->rekey_interval = seconds;
2154 ssh_packet_get_rekey_timeout(struct ssh *ssh)
2158 seconds = ssh->state->rekey_time + ssh->state->rekey_interval -
2160 return (seconds <= 0 ? 1 : seconds);
2164 ssh_packet_set_server(struct ssh *ssh)
2166 ssh->state->server_side = 1;
2167 ssh->kex->server = 1; /* XXX unify? */
2171 ssh_packet_set_authenticated(struct ssh *ssh)
2173 ssh->state->after_authentication = 1;
2177 ssh_packet_get_input(struct ssh *ssh)
2179 return (void *)ssh->state->input;
2183 ssh_packet_get_output(struct ssh *ssh)
2185 return (void *)ssh->state->output;
2188 /* Reset after_authentication and reset compression in post-auth privsep */
2190 ssh_packet_set_postauth(struct ssh *ssh)
2195 /* This was set in net child, but is not visible in user child */
2196 ssh->state->after_authentication = 1;
2197 ssh->state->rekeying = 0;
2198 if ((r = ssh_packet_enable_delayed_compress(ssh)) != 0)
2203 /* Packet state (de-)serialization for privsep */
2205 /* turn kex into a blob for packet state serialization */
2207 kex_to_blob(struct sshbuf *m, struct kex *kex)
2211 if ((r = sshbuf_put_u32(m, kex->we_need)) != 0 ||
2212 (r = sshbuf_put_cstring(m, kex->hostkey_alg)) != 0 ||
2213 (r = sshbuf_put_u32(m, kex->hostkey_type)) != 0 ||
2214 (r = sshbuf_put_u32(m, kex->hostkey_nid)) != 0 ||
2215 (r = sshbuf_put_u32(m, kex->kex_type)) != 0 ||
2216 (r = sshbuf_put_stringb(m, kex->my)) != 0 ||
2217 (r = sshbuf_put_stringb(m, kex->peer)) != 0 ||
2218 (r = sshbuf_put_stringb(m, kex->client_version)) != 0 ||
2219 (r = sshbuf_put_stringb(m, kex->server_version)) != 0 ||
2220 (r = sshbuf_put_stringb(m, kex->session_id)) != 0 ||
2221 (r = sshbuf_put_u32(m, kex->flags)) != 0)
2226 /* turn key exchange results into a blob for packet state serialization */
2228 newkeys_to_blob(struct sshbuf *m, struct ssh *ssh, int mode)
2231 struct sshcipher_ctx *cc;
2232 struct sshcomp *comp;
2235 struct newkeys *newkey;
2238 if ((newkey = ssh->state->newkeys[mode]) == NULL)
2239 return SSH_ERR_INTERNAL_ERROR;
2242 comp = &newkey->comp;
2243 cc = (mode == MODE_OUT) ? ssh->state->send_context :
2244 ssh->state->receive_context;
2245 if ((r = cipher_get_keyiv(cc, enc->iv, enc->iv_len)) != 0)
2247 if ((b = sshbuf_new()) == NULL)
2248 return SSH_ERR_ALLOC_FAIL;
2249 if ((r = sshbuf_put_cstring(b, enc->name)) != 0 ||
2250 (r = sshbuf_put_u32(b, enc->enabled)) != 0 ||
2251 (r = sshbuf_put_u32(b, enc->block_size)) != 0 ||
2252 (r = sshbuf_put_string(b, enc->key, enc->key_len)) != 0 ||
2253 (r = sshbuf_put_string(b, enc->iv, enc->iv_len)) != 0)
2255 if (cipher_authlen(enc->cipher) == 0) {
2256 if ((r = sshbuf_put_cstring(b, mac->name)) != 0 ||
2257 (r = sshbuf_put_u32(b, mac->enabled)) != 0 ||
2258 (r = sshbuf_put_string(b, mac->key, mac->key_len)) != 0)
2261 if ((r = sshbuf_put_u32(b, comp->type)) != 0 ||
2262 (r = sshbuf_put_cstring(b, comp->name)) != 0)
2264 r = sshbuf_put_stringb(m, b);
2270 /* serialize packet state into a blob */
2272 ssh_packet_get_state(struct ssh *ssh, struct sshbuf *m)
2274 struct session_state *state = ssh->state;
2277 if ((r = kex_to_blob(m, ssh->kex)) != 0 ||
2278 (r = newkeys_to_blob(m, ssh, MODE_OUT)) != 0 ||
2279 (r = newkeys_to_blob(m, ssh, MODE_IN)) != 0 ||
2280 (r = sshbuf_put_u64(m, state->rekey_limit)) != 0 ||
2281 (r = sshbuf_put_u32(m, state->rekey_interval)) != 0 ||
2282 (r = sshbuf_put_u32(m, state->p_send.seqnr)) != 0 ||
2283 (r = sshbuf_put_u64(m, state->p_send.blocks)) != 0 ||
2284 (r = sshbuf_put_u32(m, state->p_send.packets)) != 0 ||
2285 (r = sshbuf_put_u64(m, state->p_send.bytes)) != 0 ||
2286 (r = sshbuf_put_u32(m, state->p_read.seqnr)) != 0 ||
2287 (r = sshbuf_put_u64(m, state->p_read.blocks)) != 0 ||
2288 (r = sshbuf_put_u32(m, state->p_read.packets)) != 0 ||
2289 (r = sshbuf_put_u64(m, state->p_read.bytes)) != 0 ||
2290 (r = sshbuf_put_stringb(m, state->input)) != 0 ||
2291 (r = sshbuf_put_stringb(m, state->output)) != 0)
2297 /* restore key exchange results from blob for packet state de-serialization */
2299 newkeys_from_blob(struct sshbuf *m, struct ssh *ssh, int mode)
2301 struct sshbuf *b = NULL;
2302 struct sshcomp *comp;
2305 struct newkeys *newkey = NULL;
2306 size_t keylen, ivlen, maclen;
2309 if ((newkey = calloc(1, sizeof(*newkey))) == NULL) {
2310 r = SSH_ERR_ALLOC_FAIL;
2313 if ((r = sshbuf_froms(m, &b)) != 0)
2316 sshbuf_dump(b, stderr);
2320 comp = &newkey->comp;
2322 if ((r = sshbuf_get_cstring(b, &enc->name, NULL)) != 0 ||
2323 (r = sshbuf_get_u32(b, (u_int *)&enc->enabled)) != 0 ||
2324 (r = sshbuf_get_u32(b, &enc->block_size)) != 0 ||
2325 (r = sshbuf_get_string(b, &enc->key, &keylen)) != 0 ||
2326 (r = sshbuf_get_string(b, &enc->iv, &ivlen)) != 0)
2328 if ((enc->cipher = cipher_by_name(enc->name)) == NULL) {
2329 r = SSH_ERR_INVALID_FORMAT;
2332 if (cipher_authlen(enc->cipher) == 0) {
2333 if ((r = sshbuf_get_cstring(b, &mac->name, NULL)) != 0)
2335 if ((r = mac_setup(mac, mac->name)) != 0)
2337 if ((r = sshbuf_get_u32(b, (u_int *)&mac->enabled)) != 0 ||
2338 (r = sshbuf_get_string(b, &mac->key, &maclen)) != 0)
2340 if (maclen > mac->key_len) {
2341 r = SSH_ERR_INVALID_FORMAT;
2344 mac->key_len = maclen;
2346 if ((r = sshbuf_get_u32(b, &comp->type)) != 0 ||
2347 (r = sshbuf_get_cstring(b, &comp->name, NULL)) != 0)
2349 if (sshbuf_len(b) != 0) {
2350 r = SSH_ERR_INVALID_FORMAT;
2353 enc->key_len = keylen;
2354 enc->iv_len = ivlen;
2355 ssh->kex->newkeys[mode] = newkey;
2364 /* restore kex from blob for packet state de-serialization */
2366 kex_from_blob(struct sshbuf *m, struct kex **kexp)
2371 if ((kex = kex_new()) == NULL)
2372 return SSH_ERR_ALLOC_FAIL;
2373 if ((r = sshbuf_get_u32(m, &kex->we_need)) != 0 ||
2374 (r = sshbuf_get_cstring(m, &kex->hostkey_alg, NULL)) != 0 ||
2375 (r = sshbuf_get_u32(m, (u_int *)&kex->hostkey_type)) != 0 ||
2376 (r = sshbuf_get_u32(m, (u_int *)&kex->hostkey_nid)) != 0 ||
2377 (r = sshbuf_get_u32(m, &kex->kex_type)) != 0 ||
2378 (r = sshbuf_get_stringb(m, kex->my)) != 0 ||
2379 (r = sshbuf_get_stringb(m, kex->peer)) != 0 ||
2380 (r = sshbuf_get_stringb(m, kex->client_version)) != 0 ||
2381 (r = sshbuf_get_stringb(m, kex->server_version)) != 0 ||
2382 (r = sshbuf_get_stringb(m, kex->session_id)) != 0 ||
2383 (r = sshbuf_get_u32(m, &kex->flags)) != 0)
2389 if (r != 0 || kexp == NULL) {
2401 * Restore packet state from content of blob 'm' (de-serialization).
2402 * Note that 'm' will be partially consumed on parsing or any other errors.
2405 ssh_packet_set_state(struct ssh *ssh, struct sshbuf *m)
2407 struct session_state *state = ssh->state;
2408 const u_char *input, *output;
2412 if ((r = kex_from_blob(m, &ssh->kex)) != 0 ||
2413 (r = newkeys_from_blob(m, ssh, MODE_OUT)) != 0 ||
2414 (r = newkeys_from_blob(m, ssh, MODE_IN)) != 0 ||
2415 (r = sshbuf_get_u64(m, &state->rekey_limit)) != 0 ||
2416 (r = sshbuf_get_u32(m, &state->rekey_interval)) != 0 ||
2417 (r = sshbuf_get_u32(m, &state->p_send.seqnr)) != 0 ||
2418 (r = sshbuf_get_u64(m, &state->p_send.blocks)) != 0 ||
2419 (r = sshbuf_get_u32(m, &state->p_send.packets)) != 0 ||
2420 (r = sshbuf_get_u64(m, &state->p_send.bytes)) != 0 ||
2421 (r = sshbuf_get_u32(m, &state->p_read.seqnr)) != 0 ||
2422 (r = sshbuf_get_u64(m, &state->p_read.blocks)) != 0 ||
2423 (r = sshbuf_get_u32(m, &state->p_read.packets)) != 0 ||
2424 (r = sshbuf_get_u64(m, &state->p_read.bytes)) != 0)
2427 * We set the time here so that in post-auth privsep child we
2428 * count from the completion of the authentication.
2430 state->rekey_time = monotime();
2431 /* XXX ssh_set_newkeys overrides p_read.packets? XXX */
2432 if ((r = ssh_set_newkeys(ssh, MODE_IN)) != 0 ||
2433 (r = ssh_set_newkeys(ssh, MODE_OUT)) != 0)
2436 if ((r = ssh_packet_set_postauth(ssh)) != 0)
2439 sshbuf_reset(state->input);
2440 sshbuf_reset(state->output);
2441 if ((r = sshbuf_get_string_direct(m, &input, &ilen)) != 0 ||
2442 (r = sshbuf_get_string_direct(m, &output, &olen)) != 0 ||
2443 (r = sshbuf_put(state->input, input, ilen)) != 0 ||
2444 (r = sshbuf_put(state->output, output, olen)) != 0)
2448 return SSH_ERR_INVALID_FORMAT;
2455 /* put data to the outgoing packet */
2458 sshpkt_put(struct ssh *ssh, const void *v, size_t len)
2460 return sshbuf_put(ssh->state->outgoing_packet, v, len);
2464 sshpkt_putb(struct ssh *ssh, const struct sshbuf *b)
2466 return sshbuf_putb(ssh->state->outgoing_packet, b);
2470 sshpkt_put_u8(struct ssh *ssh, u_char val)
2472 return sshbuf_put_u8(ssh->state->outgoing_packet, val);
2476 sshpkt_put_u32(struct ssh *ssh, u_int32_t val)
2478 return sshbuf_put_u32(ssh->state->outgoing_packet, val);
2482 sshpkt_put_u64(struct ssh *ssh, u_int64_t val)
2484 return sshbuf_put_u64(ssh->state->outgoing_packet, val);
2488 sshpkt_put_string(struct ssh *ssh, const void *v, size_t len)
2490 return sshbuf_put_string(ssh->state->outgoing_packet, v, len);
2494 sshpkt_put_cstring(struct ssh *ssh, const void *v)
2496 return sshbuf_put_cstring(ssh->state->outgoing_packet, v);
2500 sshpkt_put_stringb(struct ssh *ssh, const struct sshbuf *v)
2502 return sshbuf_put_stringb(ssh->state->outgoing_packet, v);
2506 sshpkt_getb_froms(struct ssh *ssh, struct sshbuf **valp)
2508 return sshbuf_froms(ssh->state->incoming_packet, valp);
2512 #ifdef OPENSSL_HAS_ECC
2514 sshpkt_put_ec(struct ssh *ssh, const EC_POINT *v, const EC_GROUP *g)
2516 return sshbuf_put_ec(ssh->state->outgoing_packet, v, g);
2518 #endif /* OPENSSL_HAS_ECC */
2522 sshpkt_put_bignum2(struct ssh *ssh, const BIGNUM *v)
2524 return sshbuf_put_bignum2(ssh->state->outgoing_packet, v);
2526 #endif /* WITH_OPENSSL */
2528 /* fetch data from the incoming packet */
2531 sshpkt_get(struct ssh *ssh, void *valp, size_t len)
2533 return sshbuf_get(ssh->state->incoming_packet, valp, len);
2537 sshpkt_get_u8(struct ssh *ssh, u_char *valp)
2539 return sshbuf_get_u8(ssh->state->incoming_packet, valp);
2543 sshpkt_get_u32(struct ssh *ssh, u_int32_t *valp)
2545 return sshbuf_get_u32(ssh->state->incoming_packet, valp);
2549 sshpkt_get_u64(struct ssh *ssh, u_int64_t *valp)
2551 return sshbuf_get_u64(ssh->state->incoming_packet, valp);
2555 sshpkt_get_string(struct ssh *ssh, u_char **valp, size_t *lenp)
2557 return sshbuf_get_string(ssh->state->incoming_packet, valp, lenp);
2561 sshpkt_get_string_direct(struct ssh *ssh, const u_char **valp, size_t *lenp)
2563 return sshbuf_get_string_direct(ssh->state->incoming_packet, valp, lenp);
2567 sshpkt_peek_string_direct(struct ssh *ssh, const u_char **valp, size_t *lenp)
2569 return sshbuf_peek_string_direct(ssh->state->incoming_packet, valp, lenp);
2573 sshpkt_get_cstring(struct ssh *ssh, char **valp, size_t *lenp)
2575 return sshbuf_get_cstring(ssh->state->incoming_packet, valp, lenp);
2579 #ifdef OPENSSL_HAS_ECC
2581 sshpkt_get_ec(struct ssh *ssh, EC_POINT *v, const EC_GROUP *g)
2583 return sshbuf_get_ec(ssh->state->incoming_packet, v, g);
2585 #endif /* OPENSSL_HAS_ECC */
2588 sshpkt_get_bignum2(struct ssh *ssh, BIGNUM **valp)
2590 return sshbuf_get_bignum2(ssh->state->incoming_packet, valp);
2592 #endif /* WITH_OPENSSL */
2595 sshpkt_get_end(struct ssh *ssh)
2597 if (sshbuf_len(ssh->state->incoming_packet) > 0)
2598 return SSH_ERR_UNEXPECTED_TRAILING_DATA;
2603 sshpkt_ptr(struct ssh *ssh, size_t *lenp)
2606 *lenp = sshbuf_len(ssh->state->incoming_packet);
2607 return sshbuf_ptr(ssh->state->incoming_packet);
2610 /* start a new packet */
2613 sshpkt_start(struct ssh *ssh, u_char type)
2615 u_char buf[6]; /* u32 packet length, u8 pad len, u8 type */
2617 DBG(debug("packet_start[%d]", type));
2618 memset(buf, 0, sizeof(buf));
2619 buf[sizeof(buf) - 1] = type;
2620 sshbuf_reset(ssh->state->outgoing_packet);
2621 return sshbuf_put(ssh->state->outgoing_packet, buf, sizeof(buf));
2625 ssh_packet_send_mux(struct ssh *ssh)
2627 struct session_state *state = ssh->state;
2633 return SSH_ERR_INTERNAL_ERROR;
2634 len = sshbuf_len(state->outgoing_packet);
2636 return SSH_ERR_INTERNAL_ERROR;
2637 cp = sshbuf_mutable_ptr(state->outgoing_packet);
2639 if (ssh_packet_log_type(type))
2640 debug3_f("type %u", type);
2641 /* drop everything, but the connection protocol */
2642 if (type >= SSH2_MSG_CONNECTION_MIN &&
2643 type <= SSH2_MSG_CONNECTION_MAX) {
2644 POKE_U32(cp, len - 4);
2645 if ((r = sshbuf_putb(state->output,
2646 state->outgoing_packet)) != 0)
2648 /* sshbuf_dump(state->output, stderr); */
2650 sshbuf_reset(state->outgoing_packet);
2655 * 9.2. Ignored Data Message
2657 * byte SSH_MSG_IGNORE
2660 * All implementations MUST understand (and ignore) this message at any
2661 * time (after receiving the protocol version). No implementation is
2662 * required to send them. This message can be used as an additional
2663 * protection measure against advanced traffic analysis techniques.
2666 sshpkt_msg_ignore(struct ssh *ssh, u_int nbytes)
2672 if ((r = sshpkt_start(ssh, SSH2_MSG_IGNORE)) != 0 ||
2673 (r = sshpkt_put_u32(ssh, nbytes)) != 0)
2675 for (i = 0; i < nbytes; i++) {
2678 if ((r = sshpkt_put_u8(ssh, (u_char)rnd & 0xff)) != 0)
2688 sshpkt_send(struct ssh *ssh)
2690 if (ssh->state && ssh->state->mux)
2691 return ssh_packet_send_mux(ssh);
2692 return ssh_packet_send2(ssh);
2696 sshpkt_disconnect(struct ssh *ssh, const char *fmt,...)
2702 va_start(args, fmt);
2703 vsnprintf(buf, sizeof(buf), fmt, args);
2706 if ((r = sshpkt_start(ssh, SSH2_MSG_DISCONNECT)) != 0 ||
2707 (r = sshpkt_put_u32(ssh, SSH2_DISCONNECT_PROTOCOL_ERROR)) != 0 ||
2708 (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
2709 (r = sshpkt_put_cstring(ssh, "")) != 0 ||
2710 (r = sshpkt_send(ssh)) != 0)
2715 /* roundup current message to pad bytes */
2717 sshpkt_add_padding(struct ssh *ssh, u_char pad)
2719 ssh->state->extra_pad = pad;