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, 2001 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.91 2002/03/18 17:16:38 markus Exp $");
71 * This variable contains the file descriptors used for communicating with
72 * the other side. connection_in is used for reading; connection_out for
73 * writing. These can be the same descriptor, in which case it is assumed to
76 static int connection_in = -1;
77 static int connection_out = -1;
79 /* Protocol flags for the remote side. */
80 static u_int remote_protocol_flags = 0;
82 /* Encryption context for receiving data. This is only used for decryption. */
83 static CipherContext receive_context;
85 /* Encryption context for sending data. This is only used for encryption. */
86 static CipherContext send_context;
88 /* Buffer for raw input data from the socket. */
91 /* Buffer for raw output data going to the socket. */
94 /* Buffer for the partial outgoing packet being constructed. */
95 static Buffer outgoing_packet;
97 /* Buffer for the incoming packet currently being processed. */
98 static Buffer incoming_packet;
100 /* Scratch buffer for packet compression/decompression. */
101 static Buffer compression_buffer;
102 static int compression_buffer_ready = 0;
104 /* Flag indicating whether packet compression/decompression is enabled. */
105 static int packet_compression = 0;
107 /* default maximum packet size */
108 int max_packet_size = 32768;
110 /* Flag indicating whether this module has been initialized. */
111 static int initialized = 0;
113 /* Set to true if the connection is interactive. */
114 static int interactive_mode = 0;
116 /* Session key information for Encryption and MAC */
117 Newkeys *newkeys[MODE_MAX];
118 static u_int32_t read_seqnr = 0;
119 static u_int32_t send_seqnr = 0;
121 /* roundup current message to extra_pad bytes */
122 static u_char extra_pad = 0;
125 * Sets the descriptors used for communication. Disables encryption until
126 * packet_set_encryption_key is called.
129 packet_set_connection(int fd_in, int fd_out)
131 Cipher *none = cipher_by_name("none");
133 fatal("packet_set_connection: cannot load cipher 'none'");
134 connection_in = fd_in;
135 connection_out = fd_out;
136 cipher_init(&send_context, none, "", 0, NULL, 0, CIPHER_ENCRYPT);
137 cipher_init(&receive_context, none, "", 0, NULL, 0, CIPHER_DECRYPT);
138 newkeys[MODE_IN] = newkeys[MODE_OUT] = NULL;
142 buffer_init(&output);
143 buffer_init(&outgoing_packet);
144 buffer_init(&incoming_packet);
146 /* Kludge: arrange the close function to be called from fatal(). */
147 fatal_add_cleanup((void (*) (void *)) packet_close, NULL);
150 /* Returns 1 if remote host is connected via socket, 0 if not. */
153 packet_connection_is_on_socket(void)
155 struct sockaddr_storage from, to;
156 socklen_t fromlen, tolen;
158 /* filedescriptors in and out are the same, so it's a socket */
159 if (connection_in == connection_out)
161 fromlen = sizeof(from);
162 memset(&from, 0, sizeof(from));
163 if (getpeername(connection_in, (struct sockaddr *)&from, &fromlen) < 0)
166 memset(&to, 0, sizeof(to));
167 if (getpeername(connection_out, (struct sockaddr *)&to, &tolen) < 0)
169 if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
171 if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
177 * Exports an IV from the CipherContext required to export the key
178 * state back from the unprivileged child to the privileged parent
183 packet_get_keyiv(int mode, u_char *iv, u_int len)
187 if (mode == MODE_OUT)
190 cc = &receive_context;
192 cipher_get_keyiv(cc, iv, len);
196 packet_get_keycontext(int mode, u_char *dat)
200 if (mode == MODE_OUT)
203 cc = &receive_context;
205 return (cipher_get_keycontext(cc, dat));
209 packet_set_keycontext(int mode, u_char *dat)
213 if (mode == MODE_OUT)
216 cc = &receive_context;
218 cipher_set_keycontext(cc, dat);
222 packet_get_keyiv_len(int mode)
226 if (mode == MODE_OUT)
229 cc = &receive_context;
231 return (cipher_get_keyiv_len(cc));
234 packet_set_iv(int mode, u_char *dat)
238 if (mode == MODE_OUT)
241 cc = &receive_context;
243 cipher_set_keyiv(cc, dat);
246 packet_get_ssh1_cipher()
248 return (cipher_get_number(receive_context.cipher));
253 packet_get_seqnr(int mode)
255 return (mode == MODE_IN ? read_seqnr : send_seqnr);
259 packet_set_seqnr(int mode, u_int32_t seqnr)
263 else if (mode == MODE_OUT)
266 fatal("%s: bad mode %d", __FUNCTION__, mode);
269 /* returns 1 if connection is via ipv4 */
272 packet_connection_is_ipv4(void)
274 struct sockaddr_storage to;
275 socklen_t tolen = sizeof(to);
277 memset(&to, 0, sizeof(to));
278 if (getsockname(connection_out, (struct sockaddr *)&to, &tolen) < 0)
280 if (to.ss_family != AF_INET)
285 /* Sets the connection into non-blocking mode. */
288 packet_set_nonblocking(void)
290 /* Set the socket into non-blocking mode. */
291 if (fcntl(connection_in, F_SETFL, O_NONBLOCK) < 0)
292 error("fcntl O_NONBLOCK: %.100s", strerror(errno));
294 if (connection_out != connection_in) {
295 if (fcntl(connection_out, F_SETFL, O_NONBLOCK) < 0)
296 error("fcntl O_NONBLOCK: %.100s", strerror(errno));
300 /* Returns the socket used for reading. */
303 packet_get_connection_in(void)
305 return connection_in;
308 /* Returns the descriptor used for writing. */
311 packet_get_connection_out(void)
313 return connection_out;
316 /* Closes the connection and clears and frees internal data structures. */
324 if (connection_in == connection_out) {
325 shutdown(connection_out, SHUT_RDWR);
326 close(connection_out);
328 close(connection_in);
329 close(connection_out);
332 buffer_free(&output);
333 buffer_free(&outgoing_packet);
334 buffer_free(&incoming_packet);
335 if (compression_buffer_ready) {
336 buffer_free(&compression_buffer);
337 buffer_compress_uninit();
339 cipher_cleanup(&send_context);
340 cipher_cleanup(&receive_context);
343 /* Sets remote side protocol flags. */
346 packet_set_protocol_flags(u_int protocol_flags)
348 remote_protocol_flags = protocol_flags;
351 /* Returns the remote protocol flags set earlier by the above function. */
354 packet_get_protocol_flags(void)
356 return remote_protocol_flags;
360 * Starts packet compression from the next packet on in both directions.
361 * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
365 packet_init_compression(void)
367 if (compression_buffer_ready == 1)
369 compression_buffer_ready = 1;
370 buffer_init(&compression_buffer);
374 packet_start_compression(int level)
376 if (packet_compression && !compat20)
377 fatal("Compression already enabled.");
378 packet_compression = 1;
379 packet_init_compression();
380 buffer_compress_init_send(level);
381 buffer_compress_init_recv();
385 * Causes any further packets to be encrypted using the given key. The same
386 * key is used for both sending and reception. However, both directions are
387 * encrypted independently of each other.
390 packet_set_encryption_key(const u_char *key, u_int keylen,
393 Cipher *cipher = cipher_by_number(number);
395 fatal("packet_set_encryption_key: unknown cipher number %d", number);
397 fatal("packet_set_encryption_key: keylen too small: %d", keylen);
398 cipher_init(&send_context, cipher, key, keylen, NULL, 0, CIPHER_ENCRYPT);
399 cipher_init(&receive_context, cipher, key, keylen, NULL, 0, CIPHER_DECRYPT);
402 /* Start constructing a packet to send. */
404 packet_start(u_char type)
409 DBG(debug("packet_start[%d]", type));
410 len = compat20 ? 6 : 9;
411 memset(buf, 0, len - 1);
413 buffer_clear(&outgoing_packet);
414 buffer_append(&outgoing_packet, buf, len);
417 /* Append payload. */
419 packet_put_char(int value)
422 buffer_append(&outgoing_packet, &ch, 1);
425 packet_put_int(u_int value)
427 buffer_put_int(&outgoing_packet, value);
430 packet_put_string(const void *buf, u_int len)
432 buffer_put_string(&outgoing_packet, buf, len);
435 packet_put_cstring(const char *str)
437 buffer_put_cstring(&outgoing_packet, str);
440 packet_put_raw(const void *buf, u_int len)
442 buffer_append(&outgoing_packet, buf, len);
445 packet_put_bignum(BIGNUM * value)
447 buffer_put_bignum(&outgoing_packet, value);
450 packet_put_bignum2(BIGNUM * value)
452 buffer_put_bignum2(&outgoing_packet, value);
456 * Finalizes and sends the packet. If the encryption key has been set,
457 * encrypts the packet before sending.
469 * If using packet compression, compress the payload of the outgoing
472 if (packet_compression) {
473 buffer_clear(&compression_buffer);
475 buffer_consume(&outgoing_packet, 8);
477 buffer_append(&compression_buffer, "\0\0\0\0\0\0\0\0", 8);
478 buffer_compress(&outgoing_packet, &compression_buffer);
479 buffer_clear(&outgoing_packet);
480 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
481 buffer_len(&compression_buffer));
483 /* Compute packet length without padding (add checksum, remove padding). */
484 len = buffer_len(&outgoing_packet) + 4 - 8;
486 /* Insert padding. Initialized to zero in packet_start1() */
487 padding = 8 - len % 8;
488 if (!send_context.plaintext) {
489 cp = buffer_ptr(&outgoing_packet);
490 for (i = 0; i < padding; i++) {
493 cp[7 - i] = rand & 0xff;
497 buffer_consume(&outgoing_packet, 8 - padding);
499 /* Add check bytes. */
500 checksum = ssh_crc32(buffer_ptr(&outgoing_packet),
501 buffer_len(&outgoing_packet));
502 PUT_32BIT(buf, checksum);
503 buffer_append(&outgoing_packet, buf, 4);
506 fprintf(stderr, "packet_send plain: ");
507 buffer_dump(&outgoing_packet);
510 /* Append to output. */
512 buffer_append(&output, buf, 4);
513 cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
514 cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
515 buffer_len(&outgoing_packet));
518 fprintf(stderr, "encrypted: ");
519 buffer_dump(&output);
522 buffer_clear(&outgoing_packet);
525 * Note that the packet is now only buffered in output. It won\'t be
526 * actually sent until packet_write_wait or packet_write_poll is
532 set_newkeys(int mode)
540 debug("newkeys: mode %d", mode);
542 if (mode == MODE_OUT) {
544 encrypt = CIPHER_ENCRYPT;
546 cc = &receive_context;
547 encrypt = CIPHER_DECRYPT;
549 if (newkeys[mode] != NULL) {
550 debug("newkeys: rekeying");
552 enc = &newkeys[mode]->enc;
553 mac = &newkeys[mode]->mac;
554 comp = &newkeys[mode]->comp;
555 memset(mac->key, 0, mac->key_len);
562 xfree(newkeys[mode]);
564 newkeys[mode] = kex_get_newkeys(mode);
565 if (newkeys[mode] == NULL)
566 fatal("newkeys: no keys for mode %d", mode);
567 enc = &newkeys[mode]->enc;
568 mac = &newkeys[mode]->mac;
569 comp = &newkeys[mode]->comp;
572 DBG(debug("cipher_init_context: %d", mode));
573 cipher_init(cc, enc->cipher, enc->key, enc->key_len,
574 enc->iv, enc->block_size, encrypt);
575 /* Deleting the keys does not gain extra security */
576 /* memset(enc->iv, 0, enc->block_size);
577 memset(enc->key, 0, enc->key_len); */
578 if (comp->type != 0 && comp->enabled == 0) {
579 packet_init_compression();
580 if (mode == MODE_OUT)
581 buffer_compress_init_send(6);
583 buffer_compress_init_recv();
589 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
594 u_char type, *cp, *macbuf = NULL;
596 u_int packet_length = 0;
604 if (newkeys[MODE_OUT] != NULL) {
605 enc = &newkeys[MODE_OUT]->enc;
606 mac = &newkeys[MODE_OUT]->mac;
607 comp = &newkeys[MODE_OUT]->comp;
609 block_size = enc ? enc->block_size : 8;
611 cp = buffer_ptr(&outgoing_packet);
615 fprintf(stderr, "plain: ");
616 buffer_dump(&outgoing_packet);
619 if (comp && comp->enabled) {
620 len = buffer_len(&outgoing_packet);
621 /* skip header, compress only payload */
622 buffer_consume(&outgoing_packet, 5);
623 buffer_clear(&compression_buffer);
624 buffer_compress(&outgoing_packet, &compression_buffer);
625 buffer_clear(&outgoing_packet);
626 buffer_append(&outgoing_packet, "\0\0\0\0\0", 5);
627 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
628 buffer_len(&compression_buffer));
629 DBG(debug("compression: raw %d compressed %d", len,
630 buffer_len(&outgoing_packet)));
633 /* sizeof (packet_len + pad_len + payload) */
634 len = buffer_len(&outgoing_packet);
637 * calc size of padding, alloc space, get random data,
638 * minimum padding is 4 bytes
640 padlen = block_size - (len % block_size);
642 padlen += block_size;
644 /* will wrap if extra_pad+padlen > 255 */
645 extra_pad = roundup(extra_pad, block_size);
646 pad = extra_pad - ((len + padlen) % extra_pad);
647 debug("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
648 pad, len, padlen, extra_pad);
652 cp = buffer_append_space(&outgoing_packet, padlen);
653 if (enc && !send_context.plaintext) {
655 for (i = 0; i < padlen; i++) {
663 memset(cp, 0, padlen);
665 /* packet_length includes payload, padding and padding length field */
666 packet_length = buffer_len(&outgoing_packet) - 4;
667 cp = buffer_ptr(&outgoing_packet);
668 PUT_32BIT(cp, packet_length);
670 DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen));
672 /* compute MAC over seqnr and packet(length fields, payload, padding) */
673 if (mac && mac->enabled) {
674 macbuf = mac_compute(mac, send_seqnr,
675 buffer_ptr(&outgoing_packet),
676 buffer_len(&outgoing_packet));
677 DBG(debug("done calc MAC out #%d", send_seqnr));
679 /* encrypt packet and append to output buffer. */
680 cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
681 cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
682 buffer_len(&outgoing_packet));
683 /* append unencrypted MAC */
684 if (mac && mac->enabled)
685 buffer_append(&output, (char *)macbuf, mac->mac_len);
687 fprintf(stderr, "encrypted: ");
688 buffer_dump(&output);
690 /* increment sequence number for outgoing packets */
691 if (++send_seqnr == 0)
692 log("outgoing seqnr wraps around");
693 buffer_clear(&outgoing_packet);
695 if (type == SSH2_MSG_NEWKEYS)
696 set_newkeys(MODE_OUT);
706 DBG(debug("packet_send done"));
710 * Waits until a packet has been received, and returns its type. Note that
711 * no other data is processed until this returns, so this function should not
712 * be used during the interactive session.
716 packet_read_seqnr(u_int32_t *seqnr_p)
721 DBG(debug("packet_read()"));
723 setp = (fd_set *)xmalloc(howmany(connection_in+1, NFDBITS) *
726 /* Since we are blocking, ensure that all written packets have been sent. */
729 /* Stay in the loop until we have received a complete packet. */
731 /* Try to read a packet from the buffer. */
732 type = packet_read_poll_seqnr(seqnr_p);
734 type == SSH_SMSG_SUCCESS
735 || type == SSH_SMSG_FAILURE
736 || type == SSH_CMSG_EOF
737 || type == SSH_CMSG_EXIT_CONFIRMATION))
739 /* If we got a packet, return it. */
740 if (type != SSH_MSG_NONE) {
745 * Otherwise, wait for some data to arrive, add it to the
746 * buffer, and try again.
748 memset(setp, 0, howmany(connection_in + 1, NFDBITS) *
750 FD_SET(connection_in, setp);
752 /* Wait for some data to arrive. */
753 while (select(connection_in + 1, setp, NULL, NULL, NULL) == -1 &&
754 (errno == EAGAIN || errno == EINTR))
757 /* Read data from the socket. */
758 len = read(connection_in, buf, sizeof(buf));
760 log("Connection closed by %.200s", get_remote_ipaddr());
764 fatal("Read from socket failed: %.100s", strerror(errno));
765 /* Append it to the buffer. */
766 packet_process_incoming(buf, len);
774 return packet_read_seqnr(NULL);
778 * Waits until a packet has been received, verifies that its type matches
779 * that given, and gives a fatal error and exits if there is a mismatch.
783 packet_read_expect(int expected_type)
787 type = packet_read();
788 if (type != expected_type)
789 packet_disconnect("Protocol error: expected packet type %d, got %d",
790 expected_type, type);
793 /* Checks if a full packet is available in the data received so far via
794 * packet_process_incoming. If so, reads the packet; otherwise returns
795 * SSH_MSG_NONE. This does not wait for data from the connection.
797 * SSH_MSG_DISCONNECT is handled specially here. Also,
798 * SSH_MSG_IGNORE messages are skipped by this function and are never returned
803 packet_read_poll1(void)
805 u_int len, padded_len;
807 u_int checksum, stored_checksum;
809 /* Check if input size is less than minimum packet size. */
810 if (buffer_len(&input) < 4 + 8)
812 /* Get length of incoming packet. */
813 cp = buffer_ptr(&input);
815 if (len < 1 + 2 + 2 || len > 256 * 1024)
816 packet_disconnect("Bad packet length %d.", len);
817 padded_len = (len + 8) & ~7;
819 /* Check if the packet has been entirely received. */
820 if (buffer_len(&input) < 4 + padded_len)
823 /* The entire packet is in buffer. */
825 /* Consume packet length. */
826 buffer_consume(&input, 4);
829 * Cryptographic attack detector for ssh
830 * (C)1998 CORE-SDI, Buenos Aires Argentina
831 * Ariel Futoransky(futo@core-sdi.com)
833 if (!receive_context.plaintext &&
834 detect_attack(buffer_ptr(&input), padded_len, NULL) == DEATTACK_DETECTED)
835 packet_disconnect("crc32 compensation attack: network attack detected");
837 /* Decrypt data to incoming_packet. */
838 buffer_clear(&incoming_packet);
839 cp = buffer_append_space(&incoming_packet, padded_len);
840 cipher_crypt(&receive_context, cp, buffer_ptr(&input), padded_len);
842 buffer_consume(&input, padded_len);
845 fprintf(stderr, "read_poll plain: ");
846 buffer_dump(&incoming_packet);
849 /* Compute packet checksum. */
850 checksum = ssh_crc32(buffer_ptr(&incoming_packet),
851 buffer_len(&incoming_packet) - 4);
854 buffer_consume(&incoming_packet, 8 - len % 8);
856 /* Test check bytes. */
857 if (len != buffer_len(&incoming_packet))
858 packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
859 len, buffer_len(&incoming_packet));
861 cp = (u_char *)buffer_ptr(&incoming_packet) + len - 4;
862 stored_checksum = GET_32BIT(cp);
863 if (checksum != stored_checksum)
864 packet_disconnect("Corrupted check bytes on input.");
865 buffer_consume_end(&incoming_packet, 4);
867 if (packet_compression) {
868 buffer_clear(&compression_buffer);
869 buffer_uncompress(&incoming_packet, &compression_buffer);
870 buffer_clear(&incoming_packet);
871 buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
872 buffer_len(&compression_buffer));
874 type = buffer_get_char(&incoming_packet);
879 packet_read_poll2(u_int32_t *seqnr_p)
881 static u_int packet_length = 0;
883 u_char *macbuf, *cp, type;
884 int maclen, block_size;
889 if (newkeys[MODE_IN] != NULL) {
890 enc = &newkeys[MODE_IN]->enc;
891 mac = &newkeys[MODE_IN]->mac;
892 comp = &newkeys[MODE_IN]->comp;
894 maclen = mac && mac->enabled ? mac->mac_len : 0;
895 block_size = enc ? enc->block_size : 8;
897 if (packet_length == 0) {
899 * check if input size is less than the cipher block size,
900 * decrypt first block and extract length of incoming packet
902 if (buffer_len(&input) < block_size)
904 buffer_clear(&incoming_packet);
905 cp = buffer_append_space(&incoming_packet, block_size);
906 cipher_crypt(&receive_context, cp, buffer_ptr(&input),
908 cp = buffer_ptr(&incoming_packet);
909 packet_length = GET_32BIT(cp);
910 if (packet_length < 1 + 4 || packet_length > 256 * 1024) {
911 buffer_dump(&incoming_packet);
912 packet_disconnect("Bad packet length %d.", packet_length);
914 DBG(debug("input: packet len %d", packet_length+4));
915 buffer_consume(&input, block_size);
917 /* we have a partial packet of block_size bytes */
918 need = 4 + packet_length - block_size;
919 DBG(debug("partial packet %d, need %d, maclen %d", block_size,
921 if (need % block_size != 0)
922 fatal("padding error: need %d block %d mod %d",
923 need, block_size, need % block_size);
925 * check if the entire packet has been received and
926 * decrypt into incoming_packet
928 if (buffer_len(&input) < need + maclen)
931 fprintf(stderr, "read_poll enc/full: ");
934 cp = buffer_append_space(&incoming_packet, need);
935 cipher_crypt(&receive_context, cp, buffer_ptr(&input), need);
936 buffer_consume(&input, need);
938 * compute MAC over seqnr and packet,
939 * increment sequence number for incoming packet
941 if (mac && mac->enabled) {
942 macbuf = mac_compute(mac, read_seqnr,
943 buffer_ptr(&incoming_packet),
944 buffer_len(&incoming_packet));
945 if (memcmp(macbuf, buffer_ptr(&input), mac->mac_len) != 0)
946 packet_disconnect("Corrupted MAC on input.");
947 DBG(debug("MAC #%d ok", read_seqnr));
948 buffer_consume(&input, mac->mac_len);
951 *seqnr_p = read_seqnr;
952 if (++read_seqnr == 0)
953 log("incoming seqnr wraps around");
956 cp = buffer_ptr(&incoming_packet);
958 DBG(debug("input: padlen %d", padlen));
960 packet_disconnect("Corrupted padlen %d on input.", padlen);
962 /* skip packet size + padlen, discard padding */
963 buffer_consume(&incoming_packet, 4 + 1);
964 buffer_consume_end(&incoming_packet, padlen);
966 DBG(debug("input: len before de-compress %d", buffer_len(&incoming_packet)));
967 if (comp && comp->enabled) {
968 buffer_clear(&compression_buffer);
969 buffer_uncompress(&incoming_packet, &compression_buffer);
970 buffer_clear(&incoming_packet);
971 buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
972 buffer_len(&compression_buffer));
973 DBG(debug("input: len after de-compress %d", buffer_len(&incoming_packet)));
976 * get packet type, implies consume.
977 * return length of payload (without type field)
979 type = buffer_get_char(&incoming_packet);
980 if (type == SSH2_MSG_NEWKEYS)
981 set_newkeys(MODE_IN);
983 fprintf(stderr, "read/plain[%d]:\r\n", type);
984 buffer_dump(&incoming_packet);
986 /* reset for next packet */
992 packet_read_poll_seqnr(u_int32_t *seqnr_p)
1000 type = packet_read_poll2(seqnr_p);
1002 DBG(debug("received packet type %d", type));
1004 case SSH2_MSG_IGNORE:
1006 case SSH2_MSG_DEBUG:
1008 msg = packet_get_string(NULL);
1009 debug("Remote: %.900s", msg);
1011 msg = packet_get_string(NULL);
1014 case SSH2_MSG_DISCONNECT:
1015 reason = packet_get_int();
1016 msg = packet_get_string(NULL);
1017 log("Received disconnect from %s: %d: %.400s", get_remote_ipaddr(),
1022 case SSH2_MSG_UNIMPLEMENTED:
1023 seqnr = packet_get_int();
1024 debug("Received SSH2_MSG_UNIMPLEMENTED for %d", seqnr);
1031 type = packet_read_poll1();
1033 case SSH_MSG_IGNORE:
1036 msg = packet_get_string(NULL);
1037 debug("Remote: %.900s", msg);
1040 case SSH_MSG_DISCONNECT:
1041 msg = packet_get_string(NULL);
1042 log("Received disconnect from %s: %.400s", get_remote_ipaddr(),
1049 DBG(debug("received packet type %d", type));
1058 packet_read_poll(void)
1060 return packet_read_poll_seqnr(NULL);
1064 * Buffers the given amount of input characters. This is intended to be used
1065 * together with packet_read_poll.
1069 packet_process_incoming(const char *buf, u_int len)
1071 buffer_append(&input, buf, len);
1074 /* Returns a character from the packet. */
1077 packet_get_char(void)
1080 buffer_get(&incoming_packet, &ch, 1);
1084 /* Returns an integer from the packet data. */
1087 packet_get_int(void)
1089 return buffer_get_int(&incoming_packet);
1093 * Returns an arbitrary precision integer from the packet data. The integer
1094 * must have been initialized before this call.
1098 packet_get_bignum(BIGNUM * value)
1100 buffer_get_bignum(&incoming_packet, value);
1104 packet_get_bignum2(BIGNUM * value)
1106 buffer_get_bignum2(&incoming_packet, value);
1110 packet_get_raw(int *length_ptr)
1112 int bytes = buffer_len(&incoming_packet);
1113 if (length_ptr != NULL)
1114 *length_ptr = bytes;
1115 return buffer_ptr(&incoming_packet);
1119 packet_remaining(void)
1121 return buffer_len(&incoming_packet);
1125 * Returns a string from the packet data. The string is allocated using
1126 * xmalloc; it is the responsibility of the calling program to free it when
1127 * no longer needed. The length_ptr argument may be NULL, or point to an
1128 * integer into which the length of the string is stored.
1132 packet_get_string(u_int *length_ptr)
1134 return buffer_get_string(&incoming_packet, length_ptr);
1138 * Sends a diagnostic message from the server to the client. This message
1139 * can be sent at any time (but not while constructing another message). The
1140 * message is printed immediately, but only if the client is being executed
1141 * in verbose mode. These messages are primarily intended to ease debugging
1142 * authentication problems. The length of the formatted message must not
1143 * exceed 1024 bytes. This will automatically call packet_write_wait.
1147 packet_send_debug(const char *fmt,...)
1152 if (compat20 && (datafellows & SSH_BUG_DEBUG))
1155 va_start(args, fmt);
1156 vsnprintf(buf, sizeof(buf), fmt, args);
1160 packet_start(SSH2_MSG_DEBUG);
1161 packet_put_char(0); /* bool: always display */
1162 packet_put_cstring(buf);
1163 packet_put_cstring("");
1165 packet_start(SSH_MSG_DEBUG);
1166 packet_put_cstring(buf);
1169 packet_write_wait();
1173 * Logs the error plus constructs and sends a disconnect packet, closes the
1174 * connection, and exits. This function never returns. The error message
1175 * should not contain a newline. The length of the formatted message must
1176 * not exceed 1024 bytes.
1180 packet_disconnect(const char *fmt,...)
1184 static int disconnecting = 0;
1185 if (disconnecting) /* Guard against recursive invocations. */
1186 fatal("packet_disconnect called recursively.");
1190 * Format the message. Note that the caller must make sure the
1191 * message is of limited size.
1193 va_start(args, fmt);
1194 vsnprintf(buf, sizeof(buf), fmt, args);
1197 /* Send the disconnect message to the other side, and wait for it to get sent. */
1199 packet_start(SSH2_MSG_DISCONNECT);
1200 packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1201 packet_put_cstring(buf);
1202 packet_put_cstring("");
1204 packet_start(SSH_MSG_DISCONNECT);
1205 packet_put_cstring(buf);
1208 packet_write_wait();
1210 /* Stop listening for connections. */
1211 channel_close_all();
1213 /* Close the connection. */
1216 /* Display the error locally and exit. */
1217 log("Disconnecting: %.100s", buf);
1221 /* Checks if there is any buffered output, and tries to write some of the output. */
1224 packet_write_poll(void)
1226 int len = buffer_len(&output);
1228 len = write(connection_out, buffer_ptr(&output), len);
1230 if (errno == EAGAIN)
1233 fatal("Write failed: %.100s", strerror(errno));
1235 buffer_consume(&output, len);
1240 * Calls packet_write_poll repeatedly until all pending output data has been
1245 packet_write_wait(void)
1249 setp = (fd_set *)xmalloc(howmany(connection_out + 1, NFDBITS) *
1251 packet_write_poll();
1252 while (packet_have_data_to_write()) {
1253 memset(setp, 0, howmany(connection_out + 1, NFDBITS) *
1255 FD_SET(connection_out, setp);
1256 while (select(connection_out + 1, NULL, setp, NULL, NULL) == -1 &&
1257 (errno == EAGAIN || errno == EINTR))
1259 packet_write_poll();
1264 /* Returns true if there is buffered data to write to the connection. */
1267 packet_have_data_to_write(void)
1269 return buffer_len(&output) != 0;
1272 /* Returns true if there is not too much data to write to the connection. */
1275 packet_not_very_much_data_to_write(void)
1277 if (interactive_mode)
1278 return buffer_len(&output) < 16384;
1280 return buffer_len(&output) < 128 * 1024;
1283 /* Informs that the current session is interactive. Sets IP flags for that. */
1286 packet_set_interactive(int interactive)
1288 static int called = 0;
1289 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1290 int lowdelay = IPTOS_LOWDELAY;
1291 int throughput = IPTOS_THROUGHPUT;
1298 /* Record that we are in interactive mode. */
1299 interactive_mode = interactive;
1301 /* Only set socket options if using a socket. */
1302 if (!packet_connection_is_on_socket())
1305 * IPTOS_LOWDELAY and IPTOS_THROUGHPUT are IPv4 only
1309 * Set IP options for an interactive connection. Use
1310 * IPTOS_LOWDELAY and TCP_NODELAY.
1312 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1313 if (packet_connection_is_ipv4()) {
1314 if (setsockopt(connection_in, IPPROTO_IP, IP_TOS,
1315 &lowdelay, sizeof(lowdelay)) < 0)
1316 error("setsockopt IPTOS_LOWDELAY: %.100s",
1320 set_nodelay(connection_in);
1321 } else if (packet_connection_is_ipv4()) {
1323 * Set IP options for a non-interactive connection. Use
1326 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1327 if (setsockopt(connection_in, IPPROTO_IP, IP_TOS, &throughput,
1328 sizeof(throughput)) < 0)
1329 error("setsockopt IPTOS_THROUGHPUT: %.100s", strerror(errno));
1334 /* Returns true if the current connection is interactive. */
1337 packet_is_interactive(void)
1339 return interactive_mode;
1343 packet_set_maxsize(int s)
1345 static int called = 0;
1347 log("packet_set_maxsize: called twice: old %d new %d",
1348 max_packet_size, s);
1351 if (s < 4 * 1024 || s > 1024 * 1024) {
1352 log("packet_set_maxsize: bad size %d", s);
1356 debug("packet_set_maxsize: setting to %d", s);
1357 max_packet_size = s;
1361 /* roundup current message to pad bytes */
1363 packet_add_padding(u_char pad)
1369 * 9.2. Ignored Data Message
1371 * byte SSH_MSG_IGNORE
1374 * All implementations MUST understand (and ignore) this message at any
1375 * time (after receiving the protocol version). No implementation is
1376 * required to send them. This message can be used as an additional
1377 * protection measure against advanced traffic analysis techniques.
1380 packet_send_ignore(int nbytes)
1385 packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1386 packet_put_int(nbytes);
1387 for (i = 0; i < nbytes; i++) {
1389 rand = arc4random();
1390 packet_put_char(rand & 0xff);