1 /* $OpenBSD: packet.c,v 1.188 2013/07/12 00:19:58 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;
205 static struct session_state *
206 alloc_session_state(void)
208 struct session_state *s = xcalloc(1, sizeof(*s));
210 s->connection_in = -1;
211 s->connection_out = -1;
212 s->max_packet_size = 32768;
213 s->packet_timeout_ms = -1;
218 * Sets the descriptors used for communication. Disables encryption until
219 * packet_set_encryption_key is called.
222 packet_set_connection(int fd_in, int fd_out)
224 const Cipher *none = cipher_by_name("none");
227 fatal("packet_set_connection: cannot load cipher 'none'");
228 if (active_state == NULL)
229 active_state = alloc_session_state();
230 active_state->connection_in = fd_in;
231 active_state->connection_out = fd_out;
232 cipher_init(&active_state->send_context, none, (const u_char *)"",
233 0, NULL, 0, CIPHER_ENCRYPT);
234 cipher_init(&active_state->receive_context, none, (const u_char *)"",
235 0, NULL, 0, CIPHER_DECRYPT);
236 active_state->newkeys[MODE_IN] = active_state->newkeys[MODE_OUT] = NULL;
237 if (!active_state->initialized) {
238 active_state->initialized = 1;
239 buffer_init(&active_state->input);
240 buffer_init(&active_state->output);
241 buffer_init(&active_state->outgoing_packet);
242 buffer_init(&active_state->incoming_packet);
243 TAILQ_INIT(&active_state->outgoing);
244 active_state->p_send.packets = active_state->p_read.packets = 0;
249 packet_set_timeout(int timeout, int count)
251 if (timeout <= 0 || count <= 0) {
252 active_state->packet_timeout_ms = -1;
255 if ((INT_MAX / 1000) / count < timeout)
256 active_state->packet_timeout_ms = INT_MAX;
258 active_state->packet_timeout_ms = timeout * count * 1000;
262 packet_stop_discard(void)
264 if (active_state->packet_discard_mac) {
267 memset(buf, 'a', sizeof(buf));
268 while (buffer_len(&active_state->incoming_packet) <
270 buffer_append(&active_state->incoming_packet, buf,
272 (void) mac_compute(active_state->packet_discard_mac,
273 active_state->p_read.seqnr,
274 buffer_ptr(&active_state->incoming_packet),
277 logit("Finished discarding for %.200s", get_remote_ipaddr());
282 packet_start_discard(Enc *enc, Mac *mac, u_int packet_length, u_int discard)
284 if (enc == NULL || !cipher_is_cbc(enc->cipher) || (mac && mac->etm))
285 packet_disconnect("Packet corrupt");
286 if (packet_length != PACKET_MAX_SIZE && mac && mac->enabled)
287 active_state->packet_discard_mac = mac;
288 if (buffer_len(&active_state->input) >= discard)
289 packet_stop_discard();
290 active_state->packet_discard = discard -
291 buffer_len(&active_state->input);
294 /* Returns 1 if remote host is connected via socket, 0 if not. */
297 packet_connection_is_on_socket(void)
299 struct sockaddr_storage from, to;
300 socklen_t fromlen, tolen;
302 /* filedescriptors in and out are the same, so it's a socket */
303 if (active_state->connection_in == active_state->connection_out)
305 fromlen = sizeof(from);
306 memset(&from, 0, sizeof(from));
307 if (getpeername(active_state->connection_in, (struct sockaddr *)&from,
311 memset(&to, 0, sizeof(to));
312 if (getpeername(active_state->connection_out, (struct sockaddr *)&to,
315 if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
317 if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
323 * Exports an IV from the CipherContext required to export the key
324 * state back from the unprivileged child to the privileged parent
329 packet_get_keyiv(int mode, u_char *iv, u_int len)
333 if (mode == MODE_OUT)
334 cc = &active_state->send_context;
336 cc = &active_state->receive_context;
338 cipher_get_keyiv(cc, iv, len);
342 packet_get_keycontext(int mode, u_char *dat)
346 if (mode == MODE_OUT)
347 cc = &active_state->send_context;
349 cc = &active_state->receive_context;
351 return (cipher_get_keycontext(cc, dat));
355 packet_set_keycontext(int mode, u_char *dat)
359 if (mode == MODE_OUT)
360 cc = &active_state->send_context;
362 cc = &active_state->receive_context;
364 cipher_set_keycontext(cc, dat);
368 packet_get_keyiv_len(int mode)
372 if (mode == MODE_OUT)
373 cc = &active_state->send_context;
375 cc = &active_state->receive_context;
377 return (cipher_get_keyiv_len(cc));
381 packet_set_iv(int mode, u_char *dat)
385 if (mode == MODE_OUT)
386 cc = &active_state->send_context;
388 cc = &active_state->receive_context;
390 cipher_set_keyiv(cc, dat);
394 packet_get_ssh1_cipher(void)
396 return (cipher_get_number(active_state->receive_context.cipher));
400 packet_get_state(int mode, u_int32_t *seqnr, u_int64_t *blocks,
401 u_int32_t *packets, u_int64_t *bytes)
403 struct packet_state *state;
405 state = (mode == MODE_IN) ?
406 &active_state->p_read : &active_state->p_send;
408 *seqnr = state->seqnr;
410 *blocks = state->blocks;
412 *packets = state->packets;
414 *bytes = state->bytes;
418 packet_set_state(int mode, u_int32_t seqnr, u_int64_t blocks, u_int32_t packets,
421 struct packet_state *state;
423 state = (mode == MODE_IN) ?
424 &active_state->p_read : &active_state->p_send;
425 state->seqnr = seqnr;
426 state->blocks = blocks;
427 state->packets = packets;
428 state->bytes = bytes;
432 packet_connection_af(void)
434 struct sockaddr_storage to;
435 socklen_t tolen = sizeof(to);
437 memset(&to, 0, sizeof(to));
438 if (getsockname(active_state->connection_out, (struct sockaddr *)&to,
442 if (to.ss_family == AF_INET6 &&
443 IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&to)->sin6_addr))
449 /* Sets the connection into non-blocking mode. */
452 packet_set_nonblocking(void)
454 /* Set the socket into non-blocking mode. */
455 set_nonblock(active_state->connection_in);
457 if (active_state->connection_out != active_state->connection_in)
458 set_nonblock(active_state->connection_out);
461 /* Returns the socket used for reading. */
464 packet_get_connection_in(void)
466 return active_state->connection_in;
469 /* Returns the descriptor used for writing. */
472 packet_get_connection_out(void)
474 return active_state->connection_out;
477 /* Closes the connection and clears and frees internal data structures. */
482 if (!active_state->initialized)
484 active_state->initialized = 0;
485 if (active_state->connection_in == active_state->connection_out) {
486 shutdown(active_state->connection_out, SHUT_RDWR);
487 close(active_state->connection_out);
489 close(active_state->connection_in);
490 close(active_state->connection_out);
492 buffer_free(&active_state->input);
493 buffer_free(&active_state->output);
494 buffer_free(&active_state->outgoing_packet);
495 buffer_free(&active_state->incoming_packet);
496 if (active_state->compression_buffer_ready) {
497 buffer_free(&active_state->compression_buffer);
498 buffer_compress_uninit();
500 cipher_cleanup(&active_state->send_context);
501 cipher_cleanup(&active_state->receive_context);
504 /* Sets remote side protocol flags. */
507 packet_set_protocol_flags(u_int protocol_flags)
509 active_state->remote_protocol_flags = protocol_flags;
512 /* Returns the remote protocol flags set earlier by the above function. */
515 packet_get_protocol_flags(void)
517 return active_state->remote_protocol_flags;
521 * Starts packet compression from the next packet on in both directions.
522 * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
526 packet_init_compression(void)
528 if (active_state->compression_buffer_ready == 1)
530 active_state->compression_buffer_ready = 1;
531 buffer_init(&active_state->compression_buffer);
535 packet_start_compression(int level)
537 if (active_state->packet_compression && !compat20)
538 fatal("Compression already enabled.");
539 active_state->packet_compression = 1;
540 packet_init_compression();
541 buffer_compress_init_send(level);
542 buffer_compress_init_recv();
546 * Causes any further packets to be encrypted using the given key. The same
547 * key is used for both sending and reception. However, both directions are
548 * encrypted independently of each other.
552 packet_set_encryption_key(const u_char *key, u_int keylen, int number)
554 const Cipher *cipher = cipher_by_number(number);
557 fatal("packet_set_encryption_key: unknown cipher number %d", number);
559 fatal("packet_set_encryption_key: keylen too small: %d", keylen);
560 if (keylen > SSH_SESSION_KEY_LENGTH)
561 fatal("packet_set_encryption_key: keylen too big: %d", keylen);
562 memcpy(active_state->ssh1_key, key, keylen);
563 active_state->ssh1_keylen = keylen;
564 cipher_init(&active_state->send_context, cipher, key, keylen, NULL,
566 cipher_init(&active_state->receive_context, cipher, key, keylen, NULL,
571 packet_get_encryption_key(u_char *key)
574 return (active_state->ssh1_keylen);
575 memcpy(key, active_state->ssh1_key, active_state->ssh1_keylen);
576 return (active_state->ssh1_keylen);
579 /* Start constructing a packet to send. */
581 packet_start(u_char type)
586 DBG(debug("packet_start[%d]", type));
587 len = compat20 ? 6 : 9;
588 memset(buf, 0, len - 1);
590 buffer_clear(&active_state->outgoing_packet);
591 buffer_append(&active_state->outgoing_packet, buf, len);
594 /* Append payload. */
596 packet_put_char(int value)
600 buffer_append(&active_state->outgoing_packet, &ch, 1);
604 packet_put_int(u_int value)
606 buffer_put_int(&active_state->outgoing_packet, value);
610 packet_put_int64(u_int64_t value)
612 buffer_put_int64(&active_state->outgoing_packet, value);
616 packet_put_string(const void *buf, u_int len)
618 buffer_put_string(&active_state->outgoing_packet, buf, len);
622 packet_put_cstring(const char *str)
624 buffer_put_cstring(&active_state->outgoing_packet, str);
628 packet_put_raw(const void *buf, u_int len)
630 buffer_append(&active_state->outgoing_packet, buf, len);
634 packet_put_bignum(BIGNUM * value)
636 buffer_put_bignum(&active_state->outgoing_packet, value);
640 packet_put_bignum2(BIGNUM * value)
642 buffer_put_bignum2(&active_state->outgoing_packet, value);
645 #ifdef OPENSSL_HAS_ECC
647 packet_put_ecpoint(const EC_GROUP *curve, const EC_POINT *point)
649 buffer_put_ecpoint(&active_state->outgoing_packet, curve, point);
654 * Finalizes and sends the packet. If the encryption key has been set,
655 * encrypts the packet before sending.
667 * If using packet compression, compress the payload of the outgoing
670 if (active_state->packet_compression) {
671 buffer_clear(&active_state->compression_buffer);
673 buffer_consume(&active_state->outgoing_packet, 8);
675 buffer_append(&active_state->compression_buffer,
676 "\0\0\0\0\0\0\0\0", 8);
677 buffer_compress(&active_state->outgoing_packet,
678 &active_state->compression_buffer);
679 buffer_clear(&active_state->outgoing_packet);
680 buffer_append(&active_state->outgoing_packet,
681 buffer_ptr(&active_state->compression_buffer),
682 buffer_len(&active_state->compression_buffer));
684 /* Compute packet length without padding (add checksum, remove padding). */
685 len = buffer_len(&active_state->outgoing_packet) + 4 - 8;
687 /* Insert padding. Initialized to zero in packet_start1() */
688 padding = 8 - len % 8;
689 if (!active_state->send_context.plaintext) {
690 cp = buffer_ptr(&active_state->outgoing_packet);
691 for (i = 0; i < padding; i++) {
694 cp[7 - i] = rnd & 0xff;
698 buffer_consume(&active_state->outgoing_packet, 8 - padding);
700 /* Add check bytes. */
701 checksum = ssh_crc32(buffer_ptr(&active_state->outgoing_packet),
702 buffer_len(&active_state->outgoing_packet));
703 put_u32(buf, checksum);
704 buffer_append(&active_state->outgoing_packet, buf, 4);
707 fprintf(stderr, "packet_send plain: ");
708 buffer_dump(&active_state->outgoing_packet);
711 /* Append to output. */
713 buffer_append(&active_state->output, buf, 4);
714 cp = buffer_append_space(&active_state->output,
715 buffer_len(&active_state->outgoing_packet));
716 cipher_crypt(&active_state->send_context, cp,
717 buffer_ptr(&active_state->outgoing_packet),
718 buffer_len(&active_state->outgoing_packet), 0, 0);
721 fprintf(stderr, "encrypted: ");
722 buffer_dump(&active_state->output);
724 active_state->p_send.packets++;
725 active_state->p_send.bytes += len +
726 buffer_len(&active_state->outgoing_packet);
727 buffer_clear(&active_state->outgoing_packet);
730 * Note that the packet is now only buffered in output. It won't be
731 * actually sent until packet_write_wait or packet_write_poll is
737 set_newkeys(int mode)
743 u_int64_t *max_blocks;
746 debug2("set_newkeys: mode %d", mode);
748 if (mode == MODE_OUT) {
749 cc = &active_state->send_context;
750 crypt_type = CIPHER_ENCRYPT;
751 active_state->p_send.packets = active_state->p_send.blocks = 0;
752 max_blocks = &active_state->max_blocks_out;
754 cc = &active_state->receive_context;
755 crypt_type = CIPHER_DECRYPT;
756 active_state->p_read.packets = active_state->p_read.blocks = 0;
757 max_blocks = &active_state->max_blocks_in;
759 if (active_state->newkeys[mode] != NULL) {
760 debug("set_newkeys: rekeying");
762 enc = &active_state->newkeys[mode]->enc;
763 mac = &active_state->newkeys[mode]->mac;
764 comp = &active_state->newkeys[mode]->comp;
766 memset(enc->iv, 0, enc->iv_len);
767 memset(enc->key, 0, enc->key_len);
768 memset(mac->key, 0, mac->key_len);
775 free(active_state->newkeys[mode]);
777 active_state->newkeys[mode] = kex_get_newkeys(mode);
778 if (active_state->newkeys[mode] == NULL)
779 fatal("newkeys: no keys for mode %d", mode);
780 enc = &active_state->newkeys[mode]->enc;
781 mac = &active_state->newkeys[mode]->mac;
782 comp = &active_state->newkeys[mode]->comp;
783 if (cipher_authlen(enc->cipher) == 0 && mac_init(mac) == 0)
785 DBG(debug("cipher_init_context: %d", mode));
786 cipher_init(cc, enc->cipher, enc->key, enc->key_len,
787 enc->iv, enc->iv_len, crypt_type);
788 /* Deleting the keys does not gain extra security */
789 /* memset(enc->iv, 0, enc->block_size);
790 memset(enc->key, 0, enc->key_len);
791 memset(mac->key, 0, mac->key_len); */
792 if ((comp->type == COMP_ZLIB ||
793 (comp->type == COMP_DELAYED &&
794 active_state->after_authentication)) && comp->enabled == 0) {
795 packet_init_compression();
796 if (mode == MODE_OUT)
797 buffer_compress_init_send(6);
799 buffer_compress_init_recv();
803 * The 2^(blocksize*2) limit is too expensive for 3DES,
804 * blowfish, etc, so enforce a 1GB limit for small blocksizes.
806 if (enc->block_size >= 16)
807 *max_blocks = (u_int64_t)1 << (enc->block_size*2);
809 *max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
810 if (active_state->rekey_limit)
811 *max_blocks = MIN(*max_blocks,
812 active_state->rekey_limit / enc->block_size);
816 * Delayed compression for SSH2 is enabled after authentication:
817 * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
818 * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
821 packet_enable_delayed_compress(void)
827 * Remember that we are past the authentication step, so rekeying
828 * with COMP_DELAYED will turn on compression immediately.
830 active_state->after_authentication = 1;
831 for (mode = 0; mode < MODE_MAX; mode++) {
832 /* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
833 if (active_state->newkeys[mode] == NULL)
835 comp = &active_state->newkeys[mode]->comp;
836 if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
837 packet_init_compression();
838 if (mode == MODE_OUT)
839 buffer_compress_init_send(6);
841 buffer_compress_init_recv();
848 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
851 packet_send2_wrapped(void)
853 u_char type, *cp, *macbuf = NULL;
854 u_char padlen, pad = 0;
855 u_int i, len, authlen = 0, aadlen = 0;
862 if (active_state->newkeys[MODE_OUT] != NULL) {
863 enc = &active_state->newkeys[MODE_OUT]->enc;
864 mac = &active_state->newkeys[MODE_OUT]->mac;
865 comp = &active_state->newkeys[MODE_OUT]->comp;
866 /* disable mac for authenticated encryption */
867 if ((authlen = cipher_authlen(enc->cipher)) != 0)
870 block_size = enc ? enc->block_size : 8;
871 aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
873 cp = buffer_ptr(&active_state->outgoing_packet);
877 fprintf(stderr, "plain: ");
878 buffer_dump(&active_state->outgoing_packet);
881 if (comp && comp->enabled) {
882 len = buffer_len(&active_state->outgoing_packet);
883 /* skip header, compress only payload */
884 buffer_consume(&active_state->outgoing_packet, 5);
885 buffer_clear(&active_state->compression_buffer);
886 buffer_compress(&active_state->outgoing_packet,
887 &active_state->compression_buffer);
888 buffer_clear(&active_state->outgoing_packet);
889 buffer_append(&active_state->outgoing_packet, "\0\0\0\0\0", 5);
890 buffer_append(&active_state->outgoing_packet,
891 buffer_ptr(&active_state->compression_buffer),
892 buffer_len(&active_state->compression_buffer));
893 DBG(debug("compression: raw %d compressed %d", len,
894 buffer_len(&active_state->outgoing_packet)));
897 /* sizeof (packet_len + pad_len + payload) */
898 len = buffer_len(&active_state->outgoing_packet);
901 * calc size of padding, alloc space, get random data,
902 * minimum padding is 4 bytes
904 len -= aadlen; /* packet length is not encrypted for EtM modes */
905 padlen = block_size - (len % block_size);
907 padlen += block_size;
908 if (active_state->extra_pad) {
909 /* will wrap if extra_pad+padlen > 255 */
910 active_state->extra_pad =
911 roundup(active_state->extra_pad, block_size);
912 pad = active_state->extra_pad -
913 ((len + padlen) % active_state->extra_pad);
914 debug3("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
915 pad, len, padlen, active_state->extra_pad);
917 active_state->extra_pad = 0;
919 cp = buffer_append_space(&active_state->outgoing_packet, padlen);
920 if (enc && !active_state->send_context.plaintext) {
922 for (i = 0; i < padlen; i++) {
930 memset(cp, 0, padlen);
932 /* sizeof (packet_len + pad_len + payload + padding) */
933 len = buffer_len(&active_state->outgoing_packet);
934 cp = buffer_ptr(&active_state->outgoing_packet);
935 /* packet_length includes payload, padding and padding length field */
936 put_u32(cp, len - 4);
938 DBG(debug("send: len %d (includes padlen %d, aadlen %d)",
939 len, padlen, aadlen));
941 /* compute MAC over seqnr and packet(length fields, payload, padding) */
942 if (mac && mac->enabled && !mac->etm) {
943 macbuf = mac_compute(mac, active_state->p_send.seqnr,
944 buffer_ptr(&active_state->outgoing_packet), len);
945 DBG(debug("done calc MAC out #%d", active_state->p_send.seqnr));
947 /* encrypt packet and append to output buffer. */
948 cp = buffer_append_space(&active_state->output, len + authlen);
949 cipher_crypt(&active_state->send_context, cp,
950 buffer_ptr(&active_state->outgoing_packet),
951 len - aadlen, aadlen, authlen);
952 /* append unencrypted MAC */
953 if (mac && mac->enabled) {
955 /* EtM: compute mac over aadlen + cipher text */
956 macbuf = mac_compute(mac,
957 active_state->p_send.seqnr, cp, len);
958 DBG(debug("done calc MAC(EtM) out #%d",
959 active_state->p_send.seqnr));
961 buffer_append(&active_state->output, macbuf, mac->mac_len);
964 fprintf(stderr, "encrypted: ");
965 buffer_dump(&active_state->output);
967 /* increment sequence number for outgoing packets */
968 if (++active_state->p_send.seqnr == 0)
969 logit("outgoing seqnr wraps around");
970 if (++active_state->p_send.packets == 0)
971 if (!(datafellows & SSH_BUG_NOREKEY))
972 fatal("XXX too many packets with same key");
973 active_state->p_send.blocks += len / block_size;
974 active_state->p_send.bytes += len;
975 buffer_clear(&active_state->outgoing_packet);
977 if (type == SSH2_MSG_NEWKEYS)
978 set_newkeys(MODE_OUT);
979 else if (type == SSH2_MSG_USERAUTH_SUCCESS && active_state->server_side)
980 packet_enable_delayed_compress();
989 cp = buffer_ptr(&active_state->outgoing_packet);
992 /* during rekeying we can only send key exchange messages */
993 if (active_state->rekeying) {
994 if ((type < SSH2_MSG_TRANSPORT_MIN) ||
995 (type > SSH2_MSG_TRANSPORT_MAX) ||
996 (type == SSH2_MSG_SERVICE_REQUEST) ||
997 (type == SSH2_MSG_SERVICE_ACCEPT)) {
998 debug("enqueue packet: %u", type);
999 p = xmalloc(sizeof(*p));
1001 memcpy(&p->payload, &active_state->outgoing_packet,
1003 buffer_init(&active_state->outgoing_packet);
1004 TAILQ_INSERT_TAIL(&active_state->outgoing, p, next);
1009 /* rekeying starts with sending KEXINIT */
1010 if (type == SSH2_MSG_KEXINIT)
1011 active_state->rekeying = 1;
1013 packet_send2_wrapped();
1015 /* after a NEWKEYS message we can send the complete queue */
1016 if (type == SSH2_MSG_NEWKEYS) {
1017 active_state->rekeying = 0;
1018 active_state->rekey_time = monotime();
1019 while ((p = TAILQ_FIRST(&active_state->outgoing))) {
1021 debug("dequeue packet: %u", type);
1022 buffer_free(&active_state->outgoing_packet);
1023 memcpy(&active_state->outgoing_packet, &p->payload,
1025 TAILQ_REMOVE(&active_state->outgoing, p, next);
1027 packet_send2_wrapped();
1039 DBG(debug("packet_send done"));
1043 * Waits until a packet has been received, and returns its type. Note that
1044 * no other data is processed until this returns, so this function should not
1045 * be used during the interactive session.
1049 packet_read_seqnr(u_int32_t *seqnr_p)
1051 int type, len, ret, cont, ms_remain = 0;
1054 struct timeval timeout, start, *timeoutp = NULL;
1056 DBG(debug("packet_read()"));
1058 setp = (fd_set *)xcalloc(howmany(active_state->connection_in + 1,
1059 NFDBITS), sizeof(fd_mask));
1061 /* Since we are blocking, ensure that all written packets have been sent. */
1062 packet_write_wait();
1064 /* Stay in the loop until we have received a complete packet. */
1066 /* Try to read a packet from the buffer. */
1067 type = packet_read_poll_seqnr(seqnr_p);
1069 type == SSH_SMSG_SUCCESS
1070 || type == SSH_SMSG_FAILURE
1071 || type == SSH_CMSG_EOF
1072 || type == SSH_CMSG_EXIT_CONFIRMATION))
1074 /* If we got a packet, return it. */
1075 if (type != SSH_MSG_NONE) {
1080 * Otherwise, wait for some data to arrive, add it to the
1081 * buffer, and try again.
1083 memset(setp, 0, howmany(active_state->connection_in + 1,
1084 NFDBITS) * sizeof(fd_mask));
1085 FD_SET(active_state->connection_in, setp);
1087 if (active_state->packet_timeout_ms > 0) {
1088 ms_remain = active_state->packet_timeout_ms;
1089 timeoutp = &timeout;
1091 /* Wait for some data to arrive. */
1093 if (active_state->packet_timeout_ms != -1) {
1094 ms_to_timeval(&timeout, ms_remain);
1095 gettimeofday(&start, NULL);
1097 if ((ret = select(active_state->connection_in + 1, setp,
1098 NULL, NULL, timeoutp)) >= 0)
1100 if (errno != EAGAIN && errno != EINTR &&
1101 errno != EWOULDBLOCK)
1103 if (active_state->packet_timeout_ms == -1)
1105 ms_subtract_diff(&start, &ms_remain);
1106 if (ms_remain <= 0) {
1112 logit("Connection to %.200s timed out while "
1113 "waiting to read", get_remote_ipaddr());
1116 /* Read data from the socket. */
1119 len = roaming_read(active_state->connection_in, buf,
1120 sizeof(buf), &cont);
1121 } while (len == 0 && cont);
1123 logit("Connection closed by %.200s", get_remote_ipaddr());
1127 fatal("Read from socket failed: %.100s", strerror(errno));
1128 /* Append it to the buffer. */
1129 packet_process_incoming(buf, len);
1137 return packet_read_seqnr(NULL);
1141 * Waits until a packet has been received, verifies that its type matches
1142 * that given, and gives a fatal error and exits if there is a mismatch.
1146 packet_read_expect(int expected_type)
1150 type = packet_read();
1151 if (type != expected_type)
1152 packet_disconnect("Protocol error: expected packet type %d, got %d",
1153 expected_type, type);
1156 /* Checks if a full packet is available in the data received so far via
1157 * packet_process_incoming. If so, reads the packet; otherwise returns
1158 * SSH_MSG_NONE. This does not wait for data from the connection.
1160 * SSH_MSG_DISCONNECT is handled specially here. Also,
1161 * SSH_MSG_IGNORE messages are skipped by this function and are never returned
1166 packet_read_poll1(void)
1168 u_int len, padded_len;
1170 u_int checksum, stored_checksum;
1172 /* Check if input size is less than minimum packet size. */
1173 if (buffer_len(&active_state->input) < 4 + 8)
1174 return SSH_MSG_NONE;
1175 /* Get length of incoming packet. */
1176 cp = buffer_ptr(&active_state->input);
1178 if (len < 1 + 2 + 2 || len > 256 * 1024)
1179 packet_disconnect("Bad packet length %u.", len);
1180 padded_len = (len + 8) & ~7;
1182 /* Check if the packet has been entirely received. */
1183 if (buffer_len(&active_state->input) < 4 + padded_len)
1184 return SSH_MSG_NONE;
1186 /* The entire packet is in buffer. */
1188 /* Consume packet length. */
1189 buffer_consume(&active_state->input, 4);
1192 * Cryptographic attack detector for ssh
1193 * (C)1998 CORE-SDI, Buenos Aires Argentina
1194 * Ariel Futoransky(futo@core-sdi.com)
1196 if (!active_state->receive_context.plaintext) {
1197 switch (detect_attack(buffer_ptr(&active_state->input),
1199 case DEATTACK_DETECTED:
1200 packet_disconnect("crc32 compensation attack: "
1201 "network attack detected");
1202 case DEATTACK_DOS_DETECTED:
1203 packet_disconnect("deattack denial of "
1204 "service detected");
1208 /* Decrypt data to incoming_packet. */
1209 buffer_clear(&active_state->incoming_packet);
1210 cp = buffer_append_space(&active_state->incoming_packet, padded_len);
1211 cipher_crypt(&active_state->receive_context, cp,
1212 buffer_ptr(&active_state->input), padded_len, 0, 0);
1214 buffer_consume(&active_state->input, padded_len);
1217 fprintf(stderr, "read_poll plain: ");
1218 buffer_dump(&active_state->incoming_packet);
1221 /* Compute packet checksum. */
1222 checksum = ssh_crc32(buffer_ptr(&active_state->incoming_packet),
1223 buffer_len(&active_state->incoming_packet) - 4);
1226 buffer_consume(&active_state->incoming_packet, 8 - len % 8);
1228 /* Test check bytes. */
1229 if (len != buffer_len(&active_state->incoming_packet))
1230 packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
1231 len, buffer_len(&active_state->incoming_packet));
1233 cp = (u_char *)buffer_ptr(&active_state->incoming_packet) + len - 4;
1234 stored_checksum = get_u32(cp);
1235 if (checksum != stored_checksum)
1236 packet_disconnect("Corrupted check bytes on input.");
1237 buffer_consume_end(&active_state->incoming_packet, 4);
1239 if (active_state->packet_compression) {
1240 buffer_clear(&active_state->compression_buffer);
1241 buffer_uncompress(&active_state->incoming_packet,
1242 &active_state->compression_buffer);
1243 buffer_clear(&active_state->incoming_packet);
1244 buffer_append(&active_state->incoming_packet,
1245 buffer_ptr(&active_state->compression_buffer),
1246 buffer_len(&active_state->compression_buffer));
1248 active_state->p_read.packets++;
1249 active_state->p_read.bytes += padded_len + 4;
1250 type = buffer_get_char(&active_state->incoming_packet);
1251 if (type < SSH_MSG_MIN || type > SSH_MSG_MAX)
1252 packet_disconnect("Invalid ssh1 packet type: %d", type);
1257 packet_read_poll2(u_int32_t *seqnr_p)
1260 u_char *macbuf = NULL, *cp, type;
1261 u_int maclen, authlen = 0, aadlen = 0, block_size;
1266 if (active_state->packet_discard)
1267 return SSH_MSG_NONE;
1269 if (active_state->newkeys[MODE_IN] != NULL) {
1270 enc = &active_state->newkeys[MODE_IN]->enc;
1271 mac = &active_state->newkeys[MODE_IN]->mac;
1272 comp = &active_state->newkeys[MODE_IN]->comp;
1273 /* disable mac for authenticated encryption */
1274 if ((authlen = cipher_authlen(enc->cipher)) != 0)
1277 maclen = mac && mac->enabled ? mac->mac_len : 0;
1278 block_size = enc ? enc->block_size : 8;
1279 aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
1281 if (aadlen && active_state->packlen == 0) {
1282 if (buffer_len(&active_state->input) < 4)
1283 return SSH_MSG_NONE;
1284 cp = buffer_ptr(&active_state->input);
1285 active_state->packlen = get_u32(cp);
1286 if (active_state->packlen < 1 + 4 ||
1287 active_state->packlen > PACKET_MAX_SIZE) {
1289 buffer_dump(&active_state->input);
1291 logit("Bad packet length %u.", active_state->packlen);
1292 packet_disconnect("Packet corrupt");
1294 buffer_clear(&active_state->incoming_packet);
1295 } else if (active_state->packlen == 0) {
1297 * check if input size is less than the cipher block size,
1298 * decrypt first block and extract length of incoming packet
1300 if (buffer_len(&active_state->input) < block_size)
1301 return SSH_MSG_NONE;
1302 buffer_clear(&active_state->incoming_packet);
1303 cp = buffer_append_space(&active_state->incoming_packet,
1305 cipher_crypt(&active_state->receive_context, cp,
1306 buffer_ptr(&active_state->input), block_size, 0, 0);
1307 cp = buffer_ptr(&active_state->incoming_packet);
1308 active_state->packlen = get_u32(cp);
1309 if (active_state->packlen < 1 + 4 ||
1310 active_state->packlen > PACKET_MAX_SIZE) {
1312 buffer_dump(&active_state->incoming_packet);
1314 logit("Bad packet length %u.", active_state->packlen);
1315 packet_start_discard(enc, mac, active_state->packlen,
1317 return SSH_MSG_NONE;
1319 buffer_consume(&active_state->input, block_size);
1321 DBG(debug("input: packet len %u", active_state->packlen+4));
1323 /* only the payload is encrypted */
1324 need = active_state->packlen;
1327 * the payload size and the payload are encrypted, but we
1328 * have a partial packet of block_size bytes
1330 need = 4 + active_state->packlen - block_size;
1332 DBG(debug("partial packet: block %d, need %d, maclen %d, authlen %d,"
1333 " aadlen %d", block_size, need, maclen, authlen, aadlen));
1334 if (need % block_size != 0) {
1335 logit("padding error: need %d block %d mod %d",
1336 need, block_size, need % block_size);
1337 packet_start_discard(enc, mac, active_state->packlen,
1338 PACKET_MAX_SIZE - block_size);
1339 return SSH_MSG_NONE;
1342 * check if the entire packet has been received and
1343 * decrypt into incoming_packet:
1344 * 'aadlen' bytes are unencrypted, but authenticated.
1345 * 'need' bytes are encrypted, followed by either
1346 * 'authlen' bytes of authentication tag or
1347 * 'maclen' bytes of message authentication code.
1349 if (buffer_len(&active_state->input) < aadlen + need + authlen + maclen)
1350 return SSH_MSG_NONE;
1352 fprintf(stderr, "read_poll enc/full: ");
1353 buffer_dump(&active_state->input);
1355 /* EtM: compute mac over encrypted input */
1356 if (mac && mac->enabled && mac->etm)
1357 macbuf = mac_compute(mac, active_state->p_read.seqnr,
1358 buffer_ptr(&active_state->input), aadlen + need);
1359 cp = buffer_append_space(&active_state->incoming_packet, aadlen + need);
1360 cipher_crypt(&active_state->receive_context, cp,
1361 buffer_ptr(&active_state->input), need, aadlen, authlen);
1362 buffer_consume(&active_state->input, aadlen + need + authlen);
1364 * compute MAC over seqnr and packet,
1365 * increment sequence number for incoming packet
1367 if (mac && mac->enabled) {
1369 macbuf = mac_compute(mac, active_state->p_read.seqnr,
1370 buffer_ptr(&active_state->incoming_packet),
1371 buffer_len(&active_state->incoming_packet));
1372 if (timingsafe_bcmp(macbuf, buffer_ptr(&active_state->input),
1373 mac->mac_len) != 0) {
1374 logit("Corrupted MAC on input.");
1375 if (need > PACKET_MAX_SIZE)
1376 fatal("internal error need %d", need);
1377 packet_start_discard(enc, mac, active_state->packlen,
1378 PACKET_MAX_SIZE - need);
1379 return SSH_MSG_NONE;
1382 DBG(debug("MAC #%d ok", active_state->p_read.seqnr));
1383 buffer_consume(&active_state->input, mac->mac_len);
1385 /* XXX now it's safe to use fatal/packet_disconnect */
1386 if (seqnr_p != NULL)
1387 *seqnr_p = active_state->p_read.seqnr;
1388 if (++active_state->p_read.seqnr == 0)
1389 logit("incoming seqnr wraps around");
1390 if (++active_state->p_read.packets == 0)
1391 if (!(datafellows & SSH_BUG_NOREKEY))
1392 fatal("XXX too many packets with same key");
1393 active_state->p_read.blocks += (active_state->packlen + 4) / block_size;
1394 active_state->p_read.bytes += active_state->packlen + 4;
1397 cp = buffer_ptr(&active_state->incoming_packet);
1399 DBG(debug("input: padlen %d", padlen));
1401 packet_disconnect("Corrupted padlen %d on input.", padlen);
1403 /* skip packet size + padlen, discard padding */
1404 buffer_consume(&active_state->incoming_packet, 4 + 1);
1405 buffer_consume_end(&active_state->incoming_packet, padlen);
1407 DBG(debug("input: len before de-compress %d",
1408 buffer_len(&active_state->incoming_packet)));
1409 if (comp && comp->enabled) {
1410 buffer_clear(&active_state->compression_buffer);
1411 buffer_uncompress(&active_state->incoming_packet,
1412 &active_state->compression_buffer);
1413 buffer_clear(&active_state->incoming_packet);
1414 buffer_append(&active_state->incoming_packet,
1415 buffer_ptr(&active_state->compression_buffer),
1416 buffer_len(&active_state->compression_buffer));
1417 DBG(debug("input: len after de-compress %d",
1418 buffer_len(&active_state->incoming_packet)));
1421 * get packet type, implies consume.
1422 * return length of payload (without type field)
1424 type = buffer_get_char(&active_state->incoming_packet);
1425 if (type < SSH2_MSG_MIN || type >= SSH2_MSG_LOCAL_MIN)
1426 packet_disconnect("Invalid ssh2 packet type: %d", type);
1427 if (type == SSH2_MSG_NEWKEYS)
1428 set_newkeys(MODE_IN);
1429 else if (type == SSH2_MSG_USERAUTH_SUCCESS &&
1430 !active_state->server_side)
1431 packet_enable_delayed_compress();
1433 fprintf(stderr, "read/plain[%d]:\r\n", type);
1434 buffer_dump(&active_state->incoming_packet);
1436 /* reset for next packet */
1437 active_state->packlen = 0;
1442 packet_read_poll_seqnr(u_int32_t *seqnr_p)
1444 u_int reason, seqnr;
1450 type = packet_read_poll2(seqnr_p);
1452 active_state->keep_alive_timeouts = 0;
1453 DBG(debug("received packet type %d", type));
1456 case SSH2_MSG_IGNORE:
1457 debug3("Received SSH2_MSG_IGNORE");
1459 case SSH2_MSG_DEBUG:
1461 msg = packet_get_string(NULL);
1462 debug("Remote: %.900s", msg);
1464 msg = packet_get_string(NULL);
1467 case SSH2_MSG_DISCONNECT:
1468 reason = packet_get_int();
1469 msg = packet_get_string(NULL);
1470 /* Ignore normal client exit notifications */
1471 do_log2(active_state->server_side &&
1472 reason == SSH2_DISCONNECT_BY_APPLICATION ?
1473 SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_ERROR,
1474 "Received disconnect from %s: %u: %.400s",
1475 get_remote_ipaddr(), reason, msg);
1479 case SSH2_MSG_UNIMPLEMENTED:
1480 seqnr = packet_get_int();
1481 debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1488 type = packet_read_poll1();
1491 return SSH_MSG_NONE;
1492 case SSH_MSG_IGNORE:
1495 msg = packet_get_string(NULL);
1496 debug("Remote: %.900s", msg);
1499 case SSH_MSG_DISCONNECT:
1500 msg = packet_get_string(NULL);
1501 error("Received disconnect from %s: %.400s",
1502 get_remote_ipaddr(), msg);
1506 DBG(debug("received packet type %d", type));
1514 * Buffers the given amount of input characters. This is intended to be used
1515 * together with packet_read_poll.
1519 packet_process_incoming(const char *buf, u_int len)
1521 if (active_state->packet_discard) {
1522 active_state->keep_alive_timeouts = 0; /* ?? */
1523 if (len >= active_state->packet_discard)
1524 packet_stop_discard();
1525 active_state->packet_discard -= len;
1528 buffer_append(&active_state->input, buf, len);
1531 /* Returns a character from the packet. */
1534 packet_get_char(void)
1538 buffer_get(&active_state->incoming_packet, &ch, 1);
1542 /* Returns an integer from the packet data. */
1545 packet_get_int(void)
1547 return buffer_get_int(&active_state->incoming_packet);
1550 /* Returns an 64 bit integer from the packet data. */
1553 packet_get_int64(void)
1555 return buffer_get_int64(&active_state->incoming_packet);
1559 * Returns an arbitrary precision integer from the packet data. The integer
1560 * must have been initialized before this call.
1564 packet_get_bignum(BIGNUM * value)
1566 buffer_get_bignum(&active_state->incoming_packet, value);
1570 packet_get_bignum2(BIGNUM * value)
1572 buffer_get_bignum2(&active_state->incoming_packet, value);
1575 #ifdef OPENSSL_HAS_ECC
1577 packet_get_ecpoint(const EC_GROUP *curve, EC_POINT *point)
1579 buffer_get_ecpoint(&active_state->incoming_packet, curve, point);
1584 packet_get_raw(u_int *length_ptr)
1586 u_int bytes = buffer_len(&active_state->incoming_packet);
1588 if (length_ptr != NULL)
1589 *length_ptr = bytes;
1590 return buffer_ptr(&active_state->incoming_packet);
1594 packet_remaining(void)
1596 return buffer_len(&active_state->incoming_packet);
1600 * Returns a string from the packet data. The string is allocated using
1601 * xmalloc; it is the responsibility of the calling program to free it when
1602 * no longer needed. The length_ptr argument may be NULL, or point to an
1603 * integer into which the length of the string is stored.
1607 packet_get_string(u_int *length_ptr)
1609 return buffer_get_string(&active_state->incoming_packet, length_ptr);
1613 packet_get_string_ptr(u_int *length_ptr)
1615 return buffer_get_string_ptr(&active_state->incoming_packet, length_ptr);
1618 /* Ensures the returned string has no embedded \0 characters in it. */
1620 packet_get_cstring(u_int *length_ptr)
1622 return buffer_get_cstring(&active_state->incoming_packet, length_ptr);
1626 * Sends a diagnostic message from the server to the client. This message
1627 * can be sent at any time (but not while constructing another message). The
1628 * message is printed immediately, but only if the client is being executed
1629 * in verbose mode. These messages are primarily intended to ease debugging
1630 * authentication problems. The length of the formatted message must not
1631 * exceed 1024 bytes. This will automatically call packet_write_wait.
1635 packet_send_debug(const char *fmt,...)
1640 if (compat20 && (datafellows & SSH_BUG_DEBUG))
1643 va_start(args, fmt);
1644 vsnprintf(buf, sizeof(buf), fmt, args);
1648 packet_start(SSH2_MSG_DEBUG);
1649 packet_put_char(0); /* bool: always display */
1650 packet_put_cstring(buf);
1651 packet_put_cstring("");
1653 packet_start(SSH_MSG_DEBUG);
1654 packet_put_cstring(buf);
1657 packet_write_wait();
1661 * Logs the error plus constructs and sends a disconnect packet, closes the
1662 * connection, and exits. This function never returns. The error message
1663 * should not contain a newline. The length of the formatted message must
1664 * not exceed 1024 bytes.
1668 packet_disconnect(const char *fmt,...)
1672 static int disconnecting = 0;
1674 if (disconnecting) /* Guard against recursive invocations. */
1675 fatal("packet_disconnect called recursively.");
1679 * Format the message. Note that the caller must make sure the
1680 * message is of limited size.
1682 va_start(args, fmt);
1683 vsnprintf(buf, sizeof(buf), fmt, args);
1686 /* Display the error locally */
1687 logit("Disconnecting: %.100s", buf);
1689 /* Send the disconnect message to the other side, and wait for it to get sent. */
1691 packet_start(SSH2_MSG_DISCONNECT);
1692 packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1693 packet_put_cstring(buf);
1694 packet_put_cstring("");
1696 packet_start(SSH_MSG_DISCONNECT);
1697 packet_put_cstring(buf);
1700 packet_write_wait();
1702 /* Stop listening for connections. */
1703 channel_close_all();
1705 /* Close the connection. */
1710 /* Checks if there is any buffered output, and tries to write some of the output. */
1713 packet_write_poll(void)
1715 int len = buffer_len(&active_state->output);
1720 len = roaming_write(active_state->connection_out,
1721 buffer_ptr(&active_state->output), len, &cont);
1723 if (errno == EINTR || errno == EAGAIN ||
1724 errno == EWOULDBLOCK)
1726 fatal("Write failed: %.100s", strerror(errno));
1728 if (len == 0 && !cont)
1729 fatal("Write connection closed");
1730 buffer_consume(&active_state->output, len);
1735 * Calls packet_write_poll repeatedly until all pending output data has been
1740 packet_write_wait(void)
1743 int ret, ms_remain = 0;
1744 struct timeval start, timeout, *timeoutp = NULL;
1746 setp = (fd_set *)xcalloc(howmany(active_state->connection_out + 1,
1747 NFDBITS), sizeof(fd_mask));
1748 packet_write_poll();
1749 while (packet_have_data_to_write()) {
1750 memset(setp, 0, howmany(active_state->connection_out + 1,
1751 NFDBITS) * sizeof(fd_mask));
1752 FD_SET(active_state->connection_out, setp);
1754 if (active_state->packet_timeout_ms > 0) {
1755 ms_remain = active_state->packet_timeout_ms;
1756 timeoutp = &timeout;
1759 if (active_state->packet_timeout_ms != -1) {
1760 ms_to_timeval(&timeout, ms_remain);
1761 gettimeofday(&start, NULL);
1763 if ((ret = select(active_state->connection_out + 1,
1764 NULL, setp, NULL, timeoutp)) >= 0)
1766 if (errno != EAGAIN && errno != EINTR &&
1767 errno != EWOULDBLOCK)
1769 if (active_state->packet_timeout_ms == -1)
1771 ms_subtract_diff(&start, &ms_remain);
1772 if (ms_remain <= 0) {
1778 logit("Connection to %.200s timed out while "
1779 "waiting to write", get_remote_ipaddr());
1782 packet_write_poll();
1787 /* Returns true if there is buffered data to write to the connection. */
1790 packet_have_data_to_write(void)
1792 return buffer_len(&active_state->output) != 0;
1795 /* Returns true if there is not too much data to write to the connection. */
1798 packet_not_very_much_data_to_write(void)
1800 if (active_state->interactive_mode)
1801 return buffer_len(&active_state->output) < 16384;
1803 return buffer_len(&active_state->output) < 128 * 1024;
1807 packet_set_tos(int tos)
1809 #ifndef IP_TOS_IS_BROKEN
1810 if (!packet_connection_is_on_socket())
1812 switch (packet_connection_af()) {
1815 debug3("%s: set IP_TOS 0x%02x", __func__, tos);
1816 if (setsockopt(active_state->connection_in,
1817 IPPROTO_IP, IP_TOS, &tos, sizeof(tos)) < 0)
1818 error("setsockopt IP_TOS %d: %.100s:",
1819 tos, strerror(errno));
1821 # endif /* IP_TOS */
1824 debug3("%s: set IPV6_TCLASS 0x%02x", __func__, tos);
1825 if (setsockopt(active_state->connection_in,
1826 IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof(tos)) < 0)
1827 error("setsockopt IPV6_TCLASS %d: %.100s:",
1828 tos, strerror(errno));
1830 # endif /* IPV6_TCLASS */
1832 #endif /* IP_TOS_IS_BROKEN */
1835 /* Informs that the current session is interactive. Sets IP flags for that. */
1838 packet_set_interactive(int interactive, int qos_interactive, int qos_bulk)
1840 if (active_state->set_interactive_called)
1842 active_state->set_interactive_called = 1;
1844 /* Record that we are in interactive mode. */
1845 active_state->interactive_mode = interactive;
1847 /* Only set socket options if using a socket. */
1848 if (!packet_connection_is_on_socket())
1850 set_nodelay(active_state->connection_in);
1851 packet_set_tos(interactive ? qos_interactive : qos_bulk);
1854 /* Returns true if the current connection is interactive. */
1857 packet_is_interactive(void)
1859 return active_state->interactive_mode;
1863 packet_set_maxsize(u_int s)
1865 if (active_state->set_maxsize_called) {
1866 logit("packet_set_maxsize: called twice: old %d new %d",
1867 active_state->max_packet_size, s);
1870 if (s < 4 * 1024 || s > 1024 * 1024) {
1871 logit("packet_set_maxsize: bad size %d", s);
1874 active_state->set_maxsize_called = 1;
1875 debug("packet_set_maxsize: setting to %d", s);
1876 active_state->max_packet_size = s;
1881 packet_inc_alive_timeouts(void)
1883 return ++active_state->keep_alive_timeouts;
1887 packet_set_alive_timeouts(int ka)
1889 active_state->keep_alive_timeouts = ka;
1893 packet_get_maxsize(void)
1895 return active_state->max_packet_size;
1898 /* roundup current message to pad bytes */
1900 packet_add_padding(u_char pad)
1902 active_state->extra_pad = pad;
1906 * 9.2. Ignored Data Message
1908 * byte SSH_MSG_IGNORE
1911 * All implementations MUST understand (and ignore) this message at any
1912 * time (after receiving the protocol version). No implementation is
1913 * required to send them. This message can be used as an additional
1914 * protection measure against advanced traffic analysis techniques.
1917 packet_send_ignore(int nbytes)
1922 packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1923 packet_put_int(nbytes);
1924 for (i = 0; i < nbytes; i++) {
1927 packet_put_char((u_char)rnd & 0xff);
1932 #define MAX_PACKETS (1U<<31)
1934 packet_need_rekeying(void)
1936 if (datafellows & SSH_BUG_NOREKEY)
1939 (active_state->p_send.packets > MAX_PACKETS) ||
1940 (active_state->p_read.packets > MAX_PACKETS) ||
1941 (active_state->max_blocks_out &&
1942 (active_state->p_send.blocks > active_state->max_blocks_out)) ||
1943 (active_state->max_blocks_in &&
1944 (active_state->p_read.blocks > active_state->max_blocks_in)) ||
1945 (active_state->rekey_interval != 0 && active_state->rekey_time +
1946 active_state->rekey_interval <= monotime());
1950 packet_set_rekey_limits(u_int32_t bytes, time_t seconds)
1952 debug3("rekey after %lld bytes, %d seconds", (long long)bytes,
1954 active_state->rekey_limit = bytes;
1955 active_state->rekey_interval = seconds;
1957 * We set the time here so that in post-auth privsep slave we count
1958 * from the completion of the authentication.
1960 active_state->rekey_time = monotime();
1964 packet_get_rekey_timeout(void)
1968 seconds = active_state->rekey_time + active_state->rekey_interval -
1970 return (seconds <= 0 ? 1 : seconds);
1974 packet_set_server(void)
1976 active_state->server_side = 1;
1980 packet_set_authenticated(void)
1982 active_state->after_authentication = 1;
1986 packet_get_input(void)
1988 return (void *)&active_state->input;
1992 packet_get_output(void)
1994 return (void *)&active_state->output;
1998 packet_get_newkeys(int mode)
2000 return (void *)active_state->newkeys[mode];
2004 * Save the state for the real connection, and use a separate state when
2005 * resuming a suspended connection.
2008 packet_backup_state(void)
2010 struct session_state *tmp;
2012 close(active_state->connection_in);
2013 active_state->connection_in = -1;
2014 close(active_state->connection_out);
2015 active_state->connection_out = -1;
2019 tmp = alloc_session_state();
2020 backup_state = active_state;
2025 * Swap in the old state when resuming a connecion.
2028 packet_restore_state(void)
2030 struct session_state *tmp;
2035 backup_state = active_state;
2037 active_state->connection_in = backup_state->connection_in;
2038 backup_state->connection_in = -1;
2039 active_state->connection_out = backup_state->connection_out;
2040 backup_state->connection_out = -1;
2041 len = buffer_len(&backup_state->input);
2043 buf = buffer_ptr(&backup_state->input);
2044 buffer_append(&active_state->input, buf, len);
2045 buffer_clear(&backup_state->input);
2046 add_recv_bytes(len);