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.49 2001/02/08 19:30:52 itojun Exp $");
57 #include <openssl/bn.h>
58 #include <openssl/dh.h>
59 #include <openssl/hmac.h>
73 * This variable contains the file descriptors used for communicating with
74 * the other side. connection_in is used for reading; connection_out for
75 * writing. These can be the same descriptor, in which case it is assumed to
78 static int connection_in = -1;
79 static int connection_out = -1;
82 * Cipher type. This value is only used to determine whether to pad the
83 * packets with zeroes or random data.
85 static int cipher_type = SSH_CIPHER_NONE;
87 /* Protocol flags for the remote side. */
88 static u_int remote_protocol_flags = 0;
90 /* Encryption context for receiving data. This is only used for decryption. */
91 static CipherContext receive_context;
93 /* Encryption context for sending data. This is only used for encryption. */
94 static CipherContext send_context;
96 /* Buffer for raw input data from the socket. */
99 /* Buffer for raw output data going to the socket. */
100 static Buffer output;
102 /* Buffer for the partial outgoing packet being constructed. */
103 static Buffer outgoing_packet;
105 /* Buffer for the incoming packet currently being processed. */
106 static Buffer incoming_packet;
108 /* Scratch buffer for packet compression/decompression. */
109 static Buffer compression_buffer;
111 /* Flag indicating whether packet compression/decompression is enabled. */
112 static int packet_compression = 0;
114 /* default maximum packet size */
115 int max_packet_size = 32768;
117 /* Flag indicating whether this module has been initialized. */
118 static int initialized = 0;
120 /* Set to true if the connection is interactive. */
121 static int interactive_mode = 0;
123 /* True if SSH2 packet format is used */
124 int use_ssh2_packet_format = 0;
126 /* Session key information for Encryption and MAC */
130 packet_set_kex(Kex *k)
132 if( k->mac[MODE_IN ].key == NULL ||
133 k->enc[MODE_IN ].key == NULL ||
134 k->enc[MODE_IN ].iv == NULL ||
135 k->mac[MODE_OUT].key == NULL ||
136 k->enc[MODE_OUT].key == NULL ||
137 k->enc[MODE_OUT].iv == NULL)
142 clear_enc_keys(Enc *enc, int len)
144 memset(enc->iv, 0, len);
145 memset(enc->key, 0, len);
152 packet_set_ssh2_format(void)
154 DBG(debug("use_ssh2_packet_format"));
155 use_ssh2_packet_format = 1;
159 * Sets the descriptors used for communication. Disables encryption until
160 * packet_set_encryption_key is called.
163 packet_set_connection(int fd_in, int fd_out)
165 Cipher *none = cipher_by_name("none");
167 fatal("packet_set_connection: cannot load cipher 'none'");
168 connection_in = fd_in;
169 connection_out = fd_out;
170 cipher_type = SSH_CIPHER_NONE;
171 cipher_init(&send_context, none, (u_char *) "", 0, NULL, 0);
172 cipher_init(&receive_context, none, (u_char *) "", 0, NULL, 0);
176 buffer_init(&output);
177 buffer_init(&outgoing_packet);
178 buffer_init(&incoming_packet);
180 /* Kludge: arrange the close function to be called from fatal(). */
181 fatal_add_cleanup((void (*) (void *)) packet_close, NULL);
184 /* Returns 1 if remote host is connected via socket, 0 if not. */
187 packet_connection_is_on_socket()
189 struct sockaddr_storage from, to;
190 socklen_t fromlen, tolen;
192 /* filedescriptors in and out are the same, so it's a socket */
193 if (connection_in == connection_out)
195 fromlen = sizeof(from);
196 memset(&from, 0, sizeof(from));
197 if (getpeername(connection_in, (struct sockaddr *)&from, &fromlen) < 0)
200 memset(&to, 0, sizeof(to));
201 if (getpeername(connection_out, (struct sockaddr *)&to, &tolen) < 0)
203 if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
205 if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
210 /* returns 1 if connection is via ipv4 */
213 packet_connection_is_ipv4()
215 struct sockaddr_storage to;
216 socklen_t tolen = sizeof(to);
218 memset(&to, 0, sizeof(to));
219 if (getsockname(connection_out, (struct sockaddr *)&to, &tolen) < 0)
221 if (to.ss_family != AF_INET)
226 /* Sets the connection into non-blocking mode. */
229 packet_set_nonblocking()
231 /* Set the socket into non-blocking mode. */
232 if (fcntl(connection_in, F_SETFL, O_NONBLOCK) < 0)
233 error("fcntl O_NONBLOCK: %.100s", strerror(errno));
235 if (connection_out != connection_in) {
236 if (fcntl(connection_out, F_SETFL, O_NONBLOCK) < 0)
237 error("fcntl O_NONBLOCK: %.100s", strerror(errno));
241 /* Returns the socket used for reading. */
244 packet_get_connection_in()
246 return connection_in;
249 /* Returns the descriptor used for writing. */
252 packet_get_connection_out()
254 return connection_out;
257 /* Closes the connection and clears and frees internal data structures. */
265 if (connection_in == connection_out) {
266 shutdown(connection_out, SHUT_RDWR);
267 close(connection_out);
269 close(connection_in);
270 close(connection_out);
273 buffer_free(&output);
274 buffer_free(&outgoing_packet);
275 buffer_free(&incoming_packet);
276 if (packet_compression) {
277 buffer_free(&compression_buffer);
278 buffer_compress_uninit();
282 /* Sets remote side protocol flags. */
285 packet_set_protocol_flags(u_int protocol_flags)
287 remote_protocol_flags = protocol_flags;
288 channel_set_options((protocol_flags & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) != 0);
291 /* Returns the remote protocol flags set earlier by the above function. */
294 packet_get_protocol_flags()
296 return remote_protocol_flags;
300 * Starts packet compression from the next packet on in both directions.
301 * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
304 /*** XXXXX todo: kex means re-init */
306 packet_start_compression(int level)
308 if (packet_compression)
309 fatal("Compression already enabled.");
310 packet_compression = 1;
311 buffer_init(&compression_buffer);
312 buffer_compress_init(level);
316 * Encrypts the given number of bytes, copying from src to dest. bytes is
317 * known to be a multiple of 8.
321 packet_encrypt(CipherContext * cc, void *dest, void *src,
324 cipher_encrypt(cc, dest, src, bytes);
328 * Decrypts the given number of bytes, copying from src to dest. bytes is
329 * known to be a multiple of 8.
333 packet_decrypt(CipherContext *context, void *dest, void *src, u_int bytes)
336 * Cryptographic attack detector for ssh - Modifications for packet.c
337 * (C)1998 CORE-SDI, Buenos Aires Argentina Ariel Futoransky(futo@core-sdi.com)
340 context->cipher->number != SSH_CIPHER_NONE &&
341 detect_attack(src, bytes, NULL) == DEATTACK_DETECTED)
342 packet_disconnect("crc32 compensation attack: network attack detected");
344 cipher_decrypt(context, dest, src, bytes);
348 * Causes any further packets to be encrypted using the given key. The same
349 * key is used for both sending and reception. However, both directions are
350 * encrypted independently of each other.
354 packet_set_encryption_key(const u_char *key, u_int keylen,
357 Cipher *cipher = cipher_by_number(number);
359 fatal("packet_set_encryption_key: unknown cipher number %d", number);
361 fatal("packet_set_encryption_key: keylen too small: %d", keylen);
362 cipher_init(&receive_context, cipher, key, keylen, NULL, 0);
363 cipher_init(&send_context, cipher, key, keylen, NULL, 0);
366 /* Starts constructing a packet to send. */
369 packet_start1(int type)
373 buffer_clear(&outgoing_packet);
376 buffer_append(&outgoing_packet, buf, 9);
380 packet_start2(int type)
384 buffer_clear(&outgoing_packet);
385 memset(buf, 0, sizeof buf);
386 /* buf[0..3] = payload_len; */
387 /* buf[4] = pad_len; */
388 buf[5] = type & 0xff;
389 buffer_append(&outgoing_packet, buf, sizeof buf);
393 packet_start(int type)
395 DBG(debug("packet_start[%d]",type));
396 if (use_ssh2_packet_format)
402 /* Appends a character to the packet data. */
405 packet_put_char(int value)
408 buffer_append(&outgoing_packet, &ch, 1);
411 /* Appends an integer to the packet data. */
414 packet_put_int(u_int value)
416 buffer_put_int(&outgoing_packet, value);
419 /* Appends a string to packet data. */
422 packet_put_string(const char *buf, u_int len)
424 buffer_put_string(&outgoing_packet, buf, len);
427 packet_put_cstring(const char *str)
429 buffer_put_string(&outgoing_packet, str, strlen(str));
433 packet_put_raw(const char *buf, u_int len)
435 buffer_append(&outgoing_packet, buf, len);
439 /* Appends an arbitrary precision integer to packet data. */
442 packet_put_bignum(BIGNUM * value)
444 buffer_put_bignum(&outgoing_packet, value);
447 packet_put_bignum2(BIGNUM * value)
449 buffer_put_bignum2(&outgoing_packet, value);
453 * Finalizes and sends the packet. If the encryption key has been set,
454 * encrypts the packet before sending.
466 * If using packet compression, compress the payload of the outgoing
469 if (packet_compression) {
470 buffer_clear(&compression_buffer);
472 buffer_consume(&outgoing_packet, 8);
474 buffer_append(&compression_buffer, "\0\0\0\0\0\0\0\0", 8);
475 buffer_compress(&outgoing_packet, &compression_buffer);
476 buffer_clear(&outgoing_packet);
477 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
478 buffer_len(&compression_buffer));
480 /* Compute packet length without padding (add checksum, remove padding). */
481 len = buffer_len(&outgoing_packet) + 4 - 8;
483 /* Insert padding. Initialized to zero in packet_start1() */
484 padding = 8 - len % 8;
485 if (cipher_type != SSH_CIPHER_NONE) {
486 cp = buffer_ptr(&outgoing_packet);
487 for (i = 0; i < padding; i++) {
490 cp[7 - i] = rand & 0xff;
494 buffer_consume(&outgoing_packet, 8 - padding);
496 /* Add check bytes. */
497 checksum = ssh_crc32((u_char *) buffer_ptr(&outgoing_packet),
498 buffer_len(&outgoing_packet));
499 PUT_32BIT(buf, checksum);
500 buffer_append(&outgoing_packet, buf, 4);
503 fprintf(stderr, "packet_send plain: ");
504 buffer_dump(&outgoing_packet);
507 /* Append to output. */
509 buffer_append(&output, buf, 4);
510 buffer_append_space(&output, &cp, buffer_len(&outgoing_packet));
511 packet_encrypt(&send_context, cp, buffer_ptr(&outgoing_packet),
512 buffer_len(&outgoing_packet));
515 fprintf(stderr, "encrypted: ");
516 buffer_dump(&output);
519 buffer_clear(&outgoing_packet);
522 * Note that the packet is now only buffered in output. It won\'t be
523 * actually sent until packet_write_wait or packet_write_poll is
529 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
534 u_char *macbuf = NULL;
536 u_int packet_length = 0;
537 u_int i, padlen, len;
539 static u_int seqnr = 0;
547 enc = &kex->enc[MODE_OUT];
548 mac = &kex->mac[MODE_OUT];
549 comp = &kex->comp[MODE_OUT];
551 block_size = enc ? enc->cipher->block_size : 8;
553 cp = buffer_ptr(&outgoing_packet);
557 fprintf(stderr, "plain: ");
558 buffer_dump(&outgoing_packet);
561 if (comp && comp->enabled) {
562 len = buffer_len(&outgoing_packet);
563 /* skip header, compress only payload */
564 buffer_consume(&outgoing_packet, 5);
565 buffer_clear(&compression_buffer);
566 buffer_compress(&outgoing_packet, &compression_buffer);
567 buffer_clear(&outgoing_packet);
568 buffer_append(&outgoing_packet, "\0\0\0\0\0", 5);
569 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
570 buffer_len(&compression_buffer));
571 DBG(debug("compression: raw %d compressed %d", len,
572 buffer_len(&outgoing_packet)));
575 /* sizeof (packet_len + pad_len + payload) */
576 len = buffer_len(&outgoing_packet);
579 * calc size of padding, alloc space, get random data,
580 * minimum padding is 4 bytes
582 padlen = block_size - (len % block_size);
584 padlen += block_size;
585 buffer_append_space(&outgoing_packet, &cp, padlen);
586 if (enc && enc->cipher->number != SSH_CIPHER_NONE) {
588 for (i = 0; i < padlen; i++) {
596 memset(cp, 0, padlen);
598 /* packet_length includes payload, padding and padding length field */
599 packet_length = buffer_len(&outgoing_packet) - 4;
600 cp = buffer_ptr(&outgoing_packet);
601 PUT_32BIT(cp, packet_length);
602 cp[4] = padlen & 0xff;
603 DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen));
605 /* compute MAC over seqnr and packet(length fields, payload, padding) */
606 if (mac && mac->enabled) {
607 macbuf = hmac( mac->md, seqnr,
608 (u_char *) buffer_ptr(&outgoing_packet),
609 buffer_len(&outgoing_packet),
610 mac->key, mac->key_len
612 DBG(debug("done calc MAC out #%d", seqnr));
614 /* encrypt packet and append to output buffer. */
615 buffer_append_space(&output, &cp, buffer_len(&outgoing_packet));
616 packet_encrypt(&send_context, cp, buffer_ptr(&outgoing_packet),
617 buffer_len(&outgoing_packet));
618 /* append unencrypted MAC */
619 if (mac && mac->enabled)
620 buffer_append(&output, (char *)macbuf, mac->mac_len);
622 fprintf(stderr, "encrypted: ");
623 buffer_dump(&output);
625 /* increment sequence number for outgoing packets */
627 log("outgoing seqnr wraps around");
628 buffer_clear(&outgoing_packet);
630 if (type == SSH2_MSG_NEWKEYS) {
631 if (kex==NULL || mac==NULL || enc==NULL || comp==NULL)
632 fatal("packet_send2: no KEX");
635 DBG(debug("cipher_init send_context"));
636 cipher_init(&send_context, enc->cipher,
637 enc->key, enc->cipher->key_len,
638 enc->iv, enc->cipher->block_size);
639 clear_enc_keys(enc, kex->we_need);
640 if (comp->type != 0 && comp->enabled == 0) {
642 if (! packet_compression)
643 packet_start_compression(6);
651 if (use_ssh2_packet_format)
655 DBG(debug("packet_send done"));
659 * Waits until a packet has been received, and returns its type. Note that
660 * no other data is processed until this returns, so this function should not
661 * be used during the interactive session.
665 packet_read(int *payload_len_ptr)
670 DBG(debug("packet_read()"));
672 /* Since we are blocking, ensure that all written packets have been sent. */
675 /* Stay in the loop until we have received a complete packet. */
677 /* Try to read a packet from the buffer. */
678 type = packet_read_poll(payload_len_ptr);
679 if (!use_ssh2_packet_format && (
680 type == SSH_SMSG_SUCCESS
681 || type == SSH_SMSG_FAILURE
682 || type == SSH_CMSG_EOF
683 || type == SSH_CMSG_EXIT_CONFIRMATION))
684 packet_integrity_check(*payload_len_ptr, 0, type);
685 /* If we got a packet, return it. */
686 if (type != SSH_MSG_NONE)
689 * Otherwise, wait for some data to arrive, add it to the
690 * buffer, and try again.
693 FD_SET(connection_in, &set);
695 /* Wait for some data to arrive. */
696 select(connection_in + 1, &set, NULL, NULL, NULL);
698 /* Read data from the socket. */
699 len = read(connection_in, buf, sizeof(buf));
701 log("Connection closed by %.200s", get_remote_ipaddr());
705 fatal("Read from socket failed: %.100s", strerror(errno));
706 /* Append it to the buffer. */
707 packet_process_incoming(buf, len);
713 * Waits until a packet has been received, verifies that its type matches
714 * that given, and gives a fatal error and exits if there is a mismatch.
718 packet_read_expect(int *payload_len_ptr, int expected_type)
722 type = packet_read(payload_len_ptr);
723 if (type != expected_type)
724 packet_disconnect("Protocol error: expected packet type %d, got %d",
725 expected_type, type);
728 /* Checks if a full packet is available in the data received so far via
729 * packet_process_incoming. If so, reads the packet; otherwise returns
730 * SSH_MSG_NONE. This does not wait for data from the connection.
732 * SSH_MSG_DISCONNECT is handled specially here. Also,
733 * SSH_MSG_IGNORE messages are skipped by this function and are never returned
736 * The returned payload_len does include space consumed by:
744 packet_read_poll1(int *payload_len_ptr)
746 u_int len, padded_len;
749 u_int checksum, stored_checksum;
751 /* Check if input size is less than minimum packet size. */
752 if (buffer_len(&input) < 4 + 8)
754 /* Get length of incoming packet. */
755 ucp = (u_char *) buffer_ptr(&input);
756 len = GET_32BIT(ucp);
757 if (len < 1 + 2 + 2 || len > 256 * 1024)
758 packet_disconnect("Bad packet length %d.", len);
759 padded_len = (len + 8) & ~7;
761 /* Check if the packet has been entirely received. */
762 if (buffer_len(&input) < 4 + padded_len)
765 /* The entire packet is in buffer. */
767 /* Consume packet length. */
768 buffer_consume(&input, 4);
770 /* Copy data to incoming_packet. */
771 buffer_clear(&incoming_packet);
772 buffer_append_space(&incoming_packet, &cp, padded_len);
773 packet_decrypt(&receive_context, cp, buffer_ptr(&input), padded_len);
774 buffer_consume(&input, padded_len);
777 fprintf(stderr, "read_poll plain: ");
778 buffer_dump(&incoming_packet);
781 /* Compute packet checksum. */
782 checksum = ssh_crc32((u_char *) buffer_ptr(&incoming_packet),
783 buffer_len(&incoming_packet) - 4);
786 buffer_consume(&incoming_packet, 8 - len % 8);
788 /* Test check bytes. */
790 if (len != buffer_len(&incoming_packet))
791 packet_disconnect("packet_read_poll: len %d != buffer_len %d.",
792 len, buffer_len(&incoming_packet));
794 ucp = (u_char *) buffer_ptr(&incoming_packet) + len - 4;
795 stored_checksum = GET_32BIT(ucp);
796 if (checksum != stored_checksum)
797 packet_disconnect("Corrupted check bytes on input.");
798 buffer_consume_end(&incoming_packet, 4);
800 /* If using packet compression, decompress the packet. */
801 if (packet_compression) {
802 buffer_clear(&compression_buffer);
803 buffer_uncompress(&incoming_packet, &compression_buffer);
804 buffer_clear(&incoming_packet);
805 buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
806 buffer_len(&compression_buffer));
808 /* Get packet type. */
809 buffer_get(&incoming_packet, &buf[0], 1);
811 /* Return length of payload (without type field). */
812 *payload_len_ptr = buffer_len(&incoming_packet);
815 return (u_char) buf[0];
819 packet_read_poll2(int *payload_len_ptr)
822 u_char buf[8], *macbuf;
825 static u_int packet_length = 0;
826 static u_int seqnr = 0;
828 int maclen, block_size;
834 enc = &kex->enc[MODE_IN];
835 mac = &kex->mac[MODE_IN];
836 comp = &kex->comp[MODE_IN];
838 maclen = mac && mac->enabled ? mac->mac_len : 0;
839 block_size = enc ? enc->cipher->block_size : 8;
841 if (packet_length == 0) {
843 * check if input size is less than the cipher block size,
844 * decrypt first block and extract length of incoming packet
846 if (buffer_len(&input) < block_size)
848 buffer_clear(&incoming_packet);
849 buffer_append_space(&incoming_packet, &cp, block_size);
850 packet_decrypt(&receive_context, cp, buffer_ptr(&input),
852 ucp = (u_char *) buffer_ptr(&incoming_packet);
853 packet_length = GET_32BIT(ucp);
854 if (packet_length < 1 + 4 || packet_length > 256 * 1024) {
855 buffer_dump(&incoming_packet);
856 packet_disconnect("Bad packet length %d.", packet_length);
858 DBG(debug("input: packet len %d", packet_length+4));
859 buffer_consume(&input, block_size);
861 /* we have a partial packet of block_size bytes */
862 need = 4 + packet_length - block_size;
863 DBG(debug("partial packet %d, need %d, maclen %d", block_size,
865 if (need % block_size != 0)
866 fatal("padding error: need %d block %d mod %d",
867 need, block_size, need % block_size);
869 * check if the entire packet has been received and
870 * decrypt into incoming_packet
872 if (buffer_len(&input) < need + maclen)
875 fprintf(stderr, "read_poll enc/full: ");
878 buffer_append_space(&incoming_packet, &cp, need);
879 packet_decrypt(&receive_context, cp, buffer_ptr(&input), need);
880 buffer_consume(&input, need);
882 * compute MAC over seqnr and packet,
883 * increment sequence number for incoming packet
885 if (mac && mac->enabled) {
886 macbuf = hmac( mac->md, seqnr,
887 (u_char *) buffer_ptr(&incoming_packet),
888 buffer_len(&incoming_packet),
889 mac->key, mac->key_len
891 if (memcmp(macbuf, buffer_ptr(&input), mac->mac_len) != 0)
892 packet_disconnect("Corrupted MAC on input.");
893 DBG(debug("MAC #%d ok", seqnr));
894 buffer_consume(&input, mac->mac_len);
897 log("incoming seqnr wraps around");
900 cp = buffer_ptr(&incoming_packet) + 4;
902 DBG(debug("input: padlen %d", padlen));
904 packet_disconnect("Corrupted padlen %d on input.", padlen);
906 /* skip packet size + padlen, discard padding */
907 buffer_consume(&incoming_packet, 4 + 1);
908 buffer_consume_end(&incoming_packet, padlen);
910 DBG(debug("input: len before de-compress %d", buffer_len(&incoming_packet)));
911 if (comp && comp->enabled) {
912 buffer_clear(&compression_buffer);
913 buffer_uncompress(&incoming_packet, &compression_buffer);
914 buffer_clear(&incoming_packet);
915 buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
916 buffer_len(&compression_buffer));
917 DBG(debug("input: len after de-compress %d", buffer_len(&incoming_packet)));
920 * get packet type, implies consume.
921 * return length of payload (without type field)
923 buffer_get(&incoming_packet, (char *)&buf[0], 1);
924 *payload_len_ptr = buffer_len(&incoming_packet);
926 /* reset for next packet */
929 /* extract packet type */
930 type = (u_char)buf[0];
932 if (type == SSH2_MSG_NEWKEYS) {
933 if (kex==NULL || mac==NULL || enc==NULL || comp==NULL)
934 fatal("packet_read_poll2: no KEX");
937 DBG(debug("cipher_init receive_context"));
938 cipher_init(&receive_context, enc->cipher,
939 enc->key, enc->cipher->key_len,
940 enc->iv, enc->cipher->block_size);
941 clear_enc_keys(enc, kex->we_need);
942 if (comp->type != 0 && comp->enabled == 0) {
944 if (! packet_compression)
945 packet_start_compression(6);
950 fprintf(stderr, "read/plain[%d]:\r\n",type);
951 buffer_dump(&incoming_packet);
957 packet_read_poll(int *payload_len_ptr)
961 int type = use_ssh2_packet_format ?
962 packet_read_poll2(payload_len_ptr):
963 packet_read_poll1(payload_len_ptr);
968 DBG(debug("received packet type %d", type));
970 case SSH2_MSG_IGNORE:
974 msg = packet_get_string(NULL);
975 debug("Remote: %.900s", msg);
977 msg = packet_get_string(NULL);
980 case SSH2_MSG_DISCONNECT:
981 reason = packet_get_int();
982 msg = packet_get_string(NULL);
983 log("Received disconnect from %s: %d: %.400s", get_remote_ipaddr(),
997 msg = packet_get_string(NULL);
998 debug("Remote: %.900s", msg);
1001 case SSH_MSG_DISCONNECT:
1002 msg = packet_get_string(NULL);
1003 log("Received disconnect from %s: %.400s", get_remote_ipaddr(),
1010 DBG(debug("received packet type %d", type));
1019 * Buffers the given amount of input characters. This is intended to be used
1020 * together with packet_read_poll.
1024 packet_process_incoming(const char *buf, u_int len)
1026 buffer_append(&input, buf, len);
1029 /* Returns a character from the packet. */
1035 buffer_get(&incoming_packet, &ch, 1);
1039 /* Returns an integer from the packet data. */
1044 return buffer_get_int(&incoming_packet);
1048 * Returns an arbitrary precision integer from the packet data. The integer
1049 * must have been initialized before this call.
1053 packet_get_bignum(BIGNUM * value, int *length_ptr)
1055 *length_ptr = buffer_get_bignum(&incoming_packet, value);
1059 packet_get_bignum2(BIGNUM * value, int *length_ptr)
1061 *length_ptr = buffer_get_bignum2(&incoming_packet, value);
1065 packet_get_raw(int *length_ptr)
1067 int bytes = buffer_len(&incoming_packet);
1068 if (length_ptr != NULL)
1069 *length_ptr = bytes;
1070 return buffer_ptr(&incoming_packet);
1074 packet_remaining(void)
1076 return buffer_len(&incoming_packet);
1080 * Returns a string from the packet data. The string is allocated using
1081 * xmalloc; it is the responsibility of the calling program to free it when
1082 * no longer needed. The length_ptr argument may be NULL, or point to an
1083 * integer into which the length of the string is stored.
1087 packet_get_string(u_int *length_ptr)
1089 return buffer_get_string(&incoming_packet, length_ptr);
1093 * Sends a diagnostic message from the server to the client. This message
1094 * can be sent at any time (but not while constructing another message). The
1095 * message is printed immediately, but only if the client is being executed
1096 * in verbose mode. These messages are primarily intended to ease debugging
1097 * authentication problems. The length of the formatted message must not
1098 * exceed 1024 bytes. This will automatically call packet_write_wait.
1102 packet_send_debug(const char *fmt,...)
1107 if (compat20 && (datafellows & SSH_BUG_DEBUG))
1110 va_start(args, fmt);
1111 vsnprintf(buf, sizeof(buf), fmt, args);
1115 packet_start(SSH2_MSG_DEBUG);
1116 packet_put_char(0); /* bool: always display */
1117 packet_put_cstring(buf);
1118 packet_put_cstring("");
1120 packet_start(SSH_MSG_DEBUG);
1121 packet_put_cstring(buf);
1124 packet_write_wait();
1128 * Logs the error plus constructs and sends a disconnect packet, closes the
1129 * connection, and exits. This function never returns. The error message
1130 * should not contain a newline. The length of the formatted message must
1131 * not exceed 1024 bytes.
1135 packet_disconnect(const char *fmt,...)
1139 static int disconnecting = 0;
1140 if (disconnecting) /* Guard against recursive invocations. */
1141 fatal("packet_disconnect called recursively.");
1145 * Format the message. Note that the caller must make sure the
1146 * message is of limited size.
1148 va_start(args, fmt);
1149 vsnprintf(buf, sizeof(buf), fmt, args);
1152 /* Send the disconnect message to the other side, and wait for it to get sent. */
1154 packet_start(SSH2_MSG_DISCONNECT);
1155 packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1156 packet_put_cstring(buf);
1157 packet_put_cstring("");
1159 packet_start(SSH_MSG_DISCONNECT);
1160 packet_put_string(buf, strlen(buf));
1163 packet_write_wait();
1165 /* Stop listening for connections. */
1166 channel_stop_listening();
1168 /* Close the connection. */
1171 /* Display the error locally and exit. */
1172 log("Disconnecting: %.100s", buf);
1176 /* Checks if there is any buffered output, and tries to write some of the output. */
1181 int len = buffer_len(&output);
1183 len = write(connection_out, buffer_ptr(&output), len);
1185 if (errno == EAGAIN)
1188 fatal("Write failed: %.100s", strerror(errno));
1190 buffer_consume(&output, len);
1195 * Calls packet_write_poll repeatedly until all pending output data has been
1202 packet_write_poll();
1203 while (packet_have_data_to_write()) {
1206 FD_SET(connection_out, &set);
1207 select(connection_out + 1, NULL, &set, NULL, NULL);
1208 packet_write_poll();
1212 /* Returns true if there is buffered data to write to the connection. */
1215 packet_have_data_to_write()
1217 return buffer_len(&output) != 0;
1220 /* Returns true if there is not too much data to write to the connection. */
1223 packet_not_very_much_data_to_write()
1225 if (interactive_mode)
1226 return buffer_len(&output) < 16384;
1228 return buffer_len(&output) < 128 * 1024;
1231 /* Informs that the current session is interactive. Sets IP flags for that. */
1234 packet_set_interactive(int interactive)
1236 static int called = 0;
1237 int lowdelay = IPTOS_LOWDELAY;
1238 int throughput = IPTOS_THROUGHPUT;
1245 /* Record that we are in interactive mode. */
1246 interactive_mode = interactive;
1248 /* Only set socket options if using a socket. */
1249 if (!packet_connection_is_on_socket())
1252 * IPTOS_LOWDELAY and IPTOS_THROUGHPUT are IPv4 only
1256 * Set IP options for an interactive connection. Use
1257 * IPTOS_LOWDELAY and TCP_NODELAY.
1259 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1260 if (packet_connection_is_ipv4()) {
1261 if (setsockopt(connection_in, IPPROTO_IP, IP_TOS,
1262 (void *) &lowdelay, sizeof(lowdelay)) < 0)
1263 error("setsockopt IPTOS_LOWDELAY: %.100s",
1267 if (setsockopt(connection_in, IPPROTO_TCP, TCP_NODELAY, (void *) &on,
1269 error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
1270 } else if (packet_connection_is_ipv4()) {
1272 * Set IP options for a non-interactive connection. Use
1275 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
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;