1 /* $OpenBSD: packet.c,v 1.137 2006/07/22 20:48:23 stevesk 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/socket.h>
46 #include <netinet/in_systm.h>
47 #include <netinet/in.h>
48 #include <netinet/ip.h>
84 * This variable contains the file descriptors used for communicating with
85 * the other side. connection_in is used for reading; connection_out for
86 * writing. These can be the same descriptor, in which case it is assumed to
89 static int connection_in
= -1;
90 static int connection_out
= -1;
92 /* Protocol flags for the remote side. */
93 static u_int remote_protocol_flags
= 0;
95 /* Encryption context for receiving data. This is only used for decryption. */
96 static CipherContext receive_context
;
98 /* Encryption context for sending data. This is only used for encryption. */
99 static CipherContext send_context
;
101 /* Buffer for raw input data from the socket. */
104 /* Buffer for raw output data going to the socket. */
107 /* Buffer for the partial outgoing packet being constructed. */
108 static Buffer outgoing_packet
;
110 /* Buffer for the incoming packet currently being processed. */
111 static Buffer incoming_packet
;
113 /* Scratch buffer for packet compression/decompression. */
114 static Buffer compression_buffer
;
115 static int compression_buffer_ready
= 0;
117 /* Flag indicating whether packet compression/decompression is enabled. */
118 static int packet_compression
= 0;
120 /* default maximum packet size */
121 u_int max_packet_size
= 32768;
123 /* Flag indicating whether this module has been initialized. */
124 static int initialized
= 0;
126 /* Set to true if the connection is interactive. */
127 static int interactive_mode
= 0;
129 /* Set to true if we are the server side. */
130 static int server_side
= 0;
132 /* Set to true if we are authenticated. */
133 static int after_authentication
= 0;
135 /* Session key information for Encryption and MAC */
136 Newkeys
*newkeys
[MODE_MAX
];
137 static struct packet_state
{
143 static u_int64_t max_blocks_in
, max_blocks_out
;
144 static u_int32_t rekey_limit
;
146 /* Session key for protocol v1 */
147 static u_char ssh1_key
[SSH_SESSION_KEY_LENGTH
];
148 static u_int ssh1_keylen
;
150 /* roundup current message to extra_pad bytes */
151 static u_char extra_pad
= 0;
154 TAILQ_ENTRY(packet
) next
;
158 TAILQ_HEAD(, packet
) outgoing
;
161 * Sets the descriptors used for communication. Disables encryption until
162 * packet_set_encryption_key is called.
165 packet_set_connection(int fd_in
, int fd_out
)
167 Cipher
*none
= cipher_by_name("none");
170 fatal("packet_set_connection: cannot load cipher 'none'");
171 connection_in
= fd_in
;
172 connection_out
= fd_out
;
173 cipher_init(&send_context
, none
, (const u_char
*)"",
174 0, NULL
, 0, CIPHER_ENCRYPT
);
175 cipher_init(&receive_context
, none
, (const u_char
*)"",
176 0, NULL
, 0, CIPHER_DECRYPT
);
177 newkeys
[MODE_IN
] = newkeys
[MODE_OUT
] = NULL
;
181 buffer_init(&output
);
182 buffer_init(&outgoing_packet
);
183 buffer_init(&incoming_packet
);
184 TAILQ_INIT(&outgoing
);
188 /* Returns 1 if remote host is connected via socket, 0 if not. */
191 packet_connection_is_on_socket(void)
193 struct sockaddr_storage from
, to
;
194 socklen_t fromlen
, tolen
;
196 /* filedescriptors in and out are the same, so it's a socket */
197 if (connection_in
== connection_out
)
199 fromlen
= sizeof(from
);
200 memset(&from
, 0, sizeof(from
));
201 if (getpeername(connection_in
, (struct sockaddr
*)&from
, &fromlen
) < 0)
204 memset(&to
, 0, sizeof(to
));
205 if (getpeername(connection_out
, (struct sockaddr
*)&to
, &tolen
) < 0)
207 if (fromlen
!= tolen
|| memcmp(&from
, &to
, fromlen
) != 0)
209 if (from
.ss_family
!= AF_INET
&& from
.ss_family
!= AF_INET6
)
215 * Exports an IV from the CipherContext required to export the key
216 * state back from the unprivileged child to the privileged parent
221 packet_get_keyiv(int mode
, u_char
*iv
, u_int len
)
225 if (mode
== MODE_OUT
)
228 cc
= &receive_context
;
230 cipher_get_keyiv(cc
, iv
, len
);
234 packet_get_keycontext(int mode
, u_char
*dat
)
238 if (mode
== MODE_OUT
)
241 cc
= &receive_context
;
243 return (cipher_get_keycontext(cc
, dat
));
247 packet_set_keycontext(int mode
, u_char
*dat
)
251 if (mode
== MODE_OUT
)
254 cc
= &receive_context
;
256 cipher_set_keycontext(cc
, dat
);
260 packet_get_keyiv_len(int mode
)
264 if (mode
== MODE_OUT
)
267 cc
= &receive_context
;
269 return (cipher_get_keyiv_len(cc
));
273 packet_set_iv(int mode
, u_char
*dat
)
277 if (mode
== MODE_OUT
)
280 cc
= &receive_context
;
282 cipher_set_keyiv(cc
, dat
);
286 packet_get_ssh1_cipher(void)
288 return (cipher_get_number(receive_context
.cipher
));
292 packet_get_state(int mode
, u_int32_t
*seqnr
, u_int64_t
*blocks
, u_int32_t
*packets
)
294 struct packet_state
*state
;
296 state
= (mode
== MODE_IN
) ? &p_read
: &p_send
;
297 *seqnr
= state
->seqnr
;
298 *blocks
= state
->blocks
;
299 *packets
= state
->packets
;
303 packet_set_state(int mode
, u_int32_t seqnr
, u_int64_t blocks
, u_int32_t packets
)
305 struct packet_state
*state
;
307 state
= (mode
== MODE_IN
) ? &p_read
: &p_send
;
308 state
->seqnr
= seqnr
;
309 state
->blocks
= blocks
;
310 state
->packets
= packets
;
313 /* returns 1 if connection is via ipv4 */
316 packet_connection_is_ipv4(void)
318 struct sockaddr_storage to
;
319 socklen_t tolen
= sizeof(to
);
321 memset(&to
, 0, sizeof(to
));
322 if (getsockname(connection_out
, (struct sockaddr
*)&to
, &tolen
) < 0)
324 if (to
.ss_family
== AF_INET
)
327 if (to
.ss_family
== AF_INET6
&&
328 IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6
*)&to
)->sin6_addr
))
334 /* Sets the connection into non-blocking mode. */
337 packet_set_nonblocking(void)
339 /* Set the socket into non-blocking mode. */
340 set_nonblock(connection_in
);
342 if (connection_out
!= connection_in
)
343 set_nonblock(connection_out
);
346 /* Returns the socket used for reading. */
349 packet_get_connection_in(void)
351 return connection_in
;
354 /* Returns the descriptor used for writing. */
357 packet_get_connection_out(void)
359 return connection_out
;
362 /* Closes the connection and clears and frees internal data structures. */
370 if (connection_in
== connection_out
) {
371 shutdown(connection_out
, SHUT_RDWR
);
372 close(connection_out
);
374 close(connection_in
);
375 close(connection_out
);
378 buffer_free(&output
);
379 buffer_free(&outgoing_packet
);
380 buffer_free(&incoming_packet
);
381 if (compression_buffer_ready
) {
382 buffer_free(&compression_buffer
);
383 buffer_compress_uninit();
385 cipher_cleanup(&send_context
);
386 cipher_cleanup(&receive_context
);
389 /* Sets remote side protocol flags. */
392 packet_set_protocol_flags(u_int protocol_flags
)
394 remote_protocol_flags
= protocol_flags
;
397 /* Returns the remote protocol flags set earlier by the above function. */
400 packet_get_protocol_flags(void)
402 return remote_protocol_flags
;
406 * Starts packet compression from the next packet on in both directions.
407 * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
411 packet_init_compression(void)
413 if (compression_buffer_ready
== 1)
415 compression_buffer_ready
= 1;
416 buffer_init(&compression_buffer
);
420 packet_start_compression(int level
)
422 if (packet_compression
&& !compat20
)
423 fatal("Compression already enabled.");
424 packet_compression
= 1;
425 packet_init_compression();
426 buffer_compress_init_send(level
);
427 buffer_compress_init_recv();
431 * Causes any further packets to be encrypted using the given key. The same
432 * key is used for both sending and reception. However, both directions are
433 * encrypted independently of each other.
437 packet_set_encryption_key(const u_char
*key
, u_int keylen
,
440 Cipher
*cipher
= cipher_by_number(number
);
443 fatal("packet_set_encryption_key: unknown cipher number %d", number
);
445 fatal("packet_set_encryption_key: keylen too small: %d", keylen
);
446 if (keylen
> SSH_SESSION_KEY_LENGTH
)
447 fatal("packet_set_encryption_key: keylen too big: %d", keylen
);
448 memcpy(ssh1_key
, key
, keylen
);
449 ssh1_keylen
= keylen
;
450 cipher_init(&send_context
, cipher
, key
, keylen
, NULL
, 0, CIPHER_ENCRYPT
);
451 cipher_init(&receive_context
, cipher
, key
, keylen
, NULL
, 0, CIPHER_DECRYPT
);
455 packet_get_encryption_key(u_char
*key
)
458 return (ssh1_keylen
);
459 memcpy(key
, ssh1_key
, ssh1_keylen
);
460 return (ssh1_keylen
);
463 /* Start constructing a packet to send. */
465 packet_start(u_char type
)
470 DBG(debug("packet_start[%d]", type
));
471 len
= compat20
? 6 : 9;
472 memset(buf
, 0, len
- 1);
474 buffer_clear(&outgoing_packet
);
475 buffer_append(&outgoing_packet
, buf
, len
);
478 /* Append payload. */
480 packet_put_char(int value
)
484 buffer_append(&outgoing_packet
, &ch
, 1);
488 packet_put_int(u_int value
)
490 buffer_put_int(&outgoing_packet
, value
);
494 packet_put_string(const void *buf
, u_int len
)
496 buffer_put_string(&outgoing_packet
, buf
, len
);
500 packet_put_cstring(const char *str
)
502 buffer_put_cstring(&outgoing_packet
, str
);
506 packet_put_raw(const void *buf
, u_int len
)
508 buffer_append(&outgoing_packet
, buf
, len
);
512 packet_put_bignum(BIGNUM
* value
)
514 buffer_put_bignum(&outgoing_packet
, value
);
518 packet_put_bignum2(BIGNUM
* value
)
520 buffer_put_bignum2(&outgoing_packet
, value
);
524 * Finalizes and sends the packet. If the encryption key has been set,
525 * encrypts the packet before sending.
537 * If using packet compression, compress the payload of the outgoing
540 if (packet_compression
) {
541 buffer_clear(&compression_buffer
);
543 buffer_consume(&outgoing_packet
, 8);
545 buffer_append(&compression_buffer
, "\0\0\0\0\0\0\0\0", 8);
546 buffer_compress(&outgoing_packet
, &compression_buffer
);
547 buffer_clear(&outgoing_packet
);
548 buffer_append(&outgoing_packet
, buffer_ptr(&compression_buffer
),
549 buffer_len(&compression_buffer
));
551 /* Compute packet length without padding (add checksum, remove padding). */
552 len
= buffer_len(&outgoing_packet
) + 4 - 8;
554 /* Insert padding. Initialized to zero in packet_start1() */
555 padding
= 8 - len
% 8;
556 if (!send_context
.plaintext
) {
557 cp
= buffer_ptr(&outgoing_packet
);
558 for (i
= 0; i
< padding
; i
++) {
561 cp
[7 - i
] = rnd
& 0xff;
565 buffer_consume(&outgoing_packet
, 8 - padding
);
567 /* Add check bytes. */
568 checksum
= ssh_crc32(buffer_ptr(&outgoing_packet
),
569 buffer_len(&outgoing_packet
));
570 put_u32(buf
, checksum
);
571 buffer_append(&outgoing_packet
, buf
, 4);
574 fprintf(stderr
, "packet_send plain: ");
575 buffer_dump(&outgoing_packet
);
578 /* Append to output. */
580 buffer_append(&output
, buf
, 4);
581 cp
= buffer_append_space(&output
, buffer_len(&outgoing_packet
));
582 cipher_crypt(&send_context
, cp
, buffer_ptr(&outgoing_packet
),
583 buffer_len(&outgoing_packet
));
586 fprintf(stderr
, "encrypted: ");
587 buffer_dump(&output
);
590 buffer_clear(&outgoing_packet
);
593 * Note that the packet is now only buffered in output. It won't be
594 * actually sent until packet_write_wait or packet_write_poll is
600 set_newkeys(int mode
)
606 u_int64_t
*max_blocks
;
609 debug2("set_newkeys: mode %d", mode
);
611 if (mode
== MODE_OUT
) {
613 crypt_type
= CIPHER_ENCRYPT
;
614 p_send
.packets
= p_send
.blocks
= 0;
615 max_blocks
= &max_blocks_out
;
617 cc
= &receive_context
;
618 crypt_type
= CIPHER_DECRYPT
;
619 p_read
.packets
= p_read
.blocks
= 0;
620 max_blocks
= &max_blocks_in
;
622 if (newkeys
[mode
] != NULL
) {
623 debug("set_newkeys: rekeying");
625 enc
= &newkeys
[mode
]->enc
;
626 mac
= &newkeys
[mode
]->mac
;
627 comp
= &newkeys
[mode
]->comp
;
628 memset(mac
->key
, 0, mac
->key_len
);
635 xfree(newkeys
[mode
]);
637 newkeys
[mode
] = kex_get_newkeys(mode
);
638 if (newkeys
[mode
] == NULL
)
639 fatal("newkeys: no keys for mode %d", mode
);
640 enc
= &newkeys
[mode
]->enc
;
641 mac
= &newkeys
[mode
]->mac
;
642 comp
= &newkeys
[mode
]->comp
;
645 DBG(debug("cipher_init_context: %d", mode
));
646 cipher_init(cc
, enc
->cipher
, enc
->key
, enc
->key_len
,
647 enc
->iv
, enc
->block_size
, crypt_type
);
648 /* Deleting the keys does not gain extra security */
649 /* memset(enc->iv, 0, enc->block_size);
650 memset(enc->key, 0, enc->key_len); */
651 if ((comp
->type
== COMP_ZLIB
||
652 (comp
->type
== COMP_DELAYED
&& after_authentication
)) &&
653 comp
->enabled
== 0) {
654 packet_init_compression();
655 if (mode
== MODE_OUT
)
656 buffer_compress_init_send(6);
658 buffer_compress_init_recv();
662 * The 2^(blocksize*2) limit is too expensive for 3DES,
663 * blowfish, etc, so enforce a 1GB limit for small blocksizes.
665 if (enc
->block_size
>= 16)
666 *max_blocks
= (u_int64_t
)1 << (enc
->block_size
*2);
668 *max_blocks
= ((u_int64_t
)1 << 30) / enc
->block_size
;
670 *max_blocks
= MIN(*max_blocks
, rekey_limit
/ enc
->block_size
);
674 * Delayed compression for SSH2 is enabled after authentication:
675 * This happans on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
676 * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
679 packet_enable_delayed_compress(void)
685 * Remember that we are past the authentication step, so rekeying
686 * with COMP_DELAYED will turn on compression immediately.
688 after_authentication
= 1;
689 for (mode
= 0; mode
< MODE_MAX
; mode
++) {
690 comp
= &newkeys
[mode
]->comp
;
691 if (comp
&& !comp
->enabled
&& comp
->type
== COMP_DELAYED
) {
692 packet_init_compression();
693 if (mode
== MODE_OUT
)
694 buffer_compress_init_send(6);
696 buffer_compress_init_recv();
703 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
706 packet_send2_wrapped(void)
708 u_char type
, *cp
, *macbuf
= NULL
;
710 u_int packet_length
= 0;
718 if (newkeys
[MODE_OUT
] != NULL
) {
719 enc
= &newkeys
[MODE_OUT
]->enc
;
720 mac
= &newkeys
[MODE_OUT
]->mac
;
721 comp
= &newkeys
[MODE_OUT
]->comp
;
723 block_size
= enc
? enc
->block_size
: 8;
725 cp
= buffer_ptr(&outgoing_packet
);
729 fprintf(stderr
, "plain: ");
730 buffer_dump(&outgoing_packet
);
733 if (comp
&& comp
->enabled
) {
734 len
= buffer_len(&outgoing_packet
);
735 /* skip header, compress only payload */
736 buffer_consume(&outgoing_packet
, 5);
737 buffer_clear(&compression_buffer
);
738 buffer_compress(&outgoing_packet
, &compression_buffer
);
739 buffer_clear(&outgoing_packet
);
740 buffer_append(&outgoing_packet
, "\0\0\0\0\0", 5);
741 buffer_append(&outgoing_packet
, buffer_ptr(&compression_buffer
),
742 buffer_len(&compression_buffer
));
743 DBG(debug("compression: raw %d compressed %d", len
,
744 buffer_len(&outgoing_packet
)));
747 /* sizeof (packet_len + pad_len + payload) */
748 len
= buffer_len(&outgoing_packet
);
751 * calc size of padding, alloc space, get random data,
752 * minimum padding is 4 bytes
754 padlen
= block_size
- (len
% block_size
);
756 padlen
+= block_size
;
758 /* will wrap if extra_pad+padlen > 255 */
759 extra_pad
= roundup(extra_pad
, block_size
);
760 pad
= extra_pad
- ((len
+ padlen
) % extra_pad
);
761 debug3("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
762 pad
, len
, padlen
, extra_pad
);
766 cp
= buffer_append_space(&outgoing_packet
, padlen
);
767 if (enc
&& !send_context
.plaintext
) {
769 for (i
= 0; i
< padlen
; i
++) {
777 memset(cp
, 0, padlen
);
779 /* packet_length includes payload, padding and padding length field */
780 packet_length
= buffer_len(&outgoing_packet
) - 4;
781 cp
= buffer_ptr(&outgoing_packet
);
782 put_u32(cp
, packet_length
);
784 DBG(debug("send: len %d (includes padlen %d)", packet_length
+4, padlen
));
786 /* compute MAC over seqnr and packet(length fields, payload, padding) */
787 if (mac
&& mac
->enabled
) {
788 macbuf
= mac_compute(mac
, p_send
.seqnr
,
789 buffer_ptr(&outgoing_packet
),
790 buffer_len(&outgoing_packet
));
791 DBG(debug("done calc MAC out #%d", p_send
.seqnr
));
793 /* encrypt packet and append to output buffer. */
794 cp
= buffer_append_space(&output
, buffer_len(&outgoing_packet
));
795 cipher_crypt(&send_context
, cp
, buffer_ptr(&outgoing_packet
),
796 buffer_len(&outgoing_packet
));
797 /* append unencrypted MAC */
798 if (mac
&& mac
->enabled
)
799 buffer_append(&output
, macbuf
, mac
->mac_len
);
801 fprintf(stderr
, "encrypted: ");
802 buffer_dump(&output
);
804 /* increment sequence number for outgoing packets */
805 if (++p_send
.seqnr
== 0)
806 logit("outgoing seqnr wraps around");
807 if (++p_send
.packets
== 0)
808 if (!(datafellows
& SSH_BUG_NOREKEY
))
809 fatal("XXX too many packets with same key");
810 p_send
.blocks
+= (packet_length
+ 4) / block_size
;
811 buffer_clear(&outgoing_packet
);
813 if (type
== SSH2_MSG_NEWKEYS
)
814 set_newkeys(MODE_OUT
);
815 else if (type
== SSH2_MSG_USERAUTH_SUCCESS
&& server_side
)
816 packet_enable_delayed_compress();
822 static int rekeying
= 0;
826 cp
= buffer_ptr(&outgoing_packet
);
829 /* during rekeying we can only send key exchange messages */
831 if (!((type
>= SSH2_MSG_TRANSPORT_MIN
) &&
832 (type
<= SSH2_MSG_TRANSPORT_MAX
))) {
833 debug("enqueue packet: %u", type
);
834 p
= xmalloc(sizeof(*p
));
836 memcpy(&p
->payload
, &outgoing_packet
, sizeof(Buffer
));
837 buffer_init(&outgoing_packet
);
838 TAILQ_INSERT_TAIL(&outgoing
, p
, next
);
843 /* rekeying starts with sending KEXINIT */
844 if (type
== SSH2_MSG_KEXINIT
)
847 packet_send2_wrapped();
849 /* after a NEWKEYS message we can send the complete queue */
850 if (type
== SSH2_MSG_NEWKEYS
) {
852 while ((p
= TAILQ_FIRST(&outgoing
))) {
854 debug("dequeue packet: %u", type
);
855 buffer_free(&outgoing_packet
);
856 memcpy(&outgoing_packet
, &p
->payload
,
858 TAILQ_REMOVE(&outgoing
, p
, next
);
860 packet_send2_wrapped();
872 DBG(debug("packet_send done"));
876 * Waits until a packet has been received, and returns its type. Note that
877 * no other data is processed until this returns, so this function should not
878 * be used during the interactive session.
882 packet_read_seqnr(u_int32_t
*seqnr_p
)
887 DBG(debug("packet_read()"));
889 setp
= (fd_set
*)xcalloc(howmany(connection_in
+1, NFDBITS
),
892 /* Since we are blocking, ensure that all written packets have been sent. */
895 /* Stay in the loop until we have received a complete packet. */
897 /* Try to read a packet from the buffer. */
898 type
= packet_read_poll_seqnr(seqnr_p
);
900 type
== SSH_SMSG_SUCCESS
901 || type
== SSH_SMSG_FAILURE
902 || type
== SSH_CMSG_EOF
903 || type
== SSH_CMSG_EXIT_CONFIRMATION
))
905 /* If we got a packet, return it. */
906 if (type
!= SSH_MSG_NONE
) {
911 * Otherwise, wait for some data to arrive, add it to the
912 * buffer, and try again.
914 memset(setp
, 0, howmany(connection_in
+ 1, NFDBITS
) *
916 FD_SET(connection_in
, setp
);
918 /* Wait for some data to arrive. */
919 while (select(connection_in
+ 1, setp
, NULL
, NULL
, NULL
) == -1 &&
920 (errno
== EAGAIN
|| errno
== EINTR
))
923 /* Read data from the socket. */
924 len
= read(connection_in
, buf
, sizeof(buf
));
926 logit("Connection closed by %.200s", get_remote_ipaddr());
930 fatal("Read from socket failed: %.100s", strerror(errno
));
931 /* Append it to the buffer. */
932 packet_process_incoming(buf
, len
);
940 return packet_read_seqnr(NULL
);
944 * Waits until a packet has been received, verifies that its type matches
945 * that given, and gives a fatal error and exits if there is a mismatch.
949 packet_read_expect(int expected_type
)
953 type
= packet_read();
954 if (type
!= expected_type
)
955 packet_disconnect("Protocol error: expected packet type %d, got %d",
956 expected_type
, type
);
959 /* Checks if a full packet is available in the data received so far via
960 * packet_process_incoming. If so, reads the packet; otherwise returns
961 * SSH_MSG_NONE. This does not wait for data from the connection.
963 * SSH_MSG_DISCONNECT is handled specially here. Also,
964 * SSH_MSG_IGNORE messages are skipped by this function and are never returned
969 packet_read_poll1(void)
971 u_int len
, padded_len
;
973 u_int checksum
, stored_checksum
;
975 /* Check if input size is less than minimum packet size. */
976 if (buffer_len(&input
) < 4 + 8)
978 /* Get length of incoming packet. */
979 cp
= buffer_ptr(&input
);
981 if (len
< 1 + 2 + 2 || len
> 256 * 1024)
982 packet_disconnect("Bad packet length %u.", len
);
983 padded_len
= (len
+ 8) & ~7;
985 /* Check if the packet has been entirely received. */
986 if (buffer_len(&input
) < 4 + padded_len
)
989 /* The entire packet is in buffer. */
991 /* Consume packet length. */
992 buffer_consume(&input
, 4);
995 * Cryptographic attack detector for ssh
996 * (C)1998 CORE-SDI, Buenos Aires Argentina
997 * Ariel Futoransky(futo@core-sdi.com)
999 if (!receive_context
.plaintext
&&
1000 detect_attack(buffer_ptr(&input
), padded_len
) == DEATTACK_DETECTED
)
1001 packet_disconnect("crc32 compensation attack: network attack detected");
1003 /* Decrypt data to incoming_packet. */
1004 buffer_clear(&incoming_packet
);
1005 cp
= buffer_append_space(&incoming_packet
, padded_len
);
1006 cipher_crypt(&receive_context
, cp
, buffer_ptr(&input
), padded_len
);
1008 buffer_consume(&input
, padded_len
);
1011 fprintf(stderr
, "read_poll plain: ");
1012 buffer_dump(&incoming_packet
);
1015 /* Compute packet checksum. */
1016 checksum
= ssh_crc32(buffer_ptr(&incoming_packet
),
1017 buffer_len(&incoming_packet
) - 4);
1020 buffer_consume(&incoming_packet
, 8 - len
% 8);
1022 /* Test check bytes. */
1023 if (len
!= buffer_len(&incoming_packet
))
1024 packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
1025 len
, buffer_len(&incoming_packet
));
1027 cp
= (u_char
*)buffer_ptr(&incoming_packet
) + len
- 4;
1028 stored_checksum
= get_u32(cp
);
1029 if (checksum
!= stored_checksum
)
1030 packet_disconnect("Corrupted check bytes on input.");
1031 buffer_consume_end(&incoming_packet
, 4);
1033 if (packet_compression
) {
1034 buffer_clear(&compression_buffer
);
1035 buffer_uncompress(&incoming_packet
, &compression_buffer
);
1036 buffer_clear(&incoming_packet
);
1037 buffer_append(&incoming_packet
, buffer_ptr(&compression_buffer
),
1038 buffer_len(&compression_buffer
));
1040 type
= buffer_get_char(&incoming_packet
);
1041 if (type
< SSH_MSG_MIN
|| type
> SSH_MSG_MAX
)
1042 packet_disconnect("Invalid ssh1 packet type: %d", type
);
1047 packet_read_poll2(u_int32_t
*seqnr_p
)
1049 static u_int packet_length
= 0;
1051 u_char
*macbuf
, *cp
, type
;
1052 u_int maclen
, block_size
;
1057 if (newkeys
[MODE_IN
] != NULL
) {
1058 enc
= &newkeys
[MODE_IN
]->enc
;
1059 mac
= &newkeys
[MODE_IN
]->mac
;
1060 comp
= &newkeys
[MODE_IN
]->comp
;
1062 maclen
= mac
&& mac
->enabled
? mac
->mac_len
: 0;
1063 block_size
= enc
? enc
->block_size
: 8;
1065 if (packet_length
== 0) {
1067 * check if input size is less than the cipher block size,
1068 * decrypt first block and extract length of incoming packet
1070 if (buffer_len(&input
) < block_size
)
1071 return SSH_MSG_NONE
;
1072 buffer_clear(&incoming_packet
);
1073 cp
= buffer_append_space(&incoming_packet
, block_size
);
1074 cipher_crypt(&receive_context
, cp
, buffer_ptr(&input
),
1076 cp
= buffer_ptr(&incoming_packet
);
1077 packet_length
= get_u32(cp
);
1078 if (packet_length
< 1 + 4 || packet_length
> 256 * 1024) {
1080 buffer_dump(&incoming_packet
);
1082 packet_disconnect("Bad packet length %u.", packet_length
);
1084 DBG(debug("input: packet len %u", packet_length
+4));
1085 buffer_consume(&input
, block_size
);
1087 /* we have a partial packet of block_size bytes */
1088 need
= 4 + packet_length
- block_size
;
1089 DBG(debug("partial packet %d, need %d, maclen %d", block_size
,
1091 if (need
% block_size
!= 0)
1092 fatal("padding error: need %d block %d mod %d",
1093 need
, block_size
, need
% block_size
);
1095 * check if the entire packet has been received and
1096 * decrypt into incoming_packet
1098 if (buffer_len(&input
) < need
+ maclen
)
1099 return SSH_MSG_NONE
;
1101 fprintf(stderr
, "read_poll enc/full: ");
1102 buffer_dump(&input
);
1104 cp
= buffer_append_space(&incoming_packet
, need
);
1105 cipher_crypt(&receive_context
, cp
, buffer_ptr(&input
), need
);
1106 buffer_consume(&input
, need
);
1108 * compute MAC over seqnr and packet,
1109 * increment sequence number for incoming packet
1111 if (mac
&& mac
->enabled
) {
1112 macbuf
= mac_compute(mac
, p_read
.seqnr
,
1113 buffer_ptr(&incoming_packet
),
1114 buffer_len(&incoming_packet
));
1115 if (memcmp(macbuf
, buffer_ptr(&input
), mac
->mac_len
) != 0)
1116 packet_disconnect("Corrupted MAC on input.");
1117 DBG(debug("MAC #%d ok", p_read
.seqnr
));
1118 buffer_consume(&input
, mac
->mac_len
);
1120 if (seqnr_p
!= NULL
)
1121 *seqnr_p
= p_read
.seqnr
;
1122 if (++p_read
.seqnr
== 0)
1123 logit("incoming seqnr wraps around");
1124 if (++p_read
.packets
== 0)
1125 if (!(datafellows
& SSH_BUG_NOREKEY
))
1126 fatal("XXX too many packets with same key");
1127 p_read
.blocks
+= (packet_length
+ 4) / block_size
;
1130 cp
= buffer_ptr(&incoming_packet
);
1132 DBG(debug("input: padlen %d", padlen
));
1134 packet_disconnect("Corrupted padlen %d on input.", padlen
);
1136 /* skip packet size + padlen, discard padding */
1137 buffer_consume(&incoming_packet
, 4 + 1);
1138 buffer_consume_end(&incoming_packet
, padlen
);
1140 DBG(debug("input: len before de-compress %d", buffer_len(&incoming_packet
)));
1141 if (comp
&& comp
->enabled
) {
1142 buffer_clear(&compression_buffer
);
1143 buffer_uncompress(&incoming_packet
, &compression_buffer
);
1144 buffer_clear(&incoming_packet
);
1145 buffer_append(&incoming_packet
, buffer_ptr(&compression_buffer
),
1146 buffer_len(&compression_buffer
));
1147 DBG(debug("input: len after de-compress %d",
1148 buffer_len(&incoming_packet
)));
1151 * get packet type, implies consume.
1152 * return length of payload (without type field)
1154 type
= buffer_get_char(&incoming_packet
);
1155 if (type
< SSH2_MSG_MIN
|| type
>= SSH2_MSG_LOCAL_MIN
)
1156 packet_disconnect("Invalid ssh2 packet type: %d", type
);
1157 if (type
== SSH2_MSG_NEWKEYS
)
1158 set_newkeys(MODE_IN
);
1159 else if (type
== SSH2_MSG_USERAUTH_SUCCESS
&& !server_side
)
1160 packet_enable_delayed_compress();
1162 fprintf(stderr
, "read/plain[%d]:\r\n", type
);
1163 buffer_dump(&incoming_packet
);
1165 /* reset for next packet */
1171 packet_read_poll_seqnr(u_int32_t
*seqnr_p
)
1173 u_int reason
, seqnr
;
1179 type
= packet_read_poll2(seqnr_p
);
1181 DBG(debug("received packet type %d", type
));
1183 case SSH2_MSG_IGNORE
:
1185 case SSH2_MSG_DEBUG
:
1187 msg
= packet_get_string(NULL
);
1188 debug("Remote: %.900s", msg
);
1190 msg
= packet_get_string(NULL
);
1193 case SSH2_MSG_DISCONNECT
:
1194 reason
= packet_get_int();
1195 msg
= packet_get_string(NULL
);
1196 logit("Received disconnect from %s: %u: %.400s",
1197 get_remote_ipaddr(), reason
, msg
);
1201 case SSH2_MSG_UNIMPLEMENTED
:
1202 seqnr
= packet_get_int();
1203 debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1210 type
= packet_read_poll1();
1212 case SSH_MSG_IGNORE
:
1215 msg
= packet_get_string(NULL
);
1216 debug("Remote: %.900s", msg
);
1219 case SSH_MSG_DISCONNECT
:
1220 msg
= packet_get_string(NULL
);
1221 logit("Received disconnect from %s: %.400s",
1222 get_remote_ipaddr(), msg
);
1228 DBG(debug("received packet type %d", type
));
1236 packet_read_poll(void)
1238 return packet_read_poll_seqnr(NULL
);
1242 * Buffers the given amount of input characters. This is intended to be used
1243 * together with packet_read_poll.
1247 packet_process_incoming(const char *buf
, u_int len
)
1249 buffer_append(&input
, buf
, len
);
1252 /* Returns a character from the packet. */
1255 packet_get_char(void)
1259 buffer_get(&incoming_packet
, &ch
, 1);
1263 /* Returns an integer from the packet data. */
1266 packet_get_int(void)
1268 return buffer_get_int(&incoming_packet
);
1272 * Returns an arbitrary precision integer from the packet data. The integer
1273 * must have been initialized before this call.
1277 packet_get_bignum(BIGNUM
* value
)
1279 buffer_get_bignum(&incoming_packet
, value
);
1283 packet_get_bignum2(BIGNUM
* value
)
1285 buffer_get_bignum2(&incoming_packet
, value
);
1289 packet_get_raw(u_int
*length_ptr
)
1291 u_int bytes
= buffer_len(&incoming_packet
);
1293 if (length_ptr
!= NULL
)
1294 *length_ptr
= bytes
;
1295 return buffer_ptr(&incoming_packet
);
1299 packet_remaining(void)
1301 return buffer_len(&incoming_packet
);
1305 * Returns a string from the packet data. The string is allocated using
1306 * xmalloc; it is the responsibility of the calling program to free it when
1307 * no longer needed. The length_ptr argument may be NULL, or point to an
1308 * integer into which the length of the string is stored.
1312 packet_get_string(u_int
*length_ptr
)
1314 return buffer_get_string(&incoming_packet
, length_ptr
);
1318 * Sends a diagnostic message from the server to the client. This message
1319 * can be sent at any time (but not while constructing another message). The
1320 * message is printed immediately, but only if the client is being executed
1321 * in verbose mode. These messages are primarily intended to ease debugging
1322 * authentication problems. The length of the formatted message must not
1323 * exceed 1024 bytes. This will automatically call packet_write_wait.
1327 packet_send_debug(const char *fmt
,...)
1332 if (compat20
&& (datafellows
& SSH_BUG_DEBUG
))
1335 va_start(args
, fmt
);
1336 vsnprintf(buf
, sizeof(buf
), fmt
, args
);
1340 packet_start(SSH2_MSG_DEBUG
);
1341 packet_put_char(0); /* bool: always display */
1342 packet_put_cstring(buf
);
1343 packet_put_cstring("");
1345 packet_start(SSH_MSG_DEBUG
);
1346 packet_put_cstring(buf
);
1349 packet_write_wait();
1353 * Logs the error plus constructs and sends a disconnect packet, closes the
1354 * connection, and exits. This function never returns. The error message
1355 * should not contain a newline. The length of the formatted message must
1356 * not exceed 1024 bytes.
1360 packet_disconnect(const char *fmt
,...)
1364 static int disconnecting
= 0;
1366 if (disconnecting
) /* Guard against recursive invocations. */
1367 fatal("packet_disconnect called recursively.");
1371 * Format the message. Note that the caller must make sure the
1372 * message is of limited size.
1374 va_start(args
, fmt
);
1375 vsnprintf(buf
, sizeof(buf
), fmt
, args
);
1378 /* Display the error locally */
1379 logit("Disconnecting: %.100s", buf
);
1381 /* Send the disconnect message to the other side, and wait for it to get sent. */
1383 packet_start(SSH2_MSG_DISCONNECT
);
1384 packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR
);
1385 packet_put_cstring(buf
);
1386 packet_put_cstring("");
1388 packet_start(SSH_MSG_DISCONNECT
);
1389 packet_put_cstring(buf
);
1392 packet_write_wait();
1394 /* Stop listening for connections. */
1395 channel_close_all();
1397 /* Close the connection. */
1402 /* Checks if there is any buffered output, and tries to write some of the output. */
1405 packet_write_poll(void)
1407 int len
= buffer_len(&output
);
1410 len
= write(connection_out
, buffer_ptr(&output
), len
);
1412 if (errno
== EAGAIN
)
1415 fatal("Write failed: %.100s", strerror(errno
));
1417 buffer_consume(&output
, len
);
1422 * Calls packet_write_poll repeatedly until all pending output data has been
1427 packet_write_wait(void)
1431 setp
= (fd_set
*)xcalloc(howmany(connection_out
+ 1, NFDBITS
),
1433 packet_write_poll();
1434 while (packet_have_data_to_write()) {
1435 memset(setp
, 0, howmany(connection_out
+ 1, NFDBITS
) *
1437 FD_SET(connection_out
, setp
);
1438 while (select(connection_out
+ 1, NULL
, setp
, NULL
, NULL
) == -1 &&
1439 (errno
== EAGAIN
|| errno
== EINTR
))
1441 packet_write_poll();
1446 /* Returns true if there is buffered data to write to the connection. */
1449 packet_have_data_to_write(void)
1451 return buffer_len(&output
) != 0;
1454 /* Returns true if there is not too much data to write to the connection. */
1457 packet_not_very_much_data_to_write(void)
1459 if (interactive_mode
)
1460 return buffer_len(&output
) < 16384;
1462 return buffer_len(&output
) < 128 * 1024;
1467 packet_set_tos(int interactive
)
1469 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1470 int tos
= interactive
? IPTOS_LOWDELAY
: IPTOS_THROUGHPUT
;
1472 if (!packet_connection_is_on_socket() ||
1473 !packet_connection_is_ipv4())
1475 if (setsockopt(connection_in
, IPPROTO_IP
, IP_TOS
, &tos
,
1477 error("setsockopt IP_TOS %d: %.100s:",
1478 tos
, strerror(errno
));
1482 /* Informs that the current session is interactive. Sets IP flags for that. */
1485 packet_set_interactive(int interactive
)
1487 static int called
= 0;
1493 /* Record that we are in interactive mode. */
1494 interactive_mode
= interactive
;
1496 /* Only set socket options if using a socket. */
1497 if (!packet_connection_is_on_socket())
1499 set_nodelay(connection_in
);
1500 packet_set_tos(interactive
);
1503 /* Returns true if the current connection is interactive. */
1506 packet_is_interactive(void)
1508 return interactive_mode
;
1512 packet_set_maxsize(u_int s
)
1514 static int called
= 0;
1517 logit("packet_set_maxsize: called twice: old %d new %d",
1518 max_packet_size
, s
);
1521 if (s
< 4 * 1024 || s
> 1024 * 1024) {
1522 logit("packet_set_maxsize: bad size %d", s
);
1526 debug("packet_set_maxsize: setting to %d", s
);
1527 max_packet_size
= s
;
1531 /* roundup current message to pad bytes */
1533 packet_add_padding(u_char pad
)
1539 * 9.2. Ignored Data Message
1541 * byte SSH_MSG_IGNORE
1544 * All implementations MUST understand (and ignore) this message at any
1545 * time (after receiving the protocol version). No implementation is
1546 * required to send them. This message can be used as an additional
1547 * protection measure against advanced traffic analysis techniques.
1550 packet_send_ignore(int nbytes
)
1555 packet_start(compat20
? SSH2_MSG_IGNORE
: SSH_MSG_IGNORE
);
1556 packet_put_int(nbytes
);
1557 for (i
= 0; i
< nbytes
; i
++) {
1560 packet_put_char((u_char
)rnd
& 0xff);
1565 #define MAX_PACKETS (1U<<31)
1567 packet_need_rekeying(void)
1569 if (datafellows
& SSH_BUG_NOREKEY
)
1572 (p_send
.packets
> MAX_PACKETS
) ||
1573 (p_read
.packets
> MAX_PACKETS
) ||
1574 (max_blocks_out
&& (p_send
.blocks
> max_blocks_out
)) ||
1575 (max_blocks_in
&& (p_read
.blocks
> max_blocks_in
));
1579 packet_set_rekey_limit(u_int32_t bytes
)
1581 rekey_limit
= bytes
;
1585 packet_set_server(void)
1591 packet_set_authenticated(void)
1593 after_authentication
= 1;