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.93 2002/03/24 16:01:13 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)
283 if (to.ss_family == AF_INET6 &&
284 IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&to)->sin6_addr))
290 /* Sets the connection into non-blocking mode. */
293 packet_set_nonblocking(void)
295 /* Set the socket into non-blocking mode. */
296 if (fcntl(connection_in, F_SETFL, O_NONBLOCK) < 0)
297 error("fcntl O_NONBLOCK: %.100s", strerror(errno));
299 if (connection_out != connection_in) {
300 if (fcntl(connection_out, F_SETFL, O_NONBLOCK) < 0)
301 error("fcntl O_NONBLOCK: %.100s", strerror(errno));
305 /* Returns the socket used for reading. */
308 packet_get_connection_in(void)
310 return connection_in;
313 /* Returns the descriptor used for writing. */
316 packet_get_connection_out(void)
318 return connection_out;
321 /* Closes the connection and clears and frees internal data structures. */
329 if (connection_in == connection_out) {
330 shutdown(connection_out, SHUT_RDWR);
331 close(connection_out);
333 close(connection_in);
334 close(connection_out);
337 buffer_free(&output);
338 buffer_free(&outgoing_packet);
339 buffer_free(&incoming_packet);
340 if (compression_buffer_ready) {
341 buffer_free(&compression_buffer);
342 buffer_compress_uninit();
344 cipher_cleanup(&send_context);
345 cipher_cleanup(&receive_context);
348 /* Sets remote side protocol flags. */
351 packet_set_protocol_flags(u_int protocol_flags)
353 remote_protocol_flags = protocol_flags;
356 /* Returns the remote protocol flags set earlier by the above function. */
359 packet_get_protocol_flags(void)
361 return remote_protocol_flags;
365 * Starts packet compression from the next packet on in both directions.
366 * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
370 packet_init_compression(void)
372 if (compression_buffer_ready == 1)
374 compression_buffer_ready = 1;
375 buffer_init(&compression_buffer);
379 packet_start_compression(int level)
381 if (packet_compression && !compat20)
382 fatal("Compression already enabled.");
383 packet_compression = 1;
384 packet_init_compression();
385 buffer_compress_init_send(level);
386 buffer_compress_init_recv();
390 * Causes any further packets to be encrypted using the given key. The same
391 * key is used for both sending and reception. However, both directions are
392 * encrypted independently of each other.
395 packet_set_encryption_key(const u_char *key, u_int keylen,
398 Cipher *cipher = cipher_by_number(number);
400 fatal("packet_set_encryption_key: unknown cipher number %d", number);
402 fatal("packet_set_encryption_key: keylen too small: %d", keylen);
403 cipher_init(&send_context, cipher, key, keylen, NULL, 0, CIPHER_ENCRYPT);
404 cipher_init(&receive_context, cipher, key, keylen, NULL, 0, CIPHER_DECRYPT);
407 /* Start constructing a packet to send. */
409 packet_start(u_char type)
414 DBG(debug("packet_start[%d]", type));
415 len = compat20 ? 6 : 9;
416 memset(buf, 0, len - 1);
418 buffer_clear(&outgoing_packet);
419 buffer_append(&outgoing_packet, buf, len);
422 /* Append payload. */
424 packet_put_char(int value)
427 buffer_append(&outgoing_packet, &ch, 1);
430 packet_put_int(u_int value)
432 buffer_put_int(&outgoing_packet, value);
435 packet_put_string(const void *buf, u_int len)
437 buffer_put_string(&outgoing_packet, buf, len);
440 packet_put_cstring(const char *str)
442 buffer_put_cstring(&outgoing_packet, str);
445 packet_put_raw(const void *buf, u_int len)
447 buffer_append(&outgoing_packet, buf, len);
450 packet_put_bignum(BIGNUM * value)
452 buffer_put_bignum(&outgoing_packet, value);
455 packet_put_bignum2(BIGNUM * value)
457 buffer_put_bignum2(&outgoing_packet, value);
461 * Finalizes and sends the packet. If the encryption key has been set,
462 * encrypts the packet before sending.
474 * If using packet compression, compress the payload of the outgoing
477 if (packet_compression) {
478 buffer_clear(&compression_buffer);
480 buffer_consume(&outgoing_packet, 8);
482 buffer_append(&compression_buffer, "\0\0\0\0\0\0\0\0", 8);
483 buffer_compress(&outgoing_packet, &compression_buffer);
484 buffer_clear(&outgoing_packet);
485 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
486 buffer_len(&compression_buffer));
488 /* Compute packet length without padding (add checksum, remove padding). */
489 len = buffer_len(&outgoing_packet) + 4 - 8;
491 /* Insert padding. Initialized to zero in packet_start1() */
492 padding = 8 - len % 8;
493 if (!send_context.plaintext) {
494 cp = buffer_ptr(&outgoing_packet);
495 for (i = 0; i < padding; i++) {
498 cp[7 - i] = rand & 0xff;
502 buffer_consume(&outgoing_packet, 8 - padding);
504 /* Add check bytes. */
505 checksum = ssh_crc32(buffer_ptr(&outgoing_packet),
506 buffer_len(&outgoing_packet));
507 PUT_32BIT(buf, checksum);
508 buffer_append(&outgoing_packet, buf, 4);
511 fprintf(stderr, "packet_send plain: ");
512 buffer_dump(&outgoing_packet);
515 /* Append to output. */
517 buffer_append(&output, buf, 4);
518 cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
519 cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
520 buffer_len(&outgoing_packet));
523 fprintf(stderr, "encrypted: ");
524 buffer_dump(&output);
527 buffer_clear(&outgoing_packet);
530 * Note that the packet is now only buffered in output. It won\'t be
531 * actually sent until packet_write_wait or packet_write_poll is
537 set_newkeys(int mode)
545 debug("newkeys: mode %d", mode);
547 if (mode == MODE_OUT) {
549 encrypt = CIPHER_ENCRYPT;
551 cc = &receive_context;
552 encrypt = CIPHER_DECRYPT;
554 if (newkeys[mode] != NULL) {
555 debug("newkeys: rekeying");
557 enc = &newkeys[mode]->enc;
558 mac = &newkeys[mode]->mac;
559 comp = &newkeys[mode]->comp;
560 memset(mac->key, 0, mac->key_len);
567 xfree(newkeys[mode]);
569 newkeys[mode] = kex_get_newkeys(mode);
570 if (newkeys[mode] == NULL)
571 fatal("newkeys: no keys for mode %d", mode);
572 enc = &newkeys[mode]->enc;
573 mac = &newkeys[mode]->mac;
574 comp = &newkeys[mode]->comp;
577 DBG(debug("cipher_init_context: %d", mode));
578 cipher_init(cc, enc->cipher, enc->key, enc->key_len,
579 enc->iv, enc->block_size, encrypt);
580 /* Deleting the keys does not gain extra security */
581 /* memset(enc->iv, 0, enc->block_size);
582 memset(enc->key, 0, enc->key_len); */
583 if (comp->type != 0 && comp->enabled == 0) {
584 packet_init_compression();
585 if (mode == MODE_OUT)
586 buffer_compress_init_send(6);
588 buffer_compress_init_recv();
594 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
599 u_char type, *cp, *macbuf = NULL;
601 u_int packet_length = 0;
609 if (newkeys[MODE_OUT] != NULL) {
610 enc = &newkeys[MODE_OUT]->enc;
611 mac = &newkeys[MODE_OUT]->mac;
612 comp = &newkeys[MODE_OUT]->comp;
614 block_size = enc ? enc->block_size : 8;
616 cp = buffer_ptr(&outgoing_packet);
620 fprintf(stderr, "plain: ");
621 buffer_dump(&outgoing_packet);
624 if (comp && comp->enabled) {
625 len = buffer_len(&outgoing_packet);
626 /* skip header, compress only payload */
627 buffer_consume(&outgoing_packet, 5);
628 buffer_clear(&compression_buffer);
629 buffer_compress(&outgoing_packet, &compression_buffer);
630 buffer_clear(&outgoing_packet);
631 buffer_append(&outgoing_packet, "\0\0\0\0\0", 5);
632 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
633 buffer_len(&compression_buffer));
634 DBG(debug("compression: raw %d compressed %d", len,
635 buffer_len(&outgoing_packet)));
638 /* sizeof (packet_len + pad_len + payload) */
639 len = buffer_len(&outgoing_packet);
642 * calc size of padding, alloc space, get random data,
643 * minimum padding is 4 bytes
645 padlen = block_size - (len % block_size);
647 padlen += block_size;
649 /* will wrap if extra_pad+padlen > 255 */
650 extra_pad = roundup(extra_pad, block_size);
651 pad = extra_pad - ((len + padlen) % extra_pad);
652 debug3("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
653 pad, len, padlen, extra_pad);
657 cp = buffer_append_space(&outgoing_packet, padlen);
658 if (enc && !send_context.plaintext) {
660 for (i = 0; i < padlen; i++) {
668 memset(cp, 0, padlen);
670 /* packet_length includes payload, padding and padding length field */
671 packet_length = buffer_len(&outgoing_packet) - 4;
672 cp = buffer_ptr(&outgoing_packet);
673 PUT_32BIT(cp, packet_length);
675 DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen));
677 /* compute MAC over seqnr and packet(length fields, payload, padding) */
678 if (mac && mac->enabled) {
679 macbuf = mac_compute(mac, send_seqnr,
680 buffer_ptr(&outgoing_packet),
681 buffer_len(&outgoing_packet));
682 DBG(debug("done calc MAC out #%d", send_seqnr));
684 /* encrypt packet and append to output buffer. */
685 cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
686 cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
687 buffer_len(&outgoing_packet));
688 /* append unencrypted MAC */
689 if (mac && mac->enabled)
690 buffer_append(&output, (char *)macbuf, mac->mac_len);
692 fprintf(stderr, "encrypted: ");
693 buffer_dump(&output);
695 /* increment sequence number for outgoing packets */
696 if (++send_seqnr == 0)
697 log("outgoing seqnr wraps around");
698 buffer_clear(&outgoing_packet);
700 if (type == SSH2_MSG_NEWKEYS)
701 set_newkeys(MODE_OUT);
711 DBG(debug("packet_send done"));
715 * Waits until a packet has been received, and returns its type. Note that
716 * no other data is processed until this returns, so this function should not
717 * be used during the interactive session.
721 packet_read_seqnr(u_int32_t *seqnr_p)
726 DBG(debug("packet_read()"));
728 setp = (fd_set *)xmalloc(howmany(connection_in+1, NFDBITS) *
731 /* Since we are blocking, ensure that all written packets have been sent. */
734 /* Stay in the loop until we have received a complete packet. */
736 /* Try to read a packet from the buffer. */
737 type = packet_read_poll_seqnr(seqnr_p);
739 type == SSH_SMSG_SUCCESS
740 || type == SSH_SMSG_FAILURE
741 || type == SSH_CMSG_EOF
742 || type == SSH_CMSG_EXIT_CONFIRMATION))
744 /* If we got a packet, return it. */
745 if (type != SSH_MSG_NONE) {
750 * Otherwise, wait for some data to arrive, add it to the
751 * buffer, and try again.
753 memset(setp, 0, howmany(connection_in + 1, NFDBITS) *
755 FD_SET(connection_in, setp);
757 /* Wait for some data to arrive. */
758 while (select(connection_in + 1, setp, NULL, NULL, NULL) == -1 &&
759 (errno == EAGAIN || errno == EINTR))
762 /* Read data from the socket. */
763 len = read(connection_in, buf, sizeof(buf));
765 log("Connection closed by %.200s", get_remote_ipaddr());
769 fatal("Read from socket failed: %.100s", strerror(errno));
770 /* Append it to the buffer. */
771 packet_process_incoming(buf, len);
779 return packet_read_seqnr(NULL);
783 * Waits until a packet has been received, verifies that its type matches
784 * that given, and gives a fatal error and exits if there is a mismatch.
788 packet_read_expect(int expected_type)
792 type = packet_read();
793 if (type != expected_type)
794 packet_disconnect("Protocol error: expected packet type %d, got %d",
795 expected_type, type);
798 /* Checks if a full packet is available in the data received so far via
799 * packet_process_incoming. If so, reads the packet; otherwise returns
800 * SSH_MSG_NONE. This does not wait for data from the connection.
802 * SSH_MSG_DISCONNECT is handled specially here. Also,
803 * SSH_MSG_IGNORE messages are skipped by this function and are never returned
808 packet_read_poll1(void)
810 u_int len, padded_len;
812 u_int checksum, stored_checksum;
814 /* Check if input size is less than minimum packet size. */
815 if (buffer_len(&input) < 4 + 8)
817 /* Get length of incoming packet. */
818 cp = buffer_ptr(&input);
820 if (len < 1 + 2 + 2 || len > 256 * 1024)
821 packet_disconnect("Bad packet length %d.", len);
822 padded_len = (len + 8) & ~7;
824 /* Check if the packet has been entirely received. */
825 if (buffer_len(&input) < 4 + padded_len)
828 /* The entire packet is in buffer. */
830 /* Consume packet length. */
831 buffer_consume(&input, 4);
834 * Cryptographic attack detector for ssh
835 * (C)1998 CORE-SDI, Buenos Aires Argentina
836 * Ariel Futoransky(futo@core-sdi.com)
838 if (!receive_context.plaintext &&
839 detect_attack(buffer_ptr(&input), padded_len, NULL) == DEATTACK_DETECTED)
840 packet_disconnect("crc32 compensation attack: network attack detected");
842 /* Decrypt data to incoming_packet. */
843 buffer_clear(&incoming_packet);
844 cp = buffer_append_space(&incoming_packet, padded_len);
845 cipher_crypt(&receive_context, cp, buffer_ptr(&input), padded_len);
847 buffer_consume(&input, padded_len);
850 fprintf(stderr, "read_poll plain: ");
851 buffer_dump(&incoming_packet);
854 /* Compute packet checksum. */
855 checksum = ssh_crc32(buffer_ptr(&incoming_packet),
856 buffer_len(&incoming_packet) - 4);
859 buffer_consume(&incoming_packet, 8 - len % 8);
861 /* Test check bytes. */
862 if (len != buffer_len(&incoming_packet))
863 packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
864 len, buffer_len(&incoming_packet));
866 cp = (u_char *)buffer_ptr(&incoming_packet) + len - 4;
867 stored_checksum = GET_32BIT(cp);
868 if (checksum != stored_checksum)
869 packet_disconnect("Corrupted check bytes on input.");
870 buffer_consume_end(&incoming_packet, 4);
872 if (packet_compression) {
873 buffer_clear(&compression_buffer);
874 buffer_uncompress(&incoming_packet, &compression_buffer);
875 buffer_clear(&incoming_packet);
876 buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
877 buffer_len(&compression_buffer));
879 type = buffer_get_char(&incoming_packet);
884 packet_read_poll2(u_int32_t *seqnr_p)
886 static u_int packet_length = 0;
888 u_char *macbuf, *cp, type;
889 int maclen, block_size;
894 if (newkeys[MODE_IN] != NULL) {
895 enc = &newkeys[MODE_IN]->enc;
896 mac = &newkeys[MODE_IN]->mac;
897 comp = &newkeys[MODE_IN]->comp;
899 maclen = mac && mac->enabled ? mac->mac_len : 0;
900 block_size = enc ? enc->block_size : 8;
902 if (packet_length == 0) {
904 * check if input size is less than the cipher block size,
905 * decrypt first block and extract length of incoming packet
907 if (buffer_len(&input) < block_size)
909 buffer_clear(&incoming_packet);
910 cp = buffer_append_space(&incoming_packet, block_size);
911 cipher_crypt(&receive_context, cp, buffer_ptr(&input),
913 cp = buffer_ptr(&incoming_packet);
914 packet_length = GET_32BIT(cp);
915 if (packet_length < 1 + 4 || packet_length > 256 * 1024) {
916 buffer_dump(&incoming_packet);
917 packet_disconnect("Bad packet length %d.", packet_length);
919 DBG(debug("input: packet len %d", packet_length+4));
920 buffer_consume(&input, block_size);
922 /* we have a partial packet of block_size bytes */
923 need = 4 + packet_length - block_size;
924 DBG(debug("partial packet %d, need %d, maclen %d", block_size,
926 if (need % block_size != 0)
927 fatal("padding error: need %d block %d mod %d",
928 need, block_size, need % block_size);
930 * check if the entire packet has been received and
931 * decrypt into incoming_packet
933 if (buffer_len(&input) < need + maclen)
936 fprintf(stderr, "read_poll enc/full: ");
939 cp = buffer_append_space(&incoming_packet, need);
940 cipher_crypt(&receive_context, cp, buffer_ptr(&input), need);
941 buffer_consume(&input, need);
943 * compute MAC over seqnr and packet,
944 * increment sequence number for incoming packet
946 if (mac && mac->enabled) {
947 macbuf = mac_compute(mac, read_seqnr,
948 buffer_ptr(&incoming_packet),
949 buffer_len(&incoming_packet));
950 if (memcmp(macbuf, buffer_ptr(&input), mac->mac_len) != 0)
951 packet_disconnect("Corrupted MAC on input.");
952 DBG(debug("MAC #%d ok", read_seqnr));
953 buffer_consume(&input, mac->mac_len);
956 *seqnr_p = read_seqnr;
957 if (++read_seqnr == 0)
958 log("incoming seqnr wraps around");
961 cp = buffer_ptr(&incoming_packet);
963 DBG(debug("input: padlen %d", padlen));
965 packet_disconnect("Corrupted padlen %d on input.", padlen);
967 /* skip packet size + padlen, discard padding */
968 buffer_consume(&incoming_packet, 4 + 1);
969 buffer_consume_end(&incoming_packet, padlen);
971 DBG(debug("input: len before de-compress %d", buffer_len(&incoming_packet)));
972 if (comp && comp->enabled) {
973 buffer_clear(&compression_buffer);
974 buffer_uncompress(&incoming_packet, &compression_buffer);
975 buffer_clear(&incoming_packet);
976 buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
977 buffer_len(&compression_buffer));
978 DBG(debug("input: len after de-compress %d", buffer_len(&incoming_packet)));
981 * get packet type, implies consume.
982 * return length of payload (without type field)
984 type = buffer_get_char(&incoming_packet);
985 if (type == SSH2_MSG_NEWKEYS)
986 set_newkeys(MODE_IN);
988 fprintf(stderr, "read/plain[%d]:\r\n", type);
989 buffer_dump(&incoming_packet);
991 /* reset for next packet */
997 packet_read_poll_seqnr(u_int32_t *seqnr_p)
1005 type = packet_read_poll2(seqnr_p);
1007 DBG(debug("received packet type %d", type));
1009 case SSH2_MSG_IGNORE:
1011 case SSH2_MSG_DEBUG:
1013 msg = packet_get_string(NULL);
1014 debug("Remote: %.900s", msg);
1016 msg = packet_get_string(NULL);
1019 case SSH2_MSG_DISCONNECT:
1020 reason = packet_get_int();
1021 msg = packet_get_string(NULL);
1022 log("Received disconnect from %s: %d: %.400s", get_remote_ipaddr(),
1027 case SSH2_MSG_UNIMPLEMENTED:
1028 seqnr = packet_get_int();
1029 debug("Received SSH2_MSG_UNIMPLEMENTED for %d", seqnr);
1036 type = packet_read_poll1();
1038 case SSH_MSG_IGNORE:
1041 msg = packet_get_string(NULL);
1042 debug("Remote: %.900s", msg);
1045 case SSH_MSG_DISCONNECT:
1046 msg = packet_get_string(NULL);
1047 log("Received disconnect from %s: %.400s", get_remote_ipaddr(),
1054 DBG(debug("received packet type %d", type));
1063 packet_read_poll(void)
1065 return packet_read_poll_seqnr(NULL);
1069 * Buffers the given amount of input characters. This is intended to be used
1070 * together with packet_read_poll.
1074 packet_process_incoming(const char *buf, u_int len)
1076 buffer_append(&input, buf, len);
1079 /* Returns a character from the packet. */
1082 packet_get_char(void)
1085 buffer_get(&incoming_packet, &ch, 1);
1089 /* Returns an integer from the packet data. */
1092 packet_get_int(void)
1094 return buffer_get_int(&incoming_packet);
1098 * Returns an arbitrary precision integer from the packet data. The integer
1099 * must have been initialized before this call.
1103 packet_get_bignum(BIGNUM * value)
1105 buffer_get_bignum(&incoming_packet, value);
1109 packet_get_bignum2(BIGNUM * value)
1111 buffer_get_bignum2(&incoming_packet, value);
1115 packet_get_raw(int *length_ptr)
1117 int bytes = buffer_len(&incoming_packet);
1118 if (length_ptr != NULL)
1119 *length_ptr = bytes;
1120 return buffer_ptr(&incoming_packet);
1124 packet_remaining(void)
1126 return buffer_len(&incoming_packet);
1130 * Returns a string from the packet data. The string is allocated using
1131 * xmalloc; it is the responsibility of the calling program to free it when
1132 * no longer needed. The length_ptr argument may be NULL, or point to an
1133 * integer into which the length of the string is stored.
1137 packet_get_string(u_int *length_ptr)
1139 return buffer_get_string(&incoming_packet, length_ptr);
1142 /* Clears incoming data buffer */
1144 void packet_get_all(void)
1146 buffer_clear(&incoming_packet);
1150 * Sends a diagnostic message from the server to the client. This message
1151 * can be sent at any time (but not while constructing another message). The
1152 * message is printed immediately, but only if the client is being executed
1153 * in verbose mode. These messages are primarily intended to ease debugging
1154 * authentication problems. The length of the formatted message must not
1155 * exceed 1024 bytes. This will automatically call packet_write_wait.
1159 packet_send_debug(const char *fmt,...)
1164 if (compat20 && (datafellows & SSH_BUG_DEBUG))
1167 va_start(args, fmt);
1168 vsnprintf(buf, sizeof(buf), fmt, args);
1172 packet_start(SSH2_MSG_DEBUG);
1173 packet_put_char(0); /* bool: always display */
1174 packet_put_cstring(buf);
1175 packet_put_cstring("");
1177 packet_start(SSH_MSG_DEBUG);
1178 packet_put_cstring(buf);
1181 packet_write_wait();
1185 * Logs the error plus constructs and sends a disconnect packet, closes the
1186 * connection, and exits. This function never returns. The error message
1187 * should not contain a newline. The length of the formatted message must
1188 * not exceed 1024 bytes.
1192 packet_disconnect(const char *fmt,...)
1196 static int disconnecting = 0;
1197 if (disconnecting) /* Guard against recursive invocations. */
1198 fatal("packet_disconnect called recursively.");
1202 * Format the message. Note that the caller must make sure the
1203 * message is of limited size.
1205 va_start(args, fmt);
1206 vsnprintf(buf, sizeof(buf), fmt, args);
1209 /* Send the disconnect message to the other side, and wait for it to get sent. */
1211 packet_start(SSH2_MSG_DISCONNECT);
1212 packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1213 packet_put_cstring(buf);
1214 packet_put_cstring("");
1216 packet_start(SSH_MSG_DISCONNECT);
1217 packet_put_cstring(buf);
1220 packet_write_wait();
1222 /* Stop listening for connections. */
1223 channel_close_all();
1225 /* Close the connection. */
1228 /* Display the error locally and exit. */
1229 log("Disconnecting: %.100s", buf);
1233 /* Checks if there is any buffered output, and tries to write some of the output. */
1236 packet_write_poll(void)
1238 int len = buffer_len(&output);
1240 len = write(connection_out, buffer_ptr(&output), len);
1242 if (errno == EAGAIN)
1245 fatal("Write failed: %.100s", strerror(errno));
1247 buffer_consume(&output, len);
1252 * Calls packet_write_poll repeatedly until all pending output data has been
1257 packet_write_wait(void)
1261 setp = (fd_set *)xmalloc(howmany(connection_out + 1, NFDBITS) *
1263 packet_write_poll();
1264 while (packet_have_data_to_write()) {
1265 memset(setp, 0, howmany(connection_out + 1, NFDBITS) *
1267 FD_SET(connection_out, setp);
1268 while (select(connection_out + 1, NULL, setp, NULL, NULL) == -1 &&
1269 (errno == EAGAIN || errno == EINTR))
1271 packet_write_poll();
1276 /* Returns true if there is buffered data to write to the connection. */
1279 packet_have_data_to_write(void)
1281 return buffer_len(&output) != 0;
1284 /* Returns true if there is not too much data to write to the connection. */
1287 packet_not_very_much_data_to_write(void)
1289 if (interactive_mode)
1290 return buffer_len(&output) < 16384;
1292 return buffer_len(&output) < 128 * 1024;
1295 /* Informs that the current session is interactive. Sets IP flags for that. */
1298 packet_set_interactive(int interactive)
1300 static int called = 0;
1301 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1302 int lowdelay = IPTOS_LOWDELAY;
1303 int throughput = IPTOS_THROUGHPUT;
1310 /* Record that we are in interactive mode. */
1311 interactive_mode = interactive;
1313 /* Only set socket options if using a socket. */
1314 if (!packet_connection_is_on_socket())
1317 * IPTOS_LOWDELAY and IPTOS_THROUGHPUT are IPv4 only
1321 * Set IP options for an interactive connection. Use
1322 * IPTOS_LOWDELAY and TCP_NODELAY.
1324 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1325 if (packet_connection_is_ipv4()) {
1326 if (setsockopt(connection_in, IPPROTO_IP, IP_TOS,
1327 &lowdelay, sizeof(lowdelay)) < 0)
1328 error("setsockopt IPTOS_LOWDELAY: %.100s",
1332 set_nodelay(connection_in);
1333 } else if (packet_connection_is_ipv4()) {
1335 * Set IP options for a non-interactive connection. Use
1338 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1339 if (setsockopt(connection_in, IPPROTO_IP, IP_TOS, &throughput,
1340 sizeof(throughput)) < 0)
1341 error("setsockopt IPTOS_THROUGHPUT: %.100s", strerror(errno));
1346 /* Returns true if the current connection is interactive. */
1349 packet_is_interactive(void)
1351 return interactive_mode;
1355 packet_set_maxsize(int s)
1357 static int called = 0;
1359 log("packet_set_maxsize: called twice: old %d new %d",
1360 max_packet_size, s);
1363 if (s < 4 * 1024 || s > 1024 * 1024) {
1364 log("packet_set_maxsize: bad size %d", s);
1368 debug("packet_set_maxsize: setting to %d", s);
1369 max_packet_size = s;
1373 /* roundup current message to pad bytes */
1375 packet_add_padding(u_char pad)
1381 * 9.2. Ignored Data Message
1383 * byte SSH_MSG_IGNORE
1386 * All implementations MUST understand (and ignore) this message at any
1387 * time (after receiving the protocol version). No implementation is
1388 * required to send them. This message can be used as an additional
1389 * protection measure against advanced traffic analysis techniques.
1392 packet_send_ignore(int nbytes)
1397 packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1398 packet_put_int(nbytes);
1399 for (i = 0; i < nbytes; i++) {
1401 rand = arc4random();
1402 packet_put_char(rand & 0xff);