- (dtucker) [openbsd-compat/port-linux.c] Check is_selinux_enabled for exact
[openssh-git.git] / packet.c
bloba06c5e3efd8d3d7bbd4c37a65ff911e04250ffd9
1 /* $OpenBSD: packet.c,v 1.170 2010/08/31 11:54:45 djm Exp $ */
2 /*
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * All rights reserved
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
21 * are met:
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.
40 #include "includes.h"
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>
48 #endif
50 #include <netinet/in.h>
51 #include <netinet/ip.h>
52 #include <arpa/inet.h>
54 #include <errno.h>
55 #include <stdarg.h>
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <string.h>
59 #include <unistd.h>
60 #include <signal.h>
62 #include "xmalloc.h"
63 #include "buffer.h"
64 #include "packet.h"
65 #include "crc32.h"
66 #include "compress.h"
67 #include "deattack.h"
68 #include "channels.h"
69 #include "compat.h"
70 #include "ssh1.h"
71 #include "ssh2.h"
72 #include "cipher.h"
73 #include "key.h"
74 #include "kex.h"
75 #include "mac.h"
76 #include "log.h"
77 #include "canohost.h"
78 #include "misc.h"
79 #include "ssh.h"
80 #include "roaming.h"
82 #ifdef PACKET_DEBUG
83 #define DBG(x) x
84 #else
85 #define DBG(x)
86 #endif
88 #define PACKET_MAX_SIZE (256 * 1024)
90 struct packet_state {
91 u_int32_t seqnr;
92 u_int32_t packets;
93 u_int64_t blocks;
94 u_int64_t bytes;
97 struct packet {
98 TAILQ_ENTRY(packet) next;
99 u_char type;
100 Buffer payload;
103 struct session_state {
105 * This variable contains the file descriptors used for
106 * communicating with the other side. connection_in is used for
107 * reading; connection_out for writing. These can be the same
108 * descriptor, in which case it is assumed to be a socket.
110 int connection_in;
111 int connection_out;
113 /* Protocol flags for the remote side. */
114 u_int remote_protocol_flags;
116 /* Encryption context for receiving data. Only used for decryption. */
117 CipherContext receive_context;
119 /* Encryption context for sending data. Only used for encryption. */
120 CipherContext send_context;
122 /* Buffer for raw input data from the socket. */
123 Buffer input;
125 /* Buffer for raw output data going to the socket. */
126 Buffer output;
128 /* Buffer for the partial outgoing packet being constructed. */
129 Buffer outgoing_packet;
131 /* Buffer for the incoming packet currently being processed. */
132 Buffer incoming_packet;
134 /* Scratch buffer for packet compression/decompression. */
135 Buffer compression_buffer;
136 int compression_buffer_ready;
139 * Flag indicating whether packet compression/decompression is
140 * enabled.
142 int packet_compression;
144 /* default maximum packet size */
145 u_int max_packet_size;
147 /* Flag indicating whether this module has been initialized. */
148 int initialized;
150 /* Set to true if the connection is interactive. */
151 int interactive_mode;
153 /* Set to true if we are the server side. */
154 int server_side;
156 /* Set to true if we are authenticated. */
157 int after_authentication;
159 int keep_alive_timeouts;
161 /* The maximum time that we will wait to send or receive a packet */
162 int packet_timeout_ms;
164 /* Session key information for Encryption and MAC */
165 Newkeys *newkeys[MODE_MAX];
166 struct packet_state p_read, p_send;
168 u_int64_t max_blocks_in, max_blocks_out;
169 u_int32_t rekey_limit;
171 /* Session key for protocol v1 */
172 u_char ssh1_key[SSH_SESSION_KEY_LENGTH];
173 u_int ssh1_keylen;
175 /* roundup current message to extra_pad bytes */
176 u_char extra_pad;
178 /* XXX discard incoming data after MAC error */
179 u_int packet_discard;
180 Mac *packet_discard_mac;
182 /* Used in packet_read_poll2() */
183 u_int packlen;
185 /* Used in packet_send2 */
186 int rekeying;
188 /* Used in packet_set_interactive */
189 int set_interactive_called;
191 /* Used in packet_set_maxsize */
192 int set_maxsize_called;
194 TAILQ_HEAD(, packet) outgoing;
197 static struct session_state *active_state, *backup_state;
199 static struct session_state *
200 alloc_session_state(void)
202 struct session_state *s = xcalloc(1, sizeof(*s));
204 s->connection_in = -1;
205 s->connection_out = -1;
206 s->max_packet_size = 32768;
207 s->packet_timeout_ms = -1;
208 return s;
212 * Sets the descriptors used for communication. Disables encryption until
213 * packet_set_encryption_key is called.
215 void
216 packet_set_connection(int fd_in, int fd_out)
218 Cipher *none = cipher_by_name("none");
220 if (none == NULL)
221 fatal("packet_set_connection: cannot load cipher 'none'");
222 if (active_state == NULL)
223 active_state = alloc_session_state();
224 active_state->connection_in = fd_in;
225 active_state->connection_out = fd_out;
226 cipher_init(&active_state->send_context, none, (const u_char *)"",
227 0, NULL, 0, CIPHER_ENCRYPT);
228 cipher_init(&active_state->receive_context, none, (const u_char *)"",
229 0, NULL, 0, CIPHER_DECRYPT);
230 active_state->newkeys[MODE_IN] = active_state->newkeys[MODE_OUT] = NULL;
231 if (!active_state->initialized) {
232 active_state->initialized = 1;
233 buffer_init(&active_state->input);
234 buffer_init(&active_state->output);
235 buffer_init(&active_state->outgoing_packet);
236 buffer_init(&active_state->incoming_packet);
237 TAILQ_INIT(&active_state->outgoing);
238 active_state->p_send.packets = active_state->p_read.packets = 0;
242 void
243 packet_set_timeout(int timeout, int count)
245 if (timeout == 0 || count == 0) {
246 active_state->packet_timeout_ms = -1;
247 return;
249 if ((INT_MAX / 1000) / count < timeout)
250 active_state->packet_timeout_ms = INT_MAX;
251 else
252 active_state->packet_timeout_ms = timeout * count * 1000;
255 static void
256 packet_stop_discard(void)
258 if (active_state->packet_discard_mac) {
259 char buf[1024];
261 memset(buf, 'a', sizeof(buf));
262 while (buffer_len(&active_state->incoming_packet) <
263 PACKET_MAX_SIZE)
264 buffer_append(&active_state->incoming_packet, buf,
265 sizeof(buf));
266 (void) mac_compute(active_state->packet_discard_mac,
267 active_state->p_read.seqnr,
268 buffer_ptr(&active_state->incoming_packet),
269 PACKET_MAX_SIZE);
271 logit("Finished discarding for %.200s", get_remote_ipaddr());
272 cleanup_exit(255);
275 static void
276 packet_start_discard(Enc *enc, Mac *mac, u_int packet_length, u_int discard)
278 if (enc == NULL || !cipher_is_cbc(enc->cipher))
279 packet_disconnect("Packet corrupt");
280 if (packet_length != PACKET_MAX_SIZE && mac && mac->enabled)
281 active_state->packet_discard_mac = mac;
282 if (buffer_len(&active_state->input) >= discard)
283 packet_stop_discard();
284 active_state->packet_discard = discard -
285 buffer_len(&active_state->input);
288 /* Returns 1 if remote host is connected via socket, 0 if not. */
291 packet_connection_is_on_socket(void)
293 struct sockaddr_storage from, to;
294 socklen_t fromlen, tolen;
296 /* filedescriptors in and out are the same, so it's a socket */
297 if (active_state->connection_in == active_state->connection_out)
298 return 1;
299 fromlen = sizeof(from);
300 memset(&from, 0, sizeof(from));
301 if (getpeername(active_state->connection_in, (struct sockaddr *)&from,
302 &fromlen) < 0)
303 return 0;
304 tolen = sizeof(to);
305 memset(&to, 0, sizeof(to));
306 if (getpeername(active_state->connection_out, (struct sockaddr *)&to,
307 &tolen) < 0)
308 return 0;
309 if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
310 return 0;
311 if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
312 return 0;
313 return 1;
317 * Exports an IV from the CipherContext required to export the key
318 * state back from the unprivileged child to the privileged parent
319 * process.
322 void
323 packet_get_keyiv(int mode, u_char *iv, u_int len)
325 CipherContext *cc;
327 if (mode == MODE_OUT)
328 cc = &active_state->send_context;
329 else
330 cc = &active_state->receive_context;
332 cipher_get_keyiv(cc, iv, len);
336 packet_get_keycontext(int mode, u_char *dat)
338 CipherContext *cc;
340 if (mode == MODE_OUT)
341 cc = &active_state->send_context;
342 else
343 cc = &active_state->receive_context;
345 return (cipher_get_keycontext(cc, dat));
348 void
349 packet_set_keycontext(int mode, u_char *dat)
351 CipherContext *cc;
353 if (mode == MODE_OUT)
354 cc = &active_state->send_context;
355 else
356 cc = &active_state->receive_context;
358 cipher_set_keycontext(cc, dat);
362 packet_get_keyiv_len(int mode)
364 CipherContext *cc;
366 if (mode == MODE_OUT)
367 cc = &active_state->send_context;
368 else
369 cc = &active_state->receive_context;
371 return (cipher_get_keyiv_len(cc));
374 void
375 packet_set_iv(int mode, u_char *dat)
377 CipherContext *cc;
379 if (mode == MODE_OUT)
380 cc = &active_state->send_context;
381 else
382 cc = &active_state->receive_context;
384 cipher_set_keyiv(cc, dat);
388 packet_get_ssh1_cipher(void)
390 return (cipher_get_number(active_state->receive_context.cipher));
393 void
394 packet_get_state(int mode, u_int32_t *seqnr, u_int64_t *blocks, u_int32_t *packets,
395 u_int64_t *bytes)
397 struct packet_state *state;
399 state = (mode == MODE_IN) ?
400 &active_state->p_read : &active_state->p_send;
401 if (seqnr)
402 *seqnr = state->seqnr;
403 if (blocks)
404 *blocks = state->blocks;
405 if (packets)
406 *packets = state->packets;
407 if (bytes)
408 *bytes = state->bytes;
411 void
412 packet_set_state(int mode, u_int32_t seqnr, u_int64_t blocks, u_int32_t packets,
413 u_int64_t bytes)
415 struct packet_state *state;
417 state = (mode == MODE_IN) ?
418 &active_state->p_read : &active_state->p_send;
419 state->seqnr = seqnr;
420 state->blocks = blocks;
421 state->packets = packets;
422 state->bytes = bytes;
425 /* returns 1 if connection is via ipv4 */
428 packet_connection_is_ipv4(void)
430 struct sockaddr_storage to;
431 socklen_t tolen = sizeof(to);
433 memset(&to, 0, sizeof(to));
434 if (getsockname(active_state->connection_out, (struct sockaddr *)&to,
435 &tolen) < 0)
436 return 0;
437 if (to.ss_family == AF_INET)
438 return 1;
439 #ifdef IPV4_IN_IPV6
440 if (to.ss_family == AF_INET6 &&
441 IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&to)->sin6_addr))
442 return 1;
443 #endif
444 return 0;
447 /* Sets the connection into non-blocking mode. */
449 void
450 packet_set_nonblocking(void)
452 /* Set the socket into non-blocking mode. */
453 set_nonblock(active_state->connection_in);
455 if (active_state->connection_out != active_state->connection_in)
456 set_nonblock(active_state->connection_out);
459 /* Returns the socket used for reading. */
462 packet_get_connection_in(void)
464 return active_state->connection_in;
467 /* Returns the descriptor used for writing. */
470 packet_get_connection_out(void)
472 return active_state->connection_out;
475 /* Closes the connection and clears and frees internal data structures. */
477 void
478 packet_close(void)
480 if (!active_state->initialized)
481 return;
482 active_state->initialized = 0;
483 if (active_state->connection_in == active_state->connection_out) {
484 shutdown(active_state->connection_out, SHUT_RDWR);
485 close(active_state->connection_out);
486 } else {
487 close(active_state->connection_in);
488 close(active_state->connection_out);
490 buffer_free(&active_state->input);
491 buffer_free(&active_state->output);
492 buffer_free(&active_state->outgoing_packet);
493 buffer_free(&active_state->incoming_packet);
494 if (active_state->compression_buffer_ready) {
495 buffer_free(&active_state->compression_buffer);
496 buffer_compress_uninit();
498 cipher_cleanup(&active_state->send_context);
499 cipher_cleanup(&active_state->receive_context);
502 /* Sets remote side protocol flags. */
504 void
505 packet_set_protocol_flags(u_int protocol_flags)
507 active_state->remote_protocol_flags = protocol_flags;
510 /* Returns the remote protocol flags set earlier by the above function. */
512 u_int
513 packet_get_protocol_flags(void)
515 return active_state->remote_protocol_flags;
519 * Starts packet compression from the next packet on in both directions.
520 * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
523 static void
524 packet_init_compression(void)
526 if (active_state->compression_buffer_ready == 1)
527 return;
528 active_state->compression_buffer_ready = 1;
529 buffer_init(&active_state->compression_buffer);
532 void
533 packet_start_compression(int level)
535 if (active_state->packet_compression && !compat20)
536 fatal("Compression already enabled.");
537 active_state->packet_compression = 1;
538 packet_init_compression();
539 buffer_compress_init_send(level);
540 buffer_compress_init_recv();
544 * Causes any further packets to be encrypted using the given key. The same
545 * key is used for both sending and reception. However, both directions are
546 * encrypted independently of each other.
549 void
550 packet_set_encryption_key(const u_char *key, u_int keylen,
551 int number)
553 Cipher *cipher = cipher_by_number(number);
555 if (cipher == NULL)
556 fatal("packet_set_encryption_key: unknown cipher number %d", number);
557 if (keylen < 20)
558 fatal("packet_set_encryption_key: keylen too small: %d", keylen);
559 if (keylen > SSH_SESSION_KEY_LENGTH)
560 fatal("packet_set_encryption_key: keylen too big: %d", keylen);
561 memcpy(active_state->ssh1_key, key, keylen);
562 active_state->ssh1_keylen = keylen;
563 cipher_init(&active_state->send_context, cipher, key, keylen, NULL,
564 0, CIPHER_ENCRYPT);
565 cipher_init(&active_state->receive_context, cipher, key, keylen, NULL,
566 0, CIPHER_DECRYPT);
569 u_int
570 packet_get_encryption_key(u_char *key)
572 if (key == NULL)
573 return (active_state->ssh1_keylen);
574 memcpy(key, active_state->ssh1_key, active_state->ssh1_keylen);
575 return (active_state->ssh1_keylen);
578 /* Start constructing a packet to send. */
579 void
580 packet_start(u_char type)
582 u_char buf[9];
583 int len;
585 DBG(debug("packet_start[%d]", type));
586 len = compat20 ? 6 : 9;
587 memset(buf, 0, len - 1);
588 buf[len - 1] = type;
589 buffer_clear(&active_state->outgoing_packet);
590 buffer_append(&active_state->outgoing_packet, buf, len);
593 /* Append payload. */
594 void
595 packet_put_char(int value)
597 char ch = value;
599 buffer_append(&active_state->outgoing_packet, &ch, 1);
602 void
603 packet_put_int(u_int value)
605 buffer_put_int(&active_state->outgoing_packet, value);
608 void
609 packet_put_int64(u_int64_t value)
611 buffer_put_int64(&active_state->outgoing_packet, value);
614 void
615 packet_put_string(const void *buf, u_int len)
617 buffer_put_string(&active_state->outgoing_packet, buf, len);
620 void
621 packet_put_cstring(const char *str)
623 buffer_put_cstring(&active_state->outgoing_packet, str);
626 void
627 packet_put_raw(const void *buf, u_int len)
629 buffer_append(&active_state->outgoing_packet, buf, len);
632 void
633 packet_put_bignum(BIGNUM * value)
635 buffer_put_bignum(&active_state->outgoing_packet, value);
638 void
639 packet_put_bignum2(BIGNUM * value)
641 buffer_put_bignum2(&active_state->outgoing_packet, value);
644 void
645 packet_put_ecpoint(const EC_GROUP *curve, const EC_POINT *point)
647 buffer_put_ecpoint(&active_state->outgoing_packet, curve, point);
651 * Finalizes and sends the packet. If the encryption key has been set,
652 * encrypts the packet before sending.
655 static void
656 packet_send1(void)
658 u_char buf[8], *cp;
659 int i, padding, len;
660 u_int checksum;
661 u_int32_t rnd = 0;
664 * If using packet compression, compress the payload of the outgoing
665 * packet.
667 if (active_state->packet_compression) {
668 buffer_clear(&active_state->compression_buffer);
669 /* Skip padding. */
670 buffer_consume(&active_state->outgoing_packet, 8);
671 /* padding */
672 buffer_append(&active_state->compression_buffer,
673 "\0\0\0\0\0\0\0\0", 8);
674 buffer_compress(&active_state->outgoing_packet,
675 &active_state->compression_buffer);
676 buffer_clear(&active_state->outgoing_packet);
677 buffer_append(&active_state->outgoing_packet,
678 buffer_ptr(&active_state->compression_buffer),
679 buffer_len(&active_state->compression_buffer));
681 /* Compute packet length without padding (add checksum, remove padding). */
682 len = buffer_len(&active_state->outgoing_packet) + 4 - 8;
684 /* Insert padding. Initialized to zero in packet_start1() */
685 padding = 8 - len % 8;
686 if (!active_state->send_context.plaintext) {
687 cp = buffer_ptr(&active_state->outgoing_packet);
688 for (i = 0; i < padding; i++) {
689 if (i % 4 == 0)
690 rnd = arc4random();
691 cp[7 - i] = rnd & 0xff;
692 rnd >>= 8;
695 buffer_consume(&active_state->outgoing_packet, 8 - padding);
697 /* Add check bytes. */
698 checksum = ssh_crc32(buffer_ptr(&active_state->outgoing_packet),
699 buffer_len(&active_state->outgoing_packet));
700 put_u32(buf, checksum);
701 buffer_append(&active_state->outgoing_packet, buf, 4);
703 #ifdef PACKET_DEBUG
704 fprintf(stderr, "packet_send plain: ");
705 buffer_dump(&active_state->outgoing_packet);
706 #endif
708 /* Append to output. */
709 put_u32(buf, len);
710 buffer_append(&active_state->output, buf, 4);
711 cp = buffer_append_space(&active_state->output,
712 buffer_len(&active_state->outgoing_packet));
713 cipher_crypt(&active_state->send_context, cp,
714 buffer_ptr(&active_state->outgoing_packet),
715 buffer_len(&active_state->outgoing_packet));
717 #ifdef PACKET_DEBUG
718 fprintf(stderr, "encrypted: ");
719 buffer_dump(&active_state->output);
720 #endif
721 active_state->p_send.packets++;
722 active_state->p_send.bytes += len +
723 buffer_len(&active_state->outgoing_packet);
724 buffer_clear(&active_state->outgoing_packet);
727 * Note that the packet is now only buffered in output. It won't be
728 * actually sent until packet_write_wait or packet_write_poll is
729 * called.
733 void
734 set_newkeys(int mode)
736 Enc *enc;
737 Mac *mac;
738 Comp *comp;
739 CipherContext *cc;
740 u_int64_t *max_blocks;
741 int crypt_type;
743 debug2("set_newkeys: mode %d", mode);
745 if (mode == MODE_OUT) {
746 cc = &active_state->send_context;
747 crypt_type = CIPHER_ENCRYPT;
748 active_state->p_send.packets = active_state->p_send.blocks = 0;
749 max_blocks = &active_state->max_blocks_out;
750 } else {
751 cc = &active_state->receive_context;
752 crypt_type = CIPHER_DECRYPT;
753 active_state->p_read.packets = active_state->p_read.blocks = 0;
754 max_blocks = &active_state->max_blocks_in;
756 if (active_state->newkeys[mode] != NULL) {
757 debug("set_newkeys: rekeying");
758 cipher_cleanup(cc);
759 enc = &active_state->newkeys[mode]->enc;
760 mac = &active_state->newkeys[mode]->mac;
761 comp = &active_state->newkeys[mode]->comp;
762 mac_clear(mac);
763 xfree(enc->name);
764 xfree(enc->iv);
765 xfree(enc->key);
766 xfree(mac->name);
767 xfree(mac->key);
768 xfree(comp->name);
769 xfree(active_state->newkeys[mode]);
771 active_state->newkeys[mode] = kex_get_newkeys(mode);
772 if (active_state->newkeys[mode] == NULL)
773 fatal("newkeys: no keys for mode %d", mode);
774 enc = &active_state->newkeys[mode]->enc;
775 mac = &active_state->newkeys[mode]->mac;
776 comp = &active_state->newkeys[mode]->comp;
777 if (mac_init(mac) == 0)
778 mac->enabled = 1;
779 DBG(debug("cipher_init_context: %d", mode));
780 cipher_init(cc, enc->cipher, enc->key, enc->key_len,
781 enc->iv, enc->block_size, crypt_type);
782 /* Deleting the keys does not gain extra security */
783 /* memset(enc->iv, 0, enc->block_size);
784 memset(enc->key, 0, enc->key_len);
785 memset(mac->key, 0, mac->key_len); */
786 if ((comp->type == COMP_ZLIB ||
787 (comp->type == COMP_DELAYED &&
788 active_state->after_authentication)) && comp->enabled == 0) {
789 packet_init_compression();
790 if (mode == MODE_OUT)
791 buffer_compress_init_send(6);
792 else
793 buffer_compress_init_recv();
794 comp->enabled = 1;
797 * The 2^(blocksize*2) limit is too expensive for 3DES,
798 * blowfish, etc, so enforce a 1GB limit for small blocksizes.
800 if (enc->block_size >= 16)
801 *max_blocks = (u_int64_t)1 << (enc->block_size*2);
802 else
803 *max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
804 if (active_state->rekey_limit)
805 *max_blocks = MIN(*max_blocks,
806 active_state->rekey_limit / enc->block_size);
810 * Delayed compression for SSH2 is enabled after authentication:
811 * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
812 * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
814 static void
815 packet_enable_delayed_compress(void)
817 Comp *comp = NULL;
818 int mode;
821 * Remember that we are past the authentication step, so rekeying
822 * with COMP_DELAYED will turn on compression immediately.
824 active_state->after_authentication = 1;
825 for (mode = 0; mode < MODE_MAX; mode++) {
826 /* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
827 if (active_state->newkeys[mode] == NULL)
828 continue;
829 comp = &active_state->newkeys[mode]->comp;
830 if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
831 packet_init_compression();
832 if (mode == MODE_OUT)
833 buffer_compress_init_send(6);
834 else
835 buffer_compress_init_recv();
836 comp->enabled = 1;
842 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
844 static void
845 packet_send2_wrapped(void)
847 u_char type, *cp, *macbuf = NULL;
848 u_char padlen, pad;
849 u_int packet_length = 0;
850 u_int i, len;
851 u_int32_t rnd = 0;
852 Enc *enc = NULL;
853 Mac *mac = NULL;
854 Comp *comp = NULL;
855 int block_size;
857 if (active_state->newkeys[MODE_OUT] != NULL) {
858 enc = &active_state->newkeys[MODE_OUT]->enc;
859 mac = &active_state->newkeys[MODE_OUT]->mac;
860 comp = &active_state->newkeys[MODE_OUT]->comp;
862 block_size = enc ? enc->block_size : 8;
864 cp = buffer_ptr(&active_state->outgoing_packet);
865 type = cp[5];
867 #ifdef PACKET_DEBUG
868 fprintf(stderr, "plain: ");
869 buffer_dump(&active_state->outgoing_packet);
870 #endif
872 if (comp && comp->enabled) {
873 len = buffer_len(&active_state->outgoing_packet);
874 /* skip header, compress only payload */
875 buffer_consume(&active_state->outgoing_packet, 5);
876 buffer_clear(&active_state->compression_buffer);
877 buffer_compress(&active_state->outgoing_packet,
878 &active_state->compression_buffer);
879 buffer_clear(&active_state->outgoing_packet);
880 buffer_append(&active_state->outgoing_packet, "\0\0\0\0\0", 5);
881 buffer_append(&active_state->outgoing_packet,
882 buffer_ptr(&active_state->compression_buffer),
883 buffer_len(&active_state->compression_buffer));
884 DBG(debug("compression: raw %d compressed %d", len,
885 buffer_len(&active_state->outgoing_packet)));
888 /* sizeof (packet_len + pad_len + payload) */
889 len = buffer_len(&active_state->outgoing_packet);
892 * calc size of padding, alloc space, get random data,
893 * minimum padding is 4 bytes
895 padlen = block_size - (len % block_size);
896 if (padlen < 4)
897 padlen += block_size;
898 if (active_state->extra_pad) {
899 /* will wrap if extra_pad+padlen > 255 */
900 active_state->extra_pad =
901 roundup(active_state->extra_pad, block_size);
902 pad = active_state->extra_pad -
903 ((len + padlen) % active_state->extra_pad);
904 debug3("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
905 pad, len, padlen, active_state->extra_pad);
906 padlen += pad;
907 active_state->extra_pad = 0;
909 cp = buffer_append_space(&active_state->outgoing_packet, padlen);
910 if (enc && !active_state->send_context.plaintext) {
911 /* random padding */
912 for (i = 0; i < padlen; i++) {
913 if (i % 4 == 0)
914 rnd = arc4random();
915 cp[i] = rnd & 0xff;
916 rnd >>= 8;
918 } else {
919 /* clear padding */
920 memset(cp, 0, padlen);
922 /* packet_length includes payload, padding and padding length field */
923 packet_length = buffer_len(&active_state->outgoing_packet) - 4;
924 cp = buffer_ptr(&active_state->outgoing_packet);
925 put_u32(cp, packet_length);
926 cp[4] = padlen;
927 DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen));
929 /* compute MAC over seqnr and packet(length fields, payload, padding) */
930 if (mac && mac->enabled) {
931 macbuf = mac_compute(mac, active_state->p_send.seqnr,
932 buffer_ptr(&active_state->outgoing_packet),
933 buffer_len(&active_state->outgoing_packet));
934 DBG(debug("done calc MAC out #%d", active_state->p_send.seqnr));
936 /* encrypt packet and append to output buffer. */
937 cp = buffer_append_space(&active_state->output,
938 buffer_len(&active_state->outgoing_packet));
939 cipher_crypt(&active_state->send_context, cp,
940 buffer_ptr(&active_state->outgoing_packet),
941 buffer_len(&active_state->outgoing_packet));
942 /* append unencrypted MAC */
943 if (mac && mac->enabled)
944 buffer_append(&active_state->output, macbuf, mac->mac_len);
945 #ifdef PACKET_DEBUG
946 fprintf(stderr, "encrypted: ");
947 buffer_dump(&active_state->output);
948 #endif
949 /* increment sequence number for outgoing packets */
950 if (++active_state->p_send.seqnr == 0)
951 logit("outgoing seqnr wraps around");
952 if (++active_state->p_send.packets == 0)
953 if (!(datafellows & SSH_BUG_NOREKEY))
954 fatal("XXX too many packets with same key");
955 active_state->p_send.blocks += (packet_length + 4) / block_size;
956 active_state->p_send.bytes += packet_length + 4;
957 buffer_clear(&active_state->outgoing_packet);
959 if (type == SSH2_MSG_NEWKEYS)
960 set_newkeys(MODE_OUT);
961 else if (type == SSH2_MSG_USERAUTH_SUCCESS && active_state->server_side)
962 packet_enable_delayed_compress();
965 static void
966 packet_send2(void)
968 struct packet *p;
969 u_char type, *cp;
971 cp = buffer_ptr(&active_state->outgoing_packet);
972 type = cp[5];
974 /* during rekeying we can only send key exchange messages */
975 if (active_state->rekeying) {
976 if (!((type >= SSH2_MSG_TRANSPORT_MIN) &&
977 (type <= SSH2_MSG_TRANSPORT_MAX))) {
978 debug("enqueue packet: %u", type);
979 p = xmalloc(sizeof(*p));
980 p->type = type;
981 memcpy(&p->payload, &active_state->outgoing_packet,
982 sizeof(Buffer));
983 buffer_init(&active_state->outgoing_packet);
984 TAILQ_INSERT_TAIL(&active_state->outgoing, p, next);
985 return;
989 /* rekeying starts with sending KEXINIT */
990 if (type == SSH2_MSG_KEXINIT)
991 active_state->rekeying = 1;
993 packet_send2_wrapped();
995 /* after a NEWKEYS message we can send the complete queue */
996 if (type == SSH2_MSG_NEWKEYS) {
997 active_state->rekeying = 0;
998 while ((p = TAILQ_FIRST(&active_state->outgoing))) {
999 type = p->type;
1000 debug("dequeue packet: %u", type);
1001 buffer_free(&active_state->outgoing_packet);
1002 memcpy(&active_state->outgoing_packet, &p->payload,
1003 sizeof(Buffer));
1004 TAILQ_REMOVE(&active_state->outgoing, p, next);
1005 xfree(p);
1006 packet_send2_wrapped();
1011 void
1012 packet_send(void)
1014 if (compat20)
1015 packet_send2();
1016 else
1017 packet_send1();
1018 DBG(debug("packet_send done"));
1022 * Waits until a packet has been received, and returns its type. Note that
1023 * no other data is processed until this returns, so this function should not
1024 * be used during the interactive session.
1028 packet_read_seqnr(u_int32_t *seqnr_p)
1030 int type, len, ret, ms_remain, cont;
1031 fd_set *setp;
1032 char buf[8192];
1033 struct timeval timeout, start, *timeoutp = NULL;
1035 DBG(debug("packet_read()"));
1037 setp = (fd_set *)xcalloc(howmany(active_state->connection_in + 1,
1038 NFDBITS), sizeof(fd_mask));
1040 /* Since we are blocking, ensure that all written packets have been sent. */
1041 packet_write_wait();
1043 /* Stay in the loop until we have received a complete packet. */
1044 for (;;) {
1045 /* Try to read a packet from the buffer. */
1046 type = packet_read_poll_seqnr(seqnr_p);
1047 if (!compat20 && (
1048 type == SSH_SMSG_SUCCESS
1049 || type == SSH_SMSG_FAILURE
1050 || type == SSH_CMSG_EOF
1051 || type == SSH_CMSG_EXIT_CONFIRMATION))
1052 packet_check_eom();
1053 /* If we got a packet, return it. */
1054 if (type != SSH_MSG_NONE) {
1055 xfree(setp);
1056 return type;
1059 * Otherwise, wait for some data to arrive, add it to the
1060 * buffer, and try again.
1062 memset(setp, 0, howmany(active_state->connection_in + 1,
1063 NFDBITS) * sizeof(fd_mask));
1064 FD_SET(active_state->connection_in, setp);
1066 if (active_state->packet_timeout_ms > 0) {
1067 ms_remain = active_state->packet_timeout_ms;
1068 timeoutp = &timeout;
1070 /* Wait for some data to arrive. */
1071 for (;;) {
1072 if (active_state->packet_timeout_ms != -1) {
1073 ms_to_timeval(&timeout, ms_remain);
1074 gettimeofday(&start, NULL);
1076 if ((ret = select(active_state->connection_in + 1, setp,
1077 NULL, NULL, timeoutp)) >= 0)
1078 break;
1079 if (errno != EAGAIN && errno != EINTR &&
1080 errno != EWOULDBLOCK)
1081 break;
1082 if (active_state->packet_timeout_ms == -1)
1083 continue;
1084 ms_subtract_diff(&start, &ms_remain);
1085 if (ms_remain <= 0) {
1086 ret = 0;
1087 break;
1090 if (ret == 0) {
1091 logit("Connection to %.200s timed out while "
1092 "waiting to read", get_remote_ipaddr());
1093 cleanup_exit(255);
1095 /* Read data from the socket. */
1096 do {
1097 cont = 0;
1098 len = roaming_read(active_state->connection_in, buf,
1099 sizeof(buf), &cont);
1100 } while (len == 0 && cont);
1101 if (len == 0) {
1102 logit("Connection closed by %.200s", get_remote_ipaddr());
1103 cleanup_exit(255);
1105 if (len < 0)
1106 fatal("Read from socket failed: %.100s", strerror(errno));
1107 /* Append it to the buffer. */
1108 packet_process_incoming(buf, len);
1110 /* NOTREACHED */
1114 packet_read(void)
1116 return packet_read_seqnr(NULL);
1120 * Waits until a packet has been received, verifies that its type matches
1121 * that given, and gives a fatal error and exits if there is a mismatch.
1124 void
1125 packet_read_expect(int expected_type)
1127 int type;
1129 type = packet_read();
1130 if (type != expected_type)
1131 packet_disconnect("Protocol error: expected packet type %d, got %d",
1132 expected_type, type);
1135 /* Checks if a full packet is available in the data received so far via
1136 * packet_process_incoming. If so, reads the packet; otherwise returns
1137 * SSH_MSG_NONE. This does not wait for data from the connection.
1139 * SSH_MSG_DISCONNECT is handled specially here. Also,
1140 * SSH_MSG_IGNORE messages are skipped by this function and are never returned
1141 * to higher levels.
1144 static int
1145 packet_read_poll1(void)
1147 u_int len, padded_len;
1148 u_char *cp, type;
1149 u_int checksum, stored_checksum;
1151 /* Check if input size is less than minimum packet size. */
1152 if (buffer_len(&active_state->input) < 4 + 8)
1153 return SSH_MSG_NONE;
1154 /* Get length of incoming packet. */
1155 cp = buffer_ptr(&active_state->input);
1156 len = get_u32(cp);
1157 if (len < 1 + 2 + 2 || len > 256 * 1024)
1158 packet_disconnect("Bad packet length %u.", len);
1159 padded_len = (len + 8) & ~7;
1161 /* Check if the packet has been entirely received. */
1162 if (buffer_len(&active_state->input) < 4 + padded_len)
1163 return SSH_MSG_NONE;
1165 /* The entire packet is in buffer. */
1167 /* Consume packet length. */
1168 buffer_consume(&active_state->input, 4);
1171 * Cryptographic attack detector for ssh
1172 * (C)1998 CORE-SDI, Buenos Aires Argentina
1173 * Ariel Futoransky(futo@core-sdi.com)
1175 if (!active_state->receive_context.plaintext) {
1176 switch (detect_attack(buffer_ptr(&active_state->input),
1177 padded_len)) {
1178 case DEATTACK_DETECTED:
1179 packet_disconnect("crc32 compensation attack: "
1180 "network attack detected");
1181 case DEATTACK_DOS_DETECTED:
1182 packet_disconnect("deattack denial of "
1183 "service detected");
1187 /* Decrypt data to incoming_packet. */
1188 buffer_clear(&active_state->incoming_packet);
1189 cp = buffer_append_space(&active_state->incoming_packet, padded_len);
1190 cipher_crypt(&active_state->receive_context, cp,
1191 buffer_ptr(&active_state->input), padded_len);
1193 buffer_consume(&active_state->input, padded_len);
1195 #ifdef PACKET_DEBUG
1196 fprintf(stderr, "read_poll plain: ");
1197 buffer_dump(&active_state->incoming_packet);
1198 #endif
1200 /* Compute packet checksum. */
1201 checksum = ssh_crc32(buffer_ptr(&active_state->incoming_packet),
1202 buffer_len(&active_state->incoming_packet) - 4);
1204 /* Skip padding. */
1205 buffer_consume(&active_state->incoming_packet, 8 - len % 8);
1207 /* Test check bytes. */
1208 if (len != buffer_len(&active_state->incoming_packet))
1209 packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
1210 len, buffer_len(&active_state->incoming_packet));
1212 cp = (u_char *)buffer_ptr(&active_state->incoming_packet) + len - 4;
1213 stored_checksum = get_u32(cp);
1214 if (checksum != stored_checksum)
1215 packet_disconnect("Corrupted check bytes on input.");
1216 buffer_consume_end(&active_state->incoming_packet, 4);
1218 if (active_state->packet_compression) {
1219 buffer_clear(&active_state->compression_buffer);
1220 buffer_uncompress(&active_state->incoming_packet,
1221 &active_state->compression_buffer);
1222 buffer_clear(&active_state->incoming_packet);
1223 buffer_append(&active_state->incoming_packet,
1224 buffer_ptr(&active_state->compression_buffer),
1225 buffer_len(&active_state->compression_buffer));
1227 active_state->p_read.packets++;
1228 active_state->p_read.bytes += padded_len + 4;
1229 type = buffer_get_char(&active_state->incoming_packet);
1230 if (type < SSH_MSG_MIN || type > SSH_MSG_MAX)
1231 packet_disconnect("Invalid ssh1 packet type: %d", type);
1232 return type;
1235 static int
1236 packet_read_poll2(u_int32_t *seqnr_p)
1238 u_int padlen, need;
1239 u_char *macbuf, *cp, type;
1240 u_int maclen, block_size;
1241 Enc *enc = NULL;
1242 Mac *mac = NULL;
1243 Comp *comp = NULL;
1245 if (active_state->packet_discard)
1246 return SSH_MSG_NONE;
1248 if (active_state->newkeys[MODE_IN] != NULL) {
1249 enc = &active_state->newkeys[MODE_IN]->enc;
1250 mac = &active_state->newkeys[MODE_IN]->mac;
1251 comp = &active_state->newkeys[MODE_IN]->comp;
1253 maclen = mac && mac->enabled ? mac->mac_len : 0;
1254 block_size = enc ? enc->block_size : 8;
1256 if (active_state->packlen == 0) {
1258 * check if input size is less than the cipher block size,
1259 * decrypt first block and extract length of incoming packet
1261 if (buffer_len(&active_state->input) < block_size)
1262 return SSH_MSG_NONE;
1263 buffer_clear(&active_state->incoming_packet);
1264 cp = buffer_append_space(&active_state->incoming_packet,
1265 block_size);
1266 cipher_crypt(&active_state->receive_context, cp,
1267 buffer_ptr(&active_state->input), block_size);
1268 cp = buffer_ptr(&active_state->incoming_packet);
1269 active_state->packlen = get_u32(cp);
1270 if (active_state->packlen < 1 + 4 ||
1271 active_state->packlen > PACKET_MAX_SIZE) {
1272 #ifdef PACKET_DEBUG
1273 buffer_dump(&active_state->incoming_packet);
1274 #endif
1275 logit("Bad packet length %u.", active_state->packlen);
1276 packet_start_discard(enc, mac, active_state->packlen,
1277 PACKET_MAX_SIZE);
1278 return SSH_MSG_NONE;
1280 DBG(debug("input: packet len %u", active_state->packlen+4));
1281 buffer_consume(&active_state->input, block_size);
1283 /* we have a partial packet of block_size bytes */
1284 need = 4 + active_state->packlen - block_size;
1285 DBG(debug("partial packet %d, need %d, maclen %d", block_size,
1286 need, maclen));
1287 if (need % block_size != 0) {
1288 logit("padding error: need %d block %d mod %d",
1289 need, block_size, need % block_size);
1290 packet_start_discard(enc, mac, active_state->packlen,
1291 PACKET_MAX_SIZE - block_size);
1292 return SSH_MSG_NONE;
1295 * check if the entire packet has been received and
1296 * decrypt into incoming_packet
1298 if (buffer_len(&active_state->input) < need + maclen)
1299 return SSH_MSG_NONE;
1300 #ifdef PACKET_DEBUG
1301 fprintf(stderr, "read_poll enc/full: ");
1302 buffer_dump(&active_state->input);
1303 #endif
1304 cp = buffer_append_space(&active_state->incoming_packet, need);
1305 cipher_crypt(&active_state->receive_context, cp,
1306 buffer_ptr(&active_state->input), need);
1307 buffer_consume(&active_state->input, need);
1309 * compute MAC over seqnr and packet,
1310 * increment sequence number for incoming packet
1312 if (mac && mac->enabled) {
1313 macbuf = mac_compute(mac, active_state->p_read.seqnr,
1314 buffer_ptr(&active_state->incoming_packet),
1315 buffer_len(&active_state->incoming_packet));
1316 if (timingsafe_bcmp(macbuf, buffer_ptr(&active_state->input),
1317 mac->mac_len) != 0) {
1318 logit("Corrupted MAC on input.");
1319 if (need > PACKET_MAX_SIZE)
1320 fatal("internal error need %d", need);
1321 packet_start_discard(enc, mac, active_state->packlen,
1322 PACKET_MAX_SIZE - need);
1323 return SSH_MSG_NONE;
1326 DBG(debug("MAC #%d ok", active_state->p_read.seqnr));
1327 buffer_consume(&active_state->input, mac->mac_len);
1329 /* XXX now it's safe to use fatal/packet_disconnect */
1330 if (seqnr_p != NULL)
1331 *seqnr_p = active_state->p_read.seqnr;
1332 if (++active_state->p_read.seqnr == 0)
1333 logit("incoming seqnr wraps around");
1334 if (++active_state->p_read.packets == 0)
1335 if (!(datafellows & SSH_BUG_NOREKEY))
1336 fatal("XXX too many packets with same key");
1337 active_state->p_read.blocks += (active_state->packlen + 4) / block_size;
1338 active_state->p_read.bytes += active_state->packlen + 4;
1340 /* get padlen */
1341 cp = buffer_ptr(&active_state->incoming_packet);
1342 padlen = cp[4];
1343 DBG(debug("input: padlen %d", padlen));
1344 if (padlen < 4)
1345 packet_disconnect("Corrupted padlen %d on input.", padlen);
1347 /* skip packet size + padlen, discard padding */
1348 buffer_consume(&active_state->incoming_packet, 4 + 1);
1349 buffer_consume_end(&active_state->incoming_packet, padlen);
1351 DBG(debug("input: len before de-compress %d",
1352 buffer_len(&active_state->incoming_packet)));
1353 if (comp && comp->enabled) {
1354 buffer_clear(&active_state->compression_buffer);
1355 buffer_uncompress(&active_state->incoming_packet,
1356 &active_state->compression_buffer);
1357 buffer_clear(&active_state->incoming_packet);
1358 buffer_append(&active_state->incoming_packet,
1359 buffer_ptr(&active_state->compression_buffer),
1360 buffer_len(&active_state->compression_buffer));
1361 DBG(debug("input: len after de-compress %d",
1362 buffer_len(&active_state->incoming_packet)));
1365 * get packet type, implies consume.
1366 * return length of payload (without type field)
1368 type = buffer_get_char(&active_state->incoming_packet);
1369 if (type < SSH2_MSG_MIN || type >= SSH2_MSG_LOCAL_MIN)
1370 packet_disconnect("Invalid ssh2 packet type: %d", type);
1371 if (type == SSH2_MSG_NEWKEYS)
1372 set_newkeys(MODE_IN);
1373 else if (type == SSH2_MSG_USERAUTH_SUCCESS &&
1374 !active_state->server_side)
1375 packet_enable_delayed_compress();
1376 #ifdef PACKET_DEBUG
1377 fprintf(stderr, "read/plain[%d]:\r\n", type);
1378 buffer_dump(&active_state->incoming_packet);
1379 #endif
1380 /* reset for next packet */
1381 active_state->packlen = 0;
1382 return type;
1386 packet_read_poll_seqnr(u_int32_t *seqnr_p)
1388 u_int reason, seqnr;
1389 u_char type;
1390 char *msg;
1392 for (;;) {
1393 if (compat20) {
1394 type = packet_read_poll2(seqnr_p);
1395 if (type) {
1396 active_state->keep_alive_timeouts = 0;
1397 DBG(debug("received packet type %d", type));
1399 switch (type) {
1400 case SSH2_MSG_IGNORE:
1401 debug3("Received SSH2_MSG_IGNORE");
1402 break;
1403 case SSH2_MSG_DEBUG:
1404 packet_get_char();
1405 msg = packet_get_string(NULL);
1406 debug("Remote: %.900s", msg);
1407 xfree(msg);
1408 msg = packet_get_string(NULL);
1409 xfree(msg);
1410 break;
1411 case SSH2_MSG_DISCONNECT:
1412 reason = packet_get_int();
1413 msg = packet_get_string(NULL);
1414 logit("Received disconnect from %s: %u: %.400s",
1415 get_remote_ipaddr(), reason, msg);
1416 xfree(msg);
1417 cleanup_exit(255);
1418 break;
1419 case SSH2_MSG_UNIMPLEMENTED:
1420 seqnr = packet_get_int();
1421 debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1422 seqnr);
1423 break;
1424 default:
1425 return type;
1427 } else {
1428 type = packet_read_poll1();
1429 switch (type) {
1430 case SSH_MSG_IGNORE:
1431 break;
1432 case SSH_MSG_DEBUG:
1433 msg = packet_get_string(NULL);
1434 debug("Remote: %.900s", msg);
1435 xfree(msg);
1436 break;
1437 case SSH_MSG_DISCONNECT:
1438 msg = packet_get_string(NULL);
1439 logit("Received disconnect from %s: %.400s",
1440 get_remote_ipaddr(), msg);
1441 cleanup_exit(255);
1442 break;
1443 default:
1444 if (type)
1445 DBG(debug("received packet type %d", type));
1446 return type;
1453 packet_read_poll(void)
1455 return packet_read_poll_seqnr(NULL);
1459 * Buffers the given amount of input characters. This is intended to be used
1460 * together with packet_read_poll.
1463 void
1464 packet_process_incoming(const char *buf, u_int len)
1466 if (active_state->packet_discard) {
1467 active_state->keep_alive_timeouts = 0; /* ?? */
1468 if (len >= active_state->packet_discard)
1469 packet_stop_discard();
1470 active_state->packet_discard -= len;
1471 return;
1473 buffer_append(&active_state->input, buf, len);
1476 /* Returns a character from the packet. */
1478 u_int
1479 packet_get_char(void)
1481 char ch;
1483 buffer_get(&active_state->incoming_packet, &ch, 1);
1484 return (u_char) ch;
1487 /* Returns an integer from the packet data. */
1489 u_int
1490 packet_get_int(void)
1492 return buffer_get_int(&active_state->incoming_packet);
1495 /* Returns an 64 bit integer from the packet data. */
1497 u_int64_t
1498 packet_get_int64(void)
1500 return buffer_get_int64(&active_state->incoming_packet);
1504 * Returns an arbitrary precision integer from the packet data. The integer
1505 * must have been initialized before this call.
1508 void
1509 packet_get_bignum(BIGNUM * value)
1511 buffer_get_bignum(&active_state->incoming_packet, value);
1514 void
1515 packet_get_bignum2(BIGNUM * value)
1517 buffer_get_bignum2(&active_state->incoming_packet, value);
1520 void
1521 packet_get_ecpoint(const EC_GROUP *curve, EC_POINT *point)
1523 buffer_get_ecpoint(&active_state->incoming_packet, curve, point);
1526 void *
1527 packet_get_raw(u_int *length_ptr)
1529 u_int bytes = buffer_len(&active_state->incoming_packet);
1531 if (length_ptr != NULL)
1532 *length_ptr = bytes;
1533 return buffer_ptr(&active_state->incoming_packet);
1537 packet_remaining(void)
1539 return buffer_len(&active_state->incoming_packet);
1543 * Returns a string from the packet data. The string is allocated using
1544 * xmalloc; it is the responsibility of the calling program to free it when
1545 * no longer needed. The length_ptr argument may be NULL, or point to an
1546 * integer into which the length of the string is stored.
1549 void *
1550 packet_get_string(u_int *length_ptr)
1552 return buffer_get_string(&active_state->incoming_packet, length_ptr);
1555 void *
1556 packet_get_string_ptr(u_int *length_ptr)
1558 return buffer_get_string_ptr(&active_state->incoming_packet, length_ptr);
1561 /* Ensures the returned string has no embedded \0 characters in it. */
1562 char *
1563 packet_get_cstring(u_int *length_ptr)
1565 return buffer_get_cstring(&active_state->incoming_packet, length_ptr);
1569 * Sends a diagnostic message from the server to the client. This message
1570 * can be sent at any time (but not while constructing another message). The
1571 * message is printed immediately, but only if the client is being executed
1572 * in verbose mode. These messages are primarily intended to ease debugging
1573 * authentication problems. The length of the formatted message must not
1574 * exceed 1024 bytes. This will automatically call packet_write_wait.
1577 void
1578 packet_send_debug(const char *fmt,...)
1580 char buf[1024];
1581 va_list args;
1583 if (compat20 && (datafellows & SSH_BUG_DEBUG))
1584 return;
1586 va_start(args, fmt);
1587 vsnprintf(buf, sizeof(buf), fmt, args);
1588 va_end(args);
1590 if (compat20) {
1591 packet_start(SSH2_MSG_DEBUG);
1592 packet_put_char(0); /* bool: always display */
1593 packet_put_cstring(buf);
1594 packet_put_cstring("");
1595 } else {
1596 packet_start(SSH_MSG_DEBUG);
1597 packet_put_cstring(buf);
1599 packet_send();
1600 packet_write_wait();
1604 * Logs the error plus constructs and sends a disconnect packet, closes the
1605 * connection, and exits. This function never returns. The error message
1606 * should not contain a newline. The length of the formatted message must
1607 * not exceed 1024 bytes.
1610 void
1611 packet_disconnect(const char *fmt,...)
1613 char buf[1024];
1614 va_list args;
1615 static int disconnecting = 0;
1617 if (disconnecting) /* Guard against recursive invocations. */
1618 fatal("packet_disconnect called recursively.");
1619 disconnecting = 1;
1622 * Format the message. Note that the caller must make sure the
1623 * message is of limited size.
1625 va_start(args, fmt);
1626 vsnprintf(buf, sizeof(buf), fmt, args);
1627 va_end(args);
1629 /* Display the error locally */
1630 logit("Disconnecting: %.100s", buf);
1632 /* Send the disconnect message to the other side, and wait for it to get sent. */
1633 if (compat20) {
1634 packet_start(SSH2_MSG_DISCONNECT);
1635 packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1636 packet_put_cstring(buf);
1637 packet_put_cstring("");
1638 } else {
1639 packet_start(SSH_MSG_DISCONNECT);
1640 packet_put_cstring(buf);
1642 packet_send();
1643 packet_write_wait();
1645 /* Stop listening for connections. */
1646 channel_close_all();
1648 /* Close the connection. */
1649 packet_close();
1650 cleanup_exit(255);
1653 /* Checks if there is any buffered output, and tries to write some of the output. */
1655 void
1656 packet_write_poll(void)
1658 int len = buffer_len(&active_state->output);
1659 int cont;
1661 if (len > 0) {
1662 cont = 0;
1663 len = roaming_write(active_state->connection_out,
1664 buffer_ptr(&active_state->output), len, &cont);
1665 if (len == -1) {
1666 if (errno == EINTR || errno == EAGAIN ||
1667 errno == EWOULDBLOCK)
1668 return;
1669 fatal("Write failed: %.100s", strerror(errno));
1671 if (len == 0 && !cont)
1672 fatal("Write connection closed");
1673 buffer_consume(&active_state->output, len);
1678 * Calls packet_write_poll repeatedly until all pending output data has been
1679 * written.
1682 void
1683 packet_write_wait(void)
1685 fd_set *setp;
1686 int ret, ms_remain;
1687 struct timeval start, timeout, *timeoutp = NULL;
1689 setp = (fd_set *)xcalloc(howmany(active_state->connection_out + 1,
1690 NFDBITS), sizeof(fd_mask));
1691 packet_write_poll();
1692 while (packet_have_data_to_write()) {
1693 memset(setp, 0, howmany(active_state->connection_out + 1,
1694 NFDBITS) * sizeof(fd_mask));
1695 FD_SET(active_state->connection_out, setp);
1697 if (active_state->packet_timeout_ms > 0) {
1698 ms_remain = active_state->packet_timeout_ms;
1699 timeoutp = &timeout;
1701 for (;;) {
1702 if (active_state->packet_timeout_ms != -1) {
1703 ms_to_timeval(&timeout, ms_remain);
1704 gettimeofday(&start, NULL);
1706 if ((ret = select(active_state->connection_out + 1,
1707 NULL, setp, NULL, timeoutp)) >= 0)
1708 break;
1709 if (errno != EAGAIN && errno != EINTR &&
1710 errno != EWOULDBLOCK)
1711 break;
1712 if (active_state->packet_timeout_ms == -1)
1713 continue;
1714 ms_subtract_diff(&start, &ms_remain);
1715 if (ms_remain <= 0) {
1716 ret = 0;
1717 break;
1720 if (ret == 0) {
1721 logit("Connection to %.200s timed out while "
1722 "waiting to write", get_remote_ipaddr());
1723 cleanup_exit(255);
1725 packet_write_poll();
1727 xfree(setp);
1730 /* Returns true if there is buffered data to write to the connection. */
1733 packet_have_data_to_write(void)
1735 return buffer_len(&active_state->output) != 0;
1738 /* Returns true if there is not too much data to write to the connection. */
1741 packet_not_very_much_data_to_write(void)
1743 if (active_state->interactive_mode)
1744 return buffer_len(&active_state->output) < 16384;
1745 else
1746 return buffer_len(&active_state->output) < 128 * 1024;
1749 static void
1750 packet_set_tos(int interactive)
1752 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1753 int tos = interactive ? IPTOS_LOWDELAY : IPTOS_THROUGHPUT;
1755 if (!packet_connection_is_on_socket() ||
1756 !packet_connection_is_ipv4())
1757 return;
1758 if (setsockopt(active_state->connection_in, IPPROTO_IP, IP_TOS, &tos,
1759 sizeof(tos)) < 0)
1760 error("setsockopt IP_TOS %d: %.100s:",
1761 tos, strerror(errno));
1762 #endif
1765 /* Informs that the current session is interactive. Sets IP flags for that. */
1767 void
1768 packet_set_interactive(int interactive)
1770 if (active_state->set_interactive_called)
1771 return;
1772 active_state->set_interactive_called = 1;
1774 /* Record that we are in interactive mode. */
1775 active_state->interactive_mode = interactive;
1777 /* Only set socket options if using a socket. */
1778 if (!packet_connection_is_on_socket())
1779 return;
1780 set_nodelay(active_state->connection_in);
1781 packet_set_tos(interactive);
1784 /* Returns true if the current connection is interactive. */
1787 packet_is_interactive(void)
1789 return active_state->interactive_mode;
1793 packet_set_maxsize(u_int s)
1795 if (active_state->set_maxsize_called) {
1796 logit("packet_set_maxsize: called twice: old %d new %d",
1797 active_state->max_packet_size, s);
1798 return -1;
1800 if (s < 4 * 1024 || s > 1024 * 1024) {
1801 logit("packet_set_maxsize: bad size %d", s);
1802 return -1;
1804 active_state->set_maxsize_called = 1;
1805 debug("packet_set_maxsize: setting to %d", s);
1806 active_state->max_packet_size = s;
1807 return s;
1811 packet_inc_alive_timeouts(void)
1813 return ++active_state->keep_alive_timeouts;
1816 void
1817 packet_set_alive_timeouts(int ka)
1819 active_state->keep_alive_timeouts = ka;
1822 u_int
1823 packet_get_maxsize(void)
1825 return active_state->max_packet_size;
1828 /* roundup current message to pad bytes */
1829 void
1830 packet_add_padding(u_char pad)
1832 active_state->extra_pad = pad;
1836 * 9.2. Ignored Data Message
1838 * byte SSH_MSG_IGNORE
1839 * string data
1841 * All implementations MUST understand (and ignore) this message at any
1842 * time (after receiving the protocol version). No implementation is
1843 * required to send them. This message can be used as an additional
1844 * protection measure against advanced traffic analysis techniques.
1846 void
1847 packet_send_ignore(int nbytes)
1849 u_int32_t rnd = 0;
1850 int i;
1852 packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1853 packet_put_int(nbytes);
1854 for (i = 0; i < nbytes; i++) {
1855 if (i % 4 == 0)
1856 rnd = arc4random();
1857 packet_put_char((u_char)rnd & 0xff);
1858 rnd >>= 8;
1862 #define MAX_PACKETS (1U<<31)
1864 packet_need_rekeying(void)
1866 if (datafellows & SSH_BUG_NOREKEY)
1867 return 0;
1868 return
1869 (active_state->p_send.packets > MAX_PACKETS) ||
1870 (active_state->p_read.packets > MAX_PACKETS) ||
1871 (active_state->max_blocks_out &&
1872 (active_state->p_send.blocks > active_state->max_blocks_out)) ||
1873 (active_state->max_blocks_in &&
1874 (active_state->p_read.blocks > active_state->max_blocks_in));
1877 void
1878 packet_set_rekey_limit(u_int32_t bytes)
1880 active_state->rekey_limit = bytes;
1883 void
1884 packet_set_server(void)
1886 active_state->server_side = 1;
1889 void
1890 packet_set_authenticated(void)
1892 active_state->after_authentication = 1;
1895 void *
1896 packet_get_input(void)
1898 return (void *)&active_state->input;
1901 void *
1902 packet_get_output(void)
1904 return (void *)&active_state->output;
1907 void *
1908 packet_get_newkeys(int mode)
1910 return (void *)active_state->newkeys[mode];
1914 * Save the state for the real connection, and use a separate state when
1915 * resuming a suspended connection.
1917 void
1918 packet_backup_state(void)
1920 struct session_state *tmp;
1922 close(active_state->connection_in);
1923 active_state->connection_in = -1;
1924 close(active_state->connection_out);
1925 active_state->connection_out = -1;
1926 if (backup_state)
1927 tmp = backup_state;
1928 else
1929 tmp = alloc_session_state();
1930 backup_state = active_state;
1931 active_state = tmp;
1935 * Swap in the old state when resuming a connecion.
1937 void
1938 packet_restore_state(void)
1940 struct session_state *tmp;
1941 void *buf;
1942 u_int len;
1944 tmp = backup_state;
1945 backup_state = active_state;
1946 active_state = tmp;
1947 active_state->connection_in = backup_state->connection_in;
1948 backup_state->connection_in = -1;
1949 active_state->connection_out = backup_state->connection_out;
1950 backup_state->connection_out = -1;
1951 len = buffer_len(&backup_state->input);
1952 if (len > 0) {
1953 buf = buffer_ptr(&backup_state->input);
1954 buffer_append(&active_state->input, buf, len);
1955 buffer_clear(&backup_state->input);
1956 add_recv_bytes(len);