1 /* $OpenBSD: packet.c,v 1.192 2014/02/02 03:44:31 djm Exp $ */
4 * Author: Tatu Ylonen <ylo@cs.hut.fi>
5 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
7 * This file contains code implementing the packet protocol and communication
8 * with the other side. This same code is used both on client and server side.
10 * As far as I am concerned, the code I have written for this software
11 * can be used freely for any purpose. Any derived versions of this
12 * software must be clearly marked as such, and if the derived work is
13 * incompatible with the protocol description in the RFC file, it must be
14 * called by a name other than "ssh" or "Secure Shell".
17 * SSH2 packet format added by Markus Friedl.
18 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
20 * Redistribution and use in source and binary forms, with or without
21 * modification, are permitted provided that the following conditions
23 * 1. Redistributions of source code must retain the above copyright
24 * notice, this list of conditions and the following disclaimer.
25 * 2. Redistributions in binary form must reproduce the above copyright
26 * notice, this list of conditions and the following disclaimer in the
27 * documentation and/or other materials provided with the distribution.
29 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
30 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
31 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
32 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
33 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
34 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
38 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44 #include <sys/types.h>
45 #include "openbsd-compat/sys-queue.h"
46 #include <sys/param.h>
47 #include <sys/socket.h>
48 #ifdef HAVE_SYS_TIME_H
49 # include <sys/time.h>
52 #include <netinet/in.h>
53 #include <netinet/ip.h>
54 #include <arpa/inet.h>
91 #define PACKET_MAX_SIZE (256 * 1024)
101 TAILQ_ENTRY(packet) next;
106 struct session_state {
108 * This variable contains the file descriptors used for
109 * communicating with the other side. connection_in is used for
110 * reading; connection_out for writing. These can be the same
111 * descriptor, in which case it is assumed to be a socket.
116 /* Protocol flags for the remote side. */
117 u_int remote_protocol_flags;
119 /* Encryption context for receiving data. Only used for decryption. */
120 CipherContext receive_context;
122 /* Encryption context for sending data. Only used for encryption. */
123 CipherContext send_context;
125 /* Buffer for raw input data from the socket. */
128 /* Buffer for raw output data going to the socket. */
131 /* Buffer for the partial outgoing packet being constructed. */
132 Buffer outgoing_packet;
134 /* Buffer for the incoming packet currently being processed. */
135 Buffer incoming_packet;
137 /* Scratch buffer for packet compression/decompression. */
138 Buffer compression_buffer;
139 int compression_buffer_ready;
142 * Flag indicating whether packet compression/decompression is
145 int packet_compression;
147 /* default maximum packet size */
148 u_int max_packet_size;
150 /* Flag indicating whether this module has been initialized. */
153 /* Set to true if the connection is interactive. */
154 int interactive_mode;
156 /* Set to true if we are the server side. */
159 /* Set to true if we are authenticated. */
160 int after_authentication;
162 int keep_alive_timeouts;
164 /* The maximum time that we will wait to send or receive a packet */
165 int packet_timeout_ms;
167 /* Session key information for Encryption and MAC */
168 Newkeys *newkeys[MODE_MAX];
169 struct packet_state p_read, p_send;
171 /* Volume-based rekeying */
172 u_int64_t max_blocks_in, max_blocks_out;
173 u_int32_t rekey_limit;
175 /* Time-based rekeying */
176 time_t rekey_interval; /* how often in seconds */
177 time_t rekey_time; /* time of last rekeying */
179 /* Session key for protocol v1 */
180 u_char ssh1_key[SSH_SESSION_KEY_LENGTH];
183 /* roundup current message to extra_pad bytes */
186 /* XXX discard incoming data after MAC error */
187 u_int packet_discard;
188 Mac *packet_discard_mac;
190 /* Used in packet_read_poll2() */
193 /* Used in packet_send2 */
196 /* Used in packet_set_interactive */
197 int set_interactive_called;
199 /* Used in packet_set_maxsize */
200 int set_maxsize_called;
202 TAILQ_HEAD(, packet) outgoing;
205 static struct session_state *active_state, *backup_state;
206 #ifdef NONE_CIPHER_ENABLED
207 static int rekey_requested = 0;
210 static struct session_state *
211 alloc_session_state(void)
213 struct session_state *s = xcalloc(1, sizeof(*s));
215 s->connection_in = -1;
216 s->connection_out = -1;
217 s->max_packet_size = 32768;
218 s->packet_timeout_ms = -1;
223 * Sets the descriptors used for communication. Disables encryption until
224 * packet_set_encryption_key is called.
227 packet_set_connection(int fd_in, int fd_out)
229 const Cipher *none = cipher_by_name("none");
232 fatal("packet_set_connection: cannot load cipher 'none'");
233 if (active_state == NULL)
234 active_state = alloc_session_state();
235 active_state->connection_in = fd_in;
236 active_state->connection_out = fd_out;
237 cipher_init(&active_state->send_context, none, (const u_char *)"",
238 0, NULL, 0, CIPHER_ENCRYPT);
239 cipher_init(&active_state->receive_context, none, (const u_char *)"",
240 0, NULL, 0, CIPHER_DECRYPT);
241 active_state->newkeys[MODE_IN] = active_state->newkeys[MODE_OUT] = NULL;
242 if (!active_state->initialized) {
243 active_state->initialized = 1;
244 buffer_init(&active_state->input);
245 buffer_init(&active_state->output);
246 buffer_init(&active_state->outgoing_packet);
247 buffer_init(&active_state->incoming_packet);
248 TAILQ_INIT(&active_state->outgoing);
249 active_state->p_send.packets = active_state->p_read.packets = 0;
254 packet_set_timeout(int timeout, int count)
256 if (timeout <= 0 || count <= 0) {
257 active_state->packet_timeout_ms = -1;
260 if ((INT_MAX / 1000) / count < timeout)
261 active_state->packet_timeout_ms = INT_MAX;
263 active_state->packet_timeout_ms = timeout * count * 1000;
267 packet_stop_discard(void)
269 if (active_state->packet_discard_mac) {
272 memset(buf, 'a', sizeof(buf));
273 while (buffer_len(&active_state->incoming_packet) <
275 buffer_append(&active_state->incoming_packet, buf,
277 (void) mac_compute(active_state->packet_discard_mac,
278 active_state->p_read.seqnr,
279 buffer_ptr(&active_state->incoming_packet),
282 logit("Finished discarding for %.200s", get_remote_ipaddr());
287 packet_start_discard(Enc *enc, Mac *mac, u_int packet_length, u_int discard)
289 if (enc == NULL || !cipher_is_cbc(enc->cipher) || (mac && mac->etm))
290 packet_disconnect("Packet corrupt");
291 if (packet_length != PACKET_MAX_SIZE && mac && mac->enabled)
292 active_state->packet_discard_mac = mac;
293 if (buffer_len(&active_state->input) >= discard)
294 packet_stop_discard();
295 active_state->packet_discard = discard -
296 buffer_len(&active_state->input);
299 /* Returns 1 if remote host is connected via socket, 0 if not. */
302 packet_connection_is_on_socket(void)
304 struct sockaddr_storage from, to;
305 socklen_t fromlen, tolen;
307 /* filedescriptors in and out are the same, so it's a socket */
308 if (active_state->connection_in == active_state->connection_out)
310 fromlen = sizeof(from);
311 memset(&from, 0, sizeof(from));
312 if (getpeername(active_state->connection_in, (struct sockaddr *)&from,
316 memset(&to, 0, sizeof(to));
317 if (getpeername(active_state->connection_out, (struct sockaddr *)&to,
320 if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
322 if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
328 * Exports an IV from the CipherContext required to export the key
329 * state back from the unprivileged child to the privileged parent
334 packet_get_keyiv(int mode, u_char *iv, u_int len)
338 if (mode == MODE_OUT)
339 cc = &active_state->send_context;
341 cc = &active_state->receive_context;
343 cipher_get_keyiv(cc, iv, len);
347 packet_get_keycontext(int mode, u_char *dat)
351 if (mode == MODE_OUT)
352 cc = &active_state->send_context;
354 cc = &active_state->receive_context;
356 return (cipher_get_keycontext(cc, dat));
360 packet_set_keycontext(int mode, u_char *dat)
364 if (mode == MODE_OUT)
365 cc = &active_state->send_context;
367 cc = &active_state->receive_context;
369 cipher_set_keycontext(cc, dat);
373 packet_get_keyiv_len(int mode)
377 if (mode == MODE_OUT)
378 cc = &active_state->send_context;
380 cc = &active_state->receive_context;
382 return (cipher_get_keyiv_len(cc));
386 packet_set_iv(int mode, u_char *dat)
390 if (mode == MODE_OUT)
391 cc = &active_state->send_context;
393 cc = &active_state->receive_context;
395 cipher_set_keyiv(cc, dat);
399 packet_get_ssh1_cipher(void)
401 return (cipher_get_number(active_state->receive_context.cipher));
405 packet_get_state(int mode, u_int32_t *seqnr, u_int64_t *blocks,
406 u_int32_t *packets, u_int64_t *bytes)
408 struct packet_state *state;
410 state = (mode == MODE_IN) ?
411 &active_state->p_read : &active_state->p_send;
413 *seqnr = state->seqnr;
415 *blocks = state->blocks;
417 *packets = state->packets;
419 *bytes = state->bytes;
423 packet_set_state(int mode, u_int32_t seqnr, u_int64_t blocks, u_int32_t packets,
426 struct packet_state *state;
428 state = (mode == MODE_IN) ?
429 &active_state->p_read : &active_state->p_send;
430 state->seqnr = seqnr;
431 state->blocks = blocks;
432 state->packets = packets;
433 state->bytes = bytes;
437 packet_connection_af(void)
439 struct sockaddr_storage to;
440 socklen_t tolen = sizeof(to);
442 memset(&to, 0, sizeof(to));
443 if (getsockname(active_state->connection_out, (struct sockaddr *)&to,
447 if (to.ss_family == AF_INET6 &&
448 IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&to)->sin6_addr))
454 /* Sets the connection into non-blocking mode. */
457 packet_set_nonblocking(void)
459 /* Set the socket into non-blocking mode. */
460 set_nonblock(active_state->connection_in);
462 if (active_state->connection_out != active_state->connection_in)
463 set_nonblock(active_state->connection_out);
466 /* Returns the socket used for reading. */
469 packet_get_connection_in(void)
471 return active_state->connection_in;
474 /* Returns the descriptor used for writing. */
477 packet_get_connection_out(void)
479 return active_state->connection_out;
482 /* Closes the connection and clears and frees internal data structures. */
487 if (!active_state->initialized)
489 active_state->initialized = 0;
490 if (active_state->connection_in == active_state->connection_out) {
491 shutdown(active_state->connection_out, SHUT_RDWR);
492 close(active_state->connection_out);
494 close(active_state->connection_in);
495 close(active_state->connection_out);
497 buffer_free(&active_state->input);
498 buffer_free(&active_state->output);
499 buffer_free(&active_state->outgoing_packet);
500 buffer_free(&active_state->incoming_packet);
501 if (active_state->compression_buffer_ready) {
502 buffer_free(&active_state->compression_buffer);
503 buffer_compress_uninit();
505 cipher_cleanup(&active_state->send_context);
506 cipher_cleanup(&active_state->receive_context);
509 /* Sets remote side protocol flags. */
512 packet_set_protocol_flags(u_int protocol_flags)
514 active_state->remote_protocol_flags = protocol_flags;
517 /* Returns the remote protocol flags set earlier by the above function. */
520 packet_get_protocol_flags(void)
522 return active_state->remote_protocol_flags;
526 * Starts packet compression from the next packet on in both directions.
527 * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
531 packet_init_compression(void)
533 if (active_state->compression_buffer_ready == 1)
535 active_state->compression_buffer_ready = 1;
536 buffer_init(&active_state->compression_buffer);
540 packet_start_compression(int level)
542 if (active_state->packet_compression && !compat20)
543 fatal("Compression already enabled.");
544 active_state->packet_compression = 1;
545 packet_init_compression();
546 buffer_compress_init_send(level);
547 buffer_compress_init_recv();
551 * Causes any further packets to be encrypted using the given key. The same
552 * key is used for both sending and reception. However, both directions are
553 * encrypted independently of each other.
557 packet_set_encryption_key(const u_char *key, u_int keylen, int number)
559 const Cipher *cipher = cipher_by_number(number);
562 fatal("packet_set_encryption_key: unknown cipher number %d", number);
564 fatal("packet_set_encryption_key: keylen too small: %d", keylen);
565 if (keylen > SSH_SESSION_KEY_LENGTH)
566 fatal("packet_set_encryption_key: keylen too big: %d", keylen);
567 memcpy(active_state->ssh1_key, key, keylen);
568 active_state->ssh1_keylen = keylen;
569 cipher_init(&active_state->send_context, cipher, key, keylen, NULL,
571 cipher_init(&active_state->receive_context, cipher, key, keylen, NULL,
576 packet_get_encryption_key(u_char *key)
579 return (active_state->ssh1_keylen);
580 memcpy(key, active_state->ssh1_key, active_state->ssh1_keylen);
581 return (active_state->ssh1_keylen);
584 /* Start constructing a packet to send. */
586 packet_start(u_char type)
591 DBG(debug("packet_start[%d]", type));
592 len = compat20 ? 6 : 9;
593 memset(buf, 0, len - 1);
595 buffer_clear(&active_state->outgoing_packet);
596 buffer_append(&active_state->outgoing_packet, buf, len);
599 /* Append payload. */
601 packet_put_char(int value)
605 buffer_append(&active_state->outgoing_packet, &ch, 1);
609 packet_put_int(u_int value)
611 buffer_put_int(&active_state->outgoing_packet, value);
615 packet_put_int64(u_int64_t value)
617 buffer_put_int64(&active_state->outgoing_packet, value);
621 packet_put_string(const void *buf, u_int len)
623 buffer_put_string(&active_state->outgoing_packet, buf, len);
627 packet_put_cstring(const char *str)
629 buffer_put_cstring(&active_state->outgoing_packet, str);
633 packet_put_raw(const void *buf, u_int len)
635 buffer_append(&active_state->outgoing_packet, buf, len);
639 packet_put_bignum(BIGNUM * value)
641 buffer_put_bignum(&active_state->outgoing_packet, value);
645 packet_put_bignum2(BIGNUM * value)
647 buffer_put_bignum2(&active_state->outgoing_packet, value);
650 #ifdef OPENSSL_HAS_ECC
652 packet_put_ecpoint(const EC_GROUP *curve, const EC_POINT *point)
654 buffer_put_ecpoint(&active_state->outgoing_packet, curve, point);
659 * Finalizes and sends the packet. If the encryption key has been set,
660 * encrypts the packet before sending.
672 * If using packet compression, compress the payload of the outgoing
675 if (active_state->packet_compression) {
676 buffer_clear(&active_state->compression_buffer);
678 buffer_consume(&active_state->outgoing_packet, 8);
680 buffer_append(&active_state->compression_buffer,
681 "\0\0\0\0\0\0\0\0", 8);
682 buffer_compress(&active_state->outgoing_packet,
683 &active_state->compression_buffer);
684 buffer_clear(&active_state->outgoing_packet);
685 buffer_append(&active_state->outgoing_packet,
686 buffer_ptr(&active_state->compression_buffer),
687 buffer_len(&active_state->compression_buffer));
689 /* Compute packet length without padding (add checksum, remove padding). */
690 len = buffer_len(&active_state->outgoing_packet) + 4 - 8;
692 /* Insert padding. Initialized to zero in packet_start1() */
693 padding = 8 - len % 8;
694 if (!active_state->send_context.plaintext) {
695 cp = buffer_ptr(&active_state->outgoing_packet);
696 for (i = 0; i < padding; i++) {
699 cp[7 - i] = rnd & 0xff;
703 buffer_consume(&active_state->outgoing_packet, 8 - padding);
705 /* Add check bytes. */
706 checksum = ssh_crc32(buffer_ptr(&active_state->outgoing_packet),
707 buffer_len(&active_state->outgoing_packet));
708 put_u32(buf, checksum);
709 buffer_append(&active_state->outgoing_packet, buf, 4);
712 fprintf(stderr, "packet_send plain: ");
713 buffer_dump(&active_state->outgoing_packet);
716 /* Append to output. */
718 buffer_append(&active_state->output, buf, 4);
719 cp = buffer_append_space(&active_state->output,
720 buffer_len(&active_state->outgoing_packet));
721 if (cipher_crypt(&active_state->send_context, 0, cp,
722 buffer_ptr(&active_state->outgoing_packet),
723 buffer_len(&active_state->outgoing_packet), 0, 0) != 0)
724 fatal("%s: cipher_crypt failed", __func__);
727 fprintf(stderr, "encrypted: ");
728 buffer_dump(&active_state->output);
730 active_state->p_send.packets++;
731 active_state->p_send.bytes += len +
732 buffer_len(&active_state->outgoing_packet);
733 buffer_clear(&active_state->outgoing_packet);
736 * Note that the packet is now only buffered in output. It won't be
737 * actually sent until packet_write_wait or packet_write_poll is
743 set_newkeys(int mode)
749 u_int64_t *max_blocks;
752 debug2("set_newkeys: mode %d", mode);
754 if (mode == MODE_OUT) {
755 cc = &active_state->send_context;
756 crypt_type = CIPHER_ENCRYPT;
757 active_state->p_send.packets = active_state->p_send.blocks = 0;
758 max_blocks = &active_state->max_blocks_out;
760 cc = &active_state->receive_context;
761 crypt_type = CIPHER_DECRYPT;
762 active_state->p_read.packets = active_state->p_read.blocks = 0;
763 max_blocks = &active_state->max_blocks_in;
765 if (active_state->newkeys[mode] != NULL) {
766 debug("set_newkeys: rekeying");
768 enc = &active_state->newkeys[mode]->enc;
769 mac = &active_state->newkeys[mode]->mac;
770 comp = &active_state->newkeys[mode]->comp;
772 explicit_bzero(enc->iv, enc->iv_len);
773 explicit_bzero(enc->key, enc->key_len);
774 explicit_bzero(mac->key, mac->key_len);
781 free(active_state->newkeys[mode]);
783 active_state->newkeys[mode] = kex_get_newkeys(mode);
784 if (active_state->newkeys[mode] == NULL)
785 fatal("newkeys: no keys for mode %d", mode);
786 enc = &active_state->newkeys[mode]->enc;
787 mac = &active_state->newkeys[mode]->mac;
788 comp = &active_state->newkeys[mode]->comp;
789 if (cipher_authlen(enc->cipher) == 0 && mac_init(mac) == 0)
791 DBG(debug("cipher_init_context: %d", mode));
792 cipher_init(cc, enc->cipher, enc->key, enc->key_len,
793 enc->iv, enc->iv_len, crypt_type);
794 /* Deleting the keys does not gain extra security */
795 /* explicit_bzero(enc->iv, enc->block_size);
796 explicit_bzero(enc->key, enc->key_len);
797 explicit_bzero(mac->key, mac->key_len); */
798 if ((comp->type == COMP_ZLIB ||
799 (comp->type == COMP_DELAYED &&
800 active_state->after_authentication)) && comp->enabled == 0) {
801 packet_init_compression();
802 if (mode == MODE_OUT)
803 buffer_compress_init_send(6);
805 buffer_compress_init_recv();
809 * The 2^(blocksize*2) limit is too expensive for 3DES,
810 * blowfish, etc, so enforce a 1GB limit for small blocksizes.
812 if (enc->block_size >= 16)
813 *max_blocks = (u_int64_t)1 << (enc->block_size*2);
815 *max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
816 if (active_state->rekey_limit)
817 *max_blocks = MIN(*max_blocks,
818 active_state->rekey_limit / enc->block_size);
822 * Delayed compression for SSH2 is enabled after authentication:
823 * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
824 * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
827 packet_enable_delayed_compress(void)
833 * Remember that we are past the authentication step, so rekeying
834 * with COMP_DELAYED will turn on compression immediately.
836 active_state->after_authentication = 1;
837 for (mode = 0; mode < MODE_MAX; mode++) {
838 /* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
839 if (active_state->newkeys[mode] == NULL)
841 comp = &active_state->newkeys[mode]->comp;
842 if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
843 packet_init_compression();
844 if (mode == MODE_OUT)
845 buffer_compress_init_send(6);
847 buffer_compress_init_recv();
854 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
857 packet_send2_wrapped(void)
859 u_char type, *cp, *macbuf = NULL;
860 u_char padlen, pad = 0;
861 u_int i, len, authlen = 0, aadlen = 0;
868 if (active_state->newkeys[MODE_OUT] != NULL) {
869 enc = &active_state->newkeys[MODE_OUT]->enc;
870 mac = &active_state->newkeys[MODE_OUT]->mac;
871 comp = &active_state->newkeys[MODE_OUT]->comp;
872 /* disable mac for authenticated encryption */
873 if ((authlen = cipher_authlen(enc->cipher)) != 0)
876 block_size = enc ? enc->block_size : 8;
877 aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
879 cp = buffer_ptr(&active_state->outgoing_packet);
883 fprintf(stderr, "plain: ");
884 buffer_dump(&active_state->outgoing_packet);
887 if (comp && comp->enabled) {
888 len = buffer_len(&active_state->outgoing_packet);
889 /* skip header, compress only payload */
890 buffer_consume(&active_state->outgoing_packet, 5);
891 buffer_clear(&active_state->compression_buffer);
892 buffer_compress(&active_state->outgoing_packet,
893 &active_state->compression_buffer);
894 buffer_clear(&active_state->outgoing_packet);
895 buffer_append(&active_state->outgoing_packet, "\0\0\0\0\0", 5);
896 buffer_append(&active_state->outgoing_packet,
897 buffer_ptr(&active_state->compression_buffer),
898 buffer_len(&active_state->compression_buffer));
899 DBG(debug("compression: raw %d compressed %d", len,
900 buffer_len(&active_state->outgoing_packet)));
903 /* sizeof (packet_len + pad_len + payload) */
904 len = buffer_len(&active_state->outgoing_packet);
907 * calc size of padding, alloc space, get random data,
908 * minimum padding is 4 bytes
910 len -= aadlen; /* packet length is not encrypted for EtM modes */
911 padlen = block_size - (len % block_size);
913 padlen += block_size;
914 if (active_state->extra_pad) {
915 /* will wrap if extra_pad+padlen > 255 */
916 active_state->extra_pad =
917 roundup(active_state->extra_pad, block_size);
918 pad = active_state->extra_pad -
919 ((len + padlen) % active_state->extra_pad);
920 debug3("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
921 pad, len, padlen, active_state->extra_pad);
923 active_state->extra_pad = 0;
925 cp = buffer_append_space(&active_state->outgoing_packet, padlen);
926 if (enc && !active_state->send_context.plaintext) {
928 for (i = 0; i < padlen; i++) {
936 explicit_bzero(cp, padlen);
938 /* sizeof (packet_len + pad_len + payload + padding) */
939 len = buffer_len(&active_state->outgoing_packet);
940 cp = buffer_ptr(&active_state->outgoing_packet);
941 /* packet_length includes payload, padding and padding length field */
942 put_u32(cp, len - 4);
944 DBG(debug("send: len %d (includes padlen %d, aadlen %d)",
945 len, padlen, aadlen));
947 /* compute MAC over seqnr and packet(length fields, payload, padding) */
948 if (mac && mac->enabled && !mac->etm) {
949 macbuf = mac_compute(mac, active_state->p_send.seqnr,
950 buffer_ptr(&active_state->outgoing_packet), len);
951 DBG(debug("done calc MAC out #%d", active_state->p_send.seqnr));
953 /* encrypt packet and append to output buffer. */
954 cp = buffer_append_space(&active_state->output, len + authlen);
955 if (cipher_crypt(&active_state->send_context, active_state->p_send.seqnr,
956 cp, buffer_ptr(&active_state->outgoing_packet),
957 len - aadlen, aadlen, authlen) != 0)
958 fatal("%s: cipher_crypt failed", __func__);
959 /* append unencrypted MAC */
960 if (mac && mac->enabled) {
962 /* EtM: compute mac over aadlen + cipher text */
963 macbuf = mac_compute(mac,
964 active_state->p_send.seqnr, cp, len);
965 DBG(debug("done calc MAC(EtM) out #%d",
966 active_state->p_send.seqnr));
968 buffer_append(&active_state->output, macbuf, mac->mac_len);
971 fprintf(stderr, "encrypted: ");
972 buffer_dump(&active_state->output);
974 /* increment sequence number for outgoing packets */
975 if (++active_state->p_send.seqnr == 0)
976 logit("outgoing seqnr wraps around");
977 if (++active_state->p_send.packets == 0)
978 if (!(datafellows & SSH_BUG_NOREKEY))
979 fatal("XXX too many packets with same key");
980 active_state->p_send.blocks += len / block_size;
981 active_state->p_send.bytes += len;
982 buffer_clear(&active_state->outgoing_packet);
984 if (type == SSH2_MSG_NEWKEYS)
985 set_newkeys(MODE_OUT);
986 else if (type == SSH2_MSG_USERAUTH_SUCCESS && active_state->server_side)
987 packet_enable_delayed_compress();
996 cp = buffer_ptr(&active_state->outgoing_packet);
999 /* during rekeying we can only send key exchange messages */
1000 if (active_state->rekeying) {
1001 if ((type < SSH2_MSG_TRANSPORT_MIN) ||
1002 (type > SSH2_MSG_TRANSPORT_MAX) ||
1003 (type == SSH2_MSG_SERVICE_REQUEST) ||
1004 (type == SSH2_MSG_SERVICE_ACCEPT)) {
1005 debug("enqueue packet: %u", type);
1006 p = xcalloc(1, sizeof(*p));
1008 memcpy(&p->payload, &active_state->outgoing_packet,
1010 buffer_init(&active_state->outgoing_packet);
1011 TAILQ_INSERT_TAIL(&active_state->outgoing, p, next);
1016 /* rekeying starts with sending KEXINIT */
1017 if (type == SSH2_MSG_KEXINIT)
1018 active_state->rekeying = 1;
1020 packet_send2_wrapped();
1022 /* after a NEWKEYS message we can send the complete queue */
1023 if (type == SSH2_MSG_NEWKEYS) {
1024 active_state->rekeying = 0;
1025 active_state->rekey_time = monotime();
1026 while ((p = TAILQ_FIRST(&active_state->outgoing))) {
1028 debug("dequeue packet: %u", type);
1029 buffer_free(&active_state->outgoing_packet);
1030 memcpy(&active_state->outgoing_packet, &p->payload,
1032 TAILQ_REMOVE(&active_state->outgoing, p, next);
1034 packet_send2_wrapped();
1046 DBG(debug("packet_send done"));
1050 * Waits until a packet has been received, and returns its type. Note that
1051 * no other data is processed until this returns, so this function should not
1052 * be used during the interactive session.
1056 packet_read_seqnr(u_int32_t *seqnr_p)
1058 int type, len, ret, cont, ms_remain = 0;
1061 struct timeval timeout, start, *timeoutp = NULL;
1063 DBG(debug("packet_read()"));
1065 setp = (fd_set *)xcalloc(howmany(active_state->connection_in + 1,
1066 NFDBITS), sizeof(fd_mask));
1068 /* Since we are blocking, ensure that all written packets have been sent. */
1069 packet_write_wait();
1071 /* Stay in the loop until we have received a complete packet. */
1073 /* Try to read a packet from the buffer. */
1074 type = packet_read_poll_seqnr(seqnr_p);
1076 type == SSH_SMSG_SUCCESS
1077 || type == SSH_SMSG_FAILURE
1078 || type == SSH_CMSG_EOF
1079 || type == SSH_CMSG_EXIT_CONFIRMATION))
1081 /* If we got a packet, return it. */
1082 if (type != SSH_MSG_NONE) {
1087 * Otherwise, wait for some data to arrive, add it to the
1088 * buffer, and try again.
1090 memset(setp, 0, howmany(active_state->connection_in + 1,
1091 NFDBITS) * sizeof(fd_mask));
1092 FD_SET(active_state->connection_in, setp);
1094 if (active_state->packet_timeout_ms > 0) {
1095 ms_remain = active_state->packet_timeout_ms;
1096 timeoutp = &timeout;
1098 /* Wait for some data to arrive. */
1100 if (active_state->packet_timeout_ms != -1) {
1101 ms_to_timeval(&timeout, ms_remain);
1102 gettimeofday(&start, NULL);
1104 if ((ret = select(active_state->connection_in + 1, setp,
1105 NULL, NULL, timeoutp)) >= 0)
1107 if (errno != EAGAIN && errno != EINTR &&
1108 errno != EWOULDBLOCK)
1110 if (active_state->packet_timeout_ms == -1)
1112 ms_subtract_diff(&start, &ms_remain);
1113 if (ms_remain <= 0) {
1119 logit("Connection to %.200s timed out while "
1120 "waiting to read", get_remote_ipaddr());
1123 /* Read data from the socket. */
1126 len = roaming_read(active_state->connection_in, buf,
1127 sizeof(buf), &cont);
1128 } while (len == 0 && cont);
1130 logit("Connection closed by %.200s", get_remote_ipaddr());
1134 fatal("Read from socket failed: %.100s", strerror(errno));
1135 /* Append it to the buffer. */
1136 packet_process_incoming(buf, len);
1144 return packet_read_seqnr(NULL);
1148 * Waits until a packet has been received, verifies that its type matches
1149 * that given, and gives a fatal error and exits if there is a mismatch.
1153 packet_read_expect(int expected_type)
1157 type = packet_read();
1158 if (type != expected_type)
1159 packet_disconnect("Protocol error: expected packet type %d, got %d",
1160 expected_type, type);
1163 /* Checks if a full packet is available in the data received so far via
1164 * packet_process_incoming. If so, reads the packet; otherwise returns
1165 * SSH_MSG_NONE. This does not wait for data from the connection.
1167 * SSH_MSG_DISCONNECT is handled specially here. Also,
1168 * SSH_MSG_IGNORE messages are skipped by this function and are never returned
1173 packet_read_poll1(void)
1175 u_int len, padded_len;
1177 u_int checksum, stored_checksum;
1179 /* Check if input size is less than minimum packet size. */
1180 if (buffer_len(&active_state->input) < 4 + 8)
1181 return SSH_MSG_NONE;
1182 /* Get length of incoming packet. */
1183 cp = buffer_ptr(&active_state->input);
1185 if (len < 1 + 2 + 2 || len > 256 * 1024)
1186 packet_disconnect("Bad packet length %u.", len);
1187 padded_len = (len + 8) & ~7;
1189 /* Check if the packet has been entirely received. */
1190 if (buffer_len(&active_state->input) < 4 + padded_len)
1191 return SSH_MSG_NONE;
1193 /* The entire packet is in buffer. */
1195 /* Consume packet length. */
1196 buffer_consume(&active_state->input, 4);
1199 * Cryptographic attack detector for ssh
1200 * (C)1998 CORE-SDI, Buenos Aires Argentina
1201 * Ariel Futoransky(futo@core-sdi.com)
1203 if (!active_state->receive_context.plaintext) {
1204 switch (detect_attack(buffer_ptr(&active_state->input),
1206 case DEATTACK_DETECTED:
1207 packet_disconnect("crc32 compensation attack: "
1208 "network attack detected");
1209 case DEATTACK_DOS_DETECTED:
1210 packet_disconnect("deattack denial of "
1211 "service detected");
1215 /* Decrypt data to incoming_packet. */
1216 buffer_clear(&active_state->incoming_packet);
1217 cp = buffer_append_space(&active_state->incoming_packet, padded_len);
1218 if (cipher_crypt(&active_state->receive_context, 0, cp,
1219 buffer_ptr(&active_state->input), padded_len, 0, 0) != 0)
1220 fatal("%s: cipher_crypt failed", __func__);
1222 buffer_consume(&active_state->input, padded_len);
1225 fprintf(stderr, "read_poll plain: ");
1226 buffer_dump(&active_state->incoming_packet);
1229 /* Compute packet checksum. */
1230 checksum = ssh_crc32(buffer_ptr(&active_state->incoming_packet),
1231 buffer_len(&active_state->incoming_packet) - 4);
1234 buffer_consume(&active_state->incoming_packet, 8 - len % 8);
1236 /* Test check bytes. */
1237 if (len != buffer_len(&active_state->incoming_packet))
1238 packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
1239 len, buffer_len(&active_state->incoming_packet));
1241 cp = (u_char *)buffer_ptr(&active_state->incoming_packet) + len - 4;
1242 stored_checksum = get_u32(cp);
1243 if (checksum != stored_checksum)
1244 packet_disconnect("Corrupted check bytes on input.");
1245 buffer_consume_end(&active_state->incoming_packet, 4);
1247 if (active_state->packet_compression) {
1248 buffer_clear(&active_state->compression_buffer);
1249 buffer_uncompress(&active_state->incoming_packet,
1250 &active_state->compression_buffer);
1251 buffer_clear(&active_state->incoming_packet);
1252 buffer_append(&active_state->incoming_packet,
1253 buffer_ptr(&active_state->compression_buffer),
1254 buffer_len(&active_state->compression_buffer));
1256 active_state->p_read.packets++;
1257 active_state->p_read.bytes += padded_len + 4;
1258 type = buffer_get_char(&active_state->incoming_packet);
1259 if (type < SSH_MSG_MIN || type > SSH_MSG_MAX)
1260 packet_disconnect("Invalid ssh1 packet type: %d", type);
1265 packet_read_poll2(u_int32_t *seqnr_p)
1268 u_char *macbuf = NULL, *cp, type;
1269 u_int maclen, authlen = 0, aadlen = 0, block_size;
1274 if (active_state->packet_discard)
1275 return SSH_MSG_NONE;
1277 if (active_state->newkeys[MODE_IN] != NULL) {
1278 enc = &active_state->newkeys[MODE_IN]->enc;
1279 mac = &active_state->newkeys[MODE_IN]->mac;
1280 comp = &active_state->newkeys[MODE_IN]->comp;
1281 /* disable mac for authenticated encryption */
1282 if ((authlen = cipher_authlen(enc->cipher)) != 0)
1285 maclen = mac && mac->enabled ? mac->mac_len : 0;
1286 block_size = enc ? enc->block_size : 8;
1287 aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
1289 if (aadlen && active_state->packlen == 0) {
1290 if (cipher_get_length(&active_state->receive_context,
1291 &active_state->packlen,
1292 active_state->p_read.seqnr,
1293 buffer_ptr(&active_state->input),
1294 buffer_len(&active_state->input)) != 0)
1295 return SSH_MSG_NONE;
1296 if (active_state->packlen < 1 + 4 ||
1297 active_state->packlen > PACKET_MAX_SIZE) {
1299 buffer_dump(&active_state->input);
1301 logit("Bad packet length %u.", active_state->packlen);
1302 packet_disconnect("Packet corrupt");
1304 buffer_clear(&active_state->incoming_packet);
1305 } else if (active_state->packlen == 0) {
1307 * check if input size is less than the cipher block size,
1308 * decrypt first block and extract length of incoming packet
1310 if (buffer_len(&active_state->input) < block_size)
1311 return SSH_MSG_NONE;
1312 buffer_clear(&active_state->incoming_packet);
1313 cp = buffer_append_space(&active_state->incoming_packet,
1315 if (cipher_crypt(&active_state->receive_context,
1316 active_state->p_read.seqnr, cp,
1317 buffer_ptr(&active_state->input), block_size, 0, 0) != 0)
1318 fatal("Decryption integrity check failed");
1319 cp = buffer_ptr(&active_state->incoming_packet);
1321 active_state->packlen = get_u32(cp);
1322 if (active_state->packlen < 1 + 4 ||
1323 active_state->packlen > PACKET_MAX_SIZE) {
1325 buffer_dump(&active_state->incoming_packet);
1327 logit("Bad packet length %u.", active_state->packlen);
1328 packet_start_discard(enc, mac, active_state->packlen,
1330 return SSH_MSG_NONE;
1332 buffer_consume(&active_state->input, block_size);
1334 DBG(debug("input: packet len %u", active_state->packlen+4));
1336 /* only the payload is encrypted */
1337 need = active_state->packlen;
1340 * the payload size and the payload are encrypted, but we
1341 * have a partial packet of block_size bytes
1343 need = 4 + active_state->packlen - block_size;
1345 DBG(debug("partial packet: block %d, need %d, maclen %d, authlen %d,"
1346 " aadlen %d", block_size, need, maclen, authlen, aadlen));
1347 if (need % block_size != 0) {
1348 logit("padding error: need %d block %d mod %d",
1349 need, block_size, need % block_size);
1350 packet_start_discard(enc, mac, active_state->packlen,
1351 PACKET_MAX_SIZE - block_size);
1352 return SSH_MSG_NONE;
1355 * check if the entire packet has been received and
1356 * decrypt into incoming_packet:
1357 * 'aadlen' bytes are unencrypted, but authenticated.
1358 * 'need' bytes are encrypted, followed by either
1359 * 'authlen' bytes of authentication tag or
1360 * 'maclen' bytes of message authentication code.
1362 if (buffer_len(&active_state->input) < aadlen + need + authlen + maclen)
1363 return SSH_MSG_NONE;
1365 fprintf(stderr, "read_poll enc/full: ");
1366 buffer_dump(&active_state->input);
1368 /* EtM: compute mac over encrypted input */
1369 if (mac && mac->enabled && mac->etm)
1370 macbuf = mac_compute(mac, active_state->p_read.seqnr,
1371 buffer_ptr(&active_state->input), aadlen + need);
1372 cp = buffer_append_space(&active_state->incoming_packet, aadlen + need);
1373 if (cipher_crypt(&active_state->receive_context,
1374 active_state->p_read.seqnr, cp,
1375 buffer_ptr(&active_state->input), need, aadlen, authlen) != 0)
1376 fatal("Decryption integrity check failed");
1377 buffer_consume(&active_state->input, aadlen + need + authlen);
1379 * compute MAC over seqnr and packet,
1380 * increment sequence number for incoming packet
1382 if (mac && mac->enabled) {
1384 macbuf = mac_compute(mac, active_state->p_read.seqnr,
1385 buffer_ptr(&active_state->incoming_packet),
1386 buffer_len(&active_state->incoming_packet));
1387 if (timingsafe_bcmp(macbuf, buffer_ptr(&active_state->input),
1388 mac->mac_len) != 0) {
1389 logit("Corrupted MAC on input.");
1390 if (need > PACKET_MAX_SIZE)
1391 fatal("internal error need %d", need);
1392 packet_start_discard(enc, mac, active_state->packlen,
1393 PACKET_MAX_SIZE - need);
1394 return SSH_MSG_NONE;
1397 DBG(debug("MAC #%d ok", active_state->p_read.seqnr));
1398 buffer_consume(&active_state->input, mac->mac_len);
1400 /* XXX now it's safe to use fatal/packet_disconnect */
1401 if (seqnr_p != NULL)
1402 *seqnr_p = active_state->p_read.seqnr;
1403 if (++active_state->p_read.seqnr == 0)
1404 logit("incoming seqnr wraps around");
1405 if (++active_state->p_read.packets == 0)
1406 if (!(datafellows & SSH_BUG_NOREKEY))
1407 fatal("XXX too many packets with same key");
1408 active_state->p_read.blocks += (active_state->packlen + 4) / block_size;
1409 active_state->p_read.bytes += active_state->packlen + 4;
1412 cp = buffer_ptr(&active_state->incoming_packet);
1414 DBG(debug("input: padlen %d", padlen));
1416 packet_disconnect("Corrupted padlen %d on input.", padlen);
1418 /* skip packet size + padlen, discard padding */
1419 buffer_consume(&active_state->incoming_packet, 4 + 1);
1420 buffer_consume_end(&active_state->incoming_packet, padlen);
1422 DBG(debug("input: len before de-compress %d",
1423 buffer_len(&active_state->incoming_packet)));
1424 if (comp && comp->enabled) {
1425 buffer_clear(&active_state->compression_buffer);
1426 buffer_uncompress(&active_state->incoming_packet,
1427 &active_state->compression_buffer);
1428 buffer_clear(&active_state->incoming_packet);
1429 buffer_append(&active_state->incoming_packet,
1430 buffer_ptr(&active_state->compression_buffer),
1431 buffer_len(&active_state->compression_buffer));
1432 DBG(debug("input: len after de-compress %d",
1433 buffer_len(&active_state->incoming_packet)));
1436 * get packet type, implies consume.
1437 * return length of payload (without type field)
1439 type = buffer_get_char(&active_state->incoming_packet);
1440 if (type < SSH2_MSG_MIN || type >= SSH2_MSG_LOCAL_MIN)
1441 packet_disconnect("Invalid ssh2 packet type: %d", type);
1442 if (type == SSH2_MSG_NEWKEYS)
1443 set_newkeys(MODE_IN);
1444 else if (type == SSH2_MSG_USERAUTH_SUCCESS &&
1445 !active_state->server_side)
1446 packet_enable_delayed_compress();
1448 fprintf(stderr, "read/plain[%d]:\r\n", type);
1449 buffer_dump(&active_state->incoming_packet);
1451 /* reset for next packet */
1452 active_state->packlen = 0;
1457 packet_read_poll_seqnr(u_int32_t *seqnr_p)
1459 u_int reason, seqnr;
1465 type = packet_read_poll2(seqnr_p);
1467 active_state->keep_alive_timeouts = 0;
1468 DBG(debug("received packet type %d", type));
1471 case SSH2_MSG_IGNORE:
1472 debug3("Received SSH2_MSG_IGNORE");
1474 case SSH2_MSG_DEBUG:
1476 msg = packet_get_string(NULL);
1477 debug("Remote: %.900s", msg);
1479 msg = packet_get_string(NULL);
1482 case SSH2_MSG_DISCONNECT:
1483 reason = packet_get_int();
1484 msg = packet_get_string(NULL);
1485 /* Ignore normal client exit notifications */
1486 do_log2(active_state->server_side &&
1487 reason == SSH2_DISCONNECT_BY_APPLICATION ?
1488 SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_ERROR,
1489 "Received disconnect from %s: %u: %.400s",
1490 get_remote_ipaddr(), reason, msg);
1494 case SSH2_MSG_UNIMPLEMENTED:
1495 seqnr = packet_get_int();
1496 debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1503 type = packet_read_poll1();
1506 return SSH_MSG_NONE;
1507 case SSH_MSG_IGNORE:
1510 msg = packet_get_string(NULL);
1511 debug("Remote: %.900s", msg);
1514 case SSH_MSG_DISCONNECT:
1515 msg = packet_get_string(NULL);
1516 logit("Received disconnect from %s: %.400s",
1517 get_remote_ipaddr(), msg);
1521 DBG(debug("received packet type %d", type));
1529 * Buffers the given amount of input characters. This is intended to be used
1530 * together with packet_read_poll.
1534 packet_process_incoming(const char *buf, u_int len)
1536 if (active_state->packet_discard) {
1537 active_state->keep_alive_timeouts = 0; /* ?? */
1538 if (len >= active_state->packet_discard)
1539 packet_stop_discard();
1540 active_state->packet_discard -= len;
1543 buffer_append(&active_state->input, buf, len);
1546 /* Returns a character from the packet. */
1549 packet_get_char(void)
1553 buffer_get(&active_state->incoming_packet, &ch, 1);
1557 /* Returns an integer from the packet data. */
1560 packet_get_int(void)
1562 return buffer_get_int(&active_state->incoming_packet);
1565 /* Returns an 64 bit integer from the packet data. */
1568 packet_get_int64(void)
1570 return buffer_get_int64(&active_state->incoming_packet);
1574 * Returns an arbitrary precision integer from the packet data. The integer
1575 * must have been initialized before this call.
1579 packet_get_bignum(BIGNUM * value)
1581 buffer_get_bignum(&active_state->incoming_packet, value);
1585 packet_get_bignum2(BIGNUM * value)
1587 buffer_get_bignum2(&active_state->incoming_packet, value);
1590 #ifdef OPENSSL_HAS_ECC
1592 packet_get_ecpoint(const EC_GROUP *curve, EC_POINT *point)
1594 buffer_get_ecpoint(&active_state->incoming_packet, curve, point);
1599 packet_get_raw(u_int *length_ptr)
1601 u_int bytes = buffer_len(&active_state->incoming_packet);
1603 if (length_ptr != NULL)
1604 *length_ptr = bytes;
1605 return buffer_ptr(&active_state->incoming_packet);
1609 packet_remaining(void)
1611 return buffer_len(&active_state->incoming_packet);
1615 * Returns a string from the packet data. The string is allocated using
1616 * xmalloc; it is the responsibility of the calling program to free it when
1617 * no longer needed. The length_ptr argument may be NULL, or point to an
1618 * integer into which the length of the string is stored.
1622 packet_get_string(u_int *length_ptr)
1624 return buffer_get_string(&active_state->incoming_packet, length_ptr);
1628 packet_get_string_ptr(u_int *length_ptr)
1630 return buffer_get_string_ptr(&active_state->incoming_packet, length_ptr);
1633 /* Ensures the returned string has no embedded \0 characters in it. */
1635 packet_get_cstring(u_int *length_ptr)
1637 return buffer_get_cstring(&active_state->incoming_packet, length_ptr);
1641 * Sends a diagnostic message from the server to the client. This message
1642 * can be sent at any time (but not while constructing another message). The
1643 * message is printed immediately, but only if the client is being executed
1644 * in verbose mode. These messages are primarily intended to ease debugging
1645 * authentication problems. The length of the formatted message must not
1646 * exceed 1024 bytes. This will automatically call packet_write_wait.
1650 packet_send_debug(const char *fmt,...)
1655 if (compat20 && (datafellows & SSH_BUG_DEBUG))
1658 va_start(args, fmt);
1659 vsnprintf(buf, sizeof(buf), fmt, args);
1663 packet_start(SSH2_MSG_DEBUG);
1664 packet_put_char(0); /* bool: always display */
1665 packet_put_cstring(buf);
1666 packet_put_cstring("");
1668 packet_start(SSH_MSG_DEBUG);
1669 packet_put_cstring(buf);
1672 packet_write_wait();
1676 * Logs the error plus constructs and sends a disconnect packet, closes the
1677 * connection, and exits. This function never returns. The error message
1678 * should not contain a newline. The length of the formatted message must
1679 * not exceed 1024 bytes.
1683 packet_disconnect(const char *fmt,...)
1687 static int disconnecting = 0;
1689 if (disconnecting) /* Guard against recursive invocations. */
1690 fatal("packet_disconnect called recursively.");
1694 * Format the message. Note that the caller must make sure the
1695 * message is of limited size.
1697 va_start(args, fmt);
1698 vsnprintf(buf, sizeof(buf), fmt, args);
1701 /* Display the error locally */
1702 logit("Disconnecting: %.100s", buf);
1704 /* Send the disconnect message to the other side, and wait for it to get sent. */
1706 packet_start(SSH2_MSG_DISCONNECT);
1707 packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1708 packet_put_cstring(buf);
1709 packet_put_cstring("");
1711 packet_start(SSH_MSG_DISCONNECT);
1712 packet_put_cstring(buf);
1715 packet_write_wait();
1717 /* Stop listening for connections. */
1718 channel_close_all();
1720 /* Close the connection. */
1725 /* Checks if there is any buffered output, and tries to write some of the output. */
1728 packet_write_poll(void)
1730 int len = buffer_len(&active_state->output);
1735 len = roaming_write(active_state->connection_out,
1736 buffer_ptr(&active_state->output), len, &cont);
1738 if (errno == EINTR || errno == EAGAIN ||
1739 errno == EWOULDBLOCK)
1741 fatal("Write failed: %.100s", strerror(errno));
1743 if (len == 0 && !cont)
1744 fatal("Write connection closed");
1745 buffer_consume(&active_state->output, len);
1750 * Calls packet_write_poll repeatedly until all pending output data has been
1755 packet_write_wait(void)
1758 int ret, ms_remain = 0;
1759 struct timeval start, timeout, *timeoutp = NULL;
1761 setp = (fd_set *)xcalloc(howmany(active_state->connection_out + 1,
1762 NFDBITS), sizeof(fd_mask));
1763 packet_write_poll();
1764 while (packet_have_data_to_write()) {
1765 memset(setp, 0, howmany(active_state->connection_out + 1,
1766 NFDBITS) * sizeof(fd_mask));
1767 FD_SET(active_state->connection_out, setp);
1769 if (active_state->packet_timeout_ms > 0) {
1770 ms_remain = active_state->packet_timeout_ms;
1771 timeoutp = &timeout;
1774 if (active_state->packet_timeout_ms != -1) {
1775 ms_to_timeval(&timeout, ms_remain);
1776 gettimeofday(&start, NULL);
1778 if ((ret = select(active_state->connection_out + 1,
1779 NULL, setp, NULL, timeoutp)) >= 0)
1781 if (errno != EAGAIN && errno != EINTR &&
1782 errno != EWOULDBLOCK)
1784 if (active_state->packet_timeout_ms == -1)
1786 ms_subtract_diff(&start, &ms_remain);
1787 if (ms_remain <= 0) {
1793 logit("Connection to %.200s timed out while "
1794 "waiting to write", get_remote_ipaddr());
1797 packet_write_poll();
1802 /* Returns true if there is buffered data to write to the connection. */
1805 packet_have_data_to_write(void)
1807 return buffer_len(&active_state->output) != 0;
1810 /* Returns true if there is not too much data to write to the connection. */
1813 packet_not_very_much_data_to_write(void)
1815 if (active_state->interactive_mode)
1816 return buffer_len(&active_state->output) < 16384;
1818 return buffer_len(&active_state->output) < 128 * 1024;
1822 packet_set_tos(int tos)
1824 #ifndef IP_TOS_IS_BROKEN
1825 if (!packet_connection_is_on_socket())
1827 switch (packet_connection_af()) {
1830 debug3("%s: set IP_TOS 0x%02x", __func__, tos);
1831 if (setsockopt(active_state->connection_in,
1832 IPPROTO_IP, IP_TOS, &tos, sizeof(tos)) < 0)
1833 error("setsockopt IP_TOS %d: %.100s:",
1834 tos, strerror(errno));
1836 # endif /* IP_TOS */
1839 debug3("%s: set IPV6_TCLASS 0x%02x", __func__, tos);
1840 if (setsockopt(active_state->connection_in,
1841 IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof(tos)) < 0)
1842 error("setsockopt IPV6_TCLASS %d: %.100s:",
1843 tos, strerror(errno));
1845 # endif /* IPV6_TCLASS */
1847 #endif /* IP_TOS_IS_BROKEN */
1850 /* Informs that the current session is interactive. Sets IP flags for that. */
1853 packet_set_interactive(int interactive, int qos_interactive, int qos_bulk)
1855 if (active_state->set_interactive_called)
1857 active_state->set_interactive_called = 1;
1859 /* Record that we are in interactive mode. */
1860 active_state->interactive_mode = interactive;
1862 /* Only set socket options if using a socket. */
1863 if (!packet_connection_is_on_socket())
1865 set_nodelay(active_state->connection_in);
1866 packet_set_tos(interactive ? qos_interactive : qos_bulk);
1869 /* Returns true if the current connection is interactive. */
1872 packet_is_interactive(void)
1874 return active_state->interactive_mode;
1878 packet_set_maxsize(u_int s)
1880 if (active_state->set_maxsize_called) {
1881 logit("packet_set_maxsize: called twice: old %d new %d",
1882 active_state->max_packet_size, s);
1885 if (s < 4 * 1024 || s > 1024 * 1024) {
1886 logit("packet_set_maxsize: bad size %d", s);
1889 active_state->set_maxsize_called = 1;
1890 debug("packet_set_maxsize: setting to %d", s);
1891 active_state->max_packet_size = s;
1896 packet_inc_alive_timeouts(void)
1898 return ++active_state->keep_alive_timeouts;
1902 packet_set_alive_timeouts(int ka)
1904 active_state->keep_alive_timeouts = ka;
1908 packet_get_maxsize(void)
1910 return active_state->max_packet_size;
1913 /* roundup current message to pad bytes */
1915 packet_add_padding(u_char pad)
1917 active_state->extra_pad = pad;
1921 * 9.2. Ignored Data Message
1923 * byte SSH_MSG_IGNORE
1926 * All implementations MUST understand (and ignore) this message at any
1927 * time (after receiving the protocol version). No implementation is
1928 * required to send them. This message can be used as an additional
1929 * protection measure against advanced traffic analysis techniques.
1932 packet_send_ignore(int nbytes)
1937 packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1938 packet_put_int(nbytes);
1939 for (i = 0; i < nbytes; i++) {
1942 packet_put_char((u_char)rnd & 0xff);
1947 #ifdef NONE_CIPHER_ENABLED
1949 packet_request_rekeying(void)
1951 rekey_requested = 1;
1955 #define MAX_PACKETS (1U<<31)
1957 packet_need_rekeying(void)
1959 if (datafellows & SSH_BUG_NOREKEY)
1961 #ifdef NONE_CIPHER_ENABLED
1962 if (rekey_requested == 1) {
1963 rekey_requested = 0;
1968 (active_state->p_send.packets > MAX_PACKETS) ||
1969 (active_state->p_read.packets > MAX_PACKETS) ||
1970 (active_state->max_blocks_out &&
1971 (active_state->p_send.blocks > active_state->max_blocks_out)) ||
1972 (active_state->max_blocks_in &&
1973 (active_state->p_read.blocks > active_state->max_blocks_in)) ||
1974 (active_state->rekey_interval != 0 && active_state->rekey_time +
1975 active_state->rekey_interval <= monotime());
1979 packet_set_rekey_limits(u_int32_t bytes, time_t seconds)
1981 debug3("rekey after %lld bytes, %d seconds", (long long)bytes,
1983 active_state->rekey_limit = bytes;
1984 active_state->rekey_interval = seconds;
1986 * We set the time here so that in post-auth privsep slave we count
1987 * from the completion of the authentication.
1989 active_state->rekey_time = monotime();
1993 packet_get_rekey_timeout(void)
1997 seconds = active_state->rekey_time + active_state->rekey_interval -
1999 return (seconds <= 0 ? 1 : seconds);
2003 packet_set_server(void)
2005 active_state->server_side = 1;
2009 packet_set_authenticated(void)
2011 active_state->after_authentication = 1;
2015 packet_get_input(void)
2017 return (void *)&active_state->input;
2021 packet_get_output(void)
2023 return (void *)&active_state->output;
2027 packet_get_newkeys(int mode)
2029 return (void *)active_state->newkeys[mode];
2033 * Save the state for the real connection, and use a separate state when
2034 * resuming a suspended connection.
2037 packet_backup_state(void)
2039 struct session_state *tmp;
2041 close(active_state->connection_in);
2042 active_state->connection_in = -1;
2043 close(active_state->connection_out);
2044 active_state->connection_out = -1;
2048 tmp = alloc_session_state();
2049 backup_state = active_state;
2054 * Swap in the old state when resuming a connecion.
2057 packet_restore_state(void)
2059 struct session_state *tmp;
2064 backup_state = active_state;
2066 active_state->connection_in = backup_state->connection_in;
2067 backup_state->connection_in = -1;
2068 active_state->connection_out = backup_state->connection_out;
2069 backup_state->connection_out = -1;
2070 len = buffer_len(&backup_state->input);
2072 buf = buffer_ptr(&backup_state->input);
2073 buffer_append(&active_state->input, buf, len);
2074 buffer_clear(&backup_state->input);
2075 add_recv_bytes(len);
2079 #ifdef NONE_CIPHER_ENABLED
2081 packet_get_authentication_state(void)
2083 return (active_state->after_authentication);