No empty .Rs/.Re
[netbsd-mini2440.git] / crypto / external / bsd / openssh / dist / packet.c
blob1297b74b97594335049c04458c058f1a1d20322b
1 /* $NetBSD: packet.c,v 1.1.1.2 2009/12/27 01:07:01 christos Exp $ */
2 /* $OpenBSD: packet.c,v 1.166 2009/06/27 09:29:06 andreas Exp $ */
3 /*
4 * Author: Tatu Ylonen <ylo@cs.hut.fi>
5 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * All rights reserved
7 * This file contains code implementing the packet protocol and communication
8 * with the other side. This same code is used both on client and server side.
10 * As far as I am concerned, the code I have written for this software
11 * can be used freely for any purpose. Any derived versions of this
12 * software must be clearly marked as such, and if the derived work is
13 * incompatible with the protocol description in the RFC file, it must be
14 * called by a name other than "ssh" or "Secure Shell".
17 * SSH2 packet format added by Markus Friedl.
18 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
20 * Redistribution and use in source and binary forms, with or without
21 * modification, are permitted provided that the following conditions
22 * are met:
23 * 1. Redistributions of source code must retain the above copyright
24 * notice, this list of conditions and the following disclaimer.
25 * 2. Redistributions in binary form must reproduce the above copyright
26 * notice, this list of conditions and the following disclaimer in the
27 * documentation and/or other materials provided with the distribution.
29 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
30 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
31 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
32 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
33 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
34 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
38 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
41 #include "includes.h"
42 __RCSID("$NetBSD: packet.c,v 1.2 2009/06/07 22:38:47 christos Exp $");
43 #include <sys/types.h>
44 #include <sys/queue.h>
45 #include <sys/socket.h>
46 #include <sys/time.h>
47 #include <sys/param.h>
49 #include <netinet/in_systm.h>
50 #include <netinet/in.h>
51 #include <netinet/ip.h>
53 #include <errno.h>
54 #include <stdarg.h>
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <string.h>
58 #include <unistd.h>
59 #include <signal.h>
61 #include "xmalloc.h"
62 #include "buffer.h"
63 #include "packet.h"
64 #include "crc32.h"
65 #include "compress.h"
66 #include "deattack.h"
67 #include "channels.h"
68 #include "compat.h"
69 #include "ssh1.h"
70 #include "ssh2.h"
71 #include "cipher.h"
72 #include "key.h"
73 #include "kex.h"
74 #include "mac.h"
75 #include "log.h"
76 #include "canohost.h"
77 #include "misc.h"
78 #include "ssh.h"
79 #include "roaming.h"
81 #ifdef PACKET_DEBUG
82 #define DBG(x) x
83 #else
84 #define DBG(x)
85 #endif
87 #define PACKET_MAX_SIZE (256 * 1024)
89 struct packet_state {
90 u_int32_t seqnr;
91 u_int32_t packets;
92 u_int64_t blocks;
93 u_int64_t bytes;
96 struct packet {
97 TAILQ_ENTRY(packet) next;
98 u_char type;
99 Buffer payload;
102 struct session_state {
104 * This variable contains the file descriptors used for
105 * communicating with the other side. connection_in is used for
106 * reading; connection_out for writing. These can be the same
107 * descriptor, in which case it is assumed to be a socket.
109 int connection_in;
110 int connection_out;
112 /* Protocol flags for the remote side. */
113 u_int remote_protocol_flags;
115 /* Encryption context for receiving data. Only used for decryption. */
116 CipherContext receive_context;
118 /* Encryption context for sending data. Only used for encryption. */
119 CipherContext send_context;
121 /* Buffer for raw input data from the socket. */
122 Buffer input;
124 /* Buffer for raw output data going to the socket. */
125 Buffer output;
127 /* Buffer for the partial outgoing packet being constructed. */
128 Buffer outgoing_packet;
130 /* Buffer for the incoming packet currently being processed. */
131 Buffer incoming_packet;
133 /* Scratch buffer for packet compression/decompression. */
134 Buffer compression_buffer;
135 int compression_buffer_ready;
138 * Flag indicating whether packet compression/decompression is
139 * enabled.
141 int packet_compression;
143 /* default maximum packet size */
144 u_int max_packet_size;
146 /* Flag indicating whether this module has been initialized. */
147 int initialized;
149 /* Set to true if the connection is interactive. */
150 int interactive_mode;
152 /* Set to true if we are the server side. */
153 int server_side;
155 /* Set to true if we are authenticated. */
156 int after_authentication;
158 int keep_alive_timeouts;
160 /* The maximum time that we will wait to send or receive a packet */
161 int packet_timeout_ms;
163 /* Session key information for Encryption and MAC */
164 Newkeys *newkeys[MODE_MAX];
165 struct packet_state p_read, p_send;
167 u_int64_t max_blocks_in, max_blocks_out;
168 u_int32_t rekey_limit;
170 /* Session key for protocol v1 */
171 u_char ssh1_key[SSH_SESSION_KEY_LENGTH];
172 u_int ssh1_keylen;
174 /* roundup current message to extra_pad bytes */
175 u_char extra_pad;
177 /* XXX discard incoming data after MAC error */
178 u_int packet_discard;
179 Mac *packet_discard_mac;
181 /* Used in packet_read_poll2() */
182 u_int packlen;
184 /* Used in packet_send2 */
185 int rekeying;
187 /* Used in packet_set_interactive */
188 int set_interactive_called;
190 /* Used in packet_set_maxsize */
191 int set_maxsize_called;
193 TAILQ_HEAD(, packet) outgoing;
196 static struct session_state *active_state, *backup_state;
198 static struct session_state *
199 alloc_session_state(void)
201 struct session_state *s = xcalloc(1, sizeof(*s));
203 s->connection_in = -1;
204 s->connection_out = -1;
205 s->max_packet_size = 32768;
206 s->packet_timeout_ms = -1;
207 return s;
211 * Sets the descriptors used for communication. Disables encryption until
212 * packet_set_encryption_key is called.
214 void
215 packet_set_connection(int fd_in, int fd_out)
217 Cipher *none = cipher_by_name("none");
219 if (none == NULL)
220 fatal("packet_set_connection: cannot load cipher 'none'");
221 if (active_state == NULL)
222 active_state = alloc_session_state();
223 active_state->connection_in = fd_in;
224 active_state->connection_out = fd_out;
225 cipher_init(&active_state->send_context, none, (const u_char *)"",
226 0, NULL, 0, CIPHER_ENCRYPT);
227 cipher_init(&active_state->receive_context, none, (const u_char *)"",
228 0, NULL, 0, CIPHER_DECRYPT);
229 active_state->newkeys[MODE_IN] = active_state->newkeys[MODE_OUT] = NULL;
230 if (!active_state->initialized) {
231 active_state->initialized = 1;
232 buffer_init(&active_state->input);
233 buffer_init(&active_state->output);
234 buffer_init(&active_state->outgoing_packet);
235 buffer_init(&active_state->incoming_packet);
236 TAILQ_INIT(&active_state->outgoing);
237 active_state->p_send.packets = active_state->p_read.packets = 0;
241 void
242 packet_set_timeout(int timeout, int count)
244 if (timeout == 0 || count == 0) {
245 active_state->packet_timeout_ms = -1;
246 return;
248 if ((INT_MAX / 1000) / count < timeout)
249 active_state->packet_timeout_ms = INT_MAX;
250 else
251 active_state->packet_timeout_ms = timeout * count * 1000;
254 static void
255 packet_stop_discard(void)
257 if (active_state->packet_discard_mac) {
258 char buf[1024];
260 memset(buf, 'a', sizeof(buf));
261 while (buffer_len(&active_state->incoming_packet) <
262 PACKET_MAX_SIZE)
263 buffer_append(&active_state->incoming_packet, buf,
264 sizeof(buf));
265 (void) mac_compute(active_state->packet_discard_mac,
266 active_state->p_read.seqnr,
267 buffer_ptr(&active_state->incoming_packet),
268 PACKET_MAX_SIZE);
270 logit("Finished discarding for %.200s", get_remote_ipaddr());
271 cleanup_exit(255);
274 static void
275 packet_start_discard(Enc *enc, Mac *mac, u_int packet_length, u_int discard)
277 if (enc == NULL || !cipher_is_cbc(enc->cipher))
278 packet_disconnect("Packet corrupt");
279 if (packet_length != PACKET_MAX_SIZE && mac && mac->enabled)
280 active_state->packet_discard_mac = mac;
281 if (buffer_len(&active_state->input) >= discard)
282 packet_stop_discard();
283 active_state->packet_discard = discard -
284 buffer_len(&active_state->input);
287 /* Returns 1 if remote host is connected via socket, 0 if not. */
290 packet_connection_is_on_socket(void)
292 struct sockaddr_storage from, to;
293 socklen_t fromlen, tolen;
295 /* filedescriptors in and out are the same, so it's a socket */
296 if (active_state->connection_in == active_state->connection_out)
297 return 1;
298 fromlen = sizeof(from);
299 memset(&from, 0, sizeof(from));
300 if (getpeername(active_state->connection_in, (struct sockaddr *)&from,
301 &fromlen) < 0)
302 return 0;
303 tolen = sizeof(to);
304 memset(&to, 0, sizeof(to));
305 if (getpeername(active_state->connection_out, (struct sockaddr *)&to,
306 &tolen) < 0)
307 return 0;
308 if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
309 return 0;
310 if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
311 return 0;
312 return 1;
316 * Exports an IV from the CipherContext required to export the key
317 * state back from the unprivileged child to the privileged parent
318 * process.
321 void
322 packet_get_keyiv(int mode, u_char *iv, u_int len)
324 CipherContext *cc;
326 if (mode == MODE_OUT)
327 cc = &active_state->send_context;
328 else
329 cc = &active_state->receive_context;
331 cipher_get_keyiv(cc, iv, len);
335 packet_get_keycontext(int mode, u_char *dat)
337 CipherContext *cc;
339 if (mode == MODE_OUT)
340 cc = &active_state->send_context;
341 else
342 cc = &active_state->receive_context;
344 return (cipher_get_keycontext(cc, dat));
347 void
348 packet_set_keycontext(int mode, u_char *dat)
350 CipherContext *cc;
352 if (mode == MODE_OUT)
353 cc = &active_state->send_context;
354 else
355 cc = &active_state->receive_context;
357 cipher_set_keycontext(cc, dat);
361 packet_get_keyiv_len(int mode)
363 CipherContext *cc;
365 if (mode == MODE_OUT)
366 cc = &active_state->send_context;
367 else
368 cc = &active_state->receive_context;
370 return (cipher_get_keyiv_len(cc));
373 void
374 packet_set_iv(int mode, u_char *dat)
376 CipherContext *cc;
378 if (mode == MODE_OUT)
379 cc = &active_state->send_context;
380 else
381 cc = &active_state->receive_context;
383 cipher_set_keyiv(cc, dat);
387 packet_get_ssh1_cipher(void)
389 return (cipher_get_number(active_state->receive_context.cipher));
392 void
393 packet_get_state(int mode, u_int32_t *seqnr, u_int64_t *blocks, u_int32_t *packets,
394 u_int64_t *bytes)
396 struct packet_state *state;
398 state = (mode == MODE_IN) ?
399 &active_state->p_read : &active_state->p_send;
400 if (seqnr)
401 *seqnr = state->seqnr;
402 if (blocks)
403 *blocks = state->blocks;
404 if (packets)
405 *packets = state->packets;
406 if (bytes)
407 *bytes = state->bytes;
410 void
411 packet_set_state(int mode, u_int32_t seqnr, u_int64_t blocks, u_int32_t packets,
412 u_int64_t bytes)
414 struct packet_state *state;
416 state = (mode == MODE_IN) ?
417 &active_state->p_read : &active_state->p_send;
418 state->seqnr = seqnr;
419 state->blocks = blocks;
420 state->packets = packets;
421 state->bytes = bytes;
424 /* returns 1 if connection is via ipv4 */
427 packet_connection_is_ipv4(void)
429 struct sockaddr_storage to;
430 socklen_t tolen = sizeof(to);
432 memset(&to, 0, sizeof(to));
433 if (getsockname(active_state->connection_out, (struct sockaddr *)&to,
434 &tolen) < 0)
435 return 0;
436 if (to.ss_family != AF_INET)
437 return 0;
438 return 1;
441 /* Sets the connection into non-blocking mode. */
443 void
444 packet_set_nonblocking(void)
446 /* Set the socket into non-blocking mode. */
447 set_nonblock(active_state->connection_in);
449 if (active_state->connection_out != active_state->connection_in)
450 set_nonblock(active_state->connection_out);
453 /* Returns the socket used for reading. */
456 packet_get_connection_in(void)
458 return active_state->connection_in;
461 /* Returns the descriptor used for writing. */
464 packet_get_connection_out(void)
466 return active_state->connection_out;
469 /* Closes the connection and clears and frees internal data structures. */
471 void
472 packet_close(void)
474 if (!active_state->initialized)
475 return;
476 active_state->initialized = 0;
477 if (active_state->connection_in == active_state->connection_out) {
478 shutdown(active_state->connection_out, SHUT_RDWR);
479 close(active_state->connection_out);
480 } else {
481 close(active_state->connection_in);
482 close(active_state->connection_out);
484 buffer_free(&active_state->input);
485 buffer_free(&active_state->output);
486 buffer_free(&active_state->outgoing_packet);
487 buffer_free(&active_state->incoming_packet);
488 if (active_state->compression_buffer_ready) {
489 buffer_free(&active_state->compression_buffer);
490 buffer_compress_uninit();
492 cipher_cleanup(&active_state->send_context);
493 cipher_cleanup(&active_state->receive_context);
496 /* Sets remote side protocol flags. */
498 void
499 packet_set_protocol_flags(u_int protocol_flags)
501 active_state->remote_protocol_flags = protocol_flags;
504 /* Returns the remote protocol flags set earlier by the above function. */
506 u_int
507 packet_get_protocol_flags(void)
509 return active_state->remote_protocol_flags;
513 * Starts packet compression from the next packet on in both directions.
514 * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
517 static void
518 packet_init_compression(void)
520 if (active_state->compression_buffer_ready == 1)
521 return;
522 active_state->compression_buffer_ready = 1;
523 buffer_init(&active_state->compression_buffer);
526 void
527 packet_start_compression(int level)
529 if (active_state->packet_compression && !compat20)
530 fatal("Compression already enabled.");
531 active_state->packet_compression = 1;
532 packet_init_compression();
533 buffer_compress_init_send(level);
534 buffer_compress_init_recv();
538 * Causes any further packets to be encrypted using the given key. The same
539 * key is used for both sending and reception. However, both directions are
540 * encrypted independently of each other.
543 void
544 packet_set_encryption_key(const u_char *key, u_int keylen,
545 int number)
547 Cipher *cipher = cipher_by_number(number);
549 if (cipher == NULL)
550 fatal("packet_set_encryption_key: unknown cipher number %d", number);
551 if (keylen < 20)
552 fatal("packet_set_encryption_key: keylen too small: %d", keylen);
553 if (keylen > SSH_SESSION_KEY_LENGTH)
554 fatal("packet_set_encryption_key: keylen too big: %d", keylen);
555 memcpy(active_state->ssh1_key, key, keylen);
556 active_state->ssh1_keylen = keylen;
557 cipher_init(&active_state->send_context, cipher, key, keylen, NULL,
558 0, CIPHER_ENCRYPT);
559 cipher_init(&active_state->receive_context, cipher, key, keylen, NULL,
560 0, CIPHER_DECRYPT);
563 u_int
564 packet_get_encryption_key(u_char *key)
566 if (key == NULL)
567 return (active_state->ssh1_keylen);
568 memcpy(key, active_state->ssh1_key, active_state->ssh1_keylen);
569 return (active_state->ssh1_keylen);
572 /* Start constructing a packet to send. */
573 void
574 packet_start(u_char type)
576 u_char buf[9];
577 int len;
579 DBG(debug("packet_start[%d]", type));
580 len = compat20 ? 6 : 9;
581 memset(buf, 0, len - 1);
582 buf[len - 1] = type;
583 buffer_clear(&active_state->outgoing_packet);
584 buffer_append(&active_state->outgoing_packet, buf, len);
587 /* Append payload. */
588 void
589 packet_put_char(int value)
591 char ch = value;
593 buffer_append(&active_state->outgoing_packet, &ch, 1);
596 void
597 packet_put_int(u_int value)
599 buffer_put_int(&active_state->outgoing_packet, value);
602 void
603 packet_put_int64(u_int64_t value)
605 buffer_put_int64(&active_state->outgoing_packet, value);
608 void
609 packet_put_string(const void *buf, u_int len)
611 buffer_put_string(&active_state->outgoing_packet, buf, len);
614 void
615 packet_put_cstring(const char *str)
617 buffer_put_cstring(&active_state->outgoing_packet, str);
620 void
621 packet_put_raw(const void *buf, u_int len)
623 buffer_append(&active_state->outgoing_packet, buf, len);
626 void
627 packet_put_bignum(BIGNUM * value)
629 buffer_put_bignum(&active_state->outgoing_packet, value);
632 void
633 packet_put_bignum2(BIGNUM * value)
635 buffer_put_bignum2(&active_state->outgoing_packet, value);
639 * Finalizes and sends the packet. If the encryption key has been set,
640 * encrypts the packet before sending.
643 static void
644 packet_send1(void)
646 u_char buf[8], *cp;
647 int i, padding, len;
648 u_int checksum;
649 u_int32_t rnd = 0;
652 * If using packet compression, compress the payload of the outgoing
653 * packet.
655 if (active_state->packet_compression) {
656 buffer_clear(&active_state->compression_buffer);
657 /* Skip padding. */
658 buffer_consume(&active_state->outgoing_packet, 8);
659 /* padding */
660 buffer_append(&active_state->compression_buffer,
661 "\0\0\0\0\0\0\0\0", 8);
662 buffer_compress(&active_state->outgoing_packet,
663 &active_state->compression_buffer);
664 buffer_clear(&active_state->outgoing_packet);
665 buffer_append(&active_state->outgoing_packet,
666 buffer_ptr(&active_state->compression_buffer),
667 buffer_len(&active_state->compression_buffer));
669 /* Compute packet length without padding (add checksum, remove padding). */
670 len = buffer_len(&active_state->outgoing_packet) + 4 - 8;
672 /* Insert padding. Initialized to zero in packet_start1() */
673 padding = 8 - len % 8;
674 if (!active_state->send_context.plaintext) {
675 cp = buffer_ptr(&active_state->outgoing_packet);
676 for (i = 0; i < padding; i++) {
677 if (i % 4 == 0)
678 rnd = arc4random();
679 cp[7 - i] = rnd & 0xff;
680 rnd >>= 8;
683 buffer_consume(&active_state->outgoing_packet, 8 - padding);
685 /* Add check bytes. */
686 checksum = ssh_crc32(buffer_ptr(&active_state->outgoing_packet),
687 buffer_len(&active_state->outgoing_packet));
688 put_u32(buf, checksum);
689 buffer_append(&active_state->outgoing_packet, buf, 4);
691 #ifdef PACKET_DEBUG
692 fprintf(stderr, "packet_send plain: ");
693 buffer_dump(&active_state->outgoing_packet);
694 #endif
696 /* Append to output. */
697 put_u32(buf, len);
698 buffer_append(&active_state->output, buf, 4);
699 cp = buffer_append_space(&active_state->output,
700 buffer_len(&active_state->outgoing_packet));
701 cipher_crypt(&active_state->send_context, cp,
702 buffer_ptr(&active_state->outgoing_packet),
703 buffer_len(&active_state->outgoing_packet));
705 #ifdef PACKET_DEBUG
706 fprintf(stderr, "encrypted: ");
707 buffer_dump(&active_state->output);
708 #endif
709 active_state->p_send.packets++;
710 active_state->p_send.bytes += len +
711 buffer_len(&active_state->outgoing_packet);
712 buffer_clear(&active_state->outgoing_packet);
715 * Note that the packet is now only buffered in output. It won't be
716 * actually sent until packet_write_wait or packet_write_poll is
717 * called.
721 void
722 set_newkeys(int mode)
724 Enc *enc;
725 Mac *mac;
726 Comp *comp;
727 CipherContext *cc;
728 u_int64_t *max_blocks;
729 int crypt_type;
731 debug2("set_newkeys: mode %d", mode);
733 if (mode == MODE_OUT) {
734 cc = &active_state->send_context;
735 crypt_type = CIPHER_ENCRYPT;
736 active_state->p_send.packets = active_state->p_send.blocks = 0;
737 max_blocks = &active_state->max_blocks_out;
738 } else {
739 cc = &active_state->receive_context;
740 crypt_type = CIPHER_DECRYPT;
741 active_state->p_read.packets = active_state->p_read.blocks = 0;
742 max_blocks = &active_state->max_blocks_in;
744 if (active_state->newkeys[mode] != NULL) {
745 debug("set_newkeys: rekeying");
746 cipher_cleanup(cc);
747 enc = &active_state->newkeys[mode]->enc;
748 mac = &active_state->newkeys[mode]->mac;
749 comp = &active_state->newkeys[mode]->comp;
750 mac_clear(mac);
751 xfree(enc->name);
752 xfree(enc->iv);
753 xfree(enc->key);
754 xfree(mac->name);
755 xfree(mac->key);
756 xfree(comp->name);
757 xfree(active_state->newkeys[mode]);
759 active_state->newkeys[mode] = kex_get_newkeys(mode);
760 if (active_state->newkeys[mode] == NULL)
761 fatal("newkeys: no keys for mode %d", mode);
762 enc = &active_state->newkeys[mode]->enc;
763 mac = &active_state->newkeys[mode]->mac;
764 comp = &active_state->newkeys[mode]->comp;
765 if (mac_init(mac) == 0)
766 mac->enabled = 1;
767 DBG(debug("cipher_init_context: %d", mode));
768 cipher_init(cc, enc->cipher, enc->key, enc->key_len,
769 enc->iv, enc->block_size, crypt_type);
770 /* Deleting the keys does not gain extra security */
771 /* memset(enc->iv, 0, enc->block_size);
772 memset(enc->key, 0, enc->key_len);
773 memset(mac->key, 0, mac->key_len); */
774 if ((comp->type == COMP_ZLIB ||
775 (comp->type == COMP_DELAYED &&
776 active_state->after_authentication)) && comp->enabled == 0) {
777 packet_init_compression();
778 if (mode == MODE_OUT)
779 buffer_compress_init_send(6);
780 else
781 buffer_compress_init_recv();
782 comp->enabled = 1;
785 * The 2^(blocksize*2) limit is too expensive for 3DES,
786 * blowfish, etc, so enforce a 1GB limit for small blocksizes.
788 if (enc->block_size >= 16)
789 *max_blocks = (u_int64_t)1 << (enc->block_size*2);
790 else
791 *max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
792 if (active_state->rekey_limit)
793 *max_blocks = MIN(*max_blocks,
794 active_state->rekey_limit / enc->block_size);
798 * Delayed compression for SSH2 is enabled after authentication:
799 * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
800 * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
802 static void
803 packet_enable_delayed_compress(void)
805 Comp *comp = NULL;
806 int mode;
809 * Remember that we are past the authentication step, so rekeying
810 * with COMP_DELAYED will turn on compression immediately.
812 active_state->after_authentication = 1;
813 for (mode = 0; mode < MODE_MAX; mode++) {
814 /* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
815 if (active_state->newkeys[mode] == NULL)
816 continue;
817 comp = &active_state->newkeys[mode]->comp;
818 if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
819 packet_init_compression();
820 if (mode == MODE_OUT)
821 buffer_compress_init_send(6);
822 else
823 buffer_compress_init_recv();
824 comp->enabled = 1;
830 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
832 static int
833 packet_send2_wrapped(void)
835 u_char type, *cp, *macbuf = NULL;
836 u_char padlen, pad;
837 u_int packet_length = 0;
838 u_int i, len;
839 u_int32_t rnd = 0;
840 Enc *enc = NULL;
841 Mac *mac = NULL;
842 Comp *comp = NULL;
843 int block_size;
845 if (active_state->newkeys[MODE_OUT] != NULL) {
846 enc = &active_state->newkeys[MODE_OUT]->enc;
847 mac = &active_state->newkeys[MODE_OUT]->mac;
848 comp = &active_state->newkeys[MODE_OUT]->comp;
850 block_size = enc ? enc->block_size : 8;
852 cp = buffer_ptr(&active_state->outgoing_packet);
853 type = cp[5];
855 #ifdef PACKET_DEBUG
856 fprintf(stderr, "plain: ");
857 buffer_dump(&active_state->outgoing_packet);
858 #endif
860 if (comp && comp->enabled) {
861 len = buffer_len(&active_state->outgoing_packet);
862 /* skip header, compress only payload */
863 buffer_consume(&active_state->outgoing_packet, 5);
864 buffer_clear(&active_state->compression_buffer);
865 buffer_compress(&active_state->outgoing_packet,
866 &active_state->compression_buffer);
867 buffer_clear(&active_state->outgoing_packet);
868 buffer_append(&active_state->outgoing_packet, "\0\0\0\0\0", 5);
869 buffer_append(&active_state->outgoing_packet,
870 buffer_ptr(&active_state->compression_buffer),
871 buffer_len(&active_state->compression_buffer));
872 DBG(debug("compression: raw %d compressed %d", len,
873 buffer_len(&active_state->outgoing_packet)));
876 /* sizeof (packet_len + pad_len + payload) */
877 len = buffer_len(&active_state->outgoing_packet);
880 * calc size of padding, alloc space, get random data,
881 * minimum padding is 4 bytes
883 padlen = block_size - (len % block_size);
884 if (padlen < 4)
885 padlen += block_size;
886 if (active_state->extra_pad) {
887 /* will wrap if extra_pad+padlen > 255 */
888 active_state->extra_pad =
889 roundup(active_state->extra_pad, block_size);
890 pad = active_state->extra_pad -
891 ((len + padlen) % active_state->extra_pad);
892 debug3("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
893 pad, len, padlen, active_state->extra_pad);
894 padlen += pad;
895 active_state->extra_pad = 0;
897 cp = buffer_append_space(&active_state->outgoing_packet, padlen);
898 if (enc && !active_state->send_context.plaintext) {
899 /* random padding */
900 for (i = 0; i < padlen; i++) {
901 if (i % 4 == 0)
902 rnd = arc4random();
903 cp[i] = rnd & 0xff;
904 rnd >>= 8;
906 } else {
907 /* clear padding */
908 memset(cp, 0, padlen);
910 /* packet_length includes payload, padding and padding length field */
911 packet_length = buffer_len(&active_state->outgoing_packet) - 4;
912 cp = buffer_ptr(&active_state->outgoing_packet);
913 put_u32(cp, packet_length);
914 cp[4] = padlen;
915 DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen));
917 /* compute MAC over seqnr and packet(length fields, payload, padding) */
918 if (mac && mac->enabled) {
919 macbuf = mac_compute(mac, active_state->p_send.seqnr,
920 buffer_ptr(&active_state->outgoing_packet),
921 buffer_len(&active_state->outgoing_packet));
922 DBG(debug("done calc MAC out #%d", active_state->p_send.seqnr));
924 /* encrypt packet and append to output buffer. */
925 cp = buffer_append_space(&active_state->output,
926 buffer_len(&active_state->outgoing_packet));
927 cipher_crypt(&active_state->send_context, cp,
928 buffer_ptr(&active_state->outgoing_packet),
929 buffer_len(&active_state->outgoing_packet));
930 /* append unencrypted MAC */
931 if (mac && mac->enabled)
932 buffer_append(&active_state->output, macbuf, mac->mac_len);
933 #ifdef PACKET_DEBUG
934 fprintf(stderr, "encrypted: ");
935 buffer_dump(&active_state->output);
936 #endif
937 /* increment sequence number for outgoing packets */
938 if (++active_state->p_send.seqnr == 0)
939 logit("outgoing seqnr wraps around");
940 if (++active_state->p_send.packets == 0)
941 if (!(datafellows & SSH_BUG_NOREKEY))
942 fatal("XXX too many packets with same key");
943 active_state->p_send.blocks += (packet_length + 4) / block_size;
944 active_state->p_send.bytes += packet_length + 4;
945 buffer_clear(&active_state->outgoing_packet);
947 if (type == SSH2_MSG_NEWKEYS)
948 set_newkeys(MODE_OUT);
949 else if (type == SSH2_MSG_USERAUTH_SUCCESS && active_state->server_side)
950 packet_enable_delayed_compress();
951 return(packet_length);
954 static int
955 packet_send2(void)
957 int packet_length = 0;
958 struct packet *p;
959 u_char type, *cp;
961 cp = buffer_ptr(&active_state->outgoing_packet);
962 type = cp[5];
964 /* during rekeying we can only send key exchange messages */
965 if (active_state->rekeying) {
966 if (!((type >= SSH2_MSG_TRANSPORT_MIN) &&
967 (type <= SSH2_MSG_TRANSPORT_MAX))) {
968 debug("enqueue packet: %u", type);
969 p = xmalloc(sizeof(*p));
970 p->type = type;
971 memcpy(&p->payload, &active_state->outgoing_packet,
972 sizeof(Buffer));
973 buffer_init(&active_state->outgoing_packet);
974 TAILQ_INSERT_TAIL(&active_state->outgoing, p, next);
975 return(sizeof(Buffer));
979 /* rekeying starts with sending KEXINIT */
980 if (type == SSH2_MSG_KEXINIT)
981 active_state->rekeying = 1;
983 packet_length = packet_send2_wrapped();
985 /* after a NEWKEYS message we can send the complete queue */
986 if (type == SSH2_MSG_NEWKEYS) {
987 active_state->rekeying = 0;
988 while ((p = TAILQ_FIRST(&active_state->outgoing))) {
989 type = p->type;
990 debug("dequeue packet: %u", type);
991 buffer_free(&active_state->outgoing_packet);
992 memcpy(&active_state->outgoing_packet, &p->payload,
993 sizeof(Buffer));
994 TAILQ_REMOVE(&active_state->outgoing, p, next);
995 xfree(p);
996 packet_length += packet_send2_wrapped();
999 return(packet_length);
1003 packet_send(void)
1005 int packet_len = 0;
1006 if (compat20)
1007 packet_len = packet_send2();
1008 else
1009 packet_send1();
1010 DBG(debug("packet_send done"));
1011 return packet_len;
1015 * Waits until a packet has been received, and returns its type. Note that
1016 * no other data is processed until this returns, so this function should not
1017 * be used during the interactive session.
1021 packet_read_seqnr(u_int32_t *seqnr_p)
1023 int type, len, ret, ms_remain, cont;
1024 fd_set *setp;
1025 char buf[8192];
1026 struct timeval timeout, start, *timeoutp = NULL;
1028 DBG(debug("packet_read()"));
1030 setp = (fd_set *)xcalloc(howmany(active_state->connection_in + 1,
1031 NFDBITS), sizeof(fd_mask));
1033 /* Since we are blocking, ensure that all written packets have been sent. */
1034 packet_write_wait();
1036 /* Stay in the loop until we have received a complete packet. */
1037 for (;;) {
1038 /* Try to read a packet from the buffer. */
1039 type = packet_read_poll_seqnr(seqnr_p);
1040 if (!compat20 && (
1041 type == SSH_SMSG_SUCCESS
1042 || type == SSH_SMSG_FAILURE
1043 || type == SSH_CMSG_EOF
1044 || type == SSH_CMSG_EXIT_CONFIRMATION))
1045 packet_check_eom();
1046 /* If we got a packet, return it. */
1047 if (type != SSH_MSG_NONE) {
1048 xfree(setp);
1049 return type;
1052 * Otherwise, wait for some data to arrive, add it to the
1053 * buffer, and try again.
1055 memset(setp, 0, howmany(active_state->connection_in + 1,
1056 NFDBITS) * sizeof(fd_mask));
1057 FD_SET(active_state->connection_in, setp);
1059 if (active_state->packet_timeout_ms > 0) {
1060 ms_remain = active_state->packet_timeout_ms;
1061 timeoutp = &timeout;
1063 /* Wait for some data to arrive. */
1064 for (;;) {
1065 if (active_state->packet_timeout_ms != -1) {
1066 ms_to_timeval(&timeout, ms_remain);
1067 gettimeofday(&start, NULL);
1069 if ((ret = select(active_state->connection_in + 1, setp,
1070 NULL, NULL, timeoutp)) >= 0)
1071 break;
1072 if (errno != EAGAIN && errno != EINTR)
1073 break;
1074 if (active_state->packet_timeout_ms == -1)
1075 continue;
1076 ms_subtract_diff(&start, &ms_remain);
1077 if (ms_remain <= 0) {
1078 ret = 0;
1079 break;
1082 if (ret == 0) {
1083 logit("Connection to %.200s timed out while "
1084 "waiting to read", get_remote_ipaddr());
1085 cleanup_exit(255);
1087 /* Read data from the socket. */
1088 do {
1089 cont = 0;
1090 len = roaming_read(active_state->connection_in, buf,
1091 sizeof(buf), &cont);
1092 } while (len == 0 && cont);
1093 if (len == 0) {
1094 logit("Connection closed by %.200s", get_remote_ipaddr());
1095 cleanup_exit(255);
1097 if (len < 0)
1098 fatal("Read from socket failed: %.100s", strerror(errno));
1099 /* Append it to the buffer. */
1100 packet_process_incoming(buf, len);
1102 /* NOTREACHED */
1106 packet_read(void)
1108 return packet_read_seqnr(NULL);
1112 * Waits until a packet has been received, verifies that its type matches
1113 * that given, and gives a fatal error and exits if there is a mismatch.
1116 void
1117 packet_read_expect(int expected_type)
1119 int type;
1121 type = packet_read();
1122 if (type != expected_type)
1123 packet_disconnect("Protocol error: expected packet type %d, got %d",
1124 expected_type, type);
1127 /* Checks if a full packet is available in the data received so far via
1128 * packet_process_incoming. If so, reads the packet; otherwise returns
1129 * SSH_MSG_NONE. This does not wait for data from the connection.
1131 * SSH_MSG_DISCONNECT is handled specially here. Also,
1132 * SSH_MSG_IGNORE messages are skipped by this function and are never returned
1133 * to higher levels.
1136 static int
1137 packet_read_poll1(void)
1139 u_int len, padded_len;
1140 u_char *cp, type;
1141 u_int checksum, stored_checksum;
1143 /* Check if input size is less than minimum packet size. */
1144 if (buffer_len(&active_state->input) < 4 + 8)
1145 return SSH_MSG_NONE;
1146 /* Get length of incoming packet. */
1147 cp = buffer_ptr(&active_state->input);
1148 len = get_u32(cp);
1149 if (len < 1 + 2 + 2 || len > 256 * 1024)
1150 packet_disconnect("Bad packet length %u.", len);
1151 padded_len = (len + 8) & ~7;
1153 /* Check if the packet has been entirely received. */
1154 if (buffer_len(&active_state->input) < 4 + padded_len)
1155 return SSH_MSG_NONE;
1157 /* The entire packet is in buffer. */
1159 /* Consume packet length. */
1160 buffer_consume(&active_state->input, 4);
1163 * Cryptographic attack detector for ssh
1164 * (C)1998 CORE-SDI, Buenos Aires Argentina
1165 * Ariel Futoransky(futo@core-sdi.com)
1167 if (!active_state->receive_context.plaintext) {
1168 switch (detect_attack(buffer_ptr(&active_state->input),
1169 padded_len)) {
1170 case DEATTACK_DETECTED:
1171 packet_disconnect("crc32 compensation attack: "
1172 "network attack detected");
1173 case DEATTACK_DOS_DETECTED:
1174 packet_disconnect("deattack denial of "
1175 "service detected");
1179 /* Decrypt data to incoming_packet. */
1180 buffer_clear(&active_state->incoming_packet);
1181 cp = buffer_append_space(&active_state->incoming_packet, padded_len);
1182 cipher_crypt(&active_state->receive_context, cp,
1183 buffer_ptr(&active_state->input), padded_len);
1185 buffer_consume(&active_state->input, padded_len);
1187 #ifdef PACKET_DEBUG
1188 fprintf(stderr, "read_poll plain: ");
1189 buffer_dump(&active_state->incoming_packet);
1190 #endif
1192 /* Compute packet checksum. */
1193 checksum = ssh_crc32(buffer_ptr(&active_state->incoming_packet),
1194 buffer_len(&active_state->incoming_packet) - 4);
1196 /* Skip padding. */
1197 buffer_consume(&active_state->incoming_packet, 8 - len % 8);
1199 /* Test check bytes. */
1200 if (len != buffer_len(&active_state->incoming_packet))
1201 packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
1202 len, buffer_len(&active_state->incoming_packet));
1204 cp = (u_char *)buffer_ptr(&active_state->incoming_packet) + len - 4;
1205 stored_checksum = get_u32(cp);
1206 if (checksum != stored_checksum)
1207 packet_disconnect("Corrupted check bytes on input.");
1208 buffer_consume_end(&active_state->incoming_packet, 4);
1210 if (active_state->packet_compression) {
1211 buffer_clear(&active_state->compression_buffer);
1212 buffer_uncompress(&active_state->incoming_packet,
1213 &active_state->compression_buffer);
1214 buffer_clear(&active_state->incoming_packet);
1215 buffer_append(&active_state->incoming_packet,
1216 buffer_ptr(&active_state->compression_buffer),
1217 buffer_len(&active_state->compression_buffer));
1219 active_state->p_read.packets++;
1220 active_state->p_read.bytes += padded_len + 4;
1221 type = buffer_get_char(&active_state->incoming_packet);
1222 if (type < SSH_MSG_MIN || type > SSH_MSG_MAX)
1223 packet_disconnect("Invalid ssh1 packet type: %d", type);
1224 return type;
1227 static int
1228 packet_read_poll2(u_int32_t *seqnr_p)
1230 u_int padlen, need;
1231 u_char *macbuf, *cp, type;
1232 u_int maclen, block_size;
1233 Enc *enc = NULL;
1234 Mac *mac = NULL;
1235 Comp *comp = NULL;
1237 if (active_state->packet_discard)
1238 return SSH_MSG_NONE;
1240 if (active_state->newkeys[MODE_IN] != NULL) {
1241 enc = &active_state->newkeys[MODE_IN]->enc;
1242 mac = &active_state->newkeys[MODE_IN]->mac;
1243 comp = &active_state->newkeys[MODE_IN]->comp;
1245 maclen = mac && mac->enabled ? mac->mac_len : 0;
1246 block_size = enc ? enc->block_size : 8;
1248 if (active_state->packlen == 0) {
1250 * check if input size is less than the cipher block size,
1251 * decrypt first block and extract length of incoming packet
1253 if (buffer_len(&active_state->input) < block_size)
1254 return SSH_MSG_NONE;
1255 buffer_clear(&active_state->incoming_packet);
1256 cp = buffer_append_space(&active_state->incoming_packet,
1257 block_size);
1258 cipher_crypt(&active_state->receive_context, cp,
1259 buffer_ptr(&active_state->input), block_size);
1260 cp = buffer_ptr(&active_state->incoming_packet);
1261 active_state->packlen = get_u32(cp);
1262 if (active_state->packlen < 1 + 4 ||
1263 active_state->packlen > PACKET_MAX_SIZE) {
1264 #ifdef PACKET_DEBUG
1265 buffer_dump(&active_state->incoming_packet);
1266 #endif
1267 logit("Bad packet length %u.", active_state->packlen);
1268 packet_start_discard(enc, mac, active_state->packlen,
1269 PACKET_MAX_SIZE);
1270 return SSH_MSG_NONE;
1272 DBG(debug("input: packet len %u", active_state->packlen+4));
1273 buffer_consume(&active_state->input, block_size);
1275 /* we have a partial packet of block_size bytes */
1276 need = 4 + active_state->packlen - block_size;
1277 DBG(debug("partial packet %d, need %d, maclen %d", block_size,
1278 need, maclen));
1279 if (need % block_size != 0) {
1280 logit("padding error: need %d block %d mod %d",
1281 need, block_size, need % block_size);
1282 packet_start_discard(enc, mac, active_state->packlen,
1283 PACKET_MAX_SIZE - block_size);
1284 return SSH_MSG_NONE;
1287 * check if the entire packet has been received and
1288 * decrypt into incoming_packet
1290 if (buffer_len(&active_state->input) < need + maclen)
1291 return SSH_MSG_NONE;
1292 #ifdef PACKET_DEBUG
1293 fprintf(stderr, "read_poll enc/full: ");
1294 buffer_dump(&active_state->input);
1295 #endif
1296 cp = buffer_append_space(&active_state->incoming_packet, need);
1297 cipher_crypt(&active_state->receive_context, cp,
1298 buffer_ptr(&active_state->input), need);
1299 buffer_consume(&active_state->input, need);
1301 * compute MAC over seqnr and packet,
1302 * increment sequence number for incoming packet
1304 if (mac && mac->enabled) {
1305 macbuf = mac_compute(mac, active_state->p_read.seqnr,
1306 buffer_ptr(&active_state->incoming_packet),
1307 buffer_len(&active_state->incoming_packet));
1308 if (memcmp(macbuf, buffer_ptr(&active_state->input),
1309 mac->mac_len) != 0) {
1310 logit("Corrupted MAC on input.");
1311 if (need > PACKET_MAX_SIZE)
1312 fatal("internal error need %d", need);
1313 packet_start_discard(enc, mac, active_state->packlen,
1314 PACKET_MAX_SIZE - need);
1315 return SSH_MSG_NONE;
1318 DBG(debug("MAC #%d ok", active_state->p_read.seqnr));
1319 buffer_consume(&active_state->input, mac->mac_len);
1321 /* XXX now it's safe to use fatal/packet_disconnect */
1322 if (seqnr_p != NULL)
1323 *seqnr_p = active_state->p_read.seqnr;
1324 if (++active_state->p_read.seqnr == 0)
1325 logit("incoming seqnr wraps around");
1326 if (++active_state->p_read.packets == 0)
1327 if (!(datafellows & SSH_BUG_NOREKEY))
1328 fatal("XXX too many packets with same key");
1329 active_state->p_read.blocks += (active_state->packlen + 4) / block_size;
1330 active_state->p_read.bytes += active_state->packlen + 4;
1332 /* get padlen */
1333 cp = buffer_ptr(&active_state->incoming_packet);
1334 padlen = cp[4];
1335 DBG(debug("input: padlen %d", padlen));
1336 if (padlen < 4)
1337 packet_disconnect("Corrupted padlen %d on input.", padlen);
1339 /* skip packet size + padlen, discard padding */
1340 buffer_consume(&active_state->incoming_packet, 4 + 1);
1341 buffer_consume_end(&active_state->incoming_packet, padlen);
1343 DBG(debug("input: len before de-compress %d",
1344 buffer_len(&active_state->incoming_packet)));
1345 if (comp && comp->enabled) {
1346 buffer_clear(&active_state->compression_buffer);
1347 buffer_uncompress(&active_state->incoming_packet,
1348 &active_state->compression_buffer);
1349 buffer_clear(&active_state->incoming_packet);
1350 buffer_append(&active_state->incoming_packet,
1351 buffer_ptr(&active_state->compression_buffer),
1352 buffer_len(&active_state->compression_buffer));
1353 DBG(debug("input: len after de-compress %d",
1354 buffer_len(&active_state->incoming_packet)));
1357 * get packet type, implies consume.
1358 * return length of payload (without type field)
1360 type = buffer_get_char(&active_state->incoming_packet);
1361 if (type < SSH2_MSG_MIN || type >= SSH2_MSG_LOCAL_MIN)
1362 packet_disconnect("Invalid ssh2 packet type: %d", type);
1363 if (type == SSH2_MSG_NEWKEYS)
1364 set_newkeys(MODE_IN);
1365 else if (type == SSH2_MSG_USERAUTH_SUCCESS &&
1366 !active_state->server_side)
1367 packet_enable_delayed_compress();
1368 #ifdef PACKET_DEBUG
1369 fprintf(stderr, "read/plain[%d]:\r\n", type);
1370 buffer_dump(&active_state->incoming_packet);
1371 #endif
1372 /* reset for next packet */
1373 active_state->packlen = 0;
1374 return type;
1378 packet_read_poll_seqnr(u_int32_t *seqnr_p)
1380 u_int reason, seqnr;
1381 u_char type;
1382 char *msg;
1384 for (;;) {
1385 if (compat20) {
1386 type = packet_read_poll2(seqnr_p);
1387 if (type) {
1388 active_state->keep_alive_timeouts = 0;
1389 DBG(debug("received packet type %d", type));
1391 switch (type) {
1392 case SSH2_MSG_IGNORE:
1393 debug3("Received SSH2_MSG_IGNORE");
1394 break;
1395 case SSH2_MSG_DEBUG:
1396 packet_get_char();
1397 msg = packet_get_string(NULL);
1398 debug("Remote: %.900s", msg);
1399 xfree(msg);
1400 msg = packet_get_string(NULL);
1401 xfree(msg);
1402 break;
1403 case SSH2_MSG_DISCONNECT:
1404 reason = packet_get_int();
1405 msg = packet_get_string(NULL);
1406 logit("Received disconnect from %s: %u: %.400s",
1407 get_remote_ipaddr(), reason, msg);
1408 xfree(msg);
1409 cleanup_exit(255);
1410 break;
1411 case SSH2_MSG_UNIMPLEMENTED:
1412 seqnr = packet_get_int();
1413 debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1414 seqnr);
1415 break;
1416 default:
1417 return type;
1419 } else {
1420 type = packet_read_poll1();
1421 switch (type) {
1422 case SSH_MSG_IGNORE:
1423 break;
1424 case SSH_MSG_DEBUG:
1425 msg = packet_get_string(NULL);
1426 debug("Remote: %.900s", msg);
1427 xfree(msg);
1428 break;
1429 case SSH_MSG_DISCONNECT:
1430 msg = packet_get_string(NULL);
1431 logit("Received disconnect from %s: %.400s",
1432 get_remote_ipaddr(), msg);
1433 cleanup_exit(255);
1434 break;
1435 default:
1436 if (type)
1437 DBG(debug("received packet type %d", type));
1438 return type;
1445 packet_read_poll(void)
1447 return packet_read_poll_seqnr(NULL);
1451 * Buffers the given amount of input characters. This is intended to be used
1452 * together with packet_read_poll.
1455 void
1456 packet_process_incoming(const char *buf, u_int len)
1458 if (active_state->packet_discard) {
1459 active_state->keep_alive_timeouts = 0; /* ?? */
1460 if (len >= active_state->packet_discard)
1461 packet_stop_discard();
1462 active_state->packet_discard -= len;
1463 return;
1465 buffer_append(&active_state->input, buf, len);
1468 /* Returns a character from the packet. */
1470 u_int
1471 packet_get_char(void)
1473 char ch;
1475 buffer_get(&active_state->incoming_packet, &ch, 1);
1476 return (u_char) ch;
1479 /* Returns an integer from the packet data. */
1481 u_int
1482 packet_get_int(void)
1484 return buffer_get_int(&active_state->incoming_packet);
1487 /* Returns an 64 bit integer from the packet data. */
1489 u_int64_t
1490 packet_get_int64(void)
1492 return buffer_get_int64(&active_state->incoming_packet);
1496 * Returns an arbitrary precision integer from the packet data. The integer
1497 * must have been initialized before this call.
1500 void
1501 packet_get_bignum(BIGNUM * value)
1503 buffer_get_bignum(&active_state->incoming_packet, value);
1506 void
1507 packet_get_bignum2(BIGNUM * value)
1509 buffer_get_bignum2(&active_state->incoming_packet, value);
1512 void *
1513 packet_get_raw(u_int *length_ptr)
1515 u_int bytes = buffer_len(&active_state->incoming_packet);
1517 if (length_ptr != NULL)
1518 *length_ptr = bytes;
1519 return buffer_ptr(&active_state->incoming_packet);
1523 packet_remaining(void)
1525 return buffer_len(&active_state->incoming_packet);
1529 * Returns a string from the packet data. The string is allocated using
1530 * xmalloc; it is the responsibility of the calling program to free it when
1531 * no longer needed. The length_ptr argument may be NULL, or point to an
1532 * integer into which the length of the string is stored.
1535 void *
1536 packet_get_string(u_int *length_ptr)
1538 return buffer_get_string(&active_state->incoming_packet, length_ptr);
1541 void *
1542 packet_get_string_ptr(u_int *length_ptr)
1544 return buffer_get_string_ptr(&active_state->incoming_packet, length_ptr);
1548 * Sends a diagnostic message from the server to the client. This message
1549 * can be sent at any time (but not while constructing another message). The
1550 * message is printed immediately, but only if the client is being executed
1551 * in verbose mode. These messages are primarily intended to ease debugging
1552 * authentication problems. The length of the formatted message must not
1553 * exceed 1024 bytes. This will automatically call packet_write_wait.
1556 void
1557 packet_send_debug(const char *fmt,...)
1559 char buf[1024];
1560 va_list args;
1562 if (compat20 && (datafellows & SSH_BUG_DEBUG))
1563 return;
1565 va_start(args, fmt);
1566 vsnprintf(buf, sizeof(buf), fmt, args);
1567 va_end(args);
1569 if (compat20) {
1570 packet_start(SSH2_MSG_DEBUG);
1571 packet_put_char(0); /* bool: always display */
1572 packet_put_cstring(buf);
1573 packet_put_cstring("");
1574 } else {
1575 packet_start(SSH_MSG_DEBUG);
1576 packet_put_cstring(buf);
1578 packet_send();
1579 packet_write_wait();
1583 * Logs the error plus constructs and sends a disconnect packet, closes the
1584 * connection, and exits. This function never returns. The error message
1585 * should not contain a newline. The length of the formatted message must
1586 * not exceed 1024 bytes.
1589 void
1590 packet_disconnect(const char *fmt,...)
1592 char buf[1024];
1593 va_list args;
1594 static int disconnecting = 0;
1596 if (disconnecting) /* Guard against recursive invocations. */
1597 fatal("packet_disconnect called recursively.");
1598 disconnecting = 1;
1601 * Format the message. Note that the caller must make sure the
1602 * message is of limited size.
1604 va_start(args, fmt);
1605 vsnprintf(buf, sizeof(buf), fmt, args);
1606 va_end(args);
1608 /* Display the error locally */
1609 logit("Disconnecting: %.100s", buf);
1611 /* Send the disconnect message to the other side, and wait for it to get sent. */
1612 if (compat20) {
1613 packet_start(SSH2_MSG_DISCONNECT);
1614 packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1615 packet_put_cstring(buf);
1616 packet_put_cstring("");
1617 } else {
1618 packet_start(SSH_MSG_DISCONNECT);
1619 packet_put_cstring(buf);
1621 packet_send();
1622 packet_write_wait();
1624 /* Stop listening for connections. */
1625 channel_close_all();
1627 /* Close the connection. */
1628 packet_close();
1629 cleanup_exit(255);
1632 /* Checks if there is any buffered output, and tries to write some of the output. */
1635 packet_write_poll(void)
1637 int len = buffer_len(&active_state->output);
1638 int cont;
1640 if (len > 0) {
1641 cont = 0;
1642 len = roaming_write(active_state->connection_out,
1643 buffer_ptr(&active_state->output), len, &cont);
1644 if (len == -1) {
1645 if (errno == EINTR || errno == EAGAIN)
1646 return 0;
1647 fatal("Write failed: %.100s", strerror(errno));
1649 if (len == 0 && !cont)
1650 fatal("Write connection closed");
1651 buffer_consume(&active_state->output, len);
1653 return(len);
1657 * Calls packet_write_poll repeatedly until all pending output data has been
1658 * written.
1662 packet_write_wait(void)
1664 fd_set *setp;
1665 int ret, ms_remain;
1666 struct timeval start, timeout, *timeoutp = NULL;
1667 u_int bytes_sent = 0;
1669 setp = (fd_set *)xcalloc(howmany(active_state->connection_out + 1,
1670 NFDBITS), sizeof(fd_mask));
1671 bytes_sent += packet_write_poll();
1672 while (packet_have_data_to_write()) {
1673 memset(setp, 0, howmany(active_state->connection_out + 1,
1674 NFDBITS) * sizeof(fd_mask));
1675 FD_SET(active_state->connection_out, setp);
1677 if (active_state->packet_timeout_ms > 0) {
1678 ms_remain = active_state->packet_timeout_ms;
1679 timeoutp = &timeout;
1681 for (;;) {
1682 if (active_state->packet_timeout_ms != -1) {
1683 ms_to_timeval(&timeout, ms_remain);
1684 gettimeofday(&start, NULL);
1686 if ((ret = select(active_state->connection_out + 1,
1687 NULL, setp, NULL, timeoutp)) >= 0)
1688 break;
1689 if (errno != EAGAIN && errno != EINTR)
1690 break;
1691 if (active_state->packet_timeout_ms == -1)
1692 continue;
1693 ms_subtract_diff(&start, &ms_remain);
1694 if (ms_remain <= 0) {
1695 ret = 0;
1696 break;
1699 if (ret == 0) {
1700 logit("Connection to %.200s timed out while "
1701 "waiting to write", get_remote_ipaddr());
1702 cleanup_exit(255);
1704 bytes_sent += packet_write_poll();
1706 xfree(setp);
1707 return (bytes_sent);
1710 /* Returns true if there is buffered data to write to the connection. */
1713 packet_have_data_to_write(void)
1715 return buffer_len(&active_state->output) != 0;
1718 /* Returns true if there is not too much data to write to the connection. */
1721 packet_not_very_much_data_to_write(void)
1723 if (active_state->interactive_mode)
1724 return buffer_len(&active_state->output) < 16384;
1725 else
1726 return buffer_len(&active_state->output) < 128 * 1024;
1729 static void
1730 packet_set_tos(int interactive)
1732 int tos = interactive ? IPTOS_LOWDELAY : IPTOS_THROUGHPUT;
1734 if (!packet_connection_is_on_socket() ||
1735 !packet_connection_is_ipv4())
1736 return;
1737 if (setsockopt(active_state->connection_in, IPPROTO_IP, IP_TOS, &tos,
1738 sizeof(tos)) < 0)
1739 error("setsockopt IP_TOS %d: %.100s:",
1740 tos, strerror(errno));
1743 /* Informs that the current session is interactive. Sets IP flags for that. */
1745 void
1746 packet_set_interactive(int interactive)
1748 if (active_state->set_interactive_called)
1749 return;
1750 active_state->set_interactive_called = 1;
1752 /* Record that we are in interactive mode. */
1753 active_state->interactive_mode = interactive;
1755 /* Only set socket options if using a socket. */
1756 if (!packet_connection_is_on_socket())
1757 return;
1758 set_nodelay(active_state->connection_in);
1759 packet_set_tos(interactive);
1762 /* Returns true if the current connection is interactive. */
1765 packet_is_interactive(void)
1767 return active_state->interactive_mode;
1771 packet_set_maxsize(u_int s)
1773 if (active_state->set_maxsize_called) {
1774 logit("packet_set_maxsize: called twice: old %d new %d",
1775 active_state->max_packet_size, s);
1776 return -1;
1778 if (s < 4 * 1024 || s > 1024 * 1024) {
1779 logit("packet_set_maxsize: bad size %d", s);
1780 return -1;
1782 active_state->set_maxsize_called = 1;
1783 debug("packet_set_maxsize: setting to %d", s);
1784 active_state->max_packet_size = s;
1785 return s;
1789 packet_inc_alive_timeouts(void)
1791 return ++active_state->keep_alive_timeouts;
1794 void
1795 packet_set_alive_timeouts(int ka)
1797 active_state->keep_alive_timeouts = ka;
1800 u_int
1801 packet_get_maxsize(void)
1803 return active_state->max_packet_size;
1806 /* roundup current message to pad bytes */
1807 void
1808 packet_add_padding(u_char pad)
1810 active_state->extra_pad = pad;
1814 * 9.2. Ignored Data Message
1816 * byte SSH_MSG_IGNORE
1817 * string data
1819 * All implementations MUST understand (and ignore) this message at any
1820 * time (after receiving the protocol version). No implementation is
1821 * required to send them. This message can be used as an additional
1822 * protection measure against advanced traffic analysis techniques.
1824 void
1825 packet_send_ignore(int nbytes)
1827 u_int32_t rnd = 0;
1828 int i;
1830 packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1831 packet_put_int(nbytes);
1832 for (i = 0; i < nbytes; i++) {
1833 if (i % 4 == 0)
1834 rnd = arc4random();
1835 packet_put_char((u_char)rnd & 0xff);
1836 rnd >>= 8;
1840 int rekey_requested = 0;
1841 void
1842 packet_request_rekeying(void)
1844 rekey_requested = 1;
1847 #define MAX_PACKETS (1U<<31)
1849 packet_need_rekeying(void)
1851 if (datafellows & SSH_BUG_NOREKEY)
1852 return 0;
1853 if (rekey_requested == 1)
1855 rekey_requested = 0;
1856 return 1;
1858 return
1859 (active_state->p_send.packets > MAX_PACKETS) ||
1860 (active_state->p_read.packets > MAX_PACKETS) ||
1861 (active_state->max_blocks_out &&
1862 (active_state->p_send.blocks > active_state->max_blocks_out)) ||
1863 (active_state->max_blocks_in &&
1864 (active_state->p_read.blocks > active_state->max_blocks_in));
1867 void
1868 packet_set_rekey_limit(u_int32_t bytes)
1870 active_state->rekey_limit = bytes;
1873 void
1874 packet_set_server(void)
1876 active_state->server_side = 1;
1879 void
1880 packet_set_authenticated(void)
1882 active_state->after_authentication = 1;
1885 void *
1886 packet_get_input(void)
1888 return (void *)&active_state->input;
1891 void *
1892 packet_get_output(void)
1894 return (void *)&active_state->output;
1897 void *
1898 packet_get_newkeys(int mode)
1900 return (void *)active_state->newkeys[mode];
1904 * Save the state for the real connection, and use a separate state when
1905 * resuming a suspended connection.
1907 void
1908 packet_backup_state(void)
1910 struct session_state *tmp;
1912 close(active_state->connection_in);
1913 active_state->connection_in = -1;
1914 close(active_state->connection_out);
1915 active_state->connection_out = -1;
1916 if (backup_state)
1917 tmp = backup_state;
1918 else
1919 tmp = alloc_session_state();
1920 backup_state = active_state;
1921 active_state = tmp;
1925 * Swap in the old state when resuming a connecion.
1927 void
1928 packet_restore_state(void)
1930 struct session_state *tmp;
1931 void *buf;
1932 u_int len;
1934 tmp = backup_state;
1935 backup_state = active_state;
1936 active_state = tmp;
1937 active_state->connection_in = backup_state->connection_in;
1938 backup_state->connection_in = -1;
1939 active_state->connection_out = backup_state->connection_out;
1940 backup_state->connection_out = -1;
1941 len = buffer_len(&backup_state->input);
1942 if (len > 0) {
1943 buf = buffer_ptr(&backup_state->input);
1944 buffer_append(&active_state->input, buf, len);
1945 buffer_clear(&backup_state->input);
1946 add_recv_bytes(len);
1951 packet_authentication_state(void)
1953 return(active_state->after_authentication);