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.56 2001/03/03 21:41:07 millert Exp $");
70 * This variable contains the file descriptors used for communicating with
71 * the other side. connection_in is used for reading; connection_out for
72 * writing. These can be the same descriptor, in which case it is assumed to
75 static int connection_in = -1;
76 static int connection_out = -1;
79 * Cipher type. This value is only used to determine whether to pad the
80 * packets with zeroes or random data.
82 static int cipher_type = SSH_CIPHER_NONE;
84 /* Protocol flags for the remote side. */
85 static u_int remote_protocol_flags = 0;
87 /* Encryption context for receiving data. This is only used for decryption. */
88 static CipherContext receive_context;
90 /* Encryption context for sending data. This is only used for encryption. */
91 static CipherContext send_context;
93 /* Buffer for raw input data from the socket. */
96 /* Buffer for raw output data going to the socket. */
99 /* Buffer for the partial outgoing packet being constructed. */
100 static Buffer outgoing_packet;
102 /* Buffer for the incoming packet currently being processed. */
103 static Buffer incoming_packet;
105 /* Scratch buffer for packet compression/decompression. */
106 static Buffer compression_buffer;
108 /* Flag indicating whether packet compression/decompression is enabled. */
109 static int packet_compression = 0;
111 /* default maximum packet size */
112 int max_packet_size = 32768;
114 /* Flag indicating whether this module has been initialized. */
115 static int initialized = 0;
117 /* Set to true if the connection is interactive. */
118 static int interactive_mode = 0;
120 /* True if SSH2 packet format is used */
121 int use_ssh2_packet_format = 0;
123 /* Session key information for Encryption and MAC */
127 packet_set_kex(Kex *k)
129 if( k->mac[MODE_IN ].key == NULL ||
130 k->enc[MODE_IN ].key == NULL ||
131 k->enc[MODE_IN ].iv == NULL ||
132 k->mac[MODE_OUT].key == NULL ||
133 k->enc[MODE_OUT].key == NULL ||
134 k->enc[MODE_OUT].iv == NULL)
139 clear_enc_keys(Enc *enc, int len)
141 memset(enc->iv, 0, len);
142 memset(enc->key, 0, len);
149 packet_set_ssh2_format(void)
151 DBG(debug("use_ssh2_packet_format"));
152 use_ssh2_packet_format = 1;
156 * Sets the descriptors used for communication. Disables encryption until
157 * packet_set_encryption_key is called.
160 packet_set_connection(int fd_in, int fd_out)
162 Cipher *none = cipher_by_name("none");
164 fatal("packet_set_connection: cannot load cipher 'none'");
165 connection_in = fd_in;
166 connection_out = fd_out;
167 cipher_type = SSH_CIPHER_NONE;
168 cipher_init(&send_context, none, (u_char *) "", 0, NULL, 0);
169 cipher_init(&receive_context, none, (u_char *) "", 0, NULL, 0);
173 buffer_init(&output);
174 buffer_init(&outgoing_packet);
175 buffer_init(&incoming_packet);
177 /* Kludge: arrange the close function to be called from fatal(). */
178 fatal_add_cleanup((void (*) (void *)) packet_close, NULL);
181 /* Returns 1 if remote host is connected via socket, 0 if not. */
184 packet_connection_is_on_socket()
186 struct sockaddr_storage from, to;
187 socklen_t fromlen, tolen;
189 /* filedescriptors in and out are the same, so it's a socket */
190 if (connection_in == connection_out)
192 fromlen = sizeof(from);
193 memset(&from, 0, sizeof(from));
194 if (getpeername(connection_in, (struct sockaddr *)&from, &fromlen) < 0)
197 memset(&to, 0, sizeof(to));
198 if (getpeername(connection_out, (struct sockaddr *)&to, &tolen) < 0)
200 if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
202 if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
207 /* returns 1 if connection is via ipv4 */
210 packet_connection_is_ipv4()
212 struct sockaddr_storage to;
213 socklen_t tolen = sizeof(to);
215 memset(&to, 0, sizeof(to));
216 if (getsockname(connection_out, (struct sockaddr *)&to, &tolen) < 0)
218 if (to.ss_family != AF_INET)
223 /* Sets the connection into non-blocking mode. */
226 packet_set_nonblocking()
228 /* Set the socket into non-blocking mode. */
229 if (fcntl(connection_in, F_SETFL, O_NONBLOCK) < 0)
230 error("fcntl O_NONBLOCK: %.100s", strerror(errno));
232 if (connection_out != connection_in) {
233 if (fcntl(connection_out, F_SETFL, O_NONBLOCK) < 0)
234 error("fcntl O_NONBLOCK: %.100s", strerror(errno));
238 /* Returns the socket used for reading. */
241 packet_get_connection_in()
243 return connection_in;
246 /* Returns the descriptor used for writing. */
249 packet_get_connection_out()
251 return connection_out;
254 /* Closes the connection and clears and frees internal data structures. */
262 if (connection_in == connection_out) {
263 shutdown(connection_out, SHUT_RDWR);
264 close(connection_out);
266 close(connection_in);
267 close(connection_out);
270 buffer_free(&output);
271 buffer_free(&outgoing_packet);
272 buffer_free(&incoming_packet);
273 if (packet_compression) {
274 buffer_free(&compression_buffer);
275 buffer_compress_uninit();
279 /* Sets remote side protocol flags. */
282 packet_set_protocol_flags(u_int protocol_flags)
284 remote_protocol_flags = protocol_flags;
285 channel_set_options((protocol_flags & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) != 0);
288 /* Returns the remote protocol flags set earlier by the above function. */
291 packet_get_protocol_flags()
293 return remote_protocol_flags;
297 * Starts packet compression from the next packet on in both directions.
298 * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
301 /*** XXXXX todo: kex means re-init */
303 packet_start_compression(int level)
305 if (packet_compression)
306 fatal("Compression already enabled.");
307 packet_compression = 1;
308 buffer_init(&compression_buffer);
309 buffer_compress_init(level);
313 * Encrypts the given number of bytes, copying from src to dest. bytes is
314 * known to be a multiple of 8.
318 packet_encrypt(CipherContext * cc, void *dest, void *src,
321 cipher_encrypt(cc, dest, src, bytes);
325 * Decrypts the given number of bytes, copying from src to dest. bytes is
326 * known to be a multiple of 8.
330 packet_decrypt(CipherContext *context, void *dest, void *src, u_int bytes)
333 * Cryptographic attack detector for ssh - Modifications for packet.c
334 * (C)1998 CORE-SDI, Buenos Aires Argentina Ariel Futoransky(futo@core-sdi.com)
337 context->cipher->number != SSH_CIPHER_NONE &&
338 detect_attack(src, bytes, NULL) == DEATTACK_DETECTED)
339 packet_disconnect("crc32 compensation attack: network attack detected");
341 cipher_decrypt(context, dest, src, bytes);
345 * Causes any further packets to be encrypted using the given key. The same
346 * key is used for both sending and reception. However, both directions are
347 * encrypted independently of each other.
351 packet_set_encryption_key(const u_char *key, u_int keylen,
354 Cipher *cipher = cipher_by_number(number);
356 fatal("packet_set_encryption_key: unknown cipher number %d", number);
358 fatal("packet_set_encryption_key: keylen too small: %d", keylen);
359 cipher_init(&receive_context, cipher, key, keylen, NULL, 0);
360 cipher_init(&send_context, cipher, key, keylen, NULL, 0);
363 /* Starts constructing a packet to send. */
366 packet_start1(int type)
370 buffer_clear(&outgoing_packet);
373 buffer_append(&outgoing_packet, buf, 9);
377 packet_start2(int type)
381 buffer_clear(&outgoing_packet);
382 memset(buf, 0, sizeof buf);
383 /* buf[0..3] = payload_len; */
384 /* buf[4] = pad_len; */
385 buf[5] = type & 0xff;
386 buffer_append(&outgoing_packet, buf, sizeof buf);
390 packet_start(int type)
392 DBG(debug("packet_start[%d]", type));
393 if (use_ssh2_packet_format)
399 /* Appends a character to the packet data. */
402 packet_put_char(int value)
405 buffer_append(&outgoing_packet, &ch, 1);
408 /* Appends an integer to the packet data. */
411 packet_put_int(u_int value)
413 buffer_put_int(&outgoing_packet, value);
416 /* Appends a string to packet data. */
419 packet_put_string(const char *buf, u_int len)
421 buffer_put_string(&outgoing_packet, buf, len);
424 packet_put_cstring(const char *str)
426 buffer_put_string(&outgoing_packet, str, strlen(str));
430 packet_put_raw(const char *buf, u_int len)
432 buffer_append(&outgoing_packet, buf, len);
436 /* Appends an arbitrary precision integer to packet data. */
439 packet_put_bignum(BIGNUM * value)
441 buffer_put_bignum(&outgoing_packet, value);
444 packet_put_bignum2(BIGNUM * value)
446 buffer_put_bignum2(&outgoing_packet, value);
450 * Finalizes and sends the packet. If the encryption key has been set,
451 * encrypts the packet before sending.
463 * If using packet compression, compress the payload of the outgoing
466 if (packet_compression) {
467 buffer_clear(&compression_buffer);
469 buffer_consume(&outgoing_packet, 8);
471 buffer_append(&compression_buffer, "\0\0\0\0\0\0\0\0", 8);
472 buffer_compress(&outgoing_packet, &compression_buffer);
473 buffer_clear(&outgoing_packet);
474 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
475 buffer_len(&compression_buffer));
477 /* Compute packet length without padding (add checksum, remove padding). */
478 len = buffer_len(&outgoing_packet) + 4 - 8;
480 /* Insert padding. Initialized to zero in packet_start1() */
481 padding = 8 - len % 8;
482 if (cipher_type != SSH_CIPHER_NONE) {
483 cp = buffer_ptr(&outgoing_packet);
484 for (i = 0; i < padding; i++) {
487 cp[7 - i] = rand & 0xff;
491 buffer_consume(&outgoing_packet, 8 - padding);
493 /* Add check bytes. */
494 checksum = ssh_crc32((u_char *) buffer_ptr(&outgoing_packet),
495 buffer_len(&outgoing_packet));
496 PUT_32BIT(buf, checksum);
497 buffer_append(&outgoing_packet, buf, 4);
500 fprintf(stderr, "packet_send plain: ");
501 buffer_dump(&outgoing_packet);
504 /* Append to output. */
506 buffer_append(&output, buf, 4);
507 buffer_append_space(&output, &cp, buffer_len(&outgoing_packet));
508 packet_encrypt(&send_context, cp, buffer_ptr(&outgoing_packet),
509 buffer_len(&outgoing_packet));
512 fprintf(stderr, "encrypted: ");
513 buffer_dump(&output);
516 buffer_clear(&outgoing_packet);
519 * Note that the packet is now only buffered in output. It won\'t be
520 * actually sent until packet_write_wait or packet_write_poll is
526 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
531 static u_int32_t seqnr = 0;
532 u_char *macbuf = NULL;
534 u_int packet_length = 0;
535 u_int i, padlen, len;
544 enc = &kex->enc[MODE_OUT];
545 mac = &kex->mac[MODE_OUT];
546 comp = &kex->comp[MODE_OUT];
548 block_size = enc ? enc->cipher->block_size : 8;
550 cp = buffer_ptr(&outgoing_packet);
554 fprintf(stderr, "plain: ");
555 buffer_dump(&outgoing_packet);
558 if (comp && comp->enabled) {
559 len = buffer_len(&outgoing_packet);
560 /* skip header, compress only payload */
561 buffer_consume(&outgoing_packet, 5);
562 buffer_clear(&compression_buffer);
563 buffer_compress(&outgoing_packet, &compression_buffer);
564 buffer_clear(&outgoing_packet);
565 buffer_append(&outgoing_packet, "\0\0\0\0\0", 5);
566 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
567 buffer_len(&compression_buffer));
568 DBG(debug("compression: raw %d compressed %d", len,
569 buffer_len(&outgoing_packet)));
572 /* sizeof (packet_len + pad_len + payload) */
573 len = buffer_len(&outgoing_packet);
576 * calc size of padding, alloc space, get random data,
577 * minimum padding is 4 bytes
579 padlen = block_size - (len % block_size);
581 padlen += block_size;
582 buffer_append_space(&outgoing_packet, &cp, padlen);
583 if (enc && enc->cipher->number != SSH_CIPHER_NONE) {
585 for (i = 0; i < padlen; i++) {
593 memset(cp, 0, padlen);
595 /* packet_length includes payload, padding and padding length field */
596 packet_length = buffer_len(&outgoing_packet) - 4;
597 cp = buffer_ptr(&outgoing_packet);
598 PUT_32BIT(cp, packet_length);
599 cp[4] = padlen & 0xff;
600 DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen));
602 /* compute MAC over seqnr and packet(length fields, payload, padding) */
603 if (mac && mac->enabled) {
604 macbuf = mac_compute(mac, seqnr,
605 (u_char *) buffer_ptr(&outgoing_packet),
606 buffer_len(&outgoing_packet));
607 DBG(debug("done calc MAC out #%d", seqnr));
609 /* encrypt packet and append to output buffer. */
610 buffer_append_space(&output, &cp, buffer_len(&outgoing_packet));
611 packet_encrypt(&send_context, cp, buffer_ptr(&outgoing_packet),
612 buffer_len(&outgoing_packet));
613 /* append unencrypted MAC */
614 if (mac && mac->enabled)
615 buffer_append(&output, (char *)macbuf, mac->mac_len);
617 fprintf(stderr, "encrypted: ");
618 buffer_dump(&output);
620 /* increment sequence number for outgoing packets */
622 log("outgoing seqnr wraps around");
623 buffer_clear(&outgoing_packet);
625 if (type == SSH2_MSG_NEWKEYS) {
626 if (kex==NULL || mac==NULL || enc==NULL || comp==NULL)
627 fatal("packet_send2: no KEX");
630 DBG(debug("cipher_init send_context"));
631 cipher_init(&send_context, enc->cipher,
632 enc->key, enc->cipher->key_len,
633 enc->iv, enc->cipher->block_size);
634 clear_enc_keys(enc, kex->we_need);
635 if (comp->type != 0 && comp->enabled == 0) {
637 if (! packet_compression)
638 packet_start_compression(6);
646 if (use_ssh2_packet_format)
650 DBG(debug("packet_send done"));
654 * Waits until a packet has been received, and returns its type. Note that
655 * no other data is processed until this returns, so this function should not
656 * be used during the interactive session.
660 packet_read(int *payload_len_ptr)
665 DBG(debug("packet_read()"));
667 setp = (fd_set *)xmalloc(howmany(connection_in+1, NFDBITS) *
670 /* Since we are blocking, ensure that all written packets have been sent. */
673 /* Stay in the loop until we have received a complete packet. */
675 /* Try to read a packet from the buffer. */
676 type = packet_read_poll(payload_len_ptr);
677 if (!use_ssh2_packet_format && (
678 type == SSH_SMSG_SUCCESS
679 || type == SSH_SMSG_FAILURE
680 || type == SSH_CMSG_EOF
681 || type == SSH_CMSG_EXIT_CONFIRMATION))
682 packet_integrity_check(*payload_len_ptr, 0, type);
683 /* If we got a packet, return it. */
684 if (type != SSH_MSG_NONE) {
689 * Otherwise, wait for some data to arrive, add it to the
690 * buffer, and try again.
692 memset(setp, 0, howmany(connection_in + 1, NFDBITS) *
694 FD_SET(connection_in, setp);
696 /* Wait for some data to arrive. */
697 while (select(connection_in + 1, setp, NULL, NULL, NULL) == -1 &&
698 (errno == EAGAIN || errno == EINTR))
701 /* Read data from the socket. */
702 len = read(connection_in, buf, sizeof(buf));
704 log("Connection closed by %.200s", get_remote_ipaddr());
708 fatal("Read from socket failed: %.100s", strerror(errno));
709 /* Append it to the buffer. */
710 packet_process_incoming(buf, len);
716 * Waits until a packet has been received, verifies that its type matches
717 * that given, and gives a fatal error and exits if there is a mismatch.
721 packet_read_expect(int *payload_len_ptr, int expected_type)
725 type = packet_read(payload_len_ptr);
726 if (type != expected_type)
727 packet_disconnect("Protocol error: expected packet type %d, got %d",
728 expected_type, type);
731 /* Checks if a full packet is available in the data received so far via
732 * packet_process_incoming. If so, reads the packet; otherwise returns
733 * SSH_MSG_NONE. This does not wait for data from the connection.
735 * SSH_MSG_DISCONNECT is handled specially here. Also,
736 * SSH_MSG_IGNORE messages are skipped by this function and are never returned
739 * The returned payload_len does include space consumed by:
747 packet_read_poll1(int *payload_len_ptr)
749 u_int len, padded_len;
752 u_int checksum, stored_checksum;
754 /* Check if input size is less than minimum packet size. */
755 if (buffer_len(&input) < 4 + 8)
757 /* Get length of incoming packet. */
758 ucp = (u_char *) buffer_ptr(&input);
759 len = GET_32BIT(ucp);
760 if (len < 1 + 2 + 2 || len > 256 * 1024)
761 packet_disconnect("Bad packet length %d.", len);
762 padded_len = (len + 8) & ~7;
764 /* Check if the packet has been entirely received. */
765 if (buffer_len(&input) < 4 + padded_len)
768 /* The entire packet is in buffer. */
770 /* Consume packet length. */
771 buffer_consume(&input, 4);
773 /* Copy data to incoming_packet. */
774 buffer_clear(&incoming_packet);
775 buffer_append_space(&incoming_packet, &cp, padded_len);
776 packet_decrypt(&receive_context, cp, buffer_ptr(&input), padded_len);
777 buffer_consume(&input, padded_len);
780 fprintf(stderr, "read_poll plain: ");
781 buffer_dump(&incoming_packet);
784 /* Compute packet checksum. */
785 checksum = ssh_crc32((u_char *) buffer_ptr(&incoming_packet),
786 buffer_len(&incoming_packet) - 4);
789 buffer_consume(&incoming_packet, 8 - len % 8);
791 /* Test check bytes. */
793 if (len != buffer_len(&incoming_packet))
794 packet_disconnect("packet_read_poll: len %d != buffer_len %d.",
795 len, buffer_len(&incoming_packet));
797 ucp = (u_char *) buffer_ptr(&incoming_packet) + len - 4;
798 stored_checksum = GET_32BIT(ucp);
799 if (checksum != stored_checksum)
800 packet_disconnect("Corrupted check bytes on input.");
801 buffer_consume_end(&incoming_packet, 4);
803 /* If using packet compression, decompress the packet. */
804 if (packet_compression) {
805 buffer_clear(&compression_buffer);
806 buffer_uncompress(&incoming_packet, &compression_buffer);
807 buffer_clear(&incoming_packet);
808 buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
809 buffer_len(&compression_buffer));
811 /* Get packet type. */
812 buffer_get(&incoming_packet, &buf[0], 1);
814 /* Return length of payload (without type field). */
815 *payload_len_ptr = buffer_len(&incoming_packet);
818 return (u_char) buf[0];
822 packet_read_poll2(int *payload_len_ptr)
824 static u_int32_t seqnr = 0;
825 static u_int packet_length = 0;
827 u_char buf[8], *macbuf;
831 int maclen, block_size;
837 enc = &kex->enc[MODE_IN];
838 mac = &kex->mac[MODE_IN];
839 comp = &kex->comp[MODE_IN];
841 maclen = mac && mac->enabled ? mac->mac_len : 0;
842 block_size = enc ? enc->cipher->block_size : 8;
844 if (packet_length == 0) {
846 * check if input size is less than the cipher block size,
847 * decrypt first block and extract length of incoming packet
849 if (buffer_len(&input) < block_size)
851 buffer_clear(&incoming_packet);
852 buffer_append_space(&incoming_packet, &cp, block_size);
853 packet_decrypt(&receive_context, cp, buffer_ptr(&input),
855 ucp = (u_char *) buffer_ptr(&incoming_packet);
856 packet_length = GET_32BIT(ucp);
857 if (packet_length < 1 + 4 || packet_length > 256 * 1024) {
858 buffer_dump(&incoming_packet);
859 packet_disconnect("Bad packet length %d.", packet_length);
861 DBG(debug("input: packet len %d", packet_length+4));
862 buffer_consume(&input, block_size);
864 /* we have a partial packet of block_size bytes */
865 need = 4 + packet_length - block_size;
866 DBG(debug("partial packet %d, need %d, maclen %d", block_size,
868 if (need % block_size != 0)
869 fatal("padding error: need %d block %d mod %d",
870 need, block_size, need % block_size);
872 * check if the entire packet has been received and
873 * decrypt into incoming_packet
875 if (buffer_len(&input) < need + maclen)
878 fprintf(stderr, "read_poll enc/full: ");
881 buffer_append_space(&incoming_packet, &cp, need);
882 packet_decrypt(&receive_context, cp, buffer_ptr(&input), need);
883 buffer_consume(&input, need);
885 * compute MAC over seqnr and packet,
886 * increment sequence number for incoming packet
888 if (mac && mac->enabled) {
889 macbuf = mac_compute(mac, seqnr,
890 (u_char *) buffer_ptr(&incoming_packet),
891 buffer_len(&incoming_packet));
892 if (memcmp(macbuf, buffer_ptr(&input), mac->mac_len) != 0)
893 packet_disconnect("Corrupted MAC on input.");
894 DBG(debug("MAC #%d ok", seqnr));
895 buffer_consume(&input, mac->mac_len);
898 log("incoming seqnr wraps around");
901 cp = buffer_ptr(&incoming_packet) + 4;
903 DBG(debug("input: padlen %d", padlen));
905 packet_disconnect("Corrupted padlen %d on input.", padlen);
907 /* skip packet size + padlen, discard padding */
908 buffer_consume(&incoming_packet, 4 + 1);
909 buffer_consume_end(&incoming_packet, padlen);
911 DBG(debug("input: len before de-compress %d", buffer_len(&incoming_packet)));
912 if (comp && comp->enabled) {
913 buffer_clear(&compression_buffer);
914 buffer_uncompress(&incoming_packet, &compression_buffer);
915 buffer_clear(&incoming_packet);
916 buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
917 buffer_len(&compression_buffer));
918 DBG(debug("input: len after de-compress %d", buffer_len(&incoming_packet)));
921 * get packet type, implies consume.
922 * return length of payload (without type field)
924 buffer_get(&incoming_packet, (char *)&buf[0], 1);
925 *payload_len_ptr = buffer_len(&incoming_packet);
927 /* reset for next packet */
930 /* extract packet type */
931 type = (u_char)buf[0];
933 if (type == SSH2_MSG_NEWKEYS) {
934 if (kex==NULL || mac==NULL || enc==NULL || comp==NULL)
935 fatal("packet_read_poll2: no KEX");
938 DBG(debug("cipher_init receive_context"));
939 cipher_init(&receive_context, enc->cipher,
940 enc->key, enc->cipher->key_len,
941 enc->iv, enc->cipher->block_size);
942 clear_enc_keys(enc, kex->we_need);
943 if (comp->type != 0 && comp->enabled == 0) {
945 if (! packet_compression)
946 packet_start_compression(6);
951 fprintf(stderr, "read/plain[%d]:\r\n", type);
952 buffer_dump(&incoming_packet);
958 packet_read_poll(int *payload_len_ptr)
962 int type = use_ssh2_packet_format ?
963 packet_read_poll2(payload_len_ptr):
964 packet_read_poll1(payload_len_ptr);
969 DBG(debug("received packet type %d", type));
971 case SSH2_MSG_IGNORE:
975 msg = packet_get_string(NULL);
976 debug("Remote: %.900s", msg);
978 msg = packet_get_string(NULL);
981 case SSH2_MSG_DISCONNECT:
982 reason = packet_get_int();
983 msg = packet_get_string(NULL);
984 log("Received disconnect from %s: %d: %.400s", get_remote_ipaddr(),
998 msg = packet_get_string(NULL);
999 debug("Remote: %.900s", msg);
1002 case SSH_MSG_DISCONNECT:
1003 msg = packet_get_string(NULL);
1004 log("Received disconnect from %s: %.400s", get_remote_ipaddr(),
1011 DBG(debug("received packet type %d", type));
1020 * Buffers the given amount of input characters. This is intended to be used
1021 * together with packet_read_poll.
1025 packet_process_incoming(const char *buf, u_int len)
1027 buffer_append(&input, buf, len);
1030 /* Returns a character from the packet. */
1036 buffer_get(&incoming_packet, &ch, 1);
1040 /* Returns an integer from the packet data. */
1045 return buffer_get_int(&incoming_packet);
1049 * Returns an arbitrary precision integer from the packet data. The integer
1050 * must have been initialized before this call.
1054 packet_get_bignum(BIGNUM * value, int *length_ptr)
1056 *length_ptr = buffer_get_bignum(&incoming_packet, value);
1060 packet_get_bignum2(BIGNUM * value, int *length_ptr)
1062 *length_ptr = buffer_get_bignum2(&incoming_packet, value);
1066 packet_get_raw(int *length_ptr)
1068 int bytes = buffer_len(&incoming_packet);
1069 if (length_ptr != NULL)
1070 *length_ptr = bytes;
1071 return buffer_ptr(&incoming_packet);
1075 packet_remaining(void)
1077 return buffer_len(&incoming_packet);
1081 * Returns a string from the packet data. The string is allocated using
1082 * xmalloc; it is the responsibility of the calling program to free it when
1083 * no longer needed. The length_ptr argument may be NULL, or point to an
1084 * integer into which the length of the string is stored.
1088 packet_get_string(u_int *length_ptr)
1090 return buffer_get_string(&incoming_packet, length_ptr);
1094 * Sends a diagnostic message from the server to the client. This message
1095 * can be sent at any time (but not while constructing another message). The
1096 * message is printed immediately, but only if the client is being executed
1097 * in verbose mode. These messages are primarily intended to ease debugging
1098 * authentication problems. The length of the formatted message must not
1099 * exceed 1024 bytes. This will automatically call packet_write_wait.
1103 packet_send_debug(const char *fmt,...)
1108 if (compat20 && (datafellows & SSH_BUG_DEBUG))
1111 va_start(args, fmt);
1112 vsnprintf(buf, sizeof(buf), fmt, args);
1116 packet_start(SSH2_MSG_DEBUG);
1117 packet_put_char(0); /* bool: always display */
1118 packet_put_cstring(buf);
1119 packet_put_cstring("");
1121 packet_start(SSH_MSG_DEBUG);
1122 packet_put_cstring(buf);
1125 packet_write_wait();
1129 * Logs the error plus constructs and sends a disconnect packet, closes the
1130 * connection, and exits. This function never returns. The error message
1131 * should not contain a newline. The length of the formatted message must
1132 * not exceed 1024 bytes.
1136 packet_disconnect(const char *fmt,...)
1140 static int disconnecting = 0;
1141 if (disconnecting) /* Guard against recursive invocations. */
1142 fatal("packet_disconnect called recursively.");
1146 * Format the message. Note that the caller must make sure the
1147 * message is of limited size.
1149 va_start(args, fmt);
1150 vsnprintf(buf, sizeof(buf), fmt, args);
1153 /* Send the disconnect message to the other side, and wait for it to get sent. */
1155 packet_start(SSH2_MSG_DISCONNECT);
1156 packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1157 packet_put_cstring(buf);
1158 packet_put_cstring("");
1160 packet_start(SSH_MSG_DISCONNECT);
1161 packet_put_string(buf, strlen(buf));
1164 packet_write_wait();
1166 /* Stop listening for connections. */
1167 channel_stop_listening();
1169 /* Close the connection. */
1172 /* Display the error locally and exit. */
1173 log("Disconnecting: %.100s", buf);
1177 /* Checks if there is any buffered output, and tries to write some of the output. */
1182 int len = buffer_len(&output);
1184 len = write(connection_out, buffer_ptr(&output), len);
1186 if (errno == EAGAIN)
1189 fatal("Write failed: %.100s", strerror(errno));
1191 buffer_consume(&output, len);
1196 * Calls packet_write_poll repeatedly until all pending output data has been
1205 setp = (fd_set *)xmalloc(howmany(connection_out + 1, NFDBITS) *
1207 packet_write_poll();
1208 while (packet_have_data_to_write()) {
1209 memset(setp, 0, howmany(connection_out + 1, NFDBITS) *
1211 FD_SET(connection_out, setp);
1212 while (select(connection_out + 1, NULL, setp, NULL, NULL) == -1 &&
1213 (errno == EAGAIN || errno == EINTR))
1215 packet_write_poll();
1220 /* Returns true if there is buffered data to write to the connection. */
1223 packet_have_data_to_write()
1225 return buffer_len(&output) != 0;
1228 /* Returns true if there is not too much data to write to the connection. */
1231 packet_not_very_much_data_to_write()
1233 if (interactive_mode)
1234 return buffer_len(&output) < 16384;
1236 return buffer_len(&output) < 128 * 1024;
1239 /* Informs that the current session is interactive. Sets IP flags for that. */
1242 packet_set_interactive(int interactive)
1244 static int called = 0;
1245 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1246 int lowdelay = IPTOS_LOWDELAY;
1247 int throughput = IPTOS_THROUGHPUT;
1255 /* Record that we are in interactive mode. */
1256 interactive_mode = interactive;
1258 /* Only set socket options if using a socket. */
1259 if (!packet_connection_is_on_socket())
1262 * IPTOS_LOWDELAY and IPTOS_THROUGHPUT are IPv4 only
1266 * Set IP options for an interactive connection. Use
1267 * IPTOS_LOWDELAY and TCP_NODELAY.
1269 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1270 if (packet_connection_is_ipv4()) {
1271 if (setsockopt(connection_in, IPPROTO_IP, IP_TOS,
1272 (void *) &lowdelay, sizeof(lowdelay)) < 0)
1273 error("setsockopt IPTOS_LOWDELAY: %.100s",
1277 if (setsockopt(connection_in, IPPROTO_TCP, TCP_NODELAY, (void *) &on,
1279 error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
1280 } else if (packet_connection_is_ipv4()) {
1282 * Set IP options for a non-interactive connection. Use
1285 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1286 if (setsockopt(connection_in, IPPROTO_IP, IP_TOS, (void *) &throughput,
1287 sizeof(throughput)) < 0)
1288 error("setsockopt IPTOS_THROUGHPUT: %.100s", strerror(errno));
1293 /* Returns true if the current connection is interactive. */
1296 packet_is_interactive()
1298 return interactive_mode;
1302 packet_set_maxsize(int s)
1304 static int called = 0;
1306 log("packet_set_maxsize: called twice: old %d new %d",
1307 max_packet_size, s);
1310 if (s < 4 * 1024 || s > 1024 * 1024) {
1311 log("packet_set_maxsize: bad size %d", s);
1314 log("packet_set_maxsize: setting to %d", s);
1315 max_packet_size = s;
1320 * 9.2. Ignored Data Message
1322 * byte SSH_MSG_IGNORE
1325 * All implementations MUST understand (and ignore) this message at any
1326 * time (after receiving the protocol version). No implementation is
1327 * required to send them. This message can be used as an additional
1328 * protection measure against advanced traffic analysis techniques.
1330 /* size of current + ignore message should be n*sumlen bytes (w/o mac) */
1332 packet_inject_ignore(int sumlen)
1334 int blocksize, padlen, have, need, nb, mini, nbytes;
1337 if (use_ssh2_packet_format == 0)
1340 have = buffer_len(&outgoing_packet);
1341 debug2("packet_inject_ignore: current %d", have);
1343 enc = &kex->enc[MODE_OUT];
1344 blocksize = enc ? enc->cipher->block_size : 8;
1345 padlen = blocksize - (have % blocksize);
1347 padlen += blocksize;
1349 have /= blocksize; /* # of blocks for current message */
1351 nb = roundup(sumlen, blocksize) / blocksize; /* blocks for both */
1352 mini = roundup(5+1+4+4, blocksize) / blocksize; /* minsize ignore msg */
1353 need = nb - (have % nb); /* blocks for ignore */
1356 nbytes = (need - mini) * blocksize; /* size of ignore payload */
1357 debug2("packet_inject_ignore: block %d have %d nb %d mini %d need %d",
1358 blocksize, have, nb, mini, need);
1360 /* enqueue current message and append a ignore message */
1362 packet_send_ignore(nbytes);
1366 packet_send_ignore(int nbytes)
1371 packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1372 packet_put_int(nbytes);
1373 for(i = 0; i < nbytes; i++) {
1375 rand = arc4random();
1376 packet_put_char(rand & 0xff);