1 /* $OpenBSD: packet.c,v 1.192 2014/02/02 03:44:31 djm Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * This file contains code implementing the packet protocol and communication
7 * with the other side. This same code is used both on client and server side.
9 * As far as I am concerned, the code I have written for this software
10 * can be used freely for any purpose. Any derived versions of this
11 * software must be clearly marked as such, and if the derived work is
12 * incompatible with the protocol description in the RFC file, it must be
13 * called by a name other than "ssh" or "Secure Shell".
16 * SSH2 packet format added by Markus Friedl.
17 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
19 * Redistribution and use in source and binary forms, with or without
20 * modification, are permitted provided that the following conditions
22 * 1. Redistributions of source code must retain the above copyright
23 * notice, this list of conditions and the following disclaimer.
24 * 2. Redistributions in binary form must reproduce the above copyright
25 * notice, this list of conditions and the following disclaimer in the
26 * documentation and/or other materials provided with the distribution.
28 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
29 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
30 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
31 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
32 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
33 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
34 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
35 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
36 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
37 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
43 #include <sys/types.h>
44 #include "openbsd-compat/sys-queue.h"
45 #include <sys/param.h>
46 #include <sys/socket.h>
47 #ifdef HAVE_SYS_TIME_H
48 # include <sys/time.h>
51 #include <netinet/in.h>
52 #include <netinet/ip.h>
53 #include <arpa/inet.h>
90 #define PACKET_MAX_SIZE (256 * 1024)
100 TAILQ_ENTRY(packet) next;
105 struct session_state {
107 * This variable contains the file descriptors used for
108 * communicating with the other side. connection_in is used for
109 * reading; connection_out for writing. These can be the same
110 * descriptor, in which case it is assumed to be a socket.
115 /* Protocol flags for the remote side. */
116 u_int remote_protocol_flags;
118 /* Encryption context for receiving data. Only used for decryption. */
119 CipherContext receive_context;
121 /* Encryption context for sending data. Only used for encryption. */
122 CipherContext send_context;
124 /* Buffer for raw input data from the socket. */
127 /* Buffer for raw output data going to the socket. */
130 /* Buffer for the partial outgoing packet being constructed. */
131 Buffer outgoing_packet;
133 /* Buffer for the incoming packet currently being processed. */
134 Buffer incoming_packet;
136 /* Scratch buffer for packet compression/decompression. */
137 Buffer compression_buffer;
138 int compression_buffer_ready;
141 * Flag indicating whether packet compression/decompression is
144 int packet_compression;
146 /* default maximum packet size */
147 u_int max_packet_size;
149 /* Flag indicating whether this module has been initialized. */
152 /* Set to true if the connection is interactive. */
153 int interactive_mode;
155 /* Set to true if we are the server side. */
158 /* Set to true if we are authenticated. */
159 int after_authentication;
161 int keep_alive_timeouts;
163 /* The maximum time that we will wait to send or receive a packet */
164 int packet_timeout_ms;
166 /* Session key information for Encryption and MAC */
167 Newkeys *newkeys[MODE_MAX];
168 struct packet_state p_read, p_send;
170 /* Volume-based rekeying */
171 u_int64_t max_blocks_in, max_blocks_out;
172 u_int32_t rekey_limit;
174 /* Time-based rekeying */
175 time_t rekey_interval; /* how often in seconds */
176 time_t rekey_time; /* time of last rekeying */
178 /* Session key for protocol v1 */
179 u_char ssh1_key[SSH_SESSION_KEY_LENGTH];
182 /* roundup current message to extra_pad bytes */
185 /* XXX discard incoming data after MAC error */
186 u_int packet_discard;
187 Mac *packet_discard_mac;
189 /* Used in packet_read_poll2() */
192 /* Used in packet_send2 */
195 /* Used in packet_set_interactive */
196 int set_interactive_called;
198 /* Used in packet_set_maxsize */
199 int set_maxsize_called;
201 TAILQ_HEAD(, packet) outgoing;
204 static struct session_state *active_state, *backup_state;
206 static struct session_state *
207 alloc_session_state(void)
209 struct session_state *s = xcalloc(1, sizeof(*s));
211 s->connection_in = -1;
212 s->connection_out = -1;
213 s->max_packet_size = 32768;
214 s->packet_timeout_ms = -1;
219 * Sets the descriptors used for communication. Disables encryption until
220 * packet_set_encryption_key is called.
223 packet_set_connection(int fd_in, int fd_out)
225 const Cipher *none = cipher_by_name("none");
228 fatal("packet_set_connection: cannot load cipher 'none'");
229 if (active_state == NULL)
230 active_state = alloc_session_state();
231 active_state->connection_in = fd_in;
232 active_state->connection_out = fd_out;
233 cipher_init(&active_state->send_context, none, (const u_char *)"",
234 0, NULL, 0, CIPHER_ENCRYPT);
235 cipher_init(&active_state->receive_context, none, (const u_char *)"",
236 0, NULL, 0, CIPHER_DECRYPT);
237 active_state->newkeys[MODE_IN] = active_state->newkeys[MODE_OUT] = NULL;
238 if (!active_state->initialized) {
239 active_state->initialized = 1;
240 buffer_init(&active_state->input);
241 buffer_init(&active_state->output);
242 buffer_init(&active_state->outgoing_packet);
243 buffer_init(&active_state->incoming_packet);
244 TAILQ_INIT(&active_state->outgoing);
245 active_state->p_send.packets = active_state->p_read.packets = 0;
250 packet_set_timeout(int timeout, int count)
252 if (timeout <= 0 || count <= 0) {
253 active_state->packet_timeout_ms = -1;
256 if ((INT_MAX / 1000) / count < timeout)
257 active_state->packet_timeout_ms = INT_MAX;
259 active_state->packet_timeout_ms = timeout * count * 1000;
263 packet_stop_discard(void)
265 if (active_state->packet_discard_mac) {
268 memset(buf, 'a', sizeof(buf));
269 while (buffer_len(&active_state->incoming_packet) <
271 buffer_append(&active_state->incoming_packet, buf,
273 (void) mac_compute(active_state->packet_discard_mac,
274 active_state->p_read.seqnr,
275 buffer_ptr(&active_state->incoming_packet),
278 logit("Finished discarding for %.200s", get_remote_ipaddr());
283 packet_start_discard(Enc *enc, Mac *mac, u_int packet_length, u_int discard)
285 if (enc == NULL || !cipher_is_cbc(enc->cipher) || (mac && mac->etm))
286 packet_disconnect("Packet corrupt");
287 if (packet_length != PACKET_MAX_SIZE && mac && mac->enabled)
288 active_state->packet_discard_mac = mac;
289 if (buffer_len(&active_state->input) >= discard)
290 packet_stop_discard();
291 active_state->packet_discard = discard -
292 buffer_len(&active_state->input);
295 /* Returns 1 if remote host is connected via socket, 0 if not. */
298 packet_connection_is_on_socket(void)
300 struct sockaddr_storage from, to;
301 socklen_t fromlen, tolen;
303 /* filedescriptors in and out are the same, so it's a socket */
304 if (active_state->connection_in == active_state->connection_out)
306 fromlen = sizeof(from);
307 memset(&from, 0, sizeof(from));
308 if (getpeername(active_state->connection_in, (struct sockaddr *)&from,
312 memset(&to, 0, sizeof(to));
313 if (getpeername(active_state->connection_out, (struct sockaddr *)&to,
316 if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
318 if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
324 * Exports an IV from the CipherContext required to export the key
325 * state back from the unprivileged child to the privileged parent
330 packet_get_keyiv(int mode, u_char *iv, u_int len)
334 if (mode == MODE_OUT)
335 cc = &active_state->send_context;
337 cc = &active_state->receive_context;
339 cipher_get_keyiv(cc, iv, len);
343 packet_get_keycontext(int mode, u_char *dat)
347 if (mode == MODE_OUT)
348 cc = &active_state->send_context;
350 cc = &active_state->receive_context;
352 return (cipher_get_keycontext(cc, dat));
356 packet_set_keycontext(int mode, u_char *dat)
360 if (mode == MODE_OUT)
361 cc = &active_state->send_context;
363 cc = &active_state->receive_context;
365 cipher_set_keycontext(cc, dat);
369 packet_get_keyiv_len(int mode)
373 if (mode == MODE_OUT)
374 cc = &active_state->send_context;
376 cc = &active_state->receive_context;
378 return (cipher_get_keyiv_len(cc));
382 packet_set_iv(int mode, u_char *dat)
386 if (mode == MODE_OUT)
387 cc = &active_state->send_context;
389 cc = &active_state->receive_context;
391 cipher_set_keyiv(cc, dat);
395 packet_get_ssh1_cipher(void)
397 return (cipher_get_number(active_state->receive_context.cipher));
401 packet_get_state(int mode, u_int32_t *seqnr, u_int64_t *blocks,
402 u_int32_t *packets, u_int64_t *bytes)
404 struct packet_state *state;
406 state = (mode == MODE_IN) ?
407 &active_state->p_read : &active_state->p_send;
409 *seqnr = state->seqnr;
411 *blocks = state->blocks;
413 *packets = state->packets;
415 *bytes = state->bytes;
419 packet_set_state(int mode, u_int32_t seqnr, u_int64_t blocks, u_int32_t packets,
422 struct packet_state *state;
424 state = (mode == MODE_IN) ?
425 &active_state->p_read : &active_state->p_send;
426 state->seqnr = seqnr;
427 state->blocks = blocks;
428 state->packets = packets;
429 state->bytes = bytes;
433 packet_connection_af(void)
435 struct sockaddr_storage to;
436 socklen_t tolen = sizeof(to);
438 memset(&to, 0, sizeof(to));
439 if (getsockname(active_state->connection_out, (struct sockaddr *)&to,
443 if (to.ss_family == AF_INET6 &&
444 IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&to)->sin6_addr))
450 /* Sets the connection into non-blocking mode. */
453 packet_set_nonblocking(void)
455 /* Set the socket into non-blocking mode. */
456 set_nonblock(active_state->connection_in);
458 if (active_state->connection_out != active_state->connection_in)
459 set_nonblock(active_state->connection_out);
462 /* Returns the socket used for reading. */
465 packet_get_connection_in(void)
467 return active_state->connection_in;
470 /* Returns the descriptor used for writing. */
473 packet_get_connection_out(void)
475 return active_state->connection_out;
478 /* Closes the connection and clears and frees internal data structures. */
483 if (!active_state->initialized)
485 active_state->initialized = 0;
486 if (active_state->connection_in == active_state->connection_out) {
487 shutdown(active_state->connection_out, SHUT_RDWR);
488 close(active_state->connection_out);
490 close(active_state->connection_in);
491 close(active_state->connection_out);
493 buffer_free(&active_state->input);
494 buffer_free(&active_state->output);
495 buffer_free(&active_state->outgoing_packet);
496 buffer_free(&active_state->incoming_packet);
497 if (active_state->compression_buffer_ready) {
498 buffer_free(&active_state->compression_buffer);
499 buffer_compress_uninit();
501 cipher_cleanup(&active_state->send_context);
502 cipher_cleanup(&active_state->receive_context);
505 /* Sets remote side protocol flags. */
508 packet_set_protocol_flags(u_int protocol_flags)
510 active_state->remote_protocol_flags = protocol_flags;
513 /* Returns the remote protocol flags set earlier by the above function. */
516 packet_get_protocol_flags(void)
518 return active_state->remote_protocol_flags;
522 * Starts packet compression from the next packet on in both directions.
523 * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
527 packet_init_compression(void)
529 if (active_state->compression_buffer_ready == 1)
531 active_state->compression_buffer_ready = 1;
532 buffer_init(&active_state->compression_buffer);
536 packet_start_compression(int level)
538 if (active_state->packet_compression && !compat20)
539 fatal("Compression already enabled.");
540 active_state->packet_compression = 1;
541 packet_init_compression();
542 buffer_compress_init_send(level);
543 buffer_compress_init_recv();
547 * Causes any further packets to be encrypted using the given key. The same
548 * key is used for both sending and reception. However, both directions are
549 * encrypted independently of each other.
553 packet_set_encryption_key(const u_char *key, u_int keylen, int number)
555 const Cipher *cipher = cipher_by_number(number);
558 fatal("packet_set_encryption_key: unknown cipher number %d", number);
560 fatal("packet_set_encryption_key: keylen too small: %d", keylen);
561 if (keylen > SSH_SESSION_KEY_LENGTH)
562 fatal("packet_set_encryption_key: keylen too big: %d", keylen);
563 memcpy(active_state->ssh1_key, key, keylen);
564 active_state->ssh1_keylen = keylen;
565 cipher_init(&active_state->send_context, cipher, key, keylen, NULL,
567 cipher_init(&active_state->receive_context, cipher, key, keylen, NULL,
572 packet_get_encryption_key(u_char *key)
575 return (active_state->ssh1_keylen);
576 memcpy(key, active_state->ssh1_key, active_state->ssh1_keylen);
577 return (active_state->ssh1_keylen);
580 /* Start constructing a packet to send. */
582 packet_start(u_char type)
587 DBG(debug("packet_start[%d]", type));
588 len = compat20 ? 6 : 9;
589 memset(buf, 0, len - 1);
591 buffer_clear(&active_state->outgoing_packet);
592 buffer_append(&active_state->outgoing_packet, buf, len);
595 /* Append payload. */
597 packet_put_char(int value)
601 buffer_append(&active_state->outgoing_packet, &ch, 1);
605 packet_put_int(u_int value)
607 buffer_put_int(&active_state->outgoing_packet, value);
611 packet_put_int64(u_int64_t value)
613 buffer_put_int64(&active_state->outgoing_packet, value);
617 packet_put_string(const void *buf, u_int len)
619 buffer_put_string(&active_state->outgoing_packet, buf, len);
623 packet_put_cstring(const char *str)
625 buffer_put_cstring(&active_state->outgoing_packet, str);
629 packet_put_raw(const void *buf, u_int len)
631 buffer_append(&active_state->outgoing_packet, buf, len);
635 packet_put_bignum(BIGNUM * value)
637 buffer_put_bignum(&active_state->outgoing_packet, value);
641 packet_put_bignum2(BIGNUM * value)
643 buffer_put_bignum2(&active_state->outgoing_packet, value);
646 #ifdef OPENSSL_HAS_ECC
648 packet_put_ecpoint(const EC_GROUP *curve, const EC_POINT *point)
650 buffer_put_ecpoint(&active_state->outgoing_packet, curve, point);
655 * Finalizes and sends the packet. If the encryption key has been set,
656 * encrypts the packet before sending.
668 * If using packet compression, compress the payload of the outgoing
671 if (active_state->packet_compression) {
672 buffer_clear(&active_state->compression_buffer);
674 buffer_consume(&active_state->outgoing_packet, 8);
676 buffer_append(&active_state->compression_buffer,
677 "\0\0\0\0\0\0\0\0", 8);
678 buffer_compress(&active_state->outgoing_packet,
679 &active_state->compression_buffer);
680 buffer_clear(&active_state->outgoing_packet);
681 buffer_append(&active_state->outgoing_packet,
682 buffer_ptr(&active_state->compression_buffer),
683 buffer_len(&active_state->compression_buffer));
685 /* Compute packet length without padding (add checksum, remove padding). */
686 len = buffer_len(&active_state->outgoing_packet) + 4 - 8;
688 /* Insert padding. Initialized to zero in packet_start1() */
689 padding = 8 - len % 8;
690 if (!active_state->send_context.plaintext) {
691 cp = buffer_ptr(&active_state->outgoing_packet);
692 for (i = 0; i < padding; i++) {
695 cp[7 - i] = rnd & 0xff;
699 buffer_consume(&active_state->outgoing_packet, 8 - padding);
701 /* Add check bytes. */
702 checksum = ssh_crc32(buffer_ptr(&active_state->outgoing_packet),
703 buffer_len(&active_state->outgoing_packet));
704 put_u32(buf, checksum);
705 buffer_append(&active_state->outgoing_packet, buf, 4);
708 fprintf(stderr, "packet_send plain: ");
709 buffer_dump(&active_state->outgoing_packet);
712 /* Append to output. */
714 buffer_append(&active_state->output, buf, 4);
715 cp = buffer_append_space(&active_state->output,
716 buffer_len(&active_state->outgoing_packet));
717 if (cipher_crypt(&active_state->send_context, 0, cp,
718 buffer_ptr(&active_state->outgoing_packet),
719 buffer_len(&active_state->outgoing_packet), 0, 0) != 0)
720 fatal("%s: cipher_crypt failed", __func__);
723 fprintf(stderr, "encrypted: ");
724 buffer_dump(&active_state->output);
726 active_state->p_send.packets++;
727 active_state->p_send.bytes += len +
728 buffer_len(&active_state->outgoing_packet);
729 buffer_clear(&active_state->outgoing_packet);
732 * Note that the packet is now only buffered in output. It won't be
733 * actually sent until packet_write_wait or packet_write_poll is
739 set_newkeys(int mode)
745 u_int64_t *max_blocks;
748 debug2("set_newkeys: mode %d", mode);
750 if (mode == MODE_OUT) {
751 cc = &active_state->send_context;
752 crypt_type = CIPHER_ENCRYPT;
753 active_state->p_send.packets = active_state->p_send.blocks = 0;
754 max_blocks = &active_state->max_blocks_out;
756 cc = &active_state->receive_context;
757 crypt_type = CIPHER_DECRYPT;
758 active_state->p_read.packets = active_state->p_read.blocks = 0;
759 max_blocks = &active_state->max_blocks_in;
761 if (active_state->newkeys[mode] != NULL) {
762 debug("set_newkeys: rekeying");
764 enc = &active_state->newkeys[mode]->enc;
765 mac = &active_state->newkeys[mode]->mac;
766 comp = &active_state->newkeys[mode]->comp;
768 explicit_bzero(enc->iv, enc->iv_len);
769 explicit_bzero(enc->key, enc->key_len);
770 explicit_bzero(mac->key, mac->key_len);
777 free(active_state->newkeys[mode]);
779 active_state->newkeys[mode] = kex_get_newkeys(mode);
780 if (active_state->newkeys[mode] == NULL)
781 fatal("newkeys: no keys for mode %d", mode);
782 enc = &active_state->newkeys[mode]->enc;
783 mac = &active_state->newkeys[mode]->mac;
784 comp = &active_state->newkeys[mode]->comp;
785 if (cipher_authlen(enc->cipher) == 0 && mac_init(mac) == 0)
787 DBG(debug("cipher_init_context: %d", mode));
788 cipher_init(cc, enc->cipher, enc->key, enc->key_len,
789 enc->iv, enc->iv_len, crypt_type);
790 /* Deleting the keys does not gain extra security */
791 /* explicit_bzero(enc->iv, enc->block_size);
792 explicit_bzero(enc->key, enc->key_len);
793 explicit_bzero(mac->key, mac->key_len); */
794 if ((comp->type == COMP_ZLIB ||
795 (comp->type == COMP_DELAYED &&
796 active_state->after_authentication)) && comp->enabled == 0) {
797 packet_init_compression();
798 if (mode == MODE_OUT)
799 buffer_compress_init_send(6);
801 buffer_compress_init_recv();
805 * The 2^(blocksize*2) limit is too expensive for 3DES,
806 * blowfish, etc, so enforce a 1GB limit for small blocksizes.
808 if (enc->block_size >= 16)
809 *max_blocks = (u_int64_t)1 << (enc->block_size*2);
811 *max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
812 if (active_state->rekey_limit)
813 *max_blocks = MIN(*max_blocks,
814 active_state->rekey_limit / enc->block_size);
818 * Delayed compression for SSH2 is enabled after authentication:
819 * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
820 * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
823 packet_enable_delayed_compress(void)
829 * Remember that we are past the authentication step, so rekeying
830 * with COMP_DELAYED will turn on compression immediately.
832 active_state->after_authentication = 1;
833 for (mode = 0; mode < MODE_MAX; mode++) {
834 /* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
835 if (active_state->newkeys[mode] == NULL)
837 comp = &active_state->newkeys[mode]->comp;
838 if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
839 packet_init_compression();
840 if (mode == MODE_OUT)
841 buffer_compress_init_send(6);
843 buffer_compress_init_recv();
850 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
853 packet_send2_wrapped(void)
855 u_char type, *cp, *macbuf = NULL;
856 u_char padlen, pad = 0;
857 u_int i, len, authlen = 0, aadlen = 0;
864 if (active_state->newkeys[MODE_OUT] != NULL) {
865 enc = &active_state->newkeys[MODE_OUT]->enc;
866 mac = &active_state->newkeys[MODE_OUT]->mac;
867 comp = &active_state->newkeys[MODE_OUT]->comp;
868 /* disable mac for authenticated encryption */
869 if ((authlen = cipher_authlen(enc->cipher)) != 0)
872 block_size = enc ? enc->block_size : 8;
873 aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
875 cp = buffer_ptr(&active_state->outgoing_packet);
879 fprintf(stderr, "plain: ");
880 buffer_dump(&active_state->outgoing_packet);
883 if (comp && comp->enabled) {
884 len = buffer_len(&active_state->outgoing_packet);
885 /* skip header, compress only payload */
886 buffer_consume(&active_state->outgoing_packet, 5);
887 buffer_clear(&active_state->compression_buffer);
888 buffer_compress(&active_state->outgoing_packet,
889 &active_state->compression_buffer);
890 buffer_clear(&active_state->outgoing_packet);
891 buffer_append(&active_state->outgoing_packet, "\0\0\0\0\0", 5);
892 buffer_append(&active_state->outgoing_packet,
893 buffer_ptr(&active_state->compression_buffer),
894 buffer_len(&active_state->compression_buffer));
895 DBG(debug("compression: raw %d compressed %d", len,
896 buffer_len(&active_state->outgoing_packet)));
899 /* sizeof (packet_len + pad_len + payload) */
900 len = buffer_len(&active_state->outgoing_packet);
903 * calc size of padding, alloc space, get random data,
904 * minimum padding is 4 bytes
906 len -= aadlen; /* packet length is not encrypted for EtM modes */
907 padlen = block_size - (len % block_size);
909 padlen += block_size;
910 if (active_state->extra_pad) {
911 /* will wrap if extra_pad+padlen > 255 */
912 active_state->extra_pad =
913 roundup(active_state->extra_pad, block_size);
914 pad = active_state->extra_pad -
915 ((len + padlen) % active_state->extra_pad);
916 debug3("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
917 pad, len, padlen, active_state->extra_pad);
919 active_state->extra_pad = 0;
921 cp = buffer_append_space(&active_state->outgoing_packet, padlen);
922 if (enc && !active_state->send_context.plaintext) {
924 for (i = 0; i < padlen; i++) {
932 explicit_bzero(cp, padlen);
934 /* sizeof (packet_len + pad_len + payload + padding) */
935 len = buffer_len(&active_state->outgoing_packet);
936 cp = buffer_ptr(&active_state->outgoing_packet);
937 /* packet_length includes payload, padding and padding length field */
938 put_u32(cp, len - 4);
940 DBG(debug("send: len %d (includes padlen %d, aadlen %d)",
941 len, padlen, aadlen));
943 /* compute MAC over seqnr and packet(length fields, payload, padding) */
944 if (mac && mac->enabled && !mac->etm) {
945 macbuf = mac_compute(mac, active_state->p_send.seqnr,
946 buffer_ptr(&active_state->outgoing_packet), len);
947 DBG(debug("done calc MAC out #%d", active_state->p_send.seqnr));
949 /* encrypt packet and append to output buffer. */
950 cp = buffer_append_space(&active_state->output, len + authlen);
951 if (cipher_crypt(&active_state->send_context, active_state->p_send.seqnr,
952 cp, buffer_ptr(&active_state->outgoing_packet),
953 len - aadlen, aadlen, authlen) != 0)
954 fatal("%s: cipher_crypt failed", __func__);
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 if (cipher_crypt(&active_state->receive_context, 0, cp,
1215 buffer_ptr(&active_state->input), padded_len, 0, 0) != 0)
1216 fatal("%s: cipher_crypt failed", __func__);
1218 buffer_consume(&active_state->input, padded_len);
1221 fprintf(stderr, "read_poll plain: ");
1222 buffer_dump(&active_state->incoming_packet);
1225 /* Compute packet checksum. */
1226 checksum = ssh_crc32(buffer_ptr(&active_state->incoming_packet),
1227 buffer_len(&active_state->incoming_packet) - 4);
1230 buffer_consume(&active_state->incoming_packet, 8 - len % 8);
1232 /* Test check bytes. */
1233 if (len != buffer_len(&active_state->incoming_packet))
1234 packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
1235 len, buffer_len(&active_state->incoming_packet));
1237 cp = (u_char *)buffer_ptr(&active_state->incoming_packet) + len - 4;
1238 stored_checksum = get_u32(cp);
1239 if (checksum != stored_checksum)
1240 packet_disconnect("Corrupted check bytes on input.");
1241 buffer_consume_end(&active_state->incoming_packet, 4);
1243 if (active_state->packet_compression) {
1244 buffer_clear(&active_state->compression_buffer);
1245 buffer_uncompress(&active_state->incoming_packet,
1246 &active_state->compression_buffer);
1247 buffer_clear(&active_state->incoming_packet);
1248 buffer_append(&active_state->incoming_packet,
1249 buffer_ptr(&active_state->compression_buffer),
1250 buffer_len(&active_state->compression_buffer));
1252 active_state->p_read.packets++;
1253 active_state->p_read.bytes += padded_len + 4;
1254 type = buffer_get_char(&active_state->incoming_packet);
1255 if (type < SSH_MSG_MIN || type > SSH_MSG_MAX)
1256 packet_disconnect("Invalid ssh1 packet type: %d", type);
1261 packet_read_poll2(u_int32_t *seqnr_p)
1264 u_char *macbuf = NULL, *cp, type;
1265 u_int maclen, authlen = 0, aadlen = 0, block_size;
1270 if (active_state->packet_discard)
1271 return SSH_MSG_NONE;
1273 if (active_state->newkeys[MODE_IN] != NULL) {
1274 enc = &active_state->newkeys[MODE_IN]->enc;
1275 mac = &active_state->newkeys[MODE_IN]->mac;
1276 comp = &active_state->newkeys[MODE_IN]->comp;
1277 /* disable mac for authenticated encryption */
1278 if ((authlen = cipher_authlen(enc->cipher)) != 0)
1281 maclen = mac && mac->enabled ? mac->mac_len : 0;
1282 block_size = enc ? enc->block_size : 8;
1283 aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
1285 if (aadlen && active_state->packlen == 0) {
1286 if (cipher_get_length(&active_state->receive_context,
1287 &active_state->packlen,
1288 active_state->p_read.seqnr,
1289 buffer_ptr(&active_state->input),
1290 buffer_len(&active_state->input)) != 0)
1291 return SSH_MSG_NONE;
1292 if (active_state->packlen < 1 + 4 ||
1293 active_state->packlen > PACKET_MAX_SIZE) {
1295 buffer_dump(&active_state->input);
1297 logit("Bad packet length %u.", active_state->packlen);
1298 packet_disconnect("Packet corrupt");
1300 buffer_clear(&active_state->incoming_packet);
1301 } else if (active_state->packlen == 0) {
1303 * check if input size is less than the cipher block size,
1304 * decrypt first block and extract length of incoming packet
1306 if (buffer_len(&active_state->input) < block_size)
1307 return SSH_MSG_NONE;
1308 buffer_clear(&active_state->incoming_packet);
1309 cp = buffer_append_space(&active_state->incoming_packet,
1311 if (cipher_crypt(&active_state->receive_context,
1312 active_state->p_read.seqnr, cp,
1313 buffer_ptr(&active_state->input), block_size, 0, 0) != 0)
1314 fatal("Decryption integrity check failed");
1315 cp = buffer_ptr(&active_state->incoming_packet);
1316 active_state->packlen = get_u32(cp);
1317 if (active_state->packlen < 1 + 4 ||
1318 active_state->packlen > PACKET_MAX_SIZE) {
1320 buffer_dump(&active_state->incoming_packet);
1322 logit("Bad packet length %u.", active_state->packlen);
1323 packet_start_discard(enc, mac, active_state->packlen,
1325 return SSH_MSG_NONE;
1327 buffer_consume(&active_state->input, block_size);
1329 DBG(debug("input: packet len %u", active_state->packlen+4));
1331 /* only the payload is encrypted */
1332 need = active_state->packlen;
1335 * the payload size and the payload are encrypted, but we
1336 * have a partial packet of block_size bytes
1338 need = 4 + active_state->packlen - block_size;
1340 DBG(debug("partial packet: block %d, need %d, maclen %d, authlen %d,"
1341 " aadlen %d", block_size, need, maclen, authlen, aadlen));
1342 if (need % block_size != 0) {
1343 logit("padding error: need %d block %d mod %d",
1344 need, block_size, need % block_size);
1345 packet_start_discard(enc, mac, active_state->packlen,
1346 PACKET_MAX_SIZE - block_size);
1347 return SSH_MSG_NONE;
1350 * check if the entire packet has been received and
1351 * decrypt into incoming_packet:
1352 * 'aadlen' bytes are unencrypted, but authenticated.
1353 * 'need' bytes are encrypted, followed by either
1354 * 'authlen' bytes of authentication tag or
1355 * 'maclen' bytes of message authentication code.
1357 if (buffer_len(&active_state->input) < aadlen + need + authlen + maclen)
1358 return SSH_MSG_NONE;
1360 fprintf(stderr, "read_poll enc/full: ");
1361 buffer_dump(&active_state->input);
1363 /* EtM: compute mac over encrypted input */
1364 if (mac && mac->enabled && mac->etm)
1365 macbuf = mac_compute(mac, active_state->p_read.seqnr,
1366 buffer_ptr(&active_state->input), aadlen + need);
1367 cp = buffer_append_space(&active_state->incoming_packet, aadlen + need);
1368 if (cipher_crypt(&active_state->receive_context,
1369 active_state->p_read.seqnr, cp,
1370 buffer_ptr(&active_state->input), need, aadlen, authlen) != 0)
1371 fatal("Decryption integrity check failed");
1372 buffer_consume(&active_state->input, aadlen + need + authlen);
1374 * compute MAC over seqnr and packet,
1375 * increment sequence number for incoming packet
1377 if (mac && mac->enabled) {
1379 macbuf = mac_compute(mac, active_state->p_read.seqnr,
1380 buffer_ptr(&active_state->incoming_packet),
1381 buffer_len(&active_state->incoming_packet));
1382 if (timingsafe_bcmp(macbuf, buffer_ptr(&active_state->input),
1383 mac->mac_len) != 0) {
1384 logit("Corrupted MAC on input.");
1385 if (need > PACKET_MAX_SIZE)
1386 fatal("internal error need %d", need);
1387 packet_start_discard(enc, mac, active_state->packlen,
1388 PACKET_MAX_SIZE - need);
1389 return SSH_MSG_NONE;
1392 DBG(debug("MAC #%d ok", active_state->p_read.seqnr));
1393 buffer_consume(&active_state->input, mac->mac_len);
1395 /* XXX now it's safe to use fatal/packet_disconnect */
1396 if (seqnr_p != NULL)
1397 *seqnr_p = active_state->p_read.seqnr;
1398 if (++active_state->p_read.seqnr == 0)
1399 logit("incoming seqnr wraps around");
1400 if (++active_state->p_read.packets == 0)
1401 if (!(datafellows & SSH_BUG_NOREKEY))
1402 fatal("XXX too many packets with same key");
1403 active_state->p_read.blocks += (active_state->packlen + 4) / block_size;
1404 active_state->p_read.bytes += active_state->packlen + 4;
1407 cp = buffer_ptr(&active_state->incoming_packet);
1409 DBG(debug("input: padlen %d", padlen));
1411 packet_disconnect("Corrupted padlen %d on input.", padlen);
1413 /* skip packet size + padlen, discard padding */
1414 buffer_consume(&active_state->incoming_packet, 4 + 1);
1415 buffer_consume_end(&active_state->incoming_packet, padlen);
1417 DBG(debug("input: len before de-compress %d",
1418 buffer_len(&active_state->incoming_packet)));
1419 if (comp && comp->enabled) {
1420 buffer_clear(&active_state->compression_buffer);
1421 buffer_uncompress(&active_state->incoming_packet,
1422 &active_state->compression_buffer);
1423 buffer_clear(&active_state->incoming_packet);
1424 buffer_append(&active_state->incoming_packet,
1425 buffer_ptr(&active_state->compression_buffer),
1426 buffer_len(&active_state->compression_buffer));
1427 DBG(debug("input: len after de-compress %d",
1428 buffer_len(&active_state->incoming_packet)));
1431 * get packet type, implies consume.
1432 * return length of payload (without type field)
1434 type = buffer_get_char(&active_state->incoming_packet);
1435 if (type < SSH2_MSG_MIN || type >= SSH2_MSG_LOCAL_MIN)
1436 packet_disconnect("Invalid ssh2 packet type: %d", type);
1437 if (type == SSH2_MSG_NEWKEYS)
1438 set_newkeys(MODE_IN);
1439 else if (type == SSH2_MSG_USERAUTH_SUCCESS &&
1440 !active_state->server_side)
1441 packet_enable_delayed_compress();
1443 fprintf(stderr, "read/plain[%d]:\r\n", type);
1444 buffer_dump(&active_state->incoming_packet);
1446 /* reset for next packet */
1447 active_state->packlen = 0;
1452 packet_read_poll_seqnr(u_int32_t *seqnr_p)
1454 u_int reason, seqnr;
1460 type = packet_read_poll2(seqnr_p);
1462 active_state->keep_alive_timeouts = 0;
1463 DBG(debug("received packet type %d", type));
1466 case SSH2_MSG_IGNORE:
1467 debug3("Received SSH2_MSG_IGNORE");
1469 case SSH2_MSG_DEBUG:
1471 msg = packet_get_string(NULL);
1472 debug("Remote: %.900s", msg);
1474 msg = packet_get_string(NULL);
1477 case SSH2_MSG_DISCONNECT:
1478 reason = packet_get_int();
1479 msg = packet_get_string(NULL);
1480 /* Ignore normal client exit notifications */
1481 do_log2(active_state->server_side &&
1482 reason == SSH2_DISCONNECT_BY_APPLICATION ?
1483 SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_ERROR,
1484 "Received disconnect from %s: %u: %.400s",
1485 get_remote_ipaddr(), reason, msg);
1489 case SSH2_MSG_UNIMPLEMENTED:
1490 seqnr = packet_get_int();
1491 debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1498 type = packet_read_poll1();
1501 return SSH_MSG_NONE;
1502 case SSH_MSG_IGNORE:
1505 msg = packet_get_string(NULL);
1506 debug("Remote: %.900s", msg);
1509 case SSH_MSG_DISCONNECT:
1510 msg = packet_get_string(NULL);
1511 logit("Received disconnect from %s: %.400s",
1512 get_remote_ipaddr(), msg);
1516 DBG(debug("received packet type %d", type));
1524 * Buffers the given amount of input characters. This is intended to be used
1525 * together with packet_read_poll.
1529 packet_process_incoming(const char *buf, u_int len)
1531 if (active_state->packet_discard) {
1532 active_state->keep_alive_timeouts = 0; /* ?? */
1533 if (len >= active_state->packet_discard)
1534 packet_stop_discard();
1535 active_state->packet_discard -= len;
1538 buffer_append(&active_state->input, buf, len);
1541 /* Returns a character from the packet. */
1544 packet_get_char(void)
1548 buffer_get(&active_state->incoming_packet, &ch, 1);
1552 /* Returns an integer from the packet data. */
1555 packet_get_int(void)
1557 return buffer_get_int(&active_state->incoming_packet);
1560 /* Returns an 64 bit integer from the packet data. */
1563 packet_get_int64(void)
1565 return buffer_get_int64(&active_state->incoming_packet);
1569 * Returns an arbitrary precision integer from the packet data. The integer
1570 * must have been initialized before this call.
1574 packet_get_bignum(BIGNUM * value)
1576 buffer_get_bignum(&active_state->incoming_packet, value);
1580 packet_get_bignum2(BIGNUM * value)
1582 buffer_get_bignum2(&active_state->incoming_packet, value);
1585 #ifdef OPENSSL_HAS_ECC
1587 packet_get_ecpoint(const EC_GROUP *curve, EC_POINT *point)
1589 buffer_get_ecpoint(&active_state->incoming_packet, curve, point);
1594 packet_get_raw(u_int *length_ptr)
1596 u_int bytes = buffer_len(&active_state->incoming_packet);
1598 if (length_ptr != NULL)
1599 *length_ptr = bytes;
1600 return buffer_ptr(&active_state->incoming_packet);
1604 packet_remaining(void)
1606 return buffer_len(&active_state->incoming_packet);
1610 * Returns a string from the packet data. The string is allocated using
1611 * xmalloc; it is the responsibility of the calling program to free it when
1612 * no longer needed. The length_ptr argument may be NULL, or point to an
1613 * integer into which the length of the string is stored.
1617 packet_get_string(u_int *length_ptr)
1619 return buffer_get_string(&active_state->incoming_packet, length_ptr);
1623 packet_get_string_ptr(u_int *length_ptr)
1625 return buffer_get_string_ptr(&active_state->incoming_packet, length_ptr);
1628 /* Ensures the returned string has no embedded \0 characters in it. */
1630 packet_get_cstring(u_int *length_ptr)
1632 return buffer_get_cstring(&active_state->incoming_packet, length_ptr);
1636 * Sends a diagnostic message from the server to the client. This message
1637 * can be sent at any time (but not while constructing another message). The
1638 * message is printed immediately, but only if the client is being executed
1639 * in verbose mode. These messages are primarily intended to ease debugging
1640 * authentication problems. The length of the formatted message must not
1641 * exceed 1024 bytes. This will automatically call packet_write_wait.
1645 packet_send_debug(const char *fmt,...)
1650 if (compat20 && (datafellows & SSH_BUG_DEBUG))
1653 va_start(args, fmt);
1654 vsnprintf(buf, sizeof(buf), fmt, args);
1658 packet_start(SSH2_MSG_DEBUG);
1659 packet_put_char(0); /* bool: always display */
1660 packet_put_cstring(buf);
1661 packet_put_cstring("");
1663 packet_start(SSH_MSG_DEBUG);
1664 packet_put_cstring(buf);
1667 packet_write_wait();
1671 * Logs the error plus constructs and sends a disconnect packet, closes the
1672 * connection, and exits. This function never returns. The error message
1673 * should not contain a newline. The length of the formatted message must
1674 * not exceed 1024 bytes.
1678 packet_disconnect(const char *fmt,...)
1682 static int disconnecting = 0;
1684 if (disconnecting) /* Guard against recursive invocations. */
1685 fatal("packet_disconnect called recursively.");
1689 * Format the message. Note that the caller must make sure the
1690 * message is of limited size.
1692 va_start(args, fmt);
1693 vsnprintf(buf, sizeof(buf), fmt, args);
1696 /* Display the error locally */
1697 logit("Disconnecting: %.100s", buf);
1699 /* Send the disconnect message to the other side, and wait for it to get sent. */
1701 packet_start(SSH2_MSG_DISCONNECT);
1702 packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1703 packet_put_cstring(buf);
1704 packet_put_cstring("");
1706 packet_start(SSH_MSG_DISCONNECT);
1707 packet_put_cstring(buf);
1710 packet_write_wait();
1712 /* Stop listening for connections. */
1713 channel_close_all();
1715 /* Close the connection. */
1720 /* Checks if there is any buffered output, and tries to write some of the output. */
1723 packet_write_poll(void)
1725 int len = buffer_len(&active_state->output);
1730 len = roaming_write(active_state->connection_out,
1731 buffer_ptr(&active_state->output), len, &cont);
1733 if (errno == EINTR || errno == EAGAIN ||
1734 errno == EWOULDBLOCK)
1736 fatal("Write failed: %.100s", strerror(errno));
1738 if (len == 0 && !cont)
1739 fatal("Write connection closed");
1740 buffer_consume(&active_state->output, len);
1745 * Calls packet_write_poll repeatedly until all pending output data has been
1750 packet_write_wait(void)
1753 int ret, ms_remain = 0;
1754 struct timeval start, timeout, *timeoutp = NULL;
1756 setp = (fd_set *)xcalloc(howmany(active_state->connection_out + 1,
1757 NFDBITS), sizeof(fd_mask));
1758 packet_write_poll();
1759 while (packet_have_data_to_write()) {
1760 memset(setp, 0, howmany(active_state->connection_out + 1,
1761 NFDBITS) * sizeof(fd_mask));
1762 FD_SET(active_state->connection_out, setp);
1764 if (active_state->packet_timeout_ms > 0) {
1765 ms_remain = active_state->packet_timeout_ms;
1766 timeoutp = &timeout;
1769 if (active_state->packet_timeout_ms != -1) {
1770 ms_to_timeval(&timeout, ms_remain);
1771 gettimeofday(&start, NULL);
1773 if ((ret = select(active_state->connection_out + 1,
1774 NULL, setp, NULL, timeoutp)) >= 0)
1776 if (errno != EAGAIN && errno != EINTR &&
1777 errno != EWOULDBLOCK)
1779 if (active_state->packet_timeout_ms == -1)
1781 ms_subtract_diff(&start, &ms_remain);
1782 if (ms_remain <= 0) {
1788 logit("Connection to %.200s timed out while "
1789 "waiting to write", get_remote_ipaddr());
1792 packet_write_poll();
1797 /* Returns true if there is buffered data to write to the connection. */
1800 packet_have_data_to_write(void)
1802 return buffer_len(&active_state->output) != 0;
1805 /* Returns true if there is not too much data to write to the connection. */
1808 packet_not_very_much_data_to_write(void)
1810 if (active_state->interactive_mode)
1811 return buffer_len(&active_state->output) < 16384;
1813 return buffer_len(&active_state->output) < 128 * 1024;
1817 packet_set_tos(int tos)
1819 #ifndef IP_TOS_IS_BROKEN
1820 if (!packet_connection_is_on_socket())
1822 switch (packet_connection_af()) {
1825 debug3("%s: set IP_TOS 0x%02x", __func__, tos);
1826 if (setsockopt(active_state->connection_in,
1827 IPPROTO_IP, IP_TOS, &tos, sizeof(tos)) < 0)
1828 error("setsockopt IP_TOS %d: %.100s:",
1829 tos, strerror(errno));
1831 # endif /* IP_TOS */
1834 debug3("%s: set IPV6_TCLASS 0x%02x", __func__, tos);
1835 if (setsockopt(active_state->connection_in,
1836 IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof(tos)) < 0)
1837 error("setsockopt IPV6_TCLASS %d: %.100s:",
1838 tos, strerror(errno));
1840 # endif /* IPV6_TCLASS */
1842 #endif /* IP_TOS_IS_BROKEN */
1845 /* Informs that the current session is interactive. Sets IP flags for that. */
1848 packet_set_interactive(int interactive, int qos_interactive, int qos_bulk)
1850 if (active_state->set_interactive_called)
1852 active_state->set_interactive_called = 1;
1854 /* Record that we are in interactive mode. */
1855 active_state->interactive_mode = interactive;
1857 /* Only set socket options if using a socket. */
1858 if (!packet_connection_is_on_socket())
1860 set_nodelay(active_state->connection_in);
1861 packet_set_tos(interactive ? qos_interactive : qos_bulk);
1864 /* Returns true if the current connection is interactive. */
1867 packet_is_interactive(void)
1869 return active_state->interactive_mode;
1873 packet_set_maxsize(u_int s)
1875 if (active_state->set_maxsize_called) {
1876 logit("packet_set_maxsize: called twice: old %d new %d",
1877 active_state->max_packet_size, s);
1880 if (s < 4 * 1024 || s > 1024 * 1024) {
1881 logit("packet_set_maxsize: bad size %d", s);
1884 active_state->set_maxsize_called = 1;
1885 debug("packet_set_maxsize: setting to %d", s);
1886 active_state->max_packet_size = s;
1891 packet_inc_alive_timeouts(void)
1893 return ++active_state->keep_alive_timeouts;
1897 packet_set_alive_timeouts(int ka)
1899 active_state->keep_alive_timeouts = ka;
1903 packet_get_maxsize(void)
1905 return active_state->max_packet_size;
1908 /* roundup current message to pad bytes */
1910 packet_add_padding(u_char pad)
1912 active_state->extra_pad = pad;
1916 * 9.2. Ignored Data Message
1918 * byte SSH_MSG_IGNORE
1921 * All implementations MUST understand (and ignore) this message at any
1922 * time (after receiving the protocol version). No implementation is
1923 * required to send them. This message can be used as an additional
1924 * protection measure against advanced traffic analysis techniques.
1927 packet_send_ignore(int nbytes)
1932 packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1933 packet_put_int(nbytes);
1934 for (i = 0; i < nbytes; i++) {
1937 packet_put_char((u_char)rnd & 0xff);
1942 #define MAX_PACKETS (1U<<31)
1944 packet_need_rekeying(void)
1946 if (datafellows & SSH_BUG_NOREKEY)
1949 (active_state->p_send.packets > MAX_PACKETS) ||
1950 (active_state->p_read.packets > MAX_PACKETS) ||
1951 (active_state->max_blocks_out &&
1952 (active_state->p_send.blocks > active_state->max_blocks_out)) ||
1953 (active_state->max_blocks_in &&
1954 (active_state->p_read.blocks > active_state->max_blocks_in)) ||
1955 (active_state->rekey_interval != 0 && active_state->rekey_time +
1956 active_state->rekey_interval <= monotime());
1960 packet_set_rekey_limits(u_int32_t bytes, time_t seconds)
1962 debug3("rekey after %lld bytes, %d seconds", (long long)bytes,
1964 active_state->rekey_limit = bytes;
1965 active_state->rekey_interval = seconds;
1967 * We set the time here so that in post-auth privsep slave we count
1968 * from the completion of the authentication.
1970 active_state->rekey_time = monotime();
1974 packet_get_rekey_timeout(void)
1978 seconds = active_state->rekey_time + active_state->rekey_interval -
1980 return (seconds <= 0 ? 1 : seconds);
1984 packet_set_server(void)
1986 active_state->server_side = 1;
1990 packet_set_authenticated(void)
1992 active_state->after_authentication = 1;
1996 packet_get_input(void)
1998 return (void *)&active_state->input;
2002 packet_get_output(void)
2004 return (void *)&active_state->output;
2008 packet_get_newkeys(int mode)
2010 return (void *)active_state->newkeys[mode];
2014 * Save the state for the real connection, and use a separate state when
2015 * resuming a suspended connection.
2018 packet_backup_state(void)
2020 struct session_state *tmp;
2022 close(active_state->connection_in);
2023 active_state->connection_in = -1;
2024 close(active_state->connection_out);
2025 active_state->connection_out = -1;
2029 tmp = alloc_session_state();
2030 backup_state = active_state;
2035 * Swap in the old state when resuming a connecion.
2038 packet_restore_state(void)
2040 struct session_state *tmp;
2045 backup_state = active_state;
2047 active_state->connection_in = backup_state->connection_in;
2048 backup_state->connection_in = -1;
2049 active_state->connection_out = backup_state->connection_out;
2050 backup_state->connection_out = -1;
2051 len = buffer_len(&backup_state->input);
2053 buf = buffer_ptr(&backup_state->input);
2054 buffer_append(&active_state->input, buf, len);
2055 buffer_clear(&backup_state->input);
2056 add_recv_bytes(len);