packet.c revision 224638
1169695Skan/* $OpenBSD: packet.c,v 1.172 2010/11/13 23:27:50 djm Exp $ */
2169695Skan/* $FreeBSD$ */
3169695Skan/*
4169695Skan * Author: Tatu Ylonen <ylo@cs.hut.fi>
5169695Skan * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6169695Skan *                    All rights reserved
7169695Skan * This file contains code implementing the packet protocol and communication
8169695Skan * with the other side.  This same code is used both on client and server side.
9169695Skan *
10169695Skan * As far as I am concerned, the code I have written for this software
11169695Skan * can be used freely for any purpose.  Any derived versions of this
12169695Skan * software must be clearly marked as such, and if the derived work is
13169695Skan * incompatible with the protocol description in the RFC file, it must be
14169695Skan * called by a name other than "ssh" or "Secure Shell".
15169695Skan *
16169695Skan *
17169695Skan * SSH2 packet format added by Markus Friedl.
18169695Skan * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
19169695Skan *
20169695Skan * Redistribution and use in source and binary forms, with or without
21169695Skan * modification, are permitted provided that the following conditions
22169695Skan * are met:
23169695Skan * 1. Redistributions of source code must retain the above copyright
24169695Skan *    notice, this list of conditions and the following disclaimer.
25169695Skan * 2. Redistributions in binary form must reproduce the above copyright
26169695Skan *    notice, this list of conditions and the following disclaimer in the
27169695Skan *    documentation and/or other materials provided with the distribution.
28169695Skan *
29169695Skan * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
30169695Skan * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
31169695Skan * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
32169695Skan * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
33169695Skan * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
34169695Skan * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35169695Skan * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36169695Skan * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37169695Skan * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
38169695Skan * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39169695Skan */
40169695Skan
41169695Skan#include "includes.h"
42169695Skan
43169695Skan#include <sys/types.h>
44169695Skan#include "openbsd-compat/sys-queue.h"
45169695Skan#include <sys/param.h>
46169695Skan#include <sys/socket.h>
47169695Skan#ifdef HAVE_SYS_TIME_H
48169695Skan# include <sys/time.h>
49169695Skan#endif
50169695Skan
51169695Skan#include <netinet/in.h>
52169695Skan#include <netinet/ip.h>
53169695Skan#include <arpa/inet.h>
54169695Skan
55169695Skan#include <errno.h>
56169695Skan#include <stdarg.h>
57169695Skan#include <stdio.h>
58169695Skan#include <stdlib.h>
59169695Skan#include <string.h>
60169695Skan#include <unistd.h>
61169695Skan#include <signal.h>
62169695Skan
63169695Skan#include "xmalloc.h"
64169695Skan#include "buffer.h"
65169695Skan#include "packet.h"
66169695Skan#include "crc32.h"
67169695Skan#include "compress.h"
68169695Skan#include "deattack.h"
69169695Skan#include "channels.h"
70169695Skan#include "compat.h"
71169695Skan#include "ssh1.h"
72169695Skan#include "ssh2.h"
73169695Skan#include "cipher.h"
74169695Skan#include "key.h"
75169695Skan#include "kex.h"
76169695Skan#include "mac.h"
77169695Skan#include "log.h"
78169695Skan#include "canohost.h"
79169695Skan#include "misc.h"
80169695Skan#include "ssh.h"
81169695Skan#include "roaming.h"
82169695Skan
83169695Skan#ifdef PACKET_DEBUG
84169695Skan#define DBG(x) x
85169695Skan#else
86169695Skan#define DBG(x)
87169695Skan#endif
88169695Skan
89169695Skan#define PACKET_MAX_SIZE (256 * 1024)
90169695Skan
91169695Skanstruct packet_state {
92169695Skan	u_int32_t seqnr;
93169695Skan	u_int32_t packets;
94169695Skan	u_int64_t blocks;
95169695Skan	u_int64_t bytes;
96169695Skan};
97169695Skan
98169695Skanstruct packet {
99169695Skan	TAILQ_ENTRY(packet) next;
100169695Skan	u_char type;
101169695Skan	Buffer payload;
102169695Skan};
103169695Skan
104169695Skanstruct session_state {
105169695Skan	/*
106169695Skan	 * This variable contains the file descriptors used for
107169695Skan	 * communicating with the other side.  connection_in is used for
108169695Skan	 * reading; connection_out for writing.  These can be the same
109169695Skan	 * descriptor, in which case it is assumed to be a socket.
110169695Skan	 */
111169695Skan	int connection_in;
112169695Skan	int connection_out;
113169695Skan
114169695Skan	/* Protocol flags for the remote side. */
115169695Skan	u_int remote_protocol_flags;
116169695Skan
117169695Skan	/* Encryption context for receiving data.  Only used for decryption. */
118169695Skan	CipherContext receive_context;
119169695Skan
120169695Skan	/* Encryption context for sending data.  Only used for encryption. */
121169695Skan	CipherContext send_context;
122169695Skan
123169695Skan	/* Buffer for raw input data from the socket. */
124169695Skan	Buffer input;
125169695Skan
126169695Skan	/* Buffer for raw output data going to the socket. */
127169695Skan	Buffer output;
128169695Skan
129169695Skan	/* Buffer for the partial outgoing packet being constructed. */
130169695Skan	Buffer outgoing_packet;
131169695Skan
132169695Skan	/* Buffer for the incoming packet currently being processed. */
133169695Skan	Buffer incoming_packet;
134169695Skan
135169695Skan	/* Scratch buffer for packet compression/decompression. */
136169695Skan	Buffer compression_buffer;
137169695Skan	int compression_buffer_ready;
138169695Skan
139169695Skan	/*
140169695Skan	 * Flag indicating whether packet compression/decompression is
141169695Skan	 * enabled.
142169695Skan	 */
143169695Skan	int packet_compression;
144169695Skan
145169695Skan	/* default maximum packet size */
146169695Skan	u_int max_packet_size;
147169695Skan
148169695Skan	/* Flag indicating whether this module has been initialized. */
149169695Skan	int initialized;
150169695Skan
151169695Skan	/* Set to true if the connection is interactive. */
152169695Skan	int interactive_mode;
153169695Skan
154169695Skan	/* Set to true if we are the server side. */
155169695Skan	int server_side;
156169695Skan
157169695Skan	/* Set to true if we are authenticated. */
158169695Skan	int after_authentication;
159169695Skan
160169695Skan	int keep_alive_timeouts;
161169695Skan
162169695Skan	/* The maximum time that we will wait to send or receive a packet */
163169695Skan	int packet_timeout_ms;
164169695Skan
165169695Skan	/* Session key information for Encryption and MAC */
166169695Skan	Newkeys *newkeys[MODE_MAX];
167169695Skan	struct packet_state p_read, p_send;
168169695Skan
169169695Skan	u_int64_t max_blocks_in, max_blocks_out;
170169695Skan	u_int32_t rekey_limit;
171169695Skan
172169695Skan	/* Session key for protocol v1 */
173169695Skan	u_char ssh1_key[SSH_SESSION_KEY_LENGTH];
174169695Skan	u_int ssh1_keylen;
175169695Skan
176169695Skan	/* roundup current message to extra_pad bytes */
177169695Skan	u_char extra_pad;
178169695Skan
179169695Skan	/* XXX discard incoming data after MAC error */
180169695Skan	u_int packet_discard;
181169695Skan	Mac *packet_discard_mac;
182169695Skan
183169695Skan	/* Used in packet_read_poll2() */
184169695Skan	u_int packlen;
185169695Skan
186169695Skan	/* Used in packet_send2 */
187169695Skan	int rekeying;
188169695Skan
189169695Skan	/* Used in packet_set_interactive */
190169695Skan	int set_interactive_called;
191169695Skan
192169695Skan	/* Used in packet_set_maxsize */
193169695Skan	int set_maxsize_called;
194169695Skan
195169695Skan	TAILQ_HEAD(, packet) outgoing;
196169695Skan};
197169695Skan
198169695Skanstatic struct session_state *active_state, *backup_state;
199169695Skan#ifdef	NONE_CIPHER_ENABLED
200169695Skanstatic int rekey_requested = 0;
201169695Skan#endif
202169695Skan
203169695Skanstatic struct session_state *
204169695Skanalloc_session_state(void)
205169695Skan{
206169695Skan	struct session_state *s = xcalloc(1, sizeof(*s));
207169695Skan
208169695Skan	s->connection_in = -1;
209169695Skan	s->connection_out = -1;
210169695Skan	s->max_packet_size = 32768;
211169695Skan	s->packet_timeout_ms = -1;
212169695Skan	return s;
213169695Skan}
214169695Skan
215169695Skan/*
216169695Skan * Sets the descriptors used for communication.  Disables encryption until
217169695Skan * packet_set_encryption_key is called.
218169695Skan */
219169695Skanvoid
220169695Skanpacket_set_connection(int fd_in, int fd_out)
221169695Skan{
222169695Skan	Cipher *none = cipher_by_name("none");
223169695Skan
224169695Skan	if (none == NULL)
225169695Skan		fatal("packet_set_connection: cannot load cipher 'none'");
226169695Skan	if (active_state == NULL)
227169695Skan		active_state = alloc_session_state();
228169695Skan	active_state->connection_in = fd_in;
229169695Skan	active_state->connection_out = fd_out;
230169695Skan	cipher_init(&active_state->send_context, none, (const u_char *)"",
231169695Skan	    0, NULL, 0, CIPHER_ENCRYPT);
232169695Skan	cipher_init(&active_state->receive_context, none, (const u_char *)"",
233169695Skan	    0, NULL, 0, CIPHER_DECRYPT);
234169695Skan	active_state->newkeys[MODE_IN] = active_state->newkeys[MODE_OUT] = NULL;
235169695Skan	if (!active_state->initialized) {
236169695Skan		active_state->initialized = 1;
237169695Skan		buffer_init(&active_state->input);
238169695Skan		buffer_init(&active_state->output);
239169695Skan		buffer_init(&active_state->outgoing_packet);
240169695Skan		buffer_init(&active_state->incoming_packet);
241169695Skan		TAILQ_INIT(&active_state->outgoing);
242169695Skan		active_state->p_send.packets = active_state->p_read.packets = 0;
243169695Skan	}
244169695Skan}
245169695Skan
246169695Skanvoid
247169695Skanpacket_set_timeout(int timeout, int count)
248169695Skan{
249169695Skan	if (timeout == 0 || count == 0) {
250169695Skan		active_state->packet_timeout_ms = -1;
251169695Skan		return;
252169695Skan	}
253169695Skan	if ((INT_MAX / 1000) / count < timeout)
254169695Skan		active_state->packet_timeout_ms = INT_MAX;
255169695Skan	else
256169695Skan		active_state->packet_timeout_ms = timeout * count * 1000;
257169695Skan}
258169695Skan
259169695Skanstatic void
260169695Skanpacket_stop_discard(void)
261169695Skan{
262169695Skan	if (active_state->packet_discard_mac) {
263169695Skan		char buf[1024];
264169695Skan
265169695Skan		memset(buf, 'a', sizeof(buf));
266169695Skan		while (buffer_len(&active_state->incoming_packet) <
267169695Skan		    PACKET_MAX_SIZE)
268169695Skan			buffer_append(&active_state->incoming_packet, buf,
269169695Skan			    sizeof(buf));
270169695Skan		(void) mac_compute(active_state->packet_discard_mac,
271169695Skan		    active_state->p_read.seqnr,
272169695Skan		    buffer_ptr(&active_state->incoming_packet),
273169695Skan		    PACKET_MAX_SIZE);
274169695Skan	}
275169695Skan	logit("Finished discarding for %.200s", get_remote_ipaddr());
276169695Skan	cleanup_exit(255);
277169695Skan}
278169695Skan
279169695Skanstatic void
280169695Skanpacket_start_discard(Enc *enc, Mac *mac, u_int packet_length, u_int discard)
281169695Skan{
282169695Skan	if (enc == NULL || !cipher_is_cbc(enc->cipher))
283169695Skan		packet_disconnect("Packet corrupt");
284169695Skan	if (packet_length != PACKET_MAX_SIZE && mac && mac->enabled)
285169695Skan		active_state->packet_discard_mac = mac;
286169695Skan	if (buffer_len(&active_state->input) >= discard)
287169695Skan		packet_stop_discard();
288169695Skan	active_state->packet_discard = discard -
289169695Skan	    buffer_len(&active_state->input);
290169695Skan}
291169695Skan
292169695Skan/* Returns 1 if remote host is connected via socket, 0 if not. */
293169695Skan
294169695Skanint
295169695Skanpacket_connection_is_on_socket(void)
296169695Skan{
297169695Skan	struct sockaddr_storage from, to;
298169695Skan	socklen_t fromlen, tolen;
299169695Skan
300169695Skan	/* filedescriptors in and out are the same, so it's a socket */
301169695Skan	if (active_state->connection_in == active_state->connection_out)
302169695Skan		return 1;
303169695Skan	fromlen = sizeof(from);
304169695Skan	memset(&from, 0, sizeof(from));
305169695Skan	if (getpeername(active_state->connection_in, (struct sockaddr *)&from,
306169695Skan	    &fromlen) < 0)
307169695Skan		return 0;
308169695Skan	tolen = sizeof(to);
309169695Skan	memset(&to, 0, sizeof(to));
310169695Skan	if (getpeername(active_state->connection_out, (struct sockaddr *)&to,
311169695Skan	    &tolen) < 0)
312169695Skan		return 0;
313169695Skan	if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
314169695Skan		return 0;
315169695Skan	if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
316169695Skan		return 0;
317169695Skan	return 1;
318169695Skan}
319169695Skan
320169695Skan/*
321169695Skan * Exports an IV from the CipherContext required to export the key
322169695Skan * state back from the unprivileged child to the privileged parent
323169695Skan * process.
324169695Skan */
325169695Skan
326169695Skanvoid
327169695Skanpacket_get_keyiv(int mode, u_char *iv, u_int len)
328169695Skan{
329169695Skan	CipherContext *cc;
330169695Skan
331169695Skan	if (mode == MODE_OUT)
332169695Skan		cc = &active_state->send_context;
333169695Skan	else
334169695Skan		cc = &active_state->receive_context;
335169695Skan
336169695Skan	cipher_get_keyiv(cc, iv, len);
337169695Skan}
338169695Skan
339169695Skanint
340169695Skanpacket_get_keycontext(int mode, u_char *dat)
341169695Skan{
342169695Skan	CipherContext *cc;
343169695Skan
344169695Skan	if (mode == MODE_OUT)
345169695Skan		cc = &active_state->send_context;
346169695Skan	else
347169695Skan		cc = &active_state->receive_context;
348169695Skan
349169695Skan	return (cipher_get_keycontext(cc, dat));
350169695Skan}
351169695Skan
352169695Skanvoid
353169695Skanpacket_set_keycontext(int mode, u_char *dat)
354169695Skan{
355169695Skan	CipherContext *cc;
356169695Skan
357169695Skan	if (mode == MODE_OUT)
358169695Skan		cc = &active_state->send_context;
359169695Skan	else
360169695Skan		cc = &active_state->receive_context;
361169695Skan
362169695Skan	cipher_set_keycontext(cc, dat);
363169695Skan}
364169695Skan
365169695Skanint
366169695Skanpacket_get_keyiv_len(int mode)
367169695Skan{
368169695Skan	CipherContext *cc;
369169695Skan
370169695Skan	if (mode == MODE_OUT)
371169695Skan		cc = &active_state->send_context;
372169695Skan	else
373169695Skan		cc = &active_state->receive_context;
374169695Skan
375169695Skan	return (cipher_get_keyiv_len(cc));
376169695Skan}
377169695Skan
378169695Skanvoid
379169695Skanpacket_set_iv(int mode, u_char *dat)
380169695Skan{
381169695Skan	CipherContext *cc;
382169695Skan
383169695Skan	if (mode == MODE_OUT)
384169695Skan		cc = &active_state->send_context;
385169695Skan	else
386169695Skan		cc = &active_state->receive_context;
387169695Skan
388169695Skan	cipher_set_keyiv(cc, dat);
389169695Skan}
390169695Skan
391169695Skanint
392169695Skanpacket_get_ssh1_cipher(void)
393169695Skan{
394169695Skan	return (cipher_get_number(active_state->receive_context.cipher));
395169695Skan}
396169695Skan
397169695Skanvoid
398169695Skanpacket_get_state(int mode, u_int32_t *seqnr, u_int64_t *blocks,
399169695Skan    u_int32_t *packets, u_int64_t *bytes)
400169695Skan{
401169695Skan	struct packet_state *state;
402169695Skan
403169695Skan	state = (mode == MODE_IN) ?
404169695Skan	    &active_state->p_read : &active_state->p_send;
405169695Skan	if (seqnr)
406169695Skan		*seqnr = state->seqnr;
407169695Skan	if (blocks)
408169695Skan		*blocks = state->blocks;
409169695Skan	if (packets)
410169695Skan		*packets = state->packets;
411169695Skan	if (bytes)
412169695Skan		*bytes = state->bytes;
413169695Skan}
414169695Skan
415169695Skanvoid
416169695Skanpacket_set_state(int mode, u_int32_t seqnr, u_int64_t blocks, u_int32_t packets,
417169695Skan    u_int64_t bytes)
418169695Skan{
419169695Skan	struct packet_state *state;
420169695Skan
421169695Skan	state = (mode == MODE_IN) ?
422169695Skan	    &active_state->p_read : &active_state->p_send;
423169695Skan	state->seqnr = seqnr;
424169695Skan	state->blocks = blocks;
425169695Skan	state->packets = packets;
426169695Skan	state->bytes = bytes;
427169695Skan}
428169695Skan
429169695Skan/* returns 1 if connection is via ipv4 */
430169695Skan
431169695Skanint
432169695Skanpacket_connection_is_ipv4(void)
433169695Skan{
434169695Skan	struct sockaddr_storage to;
435169695Skan	socklen_t tolen = sizeof(to);
436169695Skan
437169695Skan	memset(&to, 0, sizeof(to));
438169695Skan	if (getsockname(active_state->connection_out, (struct sockaddr *)&to,
439169695Skan	    &tolen) < 0)
440169695Skan		return 0;
441169695Skan	if (to.ss_family == AF_INET)
442169695Skan		return 1;
443169695Skan#ifdef IPV4_IN_IPV6
444169695Skan	if (to.ss_family == AF_INET6 &&
445169695Skan	    IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&to)->sin6_addr))
446169695Skan		return 1;
447169695Skan#endif
448169695Skan	return 0;
449169695Skan}
450169695Skan
451169695Skan/* Sets the connection into non-blocking mode. */
452169695Skan
453169695Skanvoid
454169695Skanpacket_set_nonblocking(void)
455169695Skan{
456169695Skan	/* Set the socket into non-blocking mode. */
457169695Skan	set_nonblock(active_state->connection_in);
458169695Skan
459169695Skan	if (active_state->connection_out != active_state->connection_in)
460169695Skan		set_nonblock(active_state->connection_out);
461169695Skan}
462169695Skan
463169695Skan/* Returns the socket used for reading. */
464169695Skan
465169695Skanint
466169695Skanpacket_get_connection_in(void)
467169695Skan{
468169695Skan	return active_state->connection_in;
469169695Skan}
470169695Skan
471169695Skan/* Returns the descriptor used for writing. */
472169695Skan
473169695Skanint
474169695Skanpacket_get_connection_out(void)
475169695Skan{
476169695Skan	return active_state->connection_out;
477169695Skan}
478169695Skan
479169695Skan/* Closes the connection and clears and frees internal data structures. */
480169695Skan
481169695Skanvoid
482169695Skanpacket_close(void)
483169695Skan{
484169695Skan	if (!active_state->initialized)
485169695Skan		return;
486169695Skan	active_state->initialized = 0;
487169695Skan	if (active_state->connection_in == active_state->connection_out) {
488169695Skan		shutdown(active_state->connection_out, SHUT_RDWR);
489169695Skan		close(active_state->connection_out);
490169695Skan	} else {
491169695Skan		close(active_state->connection_in);
492169695Skan		close(active_state->connection_out);
493169695Skan	}
494169695Skan	buffer_free(&active_state->input);
495169695Skan	buffer_free(&active_state->output);
496169695Skan	buffer_free(&active_state->outgoing_packet);
497169695Skan	buffer_free(&active_state->incoming_packet);
498169695Skan	if (active_state->compression_buffer_ready) {
499169695Skan		buffer_free(&active_state->compression_buffer);
500169695Skan		buffer_compress_uninit();
501169695Skan	}
502169695Skan	cipher_cleanup(&active_state->send_context);
503169695Skan	cipher_cleanup(&active_state->receive_context);
504169695Skan}
505169695Skan
506169695Skan/* Sets remote side protocol flags. */
507169695Skan
508169695Skanvoid
509169695Skanpacket_set_protocol_flags(u_int protocol_flags)
510169695Skan{
511169695Skan	active_state->remote_protocol_flags = protocol_flags;
512169695Skan}
513169695Skan
514169695Skan/* Returns the remote protocol flags set earlier by the above function. */
515169695Skan
516169695Skanu_int
517169695Skanpacket_get_protocol_flags(void)
518169695Skan{
519169695Skan	return active_state->remote_protocol_flags;
520169695Skan}
521169695Skan
522169695Skan/*
523169695Skan * Starts packet compression from the next packet on in both directions.
524169695Skan * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
525169695Skan */
526169695Skan
527169695Skanstatic void
528169695Skanpacket_init_compression(void)
529169695Skan{
530169695Skan	if (active_state->compression_buffer_ready == 1)
531169695Skan		return;
532169695Skan	active_state->compression_buffer_ready = 1;
533169695Skan	buffer_init(&active_state->compression_buffer);
534169695Skan}
535169695Skan
536169695Skanvoid
537169695Skanpacket_start_compression(int level)
538169695Skan{
539169695Skan	if (active_state->packet_compression && !compat20)
540169695Skan		fatal("Compression already enabled.");
541169695Skan	active_state->packet_compression = 1;
542169695Skan	packet_init_compression();
543169695Skan	buffer_compress_init_send(level);
544169695Skan	buffer_compress_init_recv();
545169695Skan}
546169695Skan
547169695Skan/*
548169695Skan * Causes any further packets to be encrypted using the given key.  The same
549169695Skan * key is used for both sending and reception.  However, both directions are
550169695Skan * encrypted independently of each other.
551169695Skan */
552169695Skan
553169695Skanvoid
554169695Skanpacket_set_encryption_key(const u_char *key, u_int keylen, int number)
555169695Skan{
556169695Skan	Cipher *cipher = cipher_by_number(number);
557169695Skan
558169695Skan	if (cipher == NULL)
559169695Skan		fatal("packet_set_encryption_key: unknown cipher number %d", number);
560169695Skan	if (keylen < 20)
561169695Skan		fatal("packet_set_encryption_key: keylen too small: %d", keylen);
562169695Skan	if (keylen > SSH_SESSION_KEY_LENGTH)
563169695Skan		fatal("packet_set_encryption_key: keylen too big: %d", keylen);
564169695Skan	memcpy(active_state->ssh1_key, key, keylen);
565169695Skan	active_state->ssh1_keylen = keylen;
566169695Skan	cipher_init(&active_state->send_context, cipher, key, keylen, NULL,
567169695Skan	    0, CIPHER_ENCRYPT);
568169695Skan	cipher_init(&active_state->receive_context, cipher, key, keylen, NULL,
569169695Skan	    0, CIPHER_DECRYPT);
570169695Skan}
571169695Skan
572169695Skanu_int
573169695Skanpacket_get_encryption_key(u_char *key)
574169695Skan{
575169695Skan	if (key == NULL)
576169695Skan		return (active_state->ssh1_keylen);
577169695Skan	memcpy(key, active_state->ssh1_key, active_state->ssh1_keylen);
578169695Skan	return (active_state->ssh1_keylen);
579169695Skan}
580169695Skan
581169695Skan/* Start constructing a packet to send. */
582169695Skanvoid
583169695Skanpacket_start(u_char type)
584169695Skan{
585169695Skan	u_char buf[9];
586169695Skan	int len;
587169695Skan
588169695Skan	DBG(debug("packet_start[%d]", type));
589169695Skan	len = compat20 ? 6 : 9;
590169695Skan	memset(buf, 0, len - 1);
591169695Skan	buf[len - 1] = type;
592169695Skan	buffer_clear(&active_state->outgoing_packet);
593169695Skan	buffer_append(&active_state->outgoing_packet, buf, len);
594169695Skan}
595169695Skan
596169695Skan/* Append payload. */
597169695Skanvoid
598169695Skanpacket_put_char(int value)
599169695Skan{
600169695Skan	char ch = value;
601169695Skan
602169695Skan	buffer_append(&active_state->outgoing_packet, &ch, 1);
603169695Skan}
604169695Skan
605169695Skanvoid
606169695Skanpacket_put_int(u_int value)
607169695Skan{
608169695Skan	buffer_put_int(&active_state->outgoing_packet, value);
609169695Skan}
610169695Skan
611169695Skanvoid
612169695Skanpacket_put_int64(u_int64_t value)
613169695Skan{
614169695Skan	buffer_put_int64(&active_state->outgoing_packet, value);
615169695Skan}
616169695Skan
617169695Skanvoid
618169695Skanpacket_put_string(const void *buf, u_int len)
619169695Skan{
620169695Skan	buffer_put_string(&active_state->outgoing_packet, buf, len);
621169695Skan}
622169695Skan
623169695Skanvoid
624169695Skanpacket_put_cstring(const char *str)
625169695Skan{
626169695Skan	buffer_put_cstring(&active_state->outgoing_packet, str);
627169695Skan}
628169695Skan
629169695Skanvoid
630169695Skanpacket_put_raw(const void *buf, u_int len)
631169695Skan{
632169695Skan	buffer_append(&active_state->outgoing_packet, buf, len);
633169695Skan}
634169695Skan
635169695Skanvoid
636169695Skanpacket_put_bignum(BIGNUM * value)
637169695Skan{
638169695Skan	buffer_put_bignum(&active_state->outgoing_packet, value);
639169695Skan}
640169695Skan
641169695Skanvoid
642169695Skanpacket_put_bignum2(BIGNUM * value)
643169695Skan{
644169695Skan	buffer_put_bignum2(&active_state->outgoing_packet, value);
645169695Skan}
646169695Skan
647169695Skan#ifdef OPENSSL_HAS_ECC
648169695Skanvoid
649169695Skanpacket_put_ecpoint(const EC_GROUP *curve, const EC_POINT *point)
650169695Skan{
651169695Skan	buffer_put_ecpoint(&active_state->outgoing_packet, curve, point);
652169695Skan}
653169695Skan#endif
654169695Skan
655169695Skan/*
656169695Skan * Finalizes and sends the packet.  If the encryption key has been set,
657169695Skan * encrypts the packet before sending.
658169695Skan */
659169695Skan
660169695Skanstatic void
661169695Skanpacket_send1(void)
662169695Skan{
663169695Skan	u_char buf[8], *cp;
664169695Skan	int i, padding, len;
665169695Skan	u_int checksum;
666169695Skan	u_int32_t rnd = 0;
667169695Skan
668169695Skan	/*
669169695Skan	 * If using packet compression, compress the payload of the outgoing
670169695Skan	 * packet.
671169695Skan	 */
672169695Skan	if (active_state->packet_compression) {
673169695Skan		buffer_clear(&active_state->compression_buffer);
674169695Skan		/* Skip padding. */
675169695Skan		buffer_consume(&active_state->outgoing_packet, 8);
676169695Skan		/* padding */
677169695Skan		buffer_append(&active_state->compression_buffer,
678169695Skan		    "\0\0\0\0\0\0\0\0", 8);
679169695Skan		buffer_compress(&active_state->outgoing_packet,
680169695Skan		    &active_state->compression_buffer);
681169695Skan		buffer_clear(&active_state->outgoing_packet);
682169695Skan		buffer_append(&active_state->outgoing_packet,
683169695Skan		    buffer_ptr(&active_state->compression_buffer),
684169695Skan		    buffer_len(&active_state->compression_buffer));
685169695Skan	}
686169695Skan	/* Compute packet length without padding (add checksum, remove padding). */
687169695Skan	len = buffer_len(&active_state->outgoing_packet) + 4 - 8;
688169695Skan
689169695Skan	/* Insert padding. Initialized to zero in packet_start1() */
690169695Skan	padding = 8 - len % 8;
691169695Skan	if (!active_state->send_context.plaintext) {
692169695Skan		cp = buffer_ptr(&active_state->outgoing_packet);
693169695Skan		for (i = 0; i < padding; i++) {
694169695Skan			if (i % 4 == 0)
695169695Skan				rnd = arc4random();
696169695Skan			cp[7 - i] = rnd & 0xff;
697169695Skan			rnd >>= 8;
698169695Skan		}
699169695Skan	}
700169695Skan	buffer_consume(&active_state->outgoing_packet, 8 - padding);
701169695Skan
702169695Skan	/* Add check bytes. */
703169695Skan	checksum = ssh_crc32(buffer_ptr(&active_state->outgoing_packet),
704169695Skan	    buffer_len(&active_state->outgoing_packet));
705169695Skan	put_u32(buf, checksum);
706169695Skan	buffer_append(&active_state->outgoing_packet, buf, 4);
707169695Skan
708169695Skan#ifdef PACKET_DEBUG
709169695Skan	fprintf(stderr, "packet_send plain: ");
710169695Skan	buffer_dump(&active_state->outgoing_packet);
711169695Skan#endif
712169695Skan
713169695Skan	/* Append to output. */
714169695Skan	put_u32(buf, len);
715169695Skan	buffer_append(&active_state->output, buf, 4);
716169695Skan	cp = buffer_append_space(&active_state->output,
717169695Skan	    buffer_len(&active_state->outgoing_packet));
718169695Skan	cipher_crypt(&active_state->send_context, cp,
719169695Skan	    buffer_ptr(&active_state->outgoing_packet),
720169695Skan	    buffer_len(&active_state->outgoing_packet));
721169695Skan
722169695Skan#ifdef PACKET_DEBUG
723169695Skan	fprintf(stderr, "encrypted: ");
724169695Skan	buffer_dump(&active_state->output);
725169695Skan#endif
726169695Skan	active_state->p_send.packets++;
727169695Skan	active_state->p_send.bytes += len +
728169695Skan	    buffer_len(&active_state->outgoing_packet);
729169695Skan	buffer_clear(&active_state->outgoing_packet);
730169695Skan
731169695Skan	/*
732169695Skan	 * Note that the packet is now only buffered in output.  It won't be
733169695Skan	 * actually sent until packet_write_wait or packet_write_poll is
734169695Skan	 * called.
735169695Skan	 */
736169695Skan}
737169695Skan
738169695Skanvoid
739169695Skanset_newkeys(int mode)
740169695Skan{
741169695Skan	Enc *enc;
742169695Skan	Mac *mac;
743169695Skan	Comp *comp;
744169695Skan	CipherContext *cc;
745169695Skan	u_int64_t *max_blocks;
746169695Skan	int crypt_type;
747169695Skan
748169695Skan	debug2("set_newkeys: mode %d", mode);
749169695Skan
750169695Skan	if (mode == MODE_OUT) {
751169695Skan		cc = &active_state->send_context;
752169695Skan		crypt_type = CIPHER_ENCRYPT;
753169695Skan		active_state->p_send.packets = active_state->p_send.blocks = 0;
754169695Skan		max_blocks = &active_state->max_blocks_out;
755169695Skan	} else {
756169695Skan		cc = &active_state->receive_context;
757169695Skan		crypt_type = CIPHER_DECRYPT;
758169695Skan		active_state->p_read.packets = active_state->p_read.blocks = 0;
759169695Skan		max_blocks = &active_state->max_blocks_in;
760169695Skan	}
761169695Skan	if (active_state->newkeys[mode] != NULL) {
762169695Skan		debug("set_newkeys: rekeying");
763169695Skan		cipher_cleanup(cc);
764169695Skan		enc  = &active_state->newkeys[mode]->enc;
765169695Skan		mac  = &active_state->newkeys[mode]->mac;
766169695Skan		comp = &active_state->newkeys[mode]->comp;
767169695Skan		mac_clear(mac);
768169695Skan		xfree(enc->name);
769169695Skan		xfree(enc->iv);
770169695Skan		xfree(enc->key);
771169695Skan		xfree(mac->name);
772169695Skan		xfree(mac->key);
773169695Skan		xfree(comp->name);
774169695Skan		xfree(active_state->newkeys[mode]);
775169695Skan	}
776169695Skan	active_state->newkeys[mode] = kex_get_newkeys(mode);
777169695Skan	if (active_state->newkeys[mode] == NULL)
778169695Skan		fatal("newkeys: no keys for mode %d", mode);
779169695Skan	enc  = &active_state->newkeys[mode]->enc;
780169695Skan	mac  = &active_state->newkeys[mode]->mac;
781169695Skan	comp = &active_state->newkeys[mode]->comp;
782169695Skan	if (mac_init(mac) == 0)
783169695Skan		mac->enabled = 1;
784169695Skan	DBG(debug("cipher_init_context: %d", mode));
785169695Skan	cipher_init(cc, enc->cipher, enc->key, enc->key_len,
786169695Skan	    enc->iv, enc->block_size, crypt_type);
787169695Skan	/* Deleting the keys does not gain extra security */
788169695Skan	/* memset(enc->iv,  0, enc->block_size);
789169695Skan	   memset(enc->key, 0, enc->key_len);
790169695Skan	   memset(mac->key, 0, mac->key_len); */
791169695Skan	if ((comp->type == COMP_ZLIB ||
792169695Skan	    (comp->type == COMP_DELAYED &&
793169695Skan	     active_state->after_authentication)) && comp->enabled == 0) {
794169695Skan		packet_init_compression();
795169695Skan		if (mode == MODE_OUT)
796169695Skan			buffer_compress_init_send(6);
797169695Skan		else
798169695Skan			buffer_compress_init_recv();
799169695Skan		comp->enabled = 1;
800169695Skan	}
801169695Skan	/*
802169695Skan	 * The 2^(blocksize*2) limit is too expensive for 3DES,
803169695Skan	 * blowfish, etc, so enforce a 1GB limit for small blocksizes.
804169695Skan	 */
805169695Skan	if (enc->block_size >= 16)
806169695Skan		*max_blocks = (u_int64_t)1 << (enc->block_size*2);
807169695Skan	else
808169695Skan		*max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
809169695Skan	if (active_state->rekey_limit)
810169695Skan		*max_blocks = MIN(*max_blocks,
811169695Skan		    active_state->rekey_limit / enc->block_size);
812169695Skan}
813169695Skan
814169695Skan/*
815169695Skan * Delayed compression for SSH2 is enabled after authentication:
816169695Skan * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
817169695Skan * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
818169695Skan */
819169695Skanstatic void
820169695Skanpacket_enable_delayed_compress(void)
821169695Skan{
822169695Skan	Comp *comp = NULL;
823169695Skan	int mode;
824169695Skan
825169695Skan	/*
826169695Skan	 * Remember that we are past the authentication step, so rekeying
827169695Skan	 * with COMP_DELAYED will turn on compression immediately.
828169695Skan	 */
829169695Skan	active_state->after_authentication = 1;
830169695Skan	for (mode = 0; mode < MODE_MAX; mode++) {
831169695Skan		/* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
832169695Skan		if (active_state->newkeys[mode] == NULL)
833169695Skan			continue;
834169695Skan		comp = &active_state->newkeys[mode]->comp;
835169695Skan		if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
836169695Skan			packet_init_compression();
837169695Skan			if (mode == MODE_OUT)
838169695Skan				buffer_compress_init_send(6);
839169695Skan			else
840169695Skan				buffer_compress_init_recv();
841169695Skan			comp->enabled = 1;
842169695Skan		}
843169695Skan	}
844169695Skan}
845169695Skan
846169695Skan/*
847169695Skan * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
848169695Skan */
849169695Skanstatic void
850169695Skanpacket_send2_wrapped(void)
851169695Skan{
852169695Skan	u_char type, *cp, *macbuf = NULL;
853169695Skan	u_char padlen, pad;
854169695Skan	u_int packet_length = 0;
855169695Skan	u_int i, len;
856169695Skan	u_int32_t rnd = 0;
857169695Skan	Enc *enc   = NULL;
858169695Skan	Mac *mac   = NULL;
859169695Skan	Comp *comp = NULL;
860169695Skan	int block_size;
861169695Skan
862169695Skan	if (active_state->newkeys[MODE_OUT] != NULL) {
863169695Skan		enc  = &active_state->newkeys[MODE_OUT]->enc;
864169695Skan		mac  = &active_state->newkeys[MODE_OUT]->mac;
865		comp = &active_state->newkeys[MODE_OUT]->comp;
866	}
867	block_size = enc ? enc->block_size : 8;
868
869	cp = buffer_ptr(&active_state->outgoing_packet);
870	type = cp[5];
871
872#ifdef PACKET_DEBUG
873	fprintf(stderr, "plain:     ");
874	buffer_dump(&active_state->outgoing_packet);
875#endif
876
877	if (comp && comp->enabled) {
878		len = buffer_len(&active_state->outgoing_packet);
879		/* skip header, compress only payload */
880		buffer_consume(&active_state->outgoing_packet, 5);
881		buffer_clear(&active_state->compression_buffer);
882		buffer_compress(&active_state->outgoing_packet,
883		    &active_state->compression_buffer);
884		buffer_clear(&active_state->outgoing_packet);
885		buffer_append(&active_state->outgoing_packet, "\0\0\0\0\0", 5);
886		buffer_append(&active_state->outgoing_packet,
887		    buffer_ptr(&active_state->compression_buffer),
888		    buffer_len(&active_state->compression_buffer));
889		DBG(debug("compression: raw %d compressed %d", len,
890		    buffer_len(&active_state->outgoing_packet)));
891	}
892
893	/* sizeof (packet_len + pad_len + payload) */
894	len = buffer_len(&active_state->outgoing_packet);
895
896	/*
897	 * calc size of padding, alloc space, get random data,
898	 * minimum padding is 4 bytes
899	 */
900	padlen = block_size - (len % block_size);
901	if (padlen < 4)
902		padlen += block_size;
903	if (active_state->extra_pad) {
904		/* will wrap if extra_pad+padlen > 255 */
905		active_state->extra_pad =
906		    roundup(active_state->extra_pad, block_size);
907		pad = active_state->extra_pad -
908		    ((len + padlen) % active_state->extra_pad);
909		debug3("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
910		    pad, len, padlen, active_state->extra_pad);
911		padlen += pad;
912		active_state->extra_pad = 0;
913	}
914	cp = buffer_append_space(&active_state->outgoing_packet, padlen);
915	if (enc && !active_state->send_context.plaintext) {
916		/* random padding */
917		for (i = 0; i < padlen; i++) {
918			if (i % 4 == 0)
919				rnd = arc4random();
920			cp[i] = rnd & 0xff;
921			rnd >>= 8;
922		}
923	} else {
924		/* clear padding */
925		memset(cp, 0, padlen);
926	}
927	/* packet_length includes payload, padding and padding length field */
928	packet_length = buffer_len(&active_state->outgoing_packet) - 4;
929	cp = buffer_ptr(&active_state->outgoing_packet);
930	put_u32(cp, packet_length);
931	cp[4] = padlen;
932	DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen));
933
934	/* compute MAC over seqnr and packet(length fields, payload, padding) */
935	if (mac && mac->enabled) {
936		macbuf = mac_compute(mac, active_state->p_send.seqnr,
937		    buffer_ptr(&active_state->outgoing_packet),
938		    buffer_len(&active_state->outgoing_packet));
939		DBG(debug("done calc MAC out #%d", active_state->p_send.seqnr));
940	}
941	/* encrypt packet and append to output buffer. */
942	cp = buffer_append_space(&active_state->output,
943	    buffer_len(&active_state->outgoing_packet));
944	cipher_crypt(&active_state->send_context, cp,
945	    buffer_ptr(&active_state->outgoing_packet),
946	    buffer_len(&active_state->outgoing_packet));
947	/* append unencrypted MAC */
948	if (mac && mac->enabled)
949		buffer_append(&active_state->output, macbuf, mac->mac_len);
950#ifdef PACKET_DEBUG
951	fprintf(stderr, "encrypted: ");
952	buffer_dump(&active_state->output);
953#endif
954	/* increment sequence number for outgoing packets */
955	if (++active_state->p_send.seqnr == 0)
956		logit("outgoing seqnr wraps around");
957	if (++active_state->p_send.packets == 0)
958		if (!(datafellows & SSH_BUG_NOREKEY))
959			fatal("XXX too many packets with same key");
960	active_state->p_send.blocks += (packet_length + 4) / block_size;
961	active_state->p_send.bytes += packet_length + 4;
962	buffer_clear(&active_state->outgoing_packet);
963
964	if (type == SSH2_MSG_NEWKEYS)
965		set_newkeys(MODE_OUT);
966	else if (type == SSH2_MSG_USERAUTH_SUCCESS && active_state->server_side)
967		packet_enable_delayed_compress();
968}
969
970static void
971packet_send2(void)
972{
973	struct packet *p;
974	u_char type, *cp;
975
976	cp = buffer_ptr(&active_state->outgoing_packet);
977	type = cp[5];
978
979	/* during rekeying we can only send key exchange messages */
980	if (active_state->rekeying) {
981		if (!((type >= SSH2_MSG_TRANSPORT_MIN) &&
982		    (type <= SSH2_MSG_TRANSPORT_MAX))) {
983			debug("enqueue packet: %u", type);
984			p = xmalloc(sizeof(*p));
985			p->type = type;
986			memcpy(&p->payload, &active_state->outgoing_packet,
987			    sizeof(Buffer));
988			buffer_init(&active_state->outgoing_packet);
989			TAILQ_INSERT_TAIL(&active_state->outgoing, p, next);
990			return;
991		}
992	}
993
994	/* rekeying starts with sending KEXINIT */
995	if (type == SSH2_MSG_KEXINIT)
996		active_state->rekeying = 1;
997
998	packet_send2_wrapped();
999
1000	/* after a NEWKEYS message we can send the complete queue */
1001	if (type == SSH2_MSG_NEWKEYS) {
1002		active_state->rekeying = 0;
1003		while ((p = TAILQ_FIRST(&active_state->outgoing))) {
1004			type = p->type;
1005			debug("dequeue packet: %u", type);
1006			buffer_free(&active_state->outgoing_packet);
1007			memcpy(&active_state->outgoing_packet, &p->payload,
1008			    sizeof(Buffer));
1009			TAILQ_REMOVE(&active_state->outgoing, p, next);
1010			xfree(p);
1011			packet_send2_wrapped();
1012		}
1013	}
1014}
1015
1016void
1017packet_send(void)
1018{
1019	if (compat20)
1020		packet_send2();
1021	else
1022		packet_send1();
1023	DBG(debug("packet_send done"));
1024}
1025
1026/*
1027 * Waits until a packet has been received, and returns its type.  Note that
1028 * no other data is processed until this returns, so this function should not
1029 * be used during the interactive session.
1030 */
1031
1032int
1033packet_read_seqnr(u_int32_t *seqnr_p)
1034{
1035	int type, len, ret, ms_remain, cont;
1036	fd_set *setp;
1037	char buf[8192];
1038	struct timeval timeout, start, *timeoutp = NULL;
1039
1040	DBG(debug("packet_read()"));
1041
1042	setp = (fd_set *)xcalloc(howmany(active_state->connection_in + 1,
1043	    NFDBITS), sizeof(fd_mask));
1044
1045	/* Since we are blocking, ensure that all written packets have been sent. */
1046	packet_write_wait();
1047
1048	/* Stay in the loop until we have received a complete packet. */
1049	for (;;) {
1050		/* Try to read a packet from the buffer. */
1051		type = packet_read_poll_seqnr(seqnr_p);
1052		if (!compat20 && (
1053		    type == SSH_SMSG_SUCCESS
1054		    || type == SSH_SMSG_FAILURE
1055		    || type == SSH_CMSG_EOF
1056		    || type == SSH_CMSG_EXIT_CONFIRMATION))
1057			packet_check_eom();
1058		/* If we got a packet, return it. */
1059		if (type != SSH_MSG_NONE) {
1060			xfree(setp);
1061			return type;
1062		}
1063		/*
1064		 * Otherwise, wait for some data to arrive, add it to the
1065		 * buffer, and try again.
1066		 */
1067		memset(setp, 0, howmany(active_state->connection_in + 1,
1068		    NFDBITS) * sizeof(fd_mask));
1069		FD_SET(active_state->connection_in, setp);
1070
1071		if (active_state->packet_timeout_ms > 0) {
1072			ms_remain = active_state->packet_timeout_ms;
1073			timeoutp = &timeout;
1074		}
1075		/* Wait for some data to arrive. */
1076		for (;;) {
1077			if (active_state->packet_timeout_ms != -1) {
1078				ms_to_timeval(&timeout, ms_remain);
1079				gettimeofday(&start, NULL);
1080			}
1081			if ((ret = select(active_state->connection_in + 1, setp,
1082			    NULL, NULL, timeoutp)) >= 0)
1083				break;
1084			if (errno != EAGAIN && errno != EINTR &&
1085			    errno != EWOULDBLOCK)
1086				break;
1087			if (active_state->packet_timeout_ms == -1)
1088				continue;
1089			ms_subtract_diff(&start, &ms_remain);
1090			if (ms_remain <= 0) {
1091				ret = 0;
1092				break;
1093			}
1094		}
1095		if (ret == 0) {
1096			logit("Connection to %.200s timed out while "
1097			    "waiting to read", get_remote_ipaddr());
1098			cleanup_exit(255);
1099		}
1100		/* Read data from the socket. */
1101		do {
1102			cont = 0;
1103			len = roaming_read(active_state->connection_in, buf,
1104			    sizeof(buf), &cont);
1105		} while (len == 0 && cont);
1106		if (len == 0) {
1107			logit("Connection closed by %.200s", get_remote_ipaddr());
1108			cleanup_exit(255);
1109		}
1110		if (len < 0)
1111			fatal("Read from socket failed: %.100s", strerror(errno));
1112		/* Append it to the buffer. */
1113		packet_process_incoming(buf, len);
1114	}
1115	/* NOTREACHED */
1116}
1117
1118int
1119packet_read(void)
1120{
1121	return packet_read_seqnr(NULL);
1122}
1123
1124/*
1125 * Waits until a packet has been received, verifies that its type matches
1126 * that given, and gives a fatal error and exits if there is a mismatch.
1127 */
1128
1129void
1130packet_read_expect(int expected_type)
1131{
1132	int type;
1133
1134	type = packet_read();
1135	if (type != expected_type)
1136		packet_disconnect("Protocol error: expected packet type %d, got %d",
1137		    expected_type, type);
1138}
1139
1140/* Checks if a full packet is available in the data received so far via
1141 * packet_process_incoming.  If so, reads the packet; otherwise returns
1142 * SSH_MSG_NONE.  This does not wait for data from the connection.
1143 *
1144 * SSH_MSG_DISCONNECT is handled specially here.  Also,
1145 * SSH_MSG_IGNORE messages are skipped by this function and are never returned
1146 * to higher levels.
1147 */
1148
1149static int
1150packet_read_poll1(void)
1151{
1152	u_int len, padded_len;
1153	u_char *cp, type;
1154	u_int checksum, stored_checksum;
1155
1156	/* Check if input size is less than minimum packet size. */
1157	if (buffer_len(&active_state->input) < 4 + 8)
1158		return SSH_MSG_NONE;
1159	/* Get length of incoming packet. */
1160	cp = buffer_ptr(&active_state->input);
1161	len = get_u32(cp);
1162	if (len < 1 + 2 + 2 || len > 256 * 1024)
1163		packet_disconnect("Bad packet length %u.", len);
1164	padded_len = (len + 8) & ~7;
1165
1166	/* Check if the packet has been entirely received. */
1167	if (buffer_len(&active_state->input) < 4 + padded_len)
1168		return SSH_MSG_NONE;
1169
1170	/* The entire packet is in buffer. */
1171
1172	/* Consume packet length. */
1173	buffer_consume(&active_state->input, 4);
1174
1175	/*
1176	 * Cryptographic attack detector for ssh
1177	 * (C)1998 CORE-SDI, Buenos Aires Argentina
1178	 * Ariel Futoransky(futo@core-sdi.com)
1179	 */
1180	if (!active_state->receive_context.plaintext) {
1181		switch (detect_attack(buffer_ptr(&active_state->input),
1182		    padded_len)) {
1183		case DEATTACK_DETECTED:
1184			packet_disconnect("crc32 compensation attack: "
1185			    "network attack detected");
1186		case DEATTACK_DOS_DETECTED:
1187			packet_disconnect("deattack denial of "
1188			    "service detected");
1189		}
1190	}
1191
1192	/* Decrypt data to incoming_packet. */
1193	buffer_clear(&active_state->incoming_packet);
1194	cp = buffer_append_space(&active_state->incoming_packet, padded_len);
1195	cipher_crypt(&active_state->receive_context, cp,
1196	    buffer_ptr(&active_state->input), padded_len);
1197
1198	buffer_consume(&active_state->input, padded_len);
1199
1200#ifdef PACKET_DEBUG
1201	fprintf(stderr, "read_poll plain: ");
1202	buffer_dump(&active_state->incoming_packet);
1203#endif
1204
1205	/* Compute packet checksum. */
1206	checksum = ssh_crc32(buffer_ptr(&active_state->incoming_packet),
1207	    buffer_len(&active_state->incoming_packet) - 4);
1208
1209	/* Skip padding. */
1210	buffer_consume(&active_state->incoming_packet, 8 - len % 8);
1211
1212	/* Test check bytes. */
1213	if (len != buffer_len(&active_state->incoming_packet))
1214		packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
1215		    len, buffer_len(&active_state->incoming_packet));
1216
1217	cp = (u_char *)buffer_ptr(&active_state->incoming_packet) + len - 4;
1218	stored_checksum = get_u32(cp);
1219	if (checksum != stored_checksum)
1220		packet_disconnect("Corrupted check bytes on input.");
1221	buffer_consume_end(&active_state->incoming_packet, 4);
1222
1223	if (active_state->packet_compression) {
1224		buffer_clear(&active_state->compression_buffer);
1225		buffer_uncompress(&active_state->incoming_packet,
1226		    &active_state->compression_buffer);
1227		buffer_clear(&active_state->incoming_packet);
1228		buffer_append(&active_state->incoming_packet,
1229		    buffer_ptr(&active_state->compression_buffer),
1230		    buffer_len(&active_state->compression_buffer));
1231	}
1232	active_state->p_read.packets++;
1233	active_state->p_read.bytes += padded_len + 4;
1234	type = buffer_get_char(&active_state->incoming_packet);
1235	if (type < SSH_MSG_MIN || type > SSH_MSG_MAX)
1236		packet_disconnect("Invalid ssh1 packet type: %d", type);
1237	return type;
1238}
1239
1240static int
1241packet_read_poll2(u_int32_t *seqnr_p)
1242{
1243	u_int padlen, need;
1244	u_char *macbuf, *cp, type;
1245	u_int maclen, block_size;
1246	Enc *enc   = NULL;
1247	Mac *mac   = NULL;
1248	Comp *comp = NULL;
1249
1250	if (active_state->packet_discard)
1251		return SSH_MSG_NONE;
1252
1253	if (active_state->newkeys[MODE_IN] != NULL) {
1254		enc  = &active_state->newkeys[MODE_IN]->enc;
1255		mac  = &active_state->newkeys[MODE_IN]->mac;
1256		comp = &active_state->newkeys[MODE_IN]->comp;
1257	}
1258	maclen = mac && mac->enabled ? mac->mac_len : 0;
1259	block_size = enc ? enc->block_size : 8;
1260
1261	if (active_state->packlen == 0) {
1262		/*
1263		 * check if input size is less than the cipher block size,
1264		 * decrypt first block and extract length of incoming packet
1265		 */
1266		if (buffer_len(&active_state->input) < block_size)
1267			return SSH_MSG_NONE;
1268		buffer_clear(&active_state->incoming_packet);
1269		cp = buffer_append_space(&active_state->incoming_packet,
1270		    block_size);
1271		cipher_crypt(&active_state->receive_context, cp,
1272		    buffer_ptr(&active_state->input), block_size);
1273		cp = buffer_ptr(&active_state->incoming_packet);
1274		active_state->packlen = get_u32(cp);
1275		if (active_state->packlen < 1 + 4 ||
1276		    active_state->packlen > PACKET_MAX_SIZE) {
1277#ifdef PACKET_DEBUG
1278			buffer_dump(&active_state->incoming_packet);
1279#endif
1280			logit("Bad packet length %u.", active_state->packlen);
1281			packet_start_discard(enc, mac, active_state->packlen,
1282			    PACKET_MAX_SIZE);
1283			return SSH_MSG_NONE;
1284		}
1285		DBG(debug("input: packet len %u", active_state->packlen+4));
1286		buffer_consume(&active_state->input, block_size);
1287	}
1288	/* we have a partial packet of block_size bytes */
1289	need = 4 + active_state->packlen - block_size;
1290	DBG(debug("partial packet %d, need %d, maclen %d", block_size,
1291	    need, maclen));
1292	if (need % block_size != 0) {
1293		logit("padding error: need %d block %d mod %d",
1294		    need, block_size, need % block_size);
1295		packet_start_discard(enc, mac, active_state->packlen,
1296		    PACKET_MAX_SIZE - block_size);
1297		return SSH_MSG_NONE;
1298	}
1299	/*
1300	 * check if the entire packet has been received and
1301	 * decrypt into incoming_packet
1302	 */
1303	if (buffer_len(&active_state->input) < need + maclen)
1304		return SSH_MSG_NONE;
1305#ifdef PACKET_DEBUG
1306	fprintf(stderr, "read_poll enc/full: ");
1307	buffer_dump(&active_state->input);
1308#endif
1309	cp = buffer_append_space(&active_state->incoming_packet, need);
1310	cipher_crypt(&active_state->receive_context, cp,
1311	    buffer_ptr(&active_state->input), need);
1312	buffer_consume(&active_state->input, need);
1313	/*
1314	 * compute MAC over seqnr and packet,
1315	 * increment sequence number for incoming packet
1316	 */
1317	if (mac && mac->enabled) {
1318		macbuf = mac_compute(mac, active_state->p_read.seqnr,
1319		    buffer_ptr(&active_state->incoming_packet),
1320		    buffer_len(&active_state->incoming_packet));
1321		if (timingsafe_bcmp(macbuf, buffer_ptr(&active_state->input),
1322		    mac->mac_len) != 0) {
1323			logit("Corrupted MAC on input.");
1324			if (need > PACKET_MAX_SIZE)
1325				fatal("internal error need %d", need);
1326			packet_start_discard(enc, mac, active_state->packlen,
1327			    PACKET_MAX_SIZE - need);
1328			return SSH_MSG_NONE;
1329		}
1330
1331		DBG(debug("MAC #%d ok", active_state->p_read.seqnr));
1332		buffer_consume(&active_state->input, mac->mac_len);
1333	}
1334	/* XXX now it's safe to use fatal/packet_disconnect */
1335	if (seqnr_p != NULL)
1336		*seqnr_p = active_state->p_read.seqnr;
1337	if (++active_state->p_read.seqnr == 0)
1338		logit("incoming seqnr wraps around");
1339	if (++active_state->p_read.packets == 0)
1340		if (!(datafellows & SSH_BUG_NOREKEY))
1341			fatal("XXX too many packets with same key");
1342	active_state->p_read.blocks += (active_state->packlen + 4) / block_size;
1343	active_state->p_read.bytes += active_state->packlen + 4;
1344
1345	/* get padlen */
1346	cp = buffer_ptr(&active_state->incoming_packet);
1347	padlen = cp[4];
1348	DBG(debug("input: padlen %d", padlen));
1349	if (padlen < 4)
1350		packet_disconnect("Corrupted padlen %d on input.", padlen);
1351
1352	/* skip packet size + padlen, discard padding */
1353	buffer_consume(&active_state->incoming_packet, 4 + 1);
1354	buffer_consume_end(&active_state->incoming_packet, padlen);
1355
1356	DBG(debug("input: len before de-compress %d",
1357	    buffer_len(&active_state->incoming_packet)));
1358	if (comp && comp->enabled) {
1359		buffer_clear(&active_state->compression_buffer);
1360		buffer_uncompress(&active_state->incoming_packet,
1361		    &active_state->compression_buffer);
1362		buffer_clear(&active_state->incoming_packet);
1363		buffer_append(&active_state->incoming_packet,
1364		    buffer_ptr(&active_state->compression_buffer),
1365		    buffer_len(&active_state->compression_buffer));
1366		DBG(debug("input: len after de-compress %d",
1367		    buffer_len(&active_state->incoming_packet)));
1368	}
1369	/*
1370	 * get packet type, implies consume.
1371	 * return length of payload (without type field)
1372	 */
1373	type = buffer_get_char(&active_state->incoming_packet);
1374	if (type < SSH2_MSG_MIN || type >= SSH2_MSG_LOCAL_MIN)
1375		packet_disconnect("Invalid ssh2 packet type: %d", type);
1376	if (type == SSH2_MSG_NEWKEYS)
1377		set_newkeys(MODE_IN);
1378	else if (type == SSH2_MSG_USERAUTH_SUCCESS &&
1379	    !active_state->server_side)
1380		packet_enable_delayed_compress();
1381#ifdef PACKET_DEBUG
1382	fprintf(stderr, "read/plain[%d]:\r\n", type);
1383	buffer_dump(&active_state->incoming_packet);
1384#endif
1385	/* reset for next packet */
1386	active_state->packlen = 0;
1387	return type;
1388}
1389
1390int
1391packet_read_poll_seqnr(u_int32_t *seqnr_p)
1392{
1393	u_int reason, seqnr;
1394	u_char type;
1395	char *msg;
1396
1397	for (;;) {
1398		if (compat20) {
1399			type = packet_read_poll2(seqnr_p);
1400			if (type) {
1401				active_state->keep_alive_timeouts = 0;
1402				DBG(debug("received packet type %d", type));
1403			}
1404			switch (type) {
1405			case SSH2_MSG_IGNORE:
1406				debug3("Received SSH2_MSG_IGNORE");
1407				break;
1408			case SSH2_MSG_DEBUG:
1409				packet_get_char();
1410				msg = packet_get_string(NULL);
1411				debug("Remote: %.900s", msg);
1412				xfree(msg);
1413				msg = packet_get_string(NULL);
1414				xfree(msg);
1415				break;
1416			case SSH2_MSG_DISCONNECT:
1417				reason = packet_get_int();
1418				msg = packet_get_string(NULL);
1419				logit("Received disconnect from %s: %u: %.400s",
1420				    get_remote_ipaddr(), reason, msg);
1421				xfree(msg);
1422				cleanup_exit(255);
1423				break;
1424			case SSH2_MSG_UNIMPLEMENTED:
1425				seqnr = packet_get_int();
1426				debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1427				    seqnr);
1428				break;
1429			default:
1430				return type;
1431			}
1432		} else {
1433			type = packet_read_poll1();
1434			switch (type) {
1435			case SSH_MSG_IGNORE:
1436				break;
1437			case SSH_MSG_DEBUG:
1438				msg = packet_get_string(NULL);
1439				debug("Remote: %.900s", msg);
1440				xfree(msg);
1441				break;
1442			case SSH_MSG_DISCONNECT:
1443				msg = packet_get_string(NULL);
1444				logit("Received disconnect from %s: %.400s",
1445				    get_remote_ipaddr(), msg);
1446				cleanup_exit(255);
1447				break;
1448			default:
1449				if (type)
1450					DBG(debug("received packet type %d", type));
1451				return type;
1452			}
1453		}
1454	}
1455}
1456
1457int
1458packet_read_poll(void)
1459{
1460	return packet_read_poll_seqnr(NULL);
1461}
1462
1463/*
1464 * Buffers the given amount of input characters.  This is intended to be used
1465 * together with packet_read_poll.
1466 */
1467
1468void
1469packet_process_incoming(const char *buf, u_int len)
1470{
1471	if (active_state->packet_discard) {
1472		active_state->keep_alive_timeouts = 0; /* ?? */
1473		if (len >= active_state->packet_discard)
1474			packet_stop_discard();
1475		active_state->packet_discard -= len;
1476		return;
1477	}
1478	buffer_append(&active_state->input, buf, len);
1479}
1480
1481/* Returns a character from the packet. */
1482
1483u_int
1484packet_get_char(void)
1485{
1486	char ch;
1487
1488	buffer_get(&active_state->incoming_packet, &ch, 1);
1489	return (u_char) ch;
1490}
1491
1492/* Returns an integer from the packet data. */
1493
1494u_int
1495packet_get_int(void)
1496{
1497	return buffer_get_int(&active_state->incoming_packet);
1498}
1499
1500/* Returns an 64 bit integer from the packet data. */
1501
1502u_int64_t
1503packet_get_int64(void)
1504{
1505	return buffer_get_int64(&active_state->incoming_packet);
1506}
1507
1508/*
1509 * Returns an arbitrary precision integer from the packet data.  The integer
1510 * must have been initialized before this call.
1511 */
1512
1513void
1514packet_get_bignum(BIGNUM * value)
1515{
1516	buffer_get_bignum(&active_state->incoming_packet, value);
1517}
1518
1519void
1520packet_get_bignum2(BIGNUM * value)
1521{
1522	buffer_get_bignum2(&active_state->incoming_packet, value);
1523}
1524
1525#ifdef OPENSSL_HAS_ECC
1526void
1527packet_get_ecpoint(const EC_GROUP *curve, EC_POINT *point)
1528{
1529	buffer_get_ecpoint(&active_state->incoming_packet, curve, point);
1530}
1531#endif
1532
1533void *
1534packet_get_raw(u_int *length_ptr)
1535{
1536	u_int bytes = buffer_len(&active_state->incoming_packet);
1537
1538	if (length_ptr != NULL)
1539		*length_ptr = bytes;
1540	return buffer_ptr(&active_state->incoming_packet);
1541}
1542
1543int
1544packet_remaining(void)
1545{
1546	return buffer_len(&active_state->incoming_packet);
1547}
1548
1549/*
1550 * Returns a string from the packet data.  The string is allocated using
1551 * xmalloc; it is the responsibility of the calling program to free it when
1552 * no longer needed.  The length_ptr argument may be NULL, or point to an
1553 * integer into which the length of the string is stored.
1554 */
1555
1556void *
1557packet_get_string(u_int *length_ptr)
1558{
1559	return buffer_get_string(&active_state->incoming_packet, length_ptr);
1560}
1561
1562void *
1563packet_get_string_ptr(u_int *length_ptr)
1564{
1565	return buffer_get_string_ptr(&active_state->incoming_packet, length_ptr);
1566}
1567
1568/* Ensures the returned string has no embedded \0 characters in it. */
1569char *
1570packet_get_cstring(u_int *length_ptr)
1571{
1572	return buffer_get_cstring(&active_state->incoming_packet, length_ptr);
1573}
1574
1575/*
1576 * Sends a diagnostic message from the server to the client.  This message
1577 * can be sent at any time (but not while constructing another message). The
1578 * message is printed immediately, but only if the client is being executed
1579 * in verbose mode.  These messages are primarily intended to ease debugging
1580 * authentication problems.   The length of the formatted message must not
1581 * exceed 1024 bytes.  This will automatically call packet_write_wait.
1582 */
1583
1584void
1585packet_send_debug(const char *fmt,...)
1586{
1587	char buf[1024];
1588	va_list args;
1589
1590	if (compat20 && (datafellows & SSH_BUG_DEBUG))
1591		return;
1592
1593	va_start(args, fmt);
1594	vsnprintf(buf, sizeof(buf), fmt, args);
1595	va_end(args);
1596
1597	if (compat20) {
1598		packet_start(SSH2_MSG_DEBUG);
1599		packet_put_char(0);	/* bool: always display */
1600		packet_put_cstring(buf);
1601		packet_put_cstring("");
1602	} else {
1603		packet_start(SSH_MSG_DEBUG);
1604		packet_put_cstring(buf);
1605	}
1606	packet_send();
1607	packet_write_wait();
1608}
1609
1610/*
1611 * Logs the error plus constructs and sends a disconnect packet, closes the
1612 * connection, and exits.  This function never returns. The error message
1613 * should not contain a newline.  The length of the formatted message must
1614 * not exceed 1024 bytes.
1615 */
1616
1617void
1618packet_disconnect(const char *fmt,...)
1619{
1620	char buf[1024];
1621	va_list args;
1622	static int disconnecting = 0;
1623
1624	if (disconnecting)	/* Guard against recursive invocations. */
1625		fatal("packet_disconnect called recursively.");
1626	disconnecting = 1;
1627
1628	/*
1629	 * Format the message.  Note that the caller must make sure the
1630	 * message is of limited size.
1631	 */
1632	va_start(args, fmt);
1633	vsnprintf(buf, sizeof(buf), fmt, args);
1634	va_end(args);
1635
1636	/* Display the error locally */
1637	logit("Disconnecting: %.100s", buf);
1638
1639	/* Send the disconnect message to the other side, and wait for it to get sent. */
1640	if (compat20) {
1641		packet_start(SSH2_MSG_DISCONNECT);
1642		packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1643		packet_put_cstring(buf);
1644		packet_put_cstring("");
1645	} else {
1646		packet_start(SSH_MSG_DISCONNECT);
1647		packet_put_cstring(buf);
1648	}
1649	packet_send();
1650	packet_write_wait();
1651
1652	/* Stop listening for connections. */
1653	channel_close_all();
1654
1655	/* Close the connection. */
1656	packet_close();
1657	cleanup_exit(255);
1658}
1659
1660/* Checks if there is any buffered output, and tries to write some of the output. */
1661
1662void
1663packet_write_poll(void)
1664{
1665	int len = buffer_len(&active_state->output);
1666	int cont;
1667
1668	if (len > 0) {
1669		cont = 0;
1670		len = roaming_write(active_state->connection_out,
1671		    buffer_ptr(&active_state->output), len, &cont);
1672		if (len == -1) {
1673			if (errno == EINTR || errno == EAGAIN ||
1674			    errno == EWOULDBLOCK)
1675				return;
1676			fatal("Write failed: %.100s", strerror(errno));
1677		}
1678		if (len == 0 && !cont)
1679			fatal("Write connection closed");
1680		buffer_consume(&active_state->output, len);
1681	}
1682}
1683
1684/*
1685 * Calls packet_write_poll repeatedly until all pending output data has been
1686 * written.
1687 */
1688
1689void
1690packet_write_wait(void)
1691{
1692	fd_set *setp;
1693	int ret, ms_remain;
1694	struct timeval start, timeout, *timeoutp = NULL;
1695
1696	setp = (fd_set *)xcalloc(howmany(active_state->connection_out + 1,
1697	    NFDBITS), sizeof(fd_mask));
1698	packet_write_poll();
1699	while (packet_have_data_to_write()) {
1700		memset(setp, 0, howmany(active_state->connection_out + 1,
1701		    NFDBITS) * sizeof(fd_mask));
1702		FD_SET(active_state->connection_out, setp);
1703
1704		if (active_state->packet_timeout_ms > 0) {
1705			ms_remain = active_state->packet_timeout_ms;
1706			timeoutp = &timeout;
1707		}
1708		for (;;) {
1709			if (active_state->packet_timeout_ms != -1) {
1710				ms_to_timeval(&timeout, ms_remain);
1711				gettimeofday(&start, NULL);
1712			}
1713			if ((ret = select(active_state->connection_out + 1,
1714			    NULL, setp, NULL, timeoutp)) >= 0)
1715				break;
1716			if (errno != EAGAIN && errno != EINTR &&
1717			    errno != EWOULDBLOCK)
1718				break;
1719			if (active_state->packet_timeout_ms == -1)
1720				continue;
1721			ms_subtract_diff(&start, &ms_remain);
1722			if (ms_remain <= 0) {
1723				ret = 0;
1724				break;
1725			}
1726		}
1727		if (ret == 0) {
1728			logit("Connection to %.200s timed out while "
1729			    "waiting to write", get_remote_ipaddr());
1730			cleanup_exit(255);
1731		}
1732		packet_write_poll();
1733	}
1734	xfree(setp);
1735}
1736
1737/* Returns true if there is buffered data to write to the connection. */
1738
1739int
1740packet_have_data_to_write(void)
1741{
1742	return buffer_len(&active_state->output) != 0;
1743}
1744
1745/* Returns true if there is not too much data to write to the connection. */
1746
1747int
1748packet_not_very_much_data_to_write(void)
1749{
1750	if (active_state->interactive_mode)
1751		return buffer_len(&active_state->output) < 16384;
1752	else
1753		return buffer_len(&active_state->output) < 128 * 1024;
1754}
1755
1756static void
1757packet_set_tos(int tos)
1758{
1759#if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1760	if (!packet_connection_is_on_socket() ||
1761	    !packet_connection_is_ipv4())
1762		return;
1763	debug3("%s: set IP_TOS 0x%02x", __func__, tos);
1764	if (setsockopt(active_state->connection_in, IPPROTO_IP, IP_TOS, &tos,
1765	    sizeof(tos)) < 0)
1766		error("setsockopt IP_TOS %d: %.100s:",
1767		    tos, strerror(errno));
1768#endif
1769}
1770
1771/* Informs that the current session is interactive.  Sets IP flags for that. */
1772
1773void
1774packet_set_interactive(int interactive, int qos_interactive, int qos_bulk)
1775{
1776	if (active_state->set_interactive_called)
1777		return;
1778	active_state->set_interactive_called = 1;
1779
1780	/* Record that we are in interactive mode. */
1781	active_state->interactive_mode = interactive;
1782
1783	/* Only set socket options if using a socket.  */
1784	if (!packet_connection_is_on_socket())
1785		return;
1786	set_nodelay(active_state->connection_in);
1787	packet_set_tos(interactive ? qos_interactive : qos_bulk);
1788}
1789
1790/* Returns true if the current connection is interactive. */
1791
1792int
1793packet_is_interactive(void)
1794{
1795	return active_state->interactive_mode;
1796}
1797
1798int
1799packet_set_maxsize(u_int s)
1800{
1801	if (active_state->set_maxsize_called) {
1802		logit("packet_set_maxsize: called twice: old %d new %d",
1803		    active_state->max_packet_size, s);
1804		return -1;
1805	}
1806	if (s < 4 * 1024 || s > 1024 * 1024) {
1807		logit("packet_set_maxsize: bad size %d", s);
1808		return -1;
1809	}
1810	active_state->set_maxsize_called = 1;
1811	debug("packet_set_maxsize: setting to %d", s);
1812	active_state->max_packet_size = s;
1813	return s;
1814}
1815
1816int
1817packet_inc_alive_timeouts(void)
1818{
1819	return ++active_state->keep_alive_timeouts;
1820}
1821
1822void
1823packet_set_alive_timeouts(int ka)
1824{
1825	active_state->keep_alive_timeouts = ka;
1826}
1827
1828u_int
1829packet_get_maxsize(void)
1830{
1831	return active_state->max_packet_size;
1832}
1833
1834/* roundup current message to pad bytes */
1835void
1836packet_add_padding(u_char pad)
1837{
1838	active_state->extra_pad = pad;
1839}
1840
1841/*
1842 * 9.2.  Ignored Data Message
1843 *
1844 *   byte      SSH_MSG_IGNORE
1845 *   string    data
1846 *
1847 * All implementations MUST understand (and ignore) this message at any
1848 * time (after receiving the protocol version). No implementation is
1849 * required to send them. This message can be used as an additional
1850 * protection measure against advanced traffic analysis techniques.
1851 */
1852void
1853packet_send_ignore(int nbytes)
1854{
1855	u_int32_t rnd = 0;
1856	int i;
1857
1858	packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1859	packet_put_int(nbytes);
1860	for (i = 0; i < nbytes; i++) {
1861		if (i % 4 == 0)
1862			rnd = arc4random();
1863		packet_put_char((u_char)rnd & 0xff);
1864		rnd >>= 8;
1865	}
1866}
1867
1868#ifdef	NONE_CIPHER_ENABLED
1869void
1870packet_request_rekeying(void)
1871{
1872	rekey_requested = 1;
1873}
1874#endif
1875
1876#define MAX_PACKETS	(1U<<31)
1877int
1878packet_need_rekeying(void)
1879{
1880	if (datafellows & SSH_BUG_NOREKEY)
1881		return 0;
1882#ifdef	NONE_CIPHER_ENABLED
1883	if (rekey_requested == 1) {
1884		rekey_requested = 0;
1885		return 1;
1886	}
1887#endif
1888	return
1889	    (active_state->p_send.packets > MAX_PACKETS) ||
1890	    (active_state->p_read.packets > MAX_PACKETS) ||
1891	    (active_state->max_blocks_out &&
1892	        (active_state->p_send.blocks > active_state->max_blocks_out)) ||
1893	    (active_state->max_blocks_in &&
1894	        (active_state->p_read.blocks > active_state->max_blocks_in));
1895}
1896
1897void
1898packet_set_rekey_limit(u_int32_t bytes)
1899{
1900	active_state->rekey_limit = bytes;
1901}
1902
1903void
1904packet_set_server(void)
1905{
1906	active_state->server_side = 1;
1907}
1908
1909void
1910packet_set_authenticated(void)
1911{
1912	active_state->after_authentication = 1;
1913}
1914
1915void *
1916packet_get_input(void)
1917{
1918	return (void *)&active_state->input;
1919}
1920
1921void *
1922packet_get_output(void)
1923{
1924	return (void *)&active_state->output;
1925}
1926
1927void *
1928packet_get_newkeys(int mode)
1929{
1930	return (void *)active_state->newkeys[mode];
1931}
1932
1933/*
1934 * Save the state for the real connection, and use a separate state when
1935 * resuming a suspended connection.
1936 */
1937void
1938packet_backup_state(void)
1939{
1940	struct session_state *tmp;
1941
1942	close(active_state->connection_in);
1943	active_state->connection_in = -1;
1944	close(active_state->connection_out);
1945	active_state->connection_out = -1;
1946	if (backup_state)
1947		tmp = backup_state;
1948	else
1949		tmp = alloc_session_state();
1950	backup_state = active_state;
1951	active_state = tmp;
1952}
1953
1954/*
1955 * Swap in the old state when resuming a connecion.
1956 */
1957void
1958packet_restore_state(void)
1959{
1960	struct session_state *tmp;
1961	void *buf;
1962	u_int len;
1963
1964	tmp = backup_state;
1965	backup_state = active_state;
1966	active_state = tmp;
1967	active_state->connection_in = backup_state->connection_in;
1968	backup_state->connection_in = -1;
1969	active_state->connection_out = backup_state->connection_out;
1970	backup_state->connection_out = -1;
1971	len = buffer_len(&backup_state->input);
1972	if (len > 0) {
1973		buf = buffer_ptr(&backup_state->input);
1974		buffer_append(&active_state->input, buf, len);
1975		buffer_clear(&backup_state->input);
1976		add_recv_bytes(len);
1977	}
1978}
1979
1980#ifdef	NONE_CIPHER_ENABLED
1981int
1982packet_get_authentication_state(void)
1983{
1984	return (active_state->after_authentication);
1985}
1986#endif
1987