1 /* $OpenBSD: packet.c,v 1.147 2007/06/05 06:52:37 djm Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * This file contains code implementing the packet protocol and communication
7 * with the other side. This same code is used both on client and server side.
9 * As far as I am concerned, the code I have written for this software
10 * can be used freely for any purpose. Any derived versions of this
11 * software must be clearly marked as such, and if the derived work is
12 * incompatible with the protocol description in the RFC file, it must be
13 * called by a name other than "ssh" or "Secure Shell".
16 * SSH2 packet format added by Markus Friedl.
17 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
19 * Redistribution and use in source and binary forms, with or without
20 * modification, are permitted provided that the following conditions
22 * 1. Redistributions of source code must retain the above copyright
23 * notice, this list of conditions and the following disclaimer.
24 * 2. Redistributions in binary form must reproduce the above copyright
25 * notice, this list of conditions and the following disclaimer in the
26 * documentation and/or other materials provided with the distribution.
28 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
29 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
30 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
31 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
32 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
33 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
34 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
35 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
36 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
37 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42 #include <sys/types.h>
43 #include "openbsd-compat/sys-queue.h"
44 #include <sys/param.h>
45 #include <sys/socket.h>
46 #ifdef HAVE_SYS_TIME_H
47 # include <sys/time.h>
50 #include <netinet/in.h>
51 #include <netinet/ip.h>
52 #include <arpa/inet.h>
88 * This variable contains the file descriptors used for communicating with
89 * the other side. connection_in is used for reading; connection_out for
90 * writing. These can be the same descriptor, in which case it is assumed to
93 static int connection_in = -1;
94 static int connection_out = -1;
96 /* Protocol flags for the remote side. */
97 static u_int remote_protocol_flags = 0;
99 /* Encryption context for receiving data. This is only used for decryption. */
100 static CipherContext receive_context;
102 /* Encryption context for sending data. This is only used for encryption. */
103 static CipherContext send_context;
105 /* Buffer for raw input data from the socket. */
108 /* Buffer for raw output data going to the socket. */
111 /* Buffer for the partial outgoing packet being constructed. */
112 static Buffer outgoing_packet;
114 /* Buffer for the incoming packet currently being processed. */
115 static Buffer incoming_packet;
117 /* Scratch buffer for packet compression/decompression. */
118 static Buffer compression_buffer;
119 static int compression_buffer_ready = 0;
121 /* Flag indicating whether packet compression/decompression is enabled. */
122 static int packet_compression = 0;
124 /* default maximum packet size */
125 u_int max_packet_size = 32768;
127 /* Flag indicating whether this module has been initialized. */
128 static int initialized = 0;
130 /* Set to true if the connection is interactive. */
131 static int interactive_mode = 0;
133 /* Set to true if we are the server side. */
134 static int server_side = 0;
136 /* Set to true if we are authenticated. */
137 static int after_authentication = 0;
139 /* Session key information for Encryption and MAC */
140 Newkeys *newkeys[MODE_MAX];
141 static struct packet_state {
147 static u_int64_t max_blocks_in, max_blocks_out;
148 static u_int32_t rekey_limit;
150 /* Session key for protocol v1 */
151 static u_char ssh1_key[SSH_SESSION_KEY_LENGTH];
152 static u_int ssh1_keylen;
154 /* roundup current message to extra_pad bytes */
155 static u_char extra_pad = 0;
158 TAILQ_ENTRY(packet) next;
162 TAILQ_HEAD(, packet) outgoing;
165 * Sets the descriptors used for communication. Disables encryption until
166 * packet_set_encryption_key is called.
169 packet_set_connection(int fd_in, int fd_out)
171 Cipher *none = cipher_by_name("none");
174 fatal("packet_set_connection: cannot load cipher 'none'");
175 connection_in = fd_in;
176 connection_out = fd_out;
177 cipher_init(&send_context, none, (const u_char *)"",
178 0, NULL, 0, CIPHER_ENCRYPT);
179 cipher_init(&receive_context, none, (const u_char *)"",
180 0, NULL, 0, CIPHER_DECRYPT);
181 newkeys[MODE_IN] = newkeys[MODE_OUT] = NULL;
185 buffer_init(&output);
186 buffer_init(&outgoing_packet);
187 buffer_init(&incoming_packet);
188 TAILQ_INIT(&outgoing);
192 /* Returns 1 if remote host is connected via socket, 0 if not. */
195 packet_connection_is_on_socket(void)
197 struct sockaddr_storage from, to;
198 socklen_t fromlen, tolen;
200 /* filedescriptors in and out are the same, so it's a socket */
201 if (connection_in == connection_out)
203 fromlen = sizeof(from);
204 memset(&from, 0, sizeof(from));
205 if (getpeername(connection_in, (struct sockaddr *)&from, &fromlen) < 0)
208 memset(&to, 0, sizeof(to));
209 if (getpeername(connection_out, (struct sockaddr *)&to, &tolen) < 0)
211 if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
213 if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
219 * Exports an IV from the CipherContext required to export the key
220 * state back from the unprivileged child to the privileged parent
225 packet_get_keyiv(int mode, u_char *iv, u_int len)
229 if (mode == MODE_OUT)
232 cc = &receive_context;
234 cipher_get_keyiv(cc, iv, len);
238 packet_get_keycontext(int mode, u_char *dat)
242 if (mode == MODE_OUT)
245 cc = &receive_context;
247 return (cipher_get_keycontext(cc, dat));
251 packet_set_keycontext(int mode, u_char *dat)
255 if (mode == MODE_OUT)
258 cc = &receive_context;
260 cipher_set_keycontext(cc, dat);
264 packet_get_keyiv_len(int mode)
268 if (mode == MODE_OUT)
271 cc = &receive_context;
273 return (cipher_get_keyiv_len(cc));
277 packet_set_iv(int mode, u_char *dat)
281 if (mode == MODE_OUT)
284 cc = &receive_context;
286 cipher_set_keyiv(cc, dat);
290 packet_get_ssh1_cipher(void)
292 return (cipher_get_number(receive_context.cipher));
296 packet_get_state(int mode, u_int32_t *seqnr, u_int64_t *blocks, u_int32_t *packets)
298 struct packet_state *state;
300 state = (mode == MODE_IN) ? &p_read : &p_send;
301 *seqnr = state->seqnr;
302 *blocks = state->blocks;
303 *packets = state->packets;
307 packet_set_state(int mode, u_int32_t seqnr, u_int64_t blocks, u_int32_t packets)
309 struct packet_state *state;
311 state = (mode == MODE_IN) ? &p_read : &p_send;
312 state->seqnr = seqnr;
313 state->blocks = blocks;
314 state->packets = packets;
317 /* returns 1 if connection is via ipv4 */
320 packet_connection_is_ipv4(void)
322 struct sockaddr_storage to;
323 socklen_t tolen = sizeof(to);
325 memset(&to, 0, sizeof(to));
326 if (getsockname(connection_out, (struct sockaddr *)&to, &tolen) < 0)
328 if (to.ss_family == AF_INET)
331 if (to.ss_family == AF_INET6 &&
332 IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&to)->sin6_addr))
338 /* Sets the connection into non-blocking mode. */
341 packet_set_nonblocking(void)
343 /* Set the socket into non-blocking mode. */
344 set_nonblock(connection_in);
346 if (connection_out != connection_in)
347 set_nonblock(connection_out);
350 /* Returns the socket used for reading. */
353 packet_get_connection_in(void)
355 return connection_in;
358 /* Returns the descriptor used for writing. */
361 packet_get_connection_out(void)
363 return connection_out;
366 /* Closes the connection and clears and frees internal data structures. */
374 if (connection_in == connection_out) {
375 shutdown(connection_out, SHUT_RDWR);
376 close(connection_out);
378 close(connection_in);
379 close(connection_out);
382 buffer_free(&output);
383 buffer_free(&outgoing_packet);
384 buffer_free(&incoming_packet);
385 if (compression_buffer_ready) {
386 buffer_free(&compression_buffer);
387 buffer_compress_uninit();
389 cipher_cleanup(&send_context);
390 cipher_cleanup(&receive_context);
393 /* Sets remote side protocol flags. */
396 packet_set_protocol_flags(u_int protocol_flags)
398 remote_protocol_flags = protocol_flags;
401 /* Returns the remote protocol flags set earlier by the above function. */
404 packet_get_protocol_flags(void)
406 return remote_protocol_flags;
410 * Starts packet compression from the next packet on in both directions.
411 * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
415 packet_init_compression(void)
417 if (compression_buffer_ready == 1)
419 compression_buffer_ready = 1;
420 buffer_init(&compression_buffer);
424 packet_start_compression(int level)
426 if (packet_compression && !compat20)
427 fatal("Compression already enabled.");
428 packet_compression = 1;
429 packet_init_compression();
430 buffer_compress_init_send(level);
431 buffer_compress_init_recv();
435 * Causes any further packets to be encrypted using the given key. The same
436 * key is used for both sending and reception. However, both directions are
437 * encrypted independently of each other.
441 packet_set_encryption_key(const u_char *key, u_int keylen,
444 Cipher *cipher = cipher_by_number(number);
447 fatal("packet_set_encryption_key: unknown cipher number %d", number);
449 fatal("packet_set_encryption_key: keylen too small: %d", keylen);
450 if (keylen > SSH_SESSION_KEY_LENGTH)
451 fatal("packet_set_encryption_key: keylen too big: %d", keylen);
452 memcpy(ssh1_key, key, keylen);
453 ssh1_keylen = keylen;
454 cipher_init(&send_context, cipher, key, keylen, NULL, 0, CIPHER_ENCRYPT);
455 cipher_init(&receive_context, cipher, key, keylen, NULL, 0, CIPHER_DECRYPT);
459 packet_get_encryption_key(u_char *key)
462 return (ssh1_keylen);
463 memcpy(key, ssh1_key, ssh1_keylen);
464 return (ssh1_keylen);
467 /* Start constructing a packet to send. */
469 packet_start(u_char type)
474 DBG(debug("packet_start[%d]", type));
475 len = compat20 ? 6 : 9;
476 memset(buf, 0, len - 1);
478 buffer_clear(&outgoing_packet);
479 buffer_append(&outgoing_packet, buf, len);
482 /* Append payload. */
484 packet_put_char(int value)
488 buffer_append(&outgoing_packet, &ch, 1);
492 packet_put_int(u_int value)
494 buffer_put_int(&outgoing_packet, value);
498 packet_put_string(const void *buf, u_int len)
500 buffer_put_string(&outgoing_packet, buf, len);
504 packet_put_cstring(const char *str)
506 buffer_put_cstring(&outgoing_packet, str);
510 packet_put_raw(const void *buf, u_int len)
512 buffer_append(&outgoing_packet, buf, len);
516 packet_put_bignum(BIGNUM * value)
518 buffer_put_bignum(&outgoing_packet, value);
522 packet_put_bignum2(BIGNUM * value)
524 buffer_put_bignum2(&outgoing_packet, value);
528 * Finalizes and sends the packet. If the encryption key has been set,
529 * encrypts the packet before sending.
541 * If using packet compression, compress the payload of the outgoing
544 if (packet_compression) {
545 buffer_clear(&compression_buffer);
547 buffer_consume(&outgoing_packet, 8);
549 buffer_append(&compression_buffer, "\0\0\0\0\0\0\0\0", 8);
550 buffer_compress(&outgoing_packet, &compression_buffer);
551 buffer_clear(&outgoing_packet);
552 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
553 buffer_len(&compression_buffer));
555 /* Compute packet length without padding (add checksum, remove padding). */
556 len = buffer_len(&outgoing_packet) + 4 - 8;
558 /* Insert padding. Initialized to zero in packet_start1() */
559 padding = 8 - len % 8;
560 if (!send_context.plaintext) {
561 cp = buffer_ptr(&outgoing_packet);
562 for (i = 0; i < padding; i++) {
565 cp[7 - i] = rnd & 0xff;
569 buffer_consume(&outgoing_packet, 8 - padding);
571 /* Add check bytes. */
572 checksum = ssh_crc32(buffer_ptr(&outgoing_packet),
573 buffer_len(&outgoing_packet));
574 put_u32(buf, checksum);
575 buffer_append(&outgoing_packet, buf, 4);
578 fprintf(stderr, "packet_send plain: ");
579 buffer_dump(&outgoing_packet);
582 /* Append to output. */
584 buffer_append(&output, buf, 4);
585 cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
586 cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
587 buffer_len(&outgoing_packet));
590 fprintf(stderr, "encrypted: ");
591 buffer_dump(&output);
594 buffer_clear(&outgoing_packet);
597 * Note that the packet is now only buffered in output. It won't be
598 * actually sent until packet_write_wait or packet_write_poll is
604 set_newkeys(int mode)
610 u_int64_t *max_blocks;
613 debug2("set_newkeys: mode %d", mode);
615 if (mode == MODE_OUT) {
617 crypt_type = CIPHER_ENCRYPT;
618 p_send.packets = p_send.blocks = 0;
619 max_blocks = &max_blocks_out;
621 cc = &receive_context;
622 crypt_type = CIPHER_DECRYPT;
623 p_read.packets = p_read.blocks = 0;
624 max_blocks = &max_blocks_in;
626 if (newkeys[mode] != NULL) {
627 debug("set_newkeys: rekeying");
629 enc = &newkeys[mode]->enc;
630 mac = &newkeys[mode]->mac;
631 comp = &newkeys[mode]->comp;
640 xfree(newkeys[mode]);
642 newkeys[mode] = kex_get_newkeys(mode);
643 if (newkeys[mode] == NULL)
644 fatal("newkeys: no keys for mode %d", mode);
645 enc = &newkeys[mode]->enc;
646 mac = &newkeys[mode]->mac;
647 comp = &newkeys[mode]->comp;
648 if (mac->md != NULL) {
652 DBG(debug("cipher_init_context: %d", mode));
653 cipher_init(cc, enc->cipher, enc->key, enc->key_len,
654 enc->iv, enc->block_size, crypt_type);
655 /* Deleting the keys does not gain extra security */
656 /* memset(enc->iv, 0, enc->block_size);
657 memset(enc->key, 0, enc->key_len);
658 memset(mac->key, 0, mac->key_len); */
659 if ((comp->type == COMP_ZLIB ||
660 (comp->type == COMP_DELAYED && after_authentication)) &&
661 comp->enabled == 0) {
662 packet_init_compression();
663 if (mode == MODE_OUT)
664 buffer_compress_init_send(6);
666 buffer_compress_init_recv();
670 * The 2^(blocksize*2) limit is too expensive for 3DES,
671 * blowfish, etc, so enforce a 1GB limit for small blocksizes.
673 if (enc->block_size >= 16)
674 *max_blocks = (u_int64_t)1 << (enc->block_size*2);
676 *max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
678 *max_blocks = MIN(*max_blocks, rekey_limit / enc->block_size);
682 * Delayed compression for SSH2 is enabled after authentication:
683 * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
684 * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
687 packet_enable_delayed_compress(void)
693 * Remember that we are past the authentication step, so rekeying
694 * with COMP_DELAYED will turn on compression immediately.
696 after_authentication = 1;
697 for (mode = 0; mode < MODE_MAX; mode++) {
698 /* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
699 if (newkeys[mode] == NULL)
701 comp = &newkeys[mode]->comp;
702 if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
703 packet_init_compression();
704 if (mode == MODE_OUT)
705 buffer_compress_init_send(6);
707 buffer_compress_init_recv();
714 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
717 packet_send2_wrapped(void)
719 u_char type, *cp, *macbuf = NULL;
721 u_int packet_length = 0;
729 if (newkeys[MODE_OUT] != NULL) {
730 enc = &newkeys[MODE_OUT]->enc;
731 mac = &newkeys[MODE_OUT]->mac;
732 comp = &newkeys[MODE_OUT]->comp;
734 block_size = enc ? enc->block_size : 8;
736 cp = buffer_ptr(&outgoing_packet);
740 fprintf(stderr, "plain: ");
741 buffer_dump(&outgoing_packet);
744 if (comp && comp->enabled) {
745 len = buffer_len(&outgoing_packet);
746 /* skip header, compress only payload */
747 buffer_consume(&outgoing_packet, 5);
748 buffer_clear(&compression_buffer);
749 buffer_compress(&outgoing_packet, &compression_buffer);
750 buffer_clear(&outgoing_packet);
751 buffer_append(&outgoing_packet, "\0\0\0\0\0", 5);
752 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
753 buffer_len(&compression_buffer));
754 DBG(debug("compression: raw %d compressed %d", len,
755 buffer_len(&outgoing_packet)));
758 /* sizeof (packet_len + pad_len + payload) */
759 len = buffer_len(&outgoing_packet);
762 * calc size of padding, alloc space, get random data,
763 * minimum padding is 4 bytes
765 padlen = block_size - (len % block_size);
767 padlen += block_size;
769 /* will wrap if extra_pad+padlen > 255 */
770 extra_pad = roundup(extra_pad, block_size);
771 pad = extra_pad - ((len + padlen) % extra_pad);
772 debug3("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
773 pad, len, padlen, extra_pad);
777 cp = buffer_append_space(&outgoing_packet, padlen);
778 if (enc && !send_context.plaintext) {
780 for (i = 0; i < padlen; i++) {
788 memset(cp, 0, padlen);
790 /* packet_length includes payload, padding and padding length field */
791 packet_length = buffer_len(&outgoing_packet) - 4;
792 cp = buffer_ptr(&outgoing_packet);
793 put_u32(cp, packet_length);
795 DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen));
797 /* compute MAC over seqnr and packet(length fields, payload, padding) */
798 if (mac && mac->enabled) {
799 macbuf = mac_compute(mac, p_send.seqnr,
800 buffer_ptr(&outgoing_packet),
801 buffer_len(&outgoing_packet));
802 DBG(debug("done calc MAC out #%d", p_send.seqnr));
804 /* encrypt packet and append to output buffer. */
805 cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
806 cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
807 buffer_len(&outgoing_packet));
808 /* append unencrypted MAC */
809 if (mac && mac->enabled)
810 buffer_append(&output, macbuf, mac->mac_len);
812 fprintf(stderr, "encrypted: ");
813 buffer_dump(&output);
815 /* increment sequence number for outgoing packets */
816 if (++p_send.seqnr == 0)
817 logit("outgoing seqnr wraps around");
818 if (++p_send.packets == 0)
819 if (!(datafellows & SSH_BUG_NOREKEY))
820 fatal("XXX too many packets with same key");
821 p_send.blocks += (packet_length + 4) / block_size;
822 buffer_clear(&outgoing_packet);
824 if (type == SSH2_MSG_NEWKEYS)
825 set_newkeys(MODE_OUT);
826 else if (type == SSH2_MSG_USERAUTH_SUCCESS && server_side)
827 packet_enable_delayed_compress();
833 static int rekeying = 0;
837 cp = buffer_ptr(&outgoing_packet);
840 /* during rekeying we can only send key exchange messages */
842 if (!((type >= SSH2_MSG_TRANSPORT_MIN) &&
843 (type <= SSH2_MSG_TRANSPORT_MAX))) {
844 debug("enqueue packet: %u", type);
845 p = xmalloc(sizeof(*p));
847 memcpy(&p->payload, &outgoing_packet, sizeof(Buffer));
848 buffer_init(&outgoing_packet);
849 TAILQ_INSERT_TAIL(&outgoing, p, next);
854 /* rekeying starts with sending KEXINIT */
855 if (type == SSH2_MSG_KEXINIT)
858 packet_send2_wrapped();
860 /* after a NEWKEYS message we can send the complete queue */
861 if (type == SSH2_MSG_NEWKEYS) {
863 while ((p = TAILQ_FIRST(&outgoing))) {
865 debug("dequeue packet: %u", type);
866 buffer_free(&outgoing_packet);
867 memcpy(&outgoing_packet, &p->payload,
869 TAILQ_REMOVE(&outgoing, p, next);
871 packet_send2_wrapped();
883 DBG(debug("packet_send done"));
887 * Waits until a packet has been received, and returns its type. Note that
888 * no other data is processed until this returns, so this function should not
889 * be used during the interactive session.
893 packet_read_seqnr(u_int32_t *seqnr_p)
898 DBG(debug("packet_read()"));
900 setp = (fd_set *)xcalloc(howmany(connection_in+1, NFDBITS),
903 /* Since we are blocking, ensure that all written packets have been sent. */
906 /* Stay in the loop until we have received a complete packet. */
908 /* Try to read a packet from the buffer. */
909 type = packet_read_poll_seqnr(seqnr_p);
911 type == SSH_SMSG_SUCCESS
912 || type == SSH_SMSG_FAILURE
913 || type == SSH_CMSG_EOF
914 || type == SSH_CMSG_EXIT_CONFIRMATION))
916 /* If we got a packet, return it. */
917 if (type != SSH_MSG_NONE) {
922 * Otherwise, wait for some data to arrive, add it to the
923 * buffer, and try again.
925 memset(setp, 0, howmany(connection_in + 1, NFDBITS) *
927 FD_SET(connection_in, setp);
929 /* Wait for some data to arrive. */
930 while (select(connection_in + 1, setp, NULL, NULL, NULL) == -1 &&
931 (errno == EAGAIN || errno == EINTR))
934 /* Read data from the socket. */
935 len = read(connection_in, buf, sizeof(buf));
937 logit("Connection closed by %.200s", get_remote_ipaddr());
941 fatal("Read from socket failed: %.100s", strerror(errno));
942 /* Append it to the buffer. */
943 packet_process_incoming(buf, len);
951 return packet_read_seqnr(NULL);
955 * Waits until a packet has been received, verifies that its type matches
956 * that given, and gives a fatal error and exits if there is a mismatch.
960 packet_read_expect(int expected_type)
964 type = packet_read();
965 if (type != expected_type)
966 packet_disconnect("Protocol error: expected packet type %d, got %d",
967 expected_type, type);
970 /* Checks if a full packet is available in the data received so far via
971 * packet_process_incoming. If so, reads the packet; otherwise returns
972 * SSH_MSG_NONE. This does not wait for data from the connection.
974 * SSH_MSG_DISCONNECT is handled specially here. Also,
975 * SSH_MSG_IGNORE messages are skipped by this function and are never returned
980 packet_read_poll1(void)
982 u_int len, padded_len;
984 u_int checksum, stored_checksum;
986 /* Check if input size is less than minimum packet size. */
987 if (buffer_len(&input) < 4 + 8)
989 /* Get length of incoming packet. */
990 cp = buffer_ptr(&input);
992 if (len < 1 + 2 + 2 || len > 256 * 1024)
993 packet_disconnect("Bad packet length %u.", len);
994 padded_len = (len + 8) & ~7;
996 /* Check if the packet has been entirely received. */
997 if (buffer_len(&input) < 4 + padded_len)
1000 /* The entire packet is in buffer. */
1002 /* Consume packet length. */
1003 buffer_consume(&input, 4);
1006 * Cryptographic attack detector for ssh
1007 * (C)1998 CORE-SDI, Buenos Aires Argentina
1008 * Ariel Futoransky(futo@core-sdi.com)
1010 if (!receive_context.plaintext) {
1011 switch (detect_attack(buffer_ptr(&input), padded_len)) {
1012 case DEATTACK_DETECTED:
1013 packet_disconnect("crc32 compensation attack: "
1014 "network attack detected");
1015 case DEATTACK_DOS_DETECTED:
1016 packet_disconnect("deattack denial of "
1017 "service detected");
1021 /* Decrypt data to incoming_packet. */
1022 buffer_clear(&incoming_packet);
1023 cp = buffer_append_space(&incoming_packet, padded_len);
1024 cipher_crypt(&receive_context, cp, buffer_ptr(&input), padded_len);
1026 buffer_consume(&input, padded_len);
1029 fprintf(stderr, "read_poll plain: ");
1030 buffer_dump(&incoming_packet);
1033 /* Compute packet checksum. */
1034 checksum = ssh_crc32(buffer_ptr(&incoming_packet),
1035 buffer_len(&incoming_packet) - 4);
1038 buffer_consume(&incoming_packet, 8 - len % 8);
1040 /* Test check bytes. */
1041 if (len != buffer_len(&incoming_packet))
1042 packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
1043 len, buffer_len(&incoming_packet));
1045 cp = (u_char *)buffer_ptr(&incoming_packet) + len - 4;
1046 stored_checksum = get_u32(cp);
1047 if (checksum != stored_checksum)
1048 packet_disconnect("Corrupted check bytes on input.");
1049 buffer_consume_end(&incoming_packet, 4);
1051 if (packet_compression) {
1052 buffer_clear(&compression_buffer);
1053 buffer_uncompress(&incoming_packet, &compression_buffer);
1054 buffer_clear(&incoming_packet);
1055 buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
1056 buffer_len(&compression_buffer));
1058 type = buffer_get_char(&incoming_packet);
1059 if (type < SSH_MSG_MIN || type > SSH_MSG_MAX)
1060 packet_disconnect("Invalid ssh1 packet type: %d", type);
1065 packet_read_poll2(u_int32_t *seqnr_p)
1067 static u_int packet_length = 0;
1069 u_char *macbuf, *cp, type;
1070 u_int maclen, block_size;
1075 if (newkeys[MODE_IN] != NULL) {
1076 enc = &newkeys[MODE_IN]->enc;
1077 mac = &newkeys[MODE_IN]->mac;
1078 comp = &newkeys[MODE_IN]->comp;
1080 maclen = mac && mac->enabled ? mac->mac_len : 0;
1081 block_size = enc ? enc->block_size : 8;
1083 if (packet_length == 0) {
1085 * check if input size is less than the cipher block size,
1086 * decrypt first block and extract length of incoming packet
1088 if (buffer_len(&input) < block_size)
1089 return SSH_MSG_NONE;
1090 buffer_clear(&incoming_packet);
1091 cp = buffer_append_space(&incoming_packet, block_size);
1092 cipher_crypt(&receive_context, cp, buffer_ptr(&input),
1094 cp = buffer_ptr(&incoming_packet);
1095 packet_length = get_u32(cp);
1096 if (packet_length < 1 + 4 || packet_length > 256 * 1024) {
1098 buffer_dump(&incoming_packet);
1100 packet_disconnect("Bad packet length %u.", packet_length);
1102 DBG(debug("input: packet len %u", packet_length+4));
1103 buffer_consume(&input, block_size);
1105 /* we have a partial packet of block_size bytes */
1106 need = 4 + packet_length - block_size;
1107 DBG(debug("partial packet %d, need %d, maclen %d", block_size,
1109 if (need % block_size != 0)
1110 fatal("padding error: need %d block %d mod %d",
1111 need, block_size, need % block_size);
1113 * check if the entire packet has been received and
1114 * decrypt into incoming_packet
1116 if (buffer_len(&input) < need + maclen)
1117 return SSH_MSG_NONE;
1119 fprintf(stderr, "read_poll enc/full: ");
1120 buffer_dump(&input);
1122 cp = buffer_append_space(&incoming_packet, need);
1123 cipher_crypt(&receive_context, cp, buffer_ptr(&input), need);
1124 buffer_consume(&input, need);
1126 * compute MAC over seqnr and packet,
1127 * increment sequence number for incoming packet
1129 if (mac && mac->enabled) {
1130 macbuf = mac_compute(mac, p_read.seqnr,
1131 buffer_ptr(&incoming_packet),
1132 buffer_len(&incoming_packet));
1133 if (memcmp(macbuf, buffer_ptr(&input), mac->mac_len) != 0)
1134 packet_disconnect("Corrupted MAC on input.");
1135 DBG(debug("MAC #%d ok", p_read.seqnr));
1136 buffer_consume(&input, mac->mac_len);
1138 if (seqnr_p != NULL)
1139 *seqnr_p = p_read.seqnr;
1140 if (++p_read.seqnr == 0)
1141 logit("incoming seqnr wraps around");
1142 if (++p_read.packets == 0)
1143 if (!(datafellows & SSH_BUG_NOREKEY))
1144 fatal("XXX too many packets with same key");
1145 p_read.blocks += (packet_length + 4) / block_size;
1148 cp = buffer_ptr(&incoming_packet);
1150 DBG(debug("input: padlen %d", padlen));
1152 packet_disconnect("Corrupted padlen %d on input.", padlen);
1154 /* skip packet size + padlen, discard padding */
1155 buffer_consume(&incoming_packet, 4 + 1);
1156 buffer_consume_end(&incoming_packet, padlen);
1158 DBG(debug("input: len before de-compress %d", buffer_len(&incoming_packet)));
1159 if (comp && comp->enabled) {
1160 buffer_clear(&compression_buffer);
1161 buffer_uncompress(&incoming_packet, &compression_buffer);
1162 buffer_clear(&incoming_packet);
1163 buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
1164 buffer_len(&compression_buffer));
1165 DBG(debug("input: len after de-compress %d",
1166 buffer_len(&incoming_packet)));
1169 * get packet type, implies consume.
1170 * return length of payload (without type field)
1172 type = buffer_get_char(&incoming_packet);
1173 if (type < SSH2_MSG_MIN || type >= SSH2_MSG_LOCAL_MIN)
1174 packet_disconnect("Invalid ssh2 packet type: %d", type);
1175 if (type == SSH2_MSG_NEWKEYS)
1176 set_newkeys(MODE_IN);
1177 else if (type == SSH2_MSG_USERAUTH_SUCCESS && !server_side)
1178 packet_enable_delayed_compress();
1180 fprintf(stderr, "read/plain[%d]:\r\n", type);
1181 buffer_dump(&incoming_packet);
1183 /* reset for next packet */
1189 packet_read_poll_seqnr(u_int32_t *seqnr_p)
1191 u_int reason, seqnr;
1197 type = packet_read_poll2(seqnr_p);
1199 DBG(debug("received packet type %d", type));
1201 case SSH2_MSG_IGNORE:
1203 case SSH2_MSG_DEBUG:
1205 msg = packet_get_string(NULL);
1206 debug("Remote: %.900s", msg);
1208 msg = packet_get_string(NULL);
1211 case SSH2_MSG_DISCONNECT:
1212 reason = packet_get_int();
1213 msg = packet_get_string(NULL);
1214 logit("Received disconnect from %s: %u: %.400s",
1215 get_remote_ipaddr(), reason, msg);
1219 case SSH2_MSG_UNIMPLEMENTED:
1220 seqnr = packet_get_int();
1221 debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1228 type = packet_read_poll1();
1230 case SSH_MSG_IGNORE:
1233 msg = packet_get_string(NULL);
1234 debug("Remote: %.900s", msg);
1237 case SSH_MSG_DISCONNECT:
1238 msg = packet_get_string(NULL);
1239 logit("Received disconnect from %s: %.400s",
1240 get_remote_ipaddr(), msg);
1245 DBG(debug("received packet type %d", type));
1253 packet_read_poll(void)
1255 return packet_read_poll_seqnr(NULL);
1259 * Buffers the given amount of input characters. This is intended to be used
1260 * together with packet_read_poll.
1264 packet_process_incoming(const char *buf, u_int len)
1266 buffer_append(&input, buf, len);
1269 /* Returns a character from the packet. */
1272 packet_get_char(void)
1276 buffer_get(&incoming_packet, &ch, 1);
1280 /* Returns an integer from the packet data. */
1283 packet_get_int(void)
1285 return buffer_get_int(&incoming_packet);
1289 * Returns an arbitrary precision integer from the packet data. The integer
1290 * must have been initialized before this call.
1294 packet_get_bignum(BIGNUM * value)
1296 buffer_get_bignum(&incoming_packet, value);
1300 packet_get_bignum2(BIGNUM * value)
1302 buffer_get_bignum2(&incoming_packet, value);
1306 packet_get_raw(u_int *length_ptr)
1308 u_int bytes = buffer_len(&incoming_packet);
1310 if (length_ptr != NULL)
1311 *length_ptr = bytes;
1312 return buffer_ptr(&incoming_packet);
1316 packet_remaining(void)
1318 return buffer_len(&incoming_packet);
1322 * Returns a string from the packet data. The string is allocated using
1323 * xmalloc; it is the responsibility of the calling program to free it when
1324 * no longer needed. The length_ptr argument may be NULL, or point to an
1325 * integer into which the length of the string is stored.
1329 packet_get_string(u_int *length_ptr)
1331 return buffer_get_string(&incoming_packet, length_ptr);
1335 * Sends a diagnostic message from the server to the client. This message
1336 * can be sent at any time (but not while constructing another message). The
1337 * message is printed immediately, but only if the client is being executed
1338 * in verbose mode. These messages are primarily intended to ease debugging
1339 * authentication problems. The length of the formatted message must not
1340 * exceed 1024 bytes. This will automatically call packet_write_wait.
1344 packet_send_debug(const char *fmt,...)
1349 if (compat20 && (datafellows & SSH_BUG_DEBUG))
1352 va_start(args, fmt);
1353 vsnprintf(buf, sizeof(buf), fmt, args);
1357 packet_start(SSH2_MSG_DEBUG);
1358 packet_put_char(0); /* bool: always display */
1359 packet_put_cstring(buf);
1360 packet_put_cstring("");
1362 packet_start(SSH_MSG_DEBUG);
1363 packet_put_cstring(buf);
1366 packet_write_wait();
1370 * Logs the error plus constructs and sends a disconnect packet, closes the
1371 * connection, and exits. This function never returns. The error message
1372 * should not contain a newline. The length of the formatted message must
1373 * not exceed 1024 bytes.
1377 packet_disconnect(const char *fmt,...)
1381 static int disconnecting = 0;
1383 if (disconnecting) /* Guard against recursive invocations. */
1384 fatal("packet_disconnect called recursively.");
1388 * Format the message. Note that the caller must make sure the
1389 * message is of limited size.
1391 va_start(args, fmt);
1392 vsnprintf(buf, sizeof(buf), fmt, args);
1395 /* Display the error locally */
1396 logit("Disconnecting: %.100s", buf);
1398 /* Send the disconnect message to the other side, and wait for it to get sent. */
1400 packet_start(SSH2_MSG_DISCONNECT);
1401 packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1402 packet_put_cstring(buf);
1403 packet_put_cstring("");
1405 packet_start(SSH_MSG_DISCONNECT);
1406 packet_put_cstring(buf);
1409 packet_write_wait();
1411 /* Stop listening for connections. */
1412 channel_close_all();
1414 /* Close the connection. */
1419 /* Checks if there is any buffered output, and tries to write some of the output. */
1422 packet_write_poll(void)
1424 int len = buffer_len(&output);
1427 len = write(connection_out, buffer_ptr(&output), len);
1429 if (errno == EAGAIN)
1432 fatal("Write failed: %.100s", strerror(errno));
1434 buffer_consume(&output, len);
1439 * Calls packet_write_poll repeatedly until all pending output data has been
1444 packet_write_wait(void)
1448 setp = (fd_set *)xcalloc(howmany(connection_out + 1, NFDBITS),
1450 packet_write_poll();
1451 while (packet_have_data_to_write()) {
1452 memset(setp, 0, howmany(connection_out + 1, NFDBITS) *
1454 FD_SET(connection_out, setp);
1455 while (select(connection_out + 1, NULL, setp, NULL, NULL) == -1 &&
1456 (errno == EAGAIN || errno == EINTR))
1458 packet_write_poll();
1463 /* Returns true if there is buffered data to write to the connection. */
1466 packet_have_data_to_write(void)
1468 return buffer_len(&output) != 0;
1471 /* Returns true if there is not too much data to write to the connection. */
1474 packet_not_very_much_data_to_write(void)
1476 if (interactive_mode)
1477 return buffer_len(&output) < 16384;
1479 return buffer_len(&output) < 128 * 1024;
1484 packet_set_tos(int interactive)
1486 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1487 int tos = interactive ? IPTOS_LOWDELAY : IPTOS_THROUGHPUT;
1489 if (!packet_connection_is_on_socket() ||
1490 !packet_connection_is_ipv4())
1492 if (setsockopt(connection_in, IPPROTO_IP, IP_TOS, &tos,
1494 error("setsockopt IP_TOS %d: %.100s:",
1495 tos, strerror(errno));
1499 /* Informs that the current session is interactive. Sets IP flags for that. */
1502 packet_set_interactive(int interactive)
1504 static int called = 0;
1510 /* Record that we are in interactive mode. */
1511 interactive_mode = interactive;
1513 /* Only set socket options if using a socket. */
1514 if (!packet_connection_is_on_socket())
1516 set_nodelay(connection_in);
1517 packet_set_tos(interactive);
1520 /* Returns true if the current connection is interactive. */
1523 packet_is_interactive(void)
1525 return interactive_mode;
1529 packet_set_maxsize(u_int s)
1531 static int called = 0;
1534 logit("packet_set_maxsize: called twice: old %d new %d",
1535 max_packet_size, s);
1538 if (s < 4 * 1024 || s > 1024 * 1024) {
1539 logit("packet_set_maxsize: bad size %d", s);
1543 debug("packet_set_maxsize: setting to %d", s);
1544 max_packet_size = s;
1548 /* roundup current message to pad bytes */
1550 packet_add_padding(u_char pad)
1556 * 9.2. Ignored Data Message
1558 * byte SSH_MSG_IGNORE
1561 * All implementations MUST understand (and ignore) this message at any
1562 * time (after receiving the protocol version). No implementation is
1563 * required to send them. This message can be used as an additional
1564 * protection measure against advanced traffic analysis techniques.
1567 packet_send_ignore(int nbytes)
1572 packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1573 packet_put_int(nbytes);
1574 for (i = 0; i < nbytes; i++) {
1577 packet_put_char((u_char)rnd & 0xff);
1582 #define MAX_PACKETS (1U<<31)
1584 packet_need_rekeying(void)
1586 if (datafellows & SSH_BUG_NOREKEY)
1589 (p_send.packets > MAX_PACKETS) ||
1590 (p_read.packets > MAX_PACKETS) ||
1591 (max_blocks_out && (p_send.blocks > max_blocks_out)) ||
1592 (max_blocks_in && (p_read.blocks > max_blocks_in));
1596 packet_set_rekey_limit(u_int32_t bytes)
1598 rekey_limit = bytes;
1602 packet_set_server(void)
1608 packet_set_authenticated(void)
1610 after_authentication = 1;