1 /* $OpenBSD: packet.c,v 1.189 2013/11/08 00:39:15 djm Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * This file contains code implementing the packet protocol and communication
7 * with the other side. This same code is used both on client and server side.
9 * As far as I am concerned, the code I have written for this software
10 * can be used freely for any purpose. Any derived versions of this
11 * software must be clearly marked as such, and if the derived work is
12 * incompatible with the protocol description in the RFC file, it must be
13 * called by a name other than "ssh" or "Secure Shell".
16 * SSH2 packet format added by Markus Friedl.
17 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
19 * Redistribution and use in source and binary forms, with or without
20 * modification, are permitted provided that the following conditions
22 * 1. Redistributions of source code must retain the above copyright
23 * notice, this list of conditions and the following disclaimer.
24 * 2. Redistributions in binary form must reproduce the above copyright
25 * notice, this list of conditions and the following disclaimer in the
26 * documentation and/or other materials provided with the distribution.
28 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
29 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
30 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
31 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
32 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
33 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
34 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
35 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
36 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
37 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42 #include <sys/types.h>
43 #include "openbsd-compat/sys-queue.h"
44 #include <sys/param.h>
45 #include <sys/socket.h>
46 #ifdef HAVE_SYS_TIME_H
47 # include <sys/time.h>
50 #include <netinet/in.h>
51 #include <netinet/ip.h>
52 #include <arpa/inet.h>
89 #define PACKET_MAX_SIZE (256 * 1024)
99 TAILQ_ENTRY(packet) next;
104 struct session_state {
106 * This variable contains the file descriptors used for
107 * communicating with the other side. connection_in is used for
108 * reading; connection_out for writing. These can be the same
109 * descriptor, in which case it is assumed to be a socket.
114 /* Protocol flags for the remote side. */
115 u_int remote_protocol_flags;
117 /* Encryption context for receiving data. Only used for decryption. */
118 CipherContext receive_context;
120 /* Encryption context for sending data. Only used for encryption. */
121 CipherContext send_context;
123 /* Buffer for raw input data from the socket. */
126 /* Buffer for raw output data going to the socket. */
129 /* Buffer for the partial outgoing packet being constructed. */
130 Buffer outgoing_packet;
132 /* Buffer for the incoming packet currently being processed. */
133 Buffer incoming_packet;
135 /* Scratch buffer for packet compression/decompression. */
136 Buffer compression_buffer;
137 int compression_buffer_ready;
140 * Flag indicating whether packet compression/decompression is
143 int packet_compression;
145 /* default maximum packet size */
146 u_int max_packet_size;
148 /* Flag indicating whether this module has been initialized. */
151 /* Set to true if the connection is interactive. */
152 int interactive_mode;
154 /* Set to true if we are the server side. */
157 /* Set to true if we are authenticated. */
158 int after_authentication;
160 int keep_alive_timeouts;
162 /* The maximum time that we will wait to send or receive a packet */
163 int packet_timeout_ms;
165 /* Session key information for Encryption and MAC */
166 Newkeys *newkeys[MODE_MAX];
167 struct packet_state p_read, p_send;
169 /* Volume-based rekeying */
170 u_int64_t max_blocks_in, max_blocks_out;
171 u_int32_t rekey_limit;
173 /* Time-based rekeying */
174 time_t rekey_interval; /* how often in seconds */
175 time_t rekey_time; /* time of last rekeying */
177 /* Session key for protocol v1 */
178 u_char ssh1_key[SSH_SESSION_KEY_LENGTH];
181 /* roundup current message to extra_pad bytes */
184 /* XXX discard incoming data after MAC error */
185 u_int packet_discard;
186 Mac *packet_discard_mac;
188 /* Used in packet_read_poll2() */
191 /* Used in packet_send2 */
194 /* Used in packet_set_interactive */
195 int set_interactive_called;
197 /* Used in packet_set_maxsize */
198 int set_maxsize_called;
200 TAILQ_HEAD(, packet) outgoing;
203 static struct session_state *active_state, *backup_state;
204 #ifdef NONE_CIPHER_ENABLED
205 static int rekey_requested = 0;
208 static struct session_state *
209 alloc_session_state(void)
211 struct session_state *s = xcalloc(1, sizeof(*s));
213 s->connection_in = -1;
214 s->connection_out = -1;
215 s->max_packet_size = 32768;
216 s->packet_timeout_ms = -1;
221 * Sets the descriptors used for communication. Disables encryption until
222 * packet_set_encryption_key is called.
225 packet_set_connection(int fd_in, int fd_out)
227 const Cipher *none = cipher_by_name("none");
230 fatal("packet_set_connection: cannot load cipher 'none'");
231 if (active_state == NULL)
232 active_state = alloc_session_state();
233 active_state->connection_in = fd_in;
234 active_state->connection_out = fd_out;
235 cipher_init(&active_state->send_context, none, (const u_char *)"",
236 0, NULL, 0, CIPHER_ENCRYPT);
237 cipher_init(&active_state->receive_context, none, (const u_char *)"",
238 0, NULL, 0, CIPHER_DECRYPT);
239 active_state->newkeys[MODE_IN] = active_state->newkeys[MODE_OUT] = NULL;
240 if (!active_state->initialized) {
241 active_state->initialized = 1;
242 buffer_init(&active_state->input);
243 buffer_init(&active_state->output);
244 buffer_init(&active_state->outgoing_packet);
245 buffer_init(&active_state->incoming_packet);
246 TAILQ_INIT(&active_state->outgoing);
247 active_state->p_send.packets = active_state->p_read.packets = 0;
252 packet_set_timeout(int timeout, int count)
254 if (timeout <= 0 || count <= 0) {
255 active_state->packet_timeout_ms = -1;
258 if ((INT_MAX / 1000) / count < timeout)
259 active_state->packet_timeout_ms = INT_MAX;
261 active_state->packet_timeout_ms = timeout * count * 1000;
265 packet_stop_discard(void)
267 if (active_state->packet_discard_mac) {
270 memset(buf, 'a', sizeof(buf));
271 while (buffer_len(&active_state->incoming_packet) <
273 buffer_append(&active_state->incoming_packet, buf,
275 (void) mac_compute(active_state->packet_discard_mac,
276 active_state->p_read.seqnr,
277 buffer_ptr(&active_state->incoming_packet),
280 logit("Finished discarding for %.200s", get_remote_ipaddr());
285 packet_start_discard(Enc *enc, Mac *mac, u_int packet_length, u_int discard)
287 if (enc == NULL || !cipher_is_cbc(enc->cipher) || (mac && mac->etm))
288 packet_disconnect("Packet corrupt");
289 if (packet_length != PACKET_MAX_SIZE && mac && mac->enabled)
290 active_state->packet_discard_mac = mac;
291 if (buffer_len(&active_state->input) >= discard)
292 packet_stop_discard();
293 active_state->packet_discard = discard -
294 buffer_len(&active_state->input);
297 /* Returns 1 if remote host is connected via socket, 0 if not. */
300 packet_connection_is_on_socket(void)
302 struct sockaddr_storage from, to;
303 socklen_t fromlen, tolen;
305 /* filedescriptors in and out are the same, so it's a socket */
306 if (active_state->connection_in == active_state->connection_out)
308 fromlen = sizeof(from);
309 memset(&from, 0, sizeof(from));
310 if (getpeername(active_state->connection_in, (struct sockaddr *)&from,
314 memset(&to, 0, sizeof(to));
315 if (getpeername(active_state->connection_out, (struct sockaddr *)&to,
318 if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
320 if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
326 * Exports an IV from the CipherContext required to export the key
327 * state back from the unprivileged child to the privileged parent
332 packet_get_keyiv(int mode, u_char *iv, u_int len)
336 if (mode == MODE_OUT)
337 cc = &active_state->send_context;
339 cc = &active_state->receive_context;
341 cipher_get_keyiv(cc, iv, len);
345 packet_get_keycontext(int mode, u_char *dat)
349 if (mode == MODE_OUT)
350 cc = &active_state->send_context;
352 cc = &active_state->receive_context;
354 return (cipher_get_keycontext(cc, dat));
358 packet_set_keycontext(int mode, u_char *dat)
362 if (mode == MODE_OUT)
363 cc = &active_state->send_context;
365 cc = &active_state->receive_context;
367 cipher_set_keycontext(cc, dat);
371 packet_get_keyiv_len(int mode)
375 if (mode == MODE_OUT)
376 cc = &active_state->send_context;
378 cc = &active_state->receive_context;
380 return (cipher_get_keyiv_len(cc));
384 packet_set_iv(int mode, u_char *dat)
388 if (mode == MODE_OUT)
389 cc = &active_state->send_context;
391 cc = &active_state->receive_context;
393 cipher_set_keyiv(cc, dat);
397 packet_get_ssh1_cipher(void)
399 return (cipher_get_number(active_state->receive_context.cipher));
403 packet_get_state(int mode, u_int32_t *seqnr, u_int64_t *blocks,
404 u_int32_t *packets, u_int64_t *bytes)
406 struct packet_state *state;
408 state = (mode == MODE_IN) ?
409 &active_state->p_read : &active_state->p_send;
411 *seqnr = state->seqnr;
413 *blocks = state->blocks;
415 *packets = state->packets;
417 *bytes = state->bytes;
421 packet_set_state(int mode, u_int32_t seqnr, u_int64_t blocks, u_int32_t packets,
424 struct packet_state *state;
426 state = (mode == MODE_IN) ?
427 &active_state->p_read : &active_state->p_send;
428 state->seqnr = seqnr;
429 state->blocks = blocks;
430 state->packets = packets;
431 state->bytes = bytes;
435 packet_connection_af(void)
437 struct sockaddr_storage to;
438 socklen_t tolen = sizeof(to);
440 memset(&to, 0, sizeof(to));
441 if (getsockname(active_state->connection_out, (struct sockaddr *)&to,
445 if (to.ss_family == AF_INET6 &&
446 IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&to)->sin6_addr))
452 /* Sets the connection into non-blocking mode. */
455 packet_set_nonblocking(void)
457 /* Set the socket into non-blocking mode. */
458 set_nonblock(active_state->connection_in);
460 if (active_state->connection_out != active_state->connection_in)
461 set_nonblock(active_state->connection_out);
464 /* Returns the socket used for reading. */
467 packet_get_connection_in(void)
469 return active_state->connection_in;
472 /* Returns the descriptor used for writing. */
475 packet_get_connection_out(void)
477 return active_state->connection_out;
480 /* Closes the connection and clears and frees internal data structures. */
485 if (!active_state->initialized)
487 active_state->initialized = 0;
488 if (active_state->connection_in == active_state->connection_out) {
489 shutdown(active_state->connection_out, SHUT_RDWR);
490 close(active_state->connection_out);
492 close(active_state->connection_in);
493 close(active_state->connection_out);
495 buffer_free(&active_state->input);
496 buffer_free(&active_state->output);
497 buffer_free(&active_state->outgoing_packet);
498 buffer_free(&active_state->incoming_packet);
499 if (active_state->compression_buffer_ready) {
500 buffer_free(&active_state->compression_buffer);
501 buffer_compress_uninit();
503 cipher_cleanup(&active_state->send_context);
504 cipher_cleanup(&active_state->receive_context);
507 /* Sets remote side protocol flags. */
510 packet_set_protocol_flags(u_int protocol_flags)
512 active_state->remote_protocol_flags = protocol_flags;
515 /* Returns the remote protocol flags set earlier by the above function. */
518 packet_get_protocol_flags(void)
520 return active_state->remote_protocol_flags;
524 * Starts packet compression from the next packet on in both directions.
525 * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
529 packet_init_compression(void)
531 if (active_state->compression_buffer_ready == 1)
533 active_state->compression_buffer_ready = 1;
534 buffer_init(&active_state->compression_buffer);
538 packet_start_compression(int level)
540 if (active_state->packet_compression && !compat20)
541 fatal("Compression already enabled.");
542 active_state->packet_compression = 1;
543 packet_init_compression();
544 buffer_compress_init_send(level);
545 buffer_compress_init_recv();
549 * Causes any further packets to be encrypted using the given key. The same
550 * key is used for both sending and reception. However, both directions are
551 * encrypted independently of each other.
555 packet_set_encryption_key(const u_char *key, u_int keylen, int number)
557 const Cipher *cipher = cipher_by_number(number);
560 fatal("packet_set_encryption_key: unknown cipher number %d", number);
562 fatal("packet_set_encryption_key: keylen too small: %d", keylen);
563 if (keylen > SSH_SESSION_KEY_LENGTH)
564 fatal("packet_set_encryption_key: keylen too big: %d", keylen);
565 memcpy(active_state->ssh1_key, key, keylen);
566 active_state->ssh1_keylen = keylen;
567 cipher_init(&active_state->send_context, cipher, key, keylen, NULL,
569 cipher_init(&active_state->receive_context, cipher, key, keylen, NULL,
574 packet_get_encryption_key(u_char *key)
577 return (active_state->ssh1_keylen);
578 memcpy(key, active_state->ssh1_key, active_state->ssh1_keylen);
579 return (active_state->ssh1_keylen);
582 /* Start constructing a packet to send. */
584 packet_start(u_char type)
589 DBG(debug("packet_start[%d]", type));
590 len = compat20 ? 6 : 9;
591 memset(buf, 0, len - 1);
593 buffer_clear(&active_state->outgoing_packet);
594 buffer_append(&active_state->outgoing_packet, buf, len);
597 /* Append payload. */
599 packet_put_char(int value)
603 buffer_append(&active_state->outgoing_packet, &ch, 1);
607 packet_put_int(u_int value)
609 buffer_put_int(&active_state->outgoing_packet, value);
613 packet_put_int64(u_int64_t value)
615 buffer_put_int64(&active_state->outgoing_packet, value);
619 packet_put_string(const void *buf, u_int len)
621 buffer_put_string(&active_state->outgoing_packet, buf, len);
625 packet_put_cstring(const char *str)
627 buffer_put_cstring(&active_state->outgoing_packet, str);
631 packet_put_raw(const void *buf, u_int len)
633 buffer_append(&active_state->outgoing_packet, buf, len);
637 packet_put_bignum(BIGNUM * value)
639 buffer_put_bignum(&active_state->outgoing_packet, value);
643 packet_put_bignum2(BIGNUM * value)
645 buffer_put_bignum2(&active_state->outgoing_packet, value);
648 #ifdef OPENSSL_HAS_ECC
650 packet_put_ecpoint(const EC_GROUP *curve, const EC_POINT *point)
652 buffer_put_ecpoint(&active_state->outgoing_packet, curve, point);
657 * Finalizes and sends the packet. If the encryption key has been set,
658 * encrypts the packet before sending.
670 * If using packet compression, compress the payload of the outgoing
673 if (active_state->packet_compression) {
674 buffer_clear(&active_state->compression_buffer);
676 buffer_consume(&active_state->outgoing_packet, 8);
678 buffer_append(&active_state->compression_buffer,
679 "\0\0\0\0\0\0\0\0", 8);
680 buffer_compress(&active_state->outgoing_packet,
681 &active_state->compression_buffer);
682 buffer_clear(&active_state->outgoing_packet);
683 buffer_append(&active_state->outgoing_packet,
684 buffer_ptr(&active_state->compression_buffer),
685 buffer_len(&active_state->compression_buffer));
687 /* Compute packet length without padding (add checksum, remove padding). */
688 len = buffer_len(&active_state->outgoing_packet) + 4 - 8;
690 /* Insert padding. Initialized to zero in packet_start1() */
691 padding = 8 - len % 8;
692 if (!active_state->send_context.plaintext) {
693 cp = buffer_ptr(&active_state->outgoing_packet);
694 for (i = 0; i < padding; i++) {
697 cp[7 - i] = rnd & 0xff;
701 buffer_consume(&active_state->outgoing_packet, 8 - padding);
703 /* Add check bytes. */
704 checksum = ssh_crc32(buffer_ptr(&active_state->outgoing_packet),
705 buffer_len(&active_state->outgoing_packet));
706 put_u32(buf, checksum);
707 buffer_append(&active_state->outgoing_packet, buf, 4);
710 fprintf(stderr, "packet_send plain: ");
711 buffer_dump(&active_state->outgoing_packet);
714 /* Append to output. */
716 buffer_append(&active_state->output, buf, 4);
717 cp = buffer_append_space(&active_state->output,
718 buffer_len(&active_state->outgoing_packet));
719 cipher_crypt(&active_state->send_context, cp,
720 buffer_ptr(&active_state->outgoing_packet),
721 buffer_len(&active_state->outgoing_packet), 0, 0);
724 fprintf(stderr, "encrypted: ");
725 buffer_dump(&active_state->output);
727 active_state->p_send.packets++;
728 active_state->p_send.bytes += len +
729 buffer_len(&active_state->outgoing_packet);
730 buffer_clear(&active_state->outgoing_packet);
733 * Note that the packet is now only buffered in output. It won't be
734 * actually sent until packet_write_wait or packet_write_poll is
740 set_newkeys(int mode)
746 u_int64_t *max_blocks;
749 debug2("set_newkeys: mode %d", mode);
751 if (mode == MODE_OUT) {
752 cc = &active_state->send_context;
753 crypt_type = CIPHER_ENCRYPT;
754 active_state->p_send.packets = active_state->p_send.blocks = 0;
755 max_blocks = &active_state->max_blocks_out;
757 cc = &active_state->receive_context;
758 crypt_type = CIPHER_DECRYPT;
759 active_state->p_read.packets = active_state->p_read.blocks = 0;
760 max_blocks = &active_state->max_blocks_in;
762 if (active_state->newkeys[mode] != NULL) {
763 debug("set_newkeys: rekeying");
765 enc = &active_state->newkeys[mode]->enc;
766 mac = &active_state->newkeys[mode]->mac;
767 comp = &active_state->newkeys[mode]->comp;
769 memset(enc->iv, 0, enc->iv_len);
770 memset(enc->key, 0, enc->key_len);
771 memset(mac->key, 0, mac->key_len);
778 free(active_state->newkeys[mode]);
780 active_state->newkeys[mode] = kex_get_newkeys(mode);
781 if (active_state->newkeys[mode] == NULL)
782 fatal("newkeys: no keys for mode %d", mode);
783 enc = &active_state->newkeys[mode]->enc;
784 mac = &active_state->newkeys[mode]->mac;
785 comp = &active_state->newkeys[mode]->comp;
786 if (cipher_authlen(enc->cipher) == 0 && mac_init(mac) == 0)
788 DBG(debug("cipher_init_context: %d", mode));
789 cipher_init(cc, enc->cipher, enc->key, enc->key_len,
790 enc->iv, enc->iv_len, crypt_type);
791 /* Deleting the keys does not gain extra security */
792 /* memset(enc->iv, 0, enc->block_size);
793 memset(enc->key, 0, enc->key_len);
794 memset(mac->key, 0, mac->key_len); */
795 if ((comp->type == COMP_ZLIB ||
796 (comp->type == COMP_DELAYED &&
797 active_state->after_authentication)) && comp->enabled == 0) {
798 packet_init_compression();
799 if (mode == MODE_OUT)
800 buffer_compress_init_send(6);
802 buffer_compress_init_recv();
806 * The 2^(blocksize*2) limit is too expensive for 3DES,
807 * blowfish, etc, so enforce a 1GB limit for small blocksizes.
809 if (enc->block_size >= 16)
810 *max_blocks = (u_int64_t)1 << (enc->block_size*2);
812 *max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
813 if (active_state->rekey_limit)
814 *max_blocks = MIN(*max_blocks,
815 active_state->rekey_limit / enc->block_size);
819 * Delayed compression for SSH2 is enabled after authentication:
820 * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
821 * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
824 packet_enable_delayed_compress(void)
830 * Remember that we are past the authentication step, so rekeying
831 * with COMP_DELAYED will turn on compression immediately.
833 active_state->after_authentication = 1;
834 for (mode = 0; mode < MODE_MAX; mode++) {
835 /* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
836 if (active_state->newkeys[mode] == NULL)
838 comp = &active_state->newkeys[mode]->comp;
839 if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
840 packet_init_compression();
841 if (mode == MODE_OUT)
842 buffer_compress_init_send(6);
844 buffer_compress_init_recv();
851 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
854 packet_send2_wrapped(void)
856 u_char type, *cp, *macbuf = NULL;
857 u_char padlen, pad = 0;
858 u_int i, len, authlen = 0, aadlen = 0;
865 if (active_state->newkeys[MODE_OUT] != NULL) {
866 enc = &active_state->newkeys[MODE_OUT]->enc;
867 mac = &active_state->newkeys[MODE_OUT]->mac;
868 comp = &active_state->newkeys[MODE_OUT]->comp;
869 /* disable mac for authenticated encryption */
870 if ((authlen = cipher_authlen(enc->cipher)) != 0)
873 block_size = enc ? enc->block_size : 8;
874 aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
876 cp = buffer_ptr(&active_state->outgoing_packet);
880 fprintf(stderr, "plain: ");
881 buffer_dump(&active_state->outgoing_packet);
884 if (comp && comp->enabled) {
885 len = buffer_len(&active_state->outgoing_packet);
886 /* skip header, compress only payload */
887 buffer_consume(&active_state->outgoing_packet, 5);
888 buffer_clear(&active_state->compression_buffer);
889 buffer_compress(&active_state->outgoing_packet,
890 &active_state->compression_buffer);
891 buffer_clear(&active_state->outgoing_packet);
892 buffer_append(&active_state->outgoing_packet, "\0\0\0\0\0", 5);
893 buffer_append(&active_state->outgoing_packet,
894 buffer_ptr(&active_state->compression_buffer),
895 buffer_len(&active_state->compression_buffer));
896 DBG(debug("compression: raw %d compressed %d", len,
897 buffer_len(&active_state->outgoing_packet)));
900 /* sizeof (packet_len + pad_len + payload) */
901 len = buffer_len(&active_state->outgoing_packet);
904 * calc size of padding, alloc space, get random data,
905 * minimum padding is 4 bytes
907 len -= aadlen; /* packet length is not encrypted for EtM modes */
908 padlen = block_size - (len % block_size);
910 padlen += block_size;
911 if (active_state->extra_pad) {
912 /* will wrap if extra_pad+padlen > 255 */
913 active_state->extra_pad =
914 roundup(active_state->extra_pad, block_size);
915 pad = active_state->extra_pad -
916 ((len + padlen) % active_state->extra_pad);
917 debug3("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
918 pad, len, padlen, active_state->extra_pad);
920 active_state->extra_pad = 0;
922 cp = buffer_append_space(&active_state->outgoing_packet, padlen);
923 if (enc && !active_state->send_context.plaintext) {
925 for (i = 0; i < padlen; i++) {
933 memset(cp, 0, padlen);
935 /* sizeof (packet_len + pad_len + payload + padding) */
936 len = buffer_len(&active_state->outgoing_packet);
937 cp = buffer_ptr(&active_state->outgoing_packet);
938 /* packet_length includes payload, padding and padding length field */
939 put_u32(cp, len - 4);
941 DBG(debug("send: len %d (includes padlen %d, aadlen %d)",
942 len, padlen, aadlen));
944 /* compute MAC over seqnr and packet(length fields, payload, padding) */
945 if (mac && mac->enabled && !mac->etm) {
946 macbuf = mac_compute(mac, active_state->p_send.seqnr,
947 buffer_ptr(&active_state->outgoing_packet), len);
948 DBG(debug("done calc MAC out #%d", active_state->p_send.seqnr));
950 /* encrypt packet and append to output buffer. */
951 cp = buffer_append_space(&active_state->output, len + authlen);
952 cipher_crypt(&active_state->send_context, cp,
953 buffer_ptr(&active_state->outgoing_packet),
954 len - aadlen, aadlen, authlen);
955 /* append unencrypted MAC */
956 if (mac && mac->enabled) {
958 /* EtM: compute mac over aadlen + cipher text */
959 macbuf = mac_compute(mac,
960 active_state->p_send.seqnr, cp, len);
961 DBG(debug("done calc MAC(EtM) out #%d",
962 active_state->p_send.seqnr));
964 buffer_append(&active_state->output, macbuf, mac->mac_len);
967 fprintf(stderr, "encrypted: ");
968 buffer_dump(&active_state->output);
970 /* increment sequence number for outgoing packets */
971 if (++active_state->p_send.seqnr == 0)
972 logit("outgoing seqnr wraps around");
973 if (++active_state->p_send.packets == 0)
974 if (!(datafellows & SSH_BUG_NOREKEY))
975 fatal("XXX too many packets with same key");
976 active_state->p_send.blocks += len / block_size;
977 active_state->p_send.bytes += len;
978 buffer_clear(&active_state->outgoing_packet);
980 if (type == SSH2_MSG_NEWKEYS)
981 set_newkeys(MODE_OUT);
982 else if (type == SSH2_MSG_USERAUTH_SUCCESS && active_state->server_side)
983 packet_enable_delayed_compress();
992 cp = buffer_ptr(&active_state->outgoing_packet);
995 /* during rekeying we can only send key exchange messages */
996 if (active_state->rekeying) {
997 if ((type < SSH2_MSG_TRANSPORT_MIN) ||
998 (type > SSH2_MSG_TRANSPORT_MAX) ||
999 (type == SSH2_MSG_SERVICE_REQUEST) ||
1000 (type == SSH2_MSG_SERVICE_ACCEPT)) {
1001 debug("enqueue packet: %u", type);
1002 p = xcalloc(1, sizeof(*p));
1004 memcpy(&p->payload, &active_state->outgoing_packet,
1006 buffer_init(&active_state->outgoing_packet);
1007 TAILQ_INSERT_TAIL(&active_state->outgoing, p, next);
1012 /* rekeying starts with sending KEXINIT */
1013 if (type == SSH2_MSG_KEXINIT)
1014 active_state->rekeying = 1;
1016 packet_send2_wrapped();
1018 /* after a NEWKEYS message we can send the complete queue */
1019 if (type == SSH2_MSG_NEWKEYS) {
1020 active_state->rekeying = 0;
1021 active_state->rekey_time = monotime();
1022 while ((p = TAILQ_FIRST(&active_state->outgoing))) {
1024 debug("dequeue packet: %u", type);
1025 buffer_free(&active_state->outgoing_packet);
1026 memcpy(&active_state->outgoing_packet, &p->payload,
1028 TAILQ_REMOVE(&active_state->outgoing, p, next);
1030 packet_send2_wrapped();
1042 DBG(debug("packet_send done"));
1046 * Waits until a packet has been received, and returns its type. Note that
1047 * no other data is processed until this returns, so this function should not
1048 * be used during the interactive session.
1052 packet_read_seqnr(u_int32_t *seqnr_p)
1054 int type, len, ret, cont, ms_remain = 0;
1057 struct timeval timeout, start, *timeoutp = NULL;
1059 DBG(debug("packet_read()"));
1061 setp = (fd_set *)xcalloc(howmany(active_state->connection_in + 1,
1062 NFDBITS), sizeof(fd_mask));
1064 /* Since we are blocking, ensure that all written packets have been sent. */
1065 packet_write_wait();
1067 /* Stay in the loop until we have received a complete packet. */
1069 /* Try to read a packet from the buffer. */
1070 type = packet_read_poll_seqnr(seqnr_p);
1072 type == SSH_SMSG_SUCCESS
1073 || type == SSH_SMSG_FAILURE
1074 || type == SSH_CMSG_EOF
1075 || type == SSH_CMSG_EXIT_CONFIRMATION))
1077 /* If we got a packet, return it. */
1078 if (type != SSH_MSG_NONE) {
1083 * Otherwise, wait for some data to arrive, add it to the
1084 * buffer, and try again.
1086 memset(setp, 0, howmany(active_state->connection_in + 1,
1087 NFDBITS) * sizeof(fd_mask));
1088 FD_SET(active_state->connection_in, setp);
1090 if (active_state->packet_timeout_ms > 0) {
1091 ms_remain = active_state->packet_timeout_ms;
1092 timeoutp = &timeout;
1094 /* Wait for some data to arrive. */
1096 if (active_state->packet_timeout_ms != -1) {
1097 ms_to_timeval(&timeout, ms_remain);
1098 gettimeofday(&start, NULL);
1100 if ((ret = select(active_state->connection_in + 1, setp,
1101 NULL, NULL, timeoutp)) >= 0)
1103 if (errno != EAGAIN && errno != EINTR &&
1104 errno != EWOULDBLOCK)
1106 if (active_state->packet_timeout_ms == -1)
1108 ms_subtract_diff(&start, &ms_remain);
1109 if (ms_remain <= 0) {
1115 logit("Connection to %.200s timed out while "
1116 "waiting to read", get_remote_ipaddr());
1119 /* Read data from the socket. */
1122 len = roaming_read(active_state->connection_in, buf,
1123 sizeof(buf), &cont);
1124 } while (len == 0 && cont);
1126 logit("Connection closed by %.200s", get_remote_ipaddr());
1130 fatal("Read from socket failed: %.100s", strerror(errno));
1131 /* Append it to the buffer. */
1132 packet_process_incoming(buf, len);
1140 return packet_read_seqnr(NULL);
1144 * Waits until a packet has been received, verifies that its type matches
1145 * that given, and gives a fatal error and exits if there is a mismatch.
1149 packet_read_expect(int expected_type)
1153 type = packet_read();
1154 if (type != expected_type)
1155 packet_disconnect("Protocol error: expected packet type %d, got %d",
1156 expected_type, type);
1159 /* Checks if a full packet is available in the data received so far via
1160 * packet_process_incoming. If so, reads the packet; otherwise returns
1161 * SSH_MSG_NONE. This does not wait for data from the connection.
1163 * SSH_MSG_DISCONNECT is handled specially here. Also,
1164 * SSH_MSG_IGNORE messages are skipped by this function and are never returned
1169 packet_read_poll1(void)
1171 u_int len, padded_len;
1173 u_int checksum, stored_checksum;
1175 /* Check if input size is less than minimum packet size. */
1176 if (buffer_len(&active_state->input) < 4 + 8)
1177 return SSH_MSG_NONE;
1178 /* Get length of incoming packet. */
1179 cp = buffer_ptr(&active_state->input);
1181 if (len < 1 + 2 + 2 || len > 256 * 1024)
1182 packet_disconnect("Bad packet length %u.", len);
1183 padded_len = (len + 8) & ~7;
1185 /* Check if the packet has been entirely received. */
1186 if (buffer_len(&active_state->input) < 4 + padded_len)
1187 return SSH_MSG_NONE;
1189 /* The entire packet is in buffer. */
1191 /* Consume packet length. */
1192 buffer_consume(&active_state->input, 4);
1195 * Cryptographic attack detector for ssh
1196 * (C)1998 CORE-SDI, Buenos Aires Argentina
1197 * Ariel Futoransky(futo@core-sdi.com)
1199 if (!active_state->receive_context.plaintext) {
1200 switch (detect_attack(buffer_ptr(&active_state->input),
1202 case DEATTACK_DETECTED:
1203 packet_disconnect("crc32 compensation attack: "
1204 "network attack detected");
1205 case DEATTACK_DOS_DETECTED:
1206 packet_disconnect("deattack denial of "
1207 "service detected");
1211 /* Decrypt data to incoming_packet. */
1212 buffer_clear(&active_state->incoming_packet);
1213 cp = buffer_append_space(&active_state->incoming_packet, padded_len);
1214 cipher_crypt(&active_state->receive_context, cp,
1215 buffer_ptr(&active_state->input), padded_len, 0, 0);
1217 buffer_consume(&active_state->input, padded_len);
1220 fprintf(stderr, "read_poll plain: ");
1221 buffer_dump(&active_state->incoming_packet);
1224 /* Compute packet checksum. */
1225 checksum = ssh_crc32(buffer_ptr(&active_state->incoming_packet),
1226 buffer_len(&active_state->incoming_packet) - 4);
1229 buffer_consume(&active_state->incoming_packet, 8 - len % 8);
1231 /* Test check bytes. */
1232 if (len != buffer_len(&active_state->incoming_packet))
1233 packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
1234 len, buffer_len(&active_state->incoming_packet));
1236 cp = (u_char *)buffer_ptr(&active_state->incoming_packet) + len - 4;
1237 stored_checksum = get_u32(cp);
1238 if (checksum != stored_checksum)
1239 packet_disconnect("Corrupted check bytes on input.");
1240 buffer_consume_end(&active_state->incoming_packet, 4);
1242 if (active_state->packet_compression) {
1243 buffer_clear(&active_state->compression_buffer);
1244 buffer_uncompress(&active_state->incoming_packet,
1245 &active_state->compression_buffer);
1246 buffer_clear(&active_state->incoming_packet);
1247 buffer_append(&active_state->incoming_packet,
1248 buffer_ptr(&active_state->compression_buffer),
1249 buffer_len(&active_state->compression_buffer));
1251 active_state->p_read.packets++;
1252 active_state->p_read.bytes += padded_len + 4;
1253 type = buffer_get_char(&active_state->incoming_packet);
1254 if (type < SSH_MSG_MIN || type > SSH_MSG_MAX)
1255 packet_disconnect("Invalid ssh1 packet type: %d", type);
1260 packet_read_poll2(u_int32_t *seqnr_p)
1263 u_char *macbuf = NULL, *cp, type;
1264 u_int maclen, authlen = 0, aadlen = 0, block_size;
1269 if (active_state->packet_discard)
1270 return SSH_MSG_NONE;
1272 if (active_state->newkeys[MODE_IN] != NULL) {
1273 enc = &active_state->newkeys[MODE_IN]->enc;
1274 mac = &active_state->newkeys[MODE_IN]->mac;
1275 comp = &active_state->newkeys[MODE_IN]->comp;
1276 /* disable mac for authenticated encryption */
1277 if ((authlen = cipher_authlen(enc->cipher)) != 0)
1280 maclen = mac && mac->enabled ? mac->mac_len : 0;
1281 block_size = enc ? enc->block_size : 8;
1282 aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
1284 if (aadlen && active_state->packlen == 0) {
1285 if (buffer_len(&active_state->input) < 4)
1286 return SSH_MSG_NONE;
1287 cp = buffer_ptr(&active_state->input);
1288 active_state->packlen = get_u32(cp);
1289 if (active_state->packlen < 1 + 4 ||
1290 active_state->packlen > PACKET_MAX_SIZE) {
1292 buffer_dump(&active_state->input);
1294 logit("Bad packet length %u.", active_state->packlen);
1295 packet_disconnect("Packet corrupt");
1297 buffer_clear(&active_state->incoming_packet);
1298 } else if (active_state->packlen == 0) {
1300 * check if input size is less than the cipher block size,
1301 * decrypt first block and extract length of incoming packet
1303 if (buffer_len(&active_state->input) < block_size)
1304 return SSH_MSG_NONE;
1305 buffer_clear(&active_state->incoming_packet);
1306 cp = buffer_append_space(&active_state->incoming_packet,
1308 cipher_crypt(&active_state->receive_context, cp,
1309 buffer_ptr(&active_state->input), block_size, 0, 0);
1310 cp = buffer_ptr(&active_state->incoming_packet);
1312 active_state->packlen = get_u32(cp);
1313 if (active_state->packlen < 1 + 4 ||
1314 active_state->packlen > PACKET_MAX_SIZE) {
1316 buffer_dump(&active_state->incoming_packet);
1318 logit("Bad packet length %u.", active_state->packlen);
1319 packet_start_discard(enc, mac, active_state->packlen,
1321 return SSH_MSG_NONE;
1323 buffer_consume(&active_state->input, block_size);
1325 DBG(debug("input: packet len %u", active_state->packlen+4));
1327 /* only the payload is encrypted */
1328 need = active_state->packlen;
1331 * the payload size and the payload are encrypted, but we
1332 * have a partial packet of block_size bytes
1334 need = 4 + active_state->packlen - block_size;
1336 DBG(debug("partial packet: block %d, need %d, maclen %d, authlen %d,"
1337 " aadlen %d", block_size, need, maclen, authlen, aadlen));
1338 if (need % block_size != 0) {
1339 logit("padding error: need %d block %d mod %d",
1340 need, block_size, need % block_size);
1341 packet_start_discard(enc, mac, active_state->packlen,
1342 PACKET_MAX_SIZE - block_size);
1343 return SSH_MSG_NONE;
1346 * check if the entire packet has been received and
1347 * decrypt into incoming_packet:
1348 * 'aadlen' bytes are unencrypted, but authenticated.
1349 * 'need' bytes are encrypted, followed by either
1350 * 'authlen' bytes of authentication tag or
1351 * 'maclen' bytes of message authentication code.
1353 if (buffer_len(&active_state->input) < aadlen + need + authlen + maclen)
1354 return SSH_MSG_NONE;
1356 fprintf(stderr, "read_poll enc/full: ");
1357 buffer_dump(&active_state->input);
1359 /* EtM: compute mac over encrypted input */
1360 if (mac && mac->enabled && mac->etm)
1361 macbuf = mac_compute(mac, active_state->p_read.seqnr,
1362 buffer_ptr(&active_state->input), aadlen + need);
1363 cp = buffer_append_space(&active_state->incoming_packet, aadlen + need);
1364 cipher_crypt(&active_state->receive_context, cp,
1365 buffer_ptr(&active_state->input), need, aadlen, authlen);
1366 buffer_consume(&active_state->input, aadlen + need + authlen);
1368 * compute MAC over seqnr and packet,
1369 * increment sequence number for incoming packet
1371 if (mac && mac->enabled) {
1373 macbuf = mac_compute(mac, active_state->p_read.seqnr,
1374 buffer_ptr(&active_state->incoming_packet),
1375 buffer_len(&active_state->incoming_packet));
1376 if (timingsafe_bcmp(macbuf, buffer_ptr(&active_state->input),
1377 mac->mac_len) != 0) {
1378 logit("Corrupted MAC on input.");
1379 if (need > PACKET_MAX_SIZE)
1380 fatal("internal error need %d", need);
1381 packet_start_discard(enc, mac, active_state->packlen,
1382 PACKET_MAX_SIZE - need);
1383 return SSH_MSG_NONE;
1386 DBG(debug("MAC #%d ok", active_state->p_read.seqnr));
1387 buffer_consume(&active_state->input, mac->mac_len);
1389 /* XXX now it's safe to use fatal/packet_disconnect */
1390 if (seqnr_p != NULL)
1391 *seqnr_p = active_state->p_read.seqnr;
1392 if (++active_state->p_read.seqnr == 0)
1393 logit("incoming seqnr wraps around");
1394 if (++active_state->p_read.packets == 0)
1395 if (!(datafellows & SSH_BUG_NOREKEY))
1396 fatal("XXX too many packets with same key");
1397 active_state->p_read.blocks += (active_state->packlen + 4) / block_size;
1398 active_state->p_read.bytes += active_state->packlen + 4;
1401 cp = buffer_ptr(&active_state->incoming_packet);
1403 DBG(debug("input: padlen %d", padlen));
1405 packet_disconnect("Corrupted padlen %d on input.", padlen);
1407 /* skip packet size + padlen, discard padding */
1408 buffer_consume(&active_state->incoming_packet, 4 + 1);
1409 buffer_consume_end(&active_state->incoming_packet, padlen);
1411 DBG(debug("input: len before de-compress %d",
1412 buffer_len(&active_state->incoming_packet)));
1413 if (comp && comp->enabled) {
1414 buffer_clear(&active_state->compression_buffer);
1415 buffer_uncompress(&active_state->incoming_packet,
1416 &active_state->compression_buffer);
1417 buffer_clear(&active_state->incoming_packet);
1418 buffer_append(&active_state->incoming_packet,
1419 buffer_ptr(&active_state->compression_buffer),
1420 buffer_len(&active_state->compression_buffer));
1421 DBG(debug("input: len after de-compress %d",
1422 buffer_len(&active_state->incoming_packet)));
1425 * get packet type, implies consume.
1426 * return length of payload (without type field)
1428 type = buffer_get_char(&active_state->incoming_packet);
1429 if (type < SSH2_MSG_MIN || type >= SSH2_MSG_LOCAL_MIN)
1430 packet_disconnect("Invalid ssh2 packet type: %d", type);
1431 if (type == SSH2_MSG_NEWKEYS)
1432 set_newkeys(MODE_IN);
1433 else if (type == SSH2_MSG_USERAUTH_SUCCESS &&
1434 !active_state->server_side)
1435 packet_enable_delayed_compress();
1437 fprintf(stderr, "read/plain[%d]:\r\n", type);
1438 buffer_dump(&active_state->incoming_packet);
1440 /* reset for next packet */
1441 active_state->packlen = 0;
1446 packet_read_poll_seqnr(u_int32_t *seqnr_p)
1448 u_int reason, seqnr;
1454 type = packet_read_poll2(seqnr_p);
1456 active_state->keep_alive_timeouts = 0;
1457 DBG(debug("received packet type %d", type));
1460 case SSH2_MSG_IGNORE:
1461 debug3("Received SSH2_MSG_IGNORE");
1463 case SSH2_MSG_DEBUG:
1465 msg = packet_get_string(NULL);
1466 debug("Remote: %.900s", msg);
1468 msg = packet_get_string(NULL);
1471 case SSH2_MSG_DISCONNECT:
1472 reason = packet_get_int();
1473 msg = packet_get_string(NULL);
1474 /* Ignore normal client exit notifications */
1475 do_log2(active_state->server_side &&
1476 reason == SSH2_DISCONNECT_BY_APPLICATION ?
1477 SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_ERROR,
1478 "Received disconnect from %s: %u: %.400s",
1479 get_remote_ipaddr(), reason, msg);
1483 case SSH2_MSG_UNIMPLEMENTED:
1484 seqnr = packet_get_int();
1485 debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1492 type = packet_read_poll1();
1495 return SSH_MSG_NONE;
1496 case SSH_MSG_IGNORE:
1499 msg = packet_get_string(NULL);
1500 debug("Remote: %.900s", msg);
1503 case SSH_MSG_DISCONNECT:
1504 msg = packet_get_string(NULL);
1505 logit("Received disconnect from %s: %.400s",
1506 get_remote_ipaddr(), msg);
1510 DBG(debug("received packet type %d", type));
1518 * Buffers the given amount of input characters. This is intended to be used
1519 * together with packet_read_poll.
1523 packet_process_incoming(const char *buf, u_int len)
1525 if (active_state->packet_discard) {
1526 active_state->keep_alive_timeouts = 0; /* ?? */
1527 if (len >= active_state->packet_discard)
1528 packet_stop_discard();
1529 active_state->packet_discard -= len;
1532 buffer_append(&active_state->input, buf, len);
1535 /* Returns a character from the packet. */
1538 packet_get_char(void)
1542 buffer_get(&active_state->incoming_packet, &ch, 1);
1546 /* Returns an integer from the packet data. */
1549 packet_get_int(void)
1551 return buffer_get_int(&active_state->incoming_packet);
1554 /* Returns an 64 bit integer from the packet data. */
1557 packet_get_int64(void)
1559 return buffer_get_int64(&active_state->incoming_packet);
1563 * Returns an arbitrary precision integer from the packet data. The integer
1564 * must have been initialized before this call.
1568 packet_get_bignum(BIGNUM * value)
1570 buffer_get_bignum(&active_state->incoming_packet, value);
1574 packet_get_bignum2(BIGNUM * value)
1576 buffer_get_bignum2(&active_state->incoming_packet, value);
1579 #ifdef OPENSSL_HAS_ECC
1581 packet_get_ecpoint(const EC_GROUP *curve, EC_POINT *point)
1583 buffer_get_ecpoint(&active_state->incoming_packet, curve, point);
1588 packet_get_raw(u_int *length_ptr)
1590 u_int bytes = buffer_len(&active_state->incoming_packet);
1592 if (length_ptr != NULL)
1593 *length_ptr = bytes;
1594 return buffer_ptr(&active_state->incoming_packet);
1598 packet_remaining(void)
1600 return buffer_len(&active_state->incoming_packet);
1604 * Returns a string from the packet data. The string is allocated using
1605 * xmalloc; it is the responsibility of the calling program to free it when
1606 * no longer needed. The length_ptr argument may be NULL, or point to an
1607 * integer into which the length of the string is stored.
1611 packet_get_string(u_int *length_ptr)
1613 return buffer_get_string(&active_state->incoming_packet, length_ptr);
1617 packet_get_string_ptr(u_int *length_ptr)
1619 return buffer_get_string_ptr(&active_state->incoming_packet, length_ptr);
1622 /* Ensures the returned string has no embedded \0 characters in it. */
1624 packet_get_cstring(u_int *length_ptr)
1626 return buffer_get_cstring(&active_state->incoming_packet, length_ptr);
1630 * Sends a diagnostic message from the server to the client. This message
1631 * can be sent at any time (but not while constructing another message). The
1632 * message is printed immediately, but only if the client is being executed
1633 * in verbose mode. These messages are primarily intended to ease debugging
1634 * authentication problems. The length of the formatted message must not
1635 * exceed 1024 bytes. This will automatically call packet_write_wait.
1639 packet_send_debug(const char *fmt,...)
1644 if (compat20 && (datafellows & SSH_BUG_DEBUG))
1647 va_start(args, fmt);
1648 vsnprintf(buf, sizeof(buf), fmt, args);
1652 packet_start(SSH2_MSG_DEBUG);
1653 packet_put_char(0); /* bool: always display */
1654 packet_put_cstring(buf);
1655 packet_put_cstring("");
1657 packet_start(SSH_MSG_DEBUG);
1658 packet_put_cstring(buf);
1661 packet_write_wait();
1665 * Logs the error plus constructs and sends a disconnect packet, closes the
1666 * connection, and exits. This function never returns. The error message
1667 * should not contain a newline. The length of the formatted message must
1668 * not exceed 1024 bytes.
1672 packet_disconnect(const char *fmt,...)
1676 static int disconnecting = 0;
1678 if (disconnecting) /* Guard against recursive invocations. */
1679 fatal("packet_disconnect called recursively.");
1683 * Format the message. Note that the caller must make sure the
1684 * message is of limited size.
1686 va_start(args, fmt);
1687 vsnprintf(buf, sizeof(buf), fmt, args);
1690 /* Display the error locally */
1691 logit("Disconnecting: %.100s", buf);
1693 /* Send the disconnect message to the other side, and wait for it to get sent. */
1695 packet_start(SSH2_MSG_DISCONNECT);
1696 packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1697 packet_put_cstring(buf);
1698 packet_put_cstring("");
1700 packet_start(SSH_MSG_DISCONNECT);
1701 packet_put_cstring(buf);
1704 packet_write_wait();
1706 /* Stop listening for connections. */
1707 channel_close_all();
1709 /* Close the connection. */
1714 /* Checks if there is any buffered output, and tries to write some of the output. */
1717 packet_write_poll(void)
1719 int len = buffer_len(&active_state->output);
1724 len = roaming_write(active_state->connection_out,
1725 buffer_ptr(&active_state->output), len, &cont);
1727 if (errno == EINTR || errno == EAGAIN ||
1728 errno == EWOULDBLOCK)
1730 fatal("Write failed: %.100s", strerror(errno));
1732 if (len == 0 && !cont)
1733 fatal("Write connection closed");
1734 buffer_consume(&active_state->output, len);
1739 * Calls packet_write_poll repeatedly until all pending output data has been
1744 packet_write_wait(void)
1747 int ret, ms_remain = 0;
1748 struct timeval start, timeout, *timeoutp = NULL;
1750 setp = (fd_set *)xcalloc(howmany(active_state->connection_out + 1,
1751 NFDBITS), sizeof(fd_mask));
1752 packet_write_poll();
1753 while (packet_have_data_to_write()) {
1754 memset(setp, 0, howmany(active_state->connection_out + 1,
1755 NFDBITS) * sizeof(fd_mask));
1756 FD_SET(active_state->connection_out, setp);
1758 if (active_state->packet_timeout_ms > 0) {
1759 ms_remain = active_state->packet_timeout_ms;
1760 timeoutp = &timeout;
1763 if (active_state->packet_timeout_ms != -1) {
1764 ms_to_timeval(&timeout, ms_remain);
1765 gettimeofday(&start, NULL);
1767 if ((ret = select(active_state->connection_out + 1,
1768 NULL, setp, NULL, timeoutp)) >= 0)
1770 if (errno != EAGAIN && errno != EINTR &&
1771 errno != EWOULDBLOCK)
1773 if (active_state->packet_timeout_ms == -1)
1775 ms_subtract_diff(&start, &ms_remain);
1776 if (ms_remain <= 0) {
1782 logit("Connection to %.200s timed out while "
1783 "waiting to write", get_remote_ipaddr());
1786 packet_write_poll();
1791 /* Returns true if there is buffered data to write to the connection. */
1794 packet_have_data_to_write(void)
1796 return buffer_len(&active_state->output) != 0;
1799 /* Returns true if there is not too much data to write to the connection. */
1802 packet_not_very_much_data_to_write(void)
1804 if (active_state->interactive_mode)
1805 return buffer_len(&active_state->output) < 16384;
1807 return buffer_len(&active_state->output) < 128 * 1024;
1811 packet_set_tos(int tos)
1813 #ifndef IP_TOS_IS_BROKEN
1814 if (!packet_connection_is_on_socket())
1816 switch (packet_connection_af()) {
1819 debug3("%s: set IP_TOS 0x%02x", __func__, tos);
1820 if (setsockopt(active_state->connection_in,
1821 IPPROTO_IP, IP_TOS, &tos, sizeof(tos)) < 0)
1822 error("setsockopt IP_TOS %d: %.100s:",
1823 tos, strerror(errno));
1825 # endif /* IP_TOS */
1828 debug3("%s: set IPV6_TCLASS 0x%02x", __func__, tos);
1829 if (setsockopt(active_state->connection_in,
1830 IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof(tos)) < 0)
1831 error("setsockopt IPV6_TCLASS %d: %.100s:",
1832 tos, strerror(errno));
1834 # endif /* IPV6_TCLASS */
1836 #endif /* IP_TOS_IS_BROKEN */
1839 /* Informs that the current session is interactive. Sets IP flags for that. */
1842 packet_set_interactive(int interactive, int qos_interactive, int qos_bulk)
1844 if (active_state->set_interactive_called)
1846 active_state->set_interactive_called = 1;
1848 /* Record that we are in interactive mode. */
1849 active_state->interactive_mode = interactive;
1851 /* Only set socket options if using a socket. */
1852 if (!packet_connection_is_on_socket())
1854 set_nodelay(active_state->connection_in);
1855 packet_set_tos(interactive ? qos_interactive : qos_bulk);
1858 /* Returns true if the current connection is interactive. */
1861 packet_is_interactive(void)
1863 return active_state->interactive_mode;
1867 packet_set_maxsize(u_int s)
1869 if (active_state->set_maxsize_called) {
1870 logit("packet_set_maxsize: called twice: old %d new %d",
1871 active_state->max_packet_size, s);
1874 if (s < 4 * 1024 || s > 1024 * 1024) {
1875 logit("packet_set_maxsize: bad size %d", s);
1878 active_state->set_maxsize_called = 1;
1879 debug("packet_set_maxsize: setting to %d", s);
1880 active_state->max_packet_size = s;
1885 packet_inc_alive_timeouts(void)
1887 return ++active_state->keep_alive_timeouts;
1891 packet_set_alive_timeouts(int ka)
1893 active_state->keep_alive_timeouts = ka;
1897 packet_get_maxsize(void)
1899 return active_state->max_packet_size;
1902 /* roundup current message to pad bytes */
1904 packet_add_padding(u_char pad)
1906 active_state->extra_pad = pad;
1910 * 9.2. Ignored Data Message
1912 * byte SSH_MSG_IGNORE
1915 * All implementations MUST understand (and ignore) this message at any
1916 * time (after receiving the protocol version). No implementation is
1917 * required to send them. This message can be used as an additional
1918 * protection measure against advanced traffic analysis techniques.
1921 packet_send_ignore(int nbytes)
1926 packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1927 packet_put_int(nbytes);
1928 for (i = 0; i < nbytes; i++) {
1931 packet_put_char((u_char)rnd & 0xff);
1936 #ifdef NONE_CIPHER_ENABLED
1938 packet_request_rekeying(void)
1940 rekey_requested = 1;
1944 #define MAX_PACKETS (1U<<31)
1946 packet_need_rekeying(void)
1948 if (datafellows & SSH_BUG_NOREKEY)
1950 #ifdef NONE_CIPHER_ENABLED
1951 if (rekey_requested == 1) {
1952 rekey_requested = 0;
1957 (active_state->p_send.packets > MAX_PACKETS) ||
1958 (active_state->p_read.packets > MAX_PACKETS) ||
1959 (active_state->max_blocks_out &&
1960 (active_state->p_send.blocks > active_state->max_blocks_out)) ||
1961 (active_state->max_blocks_in &&
1962 (active_state->p_read.blocks > active_state->max_blocks_in)) ||
1963 (active_state->rekey_interval != 0 && active_state->rekey_time +
1964 active_state->rekey_interval <= monotime());
1968 packet_set_rekey_limits(u_int32_t bytes, time_t seconds)
1970 debug3("rekey after %lld bytes, %d seconds", (long long)bytes,
1972 active_state->rekey_limit = bytes;
1973 active_state->rekey_interval = seconds;
1975 * We set the time here so that in post-auth privsep slave we count
1976 * from the completion of the authentication.
1978 active_state->rekey_time = monotime();
1982 packet_get_rekey_timeout(void)
1986 seconds = active_state->rekey_time + active_state->rekey_interval -
1988 return (seconds <= 0 ? 1 : seconds);
1992 packet_set_server(void)
1994 active_state->server_side = 1;
1998 packet_set_authenticated(void)
2000 active_state->after_authentication = 1;
2004 packet_get_input(void)
2006 return (void *)&active_state->input;
2010 packet_get_output(void)
2012 return (void *)&active_state->output;
2016 packet_get_newkeys(int mode)
2018 return (void *)active_state->newkeys[mode];
2022 * Save the state for the real connection, and use a separate state when
2023 * resuming a suspended connection.
2026 packet_backup_state(void)
2028 struct session_state *tmp;
2030 close(active_state->connection_in);
2031 active_state->connection_in = -1;
2032 close(active_state->connection_out);
2033 active_state->connection_out = -1;
2037 tmp = alloc_session_state();
2038 backup_state = active_state;
2043 * Swap in the old state when resuming a connecion.
2046 packet_restore_state(void)
2048 struct session_state *tmp;
2053 backup_state = active_state;
2055 active_state->connection_in = backup_state->connection_in;
2056 backup_state->connection_in = -1;
2057 active_state->connection_out = backup_state->connection_out;
2058 backup_state->connection_out = -1;
2059 len = buffer_len(&backup_state->input);
2061 buf = buffer_ptr(&backup_state->input);
2062 buffer_append(&active_state->input, buf, len);
2063 buffer_clear(&backup_state->input);
2064 add_recv_bytes(len);
2068 #ifdef NONE_CIPHER_ENABLED
2070 packet_get_authentication_state(void)
2072 return (active_state->after_authentication);