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.122 2006/03/13 08:33:00 dtucker Exp $");
42 #include "openbsd-compat/sys-queue.h"
43 #include <netinet/in_systm.h>
44 #include <netinet/ip.h>
76 * This variable contains the file descriptors used for communicating with
77 * the other side. connection_in is used for reading; connection_out for
78 * writing. These can be the same descriptor, in which case it is assumed to
81 static int connection_in = -1;
82 static int connection_out = -1;
84 /* Protocol flags for the remote side. */
85 static u_int remote_protocol_flags = 0;
87 /* Encryption context for receiving data. This is only used for decryption. */
88 static CipherContext receive_context;
90 /* Encryption context for sending data. This is only used for encryption. */
91 static CipherContext send_context;
93 /* Buffer for raw input data from the socket. */
96 /* Buffer for raw output data going to the socket. */
99 /* Buffer for the partial outgoing packet being constructed. */
100 static Buffer outgoing_packet;
102 /* Buffer for the incoming packet currently being processed. */
103 static Buffer incoming_packet;
105 /* Scratch buffer for packet compression/decompression. */
106 static Buffer compression_buffer;
107 static int compression_buffer_ready = 0;
109 /* Flag indicating whether packet compression/decompression is enabled. */
110 static int packet_compression = 0;
112 /* default maximum packet size */
113 u_int max_packet_size = 32768;
115 /* Flag indicating whether this module has been initialized. */
116 static int initialized = 0;
118 /* Set to true if the connection is interactive. */
119 static int interactive_mode = 0;
121 /* Set to true if we are the server side. */
122 static int server_side = 0;
124 /* Set to true if we are authenticated. */
125 static int after_authentication = 0;
127 /* Session key information for Encryption and MAC */
128 Newkeys *newkeys[MODE_MAX];
129 static struct packet_state {
135 static u_int64_t max_blocks_in, max_blocks_out;
136 static u_int32_t rekey_limit;
138 /* Session key for protocol v1 */
139 static u_char ssh1_key[SSH_SESSION_KEY_LENGTH];
140 static u_int ssh1_keylen;
142 /* roundup current message to extra_pad bytes */
143 static u_char extra_pad = 0;
146 TAILQ_ENTRY(packet) next;
150 TAILQ_HEAD(, packet) outgoing;
153 * Sets the descriptors used for communication. Disables encryption until
154 * packet_set_encryption_key is called.
157 packet_set_connection(int fd_in, int fd_out)
159 Cipher *none = cipher_by_name("none");
162 fatal("packet_set_connection: cannot load cipher 'none'");
163 connection_in = fd_in;
164 connection_out = fd_out;
165 cipher_init(&send_context, none, (const u_char *)"",
166 0, NULL, 0, CIPHER_ENCRYPT);
167 cipher_init(&receive_context, none, (const u_char *)"",
168 0, NULL, 0, CIPHER_DECRYPT);
169 newkeys[MODE_IN] = newkeys[MODE_OUT] = NULL;
173 buffer_init(&output);
174 buffer_init(&outgoing_packet);
175 buffer_init(&incoming_packet);
176 TAILQ_INIT(&outgoing);
180 /* Returns 1 if remote host is connected via socket, 0 if not. */
183 packet_connection_is_on_socket(void)
185 struct sockaddr_storage from, to;
186 socklen_t fromlen, tolen;
188 /* filedescriptors in and out are the same, so it's a socket */
189 if (connection_in == connection_out)
191 fromlen = sizeof(from);
192 memset(&from, 0, sizeof(from));
193 if (getpeername(connection_in, (struct sockaddr *)&from, &fromlen) < 0)
196 memset(&to, 0, sizeof(to));
197 if (getpeername(connection_out, (struct sockaddr *)&to, &tolen) < 0)
199 if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
201 if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
207 * Exports an IV from the CipherContext required to export the key
208 * state back from the unprivileged child to the privileged parent
213 packet_get_keyiv(int mode, u_char *iv, u_int len)
217 if (mode == MODE_OUT)
220 cc = &receive_context;
222 cipher_get_keyiv(cc, iv, len);
226 packet_get_keycontext(int mode, u_char *dat)
230 if (mode == MODE_OUT)
233 cc = &receive_context;
235 return (cipher_get_keycontext(cc, dat));
239 packet_set_keycontext(int mode, u_char *dat)
243 if (mode == MODE_OUT)
246 cc = &receive_context;
248 cipher_set_keycontext(cc, dat);
252 packet_get_keyiv_len(int mode)
256 if (mode == MODE_OUT)
259 cc = &receive_context;
261 return (cipher_get_keyiv_len(cc));
264 packet_set_iv(int mode, u_char *dat)
268 if (mode == MODE_OUT)
271 cc = &receive_context;
273 cipher_set_keyiv(cc, dat);
276 packet_get_ssh1_cipher(void)
278 return (cipher_get_number(receive_context.cipher));
282 packet_get_state(int mode, u_int32_t *seqnr, u_int64_t *blocks, u_int32_t *packets)
284 struct packet_state *state;
286 state = (mode == MODE_IN) ? &p_read : &p_send;
287 *seqnr = state->seqnr;
288 *blocks = state->blocks;
289 *packets = state->packets;
293 packet_set_state(int mode, u_int32_t seqnr, u_int64_t blocks, u_int32_t packets)
295 struct packet_state *state;
297 state = (mode == MODE_IN) ? &p_read : &p_send;
298 state->seqnr = seqnr;
299 state->blocks = blocks;
300 state->packets = packets;
303 /* returns 1 if connection is via ipv4 */
306 packet_connection_is_ipv4(void)
308 struct sockaddr_storage to;
309 socklen_t tolen = sizeof(to);
311 memset(&to, 0, sizeof(to));
312 if (getsockname(connection_out, (struct sockaddr *)&to, &tolen) < 0)
314 if (to.ss_family == AF_INET)
317 if (to.ss_family == AF_INET6 &&
318 IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&to)->sin6_addr))
324 /* Sets the connection into non-blocking mode. */
327 packet_set_nonblocking(void)
329 /* Set the socket into non-blocking mode. */
330 set_nonblock(connection_in);
332 if (connection_out != connection_in)
333 set_nonblock(connection_out);
336 /* Returns the socket used for reading. */
339 packet_get_connection_in(void)
341 return connection_in;
344 /* Returns the descriptor used for writing. */
347 packet_get_connection_out(void)
349 return connection_out;
352 /* Closes the connection and clears and frees internal data structures. */
360 if (connection_in == connection_out) {
361 shutdown(connection_out, SHUT_RDWR);
362 close(connection_out);
364 close(connection_in);
365 close(connection_out);
368 buffer_free(&output);
369 buffer_free(&outgoing_packet);
370 buffer_free(&incoming_packet);
371 if (compression_buffer_ready) {
372 buffer_free(&compression_buffer);
373 buffer_compress_uninit();
375 cipher_cleanup(&send_context);
376 cipher_cleanup(&receive_context);
379 /* Sets remote side protocol flags. */
382 packet_set_protocol_flags(u_int protocol_flags)
384 remote_protocol_flags = protocol_flags;
387 /* Returns the remote protocol flags set earlier by the above function. */
390 packet_get_protocol_flags(void)
392 return remote_protocol_flags;
396 * Starts packet compression from the next packet on in both directions.
397 * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
401 packet_init_compression(void)
403 if (compression_buffer_ready == 1)
405 compression_buffer_ready = 1;
406 buffer_init(&compression_buffer);
410 packet_start_compression(int level)
412 if (packet_compression && !compat20)
413 fatal("Compression already enabled.");
414 packet_compression = 1;
415 packet_init_compression();
416 buffer_compress_init_send(level);
417 buffer_compress_init_recv();
421 * Causes any further packets to be encrypted using the given key. The same
422 * key is used for both sending and reception. However, both directions are
423 * encrypted independently of each other.
427 packet_set_encryption_key(const u_char *key, u_int keylen,
430 Cipher *cipher = cipher_by_number(number);
433 fatal("packet_set_encryption_key: unknown cipher number %d", number);
435 fatal("packet_set_encryption_key: keylen too small: %d", keylen);
436 if (keylen > SSH_SESSION_KEY_LENGTH)
437 fatal("packet_set_encryption_key: keylen too big: %d", keylen);
438 memcpy(ssh1_key, key, keylen);
439 ssh1_keylen = keylen;
440 cipher_init(&send_context, cipher, key, keylen, NULL, 0, CIPHER_ENCRYPT);
441 cipher_init(&receive_context, cipher, key, keylen, NULL, 0, CIPHER_DECRYPT);
445 packet_get_encryption_key(u_char *key)
448 return (ssh1_keylen);
449 memcpy(key, ssh1_key, ssh1_keylen);
450 return (ssh1_keylen);
453 /* Start constructing a packet to send. */
455 packet_start(u_char type)
460 DBG(debug("packet_start[%d]", type));
461 len = compat20 ? 6 : 9;
462 memset(buf, 0, len - 1);
464 buffer_clear(&outgoing_packet);
465 buffer_append(&outgoing_packet, buf, len);
468 /* Append payload. */
470 packet_put_char(int value)
474 buffer_append(&outgoing_packet, &ch, 1);
477 packet_put_int(u_int value)
479 buffer_put_int(&outgoing_packet, value);
482 packet_put_string(const void *buf, u_int len)
484 buffer_put_string(&outgoing_packet, buf, len);
487 packet_put_cstring(const char *str)
489 buffer_put_cstring(&outgoing_packet, str);
492 packet_put_raw(const void *buf, u_int len)
494 buffer_append(&outgoing_packet, buf, len);
497 packet_put_bignum(BIGNUM * value)
499 buffer_put_bignum(&outgoing_packet, value);
502 packet_put_bignum2(BIGNUM * value)
504 buffer_put_bignum2(&outgoing_packet, value);
508 * Finalizes and sends the packet. If the encryption key has been set,
509 * encrypts the packet before sending.
521 * If using packet compression, compress the payload of the outgoing
524 if (packet_compression) {
525 buffer_clear(&compression_buffer);
527 buffer_consume(&outgoing_packet, 8);
529 buffer_append(&compression_buffer, "\0\0\0\0\0\0\0\0", 8);
530 buffer_compress(&outgoing_packet, &compression_buffer);
531 buffer_clear(&outgoing_packet);
532 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
533 buffer_len(&compression_buffer));
535 /* Compute packet length without padding (add checksum, remove padding). */
536 len = buffer_len(&outgoing_packet) + 4 - 8;
538 /* Insert padding. Initialized to zero in packet_start1() */
539 padding = 8 - len % 8;
540 if (!send_context.plaintext) {
541 cp = buffer_ptr(&outgoing_packet);
542 for (i = 0; i < padding; i++) {
545 cp[7 - i] = rnd & 0xff;
549 buffer_consume(&outgoing_packet, 8 - padding);
551 /* Add check bytes. */
552 checksum = ssh_crc32(buffer_ptr(&outgoing_packet),
553 buffer_len(&outgoing_packet));
554 PUT_32BIT(buf, checksum);
555 buffer_append(&outgoing_packet, buf, 4);
558 fprintf(stderr, "packet_send plain: ");
559 buffer_dump(&outgoing_packet);
562 /* Append to output. */
564 buffer_append(&output, buf, 4);
565 cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
566 cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
567 buffer_len(&outgoing_packet));
570 fprintf(stderr, "encrypted: ");
571 buffer_dump(&output);
574 buffer_clear(&outgoing_packet);
577 * Note that the packet is now only buffered in output. It won't be
578 * actually sent until packet_write_wait or packet_write_poll is
584 set_newkeys(int mode)
590 u_int64_t *max_blocks;
593 debug2("set_newkeys: mode %d", mode);
595 if (mode == MODE_OUT) {
597 crypt_type = CIPHER_ENCRYPT;
598 p_send.packets = p_send.blocks = 0;
599 max_blocks = &max_blocks_out;
601 cc = &receive_context;
602 crypt_type = CIPHER_DECRYPT;
603 p_read.packets = p_read.blocks = 0;
604 max_blocks = &max_blocks_in;
606 if (newkeys[mode] != NULL) {
607 debug("set_newkeys: rekeying");
609 enc = &newkeys[mode]->enc;
610 mac = &newkeys[mode]->mac;
611 comp = &newkeys[mode]->comp;
612 memset(mac->key, 0, mac->key_len);
619 xfree(newkeys[mode]);
621 newkeys[mode] = kex_get_newkeys(mode);
622 if (newkeys[mode] == NULL)
623 fatal("newkeys: no keys for mode %d", mode);
624 enc = &newkeys[mode]->enc;
625 mac = &newkeys[mode]->mac;
626 comp = &newkeys[mode]->comp;
629 DBG(debug("cipher_init_context: %d", mode));
630 cipher_init(cc, enc->cipher, enc->key, enc->key_len,
631 enc->iv, enc->block_size, crypt_type);
632 /* Deleting the keys does not gain extra security */
633 /* memset(enc->iv, 0, enc->block_size);
634 memset(enc->key, 0, enc->key_len); */
635 if ((comp->type == COMP_ZLIB ||
636 (comp->type == COMP_DELAYED && after_authentication)) &&
637 comp->enabled == 0) {
638 packet_init_compression();
639 if (mode == MODE_OUT)
640 buffer_compress_init_send(6);
642 buffer_compress_init_recv();
646 * The 2^(blocksize*2) limit is too expensive for 3DES,
647 * blowfish, etc, so enforce a 1GB limit for small blocksizes.
649 if (enc->block_size >= 16)
650 *max_blocks = (u_int64_t)1 << (enc->block_size*2);
652 *max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
654 *max_blocks = MIN(*max_blocks, rekey_limit / enc->block_size);
658 * Delayed compression for SSH2 is enabled after authentication:
659 * This happans on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
660 * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
663 packet_enable_delayed_compress(void)
669 * Remember that we are past the authentication step, so rekeying
670 * with COMP_DELAYED will turn on compression immediately.
672 after_authentication = 1;
673 for (mode = 0; mode < MODE_MAX; mode++) {
674 comp = &newkeys[mode]->comp;
675 if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
676 packet_init_compression();
677 if (mode == MODE_OUT)
678 buffer_compress_init_send(6);
680 buffer_compress_init_recv();
687 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
690 packet_send2_wrapped(void)
692 u_char type, *cp, *macbuf = NULL;
694 u_int packet_length = 0;
702 if (newkeys[MODE_OUT] != NULL) {
703 enc = &newkeys[MODE_OUT]->enc;
704 mac = &newkeys[MODE_OUT]->mac;
705 comp = &newkeys[MODE_OUT]->comp;
707 block_size = enc ? enc->block_size : 8;
709 cp = buffer_ptr(&outgoing_packet);
713 fprintf(stderr, "plain: ");
714 buffer_dump(&outgoing_packet);
717 if (comp && comp->enabled) {
718 len = buffer_len(&outgoing_packet);
719 /* skip header, compress only payload */
720 buffer_consume(&outgoing_packet, 5);
721 buffer_clear(&compression_buffer);
722 buffer_compress(&outgoing_packet, &compression_buffer);
723 buffer_clear(&outgoing_packet);
724 buffer_append(&outgoing_packet, "\0\0\0\0\0", 5);
725 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
726 buffer_len(&compression_buffer));
727 DBG(debug("compression: raw %d compressed %d", len,
728 buffer_len(&outgoing_packet)));
731 /* sizeof (packet_len + pad_len + payload) */
732 len = buffer_len(&outgoing_packet);
735 * calc size of padding, alloc space, get random data,
736 * minimum padding is 4 bytes
738 padlen = block_size - (len % block_size);
740 padlen += block_size;
742 /* will wrap if extra_pad+padlen > 255 */
743 extra_pad = roundup(extra_pad, block_size);
744 pad = extra_pad - ((len + padlen) % extra_pad);
745 debug3("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
746 pad, len, padlen, extra_pad);
750 cp = buffer_append_space(&outgoing_packet, padlen);
751 if (enc && !send_context.plaintext) {
753 for (i = 0; i < padlen; i++) {
761 memset(cp, 0, padlen);
763 /* packet_length includes payload, padding and padding length field */
764 packet_length = buffer_len(&outgoing_packet) - 4;
765 cp = buffer_ptr(&outgoing_packet);
766 PUT_32BIT(cp, packet_length);
768 DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen));
770 /* compute MAC over seqnr and packet(length fields, payload, padding) */
771 if (mac && mac->enabled) {
772 macbuf = mac_compute(mac, p_send.seqnr,
773 buffer_ptr(&outgoing_packet),
774 buffer_len(&outgoing_packet));
775 DBG(debug("done calc MAC out #%d", p_send.seqnr));
777 /* encrypt packet and append to output buffer. */
778 cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
779 cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
780 buffer_len(&outgoing_packet));
781 /* append unencrypted MAC */
782 if (mac && mac->enabled)
783 buffer_append(&output, (char *)macbuf, mac->mac_len);
785 fprintf(stderr, "encrypted: ");
786 buffer_dump(&output);
788 /* increment sequence number for outgoing packets */
789 if (++p_send.seqnr == 0)
790 logit("outgoing seqnr wraps around");
791 if (++p_send.packets == 0)
792 if (!(datafellows & SSH_BUG_NOREKEY))
793 fatal("XXX too many packets with same key");
794 p_send.blocks += (packet_length + 4) / block_size;
795 buffer_clear(&outgoing_packet);
797 if (type == SSH2_MSG_NEWKEYS)
798 set_newkeys(MODE_OUT);
799 else if (type == SSH2_MSG_USERAUTH_SUCCESS && server_side)
800 packet_enable_delayed_compress();
806 static int rekeying = 0;
810 cp = buffer_ptr(&outgoing_packet);
813 /* during rekeying we can only send key exchange messages */
815 if (!((type >= SSH2_MSG_TRANSPORT_MIN) &&
816 (type <= SSH2_MSG_TRANSPORT_MAX))) {
817 debug("enqueue packet: %u", type);
818 p = xmalloc(sizeof(*p));
820 memcpy(&p->payload, &outgoing_packet, sizeof(Buffer));
821 buffer_init(&outgoing_packet);
822 TAILQ_INSERT_TAIL(&outgoing, p, next);
827 /* rekeying starts with sending KEXINIT */
828 if (type == SSH2_MSG_KEXINIT)
831 packet_send2_wrapped();
833 /* after a NEWKEYS message we can send the complete queue */
834 if (type == SSH2_MSG_NEWKEYS) {
836 while ((p = TAILQ_FIRST(&outgoing))) {
838 debug("dequeue packet: %u", type);
839 buffer_free(&outgoing_packet);
840 memcpy(&outgoing_packet, &p->payload,
842 TAILQ_REMOVE(&outgoing, p, next);
844 packet_send2_wrapped();
856 DBG(debug("packet_send done"));
860 * Waits until a packet has been received, and returns its type. Note that
861 * no other data is processed until this returns, so this function should not
862 * be used during the interactive session.
866 packet_read_seqnr(u_int32_t *seqnr_p)
871 DBG(debug("packet_read()"));
873 setp = (fd_set *)xmalloc(howmany(connection_in+1, NFDBITS) *
876 /* Since we are blocking, ensure that all written packets have been sent. */
879 /* Stay in the loop until we have received a complete packet. */
881 /* Try to read a packet from the buffer. */
882 type = packet_read_poll_seqnr(seqnr_p);
884 type == SSH_SMSG_SUCCESS
885 || type == SSH_SMSG_FAILURE
886 || type == SSH_CMSG_EOF
887 || type == SSH_CMSG_EXIT_CONFIRMATION))
889 /* If we got a packet, return it. */
890 if (type != SSH_MSG_NONE) {
895 * Otherwise, wait for some data to arrive, add it to the
896 * buffer, and try again.
898 memset(setp, 0, howmany(connection_in + 1, NFDBITS) *
900 FD_SET(connection_in, setp);
902 /* Wait for some data to arrive. */
903 while (select(connection_in + 1, setp, NULL, NULL, NULL) == -1 &&
904 (errno == EAGAIN || errno == EINTR))
907 /* Read data from the socket. */
908 len = read(connection_in, buf, sizeof(buf));
910 logit("Connection closed by %.200s", get_remote_ipaddr());
914 fatal("Read from socket failed: %.100s", strerror(errno));
915 /* Append it to the buffer. */
916 packet_process_incoming(buf, len);
924 return packet_read_seqnr(NULL);
928 * Waits until a packet has been received, verifies that its type matches
929 * that given, and gives a fatal error and exits if there is a mismatch.
933 packet_read_expect(int expected_type)
937 type = packet_read();
938 if (type != expected_type)
939 packet_disconnect("Protocol error: expected packet type %d, got %d",
940 expected_type, type);
943 /* Checks if a full packet is available in the data received so far via
944 * packet_process_incoming. If so, reads the packet; otherwise returns
945 * SSH_MSG_NONE. This does not wait for data from the connection.
947 * SSH_MSG_DISCONNECT is handled specially here. Also,
948 * SSH_MSG_IGNORE messages are skipped by this function and are never returned
953 packet_read_poll1(void)
955 u_int len, padded_len;
957 u_int checksum, stored_checksum;
959 /* Check if input size is less than minimum packet size. */
960 if (buffer_len(&input) < 4 + 8)
962 /* Get length of incoming packet. */
963 cp = buffer_ptr(&input);
965 if (len < 1 + 2 + 2 || len > 256 * 1024)
966 packet_disconnect("Bad packet length %u.", len);
967 padded_len = (len + 8) & ~7;
969 /* Check if the packet has been entirely received. */
970 if (buffer_len(&input) < 4 + padded_len)
973 /* The entire packet is in buffer. */
975 /* Consume packet length. */
976 buffer_consume(&input, 4);
979 * Cryptographic attack detector for ssh
980 * (C)1998 CORE-SDI, Buenos Aires Argentina
981 * Ariel Futoransky(futo@core-sdi.com)
983 if (!receive_context.plaintext &&
984 detect_attack(buffer_ptr(&input), padded_len, NULL) == DEATTACK_DETECTED)
985 packet_disconnect("crc32 compensation attack: network attack detected");
987 /* Decrypt data to incoming_packet. */
988 buffer_clear(&incoming_packet);
989 cp = buffer_append_space(&incoming_packet, padded_len);
990 cipher_crypt(&receive_context, cp, buffer_ptr(&input), padded_len);
992 buffer_consume(&input, padded_len);
995 fprintf(stderr, "read_poll plain: ");
996 buffer_dump(&incoming_packet);
999 /* Compute packet checksum. */
1000 checksum = ssh_crc32(buffer_ptr(&incoming_packet),
1001 buffer_len(&incoming_packet) - 4);
1004 buffer_consume(&incoming_packet, 8 - len % 8);
1006 /* Test check bytes. */
1007 if (len != buffer_len(&incoming_packet))
1008 packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
1009 len, buffer_len(&incoming_packet));
1011 cp = (u_char *)buffer_ptr(&incoming_packet) + len - 4;
1012 stored_checksum = GET_32BIT(cp);
1013 if (checksum != stored_checksum)
1014 packet_disconnect("Corrupted check bytes on input.");
1015 buffer_consume_end(&incoming_packet, 4);
1017 if (packet_compression) {
1018 buffer_clear(&compression_buffer);
1019 buffer_uncompress(&incoming_packet, &compression_buffer);
1020 buffer_clear(&incoming_packet);
1021 buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
1022 buffer_len(&compression_buffer));
1024 type = buffer_get_char(&incoming_packet);
1025 if (type < SSH_MSG_MIN || type > SSH_MSG_MAX)
1026 packet_disconnect("Invalid ssh1 packet type: %d", type);
1031 packet_read_poll2(u_int32_t *seqnr_p)
1033 static u_int packet_length = 0;
1035 u_char *macbuf, *cp, type;
1036 u_int maclen, block_size;
1041 if (newkeys[MODE_IN] != NULL) {
1042 enc = &newkeys[MODE_IN]->enc;
1043 mac = &newkeys[MODE_IN]->mac;
1044 comp = &newkeys[MODE_IN]->comp;
1046 maclen = mac && mac->enabled ? mac->mac_len : 0;
1047 block_size = enc ? enc->block_size : 8;
1049 if (packet_length == 0) {
1051 * check if input size is less than the cipher block size,
1052 * decrypt first block and extract length of incoming packet
1054 if (buffer_len(&input) < block_size)
1055 return SSH_MSG_NONE;
1056 buffer_clear(&incoming_packet);
1057 cp = buffer_append_space(&incoming_packet, block_size);
1058 cipher_crypt(&receive_context, cp, buffer_ptr(&input),
1060 cp = buffer_ptr(&incoming_packet);
1061 packet_length = GET_32BIT(cp);
1062 if (packet_length < 1 + 4 || packet_length > 256 * 1024) {
1064 buffer_dump(&incoming_packet);
1066 packet_disconnect("Bad packet length %u.", packet_length);
1068 DBG(debug("input: packet len %u", packet_length+4));
1069 buffer_consume(&input, block_size);
1071 /* we have a partial packet of block_size bytes */
1072 need = 4 + packet_length - block_size;
1073 DBG(debug("partial packet %d, need %d, maclen %d", block_size,
1075 if (need % block_size != 0)
1076 fatal("padding error: need %d block %d mod %d",
1077 need, block_size, need % block_size);
1079 * check if the entire packet has been received and
1080 * decrypt into incoming_packet
1082 if (buffer_len(&input) < need + maclen)
1083 return SSH_MSG_NONE;
1085 fprintf(stderr, "read_poll enc/full: ");
1086 buffer_dump(&input);
1088 cp = buffer_append_space(&incoming_packet, need);
1089 cipher_crypt(&receive_context, cp, buffer_ptr(&input), need);
1090 buffer_consume(&input, need);
1092 * compute MAC over seqnr and packet,
1093 * increment sequence number for incoming packet
1095 if (mac && mac->enabled) {
1096 macbuf = mac_compute(mac, p_read.seqnr,
1097 buffer_ptr(&incoming_packet),
1098 buffer_len(&incoming_packet));
1099 if (memcmp(macbuf, buffer_ptr(&input), mac->mac_len) != 0)
1100 packet_disconnect("Corrupted MAC on input.");
1101 DBG(debug("MAC #%d ok", p_read.seqnr));
1102 buffer_consume(&input, mac->mac_len);
1104 if (seqnr_p != NULL)
1105 *seqnr_p = p_read.seqnr;
1106 if (++p_read.seqnr == 0)
1107 logit("incoming seqnr wraps around");
1108 if (++p_read.packets == 0)
1109 if (!(datafellows & SSH_BUG_NOREKEY))
1110 fatal("XXX too many packets with same key");
1111 p_read.blocks += (packet_length + 4) / block_size;
1114 cp = buffer_ptr(&incoming_packet);
1116 DBG(debug("input: padlen %d", padlen));
1118 packet_disconnect("Corrupted padlen %d on input.", padlen);
1120 /* skip packet size + padlen, discard padding */
1121 buffer_consume(&incoming_packet, 4 + 1);
1122 buffer_consume_end(&incoming_packet, padlen);
1124 DBG(debug("input: len before de-compress %d", buffer_len(&incoming_packet)));
1125 if (comp && comp->enabled) {
1126 buffer_clear(&compression_buffer);
1127 buffer_uncompress(&incoming_packet, &compression_buffer);
1128 buffer_clear(&incoming_packet);
1129 buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
1130 buffer_len(&compression_buffer));
1131 DBG(debug("input: len after de-compress %d",
1132 buffer_len(&incoming_packet)));
1135 * get packet type, implies consume.
1136 * return length of payload (without type field)
1138 type = buffer_get_char(&incoming_packet);
1139 if (type < SSH2_MSG_MIN || type >= SSH2_MSG_LOCAL_MIN)
1140 packet_disconnect("Invalid ssh2 packet type: %d", type);
1141 if (type == SSH2_MSG_NEWKEYS)
1142 set_newkeys(MODE_IN);
1143 else if (type == SSH2_MSG_USERAUTH_SUCCESS && !server_side)
1144 packet_enable_delayed_compress();
1146 fprintf(stderr, "read/plain[%d]:\r\n", type);
1147 buffer_dump(&incoming_packet);
1149 /* reset for next packet */
1155 packet_read_poll_seqnr(u_int32_t *seqnr_p)
1157 u_int reason, seqnr;
1163 type = packet_read_poll2(seqnr_p);
1165 DBG(debug("received packet type %d", type));
1167 case SSH2_MSG_IGNORE:
1169 case SSH2_MSG_DEBUG:
1171 msg = packet_get_string(NULL);
1172 debug("Remote: %.900s", msg);
1174 msg = packet_get_string(NULL);
1177 case SSH2_MSG_DISCONNECT:
1178 reason = packet_get_int();
1179 msg = packet_get_string(NULL);
1180 logit("Received disconnect from %s: %u: %.400s",
1181 get_remote_ipaddr(), reason, msg);
1185 case SSH2_MSG_UNIMPLEMENTED:
1186 seqnr = packet_get_int();
1187 debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1195 type = packet_read_poll1();
1197 case SSH_MSG_IGNORE:
1200 msg = packet_get_string(NULL);
1201 debug("Remote: %.900s", msg);
1204 case SSH_MSG_DISCONNECT:
1205 msg = packet_get_string(NULL);
1206 logit("Received disconnect from %s: %.400s",
1207 get_remote_ipaddr(), msg);
1213 DBG(debug("received packet type %d", type));
1222 packet_read_poll(void)
1224 return packet_read_poll_seqnr(NULL);
1228 * Buffers the given amount of input characters. This is intended to be used
1229 * together with packet_read_poll.
1233 packet_process_incoming(const char *buf, u_int len)
1235 buffer_append(&input, buf, len);
1238 /* Returns a character from the packet. */
1241 packet_get_char(void)
1245 buffer_get(&incoming_packet, &ch, 1);
1249 /* Returns an integer from the packet data. */
1252 packet_get_int(void)
1254 return buffer_get_int(&incoming_packet);
1258 * Returns an arbitrary precision integer from the packet data. The integer
1259 * must have been initialized before this call.
1263 packet_get_bignum(BIGNUM * value)
1265 buffer_get_bignum(&incoming_packet, value);
1269 packet_get_bignum2(BIGNUM * value)
1271 buffer_get_bignum2(&incoming_packet, value);
1275 packet_get_raw(u_int *length_ptr)
1277 u_int bytes = buffer_len(&incoming_packet);
1279 if (length_ptr != NULL)
1280 *length_ptr = bytes;
1281 return buffer_ptr(&incoming_packet);
1285 packet_remaining(void)
1287 return buffer_len(&incoming_packet);
1291 * Returns a string from the packet data. The string is allocated using
1292 * xmalloc; it is the responsibility of the calling program to free it when
1293 * no longer needed. The length_ptr argument may be NULL, or point to an
1294 * integer into which the length of the string is stored.
1298 packet_get_string(u_int *length_ptr)
1300 return buffer_get_string(&incoming_packet, length_ptr);
1304 * Sends a diagnostic message from the server to the client. This message
1305 * can be sent at any time (but not while constructing another message). The
1306 * message is printed immediately, but only if the client is being executed
1307 * in verbose mode. These messages are primarily intended to ease debugging
1308 * authentication problems. The length of the formatted message must not
1309 * exceed 1024 bytes. This will automatically call packet_write_wait.
1313 packet_send_debug(const char *fmt,...)
1318 if (compat20 && (datafellows & SSH_BUG_DEBUG))
1321 va_start(args, fmt);
1322 vsnprintf(buf, sizeof(buf), fmt, args);
1326 packet_start(SSH2_MSG_DEBUG);
1327 packet_put_char(0); /* bool: always display */
1328 packet_put_cstring(buf);
1329 packet_put_cstring("");
1331 packet_start(SSH_MSG_DEBUG);
1332 packet_put_cstring(buf);
1335 packet_write_wait();
1339 * Logs the error plus constructs and sends a disconnect packet, closes the
1340 * connection, and exits. This function never returns. The error message
1341 * should not contain a newline. The length of the formatted message must
1342 * not exceed 1024 bytes.
1346 packet_disconnect(const char *fmt,...)
1350 static int disconnecting = 0;
1352 if (disconnecting) /* Guard against recursive invocations. */
1353 fatal("packet_disconnect called recursively.");
1357 * Format the message. Note that the caller must make sure the
1358 * message is of limited size.
1360 va_start(args, fmt);
1361 vsnprintf(buf, sizeof(buf), fmt, args);
1364 /* Display the error locally */
1365 logit("Disconnecting: %.100s", buf);
1367 /* Send the disconnect message to the other side, and wait for it to get sent. */
1369 packet_start(SSH2_MSG_DISCONNECT);
1370 packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1371 packet_put_cstring(buf);
1372 packet_put_cstring("");
1374 packet_start(SSH_MSG_DISCONNECT);
1375 packet_put_cstring(buf);
1378 packet_write_wait();
1380 /* Stop listening for connections. */
1381 channel_close_all();
1383 /* Close the connection. */
1388 /* Checks if there is any buffered output, and tries to write some of the output. */
1391 packet_write_poll(void)
1393 int len = buffer_len(&output);
1396 len = write(connection_out, buffer_ptr(&output), len);
1398 if (errno == EAGAIN)
1401 fatal("Write failed: %.100s", strerror(errno));
1403 buffer_consume(&output, len);
1408 * Calls packet_write_poll repeatedly until all pending output data has been
1413 packet_write_wait(void)
1417 setp = (fd_set *)xmalloc(howmany(connection_out + 1, NFDBITS) *
1419 packet_write_poll();
1420 while (packet_have_data_to_write()) {
1421 memset(setp, 0, howmany(connection_out + 1, NFDBITS) *
1423 FD_SET(connection_out, setp);
1424 while (select(connection_out + 1, NULL, setp, NULL, NULL) == -1 &&
1425 (errno == EAGAIN || errno == EINTR))
1427 packet_write_poll();
1432 /* Returns true if there is buffered data to write to the connection. */
1435 packet_have_data_to_write(void)
1437 return buffer_len(&output) != 0;
1440 /* Returns true if there is not too much data to write to the connection. */
1443 packet_not_very_much_data_to_write(void)
1445 if (interactive_mode)
1446 return buffer_len(&output) < 16384;
1448 return buffer_len(&output) < 128 * 1024;
1453 packet_set_tos(int interactive)
1455 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1456 int tos = interactive ? IPTOS_LOWDELAY : IPTOS_THROUGHPUT;
1458 if (!packet_connection_is_on_socket() ||
1459 !packet_connection_is_ipv4())
1461 if (setsockopt(connection_in, IPPROTO_IP, IP_TOS, &tos,
1463 error("setsockopt IP_TOS %d: %.100s:",
1464 tos, strerror(errno));
1468 /* Informs that the current session is interactive. Sets IP flags for that. */
1471 packet_set_interactive(int interactive)
1473 static int called = 0;
1479 /* Record that we are in interactive mode. */
1480 interactive_mode = interactive;
1482 /* Only set socket options if using a socket. */
1483 if (!packet_connection_is_on_socket())
1485 set_nodelay(connection_in);
1486 packet_set_tos(interactive);
1489 /* Returns true if the current connection is interactive. */
1492 packet_is_interactive(void)
1494 return interactive_mode;
1498 packet_set_maxsize(u_int s)
1500 static int called = 0;
1503 logit("packet_set_maxsize: called twice: old %d new %d",
1504 max_packet_size, s);
1507 if (s < 4 * 1024 || s > 1024 * 1024) {
1508 logit("packet_set_maxsize: bad size %d", s);
1512 debug("packet_set_maxsize: setting to %d", s);
1513 max_packet_size = s;
1517 /* roundup current message to pad bytes */
1519 packet_add_padding(u_char pad)
1525 * 9.2. Ignored Data Message
1527 * byte SSH_MSG_IGNORE
1530 * All implementations MUST understand (and ignore) this message at any
1531 * time (after receiving the protocol version). No implementation is
1532 * required to send them. This message can be used as an additional
1533 * protection measure against advanced traffic analysis techniques.
1536 packet_send_ignore(int nbytes)
1541 packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1542 packet_put_int(nbytes);
1543 for (i = 0; i < nbytes; i++) {
1546 packet_put_char(rnd & 0xff);
1551 #define MAX_PACKETS (1U<<31)
1553 packet_need_rekeying(void)
1555 if (datafellows & SSH_BUG_NOREKEY)
1558 (p_send.packets > MAX_PACKETS) ||
1559 (p_read.packets > MAX_PACKETS) ||
1560 (max_blocks_out && (p_send.blocks > max_blocks_out)) ||
1561 (max_blocks_in && (p_read.blocks > max_blocks_in));
1565 packet_set_rekey_limit(u_int32_t bytes)
1567 rekey_limit = bytes;
1571 packet_set_server(void)
1577 packet_set_authenticated(void)
1579 after_authentication = 1;