1 /* $OpenBSD: packet.c,v 1.157 2008/07/10 18:08:11 markus 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>
88 * This variable contains the file descriptors used for communicating with
89 * the other side. connection_in is used for reading; connection_out for
90 * writing. These can be the same descriptor, in which case it is assumed to
93 static int connection_in = -1;
94 static int connection_out = -1;
96 /* Protocol flags for the remote side. */
97 static u_int remote_protocol_flags = 0;
99 /* Encryption context for receiving data. This is only used for decryption. */
100 static CipherContext receive_context;
102 /* Encryption context for sending data. This is only used for encryption. */
103 static CipherContext send_context;
105 /* Buffer for raw input data from the socket. */
108 /* Buffer for raw output data going to the socket. */
111 /* Buffer for the partial outgoing packet being constructed. */
112 static Buffer outgoing_packet;
114 /* Buffer for the incoming packet currently being processed. */
115 static Buffer incoming_packet;
117 /* Scratch buffer for packet compression/decompression. */
118 static Buffer compression_buffer;
119 static int compression_buffer_ready = 0;
121 /* Flag indicating whether packet compression/decompression is enabled. */
122 static int packet_compression = 0;
124 /* default maximum packet size */
125 u_int max_packet_size = 32768;
127 /* Flag indicating whether this module has been initialized. */
128 static int initialized = 0;
130 /* Set to true if the connection is interactive. */
131 static int interactive_mode = 0;
133 /* Set to true if we are the server side. */
134 static int server_side = 0;
136 /* Set to true if we are authenticated. */
137 static int after_authentication = 0;
139 int keep_alive_timeouts = 0;
141 /* Set to the maximum time that we will wait to send or receive a packet */
142 static int packet_timeout_ms = -1;
144 /* Session key information for Encryption and MAC */
145 Newkeys *newkeys[MODE_MAX];
146 static struct packet_state {
153 static u_int64_t max_blocks_in, max_blocks_out;
154 static u_int32_t rekey_limit;
156 /* Session key for protocol v1 */
157 static u_char ssh1_key[SSH_SESSION_KEY_LENGTH];
158 static u_int ssh1_keylen;
160 /* roundup current message to extra_pad bytes */
161 static u_char extra_pad = 0;
164 TAILQ_ENTRY(packet) next;
168 TAILQ_HEAD(, packet) outgoing;
171 * Sets the descriptors used for communication. Disables encryption until
172 * packet_set_encryption_key is called.
175 packet_set_connection(int fd_in, int fd_out)
177 Cipher *none = cipher_by_name("none");
180 fatal("packet_set_connection: cannot load cipher 'none'");
181 connection_in = fd_in;
182 connection_out = fd_out;
183 cipher_init(&send_context, none, (const u_char *)"",
184 0, NULL, 0, CIPHER_ENCRYPT);
185 cipher_init(&receive_context, none, (const u_char *)"",
186 0, NULL, 0, CIPHER_DECRYPT);
187 newkeys[MODE_IN] = newkeys[MODE_OUT] = NULL;
191 buffer_init(&output);
192 buffer_init(&outgoing_packet);
193 buffer_init(&incoming_packet);
194 TAILQ_INIT(&outgoing);
195 p_send.packets = p_read.packets = 0;
200 packet_set_timeout(int timeout, int count)
202 if (timeout == 0 || count == 0) {
203 packet_timeout_ms = -1;
206 if ((INT_MAX / 1000) / count < timeout)
207 packet_timeout_ms = INT_MAX;
209 packet_timeout_ms = timeout * count * 1000;
212 /* Returns 1 if remote host is connected via socket, 0 if not. */
215 packet_connection_is_on_socket(void)
217 struct sockaddr_storage from, to;
218 socklen_t fromlen, tolen;
220 /* filedescriptors in and out are the same, so it's a socket */
221 if (connection_in == connection_out)
223 fromlen = sizeof(from);
224 memset(&from, 0, sizeof(from));
225 if (getpeername(connection_in, (struct sockaddr *)&from, &fromlen) < 0)
228 memset(&to, 0, sizeof(to));
229 if (getpeername(connection_out, (struct sockaddr *)&to, &tolen) < 0)
231 if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
233 if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
239 * Exports an IV from the CipherContext required to export the key
240 * state back from the unprivileged child to the privileged parent
245 packet_get_keyiv(int mode, u_char *iv, u_int len)
249 if (mode == MODE_OUT)
252 cc = &receive_context;
254 cipher_get_keyiv(cc, iv, len);
258 packet_get_keycontext(int mode, u_char *dat)
262 if (mode == MODE_OUT)
265 cc = &receive_context;
267 return (cipher_get_keycontext(cc, dat));
271 packet_set_keycontext(int mode, u_char *dat)
275 if (mode == MODE_OUT)
278 cc = &receive_context;
280 cipher_set_keycontext(cc, dat);
284 packet_get_keyiv_len(int mode)
288 if (mode == MODE_OUT)
291 cc = &receive_context;
293 return (cipher_get_keyiv_len(cc));
297 packet_set_iv(int mode, u_char *dat)
301 if (mode == MODE_OUT)
304 cc = &receive_context;
306 cipher_set_keyiv(cc, dat);
310 packet_get_ssh1_cipher(void)
312 return (cipher_get_number(receive_context.cipher));
316 packet_get_state(int mode, u_int32_t *seqnr, u_int64_t *blocks, u_int32_t *packets,
319 struct packet_state *state;
321 state = (mode == MODE_IN) ? &p_read : &p_send;
323 *seqnr = state->seqnr;
325 *blocks = state->blocks;
327 *packets = state->packets;
329 *bytes = state->bytes;
333 packet_set_state(int mode, u_int32_t seqnr, u_int64_t blocks, u_int32_t packets,
336 struct packet_state *state;
338 state = (mode == MODE_IN) ? &p_read : &p_send;
339 state->seqnr = seqnr;
340 state->blocks = blocks;
341 state->packets = packets;
342 state->bytes = bytes;
345 /* returns 1 if connection is via ipv4 */
348 packet_connection_is_ipv4(void)
350 struct sockaddr_storage to;
351 socklen_t tolen = sizeof(to);
353 memset(&to, 0, sizeof(to));
354 if (getsockname(connection_out, (struct sockaddr *)&to, &tolen) < 0)
356 if (to.ss_family == AF_INET)
359 if (to.ss_family == AF_INET6 &&
360 IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&to)->sin6_addr))
366 /* Sets the connection into non-blocking mode. */
369 packet_set_nonblocking(void)
371 /* Set the socket into non-blocking mode. */
372 set_nonblock(connection_in);
374 if (connection_out != connection_in)
375 set_nonblock(connection_out);
378 /* Returns the socket used for reading. */
381 packet_get_connection_in(void)
383 return connection_in;
386 /* Returns the descriptor used for writing. */
389 packet_get_connection_out(void)
391 return connection_out;
394 /* Closes the connection and clears and frees internal data structures. */
402 if (connection_in == connection_out) {
403 shutdown(connection_out, SHUT_RDWR);
404 close(connection_out);
406 close(connection_in);
407 close(connection_out);
410 buffer_free(&output);
411 buffer_free(&outgoing_packet);
412 buffer_free(&incoming_packet);
413 if (compression_buffer_ready) {
414 buffer_free(&compression_buffer);
415 buffer_compress_uninit();
417 cipher_cleanup(&send_context);
418 cipher_cleanup(&receive_context);
421 /* Sets remote side protocol flags. */
424 packet_set_protocol_flags(u_int protocol_flags)
426 remote_protocol_flags = protocol_flags;
429 /* Returns the remote protocol flags set earlier by the above function. */
432 packet_get_protocol_flags(void)
434 return remote_protocol_flags;
438 * Starts packet compression from the next packet on in both directions.
439 * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
443 packet_init_compression(void)
445 if (compression_buffer_ready == 1)
447 compression_buffer_ready = 1;
448 buffer_init(&compression_buffer);
452 packet_start_compression(int level)
454 if (packet_compression && !compat20)
455 fatal("Compression already enabled.");
456 packet_compression = 1;
457 packet_init_compression();
458 buffer_compress_init_send(level);
459 buffer_compress_init_recv();
463 * Causes any further packets to be encrypted using the given key. The same
464 * key is used for both sending and reception. However, both directions are
465 * encrypted independently of each other.
469 packet_set_encryption_key(const u_char *key, u_int keylen,
472 Cipher *cipher = cipher_by_number(number);
475 fatal("packet_set_encryption_key: unknown cipher number %d", number);
477 fatal("packet_set_encryption_key: keylen too small: %d", keylen);
478 if (keylen > SSH_SESSION_KEY_LENGTH)
479 fatal("packet_set_encryption_key: keylen too big: %d", keylen);
480 memcpy(ssh1_key, key, keylen);
481 ssh1_keylen = keylen;
482 cipher_init(&send_context, cipher, key, keylen, NULL, 0, CIPHER_ENCRYPT);
483 cipher_init(&receive_context, cipher, key, keylen, NULL, 0, CIPHER_DECRYPT);
487 packet_get_encryption_key(u_char *key)
490 return (ssh1_keylen);
491 memcpy(key, ssh1_key, ssh1_keylen);
492 return (ssh1_keylen);
495 /* Start constructing a packet to send. */
497 packet_start(u_char type)
502 DBG(debug("packet_start[%d]", type));
503 len = compat20 ? 6 : 9;
504 memset(buf, 0, len - 1);
506 buffer_clear(&outgoing_packet);
507 buffer_append(&outgoing_packet, buf, len);
510 /* Append payload. */
512 packet_put_char(int value)
516 buffer_append(&outgoing_packet, &ch, 1);
520 packet_put_int(u_int value)
522 buffer_put_int(&outgoing_packet, value);
526 packet_put_string(const void *buf, u_int len)
528 buffer_put_string(&outgoing_packet, buf, len);
532 packet_put_cstring(const char *str)
534 buffer_put_cstring(&outgoing_packet, str);
538 packet_put_raw(const void *buf, u_int len)
540 buffer_append(&outgoing_packet, buf, len);
544 packet_put_bignum(BIGNUM * value)
546 buffer_put_bignum(&outgoing_packet, value);
550 packet_put_bignum2(BIGNUM * value)
552 buffer_put_bignum2(&outgoing_packet, value);
556 * Finalizes and sends the packet. If the encryption key has been set,
557 * encrypts the packet before sending.
569 * If using packet compression, compress the payload of the outgoing
572 if (packet_compression) {
573 buffer_clear(&compression_buffer);
575 buffer_consume(&outgoing_packet, 8);
577 buffer_append(&compression_buffer, "\0\0\0\0\0\0\0\0", 8);
578 buffer_compress(&outgoing_packet, &compression_buffer);
579 buffer_clear(&outgoing_packet);
580 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
581 buffer_len(&compression_buffer));
583 /* Compute packet length without padding (add checksum, remove padding). */
584 len = buffer_len(&outgoing_packet) + 4 - 8;
586 /* Insert padding. Initialized to zero in packet_start1() */
587 padding = 8 - len % 8;
588 if (!send_context.plaintext) {
589 cp = buffer_ptr(&outgoing_packet);
590 for (i = 0; i < padding; i++) {
593 cp[7 - i] = rnd & 0xff;
597 buffer_consume(&outgoing_packet, 8 - padding);
599 /* Add check bytes. */
600 checksum = ssh_crc32(buffer_ptr(&outgoing_packet),
601 buffer_len(&outgoing_packet));
602 put_u32(buf, checksum);
603 buffer_append(&outgoing_packet, buf, 4);
606 fprintf(stderr, "packet_send plain: ");
607 buffer_dump(&outgoing_packet);
610 /* Append to output. */
612 buffer_append(&output, buf, 4);
613 cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
614 cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
615 buffer_len(&outgoing_packet));
618 fprintf(stderr, "encrypted: ");
619 buffer_dump(&output);
622 p_send.bytes += len + buffer_len(&outgoing_packet);
623 buffer_clear(&outgoing_packet);
626 * Note that the packet is now only buffered in output. It won't be
627 * actually sent until packet_write_wait or packet_write_poll is
633 set_newkeys(int mode)
639 u_int64_t *max_blocks;
642 debug2("set_newkeys: mode %d", mode);
644 if (mode == MODE_OUT) {
646 crypt_type = CIPHER_ENCRYPT;
647 p_send.packets = p_send.blocks = 0;
648 max_blocks = &max_blocks_out;
650 cc = &receive_context;
651 crypt_type = CIPHER_DECRYPT;
652 p_read.packets = p_read.blocks = 0;
653 max_blocks = &max_blocks_in;
655 if (newkeys[mode] != NULL) {
656 debug("set_newkeys: rekeying");
658 enc = &newkeys[mode]->enc;
659 mac = &newkeys[mode]->mac;
660 comp = &newkeys[mode]->comp;
668 xfree(newkeys[mode]);
670 newkeys[mode] = kex_get_newkeys(mode);
671 if (newkeys[mode] == NULL)
672 fatal("newkeys: no keys for mode %d", mode);
673 enc = &newkeys[mode]->enc;
674 mac = &newkeys[mode]->mac;
675 comp = &newkeys[mode]->comp;
676 if (mac_init(mac) == 0)
678 DBG(debug("cipher_init_context: %d", mode));
679 cipher_init(cc, enc->cipher, enc->key, enc->key_len,
680 enc->iv, enc->block_size, crypt_type);
681 /* Deleting the keys does not gain extra security */
682 /* memset(enc->iv, 0, enc->block_size);
683 memset(enc->key, 0, enc->key_len);
684 memset(mac->key, 0, mac->key_len); */
685 if ((comp->type == COMP_ZLIB ||
686 (comp->type == COMP_DELAYED && after_authentication)) &&
687 comp->enabled == 0) {
688 packet_init_compression();
689 if (mode == MODE_OUT)
690 buffer_compress_init_send(6);
692 buffer_compress_init_recv();
696 * The 2^(blocksize*2) limit is too expensive for 3DES,
697 * blowfish, etc, so enforce a 1GB limit for small blocksizes.
699 if (enc->block_size >= 16)
700 *max_blocks = (u_int64_t)1 << (enc->block_size*2);
702 *max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
704 *max_blocks = MIN(*max_blocks, rekey_limit / enc->block_size);
708 * Delayed compression for SSH2 is enabled after authentication:
709 * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
710 * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
713 packet_enable_delayed_compress(void)
719 * Remember that we are past the authentication step, so rekeying
720 * with COMP_DELAYED will turn on compression immediately.
722 after_authentication = 1;
723 for (mode = 0; mode < MODE_MAX; mode++) {
724 /* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
725 if (newkeys[mode] == NULL)
727 comp = &newkeys[mode]->comp;
728 if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
729 packet_init_compression();
730 if (mode == MODE_OUT)
731 buffer_compress_init_send(6);
733 buffer_compress_init_recv();
740 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
743 packet_send2_wrapped(void)
745 u_char type, *cp, *macbuf = NULL;
747 u_int packet_length = 0;
755 if (newkeys[MODE_OUT] != NULL) {
756 enc = &newkeys[MODE_OUT]->enc;
757 mac = &newkeys[MODE_OUT]->mac;
758 comp = &newkeys[MODE_OUT]->comp;
760 block_size = enc ? enc->block_size : 8;
762 cp = buffer_ptr(&outgoing_packet);
766 fprintf(stderr, "plain: ");
767 buffer_dump(&outgoing_packet);
770 if (comp && comp->enabled) {
771 len = buffer_len(&outgoing_packet);
772 /* skip header, compress only payload */
773 buffer_consume(&outgoing_packet, 5);
774 buffer_clear(&compression_buffer);
775 buffer_compress(&outgoing_packet, &compression_buffer);
776 buffer_clear(&outgoing_packet);
777 buffer_append(&outgoing_packet, "\0\0\0\0\0", 5);
778 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
779 buffer_len(&compression_buffer));
780 DBG(debug("compression: raw %d compressed %d", len,
781 buffer_len(&outgoing_packet)));
784 /* sizeof (packet_len + pad_len + payload) */
785 len = buffer_len(&outgoing_packet);
788 * calc size of padding, alloc space, get random data,
789 * minimum padding is 4 bytes
791 padlen = block_size - (len % block_size);
793 padlen += block_size;
795 /* will wrap if extra_pad+padlen > 255 */
796 extra_pad = roundup(extra_pad, block_size);
797 pad = extra_pad - ((len + padlen) % extra_pad);
798 debug3("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
799 pad, len, padlen, extra_pad);
803 cp = buffer_append_space(&outgoing_packet, padlen);
804 if (enc && !send_context.plaintext) {
806 for (i = 0; i < padlen; i++) {
814 memset(cp, 0, padlen);
816 /* packet_length includes payload, padding and padding length field */
817 packet_length = buffer_len(&outgoing_packet) - 4;
818 cp = buffer_ptr(&outgoing_packet);
819 put_u32(cp, packet_length);
821 DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen));
823 /* compute MAC over seqnr and packet(length fields, payload, padding) */
824 if (mac && mac->enabled) {
825 macbuf = mac_compute(mac, p_send.seqnr,
826 buffer_ptr(&outgoing_packet),
827 buffer_len(&outgoing_packet));
828 DBG(debug("done calc MAC out #%d", p_send.seqnr));
830 /* encrypt packet and append to output buffer. */
831 cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
832 cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
833 buffer_len(&outgoing_packet));
834 /* append unencrypted MAC */
835 if (mac && mac->enabled)
836 buffer_append(&output, macbuf, mac->mac_len);
838 fprintf(stderr, "encrypted: ");
839 buffer_dump(&output);
841 /* increment sequence number for outgoing packets */
842 if (++p_send.seqnr == 0)
843 logit("outgoing seqnr wraps around");
844 if (++p_send.packets == 0)
845 if (!(datafellows & SSH_BUG_NOREKEY))
846 fatal("XXX too many packets with same key");
847 p_send.blocks += (packet_length + 4) / block_size;
848 p_send.bytes += packet_length + 4;
849 buffer_clear(&outgoing_packet);
851 if (type == SSH2_MSG_NEWKEYS)
852 set_newkeys(MODE_OUT);
853 else if (type == SSH2_MSG_USERAUTH_SUCCESS && server_side)
854 packet_enable_delayed_compress();
855 return(packet_length);
861 static int packet_length = 0;
862 static int rekeying = 0;
866 cp = buffer_ptr(&outgoing_packet);
869 /* during rekeying we can only send key exchange messages */
871 if (!((type >= SSH2_MSG_TRANSPORT_MIN) &&
872 (type <= SSH2_MSG_TRANSPORT_MAX))) {
873 debug("enqueue packet: %u", type);
874 p = xmalloc(sizeof(*p));
876 memcpy(&p->payload, &outgoing_packet, sizeof(Buffer));
877 buffer_init(&outgoing_packet);
878 TAILQ_INSERT_TAIL(&outgoing, p, next);
879 return(sizeof(Buffer));
883 /* rekeying starts with sending KEXINIT */
884 if (type == SSH2_MSG_KEXINIT)
887 packet_length = packet_send2_wrapped();
889 /* after a NEWKEYS message we can send the complete queue */
890 if (type == SSH2_MSG_NEWKEYS) {
892 while ((p = TAILQ_FIRST(&outgoing))) {
894 debug("dequeue packet: %u", type);
895 buffer_free(&outgoing_packet);
896 memcpy(&outgoing_packet, &p->payload,
898 TAILQ_REMOVE(&outgoing, p, next);
900 packet_length += packet_send2_wrapped();
903 return(packet_length);
911 packet_len = packet_send2();
914 DBG(debug("packet_send done"));
919 * Waits until a packet has been received, and returns its type. Note that
920 * no other data is processed until this returns, so this function should not
921 * be used during the interactive session.
925 packet_read_seqnr(u_int32_t *seqnr_p)
927 int type, len, ret, ms_remain;
930 struct timeval timeout, start, *timeoutp = NULL;
932 DBG(debug("packet_read()"));
934 setp = (fd_set *)xcalloc(howmany(connection_in+1, NFDBITS),
937 /* Since we are blocking, ensure that all written packets have been sent. */
940 /* Stay in the loop until we have received a complete packet. */
942 /* Try to read a packet from the buffer. */
943 type = packet_read_poll_seqnr(seqnr_p);
945 type == SSH_SMSG_SUCCESS
946 || type == SSH_SMSG_FAILURE
947 || type == SSH_CMSG_EOF
948 || type == SSH_CMSG_EXIT_CONFIRMATION))
950 /* If we got a packet, return it. */
951 if (type != SSH_MSG_NONE) {
956 * Otherwise, wait for some data to arrive, add it to the
957 * buffer, and try again.
959 memset(setp, 0, howmany(connection_in + 1, NFDBITS) *
961 FD_SET(connection_in, setp);
963 if (packet_timeout_ms > 0) {
964 ms_remain = packet_timeout_ms;
967 /* Wait for some data to arrive. */
969 if (packet_timeout_ms != -1) {
970 ms_to_timeval(&timeout, ms_remain);
971 gettimeofday(&start, NULL);
973 if ((ret = select(connection_in + 1, setp, NULL,
974 NULL, timeoutp)) >= 0)
976 if (errno != EAGAIN && errno != EINTR &&
977 errno != EWOULDBLOCK)
979 if (packet_timeout_ms == -1)
981 ms_subtract_diff(&start, &ms_remain);
982 if (ms_remain <= 0) {
988 logit("Connection to %.200s timed out while "
989 "waiting to read", get_remote_ipaddr());
992 /* Read data from the socket. */
993 len = read(connection_in, buf, sizeof(buf));
995 logit("Connection closed by %.200s", get_remote_ipaddr());
999 fatal("Read from socket failed: %.100s", strerror(errno));
1000 /* Append it to the buffer. */
1001 packet_process_incoming(buf, len);
1009 return packet_read_seqnr(NULL);
1013 * Waits until a packet has been received, verifies that its type matches
1014 * that given, and gives a fatal error and exits if there is a mismatch.
1018 packet_read_expect(int expected_type)
1022 type = packet_read();
1023 if (type != expected_type)
1024 packet_disconnect("Protocol error: expected packet type %d, got %d",
1025 expected_type, type);
1028 /* Checks if a full packet is available in the data received so far via
1029 * packet_process_incoming. If so, reads the packet; otherwise returns
1030 * SSH_MSG_NONE. This does not wait for data from the connection.
1032 * SSH_MSG_DISCONNECT is handled specially here. Also,
1033 * SSH_MSG_IGNORE messages are skipped by this function and are never returned
1038 packet_read_poll1(void)
1040 u_int len, padded_len;
1042 u_int checksum, stored_checksum;
1044 /* Check if input size is less than minimum packet size. */
1045 if (buffer_len(&input) < 4 + 8)
1046 return SSH_MSG_NONE;
1047 /* Get length of incoming packet. */
1048 cp = buffer_ptr(&input);
1050 if (len < 1 + 2 + 2 || len > 256 * 1024)
1051 packet_disconnect("Bad packet length %u.", len);
1052 padded_len = (len + 8) & ~7;
1054 /* Check if the packet has been entirely received. */
1055 if (buffer_len(&input) < 4 + padded_len)
1056 return SSH_MSG_NONE;
1058 /* The entire packet is in buffer. */
1060 /* Consume packet length. */
1061 buffer_consume(&input, 4);
1064 * Cryptographic attack detector for ssh
1065 * (C)1998 CORE-SDI, Buenos Aires Argentina
1066 * Ariel Futoransky(futo@core-sdi.com)
1068 if (!receive_context.plaintext) {
1069 switch (detect_attack(buffer_ptr(&input), padded_len)) {
1070 case DEATTACK_DETECTED:
1071 packet_disconnect("crc32 compensation attack: "
1072 "network attack detected");
1073 case DEATTACK_DOS_DETECTED:
1074 packet_disconnect("deattack denial of "
1075 "service detected");
1079 /* Decrypt data to incoming_packet. */
1080 buffer_clear(&incoming_packet);
1081 cp = buffer_append_space(&incoming_packet, padded_len);
1082 cipher_crypt(&receive_context, cp, buffer_ptr(&input), padded_len);
1084 buffer_consume(&input, padded_len);
1087 fprintf(stderr, "read_poll plain: ");
1088 buffer_dump(&incoming_packet);
1091 /* Compute packet checksum. */
1092 checksum = ssh_crc32(buffer_ptr(&incoming_packet),
1093 buffer_len(&incoming_packet) - 4);
1096 buffer_consume(&incoming_packet, 8 - len % 8);
1098 /* Test check bytes. */
1099 if (len != buffer_len(&incoming_packet))
1100 packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
1101 len, buffer_len(&incoming_packet));
1103 cp = (u_char *)buffer_ptr(&incoming_packet) + len - 4;
1104 stored_checksum = get_u32(cp);
1105 if (checksum != stored_checksum)
1106 packet_disconnect("Corrupted check bytes on input.");
1107 buffer_consume_end(&incoming_packet, 4);
1109 if (packet_compression) {
1110 buffer_clear(&compression_buffer);
1111 buffer_uncompress(&incoming_packet, &compression_buffer);
1112 buffer_clear(&incoming_packet);
1113 buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
1114 buffer_len(&compression_buffer));
1117 p_read.bytes += padded_len + 4;
1118 type = buffer_get_char(&incoming_packet);
1119 if (type < SSH_MSG_MIN || type > SSH_MSG_MAX)
1120 packet_disconnect("Invalid ssh1 packet type: %d", type);
1125 packet_read_poll2(u_int32_t *seqnr_p)
1127 static u_int packet_length = 0;
1129 u_char *macbuf, *cp, type;
1130 u_int maclen, block_size;
1135 if (newkeys[MODE_IN] != NULL) {
1136 enc = &newkeys[MODE_IN]->enc;
1137 mac = &newkeys[MODE_IN]->mac;
1138 comp = &newkeys[MODE_IN]->comp;
1140 maclen = mac && mac->enabled ? mac->mac_len : 0;
1141 block_size = enc ? enc->block_size : 8;
1143 if (packet_length == 0) {
1145 * check if input size is less than the cipher block size,
1146 * decrypt first block and extract length of incoming packet
1148 if (buffer_len(&input) < block_size)
1149 return SSH_MSG_NONE;
1150 buffer_clear(&incoming_packet);
1151 cp = buffer_append_space(&incoming_packet, block_size);
1152 cipher_crypt(&receive_context, cp, buffer_ptr(&input),
1154 cp = buffer_ptr(&incoming_packet);
1155 packet_length = get_u32(cp);
1156 if (packet_length < 1 + 4 || packet_length > 256 * 1024) {
1158 buffer_dump(&incoming_packet);
1160 packet_disconnect("Bad packet length %u.", packet_length);
1162 DBG(debug("input: packet len %u", packet_length+4));
1163 buffer_consume(&input, block_size);
1165 /* we have a partial packet of block_size bytes */
1166 need = 4 + packet_length - block_size;
1167 DBG(debug("partial packet %d, need %d, maclen %d", block_size,
1169 if (need % block_size != 0)
1170 fatal("padding error: need %d block %d mod %d",
1171 need, block_size, need % block_size);
1173 * check if the entire packet has been received and
1174 * decrypt into incoming_packet
1176 if (buffer_len(&input) < need + maclen)
1177 return SSH_MSG_NONE;
1179 fprintf(stderr, "read_poll enc/full: ");
1180 buffer_dump(&input);
1182 cp = buffer_append_space(&incoming_packet, need);
1183 cipher_crypt(&receive_context, cp, buffer_ptr(&input), need);
1184 buffer_consume(&input, need);
1186 * compute MAC over seqnr and packet,
1187 * increment sequence number for incoming packet
1189 if (mac && mac->enabled) {
1190 macbuf = mac_compute(mac, p_read.seqnr,
1191 buffer_ptr(&incoming_packet),
1192 buffer_len(&incoming_packet));
1193 if (memcmp(macbuf, buffer_ptr(&input), mac->mac_len) != 0)
1194 packet_disconnect("Corrupted MAC on input.");
1195 DBG(debug("MAC #%d ok", p_read.seqnr));
1196 buffer_consume(&input, mac->mac_len);
1198 if (seqnr_p != NULL)
1199 *seqnr_p = p_read.seqnr;
1200 if (++p_read.seqnr == 0)
1201 logit("incoming seqnr wraps around");
1202 if (++p_read.packets == 0)
1203 if (!(datafellows & SSH_BUG_NOREKEY))
1204 fatal("XXX too many packets with same key");
1205 p_read.blocks += (packet_length + 4) / block_size;
1206 p_read.bytes += packet_length + 4;
1209 cp = buffer_ptr(&incoming_packet);
1211 DBG(debug("input: padlen %d", padlen));
1213 packet_disconnect("Corrupted padlen %d on input.", padlen);
1215 /* skip packet size + padlen, discard padding */
1216 buffer_consume(&incoming_packet, 4 + 1);
1217 buffer_consume_end(&incoming_packet, padlen);
1219 DBG(debug("input: len before de-compress %d", buffer_len(&incoming_packet)));
1220 if (comp && comp->enabled) {
1221 buffer_clear(&compression_buffer);
1222 buffer_uncompress(&incoming_packet, &compression_buffer);
1223 buffer_clear(&incoming_packet);
1224 buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
1225 buffer_len(&compression_buffer));
1226 DBG(debug("input: len after de-compress %d",
1227 buffer_len(&incoming_packet)));
1230 * get packet type, implies consume.
1231 * return length of payload (without type field)
1233 type = buffer_get_char(&incoming_packet);
1234 if (type < SSH2_MSG_MIN || type >= SSH2_MSG_LOCAL_MIN)
1235 packet_disconnect("Invalid ssh2 packet type: %d", type);
1236 if (type == SSH2_MSG_NEWKEYS)
1237 set_newkeys(MODE_IN);
1238 else if (type == SSH2_MSG_USERAUTH_SUCCESS && !server_side)
1239 packet_enable_delayed_compress();
1241 fprintf(stderr, "read/plain[%d]:\r\n", type);
1242 buffer_dump(&incoming_packet);
1244 /* reset for next packet */
1250 packet_read_poll_seqnr(u_int32_t *seqnr_p)
1252 u_int reason, seqnr;
1258 type = packet_read_poll2(seqnr_p);
1260 keep_alive_timeouts = 0;
1261 DBG(debug("received packet type %d", type));
1264 case SSH2_MSG_IGNORE:
1265 debug3("Received SSH2_MSG_IGNORE");
1267 case SSH2_MSG_DEBUG:
1269 msg = packet_get_string(NULL);
1270 debug("Remote: %.900s", msg);
1272 msg = packet_get_string(NULL);
1275 case SSH2_MSG_DISCONNECT:
1276 reason = packet_get_int();
1277 msg = packet_get_string(NULL);
1278 logit("Received disconnect from %s: %u: %.400s",
1279 get_remote_ipaddr(), reason, msg);
1283 case SSH2_MSG_UNIMPLEMENTED:
1284 seqnr = packet_get_int();
1285 debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1292 type = packet_read_poll1();
1294 case SSH_MSG_IGNORE:
1297 msg = packet_get_string(NULL);
1298 debug("Remote: %.900s", msg);
1301 case SSH_MSG_DISCONNECT:
1302 msg = packet_get_string(NULL);
1303 logit("Received disconnect from %s: %.400s",
1304 get_remote_ipaddr(), msg);
1309 DBG(debug("received packet type %d", type));
1317 packet_read_poll(void)
1319 return packet_read_poll_seqnr(NULL);
1323 * Buffers the given amount of input characters. This is intended to be used
1324 * together with packet_read_poll.
1328 packet_process_incoming(const char *buf, u_int len)
1330 buffer_append(&input, buf, len);
1333 /* Returns a character from the packet. */
1336 packet_get_char(void)
1340 buffer_get(&incoming_packet, &ch, 1);
1344 /* Returns an integer from the packet data. */
1347 packet_get_int(void)
1349 return buffer_get_int(&incoming_packet);
1353 * Returns an arbitrary precision integer from the packet data. The integer
1354 * must have been initialized before this call.
1358 packet_get_bignum(BIGNUM * value)
1360 buffer_get_bignum(&incoming_packet, value);
1364 packet_get_bignum2(BIGNUM * value)
1366 buffer_get_bignum2(&incoming_packet, value);
1370 packet_get_raw(u_int *length_ptr)
1372 u_int bytes = buffer_len(&incoming_packet);
1374 if (length_ptr != NULL)
1375 *length_ptr = bytes;
1376 return buffer_ptr(&incoming_packet);
1380 packet_remaining(void)
1382 return buffer_len(&incoming_packet);
1386 * Returns a string from the packet data. The string is allocated using
1387 * xmalloc; it is the responsibility of the calling program to free it when
1388 * no longer needed. The length_ptr argument may be NULL, or point to an
1389 * integer into which the length of the string is stored.
1393 packet_get_string(u_int *length_ptr)
1395 return buffer_get_string(&incoming_packet, length_ptr);
1399 packet_get_string_ptr(u_int *length_ptr)
1401 return buffer_get_string_ptr(&incoming_packet, length_ptr);
1405 * Sends a diagnostic message from the server to the client. This message
1406 * can be sent at any time (but not while constructing another message). The
1407 * message is printed immediately, but only if the client is being executed
1408 * in verbose mode. These messages are primarily intended to ease debugging
1409 * authentication problems. The length of the formatted message must not
1410 * exceed 1024 bytes. This will automatically call packet_write_wait.
1414 packet_send_debug(const char *fmt,...)
1419 if (compat20 && (datafellows & SSH_BUG_DEBUG))
1422 va_start(args, fmt);
1423 vsnprintf(buf, sizeof(buf), fmt, args);
1427 packet_start(SSH2_MSG_DEBUG);
1428 packet_put_char(0); /* bool: always display */
1429 packet_put_cstring(buf);
1430 packet_put_cstring("");
1432 packet_start(SSH_MSG_DEBUG);
1433 packet_put_cstring(buf);
1436 packet_write_wait();
1440 * Logs the error plus constructs and sends a disconnect packet, closes the
1441 * connection, and exits. This function never returns. The error message
1442 * should not contain a newline. The length of the formatted message must
1443 * not exceed 1024 bytes.
1447 packet_disconnect(const char *fmt,...)
1451 static int disconnecting = 0;
1453 if (disconnecting) /* Guard against recursive invocations. */
1454 fatal("packet_disconnect called recursively.");
1458 * Format the message. Note that the caller must make sure the
1459 * message is of limited size.
1461 va_start(args, fmt);
1462 vsnprintf(buf, sizeof(buf), fmt, args);
1465 /* Display the error locally */
1466 logit("Disconnecting: %.100s", buf);
1468 /* Send the disconnect message to the other side, and wait for it to get sent. */
1470 packet_start(SSH2_MSG_DISCONNECT);
1471 packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1472 packet_put_cstring(buf);
1473 packet_put_cstring("");
1475 packet_start(SSH_MSG_DISCONNECT);
1476 packet_put_cstring(buf);
1479 packet_write_wait();
1481 /* Stop listening for connections. */
1482 channel_close_all();
1484 /* Close the connection. */
1489 /* Checks if there is any buffered output, and tries to write some of the output. */
1492 packet_write_poll(void)
1495 len = buffer_len(&output);
1498 len = write(connection_out, buffer_ptr(&output), len);
1500 if (errno == EINTR || errno == EAGAIN ||
1501 errno == EWOULDBLOCK)
1503 fatal("Write failed: %.100s", strerror(errno));
1506 fatal("Write connection closed");
1507 buffer_consume(&output, len);
1514 * Calls packet_write_poll repeatedly until all pending output data has been
1519 packet_write_wait(void)
1522 u_int bytes_sent = 0;
1524 struct timeval start, timeout, *timeoutp = NULL;
1526 setp = (fd_set *)xcalloc(howmany(connection_out + 1, NFDBITS),
1528 bytes_sent += packet_write_poll();
1529 while (packet_have_data_to_write()) {
1530 memset(setp, 0, howmany(connection_out + 1, NFDBITS) *
1532 FD_SET(connection_out, setp);
1534 if (packet_timeout_ms > 0) {
1535 ms_remain = packet_timeout_ms;
1536 timeoutp = &timeout;
1539 if (packet_timeout_ms != -1) {
1540 ms_to_timeval(&timeout, ms_remain);
1541 gettimeofday(&start, NULL);
1543 if ((ret = select(connection_out + 1, NULL, setp,
1544 NULL, timeoutp)) >= 0)
1546 if (errno != EAGAIN && errno != EINTR &&
1547 errno != EWOULDBLOCK)
1549 if (packet_timeout_ms == -1)
1551 ms_subtract_diff(&start, &ms_remain);
1552 if (ms_remain <= 0) {
1558 logit("Connection to %.200s timed out while "
1559 "waiting to write", get_remote_ipaddr());
1562 bytes_sent += packet_write_poll();
1565 return (bytes_sent);
1568 /* Returns true if there is buffered data to write to the connection. */
1571 packet_have_data_to_write(void)
1573 return buffer_len(&output) != 0;
1576 /* Returns true if there is not too much data to write to the connection. */
1579 packet_not_very_much_data_to_write(void)
1581 if (interactive_mode)
1582 return buffer_len(&output) < 16384;
1584 return buffer_len(&output) < 128 * 1024;
1589 packet_set_tos(int interactive)
1591 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1592 int tos = interactive ? IPTOS_LOWDELAY : IPTOS_THROUGHPUT;
1594 if (!packet_connection_is_on_socket() ||
1595 !packet_connection_is_ipv4())
1597 if (setsockopt(connection_in, IPPROTO_IP, IP_TOS, &tos,
1599 error("setsockopt IP_TOS %d: %.100s:",
1600 tos, strerror(errno));
1604 /* Informs that the current session is interactive. Sets IP flags for that. */
1607 packet_set_interactive(int interactive)
1609 static int called = 0;
1615 /* Record that we are in interactive mode. */
1616 interactive_mode = interactive;
1618 /* Only set socket options if using a socket. */
1619 if (!packet_connection_is_on_socket())
1621 set_nodelay(connection_in);
1622 packet_set_tos(interactive);
1625 /* Returns true if the current connection is interactive. */
1628 packet_is_interactive(void)
1630 return interactive_mode;
1634 packet_set_maxsize(u_int s)
1636 static int called = 0;
1639 logit("packet_set_maxsize: called twice: old %d new %d",
1640 max_packet_size, s);
1643 if (s < 4 * 1024 || s > 1024 * 1024) {
1644 logit("packet_set_maxsize: bad size %d", s);
1648 debug("packet_set_maxsize: setting to %d", s);
1649 max_packet_size = s;
1653 /* roundup current message to pad bytes */
1655 packet_add_padding(u_char pad)
1661 * 9.2. Ignored Data Message
1663 * byte SSH_MSG_IGNORE
1666 * All implementations MUST understand (and ignore) this message at any
1667 * time (after receiving the protocol version). No implementation is
1668 * required to send them. This message can be used as an additional
1669 * protection measure against advanced traffic analysis techniques.
1672 packet_send_ignore(int nbytes)
1677 packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1678 packet_put_int(nbytes);
1679 for (i = 0; i < nbytes; i++) {
1682 packet_put_char((u_char)rnd & 0xff);
1687 int rekey_requested = 0;
1689 packet_request_rekeying(void)
1691 rekey_requested = 1;
1694 #define MAX_PACKETS (1U<<31)
1696 packet_need_rekeying(void)
1698 if (datafellows & SSH_BUG_NOREKEY)
1700 if (rekey_requested == 1)
1702 rekey_requested = 0;
1706 (p_send.packets > MAX_PACKETS) ||
1707 (p_read.packets > MAX_PACKETS) ||
1708 (max_blocks_out && (p_send.blocks > max_blocks_out)) ||
1709 (max_blocks_in && (p_read.blocks > max_blocks_in));
1713 packet_set_rekey_limit(u_int32_t bytes)
1715 rekey_limit = bytes;
1719 packet_set_server(void)
1725 packet_set_authenticated(void)
1727 after_authentication = 1;
1731 packet_authentication_state(void)
1733 return(after_authentication);