1 /* $OpenBSD: packet.c,v 1.136 2006/07/17 01:31:09 stevesk 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/socket.h>
46 #include <netinet/in_systm.h>
47 #include <netinet/in.h>
48 #include <netinet/ip.h>
83 * This variable contains the file descriptors used for communicating with
84 * the other side. connection_in is used for reading; connection_out for
85 * writing. These can be the same descriptor, in which case it is assumed to
88 static int connection_in = -1;
89 static int connection_out = -1;
91 /* Protocol flags for the remote side. */
92 static u_int remote_protocol_flags = 0;
94 /* Encryption context for receiving data. This is only used for decryption. */
95 static CipherContext receive_context;
97 /* Encryption context for sending data. This is only used for encryption. */
98 static CipherContext send_context;
100 /* Buffer for raw input data from the socket. */
103 /* Buffer for raw output data going to the socket. */
106 /* Buffer for the partial outgoing packet being constructed. */
107 static Buffer outgoing_packet;
109 /* Buffer for the incoming packet currently being processed. */
110 static Buffer incoming_packet;
112 /* Scratch buffer for packet compression/decompression. */
113 static Buffer compression_buffer;
114 static int compression_buffer_ready = 0;
116 /* Flag indicating whether packet compression/decompression is enabled. */
117 static int packet_compression = 0;
119 /* default maximum packet size */
120 u_int max_packet_size = 32768;
122 /* Flag indicating whether this module has been initialized. */
123 static int initialized = 0;
125 /* Set to true if the connection is interactive. */
126 static int interactive_mode = 0;
128 /* Set to true if we are the server side. */
129 static int server_side = 0;
131 /* Set to true if we are authenticated. */
132 static int after_authentication = 0;
134 /* Session key information for Encryption and MAC */
135 Newkeys *newkeys[MODE_MAX];
136 static struct packet_state {
142 static u_int64_t max_blocks_in, max_blocks_out;
143 static u_int32_t rekey_limit;
145 /* Session key for protocol v1 */
146 static u_char ssh1_key[SSH_SESSION_KEY_LENGTH];
147 static u_int ssh1_keylen;
149 /* roundup current message to extra_pad bytes */
150 static u_char extra_pad = 0;
153 TAILQ_ENTRY(packet) next;
157 TAILQ_HEAD(, packet) outgoing;
160 * Sets the descriptors used for communication. Disables encryption until
161 * packet_set_encryption_key is called.
164 packet_set_connection(int fd_in, int fd_out)
166 Cipher *none = cipher_by_name("none");
169 fatal("packet_set_connection: cannot load cipher 'none'");
170 connection_in = fd_in;
171 connection_out = fd_out;
172 cipher_init(&send_context, none, (const u_char *)"",
173 0, NULL, 0, CIPHER_ENCRYPT);
174 cipher_init(&receive_context, none, (const u_char *)"",
175 0, NULL, 0, CIPHER_DECRYPT);
176 newkeys[MODE_IN] = newkeys[MODE_OUT] = NULL;
180 buffer_init(&output);
181 buffer_init(&outgoing_packet);
182 buffer_init(&incoming_packet);
183 TAILQ_INIT(&outgoing);
187 /* Returns 1 if remote host is connected via socket, 0 if not. */
190 packet_connection_is_on_socket(void)
192 struct sockaddr_storage from, to;
193 socklen_t fromlen, tolen;
195 /* filedescriptors in and out are the same, so it's a socket */
196 if (connection_in == connection_out)
198 fromlen = sizeof(from);
199 memset(&from, 0, sizeof(from));
200 if (getpeername(connection_in, (struct sockaddr *)&from, &fromlen) < 0)
203 memset(&to, 0, sizeof(to));
204 if (getpeername(connection_out, (struct sockaddr *)&to, &tolen) < 0)
206 if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
208 if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
214 * Exports an IV from the CipherContext required to export the key
215 * state back from the unprivileged child to the privileged parent
220 packet_get_keyiv(int mode, u_char *iv, u_int len)
224 if (mode == MODE_OUT)
227 cc = &receive_context;
229 cipher_get_keyiv(cc, iv, len);
233 packet_get_keycontext(int mode, u_char *dat)
237 if (mode == MODE_OUT)
240 cc = &receive_context;
242 return (cipher_get_keycontext(cc, dat));
246 packet_set_keycontext(int mode, u_char *dat)
250 if (mode == MODE_OUT)
253 cc = &receive_context;
255 cipher_set_keycontext(cc, dat);
259 packet_get_keyiv_len(int mode)
263 if (mode == MODE_OUT)
266 cc = &receive_context;
268 return (cipher_get_keyiv_len(cc));
272 packet_set_iv(int mode, u_char *dat)
276 if (mode == MODE_OUT)
279 cc = &receive_context;
281 cipher_set_keyiv(cc, dat);
285 packet_get_ssh1_cipher(void)
287 return (cipher_get_number(receive_context.cipher));
291 packet_get_state(int mode, u_int32_t *seqnr, u_int64_t *blocks, u_int32_t *packets)
293 struct packet_state *state;
295 state = (mode == MODE_IN) ? &p_read : &p_send;
296 *seqnr = state->seqnr;
297 *blocks = state->blocks;
298 *packets = state->packets;
302 packet_set_state(int mode, u_int32_t seqnr, u_int64_t blocks, u_int32_t packets)
304 struct packet_state *state;
306 state = (mode == MODE_IN) ? &p_read : &p_send;
307 state->seqnr = seqnr;
308 state->blocks = blocks;
309 state->packets = packets;
312 /* returns 1 if connection is via ipv4 */
315 packet_connection_is_ipv4(void)
317 struct sockaddr_storage to;
318 socklen_t tolen = sizeof(to);
320 memset(&to, 0, sizeof(to));
321 if (getsockname(connection_out, (struct sockaddr *)&to, &tolen) < 0)
323 if (to.ss_family == AF_INET)
326 if (to.ss_family == AF_INET6 &&
327 IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&to)->sin6_addr))
333 /* Sets the connection into non-blocking mode. */
336 packet_set_nonblocking(void)
338 /* Set the socket into non-blocking mode. */
339 set_nonblock(connection_in);
341 if (connection_out != connection_in)
342 set_nonblock(connection_out);
345 /* Returns the socket used for reading. */
348 packet_get_connection_in(void)
350 return connection_in;
353 /* Returns the descriptor used for writing. */
356 packet_get_connection_out(void)
358 return connection_out;
361 /* Closes the connection and clears and frees internal data structures. */
369 if (connection_in == connection_out) {
370 shutdown(connection_out, SHUT_RDWR);
371 close(connection_out);
373 close(connection_in);
374 close(connection_out);
377 buffer_free(&output);
378 buffer_free(&outgoing_packet);
379 buffer_free(&incoming_packet);
380 if (compression_buffer_ready) {
381 buffer_free(&compression_buffer);
382 buffer_compress_uninit();
384 cipher_cleanup(&send_context);
385 cipher_cleanup(&receive_context);
388 /* Sets remote side protocol flags. */
391 packet_set_protocol_flags(u_int protocol_flags)
393 remote_protocol_flags = protocol_flags;
396 /* Returns the remote protocol flags set earlier by the above function. */
399 packet_get_protocol_flags(void)
401 return remote_protocol_flags;
405 * Starts packet compression from the next packet on in both directions.
406 * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
410 packet_init_compression(void)
412 if (compression_buffer_ready == 1)
414 compression_buffer_ready = 1;
415 buffer_init(&compression_buffer);
419 packet_start_compression(int level)
421 if (packet_compression && !compat20)
422 fatal("Compression already enabled.");
423 packet_compression = 1;
424 packet_init_compression();
425 buffer_compress_init_send(level);
426 buffer_compress_init_recv();
430 * Causes any further packets to be encrypted using the given key. The same
431 * key is used for both sending and reception. However, both directions are
432 * encrypted independently of each other.
436 packet_set_encryption_key(const u_char *key, u_int keylen,
439 Cipher *cipher = cipher_by_number(number);
442 fatal("packet_set_encryption_key: unknown cipher number %d", number);
444 fatal("packet_set_encryption_key: keylen too small: %d", keylen);
445 if (keylen > SSH_SESSION_KEY_LENGTH)
446 fatal("packet_set_encryption_key: keylen too big: %d", keylen);
447 memcpy(ssh1_key, key, keylen);
448 ssh1_keylen = keylen;
449 cipher_init(&send_context, cipher, key, keylen, NULL, 0, CIPHER_ENCRYPT);
450 cipher_init(&receive_context, cipher, key, keylen, NULL, 0, CIPHER_DECRYPT);
454 packet_get_encryption_key(u_char *key)
457 return (ssh1_keylen);
458 memcpy(key, ssh1_key, ssh1_keylen);
459 return (ssh1_keylen);
462 /* Start constructing a packet to send. */
464 packet_start(u_char type)
469 DBG(debug("packet_start[%d]", type));
470 len = compat20 ? 6 : 9;
471 memset(buf, 0, len - 1);
473 buffer_clear(&outgoing_packet);
474 buffer_append(&outgoing_packet, buf, len);
477 /* Append payload. */
479 packet_put_char(int value)
483 buffer_append(&outgoing_packet, &ch, 1);
487 packet_put_int(u_int value)
489 buffer_put_int(&outgoing_packet, value);
493 packet_put_string(const void *buf, u_int len)
495 buffer_put_string(&outgoing_packet, buf, len);
499 packet_put_cstring(const char *str)
501 buffer_put_cstring(&outgoing_packet, str);
505 packet_put_raw(const void *buf, u_int len)
507 buffer_append(&outgoing_packet, buf, len);
511 packet_put_bignum(BIGNUM * value)
513 buffer_put_bignum(&outgoing_packet, value);
517 packet_put_bignum2(BIGNUM * value)
519 buffer_put_bignum2(&outgoing_packet, value);
523 * Finalizes and sends the packet. If the encryption key has been set,
524 * encrypts the packet before sending.
536 * If using packet compression, compress the payload of the outgoing
539 if (packet_compression) {
540 buffer_clear(&compression_buffer);
542 buffer_consume(&outgoing_packet, 8);
544 buffer_append(&compression_buffer, "\0\0\0\0\0\0\0\0", 8);
545 buffer_compress(&outgoing_packet, &compression_buffer);
546 buffer_clear(&outgoing_packet);
547 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
548 buffer_len(&compression_buffer));
550 /* Compute packet length without padding (add checksum, remove padding). */
551 len = buffer_len(&outgoing_packet) + 4 - 8;
553 /* Insert padding. Initialized to zero in packet_start1() */
554 padding = 8 - len % 8;
555 if (!send_context.plaintext) {
556 cp = buffer_ptr(&outgoing_packet);
557 for (i = 0; i < padding; i++) {
560 cp[7 - i] = rnd & 0xff;
564 buffer_consume(&outgoing_packet, 8 - padding);
566 /* Add check bytes. */
567 checksum = ssh_crc32(buffer_ptr(&outgoing_packet),
568 buffer_len(&outgoing_packet));
569 put_u32(buf, checksum);
570 buffer_append(&outgoing_packet, buf, 4);
573 fprintf(stderr, "packet_send plain: ");
574 buffer_dump(&outgoing_packet);
577 /* Append to output. */
579 buffer_append(&output, buf, 4);
580 cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
581 cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
582 buffer_len(&outgoing_packet));
585 fprintf(stderr, "encrypted: ");
586 buffer_dump(&output);
589 buffer_clear(&outgoing_packet);
592 * Note that the packet is now only buffered in output. It won't be
593 * actually sent until packet_write_wait or packet_write_poll is
599 set_newkeys(int mode)
605 u_int64_t *max_blocks;
608 debug2("set_newkeys: mode %d", mode);
610 if (mode == MODE_OUT) {
612 crypt_type = CIPHER_ENCRYPT;
613 p_send.packets = p_send.blocks = 0;
614 max_blocks = &max_blocks_out;
616 cc = &receive_context;
617 crypt_type = CIPHER_DECRYPT;
618 p_read.packets = p_read.blocks = 0;
619 max_blocks = &max_blocks_in;
621 if (newkeys[mode] != NULL) {
622 debug("set_newkeys: rekeying");
624 enc = &newkeys[mode]->enc;
625 mac = &newkeys[mode]->mac;
626 comp = &newkeys[mode]->comp;
627 memset(mac->key, 0, mac->key_len);
634 xfree(newkeys[mode]);
636 newkeys[mode] = kex_get_newkeys(mode);
637 if (newkeys[mode] == NULL)
638 fatal("newkeys: no keys for mode %d", mode);
639 enc = &newkeys[mode]->enc;
640 mac = &newkeys[mode]->mac;
641 comp = &newkeys[mode]->comp;
644 DBG(debug("cipher_init_context: %d", mode));
645 cipher_init(cc, enc->cipher, enc->key, enc->key_len,
646 enc->iv, enc->block_size, crypt_type);
647 /* Deleting the keys does not gain extra security */
648 /* memset(enc->iv, 0, enc->block_size);
649 memset(enc->key, 0, enc->key_len); */
650 if ((comp->type == COMP_ZLIB ||
651 (comp->type == COMP_DELAYED && after_authentication)) &&
652 comp->enabled == 0) {
653 packet_init_compression();
654 if (mode == MODE_OUT)
655 buffer_compress_init_send(6);
657 buffer_compress_init_recv();
661 * The 2^(blocksize*2) limit is too expensive for 3DES,
662 * blowfish, etc, so enforce a 1GB limit for small blocksizes.
664 if (enc->block_size >= 16)
665 *max_blocks = (u_int64_t)1 << (enc->block_size*2);
667 *max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
669 *max_blocks = MIN(*max_blocks, rekey_limit / enc->block_size);
673 * Delayed compression for SSH2 is enabled after authentication:
674 * This happans on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
675 * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
678 packet_enable_delayed_compress(void)
684 * Remember that we are past the authentication step, so rekeying
685 * with COMP_DELAYED will turn on compression immediately.
687 after_authentication = 1;
688 for (mode = 0; mode < MODE_MAX; mode++) {
689 comp = &newkeys[mode]->comp;
690 if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
691 packet_init_compression();
692 if (mode == MODE_OUT)
693 buffer_compress_init_send(6);
695 buffer_compress_init_recv();
702 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
705 packet_send2_wrapped(void)
707 u_char type, *cp, *macbuf = NULL;
709 u_int packet_length = 0;
717 if (newkeys[MODE_OUT] != NULL) {
718 enc = &newkeys[MODE_OUT]->enc;
719 mac = &newkeys[MODE_OUT]->mac;
720 comp = &newkeys[MODE_OUT]->comp;
722 block_size = enc ? enc->block_size : 8;
724 cp = buffer_ptr(&outgoing_packet);
728 fprintf(stderr, "plain: ");
729 buffer_dump(&outgoing_packet);
732 if (comp && comp->enabled) {
733 len = buffer_len(&outgoing_packet);
734 /* skip header, compress only payload */
735 buffer_consume(&outgoing_packet, 5);
736 buffer_clear(&compression_buffer);
737 buffer_compress(&outgoing_packet, &compression_buffer);
738 buffer_clear(&outgoing_packet);
739 buffer_append(&outgoing_packet, "\0\0\0\0\0", 5);
740 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
741 buffer_len(&compression_buffer));
742 DBG(debug("compression: raw %d compressed %d", len,
743 buffer_len(&outgoing_packet)));
746 /* sizeof (packet_len + pad_len + payload) */
747 len = buffer_len(&outgoing_packet);
750 * calc size of padding, alloc space, get random data,
751 * minimum padding is 4 bytes
753 padlen = block_size - (len % block_size);
755 padlen += block_size;
757 /* will wrap if extra_pad+padlen > 255 */
758 extra_pad = roundup(extra_pad, block_size);
759 pad = extra_pad - ((len + padlen) % extra_pad);
760 debug3("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
761 pad, len, padlen, extra_pad);
765 cp = buffer_append_space(&outgoing_packet, padlen);
766 if (enc && !send_context.plaintext) {
768 for (i = 0; i < padlen; i++) {
776 memset(cp, 0, padlen);
778 /* packet_length includes payload, padding and padding length field */
779 packet_length = buffer_len(&outgoing_packet) - 4;
780 cp = buffer_ptr(&outgoing_packet);
781 put_u32(cp, packet_length);
783 DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen));
785 /* compute MAC over seqnr and packet(length fields, payload, padding) */
786 if (mac && mac->enabled) {
787 macbuf = mac_compute(mac, p_send.seqnr,
788 buffer_ptr(&outgoing_packet),
789 buffer_len(&outgoing_packet));
790 DBG(debug("done calc MAC out #%d", p_send.seqnr));
792 /* encrypt packet and append to output buffer. */
793 cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
794 cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
795 buffer_len(&outgoing_packet));
796 /* append unencrypted MAC */
797 if (mac && mac->enabled)
798 buffer_append(&output, macbuf, mac->mac_len);
800 fprintf(stderr, "encrypted: ");
801 buffer_dump(&output);
803 /* increment sequence number for outgoing packets */
804 if (++p_send.seqnr == 0)
805 logit("outgoing seqnr wraps around");
806 if (++p_send.packets == 0)
807 if (!(datafellows & SSH_BUG_NOREKEY))
808 fatal("XXX too many packets with same key");
809 p_send.blocks += (packet_length + 4) / block_size;
810 buffer_clear(&outgoing_packet);
812 if (type == SSH2_MSG_NEWKEYS)
813 set_newkeys(MODE_OUT);
814 else if (type == SSH2_MSG_USERAUTH_SUCCESS && server_side)
815 packet_enable_delayed_compress();
821 static int rekeying = 0;
825 cp = buffer_ptr(&outgoing_packet);
828 /* during rekeying we can only send key exchange messages */
830 if (!((type >= SSH2_MSG_TRANSPORT_MIN) &&
831 (type <= SSH2_MSG_TRANSPORT_MAX))) {
832 debug("enqueue packet: %u", type);
833 p = xmalloc(sizeof(*p));
835 memcpy(&p->payload, &outgoing_packet, sizeof(Buffer));
836 buffer_init(&outgoing_packet);
837 TAILQ_INSERT_TAIL(&outgoing, p, next);
842 /* rekeying starts with sending KEXINIT */
843 if (type == SSH2_MSG_KEXINIT)
846 packet_send2_wrapped();
848 /* after a NEWKEYS message we can send the complete queue */
849 if (type == SSH2_MSG_NEWKEYS) {
851 while ((p = TAILQ_FIRST(&outgoing))) {
853 debug("dequeue packet: %u", type);
854 buffer_free(&outgoing_packet);
855 memcpy(&outgoing_packet, &p->payload,
857 TAILQ_REMOVE(&outgoing, p, next);
859 packet_send2_wrapped();
871 DBG(debug("packet_send done"));
875 * Waits until a packet has been received, and returns its type. Note that
876 * no other data is processed until this returns, so this function should not
877 * be used during the interactive session.
881 packet_read_seqnr(u_int32_t *seqnr_p)
886 DBG(debug("packet_read()"));
888 setp = (fd_set *)xcalloc(howmany(connection_in+1, NFDBITS),
891 /* Since we are blocking, ensure that all written packets have been sent. */
894 /* Stay in the loop until we have received a complete packet. */
896 /* Try to read a packet from the buffer. */
897 type = packet_read_poll_seqnr(seqnr_p);
899 type == SSH_SMSG_SUCCESS
900 || type == SSH_SMSG_FAILURE
901 || type == SSH_CMSG_EOF
902 || type == SSH_CMSG_EXIT_CONFIRMATION))
904 /* If we got a packet, return it. */
905 if (type != SSH_MSG_NONE) {
910 * Otherwise, wait for some data to arrive, add it to the
911 * buffer, and try again.
913 memset(setp, 0, howmany(connection_in + 1, NFDBITS) *
915 FD_SET(connection_in, setp);
917 /* Wait for some data to arrive. */
918 while (select(connection_in + 1, setp, NULL, NULL, NULL) == -1 &&
919 (errno == EAGAIN || errno == EINTR))
922 /* Read data from the socket. */
923 len = read(connection_in, buf, sizeof(buf));
925 logit("Connection closed by %.200s", get_remote_ipaddr());
929 fatal("Read from socket failed: %.100s", strerror(errno));
930 /* Append it to the buffer. */
931 packet_process_incoming(buf, len);
939 return packet_read_seqnr(NULL);
943 * Waits until a packet has been received, verifies that its type matches
944 * that given, and gives a fatal error and exits if there is a mismatch.
948 packet_read_expect(int expected_type)
952 type = packet_read();
953 if (type != expected_type)
954 packet_disconnect("Protocol error: expected packet type %d, got %d",
955 expected_type, type);
958 /* Checks if a full packet is available in the data received so far via
959 * packet_process_incoming. If so, reads the packet; otherwise returns
960 * SSH_MSG_NONE. This does not wait for data from the connection.
962 * SSH_MSG_DISCONNECT is handled specially here. Also,
963 * SSH_MSG_IGNORE messages are skipped by this function and are never returned
968 packet_read_poll1(void)
970 u_int len, padded_len;
972 u_int checksum, stored_checksum;
974 /* Check if input size is less than minimum packet size. */
975 if (buffer_len(&input) < 4 + 8)
977 /* Get length of incoming packet. */
978 cp = buffer_ptr(&input);
980 if (len < 1 + 2 + 2 || len > 256 * 1024)
981 packet_disconnect("Bad packet length %u.", len);
982 padded_len = (len + 8) & ~7;
984 /* Check if the packet has been entirely received. */
985 if (buffer_len(&input) < 4 + padded_len)
988 /* The entire packet is in buffer. */
990 /* Consume packet length. */
991 buffer_consume(&input, 4);
994 * Cryptographic attack detector for ssh
995 * (C)1998 CORE-SDI, Buenos Aires Argentina
996 * Ariel Futoransky(futo@core-sdi.com)
998 if (!receive_context.plaintext &&
999 detect_attack(buffer_ptr(&input), padded_len) == DEATTACK_DETECTED)
1000 packet_disconnect("crc32 compensation attack: network attack detected");
1002 /* Decrypt data to incoming_packet. */
1003 buffer_clear(&incoming_packet);
1004 cp = buffer_append_space(&incoming_packet, padded_len);
1005 cipher_crypt(&receive_context, cp, buffer_ptr(&input), padded_len);
1007 buffer_consume(&input, padded_len);
1010 fprintf(stderr, "read_poll plain: ");
1011 buffer_dump(&incoming_packet);
1014 /* Compute packet checksum. */
1015 checksum = ssh_crc32(buffer_ptr(&incoming_packet),
1016 buffer_len(&incoming_packet) - 4);
1019 buffer_consume(&incoming_packet, 8 - len % 8);
1021 /* Test check bytes. */
1022 if (len != buffer_len(&incoming_packet))
1023 packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
1024 len, buffer_len(&incoming_packet));
1026 cp = (u_char *)buffer_ptr(&incoming_packet) + len - 4;
1027 stored_checksum = get_u32(cp);
1028 if (checksum != stored_checksum)
1029 packet_disconnect("Corrupted check bytes on input.");
1030 buffer_consume_end(&incoming_packet, 4);
1032 if (packet_compression) {
1033 buffer_clear(&compression_buffer);
1034 buffer_uncompress(&incoming_packet, &compression_buffer);
1035 buffer_clear(&incoming_packet);
1036 buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
1037 buffer_len(&compression_buffer));
1039 type = buffer_get_char(&incoming_packet);
1040 if (type < SSH_MSG_MIN || type > SSH_MSG_MAX)
1041 packet_disconnect("Invalid ssh1 packet type: %d", type);
1046 packet_read_poll2(u_int32_t *seqnr_p)
1048 static u_int packet_length = 0;
1050 u_char *macbuf, *cp, type;
1051 u_int maclen, block_size;
1056 if (newkeys[MODE_IN] != NULL) {
1057 enc = &newkeys[MODE_IN]->enc;
1058 mac = &newkeys[MODE_IN]->mac;
1059 comp = &newkeys[MODE_IN]->comp;
1061 maclen = mac && mac->enabled ? mac->mac_len : 0;
1062 block_size = enc ? enc->block_size : 8;
1064 if (packet_length == 0) {
1066 * check if input size is less than the cipher block size,
1067 * decrypt first block and extract length of incoming packet
1069 if (buffer_len(&input) < block_size)
1070 return SSH_MSG_NONE;
1071 buffer_clear(&incoming_packet);
1072 cp = buffer_append_space(&incoming_packet, block_size);
1073 cipher_crypt(&receive_context, cp, buffer_ptr(&input),
1075 cp = buffer_ptr(&incoming_packet);
1076 packet_length = get_u32(cp);
1077 if (packet_length < 1 + 4 || packet_length > 256 * 1024) {
1079 buffer_dump(&incoming_packet);
1081 packet_disconnect("Bad packet length %u.", packet_length);
1083 DBG(debug("input: packet len %u", packet_length+4));
1084 buffer_consume(&input, block_size);
1086 /* we have a partial packet of block_size bytes */
1087 need = 4 + packet_length - block_size;
1088 DBG(debug("partial packet %d, need %d, maclen %d", block_size,
1090 if (need % block_size != 0)
1091 fatal("padding error: need %d block %d mod %d",
1092 need, block_size, need % block_size);
1094 * check if the entire packet has been received and
1095 * decrypt into incoming_packet
1097 if (buffer_len(&input) < need + maclen)
1098 return SSH_MSG_NONE;
1100 fprintf(stderr, "read_poll enc/full: ");
1101 buffer_dump(&input);
1103 cp = buffer_append_space(&incoming_packet, need);
1104 cipher_crypt(&receive_context, cp, buffer_ptr(&input), need);
1105 buffer_consume(&input, need);
1107 * compute MAC over seqnr and packet,
1108 * increment sequence number for incoming packet
1110 if (mac && mac->enabled) {
1111 macbuf = mac_compute(mac, p_read.seqnr,
1112 buffer_ptr(&incoming_packet),
1113 buffer_len(&incoming_packet));
1114 if (memcmp(macbuf, buffer_ptr(&input), mac->mac_len) != 0)
1115 packet_disconnect("Corrupted MAC on input.");
1116 DBG(debug("MAC #%d ok", p_read.seqnr));
1117 buffer_consume(&input, mac->mac_len);
1119 if (seqnr_p != NULL)
1120 *seqnr_p = p_read.seqnr;
1121 if (++p_read.seqnr == 0)
1122 logit("incoming seqnr wraps around");
1123 if (++p_read.packets == 0)
1124 if (!(datafellows & SSH_BUG_NOREKEY))
1125 fatal("XXX too many packets with same key");
1126 p_read.blocks += (packet_length + 4) / block_size;
1129 cp = buffer_ptr(&incoming_packet);
1131 DBG(debug("input: padlen %d", padlen));
1133 packet_disconnect("Corrupted padlen %d on input.", padlen);
1135 /* skip packet size + padlen, discard padding */
1136 buffer_consume(&incoming_packet, 4 + 1);
1137 buffer_consume_end(&incoming_packet, padlen);
1139 DBG(debug("input: len before de-compress %d", buffer_len(&incoming_packet)));
1140 if (comp && comp->enabled) {
1141 buffer_clear(&compression_buffer);
1142 buffer_uncompress(&incoming_packet, &compression_buffer);
1143 buffer_clear(&incoming_packet);
1144 buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
1145 buffer_len(&compression_buffer));
1146 DBG(debug("input: len after de-compress %d",
1147 buffer_len(&incoming_packet)));
1150 * get packet type, implies consume.
1151 * return length of payload (without type field)
1153 type = buffer_get_char(&incoming_packet);
1154 if (type < SSH2_MSG_MIN || type >= SSH2_MSG_LOCAL_MIN)
1155 packet_disconnect("Invalid ssh2 packet type: %d", type);
1156 if (type == SSH2_MSG_NEWKEYS)
1157 set_newkeys(MODE_IN);
1158 else if (type == SSH2_MSG_USERAUTH_SUCCESS && !server_side)
1159 packet_enable_delayed_compress();
1161 fprintf(stderr, "read/plain[%d]:\r\n", type);
1162 buffer_dump(&incoming_packet);
1164 /* reset for next packet */
1170 packet_read_poll_seqnr(u_int32_t *seqnr_p)
1172 u_int reason, seqnr;
1178 type = packet_read_poll2(seqnr_p);
1180 DBG(debug("received packet type %d", type));
1182 case SSH2_MSG_IGNORE:
1184 case SSH2_MSG_DEBUG:
1186 msg = packet_get_string(NULL);
1187 debug("Remote: %.900s", msg);
1189 msg = packet_get_string(NULL);
1192 case SSH2_MSG_DISCONNECT:
1193 reason = packet_get_int();
1194 msg = packet_get_string(NULL);
1195 logit("Received disconnect from %s: %u: %.400s",
1196 get_remote_ipaddr(), reason, msg);
1200 case SSH2_MSG_UNIMPLEMENTED:
1201 seqnr = packet_get_int();
1202 debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1209 type = packet_read_poll1();
1211 case SSH_MSG_IGNORE:
1214 msg = packet_get_string(NULL);
1215 debug("Remote: %.900s", msg);
1218 case SSH_MSG_DISCONNECT:
1219 msg = packet_get_string(NULL);
1220 logit("Received disconnect from %s: %.400s",
1221 get_remote_ipaddr(), msg);
1227 DBG(debug("received packet type %d", type));
1235 packet_read_poll(void)
1237 return packet_read_poll_seqnr(NULL);
1241 * Buffers the given amount of input characters. This is intended to be used
1242 * together with packet_read_poll.
1246 packet_process_incoming(const char *buf, u_int len)
1248 buffer_append(&input, buf, len);
1251 /* Returns a character from the packet. */
1254 packet_get_char(void)
1258 buffer_get(&incoming_packet, &ch, 1);
1262 /* Returns an integer from the packet data. */
1265 packet_get_int(void)
1267 return buffer_get_int(&incoming_packet);
1271 * Returns an arbitrary precision integer from the packet data. The integer
1272 * must have been initialized before this call.
1276 packet_get_bignum(BIGNUM * value)
1278 buffer_get_bignum(&incoming_packet, value);
1282 packet_get_bignum2(BIGNUM * value)
1284 buffer_get_bignum2(&incoming_packet, value);
1288 packet_get_raw(u_int *length_ptr)
1290 u_int bytes = buffer_len(&incoming_packet);
1292 if (length_ptr != NULL)
1293 *length_ptr = bytes;
1294 return buffer_ptr(&incoming_packet);
1298 packet_remaining(void)
1300 return buffer_len(&incoming_packet);
1304 * Returns a string from the packet data. The string is allocated using
1305 * xmalloc; it is the responsibility of the calling program to free it when
1306 * no longer needed. The length_ptr argument may be NULL, or point to an
1307 * integer into which the length of the string is stored.
1311 packet_get_string(u_int *length_ptr)
1313 return buffer_get_string(&incoming_packet, length_ptr);
1317 * Sends a diagnostic message from the server to the client. This message
1318 * can be sent at any time (but not while constructing another message). The
1319 * message is printed immediately, but only if the client is being executed
1320 * in verbose mode. These messages are primarily intended to ease debugging
1321 * authentication problems. The length of the formatted message must not
1322 * exceed 1024 bytes. This will automatically call packet_write_wait.
1326 packet_send_debug(const char *fmt,...)
1331 if (compat20 && (datafellows & SSH_BUG_DEBUG))
1334 va_start(args, fmt);
1335 vsnprintf(buf, sizeof(buf), fmt, args);
1339 packet_start(SSH2_MSG_DEBUG);
1340 packet_put_char(0); /* bool: always display */
1341 packet_put_cstring(buf);
1342 packet_put_cstring("");
1344 packet_start(SSH_MSG_DEBUG);
1345 packet_put_cstring(buf);
1348 packet_write_wait();
1352 * Logs the error plus constructs and sends a disconnect packet, closes the
1353 * connection, and exits. This function never returns. The error message
1354 * should not contain a newline. The length of the formatted message must
1355 * not exceed 1024 bytes.
1359 packet_disconnect(const char *fmt,...)
1363 static int disconnecting = 0;
1365 if (disconnecting) /* Guard against recursive invocations. */
1366 fatal("packet_disconnect called recursively.");
1370 * Format the message. Note that the caller must make sure the
1371 * message is of limited size.
1373 va_start(args, fmt);
1374 vsnprintf(buf, sizeof(buf), fmt, args);
1377 /* Display the error locally */
1378 logit("Disconnecting: %.100s", buf);
1380 /* Send the disconnect message to the other side, and wait for it to get sent. */
1382 packet_start(SSH2_MSG_DISCONNECT);
1383 packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1384 packet_put_cstring(buf);
1385 packet_put_cstring("");
1387 packet_start(SSH_MSG_DISCONNECT);
1388 packet_put_cstring(buf);
1391 packet_write_wait();
1393 /* Stop listening for connections. */
1394 channel_close_all();
1396 /* Close the connection. */
1401 /* Checks if there is any buffered output, and tries to write some of the output. */
1404 packet_write_poll(void)
1406 int len = buffer_len(&output);
1409 len = write(connection_out, buffer_ptr(&output), len);
1411 if (errno == EAGAIN)
1414 fatal("Write failed: %.100s", strerror(errno));
1416 buffer_consume(&output, len);
1421 * Calls packet_write_poll repeatedly until all pending output data has been
1426 packet_write_wait(void)
1430 setp = (fd_set *)xcalloc(howmany(connection_out + 1, NFDBITS),
1432 packet_write_poll();
1433 while (packet_have_data_to_write()) {
1434 memset(setp, 0, howmany(connection_out + 1, NFDBITS) *
1436 FD_SET(connection_out, setp);
1437 while (select(connection_out + 1, NULL, setp, NULL, NULL) == -1 &&
1438 (errno == EAGAIN || errno == EINTR))
1440 packet_write_poll();
1445 /* Returns true if there is buffered data to write to the connection. */
1448 packet_have_data_to_write(void)
1450 return buffer_len(&output) != 0;
1453 /* Returns true if there is not too much data to write to the connection. */
1456 packet_not_very_much_data_to_write(void)
1458 if (interactive_mode)
1459 return buffer_len(&output) < 16384;
1461 return buffer_len(&output) < 128 * 1024;
1466 packet_set_tos(int interactive)
1468 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1469 int tos = interactive ? IPTOS_LOWDELAY : IPTOS_THROUGHPUT;
1471 if (!packet_connection_is_on_socket() ||
1472 !packet_connection_is_ipv4())
1474 if (setsockopt(connection_in, IPPROTO_IP, IP_TOS, &tos,
1476 error("setsockopt IP_TOS %d: %.100s:",
1477 tos, strerror(errno));
1481 /* Informs that the current session is interactive. Sets IP flags for that. */
1484 packet_set_interactive(int interactive)
1486 static int called = 0;
1492 /* Record that we are in interactive mode. */
1493 interactive_mode = interactive;
1495 /* Only set socket options if using a socket. */
1496 if (!packet_connection_is_on_socket())
1498 set_nodelay(connection_in);
1499 packet_set_tos(interactive);
1502 /* Returns true if the current connection is interactive. */
1505 packet_is_interactive(void)
1507 return interactive_mode;
1511 packet_set_maxsize(u_int s)
1513 static int called = 0;
1516 logit("packet_set_maxsize: called twice: old %d new %d",
1517 max_packet_size, s);
1520 if (s < 4 * 1024 || s > 1024 * 1024) {
1521 logit("packet_set_maxsize: bad size %d", s);
1525 debug("packet_set_maxsize: setting to %d", s);
1526 max_packet_size = s;
1530 /* roundup current message to pad bytes */
1532 packet_add_padding(u_char pad)
1538 * 9.2. Ignored Data Message
1540 * byte SSH_MSG_IGNORE
1543 * All implementations MUST understand (and ignore) this message at any
1544 * time (after receiving the protocol version). No implementation is
1545 * required to send them. This message can be used as an additional
1546 * protection measure against advanced traffic analysis techniques.
1549 packet_send_ignore(int nbytes)
1554 packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1555 packet_put_int(nbytes);
1556 for (i = 0; i < nbytes; i++) {
1559 packet_put_char((u_char)rnd & 0xff);
1564 #define MAX_PACKETS (1U<<31)
1566 packet_need_rekeying(void)
1568 if (datafellows & SSH_BUG_NOREKEY)
1571 (p_send.packets > MAX_PACKETS) ||
1572 (p_read.packets > MAX_PACKETS) ||
1573 (max_blocks_out && (p_send.blocks > max_blocks_out)) ||
1574 (max_blocks_in && (p_read.blocks > max_blocks_in));
1578 packet_set_rekey_limit(u_int32_t bytes)
1580 rekey_limit = bytes;
1584 packet_set_server(void)
1590 packet_set_authenticated(void)
1592 after_authentication = 1;