1 /* $OpenBSD: packet.c,v 1.145 2006/09/19 21:14:08 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_systm.h>
51 #include <netinet/in.h>
52 #include <netinet/ip.h>
53 #include <arpa/inet.h>
89 * This variable contains the file descriptors used for communicating with
90 * the other side. connection_in is used for reading; connection_out for
91 * writing. These can be the same descriptor, in which case it is assumed to
94 static int connection_in = -1;
95 static int connection_out = -1;
97 /* Protocol flags for the remote side. */
98 static u_int remote_protocol_flags = 0;
100 /* Encryption context for receiving data. This is only used for decryption. */
101 static CipherContext receive_context;
103 /* Encryption context for sending data. This is only used for encryption. */
104 static CipherContext send_context;
106 /* Buffer for raw input data from the socket. */
109 /* Buffer for raw output data going to the socket. */
112 /* Buffer for the partial outgoing packet being constructed. */
113 static Buffer outgoing_packet;
115 /* Buffer for the incoming packet currently being processed. */
116 static Buffer incoming_packet;
118 /* Scratch buffer for packet compression/decompression. */
119 static Buffer compression_buffer;
120 static int compression_buffer_ready = 0;
122 /* Flag indicating whether packet compression/decompression is enabled. */
123 static int packet_compression = 0;
125 /* default maximum packet size */
126 u_int max_packet_size = 32768;
128 /* Flag indicating whether this module has been initialized. */
129 static int initialized = 0;
131 /* Set to true if the connection is interactive. */
132 static int interactive_mode = 0;
134 /* Set to true if we are the server side. */
135 static int server_side = 0;
137 /* Set to true if we are authenticated. */
138 static int after_authentication = 0;
140 /* Session key information for Encryption and MAC */
141 Newkeys *newkeys[MODE_MAX];
142 static struct packet_state {
148 static u_int64_t max_blocks_in, max_blocks_out;
149 static u_int32_t rekey_limit;
151 /* Session key for protocol v1 */
152 static u_char ssh1_key[SSH_SESSION_KEY_LENGTH];
153 static u_int ssh1_keylen;
155 /* roundup current message to extra_pad bytes */
156 static u_char extra_pad = 0;
159 TAILQ_ENTRY(packet) next;
163 TAILQ_HEAD(, packet) outgoing;
166 * Sets the descriptors used for communication. Disables encryption until
167 * packet_set_encryption_key is called.
170 packet_set_connection(int fd_in, int fd_out)
172 Cipher *none = cipher_by_name("none");
175 fatal("packet_set_connection: cannot load cipher 'none'");
176 connection_in = fd_in;
177 connection_out = fd_out;
178 cipher_init(&send_context, none, (const u_char *)"",
179 0, NULL, 0, CIPHER_ENCRYPT);
180 cipher_init(&receive_context, none, (const u_char *)"",
181 0, NULL, 0, CIPHER_DECRYPT);
182 newkeys[MODE_IN] = newkeys[MODE_OUT] = NULL;
186 buffer_init(&output);
187 buffer_init(&outgoing_packet);
188 buffer_init(&incoming_packet);
189 TAILQ_INIT(&outgoing);
193 /* Returns 1 if remote host is connected via socket, 0 if not. */
196 packet_connection_is_on_socket(void)
198 struct sockaddr_storage from, to;
199 socklen_t fromlen, tolen;
201 /* filedescriptors in and out are the same, so it's a socket */
202 if (connection_in == connection_out)
204 fromlen = sizeof(from);
205 memset(&from, 0, sizeof(from));
206 if (getpeername(connection_in, (struct sockaddr *)&from, &fromlen) < 0)
209 memset(&to, 0, sizeof(to));
210 if (getpeername(connection_out, (struct sockaddr *)&to, &tolen) < 0)
212 if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
214 if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
220 * Exports an IV from the CipherContext required to export the key
221 * state back from the unprivileged child to the privileged parent
226 packet_get_keyiv(int mode, u_char *iv, u_int len)
230 if (mode == MODE_OUT)
233 cc = &receive_context;
235 cipher_get_keyiv(cc, iv, len);
239 packet_get_keycontext(int mode, u_char *dat)
243 if (mode == MODE_OUT)
246 cc = &receive_context;
248 return (cipher_get_keycontext(cc, dat));
252 packet_set_keycontext(int mode, u_char *dat)
256 if (mode == MODE_OUT)
259 cc = &receive_context;
261 cipher_set_keycontext(cc, dat);
265 packet_get_keyiv_len(int mode)
269 if (mode == MODE_OUT)
272 cc = &receive_context;
274 return (cipher_get_keyiv_len(cc));
278 packet_set_iv(int mode, u_char *dat)
282 if (mode == MODE_OUT)
285 cc = &receive_context;
287 cipher_set_keyiv(cc, dat);
291 packet_get_ssh1_cipher(void)
293 return (cipher_get_number(receive_context.cipher));
297 packet_get_state(int mode, u_int32_t *seqnr, u_int64_t *blocks, u_int32_t *packets)
299 struct packet_state *state;
301 state = (mode == MODE_IN) ? &p_read : &p_send;
302 *seqnr = state->seqnr;
303 *blocks = state->blocks;
304 *packets = state->packets;
308 packet_set_state(int mode, u_int32_t seqnr, u_int64_t blocks, u_int32_t packets)
310 struct packet_state *state;
312 state = (mode == MODE_IN) ? &p_read : &p_send;
313 state->seqnr = seqnr;
314 state->blocks = blocks;
315 state->packets = packets;
318 /* returns 1 if connection is via ipv4 */
321 packet_connection_is_ipv4(void)
323 struct sockaddr_storage to;
324 socklen_t tolen = sizeof(to);
326 memset(&to, 0, sizeof(to));
327 if (getsockname(connection_out, (struct sockaddr *)&to, &tolen) < 0)
329 if (to.ss_family == AF_INET)
332 if (to.ss_family == AF_INET6 &&
333 IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&to)->sin6_addr))
339 /* Sets the connection into non-blocking mode. */
342 packet_set_nonblocking(void)
344 /* Set the socket into non-blocking mode. */
345 set_nonblock(connection_in);
347 if (connection_out != connection_in)
348 set_nonblock(connection_out);
351 /* Returns the socket used for reading. */
354 packet_get_connection_in(void)
356 return connection_in;
359 /* Returns the descriptor used for writing. */
362 packet_get_connection_out(void)
364 return connection_out;
367 /* Closes the connection and clears and frees internal data structures. */
375 if (connection_in == connection_out) {
376 shutdown(connection_out, SHUT_RDWR);
377 close(connection_out);
379 close(connection_in);
380 close(connection_out);
383 buffer_free(&output);
384 buffer_free(&outgoing_packet);
385 buffer_free(&incoming_packet);
386 if (compression_buffer_ready) {
387 buffer_free(&compression_buffer);
388 buffer_compress_uninit();
390 cipher_cleanup(&send_context);
391 cipher_cleanup(&receive_context);
394 /* Sets remote side protocol flags. */
397 packet_set_protocol_flags(u_int protocol_flags)
399 remote_protocol_flags = protocol_flags;
402 /* Returns the remote protocol flags set earlier by the above function. */
405 packet_get_protocol_flags(void)
407 return remote_protocol_flags;
411 * Starts packet compression from the next packet on in both directions.
412 * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
416 packet_init_compression(void)
418 if (compression_buffer_ready == 1)
420 compression_buffer_ready = 1;
421 buffer_init(&compression_buffer);
425 packet_start_compression(int level)
427 if (packet_compression && !compat20)
428 fatal("Compression already enabled.");
429 packet_compression = 1;
430 packet_init_compression();
431 buffer_compress_init_send(level);
432 buffer_compress_init_recv();
436 * Causes any further packets to be encrypted using the given key. The same
437 * key is used for both sending and reception. However, both directions are
438 * encrypted independently of each other.
442 packet_set_encryption_key(const u_char *key, u_int keylen,
445 Cipher *cipher = cipher_by_number(number);
448 fatal("packet_set_encryption_key: unknown cipher number %d", number);
450 fatal("packet_set_encryption_key: keylen too small: %d", keylen);
451 if (keylen > SSH_SESSION_KEY_LENGTH)
452 fatal("packet_set_encryption_key: keylen too big: %d", keylen);
453 memcpy(ssh1_key, key, keylen);
454 ssh1_keylen = keylen;
455 cipher_init(&send_context, cipher, key, keylen, NULL, 0, CIPHER_ENCRYPT);
456 cipher_init(&receive_context, cipher, key, keylen, NULL, 0, CIPHER_DECRYPT);
460 packet_get_encryption_key(u_char *key)
463 return (ssh1_keylen);
464 memcpy(key, ssh1_key, ssh1_keylen);
465 return (ssh1_keylen);
468 /* Start constructing a packet to send. */
470 packet_start(u_char type)
475 DBG(debug("packet_start[%d]", type));
476 len = compat20 ? 6 : 9;
477 memset(buf, 0, len - 1);
479 buffer_clear(&outgoing_packet);
480 buffer_append(&outgoing_packet, buf, len);
483 /* Append payload. */
485 packet_put_char(int value)
489 buffer_append(&outgoing_packet, &ch, 1);
493 packet_put_int(u_int value)
495 buffer_put_int(&outgoing_packet, value);
499 packet_put_string(const void *buf, u_int len)
501 buffer_put_string(&outgoing_packet, buf, len);
505 packet_put_cstring(const char *str)
507 buffer_put_cstring(&outgoing_packet, str);
511 packet_put_raw(const void *buf, u_int len)
513 buffer_append(&outgoing_packet, buf, len);
517 packet_put_bignum(BIGNUM * value)
519 buffer_put_bignum(&outgoing_packet, value);
523 packet_put_bignum2(BIGNUM * value)
525 buffer_put_bignum2(&outgoing_packet, value);
529 * Finalizes and sends the packet. If the encryption key has been set,
530 * encrypts the packet before sending.
542 * If using packet compression, compress the payload of the outgoing
545 if (packet_compression) {
546 buffer_clear(&compression_buffer);
548 buffer_consume(&outgoing_packet, 8);
550 buffer_append(&compression_buffer, "\0\0\0\0\0\0\0\0", 8);
551 buffer_compress(&outgoing_packet, &compression_buffer);
552 buffer_clear(&outgoing_packet);
553 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
554 buffer_len(&compression_buffer));
556 /* Compute packet length without padding (add checksum, remove padding). */
557 len = buffer_len(&outgoing_packet) + 4 - 8;
559 /* Insert padding. Initialized to zero in packet_start1() */
560 padding = 8 - len % 8;
561 if (!send_context.plaintext) {
562 cp = buffer_ptr(&outgoing_packet);
563 for (i = 0; i < padding; i++) {
566 cp[7 - i] = rnd & 0xff;
570 buffer_consume(&outgoing_packet, 8 - padding);
572 /* Add check bytes. */
573 checksum = ssh_crc32(buffer_ptr(&outgoing_packet),
574 buffer_len(&outgoing_packet));
575 put_u32(buf, checksum);
576 buffer_append(&outgoing_packet, buf, 4);
579 fprintf(stderr, "packet_send plain: ");
580 buffer_dump(&outgoing_packet);
583 /* Append to output. */
585 buffer_append(&output, buf, 4);
586 cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
587 cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
588 buffer_len(&outgoing_packet));
591 fprintf(stderr, "encrypted: ");
592 buffer_dump(&output);
595 buffer_clear(&outgoing_packet);
598 * Note that the packet is now only buffered in output. It won't be
599 * actually sent until packet_write_wait or packet_write_poll is
605 set_newkeys(int mode)
611 u_int64_t *max_blocks;
614 debug2("set_newkeys: mode %d", mode);
616 if (mode == MODE_OUT) {
618 crypt_type = CIPHER_ENCRYPT;
619 p_send.packets = p_send.blocks = 0;
620 max_blocks = &max_blocks_out;
622 cc = &receive_context;
623 crypt_type = CIPHER_DECRYPT;
624 p_read.packets = p_read.blocks = 0;
625 max_blocks = &max_blocks_in;
627 if (newkeys[mode] != NULL) {
628 debug("set_newkeys: rekeying");
630 enc = &newkeys[mode]->enc;
631 mac = &newkeys[mode]->mac;
632 comp = &newkeys[mode]->comp;
633 memset(mac->key, 0, mac->key_len);
640 xfree(newkeys[mode]);
642 newkeys[mode] = kex_get_newkeys(mode);
643 if (newkeys[mode] == NULL)
644 fatal("newkeys: no keys for mode %d", mode);
645 enc = &newkeys[mode]->enc;
646 mac = &newkeys[mode]->mac;
647 comp = &newkeys[mode]->comp;
650 DBG(debug("cipher_init_context: %d", mode));
651 cipher_init(cc, enc->cipher, enc->key, enc->key_len,
652 enc->iv, enc->block_size, crypt_type);
653 /* Deleting the keys does not gain extra security */
654 /* memset(enc->iv, 0, enc->block_size);
655 memset(enc->key, 0, enc->key_len); */
656 if ((comp->type == COMP_ZLIB ||
657 (comp->type == COMP_DELAYED && after_authentication)) &&
658 comp->enabled == 0) {
659 packet_init_compression();
660 if (mode == MODE_OUT)
661 buffer_compress_init_send(6);
663 buffer_compress_init_recv();
667 * The 2^(blocksize*2) limit is too expensive for 3DES,
668 * blowfish, etc, so enforce a 1GB limit for small blocksizes.
670 if (enc->block_size >= 16)
671 *max_blocks = (u_int64_t)1 << (enc->block_size*2);
673 *max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
675 *max_blocks = MIN(*max_blocks, rekey_limit / enc->block_size);
679 * Delayed compression for SSH2 is enabled after authentication:
680 * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
681 * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
684 packet_enable_delayed_compress(void)
690 * Remember that we are past the authentication step, so rekeying
691 * with COMP_DELAYED will turn on compression immediately.
693 after_authentication = 1;
694 for (mode = 0; mode < MODE_MAX; mode++) {
695 /* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
696 if (newkeys[mode] == NULL)
698 comp = &newkeys[mode]->comp;
699 if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
700 packet_init_compression();
701 if (mode == MODE_OUT)
702 buffer_compress_init_send(6);
704 buffer_compress_init_recv();
711 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
714 packet_send2_wrapped(void)
716 u_char type, *cp, *macbuf = NULL;
718 u_int packet_length = 0;
726 if (newkeys[MODE_OUT] != NULL) {
727 enc = &newkeys[MODE_OUT]->enc;
728 mac = &newkeys[MODE_OUT]->mac;
729 comp = &newkeys[MODE_OUT]->comp;
731 block_size = enc ? enc->block_size : 8;
733 cp = buffer_ptr(&outgoing_packet);
737 fprintf(stderr, "plain: ");
738 buffer_dump(&outgoing_packet);
741 if (comp && comp->enabled) {
742 len = buffer_len(&outgoing_packet);
743 /* skip header, compress only payload */
744 buffer_consume(&outgoing_packet, 5);
745 buffer_clear(&compression_buffer);
746 buffer_compress(&outgoing_packet, &compression_buffer);
747 buffer_clear(&outgoing_packet);
748 buffer_append(&outgoing_packet, "\0\0\0\0\0", 5);
749 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
750 buffer_len(&compression_buffer));
751 DBG(debug("compression: raw %d compressed %d", len,
752 buffer_len(&outgoing_packet)));
755 /* sizeof (packet_len + pad_len + payload) */
756 len = buffer_len(&outgoing_packet);
759 * calc size of padding, alloc space, get random data,
760 * minimum padding is 4 bytes
762 padlen = block_size - (len % block_size);
764 padlen += block_size;
766 /* will wrap if extra_pad+padlen > 255 */
767 extra_pad = roundup(extra_pad, block_size);
768 pad = extra_pad - ((len + padlen) % extra_pad);
769 debug3("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
770 pad, len, padlen, extra_pad);
774 cp = buffer_append_space(&outgoing_packet, padlen);
775 if (enc && !send_context.plaintext) {
777 for (i = 0; i < padlen; i++) {
785 memset(cp, 0, padlen);
787 /* packet_length includes payload, padding and padding length field */
788 packet_length = buffer_len(&outgoing_packet) - 4;
789 cp = buffer_ptr(&outgoing_packet);
790 put_u32(cp, packet_length);
792 DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen));
794 /* compute MAC over seqnr and packet(length fields, payload, padding) */
795 if (mac && mac->enabled) {
796 macbuf = mac_compute(mac, p_send.seqnr,
797 buffer_ptr(&outgoing_packet),
798 buffer_len(&outgoing_packet));
799 DBG(debug("done calc MAC out #%d", p_send.seqnr));
801 /* encrypt packet and append to output buffer. */
802 cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
803 cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
804 buffer_len(&outgoing_packet));
805 /* append unencrypted MAC */
806 if (mac && mac->enabled)
807 buffer_append(&output, macbuf, mac->mac_len);
809 fprintf(stderr, "encrypted: ");
810 buffer_dump(&output);
812 /* increment sequence number for outgoing packets */
813 if (++p_send.seqnr == 0)
814 logit("outgoing seqnr wraps around");
815 if (++p_send.packets == 0)
816 if (!(datafellows & SSH_BUG_NOREKEY))
817 fatal("XXX too many packets with same key");
818 p_send.blocks += (packet_length + 4) / block_size;
819 buffer_clear(&outgoing_packet);
821 if (type == SSH2_MSG_NEWKEYS)
822 set_newkeys(MODE_OUT);
823 else if (type == SSH2_MSG_USERAUTH_SUCCESS && server_side)
824 packet_enable_delayed_compress();
830 static int rekeying = 0;
834 cp = buffer_ptr(&outgoing_packet);
837 /* during rekeying we can only send key exchange messages */
839 if (!((type >= SSH2_MSG_TRANSPORT_MIN) &&
840 (type <= SSH2_MSG_TRANSPORT_MAX))) {
841 debug("enqueue packet: %u", type);
842 p = xmalloc(sizeof(*p));
844 memcpy(&p->payload, &outgoing_packet, sizeof(Buffer));
845 buffer_init(&outgoing_packet);
846 TAILQ_INSERT_TAIL(&outgoing, p, next);
851 /* rekeying starts with sending KEXINIT */
852 if (type == SSH2_MSG_KEXINIT)
855 packet_send2_wrapped();
857 /* after a NEWKEYS message we can send the complete queue */
858 if (type == SSH2_MSG_NEWKEYS) {
860 while ((p = TAILQ_FIRST(&outgoing))) {
862 debug("dequeue packet: %u", type);
863 buffer_free(&outgoing_packet);
864 memcpy(&outgoing_packet, &p->payload,
866 TAILQ_REMOVE(&outgoing, p, next);
868 packet_send2_wrapped();
880 DBG(debug("packet_send done"));
884 * Waits until a packet has been received, and returns its type. Note that
885 * no other data is processed until this returns, so this function should not
886 * be used during the interactive session.
890 packet_read_seqnr(u_int32_t *seqnr_p)
895 DBG(debug("packet_read()"));
897 setp = (fd_set *)xcalloc(howmany(connection_in+1, NFDBITS),
900 /* Since we are blocking, ensure that all written packets have been sent. */
903 /* Stay in the loop until we have received a complete packet. */
905 /* Try to read a packet from the buffer. */
906 type = packet_read_poll_seqnr(seqnr_p);
908 type == SSH_SMSG_SUCCESS
909 || type == SSH_SMSG_FAILURE
910 || type == SSH_CMSG_EOF
911 || type == SSH_CMSG_EXIT_CONFIRMATION))
913 /* If we got a packet, return it. */
914 if (type != SSH_MSG_NONE) {
919 * Otherwise, wait for some data to arrive, add it to the
920 * buffer, and try again.
922 memset(setp, 0, howmany(connection_in + 1, NFDBITS) *
924 FD_SET(connection_in, setp);
926 /* Wait for some data to arrive. */
927 while (select(connection_in + 1, setp, NULL, NULL, NULL) == -1 &&
928 (errno == EAGAIN || errno == EINTR))
931 /* Read data from the socket. */
932 len = read(connection_in, buf, sizeof(buf));
934 logit("Connection closed by %.200s", get_remote_ipaddr());
938 fatal("Read from socket failed: %.100s", strerror(errno));
939 /* Append it to the buffer. */
940 packet_process_incoming(buf, len);
948 return packet_read_seqnr(NULL);
952 * Waits until a packet has been received, verifies that its type matches
953 * that given, and gives a fatal error and exits if there is a mismatch.
957 packet_read_expect(int expected_type)
961 type = packet_read();
962 if (type != expected_type)
963 packet_disconnect("Protocol error: expected packet type %d, got %d",
964 expected_type, type);
967 /* Checks if a full packet is available in the data received so far via
968 * packet_process_incoming. If so, reads the packet; otherwise returns
969 * SSH_MSG_NONE. This does not wait for data from the connection.
971 * SSH_MSG_DISCONNECT is handled specially here. Also,
972 * SSH_MSG_IGNORE messages are skipped by this function and are never returned
977 packet_read_poll1(void)
979 u_int len, padded_len;
981 u_int checksum, stored_checksum;
983 /* Check if input size is less than minimum packet size. */
984 if (buffer_len(&input) < 4 + 8)
986 /* Get length of incoming packet. */
987 cp = buffer_ptr(&input);
989 if (len < 1 + 2 + 2 || len > 256 * 1024)
990 packet_disconnect("Bad packet length %u.", len);
991 padded_len = (len + 8) & ~7;
993 /* Check if the packet has been entirely received. */
994 if (buffer_len(&input) < 4 + padded_len)
997 /* The entire packet is in buffer. */
999 /* Consume packet length. */
1000 buffer_consume(&input, 4);
1003 * Cryptographic attack detector for ssh
1004 * (C)1998 CORE-SDI, Buenos Aires Argentina
1005 * Ariel Futoransky(futo@core-sdi.com)
1007 if (!receive_context.plaintext) {
1008 switch (detect_attack(buffer_ptr(&input), padded_len)) {
1009 case DEATTACK_DETECTED:
1010 packet_disconnect("crc32 compensation attack: "
1011 "network attack detected");
1012 case DEATTACK_DOS_DETECTED:
1013 packet_disconnect("deattack denial of "
1014 "service detected");
1018 /* Decrypt data to incoming_packet. */
1019 buffer_clear(&incoming_packet);
1020 cp = buffer_append_space(&incoming_packet, padded_len);
1021 cipher_crypt(&receive_context, cp, buffer_ptr(&input), padded_len);
1023 buffer_consume(&input, padded_len);
1026 fprintf(stderr, "read_poll plain: ");
1027 buffer_dump(&incoming_packet);
1030 /* Compute packet checksum. */
1031 checksum = ssh_crc32(buffer_ptr(&incoming_packet),
1032 buffer_len(&incoming_packet) - 4);
1035 buffer_consume(&incoming_packet, 8 - len % 8);
1037 /* Test check bytes. */
1038 if (len != buffer_len(&incoming_packet))
1039 packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
1040 len, buffer_len(&incoming_packet));
1042 cp = (u_char *)buffer_ptr(&incoming_packet) + len - 4;
1043 stored_checksum = get_u32(cp);
1044 if (checksum != stored_checksum)
1045 packet_disconnect("Corrupted check bytes on input.");
1046 buffer_consume_end(&incoming_packet, 4);
1048 if (packet_compression) {
1049 buffer_clear(&compression_buffer);
1050 buffer_uncompress(&incoming_packet, &compression_buffer);
1051 buffer_clear(&incoming_packet);
1052 buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
1053 buffer_len(&compression_buffer));
1055 type = buffer_get_char(&incoming_packet);
1056 if (type < SSH_MSG_MIN || type > SSH_MSG_MAX)
1057 packet_disconnect("Invalid ssh1 packet type: %d", type);
1062 packet_read_poll2(u_int32_t *seqnr_p)
1064 static u_int packet_length = 0;
1066 u_char *macbuf, *cp, type;
1067 u_int maclen, block_size;
1072 if (newkeys[MODE_IN] != NULL) {
1073 enc = &newkeys[MODE_IN]->enc;
1074 mac = &newkeys[MODE_IN]->mac;
1075 comp = &newkeys[MODE_IN]->comp;
1077 maclen = mac && mac->enabled ? mac->mac_len : 0;
1078 block_size = enc ? enc->block_size : 8;
1080 if (packet_length == 0) {
1082 * check if input size is less than the cipher block size,
1083 * decrypt first block and extract length of incoming packet
1085 if (buffer_len(&input) < block_size)
1086 return SSH_MSG_NONE;
1087 buffer_clear(&incoming_packet);
1088 cp = buffer_append_space(&incoming_packet, block_size);
1089 cipher_crypt(&receive_context, cp, buffer_ptr(&input),
1091 cp = buffer_ptr(&incoming_packet);
1092 packet_length = get_u32(cp);
1093 if (packet_length < 1 + 4 || packet_length > 256 * 1024) {
1095 buffer_dump(&incoming_packet);
1097 packet_disconnect("Bad packet length %u.", packet_length);
1099 DBG(debug("input: packet len %u", packet_length+4));
1100 buffer_consume(&input, block_size);
1102 /* we have a partial packet of block_size bytes */
1103 need = 4 + packet_length - block_size;
1104 DBG(debug("partial packet %d, need %d, maclen %d", block_size,
1106 if (need % block_size != 0)
1107 fatal("padding error: need %d block %d mod %d",
1108 need, block_size, need % block_size);
1110 * check if the entire packet has been received and
1111 * decrypt into incoming_packet
1113 if (buffer_len(&input) < need + maclen)
1114 return SSH_MSG_NONE;
1116 fprintf(stderr, "read_poll enc/full: ");
1117 buffer_dump(&input);
1119 cp = buffer_append_space(&incoming_packet, need);
1120 cipher_crypt(&receive_context, cp, buffer_ptr(&input), need);
1121 buffer_consume(&input, need);
1123 * compute MAC over seqnr and packet,
1124 * increment sequence number for incoming packet
1126 if (mac && mac->enabled) {
1127 macbuf = mac_compute(mac, p_read.seqnr,
1128 buffer_ptr(&incoming_packet),
1129 buffer_len(&incoming_packet));
1130 if (memcmp(macbuf, buffer_ptr(&input), mac->mac_len) != 0)
1131 packet_disconnect("Corrupted MAC on input.");
1132 DBG(debug("MAC #%d ok", p_read.seqnr));
1133 buffer_consume(&input, mac->mac_len);
1135 if (seqnr_p != NULL)
1136 *seqnr_p = p_read.seqnr;
1137 if (++p_read.seqnr == 0)
1138 logit("incoming seqnr wraps around");
1139 if (++p_read.packets == 0)
1140 if (!(datafellows & SSH_BUG_NOREKEY))
1141 fatal("XXX too many packets with same key");
1142 p_read.blocks += (packet_length + 4) / block_size;
1145 cp = buffer_ptr(&incoming_packet);
1147 DBG(debug("input: padlen %d", padlen));
1149 packet_disconnect("Corrupted padlen %d on input.", padlen);
1151 /* skip packet size + padlen, discard padding */
1152 buffer_consume(&incoming_packet, 4 + 1);
1153 buffer_consume_end(&incoming_packet, padlen);
1155 DBG(debug("input: len before de-compress %d", buffer_len(&incoming_packet)));
1156 if (comp && comp->enabled) {
1157 buffer_clear(&compression_buffer);
1158 buffer_uncompress(&incoming_packet, &compression_buffer);
1159 buffer_clear(&incoming_packet);
1160 buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
1161 buffer_len(&compression_buffer));
1162 DBG(debug("input: len after de-compress %d",
1163 buffer_len(&incoming_packet)));
1166 * get packet type, implies consume.
1167 * return length of payload (without type field)
1169 type = buffer_get_char(&incoming_packet);
1170 if (type < SSH2_MSG_MIN || type >= SSH2_MSG_LOCAL_MIN)
1171 packet_disconnect("Invalid ssh2 packet type: %d", type);
1172 if (type == SSH2_MSG_NEWKEYS)
1173 set_newkeys(MODE_IN);
1174 else if (type == SSH2_MSG_USERAUTH_SUCCESS && !server_side)
1175 packet_enable_delayed_compress();
1177 fprintf(stderr, "read/plain[%d]:\r\n", type);
1178 buffer_dump(&incoming_packet);
1180 /* reset for next packet */
1186 packet_read_poll_seqnr(u_int32_t *seqnr_p)
1188 u_int reason, seqnr;
1194 type = packet_read_poll2(seqnr_p);
1196 DBG(debug("received packet type %d", type));
1198 case SSH2_MSG_IGNORE:
1200 case SSH2_MSG_DEBUG:
1202 msg = packet_get_string(NULL);
1203 debug("Remote: %.900s", msg);
1205 msg = packet_get_string(NULL);
1208 case SSH2_MSG_DISCONNECT:
1209 reason = packet_get_int();
1210 msg = packet_get_string(NULL);
1211 logit("Received disconnect from %s: %u: %.400s",
1212 get_remote_ipaddr(), reason, msg);
1216 case SSH2_MSG_UNIMPLEMENTED:
1217 seqnr = packet_get_int();
1218 debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1225 type = packet_read_poll1();
1227 case SSH_MSG_IGNORE:
1230 msg = packet_get_string(NULL);
1231 debug("Remote: %.900s", msg);
1234 case SSH_MSG_DISCONNECT:
1235 msg = packet_get_string(NULL);
1236 logit("Received disconnect from %s: %.400s",
1237 get_remote_ipaddr(), msg);
1243 DBG(debug("received packet type %d", type));
1251 packet_read_poll(void)
1253 return packet_read_poll_seqnr(NULL);
1257 * Buffers the given amount of input characters. This is intended to be used
1258 * together with packet_read_poll.
1262 packet_process_incoming(const char *buf, u_int len)
1264 buffer_append(&input, buf, len);
1267 /* Returns a character from the packet. */
1270 packet_get_char(void)
1274 buffer_get(&incoming_packet, &ch, 1);
1278 /* Returns an integer from the packet data. */
1281 packet_get_int(void)
1283 return buffer_get_int(&incoming_packet);
1287 * Returns an arbitrary precision integer from the packet data. The integer
1288 * must have been initialized before this call.
1292 packet_get_bignum(BIGNUM * value)
1294 buffer_get_bignum(&incoming_packet, value);
1298 packet_get_bignum2(BIGNUM * value)
1300 buffer_get_bignum2(&incoming_packet, value);
1304 packet_get_raw(u_int *length_ptr)
1306 u_int bytes = buffer_len(&incoming_packet);
1308 if (length_ptr != NULL)
1309 *length_ptr = bytes;
1310 return buffer_ptr(&incoming_packet);
1314 packet_remaining(void)
1316 return buffer_len(&incoming_packet);
1320 * Returns a string from the packet data. The string is allocated using
1321 * xmalloc; it is the responsibility of the calling program to free it when
1322 * no longer needed. The length_ptr argument may be NULL, or point to an
1323 * integer into which the length of the string is stored.
1327 packet_get_string(u_int *length_ptr)
1329 return buffer_get_string(&incoming_packet, length_ptr);
1333 * Sends a diagnostic message from the server to the client. This message
1334 * can be sent at any time (but not while constructing another message). The
1335 * message is printed immediately, but only if the client is being executed
1336 * in verbose mode. These messages are primarily intended to ease debugging
1337 * authentication problems. The length of the formatted message must not
1338 * exceed 1024 bytes. This will automatically call packet_write_wait.
1342 packet_send_debug(const char *fmt,...)
1347 if (compat20 && (datafellows & SSH_BUG_DEBUG))
1350 va_start(args, fmt);
1351 vsnprintf(buf, sizeof(buf), fmt, args);
1355 packet_start(SSH2_MSG_DEBUG);
1356 packet_put_char(0); /* bool: always display */
1357 packet_put_cstring(buf);
1358 packet_put_cstring("");
1360 packet_start(SSH_MSG_DEBUG);
1361 packet_put_cstring(buf);
1364 packet_write_wait();
1368 * Logs the error plus constructs and sends a disconnect packet, closes the
1369 * connection, and exits. This function never returns. The error message
1370 * should not contain a newline. The length of the formatted message must
1371 * not exceed 1024 bytes.
1375 packet_disconnect(const char *fmt,...)
1379 static int disconnecting = 0;
1381 if (disconnecting) /* Guard against recursive invocations. */
1382 fatal("packet_disconnect called recursively.");
1386 * Format the message. Note that the caller must make sure the
1387 * message is of limited size.
1389 va_start(args, fmt);
1390 vsnprintf(buf, sizeof(buf), fmt, args);
1393 /* Display the error locally */
1394 logit("Disconnecting: %.100s", buf);
1396 /* Send the disconnect message to the other side, and wait for it to get sent. */
1398 packet_start(SSH2_MSG_DISCONNECT);
1399 packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1400 packet_put_cstring(buf);
1401 packet_put_cstring("");
1403 packet_start(SSH_MSG_DISCONNECT);
1404 packet_put_cstring(buf);
1407 packet_write_wait();
1409 /* Stop listening for connections. */
1410 channel_close_all();
1412 /* Close the connection. */
1417 /* Checks if there is any buffered output, and tries to write some of the output. */
1420 packet_write_poll(void)
1422 int len = buffer_len(&output);
1425 len = write(connection_out, buffer_ptr(&output), len);
1427 if (errno == EAGAIN)
1430 fatal("Write failed: %.100s", strerror(errno));
1432 buffer_consume(&output, len);
1437 * Calls packet_write_poll repeatedly until all pending output data has been
1442 packet_write_wait(void)
1446 setp = (fd_set *)xcalloc(howmany(connection_out + 1, NFDBITS),
1448 packet_write_poll();
1449 while (packet_have_data_to_write()) {
1450 memset(setp, 0, howmany(connection_out + 1, NFDBITS) *
1452 FD_SET(connection_out, setp);
1453 while (select(connection_out + 1, NULL, setp, NULL, NULL) == -1 &&
1454 (errno == EAGAIN || errno == EINTR))
1456 packet_write_poll();
1461 /* Returns true if there is buffered data to write to the connection. */
1464 packet_have_data_to_write(void)
1466 return buffer_len(&output) != 0;
1469 /* Returns true if there is not too much data to write to the connection. */
1472 packet_not_very_much_data_to_write(void)
1474 if (interactive_mode)
1475 return buffer_len(&output) < 16384;
1477 return buffer_len(&output) < 128 * 1024;
1482 packet_set_tos(int interactive)
1484 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1485 int tos = interactive ? IPTOS_LOWDELAY : IPTOS_THROUGHPUT;
1487 if (!packet_connection_is_on_socket() ||
1488 !packet_connection_is_ipv4())
1490 if (setsockopt(connection_in, IPPROTO_IP, IP_TOS, &tos,
1492 error("setsockopt IP_TOS %d: %.100s:",
1493 tos, strerror(errno));
1497 /* Informs that the current session is interactive. Sets IP flags for that. */
1500 packet_set_interactive(int interactive)
1502 static int called = 0;
1508 /* Record that we are in interactive mode. */
1509 interactive_mode = interactive;
1511 /* Only set socket options if using a socket. */
1512 if (!packet_connection_is_on_socket())
1514 set_nodelay(connection_in);
1515 packet_set_tos(interactive);
1518 /* Returns true if the current connection is interactive. */
1521 packet_is_interactive(void)
1523 return interactive_mode;
1527 packet_set_maxsize(u_int s)
1529 static int called = 0;
1532 logit("packet_set_maxsize: called twice: old %d new %d",
1533 max_packet_size, s);
1536 if (s < 4 * 1024 || s > 1024 * 1024) {
1537 logit("packet_set_maxsize: bad size %d", s);
1541 debug("packet_set_maxsize: setting to %d", s);
1542 max_packet_size = s;
1546 /* roundup current message to pad bytes */
1548 packet_add_padding(u_char pad)
1554 * 9.2. Ignored Data Message
1556 * byte SSH_MSG_IGNORE
1559 * All implementations MUST understand (and ignore) this message at any
1560 * time (after receiving the protocol version). No implementation is
1561 * required to send them. This message can be used as an additional
1562 * protection measure against advanced traffic analysis techniques.
1565 packet_send_ignore(int nbytes)
1570 packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1571 packet_put_int(nbytes);
1572 for (i = 0; i < nbytes; i++) {
1575 packet_put_char((u_char)rnd & 0xff);
1579 int rekey_requested = 0;
1582 packet_request_rekeying(void)
1584 rekey_requested = 1;
1587 #define MAX_PACKETS (1U<<31)
1589 packet_need_rekeying(void)
1591 if (datafellows & SSH_BUG_NOREKEY)
1593 if (rekey_requested == 1)
1595 rekey_requested = 0;
1599 (p_send.packets > MAX_PACKETS) ||
1600 (p_read.packets > MAX_PACKETS) ||
1601 (max_blocks_out && (p_send.blocks > max_blocks_out)) ||
1602 (max_blocks_in && (p_read.blocks > max_blocks_in));
1606 packet_set_rekey_limit(u_int32_t bytes)
1608 rekey_limit = bytes;
1612 packet_set_server(void)
1618 packet_set_authenticated(void)
1620 after_authentication = 1;