1 /* $OpenBSD: packet.c,v 1.160 2009/02/13 11:50:21 markus 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>
87 #define PACKET_MAX_SIZE (256 * 1024)
90 * This variable contains the file descriptors used for communicating with
91 * the other side. connection_in is used for reading; connection_out for
92 * writing. These can be the same descriptor, in which case it is assumed to
95 static int connection_in
= -1;
96 static int connection_out
= -1;
98 /* Protocol flags for the remote side. */
99 static u_int remote_protocol_flags
= 0;
101 /* Encryption context for receiving data. This is only used for decryption. */
102 static CipherContext receive_context
;
104 /* Encryption context for sending data. This is only used for encryption. */
105 static CipherContext send_context
;
107 /* Buffer for raw input data from the socket. */
110 /* Buffer for raw output data going to the socket. */
113 /* Buffer for the partial outgoing packet being constructed. */
114 static Buffer outgoing_packet
;
116 /* Buffer for the incoming packet currently being processed. */
117 static Buffer incoming_packet
;
119 /* Scratch buffer for packet compression/decompression. */
120 static Buffer compression_buffer
;
121 static int compression_buffer_ready
= 0;
123 /* Flag indicating whether packet compression/decompression is enabled. */
124 static int packet_compression
= 0;
126 /* default maximum packet size */
127 u_int max_packet_size
= 32768;
129 /* Flag indicating whether this module has been initialized. */
130 static int initialized
= 0;
132 /* Set to true if the connection is interactive. */
133 static int interactive_mode
= 0;
135 /* Set to true if we are the server side. */
136 static int server_side
= 0;
138 /* Set to true if we are authenticated. */
139 static int after_authentication
= 0;
141 int keep_alive_timeouts
= 0;
143 /* Set to the maximum time that we will wait to send or receive a packet */
144 static int packet_timeout_ms
= -1;
146 /* Session key information for Encryption and MAC */
147 Newkeys
*newkeys
[MODE_MAX
];
148 static struct packet_state
{
155 static u_int64_t max_blocks_in
, max_blocks_out
;
156 static u_int32_t rekey_limit
;
158 /* Session key for protocol v1 */
159 static u_char ssh1_key
[SSH_SESSION_KEY_LENGTH
];
160 static u_int ssh1_keylen
;
162 /* roundup current message to extra_pad bytes */
163 static u_char extra_pad
= 0;
165 /* XXX discard incoming data after MAC error */
166 static u_int packet_discard
= 0;
167 static Mac
*packet_discard_mac
= NULL
;
170 TAILQ_ENTRY(packet
) next
;
174 TAILQ_HEAD(, packet
) outgoing
;
177 * Sets the descriptors used for communication. Disables encryption until
178 * packet_set_encryption_key is called.
181 packet_set_connection(int fd_in
, int fd_out
)
183 Cipher
*none
= cipher_by_name("none");
186 fatal("packet_set_connection: cannot load cipher 'none'");
187 connection_in
= fd_in
;
188 connection_out
= fd_out
;
189 cipher_init(&send_context
, none
, (const u_char
*)"",
190 0, NULL
, 0, CIPHER_ENCRYPT
);
191 cipher_init(&receive_context
, none
, (const u_char
*)"",
192 0, NULL
, 0, CIPHER_DECRYPT
);
193 newkeys
[MODE_IN
] = newkeys
[MODE_OUT
] = NULL
;
197 buffer_init(&output
);
198 buffer_init(&outgoing_packet
);
199 buffer_init(&incoming_packet
);
200 TAILQ_INIT(&outgoing
);
201 p_send
.packets
= p_read
.packets
= 0;
206 packet_set_timeout(int timeout
, int count
)
208 if (timeout
== 0 || count
== 0) {
209 packet_timeout_ms
= -1;
212 if ((INT_MAX
/ 1000) / count
< timeout
)
213 packet_timeout_ms
= INT_MAX
;
215 packet_timeout_ms
= timeout
* count
* 1000;
219 packet_stop_discard(void)
221 if (packet_discard_mac
) {
224 memset(buf
, 'a', sizeof(buf
));
225 while (buffer_len(&incoming_packet
) < PACKET_MAX_SIZE
)
226 buffer_append(&incoming_packet
, buf
, sizeof(buf
));
227 (void) mac_compute(packet_discard_mac
,
229 buffer_ptr(&incoming_packet
),
232 logit("Finished discarding for %.200s", get_remote_ipaddr());
237 packet_start_discard(Enc
*enc
, Mac
*mac
, u_int packet_length
, u_int discard
)
239 if (enc
== NULL
|| !cipher_is_cbc(enc
->cipher
))
240 packet_disconnect("Packet corrupt");
241 if (packet_length
!= PACKET_MAX_SIZE
&& mac
&& mac
->enabled
)
242 packet_discard_mac
= mac
;
243 if (buffer_len(&input
) >= discard
)
244 packet_stop_discard();
245 packet_discard
= discard
- buffer_len(&input
);
248 /* Returns 1 if remote host is connected via socket, 0 if not. */
251 packet_connection_is_on_socket(void)
253 struct sockaddr_storage from
, to
;
254 socklen_t fromlen
, tolen
;
256 /* filedescriptors in and out are the same, so it's a socket */
257 if (connection_in
== connection_out
)
259 fromlen
= sizeof(from
);
260 memset(&from
, 0, sizeof(from
));
261 if (getpeername(connection_in
, (struct sockaddr
*)&from
, &fromlen
) < 0)
264 memset(&to
, 0, sizeof(to
));
265 if (getpeername(connection_out
, (struct sockaddr
*)&to
, &tolen
) < 0)
267 if (fromlen
!= tolen
|| memcmp(&from
, &to
, fromlen
) != 0)
269 if (from
.ss_family
!= AF_INET
&& from
.ss_family
!= AF_INET6
)
275 * Exports an IV from the CipherContext required to export the key
276 * state back from the unprivileged child to the privileged parent
281 packet_get_keyiv(int mode
, u_char
*iv
, u_int len
)
285 if (mode
== MODE_OUT
)
288 cc
= &receive_context
;
290 cipher_get_keyiv(cc
, iv
, len
);
294 packet_get_keycontext(int mode
, u_char
*dat
)
298 if (mode
== MODE_OUT
)
301 cc
= &receive_context
;
303 return (cipher_get_keycontext(cc
, dat
));
307 packet_set_keycontext(int mode
, u_char
*dat
)
311 if (mode
== MODE_OUT
)
314 cc
= &receive_context
;
316 cipher_set_keycontext(cc
, dat
);
320 packet_get_keyiv_len(int mode
)
324 if (mode
== MODE_OUT
)
327 cc
= &receive_context
;
329 return (cipher_get_keyiv_len(cc
));
333 packet_set_iv(int mode
, u_char
*dat
)
337 if (mode
== MODE_OUT
)
340 cc
= &receive_context
;
342 cipher_set_keyiv(cc
, dat
);
346 packet_get_ssh1_cipher(void)
348 return (cipher_get_number(receive_context
.cipher
));
352 packet_get_state(int mode
, u_int32_t
*seqnr
, u_int64_t
*blocks
, u_int32_t
*packets
,
355 struct packet_state
*state
;
357 state
= (mode
== MODE_IN
) ? &p_read
: &p_send
;
359 *seqnr
= state
->seqnr
;
361 *blocks
= state
->blocks
;
363 *packets
= state
->packets
;
365 *bytes
= state
->bytes
;
369 packet_set_state(int mode
, u_int32_t seqnr
, u_int64_t blocks
, u_int32_t packets
,
372 struct packet_state
*state
;
374 state
= (mode
== MODE_IN
) ? &p_read
: &p_send
;
375 state
->seqnr
= seqnr
;
376 state
->blocks
= blocks
;
377 state
->packets
= packets
;
378 state
->bytes
= bytes
;
381 /* returns 1 if connection is via ipv4 */
384 packet_connection_is_ipv4(void)
386 struct sockaddr_storage to
;
387 socklen_t tolen
= sizeof(to
);
389 memset(&to
, 0, sizeof(to
));
390 if (getsockname(connection_out
, (struct sockaddr
*)&to
, &tolen
) < 0)
392 if (to
.ss_family
== AF_INET
)
395 if (to
.ss_family
== AF_INET6
&&
396 IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6
*)&to
)->sin6_addr
))
402 /* Sets the connection into non-blocking mode. */
405 packet_set_nonblocking(void)
407 /* Set the socket into non-blocking mode. */
408 set_nonblock(connection_in
);
410 if (connection_out
!= connection_in
)
411 set_nonblock(connection_out
);
414 /* Returns the socket used for reading. */
417 packet_get_connection_in(void)
419 return connection_in
;
422 /* Returns the descriptor used for writing. */
425 packet_get_connection_out(void)
427 return connection_out
;
430 /* Closes the connection and clears and frees internal data structures. */
438 if (connection_in
== connection_out
) {
439 shutdown(connection_out
, SHUT_RDWR
);
440 close(connection_out
);
442 close(connection_in
);
443 close(connection_out
);
446 buffer_free(&output
);
447 buffer_free(&outgoing_packet
);
448 buffer_free(&incoming_packet
);
449 if (compression_buffer_ready
) {
450 buffer_free(&compression_buffer
);
451 buffer_compress_uninit();
453 cipher_cleanup(&send_context
);
454 cipher_cleanup(&receive_context
);
457 /* Sets remote side protocol flags. */
460 packet_set_protocol_flags(u_int protocol_flags
)
462 remote_protocol_flags
= protocol_flags
;
465 /* Returns the remote protocol flags set earlier by the above function. */
468 packet_get_protocol_flags(void)
470 return remote_protocol_flags
;
474 * Starts packet compression from the next packet on in both directions.
475 * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
479 packet_init_compression(void)
481 if (compression_buffer_ready
== 1)
483 compression_buffer_ready
= 1;
484 buffer_init(&compression_buffer
);
488 packet_start_compression(int level
)
490 if (packet_compression
&& !compat20
)
491 fatal("Compression already enabled.");
492 packet_compression
= 1;
493 packet_init_compression();
494 buffer_compress_init_send(level
);
495 buffer_compress_init_recv();
499 * Causes any further packets to be encrypted using the given key. The same
500 * key is used for both sending and reception. However, both directions are
501 * encrypted independently of each other.
505 packet_set_encryption_key(const u_char
*key
, u_int keylen
,
508 Cipher
*cipher
= cipher_by_number(number
);
511 fatal("packet_set_encryption_key: unknown cipher number %d", number
);
513 fatal("packet_set_encryption_key: keylen too small: %d", keylen
);
514 if (keylen
> SSH_SESSION_KEY_LENGTH
)
515 fatal("packet_set_encryption_key: keylen too big: %d", keylen
);
516 memcpy(ssh1_key
, key
, keylen
);
517 ssh1_keylen
= keylen
;
518 cipher_init(&send_context
, cipher
, key
, keylen
, NULL
, 0, CIPHER_ENCRYPT
);
519 cipher_init(&receive_context
, cipher
, key
, keylen
, NULL
, 0, CIPHER_DECRYPT
);
523 packet_get_encryption_key(u_char
*key
)
526 return (ssh1_keylen
);
527 memcpy(key
, ssh1_key
, ssh1_keylen
);
528 return (ssh1_keylen
);
531 /* Start constructing a packet to send. */
533 packet_start(u_char type
)
538 DBG(debug("packet_start[%d]", type
));
539 len
= compat20
? 6 : 9;
540 memset(buf
, 0, len
- 1);
542 buffer_clear(&outgoing_packet
);
543 buffer_append(&outgoing_packet
, buf
, len
);
546 /* Append payload. */
548 packet_put_char(int value
)
552 buffer_append(&outgoing_packet
, &ch
, 1);
556 packet_put_int(u_int value
)
558 buffer_put_int(&outgoing_packet
, value
);
562 packet_put_string(const void *buf
, u_int len
)
564 buffer_put_string(&outgoing_packet
, buf
, len
);
568 packet_put_cstring(const char *str
)
570 buffer_put_cstring(&outgoing_packet
, str
);
574 packet_put_raw(const void *buf
, u_int len
)
576 buffer_append(&outgoing_packet
, buf
, len
);
580 packet_put_bignum(BIGNUM
* value
)
582 buffer_put_bignum(&outgoing_packet
, value
);
586 packet_put_bignum2(BIGNUM
* value
)
588 buffer_put_bignum2(&outgoing_packet
, value
);
592 * Finalizes and sends the packet. If the encryption key has been set,
593 * encrypts the packet before sending.
605 * If using packet compression, compress the payload of the outgoing
608 if (packet_compression
) {
609 buffer_clear(&compression_buffer
);
611 buffer_consume(&outgoing_packet
, 8);
613 buffer_append(&compression_buffer
, "\0\0\0\0\0\0\0\0", 8);
614 buffer_compress(&outgoing_packet
, &compression_buffer
);
615 buffer_clear(&outgoing_packet
);
616 buffer_append(&outgoing_packet
, buffer_ptr(&compression_buffer
),
617 buffer_len(&compression_buffer
));
619 /* Compute packet length without padding (add checksum, remove padding). */
620 len
= buffer_len(&outgoing_packet
) + 4 - 8;
622 /* Insert padding. Initialized to zero in packet_start1() */
623 padding
= 8 - len
% 8;
624 if (!send_context
.plaintext
) {
625 cp
= buffer_ptr(&outgoing_packet
);
626 for (i
= 0; i
< padding
; i
++) {
629 cp
[7 - i
] = rnd
& 0xff;
633 buffer_consume(&outgoing_packet
, 8 - padding
);
635 /* Add check bytes. */
636 checksum
= ssh_crc32(buffer_ptr(&outgoing_packet
),
637 buffer_len(&outgoing_packet
));
638 put_u32(buf
, checksum
);
639 buffer_append(&outgoing_packet
, buf
, 4);
642 fprintf(stderr
, "packet_send plain: ");
643 buffer_dump(&outgoing_packet
);
646 /* Append to output. */
648 buffer_append(&output
, buf
, 4);
649 cp
= buffer_append_space(&output
, buffer_len(&outgoing_packet
));
650 cipher_crypt(&send_context
, cp
, buffer_ptr(&outgoing_packet
),
651 buffer_len(&outgoing_packet
));
654 fprintf(stderr
, "encrypted: ");
655 buffer_dump(&output
);
658 p_send
.bytes
+= len
+ buffer_len(&outgoing_packet
);
659 buffer_clear(&outgoing_packet
);
662 * Note that the packet is now only buffered in output. It won't be
663 * actually sent until packet_write_wait or packet_write_poll is
669 set_newkeys(int mode
)
675 u_int64_t
*max_blocks
;
678 debug2("set_newkeys: mode %d", mode
);
680 if (mode
== MODE_OUT
) {
682 crypt_type
= CIPHER_ENCRYPT
;
683 p_send
.packets
= p_send
.blocks
= 0;
684 max_blocks
= &max_blocks_out
;
686 cc
= &receive_context
;
687 crypt_type
= CIPHER_DECRYPT
;
688 p_read
.packets
= p_read
.blocks
= 0;
689 max_blocks
= &max_blocks_in
;
691 if (newkeys
[mode
] != NULL
) {
692 debug("set_newkeys: rekeying");
694 enc
= &newkeys
[mode
]->enc
;
695 mac
= &newkeys
[mode
]->mac
;
696 comp
= &newkeys
[mode
]->comp
;
704 xfree(newkeys
[mode
]);
706 newkeys
[mode
] = kex_get_newkeys(mode
);
707 if (newkeys
[mode
] == NULL
)
708 fatal("newkeys: no keys for mode %d", mode
);
709 enc
= &newkeys
[mode
]->enc
;
710 mac
= &newkeys
[mode
]->mac
;
711 comp
= &newkeys
[mode
]->comp
;
712 if (mac_init(mac
) == 0)
714 DBG(debug("cipher_init_context: %d", mode
));
715 cipher_init(cc
, enc
->cipher
, enc
->key
, enc
->key_len
,
716 enc
->iv
, enc
->block_size
, crypt_type
);
717 /* Deleting the keys does not gain extra security */
718 /* memset(enc->iv, 0, enc->block_size);
719 memset(enc->key, 0, enc->key_len);
720 memset(mac->key, 0, mac->key_len); */
721 if ((comp
->type
== COMP_ZLIB
||
722 (comp
->type
== COMP_DELAYED
&& after_authentication
)) &&
723 comp
->enabled
== 0) {
724 packet_init_compression();
725 if (mode
== MODE_OUT
)
726 buffer_compress_init_send(6);
728 buffer_compress_init_recv();
732 * The 2^(blocksize*2) limit is too expensive for 3DES,
733 * blowfish, etc, so enforce a 1GB limit for small blocksizes.
735 if (enc
->block_size
>= 16)
736 *max_blocks
= (u_int64_t
)1 << (enc
->block_size
*2);
738 *max_blocks
= ((u_int64_t
)1 << 30) / enc
->block_size
;
740 *max_blocks
= MIN(*max_blocks
, rekey_limit
/ enc
->block_size
);
744 * Delayed compression for SSH2 is enabled after authentication:
745 * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
746 * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
749 packet_enable_delayed_compress(void)
755 * Remember that we are past the authentication step, so rekeying
756 * with COMP_DELAYED will turn on compression immediately.
758 after_authentication
= 1;
759 for (mode
= 0; mode
< MODE_MAX
; mode
++) {
760 /* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
761 if (newkeys
[mode
] == NULL
)
763 comp
= &newkeys
[mode
]->comp
;
764 if (comp
&& !comp
->enabled
&& comp
->type
== COMP_DELAYED
) {
765 packet_init_compression();
766 if (mode
== MODE_OUT
)
767 buffer_compress_init_send(6);
769 buffer_compress_init_recv();
776 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
779 packet_send2_wrapped(void)
781 u_char type
, *cp
, *macbuf
= NULL
;
783 u_int packet_length
= 0;
791 if (newkeys
[MODE_OUT
] != NULL
) {
792 enc
= &newkeys
[MODE_OUT
]->enc
;
793 mac
= &newkeys
[MODE_OUT
]->mac
;
794 comp
= &newkeys
[MODE_OUT
]->comp
;
796 block_size
= enc
? enc
->block_size
: 8;
798 cp
= buffer_ptr(&outgoing_packet
);
802 fprintf(stderr
, "plain: ");
803 buffer_dump(&outgoing_packet
);
806 if (comp
&& comp
->enabled
) {
807 len
= buffer_len(&outgoing_packet
);
808 /* skip header, compress only payload */
809 buffer_consume(&outgoing_packet
, 5);
810 buffer_clear(&compression_buffer
);
811 buffer_compress(&outgoing_packet
, &compression_buffer
);
812 buffer_clear(&outgoing_packet
);
813 buffer_append(&outgoing_packet
, "\0\0\0\0\0", 5);
814 buffer_append(&outgoing_packet
, buffer_ptr(&compression_buffer
),
815 buffer_len(&compression_buffer
));
816 DBG(debug("compression: raw %d compressed %d", len
,
817 buffer_len(&outgoing_packet
)));
820 /* sizeof (packet_len + pad_len + payload) */
821 len
= buffer_len(&outgoing_packet
);
824 * calc size of padding, alloc space, get random data,
825 * minimum padding is 4 bytes
827 padlen
= block_size
- (len
% block_size
);
829 padlen
+= block_size
;
831 /* will wrap if extra_pad+padlen > 255 */
832 extra_pad
= roundup(extra_pad
, block_size
);
833 pad
= extra_pad
- ((len
+ padlen
) % extra_pad
);
834 debug3("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
835 pad
, len
, padlen
, extra_pad
);
839 cp
= buffer_append_space(&outgoing_packet
, padlen
);
840 if (enc
&& !send_context
.plaintext
) {
842 for (i
= 0; i
< padlen
; i
++) {
850 memset(cp
, 0, padlen
);
852 /* packet_length includes payload, padding and padding length field */
853 packet_length
= buffer_len(&outgoing_packet
) - 4;
854 cp
= buffer_ptr(&outgoing_packet
);
855 put_u32(cp
, packet_length
);
857 DBG(debug("send: len %d (includes padlen %d)", packet_length
+4, padlen
));
859 /* compute MAC over seqnr and packet(length fields, payload, padding) */
860 if (mac
&& mac
->enabled
) {
861 macbuf
= mac_compute(mac
, p_send
.seqnr
,
862 buffer_ptr(&outgoing_packet
),
863 buffer_len(&outgoing_packet
));
864 DBG(debug("done calc MAC out #%d", p_send
.seqnr
));
866 /* encrypt packet and append to output buffer. */
867 cp
= buffer_append_space(&output
, buffer_len(&outgoing_packet
));
868 cipher_crypt(&send_context
, cp
, buffer_ptr(&outgoing_packet
),
869 buffer_len(&outgoing_packet
));
870 /* append unencrypted MAC */
871 if (mac
&& mac
->enabled
)
872 buffer_append(&output
, macbuf
, mac
->mac_len
);
874 fprintf(stderr
, "encrypted: ");
875 buffer_dump(&output
);
877 /* increment sequence number for outgoing packets */
878 if (++p_send
.seqnr
== 0)
879 logit("outgoing seqnr wraps around");
880 if (++p_send
.packets
== 0)
881 if (!(datafellows
& SSH_BUG_NOREKEY
))
882 fatal("XXX too many packets with same key");
883 p_send
.blocks
+= (packet_length
+ 4) / block_size
;
884 p_send
.bytes
+= packet_length
+ 4;
885 buffer_clear(&outgoing_packet
);
887 if (type
== SSH2_MSG_NEWKEYS
)
888 set_newkeys(MODE_OUT
);
889 else if (type
== SSH2_MSG_USERAUTH_SUCCESS
&& server_side
)
890 packet_enable_delayed_compress();
896 static int rekeying
= 0;
900 cp
= buffer_ptr(&outgoing_packet
);
903 /* during rekeying we can only send key exchange messages */
905 if (!((type
>= SSH2_MSG_TRANSPORT_MIN
) &&
906 (type
<= SSH2_MSG_TRANSPORT_MAX
))) {
907 debug("enqueue packet: %u", type
);
908 p
= xmalloc(sizeof(*p
));
910 memcpy(&p
->payload
, &outgoing_packet
, sizeof(Buffer
));
911 buffer_init(&outgoing_packet
);
912 TAILQ_INSERT_TAIL(&outgoing
, p
, next
);
917 /* rekeying starts with sending KEXINIT */
918 if (type
== SSH2_MSG_KEXINIT
)
921 packet_send2_wrapped();
923 /* after a NEWKEYS message we can send the complete queue */
924 if (type
== SSH2_MSG_NEWKEYS
) {
926 while ((p
= TAILQ_FIRST(&outgoing
))) {
928 debug("dequeue packet: %u", type
);
929 buffer_free(&outgoing_packet
);
930 memcpy(&outgoing_packet
, &p
->payload
,
932 TAILQ_REMOVE(&outgoing
, p
, next
);
934 packet_send2_wrapped();
946 DBG(debug("packet_send done"));
950 * Waits until a packet has been received, and returns its type. Note that
951 * no other data is processed until this returns, so this function should not
952 * be used during the interactive session.
956 packet_read_seqnr(u_int32_t
*seqnr_p
)
958 int type
, len
, ret
, ms_remain
;
961 struct timeval timeout
, start
, *timeoutp
= NULL
;
963 DBG(debug("packet_read()"));
965 setp
= (fd_set
*)xcalloc(howmany(connection_in
+1, NFDBITS
),
968 /* Since we are blocking, ensure that all written packets have been sent. */
971 /* Stay in the loop until we have received a complete packet. */
973 /* Try to read a packet from the buffer. */
974 type
= packet_read_poll_seqnr(seqnr_p
);
976 type
== SSH_SMSG_SUCCESS
977 || type
== SSH_SMSG_FAILURE
978 || type
== SSH_CMSG_EOF
979 || type
== SSH_CMSG_EXIT_CONFIRMATION
))
981 /* If we got a packet, return it. */
982 if (type
!= SSH_MSG_NONE
) {
987 * Otherwise, wait for some data to arrive, add it to the
988 * buffer, and try again.
990 memset(setp
, 0, howmany(connection_in
+ 1, NFDBITS
) *
992 FD_SET(connection_in
, setp
);
994 if (packet_timeout_ms
> 0) {
995 ms_remain
= packet_timeout_ms
;
998 /* Wait for some data to arrive. */
1000 if (packet_timeout_ms
!= -1) {
1001 ms_to_timeval(&timeout
, ms_remain
);
1002 gettimeofday(&start
, NULL
);
1004 if ((ret
= select(connection_in
+ 1, setp
, NULL
,
1005 NULL
, timeoutp
)) >= 0)
1007 if (errno
!= EAGAIN
&& errno
!= EINTR
&&
1008 errno
!= EWOULDBLOCK
)
1010 if (packet_timeout_ms
== -1)
1012 ms_subtract_diff(&start
, &ms_remain
);
1013 if (ms_remain
<= 0) {
1019 logit("Connection to %.200s timed out while "
1020 "waiting to read", get_remote_ipaddr());
1023 /* Read data from the socket. */
1024 len
= read(connection_in
, buf
, sizeof(buf
));
1026 logit("Connection closed by %.200s", get_remote_ipaddr());
1030 fatal("Read from socket failed: %.100s", strerror(errno
));
1031 /* Append it to the buffer. */
1032 packet_process_incoming(buf
, len
);
1040 return packet_read_seqnr(NULL
);
1044 * Waits until a packet has been received, verifies that its type matches
1045 * that given, and gives a fatal error and exits if there is a mismatch.
1049 packet_read_expect(int expected_type
)
1053 type
= packet_read();
1054 if (type
!= expected_type
)
1055 packet_disconnect("Protocol error: expected packet type %d, got %d",
1056 expected_type
, type
);
1059 /* Checks if a full packet is available in the data received so far via
1060 * packet_process_incoming. If so, reads the packet; otherwise returns
1061 * SSH_MSG_NONE. This does not wait for data from the connection.
1063 * SSH_MSG_DISCONNECT is handled specially here. Also,
1064 * SSH_MSG_IGNORE messages are skipped by this function and are never returned
1069 packet_read_poll1(void)
1071 u_int len
, padded_len
;
1073 u_int checksum
, stored_checksum
;
1075 /* Check if input size is less than minimum packet size. */
1076 if (buffer_len(&input
) < 4 + 8)
1077 return SSH_MSG_NONE
;
1078 /* Get length of incoming packet. */
1079 cp
= buffer_ptr(&input
);
1081 if (len
< 1 + 2 + 2 || len
> 256 * 1024)
1082 packet_disconnect("Bad packet length %u.", len
);
1083 padded_len
= (len
+ 8) & ~7;
1085 /* Check if the packet has been entirely received. */
1086 if (buffer_len(&input
) < 4 + padded_len
)
1087 return SSH_MSG_NONE
;
1089 /* The entire packet is in buffer. */
1091 /* Consume packet length. */
1092 buffer_consume(&input
, 4);
1095 * Cryptographic attack detector for ssh
1096 * (C)1998 CORE-SDI, Buenos Aires Argentina
1097 * Ariel Futoransky(futo@core-sdi.com)
1099 if (!receive_context
.plaintext
) {
1100 switch (detect_attack(buffer_ptr(&input
), padded_len
)) {
1101 case DEATTACK_DETECTED
:
1102 packet_disconnect("crc32 compensation attack: "
1103 "network attack detected");
1104 case DEATTACK_DOS_DETECTED
:
1105 packet_disconnect("deattack denial of "
1106 "service detected");
1110 /* Decrypt data to incoming_packet. */
1111 buffer_clear(&incoming_packet
);
1112 cp
= buffer_append_space(&incoming_packet
, padded_len
);
1113 cipher_crypt(&receive_context
, cp
, buffer_ptr(&input
), padded_len
);
1115 buffer_consume(&input
, padded_len
);
1118 fprintf(stderr
, "read_poll plain: ");
1119 buffer_dump(&incoming_packet
);
1122 /* Compute packet checksum. */
1123 checksum
= ssh_crc32(buffer_ptr(&incoming_packet
),
1124 buffer_len(&incoming_packet
) - 4);
1127 buffer_consume(&incoming_packet
, 8 - len
% 8);
1129 /* Test check bytes. */
1130 if (len
!= buffer_len(&incoming_packet
))
1131 packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
1132 len
, buffer_len(&incoming_packet
));
1134 cp
= (u_char
*)buffer_ptr(&incoming_packet
) + len
- 4;
1135 stored_checksum
= get_u32(cp
);
1136 if (checksum
!= stored_checksum
)
1137 packet_disconnect("Corrupted check bytes on input.");
1138 buffer_consume_end(&incoming_packet
, 4);
1140 if (packet_compression
) {
1141 buffer_clear(&compression_buffer
);
1142 buffer_uncompress(&incoming_packet
, &compression_buffer
);
1143 buffer_clear(&incoming_packet
);
1144 buffer_append(&incoming_packet
, buffer_ptr(&compression_buffer
),
1145 buffer_len(&compression_buffer
));
1148 p_read
.bytes
+= padded_len
+ 4;
1149 type
= buffer_get_char(&incoming_packet
);
1150 if (type
< SSH_MSG_MIN
|| type
> SSH_MSG_MAX
)
1151 packet_disconnect("Invalid ssh1 packet type: %d", type
);
1156 packet_read_poll2(u_int32_t
*seqnr_p
)
1158 static u_int packet_length
= 0;
1160 u_char
*macbuf
, *cp
, type
;
1161 u_int maclen
, block_size
;
1167 return SSH_MSG_NONE
;
1169 if (newkeys
[MODE_IN
] != NULL
) {
1170 enc
= &newkeys
[MODE_IN
]->enc
;
1171 mac
= &newkeys
[MODE_IN
]->mac
;
1172 comp
= &newkeys
[MODE_IN
]->comp
;
1174 maclen
= mac
&& mac
->enabled
? mac
->mac_len
: 0;
1175 block_size
= enc
? enc
->block_size
: 8;
1177 if (packet_length
== 0) {
1179 * check if input size is less than the cipher block size,
1180 * decrypt first block and extract length of incoming packet
1182 if (buffer_len(&input
) < block_size
)
1183 return SSH_MSG_NONE
;
1184 buffer_clear(&incoming_packet
);
1185 cp
= buffer_append_space(&incoming_packet
, block_size
);
1186 cipher_crypt(&receive_context
, cp
, buffer_ptr(&input
),
1188 cp
= buffer_ptr(&incoming_packet
);
1189 packet_length
= get_u32(cp
);
1190 if (packet_length
< 1 + 4 || packet_length
> PACKET_MAX_SIZE
) {
1192 buffer_dump(&incoming_packet
);
1194 logit("Bad packet length %u.", packet_length
);
1195 packet_start_discard(enc
, mac
, packet_length
,
1197 return SSH_MSG_NONE
;
1199 DBG(debug("input: packet len %u", packet_length
+4));
1200 buffer_consume(&input
, block_size
);
1202 /* we have a partial packet of block_size bytes */
1203 need
= 4 + packet_length
- block_size
;
1204 DBG(debug("partial packet %d, need %d, maclen %d", block_size
,
1206 if (need
% block_size
!= 0) {
1207 logit("padding error: need %d block %d mod %d",
1208 need
, block_size
, need
% block_size
);
1209 packet_start_discard(enc
, mac
, packet_length
,
1210 PACKET_MAX_SIZE
- block_size
);
1211 return SSH_MSG_NONE
;
1214 * check if the entire packet has been received and
1215 * decrypt into incoming_packet
1217 if (buffer_len(&input
) < need
+ maclen
)
1218 return SSH_MSG_NONE
;
1220 fprintf(stderr
, "read_poll enc/full: ");
1221 buffer_dump(&input
);
1223 cp
= buffer_append_space(&incoming_packet
, need
);
1224 cipher_crypt(&receive_context
, cp
, buffer_ptr(&input
), need
);
1225 buffer_consume(&input
, need
);
1227 * compute MAC over seqnr and packet,
1228 * increment sequence number for incoming packet
1230 if (mac
&& mac
->enabled
) {
1231 macbuf
= mac_compute(mac
, p_read
.seqnr
,
1232 buffer_ptr(&incoming_packet
),
1233 buffer_len(&incoming_packet
));
1234 if (memcmp(macbuf
, buffer_ptr(&input
), mac
->mac_len
) != 0) {
1235 logit("Corrupted MAC on input.");
1236 if (need
> PACKET_MAX_SIZE
)
1237 fatal("internal error need %d", need
);
1238 packet_start_discard(enc
, mac
, packet_length
,
1239 PACKET_MAX_SIZE
- need
);
1240 return SSH_MSG_NONE
;
1243 DBG(debug("MAC #%d ok", p_read
.seqnr
));
1244 buffer_consume(&input
, mac
->mac_len
);
1246 /* XXX now it's safe to use fatal/packet_disconnect */
1247 if (seqnr_p
!= NULL
)
1248 *seqnr_p
= p_read
.seqnr
;
1249 if (++p_read
.seqnr
== 0)
1250 logit("incoming seqnr wraps around");
1251 if (++p_read
.packets
== 0)
1252 if (!(datafellows
& SSH_BUG_NOREKEY
))
1253 fatal("XXX too many packets with same key");
1254 p_read
.blocks
+= (packet_length
+ 4) / block_size
;
1255 p_read
.bytes
+= packet_length
+ 4;
1258 cp
= buffer_ptr(&incoming_packet
);
1260 DBG(debug("input: padlen %d", padlen
));
1262 packet_disconnect("Corrupted padlen %d on input.", padlen
);
1264 /* skip packet size + padlen, discard padding */
1265 buffer_consume(&incoming_packet
, 4 + 1);
1266 buffer_consume_end(&incoming_packet
, padlen
);
1268 DBG(debug("input: len before de-compress %d", buffer_len(&incoming_packet
)));
1269 if (comp
&& comp
->enabled
) {
1270 buffer_clear(&compression_buffer
);
1271 buffer_uncompress(&incoming_packet
, &compression_buffer
);
1272 buffer_clear(&incoming_packet
);
1273 buffer_append(&incoming_packet
, buffer_ptr(&compression_buffer
),
1274 buffer_len(&compression_buffer
));
1275 DBG(debug("input: len after de-compress %d",
1276 buffer_len(&incoming_packet
)));
1279 * get packet type, implies consume.
1280 * return length of payload (without type field)
1282 type
= buffer_get_char(&incoming_packet
);
1283 if (type
< SSH2_MSG_MIN
|| type
>= SSH2_MSG_LOCAL_MIN
)
1284 packet_disconnect("Invalid ssh2 packet type: %d", type
);
1285 if (type
== SSH2_MSG_NEWKEYS
)
1286 set_newkeys(MODE_IN
);
1287 else if (type
== SSH2_MSG_USERAUTH_SUCCESS
&& !server_side
)
1288 packet_enable_delayed_compress();
1290 fprintf(stderr
, "read/plain[%d]:\r\n", type
);
1291 buffer_dump(&incoming_packet
);
1293 /* reset for next packet */
1299 packet_read_poll_seqnr(u_int32_t
*seqnr_p
)
1301 u_int reason
, seqnr
;
1307 type
= packet_read_poll2(seqnr_p
);
1309 keep_alive_timeouts
= 0;
1310 DBG(debug("received packet type %d", type
));
1313 case SSH2_MSG_IGNORE
:
1314 debug3("Received SSH2_MSG_IGNORE");
1316 case SSH2_MSG_DEBUG
:
1318 msg
= packet_get_string(NULL
);
1319 debug("Remote: %.900s", msg
);
1321 msg
= packet_get_string(NULL
);
1324 case SSH2_MSG_DISCONNECT
:
1325 reason
= packet_get_int();
1326 msg
= packet_get_string(NULL
);
1327 logit("Received disconnect from %s: %u: %.400s",
1328 get_remote_ipaddr(), reason
, msg
);
1332 case SSH2_MSG_UNIMPLEMENTED
:
1333 seqnr
= packet_get_int();
1334 debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1341 type
= packet_read_poll1();
1343 case SSH_MSG_IGNORE
:
1346 msg
= packet_get_string(NULL
);
1347 debug("Remote: %.900s", msg
);
1350 case SSH_MSG_DISCONNECT
:
1351 msg
= packet_get_string(NULL
);
1352 logit("Received disconnect from %s: %.400s",
1353 get_remote_ipaddr(), msg
);
1358 DBG(debug("received packet type %d", type
));
1366 packet_read_poll(void)
1368 return packet_read_poll_seqnr(NULL
);
1372 * Buffers the given amount of input characters. This is intended to be used
1373 * together with packet_read_poll.
1377 packet_process_incoming(const char *buf
, u_int len
)
1379 if (packet_discard
) {
1380 keep_alive_timeouts
= 0; /* ?? */
1381 if (len
>= packet_discard
)
1382 packet_stop_discard();
1383 packet_discard
-= len
;
1386 buffer_append(&input
, buf
, len
);
1389 /* Returns a character from the packet. */
1392 packet_get_char(void)
1396 buffer_get(&incoming_packet
, &ch
, 1);
1400 /* Returns an integer from the packet data. */
1403 packet_get_int(void)
1405 return buffer_get_int(&incoming_packet
);
1409 * Returns an arbitrary precision integer from the packet data. The integer
1410 * must have been initialized before this call.
1414 packet_get_bignum(BIGNUM
* value
)
1416 buffer_get_bignum(&incoming_packet
, value
);
1420 packet_get_bignum2(BIGNUM
* value
)
1422 buffer_get_bignum2(&incoming_packet
, value
);
1426 packet_get_raw(u_int
*length_ptr
)
1428 u_int bytes
= buffer_len(&incoming_packet
);
1430 if (length_ptr
!= NULL
)
1431 *length_ptr
= bytes
;
1432 return buffer_ptr(&incoming_packet
);
1436 packet_remaining(void)
1438 return buffer_len(&incoming_packet
);
1442 * Returns a string from the packet data. The string is allocated using
1443 * xmalloc; it is the responsibility of the calling program to free it when
1444 * no longer needed. The length_ptr argument may be NULL, or point to an
1445 * integer into which the length of the string is stored.
1449 packet_get_string(u_int
*length_ptr
)
1451 return buffer_get_string(&incoming_packet
, length_ptr
);
1455 packet_get_string_ptr(u_int
*length_ptr
)
1457 return buffer_get_string_ptr(&incoming_packet
, length_ptr
);
1461 * Sends a diagnostic message from the server to the client. This message
1462 * can be sent at any time (but not while constructing another message). The
1463 * message is printed immediately, but only if the client is being executed
1464 * in verbose mode. These messages are primarily intended to ease debugging
1465 * authentication problems. The length of the formatted message must not
1466 * exceed 1024 bytes. This will automatically call packet_write_wait.
1470 packet_send_debug(const char *fmt
,...)
1475 if (compat20
&& (datafellows
& SSH_BUG_DEBUG
))
1478 va_start(args
, fmt
);
1479 vsnprintf(buf
, sizeof(buf
), fmt
, args
);
1483 packet_start(SSH2_MSG_DEBUG
);
1484 packet_put_char(0); /* bool: always display */
1485 packet_put_cstring(buf
);
1486 packet_put_cstring("");
1488 packet_start(SSH_MSG_DEBUG
);
1489 packet_put_cstring(buf
);
1492 packet_write_wait();
1496 * Logs the error plus constructs and sends a disconnect packet, closes the
1497 * connection, and exits. This function never returns. The error message
1498 * should not contain a newline. The length of the formatted message must
1499 * not exceed 1024 bytes.
1503 packet_disconnect(const char *fmt
,...)
1507 static int disconnecting
= 0;
1509 if (disconnecting
) /* Guard against recursive invocations. */
1510 fatal("packet_disconnect called recursively.");
1514 * Format the message. Note that the caller must make sure the
1515 * message is of limited size.
1517 va_start(args
, fmt
);
1518 vsnprintf(buf
, sizeof(buf
), fmt
, args
);
1521 /* Display the error locally */
1522 logit("Disconnecting: %.100s", buf
);
1524 /* Send the disconnect message to the other side, and wait for it to get sent. */
1526 packet_start(SSH2_MSG_DISCONNECT
);
1527 packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR
);
1528 packet_put_cstring(buf
);
1529 packet_put_cstring("");
1531 packet_start(SSH_MSG_DISCONNECT
);
1532 packet_put_cstring(buf
);
1535 packet_write_wait();
1537 /* Stop listening for connections. */
1538 channel_close_all();
1540 /* Close the connection. */
1545 /* Checks if there is any buffered output, and tries to write some of the output. */
1548 packet_write_poll(void)
1550 int len
= buffer_len(&output
);
1553 len
= write(connection_out
, buffer_ptr(&output
), len
);
1555 if (errno
== EINTR
|| errno
== EAGAIN
||
1556 errno
== EWOULDBLOCK
)
1558 fatal("Write failed: %.100s", strerror(errno
));
1561 fatal("Write connection closed");
1562 buffer_consume(&output
, len
);
1568 * Calls packet_write_poll repeatedly until all pending output data has been
1573 packet_write_wait(void)
1577 struct timeval start
, timeout
, *timeoutp
= NULL
;
1579 setp
= (fd_set
*)xcalloc(howmany(connection_out
+ 1, NFDBITS
),
1581 packet_write_poll();
1582 while (packet_have_data_to_write()) {
1583 memset(setp
, 0, howmany(connection_out
+ 1, NFDBITS
) *
1585 FD_SET(connection_out
, setp
);
1587 if (packet_timeout_ms
> 0) {
1588 ms_remain
= packet_timeout_ms
;
1589 timeoutp
= &timeout
;
1592 if (packet_timeout_ms
!= -1) {
1593 ms_to_timeval(&timeout
, ms_remain
);
1594 gettimeofday(&start
, NULL
);
1596 if ((ret
= select(connection_out
+ 1, NULL
, setp
,
1597 NULL
, timeoutp
)) >= 0)
1599 if (errno
!= EAGAIN
&& errno
!= EINTR
&&
1600 errno
!= EWOULDBLOCK
)
1602 if (packet_timeout_ms
== -1)
1604 ms_subtract_diff(&start
, &ms_remain
);
1605 if (ms_remain
<= 0) {
1611 logit("Connection to %.200s timed out while "
1612 "waiting to write", get_remote_ipaddr());
1615 packet_write_poll();
1620 /* Returns true if there is buffered data to write to the connection. */
1623 packet_have_data_to_write(void)
1625 return buffer_len(&output
) != 0;
1628 /* Returns true if there is not too much data to write to the connection. */
1631 packet_not_very_much_data_to_write(void)
1633 if (interactive_mode
)
1634 return buffer_len(&output
) < 16384;
1636 return buffer_len(&output
) < 128 * 1024;
1641 packet_set_tos(int interactive
)
1643 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1644 int tos
= interactive
? IPTOS_LOWDELAY
: IPTOS_THROUGHPUT
;
1646 if (!packet_connection_is_on_socket() ||
1647 !packet_connection_is_ipv4())
1649 if (setsockopt(connection_in
, IPPROTO_IP
, IP_TOS
, &tos
,
1651 error("setsockopt IP_TOS %d: %.100s:",
1652 tos
, strerror(errno
));
1656 /* Informs that the current session is interactive. Sets IP flags for that. */
1659 packet_set_interactive(int interactive
)
1661 static int called
= 0;
1667 /* Record that we are in interactive mode. */
1668 interactive_mode
= interactive
;
1670 /* Only set socket options if using a socket. */
1671 if (!packet_connection_is_on_socket())
1673 set_nodelay(connection_in
);
1674 packet_set_tos(interactive
);
1677 /* Returns true if the current connection is interactive. */
1680 packet_is_interactive(void)
1682 return interactive_mode
;
1686 packet_set_maxsize(u_int s
)
1688 static int called
= 0;
1691 logit("packet_set_maxsize: called twice: old %d new %d",
1692 max_packet_size
, s
);
1695 if (s
< 4 * 1024 || s
> 1024 * 1024) {
1696 logit("packet_set_maxsize: bad size %d", s
);
1700 debug("packet_set_maxsize: setting to %d", s
);
1701 max_packet_size
= s
;
1705 /* roundup current message to pad bytes */
1707 packet_add_padding(u_char pad
)
1713 * 9.2. Ignored Data Message
1715 * byte SSH_MSG_IGNORE
1718 * All implementations MUST understand (and ignore) this message at any
1719 * time (after receiving the protocol version). No implementation is
1720 * required to send them. This message can be used as an additional
1721 * protection measure against advanced traffic analysis techniques.
1724 packet_send_ignore(int nbytes
)
1729 packet_start(compat20
? SSH2_MSG_IGNORE
: SSH_MSG_IGNORE
);
1730 packet_put_int(nbytes
);
1731 for (i
= 0; i
< nbytes
; i
++) {
1734 packet_put_char((u_char
)rnd
& 0xff);
1739 #define MAX_PACKETS (1U<<31)
1741 packet_need_rekeying(void)
1743 if (datafellows
& SSH_BUG_NOREKEY
)
1746 (p_send
.packets
> MAX_PACKETS
) ||
1747 (p_read
.packets
> MAX_PACKETS
) ||
1748 (max_blocks_out
&& (p_send
.blocks
> max_blocks_out
)) ||
1749 (max_blocks_in
&& (p_read
.blocks
> max_blocks_in
));
1753 packet_set_rekey_limit(u_int32_t bytes
)
1755 rekey_limit
= bytes
;
1759 packet_set_server(void)
1765 packet_set_authenticated(void)
1767 after_authentication
= 1;