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.105 2003/04/02 09:48:07 markus Exp $");
42 #include "openbsd-compat/sys-queue.h"
74 * This variable contains the file descriptors used for communicating with
75 * the other side. connection_in is used for reading; connection_out for
76 * writing. These can be the same descriptor, in which case it is assumed to
79 static int connection_in = -1;
80 static int connection_out = -1;
82 /* Protocol flags for the remote side. */
83 static u_int remote_protocol_flags = 0;
85 /* Encryption context for receiving data. This is only used for decryption. */
86 static CipherContext receive_context;
88 /* Encryption context for sending data. This is only used for encryption. */
89 static CipherContext send_context;
91 /* Buffer for raw input data from the socket. */
94 /* Buffer for raw output data going to the socket. */
97 /* Buffer for the partial outgoing packet being constructed. */
98 static Buffer outgoing_packet;
100 /* Buffer for the incoming packet currently being processed. */
101 static Buffer incoming_packet;
103 /* Scratch buffer for packet compression/decompression. */
104 static Buffer compression_buffer;
105 static int compression_buffer_ready = 0;
107 /* Flag indicating whether packet compression/decompression is enabled. */
108 static int packet_compression = 0;
110 /* default maximum packet size */
111 int max_packet_size = 32768;
113 /* Flag indicating whether this module has been initialized. */
114 static int initialized = 0;
116 /* Set to true if the connection is interactive. */
117 static int interactive_mode = 0;
119 /* Session key information for Encryption and MAC */
120 Newkeys *newkeys[MODE_MAX];
121 static struct packet_state {
127 static u_int64_t max_blocks_in, max_blocks_out;
128 static u_int32_t rekey_limit;
130 /* Session key for protocol v1 */
131 static u_char ssh1_key[SSH_SESSION_KEY_LENGTH];
132 static u_int ssh1_keylen;
134 /* roundup current message to extra_pad bytes */
135 static u_char extra_pad = 0;
138 TAILQ_ENTRY(packet) next;
142 TAILQ_HEAD(, packet) outgoing;
145 * Sets the descriptors used for communication. Disables encryption until
146 * packet_set_encryption_key is called.
149 packet_set_connection(int fd_in, int fd_out)
151 Cipher *none = cipher_by_name("none");
154 fatal("packet_set_connection: cannot load cipher 'none'");
155 connection_in = fd_in;
156 connection_out = fd_out;
157 cipher_init(&send_context, none, "", 0, NULL, 0, CIPHER_ENCRYPT);
158 cipher_init(&receive_context, none, "", 0, NULL, 0, CIPHER_DECRYPT);
159 newkeys[MODE_IN] = newkeys[MODE_OUT] = NULL;
163 buffer_init(&output);
164 buffer_init(&outgoing_packet);
165 buffer_init(&incoming_packet);
166 TAILQ_INIT(&outgoing);
168 /* Kludge: arrange the close function to be called from fatal(). */
169 fatal_add_cleanup((void (*) (void *)) packet_close, NULL);
172 /* Returns 1 if remote host is connected via socket, 0 if not. */
175 packet_connection_is_on_socket(void)
177 struct sockaddr_storage from, to;
178 socklen_t fromlen, tolen;
180 /* filedescriptors in and out are the same, so it's a socket */
181 if (connection_in == connection_out)
183 fromlen = sizeof(from);
184 memset(&from, 0, sizeof(from));
185 if (getpeername(connection_in, (struct sockaddr *)&from, &fromlen) < 0)
188 memset(&to, 0, sizeof(to));
189 if (getpeername(connection_out, (struct sockaddr *)&to, &tolen) < 0)
191 if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
193 if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
199 * Exports an IV from the CipherContext required to export the key
200 * state back from the unprivileged child to the privileged parent
205 packet_get_keyiv(int mode, u_char *iv, u_int len)
209 if (mode == MODE_OUT)
212 cc = &receive_context;
214 cipher_get_keyiv(cc, iv, len);
218 packet_get_keycontext(int mode, u_char *dat)
222 if (mode == MODE_OUT)
225 cc = &receive_context;
227 return (cipher_get_keycontext(cc, dat));
231 packet_set_keycontext(int mode, u_char *dat)
235 if (mode == MODE_OUT)
238 cc = &receive_context;
240 cipher_set_keycontext(cc, dat);
244 packet_get_keyiv_len(int mode)
248 if (mode == MODE_OUT)
251 cc = &receive_context;
253 return (cipher_get_keyiv_len(cc));
256 packet_set_iv(int mode, u_char *dat)
260 if (mode == MODE_OUT)
263 cc = &receive_context;
265 cipher_set_keyiv(cc, dat);
268 packet_get_ssh1_cipher()
270 return (cipher_get_number(receive_context.cipher));
274 packet_get_state(int mode, u_int32_t *seqnr, u_int64_t *blocks, u_int32_t *packets)
276 struct packet_state *state;
278 state = (mode == MODE_IN) ? &p_read : &p_send;
279 *seqnr = state->seqnr;
280 *blocks = state->blocks;
281 *packets = state->packets;
285 packet_set_state(int mode, u_int32_t seqnr, u_int64_t blocks, u_int32_t packets)
287 struct packet_state *state;
289 state = (mode == MODE_IN) ? &p_read : &p_send;
290 state->seqnr = seqnr;
291 state->blocks = blocks;
292 state->packets = packets;
295 /* returns 1 if connection is via ipv4 */
298 packet_connection_is_ipv4(void)
300 struct sockaddr_storage to;
301 socklen_t tolen = sizeof(to);
303 memset(&to, 0, sizeof(to));
304 if (getsockname(connection_out, (struct sockaddr *)&to, &tolen) < 0)
306 if (to.ss_family == AF_INET)
309 if (to.ss_family == AF_INET6 &&
310 IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&to)->sin6_addr))
316 /* Sets the connection into non-blocking mode. */
319 packet_set_nonblocking(void)
321 /* Set the socket into non-blocking mode. */
322 if (fcntl(connection_in, F_SETFL, O_NONBLOCK) < 0)
323 error("fcntl O_NONBLOCK: %.100s", strerror(errno));
325 if (connection_out != connection_in) {
326 if (fcntl(connection_out, F_SETFL, O_NONBLOCK) < 0)
327 error("fcntl O_NONBLOCK: %.100s", strerror(errno));
331 /* Returns the socket used for reading. */
334 packet_get_connection_in(void)
336 return connection_in;
339 /* Returns the descriptor used for writing. */
342 packet_get_connection_out(void)
344 return connection_out;
347 /* Closes the connection and clears and frees internal data structures. */
355 if (connection_in == connection_out) {
356 shutdown(connection_out, SHUT_RDWR);
357 close(connection_out);
359 close(connection_in);
360 close(connection_out);
363 buffer_free(&output);
364 buffer_free(&outgoing_packet);
365 buffer_free(&incoming_packet);
366 if (compression_buffer_ready) {
367 buffer_free(&compression_buffer);
368 buffer_compress_uninit();
370 cipher_cleanup(&send_context);
371 cipher_cleanup(&receive_context);
374 /* Sets remote side protocol flags. */
377 packet_set_protocol_flags(u_int protocol_flags)
379 remote_protocol_flags = protocol_flags;
382 /* Returns the remote protocol flags set earlier by the above function. */
385 packet_get_protocol_flags(void)
387 return remote_protocol_flags;
391 * Starts packet compression from the next packet on in both directions.
392 * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
396 packet_init_compression(void)
398 if (compression_buffer_ready == 1)
400 compression_buffer_ready = 1;
401 buffer_init(&compression_buffer);
405 packet_start_compression(int level)
407 if (packet_compression && !compat20)
408 fatal("Compression already enabled.");
409 packet_compression = 1;
410 packet_init_compression();
411 buffer_compress_init_send(level);
412 buffer_compress_init_recv();
416 * Causes any further packets to be encrypted using the given key. The same
417 * key is used for both sending and reception. However, both directions are
418 * encrypted independently of each other.
422 packet_set_encryption_key(const u_char *key, u_int keylen,
425 Cipher *cipher = cipher_by_number(number);
428 fatal("packet_set_encryption_key: unknown cipher number %d", number);
430 fatal("packet_set_encryption_key: keylen too small: %d", keylen);
431 if (keylen > SSH_SESSION_KEY_LENGTH)
432 fatal("packet_set_encryption_key: keylen too big: %d", keylen);
433 memcpy(ssh1_key, key, keylen);
434 ssh1_keylen = keylen;
435 cipher_init(&send_context, cipher, key, keylen, NULL, 0, CIPHER_ENCRYPT);
436 cipher_init(&receive_context, cipher, key, keylen, NULL, 0, CIPHER_DECRYPT);
440 packet_get_encryption_key(u_char *key)
443 return (ssh1_keylen);
444 memcpy(key, ssh1_key, ssh1_keylen);
445 return (ssh1_keylen);
448 /* Start constructing a packet to send. */
450 packet_start(u_char type)
455 DBG(debug("packet_start[%d]", type));
456 len = compat20 ? 6 : 9;
457 memset(buf, 0, len - 1);
459 buffer_clear(&outgoing_packet);
460 buffer_append(&outgoing_packet, buf, len);
463 /* Append payload. */
465 packet_put_char(int value)
469 buffer_append(&outgoing_packet, &ch, 1);
472 packet_put_int(u_int value)
474 buffer_put_int(&outgoing_packet, value);
477 packet_put_string(const void *buf, u_int len)
479 buffer_put_string(&outgoing_packet, buf, len);
482 packet_put_cstring(const char *str)
484 buffer_put_cstring(&outgoing_packet, str);
487 packet_put_raw(const void *buf, u_int len)
489 buffer_append(&outgoing_packet, buf, len);
492 packet_put_bignum(BIGNUM * value)
494 buffer_put_bignum(&outgoing_packet, value);
497 packet_put_bignum2(BIGNUM * value)
499 buffer_put_bignum2(&outgoing_packet, value);
503 * Finalizes and sends the packet. If the encryption key has been set,
504 * encrypts the packet before sending.
516 * If using packet compression, compress the payload of the outgoing
519 if (packet_compression) {
520 buffer_clear(&compression_buffer);
522 buffer_consume(&outgoing_packet, 8);
524 buffer_append(&compression_buffer, "\0\0\0\0\0\0\0\0", 8);
525 buffer_compress(&outgoing_packet, &compression_buffer);
526 buffer_clear(&outgoing_packet);
527 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
528 buffer_len(&compression_buffer));
530 /* Compute packet length without padding (add checksum, remove padding). */
531 len = buffer_len(&outgoing_packet) + 4 - 8;
533 /* Insert padding. Initialized to zero in packet_start1() */
534 padding = 8 - len % 8;
535 if (!send_context.plaintext) {
536 cp = buffer_ptr(&outgoing_packet);
537 for (i = 0; i < padding; i++) {
540 cp[7 - i] = rand & 0xff;
544 buffer_consume(&outgoing_packet, 8 - padding);
546 /* Add check bytes. */
547 checksum = ssh_crc32(buffer_ptr(&outgoing_packet),
548 buffer_len(&outgoing_packet));
549 PUT_32BIT(buf, checksum);
550 buffer_append(&outgoing_packet, buf, 4);
553 fprintf(stderr, "packet_send plain: ");
554 buffer_dump(&outgoing_packet);
557 /* Append to output. */
559 buffer_append(&output, buf, 4);
560 cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
561 cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
562 buffer_len(&outgoing_packet));
565 fprintf(stderr, "encrypted: ");
566 buffer_dump(&output);
569 buffer_clear(&outgoing_packet);
572 * Note that the packet is now only buffered in output. It won\'t be
573 * actually sent until packet_write_wait or packet_write_poll is
579 set_newkeys(int mode)
585 u_int64_t *max_blocks;
588 debug2("set_newkeys: mode %d", mode);
590 if (mode == MODE_OUT) {
592 encrypt = CIPHER_ENCRYPT;
593 p_send.packets = p_send.blocks = 0;
594 max_blocks = &max_blocks_out;
596 cc = &receive_context;
597 encrypt = CIPHER_DECRYPT;
598 p_read.packets = p_read.blocks = 0;
599 max_blocks = &max_blocks_in;
601 if (newkeys[mode] != NULL) {
602 debug("set_newkeys: rekeying");
604 enc = &newkeys[mode]->enc;
605 mac = &newkeys[mode]->mac;
606 comp = &newkeys[mode]->comp;
607 memset(mac->key, 0, mac->key_len);
614 xfree(newkeys[mode]);
616 newkeys[mode] = kex_get_newkeys(mode);
617 if (newkeys[mode] == NULL)
618 fatal("newkeys: no keys for mode %d", mode);
619 enc = &newkeys[mode]->enc;
620 mac = &newkeys[mode]->mac;
621 comp = &newkeys[mode]->comp;
624 DBG(debug("cipher_init_context: %d", mode));
625 cipher_init(cc, enc->cipher, enc->key, enc->key_len,
626 enc->iv, enc->block_size, encrypt);
627 /* Deleting the keys does not gain extra security */
628 /* memset(enc->iv, 0, enc->block_size);
629 memset(enc->key, 0, enc->key_len); */
630 if (comp->type != 0 && comp->enabled == 0) {
631 packet_init_compression();
632 if (mode == MODE_OUT)
633 buffer_compress_init_send(6);
635 buffer_compress_init_recv();
638 *max_blocks = ((u_int64_t)1 << (enc->block_size*2));
640 *max_blocks = MIN(*max_blocks, rekey_limit / enc->block_size);
644 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
647 packet_send2_wrapped(void)
649 u_char type, *cp, *macbuf = NULL;
651 u_int packet_length = 0;
659 if (newkeys[MODE_OUT] != NULL) {
660 enc = &newkeys[MODE_OUT]->enc;
661 mac = &newkeys[MODE_OUT]->mac;
662 comp = &newkeys[MODE_OUT]->comp;
664 block_size = enc ? enc->block_size : 8;
666 cp = buffer_ptr(&outgoing_packet);
670 fprintf(stderr, "plain: ");
671 buffer_dump(&outgoing_packet);
674 if (comp && comp->enabled) {
675 len = buffer_len(&outgoing_packet);
676 /* skip header, compress only payload */
677 buffer_consume(&outgoing_packet, 5);
678 buffer_clear(&compression_buffer);
679 buffer_compress(&outgoing_packet, &compression_buffer);
680 buffer_clear(&outgoing_packet);
681 buffer_append(&outgoing_packet, "\0\0\0\0\0", 5);
682 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
683 buffer_len(&compression_buffer));
684 DBG(debug("compression: raw %d compressed %d", len,
685 buffer_len(&outgoing_packet)));
688 /* sizeof (packet_len + pad_len + payload) */
689 len = buffer_len(&outgoing_packet);
692 * calc size of padding, alloc space, get random data,
693 * minimum padding is 4 bytes
695 padlen = block_size - (len % block_size);
697 padlen += block_size;
699 /* will wrap if extra_pad+padlen > 255 */
700 extra_pad = roundup(extra_pad, block_size);
701 pad = extra_pad - ((len + padlen) % extra_pad);
702 debug3("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
703 pad, len, padlen, extra_pad);
707 cp = buffer_append_space(&outgoing_packet, padlen);
708 if (enc && !send_context.plaintext) {
710 for (i = 0; i < padlen; i++) {
718 memset(cp, 0, padlen);
720 /* packet_length includes payload, padding and padding length field */
721 packet_length = buffer_len(&outgoing_packet) - 4;
722 cp = buffer_ptr(&outgoing_packet);
723 PUT_32BIT(cp, packet_length);
725 DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen));
727 /* compute MAC over seqnr and packet(length fields, payload, padding) */
728 if (mac && mac->enabled) {
729 macbuf = mac_compute(mac, p_send.seqnr,
730 buffer_ptr(&outgoing_packet),
731 buffer_len(&outgoing_packet));
732 DBG(debug("done calc MAC out #%d", p_send.seqnr));
734 /* encrypt packet and append to output buffer. */
735 cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
736 cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
737 buffer_len(&outgoing_packet));
738 /* append unencrypted MAC */
739 if (mac && mac->enabled)
740 buffer_append(&output, (char *)macbuf, mac->mac_len);
742 fprintf(stderr, "encrypted: ");
743 buffer_dump(&output);
745 /* increment sequence number for outgoing packets */
746 if (++p_send.seqnr == 0)
747 logit("outgoing seqnr wraps around");
748 if (++p_send.packets == 0)
749 if (!(datafellows & SSH_BUG_NOREKEY))
750 fatal("XXX too many packets with same key");
751 p_send.blocks += (packet_length + 4) / block_size;
752 buffer_clear(&outgoing_packet);
754 if (type == SSH2_MSG_NEWKEYS)
755 set_newkeys(MODE_OUT);
761 static int rekeying = 0;
765 cp = buffer_ptr(&outgoing_packet);
768 /* during rekeying we can only send key exchange messages */
770 if (!((type >= SSH2_MSG_TRANSPORT_MIN) &&
771 (type <= SSH2_MSG_TRANSPORT_MAX))) {
772 debug("enqueue packet: %u", type);
773 p = xmalloc(sizeof(*p));
775 memcpy(&p->payload, &outgoing_packet, sizeof(Buffer));
776 buffer_init(&outgoing_packet);
777 TAILQ_INSERT_TAIL(&outgoing, p, next);
782 /* rekeying starts with sending KEXINIT */
783 if (type == SSH2_MSG_KEXINIT)
786 packet_send2_wrapped();
788 /* after a NEWKEYS message we can send the complete queue */
789 if (type == SSH2_MSG_NEWKEYS) {
791 while ((p = TAILQ_FIRST(&outgoing))) {
793 debug("dequeue packet: %u", type);
794 buffer_free(&outgoing_packet);
795 memcpy(&outgoing_packet, &p->payload,
797 TAILQ_REMOVE(&outgoing, p, next);
799 packet_send2_wrapped();
811 DBG(debug("packet_send done"));
815 * Waits until a packet has been received, and returns its type. Note that
816 * no other data is processed until this returns, so this function should not
817 * be used during the interactive session.
821 packet_read_seqnr(u_int32_t *seqnr_p)
826 DBG(debug("packet_read()"));
828 setp = (fd_set *)xmalloc(howmany(connection_in+1, NFDBITS) *
831 /* Since we are blocking, ensure that all written packets have been sent. */
834 /* Stay in the loop until we have received a complete packet. */
836 /* Try to read a packet from the buffer. */
837 type = packet_read_poll_seqnr(seqnr_p);
839 type == SSH_SMSG_SUCCESS
840 || type == SSH_SMSG_FAILURE
841 || type == SSH_CMSG_EOF
842 || type == SSH_CMSG_EXIT_CONFIRMATION))
844 /* If we got a packet, return it. */
845 if (type != SSH_MSG_NONE) {
850 * Otherwise, wait for some data to arrive, add it to the
851 * buffer, and try again.
853 memset(setp, 0, howmany(connection_in + 1, NFDBITS) *
855 FD_SET(connection_in, setp);
857 /* Wait for some data to arrive. */
858 while (select(connection_in + 1, setp, NULL, NULL, NULL) == -1 &&
859 (errno == EAGAIN || errno == EINTR))
862 /* Read data from the socket. */
863 len = read(connection_in, buf, sizeof(buf));
865 logit("Connection closed by %.200s", get_remote_ipaddr());
869 fatal("Read from socket failed: %.100s", strerror(errno));
870 /* Append it to the buffer. */
871 packet_process_incoming(buf, len);
879 return packet_read_seqnr(NULL);
883 * Waits until a packet has been received, verifies that its type matches
884 * that given, and gives a fatal error and exits if there is a mismatch.
888 packet_read_expect(int expected_type)
892 type = packet_read();
893 if (type != expected_type)
894 packet_disconnect("Protocol error: expected packet type %d, got %d",
895 expected_type, type);
898 /* Checks if a full packet is available in the data received so far via
899 * packet_process_incoming. If so, reads the packet; otherwise returns
900 * SSH_MSG_NONE. This does not wait for data from the connection.
902 * SSH_MSG_DISCONNECT is handled specially here. Also,
903 * SSH_MSG_IGNORE messages are skipped by this function and are never returned
908 packet_read_poll1(void)
910 u_int len, padded_len;
912 u_int checksum, stored_checksum;
914 /* Check if input size is less than minimum packet size. */
915 if (buffer_len(&input) < 4 + 8)
917 /* Get length of incoming packet. */
918 cp = buffer_ptr(&input);
920 if (len < 1 + 2 + 2 || len > 256 * 1024)
921 packet_disconnect("Bad packet length %u.", len);
922 padded_len = (len + 8) & ~7;
924 /* Check if the packet has been entirely received. */
925 if (buffer_len(&input) < 4 + padded_len)
928 /* The entire packet is in buffer. */
930 /* Consume packet length. */
931 buffer_consume(&input, 4);
934 * Cryptographic attack detector for ssh
935 * (C)1998 CORE-SDI, Buenos Aires Argentina
936 * Ariel Futoransky(futo@core-sdi.com)
938 if (!receive_context.plaintext &&
939 detect_attack(buffer_ptr(&input), padded_len, NULL) == DEATTACK_DETECTED)
940 packet_disconnect("crc32 compensation attack: network attack detected");
942 /* Decrypt data to incoming_packet. */
943 buffer_clear(&incoming_packet);
944 cp = buffer_append_space(&incoming_packet, padded_len);
945 cipher_crypt(&receive_context, cp, buffer_ptr(&input), padded_len);
947 buffer_consume(&input, padded_len);
950 fprintf(stderr, "read_poll plain: ");
951 buffer_dump(&incoming_packet);
954 /* Compute packet checksum. */
955 checksum = ssh_crc32(buffer_ptr(&incoming_packet),
956 buffer_len(&incoming_packet) - 4);
959 buffer_consume(&incoming_packet, 8 - len % 8);
961 /* Test check bytes. */
962 if (len != buffer_len(&incoming_packet))
963 packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
964 len, buffer_len(&incoming_packet));
966 cp = (u_char *)buffer_ptr(&incoming_packet) + len - 4;
967 stored_checksum = GET_32BIT(cp);
968 if (checksum != stored_checksum)
969 packet_disconnect("Corrupted check bytes on input.");
970 buffer_consume_end(&incoming_packet, 4);
972 if (packet_compression) {
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));
979 type = buffer_get_char(&incoming_packet);
984 packet_read_poll2(u_int32_t *seqnr_p)
986 static u_int packet_length = 0;
988 u_char *macbuf, *cp, type;
989 int maclen, block_size;
994 if (newkeys[MODE_IN] != NULL) {
995 enc = &newkeys[MODE_IN]->enc;
996 mac = &newkeys[MODE_IN]->mac;
997 comp = &newkeys[MODE_IN]->comp;
999 maclen = mac && mac->enabled ? mac->mac_len : 0;
1000 block_size = enc ? enc->block_size : 8;
1002 if (packet_length == 0) {
1004 * check if input size is less than the cipher block size,
1005 * decrypt first block and extract length of incoming packet
1007 if (buffer_len(&input) < block_size)
1008 return SSH_MSG_NONE;
1009 buffer_clear(&incoming_packet);
1010 cp = buffer_append_space(&incoming_packet, block_size);
1011 cipher_crypt(&receive_context, cp, buffer_ptr(&input),
1013 cp = buffer_ptr(&incoming_packet);
1014 packet_length = GET_32BIT(cp);
1015 if (packet_length < 1 + 4 || packet_length > 256 * 1024) {
1016 buffer_dump(&incoming_packet);
1017 packet_disconnect("Bad packet length %u.", packet_length);
1019 DBG(debug("input: packet len %u", packet_length+4));
1020 buffer_consume(&input, block_size);
1022 /* we have a partial packet of block_size bytes */
1023 need = 4 + packet_length - block_size;
1024 DBG(debug("partial packet %d, need %d, maclen %d", block_size,
1026 if (need % block_size != 0)
1027 fatal("padding error: need %d block %d mod %d",
1028 need, block_size, need % block_size);
1030 * check if the entire packet has been received and
1031 * decrypt into incoming_packet
1033 if (buffer_len(&input) < need + maclen)
1034 return SSH_MSG_NONE;
1036 fprintf(stderr, "read_poll enc/full: ");
1037 buffer_dump(&input);
1039 cp = buffer_append_space(&incoming_packet, need);
1040 cipher_crypt(&receive_context, cp, buffer_ptr(&input), need);
1041 buffer_consume(&input, need);
1043 * compute MAC over seqnr and packet,
1044 * increment sequence number for incoming packet
1046 if (mac && mac->enabled) {
1047 macbuf = mac_compute(mac, p_read.seqnr,
1048 buffer_ptr(&incoming_packet),
1049 buffer_len(&incoming_packet));
1050 if (memcmp(macbuf, buffer_ptr(&input), mac->mac_len) != 0)
1051 packet_disconnect("Corrupted MAC on input.");
1052 DBG(debug("MAC #%d ok", p_read.seqnr));
1053 buffer_consume(&input, mac->mac_len);
1055 if (seqnr_p != NULL)
1056 *seqnr_p = p_read.seqnr;
1057 if (++p_read.seqnr == 0)
1058 logit("incoming seqnr wraps around");
1059 if (++p_read.packets == 0)
1060 if (!(datafellows & SSH_BUG_NOREKEY))
1061 fatal("XXX too many packets with same key");
1062 p_read.blocks += (packet_length + 4) / block_size;
1065 cp = buffer_ptr(&incoming_packet);
1067 DBG(debug("input: padlen %d", padlen));
1069 packet_disconnect("Corrupted padlen %d on input.", padlen);
1071 /* skip packet size + padlen, discard padding */
1072 buffer_consume(&incoming_packet, 4 + 1);
1073 buffer_consume_end(&incoming_packet, padlen);
1075 DBG(debug("input: len before de-compress %d", buffer_len(&incoming_packet)));
1076 if (comp && comp->enabled) {
1077 buffer_clear(&compression_buffer);
1078 buffer_uncompress(&incoming_packet, &compression_buffer);
1079 buffer_clear(&incoming_packet);
1080 buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
1081 buffer_len(&compression_buffer));
1082 DBG(debug("input: len after de-compress %d",
1083 buffer_len(&incoming_packet)));
1086 * get packet type, implies consume.
1087 * return length of payload (without type field)
1089 type = buffer_get_char(&incoming_packet);
1090 if (type == SSH2_MSG_NEWKEYS)
1091 set_newkeys(MODE_IN);
1093 fprintf(stderr, "read/plain[%d]:\r\n", type);
1094 buffer_dump(&incoming_packet);
1096 /* reset for next packet */
1102 packet_read_poll_seqnr(u_int32_t *seqnr_p)
1104 u_int reason, seqnr;
1110 type = packet_read_poll2(seqnr_p);
1112 DBG(debug("received packet type %d", type));
1114 case SSH2_MSG_IGNORE:
1116 case SSH2_MSG_DEBUG:
1118 msg = packet_get_string(NULL);
1119 debug("Remote: %.900s", msg);
1121 msg = packet_get_string(NULL);
1124 case SSH2_MSG_DISCONNECT:
1125 reason = packet_get_int();
1126 msg = packet_get_string(NULL);
1127 logit("Received disconnect from %s: %u: %.400s",
1128 get_remote_ipaddr(), reason, msg);
1132 case SSH2_MSG_UNIMPLEMENTED:
1133 seqnr = packet_get_int();
1134 debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1142 type = packet_read_poll1();
1144 case SSH_MSG_IGNORE:
1147 msg = packet_get_string(NULL);
1148 debug("Remote: %.900s", msg);
1151 case SSH_MSG_DISCONNECT:
1152 msg = packet_get_string(NULL);
1153 logit("Received disconnect from %s: %.400s",
1154 get_remote_ipaddr(), msg);
1160 DBG(debug("received packet type %d", type));
1169 packet_read_poll(void)
1171 return packet_read_poll_seqnr(NULL);
1175 * Buffers the given amount of input characters. This is intended to be used
1176 * together with packet_read_poll.
1180 packet_process_incoming(const char *buf, u_int len)
1182 buffer_append(&input, buf, len);
1185 /* Returns a character from the packet. */
1188 packet_get_char(void)
1192 buffer_get(&incoming_packet, &ch, 1);
1196 /* Returns an integer from the packet data. */
1199 packet_get_int(void)
1201 return buffer_get_int(&incoming_packet);
1205 * Returns an arbitrary precision integer from the packet data. The integer
1206 * must have been initialized before this call.
1210 packet_get_bignum(BIGNUM * value)
1212 buffer_get_bignum(&incoming_packet, value);
1216 packet_get_bignum2(BIGNUM * value)
1218 buffer_get_bignum2(&incoming_packet, value);
1222 packet_get_raw(int *length_ptr)
1224 int bytes = buffer_len(&incoming_packet);
1226 if (length_ptr != NULL)
1227 *length_ptr = bytes;
1228 return buffer_ptr(&incoming_packet);
1232 packet_remaining(void)
1234 return buffer_len(&incoming_packet);
1238 * Returns a string from the packet data. The string is allocated using
1239 * xmalloc; it is the responsibility of the calling program to free it when
1240 * no longer needed. The length_ptr argument may be NULL, or point to an
1241 * integer into which the length of the string is stored.
1245 packet_get_string(u_int *length_ptr)
1247 return buffer_get_string(&incoming_packet, length_ptr);
1251 * Sends a diagnostic message from the server to the client. This message
1252 * can be sent at any time (but not while constructing another message). The
1253 * message is printed immediately, but only if the client is being executed
1254 * in verbose mode. These messages are primarily intended to ease debugging
1255 * authentication problems. The length of the formatted message must not
1256 * exceed 1024 bytes. This will automatically call packet_write_wait.
1260 packet_send_debug(const char *fmt,...)
1265 if (compat20 && (datafellows & SSH_BUG_DEBUG))
1268 va_start(args, fmt);
1269 vsnprintf(buf, sizeof(buf), fmt, args);
1273 packet_start(SSH2_MSG_DEBUG);
1274 packet_put_char(0); /* bool: always display */
1275 packet_put_cstring(buf);
1276 packet_put_cstring("");
1278 packet_start(SSH_MSG_DEBUG);
1279 packet_put_cstring(buf);
1282 packet_write_wait();
1286 * Logs the error plus constructs and sends a disconnect packet, closes the
1287 * connection, and exits. This function never returns. The error message
1288 * should not contain a newline. The length of the formatted message must
1289 * not exceed 1024 bytes.
1293 packet_disconnect(const char *fmt,...)
1297 static int disconnecting = 0;
1299 if (disconnecting) /* Guard against recursive invocations. */
1300 fatal("packet_disconnect called recursively.");
1304 * Format the message. Note that the caller must make sure the
1305 * message is of limited size.
1307 va_start(args, fmt);
1308 vsnprintf(buf, sizeof(buf), fmt, args);
1311 /* Display the error locally */
1312 logit("Disconnecting: %.100s", buf);
1314 /* Send the disconnect message to the other side, and wait for it to get sent. */
1316 packet_start(SSH2_MSG_DISCONNECT);
1317 packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1318 packet_put_cstring(buf);
1319 packet_put_cstring("");
1321 packet_start(SSH_MSG_DISCONNECT);
1322 packet_put_cstring(buf);
1325 packet_write_wait();
1327 /* Stop listening for connections. */
1328 channel_close_all();
1330 /* Close the connection. */
1336 /* Checks if there is any buffered output, and tries to write some of the output. */
1339 packet_write_poll(void)
1341 int len = buffer_len(&output);
1344 len = write(connection_out, buffer_ptr(&output), len);
1346 if (errno == EAGAIN)
1349 fatal("Write failed: %.100s", strerror(errno));
1351 buffer_consume(&output, len);
1356 * Calls packet_write_poll repeatedly until all pending output data has been
1361 packet_write_wait(void)
1365 setp = (fd_set *)xmalloc(howmany(connection_out + 1, NFDBITS) *
1367 packet_write_poll();
1368 while (packet_have_data_to_write()) {
1369 memset(setp, 0, howmany(connection_out + 1, NFDBITS) *
1371 FD_SET(connection_out, setp);
1372 while (select(connection_out + 1, NULL, setp, NULL, NULL) == -1 &&
1373 (errno == EAGAIN || errno == EINTR))
1375 packet_write_poll();
1380 /* Returns true if there is buffered data to write to the connection. */
1383 packet_have_data_to_write(void)
1385 return buffer_len(&output) != 0;
1388 /* Returns true if there is not too much data to write to the connection. */
1391 packet_not_very_much_data_to_write(void)
1393 if (interactive_mode)
1394 return buffer_len(&output) < 16384;
1396 return buffer_len(&output) < 128 * 1024;
1400 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1402 packet_set_tos(int interactive)
1404 int tos = interactive ? IPTOS_LOWDELAY : IPTOS_THROUGHPUT;
1406 if (!packet_connection_is_on_socket() ||
1407 !packet_connection_is_ipv4())
1409 if (setsockopt(connection_in, IPPROTO_IP, IP_TOS, &tos,
1411 error("setsockopt IP_TOS %d: %.100s:",
1412 tos, strerror(errno));
1416 /* Informs that the current session is interactive. Sets IP flags for that. */
1419 packet_set_interactive(int interactive)
1421 static int called = 0;
1427 /* Record that we are in interactive mode. */
1428 interactive_mode = interactive;
1430 /* Only set socket options if using a socket. */
1431 if (!packet_connection_is_on_socket())
1434 set_nodelay(connection_in);
1435 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1436 packet_set_tos(interactive);
1441 /* Returns true if the current connection is interactive. */
1444 packet_is_interactive(void)
1446 return interactive_mode;
1450 packet_set_maxsize(int s)
1452 static int called = 0;
1455 logit("packet_set_maxsize: called twice: old %d new %d",
1456 max_packet_size, s);
1459 if (s < 4 * 1024 || s > 1024 * 1024) {
1460 logit("packet_set_maxsize: bad size %d", s);
1464 debug("packet_set_maxsize: setting to %d", s);
1465 max_packet_size = s;
1469 /* roundup current message to pad bytes */
1471 packet_add_padding(u_char pad)
1477 * 9.2. Ignored Data Message
1479 * byte SSH_MSG_IGNORE
1482 * All implementations MUST understand (and ignore) this message at any
1483 * time (after receiving the protocol version). No implementation is
1484 * required to send them. This message can be used as an additional
1485 * protection measure against advanced traffic analysis techniques.
1488 packet_send_ignore(int nbytes)
1493 packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1494 packet_put_int(nbytes);
1495 for (i = 0; i < nbytes; i++) {
1497 rand = arc4random();
1498 packet_put_char(rand & 0xff);
1503 #define MAX_PACKETS (1<<31)
1505 packet_need_rekeying(void)
1507 if (datafellows & SSH_BUG_NOREKEY)
1510 (p_send.packets > MAX_PACKETS) ||
1511 (p_read.packets > MAX_PACKETS) ||
1512 (max_blocks_out && (p_send.blocks > max_blocks_out)) ||
1513 (max_blocks_in && (p_read.blocks > max_blocks_in));
1517 packet_set_rekey_limit(u_int32_t bytes)
1519 rekey_limit = bytes;