1 /* $OpenBSD: packet.c,v 1.301 2021/07/16 09:00:23 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.
43 #include <sys/types.h>
44 #include "openbsd-compat/sys-queue.h"
45 #include <sys/socket.h>
46 #ifdef HAVE_SYS_TIME_H
47 # include <sys/time.h>
50 #include <netinet/in.h>
51 #include <netinet/ip.h>
52 #include <arpa/inet.h>
69 * Explicitly include OpenSSL before zlib as some versions of OpenSSL have
70 * "free_func" in their headers, which zlib typedefs.
73 # include <openssl/bn.h>
74 # include <openssl/evp.h>
75 # ifdef OPENSSL_HAS_ECC
76 # include <openssl/ec.h>
100 #include "blacklist_client.h"
108 #define PACKET_MAX_SIZE (256 * 1024)
110 struct packet_state {
118 TAILQ_ENTRY(packet) next;
120 struct sshbuf *payload;
123 struct session_state {
125 * This variable contains the file descriptors used for
126 * communicating with the other side. connection_in is used for
127 * reading; connection_out for writing. These can be the same
128 * descriptor, in which case it is assumed to be a socket.
133 /* Protocol flags for the remote side. */
134 u_int remote_protocol_flags;
136 /* Encryption context for receiving data. Only used for decryption. */
137 struct sshcipher_ctx *receive_context;
139 /* Encryption context for sending data. Only used for encryption. */
140 struct sshcipher_ctx *send_context;
142 /* Buffer for raw input data from the socket. */
143 struct sshbuf *input;
145 /* Buffer for raw output data going to the socket. */
146 struct sshbuf *output;
148 /* Buffer for the partial outgoing packet being constructed. */
149 struct sshbuf *outgoing_packet;
151 /* Buffer for the incoming packet currently being processed. */
152 struct sshbuf *incoming_packet;
154 /* Scratch buffer for packet compression/decompression. */
155 struct sshbuf *compression_buffer;
158 /* Incoming/outgoing compression dictionaries */
159 z_stream compression_in_stream;
160 z_stream compression_out_stream;
162 int compression_in_started;
163 int compression_out_started;
164 int compression_in_failures;
165 int compression_out_failures;
167 /* default maximum packet size */
168 u_int max_packet_size;
170 /* Flag indicating whether this module has been initialized. */
173 /* Set to true if the connection is interactive. */
174 int interactive_mode;
176 /* Set to true if we are the server side. */
179 /* Set to true if we are authenticated. */
180 int after_authentication;
182 int keep_alive_timeouts;
184 /* The maximum time that we will wait to send or receive a packet */
185 int packet_timeout_ms;
187 /* Session key information for Encryption and MAC */
188 struct newkeys *newkeys[MODE_MAX];
189 struct packet_state p_read, p_send;
191 /* Volume-based rekeying */
192 u_int64_t max_blocks_in, max_blocks_out, rekey_limit;
194 /* Time-based rekeying */
195 u_int32_t rekey_interval; /* how often in seconds */
196 time_t rekey_time; /* time of last rekeying */
198 /* roundup current message to extra_pad bytes */
201 /* XXX discard incoming data after MAC error */
202 u_int packet_discard;
203 size_t packet_discard_mac_already;
204 struct sshmac *packet_discard_mac;
206 /* Used in packet_read_poll2() */
209 /* Used in packet_send2 */
212 /* Used in ssh_packet_send_mux() */
215 /* Used in packet_set_interactive */
216 int set_interactive_called;
218 /* Used in packet_set_maxsize */
219 int set_maxsize_called;
221 /* One-off warning about weak ciphers */
222 int cipher_warning_done;
224 /* Hook for fuzzing inbound packets */
225 ssh_packet_hook_fn *hook_in;
228 TAILQ_HEAD(, packet) outgoing;
232 ssh_alloc_session_state(void)
234 struct ssh *ssh = NULL;
235 struct session_state *state = NULL;
237 if ((ssh = calloc(1, sizeof(*ssh))) == NULL ||
238 (state = calloc(1, sizeof(*state))) == NULL ||
239 (ssh->kex = kex_new()) == NULL ||
240 (state->input = sshbuf_new()) == NULL ||
241 (state->output = sshbuf_new()) == NULL ||
242 (state->outgoing_packet = sshbuf_new()) == NULL ||
243 (state->incoming_packet = sshbuf_new()) == NULL)
245 TAILQ_INIT(&state->outgoing);
246 TAILQ_INIT(&ssh->private_keys);
247 TAILQ_INIT(&ssh->public_keys);
248 state->connection_in = -1;
249 state->connection_out = -1;
250 state->max_packet_size = 32768;
251 state->packet_timeout_ms = -1;
252 state->p_send.packets = state->p_read.packets = 0;
253 state->initialized = 1;
255 * ssh_packet_send2() needs to queue packets until
256 * we've done the initial key exchange.
267 sshbuf_free(state->input);
268 sshbuf_free(state->output);
269 sshbuf_free(state->incoming_packet);
270 sshbuf_free(state->outgoing_packet);
277 ssh_packet_set_input_hook(struct ssh *ssh, ssh_packet_hook_fn *hook, void *ctx)
279 ssh->state->hook_in = hook;
280 ssh->state->hook_in_ctx = ctx;
283 /* Returns nonzero if rekeying is in progress */
285 ssh_packet_is_rekeying(struct ssh *ssh)
287 return ssh->state->rekeying ||
288 (ssh->kex != NULL && ssh->kex->done == 0);
292 * Sets the descriptors used for communication.
295 ssh_packet_set_connection(struct ssh *ssh, int fd_in, int fd_out)
297 struct session_state *state;
298 const struct sshcipher *none = cipher_by_name("none");
302 error_f("cannot load cipher 'none'");
306 ssh = ssh_alloc_session_state();
308 error_f("could not allocate state");
312 state->connection_in = fd_in;
313 state->connection_out = fd_out;
314 if ((r = cipher_init(&state->send_context, none,
315 (const u_char *)"", 0, NULL, 0, CIPHER_ENCRYPT)) != 0 ||
316 (r = cipher_init(&state->receive_context, none,
317 (const u_char *)"", 0, NULL, 0, CIPHER_DECRYPT)) != 0) {
318 error_fr(r, "cipher_init failed");
319 free(ssh); /* XXX need ssh_free_session_state? */
322 state->newkeys[MODE_IN] = state->newkeys[MODE_OUT] = NULL;
324 * Cache the IP address of the remote connection for use in error
325 * messages that might be generated after the connection has closed.
327 (void)ssh_remote_ipaddr(ssh);
332 ssh_packet_set_timeout(struct ssh *ssh, int timeout, int count)
334 struct session_state *state = ssh->state;
336 if (timeout <= 0 || count <= 0) {
337 state->packet_timeout_ms = -1;
340 if ((INT_MAX / 1000) / count < timeout)
341 state->packet_timeout_ms = INT_MAX;
343 state->packet_timeout_ms = timeout * count * 1000;
347 ssh_packet_set_mux(struct ssh *ssh)
350 ssh->state->rekeying = 0;
356 ssh_packet_get_mux(struct ssh *ssh)
358 return ssh->state->mux;
362 ssh_packet_set_log_preamble(struct ssh *ssh, const char *fmt, ...)
367 free(ssh->log_preamble);
369 ssh->log_preamble = NULL;
372 r = vasprintf(&ssh->log_preamble, fmt, args);
374 if (r < 0 || ssh->log_preamble == NULL)
375 return SSH_ERR_ALLOC_FAIL;
381 ssh_packet_stop_discard(struct ssh *ssh)
383 struct session_state *state = ssh->state;
386 if (state->packet_discard_mac) {
388 size_t dlen = PACKET_MAX_SIZE;
390 if (dlen > state->packet_discard_mac_already)
391 dlen -= state->packet_discard_mac_already;
392 memset(buf, 'a', sizeof(buf));
393 while (sshbuf_len(state->incoming_packet) < dlen)
394 if ((r = sshbuf_put(state->incoming_packet, buf,
397 (void) mac_compute(state->packet_discard_mac,
399 sshbuf_ptr(state->incoming_packet), dlen,
402 logit("Finished discarding for %.200s port %d",
403 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
404 return SSH_ERR_MAC_INVALID;
408 ssh_packet_start_discard(struct ssh *ssh, struct sshenc *enc,
409 struct sshmac *mac, size_t mac_already, u_int discard)
411 struct session_state *state = ssh->state;
414 if (enc == NULL || !cipher_is_cbc(enc->cipher) || (mac && mac->etm)) {
415 if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0)
417 return SSH_ERR_MAC_INVALID;
420 * Record number of bytes over which the mac has already
421 * been computed in order to minimize timing attacks.
423 if (mac && mac->enabled) {
424 state->packet_discard_mac = mac;
425 state->packet_discard_mac_already = mac_already;
427 if (sshbuf_len(state->input) >= discard)
428 return ssh_packet_stop_discard(ssh);
429 state->packet_discard = discard - sshbuf_len(state->input);
433 /* Returns 1 if remote host is connected via socket, 0 if not. */
436 ssh_packet_connection_is_on_socket(struct ssh *ssh)
438 struct session_state *state;
439 struct sockaddr_storage from, to;
440 socklen_t fromlen, tolen;
442 if (ssh == NULL || ssh->state == NULL)
446 if (state->connection_in == -1 || state->connection_out == -1)
448 /* filedescriptors in and out are the same, so it's a socket */
449 if (state->connection_in == state->connection_out)
451 fromlen = sizeof(from);
452 memset(&from, 0, sizeof(from));
453 if (getpeername(state->connection_in, (struct sockaddr *)&from,
457 memset(&to, 0, sizeof(to));
458 if (getpeername(state->connection_out, (struct sockaddr *)&to,
461 if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
463 if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
469 ssh_packet_get_bytes(struct ssh *ssh, u_int64_t *ibytes, u_int64_t *obytes)
472 *ibytes = ssh->state->p_read.bytes;
474 *obytes = ssh->state->p_send.bytes;
478 ssh_packet_connection_af(struct ssh *ssh)
480 return get_sock_af(ssh->state->connection_out);
483 /* Sets the connection into non-blocking mode. */
486 ssh_packet_set_nonblocking(struct ssh *ssh)
488 /* Set the socket into non-blocking mode. */
489 set_nonblock(ssh->state->connection_in);
491 if (ssh->state->connection_out != ssh->state->connection_in)
492 set_nonblock(ssh->state->connection_out);
495 /* Returns the socket used for reading. */
498 ssh_packet_get_connection_in(struct ssh *ssh)
500 return ssh->state->connection_in;
503 /* Returns the descriptor used for writing. */
506 ssh_packet_get_connection_out(struct ssh *ssh)
508 return ssh->state->connection_out;
512 * Returns the IP-address of the remote host as a string. The returned
513 * string must not be freed.
517 ssh_remote_ipaddr(struct ssh *ssh)
521 /* Check whether we have cached the ipaddr. */
522 if (ssh->remote_ipaddr == NULL) {
523 if (ssh_packet_connection_is_on_socket(ssh)) {
524 sock = ssh->state->connection_in;
525 ssh->remote_ipaddr = get_peer_ipaddr(sock);
526 ssh->remote_port = get_peer_port(sock);
527 ssh->local_ipaddr = get_local_ipaddr(sock);
528 ssh->local_port = get_local_port(sock);
530 ssh->remote_ipaddr = xstrdup("UNKNOWN");
531 ssh->remote_port = 65535;
532 ssh->local_ipaddr = xstrdup("UNKNOWN");
533 ssh->local_port = 65535;
536 return ssh->remote_ipaddr;
539 /* Returns the port number of the remote host. */
542 ssh_remote_port(struct ssh *ssh)
544 (void)ssh_remote_ipaddr(ssh); /* Will lookup and cache. */
545 return ssh->remote_port;
549 * Returns the IP-address of the local host as a string. The returned
550 * string must not be freed.
554 ssh_local_ipaddr(struct ssh *ssh)
556 (void)ssh_remote_ipaddr(ssh); /* Will lookup and cache. */
557 return ssh->local_ipaddr;
560 /* Returns the port number of the local host. */
563 ssh_local_port(struct ssh *ssh)
565 (void)ssh_remote_ipaddr(ssh); /* Will lookup and cache. */
566 return ssh->local_port;
569 /* Returns the routing domain of the input socket, or NULL if unavailable */
571 ssh_packet_rdomain_in(struct ssh *ssh)
573 if (ssh->rdomain_in != NULL)
574 return ssh->rdomain_in;
575 if (!ssh_packet_connection_is_on_socket(ssh))
577 ssh->rdomain_in = get_rdomain(ssh->state->connection_in);
578 return ssh->rdomain_in;
581 /* Closes the connection and clears and frees internal data structures. */
584 ssh_packet_close_internal(struct ssh *ssh, int do_close)
586 struct session_state *state = ssh->state;
589 if (!state->initialized)
591 state->initialized = 0;
593 if (state->connection_in == state->connection_out) {
594 close(state->connection_out);
596 close(state->connection_in);
597 close(state->connection_out);
600 sshbuf_free(state->input);
601 sshbuf_free(state->output);
602 sshbuf_free(state->outgoing_packet);
603 sshbuf_free(state->incoming_packet);
604 for (mode = 0; mode < MODE_MAX; mode++) {
605 kex_free_newkeys(state->newkeys[mode]); /* current keys */
606 state->newkeys[mode] = NULL;
607 ssh_clear_newkeys(ssh, mode); /* next keys */
610 /* compression state is in shared mem, so we can only release it once */
611 if (do_close && state->compression_buffer) {
612 sshbuf_free(state->compression_buffer);
613 if (state->compression_out_started) {
614 z_streamp stream = &state->compression_out_stream;
615 debug("compress outgoing: "
616 "raw data %llu, compressed %llu, factor %.2f",
617 (unsigned long long)stream->total_in,
618 (unsigned long long)stream->total_out,
619 stream->total_in == 0 ? 0.0 :
620 (double) stream->total_out / stream->total_in);
621 if (state->compression_out_failures == 0)
624 if (state->compression_in_started) {
625 z_streamp stream = &state->compression_in_stream;
626 debug("compress incoming: "
627 "raw data %llu, compressed %llu, factor %.2f",
628 (unsigned long long)stream->total_out,
629 (unsigned long long)stream->total_in,
630 stream->total_out == 0 ? 0.0 :
631 (double) stream->total_in / stream->total_out);
632 if (state->compression_in_failures == 0)
636 #endif /* WITH_ZLIB */
637 cipher_free(state->send_context);
638 cipher_free(state->receive_context);
639 state->send_context = state->receive_context = NULL;
641 free(ssh->local_ipaddr);
642 ssh->local_ipaddr = NULL;
643 free(ssh->remote_ipaddr);
644 ssh->remote_ipaddr = NULL;
653 ssh_packet_close(struct ssh *ssh)
655 ssh_packet_close_internal(ssh, 1);
659 ssh_packet_clear_keys(struct ssh *ssh)
661 ssh_packet_close_internal(ssh, 0);
664 /* Sets remote side protocol flags. */
667 ssh_packet_set_protocol_flags(struct ssh *ssh, u_int protocol_flags)
669 ssh->state->remote_protocol_flags = protocol_flags;
672 /* Returns the remote protocol flags set earlier by the above function. */
675 ssh_packet_get_protocol_flags(struct ssh *ssh)
677 return ssh->state->remote_protocol_flags;
681 * Starts packet compression from the next packet on in both directions.
682 * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
686 ssh_packet_init_compression(struct ssh *ssh)
688 if (!ssh->state->compression_buffer &&
689 ((ssh->state->compression_buffer = sshbuf_new()) == NULL))
690 return SSH_ERR_ALLOC_FAIL;
696 start_compression_out(struct ssh *ssh, int level)
698 if (level < 1 || level > 9)
699 return SSH_ERR_INVALID_ARGUMENT;
700 debug("Enabling compression at level %d.", level);
701 if (ssh->state->compression_out_started == 1)
702 deflateEnd(&ssh->state->compression_out_stream);
703 switch (deflateInit(&ssh->state->compression_out_stream, level)) {
705 ssh->state->compression_out_started = 1;
708 return SSH_ERR_ALLOC_FAIL;
710 return SSH_ERR_INTERNAL_ERROR;
716 start_compression_in(struct ssh *ssh)
718 if (ssh->state->compression_in_started == 1)
719 inflateEnd(&ssh->state->compression_in_stream);
720 switch (inflateInit(&ssh->state->compression_in_stream)) {
722 ssh->state->compression_in_started = 1;
725 return SSH_ERR_ALLOC_FAIL;
727 return SSH_ERR_INTERNAL_ERROR;
732 /* XXX remove need for separate compression buffer */
734 compress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
739 if (ssh->state->compression_out_started != 1)
740 return SSH_ERR_INTERNAL_ERROR;
742 /* This case is not handled below. */
743 if (sshbuf_len(in) == 0)
746 /* Input is the contents of the input buffer. */
747 if ((ssh->state->compression_out_stream.next_in =
748 sshbuf_mutable_ptr(in)) == NULL)
749 return SSH_ERR_INTERNAL_ERROR;
750 ssh->state->compression_out_stream.avail_in = sshbuf_len(in);
752 /* Loop compressing until deflate() returns with avail_out != 0. */
754 /* Set up fixed-size output buffer. */
755 ssh->state->compression_out_stream.next_out = buf;
756 ssh->state->compression_out_stream.avail_out = sizeof(buf);
758 /* Compress as much data into the buffer as possible. */
759 status = deflate(&ssh->state->compression_out_stream,
763 return SSH_ERR_ALLOC_FAIL;
765 /* Append compressed data to output_buffer. */
766 if ((r = sshbuf_put(out, buf, sizeof(buf) -
767 ssh->state->compression_out_stream.avail_out)) != 0)
772 ssh->state->compression_out_failures++;
773 return SSH_ERR_INVALID_FORMAT;
775 } while (ssh->state->compression_out_stream.avail_out == 0);
780 uncompress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
785 if (ssh->state->compression_in_started != 1)
786 return SSH_ERR_INTERNAL_ERROR;
788 if ((ssh->state->compression_in_stream.next_in =
789 sshbuf_mutable_ptr(in)) == NULL)
790 return SSH_ERR_INTERNAL_ERROR;
791 ssh->state->compression_in_stream.avail_in = sshbuf_len(in);
794 /* Set up fixed-size output buffer. */
795 ssh->state->compression_in_stream.next_out = buf;
796 ssh->state->compression_in_stream.avail_out = sizeof(buf);
798 status = inflate(&ssh->state->compression_in_stream,
802 if ((r = sshbuf_put(out, buf, sizeof(buf) -
803 ssh->state->compression_in_stream.avail_out)) != 0)
808 * Comments in zlib.h say that we should keep calling
809 * inflate() until we get an error. This appears to
810 * be the error that we get.
814 return SSH_ERR_INVALID_FORMAT;
816 return SSH_ERR_ALLOC_FAIL;
819 ssh->state->compression_in_failures++;
820 return SSH_ERR_INTERNAL_ERROR;
826 #else /* WITH_ZLIB */
829 start_compression_out(struct ssh *ssh, int level)
831 return SSH_ERR_INTERNAL_ERROR;
835 start_compression_in(struct ssh *ssh)
837 return SSH_ERR_INTERNAL_ERROR;
841 compress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
843 return SSH_ERR_INTERNAL_ERROR;
847 uncompress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
849 return SSH_ERR_INTERNAL_ERROR;
851 #endif /* WITH_ZLIB */
854 ssh_clear_newkeys(struct ssh *ssh, int mode)
856 if (ssh->kex && ssh->kex->newkeys[mode]) {
857 kex_free_newkeys(ssh->kex->newkeys[mode]);
858 ssh->kex->newkeys[mode] = NULL;
863 ssh_set_newkeys(struct ssh *ssh, int mode)
865 struct session_state *state = ssh->state;
868 struct sshcomp *comp;
869 struct sshcipher_ctx **ccp;
870 struct packet_state *ps;
871 u_int64_t *max_blocks;
874 const char *dir = mode == MODE_OUT ? "out" : "in";
876 debug2("set_newkeys: mode %d", mode);
878 if (mode == MODE_OUT) {
879 ccp = &state->send_context;
880 crypt_type = CIPHER_ENCRYPT;
882 max_blocks = &state->max_blocks_out;
884 ccp = &state->receive_context;
885 crypt_type = CIPHER_DECRYPT;
887 max_blocks = &state->max_blocks_in;
889 if (state->newkeys[mode] != NULL) {
890 debug_f("rekeying %s, input %llu bytes %llu blocks, "
891 "output %llu bytes %llu blocks", dir,
892 (unsigned long long)state->p_read.bytes,
893 (unsigned long long)state->p_read.blocks,
894 (unsigned long long)state->p_send.bytes,
895 (unsigned long long)state->p_send.blocks);
896 kex_free_newkeys(state->newkeys[mode]);
897 state->newkeys[mode] = NULL;
899 /* note that both bytes and the seqnr are not reset */
900 ps->packets = ps->blocks = 0;
901 /* move newkeys from kex to state */
902 if ((state->newkeys[mode] = ssh->kex->newkeys[mode]) == NULL)
903 return SSH_ERR_INTERNAL_ERROR;
904 ssh->kex->newkeys[mode] = NULL;
905 enc = &state->newkeys[mode]->enc;
906 mac = &state->newkeys[mode]->mac;
907 comp = &state->newkeys[mode]->comp;
908 if (cipher_authlen(enc->cipher) == 0) {
909 if ((r = mac_init(mac)) != 0)
913 DBG(debug_f("cipher_init_context: %s", dir));
916 if ((r = cipher_init(ccp, enc->cipher, enc->key, enc->key_len,
917 enc->iv, enc->iv_len, crypt_type)) != 0)
919 if (!state->cipher_warning_done &&
920 (wmsg = cipher_warning_message(*ccp)) != NULL) {
921 error("Warning: %s", wmsg);
922 state->cipher_warning_done = 1;
924 /* Deleting the keys does not gain extra security */
925 /* explicit_bzero(enc->iv, enc->block_size);
926 explicit_bzero(enc->key, enc->key_len);
927 explicit_bzero(mac->key, mac->key_len); */
928 if ((comp->type == COMP_ZLIB ||
929 (comp->type == COMP_DELAYED &&
930 state->after_authentication)) && comp->enabled == 0) {
931 if ((r = ssh_packet_init_compression(ssh)) < 0)
933 if (mode == MODE_OUT) {
934 if ((r = start_compression_out(ssh, 6)) != 0)
937 if ((r = start_compression_in(ssh)) != 0)
943 * The 2^(blocksize*2) limit is too expensive for 3DES,
944 * so enforce a 1GB limit for small blocksizes.
945 * See RFC4344 section 3.2.
947 if (enc->block_size >= 16)
948 *max_blocks = (u_int64_t)1 << (enc->block_size*2);
950 *max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
951 if (state->rekey_limit)
952 *max_blocks = MINIMUM(*max_blocks,
953 state->rekey_limit / enc->block_size);
954 debug("rekey %s after %llu blocks", dir,
955 (unsigned long long)*max_blocks);
959 #define MAX_PACKETS (1U<<31)
961 ssh_packet_need_rekeying(struct ssh *ssh, u_int outbound_packet_len)
963 struct session_state *state = ssh->state;
964 u_int32_t out_blocks;
966 /* XXX client can't cope with rekeying pre-auth */
967 if (!state->after_authentication)
970 /* Haven't keyed yet or KEX in progress. */
971 if (ssh_packet_is_rekeying(ssh))
974 /* Peer can't rekey */
975 if (ssh->compat & SSH_BUG_NOREKEY)
979 * Permit one packet in or out per rekey - this allows us to
980 * make progress when rekey limits are very small.
982 if (state->p_send.packets == 0 && state->p_read.packets == 0)
985 /* Time-based rekeying */
986 if (state->rekey_interval != 0 &&
987 (int64_t)state->rekey_time + state->rekey_interval <= monotime())
991 * Always rekey when MAX_PACKETS sent in either direction
992 * As per RFC4344 section 3.1 we do this after 2^31 packets.
994 if (state->p_send.packets > MAX_PACKETS ||
995 state->p_read.packets > MAX_PACKETS)
998 /* Rekey after (cipher-specific) maximum blocks */
999 out_blocks = ROUNDUP(outbound_packet_len,
1000 state->newkeys[MODE_OUT]->enc.block_size);
1001 return (state->max_blocks_out &&
1002 (state->p_send.blocks + out_blocks > state->max_blocks_out)) ||
1003 (state->max_blocks_in &&
1004 (state->p_read.blocks > state->max_blocks_in));
1008 ssh_packet_check_rekey(struct ssh *ssh)
1010 if (!ssh_packet_need_rekeying(ssh, 0))
1012 debug3_f("rekex triggered");
1013 return kex_start_rekex(ssh);
1017 * Delayed compression for SSH2 is enabled after authentication:
1018 * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
1019 * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
1022 ssh_packet_enable_delayed_compress(struct ssh *ssh)
1024 struct session_state *state = ssh->state;
1025 struct sshcomp *comp = NULL;
1029 * Remember that we are past the authentication step, so rekeying
1030 * with COMP_DELAYED will turn on compression immediately.
1032 state->after_authentication = 1;
1033 for (mode = 0; mode < MODE_MAX; mode++) {
1034 /* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
1035 if (state->newkeys[mode] == NULL)
1037 comp = &state->newkeys[mode]->comp;
1038 if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
1039 if ((r = ssh_packet_init_compression(ssh)) != 0)
1041 if (mode == MODE_OUT) {
1042 if ((r = start_compression_out(ssh, 6)) != 0)
1045 if ((r = start_compression_in(ssh)) != 0)
1054 /* Used to mute debug logging for noisy packet types */
1056 ssh_packet_log_type(u_char type)
1059 case SSH2_MSG_CHANNEL_DATA:
1060 case SSH2_MSG_CHANNEL_EXTENDED_DATA:
1061 case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
1069 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
1072 ssh_packet_send2_wrapped(struct ssh *ssh)
1074 struct session_state *state = ssh->state;
1075 u_char type, *cp, macbuf[SSH_DIGEST_MAX_LENGTH];
1076 u_char tmp, padlen, pad = 0;
1077 u_int authlen = 0, aadlen = 0;
1079 struct sshenc *enc = NULL;
1080 struct sshmac *mac = NULL;
1081 struct sshcomp *comp = NULL;
1084 if (state->newkeys[MODE_OUT] != NULL) {
1085 enc = &state->newkeys[MODE_OUT]->enc;
1086 mac = &state->newkeys[MODE_OUT]->mac;
1087 comp = &state->newkeys[MODE_OUT]->comp;
1088 /* disable mac for authenticated encryption */
1089 if ((authlen = cipher_authlen(enc->cipher)) != 0)
1092 block_size = enc ? enc->block_size : 8;
1093 aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
1095 type = (sshbuf_ptr(state->outgoing_packet))[5];
1096 if (ssh_packet_log_type(type))
1097 debug3("send packet: type %u", type);
1099 fprintf(stderr, "plain: ");
1100 sshbuf_dump(state->outgoing_packet, stderr);
1103 if (comp && comp->enabled) {
1104 len = sshbuf_len(state->outgoing_packet);
1105 /* skip header, compress only payload */
1106 if ((r = sshbuf_consume(state->outgoing_packet, 5)) != 0)
1108 sshbuf_reset(state->compression_buffer);
1109 if ((r = compress_buffer(ssh, state->outgoing_packet,
1110 state->compression_buffer)) != 0)
1112 sshbuf_reset(state->outgoing_packet);
1113 if ((r = sshbuf_put(state->outgoing_packet,
1114 "\0\0\0\0\0", 5)) != 0 ||
1115 (r = sshbuf_putb(state->outgoing_packet,
1116 state->compression_buffer)) != 0)
1118 DBG(debug("compression: raw %d compressed %zd", len,
1119 sshbuf_len(state->outgoing_packet)));
1122 /* sizeof (packet_len + pad_len + payload) */
1123 len = sshbuf_len(state->outgoing_packet);
1126 * calc size of padding, alloc space, get random data,
1127 * minimum padding is 4 bytes
1129 len -= aadlen; /* packet length is not encrypted for EtM modes */
1130 padlen = block_size - (len % block_size);
1132 padlen += block_size;
1133 if (state->extra_pad) {
1134 tmp = state->extra_pad;
1136 ROUNDUP(state->extra_pad, block_size);
1137 /* check if roundup overflowed */
1138 if (state->extra_pad < tmp)
1139 return SSH_ERR_INVALID_ARGUMENT;
1140 tmp = (len + padlen) % state->extra_pad;
1141 /* Check whether pad calculation below will underflow */
1142 if (tmp > state->extra_pad)
1143 return SSH_ERR_INVALID_ARGUMENT;
1144 pad = state->extra_pad - tmp;
1145 DBG(debug3_f("adding %d (len %d padlen %d extra_pad %d)",
1146 pad, len, padlen, state->extra_pad));
1149 /* Check whether padlen calculation overflowed */
1151 return SSH_ERR_INVALID_ARGUMENT; /* overflow */
1152 state->extra_pad = 0;
1154 if ((r = sshbuf_reserve(state->outgoing_packet, padlen, &cp)) != 0)
1156 if (enc && !cipher_ctx_is_plaintext(state->send_context)) {
1157 /* random padding */
1158 arc4random_buf(cp, padlen);
1161 explicit_bzero(cp, padlen);
1163 /* sizeof (packet_len + pad_len + payload + padding) */
1164 len = sshbuf_len(state->outgoing_packet);
1165 cp = sshbuf_mutable_ptr(state->outgoing_packet);
1167 r = SSH_ERR_INTERNAL_ERROR;
1170 /* packet_length includes payload, padding and padding length field */
1171 POKE_U32(cp, len - 4);
1173 DBG(debug("send: len %d (includes padlen %d, aadlen %d)",
1174 len, padlen, aadlen));
1176 /* compute MAC over seqnr and packet(length fields, payload, padding) */
1177 if (mac && mac->enabled && !mac->etm) {
1178 if ((r = mac_compute(mac, state->p_send.seqnr,
1179 sshbuf_ptr(state->outgoing_packet), len,
1180 macbuf, sizeof(macbuf))) != 0)
1182 DBG(debug("done calc MAC out #%d", state->p_send.seqnr));
1184 /* encrypt packet and append to output buffer. */
1185 if ((r = sshbuf_reserve(state->output,
1186 sshbuf_len(state->outgoing_packet) + authlen, &cp)) != 0)
1188 if ((r = cipher_crypt(state->send_context, state->p_send.seqnr, cp,
1189 sshbuf_ptr(state->outgoing_packet),
1190 len - aadlen, aadlen, authlen)) != 0)
1192 /* append unencrypted MAC */
1193 if (mac && mac->enabled) {
1195 /* EtM: compute mac over aadlen + cipher text */
1196 if ((r = mac_compute(mac, state->p_send.seqnr,
1197 cp, len, macbuf, sizeof(macbuf))) != 0)
1199 DBG(debug("done calc MAC(EtM) out #%d",
1200 state->p_send.seqnr));
1202 if ((r = sshbuf_put(state->output, macbuf, mac->mac_len)) != 0)
1206 fprintf(stderr, "encrypted: ");
1207 sshbuf_dump(state->output, stderr);
1209 /* increment sequence number for outgoing packets */
1210 if (++state->p_send.seqnr == 0)
1211 logit("outgoing seqnr wraps around");
1212 if (++state->p_send.packets == 0)
1213 if (!(ssh->compat & SSH_BUG_NOREKEY))
1214 return SSH_ERR_NEED_REKEY;
1215 state->p_send.blocks += len / block_size;
1216 state->p_send.bytes += len;
1217 sshbuf_reset(state->outgoing_packet);
1219 if (type == SSH2_MSG_NEWKEYS)
1220 r = ssh_set_newkeys(ssh, MODE_OUT);
1221 else if (type == SSH2_MSG_USERAUTH_SUCCESS && state->server_side)
1222 r = ssh_packet_enable_delayed_compress(ssh);
1229 /* returns non-zero if the specified packet type is usec by KEX */
1231 ssh_packet_type_is_kex(u_char type)
1234 type >= SSH2_MSG_TRANSPORT_MIN &&
1235 type <= SSH2_MSG_TRANSPORT_MAX &&
1236 type != SSH2_MSG_SERVICE_REQUEST &&
1237 type != SSH2_MSG_SERVICE_ACCEPT &&
1238 type != SSH2_MSG_EXT_INFO;
1242 ssh_packet_send2(struct ssh *ssh)
1244 struct session_state *state = ssh->state;
1249 if (sshbuf_len(state->outgoing_packet) < 6)
1250 return SSH_ERR_INTERNAL_ERROR;
1251 type = sshbuf_ptr(state->outgoing_packet)[5];
1252 need_rekey = !ssh_packet_type_is_kex(type) &&
1253 ssh_packet_need_rekeying(ssh, sshbuf_len(state->outgoing_packet));
1256 * During rekeying we can only send key exchange messages.
1257 * Queue everything else.
1259 if ((need_rekey || state->rekeying) && !ssh_packet_type_is_kex(type)) {
1261 debug3_f("rekex triggered");
1262 debug("enqueue packet: %u", type);
1263 p = calloc(1, sizeof(*p));
1265 return SSH_ERR_ALLOC_FAIL;
1267 p->payload = state->outgoing_packet;
1268 TAILQ_INSERT_TAIL(&state->outgoing, p, next);
1269 state->outgoing_packet = sshbuf_new();
1270 if (state->outgoing_packet == NULL)
1271 return SSH_ERR_ALLOC_FAIL;
1274 * This packet triggered a rekey, so send the
1276 * NB. reenters this function via kex_start_rekex().
1278 return kex_start_rekex(ssh);
1283 /* rekeying starts with sending KEXINIT */
1284 if (type == SSH2_MSG_KEXINIT)
1285 state->rekeying = 1;
1287 if ((r = ssh_packet_send2_wrapped(ssh)) != 0)
1290 /* after a NEWKEYS message we can send the complete queue */
1291 if (type == SSH2_MSG_NEWKEYS) {
1292 state->rekeying = 0;
1293 state->rekey_time = monotime();
1294 while ((p = TAILQ_FIRST(&state->outgoing))) {
1297 * If this packet triggers a rekex, then skip the
1298 * remaining packets in the queue for now.
1299 * NB. re-enters this function via kex_start_rekex.
1301 if (ssh_packet_need_rekeying(ssh,
1302 sshbuf_len(p->payload))) {
1303 debug3_f("queued packet triggered rekex");
1304 return kex_start_rekex(ssh);
1306 debug("dequeue packet: %u", type);
1307 sshbuf_free(state->outgoing_packet);
1308 state->outgoing_packet = p->payload;
1309 TAILQ_REMOVE(&state->outgoing, p, next);
1310 memset(p, 0, sizeof(*p));
1312 if ((r = ssh_packet_send2_wrapped(ssh)) != 0)
1320 * Waits until a packet has been received, and returns its type. Note that
1321 * no other data is processed until this returns, so this function should not
1322 * be used during the interactive session.
1326 ssh_packet_read_seqnr(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1328 struct session_state *state = ssh->state;
1329 int len, r, ms_remain;
1332 struct timeval timeout, start, *timeoutp = NULL;
1334 DBG(debug("packet_read()"));
1336 setp = calloc(howmany(state->connection_in + 1,
1337 NFDBITS), sizeof(fd_mask));
1339 return SSH_ERR_ALLOC_FAIL;
1342 * Since we are blocking, ensure that all written packets have
1345 if ((r = ssh_packet_write_wait(ssh)) != 0)
1348 /* Stay in the loop until we have received a complete packet. */
1350 /* Try to read a packet from the buffer. */
1351 r = ssh_packet_read_poll_seqnr(ssh, typep, seqnr_p);
1354 /* If we got a packet, return it. */
1355 if (*typep != SSH_MSG_NONE)
1358 * Otherwise, wait for some data to arrive, add it to the
1359 * buffer, and try again.
1361 memset(setp, 0, howmany(state->connection_in + 1,
1362 NFDBITS) * sizeof(fd_mask));
1363 FD_SET(state->connection_in, setp);
1365 if (state->packet_timeout_ms > 0) {
1366 ms_remain = state->packet_timeout_ms;
1367 timeoutp = &timeout;
1369 /* Wait for some data to arrive. */
1371 if (state->packet_timeout_ms > 0) {
1372 ms_to_timeval(&timeout, ms_remain);
1373 monotime_tv(&start);
1375 if ((r = select(state->connection_in + 1, setp,
1376 NULL, NULL, timeoutp)) >= 0)
1378 if (errno != EAGAIN && errno != EINTR &&
1379 errno != EWOULDBLOCK) {
1380 r = SSH_ERR_SYSTEM_ERROR;
1383 if (state->packet_timeout_ms <= 0)
1385 ms_subtract_diff(&start, &ms_remain);
1386 if (ms_remain <= 0) {
1392 r = SSH_ERR_CONN_TIMEOUT;
1395 /* Read data from the socket. */
1396 len = read(state->connection_in, buf, sizeof(buf));
1398 r = SSH_ERR_CONN_CLOSED;
1402 r = SSH_ERR_SYSTEM_ERROR;
1406 /* Append it to the buffer. */
1407 if ((r = ssh_packet_process_incoming(ssh, buf, len)) != 0)
1416 ssh_packet_read(struct ssh *ssh)
1421 if ((r = ssh_packet_read_seqnr(ssh, &type, NULL)) != 0)
1422 fatal_fr(r, "read");
1427 * Waits until a packet has been received, verifies that its type matches
1428 * that given, and gives a fatal error and exits if there is a mismatch.
1432 ssh_packet_read_expect(struct ssh *ssh, u_int expected_type)
1437 if ((r = ssh_packet_read_seqnr(ssh, &type, NULL)) != 0)
1439 if (type != expected_type) {
1440 if ((r = sshpkt_disconnect(ssh,
1441 "Protocol error: expected packet type %d, got %d",
1442 expected_type, type)) != 0)
1444 return SSH_ERR_PROTOCOL_ERROR;
1450 ssh_packet_read_poll2_mux(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1452 struct session_state *state = ssh->state;
1458 return SSH_ERR_INTERNAL_ERROR;
1459 *typep = SSH_MSG_NONE;
1460 cp = sshbuf_ptr(state->input);
1461 if (state->packlen == 0) {
1462 if (sshbuf_len(state->input) < 4 + 1)
1463 return 0; /* packet is incomplete */
1464 state->packlen = PEEK_U32(cp);
1465 if (state->packlen < 4 + 1 ||
1466 state->packlen > PACKET_MAX_SIZE)
1467 return SSH_ERR_MESSAGE_INCOMPLETE;
1469 need = state->packlen + 4;
1470 if (sshbuf_len(state->input) < need)
1471 return 0; /* packet is incomplete */
1472 sshbuf_reset(state->incoming_packet);
1473 if ((r = sshbuf_put(state->incoming_packet, cp + 4,
1474 state->packlen)) != 0 ||
1475 (r = sshbuf_consume(state->input, need)) != 0 ||
1476 (r = sshbuf_get_u8(state->incoming_packet, NULL)) != 0 ||
1477 (r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
1479 if (ssh_packet_log_type(*typep))
1480 debug3_f("type %u", *typep);
1481 /* sshbuf_dump(state->incoming_packet, stderr); */
1482 /* reset for next packet */
1488 ssh_packet_read_poll2(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1490 struct session_state *state = ssh->state;
1493 u_int maclen, aadlen = 0, authlen = 0, block_size;
1494 struct sshenc *enc = NULL;
1495 struct sshmac *mac = NULL;
1496 struct sshcomp *comp = NULL;
1500 return ssh_packet_read_poll2_mux(ssh, typep, seqnr_p);
1502 *typep = SSH_MSG_NONE;
1504 if (state->packet_discard)
1507 if (state->newkeys[MODE_IN] != NULL) {
1508 enc = &state->newkeys[MODE_IN]->enc;
1509 mac = &state->newkeys[MODE_IN]->mac;
1510 comp = &state->newkeys[MODE_IN]->comp;
1511 /* disable mac for authenticated encryption */
1512 if ((authlen = cipher_authlen(enc->cipher)) != 0)
1515 maclen = mac && mac->enabled ? mac->mac_len : 0;
1516 block_size = enc ? enc->block_size : 8;
1517 aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
1519 if (aadlen && state->packlen == 0) {
1520 if (cipher_get_length(state->receive_context,
1521 &state->packlen, state->p_read.seqnr,
1522 sshbuf_ptr(state->input), sshbuf_len(state->input)) != 0)
1524 if (state->packlen < 1 + 4 ||
1525 state->packlen > PACKET_MAX_SIZE) {
1527 sshbuf_dump(state->input, stderr);
1529 logit("Bad packet length %u.", state->packlen);
1530 if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0)
1532 return SSH_ERR_CONN_CORRUPT;
1534 sshbuf_reset(state->incoming_packet);
1535 } else if (state->packlen == 0) {
1537 * check if input size is less than the cipher block size,
1538 * decrypt first block and extract length of incoming packet
1540 if (sshbuf_len(state->input) < block_size)
1542 sshbuf_reset(state->incoming_packet);
1543 if ((r = sshbuf_reserve(state->incoming_packet, block_size,
1546 if ((r = cipher_crypt(state->receive_context,
1547 state->p_send.seqnr, cp, sshbuf_ptr(state->input),
1548 block_size, 0, 0)) != 0)
1550 state->packlen = PEEK_U32(sshbuf_ptr(state->incoming_packet));
1551 if (state->packlen < 1 + 4 ||
1552 state->packlen > PACKET_MAX_SIZE) {
1554 fprintf(stderr, "input: \n");
1555 sshbuf_dump(state->input, stderr);
1556 fprintf(stderr, "incoming_packet: \n");
1557 sshbuf_dump(state->incoming_packet, stderr);
1559 logit("Bad packet length %u.", state->packlen);
1560 return ssh_packet_start_discard(ssh, enc, mac, 0,
1563 if ((r = sshbuf_consume(state->input, block_size)) != 0)
1566 DBG(debug("input: packet len %u", state->packlen+4));
1569 /* only the payload is encrypted */
1570 need = state->packlen;
1573 * the payload size and the payload are encrypted, but we
1574 * have a partial packet of block_size bytes
1576 need = 4 + state->packlen - block_size;
1578 DBG(debug("partial packet: block %d, need %d, maclen %d, authlen %d,"
1579 " aadlen %d", block_size, need, maclen, authlen, aadlen));
1580 if (need % block_size != 0) {
1581 logit("padding error: need %d block %d mod %d",
1582 need, block_size, need % block_size);
1583 return ssh_packet_start_discard(ssh, enc, mac, 0,
1584 PACKET_MAX_SIZE - block_size);
1587 * check if the entire packet has been received and
1588 * decrypt into incoming_packet:
1589 * 'aadlen' bytes are unencrypted, but authenticated.
1590 * 'need' bytes are encrypted, followed by either
1591 * 'authlen' bytes of authentication tag or
1592 * 'maclen' bytes of message authentication code.
1594 if (sshbuf_len(state->input) < aadlen + need + authlen + maclen)
1595 return 0; /* packet is incomplete */
1597 fprintf(stderr, "read_poll enc/full: ");
1598 sshbuf_dump(state->input, stderr);
1600 /* EtM: check mac over encrypted input */
1601 if (mac && mac->enabled && mac->etm) {
1602 if ((r = mac_check(mac, state->p_read.seqnr,
1603 sshbuf_ptr(state->input), aadlen + need,
1604 sshbuf_ptr(state->input) + aadlen + need + authlen,
1606 if (r == SSH_ERR_MAC_INVALID)
1607 logit("Corrupted MAC on input.");
1611 if ((r = sshbuf_reserve(state->incoming_packet, aadlen + need,
1614 if ((r = cipher_crypt(state->receive_context, state->p_read.seqnr, cp,
1615 sshbuf_ptr(state->input), need, aadlen, authlen)) != 0)
1617 if ((r = sshbuf_consume(state->input, aadlen + need + authlen)) != 0)
1619 if (mac && mac->enabled) {
1620 /* Not EtM: check MAC over cleartext */
1621 if (!mac->etm && (r = mac_check(mac, state->p_read.seqnr,
1622 sshbuf_ptr(state->incoming_packet),
1623 sshbuf_len(state->incoming_packet),
1624 sshbuf_ptr(state->input), maclen)) != 0) {
1625 if (r != SSH_ERR_MAC_INVALID)
1627 logit("Corrupted MAC on input.");
1628 if (need + block_size > PACKET_MAX_SIZE)
1629 return SSH_ERR_INTERNAL_ERROR;
1630 return ssh_packet_start_discard(ssh, enc, mac,
1631 sshbuf_len(state->incoming_packet),
1632 PACKET_MAX_SIZE - need - block_size);
1634 /* Remove MAC from input buffer */
1635 DBG(debug("MAC #%d ok", state->p_read.seqnr));
1636 if ((r = sshbuf_consume(state->input, mac->mac_len)) != 0)
1639 if (seqnr_p != NULL)
1640 *seqnr_p = state->p_read.seqnr;
1641 if (++state->p_read.seqnr == 0)
1642 logit("incoming seqnr wraps around");
1643 if (++state->p_read.packets == 0)
1644 if (!(ssh->compat & SSH_BUG_NOREKEY))
1645 return SSH_ERR_NEED_REKEY;
1646 state->p_read.blocks += (state->packlen + 4) / block_size;
1647 state->p_read.bytes += state->packlen + 4;
1650 padlen = sshbuf_ptr(state->incoming_packet)[4];
1651 DBG(debug("input: padlen %d", padlen));
1653 if ((r = sshpkt_disconnect(ssh,
1654 "Corrupted padlen %d on input.", padlen)) != 0 ||
1655 (r = ssh_packet_write_wait(ssh)) != 0)
1657 return SSH_ERR_CONN_CORRUPT;
1660 /* skip packet size + padlen, discard padding */
1661 if ((r = sshbuf_consume(state->incoming_packet, 4 + 1)) != 0 ||
1662 ((r = sshbuf_consume_end(state->incoming_packet, padlen)) != 0))
1665 DBG(debug("input: len before de-compress %zd",
1666 sshbuf_len(state->incoming_packet)));
1667 if (comp && comp->enabled) {
1668 sshbuf_reset(state->compression_buffer);
1669 if ((r = uncompress_buffer(ssh, state->incoming_packet,
1670 state->compression_buffer)) != 0)
1672 sshbuf_reset(state->incoming_packet);
1673 if ((r = sshbuf_putb(state->incoming_packet,
1674 state->compression_buffer)) != 0)
1676 DBG(debug("input: len after de-compress %zd",
1677 sshbuf_len(state->incoming_packet)));
1680 * get packet type, implies consume.
1681 * return length of payload (without type field)
1683 if ((r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
1685 if (ssh_packet_log_type(*typep))
1686 debug3("receive packet: type %u", *typep);
1687 if (*typep < SSH2_MSG_MIN || *typep >= SSH2_MSG_LOCAL_MIN) {
1688 if ((r = sshpkt_disconnect(ssh,
1689 "Invalid ssh2 packet type: %d", *typep)) != 0 ||
1690 (r = ssh_packet_write_wait(ssh)) != 0)
1692 return SSH_ERR_PROTOCOL_ERROR;
1694 if (state->hook_in != NULL &&
1695 (r = state->hook_in(ssh, state->incoming_packet, typep,
1696 state->hook_in_ctx)) != 0)
1698 if (*typep == SSH2_MSG_USERAUTH_SUCCESS && !state->server_side)
1699 r = ssh_packet_enable_delayed_compress(ssh);
1703 fprintf(stderr, "read/plain[%d]:\r\n", *typep);
1704 sshbuf_dump(state->incoming_packet, stderr);
1706 /* reset for next packet */
1709 if ((r = ssh_packet_check_rekey(ssh)) != 0)
1716 ssh_packet_read_poll_seqnr(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1718 struct session_state *state = ssh->state;
1719 u_int reason, seqnr;
1725 r = ssh_packet_read_poll2(ssh, typep, seqnr_p);
1729 state->keep_alive_timeouts = 0;
1730 DBG(debug("received packet type %d", *typep));
1733 case SSH2_MSG_IGNORE:
1734 debug3("Received SSH2_MSG_IGNORE");
1736 case SSH2_MSG_DEBUG:
1737 if ((r = sshpkt_get_u8(ssh, NULL)) != 0 ||
1738 (r = sshpkt_get_string(ssh, &msg, NULL)) != 0 ||
1739 (r = sshpkt_get_string(ssh, NULL, NULL)) != 0) {
1743 debug("Remote: %.900s", msg);
1746 case SSH2_MSG_DISCONNECT:
1747 if ((r = sshpkt_get_u32(ssh, &reason)) != 0 ||
1748 (r = sshpkt_get_string(ssh, &msg, NULL)) != 0)
1750 /* Ignore normal client exit notifications */
1751 do_log2(ssh->state->server_side &&
1752 reason == SSH2_DISCONNECT_BY_APPLICATION ?
1753 SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_ERROR,
1754 "Received disconnect from %s port %d:"
1755 "%u: %.400s", ssh_remote_ipaddr(ssh),
1756 ssh_remote_port(ssh), reason, msg);
1758 return SSH_ERR_DISCONNECTED;
1759 case SSH2_MSG_UNIMPLEMENTED:
1760 if ((r = sshpkt_get_u32(ssh, &seqnr)) != 0)
1762 debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1772 * Buffers the given amount of input characters. This is intended to be used
1773 * together with packet_read_poll.
1777 ssh_packet_process_incoming(struct ssh *ssh, const char *buf, u_int len)
1779 struct session_state *state = ssh->state;
1782 if (state->packet_discard) {
1783 state->keep_alive_timeouts = 0; /* ?? */
1784 if (len >= state->packet_discard) {
1785 if ((r = ssh_packet_stop_discard(ssh)) != 0)
1788 state->packet_discard -= len;
1791 if ((r = sshbuf_put(ssh->state->input, buf, len)) != 0)
1798 ssh_packet_remaining(struct ssh *ssh)
1800 return sshbuf_len(ssh->state->incoming_packet);
1804 * Sends a diagnostic message from the server to the client. This message
1805 * can be sent at any time (but not while constructing another message). The
1806 * message is printed immediately, but only if the client is being executed
1807 * in verbose mode. These messages are primarily intended to ease debugging
1808 * authentication problems. The length of the formatted message must not
1809 * exceed 1024 bytes. This will automatically call ssh_packet_write_wait.
1812 ssh_packet_send_debug(struct ssh *ssh, const char *fmt,...)
1818 if ((ssh->compat & SSH_BUG_DEBUG))
1821 va_start(args, fmt);
1822 vsnprintf(buf, sizeof(buf), fmt, args);
1825 debug3("sending debug message: %s", buf);
1827 if ((r = sshpkt_start(ssh, SSH2_MSG_DEBUG)) != 0 ||
1828 (r = sshpkt_put_u8(ssh, 0)) != 0 || /* always display */
1829 (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
1830 (r = sshpkt_put_cstring(ssh, "")) != 0 ||
1831 (r = sshpkt_send(ssh)) != 0 ||
1832 (r = ssh_packet_write_wait(ssh)) != 0)
1833 fatal_fr(r, "send DEBUG");
1837 sshpkt_fmt_connection_id(struct ssh *ssh, char *s, size_t l)
1839 snprintf(s, l, "%.200s%s%s port %d",
1840 ssh->log_preamble ? ssh->log_preamble : "",
1841 ssh->log_preamble ? " " : "",
1842 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
1846 * Pretty-print connection-terminating errors and exit.
1849 sshpkt_vfatal(struct ssh *ssh, int r, const char *fmt, va_list ap)
1851 char *tag = NULL, remote_id[512];
1854 sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id));
1857 case SSH_ERR_CONN_CLOSED:
1858 ssh_packet_clear_keys(ssh);
1859 logdie("Connection closed by %s", remote_id);
1860 case SSH_ERR_CONN_TIMEOUT:
1861 ssh_packet_clear_keys(ssh);
1862 logdie("Connection %s %s timed out",
1863 ssh->state->server_side ? "from" : "to", remote_id);
1864 case SSH_ERR_DISCONNECTED:
1865 ssh_packet_clear_keys(ssh);
1866 logdie("Disconnected from %s", remote_id);
1867 case SSH_ERR_SYSTEM_ERROR:
1868 if (errno == ECONNRESET) {
1869 ssh_packet_clear_keys(ssh);
1870 logdie("Connection reset by %s", remote_id);
1873 case SSH_ERR_NO_CIPHER_ALG_MATCH:
1874 case SSH_ERR_NO_MAC_ALG_MATCH:
1875 case SSH_ERR_NO_COMPRESS_ALG_MATCH:
1876 case SSH_ERR_NO_KEX_ALG_MATCH:
1877 case SSH_ERR_NO_HOSTKEY_ALG_MATCH:
1878 if (ssh && ssh->kex && ssh->kex->failed_choice) {
1879 BLACKLIST_NOTIFY(ssh, BLACKLIST_AUTH_FAIL, "ssh");
1880 ssh_packet_clear_keys(ssh);
1882 logdie("Unable to negotiate with %s: %s. "
1883 "Their offer: %s", remote_id, ssh_err(r),
1884 ssh->kex->failed_choice);
1888 if (vasprintf(&tag, fmt, ap) == -1) {
1889 ssh_packet_clear_keys(ssh);
1890 logdie_f("could not allocate failure message");
1892 ssh_packet_clear_keys(ssh);
1894 logdie_r(r, "%s%sConnection %s %s",
1895 tag != NULL ? tag : "", tag != NULL ? ": " : "",
1896 ssh->state->server_side ? "from" : "to", remote_id);
1901 sshpkt_fatal(struct ssh *ssh, int r, const char *fmt, ...)
1906 sshpkt_vfatal(ssh, r, fmt, ap);
1909 logdie_f("should have exited");
1913 * Logs the error plus constructs and sends a disconnect packet, closes the
1914 * connection, and exits. This function never returns. The error message
1915 * should not contain a newline. The length of the formatted message must
1916 * not exceed 1024 bytes.
1919 ssh_packet_disconnect(struct ssh *ssh, const char *fmt,...)
1921 char buf[1024], remote_id[512];
1923 static int disconnecting = 0;
1926 if (disconnecting) /* Guard against recursive invocations. */
1927 fatal("packet_disconnect called recursively.");
1931 * Format the message. Note that the caller must make sure the
1932 * message is of limited size.
1934 sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id));
1935 va_start(args, fmt);
1936 vsnprintf(buf, sizeof(buf), fmt, args);
1939 /* Display the error locally */
1940 logit("Disconnecting %s: %.100s", remote_id, buf);
1943 * Send the disconnect message to the other side, and wait
1944 * for it to get sent.
1946 if ((r = sshpkt_disconnect(ssh, "%s", buf)) != 0)
1947 sshpkt_fatal(ssh, r, "%s", __func__);
1949 if ((r = ssh_packet_write_wait(ssh)) != 0)
1950 sshpkt_fatal(ssh, r, "%s", __func__);
1952 /* Close the connection. */
1953 ssh_packet_close(ssh);
1958 * Checks if there is any buffered output, and tries to write some of
1962 ssh_packet_write_poll(struct ssh *ssh)
1964 struct session_state *state = ssh->state;
1965 int len = sshbuf_len(state->output);
1969 len = write(state->connection_out,
1970 sshbuf_ptr(state->output), len);
1972 if (errno == EINTR || errno == EAGAIN ||
1973 errno == EWOULDBLOCK)
1975 return SSH_ERR_SYSTEM_ERROR;
1978 return SSH_ERR_CONN_CLOSED;
1979 if ((r = sshbuf_consume(state->output, len)) != 0)
1986 * Calls packet_write_poll repeatedly until all pending output data has been
1990 ssh_packet_write_wait(struct ssh *ssh)
1993 int ret, r, ms_remain = 0;
1994 struct timeval start, timeout, *timeoutp = NULL;
1995 struct session_state *state = ssh->state;
1997 setp = calloc(howmany(state->connection_out + 1,
1998 NFDBITS), sizeof(fd_mask));
2000 return SSH_ERR_ALLOC_FAIL;
2001 if ((r = ssh_packet_write_poll(ssh)) != 0) {
2005 while (ssh_packet_have_data_to_write(ssh)) {
2006 memset(setp, 0, howmany(state->connection_out + 1,
2007 NFDBITS) * sizeof(fd_mask));
2008 FD_SET(state->connection_out, setp);
2010 if (state->packet_timeout_ms > 0) {
2011 ms_remain = state->packet_timeout_ms;
2012 timeoutp = &timeout;
2015 if (state->packet_timeout_ms > 0) {
2016 ms_to_timeval(&timeout, ms_remain);
2017 monotime_tv(&start);
2019 if ((ret = select(state->connection_out + 1,
2020 NULL, setp, NULL, timeoutp)) >= 0)
2022 if (errno != EAGAIN && errno != EINTR &&
2023 errno != EWOULDBLOCK)
2025 if (state->packet_timeout_ms <= 0)
2027 ms_subtract_diff(&start, &ms_remain);
2028 if (ms_remain <= 0) {
2035 return SSH_ERR_CONN_TIMEOUT;
2037 if ((r = ssh_packet_write_poll(ssh)) != 0) {
2046 /* Returns true if there is buffered data to write to the connection. */
2049 ssh_packet_have_data_to_write(struct ssh *ssh)
2051 return sshbuf_len(ssh->state->output) != 0;
2054 /* Returns true if there is not too much data to write to the connection. */
2057 ssh_packet_not_very_much_data_to_write(struct ssh *ssh)
2059 if (ssh->state->interactive_mode)
2060 return sshbuf_len(ssh->state->output) < 16384;
2062 return sshbuf_len(ssh->state->output) < 128 * 1024;
2066 ssh_packet_set_tos(struct ssh *ssh, int tos)
2068 if (!ssh_packet_connection_is_on_socket(ssh) || tos == INT_MAX)
2070 set_sock_tos(ssh->state->connection_in, tos);
2073 /* Informs that the current session is interactive. Sets IP flags for that. */
2076 ssh_packet_set_interactive(struct ssh *ssh, int interactive, int qos_interactive, int qos_bulk)
2078 struct session_state *state = ssh->state;
2080 if (state->set_interactive_called)
2082 state->set_interactive_called = 1;
2084 /* Record that we are in interactive mode. */
2085 state->interactive_mode = interactive;
2087 /* Only set socket options if using a socket. */
2088 if (!ssh_packet_connection_is_on_socket(ssh))
2090 set_nodelay(state->connection_in);
2091 ssh_packet_set_tos(ssh, interactive ? qos_interactive : qos_bulk);
2094 /* Returns true if the current connection is interactive. */
2097 ssh_packet_is_interactive(struct ssh *ssh)
2099 return ssh->state->interactive_mode;
2103 ssh_packet_set_maxsize(struct ssh *ssh, u_int s)
2105 struct session_state *state = ssh->state;
2107 if (state->set_maxsize_called) {
2108 logit("packet_set_maxsize: called twice: old %d new %d",
2109 state->max_packet_size, s);
2112 if (s < 4 * 1024 || s > 1024 * 1024) {
2113 logit("packet_set_maxsize: bad size %d", s);
2116 state->set_maxsize_called = 1;
2117 debug("packet_set_maxsize: setting to %d", s);
2118 state->max_packet_size = s;
2123 ssh_packet_inc_alive_timeouts(struct ssh *ssh)
2125 return ++ssh->state->keep_alive_timeouts;
2129 ssh_packet_set_alive_timeouts(struct ssh *ssh, int ka)
2131 ssh->state->keep_alive_timeouts = ka;
2135 ssh_packet_get_maxsize(struct ssh *ssh)
2137 return ssh->state->max_packet_size;
2141 ssh_packet_set_rekey_limits(struct ssh *ssh, u_int64_t bytes, u_int32_t seconds)
2143 debug3("rekey after %llu bytes, %u seconds", (unsigned long long)bytes,
2144 (unsigned int)seconds);
2145 ssh->state->rekey_limit = bytes;
2146 ssh->state->rekey_interval = seconds;
2150 ssh_packet_get_rekey_timeout(struct ssh *ssh)
2154 seconds = ssh->state->rekey_time + ssh->state->rekey_interval -
2156 return (seconds <= 0 ? 1 : seconds);
2160 ssh_packet_set_server(struct ssh *ssh)
2162 ssh->state->server_side = 1;
2163 ssh->kex->server = 1; /* XXX unify? */
2167 ssh_packet_set_authenticated(struct ssh *ssh)
2169 ssh->state->after_authentication = 1;
2173 ssh_packet_get_input(struct ssh *ssh)
2175 return (void *)ssh->state->input;
2179 ssh_packet_get_output(struct ssh *ssh)
2181 return (void *)ssh->state->output;
2184 /* Reset after_authentication and reset compression in post-auth privsep */
2186 ssh_packet_set_postauth(struct ssh *ssh)
2191 /* This was set in net child, but is not visible in user child */
2192 ssh->state->after_authentication = 1;
2193 ssh->state->rekeying = 0;
2194 if ((r = ssh_packet_enable_delayed_compress(ssh)) != 0)
2199 /* Packet state (de-)serialization for privsep */
2201 /* turn kex into a blob for packet state serialization */
2203 kex_to_blob(struct sshbuf *m, struct kex *kex)
2207 if ((r = sshbuf_put_u32(m, kex->we_need)) != 0 ||
2208 (r = sshbuf_put_cstring(m, kex->hostkey_alg)) != 0 ||
2209 (r = sshbuf_put_u32(m, kex->hostkey_type)) != 0 ||
2210 (r = sshbuf_put_u32(m, kex->hostkey_nid)) != 0 ||
2211 (r = sshbuf_put_u32(m, kex->kex_type)) != 0 ||
2212 (r = sshbuf_put_stringb(m, kex->my)) != 0 ||
2213 (r = sshbuf_put_stringb(m, kex->peer)) != 0 ||
2214 (r = sshbuf_put_stringb(m, kex->client_version)) != 0 ||
2215 (r = sshbuf_put_stringb(m, kex->server_version)) != 0 ||
2216 (r = sshbuf_put_stringb(m, kex->session_id)) != 0 ||
2217 (r = sshbuf_put_u32(m, kex->flags)) != 0)
2222 /* turn key exchange results into a blob for packet state serialization */
2224 newkeys_to_blob(struct sshbuf *m, struct ssh *ssh, int mode)
2227 struct sshcipher_ctx *cc;
2228 struct sshcomp *comp;
2231 struct newkeys *newkey;
2234 if ((newkey = ssh->state->newkeys[mode]) == NULL)
2235 return SSH_ERR_INTERNAL_ERROR;
2238 comp = &newkey->comp;
2239 cc = (mode == MODE_OUT) ? ssh->state->send_context :
2240 ssh->state->receive_context;
2241 if ((r = cipher_get_keyiv(cc, enc->iv, enc->iv_len)) != 0)
2243 if ((b = sshbuf_new()) == NULL)
2244 return SSH_ERR_ALLOC_FAIL;
2245 if ((r = sshbuf_put_cstring(b, enc->name)) != 0 ||
2246 (r = sshbuf_put_u32(b, enc->enabled)) != 0 ||
2247 (r = sshbuf_put_u32(b, enc->block_size)) != 0 ||
2248 (r = sshbuf_put_string(b, enc->key, enc->key_len)) != 0 ||
2249 (r = sshbuf_put_string(b, enc->iv, enc->iv_len)) != 0)
2251 if (cipher_authlen(enc->cipher) == 0) {
2252 if ((r = sshbuf_put_cstring(b, mac->name)) != 0 ||
2253 (r = sshbuf_put_u32(b, mac->enabled)) != 0 ||
2254 (r = sshbuf_put_string(b, mac->key, mac->key_len)) != 0)
2257 if ((r = sshbuf_put_u32(b, comp->type)) != 0 ||
2258 (r = sshbuf_put_cstring(b, comp->name)) != 0)
2260 r = sshbuf_put_stringb(m, b);
2266 /* serialize packet state into a blob */
2268 ssh_packet_get_state(struct ssh *ssh, struct sshbuf *m)
2270 struct session_state *state = ssh->state;
2273 if ((r = kex_to_blob(m, ssh->kex)) != 0 ||
2274 (r = newkeys_to_blob(m, ssh, MODE_OUT)) != 0 ||
2275 (r = newkeys_to_blob(m, ssh, MODE_IN)) != 0 ||
2276 (r = sshbuf_put_u64(m, state->rekey_limit)) != 0 ||
2277 (r = sshbuf_put_u32(m, state->rekey_interval)) != 0 ||
2278 (r = sshbuf_put_u32(m, state->p_send.seqnr)) != 0 ||
2279 (r = sshbuf_put_u64(m, state->p_send.blocks)) != 0 ||
2280 (r = sshbuf_put_u32(m, state->p_send.packets)) != 0 ||
2281 (r = sshbuf_put_u64(m, state->p_send.bytes)) != 0 ||
2282 (r = sshbuf_put_u32(m, state->p_read.seqnr)) != 0 ||
2283 (r = sshbuf_put_u64(m, state->p_read.blocks)) != 0 ||
2284 (r = sshbuf_put_u32(m, state->p_read.packets)) != 0 ||
2285 (r = sshbuf_put_u64(m, state->p_read.bytes)) != 0 ||
2286 (r = sshbuf_put_stringb(m, state->input)) != 0 ||
2287 (r = sshbuf_put_stringb(m, state->output)) != 0)
2293 /* restore key exchange results from blob for packet state de-serialization */
2295 newkeys_from_blob(struct sshbuf *m, struct ssh *ssh, int mode)
2297 struct sshbuf *b = NULL;
2298 struct sshcomp *comp;
2301 struct newkeys *newkey = NULL;
2302 size_t keylen, ivlen, maclen;
2305 if ((newkey = calloc(1, sizeof(*newkey))) == NULL) {
2306 r = SSH_ERR_ALLOC_FAIL;
2309 if ((r = sshbuf_froms(m, &b)) != 0)
2312 sshbuf_dump(b, stderr);
2316 comp = &newkey->comp;
2318 if ((r = sshbuf_get_cstring(b, &enc->name, NULL)) != 0 ||
2319 (r = sshbuf_get_u32(b, (u_int *)&enc->enabled)) != 0 ||
2320 (r = sshbuf_get_u32(b, &enc->block_size)) != 0 ||
2321 (r = sshbuf_get_string(b, &enc->key, &keylen)) != 0 ||
2322 (r = sshbuf_get_string(b, &enc->iv, &ivlen)) != 0)
2324 if ((enc->cipher = cipher_by_name(enc->name)) == NULL) {
2325 r = SSH_ERR_INVALID_FORMAT;
2328 if (cipher_authlen(enc->cipher) == 0) {
2329 if ((r = sshbuf_get_cstring(b, &mac->name, NULL)) != 0)
2331 if ((r = mac_setup(mac, mac->name)) != 0)
2333 if ((r = sshbuf_get_u32(b, (u_int *)&mac->enabled)) != 0 ||
2334 (r = sshbuf_get_string(b, &mac->key, &maclen)) != 0)
2336 if (maclen > mac->key_len) {
2337 r = SSH_ERR_INVALID_FORMAT;
2340 mac->key_len = maclen;
2342 if ((r = sshbuf_get_u32(b, &comp->type)) != 0 ||
2343 (r = sshbuf_get_cstring(b, &comp->name, NULL)) != 0)
2345 if (sshbuf_len(b) != 0) {
2346 r = SSH_ERR_INVALID_FORMAT;
2349 enc->key_len = keylen;
2350 enc->iv_len = ivlen;
2351 ssh->kex->newkeys[mode] = newkey;
2360 /* restore kex from blob for packet state de-serialization */
2362 kex_from_blob(struct sshbuf *m, struct kex **kexp)
2367 if ((kex = kex_new()) == NULL)
2368 return SSH_ERR_ALLOC_FAIL;
2369 if ((r = sshbuf_get_u32(m, &kex->we_need)) != 0 ||
2370 (r = sshbuf_get_cstring(m, &kex->hostkey_alg, NULL)) != 0 ||
2371 (r = sshbuf_get_u32(m, (u_int *)&kex->hostkey_type)) != 0 ||
2372 (r = sshbuf_get_u32(m, (u_int *)&kex->hostkey_nid)) != 0 ||
2373 (r = sshbuf_get_u32(m, &kex->kex_type)) != 0 ||
2374 (r = sshbuf_get_stringb(m, kex->my)) != 0 ||
2375 (r = sshbuf_get_stringb(m, kex->peer)) != 0 ||
2376 (r = sshbuf_get_stringb(m, kex->client_version)) != 0 ||
2377 (r = sshbuf_get_stringb(m, kex->server_version)) != 0 ||
2378 (r = sshbuf_get_stringb(m, kex->session_id)) != 0 ||
2379 (r = sshbuf_get_u32(m, &kex->flags)) != 0)
2385 if (r != 0 || kexp == NULL) {
2397 * Restore packet state from content of blob 'm' (de-serialization).
2398 * Note that 'm' will be partially consumed on parsing or any other errors.
2401 ssh_packet_set_state(struct ssh *ssh, struct sshbuf *m)
2403 struct session_state *state = ssh->state;
2404 const u_char *input, *output;
2408 if ((r = kex_from_blob(m, &ssh->kex)) != 0 ||
2409 (r = newkeys_from_blob(m, ssh, MODE_OUT)) != 0 ||
2410 (r = newkeys_from_blob(m, ssh, MODE_IN)) != 0 ||
2411 (r = sshbuf_get_u64(m, &state->rekey_limit)) != 0 ||
2412 (r = sshbuf_get_u32(m, &state->rekey_interval)) != 0 ||
2413 (r = sshbuf_get_u32(m, &state->p_send.seqnr)) != 0 ||
2414 (r = sshbuf_get_u64(m, &state->p_send.blocks)) != 0 ||
2415 (r = sshbuf_get_u32(m, &state->p_send.packets)) != 0 ||
2416 (r = sshbuf_get_u64(m, &state->p_send.bytes)) != 0 ||
2417 (r = sshbuf_get_u32(m, &state->p_read.seqnr)) != 0 ||
2418 (r = sshbuf_get_u64(m, &state->p_read.blocks)) != 0 ||
2419 (r = sshbuf_get_u32(m, &state->p_read.packets)) != 0 ||
2420 (r = sshbuf_get_u64(m, &state->p_read.bytes)) != 0)
2423 * We set the time here so that in post-auth privsep child we
2424 * count from the completion of the authentication.
2426 state->rekey_time = monotime();
2427 /* XXX ssh_set_newkeys overrides p_read.packets? XXX */
2428 if ((r = ssh_set_newkeys(ssh, MODE_IN)) != 0 ||
2429 (r = ssh_set_newkeys(ssh, MODE_OUT)) != 0)
2432 if ((r = ssh_packet_set_postauth(ssh)) != 0)
2435 sshbuf_reset(state->input);
2436 sshbuf_reset(state->output);
2437 if ((r = sshbuf_get_string_direct(m, &input, &ilen)) != 0 ||
2438 (r = sshbuf_get_string_direct(m, &output, &olen)) != 0 ||
2439 (r = sshbuf_put(state->input, input, ilen)) != 0 ||
2440 (r = sshbuf_put(state->output, output, olen)) != 0)
2444 return SSH_ERR_INVALID_FORMAT;
2451 /* put data to the outgoing packet */
2454 sshpkt_put(struct ssh *ssh, const void *v, size_t len)
2456 return sshbuf_put(ssh->state->outgoing_packet, v, len);
2460 sshpkt_putb(struct ssh *ssh, const struct sshbuf *b)
2462 return sshbuf_putb(ssh->state->outgoing_packet, b);
2466 sshpkt_put_u8(struct ssh *ssh, u_char val)
2468 return sshbuf_put_u8(ssh->state->outgoing_packet, val);
2472 sshpkt_put_u32(struct ssh *ssh, u_int32_t val)
2474 return sshbuf_put_u32(ssh->state->outgoing_packet, val);
2478 sshpkt_put_u64(struct ssh *ssh, u_int64_t val)
2480 return sshbuf_put_u64(ssh->state->outgoing_packet, val);
2484 sshpkt_put_string(struct ssh *ssh, const void *v, size_t len)
2486 return sshbuf_put_string(ssh->state->outgoing_packet, v, len);
2490 sshpkt_put_cstring(struct ssh *ssh, const void *v)
2492 return sshbuf_put_cstring(ssh->state->outgoing_packet, v);
2496 sshpkt_put_stringb(struct ssh *ssh, const struct sshbuf *v)
2498 return sshbuf_put_stringb(ssh->state->outgoing_packet, v);
2502 sshpkt_getb_froms(struct ssh *ssh, struct sshbuf **valp)
2504 return sshbuf_froms(ssh->state->incoming_packet, valp);
2508 #ifdef OPENSSL_HAS_ECC
2510 sshpkt_put_ec(struct ssh *ssh, const EC_POINT *v, const EC_GROUP *g)
2512 return sshbuf_put_ec(ssh->state->outgoing_packet, v, g);
2514 #endif /* OPENSSL_HAS_ECC */
2518 sshpkt_put_bignum2(struct ssh *ssh, const BIGNUM *v)
2520 return sshbuf_put_bignum2(ssh->state->outgoing_packet, v);
2522 #endif /* WITH_OPENSSL */
2524 /* fetch data from the incoming packet */
2527 sshpkt_get(struct ssh *ssh, void *valp, size_t len)
2529 return sshbuf_get(ssh->state->incoming_packet, valp, len);
2533 sshpkt_get_u8(struct ssh *ssh, u_char *valp)
2535 return sshbuf_get_u8(ssh->state->incoming_packet, valp);
2539 sshpkt_get_u32(struct ssh *ssh, u_int32_t *valp)
2541 return sshbuf_get_u32(ssh->state->incoming_packet, valp);
2545 sshpkt_get_u64(struct ssh *ssh, u_int64_t *valp)
2547 return sshbuf_get_u64(ssh->state->incoming_packet, valp);
2551 sshpkt_get_string(struct ssh *ssh, u_char **valp, size_t *lenp)
2553 return sshbuf_get_string(ssh->state->incoming_packet, valp, lenp);
2557 sshpkt_get_string_direct(struct ssh *ssh, const u_char **valp, size_t *lenp)
2559 return sshbuf_get_string_direct(ssh->state->incoming_packet, valp, lenp);
2563 sshpkt_peek_string_direct(struct ssh *ssh, const u_char **valp, size_t *lenp)
2565 return sshbuf_peek_string_direct(ssh->state->incoming_packet, valp, lenp);
2569 sshpkt_get_cstring(struct ssh *ssh, char **valp, size_t *lenp)
2571 return sshbuf_get_cstring(ssh->state->incoming_packet, valp, lenp);
2575 #ifdef OPENSSL_HAS_ECC
2577 sshpkt_get_ec(struct ssh *ssh, EC_POINT *v, const EC_GROUP *g)
2579 return sshbuf_get_ec(ssh->state->incoming_packet, v, g);
2581 #endif /* OPENSSL_HAS_ECC */
2584 sshpkt_get_bignum2(struct ssh *ssh, BIGNUM **valp)
2586 return sshbuf_get_bignum2(ssh->state->incoming_packet, valp);
2588 #endif /* WITH_OPENSSL */
2591 sshpkt_get_end(struct ssh *ssh)
2593 if (sshbuf_len(ssh->state->incoming_packet) > 0)
2594 return SSH_ERR_UNEXPECTED_TRAILING_DATA;
2599 sshpkt_ptr(struct ssh *ssh, size_t *lenp)
2602 *lenp = sshbuf_len(ssh->state->incoming_packet);
2603 return sshbuf_ptr(ssh->state->incoming_packet);
2606 /* start a new packet */
2609 sshpkt_start(struct ssh *ssh, u_char type)
2611 u_char buf[6]; /* u32 packet length, u8 pad len, u8 type */
2613 DBG(debug("packet_start[%d]", type));
2614 memset(buf, 0, sizeof(buf));
2615 buf[sizeof(buf) - 1] = type;
2616 sshbuf_reset(ssh->state->outgoing_packet);
2617 return sshbuf_put(ssh->state->outgoing_packet, buf, sizeof(buf));
2621 ssh_packet_send_mux(struct ssh *ssh)
2623 struct session_state *state = ssh->state;
2629 return SSH_ERR_INTERNAL_ERROR;
2630 len = sshbuf_len(state->outgoing_packet);
2632 return SSH_ERR_INTERNAL_ERROR;
2633 cp = sshbuf_mutable_ptr(state->outgoing_packet);
2635 if (ssh_packet_log_type(type))
2636 debug3_f("type %u", type);
2637 /* drop everything, but the connection protocol */
2638 if (type >= SSH2_MSG_CONNECTION_MIN &&
2639 type <= SSH2_MSG_CONNECTION_MAX) {
2640 POKE_U32(cp, len - 4);
2641 if ((r = sshbuf_putb(state->output,
2642 state->outgoing_packet)) != 0)
2644 /* sshbuf_dump(state->output, stderr); */
2646 sshbuf_reset(state->outgoing_packet);
2651 * 9.2. Ignored Data Message
2653 * byte SSH_MSG_IGNORE
2656 * All implementations MUST understand (and ignore) this message at any
2657 * time (after receiving the protocol version). No implementation is
2658 * required to send them. This message can be used as an additional
2659 * protection measure against advanced traffic analysis techniques.
2662 sshpkt_msg_ignore(struct ssh *ssh, u_int nbytes)
2668 if ((r = sshpkt_start(ssh, SSH2_MSG_IGNORE)) != 0 ||
2669 (r = sshpkt_put_u32(ssh, nbytes)) != 0)
2671 for (i = 0; i < nbytes; i++) {
2674 if ((r = sshpkt_put_u8(ssh, (u_char)rnd & 0xff)) != 0)
2684 sshpkt_send(struct ssh *ssh)
2686 if (ssh->state && ssh->state->mux)
2687 return ssh_packet_send_mux(ssh);
2688 return ssh_packet_send2(ssh);
2692 sshpkt_disconnect(struct ssh *ssh, const char *fmt,...)
2698 va_start(args, fmt);
2699 vsnprintf(buf, sizeof(buf), fmt, args);
2702 if ((r = sshpkt_start(ssh, SSH2_MSG_DISCONNECT)) != 0 ||
2703 (r = sshpkt_put_u32(ssh, SSH2_DISCONNECT_PROTOCOL_ERROR)) != 0 ||
2704 (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
2705 (r = sshpkt_put_cstring(ssh, "")) != 0 ||
2706 (r = sshpkt_send(ssh)) != 0)
2711 /* roundup current message to pad bytes */
2713 sshpkt_add_padding(struct ssh *ssh, u_char pad)
2715 ssh->state->extra_pad = pad;