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.
42 #include <sys/types.h>
43 #include "openbsd-compat/sys-queue.h"
44 #include <sys/param.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>
89 #define PACKET_MAX_SIZE (256 * 1024)
99 TAILQ_ENTRY(packet) next;
104 struct session_state {
106 * This variable contains the file descriptors used for
107 * communicating with the other side. connection_in is used for
108 * reading; connection_out for writing. These can be the same
109 * descriptor, in which case it is assumed to be a socket.
114 /* Protocol flags for the remote side. */
115 u_int remote_protocol_flags;
117 /* Encryption context for receiving data. Only used for decryption. */
118 CipherContext receive_context;
120 /* Encryption context for sending data. Only used for encryption. */
121 CipherContext send_context;
123 /* Buffer for raw input data from the socket. */
126 /* Buffer for raw output data going to the socket. */
129 /* Buffer for the partial outgoing packet being constructed. */
130 Buffer outgoing_packet;
132 /* Buffer for the incoming packet currently being processed. */
133 Buffer incoming_packet;
135 /* Scratch buffer for packet compression/decompression. */
136 Buffer compression_buffer;
137 int compression_buffer_ready;
140 * Flag indicating whether packet compression/decompression is
143 int packet_compression;
145 /* default maximum packet size */
146 u_int max_packet_size;
148 /* Flag indicating whether this module has been initialized. */
151 /* Set to true if the connection is interactive. */
152 int interactive_mode;
154 /* Set to true if we are the server side. */
157 /* Set to true if we are authenticated. */
158 int after_authentication;
160 int keep_alive_timeouts;
162 /* The maximum time that we will wait to send or receive a packet */
163 int packet_timeout_ms;
165 /* Session key information for Encryption and MAC */
166 Newkeys *newkeys[MODE_MAX];
167 struct packet_state p_read, p_send;
169 /* Volume-based rekeying */
170 u_int64_t max_blocks_in, max_blocks_out;
171 u_int32_t rekey_limit;
173 /* Time-based rekeying */
174 time_t rekey_interval; /* how often in seconds */
175 time_t rekey_time; /* time of last rekeying */
177 /* Session key for protocol v1 */
178 u_char ssh1_key[SSH_SESSION_KEY_LENGTH];
181 /* roundup current message to extra_pad bytes */
184 /* XXX discard incoming data after MAC error */
185 u_int packet_discard;
186 Mac *packet_discard_mac;
188 /* Used in packet_read_poll2() */
191 /* Used in packet_send2 */
194 /* Used in packet_set_interactive */
195 int set_interactive_called;
197 /* Used in packet_set_maxsize */
198 int set_maxsize_called;
200 TAILQ_HEAD(, packet) outgoing;
203 static struct session_state *active_state, *backup_state;
204 #ifdef NONE_CIPHER_ENABLED
205 static int rekey_requested = 0;
208 static struct session_state *
209 alloc_session_state(void)
211 struct session_state *s = xcalloc(1, sizeof(*s));
213 s->connection_in = -1;
214 s->connection_out = -1;
215 s->max_packet_size = 32768;
216 s->packet_timeout_ms = -1;
221 * Sets the descriptors used for communication. Disables encryption until
222 * packet_set_encryption_key is called.
225 packet_set_connection(int fd_in, int fd_out)
227 const Cipher *none = cipher_by_name("none");
230 fatal("packet_set_connection: cannot load cipher 'none'");
231 if (active_state == NULL)
232 active_state = alloc_session_state();
233 active_state->connection_in = fd_in;
234 active_state->connection_out = fd_out;
235 cipher_init(&active_state->send_context, none, (const u_char *)"",
236 0, NULL, 0, CIPHER_ENCRYPT);
237 cipher_init(&active_state->receive_context, none, (const u_char *)"",
238 0, NULL, 0, CIPHER_DECRYPT);
239 active_state->newkeys[MODE_IN] = active_state->newkeys[MODE_OUT] = NULL;
240 if (!active_state->initialized) {
241 active_state->initialized = 1;
242 buffer_init(&active_state->input);
243 buffer_init(&active_state->output);
244 buffer_init(&active_state->outgoing_packet);
245 buffer_init(&active_state->incoming_packet);
246 TAILQ_INIT(&active_state->outgoing);
247 active_state->p_send.packets = active_state->p_read.packets = 0;
252 packet_set_timeout(int timeout, int count)
254 if (timeout <= 0 || count <= 0) {
255 active_state->packet_timeout_ms = -1;
258 if ((INT_MAX / 1000) / count < timeout)
259 active_state->packet_timeout_ms = INT_MAX;
261 active_state->packet_timeout_ms = timeout * count * 1000;
265 packet_stop_discard(void)
267 if (active_state->packet_discard_mac) {
270 memset(buf, 'a', sizeof(buf));
271 while (buffer_len(&active_state->incoming_packet) <
273 buffer_append(&active_state->incoming_packet, buf,
275 (void) mac_compute(active_state->packet_discard_mac,
276 active_state->p_read.seqnr,
277 buffer_ptr(&active_state->incoming_packet),
280 logit("Finished discarding for %.200s", get_remote_ipaddr());
285 packet_start_discard(Enc *enc, Mac *mac, u_int packet_length, u_int discard)
287 if (enc == NULL || !cipher_is_cbc(enc->cipher) || (mac && mac->etm))
288 packet_disconnect("Packet corrupt");
289 if (packet_length != PACKET_MAX_SIZE && mac && mac->enabled)
290 active_state->packet_discard_mac = mac;
291 if (buffer_len(&active_state->input) >= discard)
292 packet_stop_discard();
293 active_state->packet_discard = discard -
294 buffer_len(&active_state->input);
297 /* Returns 1 if remote host is connected via socket, 0 if not. */
300 packet_connection_is_on_socket(void)
302 struct sockaddr_storage from, to;
303 socklen_t fromlen, tolen;
305 /* filedescriptors in and out are the same, so it's a socket */
306 if (active_state->connection_in == active_state->connection_out)
308 fromlen = sizeof(from);
309 memset(&from, 0, sizeof(from));
310 if (getpeername(active_state->connection_in, (struct sockaddr *)&from,
314 memset(&to, 0, sizeof(to));
315 if (getpeername(active_state->connection_out, (struct sockaddr *)&to,
318 if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
320 if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
326 * Exports an IV from the CipherContext required to export the key
327 * state back from the unprivileged child to the privileged parent
332 packet_get_keyiv(int mode, u_char *iv, u_int len)
336 if (mode == MODE_OUT)
337 cc = &active_state->send_context;
339 cc = &active_state->receive_context;
341 cipher_get_keyiv(cc, iv, len);
345 packet_get_keycontext(int mode, u_char *dat)
349 if (mode == MODE_OUT)
350 cc = &active_state->send_context;
352 cc = &active_state->receive_context;
354 return (cipher_get_keycontext(cc, dat));
358 packet_set_keycontext(int mode, u_char *dat)
362 if (mode == MODE_OUT)
363 cc = &active_state->send_context;
365 cc = &active_state->receive_context;
367 cipher_set_keycontext(cc, dat);
371 packet_get_keyiv_len(int mode)
375 if (mode == MODE_OUT)
376 cc = &active_state->send_context;
378 cc = &active_state->receive_context;
380 return (cipher_get_keyiv_len(cc));
384 packet_set_iv(int mode, u_char *dat)
388 if (mode == MODE_OUT)
389 cc = &active_state->send_context;
391 cc = &active_state->receive_context;
393 cipher_set_keyiv(cc, dat);
397 packet_get_ssh1_cipher(void)
399 return (cipher_get_number(active_state->receive_context.cipher));
403 packet_get_state(int mode, u_int32_t *seqnr, u_int64_t *blocks,
404 u_int32_t *packets, u_int64_t *bytes)
406 struct packet_state *state;
408 state = (mode == MODE_IN) ?
409 &active_state->p_read : &active_state->p_send;
411 *seqnr = state->seqnr;
413 *blocks = state->blocks;
415 *packets = state->packets;
417 *bytes = state->bytes;
421 packet_set_state(int mode, u_int32_t seqnr, u_int64_t blocks, u_int32_t packets,
424 struct packet_state *state;
426 state = (mode == MODE_IN) ?
427 &active_state->p_read : &active_state->p_send;
428 state->seqnr = seqnr;
429 state->blocks = blocks;
430 state->packets = packets;
431 state->bytes = bytes;
435 packet_connection_af(void)
437 struct sockaddr_storage to;
438 socklen_t tolen = sizeof(to);
440 memset(&to, 0, sizeof(to));
441 if (getsockname(active_state->connection_out, (struct sockaddr *)&to,
445 if (to.ss_family == AF_INET6 &&
446 IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&to)->sin6_addr))
452 /* Sets the connection into non-blocking mode. */
455 packet_set_nonblocking(void)
457 /* Set the socket into non-blocking mode. */
458 set_nonblock(active_state->connection_in);
460 if (active_state->connection_out != active_state->connection_in)
461 set_nonblock(active_state->connection_out);
464 /* Returns the socket used for reading. */
467 packet_get_connection_in(void)
469 return active_state->connection_in;
472 /* Returns the descriptor used for writing. */
475 packet_get_connection_out(void)
477 return active_state->connection_out;
480 /* Closes the connection and clears and frees internal data structures. */
485 if (!active_state->initialized)
487 active_state->initialized = 0;
488 if (active_state->connection_in == active_state->connection_out) {
489 shutdown(active_state->connection_out, SHUT_RDWR);
490 close(active_state->connection_out);
492 close(active_state->connection_in);
493 close(active_state->connection_out);
495 buffer_free(&active_state->input);
496 buffer_free(&active_state->output);
497 buffer_free(&active_state->outgoing_packet);
498 buffer_free(&active_state->incoming_packet);
499 if (active_state->compression_buffer_ready) {
500 buffer_free(&active_state->compression_buffer);
501 buffer_compress_uninit();
503 cipher_cleanup(&active_state->send_context);
504 cipher_cleanup(&active_state->receive_context);
507 /* Sets remote side protocol flags. */
510 packet_set_protocol_flags(u_int protocol_flags)
512 active_state->remote_protocol_flags = protocol_flags;
515 /* Returns the remote protocol flags set earlier by the above function. */
518 packet_get_protocol_flags(void)
520 return active_state->remote_protocol_flags;
524 * Starts packet compression from the next packet on in both directions.
525 * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
529 packet_init_compression(void)
531 if (active_state->compression_buffer_ready == 1)
533 active_state->compression_buffer_ready = 1;
534 buffer_init(&active_state->compression_buffer);
538 packet_start_compression(int level)
540 if (active_state->packet_compression && !compat20)
541 fatal("Compression already enabled.");
542 active_state->packet_compression = 1;
543 packet_init_compression();
544 buffer_compress_init_send(level);
545 buffer_compress_init_recv();
549 * Causes any further packets to be encrypted using the given key. The same
550 * key is used for both sending and reception. However, both directions are
551 * encrypted independently of each other.
555 packet_set_encryption_key(const u_char *key, u_int keylen, int number)
557 const Cipher *cipher = cipher_by_number(number);
560 fatal("packet_set_encryption_key: unknown cipher number %d", number);
562 fatal("packet_set_encryption_key: keylen too small: %d", keylen);
563 if (keylen > SSH_SESSION_KEY_LENGTH)
564 fatal("packet_set_encryption_key: keylen too big: %d", keylen);
565 memcpy(active_state->ssh1_key, key, keylen);
566 active_state->ssh1_keylen = keylen;
567 cipher_init(&active_state->send_context, cipher, key, keylen, NULL,
569 cipher_init(&active_state->receive_context, cipher, key, keylen, NULL,
574 packet_get_encryption_key(u_char *key)
577 return (active_state->ssh1_keylen);
578 memcpy(key, active_state->ssh1_key, active_state->ssh1_keylen);
579 return (active_state->ssh1_keylen);
582 /* Start constructing a packet to send. */
584 packet_start(u_char type)
589 DBG(debug("packet_start[%d]", type));
590 len = compat20 ? 6 : 9;
591 memset(buf, 0, len - 1);
593 buffer_clear(&active_state->outgoing_packet);
594 buffer_append(&active_state->outgoing_packet, buf, len);
597 /* Append payload. */
599 packet_put_char(int value)
603 buffer_append(&active_state->outgoing_packet, &ch, 1);
607 packet_put_int(u_int value)
609 buffer_put_int(&active_state->outgoing_packet, value);
613 packet_put_int64(u_int64_t value)
615 buffer_put_int64(&active_state->outgoing_packet, value);
619 packet_put_string(const void *buf, u_int len)
621 buffer_put_string(&active_state->outgoing_packet, buf, len);
625 packet_put_cstring(const char *str)
627 buffer_put_cstring(&active_state->outgoing_packet, str);
631 packet_put_raw(const void *buf, u_int len)
633 buffer_append(&active_state->outgoing_packet, buf, len);
637 packet_put_bignum(BIGNUM * value)
639 buffer_put_bignum(&active_state->outgoing_packet, value);
643 packet_put_bignum2(BIGNUM * value)
645 buffer_put_bignum2(&active_state->outgoing_packet, value);
648 #ifdef OPENSSL_HAS_ECC
650 packet_put_ecpoint(const EC_GROUP *curve, const EC_POINT *point)
652 buffer_put_ecpoint(&active_state->outgoing_packet, curve, point);
657 * Finalizes and sends the packet. If the encryption key has been set,
658 * encrypts the packet before sending.
670 * If using packet compression, compress the payload of the outgoing
673 if (active_state->packet_compression) {
674 buffer_clear(&active_state->compression_buffer);
676 buffer_consume(&active_state->outgoing_packet, 8);
678 buffer_append(&active_state->compression_buffer,
679 "\0\0\0\0\0\0\0\0", 8);
680 buffer_compress(&active_state->outgoing_packet,
681 &active_state->compression_buffer);
682 buffer_clear(&active_state->outgoing_packet);
683 buffer_append(&active_state->outgoing_packet,
684 buffer_ptr(&active_state->compression_buffer),
685 buffer_len(&active_state->compression_buffer));
687 /* Compute packet length without padding (add checksum, remove padding). */
688 len = buffer_len(&active_state->outgoing_packet) + 4 - 8;
690 /* Insert padding. Initialized to zero in packet_start1() */
691 padding = 8 - len % 8;
692 if (!active_state->send_context.plaintext) {
693 cp = buffer_ptr(&active_state->outgoing_packet);
694 for (i = 0; i < padding; i++) {
697 cp[7 - i] = rnd & 0xff;
701 buffer_consume(&active_state->outgoing_packet, 8 - padding);
703 /* Add check bytes. */
704 checksum = ssh_crc32(buffer_ptr(&active_state->outgoing_packet),
705 buffer_len(&active_state->outgoing_packet));
706 put_u32(buf, checksum);
707 buffer_append(&active_state->outgoing_packet, buf, 4);
710 fprintf(stderr, "packet_send plain: ");
711 buffer_dump(&active_state->outgoing_packet);
714 /* Append to output. */
716 buffer_append(&active_state->output, buf, 4);
717 cp = buffer_append_space(&active_state->output,
718 buffer_len(&active_state->outgoing_packet));
719 if (cipher_crypt(&active_state->send_context, 0, cp,
720 buffer_ptr(&active_state->outgoing_packet),
721 buffer_len(&active_state->outgoing_packet), 0, 0) != 0)
722 fatal("%s: cipher_crypt failed", __func__);
725 fprintf(stderr, "encrypted: ");
726 buffer_dump(&active_state->output);
728 active_state->p_send.packets++;
729 active_state->p_send.bytes += len +
730 buffer_len(&active_state->outgoing_packet);
731 buffer_clear(&active_state->outgoing_packet);
734 * Note that the packet is now only buffered in output. It won't be
735 * actually sent until packet_write_wait or packet_write_poll is
741 set_newkeys(int mode)
747 u_int64_t *max_blocks;
750 debug2("set_newkeys: mode %d", mode);
752 if (mode == MODE_OUT) {
753 cc = &active_state->send_context;
754 crypt_type = CIPHER_ENCRYPT;
755 active_state->p_send.packets = active_state->p_send.blocks = 0;
756 max_blocks = &active_state->max_blocks_out;
758 cc = &active_state->receive_context;
759 crypt_type = CIPHER_DECRYPT;
760 active_state->p_read.packets = active_state->p_read.blocks = 0;
761 max_blocks = &active_state->max_blocks_in;
763 if (active_state->newkeys[mode] != NULL) {
764 debug("set_newkeys: rekeying");
766 enc = &active_state->newkeys[mode]->enc;
767 mac = &active_state->newkeys[mode]->mac;
768 comp = &active_state->newkeys[mode]->comp;
770 explicit_bzero(enc->iv, enc->iv_len);
771 explicit_bzero(enc->key, enc->key_len);
772 explicit_bzero(mac->key, mac->key_len);
779 free(active_state->newkeys[mode]);
781 active_state->newkeys[mode] = kex_get_newkeys(mode);
782 if (active_state->newkeys[mode] == NULL)
783 fatal("newkeys: no keys for mode %d", mode);
784 enc = &active_state->newkeys[mode]->enc;
785 mac = &active_state->newkeys[mode]->mac;
786 comp = &active_state->newkeys[mode]->comp;
787 if (cipher_authlen(enc->cipher) == 0 && mac_init(mac) == 0)
789 DBG(debug("cipher_init_context: %d", mode));
790 cipher_init(cc, enc->cipher, enc->key, enc->key_len,
791 enc->iv, enc->iv_len, crypt_type);
792 /* Deleting the keys does not gain extra security */
793 /* explicit_bzero(enc->iv, enc->block_size);
794 explicit_bzero(enc->key, enc->key_len);
795 explicit_bzero(mac->key, mac->key_len); */
796 if ((comp->type == COMP_ZLIB ||
797 (comp->type == COMP_DELAYED &&
798 active_state->after_authentication)) && comp->enabled == 0) {
799 packet_init_compression();
800 if (mode == MODE_OUT)
801 buffer_compress_init_send(6);
803 buffer_compress_init_recv();
807 * The 2^(blocksize*2) limit is too expensive for 3DES,
808 * blowfish, etc, so enforce a 1GB limit for small blocksizes.
810 if (enc->block_size >= 16)
811 *max_blocks = (u_int64_t)1 << (enc->block_size*2);
813 *max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
814 if (active_state->rekey_limit)
815 *max_blocks = MIN(*max_blocks,
816 active_state->rekey_limit / enc->block_size);
820 * Delayed compression for SSH2 is enabled after authentication:
821 * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
822 * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
825 packet_enable_delayed_compress(void)
831 * Remember that we are past the authentication step, so rekeying
832 * with COMP_DELAYED will turn on compression immediately.
834 active_state->after_authentication = 1;
835 for (mode = 0; mode < MODE_MAX; mode++) {
836 /* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
837 if (active_state->newkeys[mode] == NULL)
839 comp = &active_state->newkeys[mode]->comp;
840 if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
841 packet_init_compression();
842 if (mode == MODE_OUT)
843 buffer_compress_init_send(6);
845 buffer_compress_init_recv();
852 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
855 packet_send2_wrapped(void)
857 u_char type, *cp, *macbuf = NULL;
858 u_char padlen, pad = 0;
859 u_int i, len, authlen = 0, aadlen = 0;
866 if (active_state->newkeys[MODE_OUT] != NULL) {
867 enc = &active_state->newkeys[MODE_OUT]->enc;
868 mac = &active_state->newkeys[MODE_OUT]->mac;
869 comp = &active_state->newkeys[MODE_OUT]->comp;
870 /* disable mac for authenticated encryption */
871 if ((authlen = cipher_authlen(enc->cipher)) != 0)
874 block_size = enc ? enc->block_size : 8;
875 aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
877 cp = buffer_ptr(&active_state->outgoing_packet);
881 fprintf(stderr, "plain: ");
882 buffer_dump(&active_state->outgoing_packet);
885 if (comp && comp->enabled) {
886 len = buffer_len(&active_state->outgoing_packet);
887 /* skip header, compress only payload */
888 buffer_consume(&active_state->outgoing_packet, 5);
889 buffer_clear(&active_state->compression_buffer);
890 buffer_compress(&active_state->outgoing_packet,
891 &active_state->compression_buffer);
892 buffer_clear(&active_state->outgoing_packet);
893 buffer_append(&active_state->outgoing_packet, "\0\0\0\0\0", 5);
894 buffer_append(&active_state->outgoing_packet,
895 buffer_ptr(&active_state->compression_buffer),
896 buffer_len(&active_state->compression_buffer));
897 DBG(debug("compression: raw %d compressed %d", len,
898 buffer_len(&active_state->outgoing_packet)));
901 /* sizeof (packet_len + pad_len + payload) */
902 len = buffer_len(&active_state->outgoing_packet);
905 * calc size of padding, alloc space, get random data,
906 * minimum padding is 4 bytes
908 len -= aadlen; /* packet length is not encrypted for EtM modes */
909 padlen = block_size - (len % block_size);
911 padlen += block_size;
912 if (active_state->extra_pad) {
913 /* will wrap if extra_pad+padlen > 255 */
914 active_state->extra_pad =
915 roundup(active_state->extra_pad, block_size);
916 pad = active_state->extra_pad -
917 ((len + padlen) % active_state->extra_pad);
918 debug3("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
919 pad, len, padlen, active_state->extra_pad);
921 active_state->extra_pad = 0;
923 cp = buffer_append_space(&active_state->outgoing_packet, padlen);
924 if (enc && !active_state->send_context.plaintext) {
926 for (i = 0; i < padlen; i++) {
934 explicit_bzero(cp, padlen);
936 /* sizeof (packet_len + pad_len + payload + padding) */
937 len = buffer_len(&active_state->outgoing_packet);
938 cp = buffer_ptr(&active_state->outgoing_packet);
939 /* packet_length includes payload, padding and padding length field */
940 put_u32(cp, len - 4);
942 DBG(debug("send: len %d (includes padlen %d, aadlen %d)",
943 len, padlen, aadlen));
945 /* compute MAC over seqnr and packet(length fields, payload, padding) */
946 if (mac && mac->enabled && !mac->etm) {
947 macbuf = mac_compute(mac, active_state->p_send.seqnr,
948 buffer_ptr(&active_state->outgoing_packet), len);
949 DBG(debug("done calc MAC out #%d", active_state->p_send.seqnr));
951 /* encrypt packet and append to output buffer. */
952 cp = buffer_append_space(&active_state->output, len + authlen);
953 if (cipher_crypt(&active_state->send_context, active_state->p_send.seqnr,
954 cp, buffer_ptr(&active_state->outgoing_packet),
955 len - aadlen, aadlen, authlen) != 0)
956 fatal("%s: cipher_crypt failed", __func__);
957 /* append unencrypted MAC */
958 if (mac && mac->enabled) {
960 /* EtM: compute mac over aadlen + cipher text */
961 macbuf = mac_compute(mac,
962 active_state->p_send.seqnr, cp, len);
963 DBG(debug("done calc MAC(EtM) out #%d",
964 active_state->p_send.seqnr));
966 buffer_append(&active_state->output, macbuf, mac->mac_len);
969 fprintf(stderr, "encrypted: ");
970 buffer_dump(&active_state->output);
972 /* increment sequence number for outgoing packets */
973 if (++active_state->p_send.seqnr == 0)
974 logit("outgoing seqnr wraps around");
975 if (++active_state->p_send.packets == 0)
976 if (!(datafellows & SSH_BUG_NOREKEY))
977 fatal("XXX too many packets with same key");
978 active_state->p_send.blocks += len / block_size;
979 active_state->p_send.bytes += len;
980 buffer_clear(&active_state->outgoing_packet);
982 if (type == SSH2_MSG_NEWKEYS)
983 set_newkeys(MODE_OUT);
984 else if (type == SSH2_MSG_USERAUTH_SUCCESS && active_state->server_side)
985 packet_enable_delayed_compress();
994 cp = buffer_ptr(&active_state->outgoing_packet);
997 /* during rekeying we can only send key exchange messages */
998 if (active_state->rekeying) {
999 if ((type < SSH2_MSG_TRANSPORT_MIN) ||
1000 (type > SSH2_MSG_TRANSPORT_MAX) ||
1001 (type == SSH2_MSG_SERVICE_REQUEST) ||
1002 (type == SSH2_MSG_SERVICE_ACCEPT)) {
1003 debug("enqueue packet: %u", type);
1004 p = xcalloc(1, sizeof(*p));
1006 memcpy(&p->payload, &active_state->outgoing_packet,
1008 buffer_init(&active_state->outgoing_packet);
1009 TAILQ_INSERT_TAIL(&active_state->outgoing, p, next);
1014 /* rekeying starts with sending KEXINIT */
1015 if (type == SSH2_MSG_KEXINIT)
1016 active_state->rekeying = 1;
1018 packet_send2_wrapped();
1020 /* after a NEWKEYS message we can send the complete queue */
1021 if (type == SSH2_MSG_NEWKEYS) {
1022 active_state->rekeying = 0;
1023 active_state->rekey_time = monotime();
1024 while ((p = TAILQ_FIRST(&active_state->outgoing))) {
1026 debug("dequeue packet: %u", type);
1027 buffer_free(&active_state->outgoing_packet);
1028 memcpy(&active_state->outgoing_packet, &p->payload,
1030 TAILQ_REMOVE(&active_state->outgoing, p, next);
1032 packet_send2_wrapped();
1044 DBG(debug("packet_send done"));
1048 * Waits until a packet has been received, and returns its type. Note that
1049 * no other data is processed until this returns, so this function should not
1050 * be used during the interactive session.
1054 packet_read_seqnr(u_int32_t *seqnr_p)
1056 int type, len, ret, cont, ms_remain = 0;
1059 struct timeval timeout, start, *timeoutp = NULL;
1061 DBG(debug("packet_read()"));
1063 setp = (fd_set *)xcalloc(howmany(active_state->connection_in + 1,
1064 NFDBITS), sizeof(fd_mask));
1066 /* Since we are blocking, ensure that all written packets have been sent. */
1067 packet_write_wait();
1069 /* Stay in the loop until we have received a complete packet. */
1071 /* Try to read a packet from the buffer. */
1072 type = packet_read_poll_seqnr(seqnr_p);
1074 type == SSH_SMSG_SUCCESS
1075 || type == SSH_SMSG_FAILURE
1076 || type == SSH_CMSG_EOF
1077 || type == SSH_CMSG_EXIT_CONFIRMATION))
1079 /* If we got a packet, return it. */
1080 if (type != SSH_MSG_NONE) {
1085 * Otherwise, wait for some data to arrive, add it to the
1086 * buffer, and try again.
1088 memset(setp, 0, howmany(active_state->connection_in + 1,
1089 NFDBITS) * sizeof(fd_mask));
1090 FD_SET(active_state->connection_in, setp);
1092 if (active_state->packet_timeout_ms > 0) {
1093 ms_remain = active_state->packet_timeout_ms;
1094 timeoutp = &timeout;
1096 /* Wait for some data to arrive. */
1098 if (active_state->packet_timeout_ms != -1) {
1099 ms_to_timeval(&timeout, ms_remain);
1100 gettimeofday(&start, NULL);
1102 if ((ret = select(active_state->connection_in + 1, setp,
1103 NULL, NULL, timeoutp)) >= 0)
1105 if (errno != EAGAIN && errno != EINTR &&
1106 errno != EWOULDBLOCK)
1108 if (active_state->packet_timeout_ms == -1)
1110 ms_subtract_diff(&start, &ms_remain);
1111 if (ms_remain <= 0) {
1117 logit("Connection to %.200s timed out while "
1118 "waiting to read", get_remote_ipaddr());
1121 /* Read data from the socket. */
1124 len = roaming_read(active_state->connection_in, buf,
1125 sizeof(buf), &cont);
1126 } while (len == 0 && cont);
1128 logit("Connection closed by %.200s", get_remote_ipaddr());
1132 fatal("Read from socket failed: %.100s", strerror(errno));
1133 /* Append it to the buffer. */
1134 packet_process_incoming(buf, len);
1142 return packet_read_seqnr(NULL);
1146 * Waits until a packet has been received, verifies that its type matches
1147 * that given, and gives a fatal error and exits if there is a mismatch.
1151 packet_read_expect(int expected_type)
1155 type = packet_read();
1156 if (type != expected_type)
1157 packet_disconnect("Protocol error: expected packet type %d, got %d",
1158 expected_type, type);
1161 /* Checks if a full packet is available in the data received so far via
1162 * packet_process_incoming. If so, reads the packet; otherwise returns
1163 * SSH_MSG_NONE. This does not wait for data from the connection.
1165 * SSH_MSG_DISCONNECT is handled specially here. Also,
1166 * SSH_MSG_IGNORE messages are skipped by this function and are never returned
1171 packet_read_poll1(void)
1173 u_int len, padded_len;
1175 u_int checksum, stored_checksum;
1177 /* Check if input size is less than minimum packet size. */
1178 if (buffer_len(&active_state->input) < 4 + 8)
1179 return SSH_MSG_NONE;
1180 /* Get length of incoming packet. */
1181 cp = buffer_ptr(&active_state->input);
1183 if (len < 1 + 2 + 2 || len > 256 * 1024)
1184 packet_disconnect("Bad packet length %u.", len);
1185 padded_len = (len + 8) & ~7;
1187 /* Check if the packet has been entirely received. */
1188 if (buffer_len(&active_state->input) < 4 + padded_len)
1189 return SSH_MSG_NONE;
1191 /* The entire packet is in buffer. */
1193 /* Consume packet length. */
1194 buffer_consume(&active_state->input, 4);
1197 * Cryptographic attack detector for ssh
1198 * (C)1998 CORE-SDI, Buenos Aires Argentina
1199 * Ariel Futoransky(futo@core-sdi.com)
1201 if (!active_state->receive_context.plaintext) {
1202 switch (detect_attack(buffer_ptr(&active_state->input),
1204 case DEATTACK_DETECTED:
1205 packet_disconnect("crc32 compensation attack: "
1206 "network attack detected");
1207 case DEATTACK_DOS_DETECTED:
1208 packet_disconnect("deattack denial of "
1209 "service detected");
1213 /* Decrypt data to incoming_packet. */
1214 buffer_clear(&active_state->incoming_packet);
1215 cp = buffer_append_space(&active_state->incoming_packet, padded_len);
1216 if (cipher_crypt(&active_state->receive_context, 0, cp,
1217 buffer_ptr(&active_state->input), padded_len, 0, 0) != 0)
1218 fatal("%s: cipher_crypt failed", __func__);
1220 buffer_consume(&active_state->input, padded_len);
1223 fprintf(stderr, "read_poll plain: ");
1224 buffer_dump(&active_state->incoming_packet);
1227 /* Compute packet checksum. */
1228 checksum = ssh_crc32(buffer_ptr(&active_state->incoming_packet),
1229 buffer_len(&active_state->incoming_packet) - 4);
1232 buffer_consume(&active_state->incoming_packet, 8 - len % 8);
1234 /* Test check bytes. */
1235 if (len != buffer_len(&active_state->incoming_packet))
1236 packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
1237 len, buffer_len(&active_state->incoming_packet));
1239 cp = (u_char *)buffer_ptr(&active_state->incoming_packet) + len - 4;
1240 stored_checksum = get_u32(cp);
1241 if (checksum != stored_checksum)
1242 packet_disconnect("Corrupted check bytes on input.");
1243 buffer_consume_end(&active_state->incoming_packet, 4);
1245 if (active_state->packet_compression) {
1246 buffer_clear(&active_state->compression_buffer);
1247 buffer_uncompress(&active_state->incoming_packet,
1248 &active_state->compression_buffer);
1249 buffer_clear(&active_state->incoming_packet);
1250 buffer_append(&active_state->incoming_packet,
1251 buffer_ptr(&active_state->compression_buffer),
1252 buffer_len(&active_state->compression_buffer));
1254 active_state->p_read.packets++;
1255 active_state->p_read.bytes += padded_len + 4;
1256 type = buffer_get_char(&active_state->incoming_packet);
1257 if (type < SSH_MSG_MIN || type > SSH_MSG_MAX)
1258 packet_disconnect("Invalid ssh1 packet type: %d", type);
1263 packet_read_poll2(u_int32_t *seqnr_p)
1266 u_char *macbuf = NULL, *cp, type;
1267 u_int maclen, authlen = 0, aadlen = 0, block_size;
1272 if (active_state->packet_discard)
1273 return SSH_MSG_NONE;
1275 if (active_state->newkeys[MODE_IN] != NULL) {
1276 enc = &active_state->newkeys[MODE_IN]->enc;
1277 mac = &active_state->newkeys[MODE_IN]->mac;
1278 comp = &active_state->newkeys[MODE_IN]->comp;
1279 /* disable mac for authenticated encryption */
1280 if ((authlen = cipher_authlen(enc->cipher)) != 0)
1283 maclen = mac && mac->enabled ? mac->mac_len : 0;
1284 block_size = enc ? enc->block_size : 8;
1285 aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
1287 if (aadlen && active_state->packlen == 0) {
1288 if (cipher_get_length(&active_state->receive_context,
1289 &active_state->packlen,
1290 active_state->p_read.seqnr,
1291 buffer_ptr(&active_state->input),
1292 buffer_len(&active_state->input)) != 0)
1293 return SSH_MSG_NONE;
1294 if (active_state->packlen < 1 + 4 ||
1295 active_state->packlen > PACKET_MAX_SIZE) {
1297 buffer_dump(&active_state->input);
1299 logit("Bad packet length %u.", active_state->packlen);
1300 packet_disconnect("Packet corrupt");
1302 buffer_clear(&active_state->incoming_packet);
1303 } else if (active_state->packlen == 0) {
1305 * check if input size is less than the cipher block size,
1306 * decrypt first block and extract length of incoming packet
1308 if (buffer_len(&active_state->input) < block_size)
1309 return SSH_MSG_NONE;
1310 buffer_clear(&active_state->incoming_packet);
1311 cp = buffer_append_space(&active_state->incoming_packet,
1313 if (cipher_crypt(&active_state->receive_context,
1314 active_state->p_read.seqnr, cp,
1315 buffer_ptr(&active_state->input), block_size, 0, 0) != 0)
1316 fatal("Decryption integrity check failed");
1317 cp = buffer_ptr(&active_state->incoming_packet);
1319 active_state->packlen = get_u32(cp);
1320 if (active_state->packlen < 1 + 4 ||
1321 active_state->packlen > PACKET_MAX_SIZE) {
1323 buffer_dump(&active_state->incoming_packet);
1325 logit("Bad packet length %u.", active_state->packlen);
1326 packet_start_discard(enc, mac, active_state->packlen,
1328 return SSH_MSG_NONE;
1330 buffer_consume(&active_state->input, block_size);
1332 DBG(debug("input: packet len %u", active_state->packlen+4));
1334 /* only the payload is encrypted */
1335 need = active_state->packlen;
1338 * the payload size and the payload are encrypted, but we
1339 * have a partial packet of block_size bytes
1341 need = 4 + active_state->packlen - block_size;
1343 DBG(debug("partial packet: block %d, need %d, maclen %d, authlen %d,"
1344 " aadlen %d", block_size, need, maclen, authlen, aadlen));
1345 if (need % block_size != 0) {
1346 logit("padding error: need %d block %d mod %d",
1347 need, block_size, need % block_size);
1348 packet_start_discard(enc, mac, active_state->packlen,
1349 PACKET_MAX_SIZE - block_size);
1350 return SSH_MSG_NONE;
1353 * check if the entire packet has been received and
1354 * decrypt into incoming_packet:
1355 * 'aadlen' bytes are unencrypted, but authenticated.
1356 * 'need' bytes are encrypted, followed by either
1357 * 'authlen' bytes of authentication tag or
1358 * 'maclen' bytes of message authentication code.
1360 if (buffer_len(&active_state->input) < aadlen + need + authlen + maclen)
1361 return SSH_MSG_NONE;
1363 fprintf(stderr, "read_poll enc/full: ");
1364 buffer_dump(&active_state->input);
1366 /* EtM: compute mac over encrypted input */
1367 if (mac && mac->enabled && mac->etm)
1368 macbuf = mac_compute(mac, active_state->p_read.seqnr,
1369 buffer_ptr(&active_state->input), aadlen + need);
1370 cp = buffer_append_space(&active_state->incoming_packet, aadlen + need);
1371 if (cipher_crypt(&active_state->receive_context,
1372 active_state->p_read.seqnr, cp,
1373 buffer_ptr(&active_state->input), need, aadlen, authlen) != 0)
1374 fatal("Decryption integrity check failed");
1375 buffer_consume(&active_state->input, aadlen + need + authlen);
1377 * compute MAC over seqnr and packet,
1378 * increment sequence number for incoming packet
1380 if (mac && mac->enabled) {
1382 macbuf = mac_compute(mac, active_state->p_read.seqnr,
1383 buffer_ptr(&active_state->incoming_packet),
1384 buffer_len(&active_state->incoming_packet));
1385 if (timingsafe_bcmp(macbuf, buffer_ptr(&active_state->input),
1386 mac->mac_len) != 0) {
1387 logit("Corrupted MAC on input.");
1388 if (need > PACKET_MAX_SIZE)
1389 fatal("internal error need %d", need);
1390 packet_start_discard(enc, mac, active_state->packlen,
1391 PACKET_MAX_SIZE - need);
1392 return SSH_MSG_NONE;
1395 DBG(debug("MAC #%d ok", active_state->p_read.seqnr));
1396 buffer_consume(&active_state->input, mac->mac_len);
1398 /* XXX now it's safe to use fatal/packet_disconnect */
1399 if (seqnr_p != NULL)
1400 *seqnr_p = active_state->p_read.seqnr;
1401 if (++active_state->p_read.seqnr == 0)
1402 logit("incoming seqnr wraps around");
1403 if (++active_state->p_read.packets == 0)
1404 if (!(datafellows & SSH_BUG_NOREKEY))
1405 fatal("XXX too many packets with same key");
1406 active_state->p_read.blocks += (active_state->packlen + 4) / block_size;
1407 active_state->p_read.bytes += active_state->packlen + 4;
1410 cp = buffer_ptr(&active_state->incoming_packet);
1412 DBG(debug("input: padlen %d", padlen));
1414 packet_disconnect("Corrupted padlen %d on input.", padlen);
1416 /* skip packet size + padlen, discard padding */
1417 buffer_consume(&active_state->incoming_packet, 4 + 1);
1418 buffer_consume_end(&active_state->incoming_packet, padlen);
1420 DBG(debug("input: len before de-compress %d",
1421 buffer_len(&active_state->incoming_packet)));
1422 if (comp && comp->enabled) {
1423 buffer_clear(&active_state->compression_buffer);
1424 buffer_uncompress(&active_state->incoming_packet,
1425 &active_state->compression_buffer);
1426 buffer_clear(&active_state->incoming_packet);
1427 buffer_append(&active_state->incoming_packet,
1428 buffer_ptr(&active_state->compression_buffer),
1429 buffer_len(&active_state->compression_buffer));
1430 DBG(debug("input: len after de-compress %d",
1431 buffer_len(&active_state->incoming_packet)));
1434 * get packet type, implies consume.
1435 * return length of payload (without type field)
1437 type = buffer_get_char(&active_state->incoming_packet);
1438 if (type < SSH2_MSG_MIN || type >= SSH2_MSG_LOCAL_MIN)
1439 packet_disconnect("Invalid ssh2 packet type: %d", type);
1440 if (type == SSH2_MSG_NEWKEYS)
1441 set_newkeys(MODE_IN);
1442 else if (type == SSH2_MSG_USERAUTH_SUCCESS &&
1443 !active_state->server_side)
1444 packet_enable_delayed_compress();
1446 fprintf(stderr, "read/plain[%d]:\r\n", type);
1447 buffer_dump(&active_state->incoming_packet);
1449 /* reset for next packet */
1450 active_state->packlen = 0;
1455 packet_read_poll_seqnr(u_int32_t *seqnr_p)
1457 u_int reason, seqnr;
1463 type = packet_read_poll2(seqnr_p);
1465 active_state->keep_alive_timeouts = 0;
1466 DBG(debug("received packet type %d", type));
1469 case SSH2_MSG_IGNORE:
1470 debug3("Received SSH2_MSG_IGNORE");
1472 case SSH2_MSG_DEBUG:
1474 msg = packet_get_string(NULL);
1475 debug("Remote: %.900s", msg);
1477 msg = packet_get_string(NULL);
1480 case SSH2_MSG_DISCONNECT:
1481 reason = packet_get_int();
1482 msg = packet_get_string(NULL);
1483 /* Ignore normal client exit notifications */
1484 do_log2(active_state->server_side &&
1485 reason == SSH2_DISCONNECT_BY_APPLICATION ?
1486 SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_ERROR,
1487 "Received disconnect from %s: %u: %.400s",
1488 get_remote_ipaddr(), reason, msg);
1492 case SSH2_MSG_UNIMPLEMENTED:
1493 seqnr = packet_get_int();
1494 debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1501 type = packet_read_poll1();
1504 return SSH_MSG_NONE;
1505 case SSH_MSG_IGNORE:
1508 msg = packet_get_string(NULL);
1509 debug("Remote: %.900s", msg);
1512 case SSH_MSG_DISCONNECT:
1513 msg = packet_get_string(NULL);
1514 logit("Received disconnect from %s: %.400s",
1515 get_remote_ipaddr(), msg);
1519 DBG(debug("received packet type %d", type));
1527 * Buffers the given amount of input characters. This is intended to be used
1528 * together with packet_read_poll.
1532 packet_process_incoming(const char *buf, u_int len)
1534 if (active_state->packet_discard) {
1535 active_state->keep_alive_timeouts = 0; /* ?? */
1536 if (len >= active_state->packet_discard)
1537 packet_stop_discard();
1538 active_state->packet_discard -= len;
1541 buffer_append(&active_state->input, buf, len);
1544 /* Returns a character from the packet. */
1547 packet_get_char(void)
1551 buffer_get(&active_state->incoming_packet, &ch, 1);
1555 /* Returns an integer from the packet data. */
1558 packet_get_int(void)
1560 return buffer_get_int(&active_state->incoming_packet);
1563 /* Returns an 64 bit integer from the packet data. */
1566 packet_get_int64(void)
1568 return buffer_get_int64(&active_state->incoming_packet);
1572 * Returns an arbitrary precision integer from the packet data. The integer
1573 * must have been initialized before this call.
1577 packet_get_bignum(BIGNUM * value)
1579 buffer_get_bignum(&active_state->incoming_packet, value);
1583 packet_get_bignum2(BIGNUM * value)
1585 buffer_get_bignum2(&active_state->incoming_packet, value);
1588 #ifdef OPENSSL_HAS_ECC
1590 packet_get_ecpoint(const EC_GROUP *curve, EC_POINT *point)
1592 buffer_get_ecpoint(&active_state->incoming_packet, curve, point);
1597 packet_get_raw(u_int *length_ptr)
1599 u_int bytes = buffer_len(&active_state->incoming_packet);
1601 if (length_ptr != NULL)
1602 *length_ptr = bytes;
1603 return buffer_ptr(&active_state->incoming_packet);
1607 packet_remaining(void)
1609 return buffer_len(&active_state->incoming_packet);
1613 * Returns a string from the packet data. The string is allocated using
1614 * xmalloc; it is the responsibility of the calling program to free it when
1615 * no longer needed. The length_ptr argument may be NULL, or point to an
1616 * integer into which the length of the string is stored.
1620 packet_get_string(u_int *length_ptr)
1622 return buffer_get_string(&active_state->incoming_packet, length_ptr);
1626 packet_get_string_ptr(u_int *length_ptr)
1628 return buffer_get_string_ptr(&active_state->incoming_packet, length_ptr);
1631 /* Ensures the returned string has no embedded \0 characters in it. */
1633 packet_get_cstring(u_int *length_ptr)
1635 return buffer_get_cstring(&active_state->incoming_packet, length_ptr);
1639 * Sends a diagnostic message from the server to the client. This message
1640 * can be sent at any time (but not while constructing another message). The
1641 * message is printed immediately, but only if the client is being executed
1642 * in verbose mode. These messages are primarily intended to ease debugging
1643 * authentication problems. The length of the formatted message must not
1644 * exceed 1024 bytes. This will automatically call packet_write_wait.
1648 packet_send_debug(const char *fmt,...)
1653 if (compat20 && (datafellows & SSH_BUG_DEBUG))
1656 va_start(args, fmt);
1657 vsnprintf(buf, sizeof(buf), fmt, args);
1661 packet_start(SSH2_MSG_DEBUG);
1662 packet_put_char(0); /* bool: always display */
1663 packet_put_cstring(buf);
1664 packet_put_cstring("");
1666 packet_start(SSH_MSG_DEBUG);
1667 packet_put_cstring(buf);
1670 packet_write_wait();
1674 * Logs the error plus constructs and sends a disconnect packet, closes the
1675 * connection, and exits. This function never returns. The error message
1676 * should not contain a newline. The length of the formatted message must
1677 * not exceed 1024 bytes.
1681 packet_disconnect(const char *fmt,...)
1685 static int disconnecting = 0;
1687 if (disconnecting) /* Guard against recursive invocations. */
1688 fatal("packet_disconnect called recursively.");
1692 * Format the message. Note that the caller must make sure the
1693 * message is of limited size.
1695 va_start(args, fmt);
1696 vsnprintf(buf, sizeof(buf), fmt, args);
1699 /* Display the error locally */
1700 logit("Disconnecting: %.100s", buf);
1702 /* Send the disconnect message to the other side, and wait for it to get sent. */
1704 packet_start(SSH2_MSG_DISCONNECT);
1705 packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1706 packet_put_cstring(buf);
1707 packet_put_cstring("");
1709 packet_start(SSH_MSG_DISCONNECT);
1710 packet_put_cstring(buf);
1713 packet_write_wait();
1715 /* Stop listening for connections. */
1716 channel_close_all();
1718 /* Close the connection. */
1723 /* Checks if there is any buffered output, and tries to write some of the output. */
1726 packet_write_poll(void)
1728 int len = buffer_len(&active_state->output);
1733 len = roaming_write(active_state->connection_out,
1734 buffer_ptr(&active_state->output), len, &cont);
1736 if (errno == EINTR || errno == EAGAIN ||
1737 errno == EWOULDBLOCK)
1739 fatal("Write failed: %.100s", strerror(errno));
1741 if (len == 0 && !cont)
1742 fatal("Write connection closed");
1743 buffer_consume(&active_state->output, len);
1748 * Calls packet_write_poll repeatedly until all pending output data has been
1753 packet_write_wait(void)
1756 int ret, ms_remain = 0;
1757 struct timeval start, timeout, *timeoutp = NULL;
1759 setp = (fd_set *)xcalloc(howmany(active_state->connection_out + 1,
1760 NFDBITS), sizeof(fd_mask));
1761 packet_write_poll();
1762 while (packet_have_data_to_write()) {
1763 memset(setp, 0, howmany(active_state->connection_out + 1,
1764 NFDBITS) * sizeof(fd_mask));
1765 FD_SET(active_state->connection_out, setp);
1767 if (active_state->packet_timeout_ms > 0) {
1768 ms_remain = active_state->packet_timeout_ms;
1769 timeoutp = &timeout;
1772 if (active_state->packet_timeout_ms != -1) {
1773 ms_to_timeval(&timeout, ms_remain);
1774 gettimeofday(&start, NULL);
1776 if ((ret = select(active_state->connection_out + 1,
1777 NULL, setp, NULL, timeoutp)) >= 0)
1779 if (errno != EAGAIN && errno != EINTR &&
1780 errno != EWOULDBLOCK)
1782 if (active_state->packet_timeout_ms == -1)
1784 ms_subtract_diff(&start, &ms_remain);
1785 if (ms_remain <= 0) {
1791 logit("Connection to %.200s timed out while "
1792 "waiting to write", get_remote_ipaddr());
1795 packet_write_poll();
1800 /* Returns true if there is buffered data to write to the connection. */
1803 packet_have_data_to_write(void)
1805 return buffer_len(&active_state->output) != 0;
1808 /* Returns true if there is not too much data to write to the connection. */
1811 packet_not_very_much_data_to_write(void)
1813 if (active_state->interactive_mode)
1814 return buffer_len(&active_state->output) < 16384;
1816 return buffer_len(&active_state->output) < 128 * 1024;
1820 packet_set_tos(int tos)
1822 #ifndef IP_TOS_IS_BROKEN
1823 if (!packet_connection_is_on_socket())
1825 switch (packet_connection_af()) {
1828 debug3("%s: set IP_TOS 0x%02x", __func__, tos);
1829 if (setsockopt(active_state->connection_in,
1830 IPPROTO_IP, IP_TOS, &tos, sizeof(tos)) < 0)
1831 error("setsockopt IP_TOS %d: %.100s:",
1832 tos, strerror(errno));
1834 # endif /* IP_TOS */
1837 debug3("%s: set IPV6_TCLASS 0x%02x", __func__, tos);
1838 if (setsockopt(active_state->connection_in,
1839 IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof(tos)) < 0)
1840 error("setsockopt IPV6_TCLASS %d: %.100s:",
1841 tos, strerror(errno));
1843 # endif /* IPV6_TCLASS */
1845 #endif /* IP_TOS_IS_BROKEN */
1848 /* Informs that the current session is interactive. Sets IP flags for that. */
1851 packet_set_interactive(int interactive, int qos_interactive, int qos_bulk)
1853 if (active_state->set_interactive_called)
1855 active_state->set_interactive_called = 1;
1857 /* Record that we are in interactive mode. */
1858 active_state->interactive_mode = interactive;
1860 /* Only set socket options if using a socket. */
1861 if (!packet_connection_is_on_socket())
1863 set_nodelay(active_state->connection_in);
1864 packet_set_tos(interactive ? qos_interactive : qos_bulk);
1867 /* Returns true if the current connection is interactive. */
1870 packet_is_interactive(void)
1872 return active_state->interactive_mode;
1876 packet_set_maxsize(u_int s)
1878 if (active_state->set_maxsize_called) {
1879 logit("packet_set_maxsize: called twice: old %d new %d",
1880 active_state->max_packet_size, s);
1883 if (s < 4 * 1024 || s > 1024 * 1024) {
1884 logit("packet_set_maxsize: bad size %d", s);
1887 active_state->set_maxsize_called = 1;
1888 debug("packet_set_maxsize: setting to %d", s);
1889 active_state->max_packet_size = s;
1894 packet_inc_alive_timeouts(void)
1896 return ++active_state->keep_alive_timeouts;
1900 packet_set_alive_timeouts(int ka)
1902 active_state->keep_alive_timeouts = ka;
1906 packet_get_maxsize(void)
1908 return active_state->max_packet_size;
1911 /* roundup current message to pad bytes */
1913 packet_add_padding(u_char pad)
1915 active_state->extra_pad = pad;
1919 * 9.2. Ignored Data Message
1921 * byte SSH_MSG_IGNORE
1924 * All implementations MUST understand (and ignore) this message at any
1925 * time (after receiving the protocol version). No implementation is
1926 * required to send them. This message can be used as an additional
1927 * protection measure against advanced traffic analysis techniques.
1930 packet_send_ignore(int nbytes)
1935 packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1936 packet_put_int(nbytes);
1937 for (i = 0; i < nbytes; i++) {
1940 packet_put_char((u_char)rnd & 0xff);
1945 #ifdef NONE_CIPHER_ENABLED
1947 packet_request_rekeying(void)
1949 rekey_requested = 1;
1953 #define MAX_PACKETS (1U<<31)
1955 packet_need_rekeying(void)
1957 if (datafellows & SSH_BUG_NOREKEY)
1959 #ifdef NONE_CIPHER_ENABLED
1960 if (rekey_requested == 1) {
1961 rekey_requested = 0;
1966 (active_state->p_send.packets > MAX_PACKETS) ||
1967 (active_state->p_read.packets > MAX_PACKETS) ||
1968 (active_state->max_blocks_out &&
1969 (active_state->p_send.blocks > active_state->max_blocks_out)) ||
1970 (active_state->max_blocks_in &&
1971 (active_state->p_read.blocks > active_state->max_blocks_in)) ||
1972 (active_state->rekey_interval != 0 && active_state->rekey_time +
1973 active_state->rekey_interval <= monotime());
1977 packet_set_rekey_limits(u_int32_t bytes, time_t seconds)
1979 debug3("rekey after %lld bytes, %d seconds", (long long)bytes,
1981 active_state->rekey_limit = bytes;
1982 active_state->rekey_interval = seconds;
1984 * We set the time here so that in post-auth privsep slave we count
1985 * from the completion of the authentication.
1987 active_state->rekey_time = monotime();
1991 packet_get_rekey_timeout(void)
1995 seconds = active_state->rekey_time + active_state->rekey_interval -
1997 return (seconds <= 0 ? 1 : seconds);
2001 packet_set_server(void)
2003 active_state->server_side = 1;
2007 packet_set_authenticated(void)
2009 active_state->after_authentication = 1;
2013 packet_get_input(void)
2015 return (void *)&active_state->input;
2019 packet_get_output(void)
2021 return (void *)&active_state->output;
2025 packet_get_newkeys(int mode)
2027 return (void *)active_state->newkeys[mode];
2031 * Save the state for the real connection, and use a separate state when
2032 * resuming a suspended connection.
2035 packet_backup_state(void)
2037 struct session_state *tmp;
2039 close(active_state->connection_in);
2040 active_state->connection_in = -1;
2041 close(active_state->connection_out);
2042 active_state->connection_out = -1;
2046 tmp = alloc_session_state();
2047 backup_state = active_state;
2052 * Swap in the old state when resuming a connecion.
2055 packet_restore_state(void)
2057 struct session_state *tmp;
2062 backup_state = active_state;
2064 active_state->connection_in = backup_state->connection_in;
2065 backup_state->connection_in = -1;
2066 active_state->connection_out = backup_state->connection_out;
2067 backup_state->connection_out = -1;
2068 len = buffer_len(&backup_state->input);
2070 buf = buffer_ptr(&backup_state->input);
2071 buffer_append(&active_state->input, buf, len);
2072 buffer_clear(&backup_state->input);
2073 add_recv_bytes(len);
2077 #ifdef NONE_CIPHER_ENABLED
2079 packet_get_authentication_state(void)
2081 return (active_state->after_authentication);