1 /* $OpenBSD: packet.c,v 1.131 2006/03/30 09:58:16 djm Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * This file contains code implementing the packet protocol and communication
7 * with the other side. This same code is used both on client and server side.
9 * As far as I am concerned, the code I have written for this software
10 * can be used freely for any purpose. Any derived versions of this
11 * software must be clearly marked as such, and if the derived work is
12 * incompatible with the protocol description in the RFC file, it must be
13 * called by a name other than "ssh" or "Secure Shell".
16 * SSH2 packet format added by Markus Friedl.
17 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
19 * Redistribution and use in source and binary forms, with or without
20 * modification, are permitted provided that the following conditions
22 * 1. Redistributions of source code must retain the above copyright
23 * notice, this list of conditions and the following disclaimer.
24 * 2. Redistributions in binary form must reproduce the above copyright
25 * notice, this list of conditions and the following disclaimer in the
26 * documentation and/or other materials provided with the distribution.
28 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
29 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
30 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
31 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
32 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
33 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
34 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
35 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
36 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
37 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42 #include "openbsd-compat/sys-queue.h"
43 #include <netinet/ip.h>
74 * This variable contains the file descriptors used for communicating with
75 * the other side. connection_in is used for reading; connection_out for
76 * writing. These can be the same descriptor, in which case it is assumed to
79 static int connection_in = -1;
80 static int connection_out = -1;
82 /* Protocol flags for the remote side. */
83 static u_int remote_protocol_flags = 0;
85 /* Encryption context for receiving data. This is only used for decryption. */
86 static CipherContext receive_context;
88 /* Encryption context for sending data. This is only used for encryption. */
89 static CipherContext send_context;
91 /* Buffer for raw input data from the socket. */
94 /* Buffer for raw output data going to the socket. */
97 /* Buffer for the partial outgoing packet being constructed. */
98 static Buffer outgoing_packet;
100 /* Buffer for the incoming packet currently being processed. */
101 static Buffer incoming_packet;
103 /* Scratch buffer for packet compression/decompression. */
104 static Buffer compression_buffer;
105 static int compression_buffer_ready = 0;
107 /* Flag indicating whether packet compression/decompression is enabled. */
108 static int packet_compression = 0;
110 /* default maximum packet size */
111 u_int max_packet_size = 32768;
113 /* Flag indicating whether this module has been initialized. */
114 static int initialized = 0;
116 /* Set to true if the connection is interactive. */
117 static int interactive_mode = 0;
119 /* Set to true if we are the server side. */
120 static int server_side = 0;
122 /* Set to true if we are authenticated. */
123 static int after_authentication = 0;
125 /* Session key information for Encryption and MAC */
126 Newkeys *newkeys[MODE_MAX];
127 static struct packet_state {
133 static u_int64_t max_blocks_in, max_blocks_out;
134 static u_int32_t rekey_limit;
136 /* Session key for protocol v1 */
137 static u_char ssh1_key[SSH_SESSION_KEY_LENGTH];
138 static u_int ssh1_keylen;
140 /* roundup current message to extra_pad bytes */
141 static u_char extra_pad = 0;
144 TAILQ_ENTRY(packet) next;
148 TAILQ_HEAD(, packet) outgoing;
151 * Sets the descriptors used for communication. Disables encryption until
152 * packet_set_encryption_key is called.
155 packet_set_connection(int fd_in, int fd_out)
157 Cipher *none = cipher_by_name("none");
160 fatal("packet_set_connection: cannot load cipher 'none'");
161 connection_in = fd_in;
162 connection_out = fd_out;
163 cipher_init(&send_context, none, (const u_char *)"",
164 0, NULL, 0, CIPHER_ENCRYPT);
165 cipher_init(&receive_context, none, (const u_char *)"",
166 0, NULL, 0, CIPHER_DECRYPT);
167 newkeys[MODE_IN] = newkeys[MODE_OUT] = NULL;
171 buffer_init(&output);
172 buffer_init(&outgoing_packet);
173 buffer_init(&incoming_packet);
174 TAILQ_INIT(&outgoing);
178 /* Returns 1 if remote host is connected via socket, 0 if not. */
181 packet_connection_is_on_socket(void)
183 struct sockaddr_storage from, to;
184 socklen_t fromlen, tolen;
186 /* filedescriptors in and out are the same, so it's a socket */
187 if (connection_in == connection_out)
189 fromlen = sizeof(from);
190 memset(&from, 0, sizeof(from));
191 if (getpeername(connection_in, (struct sockaddr *)&from, &fromlen) < 0)
194 memset(&to, 0, sizeof(to));
195 if (getpeername(connection_out, (struct sockaddr *)&to, &tolen) < 0)
197 if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
199 if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
205 * Exports an IV from the CipherContext required to export the key
206 * state back from the unprivileged child to the privileged parent
211 packet_get_keyiv(int mode, u_char *iv, u_int len)
215 if (mode == MODE_OUT)
218 cc = &receive_context;
220 cipher_get_keyiv(cc, iv, len);
224 packet_get_keycontext(int mode, u_char *dat)
228 if (mode == MODE_OUT)
231 cc = &receive_context;
233 return (cipher_get_keycontext(cc, dat));
237 packet_set_keycontext(int mode, u_char *dat)
241 if (mode == MODE_OUT)
244 cc = &receive_context;
246 cipher_set_keycontext(cc, dat);
250 packet_get_keyiv_len(int mode)
254 if (mode == MODE_OUT)
257 cc = &receive_context;
259 return (cipher_get_keyiv_len(cc));
263 packet_set_iv(int mode, u_char *dat)
267 if (mode == MODE_OUT)
270 cc = &receive_context;
272 cipher_set_keyiv(cc, dat);
276 packet_get_ssh1_cipher(void)
278 return (cipher_get_number(receive_context.cipher));
282 packet_get_state(int mode, u_int32_t *seqnr, u_int64_t *blocks, u_int32_t *packets)
284 struct packet_state *state;
286 state = (mode == MODE_IN) ? &p_read : &p_send;
287 *seqnr = state->seqnr;
288 *blocks = state->blocks;
289 *packets = state->packets;
293 packet_set_state(int mode, u_int32_t seqnr, u_int64_t blocks, u_int32_t packets)
295 struct packet_state *state;
297 state = (mode == MODE_IN) ? &p_read : &p_send;
298 state->seqnr = seqnr;
299 state->blocks = blocks;
300 state->packets = packets;
303 /* returns 1 if connection is via ipv4 */
306 packet_connection_is_ipv4(void)
308 struct sockaddr_storage to;
309 socklen_t tolen = sizeof(to);
311 memset(&to, 0, sizeof(to));
312 if (getsockname(connection_out, (struct sockaddr *)&to, &tolen) < 0)
314 if (to.ss_family == AF_INET)
317 if (to.ss_family == AF_INET6 &&
318 IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&to)->sin6_addr))
324 /* Sets the connection into non-blocking mode. */
327 packet_set_nonblocking(void)
329 /* Set the socket into non-blocking mode. */
330 set_nonblock(connection_in);
332 if (connection_out != connection_in)
333 set_nonblock(connection_out);
336 /* Returns the socket used for reading. */
339 packet_get_connection_in(void)
341 return connection_in;
344 /* Returns the descriptor used for writing. */
347 packet_get_connection_out(void)
349 return connection_out;
352 /* Closes the connection and clears and frees internal data structures. */
360 if (connection_in == connection_out) {
361 shutdown(connection_out, SHUT_RDWR);
362 close(connection_out);
364 close(connection_in);
365 close(connection_out);
368 buffer_free(&output);
369 buffer_free(&outgoing_packet);
370 buffer_free(&incoming_packet);
371 if (compression_buffer_ready) {
372 buffer_free(&compression_buffer);
373 buffer_compress_uninit();
375 cipher_cleanup(&send_context);
376 cipher_cleanup(&receive_context);
379 /* Sets remote side protocol flags. */
382 packet_set_protocol_flags(u_int protocol_flags)
384 remote_protocol_flags = protocol_flags;
387 /* Returns the remote protocol flags set earlier by the above function. */
390 packet_get_protocol_flags(void)
392 return remote_protocol_flags;
396 * Starts packet compression from the next packet on in both directions.
397 * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
401 packet_init_compression(void)
403 if (compression_buffer_ready == 1)
405 compression_buffer_ready = 1;
406 buffer_init(&compression_buffer);
410 packet_start_compression(int level)
412 if (packet_compression && !compat20)
413 fatal("Compression already enabled.");
414 packet_compression = 1;
415 packet_init_compression();
416 buffer_compress_init_send(level);
417 buffer_compress_init_recv();
421 * Causes any further packets to be encrypted using the given key. The same
422 * key is used for both sending and reception. However, both directions are
423 * encrypted independently of each other.
427 packet_set_encryption_key(const u_char *key, u_int keylen,
430 Cipher *cipher = cipher_by_number(number);
433 fatal("packet_set_encryption_key: unknown cipher number %d", number);
435 fatal("packet_set_encryption_key: keylen too small: %d", keylen);
436 if (keylen > SSH_SESSION_KEY_LENGTH)
437 fatal("packet_set_encryption_key: keylen too big: %d", keylen);
438 memcpy(ssh1_key, key, keylen);
439 ssh1_keylen = keylen;
440 cipher_init(&send_context, cipher, key, keylen, NULL, 0, CIPHER_ENCRYPT);
441 cipher_init(&receive_context, cipher, key, keylen, NULL, 0, CIPHER_DECRYPT);
445 packet_get_encryption_key(u_char *key)
448 return (ssh1_keylen);
449 memcpy(key, ssh1_key, ssh1_keylen);
450 return (ssh1_keylen);
453 /* Start constructing a packet to send. */
455 packet_start(u_char type)
460 DBG(debug("packet_start[%d]", type));
461 len = compat20 ? 6 : 9;
462 memset(buf, 0, len - 1);
464 buffer_clear(&outgoing_packet);
465 buffer_append(&outgoing_packet, buf, len);
468 /* Append payload. */
470 packet_put_char(int value)
474 buffer_append(&outgoing_packet, &ch, 1);
478 packet_put_int(u_int value)
480 buffer_put_int(&outgoing_packet, value);
484 packet_put_string(const void *buf, u_int len)
486 buffer_put_string(&outgoing_packet, buf, len);
490 packet_put_cstring(const char *str)
492 buffer_put_cstring(&outgoing_packet, str);
496 packet_put_raw(const void *buf, u_int len)
498 buffer_append(&outgoing_packet, buf, len);
502 packet_put_bignum(BIGNUM * value)
504 buffer_put_bignum(&outgoing_packet, value);
508 packet_put_bignum2(BIGNUM * value)
510 buffer_put_bignum2(&outgoing_packet, value);
514 * Finalizes and sends the packet. If the encryption key has been set,
515 * encrypts the packet before sending.
527 * If using packet compression, compress the payload of the outgoing
530 if (packet_compression) {
531 buffer_clear(&compression_buffer);
533 buffer_consume(&outgoing_packet, 8);
535 buffer_append(&compression_buffer, "\0\0\0\0\0\0\0\0", 8);
536 buffer_compress(&outgoing_packet, &compression_buffer);
537 buffer_clear(&outgoing_packet);
538 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
539 buffer_len(&compression_buffer));
541 /* Compute packet length without padding (add checksum, remove padding). */
542 len = buffer_len(&outgoing_packet) + 4 - 8;
544 /* Insert padding. Initialized to zero in packet_start1() */
545 padding = 8 - len % 8;
546 if (!send_context.plaintext) {
547 cp = buffer_ptr(&outgoing_packet);
548 for (i = 0; i < padding; i++) {
551 cp[7 - i] = rnd & 0xff;
555 buffer_consume(&outgoing_packet, 8 - padding);
557 /* Add check bytes. */
558 checksum = ssh_crc32(buffer_ptr(&outgoing_packet),
559 buffer_len(&outgoing_packet));
560 put_u32(buf, checksum);
561 buffer_append(&outgoing_packet, buf, 4);
564 fprintf(stderr, "packet_send plain: ");
565 buffer_dump(&outgoing_packet);
568 /* Append to output. */
570 buffer_append(&output, buf, 4);
571 cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
572 cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
573 buffer_len(&outgoing_packet));
576 fprintf(stderr, "encrypted: ");
577 buffer_dump(&output);
580 buffer_clear(&outgoing_packet);
583 * Note that the packet is now only buffered in output. It won't be
584 * actually sent until packet_write_wait or packet_write_poll is
590 set_newkeys(int mode)
596 u_int64_t *max_blocks;
599 debug2("set_newkeys: mode %d", mode);
601 if (mode == MODE_OUT) {
603 crypt_type = CIPHER_ENCRYPT;
604 p_send.packets = p_send.blocks = 0;
605 max_blocks = &max_blocks_out;
607 cc = &receive_context;
608 crypt_type = CIPHER_DECRYPT;
609 p_read.packets = p_read.blocks = 0;
610 max_blocks = &max_blocks_in;
612 if (newkeys[mode] != NULL) {
613 debug("set_newkeys: rekeying");
615 enc = &newkeys[mode]->enc;
616 mac = &newkeys[mode]->mac;
617 comp = &newkeys[mode]->comp;
618 memset(mac->key, 0, mac->key_len);
625 xfree(newkeys[mode]);
627 newkeys[mode] = kex_get_newkeys(mode);
628 if (newkeys[mode] == NULL)
629 fatal("newkeys: no keys for mode %d", mode);
630 enc = &newkeys[mode]->enc;
631 mac = &newkeys[mode]->mac;
632 comp = &newkeys[mode]->comp;
635 DBG(debug("cipher_init_context: %d", mode));
636 cipher_init(cc, enc->cipher, enc->key, enc->key_len,
637 enc->iv, enc->block_size, crypt_type);
638 /* Deleting the keys does not gain extra security */
639 /* memset(enc->iv, 0, enc->block_size);
640 memset(enc->key, 0, enc->key_len); */
641 if ((comp->type == COMP_ZLIB ||
642 (comp->type == COMP_DELAYED && after_authentication)) &&
643 comp->enabled == 0) {
644 packet_init_compression();
645 if (mode == MODE_OUT)
646 buffer_compress_init_send(6);
648 buffer_compress_init_recv();
652 * The 2^(blocksize*2) limit is too expensive for 3DES,
653 * blowfish, etc, so enforce a 1GB limit for small blocksizes.
655 if (enc->block_size >= 16)
656 *max_blocks = (u_int64_t)1 << (enc->block_size*2);
658 *max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
660 *max_blocks = MIN(*max_blocks, rekey_limit / enc->block_size);
664 * Delayed compression for SSH2 is enabled after authentication:
665 * This happans on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
666 * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
669 packet_enable_delayed_compress(void)
675 * Remember that we are past the authentication step, so rekeying
676 * with COMP_DELAYED will turn on compression immediately.
678 after_authentication = 1;
679 for (mode = 0; mode < MODE_MAX; mode++) {
680 comp = &newkeys[mode]->comp;
681 if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
682 packet_init_compression();
683 if (mode == MODE_OUT)
684 buffer_compress_init_send(6);
686 buffer_compress_init_recv();
693 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
696 packet_send2_wrapped(void)
698 u_char type, *cp, *macbuf = NULL;
700 u_int packet_length = 0;
708 if (newkeys[MODE_OUT] != NULL) {
709 enc = &newkeys[MODE_OUT]->enc;
710 mac = &newkeys[MODE_OUT]->mac;
711 comp = &newkeys[MODE_OUT]->comp;
713 block_size = enc ? enc->block_size : 8;
715 cp = buffer_ptr(&outgoing_packet);
719 fprintf(stderr, "plain: ");
720 buffer_dump(&outgoing_packet);
723 if (comp && comp->enabled) {
724 len = buffer_len(&outgoing_packet);
725 /* skip header, compress only payload */
726 buffer_consume(&outgoing_packet, 5);
727 buffer_clear(&compression_buffer);
728 buffer_compress(&outgoing_packet, &compression_buffer);
729 buffer_clear(&outgoing_packet);
730 buffer_append(&outgoing_packet, "\0\0\0\0\0", 5);
731 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
732 buffer_len(&compression_buffer));
733 DBG(debug("compression: raw %d compressed %d", len,
734 buffer_len(&outgoing_packet)));
737 /* sizeof (packet_len + pad_len + payload) */
738 len = buffer_len(&outgoing_packet);
741 * calc size of padding, alloc space, get random data,
742 * minimum padding is 4 bytes
744 padlen = block_size - (len % block_size);
746 padlen += block_size;
748 /* will wrap if extra_pad+padlen > 255 */
749 extra_pad = roundup(extra_pad, block_size);
750 pad = extra_pad - ((len + padlen) % extra_pad);
751 debug3("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
752 pad, len, padlen, extra_pad);
756 cp = buffer_append_space(&outgoing_packet, padlen);
757 if (enc && !send_context.plaintext) {
759 for (i = 0; i < padlen; i++) {
767 memset(cp, 0, padlen);
769 /* packet_length includes payload, padding and padding length field */
770 packet_length = buffer_len(&outgoing_packet) - 4;
771 cp = buffer_ptr(&outgoing_packet);
772 put_u32(cp, packet_length);
774 DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen));
776 /* compute MAC over seqnr and packet(length fields, payload, padding) */
777 if (mac && mac->enabled) {
778 macbuf = mac_compute(mac, p_send.seqnr,
779 buffer_ptr(&outgoing_packet),
780 buffer_len(&outgoing_packet));
781 DBG(debug("done calc MAC out #%d", p_send.seqnr));
783 /* encrypt packet and append to output buffer. */
784 cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
785 cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
786 buffer_len(&outgoing_packet));
787 /* append unencrypted MAC */
788 if (mac && mac->enabled)
789 buffer_append(&output, macbuf, mac->mac_len);
791 fprintf(stderr, "encrypted: ");
792 buffer_dump(&output);
794 /* increment sequence number for outgoing packets */
795 if (++p_send.seqnr == 0)
796 logit("outgoing seqnr wraps around");
797 if (++p_send.packets == 0)
798 if (!(datafellows & SSH_BUG_NOREKEY))
799 fatal("XXX too many packets with same key");
800 p_send.blocks += (packet_length + 4) / block_size;
801 buffer_clear(&outgoing_packet);
803 if (type == SSH2_MSG_NEWKEYS)
804 set_newkeys(MODE_OUT);
805 else if (type == SSH2_MSG_USERAUTH_SUCCESS && server_side)
806 packet_enable_delayed_compress();
812 static int rekeying = 0;
816 cp = buffer_ptr(&outgoing_packet);
819 /* during rekeying we can only send key exchange messages */
821 if (!((type >= SSH2_MSG_TRANSPORT_MIN) &&
822 (type <= SSH2_MSG_TRANSPORT_MAX))) {
823 debug("enqueue packet: %u", type);
824 p = xmalloc(sizeof(*p));
826 memcpy(&p->payload, &outgoing_packet, sizeof(Buffer));
827 buffer_init(&outgoing_packet);
828 TAILQ_INSERT_TAIL(&outgoing, p, next);
833 /* rekeying starts with sending KEXINIT */
834 if (type == SSH2_MSG_KEXINIT)
837 packet_send2_wrapped();
839 /* after a NEWKEYS message we can send the complete queue */
840 if (type == SSH2_MSG_NEWKEYS) {
842 while ((p = TAILQ_FIRST(&outgoing))) {
844 debug("dequeue packet: %u", type);
845 buffer_free(&outgoing_packet);
846 memcpy(&outgoing_packet, &p->payload,
848 TAILQ_REMOVE(&outgoing, p, next);
850 packet_send2_wrapped();
862 DBG(debug("packet_send done"));
866 * Waits until a packet has been received, and returns its type. Note that
867 * no other data is processed until this returns, so this function should not
868 * be used during the interactive session.
872 packet_read_seqnr(u_int32_t *seqnr_p)
877 DBG(debug("packet_read()"));
879 setp = (fd_set *)xcalloc(howmany(connection_in+1, NFDBITS),
882 /* Since we are blocking, ensure that all written packets have been sent. */
885 /* Stay in the loop until we have received a complete packet. */
887 /* Try to read a packet from the buffer. */
888 type = packet_read_poll_seqnr(seqnr_p);
890 type == SSH_SMSG_SUCCESS
891 || type == SSH_SMSG_FAILURE
892 || type == SSH_CMSG_EOF
893 || type == SSH_CMSG_EXIT_CONFIRMATION))
895 /* If we got a packet, return it. */
896 if (type != SSH_MSG_NONE) {
901 * Otherwise, wait for some data to arrive, add it to the
902 * buffer, and try again.
904 memset(setp, 0, howmany(connection_in + 1, NFDBITS) *
906 FD_SET(connection_in, setp);
908 /* Wait for some data to arrive. */
909 while (select(connection_in + 1, setp, NULL, NULL, NULL) == -1 &&
910 (errno == EAGAIN || errno == EINTR))
913 /* Read data from the socket. */
914 len = read(connection_in, buf, sizeof(buf));
916 logit("Connection closed by %.200s", get_remote_ipaddr());
920 fatal("Read from socket failed: %.100s", strerror(errno));
921 /* Append it to the buffer. */
922 packet_process_incoming(buf, len);
930 return packet_read_seqnr(NULL);
934 * Waits until a packet has been received, verifies that its type matches
935 * that given, and gives a fatal error and exits if there is a mismatch.
939 packet_read_expect(int expected_type)
943 type = packet_read();
944 if (type != expected_type)
945 packet_disconnect("Protocol error: expected packet type %d, got %d",
946 expected_type, type);
949 /* Checks if a full packet is available in the data received so far via
950 * packet_process_incoming. If so, reads the packet; otherwise returns
951 * SSH_MSG_NONE. This does not wait for data from the connection.
953 * SSH_MSG_DISCONNECT is handled specially here. Also,
954 * SSH_MSG_IGNORE messages are skipped by this function and are never returned
959 packet_read_poll1(void)
961 u_int len, padded_len;
963 u_int checksum, stored_checksum;
965 /* Check if input size is less than minimum packet size. */
966 if (buffer_len(&input) < 4 + 8)
968 /* Get length of incoming packet. */
969 cp = buffer_ptr(&input);
971 if (len < 1 + 2 + 2 || len > 256 * 1024)
972 packet_disconnect("Bad packet length %u.", len);
973 padded_len = (len + 8) & ~7;
975 /* Check if the packet has been entirely received. */
976 if (buffer_len(&input) < 4 + padded_len)
979 /* The entire packet is in buffer. */
981 /* Consume packet length. */
982 buffer_consume(&input, 4);
985 * Cryptographic attack detector for ssh
986 * (C)1998 CORE-SDI, Buenos Aires Argentina
987 * Ariel Futoransky(futo@core-sdi.com)
989 if (!receive_context.plaintext &&
990 detect_attack(buffer_ptr(&input), padded_len) == DEATTACK_DETECTED)
991 packet_disconnect("crc32 compensation attack: network attack detected");
993 /* Decrypt data to incoming_packet. */
994 buffer_clear(&incoming_packet);
995 cp = buffer_append_space(&incoming_packet, padded_len);
996 cipher_crypt(&receive_context, cp, buffer_ptr(&input), padded_len);
998 buffer_consume(&input, padded_len);
1001 fprintf(stderr, "read_poll plain: ");
1002 buffer_dump(&incoming_packet);
1005 /* Compute packet checksum. */
1006 checksum = ssh_crc32(buffer_ptr(&incoming_packet),
1007 buffer_len(&incoming_packet) - 4);
1010 buffer_consume(&incoming_packet, 8 - len % 8);
1012 /* Test check bytes. */
1013 if (len != buffer_len(&incoming_packet))
1014 packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
1015 len, buffer_len(&incoming_packet));
1017 cp = (u_char *)buffer_ptr(&incoming_packet) + len - 4;
1018 stored_checksum = get_u32(cp);
1019 if (checksum != stored_checksum)
1020 packet_disconnect("Corrupted check bytes on input.");
1021 buffer_consume_end(&incoming_packet, 4);
1023 if (packet_compression) {
1024 buffer_clear(&compression_buffer);
1025 buffer_uncompress(&incoming_packet, &compression_buffer);
1026 buffer_clear(&incoming_packet);
1027 buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
1028 buffer_len(&compression_buffer));
1030 type = buffer_get_char(&incoming_packet);
1031 if (type < SSH_MSG_MIN || type > SSH_MSG_MAX)
1032 packet_disconnect("Invalid ssh1 packet type: %d", type);
1037 packet_read_poll2(u_int32_t *seqnr_p)
1039 static u_int packet_length = 0;
1041 u_char *macbuf, *cp, type;
1042 u_int maclen, block_size;
1047 if (newkeys[MODE_IN] != NULL) {
1048 enc = &newkeys[MODE_IN]->enc;
1049 mac = &newkeys[MODE_IN]->mac;
1050 comp = &newkeys[MODE_IN]->comp;
1052 maclen = mac && mac->enabled ? mac->mac_len : 0;
1053 block_size = enc ? enc->block_size : 8;
1055 if (packet_length == 0) {
1057 * check if input size is less than the cipher block size,
1058 * decrypt first block and extract length of incoming packet
1060 if (buffer_len(&input) < block_size)
1061 return SSH_MSG_NONE;
1062 buffer_clear(&incoming_packet);
1063 cp = buffer_append_space(&incoming_packet, block_size);
1064 cipher_crypt(&receive_context, cp, buffer_ptr(&input),
1066 cp = buffer_ptr(&incoming_packet);
1067 packet_length = get_u32(cp);
1068 if (packet_length < 1 + 4 || packet_length > 256 * 1024) {
1070 buffer_dump(&incoming_packet);
1072 packet_disconnect("Bad packet length %u.", packet_length);
1074 DBG(debug("input: packet len %u", packet_length+4));
1075 buffer_consume(&input, block_size);
1077 /* we have a partial packet of block_size bytes */
1078 need = 4 + packet_length - block_size;
1079 DBG(debug("partial packet %d, need %d, maclen %d", block_size,
1081 if (need % block_size != 0)
1082 fatal("padding error: need %d block %d mod %d",
1083 need, block_size, need % block_size);
1085 * check if the entire packet has been received and
1086 * decrypt into incoming_packet
1088 if (buffer_len(&input) < need + maclen)
1089 return SSH_MSG_NONE;
1091 fprintf(stderr, "read_poll enc/full: ");
1092 buffer_dump(&input);
1094 cp = buffer_append_space(&incoming_packet, need);
1095 cipher_crypt(&receive_context, cp, buffer_ptr(&input), need);
1096 buffer_consume(&input, need);
1098 * compute MAC over seqnr and packet,
1099 * increment sequence number for incoming packet
1101 if (mac && mac->enabled) {
1102 macbuf = mac_compute(mac, p_read.seqnr,
1103 buffer_ptr(&incoming_packet),
1104 buffer_len(&incoming_packet));
1105 if (memcmp(macbuf, buffer_ptr(&input), mac->mac_len) != 0)
1106 packet_disconnect("Corrupted MAC on input.");
1107 DBG(debug("MAC #%d ok", p_read.seqnr));
1108 buffer_consume(&input, mac->mac_len);
1110 if (seqnr_p != NULL)
1111 *seqnr_p = p_read.seqnr;
1112 if (++p_read.seqnr == 0)
1113 logit("incoming seqnr wraps around");
1114 if (++p_read.packets == 0)
1115 if (!(datafellows & SSH_BUG_NOREKEY))
1116 fatal("XXX too many packets with same key");
1117 p_read.blocks += (packet_length + 4) / block_size;
1120 cp = buffer_ptr(&incoming_packet);
1122 DBG(debug("input: padlen %d", padlen));
1124 packet_disconnect("Corrupted padlen %d on input.", padlen);
1126 /* skip packet size + padlen, discard padding */
1127 buffer_consume(&incoming_packet, 4 + 1);
1128 buffer_consume_end(&incoming_packet, padlen);
1130 DBG(debug("input: len before de-compress %d", buffer_len(&incoming_packet)));
1131 if (comp && comp->enabled) {
1132 buffer_clear(&compression_buffer);
1133 buffer_uncompress(&incoming_packet, &compression_buffer);
1134 buffer_clear(&incoming_packet);
1135 buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
1136 buffer_len(&compression_buffer));
1137 DBG(debug("input: len after de-compress %d",
1138 buffer_len(&incoming_packet)));
1141 * get packet type, implies consume.
1142 * return length of payload (without type field)
1144 type = buffer_get_char(&incoming_packet);
1145 if (type < SSH2_MSG_MIN || type >= SSH2_MSG_LOCAL_MIN)
1146 packet_disconnect("Invalid ssh2 packet type: %d", type);
1147 if (type == SSH2_MSG_NEWKEYS)
1148 set_newkeys(MODE_IN);
1149 else if (type == SSH2_MSG_USERAUTH_SUCCESS && !server_side)
1150 packet_enable_delayed_compress();
1152 fprintf(stderr, "read/plain[%d]:\r\n", type);
1153 buffer_dump(&incoming_packet);
1155 /* reset for next packet */
1161 packet_read_poll_seqnr(u_int32_t *seqnr_p)
1163 u_int reason, seqnr;
1169 type = packet_read_poll2(seqnr_p);
1171 DBG(debug("received packet type %d", type));
1173 case SSH2_MSG_IGNORE:
1175 case SSH2_MSG_DEBUG:
1177 msg = packet_get_string(NULL);
1178 debug("Remote: %.900s", msg);
1180 msg = packet_get_string(NULL);
1183 case SSH2_MSG_DISCONNECT:
1184 reason = packet_get_int();
1185 msg = packet_get_string(NULL);
1186 logit("Received disconnect from %s: %u: %.400s",
1187 get_remote_ipaddr(), reason, msg);
1191 case SSH2_MSG_UNIMPLEMENTED:
1192 seqnr = packet_get_int();
1193 debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1200 type = packet_read_poll1();
1202 case SSH_MSG_IGNORE:
1205 msg = packet_get_string(NULL);
1206 debug("Remote: %.900s", msg);
1209 case SSH_MSG_DISCONNECT:
1210 msg = packet_get_string(NULL);
1211 logit("Received disconnect from %s: %.400s",
1212 get_remote_ipaddr(), msg);
1218 DBG(debug("received packet type %d", type));
1226 packet_read_poll(void)
1228 return packet_read_poll_seqnr(NULL);
1232 * Buffers the given amount of input characters. This is intended to be used
1233 * together with packet_read_poll.
1237 packet_process_incoming(const char *buf, u_int len)
1239 buffer_append(&input, buf, len);
1242 /* Returns a character from the packet. */
1245 packet_get_char(void)
1249 buffer_get(&incoming_packet, &ch, 1);
1253 /* Returns an integer from the packet data. */
1256 packet_get_int(void)
1258 return buffer_get_int(&incoming_packet);
1262 * Returns an arbitrary precision integer from the packet data. The integer
1263 * must have been initialized before this call.
1267 packet_get_bignum(BIGNUM * value)
1269 buffer_get_bignum(&incoming_packet, value);
1273 packet_get_bignum2(BIGNUM * value)
1275 buffer_get_bignum2(&incoming_packet, value);
1279 packet_get_raw(u_int *length_ptr)
1281 u_int bytes = buffer_len(&incoming_packet);
1283 if (length_ptr != NULL)
1284 *length_ptr = bytes;
1285 return buffer_ptr(&incoming_packet);
1289 packet_remaining(void)
1291 return buffer_len(&incoming_packet);
1295 * Returns a string from the packet data. The string is allocated using
1296 * xmalloc; it is the responsibility of the calling program to free it when
1297 * no longer needed. The length_ptr argument may be NULL, or point to an
1298 * integer into which the length of the string is stored.
1302 packet_get_string(u_int *length_ptr)
1304 return buffer_get_string(&incoming_packet, length_ptr);
1308 * Sends a diagnostic message from the server to the client. This message
1309 * can be sent at any time (but not while constructing another message). The
1310 * message is printed immediately, but only if the client is being executed
1311 * in verbose mode. These messages are primarily intended to ease debugging
1312 * authentication problems. The length of the formatted message must not
1313 * exceed 1024 bytes. This will automatically call packet_write_wait.
1317 packet_send_debug(const char *fmt,...)
1322 if (compat20 && (datafellows & SSH_BUG_DEBUG))
1325 va_start(args, fmt);
1326 vsnprintf(buf, sizeof(buf), fmt, args);
1330 packet_start(SSH2_MSG_DEBUG);
1331 packet_put_char(0); /* bool: always display */
1332 packet_put_cstring(buf);
1333 packet_put_cstring("");
1335 packet_start(SSH_MSG_DEBUG);
1336 packet_put_cstring(buf);
1339 packet_write_wait();
1343 * Logs the error plus constructs and sends a disconnect packet, closes the
1344 * connection, and exits. This function never returns. The error message
1345 * should not contain a newline. The length of the formatted message must
1346 * not exceed 1024 bytes.
1350 packet_disconnect(const char *fmt,...)
1354 static int disconnecting = 0;
1356 if (disconnecting) /* Guard against recursive invocations. */
1357 fatal("packet_disconnect called recursively.");
1361 * Format the message. Note that the caller must make sure the
1362 * message is of limited size.
1364 va_start(args, fmt);
1365 vsnprintf(buf, sizeof(buf), fmt, args);
1368 /* Display the error locally */
1369 logit("Disconnecting: %.100s", buf);
1371 /* Send the disconnect message to the other side, and wait for it to get sent. */
1373 packet_start(SSH2_MSG_DISCONNECT);
1374 packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1375 packet_put_cstring(buf);
1376 packet_put_cstring("");
1378 packet_start(SSH_MSG_DISCONNECT);
1379 packet_put_cstring(buf);
1382 packet_write_wait();
1384 /* Stop listening for connections. */
1385 channel_close_all();
1387 /* Close the connection. */
1392 /* Checks if there is any buffered output, and tries to write some of the output. */
1395 packet_write_poll(void)
1397 int len = buffer_len(&output);
1400 len = write(connection_out, buffer_ptr(&output), len);
1402 if (errno == EAGAIN)
1405 fatal("Write failed: %.100s", strerror(errno));
1407 buffer_consume(&output, len);
1412 * Calls packet_write_poll repeatedly until all pending output data has been
1417 packet_write_wait(void)
1421 setp = (fd_set *)xcalloc(howmany(connection_out + 1, NFDBITS),
1423 packet_write_poll();
1424 while (packet_have_data_to_write()) {
1425 memset(setp, 0, howmany(connection_out + 1, NFDBITS) *
1427 FD_SET(connection_out, setp);
1428 while (select(connection_out + 1, NULL, setp, NULL, NULL) == -1 &&
1429 (errno == EAGAIN || errno == EINTR))
1431 packet_write_poll();
1436 /* Returns true if there is buffered data to write to the connection. */
1439 packet_have_data_to_write(void)
1441 return buffer_len(&output) != 0;
1444 /* Returns true if there is not too much data to write to the connection. */
1447 packet_not_very_much_data_to_write(void)
1449 if (interactive_mode)
1450 return buffer_len(&output) < 16384;
1452 return buffer_len(&output) < 128 * 1024;
1457 packet_set_tos(int interactive)
1459 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1460 int tos = interactive ? IPTOS_LOWDELAY : IPTOS_THROUGHPUT;
1462 if (!packet_connection_is_on_socket() ||
1463 !packet_connection_is_ipv4())
1465 if (setsockopt(connection_in, IPPROTO_IP, IP_TOS, &tos,
1467 error("setsockopt IP_TOS %d: %.100s:",
1468 tos, strerror(errno));
1472 /* Informs that the current session is interactive. Sets IP flags for that. */
1475 packet_set_interactive(int interactive)
1477 static int called = 0;
1483 /* Record that we are in interactive mode. */
1484 interactive_mode = interactive;
1486 /* Only set socket options if using a socket. */
1487 if (!packet_connection_is_on_socket())
1489 set_nodelay(connection_in);
1490 packet_set_tos(interactive);
1493 /* Returns true if the current connection is interactive. */
1496 packet_is_interactive(void)
1498 return interactive_mode;
1502 packet_set_maxsize(u_int s)
1504 static int called = 0;
1507 logit("packet_set_maxsize: called twice: old %d new %d",
1508 max_packet_size, s);
1511 if (s < 4 * 1024 || s > 1024 * 1024) {
1512 logit("packet_set_maxsize: bad size %d", s);
1516 debug("packet_set_maxsize: setting to %d", s);
1517 max_packet_size = s;
1521 /* roundup current message to pad bytes */
1523 packet_add_padding(u_char pad)
1529 * 9.2. Ignored Data Message
1531 * byte SSH_MSG_IGNORE
1534 * All implementations MUST understand (and ignore) this message at any
1535 * time (after receiving the protocol version). No implementation is
1536 * required to send them. This message can be used as an additional
1537 * protection measure against advanced traffic analysis techniques.
1540 packet_send_ignore(int nbytes)
1545 packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1546 packet_put_int(nbytes);
1547 for (i = 0; i < nbytes; i++) {
1550 packet_put_char((u_char)rnd & 0xff);
1555 #define MAX_PACKETS (1U<<31)
1557 packet_need_rekeying(void)
1559 if (datafellows & SSH_BUG_NOREKEY)
1562 (p_send.packets > MAX_PACKETS) ||
1563 (p_read.packets > MAX_PACKETS) ||
1564 (max_blocks_out && (p_send.blocks > max_blocks_out)) ||
1565 (max_blocks_in && (p_read.blocks > max_blocks_in));
1569 packet_set_rekey_limit(u_int32_t bytes)
1571 rekey_limit = bytes;
1575 packet_set_server(void)
1581 packet_set_authenticated(void)
1583 after_authentication = 1;