2 * Author: Tatu Ylonen <ylo@cs.hut.fi>
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * This file contains code implementing the packet protocol and communication
6 * with the other side. This same code is used both on client and server side.
8 * As far as I am concerned, the code I have written for this software
9 * can be used freely for any purpose. Any derived versions of this
10 * software must be clearly marked as such, and if the derived work is
11 * incompatible with the protocol description in the RFC file, it must be
12 * called by a name other than "ssh" or "Secure Shell".
15 * SSH2 packet format added by Markus Friedl.
16 * Copyright (c) 2000 Markus Friedl. All rights reserved.
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions
21 * 1. Redistributions of source code must retain the above copyright
22 * notice, this list of conditions and the following disclaimer.
23 * 2. Redistributions in binary form must reproduce the above copyright
24 * notice, this list of conditions and the following disclaimer in the
25 * documentation and/or other materials provided with the distribution.
27 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
28 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
29 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
30 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
31 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
32 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
33 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
34 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
35 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
36 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 RCSID("$OpenBSD: packet.c,v 1.42 2001/01/09 21:19:50 markus Exp $");
57 #include <openssl/bn.h>
58 #include <openssl/dh.h>
59 #include <openssl/hmac.h>
72 * This variable contains the file descriptors used for communicating with
73 * the other side. connection_in is used for reading; connection_out for
74 * writing. These can be the same descriptor, in which case it is assumed to
77 static int connection_in = -1;
78 static int connection_out = -1;
81 * Cipher type. This value is only used to determine whether to pad the
82 * packets with zeroes or random data.
84 static int cipher_type = SSH_CIPHER_NONE;
86 /* Protocol flags for the remote side. */
87 static u_int remote_protocol_flags = 0;
89 /* Encryption context for receiving data. This is only used for decryption. */
90 static CipherContext receive_context;
92 /* Encryption context for sending data. This is only used for encryption. */
93 static CipherContext send_context;
95 /* Buffer for raw input data from the socket. */
98 /* Buffer for raw output data going to the socket. */
101 /* Buffer for the partial outgoing packet being constructed. */
102 static Buffer outgoing_packet;
104 /* Buffer for the incoming packet currently being processed. */
105 static Buffer incoming_packet;
107 /* Scratch buffer for packet compression/decompression. */
108 static Buffer compression_buffer;
110 /* Flag indicating whether packet compression/decompression is enabled. */
111 static int packet_compression = 0;
113 /* default maximum packet size */
114 int max_packet_size = 32768;
116 /* Flag indicating whether this module has been initialized. */
117 static int initialized = 0;
119 /* Set to true if the connection is interactive. */
120 static int interactive_mode = 0;
122 /* True if SSH2 packet format is used */
123 int use_ssh2_packet_format = 0;
125 /* Session key information for Encryption and MAC */
129 packet_set_kex(Kex *k)
131 if( k->mac[MODE_IN ].key == NULL ||
132 k->enc[MODE_IN ].key == NULL ||
133 k->enc[MODE_IN ].iv == NULL ||
134 k->mac[MODE_OUT].key == NULL ||
135 k->enc[MODE_OUT].key == NULL ||
136 k->enc[MODE_OUT].iv == NULL)
141 clear_enc_keys(Enc *enc, int len)
143 memset(enc->iv, 0, len);
144 memset(enc->key, 0, len);
151 packet_set_ssh2_format(void)
153 DBG(debug("use_ssh2_packet_format"));
154 use_ssh2_packet_format = 1;
158 * Sets the descriptors used for communication. Disables encryption until
159 * packet_set_encryption_key is called.
162 packet_set_connection(int fd_in, int fd_out)
164 Cipher *none = cipher_by_name("none");
166 fatal("packet_set_connection: cannot load cipher 'none'");
167 connection_in = fd_in;
168 connection_out = fd_out;
169 cipher_type = SSH_CIPHER_NONE;
170 cipher_init(&send_context, none, (u_char *) "", 0, NULL, 0);
171 cipher_init(&receive_context, none, (u_char *) "", 0, NULL, 0);
175 buffer_init(&output);
176 buffer_init(&outgoing_packet);
177 buffer_init(&incoming_packet);
179 /* Kludge: arrange the close function to be called from fatal(). */
180 fatal_add_cleanup((void (*) (void *)) packet_close, NULL);
183 /* Returns 1 if remote host is connected via socket, 0 if not. */
186 packet_connection_is_on_socket()
188 struct sockaddr_storage from, to;
189 socklen_t fromlen, tolen;
191 /* filedescriptors in and out are the same, so it's a socket */
192 if (connection_in == connection_out)
194 fromlen = sizeof(from);
195 memset(&from, 0, sizeof(from));
196 if (getpeername(connection_in, (struct sockaddr *)&from, &fromlen) < 0)
199 memset(&to, 0, sizeof(to));
200 if (getpeername(connection_out, (struct sockaddr *)&to, &tolen) < 0)
202 if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
204 if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
209 /* returns 1 if connection is via ipv4 */
212 packet_connection_is_ipv4()
214 struct sockaddr_storage to;
215 socklen_t tolen = sizeof(to);
217 memset(&to, 0, sizeof(to));
218 if (getsockname(connection_out, (struct sockaddr *)&to, &tolen) < 0)
220 if (to.ss_family != AF_INET)
225 /* Sets the connection into non-blocking mode. */
228 packet_set_nonblocking()
230 /* Set the socket into non-blocking mode. */
231 if (fcntl(connection_in, F_SETFL, O_NONBLOCK) < 0)
232 error("fcntl O_NONBLOCK: %.100s", strerror(errno));
234 if (connection_out != connection_in) {
235 if (fcntl(connection_out, F_SETFL, O_NONBLOCK) < 0)
236 error("fcntl O_NONBLOCK: %.100s", strerror(errno));
240 /* Returns the socket used for reading. */
243 packet_get_connection_in()
245 return connection_in;
248 /* Returns the descriptor used for writing. */
251 packet_get_connection_out()
253 return connection_out;
256 /* Closes the connection and clears and frees internal data structures. */
264 if (connection_in == connection_out) {
265 shutdown(connection_out, SHUT_RDWR);
266 close(connection_out);
268 close(connection_in);
269 close(connection_out);
272 buffer_free(&output);
273 buffer_free(&outgoing_packet);
274 buffer_free(&incoming_packet);
275 if (packet_compression) {
276 buffer_free(&compression_buffer);
277 buffer_compress_uninit();
281 /* Sets remote side protocol flags. */
284 packet_set_protocol_flags(u_int protocol_flags)
286 remote_protocol_flags = protocol_flags;
287 channel_set_options((protocol_flags & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) != 0);
290 /* Returns the remote protocol flags set earlier by the above function. */
293 packet_get_protocol_flags()
295 return remote_protocol_flags;
299 * Starts packet compression from the next packet on in both directions.
300 * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
303 /*** XXXXX todo: kex means re-init */
305 packet_start_compression(int level)
307 if (packet_compression)
308 fatal("Compression already enabled.");
309 packet_compression = 1;
310 buffer_init(&compression_buffer);
311 buffer_compress_init(level);
315 * Encrypts the given number of bytes, copying from src to dest. bytes is
316 * known to be a multiple of 8.
320 packet_encrypt(CipherContext * cc, void *dest, void *src,
323 cipher_encrypt(cc, dest, src, bytes);
327 * Decrypts the given number of bytes, copying from src to dest. bytes is
328 * known to be a multiple of 8.
332 packet_decrypt(CipherContext *context, void *dest, void *src, u_int bytes)
335 * Cryptographic attack detector for ssh - Modifications for packet.c
336 * (C)1998 CORE-SDI, Buenos Aires Argentina Ariel Futoransky(futo@core-sdi.com)
339 context->cipher->number != SSH_CIPHER_NONE &&
340 detect_attack(src, bytes, NULL) == DEATTACK_DETECTED)
341 packet_disconnect("crc32 compensation attack: network attack detected");
343 cipher_decrypt(context, dest, src, bytes);
347 * Causes any further packets to be encrypted using the given key. The same
348 * key is used for both sending and reception. However, both directions are
349 * encrypted independently of each other.
353 packet_set_encryption_key(const u_char *key, u_int keylen,
356 Cipher *cipher = cipher_by_number(number);
358 fatal("packet_set_encryption_key: unknown cipher number %d", number);
360 fatal("packet_set_encryption_key: keylen too small: %d", keylen);
361 cipher_init(&receive_context, cipher, key, keylen, NULL, 0);
362 cipher_init(&send_context, cipher, key, keylen, NULL, 0);
365 /* Starts constructing a packet to send. */
368 packet_start1(int type)
372 buffer_clear(&outgoing_packet);
375 buffer_append(&outgoing_packet, buf, 9);
379 packet_start2(int type)
383 buffer_clear(&outgoing_packet);
384 memset(buf, 0, sizeof buf);
385 /* buf[0..3] = payload_len; */
386 /* buf[4] = pad_len; */
387 buf[5] = type & 0xff;
388 buffer_append(&outgoing_packet, buf, sizeof buf);
392 packet_start(int type)
394 DBG(debug("packet_start[%d]",type));
395 if (use_ssh2_packet_format)
401 /* Appends a character to the packet data. */
404 packet_put_char(int value)
407 buffer_append(&outgoing_packet, &ch, 1);
410 /* Appends an integer to the packet data. */
413 packet_put_int(u_int value)
415 buffer_put_int(&outgoing_packet, value);
418 /* Appends a string to packet data. */
421 packet_put_string(const char *buf, u_int len)
423 buffer_put_string(&outgoing_packet, buf, len);
426 packet_put_cstring(const char *str)
428 buffer_put_string(&outgoing_packet, str, strlen(str));
432 packet_put_raw(const char *buf, u_int len)
434 buffer_append(&outgoing_packet, buf, len);
438 /* Appends an arbitrary precision integer to packet data. */
441 packet_put_bignum(BIGNUM * value)
443 buffer_put_bignum(&outgoing_packet, value);
446 packet_put_bignum2(BIGNUM * value)
448 buffer_put_bignum2(&outgoing_packet, value);
452 * Finalizes and sends the packet. If the encryption key has been set,
453 * encrypts the packet before sending.
465 * If using packet compression, compress the payload of the outgoing
468 if (packet_compression) {
469 buffer_clear(&compression_buffer);
471 buffer_consume(&outgoing_packet, 8);
473 buffer_append(&compression_buffer, "\0\0\0\0\0\0\0\0", 8);
474 buffer_compress(&outgoing_packet, &compression_buffer);
475 buffer_clear(&outgoing_packet);
476 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
477 buffer_len(&compression_buffer));
479 /* Compute packet length without padding (add checksum, remove padding). */
480 len = buffer_len(&outgoing_packet) + 4 - 8;
482 /* Insert padding. Initialized to zero in packet_start1() */
483 padding = 8 - len % 8;
484 if (cipher_type != SSH_CIPHER_NONE) {
485 cp = buffer_ptr(&outgoing_packet);
486 for (i = 0; i < padding; i++) {
489 cp[7 - i] = rand & 0xff;
493 buffer_consume(&outgoing_packet, 8 - padding);
495 /* Add check bytes. */
496 checksum = ssh_crc32((u_char *) buffer_ptr(&outgoing_packet),
497 buffer_len(&outgoing_packet));
498 PUT_32BIT(buf, checksum);
499 buffer_append(&outgoing_packet, buf, 4);
502 fprintf(stderr, "packet_send plain: ");
503 buffer_dump(&outgoing_packet);
506 /* Append to output. */
508 buffer_append(&output, buf, 4);
509 buffer_append_space(&output, &cp, buffer_len(&outgoing_packet));
510 packet_encrypt(&send_context, cp, buffer_ptr(&outgoing_packet),
511 buffer_len(&outgoing_packet));
514 fprintf(stderr, "encrypted: ");
515 buffer_dump(&output);
518 buffer_clear(&outgoing_packet);
521 * Note that the packet is now only buffered in output. It won\'t be
522 * actually sent until packet_write_wait or packet_write_poll is
528 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
533 u_char *macbuf = NULL;
535 u_int packet_length = 0;
536 u_int i, padlen, len;
538 static u_int seqnr = 0;
546 enc = &kex->enc[MODE_OUT];
547 mac = &kex->mac[MODE_OUT];
548 comp = &kex->comp[MODE_OUT];
550 block_size = enc ? enc->cipher->block_size : 8;
552 cp = buffer_ptr(&outgoing_packet);
556 fprintf(stderr, "plain: ");
557 buffer_dump(&outgoing_packet);
560 if (comp && comp->enabled) {
561 len = buffer_len(&outgoing_packet);
562 /* skip header, compress only payload */
563 buffer_consume(&outgoing_packet, 5);
564 buffer_clear(&compression_buffer);
565 buffer_compress(&outgoing_packet, &compression_buffer);
566 buffer_clear(&outgoing_packet);
567 buffer_append(&outgoing_packet, "\0\0\0\0\0", 5);
568 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
569 buffer_len(&compression_buffer));
570 DBG(debug("compression: raw %d compressed %d", len,
571 buffer_len(&outgoing_packet)));
574 /* sizeof (packet_len + pad_len + payload) */
575 len = buffer_len(&outgoing_packet);
578 * calc size of padding, alloc space, get random data,
579 * minimum padding is 4 bytes
581 padlen = block_size - (len % block_size);
583 padlen += block_size;
584 buffer_append_space(&outgoing_packet, &cp, padlen);
585 if (enc && enc->cipher->number != SSH_CIPHER_NONE) {
587 for (i = 0; i < padlen; i++) {
595 memset(cp, 0, padlen);
597 /* packet_length includes payload, padding and padding length field */
598 packet_length = buffer_len(&outgoing_packet) - 4;
599 cp = buffer_ptr(&outgoing_packet);
600 PUT_32BIT(cp, packet_length);
601 cp[4] = padlen & 0xff;
602 DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen));
604 /* compute MAC over seqnr and packet(length fields, payload, padding) */
605 if (mac && mac->enabled) {
606 macbuf = hmac( mac->md, seqnr,
607 (u_char *) buffer_ptr(&outgoing_packet),
608 buffer_len(&outgoing_packet),
609 mac->key, mac->key_len
611 DBG(debug("done calc MAC out #%d", seqnr));
613 /* encrypt packet and append to output buffer. */
614 buffer_append_space(&output, &cp, buffer_len(&outgoing_packet));
615 packet_encrypt(&send_context, cp, buffer_ptr(&outgoing_packet),
616 buffer_len(&outgoing_packet));
617 /* append unencrypted MAC */
618 if (mac && mac->enabled)
619 buffer_append(&output, (char *)macbuf, mac->mac_len);
621 fprintf(stderr, "encrypted: ");
622 buffer_dump(&output);
624 /* increment sequence number for outgoing packets */
626 log("outgoing seqnr wraps around");
627 buffer_clear(&outgoing_packet);
629 if (type == SSH2_MSG_NEWKEYS) {
630 if (kex==NULL || mac==NULL || enc==NULL || comp==NULL)
631 fatal("packet_send2: no KEX");
634 DBG(debug("cipher_init send_context"));
635 cipher_init(&send_context, enc->cipher,
636 enc->key, enc->cipher->key_len,
637 enc->iv, enc->cipher->block_size);
638 clear_enc_keys(enc, kex->we_need);
639 if (comp->type != 0 && comp->enabled == 0) {
641 if (! packet_compression)
642 packet_start_compression(6);
650 if (use_ssh2_packet_format)
654 DBG(debug("packet_send done"));
658 * Waits until a packet has been received, and returns its type. Note that
659 * no other data is processed until this returns, so this function should not
660 * be used during the interactive session.
664 packet_read(int *payload_len_ptr)
669 DBG(debug("packet_read()"));
671 /* Since we are blocking, ensure that all written packets have been sent. */
674 /* Stay in the loop until we have received a complete packet. */
676 /* Try to read a packet from the buffer. */
677 type = packet_read_poll(payload_len_ptr);
678 if (!use_ssh2_packet_format && (
679 type == SSH_SMSG_SUCCESS
680 || type == SSH_SMSG_FAILURE
681 || type == SSH_CMSG_EOF
682 || type == SSH_CMSG_EXIT_CONFIRMATION))
683 packet_integrity_check(*payload_len_ptr, 0, type);
684 /* If we got a packet, return it. */
685 if (type != SSH_MSG_NONE)
688 * Otherwise, wait for some data to arrive, add it to the
689 * buffer, and try again.
692 FD_SET(connection_in, &set);
694 /* Wait for some data to arrive. */
695 select(connection_in + 1, &set, NULL, NULL, NULL);
697 /* Read data from the socket. */
698 len = read(connection_in, buf, sizeof(buf));
700 log("Connection closed by %.200s", get_remote_ipaddr());
704 fatal("Read from socket failed: %.100s", strerror(errno));
705 /* Append it to the buffer. */
706 packet_process_incoming(buf, len);
712 * Waits until a packet has been received, verifies that its type matches
713 * that given, and gives a fatal error and exits if there is a mismatch.
717 packet_read_expect(int *payload_len_ptr, int expected_type)
721 type = packet_read(payload_len_ptr);
722 if (type != expected_type)
723 packet_disconnect("Protocol error: expected packet type %d, got %d",
724 expected_type, type);
727 /* Checks if a full packet is available in the data received so far via
728 * packet_process_incoming. If so, reads the packet; otherwise returns
729 * SSH_MSG_NONE. This does not wait for data from the connection.
731 * SSH_MSG_DISCONNECT is handled specially here. Also,
732 * SSH_MSG_IGNORE messages are skipped by this function and are never returned
735 * The returned payload_len does include space consumed by:
743 packet_read_poll1(int *payload_len_ptr)
745 u_int len, padded_len;
748 u_int checksum, stored_checksum;
750 /* Check if input size is less than minimum packet size. */
751 if (buffer_len(&input) < 4 + 8)
753 /* Get length of incoming packet. */
754 ucp = (u_char *) buffer_ptr(&input);
755 len = GET_32BIT(ucp);
756 if (len < 1 + 2 + 2 || len > 256 * 1024)
757 packet_disconnect("Bad packet length %d.", len);
758 padded_len = (len + 8) & ~7;
760 /* Check if the packet has been entirely received. */
761 if (buffer_len(&input) < 4 + padded_len)
764 /* The entire packet is in buffer. */
766 /* Consume packet length. */
767 buffer_consume(&input, 4);
769 /* Copy data to incoming_packet. */
770 buffer_clear(&incoming_packet);
771 buffer_append_space(&incoming_packet, &cp, padded_len);
772 packet_decrypt(&receive_context, cp, buffer_ptr(&input), padded_len);
773 buffer_consume(&input, padded_len);
776 fprintf(stderr, "read_poll plain: ");
777 buffer_dump(&incoming_packet);
780 /* Compute packet checksum. */
781 checksum = ssh_crc32((u_char *) buffer_ptr(&incoming_packet),
782 buffer_len(&incoming_packet) - 4);
785 buffer_consume(&incoming_packet, 8 - len % 8);
787 /* Test check bytes. */
789 if (len != buffer_len(&incoming_packet))
790 packet_disconnect("packet_read_poll: len %d != buffer_len %d.",
791 len, buffer_len(&incoming_packet));
793 ucp = (u_char *) buffer_ptr(&incoming_packet) + len - 4;
794 stored_checksum = GET_32BIT(ucp);
795 if (checksum != stored_checksum)
796 packet_disconnect("Corrupted check bytes on input.");
797 buffer_consume_end(&incoming_packet, 4);
799 /* If using packet compression, decompress the packet. */
800 if (packet_compression) {
801 buffer_clear(&compression_buffer);
802 buffer_uncompress(&incoming_packet, &compression_buffer);
803 buffer_clear(&incoming_packet);
804 buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
805 buffer_len(&compression_buffer));
807 /* Get packet type. */
808 buffer_get(&incoming_packet, &buf[0], 1);
810 /* Return length of payload (without type field). */
811 *payload_len_ptr = buffer_len(&incoming_packet);
814 return (u_char) buf[0];
818 packet_read_poll2(int *payload_len_ptr)
821 u_char buf[8], *macbuf;
824 static u_int packet_length = 0;
825 static u_int seqnr = 0;
827 int maclen, block_size;
833 enc = &kex->enc[MODE_IN];
834 mac = &kex->mac[MODE_IN];
835 comp = &kex->comp[MODE_IN];
837 maclen = mac && mac->enabled ? mac->mac_len : 0;
838 block_size = enc ? enc->cipher->block_size : 8;
840 if (packet_length == 0) {
842 * check if input size is less than the cipher block size,
843 * decrypt first block and extract length of incoming packet
845 if (buffer_len(&input) < block_size)
847 buffer_clear(&incoming_packet);
848 buffer_append_space(&incoming_packet, &cp, block_size);
849 packet_decrypt(&receive_context, cp, buffer_ptr(&input),
851 ucp = (u_char *) buffer_ptr(&incoming_packet);
852 packet_length = GET_32BIT(ucp);
853 if (packet_length < 1 + 4 || packet_length > 256 * 1024) {
854 buffer_dump(&incoming_packet);
855 packet_disconnect("Bad packet length %d.", packet_length);
857 DBG(debug("input: packet len %d", packet_length+4));
858 buffer_consume(&input, block_size);
860 /* we have a partial packet of block_size bytes */
861 need = 4 + packet_length - block_size;
862 DBG(debug("partial packet %d, need %d, maclen %d", block_size,
864 if (need % block_size != 0)
865 fatal("padding error: need %d block %d mod %d",
866 need, block_size, need % block_size);
868 * check if the entire packet has been received and
869 * decrypt into incoming_packet
871 if (buffer_len(&input) < need + maclen)
874 fprintf(stderr, "read_poll enc/full: ");
877 buffer_append_space(&incoming_packet, &cp, need);
878 packet_decrypt(&receive_context, cp, buffer_ptr(&input), need);
879 buffer_consume(&input, need);
881 * compute MAC over seqnr and packet,
882 * increment sequence number for incoming packet
884 if (mac && mac->enabled) {
885 macbuf = hmac( mac->md, seqnr,
886 (u_char *) buffer_ptr(&incoming_packet),
887 buffer_len(&incoming_packet),
888 mac->key, mac->key_len
890 if (memcmp(macbuf, buffer_ptr(&input), mac->mac_len) != 0)
891 packet_disconnect("Corrupted MAC on input.");
892 DBG(debug("MAC #%d ok", seqnr));
893 buffer_consume(&input, mac->mac_len);
896 log("incoming seqnr wraps around");
899 cp = buffer_ptr(&incoming_packet) + 4;
901 DBG(debug("input: padlen %d", padlen));
903 packet_disconnect("Corrupted padlen %d on input.", padlen);
905 /* skip packet size + padlen, discard padding */
906 buffer_consume(&incoming_packet, 4 + 1);
907 buffer_consume_end(&incoming_packet, padlen);
909 DBG(debug("input: len before de-compress %d", buffer_len(&incoming_packet)));
910 if (comp && comp->enabled) {
911 buffer_clear(&compression_buffer);
912 buffer_uncompress(&incoming_packet, &compression_buffer);
913 buffer_clear(&incoming_packet);
914 buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
915 buffer_len(&compression_buffer));
916 DBG(debug("input: len after de-compress %d", buffer_len(&incoming_packet)));
919 * get packet type, implies consume.
920 * return length of payload (without type field)
922 buffer_get(&incoming_packet, (char *)&buf[0], 1);
923 *payload_len_ptr = buffer_len(&incoming_packet);
925 /* reset for next packet */
928 /* extract packet type */
929 type = (u_char)buf[0];
931 if (type == SSH2_MSG_NEWKEYS) {
932 if (kex==NULL || mac==NULL || enc==NULL || comp==NULL)
933 fatal("packet_read_poll2: no KEX");
936 DBG(debug("cipher_init receive_context"));
937 cipher_init(&receive_context, enc->cipher,
938 enc->key, enc->cipher->key_len,
939 enc->iv, enc->cipher->block_size);
940 clear_enc_keys(enc, kex->we_need);
941 if (comp->type != 0 && comp->enabled == 0) {
943 if (! packet_compression)
944 packet_start_compression(6);
949 fprintf(stderr, "read/plain[%d]:\r\n",type);
950 buffer_dump(&incoming_packet);
956 packet_read_poll(int *payload_len_ptr)
960 int type = use_ssh2_packet_format ?
961 packet_read_poll2(payload_len_ptr):
962 packet_read_poll1(payload_len_ptr);
967 DBG(debug("received packet type %d", type));
969 case SSH2_MSG_IGNORE:
973 msg = packet_get_string(NULL);
974 debug("Remote: %.900s", msg);
976 msg = packet_get_string(NULL);
979 case SSH2_MSG_DISCONNECT:
980 reason = packet_get_int();
981 msg = packet_get_string(NULL);
982 log("Received disconnect from %s: %d: %.400s", get_remote_ipaddr(),
996 msg = packet_get_string(NULL);
997 debug("Remote: %.900s", msg);
1000 case SSH_MSG_DISCONNECT:
1001 msg = packet_get_string(NULL);
1002 log("Received disconnect from %s: %.400s", get_remote_ipaddr(),
1009 DBG(debug("received packet type %d", type));
1018 * Buffers the given amount of input characters. This is intended to be used
1019 * together with packet_read_poll.
1023 packet_process_incoming(const char *buf, u_int len)
1025 buffer_append(&input, buf, len);
1028 /* Returns a character from the packet. */
1034 buffer_get(&incoming_packet, &ch, 1);
1038 /* Returns an integer from the packet data. */
1043 return buffer_get_int(&incoming_packet);
1047 * Returns an arbitrary precision integer from the packet data. The integer
1048 * must have been initialized before this call.
1052 packet_get_bignum(BIGNUM * value, int *length_ptr)
1054 *length_ptr = buffer_get_bignum(&incoming_packet, value);
1058 packet_get_bignum2(BIGNUM * value, int *length_ptr)
1060 *length_ptr = buffer_get_bignum2(&incoming_packet, value);
1064 packet_get_raw(int *length_ptr)
1066 int bytes = buffer_len(&incoming_packet);
1067 if (length_ptr != NULL)
1068 *length_ptr = bytes;
1069 return buffer_ptr(&incoming_packet);
1073 packet_remaining(void)
1075 return buffer_len(&incoming_packet);
1079 * Returns a string from the packet data. The string is allocated using
1080 * xmalloc; it is the responsibility of the calling program to free it when
1081 * no longer needed. The length_ptr argument may be NULL, or point to an
1082 * integer into which the length of the string is stored.
1086 packet_get_string(u_int *length_ptr)
1088 return buffer_get_string(&incoming_packet, length_ptr);
1092 * Sends a diagnostic message from the server to the client. This message
1093 * can be sent at any time (but not while constructing another message). The
1094 * message is printed immediately, but only if the client is being executed
1095 * in verbose mode. These messages are primarily intended to ease debugging
1096 * authentication problems. The length of the formatted message must not
1097 * exceed 1024 bytes. This will automatically call packet_write_wait.
1101 packet_send_debug(const char *fmt,...)
1106 if (compat20 && (datafellows & SSH_BUG_DEBUG))
1109 va_start(args, fmt);
1110 vsnprintf(buf, sizeof(buf), fmt, args);
1114 packet_start(SSH2_MSG_DEBUG);
1115 packet_put_char(0); /* bool: always display */
1116 packet_put_cstring(buf);
1117 packet_put_cstring("");
1119 packet_start(SSH_MSG_DEBUG);
1120 packet_put_cstring(buf);
1123 packet_write_wait();
1127 * Logs the error plus constructs and sends a disconnect packet, closes the
1128 * connection, and exits. This function never returns. The error message
1129 * should not contain a newline. The length of the formatted message must
1130 * not exceed 1024 bytes.
1134 packet_disconnect(const char *fmt,...)
1138 static int disconnecting = 0;
1139 if (disconnecting) /* Guard against recursive invocations. */
1140 fatal("packet_disconnect called recursively.");
1144 * Format the message. Note that the caller must make sure the
1145 * message is of limited size.
1147 va_start(args, fmt);
1148 vsnprintf(buf, sizeof(buf), fmt, args);
1151 /* Send the disconnect message to the other side, and wait for it to get sent. */
1153 packet_start(SSH2_MSG_DISCONNECT);
1154 packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1155 packet_put_cstring(buf);
1156 packet_put_cstring("");
1158 packet_start(SSH_MSG_DISCONNECT);
1159 packet_put_string(buf, strlen(buf));
1162 packet_write_wait();
1164 /* Stop listening for connections. */
1165 channel_stop_listening();
1167 /* Close the connection. */
1170 /* Display the error locally and exit. */
1171 log("Disconnecting: %.100s", buf);
1175 /* Checks if there is any buffered output, and tries to write some of the output. */
1180 int len = buffer_len(&output);
1182 len = write(connection_out, buffer_ptr(&output), len);
1184 if (errno == EAGAIN)
1187 fatal("Write failed: %.100s", strerror(errno));
1189 buffer_consume(&output, len);
1194 * Calls packet_write_poll repeatedly until all pending output data has been
1201 packet_write_poll();
1202 while (packet_have_data_to_write()) {
1205 FD_SET(connection_out, &set);
1206 select(connection_out + 1, NULL, &set, NULL, NULL);
1207 packet_write_poll();
1211 /* Returns true if there is buffered data to write to the connection. */
1214 packet_have_data_to_write()
1216 return buffer_len(&output) != 0;
1219 /* Returns true if there is not too much data to write to the connection. */
1222 packet_not_very_much_data_to_write()
1224 if (interactive_mode)
1225 return buffer_len(&output) < 16384;
1227 return buffer_len(&output) < 128 * 1024;
1230 /* Informs that the current session is interactive. Sets IP flags for that. */
1233 packet_set_interactive(int interactive, int keepalives)
1237 /* Record that we are in interactive mode. */
1238 interactive_mode = interactive;
1240 /* Only set socket options if using a socket. */
1241 if (!packet_connection_is_on_socket())
1244 /* Set keepalives if requested. */
1245 if (setsockopt(connection_in, SOL_SOCKET, SO_KEEPALIVE, (void *) &on,
1247 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1250 * IPTOS_LOWDELAY and IPTOS_THROUGHPUT are IPv4 only
1254 * Set IP options for an interactive connection. Use
1255 * IPTOS_LOWDELAY and TCP_NODELAY.
1257 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1258 if (packet_connection_is_ipv4()) {
1259 int lowdelay = IPTOS_LOWDELAY;
1260 if (setsockopt(connection_in, IPPROTO_IP, IP_TOS,
1261 (void *) &lowdelay, sizeof(lowdelay)) < 0)
1262 error("setsockopt IPTOS_LOWDELAY: %.100s",
1266 if (setsockopt(connection_in, IPPROTO_TCP, TCP_NODELAY, (void *) &on,
1268 error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
1269 } else if (packet_connection_is_ipv4()) {
1271 * Set IP options for a non-interactive connection. Use
1274 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1275 int throughput = IPTOS_THROUGHPUT;
1276 if (setsockopt(connection_in, IPPROTO_IP, IP_TOS, (void *) &throughput,
1277 sizeof(throughput)) < 0)
1278 error("setsockopt IPTOS_THROUGHPUT: %.100s", strerror(errno));
1283 /* Returns true if the current connection is interactive. */
1286 packet_is_interactive()
1288 return interactive_mode;
1292 packet_set_maxsize(int s)
1294 static int called = 0;
1296 log("packet_set_maxsize: called twice: old %d new %d",
1297 max_packet_size, s);
1300 if (s < 4 * 1024 || s > 1024 * 1024) {
1301 log("packet_set_maxsize: bad size %d", s);
1304 log("packet_set_maxsize: setting to %d", s);
1305 max_packet_size = s;