- (dtucker) [regress/keytype.sh] Import new test.
[openssh-git.git] / packet.c
blob0018d5839d91d7be2c0bff759d5a827700cfabec
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 #ifdef OPENSSL_HAS_ECC
645 void
646 packet_put_ecpoint(const EC_GROUP *curve, const EC_POINT *point)
648 buffer_put_ecpoint(&active_state->outgoing_packet, curve, point);
650 #endif
653 * Finalizes and sends the packet. If the encryption key has been set,
654 * encrypts the packet before sending.
657 static void
658 packet_send1(void)
660 u_char buf[8], *cp;
661 int i, padding, len;
662 u_int checksum;
663 u_int32_t rnd = 0;
666 * If using packet compression, compress the payload of the outgoing
667 * packet.
669 if (active_state->packet_compression) {
670 buffer_clear(&active_state->compression_buffer);
671 /* Skip padding. */
672 buffer_consume(&active_state->outgoing_packet, 8);
673 /* padding */
674 buffer_append(&active_state->compression_buffer,
675 "\0\0\0\0\0\0\0\0", 8);
676 buffer_compress(&active_state->outgoing_packet,
677 &active_state->compression_buffer);
678 buffer_clear(&active_state->outgoing_packet);
679 buffer_append(&active_state->outgoing_packet,
680 buffer_ptr(&active_state->compression_buffer),
681 buffer_len(&active_state->compression_buffer));
683 /* Compute packet length without padding (add checksum, remove padding). */
684 len = buffer_len(&active_state->outgoing_packet) + 4 - 8;
686 /* Insert padding. Initialized to zero in packet_start1() */
687 padding = 8 - len % 8;
688 if (!active_state->send_context.plaintext) {
689 cp = buffer_ptr(&active_state->outgoing_packet);
690 for (i = 0; i < padding; i++) {
691 if (i % 4 == 0)
692 rnd = arc4random();
693 cp[7 - i] = rnd & 0xff;
694 rnd >>= 8;
697 buffer_consume(&active_state->outgoing_packet, 8 - padding);
699 /* Add check bytes. */
700 checksum = ssh_crc32(buffer_ptr(&active_state->outgoing_packet),
701 buffer_len(&active_state->outgoing_packet));
702 put_u32(buf, checksum);
703 buffer_append(&active_state->outgoing_packet, buf, 4);
705 #ifdef PACKET_DEBUG
706 fprintf(stderr, "packet_send plain: ");
707 buffer_dump(&active_state->outgoing_packet);
708 #endif
710 /* Append to output. */
711 put_u32(buf, len);
712 buffer_append(&active_state->output, buf, 4);
713 cp = buffer_append_space(&active_state->output,
714 buffer_len(&active_state->outgoing_packet));
715 cipher_crypt(&active_state->send_context, cp,
716 buffer_ptr(&active_state->outgoing_packet),
717 buffer_len(&active_state->outgoing_packet));
719 #ifdef PACKET_DEBUG
720 fprintf(stderr, "encrypted: ");
721 buffer_dump(&active_state->output);
722 #endif
723 active_state->p_send.packets++;
724 active_state->p_send.bytes += len +
725 buffer_len(&active_state->outgoing_packet);
726 buffer_clear(&active_state->outgoing_packet);
729 * Note that the packet is now only buffered in output. It won't be
730 * actually sent until packet_write_wait or packet_write_poll is
731 * called.
735 void
736 set_newkeys(int mode)
738 Enc *enc;
739 Mac *mac;
740 Comp *comp;
741 CipherContext *cc;
742 u_int64_t *max_blocks;
743 int crypt_type;
745 debug2("set_newkeys: mode %d", mode);
747 if (mode == MODE_OUT) {
748 cc = &active_state->send_context;
749 crypt_type = CIPHER_ENCRYPT;
750 active_state->p_send.packets = active_state->p_send.blocks = 0;
751 max_blocks = &active_state->max_blocks_out;
752 } else {
753 cc = &active_state->receive_context;
754 crypt_type = CIPHER_DECRYPT;
755 active_state->p_read.packets = active_state->p_read.blocks = 0;
756 max_blocks = &active_state->max_blocks_in;
758 if (active_state->newkeys[mode] != NULL) {
759 debug("set_newkeys: rekeying");
760 cipher_cleanup(cc);
761 enc = &active_state->newkeys[mode]->enc;
762 mac = &active_state->newkeys[mode]->mac;
763 comp = &active_state->newkeys[mode]->comp;
764 mac_clear(mac);
765 xfree(enc->name);
766 xfree(enc->iv);
767 xfree(enc->key);
768 xfree(mac->name);
769 xfree(mac->key);
770 xfree(comp->name);
771 xfree(active_state->newkeys[mode]);
773 active_state->newkeys[mode] = kex_get_newkeys(mode);
774 if (active_state->newkeys[mode] == NULL)
775 fatal("newkeys: no keys for mode %d", mode);
776 enc = &active_state->newkeys[mode]->enc;
777 mac = &active_state->newkeys[mode]->mac;
778 comp = &active_state->newkeys[mode]->comp;
779 if (mac_init(mac) == 0)
780 mac->enabled = 1;
781 DBG(debug("cipher_init_context: %d", mode));
782 cipher_init(cc, enc->cipher, enc->key, enc->key_len,
783 enc->iv, enc->block_size, crypt_type);
784 /* Deleting the keys does not gain extra security */
785 /* memset(enc->iv, 0, enc->block_size);
786 memset(enc->key, 0, enc->key_len);
787 memset(mac->key, 0, mac->key_len); */
788 if ((comp->type == COMP_ZLIB ||
789 (comp->type == COMP_DELAYED &&
790 active_state->after_authentication)) && comp->enabled == 0) {
791 packet_init_compression();
792 if (mode == MODE_OUT)
793 buffer_compress_init_send(6);
794 else
795 buffer_compress_init_recv();
796 comp->enabled = 1;
799 * The 2^(blocksize*2) limit is too expensive for 3DES,
800 * blowfish, etc, so enforce a 1GB limit for small blocksizes.
802 if (enc->block_size >= 16)
803 *max_blocks = (u_int64_t)1 << (enc->block_size*2);
804 else
805 *max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
806 if (active_state->rekey_limit)
807 *max_blocks = MIN(*max_blocks,
808 active_state->rekey_limit / enc->block_size);
812 * Delayed compression for SSH2 is enabled after authentication:
813 * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
814 * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
816 static void
817 packet_enable_delayed_compress(void)
819 Comp *comp = NULL;
820 int mode;
823 * Remember that we are past the authentication step, so rekeying
824 * with COMP_DELAYED will turn on compression immediately.
826 active_state->after_authentication = 1;
827 for (mode = 0; mode < MODE_MAX; mode++) {
828 /* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
829 if (active_state->newkeys[mode] == NULL)
830 continue;
831 comp = &active_state->newkeys[mode]->comp;
832 if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
833 packet_init_compression();
834 if (mode == MODE_OUT)
835 buffer_compress_init_send(6);
836 else
837 buffer_compress_init_recv();
838 comp->enabled = 1;
844 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
846 static void
847 packet_send2_wrapped(void)
849 u_char type, *cp, *macbuf = NULL;
850 u_char padlen, pad;
851 u_int packet_length = 0;
852 u_int i, len;
853 u_int32_t rnd = 0;
854 Enc *enc = NULL;
855 Mac *mac = NULL;
856 Comp *comp = NULL;
857 int block_size;
859 if (active_state->newkeys[MODE_OUT] != NULL) {
860 enc = &active_state->newkeys[MODE_OUT]->enc;
861 mac = &active_state->newkeys[MODE_OUT]->mac;
862 comp = &active_state->newkeys[MODE_OUT]->comp;
864 block_size = enc ? enc->block_size : 8;
866 cp = buffer_ptr(&active_state->outgoing_packet);
867 type = cp[5];
869 #ifdef PACKET_DEBUG
870 fprintf(stderr, "plain: ");
871 buffer_dump(&active_state->outgoing_packet);
872 #endif
874 if (comp && comp->enabled) {
875 len = buffer_len(&active_state->outgoing_packet);
876 /* skip header, compress only payload */
877 buffer_consume(&active_state->outgoing_packet, 5);
878 buffer_clear(&active_state->compression_buffer);
879 buffer_compress(&active_state->outgoing_packet,
880 &active_state->compression_buffer);
881 buffer_clear(&active_state->outgoing_packet);
882 buffer_append(&active_state->outgoing_packet, "\0\0\0\0\0", 5);
883 buffer_append(&active_state->outgoing_packet,
884 buffer_ptr(&active_state->compression_buffer),
885 buffer_len(&active_state->compression_buffer));
886 DBG(debug("compression: raw %d compressed %d", len,
887 buffer_len(&active_state->outgoing_packet)));
890 /* sizeof (packet_len + pad_len + payload) */
891 len = buffer_len(&active_state->outgoing_packet);
894 * calc size of padding, alloc space, get random data,
895 * minimum padding is 4 bytes
897 padlen = block_size - (len % block_size);
898 if (padlen < 4)
899 padlen += block_size;
900 if (active_state->extra_pad) {
901 /* will wrap if extra_pad+padlen > 255 */
902 active_state->extra_pad =
903 roundup(active_state->extra_pad, block_size);
904 pad = active_state->extra_pad -
905 ((len + padlen) % active_state->extra_pad);
906 debug3("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
907 pad, len, padlen, active_state->extra_pad);
908 padlen += pad;
909 active_state->extra_pad = 0;
911 cp = buffer_append_space(&active_state->outgoing_packet, padlen);
912 if (enc && !active_state->send_context.plaintext) {
913 /* random padding */
914 for (i = 0; i < padlen; i++) {
915 if (i % 4 == 0)
916 rnd = arc4random();
917 cp[i] = rnd & 0xff;
918 rnd >>= 8;
920 } else {
921 /* clear padding */
922 memset(cp, 0, padlen);
924 /* packet_length includes payload, padding and padding length field */
925 packet_length = buffer_len(&active_state->outgoing_packet) - 4;
926 cp = buffer_ptr(&active_state->outgoing_packet);
927 put_u32(cp, packet_length);
928 cp[4] = padlen;
929 DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen));
931 /* compute MAC over seqnr and packet(length fields, payload, padding) */
932 if (mac && mac->enabled) {
933 macbuf = mac_compute(mac, active_state->p_send.seqnr,
934 buffer_ptr(&active_state->outgoing_packet),
935 buffer_len(&active_state->outgoing_packet));
936 DBG(debug("done calc MAC out #%d", active_state->p_send.seqnr));
938 /* encrypt packet and append to output buffer. */
939 cp = buffer_append_space(&active_state->output,
940 buffer_len(&active_state->outgoing_packet));
941 cipher_crypt(&active_state->send_context, cp,
942 buffer_ptr(&active_state->outgoing_packet),
943 buffer_len(&active_state->outgoing_packet));
944 /* append unencrypted MAC */
945 if (mac && mac->enabled)
946 buffer_append(&active_state->output, macbuf, mac->mac_len);
947 #ifdef PACKET_DEBUG
948 fprintf(stderr, "encrypted: ");
949 buffer_dump(&active_state->output);
950 #endif
951 /* increment sequence number for outgoing packets */
952 if (++active_state->p_send.seqnr == 0)
953 logit("outgoing seqnr wraps around");
954 if (++active_state->p_send.packets == 0)
955 if (!(datafellows & SSH_BUG_NOREKEY))
956 fatal("XXX too many packets with same key");
957 active_state->p_send.blocks += (packet_length + 4) / block_size;
958 active_state->p_send.bytes += packet_length + 4;
959 buffer_clear(&active_state->outgoing_packet);
961 if (type == SSH2_MSG_NEWKEYS)
962 set_newkeys(MODE_OUT);
963 else if (type == SSH2_MSG_USERAUTH_SUCCESS && active_state->server_side)
964 packet_enable_delayed_compress();
967 static void
968 packet_send2(void)
970 struct packet *p;
971 u_char type, *cp;
973 cp = buffer_ptr(&active_state->outgoing_packet);
974 type = cp[5];
976 /* during rekeying we can only send key exchange messages */
977 if (active_state->rekeying) {
978 if (!((type >= SSH2_MSG_TRANSPORT_MIN) &&
979 (type <= SSH2_MSG_TRANSPORT_MAX))) {
980 debug("enqueue packet: %u", type);
981 p = xmalloc(sizeof(*p));
982 p->type = type;
983 memcpy(&p->payload, &active_state->outgoing_packet,
984 sizeof(Buffer));
985 buffer_init(&active_state->outgoing_packet);
986 TAILQ_INSERT_TAIL(&active_state->outgoing, p, next);
987 return;
991 /* rekeying starts with sending KEXINIT */
992 if (type == SSH2_MSG_KEXINIT)
993 active_state->rekeying = 1;
995 packet_send2_wrapped();
997 /* after a NEWKEYS message we can send the complete queue */
998 if (type == SSH2_MSG_NEWKEYS) {
999 active_state->rekeying = 0;
1000 while ((p = TAILQ_FIRST(&active_state->outgoing))) {
1001 type = p->type;
1002 debug("dequeue packet: %u", type);
1003 buffer_free(&active_state->outgoing_packet);
1004 memcpy(&active_state->outgoing_packet, &p->payload,
1005 sizeof(Buffer));
1006 TAILQ_REMOVE(&active_state->outgoing, p, next);
1007 xfree(p);
1008 packet_send2_wrapped();
1013 void
1014 packet_send(void)
1016 if (compat20)
1017 packet_send2();
1018 else
1019 packet_send1();
1020 DBG(debug("packet_send done"));
1024 * Waits until a packet has been received, and returns its type. Note that
1025 * no other data is processed until this returns, so this function should not
1026 * be used during the interactive session.
1030 packet_read_seqnr(u_int32_t *seqnr_p)
1032 int type, len, ret, ms_remain, cont;
1033 fd_set *setp;
1034 char buf[8192];
1035 struct timeval timeout, start, *timeoutp = NULL;
1037 DBG(debug("packet_read()"));
1039 setp = (fd_set *)xcalloc(howmany(active_state->connection_in + 1,
1040 NFDBITS), sizeof(fd_mask));
1042 /* Since we are blocking, ensure that all written packets have been sent. */
1043 packet_write_wait();
1045 /* Stay in the loop until we have received a complete packet. */
1046 for (;;) {
1047 /* Try to read a packet from the buffer. */
1048 type = packet_read_poll_seqnr(seqnr_p);
1049 if (!compat20 && (
1050 type == SSH_SMSG_SUCCESS
1051 || type == SSH_SMSG_FAILURE
1052 || type == SSH_CMSG_EOF
1053 || type == SSH_CMSG_EXIT_CONFIRMATION))
1054 packet_check_eom();
1055 /* If we got a packet, return it. */
1056 if (type != SSH_MSG_NONE) {
1057 xfree(setp);
1058 return type;
1061 * Otherwise, wait for some data to arrive, add it to the
1062 * buffer, and try again.
1064 memset(setp, 0, howmany(active_state->connection_in + 1,
1065 NFDBITS) * sizeof(fd_mask));
1066 FD_SET(active_state->connection_in, setp);
1068 if (active_state->packet_timeout_ms > 0) {
1069 ms_remain = active_state->packet_timeout_ms;
1070 timeoutp = &timeout;
1072 /* Wait for some data to arrive. */
1073 for (;;) {
1074 if (active_state->packet_timeout_ms != -1) {
1075 ms_to_timeval(&timeout, ms_remain);
1076 gettimeofday(&start, NULL);
1078 if ((ret = select(active_state->connection_in + 1, setp,
1079 NULL, NULL, timeoutp)) >= 0)
1080 break;
1081 if (errno != EAGAIN && errno != EINTR &&
1082 errno != EWOULDBLOCK)
1083 break;
1084 if (active_state->packet_timeout_ms == -1)
1085 continue;
1086 ms_subtract_diff(&start, &ms_remain);
1087 if (ms_remain <= 0) {
1088 ret = 0;
1089 break;
1092 if (ret == 0) {
1093 logit("Connection to %.200s timed out while "
1094 "waiting to read", get_remote_ipaddr());
1095 cleanup_exit(255);
1097 /* Read data from the socket. */
1098 do {
1099 cont = 0;
1100 len = roaming_read(active_state->connection_in, buf,
1101 sizeof(buf), &cont);
1102 } while (len == 0 && cont);
1103 if (len == 0) {
1104 logit("Connection closed by %.200s", get_remote_ipaddr());
1105 cleanup_exit(255);
1107 if (len < 0)
1108 fatal("Read from socket failed: %.100s", strerror(errno));
1109 /* Append it to the buffer. */
1110 packet_process_incoming(buf, len);
1112 /* NOTREACHED */
1116 packet_read(void)
1118 return packet_read_seqnr(NULL);
1122 * Waits until a packet has been received, verifies that its type matches
1123 * that given, and gives a fatal error and exits if there is a mismatch.
1126 void
1127 packet_read_expect(int expected_type)
1129 int type;
1131 type = packet_read();
1132 if (type != expected_type)
1133 packet_disconnect("Protocol error: expected packet type %d, got %d",
1134 expected_type, type);
1137 /* Checks if a full packet is available in the data received so far via
1138 * packet_process_incoming. If so, reads the packet; otherwise returns
1139 * SSH_MSG_NONE. This does not wait for data from the connection.
1141 * SSH_MSG_DISCONNECT is handled specially here. Also,
1142 * SSH_MSG_IGNORE messages are skipped by this function and are never returned
1143 * to higher levels.
1146 static int
1147 packet_read_poll1(void)
1149 u_int len, padded_len;
1150 u_char *cp, type;
1151 u_int checksum, stored_checksum;
1153 /* Check if input size is less than minimum packet size. */
1154 if (buffer_len(&active_state->input) < 4 + 8)
1155 return SSH_MSG_NONE;
1156 /* Get length of incoming packet. */
1157 cp = buffer_ptr(&active_state->input);
1158 len = get_u32(cp);
1159 if (len < 1 + 2 + 2 || len > 256 * 1024)
1160 packet_disconnect("Bad packet length %u.", len);
1161 padded_len = (len + 8) & ~7;
1163 /* Check if the packet has been entirely received. */
1164 if (buffer_len(&active_state->input) < 4 + padded_len)
1165 return SSH_MSG_NONE;
1167 /* The entire packet is in buffer. */
1169 /* Consume packet length. */
1170 buffer_consume(&active_state->input, 4);
1173 * Cryptographic attack detector for ssh
1174 * (C)1998 CORE-SDI, Buenos Aires Argentina
1175 * Ariel Futoransky(futo@core-sdi.com)
1177 if (!active_state->receive_context.plaintext) {
1178 switch (detect_attack(buffer_ptr(&active_state->input),
1179 padded_len)) {
1180 case DEATTACK_DETECTED:
1181 packet_disconnect("crc32 compensation attack: "
1182 "network attack detected");
1183 case DEATTACK_DOS_DETECTED:
1184 packet_disconnect("deattack denial of "
1185 "service detected");
1189 /* Decrypt data to incoming_packet. */
1190 buffer_clear(&active_state->incoming_packet);
1191 cp = buffer_append_space(&active_state->incoming_packet, padded_len);
1192 cipher_crypt(&active_state->receive_context, cp,
1193 buffer_ptr(&active_state->input), padded_len);
1195 buffer_consume(&active_state->input, padded_len);
1197 #ifdef PACKET_DEBUG
1198 fprintf(stderr, "read_poll plain: ");
1199 buffer_dump(&active_state->incoming_packet);
1200 #endif
1202 /* Compute packet checksum. */
1203 checksum = ssh_crc32(buffer_ptr(&active_state->incoming_packet),
1204 buffer_len(&active_state->incoming_packet) - 4);
1206 /* Skip padding. */
1207 buffer_consume(&active_state->incoming_packet, 8 - len % 8);
1209 /* Test check bytes. */
1210 if (len != buffer_len(&active_state->incoming_packet))
1211 packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
1212 len, buffer_len(&active_state->incoming_packet));
1214 cp = (u_char *)buffer_ptr(&active_state->incoming_packet) + len - 4;
1215 stored_checksum = get_u32(cp);
1216 if (checksum != stored_checksum)
1217 packet_disconnect("Corrupted check bytes on input.");
1218 buffer_consume_end(&active_state->incoming_packet, 4);
1220 if (active_state->packet_compression) {
1221 buffer_clear(&active_state->compression_buffer);
1222 buffer_uncompress(&active_state->incoming_packet,
1223 &active_state->compression_buffer);
1224 buffer_clear(&active_state->incoming_packet);
1225 buffer_append(&active_state->incoming_packet,
1226 buffer_ptr(&active_state->compression_buffer),
1227 buffer_len(&active_state->compression_buffer));
1229 active_state->p_read.packets++;
1230 active_state->p_read.bytes += padded_len + 4;
1231 type = buffer_get_char(&active_state->incoming_packet);
1232 if (type < SSH_MSG_MIN || type > SSH_MSG_MAX)
1233 packet_disconnect("Invalid ssh1 packet type: %d", type);
1234 return type;
1237 static int
1238 packet_read_poll2(u_int32_t *seqnr_p)
1240 u_int padlen, need;
1241 u_char *macbuf, *cp, type;
1242 u_int maclen, block_size;
1243 Enc *enc = NULL;
1244 Mac *mac = NULL;
1245 Comp *comp = NULL;
1247 if (active_state->packet_discard)
1248 return SSH_MSG_NONE;
1250 if (active_state->newkeys[MODE_IN] != NULL) {
1251 enc = &active_state->newkeys[MODE_IN]->enc;
1252 mac = &active_state->newkeys[MODE_IN]->mac;
1253 comp = &active_state->newkeys[MODE_IN]->comp;
1255 maclen = mac && mac->enabled ? mac->mac_len : 0;
1256 block_size = enc ? enc->block_size : 8;
1258 if (active_state->packlen == 0) {
1260 * check if input size is less than the cipher block size,
1261 * decrypt first block and extract length of incoming packet
1263 if (buffer_len(&active_state->input) < block_size)
1264 return SSH_MSG_NONE;
1265 buffer_clear(&active_state->incoming_packet);
1266 cp = buffer_append_space(&active_state->incoming_packet,
1267 block_size);
1268 cipher_crypt(&active_state->receive_context, cp,
1269 buffer_ptr(&active_state->input), block_size);
1270 cp = buffer_ptr(&active_state->incoming_packet);
1271 active_state->packlen = get_u32(cp);
1272 if (active_state->packlen < 1 + 4 ||
1273 active_state->packlen > PACKET_MAX_SIZE) {
1274 #ifdef PACKET_DEBUG
1275 buffer_dump(&active_state->incoming_packet);
1276 #endif
1277 logit("Bad packet length %u.", active_state->packlen);
1278 packet_start_discard(enc, mac, active_state->packlen,
1279 PACKET_MAX_SIZE);
1280 return SSH_MSG_NONE;
1282 DBG(debug("input: packet len %u", active_state->packlen+4));
1283 buffer_consume(&active_state->input, block_size);
1285 /* we have a partial packet of block_size bytes */
1286 need = 4 + active_state->packlen - block_size;
1287 DBG(debug("partial packet %d, need %d, maclen %d", block_size,
1288 need, maclen));
1289 if (need % block_size != 0) {
1290 logit("padding error: need %d block %d mod %d",
1291 need, block_size, need % block_size);
1292 packet_start_discard(enc, mac, active_state->packlen,
1293 PACKET_MAX_SIZE - block_size);
1294 return SSH_MSG_NONE;
1297 * check if the entire packet has been received and
1298 * decrypt into incoming_packet
1300 if (buffer_len(&active_state->input) < need + maclen)
1301 return SSH_MSG_NONE;
1302 #ifdef PACKET_DEBUG
1303 fprintf(stderr, "read_poll enc/full: ");
1304 buffer_dump(&active_state->input);
1305 #endif
1306 cp = buffer_append_space(&active_state->incoming_packet, need);
1307 cipher_crypt(&active_state->receive_context, cp,
1308 buffer_ptr(&active_state->input), need);
1309 buffer_consume(&active_state->input, need);
1311 * compute MAC over seqnr and packet,
1312 * increment sequence number for incoming packet
1314 if (mac && mac->enabled) {
1315 macbuf = mac_compute(mac, active_state->p_read.seqnr,
1316 buffer_ptr(&active_state->incoming_packet),
1317 buffer_len(&active_state->incoming_packet));
1318 if (timingsafe_bcmp(macbuf, buffer_ptr(&active_state->input),
1319 mac->mac_len) != 0) {
1320 logit("Corrupted MAC on input.");
1321 if (need > PACKET_MAX_SIZE)
1322 fatal("internal error need %d", need);
1323 packet_start_discard(enc, mac, active_state->packlen,
1324 PACKET_MAX_SIZE - need);
1325 return SSH_MSG_NONE;
1328 DBG(debug("MAC #%d ok", active_state->p_read.seqnr));
1329 buffer_consume(&active_state->input, mac->mac_len);
1331 /* XXX now it's safe to use fatal/packet_disconnect */
1332 if (seqnr_p != NULL)
1333 *seqnr_p = active_state->p_read.seqnr;
1334 if (++active_state->p_read.seqnr == 0)
1335 logit("incoming seqnr wraps around");
1336 if (++active_state->p_read.packets == 0)
1337 if (!(datafellows & SSH_BUG_NOREKEY))
1338 fatal("XXX too many packets with same key");
1339 active_state->p_read.blocks += (active_state->packlen + 4) / block_size;
1340 active_state->p_read.bytes += active_state->packlen + 4;
1342 /* get padlen */
1343 cp = buffer_ptr(&active_state->incoming_packet);
1344 padlen = cp[4];
1345 DBG(debug("input: padlen %d", padlen));
1346 if (padlen < 4)
1347 packet_disconnect("Corrupted padlen %d on input.", padlen);
1349 /* skip packet size + padlen, discard padding */
1350 buffer_consume(&active_state->incoming_packet, 4 + 1);
1351 buffer_consume_end(&active_state->incoming_packet, padlen);
1353 DBG(debug("input: len before de-compress %d",
1354 buffer_len(&active_state->incoming_packet)));
1355 if (comp && comp->enabled) {
1356 buffer_clear(&active_state->compression_buffer);
1357 buffer_uncompress(&active_state->incoming_packet,
1358 &active_state->compression_buffer);
1359 buffer_clear(&active_state->incoming_packet);
1360 buffer_append(&active_state->incoming_packet,
1361 buffer_ptr(&active_state->compression_buffer),
1362 buffer_len(&active_state->compression_buffer));
1363 DBG(debug("input: len after de-compress %d",
1364 buffer_len(&active_state->incoming_packet)));
1367 * get packet type, implies consume.
1368 * return length of payload (without type field)
1370 type = buffer_get_char(&active_state->incoming_packet);
1371 if (type < SSH2_MSG_MIN || type >= SSH2_MSG_LOCAL_MIN)
1372 packet_disconnect("Invalid ssh2 packet type: %d", type);
1373 if (type == SSH2_MSG_NEWKEYS)
1374 set_newkeys(MODE_IN);
1375 else if (type == SSH2_MSG_USERAUTH_SUCCESS &&
1376 !active_state->server_side)
1377 packet_enable_delayed_compress();
1378 #ifdef PACKET_DEBUG
1379 fprintf(stderr, "read/plain[%d]:\r\n", type);
1380 buffer_dump(&active_state->incoming_packet);
1381 #endif
1382 /* reset for next packet */
1383 active_state->packlen = 0;
1384 return type;
1388 packet_read_poll_seqnr(u_int32_t *seqnr_p)
1390 u_int reason, seqnr;
1391 u_char type;
1392 char *msg;
1394 for (;;) {
1395 if (compat20) {
1396 type = packet_read_poll2(seqnr_p);
1397 if (type) {
1398 active_state->keep_alive_timeouts = 0;
1399 DBG(debug("received packet type %d", type));
1401 switch (type) {
1402 case SSH2_MSG_IGNORE:
1403 debug3("Received SSH2_MSG_IGNORE");
1404 break;
1405 case SSH2_MSG_DEBUG:
1406 packet_get_char();
1407 msg = packet_get_string(NULL);
1408 debug("Remote: %.900s", msg);
1409 xfree(msg);
1410 msg = packet_get_string(NULL);
1411 xfree(msg);
1412 break;
1413 case SSH2_MSG_DISCONNECT:
1414 reason = packet_get_int();
1415 msg = packet_get_string(NULL);
1416 logit("Received disconnect from %s: %u: %.400s",
1417 get_remote_ipaddr(), reason, msg);
1418 xfree(msg);
1419 cleanup_exit(255);
1420 break;
1421 case SSH2_MSG_UNIMPLEMENTED:
1422 seqnr = packet_get_int();
1423 debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1424 seqnr);
1425 break;
1426 default:
1427 return type;
1429 } else {
1430 type = packet_read_poll1();
1431 switch (type) {
1432 case SSH_MSG_IGNORE:
1433 break;
1434 case SSH_MSG_DEBUG:
1435 msg = packet_get_string(NULL);
1436 debug("Remote: %.900s", msg);
1437 xfree(msg);
1438 break;
1439 case SSH_MSG_DISCONNECT:
1440 msg = packet_get_string(NULL);
1441 logit("Received disconnect from %s: %.400s",
1442 get_remote_ipaddr(), msg);
1443 cleanup_exit(255);
1444 break;
1445 default:
1446 if (type)
1447 DBG(debug("received packet type %d", type));
1448 return type;
1455 packet_read_poll(void)
1457 return packet_read_poll_seqnr(NULL);
1461 * Buffers the given amount of input characters. This is intended to be used
1462 * together with packet_read_poll.
1465 void
1466 packet_process_incoming(const char *buf, u_int len)
1468 if (active_state->packet_discard) {
1469 active_state->keep_alive_timeouts = 0; /* ?? */
1470 if (len >= active_state->packet_discard)
1471 packet_stop_discard();
1472 active_state->packet_discard -= len;
1473 return;
1475 buffer_append(&active_state->input, buf, len);
1478 /* Returns a character from the packet. */
1480 u_int
1481 packet_get_char(void)
1483 char ch;
1485 buffer_get(&active_state->incoming_packet, &ch, 1);
1486 return (u_char) ch;
1489 /* Returns an integer from the packet data. */
1491 u_int
1492 packet_get_int(void)
1494 return buffer_get_int(&active_state->incoming_packet);
1497 /* Returns an 64 bit integer from the packet data. */
1499 u_int64_t
1500 packet_get_int64(void)
1502 return buffer_get_int64(&active_state->incoming_packet);
1506 * Returns an arbitrary precision integer from the packet data. The integer
1507 * must have been initialized before this call.
1510 void
1511 packet_get_bignum(BIGNUM * value)
1513 buffer_get_bignum(&active_state->incoming_packet, value);
1516 void
1517 packet_get_bignum2(BIGNUM * value)
1519 buffer_get_bignum2(&active_state->incoming_packet, value);
1522 #ifdef OPENSSL_HAS_ECC
1523 void
1524 packet_get_ecpoint(const EC_GROUP *curve, EC_POINT *point)
1526 buffer_get_ecpoint(&active_state->incoming_packet, curve, point);
1528 #endif
1530 void *
1531 packet_get_raw(u_int *length_ptr)
1533 u_int bytes = buffer_len(&active_state->incoming_packet);
1535 if (length_ptr != NULL)
1536 *length_ptr = bytes;
1537 return buffer_ptr(&active_state->incoming_packet);
1541 packet_remaining(void)
1543 return buffer_len(&active_state->incoming_packet);
1547 * Returns a string from the packet data. The string is allocated using
1548 * xmalloc; it is the responsibility of the calling program to free it when
1549 * no longer needed. The length_ptr argument may be NULL, or point to an
1550 * integer into which the length of the string is stored.
1553 void *
1554 packet_get_string(u_int *length_ptr)
1556 return buffer_get_string(&active_state->incoming_packet, length_ptr);
1559 void *
1560 packet_get_string_ptr(u_int *length_ptr)
1562 return buffer_get_string_ptr(&active_state->incoming_packet, length_ptr);
1565 /* Ensures the returned string has no embedded \0 characters in it. */
1566 char *
1567 packet_get_cstring(u_int *length_ptr)
1569 return buffer_get_cstring(&active_state->incoming_packet, length_ptr);
1573 * Sends a diagnostic message from the server to the client. This message
1574 * can be sent at any time (but not while constructing another message). The
1575 * message is printed immediately, but only if the client is being executed
1576 * in verbose mode. These messages are primarily intended to ease debugging
1577 * authentication problems. The length of the formatted message must not
1578 * exceed 1024 bytes. This will automatically call packet_write_wait.
1581 void
1582 packet_send_debug(const char *fmt,...)
1584 char buf[1024];
1585 va_list args;
1587 if (compat20 && (datafellows & SSH_BUG_DEBUG))
1588 return;
1590 va_start(args, fmt);
1591 vsnprintf(buf, sizeof(buf), fmt, args);
1592 va_end(args);
1594 if (compat20) {
1595 packet_start(SSH2_MSG_DEBUG);
1596 packet_put_char(0); /* bool: always display */
1597 packet_put_cstring(buf);
1598 packet_put_cstring("");
1599 } else {
1600 packet_start(SSH_MSG_DEBUG);
1601 packet_put_cstring(buf);
1603 packet_send();
1604 packet_write_wait();
1608 * Logs the error plus constructs and sends a disconnect packet, closes the
1609 * connection, and exits. This function never returns. The error message
1610 * should not contain a newline. The length of the formatted message must
1611 * not exceed 1024 bytes.
1614 void
1615 packet_disconnect(const char *fmt,...)
1617 char buf[1024];
1618 va_list args;
1619 static int disconnecting = 0;
1621 if (disconnecting) /* Guard against recursive invocations. */
1622 fatal("packet_disconnect called recursively.");
1623 disconnecting = 1;
1626 * Format the message. Note that the caller must make sure the
1627 * message is of limited size.
1629 va_start(args, fmt);
1630 vsnprintf(buf, sizeof(buf), fmt, args);
1631 va_end(args);
1633 /* Display the error locally */
1634 logit("Disconnecting: %.100s", buf);
1636 /* Send the disconnect message to the other side, and wait for it to get sent. */
1637 if (compat20) {
1638 packet_start(SSH2_MSG_DISCONNECT);
1639 packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1640 packet_put_cstring(buf);
1641 packet_put_cstring("");
1642 } else {
1643 packet_start(SSH_MSG_DISCONNECT);
1644 packet_put_cstring(buf);
1646 packet_send();
1647 packet_write_wait();
1649 /* Stop listening for connections. */
1650 channel_close_all();
1652 /* Close the connection. */
1653 packet_close();
1654 cleanup_exit(255);
1657 /* Checks if there is any buffered output, and tries to write some of the output. */
1659 void
1660 packet_write_poll(void)
1662 int len = buffer_len(&active_state->output);
1663 int cont;
1665 if (len > 0) {
1666 cont = 0;
1667 len = roaming_write(active_state->connection_out,
1668 buffer_ptr(&active_state->output), len, &cont);
1669 if (len == -1) {
1670 if (errno == EINTR || errno == EAGAIN ||
1671 errno == EWOULDBLOCK)
1672 return;
1673 fatal("Write failed: %.100s", strerror(errno));
1675 if (len == 0 && !cont)
1676 fatal("Write connection closed");
1677 buffer_consume(&active_state->output, len);
1682 * Calls packet_write_poll repeatedly until all pending output data has been
1683 * written.
1686 void
1687 packet_write_wait(void)
1689 fd_set *setp;
1690 int ret, ms_remain;
1691 struct timeval start, timeout, *timeoutp = NULL;
1693 setp = (fd_set *)xcalloc(howmany(active_state->connection_out + 1,
1694 NFDBITS), sizeof(fd_mask));
1695 packet_write_poll();
1696 while (packet_have_data_to_write()) {
1697 memset(setp, 0, howmany(active_state->connection_out + 1,
1698 NFDBITS) * sizeof(fd_mask));
1699 FD_SET(active_state->connection_out, setp);
1701 if (active_state->packet_timeout_ms > 0) {
1702 ms_remain = active_state->packet_timeout_ms;
1703 timeoutp = &timeout;
1705 for (;;) {
1706 if (active_state->packet_timeout_ms != -1) {
1707 ms_to_timeval(&timeout, ms_remain);
1708 gettimeofday(&start, NULL);
1710 if ((ret = select(active_state->connection_out + 1,
1711 NULL, setp, NULL, timeoutp)) >= 0)
1712 break;
1713 if (errno != EAGAIN && errno != EINTR &&
1714 errno != EWOULDBLOCK)
1715 break;
1716 if (active_state->packet_timeout_ms == -1)
1717 continue;
1718 ms_subtract_diff(&start, &ms_remain);
1719 if (ms_remain <= 0) {
1720 ret = 0;
1721 break;
1724 if (ret == 0) {
1725 logit("Connection to %.200s timed out while "
1726 "waiting to write", get_remote_ipaddr());
1727 cleanup_exit(255);
1729 packet_write_poll();
1731 xfree(setp);
1734 /* Returns true if there is buffered data to write to the connection. */
1737 packet_have_data_to_write(void)
1739 return buffer_len(&active_state->output) != 0;
1742 /* Returns true if there is not too much data to write to the connection. */
1745 packet_not_very_much_data_to_write(void)
1747 if (active_state->interactive_mode)
1748 return buffer_len(&active_state->output) < 16384;
1749 else
1750 return buffer_len(&active_state->output) < 128 * 1024;
1753 static void
1754 packet_set_tos(int interactive)
1756 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1757 int tos = interactive ? IPTOS_LOWDELAY : IPTOS_THROUGHPUT;
1759 if (!packet_connection_is_on_socket() ||
1760 !packet_connection_is_ipv4())
1761 return;
1762 if (setsockopt(active_state->connection_in, IPPROTO_IP, IP_TOS, &tos,
1763 sizeof(tos)) < 0)
1764 error("setsockopt IP_TOS %d: %.100s:",
1765 tos, strerror(errno));
1766 #endif
1769 /* Informs that the current session is interactive. Sets IP flags for that. */
1771 void
1772 packet_set_interactive(int interactive)
1774 if (active_state->set_interactive_called)
1775 return;
1776 active_state->set_interactive_called = 1;
1778 /* Record that we are in interactive mode. */
1779 active_state->interactive_mode = interactive;
1781 /* Only set socket options if using a socket. */
1782 if (!packet_connection_is_on_socket())
1783 return;
1784 set_nodelay(active_state->connection_in);
1785 packet_set_tos(interactive);
1788 /* Returns true if the current connection is interactive. */
1791 packet_is_interactive(void)
1793 return active_state->interactive_mode;
1797 packet_set_maxsize(u_int s)
1799 if (active_state->set_maxsize_called) {
1800 logit("packet_set_maxsize: called twice: old %d new %d",
1801 active_state->max_packet_size, s);
1802 return -1;
1804 if (s < 4 * 1024 || s > 1024 * 1024) {
1805 logit("packet_set_maxsize: bad size %d", s);
1806 return -1;
1808 active_state->set_maxsize_called = 1;
1809 debug("packet_set_maxsize: setting to %d", s);
1810 active_state->max_packet_size = s;
1811 return s;
1815 packet_inc_alive_timeouts(void)
1817 return ++active_state->keep_alive_timeouts;
1820 void
1821 packet_set_alive_timeouts(int ka)
1823 active_state->keep_alive_timeouts = ka;
1826 u_int
1827 packet_get_maxsize(void)
1829 return active_state->max_packet_size;
1832 /* roundup current message to pad bytes */
1833 void
1834 packet_add_padding(u_char pad)
1836 active_state->extra_pad = pad;
1840 * 9.2. Ignored Data Message
1842 * byte SSH_MSG_IGNORE
1843 * string data
1845 * All implementations MUST understand (and ignore) this message at any
1846 * time (after receiving the protocol version). No implementation is
1847 * required to send them. This message can be used as an additional
1848 * protection measure against advanced traffic analysis techniques.
1850 void
1851 packet_send_ignore(int nbytes)
1853 u_int32_t rnd = 0;
1854 int i;
1856 packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1857 packet_put_int(nbytes);
1858 for (i = 0; i < nbytes; i++) {
1859 if (i % 4 == 0)
1860 rnd = arc4random();
1861 packet_put_char((u_char)rnd & 0xff);
1862 rnd >>= 8;
1866 #define MAX_PACKETS (1U<<31)
1868 packet_need_rekeying(void)
1870 if (datafellows & SSH_BUG_NOREKEY)
1871 return 0;
1872 return
1873 (active_state->p_send.packets > MAX_PACKETS) ||
1874 (active_state->p_read.packets > MAX_PACKETS) ||
1875 (active_state->max_blocks_out &&
1876 (active_state->p_send.blocks > active_state->max_blocks_out)) ||
1877 (active_state->max_blocks_in &&
1878 (active_state->p_read.blocks > active_state->max_blocks_in));
1881 void
1882 packet_set_rekey_limit(u_int32_t bytes)
1884 active_state->rekey_limit = bytes;
1887 void
1888 packet_set_server(void)
1890 active_state->server_side = 1;
1893 void
1894 packet_set_authenticated(void)
1896 active_state->after_authentication = 1;
1899 void *
1900 packet_get_input(void)
1902 return (void *)&active_state->input;
1905 void *
1906 packet_get_output(void)
1908 return (void *)&active_state->output;
1911 void *
1912 packet_get_newkeys(int mode)
1914 return (void *)active_state->newkeys[mode];
1918 * Save the state for the real connection, and use a separate state when
1919 * resuming a suspended connection.
1921 void
1922 packet_backup_state(void)
1924 struct session_state *tmp;
1926 close(active_state->connection_in);
1927 active_state->connection_in = -1;
1928 close(active_state->connection_out);
1929 active_state->connection_out = -1;
1930 if (backup_state)
1931 tmp = backup_state;
1932 else
1933 tmp = alloc_session_state();
1934 backup_state = active_state;
1935 active_state = tmp;
1939 * Swap in the old state when resuming a connecion.
1941 void
1942 packet_restore_state(void)
1944 struct session_state *tmp;
1945 void *buf;
1946 u_int len;
1948 tmp = backup_state;
1949 backup_state = active_state;
1950 active_state = tmp;
1951 active_state->connection_in = backup_state->connection_in;
1952 backup_state->connection_in = -1;
1953 active_state->connection_out = backup_state->connection_out;
1954 backup_state->connection_out = -1;
1955 len = buffer_len(&backup_state->input);
1956 if (len > 0) {
1957 buf = buffer_ptr(&backup_state->input);
1958 buffer_append(&active_state->input, buf, len);
1959 buffer_clear(&backup_state->input);
1960 add_recv_bytes(len);