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.35 2000/09/07 20:27:52 deraadt Exp $");
58 #include <openssl/bn.h>
59 #include <openssl/dh.h>
60 #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 unsigned 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 connection_in = fd_in;
165 connection_out = fd_out;
166 cipher_type = SSH_CIPHER_NONE;
167 cipher_set_key(&send_context, SSH_CIPHER_NONE, (unsigned char *) "", 0);
168 cipher_set_key(&receive_context, SSH_CIPHER_NONE, (unsigned char *) "", 0);
172 buffer_init(&output);
173 buffer_init(&outgoing_packet);
174 buffer_init(&incoming_packet);
176 /* Kludge: arrange the close function to be called from fatal(). */
177 fatal_add_cleanup((void (*) (void *)) packet_close, NULL);
180 /* Returns 1 if remote host is connected via socket, 0 if not. */
183 packet_connection_is_on_socket()
185 struct sockaddr_storage from, to;
186 socklen_t fromlen, tolen;
188 /* filedescriptors in and out are the same, so it's a socket */
189 if (connection_in == connection_out)
191 fromlen = sizeof(from);
192 memset(&from, 0, sizeof(from));
193 if (getpeername(connection_in, (struct sockaddr *)&from, &fromlen) < 0)
196 memset(&to, 0, sizeof(to));
197 if (getpeername(connection_out, (struct sockaddr *)&to, &tolen) < 0)
199 if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
201 if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
206 /* returns 1 if connection is via ipv4 */
209 packet_connection_is_ipv4()
211 struct sockaddr_storage to;
212 socklen_t tolen = sizeof(to);
214 memset(&to, 0, sizeof(to));
215 if (getsockname(connection_out, (struct sockaddr *)&to, &tolen) < 0)
217 if (to.ss_family != AF_INET)
222 /* Sets the connection into non-blocking mode. */
225 packet_set_nonblocking()
227 /* Set the socket into non-blocking mode. */
228 if (fcntl(connection_in, F_SETFL, O_NONBLOCK) < 0)
229 error("fcntl O_NONBLOCK: %.100s", strerror(errno));
231 if (connection_out != connection_in) {
232 if (fcntl(connection_out, F_SETFL, O_NONBLOCK) < 0)
233 error("fcntl O_NONBLOCK: %.100s", strerror(errno));
237 /* Returns the socket used for reading. */
240 packet_get_connection_in()
242 return connection_in;
245 /* Returns the descriptor used for writing. */
248 packet_get_connection_out()
250 return connection_out;
253 /* Closes the connection and clears and frees internal data structures. */
261 if (connection_in == connection_out) {
262 shutdown(connection_out, SHUT_RDWR);
263 close(connection_out);
265 close(connection_in);
266 close(connection_out);
269 buffer_free(&output);
270 buffer_free(&outgoing_packet);
271 buffer_free(&incoming_packet);
272 if (packet_compression) {
273 buffer_free(&compression_buffer);
274 buffer_compress_uninit();
278 /* Sets remote side protocol flags. */
281 packet_set_protocol_flags(unsigned int protocol_flags)
283 remote_protocol_flags = protocol_flags;
284 channel_set_options((protocol_flags & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) != 0);
287 /* Returns the remote protocol flags set earlier by the above function. */
290 packet_get_protocol_flags()
292 return remote_protocol_flags;
296 * Starts packet compression from the next packet on in both directions.
297 * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
300 /*** XXXXX todo: kex means re-init */
302 packet_start_compression(int level)
304 if (packet_compression)
305 fatal("Compression already enabled.");
306 packet_compression = 1;
307 buffer_init(&compression_buffer);
308 buffer_compress_init(level);
312 * Encrypts the given number of bytes, copying from src to dest. bytes is
313 * known to be a multiple of 8.
317 packet_encrypt(CipherContext * cc, void *dest, void *src,
320 cipher_encrypt(cc, dest, src, bytes);
324 * Decrypts the given number of bytes, copying from src to dest. bytes is
325 * known to be a multiple of 8.
329 packet_decrypt(CipherContext * cc, void *dest, void *src,
334 if ((bytes % 8) != 0)
335 fatal("packet_decrypt: bad ciphertext length %d", bytes);
338 * Cryptographic attack detector for ssh - Modifications for packet.c
339 * (C)1998 CORE-SDI, Buenos Aires Argentina Ariel Futoransky(futo@core-sdi.com)
342 if (cc->type == SSH_CIPHER_NONE || compat20) {
345 i = detect_attack(src, bytes, NULL);
347 if (i == DEATTACK_DETECTED)
348 packet_disconnect("crc32 compensation attack: network attack detected");
350 cipher_decrypt(cc, dest, src, bytes);
354 * Causes any further packets to be encrypted using the given key. The same
355 * key is used for both sending and reception. However, both directions are
356 * encrypted independently of each other.
360 packet_set_encryption_key(const unsigned char *key, unsigned int keylen,
364 fatal("keylen too small: %d", keylen);
366 /* All other ciphers use the same key in both directions for now. */
367 cipher_set_key(&receive_context, cipher, key, keylen);
368 cipher_set_key(&send_context, cipher, key, keylen);
371 /* Starts constructing a packet to send. */
374 packet_start1(int type)
378 buffer_clear(&outgoing_packet);
381 buffer_append(&outgoing_packet, buf, 9);
385 packet_start2(int type)
389 buffer_clear(&outgoing_packet);
390 memset(buf, 0, sizeof buf);
391 /* buf[0..3] = payload_len; */
392 /* buf[4] = pad_len; */
393 buf[5] = type & 0xff;
394 buffer_append(&outgoing_packet, buf, sizeof buf);
398 packet_start(int type)
400 DBG(debug("packet_start[%d]",type));
401 if (use_ssh2_packet_format)
407 /* Appends a character to the packet data. */
410 packet_put_char(int value)
413 buffer_append(&outgoing_packet, &ch, 1);
416 /* Appends an integer to the packet data. */
419 packet_put_int(unsigned int value)
421 buffer_put_int(&outgoing_packet, value);
424 /* Appends a string to packet data. */
427 packet_put_string(const char *buf, unsigned int len)
429 buffer_put_string(&outgoing_packet, buf, len);
432 packet_put_cstring(const char *str)
434 buffer_put_string(&outgoing_packet, str, strlen(str));
438 packet_put_raw(const char *buf, unsigned int len)
440 buffer_append(&outgoing_packet, buf, len);
444 /* Appends an arbitrary precision integer to packet data. */
447 packet_put_bignum(BIGNUM * value)
449 buffer_put_bignum(&outgoing_packet, value);
452 packet_put_bignum2(BIGNUM * value)
454 buffer_put_bignum2(&outgoing_packet, value);
458 * Finalizes and sends the packet. If the encryption key has been set,
459 * encrypts the packet before sending.
467 unsigned int checksum;
471 * If using packet compression, compress the payload of the outgoing
474 if (packet_compression) {
475 buffer_clear(&compression_buffer);
477 buffer_consume(&outgoing_packet, 8);
479 buffer_append(&compression_buffer, "\0\0\0\0\0\0\0\0", 8);
480 buffer_compress(&outgoing_packet, &compression_buffer);
481 buffer_clear(&outgoing_packet);
482 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
483 buffer_len(&compression_buffer));
485 /* Compute packet length without padding (add checksum, remove padding). */
486 len = buffer_len(&outgoing_packet) + 4 - 8;
488 /* Insert padding. Initialized to zero in packet_start1() */
489 padding = 8 - len % 8;
490 if (cipher_type != SSH_CIPHER_NONE) {
491 cp = buffer_ptr(&outgoing_packet);
492 for (i = 0; i < padding; i++) {
495 cp[7 - i] = rand & 0xff;
499 buffer_consume(&outgoing_packet, 8 - padding);
501 /* Add check bytes. */
502 checksum = ssh_crc32((unsigned char *) buffer_ptr(&outgoing_packet),
503 buffer_len(&outgoing_packet));
504 PUT_32BIT(buf, checksum);
505 buffer_append(&outgoing_packet, buf, 4);
508 fprintf(stderr, "packet_send plain: ");
509 buffer_dump(&outgoing_packet);
512 /* Append to output. */
514 buffer_append(&output, buf, 4);
515 buffer_append_space(&output, &cp, buffer_len(&outgoing_packet));
516 packet_encrypt(&send_context, cp, buffer_ptr(&outgoing_packet),
517 buffer_len(&outgoing_packet));
520 fprintf(stderr, "encrypted: ");
521 buffer_dump(&output);
524 buffer_clear(&outgoing_packet);
527 * Note that the packet is now only buffered in output. It won\'t be
528 * actually sent until packet_write_wait or packet_write_poll is
534 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
539 unsigned char *macbuf = NULL;
541 unsigned int packet_length = 0;
542 unsigned int i, padlen, len;
544 static unsigned int seqnr = 0;
552 enc = &kex->enc[MODE_OUT];
553 mac = &kex->mac[MODE_OUT];
554 comp = &kex->comp[MODE_OUT];
556 block_size = enc ? enc->block_size : 8;
558 cp = buffer_ptr(&outgoing_packet);
562 fprintf(stderr, "plain: ");
563 buffer_dump(&outgoing_packet);
566 if (comp && comp->enabled) {
567 len = buffer_len(&outgoing_packet);
568 /* skip header, compress only payload */
569 buffer_consume(&outgoing_packet, 5);
570 buffer_clear(&compression_buffer);
571 buffer_compress(&outgoing_packet, &compression_buffer);
572 buffer_clear(&outgoing_packet);
573 buffer_append(&outgoing_packet, "\0\0\0\0\0", 5);
574 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
575 buffer_len(&compression_buffer));
576 DBG(debug("compression: raw %d compressed %d", len,
577 buffer_len(&outgoing_packet)));
580 /* sizeof (packet_len + pad_len + payload) */
581 len = buffer_len(&outgoing_packet);
584 * calc size of padding, alloc space, get random data,
585 * minimum padding is 4 bytes
587 padlen = block_size - (len % block_size);
589 padlen += block_size;
590 buffer_append_space(&outgoing_packet, &cp, padlen);
591 if (enc && enc->type != SSH_CIPHER_NONE) {
593 for (i = 0; i < padlen; i++) {
601 memset(cp, 0, padlen);
603 /* packet_length includes payload, padding and padding length field */
604 packet_length = buffer_len(&outgoing_packet) - 4;
605 cp = buffer_ptr(&outgoing_packet);
606 PUT_32BIT(cp, packet_length);
607 cp[4] = padlen & 0xff;
608 DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen));
610 /* compute MAC over seqnr and packet(length fields, payload, padding) */
611 if (mac && mac->enabled) {
612 macbuf = hmac( mac->md, seqnr,
613 (unsigned char *) buffer_ptr(&outgoing_packet),
614 buffer_len(&outgoing_packet),
615 mac->key, mac->key_len
617 DBG(debug("done calc HMAC out #%d", seqnr));
619 /* encrypt packet and append to output buffer. */
620 buffer_append_space(&output, &cp, buffer_len(&outgoing_packet));
621 packet_encrypt(&send_context, cp, buffer_ptr(&outgoing_packet),
622 buffer_len(&outgoing_packet));
623 /* append unencrypted MAC */
624 if (mac && mac->enabled)
625 buffer_append(&output, (char *)macbuf, mac->mac_len);
627 fprintf(stderr, "encrypted: ");
628 buffer_dump(&output);
630 /* increment sequence number for outgoing packets */
632 log("outgoing seqnr wraps around");
633 buffer_clear(&outgoing_packet);
635 if (type == SSH2_MSG_NEWKEYS) {
636 if (kex==NULL || mac==NULL || enc==NULL || comp==NULL)
637 fatal("packet_send2: no KEX");
640 DBG(debug("cipher_set_key_iv send_context"));
641 cipher_set_key_iv(&send_context, enc->type,
642 enc->key, enc->key_len,
643 enc->iv, enc->iv_len);
644 clear_enc_keys(enc, kex->we_need);
645 if (comp->type != 0 && comp->enabled == 0) {
647 if (! packet_compression)
648 packet_start_compression(6);
656 if (use_ssh2_packet_format)
660 DBG(debug("packet_send done"));
664 * Waits until a packet has been received, and returns its type. Note that
665 * no other data is processed until this returns, so this function should not
666 * be used during the interactive session.
670 packet_read(int *payload_len_ptr)
675 DBG(debug("packet_read()"));
677 /* Since we are blocking, ensure that all written packets have been sent. */
680 /* Stay in the loop until we have received a complete packet. */
682 /* Try to read a packet from the buffer. */
683 type = packet_read_poll(payload_len_ptr);
684 if (!use_ssh2_packet_format && (
685 type == SSH_SMSG_SUCCESS
686 || type == SSH_SMSG_FAILURE
687 || type == SSH_CMSG_EOF
688 || type == SSH_CMSG_EXIT_CONFIRMATION))
689 packet_integrity_check(*payload_len_ptr, 0, type);
690 /* If we got a packet, return it. */
691 if (type != SSH_MSG_NONE)
694 * Otherwise, wait for some data to arrive, add it to the
695 * buffer, and try again.
698 FD_SET(connection_in, &set);
700 /* Wait for some data to arrive. */
701 select(connection_in + 1, &set, NULL, NULL, NULL);
703 /* Read data from the socket. */
704 len = read(connection_in, buf, sizeof(buf));
706 log("Connection closed by %.200s", get_remote_ipaddr());
710 fatal("Read from socket failed: %.100s", strerror(errno));
711 /* Append it to the buffer. */
712 packet_process_incoming(buf, len);
718 * Waits until a packet has been received, verifies that its type matches
719 * that given, and gives a fatal error and exits if there is a mismatch.
723 packet_read_expect(int *payload_len_ptr, int expected_type)
727 type = packet_read(payload_len_ptr);
728 if (type != expected_type)
729 packet_disconnect("Protocol error: expected packet type %d, got %d",
730 expected_type, type);
733 /* Checks if a full packet is available in the data received so far via
734 * packet_process_incoming. If so, reads the packet; otherwise returns
735 * SSH_MSG_NONE. This does not wait for data from the connection.
737 * SSH_MSG_DISCONNECT is handled specially here. Also,
738 * SSH_MSG_IGNORE messages are skipped by this function and are never returned
741 * The returned payload_len does include space consumed by:
749 packet_read_poll1(int *payload_len_ptr)
751 unsigned int len, padded_len;
754 unsigned int checksum, stored_checksum;
756 /* Check if input size is less than minimum packet size. */
757 if (buffer_len(&input) < 4 + 8)
759 /* Get length of incoming packet. */
760 ucp = (unsigned char *) buffer_ptr(&input);
761 len = GET_32BIT(ucp);
762 if (len < 1 + 2 + 2 || len > 256 * 1024)
763 packet_disconnect("Bad packet length %d.", len);
764 padded_len = (len + 8) & ~7;
766 /* Check if the packet has been entirely received. */
767 if (buffer_len(&input) < 4 + padded_len)
770 /* The entire packet is in buffer. */
772 /* Consume packet length. */
773 buffer_consume(&input, 4);
775 /* Copy data to incoming_packet. */
776 buffer_clear(&incoming_packet);
777 buffer_append_space(&incoming_packet, &cp, padded_len);
778 packet_decrypt(&receive_context, cp, buffer_ptr(&input), padded_len);
779 buffer_consume(&input, padded_len);
782 fprintf(stderr, "read_poll plain: ");
783 buffer_dump(&incoming_packet);
786 /* Compute packet checksum. */
787 checksum = ssh_crc32((unsigned char *) buffer_ptr(&incoming_packet),
788 buffer_len(&incoming_packet) - 4);
791 buffer_consume(&incoming_packet, 8 - len % 8);
793 /* Test check bytes. */
795 if (len != buffer_len(&incoming_packet))
796 packet_disconnect("packet_read_poll: len %d != buffer_len %d.",
797 len, buffer_len(&incoming_packet));
799 ucp = (unsigned char *) buffer_ptr(&incoming_packet) + len - 4;
800 stored_checksum = GET_32BIT(ucp);
801 if (checksum != stored_checksum)
802 packet_disconnect("Corrupted check bytes on input.");
803 buffer_consume_end(&incoming_packet, 4);
805 /* If using packet compression, decompress the packet. */
806 if (packet_compression) {
807 buffer_clear(&compression_buffer);
808 buffer_uncompress(&incoming_packet, &compression_buffer);
809 buffer_clear(&incoming_packet);
810 buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
811 buffer_len(&compression_buffer));
813 /* Get packet type. */
814 buffer_get(&incoming_packet, &buf[0], 1);
816 /* Return length of payload (without type field). */
817 *payload_len_ptr = buffer_len(&incoming_packet);
820 return (unsigned char) buf[0];
824 packet_read_poll2(int *payload_len_ptr)
826 unsigned int padlen, need;
827 unsigned char buf[8], *macbuf;
830 static unsigned int packet_length = 0;
831 static unsigned int seqnr = 0;
833 int maclen, block_size;
839 enc = &kex->enc[MODE_IN];
840 mac = &kex->mac[MODE_IN];
841 comp = &kex->comp[MODE_IN];
843 maclen = mac && mac->enabled ? mac->mac_len : 0;
844 block_size = enc ? enc->block_size : 8;
846 if (packet_length == 0) {
848 * check if input size is less than the cipher block size,
849 * decrypt first block and extract length of incoming packet
851 if (buffer_len(&input) < block_size)
853 buffer_clear(&incoming_packet);
854 buffer_append_space(&incoming_packet, &cp, block_size);
855 packet_decrypt(&receive_context, cp, buffer_ptr(&input),
857 ucp = (unsigned char *) buffer_ptr(&incoming_packet);
858 packet_length = GET_32BIT(ucp);
859 if (packet_length < 1 + 4 || packet_length > 256 * 1024) {
860 buffer_dump(&incoming_packet);
861 packet_disconnect("Bad packet length %d.", packet_length);
863 DBG(debug("input: packet len %d", packet_length+4));
864 buffer_consume(&input, block_size);
866 /* we have a partial packet of block_size bytes */
867 need = 4 + packet_length - block_size;
868 DBG(debug("partial packet %d, need %d, maclen %d", block_size,
870 if (need % block_size != 0)
871 fatal("padding error: need %d block %d mod %d",
872 need, block_size, need % block_size);
874 * check if the entire packet has been received and
875 * decrypt into incoming_packet
877 if (buffer_len(&input) < need + maclen)
880 fprintf(stderr, "read_poll enc/full: ");
883 buffer_append_space(&incoming_packet, &cp, need);
884 packet_decrypt(&receive_context, cp, buffer_ptr(&input), need);
885 buffer_consume(&input, need);
887 * compute MAC over seqnr and packet,
888 * increment sequence number for incoming packet
890 if (mac && mac->enabled) {
891 macbuf = hmac( mac->md, seqnr,
892 (unsigned char *) buffer_ptr(&incoming_packet),
893 buffer_len(&incoming_packet),
894 mac->key, mac->key_len
896 if (memcmp(macbuf, buffer_ptr(&input), mac->mac_len) != 0)
897 packet_disconnect("Corrupted HMAC on input.");
898 DBG(debug("HMAC #%d ok", seqnr));
899 buffer_consume(&input, mac->mac_len);
902 log("incoming seqnr wraps around");
905 cp = buffer_ptr(&incoming_packet) + 4;
907 DBG(debug("input: padlen %d", padlen));
909 packet_disconnect("Corrupted padlen %d on input.", padlen);
911 /* skip packet size + padlen, discard padding */
912 buffer_consume(&incoming_packet, 4 + 1);
913 buffer_consume_end(&incoming_packet, padlen);
915 DBG(debug("input: len before de-compress %d", buffer_len(&incoming_packet)));
916 if (comp && comp->enabled) {
917 buffer_clear(&compression_buffer);
918 buffer_uncompress(&incoming_packet, &compression_buffer);
919 buffer_clear(&incoming_packet);
920 buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
921 buffer_len(&compression_buffer));
922 DBG(debug("input: len after de-compress %d", buffer_len(&incoming_packet)));
925 * get packet type, implies consume.
926 * return length of payload (without type field)
928 buffer_get(&incoming_packet, (char *)&buf[0], 1);
929 *payload_len_ptr = buffer_len(&incoming_packet);
931 /* reset for next packet */
934 /* extract packet type */
935 type = (unsigned char)buf[0];
937 if (type == SSH2_MSG_NEWKEYS) {
938 if (kex==NULL || mac==NULL || enc==NULL || comp==NULL)
939 fatal("packet_read_poll2: no KEX");
942 DBG(debug("cipher_set_key_iv receive_context"));
943 cipher_set_key_iv(&receive_context, enc->type,
944 enc->key, enc->key_len,
945 enc->iv, enc->iv_len);
946 clear_enc_keys(enc, kex->we_need);
947 if (comp->type != 0 && comp->enabled == 0) {
949 if (! packet_compression)
950 packet_start_compression(6);
955 fprintf(stderr, "read/plain[%d]:\r\n",type);
956 buffer_dump(&incoming_packet);
958 return (unsigned char)type;
962 packet_read_poll(int *payload_len_ptr)
966 int type = use_ssh2_packet_format ?
967 packet_read_poll2(payload_len_ptr):
968 packet_read_poll1(payload_len_ptr);
973 DBG(debug("received packet type %d", type));
975 case SSH2_MSG_IGNORE:
979 msg = packet_get_string(NULL);
980 debug("Remote: %.900s", msg);
982 msg = packet_get_string(NULL);
985 case SSH2_MSG_DISCONNECT:
986 reason = packet_get_int();
987 msg = packet_get_string(NULL);
988 log("Received disconnect: %d: %.900s", reason, msg);
1001 msg = packet_get_string(NULL);
1002 debug("Remote: %.900s", msg);
1005 case SSH_MSG_DISCONNECT:
1006 msg = packet_get_string(NULL);
1007 log("Received disconnect: %.900s", msg);
1013 DBG(debug("received packet type %d", type));
1022 * Buffers the given amount of input characters. This is intended to be used
1023 * together with packet_read_poll.
1027 packet_process_incoming(const char *buf, unsigned int len)
1029 buffer_append(&input, buf, len);
1032 /* Returns a character from the packet. */
1038 buffer_get(&incoming_packet, &ch, 1);
1039 return (unsigned char) ch;
1042 /* Returns an integer from the packet data. */
1047 return buffer_get_int(&incoming_packet);
1051 * Returns an arbitrary precision integer from the packet data. The integer
1052 * must have been initialized before this call.
1056 packet_get_bignum(BIGNUM * value, int *length_ptr)
1058 *length_ptr = buffer_get_bignum(&incoming_packet, value);
1062 packet_get_bignum2(BIGNUM * value, int *length_ptr)
1064 *length_ptr = buffer_get_bignum2(&incoming_packet, value);
1068 packet_get_raw(int *length_ptr)
1070 int bytes = buffer_len(&incoming_packet);
1071 if (length_ptr != NULL)
1072 *length_ptr = bytes;
1073 return buffer_ptr(&incoming_packet);
1077 packet_remaining(void)
1079 return buffer_len(&incoming_packet);
1083 * Returns a string from the packet data. The string is allocated using
1084 * xmalloc; it is the responsibility of the calling program to free it when
1085 * no longer needed. The length_ptr argument may be NULL, or point to an
1086 * integer into which the length of the string is stored.
1090 packet_get_string(unsigned int *length_ptr)
1092 return buffer_get_string(&incoming_packet, length_ptr);
1096 * Sends a diagnostic message from the server to the client. This message
1097 * can be sent at any time (but not while constructing another message). The
1098 * message is printed immediately, but only if the client is being executed
1099 * in verbose mode. These messages are primarily intended to ease debugging
1100 * authentication problems. The length of the formatted message must not
1101 * exceed 1024 bytes. This will automatically call packet_write_wait.
1105 packet_send_debug(const char *fmt,...)
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, int keepalives)
1238 /* Record that we are in interactive mode. */
1239 interactive_mode = interactive;
1241 /* Only set socket options if using a socket. */
1242 if (!packet_connection_is_on_socket())
1245 /* Set keepalives if requested. */
1246 if (setsockopt(connection_in, SOL_SOCKET, SO_KEEPALIVE, (void *) &on,
1248 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1251 * IPTOS_LOWDELAY, TCP_NODELAY and IPTOS_THROUGHPUT are IPv4 only
1253 if (!packet_connection_is_ipv4())
1257 * Set IP options for an interactive connection. Use
1258 * IPTOS_LOWDELAY and TCP_NODELAY.
1260 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1261 int lowdelay = IPTOS_LOWDELAY;
1262 if (setsockopt(connection_in, IPPROTO_IP, IP_TOS, (void *) &lowdelay,
1263 sizeof(lowdelay)) < 0)
1264 error("setsockopt IPTOS_LOWDELAY: %.100s", strerror(errno));
1266 if (setsockopt(connection_in, IPPROTO_TCP, TCP_NODELAY, (void *) &on,
1268 error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
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;