1 /* $OpenBSD: packet.c,v 1.192 2014/02/02 03:44: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.
43 #include <sys/types.h>
44 #include "openbsd-compat/sys-queue.h"
45 #include <sys/param.h>
46 #include <sys/socket.h>
47 #ifdef HAVE_SYS_TIME_H
48 # include <sys/time.h>
51 #include <netinet/in.h>
52 #include <netinet/ip.h>
53 #include <arpa/inet.h>
90 #define PACKET_MAX_SIZE (256 * 1024)
100 TAILQ_ENTRY(packet) next;
105 struct session_state {
107 * This variable contains the file descriptors used for
108 * communicating with the other side. connection_in is used for
109 * reading; connection_out for writing. These can be the same
110 * descriptor, in which case it is assumed to be a socket.
115 /* Protocol flags for the remote side. */
116 u_int remote_protocol_flags;
118 /* Encryption context for receiving data. Only used for decryption. */
119 CipherContext receive_context;
121 /* Encryption context for sending data. Only used for encryption. */
122 CipherContext send_context;
124 /* Buffer for raw input data from the socket. */
127 /* Buffer for raw output data going to the socket. */
130 /* Buffer for the partial outgoing packet being constructed. */
131 Buffer outgoing_packet;
133 /* Buffer for the incoming packet currently being processed. */
134 Buffer incoming_packet;
136 /* Scratch buffer for packet compression/decompression. */
137 Buffer compression_buffer;
138 int compression_buffer_ready;
141 * Flag indicating whether packet compression/decompression is
144 int packet_compression;
146 /* default maximum packet size */
147 u_int max_packet_size;
149 /* Flag indicating whether this module has been initialized. */
152 /* Set to true if the connection is interactive. */
153 int interactive_mode;
155 /* Set to true if we are the server side. */
158 /* Set to true if we are authenticated. */
159 int after_authentication;
161 int keep_alive_timeouts;
163 /* The maximum time that we will wait to send or receive a packet */
164 int packet_timeout_ms;
166 /* Session key information for Encryption and MAC */
167 Newkeys *newkeys[MODE_MAX];
168 struct packet_state p_read, p_send;
170 /* Volume-based rekeying */
171 u_int64_t max_blocks_in, max_blocks_out;
172 u_int32_t rekey_limit;
174 /* Time-based rekeying */
175 time_t rekey_interval; /* how often in seconds */
176 time_t rekey_time; /* time of last rekeying */
178 /* Session key for protocol v1 */
179 u_char ssh1_key[SSH_SESSION_KEY_LENGTH];
182 /* roundup current message to extra_pad bytes */
185 /* XXX discard incoming data after MAC error */
186 u_int packet_discard;
187 Mac *packet_discard_mac;
189 /* Used in packet_read_poll2() */
192 /* Used in packet_send2 */
195 /* Used in packet_set_interactive */
196 int set_interactive_called;
198 /* Used in packet_set_maxsize */
199 int set_maxsize_called;
201 TAILQ_HEAD(, packet) outgoing;
204 static struct session_state *active_state, *backup_state;
205 #ifdef NONE_CIPHER_ENABLED
206 static int rekey_requested = 0;
209 static struct session_state *
210 alloc_session_state(void)
212 struct session_state *s = xcalloc(1, sizeof(*s));
214 s->connection_in = -1;
215 s->connection_out = -1;
216 s->max_packet_size = 32768;
217 s->packet_timeout_ms = -1;
222 * Sets the descriptors used for communication. Disables encryption until
223 * packet_set_encryption_key is called.
226 packet_set_connection(int fd_in, int fd_out)
228 const Cipher *none = cipher_by_name("none");
231 fatal("packet_set_connection: cannot load cipher 'none'");
232 if (active_state == NULL)
233 active_state = alloc_session_state();
234 active_state->connection_in = fd_in;
235 active_state->connection_out = fd_out;
236 cipher_init(&active_state->send_context, none, (const u_char *)"",
237 0, NULL, 0, CIPHER_ENCRYPT);
238 cipher_init(&active_state->receive_context, none, (const u_char *)"",
239 0, NULL, 0, CIPHER_DECRYPT);
240 active_state->newkeys[MODE_IN] = active_state->newkeys[MODE_OUT] = NULL;
241 if (!active_state->initialized) {
242 active_state->initialized = 1;
243 buffer_init(&active_state->input);
244 buffer_init(&active_state->output);
245 buffer_init(&active_state->outgoing_packet);
246 buffer_init(&active_state->incoming_packet);
247 TAILQ_INIT(&active_state->outgoing);
248 active_state->p_send.packets = active_state->p_read.packets = 0;
253 packet_set_timeout(int timeout, int count)
255 if (timeout <= 0 || count <= 0) {
256 active_state->packet_timeout_ms = -1;
259 if ((INT_MAX / 1000) / count < timeout)
260 active_state->packet_timeout_ms = INT_MAX;
262 active_state->packet_timeout_ms = timeout * count * 1000;
266 packet_stop_discard(void)
268 if (active_state->packet_discard_mac) {
271 memset(buf, 'a', sizeof(buf));
272 while (buffer_len(&active_state->incoming_packet) <
274 buffer_append(&active_state->incoming_packet, buf,
276 (void) mac_compute(active_state->packet_discard_mac,
277 active_state->p_read.seqnr,
278 buffer_ptr(&active_state->incoming_packet),
281 logit("Finished discarding for %.200s", get_remote_ipaddr());
286 packet_start_discard(Enc *enc, Mac *mac, u_int packet_length, u_int discard)
288 if (enc == NULL || !cipher_is_cbc(enc->cipher) || (mac && mac->etm))
289 packet_disconnect("Packet corrupt");
290 if (packet_length != PACKET_MAX_SIZE && mac && mac->enabled)
291 active_state->packet_discard_mac = mac;
292 if (buffer_len(&active_state->input) >= discard)
293 packet_stop_discard();
294 active_state->packet_discard = discard -
295 buffer_len(&active_state->input);
298 /* Returns 1 if remote host is connected via socket, 0 if not. */
301 packet_connection_is_on_socket(void)
303 struct sockaddr_storage from, to;
304 socklen_t fromlen, tolen;
306 /* filedescriptors in and out are the same, so it's a socket */
307 if (active_state->connection_in == active_state->connection_out)
309 fromlen = sizeof(from);
310 memset(&from, 0, sizeof(from));
311 if (getpeername(active_state->connection_in, (struct sockaddr *)&from,
315 memset(&to, 0, sizeof(to));
316 if (getpeername(active_state->connection_out, (struct sockaddr *)&to,
319 if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
321 if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
327 * Exports an IV from the CipherContext required to export the key
328 * state back from the unprivileged child to the privileged parent
333 packet_get_keyiv(int mode, u_char *iv, u_int len)
337 if (mode == MODE_OUT)
338 cc = &active_state->send_context;
340 cc = &active_state->receive_context;
342 cipher_get_keyiv(cc, iv, len);
346 packet_get_keycontext(int mode, u_char *dat)
350 if (mode == MODE_OUT)
351 cc = &active_state->send_context;
353 cc = &active_state->receive_context;
355 return (cipher_get_keycontext(cc, dat));
359 packet_set_keycontext(int mode, u_char *dat)
363 if (mode == MODE_OUT)
364 cc = &active_state->send_context;
366 cc = &active_state->receive_context;
368 cipher_set_keycontext(cc, dat);
372 packet_get_keyiv_len(int mode)
376 if (mode == MODE_OUT)
377 cc = &active_state->send_context;
379 cc = &active_state->receive_context;
381 return (cipher_get_keyiv_len(cc));
385 packet_set_iv(int mode, u_char *dat)
389 if (mode == MODE_OUT)
390 cc = &active_state->send_context;
392 cc = &active_state->receive_context;
394 cipher_set_keyiv(cc, dat);
398 packet_get_ssh1_cipher(void)
400 return (cipher_get_number(active_state->receive_context.cipher));
404 packet_get_state(int mode, u_int32_t *seqnr, u_int64_t *blocks,
405 u_int32_t *packets, u_int64_t *bytes)
407 struct packet_state *state;
409 state = (mode == MODE_IN) ?
410 &active_state->p_read : &active_state->p_send;
412 *seqnr = state->seqnr;
414 *blocks = state->blocks;
416 *packets = state->packets;
418 *bytes = state->bytes;
422 packet_set_state(int mode, u_int32_t seqnr, u_int64_t blocks, u_int32_t packets,
425 struct packet_state *state;
427 state = (mode == MODE_IN) ?
428 &active_state->p_read : &active_state->p_send;
429 state->seqnr = seqnr;
430 state->blocks = blocks;
431 state->packets = packets;
432 state->bytes = bytes;
436 packet_connection_af(void)
438 struct sockaddr_storage to;
439 socklen_t tolen = sizeof(to);
441 memset(&to, 0, sizeof(to));
442 if (getsockname(active_state->connection_out, (struct sockaddr *)&to,
446 if (to.ss_family == AF_INET6 &&
447 IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&to)->sin6_addr))
453 /* Sets the connection into non-blocking mode. */
456 packet_set_nonblocking(void)
458 /* Set the socket into non-blocking mode. */
459 set_nonblock(active_state->connection_in);
461 if (active_state->connection_out != active_state->connection_in)
462 set_nonblock(active_state->connection_out);
465 /* Returns the socket used for reading. */
468 packet_get_connection_in(void)
470 return active_state->connection_in;
473 /* Returns the descriptor used for writing. */
476 packet_get_connection_out(void)
478 return active_state->connection_out;
481 /* Closes the connection and clears and frees internal data structures. */
486 if (!active_state->initialized)
488 active_state->initialized = 0;
489 if (active_state->connection_in == active_state->connection_out) {
490 shutdown(active_state->connection_out, SHUT_RDWR);
491 close(active_state->connection_out);
493 close(active_state->connection_in);
494 close(active_state->connection_out);
496 buffer_free(&active_state->input);
497 buffer_free(&active_state->output);
498 buffer_free(&active_state->outgoing_packet);
499 buffer_free(&active_state->incoming_packet);
500 if (active_state->compression_buffer_ready) {
501 buffer_free(&active_state->compression_buffer);
502 buffer_compress_uninit();
504 cipher_cleanup(&active_state->send_context);
505 cipher_cleanup(&active_state->receive_context);
508 /* Sets remote side protocol flags. */
511 packet_set_protocol_flags(u_int protocol_flags)
513 active_state->remote_protocol_flags = protocol_flags;
516 /* Returns the remote protocol flags set earlier by the above function. */
519 packet_get_protocol_flags(void)
521 return active_state->remote_protocol_flags;
525 * Starts packet compression from the next packet on in both directions.
526 * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
530 packet_init_compression(void)
532 if (active_state->compression_buffer_ready == 1)
534 active_state->compression_buffer_ready = 1;
535 buffer_init(&active_state->compression_buffer);
539 packet_start_compression(int level)
541 if (active_state->packet_compression && !compat20)
542 fatal("Compression already enabled.");
543 active_state->packet_compression = 1;
544 packet_init_compression();
545 buffer_compress_init_send(level);
546 buffer_compress_init_recv();
550 * Causes any further packets to be encrypted using the given key. The same
551 * key is used for both sending and reception. However, both directions are
552 * encrypted independently of each other.
556 packet_set_encryption_key(const u_char *key, u_int keylen, int number)
558 const Cipher *cipher = cipher_by_number(number);
561 fatal("packet_set_encryption_key: unknown cipher number %d", number);
563 fatal("packet_set_encryption_key: keylen too small: %d", keylen);
564 if (keylen > SSH_SESSION_KEY_LENGTH)
565 fatal("packet_set_encryption_key: keylen too big: %d", keylen);
566 memcpy(active_state->ssh1_key, key, keylen);
567 active_state->ssh1_keylen = keylen;
568 cipher_init(&active_state->send_context, cipher, key, keylen, NULL,
570 cipher_init(&active_state->receive_context, cipher, key, keylen, NULL,
575 packet_get_encryption_key(u_char *key)
578 return (active_state->ssh1_keylen);
579 memcpy(key, active_state->ssh1_key, active_state->ssh1_keylen);
580 return (active_state->ssh1_keylen);
583 /* Start constructing a packet to send. */
585 packet_start(u_char type)
590 DBG(debug("packet_start[%d]", type));
591 len = compat20 ? 6 : 9;
592 memset(buf, 0, len - 1);
594 buffer_clear(&active_state->outgoing_packet);
595 buffer_append(&active_state->outgoing_packet, buf, len);
598 /* Append payload. */
600 packet_put_char(int value)
604 buffer_append(&active_state->outgoing_packet, &ch, 1);
608 packet_put_int(u_int value)
610 buffer_put_int(&active_state->outgoing_packet, value);
614 packet_put_int64(u_int64_t value)
616 buffer_put_int64(&active_state->outgoing_packet, value);
620 packet_put_string(const void *buf, u_int len)
622 buffer_put_string(&active_state->outgoing_packet, buf, len);
626 packet_put_cstring(const char *str)
628 buffer_put_cstring(&active_state->outgoing_packet, str);
632 packet_put_raw(const void *buf, u_int len)
634 buffer_append(&active_state->outgoing_packet, buf, len);
638 packet_put_bignum(BIGNUM * value)
640 buffer_put_bignum(&active_state->outgoing_packet, value);
644 packet_put_bignum2(BIGNUM * value)
646 buffer_put_bignum2(&active_state->outgoing_packet, value);
649 #ifdef OPENSSL_HAS_ECC
651 packet_put_ecpoint(const EC_GROUP *curve, const EC_POINT *point)
653 buffer_put_ecpoint(&active_state->outgoing_packet, curve, point);
658 * Finalizes and sends the packet. If the encryption key has been set,
659 * encrypts the packet before sending.
671 * If using packet compression, compress the payload of the outgoing
674 if (active_state->packet_compression) {
675 buffer_clear(&active_state->compression_buffer);
677 buffer_consume(&active_state->outgoing_packet, 8);
679 buffer_append(&active_state->compression_buffer,
680 "\0\0\0\0\0\0\0\0", 8);
681 buffer_compress(&active_state->outgoing_packet,
682 &active_state->compression_buffer);
683 buffer_clear(&active_state->outgoing_packet);
684 buffer_append(&active_state->outgoing_packet,
685 buffer_ptr(&active_state->compression_buffer),
686 buffer_len(&active_state->compression_buffer));
688 /* Compute packet length without padding (add checksum, remove padding). */
689 len = buffer_len(&active_state->outgoing_packet) + 4 - 8;
691 /* Insert padding. Initialized to zero in packet_start1() */
692 padding = 8 - len % 8;
693 if (!active_state->send_context.plaintext) {
694 cp = buffer_ptr(&active_state->outgoing_packet);
695 for (i = 0; i < padding; i++) {
698 cp[7 - i] = rnd & 0xff;
702 buffer_consume(&active_state->outgoing_packet, 8 - padding);
704 /* Add check bytes. */
705 checksum = ssh_crc32(buffer_ptr(&active_state->outgoing_packet),
706 buffer_len(&active_state->outgoing_packet));
707 put_u32(buf, checksum);
708 buffer_append(&active_state->outgoing_packet, buf, 4);
711 fprintf(stderr, "packet_send plain: ");
712 buffer_dump(&active_state->outgoing_packet);
715 /* Append to output. */
717 buffer_append(&active_state->output, buf, 4);
718 cp = buffer_append_space(&active_state->output,
719 buffer_len(&active_state->outgoing_packet));
720 if (cipher_crypt(&active_state->send_context, 0, cp,
721 buffer_ptr(&active_state->outgoing_packet),
722 buffer_len(&active_state->outgoing_packet), 0, 0) != 0)
723 fatal("%s: cipher_crypt failed", __func__);
726 fprintf(stderr, "encrypted: ");
727 buffer_dump(&active_state->output);
729 active_state->p_send.packets++;
730 active_state->p_send.bytes += len +
731 buffer_len(&active_state->outgoing_packet);
732 buffer_clear(&active_state->outgoing_packet);
735 * Note that the packet is now only buffered in output. It won't be
736 * actually sent until packet_write_wait or packet_write_poll is
742 set_newkeys(int mode)
748 u_int64_t *max_blocks;
751 debug2("set_newkeys: mode %d", mode);
753 if (mode == MODE_OUT) {
754 cc = &active_state->send_context;
755 crypt_type = CIPHER_ENCRYPT;
756 active_state->p_send.packets = active_state->p_send.blocks = 0;
757 max_blocks = &active_state->max_blocks_out;
759 cc = &active_state->receive_context;
760 crypt_type = CIPHER_DECRYPT;
761 active_state->p_read.packets = active_state->p_read.blocks = 0;
762 max_blocks = &active_state->max_blocks_in;
764 if (active_state->newkeys[mode] != NULL) {
765 debug("set_newkeys: rekeying");
767 enc = &active_state->newkeys[mode]->enc;
768 mac = &active_state->newkeys[mode]->mac;
769 comp = &active_state->newkeys[mode]->comp;
771 explicit_bzero(enc->iv, enc->iv_len);
772 explicit_bzero(enc->key, enc->key_len);
773 explicit_bzero(mac->key, mac->key_len);
780 free(active_state->newkeys[mode]);
782 active_state->newkeys[mode] = kex_get_newkeys(mode);
783 if (active_state->newkeys[mode] == NULL)
784 fatal("newkeys: no keys for mode %d", mode);
785 enc = &active_state->newkeys[mode]->enc;
786 mac = &active_state->newkeys[mode]->mac;
787 comp = &active_state->newkeys[mode]->comp;
788 if (cipher_authlen(enc->cipher) == 0 && mac_init(mac) == 0)
790 DBG(debug("cipher_init_context: %d", mode));
791 cipher_init(cc, enc->cipher, enc->key, enc->key_len,
792 enc->iv, enc->iv_len, crypt_type);
793 /* Deleting the keys does not gain extra security */
794 /* explicit_bzero(enc->iv, enc->block_size);
795 explicit_bzero(enc->key, enc->key_len);
796 explicit_bzero(mac->key, mac->key_len); */
797 if ((comp->type == COMP_ZLIB ||
798 (comp->type == COMP_DELAYED &&
799 active_state->after_authentication)) && comp->enabled == 0) {
800 packet_init_compression();
801 if (mode == MODE_OUT)
802 buffer_compress_init_send(6);
804 buffer_compress_init_recv();
808 * The 2^(blocksize*2) limit is too expensive for 3DES,
809 * blowfish, etc, so enforce a 1GB limit for small blocksizes.
811 if (enc->block_size >= 16)
812 *max_blocks = (u_int64_t)1 << (enc->block_size*2);
814 *max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
815 if (active_state->rekey_limit)
816 *max_blocks = MIN(*max_blocks,
817 active_state->rekey_limit / enc->block_size);
821 * Delayed compression for SSH2 is enabled after authentication:
822 * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
823 * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
826 packet_enable_delayed_compress(void)
832 * Remember that we are past the authentication step, so rekeying
833 * with COMP_DELAYED will turn on compression immediately.
835 active_state->after_authentication = 1;
836 for (mode = 0; mode < MODE_MAX; mode++) {
837 /* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
838 if (active_state->newkeys[mode] == NULL)
840 comp = &active_state->newkeys[mode]->comp;
841 if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
842 packet_init_compression();
843 if (mode == MODE_OUT)
844 buffer_compress_init_send(6);
846 buffer_compress_init_recv();
853 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
856 packet_send2_wrapped(void)
858 u_char type, *cp, *macbuf = NULL;
859 u_char padlen, pad = 0;
860 u_int i, len, authlen = 0, aadlen = 0;
867 if (active_state->newkeys[MODE_OUT] != NULL) {
868 enc = &active_state->newkeys[MODE_OUT]->enc;
869 mac = &active_state->newkeys[MODE_OUT]->mac;
870 comp = &active_state->newkeys[MODE_OUT]->comp;
871 /* disable mac for authenticated encryption */
872 if ((authlen = cipher_authlen(enc->cipher)) != 0)
875 block_size = enc ? enc->block_size : 8;
876 aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
878 cp = buffer_ptr(&active_state->outgoing_packet);
882 fprintf(stderr, "plain: ");
883 buffer_dump(&active_state->outgoing_packet);
886 if (comp && comp->enabled) {
887 len = buffer_len(&active_state->outgoing_packet);
888 /* skip header, compress only payload */
889 buffer_consume(&active_state->outgoing_packet, 5);
890 buffer_clear(&active_state->compression_buffer);
891 buffer_compress(&active_state->outgoing_packet,
892 &active_state->compression_buffer);
893 buffer_clear(&active_state->outgoing_packet);
894 buffer_append(&active_state->outgoing_packet, "\0\0\0\0\0", 5);
895 buffer_append(&active_state->outgoing_packet,
896 buffer_ptr(&active_state->compression_buffer),
897 buffer_len(&active_state->compression_buffer));
898 DBG(debug("compression: raw %d compressed %d", len,
899 buffer_len(&active_state->outgoing_packet)));
902 /* sizeof (packet_len + pad_len + payload) */
903 len = buffer_len(&active_state->outgoing_packet);
906 * calc size of padding, alloc space, get random data,
907 * minimum padding is 4 bytes
909 len -= aadlen; /* packet length is not encrypted for EtM modes */
910 padlen = block_size - (len % block_size);
912 padlen += block_size;
913 if (active_state->extra_pad) {
914 /* will wrap if extra_pad+padlen > 255 */
915 active_state->extra_pad =
916 roundup(active_state->extra_pad, block_size);
917 pad = active_state->extra_pad -
918 ((len + padlen) % active_state->extra_pad);
919 debug3("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
920 pad, len, padlen, active_state->extra_pad);
922 active_state->extra_pad = 0;
924 cp = buffer_append_space(&active_state->outgoing_packet, padlen);
925 if (enc && !active_state->send_context.plaintext) {
927 for (i = 0; i < padlen; i++) {
935 explicit_bzero(cp, padlen);
937 /* sizeof (packet_len + pad_len + payload + padding) */
938 len = buffer_len(&active_state->outgoing_packet);
939 cp = buffer_ptr(&active_state->outgoing_packet);
940 /* packet_length includes payload, padding and padding length field */
941 put_u32(cp, len - 4);
943 DBG(debug("send: len %d (includes padlen %d, aadlen %d)",
944 len, padlen, aadlen));
946 /* compute MAC over seqnr and packet(length fields, payload, padding) */
947 if (mac && mac->enabled && !mac->etm) {
948 macbuf = mac_compute(mac, active_state->p_send.seqnr,
949 buffer_ptr(&active_state->outgoing_packet), len);
950 DBG(debug("done calc MAC out #%d", active_state->p_send.seqnr));
952 /* encrypt packet and append to output buffer. */
953 cp = buffer_append_space(&active_state->output, len + authlen);
954 if (cipher_crypt(&active_state->send_context, active_state->p_send.seqnr,
955 cp, buffer_ptr(&active_state->outgoing_packet),
956 len - aadlen, aadlen, authlen) != 0)
957 fatal("%s: cipher_crypt failed", __func__);
958 /* append unencrypted MAC */
959 if (mac && mac->enabled) {
961 /* EtM: compute mac over aadlen + cipher text */
962 macbuf = mac_compute(mac,
963 active_state->p_send.seqnr, cp, len);
964 DBG(debug("done calc MAC(EtM) out #%d",
965 active_state->p_send.seqnr));
967 buffer_append(&active_state->output, macbuf, mac->mac_len);
970 fprintf(stderr, "encrypted: ");
971 buffer_dump(&active_state->output);
973 /* increment sequence number for outgoing packets */
974 if (++active_state->p_send.seqnr == 0)
975 logit("outgoing seqnr wraps around");
976 if (++active_state->p_send.packets == 0)
977 if (!(datafellows & SSH_BUG_NOREKEY))
978 fatal("XXX too many packets with same key");
979 active_state->p_send.blocks += len / block_size;
980 active_state->p_send.bytes += len;
981 buffer_clear(&active_state->outgoing_packet);
983 if (type == SSH2_MSG_NEWKEYS)
984 set_newkeys(MODE_OUT);
985 else if (type == SSH2_MSG_USERAUTH_SUCCESS && active_state->server_side)
986 packet_enable_delayed_compress();
995 cp = buffer_ptr(&active_state->outgoing_packet);
998 /* during rekeying we can only send key exchange messages */
999 if (active_state->rekeying) {
1000 if ((type < SSH2_MSG_TRANSPORT_MIN) ||
1001 (type > SSH2_MSG_TRANSPORT_MAX) ||
1002 (type == SSH2_MSG_SERVICE_REQUEST) ||
1003 (type == SSH2_MSG_SERVICE_ACCEPT)) {
1004 debug("enqueue packet: %u", type);
1005 p = xcalloc(1, sizeof(*p));
1007 memcpy(&p->payload, &active_state->outgoing_packet,
1009 buffer_init(&active_state->outgoing_packet);
1010 TAILQ_INSERT_TAIL(&active_state->outgoing, p, next);
1015 /* rekeying starts with sending KEXINIT */
1016 if (type == SSH2_MSG_KEXINIT)
1017 active_state->rekeying = 1;
1019 packet_send2_wrapped();
1021 /* after a NEWKEYS message we can send the complete queue */
1022 if (type == SSH2_MSG_NEWKEYS) {
1023 active_state->rekeying = 0;
1024 active_state->rekey_time = monotime();
1025 while ((p = TAILQ_FIRST(&active_state->outgoing))) {
1027 debug("dequeue packet: %u", type);
1028 buffer_free(&active_state->outgoing_packet);
1029 memcpy(&active_state->outgoing_packet, &p->payload,
1031 TAILQ_REMOVE(&active_state->outgoing, p, next);
1033 packet_send2_wrapped();
1045 DBG(debug("packet_send done"));
1049 * Waits until a packet has been received, and returns its type. Note that
1050 * no other data is processed until this returns, so this function should not
1051 * be used during the interactive session.
1055 packet_read_seqnr(u_int32_t *seqnr_p)
1057 int type, len, ret, cont, ms_remain = 0;
1060 struct timeval timeout, start, *timeoutp = NULL;
1062 DBG(debug("packet_read()"));
1064 setp = (fd_set *)xcalloc(howmany(active_state->connection_in + 1,
1065 NFDBITS), sizeof(fd_mask));
1067 /* Since we are blocking, ensure that all written packets have been sent. */
1068 packet_write_wait();
1070 /* Stay in the loop until we have received a complete packet. */
1072 /* Try to read a packet from the buffer. */
1073 type = packet_read_poll_seqnr(seqnr_p);
1075 type == SSH_SMSG_SUCCESS
1076 || type == SSH_SMSG_FAILURE
1077 || type == SSH_CMSG_EOF
1078 || type == SSH_CMSG_EXIT_CONFIRMATION))
1080 /* If we got a packet, return it. */
1081 if (type != SSH_MSG_NONE) {
1086 * Otherwise, wait for some data to arrive, add it to the
1087 * buffer, and try again.
1089 memset(setp, 0, howmany(active_state->connection_in + 1,
1090 NFDBITS) * sizeof(fd_mask));
1091 FD_SET(active_state->connection_in, setp);
1093 if (active_state->packet_timeout_ms > 0) {
1094 ms_remain = active_state->packet_timeout_ms;
1095 timeoutp = &timeout;
1097 /* Wait for some data to arrive. */
1099 if (active_state->packet_timeout_ms != -1) {
1100 ms_to_timeval(&timeout, ms_remain);
1101 gettimeofday(&start, NULL);
1103 if ((ret = select(active_state->connection_in + 1, setp,
1104 NULL, NULL, timeoutp)) >= 0)
1106 if (errno != EAGAIN && errno != EINTR &&
1107 errno != EWOULDBLOCK)
1109 if (active_state->packet_timeout_ms == -1)
1111 ms_subtract_diff(&start, &ms_remain);
1112 if (ms_remain <= 0) {
1118 logit("Connection to %.200s timed out while "
1119 "waiting to read", get_remote_ipaddr());
1122 /* Read data from the socket. */
1125 len = roaming_read(active_state->connection_in, buf,
1126 sizeof(buf), &cont);
1127 } while (len == 0 && cont);
1129 logit("Connection closed by %.200s", get_remote_ipaddr());
1133 fatal("Read from socket failed: %.100s", strerror(errno));
1134 /* Append it to the buffer. */
1135 packet_process_incoming(buf, len);
1143 return packet_read_seqnr(NULL);
1147 * Waits until a packet has been received, verifies that its type matches
1148 * that given, and gives a fatal error and exits if there is a mismatch.
1152 packet_read_expect(int expected_type)
1156 type = packet_read();
1157 if (type != expected_type)
1158 packet_disconnect("Protocol error: expected packet type %d, got %d",
1159 expected_type, type);
1162 /* Checks if a full packet is available in the data received so far via
1163 * packet_process_incoming. If so, reads the packet; otherwise returns
1164 * SSH_MSG_NONE. This does not wait for data from the connection.
1166 * SSH_MSG_DISCONNECT is handled specially here. Also,
1167 * SSH_MSG_IGNORE messages are skipped by this function and are never returned
1172 packet_read_poll1(void)
1174 u_int len, padded_len;
1176 u_int checksum, stored_checksum;
1178 /* Check if input size is less than minimum packet size. */
1179 if (buffer_len(&active_state->input) < 4 + 8)
1180 return SSH_MSG_NONE;
1181 /* Get length of incoming packet. */
1182 cp = buffer_ptr(&active_state->input);
1184 if (len < 1 + 2 + 2 || len > 256 * 1024)
1185 packet_disconnect("Bad packet length %u.", len);
1186 padded_len = (len + 8) & ~7;
1188 /* Check if the packet has been entirely received. */
1189 if (buffer_len(&active_state->input) < 4 + padded_len)
1190 return SSH_MSG_NONE;
1192 /* The entire packet is in buffer. */
1194 /* Consume packet length. */
1195 buffer_consume(&active_state->input, 4);
1198 * Cryptographic attack detector for ssh
1199 * (C)1998 CORE-SDI, Buenos Aires Argentina
1200 * Ariel Futoransky(futo@core-sdi.com)
1202 if (!active_state->receive_context.plaintext) {
1203 switch (detect_attack(buffer_ptr(&active_state->input),
1205 case DEATTACK_DETECTED:
1206 packet_disconnect("crc32 compensation attack: "
1207 "network attack detected");
1208 case DEATTACK_DOS_DETECTED:
1209 packet_disconnect("deattack denial of "
1210 "service detected");
1214 /* Decrypt data to incoming_packet. */
1215 buffer_clear(&active_state->incoming_packet);
1216 cp = buffer_append_space(&active_state->incoming_packet, padded_len);
1217 if (cipher_crypt(&active_state->receive_context, 0, cp,
1218 buffer_ptr(&active_state->input), padded_len, 0, 0) != 0)
1219 fatal("%s: cipher_crypt failed", __func__);
1221 buffer_consume(&active_state->input, padded_len);
1224 fprintf(stderr, "read_poll plain: ");
1225 buffer_dump(&active_state->incoming_packet);
1228 /* Compute packet checksum. */
1229 checksum = ssh_crc32(buffer_ptr(&active_state->incoming_packet),
1230 buffer_len(&active_state->incoming_packet) - 4);
1233 buffer_consume(&active_state->incoming_packet, 8 - len % 8);
1235 /* Test check bytes. */
1236 if (len != buffer_len(&active_state->incoming_packet))
1237 packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
1238 len, buffer_len(&active_state->incoming_packet));
1240 cp = (u_char *)buffer_ptr(&active_state->incoming_packet) + len - 4;
1241 stored_checksum = get_u32(cp);
1242 if (checksum != stored_checksum)
1243 packet_disconnect("Corrupted check bytes on input.");
1244 buffer_consume_end(&active_state->incoming_packet, 4);
1246 if (active_state->packet_compression) {
1247 buffer_clear(&active_state->compression_buffer);
1248 buffer_uncompress(&active_state->incoming_packet,
1249 &active_state->compression_buffer);
1250 buffer_clear(&active_state->incoming_packet);
1251 buffer_append(&active_state->incoming_packet,
1252 buffer_ptr(&active_state->compression_buffer),
1253 buffer_len(&active_state->compression_buffer));
1255 active_state->p_read.packets++;
1256 active_state->p_read.bytes += padded_len + 4;
1257 type = buffer_get_char(&active_state->incoming_packet);
1258 if (type < SSH_MSG_MIN || type > SSH_MSG_MAX)
1259 packet_disconnect("Invalid ssh1 packet type: %d", type);
1264 packet_read_poll2(u_int32_t *seqnr_p)
1267 u_char *macbuf = NULL, *cp, type;
1268 u_int maclen, authlen = 0, aadlen = 0, block_size;
1273 if (active_state->packet_discard)
1274 return SSH_MSG_NONE;
1276 if (active_state->newkeys[MODE_IN] != NULL) {
1277 enc = &active_state->newkeys[MODE_IN]->enc;
1278 mac = &active_state->newkeys[MODE_IN]->mac;
1279 comp = &active_state->newkeys[MODE_IN]->comp;
1280 /* disable mac for authenticated encryption */
1281 if ((authlen = cipher_authlen(enc->cipher)) != 0)
1284 maclen = mac && mac->enabled ? mac->mac_len : 0;
1285 block_size = enc ? enc->block_size : 8;
1286 aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
1288 if (aadlen && active_state->packlen == 0) {
1289 if (cipher_get_length(&active_state->receive_context,
1290 &active_state->packlen,
1291 active_state->p_read.seqnr,
1292 buffer_ptr(&active_state->input),
1293 buffer_len(&active_state->input)) != 0)
1294 return SSH_MSG_NONE;
1295 if (active_state->packlen < 1 + 4 ||
1296 active_state->packlen > PACKET_MAX_SIZE) {
1298 buffer_dump(&active_state->input);
1300 logit("Bad packet length %u.", active_state->packlen);
1301 packet_disconnect("Packet corrupt");
1303 buffer_clear(&active_state->incoming_packet);
1304 } else if (active_state->packlen == 0) {
1306 * check if input size is less than the cipher block size,
1307 * decrypt first block and extract length of incoming packet
1309 if (buffer_len(&active_state->input) < block_size)
1310 return SSH_MSG_NONE;
1311 buffer_clear(&active_state->incoming_packet);
1312 cp = buffer_append_space(&active_state->incoming_packet,
1314 if (cipher_crypt(&active_state->receive_context,
1315 active_state->p_read.seqnr, cp,
1316 buffer_ptr(&active_state->input), block_size, 0, 0) != 0)
1317 fatal("Decryption integrity check failed");
1318 cp = buffer_ptr(&active_state->incoming_packet);
1320 active_state->packlen = get_u32(cp);
1321 if (active_state->packlen < 1 + 4 ||
1322 active_state->packlen > PACKET_MAX_SIZE) {
1324 buffer_dump(&active_state->incoming_packet);
1326 logit("Bad packet length %u.", active_state->packlen);
1327 packet_start_discard(enc, mac, active_state->packlen,
1329 return SSH_MSG_NONE;
1331 buffer_consume(&active_state->input, block_size);
1333 DBG(debug("input: packet len %u", active_state->packlen+4));
1335 /* only the payload is encrypted */
1336 need = active_state->packlen;
1339 * the payload size and the payload are encrypted, but we
1340 * have a partial packet of block_size bytes
1342 need = 4 + active_state->packlen - block_size;
1344 DBG(debug("partial packet: block %d, need %d, maclen %d, authlen %d,"
1345 " aadlen %d", block_size, need, maclen, authlen, aadlen));
1346 if (need % block_size != 0) {
1347 logit("padding error: need %d block %d mod %d",
1348 need, block_size, need % block_size);
1349 packet_start_discard(enc, mac, active_state->packlen,
1350 PACKET_MAX_SIZE - block_size);
1351 return SSH_MSG_NONE;
1354 * check if the entire packet has been received and
1355 * decrypt into incoming_packet:
1356 * 'aadlen' bytes are unencrypted, but authenticated.
1357 * 'need' bytes are encrypted, followed by either
1358 * 'authlen' bytes of authentication tag or
1359 * 'maclen' bytes of message authentication code.
1361 if (buffer_len(&active_state->input) < aadlen + need + authlen + maclen)
1362 return SSH_MSG_NONE;
1364 fprintf(stderr, "read_poll enc/full: ");
1365 buffer_dump(&active_state->input);
1367 /* EtM: compute mac over encrypted input */
1368 if (mac && mac->enabled && mac->etm)
1369 macbuf = mac_compute(mac, active_state->p_read.seqnr,
1370 buffer_ptr(&active_state->input), aadlen + need);
1371 cp = buffer_append_space(&active_state->incoming_packet, aadlen + need);
1372 if (cipher_crypt(&active_state->receive_context,
1373 active_state->p_read.seqnr, cp,
1374 buffer_ptr(&active_state->input), need, aadlen, authlen) != 0)
1375 fatal("Decryption integrity check failed");
1376 buffer_consume(&active_state->input, aadlen + need + authlen);
1378 * compute MAC over seqnr and packet,
1379 * increment sequence number for incoming packet
1381 if (mac && mac->enabled) {
1383 macbuf = mac_compute(mac, active_state->p_read.seqnr,
1384 buffer_ptr(&active_state->incoming_packet),
1385 buffer_len(&active_state->incoming_packet));
1386 if (timingsafe_bcmp(macbuf, buffer_ptr(&active_state->input),
1387 mac->mac_len) != 0) {
1388 logit("Corrupted MAC on input.");
1389 if (need > PACKET_MAX_SIZE)
1390 fatal("internal error need %d", need);
1391 packet_start_discard(enc, mac, active_state->packlen,
1392 PACKET_MAX_SIZE - need);
1393 return SSH_MSG_NONE;
1396 DBG(debug("MAC #%d ok", active_state->p_read.seqnr));
1397 buffer_consume(&active_state->input, mac->mac_len);
1399 /* XXX now it's safe to use fatal/packet_disconnect */
1400 if (seqnr_p != NULL)
1401 *seqnr_p = active_state->p_read.seqnr;
1402 if (++active_state->p_read.seqnr == 0)
1403 logit("incoming seqnr wraps around");
1404 if (++active_state->p_read.packets == 0)
1405 if (!(datafellows & SSH_BUG_NOREKEY))
1406 fatal("XXX too many packets with same key");
1407 active_state->p_read.blocks += (active_state->packlen + 4) / block_size;
1408 active_state->p_read.bytes += active_state->packlen + 4;
1411 cp = buffer_ptr(&active_state->incoming_packet);
1413 DBG(debug("input: padlen %d", padlen));
1415 packet_disconnect("Corrupted padlen %d on input.", padlen);
1417 /* skip packet size + padlen, discard padding */
1418 buffer_consume(&active_state->incoming_packet, 4 + 1);
1419 buffer_consume_end(&active_state->incoming_packet, padlen);
1421 DBG(debug("input: len before de-compress %d",
1422 buffer_len(&active_state->incoming_packet)));
1423 if (comp && comp->enabled) {
1424 buffer_clear(&active_state->compression_buffer);
1425 buffer_uncompress(&active_state->incoming_packet,
1426 &active_state->compression_buffer);
1427 buffer_clear(&active_state->incoming_packet);
1428 buffer_append(&active_state->incoming_packet,
1429 buffer_ptr(&active_state->compression_buffer),
1430 buffer_len(&active_state->compression_buffer));
1431 DBG(debug("input: len after de-compress %d",
1432 buffer_len(&active_state->incoming_packet)));
1435 * get packet type, implies consume.
1436 * return length of payload (without type field)
1438 type = buffer_get_char(&active_state->incoming_packet);
1439 if (type < SSH2_MSG_MIN || type >= SSH2_MSG_LOCAL_MIN)
1440 packet_disconnect("Invalid ssh2 packet type: %d", type);
1441 if (type == SSH2_MSG_NEWKEYS)
1442 set_newkeys(MODE_IN);
1443 else if (type == SSH2_MSG_USERAUTH_SUCCESS &&
1444 !active_state->server_side)
1445 packet_enable_delayed_compress();
1447 fprintf(stderr, "read/plain[%d]:\r\n", type);
1448 buffer_dump(&active_state->incoming_packet);
1450 /* reset for next packet */
1451 active_state->packlen = 0;
1456 packet_read_poll_seqnr(u_int32_t *seqnr_p)
1458 u_int reason, seqnr;
1464 type = packet_read_poll2(seqnr_p);
1466 active_state->keep_alive_timeouts = 0;
1467 DBG(debug("received packet type %d", type));
1470 case SSH2_MSG_IGNORE:
1471 debug3("Received SSH2_MSG_IGNORE");
1473 case SSH2_MSG_DEBUG:
1475 msg = packet_get_string(NULL);
1476 debug("Remote: %.900s", msg);
1478 msg = packet_get_string(NULL);
1481 case SSH2_MSG_DISCONNECT:
1482 reason = packet_get_int();
1483 msg = packet_get_string(NULL);
1484 /* Ignore normal client exit notifications */
1485 do_log2(active_state->server_side &&
1486 reason == SSH2_DISCONNECT_BY_APPLICATION ?
1487 SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_ERROR,
1488 "Received disconnect from %s: %u: %.400s",
1489 get_remote_ipaddr(), reason, msg);
1493 case SSH2_MSG_UNIMPLEMENTED:
1494 seqnr = packet_get_int();
1495 debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1502 type = packet_read_poll1();
1505 return SSH_MSG_NONE;
1506 case SSH_MSG_IGNORE:
1509 msg = packet_get_string(NULL);
1510 debug("Remote: %.900s", msg);
1513 case SSH_MSG_DISCONNECT:
1514 msg = packet_get_string(NULL);
1515 logit("Received disconnect from %s: %.400s",
1516 get_remote_ipaddr(), msg);
1520 DBG(debug("received packet type %d", type));
1528 * Buffers the given amount of input characters. This is intended to be used
1529 * together with packet_read_poll.
1533 packet_process_incoming(const char *buf, u_int len)
1535 if (active_state->packet_discard) {
1536 active_state->keep_alive_timeouts = 0; /* ?? */
1537 if (len >= active_state->packet_discard)
1538 packet_stop_discard();
1539 active_state->packet_discard -= len;
1542 buffer_append(&active_state->input, buf, len);
1545 /* Returns a character from the packet. */
1548 packet_get_char(void)
1552 buffer_get(&active_state->incoming_packet, &ch, 1);
1556 /* Returns an integer from the packet data. */
1559 packet_get_int(void)
1561 return buffer_get_int(&active_state->incoming_packet);
1564 /* Returns an 64 bit integer from the packet data. */
1567 packet_get_int64(void)
1569 return buffer_get_int64(&active_state->incoming_packet);
1573 * Returns an arbitrary precision integer from the packet data. The integer
1574 * must have been initialized before this call.
1578 packet_get_bignum(BIGNUM * value)
1580 buffer_get_bignum(&active_state->incoming_packet, value);
1584 packet_get_bignum2(BIGNUM * value)
1586 buffer_get_bignum2(&active_state->incoming_packet, value);
1589 #ifdef OPENSSL_HAS_ECC
1591 packet_get_ecpoint(const EC_GROUP *curve, EC_POINT *point)
1593 buffer_get_ecpoint(&active_state->incoming_packet, curve, point);
1598 packet_get_raw(u_int *length_ptr)
1600 u_int bytes = buffer_len(&active_state->incoming_packet);
1602 if (length_ptr != NULL)
1603 *length_ptr = bytes;
1604 return buffer_ptr(&active_state->incoming_packet);
1608 packet_remaining(void)
1610 return buffer_len(&active_state->incoming_packet);
1614 * Returns a string from the packet data. The string is allocated using
1615 * xmalloc; it is the responsibility of the calling program to free it when
1616 * no longer needed. The length_ptr argument may be NULL, or point to an
1617 * integer into which the length of the string is stored.
1621 packet_get_string(u_int *length_ptr)
1623 return buffer_get_string(&active_state->incoming_packet, length_ptr);
1627 packet_get_string_ptr(u_int *length_ptr)
1629 return buffer_get_string_ptr(&active_state->incoming_packet, length_ptr);
1632 /* Ensures the returned string has no embedded \0 characters in it. */
1634 packet_get_cstring(u_int *length_ptr)
1636 return buffer_get_cstring(&active_state->incoming_packet, length_ptr);
1640 * Sends a diagnostic message from the server to the client. This message
1641 * can be sent at any time (but not while constructing another message). The
1642 * message is printed immediately, but only if the client is being executed
1643 * in verbose mode. These messages are primarily intended to ease debugging
1644 * authentication problems. The length of the formatted message must not
1645 * exceed 1024 bytes. This will automatically call packet_write_wait.
1649 packet_send_debug(const char *fmt,...)
1654 if (compat20 && (datafellows & SSH_BUG_DEBUG))
1657 va_start(args, fmt);
1658 vsnprintf(buf, sizeof(buf), fmt, args);
1662 packet_start(SSH2_MSG_DEBUG);
1663 packet_put_char(0); /* bool: always display */
1664 packet_put_cstring(buf);
1665 packet_put_cstring("");
1667 packet_start(SSH_MSG_DEBUG);
1668 packet_put_cstring(buf);
1671 packet_write_wait();
1675 * Logs the error plus constructs and sends a disconnect packet, closes the
1676 * connection, and exits. This function never returns. The error message
1677 * should not contain a newline. The length of the formatted message must
1678 * not exceed 1024 bytes.
1682 packet_disconnect(const char *fmt,...)
1686 static int disconnecting = 0;
1688 if (disconnecting) /* Guard against recursive invocations. */
1689 fatal("packet_disconnect called recursively.");
1693 * Format the message. Note that the caller must make sure the
1694 * message is of limited size.
1696 va_start(args, fmt);
1697 vsnprintf(buf, sizeof(buf), fmt, args);
1700 /* Display the error locally */
1701 logit("Disconnecting: %.100s", buf);
1703 /* Send the disconnect message to the other side, and wait for it to get sent. */
1705 packet_start(SSH2_MSG_DISCONNECT);
1706 packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1707 packet_put_cstring(buf);
1708 packet_put_cstring("");
1710 packet_start(SSH_MSG_DISCONNECT);
1711 packet_put_cstring(buf);
1714 packet_write_wait();
1716 /* Stop listening for connections. */
1717 channel_close_all();
1719 /* Close the connection. */
1724 /* Checks if there is any buffered output, and tries to write some of the output. */
1727 packet_write_poll(void)
1729 int len = buffer_len(&active_state->output);
1734 len = roaming_write(active_state->connection_out,
1735 buffer_ptr(&active_state->output), len, &cont);
1737 if (errno == EINTR || errno == EAGAIN ||
1738 errno == EWOULDBLOCK)
1740 fatal("Write failed: %.100s", strerror(errno));
1742 if (len == 0 && !cont)
1743 fatal("Write connection closed");
1744 buffer_consume(&active_state->output, len);
1749 * Calls packet_write_poll repeatedly until all pending output data has been
1754 packet_write_wait(void)
1757 int ret, ms_remain = 0;
1758 struct timeval start, timeout, *timeoutp = NULL;
1760 setp = (fd_set *)xcalloc(howmany(active_state->connection_out + 1,
1761 NFDBITS), sizeof(fd_mask));
1762 packet_write_poll();
1763 while (packet_have_data_to_write()) {
1764 memset(setp, 0, howmany(active_state->connection_out + 1,
1765 NFDBITS) * sizeof(fd_mask));
1766 FD_SET(active_state->connection_out, setp);
1768 if (active_state->packet_timeout_ms > 0) {
1769 ms_remain = active_state->packet_timeout_ms;
1770 timeoutp = &timeout;
1773 if (active_state->packet_timeout_ms != -1) {
1774 ms_to_timeval(&timeout, ms_remain);
1775 gettimeofday(&start, NULL);
1777 if ((ret = select(active_state->connection_out + 1,
1778 NULL, setp, NULL, timeoutp)) >= 0)
1780 if (errno != EAGAIN && errno != EINTR &&
1781 errno != EWOULDBLOCK)
1783 if (active_state->packet_timeout_ms == -1)
1785 ms_subtract_diff(&start, &ms_remain);
1786 if (ms_remain <= 0) {
1792 logit("Connection to %.200s timed out while "
1793 "waiting to write", get_remote_ipaddr());
1796 packet_write_poll();
1801 /* Returns true if there is buffered data to write to the connection. */
1804 packet_have_data_to_write(void)
1806 return buffer_len(&active_state->output) != 0;
1809 /* Returns true if there is not too much data to write to the connection. */
1812 packet_not_very_much_data_to_write(void)
1814 if (active_state->interactive_mode)
1815 return buffer_len(&active_state->output) < 16384;
1817 return buffer_len(&active_state->output) < 128 * 1024;
1821 packet_set_tos(int tos)
1823 #ifndef IP_TOS_IS_BROKEN
1824 if (!packet_connection_is_on_socket())
1826 switch (packet_connection_af()) {
1829 debug3("%s: set IP_TOS 0x%02x", __func__, tos);
1830 if (setsockopt(active_state->connection_in,
1831 IPPROTO_IP, IP_TOS, &tos, sizeof(tos)) < 0)
1832 error("setsockopt IP_TOS %d: %.100s:",
1833 tos, strerror(errno));
1835 # endif /* IP_TOS */
1838 debug3("%s: set IPV6_TCLASS 0x%02x", __func__, tos);
1839 if (setsockopt(active_state->connection_in,
1840 IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof(tos)) < 0)
1841 error("setsockopt IPV6_TCLASS %d: %.100s:",
1842 tos, strerror(errno));
1844 # endif /* IPV6_TCLASS */
1846 #endif /* IP_TOS_IS_BROKEN */
1849 /* Informs that the current session is interactive. Sets IP flags for that. */
1852 packet_set_interactive(int interactive, int qos_interactive, int qos_bulk)
1854 if (active_state->set_interactive_called)
1856 active_state->set_interactive_called = 1;
1858 /* Record that we are in interactive mode. */
1859 active_state->interactive_mode = interactive;
1861 /* Only set socket options if using a socket. */
1862 if (!packet_connection_is_on_socket())
1864 set_nodelay(active_state->connection_in);
1865 packet_set_tos(interactive ? qos_interactive : qos_bulk);
1868 /* Returns true if the current connection is interactive. */
1871 packet_is_interactive(void)
1873 return active_state->interactive_mode;
1877 packet_set_maxsize(u_int s)
1879 if (active_state->set_maxsize_called) {
1880 logit("packet_set_maxsize: called twice: old %d new %d",
1881 active_state->max_packet_size, s);
1884 if (s < 4 * 1024 || s > 1024 * 1024) {
1885 logit("packet_set_maxsize: bad size %d", s);
1888 active_state->set_maxsize_called = 1;
1889 debug("packet_set_maxsize: setting to %d", s);
1890 active_state->max_packet_size = s;
1895 packet_inc_alive_timeouts(void)
1897 return ++active_state->keep_alive_timeouts;
1901 packet_set_alive_timeouts(int ka)
1903 active_state->keep_alive_timeouts = ka;
1907 packet_get_maxsize(void)
1909 return active_state->max_packet_size;
1912 /* roundup current message to pad bytes */
1914 packet_add_padding(u_char pad)
1916 active_state->extra_pad = pad;
1920 * 9.2. Ignored Data Message
1922 * byte SSH_MSG_IGNORE
1925 * All implementations MUST understand (and ignore) this message at any
1926 * time (after receiving the protocol version). No implementation is
1927 * required to send them. This message can be used as an additional
1928 * protection measure against advanced traffic analysis techniques.
1931 packet_send_ignore(int nbytes)
1936 packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1937 packet_put_int(nbytes);
1938 for (i = 0; i < nbytes; i++) {
1941 packet_put_char((u_char)rnd & 0xff);
1946 #ifdef NONE_CIPHER_ENABLED
1948 packet_request_rekeying(void)
1950 rekey_requested = 1;
1954 #define MAX_PACKETS (1U<<31)
1956 packet_need_rekeying(void)
1958 if (datafellows & SSH_BUG_NOREKEY)
1960 #ifdef NONE_CIPHER_ENABLED
1961 if (rekey_requested == 1) {
1962 rekey_requested = 0;
1967 (active_state->p_send.packets > MAX_PACKETS) ||
1968 (active_state->p_read.packets > MAX_PACKETS) ||
1969 (active_state->max_blocks_out &&
1970 (active_state->p_send.blocks > active_state->max_blocks_out)) ||
1971 (active_state->max_blocks_in &&
1972 (active_state->p_read.blocks > active_state->max_blocks_in)) ||
1973 (active_state->rekey_interval != 0 && active_state->rekey_time +
1974 active_state->rekey_interval <= monotime());
1978 packet_set_rekey_limits(u_int32_t bytes, time_t seconds)
1980 debug3("rekey after %lld bytes, %d seconds", (long long)bytes,
1982 active_state->rekey_limit = bytes;
1983 active_state->rekey_interval = seconds;
1985 * We set the time here so that in post-auth privsep slave we count
1986 * from the completion of the authentication.
1988 active_state->rekey_time = monotime();
1992 packet_get_rekey_timeout(void)
1996 seconds = active_state->rekey_time + active_state->rekey_interval -
1998 return (seconds <= 0 ? 1 : seconds);
2002 packet_set_server(void)
2004 active_state->server_side = 1;
2008 packet_set_authenticated(void)
2010 active_state->after_authentication = 1;
2014 packet_get_input(void)
2016 return (void *)&active_state->input;
2020 packet_get_output(void)
2022 return (void *)&active_state->output;
2026 packet_get_newkeys(int mode)
2028 return (void *)active_state->newkeys[mode];
2032 * Save the state for the real connection, and use a separate state when
2033 * resuming a suspended connection.
2036 packet_backup_state(void)
2038 struct session_state *tmp;
2040 close(active_state->connection_in);
2041 active_state->connection_in = -1;
2042 close(active_state->connection_out);
2043 active_state->connection_out = -1;
2047 tmp = alloc_session_state();
2048 backup_state = active_state;
2053 * Swap in the old state when resuming a connecion.
2056 packet_restore_state(void)
2058 struct session_state *tmp;
2063 backup_state = active_state;
2065 active_state->connection_in = backup_state->connection_in;
2066 backup_state->connection_in = -1;
2067 active_state->connection_out = backup_state->connection_out;
2068 backup_state->connection_out = -1;
2069 len = buffer_len(&backup_state->input);
2071 buf = buffer_ptr(&backup_state->input);
2072 buffer_append(&active_state->input, buf, len);
2073 buffer_clear(&backup_state->input);
2074 add_recv_bytes(len);
2078 #ifdef NONE_CIPHER_ENABLED
2080 packet_get_authentication_state(void)
2082 return (active_state->after_authentication);