packet.c revision 248619
1331722Seadler/* $OpenBSD: packet.c,v 1.181 2013/02/10 23:35:24 djm Exp $ */
2341477Svmaffione/* $FreeBSD: head/crypto/openssh/packet.c 248619 2013-03-22 17:55:38Z des $ */
3341477Svmaffione/*
4261909Sluigi * Author: Tatu Ylonen <ylo@cs.hut.fi>
5261909Sluigi * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6261909Sluigi *                    All rights reserved
7261909Sluigi * This file contains code implementing the packet protocol and communication
8261909Sluigi * with the other side.  This same code is used both on client and server side.
9261909Sluigi *
10261909Sluigi * As far as I am concerned, the code I have written for this software
11261909Sluigi * can be used freely for any purpose.  Any derived versions of this
12261909Sluigi * software must be clearly marked as such, and if the derived work is
13261909Sluigi * incompatible with the protocol description in the RFC file, it must be
14261909Sluigi * called by a name other than "ssh" or "Secure Shell".
15261909Sluigi *
16261909Sluigi *
17261909Sluigi * SSH2 packet format added by Markus Friedl.
18261909Sluigi * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
19261909Sluigi *
20261909Sluigi * Redistribution and use in source and binary forms, with or without
21261909Sluigi * modification, are permitted provided that the following conditions
22261909Sluigi * are met:
23261909Sluigi * 1. Redistributions of source code must retain the above copyright
24261909Sluigi *    notice, this list of conditions and the following disclaimer.
25261909Sluigi * 2. Redistributions in binary form must reproduce the above copyright
26261909Sluigi *    notice, this list of conditions and the following disclaimer in the
27261909Sluigi *    documentation and/or other materials provided with the distribution.
28261909Sluigi *
29261909Sluigi * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
30261909Sluigi * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
31261909Sluigi * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
32261909Sluigi * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
33261909Sluigi * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
34261909Sluigi * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35261909Sluigi * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36261909Sluigi * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37261909Sluigi * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
38261909Sluigi * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39261909Sluigi */
40261909Sluigi
41261909Sluigi#include "includes.h"
42261909Sluigi
43261909Sluigi#include <sys/types.h>
44261909Sluigi#include "openbsd-compat/sys-queue.h"
45261909Sluigi#include <sys/param.h>
46261909Sluigi#include <sys/socket.h>
47261909Sluigi#ifdef HAVE_SYS_TIME_H
48261909Sluigi# include <sys/time.h>
49261909Sluigi#endif
50261909Sluigi
51261909Sluigi#include <netinet/in.h>
52261909Sluigi#include <netinet/ip.h>
53261909Sluigi#include <arpa/inet.h>
54261909Sluigi
55261909Sluigi#include <errno.h>
56261909Sluigi#include <stdarg.h>
57261909Sluigi#include <stdio.h>
58341477Svmaffione#include <stdlib.h>
59341477Svmaffione#include <string.h>
60341477Svmaffione#include <unistd.h>
61261909Sluigi#include <signal.h>
62261909Sluigi
63261909Sluigi#include "xmalloc.h"
64261909Sluigi#include "buffer.h"
65261909Sluigi#include "packet.h"
66261909Sluigi#include "crc32.h"
67261909Sluigi#include "compress.h"
68261909Sluigi#include "deattack.h"
69261909Sluigi#include "channels.h"
70261909Sluigi#include "compat.h"
71261909Sluigi#include "ssh1.h"
72261909Sluigi#include "ssh2.h"
73261909Sluigi#include "cipher.h"
74261909Sluigi#include "key.h"
75261909Sluigi#include "kex.h"
76261909Sluigi#include "mac.h"
77261909Sluigi#include "log.h"
78341477Svmaffione#include "canohost.h"
79261909Sluigi#include "misc.h"
80341477Svmaffione#include "ssh.h"
81341477Svmaffione#include "roaming.h"
82261909Sluigi
83341477Svmaffione#ifdef PACKET_DEBUG
84341477Svmaffione#define DBG(x) x
85341477Svmaffione#else
86261909Sluigi#define DBG(x)
87261909Sluigi#endif
88285349Sluigi
89285349Sluigi#define PACKET_MAX_SIZE (256 * 1024)
90261909Sluigi
91341477Svmaffionestruct packet_state {
92285349Sluigi	u_int32_t seqnr;
93261909Sluigi	u_int32_t packets;
94285349Sluigi	u_int64_t blocks;
95285349Sluigi	u_int64_t bytes;
96261909Sluigi};
97341477Svmaffione
98285349Sluigistruct packet {
99285349Sluigi	TAILQ_ENTRY(packet) next;
100261909Sluigi	u_char type;
101341477Svmaffione	Buffer payload;
102341477Svmaffione};
103341477Svmaffione
104285349Sluigistruct session_state {
105261909Sluigi	/*
106261909Sluigi	 * This variable contains the file descriptors used for
107285349Sluigi	 * communicating with the other side.  connection_in is used for
108261909Sluigi	 * reading; connection_out for writing.  These can be the same
109261909Sluigi	 * descriptor, in which case it is assumed to be a socket.
110261909Sluigi	 */
111261909Sluigi	int connection_in;
112261909Sluigi	int connection_out;
113261909Sluigi
114261909Sluigi	/* Protocol flags for the remote side. */
115261909Sluigi	u_int remote_protocol_flags;
116261909Sluigi
117261909Sluigi	/* Encryption context for receiving data.  Only used for decryption. */
118285349Sluigi	CipherContext receive_context;
119285349Sluigi
120285349Sluigi	/* Encryption context for sending data.  Only used for encryption. */
121285349Sluigi	CipherContext send_context;
122341477Svmaffione
123261909Sluigi	/* Buffer for raw input data from the socket. */
124261909Sluigi	Buffer input;
125261909Sluigi
126261909Sluigi	/* Buffer for raw output data going to the socket. */
127261909Sluigi	Buffer output;
128261909Sluigi
129261909Sluigi	/* Buffer for the partial outgoing packet being constructed. */
130261909Sluigi	Buffer outgoing_packet;
131341477Svmaffione
132261909Sluigi	/* Buffer for the incoming packet currently being processed. */
133261909Sluigi	Buffer incoming_packet;
134261909Sluigi
135261909Sluigi	/* Scratch buffer for packet compression/decompression. */
136261909Sluigi	Buffer compression_buffer;
137341477Svmaffione	int compression_buffer_ready;
138261909Sluigi
139341477Svmaffione	/*
140341477Svmaffione	 * Flag indicating whether packet compression/decompression is
141341477Svmaffione	 * enabled.
142341477Svmaffione	 */
143341477Svmaffione	int packet_compression;
144261909Sluigi
145261909Sluigi	/* default maximum packet size */
146261909Sluigi	u_int max_packet_size;
147261909Sluigi
148261909Sluigi	/* Flag indicating whether this module has been initialized. */
149261909Sluigi	int initialized;
150261909Sluigi
151261909Sluigi	/* Set to true if the connection is interactive. */
152261909Sluigi	int interactive_mode;
153261909Sluigi
154261909Sluigi	/* Set to true if we are the server side. */
155285349Sluigi	int server_side;
156285349Sluigi
157285349Sluigi	/* Set to true if we are authenticated. */
158285349Sluigi	int after_authentication;
159261909Sluigi
160261909Sluigi	int keep_alive_timeouts;
161261909Sluigi
162261909Sluigi	/* The maximum time that we will wait to send or receive a packet */
163261909Sluigi	int packet_timeout_ms;
164261909Sluigi
165261909Sluigi	/* Session key information for Encryption and MAC */
166261909Sluigi	Newkeys *newkeys[MODE_MAX];
167261909Sluigi	struct packet_state p_read, p_send;
168261909Sluigi
169261909Sluigi	u_int64_t max_blocks_in, max_blocks_out;
170261909Sluigi	u_int32_t rekey_limit;
171261909Sluigi
172261909Sluigi	/* Session key for protocol v1 */
173261909Sluigi	u_char ssh1_key[SSH_SESSION_KEY_LENGTH];
174285349Sluigi	u_int ssh1_keylen;
175285349Sluigi
176285349Sluigi	/* roundup current message to extra_pad bytes */
177285349Sluigi	u_char extra_pad;
178261909Sluigi
179261909Sluigi	/* XXX discard incoming data after MAC error */
180261909Sluigi	u_int packet_discard;
181261909Sluigi	Mac *packet_discard_mac;
182341477Svmaffione
183270063Sluigi	/* Used in packet_read_poll2() */
184261909Sluigi	u_int packlen;
185341477Svmaffione
186341477Svmaffione	/* Used in packet_send2 */
187341477Svmaffione	int rekeying;
188341477Svmaffione
189341477Svmaffione	/* Used in packet_set_interactive */
190261909Sluigi	int set_interactive_called;
191341477Svmaffione
192341477Svmaffione	/* Used in packet_set_maxsize */
193341477Svmaffione	int set_maxsize_called;
194341477Svmaffione
195261909Sluigi	TAILQ_HEAD(, packet) outgoing;
196341477Svmaffione};
197341477Svmaffione
198261909Sluigistatic struct session_state *active_state, *backup_state;
199341477Svmaffione#ifdef	NONE_CIPHER_ENABLED
200341477Svmaffionestatic int rekey_requested = 0;
201341477Svmaffione#endif
202341477Svmaffione
203341477Svmaffionestatic struct session_state *
204341477Svmaffionealloc_session_state(void)
205261909Sluigi{
206261909Sluigi	struct session_state *s = xcalloc(1, sizeof(*s));
207261909Sluigi
208341477Svmaffione	s->connection_in = -1;
209341477Svmaffione	s->connection_out = -1;
210341477Svmaffione	s->max_packet_size = 32768;
211341477Svmaffione	s->packet_timeout_ms = -1;
212261909Sluigi	return s;
213341477Svmaffione}
214341477Svmaffione
215341477Svmaffione/*
216341477Svmaffione * Sets the descriptors used for communication.  Disables encryption until
217341477Svmaffione * packet_set_encryption_key is called.
218341477Svmaffione */
219261909Sluigivoid
220341477Svmaffionepacket_set_connection(int fd_in, int fd_out)
221261909Sluigi{
222341477Svmaffione	Cipher *none = cipher_by_name("none");
223341477Svmaffione
224341477Svmaffione	if (none == NULL)
225261909Sluigi		fatal("packet_set_connection: cannot load cipher 'none'");
226341477Svmaffione	if (active_state == NULL)
227341477Svmaffione		active_state = alloc_session_state();
228341477Svmaffione	active_state->connection_in = fd_in;
229341477Svmaffione	active_state->connection_out = fd_out;
230341477Svmaffione	cipher_init(&active_state->send_context, none, (const u_char *)"",
231261909Sluigi	    0, NULL, 0, CIPHER_ENCRYPT);
232261909Sluigi	cipher_init(&active_state->receive_context, none, (const u_char *)"",
233261909Sluigi	    0, NULL, 0, CIPHER_DECRYPT);
234261909Sluigi	active_state->newkeys[MODE_IN] = active_state->newkeys[MODE_OUT] = NULL;
235341477Svmaffione	if (!active_state->initialized) {
236270063Sluigi		active_state->initialized = 1;
237261909Sluigi		buffer_init(&active_state->input);
238341477Svmaffione		buffer_init(&active_state->output);
239341477Svmaffione		buffer_init(&active_state->outgoing_packet);
240341477Svmaffione		buffer_init(&active_state->incoming_packet);
241341477Svmaffione		TAILQ_INIT(&active_state->outgoing);
242261909Sluigi		active_state->p_send.packets = active_state->p_read.packets = 0;
243341477Svmaffione	}
244341477Svmaffione}
245341477Svmaffione
246341477Svmaffionevoid
247261909Sluigipacket_set_timeout(int timeout, int count)
248341477Svmaffione{
249341477Svmaffione	if (timeout <= 0 || count <= 0) {
250341477Svmaffione		active_state->packet_timeout_ms = -1;
251341477Svmaffione		return;
252341477Svmaffione	}
253341477Svmaffione	if ((INT_MAX / 1000) / count < timeout)
254341477Svmaffione		active_state->packet_timeout_ms = INT_MAX;
255341477Svmaffione	else
256341477Svmaffione		active_state->packet_timeout_ms = timeout * count * 1000;
257341477Svmaffione}
258261909Sluigi
259341477Svmaffionestatic void
260341477Svmaffionepacket_stop_discard(void)
261341477Svmaffione{
262341477Svmaffione	if (active_state->packet_discard_mac) {
263341477Svmaffione		char buf[1024];
264341477Svmaffione
265341477Svmaffione		memset(buf, 'a', sizeof(buf));
266341477Svmaffione		while (buffer_len(&active_state->incoming_packet) <
267341477Svmaffione		    PACKET_MAX_SIZE)
268341477Svmaffione			buffer_append(&active_state->incoming_packet, buf,
269341477Svmaffione			    sizeof(buf));
270341477Svmaffione		(void) mac_compute(active_state->packet_discard_mac,
271341477Svmaffione		    active_state->p_read.seqnr,
272341477Svmaffione		    buffer_ptr(&active_state->incoming_packet),
273341477Svmaffione		    PACKET_MAX_SIZE);
274341477Svmaffione	}
275341477Svmaffione	logit("Finished discarding for %.200s", get_remote_ipaddr());
276341477Svmaffione	cleanup_exit(255);
277341477Svmaffione}
278341477Svmaffione
279341477Svmaffionestatic void
280341477Svmaffionepacket_start_discard(Enc *enc, Mac *mac, u_int packet_length, u_int discard)
281341477Svmaffione{
282261909Sluigi	if (enc == NULL || !cipher_is_cbc(enc->cipher) || (mac && mac->etm))
283261909Sluigi		packet_disconnect("Packet corrupt");
284261909Sluigi	if (packet_length != PACKET_MAX_SIZE && mac && mac->enabled)
285261909Sluigi		active_state->packet_discard_mac = mac;
286261909Sluigi	if (buffer_len(&active_state->input) >= discard)
287261909Sluigi		packet_stop_discard();
288261909Sluigi	active_state->packet_discard = discard -
289261909Sluigi	    buffer_len(&active_state->input);
290261909Sluigi}
291261909Sluigi
292261909Sluigi/* Returns 1 if remote host is connected via socket, 0 if not. */
293261909Sluigi
294261909Sluigiint
295261909Sluigipacket_connection_is_on_socket(void)
296261909Sluigi{
297261909Sluigi	struct sockaddr_storage from, to;
298261909Sluigi	socklen_t fromlen, tolen;
299261909Sluigi
300261909Sluigi	/* filedescriptors in and out are the same, so it's a socket */
301261909Sluigi	if (active_state->connection_in == active_state->connection_out)
302261909Sluigi		return 1;
303261909Sluigi	fromlen = sizeof(from);
304261909Sluigi	memset(&from, 0, sizeof(from));
305261909Sluigi	if (getpeername(active_state->connection_in, (struct sockaddr *)&from,
306261909Sluigi	    &fromlen) < 0)
307261909Sluigi		return 0;
308261909Sluigi	tolen = sizeof(to);
309261909Sluigi	memset(&to, 0, sizeof(to));
310261909Sluigi	if (getpeername(active_state->connection_out, (struct sockaddr *)&to,
311261909Sluigi	    &tolen) < 0)
312261909Sluigi		return 0;
313341477Svmaffione	if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
314261909Sluigi		return 0;
315261909Sluigi	if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
316261909Sluigi		return 0;
317261909Sluigi	return 1;
318261909Sluigi}
319261909Sluigi
320261909Sluigi/*
321261909Sluigi * Exports an IV from the CipherContext required to export the key
322261909Sluigi * state back from the unprivileged child to the privileged parent
323261909Sluigi * process.
324261909Sluigi */
325261909Sluigi
326261909Sluigivoid
327261909Sluigipacket_get_keyiv(int mode, u_char *iv, u_int len)
328261909Sluigi{
329341477Svmaffione	CipherContext *cc;
330261909Sluigi
331261909Sluigi	if (mode == MODE_OUT)
332261909Sluigi		cc = &active_state->send_context;
333261909Sluigi	else
334261909Sluigi		cc = &active_state->receive_context;
335261909Sluigi
336261909Sluigi	cipher_get_keyiv(cc, iv, len);
337261909Sluigi}
338285349Sluigi
339285349Sluigiint
340261909Sluigipacket_get_keycontext(int mode, u_char *dat)
341261909Sluigi{
342261909Sluigi	CipherContext *cc;
343261909Sluigi
344341477Svmaffione	if (mode == MODE_OUT)
345261909Sluigi		cc = &active_state->send_context;
346261909Sluigi	else
347261909Sluigi		cc = &active_state->receive_context;
348261909Sluigi
349341477Svmaffione	return (cipher_get_keycontext(cc, dat));
350341477Svmaffione}
351261909Sluigi
352261909Sluigivoid
353261909Sluigipacket_set_keycontext(int mode, u_char *dat)
354341477Svmaffione{
355285349Sluigi	CipherContext *cc;
356341477Svmaffione
357285349Sluigi	if (mode == MODE_OUT)
358341477Svmaffione		cc = &active_state->send_context;
359341477Svmaffione	else
360341477Svmaffione		cc = &active_state->receive_context;
361341477Svmaffione
362341477Svmaffione	cipher_set_keycontext(cc, dat);
363341477Svmaffione}
364341477Svmaffione
365341477Svmaffioneint
366341477Svmaffionepacket_get_keyiv_len(int mode)
367285349Sluigi{
368261909Sluigi	CipherContext *cc;
369341477Svmaffione
370261909Sluigi	if (mode == MODE_OUT)
371261909Sluigi		cc = &active_state->send_context;
372261909Sluigi	else
373261909Sluigi		cc = &active_state->receive_context;
374261909Sluigi
375261909Sluigi	return (cipher_get_keyiv_len(cc));
376261909Sluigi}
377261909Sluigi
378261909Sluigivoid
379261909Sluigipacket_set_iv(int mode, u_char *dat)
380261909Sluigi{
381261909Sluigi	CipherContext *cc;
382267128Sluigi
383261909Sluigi	if (mode == MODE_OUT)
384261909Sluigi		cc = &active_state->send_context;
385261909Sluigi	else
386261909Sluigi		cc = &active_state->receive_context;
387341477Svmaffione
388341477Svmaffione	cipher_set_keyiv(cc, dat);
389261909Sluigi}
390261909Sluigi
391261909Sluigiint
392261909Sluigipacket_get_ssh1_cipher(void)
393261909Sluigi{
394261909Sluigi	return (cipher_get_number(active_state->receive_context.cipher));
395267128Sluigi}
396261909Sluigi
397261909Sluigivoid
398261909Sluigipacket_get_state(int mode, u_int32_t *seqnr, u_int64_t *blocks,
399261909Sluigi    u_int32_t *packets, u_int64_t *bytes)
400261909Sluigi{
401261909Sluigi	struct packet_state *state;
402261909Sluigi
403261909Sluigi	state = (mode == MODE_IN) ?
404261909Sluigi	    &active_state->p_read : &active_state->p_send;
405261909Sluigi	if (seqnr)
406261909Sluigi		*seqnr = state->seqnr;
407261909Sluigi	if (blocks)
408261909Sluigi		*blocks = state->blocks;
409261909Sluigi	if (packets)
410341477Svmaffione		*packets = state->packets;
411261909Sluigi	if (bytes)
412261909Sluigi		*bytes = state->bytes;
413261909Sluigi}
414261909Sluigi
415261909Sluigivoid
416261909Sluigipacket_set_state(int mode, u_int32_t seqnr, u_int64_t blocks, u_int32_t packets,
417341477Svmaffione    u_int64_t bytes)
418341477Svmaffione{
419285349Sluigi	struct packet_state *state;
420285349Sluigi
421261909Sluigi	state = (mode == MODE_IN) ?
422261909Sluigi	    &active_state->p_read : &active_state->p_send;
423341477Svmaffione	state->seqnr = seqnr;
424341477Svmaffione	state->blocks = blocks;
425341477Svmaffione	state->packets = packets;
426341477Svmaffione	state->bytes = bytes;
427341477Svmaffione}
428341477Svmaffione
429341477Svmaffionestatic int
430341477Svmaffionepacket_connection_af(void)
431341477Svmaffione{
432341477Svmaffione	struct sockaddr_storage to;
433341477Svmaffione	socklen_t tolen = sizeof(to);
434341477Svmaffione
435341477Svmaffione	memset(&to, 0, sizeof(to));
436341477Svmaffione	if (getsockname(active_state->connection_out, (struct sockaddr *)&to,
437341477Svmaffione	    &tolen) < 0)
438341477Svmaffione		return 0;
439341477Svmaffione#ifdef IPV4_IN_IPV6
440341477Svmaffione	if (to.ss_family == AF_INET6 &&
441341477Svmaffione	    IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&to)->sin6_addr))
442341477Svmaffione		return AF_INET;
443341477Svmaffione#endif
444341477Svmaffione	return to.ss_family;
445341477Svmaffione}
446341477Svmaffione
447341477Svmaffione/* Sets the connection into non-blocking mode. */
448341477Svmaffione
449341477Svmaffionevoid
450341477Svmaffionepacket_set_nonblocking(void)
451341477Svmaffione{
452341477Svmaffione	/* Set the socket into non-blocking mode. */
453341477Svmaffione	set_nonblock(active_state->connection_in);
454341477Svmaffione
455341477Svmaffione	if (active_state->connection_out != active_state->connection_in)
456341477Svmaffione		set_nonblock(active_state->connection_out);
457341477Svmaffione}
458341477Svmaffione
459341477Svmaffione/* Returns the socket used for reading. */
460341477Svmaffione
461341477Svmaffioneint
462341477Svmaffionepacket_get_connection_in(void)
463341477Svmaffione{
464341477Svmaffione	return active_state->connection_in;
465341477Svmaffione}
466341477Svmaffione
467341477Svmaffione/* Returns the descriptor used for writing. */
468341477Svmaffione
469341477Svmaffioneint
470341477Svmaffionepacket_get_connection_out(void)
471341477Svmaffione{
472341477Svmaffione	return active_state->connection_out;
473341477Svmaffione}
474341477Svmaffione
475341477Svmaffione/* Closes the connection and clears and frees internal data structures. */
476341477Svmaffione
477341477Svmaffionevoid
478341477Svmaffionepacket_close(void)
479341477Svmaffione{
480341477Svmaffione	if (!active_state->initialized)
481341477Svmaffione		return;
482341477Svmaffione	active_state->initialized = 0;
483341477Svmaffione	if (active_state->connection_in == active_state->connection_out) {
484341477Svmaffione		shutdown(active_state->connection_out, SHUT_RDWR);
485341477Svmaffione		close(active_state->connection_out);
486341477Svmaffione	} else {
487261909Sluigi		close(active_state->connection_in);
488341477Svmaffione		close(active_state->connection_out);
489341477Svmaffione	}
490341477Svmaffione	buffer_free(&active_state->input);
491341477Svmaffione	buffer_free(&active_state->output);
492341477Svmaffione	buffer_free(&active_state->outgoing_packet);
493341477Svmaffione	buffer_free(&active_state->incoming_packet);
494341477Svmaffione	if (active_state->compression_buffer_ready) {
495341477Svmaffione		buffer_free(&active_state->compression_buffer);
496341477Svmaffione		buffer_compress_uninit();
497341477Svmaffione	}
498341477Svmaffione	cipher_cleanup(&active_state->send_context);
499261909Sluigi	cipher_cleanup(&active_state->receive_context);
500341477Svmaffione}
501341477Svmaffione
502341477Svmaffione/* Sets remote side protocol flags. */
503341477Svmaffione
504341477Svmaffionevoid
505341477Svmaffionepacket_set_protocol_flags(u_int protocol_flags)
506261909Sluigi{
507261909Sluigi	active_state->remote_protocol_flags = protocol_flags;
508261909Sluigi}
509261909Sluigi
510261909Sluigi/* Returns the remote protocol flags set earlier by the above function. */
511261909Sluigi
512261909Sluigiu_int
513261909Sluigipacket_get_protocol_flags(void)
514261909Sluigi{
515261909Sluigi	return active_state->remote_protocol_flags;
516261909Sluigi}
517261909Sluigi
518261909Sluigi/*
519341477Svmaffione * Starts packet compression from the next packet on in both directions.
520261909Sluigi * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
521261909Sluigi */
522261909Sluigi
523261909Sluigistatic void
524261909Sluigipacket_init_compression(void)
525261909Sluigi{
526261909Sluigi	if (active_state->compression_buffer_ready == 1)
527261909Sluigi		return;
528267128Sluigi	active_state->compression_buffer_ready = 1;
529261909Sluigi	buffer_init(&active_state->compression_buffer);
530267128Sluigi}
531261909Sluigi
532261909Sluigivoid
533261909Sluigipacket_start_compression(int level)
534261909Sluigi{
535267128Sluigi	if (active_state->packet_compression && !compat20)
536261909Sluigi		fatal("Compression already enabled.");
537261909Sluigi	active_state->packet_compression = 1;
538261909Sluigi	packet_init_compression();
539261909Sluigi	buffer_compress_init_send(level);
540341477Svmaffione	buffer_compress_init_recv();
541261909Sluigi}
542261909Sluigi
543261909Sluigi/*
544261909Sluigi * Causes any further packets to be encrypted using the given key.  The same
545261909Sluigi * key is used for both sending and reception.  However, both directions are
546261909Sluigi * encrypted independently of each other.
547341477Svmaffione */
548341477Svmaffione
549261909Sluigivoid
550261909Sluigipacket_set_encryption_key(const u_char *key, u_int keylen, int number)
551261909Sluigi{
552261909Sluigi	Cipher *cipher = cipher_by_number(number);
553261909Sluigi
554261909Sluigi	if (cipher == NULL)
555341477Svmaffione		fatal("packet_set_encryption_key: unknown cipher number %d", number);
556261909Sluigi	if (keylen < 20)
557341477Svmaffione		fatal("packet_set_encryption_key: keylen too small: %d", keylen);
558341477Svmaffione	if (keylen > SSH_SESSION_KEY_LENGTH)
559341477Svmaffione		fatal("packet_set_encryption_key: keylen too big: %d", keylen);
560341477Svmaffione	memcpy(active_state->ssh1_key, key, keylen);
561341477Svmaffione	active_state->ssh1_keylen = keylen;
562341477Svmaffione	cipher_init(&active_state->send_context, cipher, key, keylen, NULL,
563341477Svmaffione	    0, CIPHER_ENCRYPT);
564341477Svmaffione	cipher_init(&active_state->receive_context, cipher, key, keylen, NULL,
565341477Svmaffione	    0, CIPHER_DECRYPT);
566341477Svmaffione}
567341477Svmaffione
568341477Svmaffioneu_int
569341477Svmaffionepacket_get_encryption_key(u_char *key)
570341477Svmaffione{
571341477Svmaffione	if (key == NULL)
572341477Svmaffione		return (active_state->ssh1_keylen);
573341477Svmaffione	memcpy(key, active_state->ssh1_key, active_state->ssh1_keylen);
574341477Svmaffione	return (active_state->ssh1_keylen);
575341477Svmaffione}
576341477Svmaffione
577341477Svmaffione/* Start constructing a packet to send. */
578341477Svmaffionevoid
579341477Svmaffionepacket_start(u_char type)
580341477Svmaffione{
581341477Svmaffione	u_char buf[9];
582341477Svmaffione	int len;
583341477Svmaffione
584341477Svmaffione	DBG(debug("packet_start[%d]", type));
585341477Svmaffione	len = compat20 ? 6 : 9;
586341477Svmaffione	memset(buf, 0, len - 1);
587341477Svmaffione	buf[len - 1] = type;
588341477Svmaffione	buffer_clear(&active_state->outgoing_packet);
589341477Svmaffione	buffer_append(&active_state->outgoing_packet, buf, len);
590341477Svmaffione}
591341477Svmaffione
592341477Svmaffione/* Append payload. */
593341477Svmaffionevoid
594341477Svmaffionepacket_put_char(int value)
595341477Svmaffione{
596341477Svmaffione	char ch = value;
597341477Svmaffione
598341477Svmaffione	buffer_append(&active_state->outgoing_packet, &ch, 1);
599261909Sluigi}
600341477Svmaffione
601261909Sluigivoid
602261909Sluigipacket_put_int(u_int value)
603341477Svmaffione{
604261909Sluigi	buffer_put_int(&active_state->outgoing_packet, value);
605261909Sluigi}
606261909Sluigi
607261909Sluigivoid
608261909Sluigipacket_put_int64(u_int64_t value)
609261909Sluigi{
610261909Sluigi	buffer_put_int64(&active_state->outgoing_packet, value);
611261909Sluigi}
612261909Sluigi
613261909Sluigivoid
614261909Sluigipacket_put_string(const void *buf, u_int len)
615261909Sluigi{
616341477Svmaffione	buffer_put_string(&active_state->outgoing_packet, buf, len);
617261909Sluigi}
618261909Sluigi
619261909Sluigivoid
620261909Sluigipacket_put_cstring(const char *str)
621261909Sluigi{
622341477Svmaffione	buffer_put_cstring(&active_state->outgoing_packet, str);
623261909Sluigi}
624341477Svmaffione
625341477Svmaffionevoid
626261909Sluigipacket_put_raw(const void *buf, u_int len)
627261909Sluigi{
628261909Sluigi	buffer_append(&active_state->outgoing_packet, buf, len);
629261909Sluigi}
630261909Sluigi
631341477Svmaffionevoid
632341477Svmaffionepacket_put_bignum(BIGNUM * value)
633261909Sluigi{
634341477Svmaffione	buffer_put_bignum(&active_state->outgoing_packet, value);
635261909Sluigi}
636341477Svmaffione
637341477Svmaffionevoid
638341477Svmaffionepacket_put_bignum2(BIGNUM * value)
639341477Svmaffione{
640341477Svmaffione	buffer_put_bignum2(&active_state->outgoing_packet, value);
641341477Svmaffione}
642261909Sluigi
643341477Svmaffione#ifdef OPENSSL_HAS_ECC
644341477Svmaffionevoid
645341477Svmaffionepacket_put_ecpoint(const EC_GROUP *curve, const EC_POINT *point)
646341477Svmaffione{
647341477Svmaffione	buffer_put_ecpoint(&active_state->outgoing_packet, curve, point);
648341477Svmaffione}
649341477Svmaffione#endif
650341477Svmaffione
651341477Svmaffione/*
652341477Svmaffione * Finalizes and sends the packet.  If the encryption key has been set,
653341477Svmaffione * encrypts the packet before sending.
654341477Svmaffione */
655341477Svmaffione
656341477Svmaffionestatic void
657341477Svmaffionepacket_send1(void)
658341477Svmaffione{
659341477Svmaffione	u_char buf[8], *cp;
660341477Svmaffione	int i, padding, len;
661341477Svmaffione	u_int checksum;
662341477Svmaffione	u_int32_t rnd = 0;
663261909Sluigi
664341477Svmaffione	/*
665341477Svmaffione	 * If using packet compression, compress the payload of the outgoing
666341477Svmaffione	 * packet.
667261909Sluigi	 */
668261909Sluigi	if (active_state->packet_compression) {
669261909Sluigi		buffer_clear(&active_state->compression_buffer);
670341477Svmaffione		/* Skip padding. */
671341477Svmaffione		buffer_consume(&active_state->outgoing_packet, 8);
672341477Svmaffione		/* padding */
673341477Svmaffione		buffer_append(&active_state->compression_buffer,
674341477Svmaffione		    "\0\0\0\0\0\0\0\0", 8);
675341477Svmaffione		buffer_compress(&active_state->outgoing_packet,
676341477Svmaffione		    &active_state->compression_buffer);
677341477Svmaffione		buffer_clear(&active_state->outgoing_packet);
678341477Svmaffione		buffer_append(&active_state->outgoing_packet,
679341477Svmaffione		    buffer_ptr(&active_state->compression_buffer),
680341477Svmaffione		    buffer_len(&active_state->compression_buffer));
681341477Svmaffione	}
682341477Svmaffione	/* Compute packet length without padding (add checksum, remove padding). */
683341477Svmaffione	len = buffer_len(&active_state->outgoing_packet) + 4 - 8;
684341477Svmaffione
685341477Svmaffione	/* Insert padding. Initialized to zero in packet_start1() */
686341477Svmaffione	padding = 8 - len % 8;
687341477Svmaffione	if (!active_state->send_context.plaintext) {
688341477Svmaffione		cp = buffer_ptr(&active_state->outgoing_packet);
689341477Svmaffione		for (i = 0; i < padding; i++) {
690341477Svmaffione			if (i % 4 == 0)
691341477Svmaffione				rnd = arc4random();
692341477Svmaffione			cp[7 - i] = rnd & 0xff;
693341477Svmaffione			rnd >>= 8;
694341477Svmaffione		}
695341477Svmaffione	}
696341477Svmaffione	buffer_consume(&active_state->outgoing_packet, 8 - padding);
697341477Svmaffione
698341477Svmaffione	/* Add check bytes. */
699261909Sluigi	checksum = ssh_crc32(buffer_ptr(&active_state->outgoing_packet),
700261909Sluigi	    buffer_len(&active_state->outgoing_packet));
701261909Sluigi	put_u32(buf, checksum);
702261909Sluigi	buffer_append(&active_state->outgoing_packet, buf, 4);
703261909Sluigi
704261909Sluigi#ifdef PACKET_DEBUG
705261909Sluigi	fprintf(stderr, "packet_send plain: ");
706261909Sluigi	buffer_dump(&active_state->outgoing_packet);
707261909Sluigi#endif
708341477Svmaffione
709261909Sluigi	/* Append to output. */
710261909Sluigi	put_u32(buf, len);
711261909Sluigi	buffer_append(&active_state->output, buf, 4);
712341477Svmaffione	cp = buffer_append_space(&active_state->output,
713341477Svmaffione	    buffer_len(&active_state->outgoing_packet));
714261909Sluigi	cipher_crypt(&active_state->send_context, cp,
715341477Svmaffione	    buffer_ptr(&active_state->outgoing_packet),
716341477Svmaffione	    buffer_len(&active_state->outgoing_packet), 0, 0);
717261909Sluigi
718261909Sluigi#ifdef PACKET_DEBUG
719341477Svmaffione	fprintf(stderr, "encrypted: ");
720341477Svmaffione	buffer_dump(&active_state->output);
721341477Svmaffione#endif
722261909Sluigi	active_state->p_send.packets++;
723261909Sluigi	active_state->p_send.bytes += len +
724341477Svmaffione	    buffer_len(&active_state->outgoing_packet);
725261909Sluigi	buffer_clear(&active_state->outgoing_packet);
726261909Sluigi
727261909Sluigi	/*
728261909Sluigi	 * Note that the packet is now only buffered in output.  It won't be
729267128Sluigi	 * actually sent until packet_write_wait or packet_write_poll is
730341477Svmaffione	 * called.
731341477Svmaffione	 */
732341477Svmaffione}
733341477Svmaffione
734261909Sluigivoid
735261909Sluigiset_newkeys(int mode)
736270063Sluigi{
737261909Sluigi	Enc *enc;
738341477Svmaffione	Mac *mac;
739261909Sluigi	Comp *comp;
740341477Svmaffione	CipherContext *cc;
741261909Sluigi	u_int64_t *max_blocks;
742341477Svmaffione	int crypt_type;
743261909Sluigi
744261909Sluigi	debug2("set_newkeys: mode %d", mode);
745261909Sluigi
746261909Sluigi	if (mode == MODE_OUT) {
747261909Sluigi		cc = &active_state->send_context;
748261909Sluigi		crypt_type = CIPHER_ENCRYPT;
749261909Sluigi		active_state->p_send.packets = active_state->p_send.blocks = 0;
750341477Svmaffione		max_blocks = &active_state->max_blocks_out;
751341477Svmaffione	} else {
752261909Sluigi		cc = &active_state->receive_context;
753261909Sluigi		crypt_type = CIPHER_DECRYPT;
754341477Svmaffione		active_state->p_read.packets = active_state->p_read.blocks = 0;
755341477Svmaffione		max_blocks = &active_state->max_blocks_in;
756341477Svmaffione	}
757341477Svmaffione	if (active_state->newkeys[mode] != NULL) {
758341477Svmaffione		debug("set_newkeys: rekeying");
759341477Svmaffione		cipher_cleanup(cc);
760341477Svmaffione		enc  = &active_state->newkeys[mode]->enc;
761261909Sluigi		mac  = &active_state->newkeys[mode]->mac;
762261909Sluigi		comp = &active_state->newkeys[mode]->comp;
763341477Svmaffione		mac_clear(mac);
764261909Sluigi		memset(enc->iv,  0, enc->iv_len);
765261909Sluigi		memset(enc->key, 0, enc->key_len);
766261909Sluigi		memset(mac->key, 0, mac->key_len);
767261909Sluigi		xfree(enc->name);
768270063Sluigi		xfree(enc->iv);
769261909Sluigi		xfree(enc->key);
770261909Sluigi		xfree(mac->name);
771261909Sluigi		xfree(mac->key);
772261909Sluigi		xfree(comp->name);
773261909Sluigi		xfree(active_state->newkeys[mode]);
774261909Sluigi	}
775341477Svmaffione	active_state->newkeys[mode] = kex_get_newkeys(mode);
776261909Sluigi	if (active_state->newkeys[mode] == NULL)
777261909Sluigi		fatal("newkeys: no keys for mode %d", mode);
778285697Sluigi	enc  = &active_state->newkeys[mode]->enc;
779261909Sluigi	mac  = &active_state->newkeys[mode]->mac;
780261909Sluigi	comp = &active_state->newkeys[mode]->comp;
781261909Sluigi	if (cipher_authlen(enc->cipher) == 0 && mac_init(mac) == 0)
782341477Svmaffione		mac->enabled = 1;
783341477Svmaffione	DBG(debug("cipher_init_context: %d", mode));
784341477Svmaffione	cipher_init(cc, enc->cipher, enc->key, enc->key_len,
785341477Svmaffione	    enc->iv, enc->iv_len, crypt_type);
786341477Svmaffione	/* Deleting the keys does not gain extra security */
787341477Svmaffione	/* memset(enc->iv,  0, enc->block_size);
788261909Sluigi	   memset(enc->key, 0, enc->key_len);
789261909Sluigi	   memset(mac->key, 0, mac->key_len); */
790261909Sluigi	if ((comp->type == COMP_ZLIB ||
791261909Sluigi	    (comp->type == COMP_DELAYED &&
792261909Sluigi	     active_state->after_authentication)) && comp->enabled == 0) {
793261909Sluigi		packet_init_compression();
794261909Sluigi		if (mode == MODE_OUT)
795261909Sluigi			buffer_compress_init_send(6);
796261909Sluigi		else
797341477Svmaffione			buffer_compress_init_recv();
798341477Svmaffione		comp->enabled = 1;
799261909Sluigi	}
800341477Svmaffione	/*
801341477Svmaffione	 * The 2^(blocksize*2) limit is too expensive for 3DES,
802341477Svmaffione	 * blowfish, etc, so enforce a 1GB limit for small blocksizes.
803261909Sluigi	 */
804341477Svmaffione	if (enc->block_size >= 16)
805341477Svmaffione		*max_blocks = (u_int64_t)1 << (enc->block_size*2);
806261909Sluigi	else
807261909Sluigi		*max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
808261909Sluigi	if (active_state->rekey_limit)
809341477Svmaffione		*max_blocks = MIN(*max_blocks,
810261909Sluigi		    active_state->rekey_limit / enc->block_size);
811261909Sluigi}
812261909Sluigi
813261909Sluigi/*
814261909Sluigi * Delayed compression for SSH2 is enabled after authentication:
815261909Sluigi * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
816341477Svmaffione * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
817341477Svmaffione */
818341477Svmaffionestatic void
819261909Sluigipacket_enable_delayed_compress(void)
820261909Sluigi{
821261909Sluigi	Comp *comp = NULL;
822341477Svmaffione	int mode;
823341477Svmaffione
824261909Sluigi	/*
825261909Sluigi	 * Remember that we are past the authentication step, so rekeying
826261909Sluigi	 * with COMP_DELAYED will turn on compression immediately.
827261909Sluigi	 */
828341477Svmaffione	active_state->after_authentication = 1;
829285697Sluigi	for (mode = 0; mode < MODE_MAX; mode++) {
830285697Sluigi		/* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
831261909Sluigi		if (active_state->newkeys[mode] == NULL)
832341477Svmaffione			continue;
833261909Sluigi		comp = &active_state->newkeys[mode]->comp;
834341477Svmaffione		if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
835261909Sluigi			packet_init_compression();
836261909Sluigi			if (mode == MODE_OUT)
837261909Sluigi				buffer_compress_init_send(6);
838261909Sluigi			else
839261909Sluigi				buffer_compress_init_recv();
840			comp->enabled = 1;
841		}
842	}
843}
844
845/*
846 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
847 */
848static void
849packet_send2_wrapped(void)
850{
851	u_char type, *cp, *macbuf = NULL;
852	u_char padlen, pad = 0;
853	u_int i, len, authlen = 0, aadlen = 0;
854	u_int32_t rnd = 0;
855	Enc *enc   = NULL;
856	Mac *mac   = NULL;
857	Comp *comp = NULL;
858	int block_size;
859
860	if (active_state->newkeys[MODE_OUT] != NULL) {
861		enc  = &active_state->newkeys[MODE_OUT]->enc;
862		mac  = &active_state->newkeys[MODE_OUT]->mac;
863		comp = &active_state->newkeys[MODE_OUT]->comp;
864		/* disable mac for authenticated encryption */
865		if ((authlen = cipher_authlen(enc->cipher)) != 0)
866			mac = NULL;
867	}
868	block_size = enc ? enc->block_size : 8;
869	aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
870
871	cp = buffer_ptr(&active_state->outgoing_packet);
872	type = cp[5];
873
874#ifdef PACKET_DEBUG
875	fprintf(stderr, "plain:     ");
876	buffer_dump(&active_state->outgoing_packet);
877#endif
878
879	if (comp && comp->enabled) {
880		len = buffer_len(&active_state->outgoing_packet);
881		/* skip header, compress only payload */
882		buffer_consume(&active_state->outgoing_packet, 5);
883		buffer_clear(&active_state->compression_buffer);
884		buffer_compress(&active_state->outgoing_packet,
885		    &active_state->compression_buffer);
886		buffer_clear(&active_state->outgoing_packet);
887		buffer_append(&active_state->outgoing_packet, "\0\0\0\0\0", 5);
888		buffer_append(&active_state->outgoing_packet,
889		    buffer_ptr(&active_state->compression_buffer),
890		    buffer_len(&active_state->compression_buffer));
891		DBG(debug("compression: raw %d compressed %d", len,
892		    buffer_len(&active_state->outgoing_packet)));
893	}
894
895	/* sizeof (packet_len + pad_len + payload) */
896	len = buffer_len(&active_state->outgoing_packet);
897
898	/*
899	 * calc size of padding, alloc space, get random data,
900	 * minimum padding is 4 bytes
901	 */
902	len -= aadlen; /* packet length is not encrypted for EtM modes */
903	padlen = block_size - (len % block_size);
904	if (padlen < 4)
905		padlen += block_size;
906	if (active_state->extra_pad) {
907		/* will wrap if extra_pad+padlen > 255 */
908		active_state->extra_pad =
909		    roundup(active_state->extra_pad, block_size);
910		pad = active_state->extra_pad -
911		    ((len + padlen) % active_state->extra_pad);
912		debug3("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
913		    pad, len, padlen, active_state->extra_pad);
914		padlen += pad;
915		active_state->extra_pad = 0;
916	}
917	cp = buffer_append_space(&active_state->outgoing_packet, padlen);
918	if (enc && !active_state->send_context.plaintext) {
919		/* random padding */
920		for (i = 0; i < padlen; i++) {
921			if (i % 4 == 0)
922				rnd = arc4random();
923			cp[i] = rnd & 0xff;
924			rnd >>= 8;
925		}
926	} else {
927		/* clear padding */
928		memset(cp, 0, padlen);
929	}
930	/* sizeof (packet_len + pad_len + payload + padding) */
931	len = buffer_len(&active_state->outgoing_packet);
932	cp = buffer_ptr(&active_state->outgoing_packet);
933	/* packet_length includes payload, padding and padding length field */
934	put_u32(cp, len - 4);
935	cp[4] = padlen;
936	DBG(debug("send: len %d (includes padlen %d, aadlen %d)",
937	    len, padlen, aadlen));
938
939	/* compute MAC over seqnr and packet(length fields, payload, padding) */
940	if (mac && mac->enabled && !mac->etm) {
941		macbuf = mac_compute(mac, active_state->p_send.seqnr,
942		    buffer_ptr(&active_state->outgoing_packet), len);
943		DBG(debug("done calc MAC out #%d", active_state->p_send.seqnr));
944	}
945	/* encrypt packet and append to output buffer. */
946	cp = buffer_append_space(&active_state->output, len + authlen);
947	cipher_crypt(&active_state->send_context, cp,
948	    buffer_ptr(&active_state->outgoing_packet),
949	    len - aadlen, aadlen, authlen);
950	/* append unencrypted MAC */
951	if (mac && mac->enabled) {
952		if (mac->etm) {
953			/* EtM: compute mac over aadlen + cipher text */
954			macbuf = mac_compute(mac,
955			    active_state->p_send.seqnr, cp, len);
956			DBG(debug("done calc MAC(EtM) out #%d",
957			    active_state->p_send.seqnr));
958		}
959		buffer_append(&active_state->output, macbuf, mac->mac_len);
960	}
961#ifdef PACKET_DEBUG
962	fprintf(stderr, "encrypted: ");
963	buffer_dump(&active_state->output);
964#endif
965	/* increment sequence number for outgoing packets */
966	if (++active_state->p_send.seqnr == 0)
967		logit("outgoing seqnr wraps around");
968	if (++active_state->p_send.packets == 0)
969		if (!(datafellows & SSH_BUG_NOREKEY))
970			fatal("XXX too many packets with same key");
971	active_state->p_send.blocks += len / block_size;
972	active_state->p_send.bytes += len;
973	buffer_clear(&active_state->outgoing_packet);
974
975	if (type == SSH2_MSG_NEWKEYS)
976		set_newkeys(MODE_OUT);
977	else if (type == SSH2_MSG_USERAUTH_SUCCESS && active_state->server_side)
978		packet_enable_delayed_compress();
979}
980
981static void
982packet_send2(void)
983{
984	struct packet *p;
985	u_char type, *cp;
986
987	cp = buffer_ptr(&active_state->outgoing_packet);
988	type = cp[5];
989
990	/* during rekeying we can only send key exchange messages */
991	if (active_state->rekeying) {
992		if ((type < SSH2_MSG_TRANSPORT_MIN) ||
993		    (type > SSH2_MSG_TRANSPORT_MAX) ||
994		    (type == SSH2_MSG_SERVICE_REQUEST) ||
995		    (type == SSH2_MSG_SERVICE_ACCEPT)) {
996			debug("enqueue packet: %u", type);
997			p = xmalloc(sizeof(*p));
998			p->type = type;
999			memcpy(&p->payload, &active_state->outgoing_packet,
1000			    sizeof(Buffer));
1001			buffer_init(&active_state->outgoing_packet);
1002			TAILQ_INSERT_TAIL(&active_state->outgoing, p, next);
1003			return;
1004		}
1005	}
1006
1007	/* rekeying starts with sending KEXINIT */
1008	if (type == SSH2_MSG_KEXINIT)
1009		active_state->rekeying = 1;
1010
1011	packet_send2_wrapped();
1012
1013	/* after a NEWKEYS message we can send the complete queue */
1014	if (type == SSH2_MSG_NEWKEYS) {
1015		active_state->rekeying = 0;
1016		while ((p = TAILQ_FIRST(&active_state->outgoing))) {
1017			type = p->type;
1018			debug("dequeue packet: %u", type);
1019			buffer_free(&active_state->outgoing_packet);
1020			memcpy(&active_state->outgoing_packet, &p->payload,
1021			    sizeof(Buffer));
1022			TAILQ_REMOVE(&active_state->outgoing, p, next);
1023			xfree(p);
1024			packet_send2_wrapped();
1025		}
1026	}
1027}
1028
1029void
1030packet_send(void)
1031{
1032	if (compat20)
1033		packet_send2();
1034	else
1035		packet_send1();
1036	DBG(debug("packet_send done"));
1037}
1038
1039/*
1040 * Waits until a packet has been received, and returns its type.  Note that
1041 * no other data is processed until this returns, so this function should not
1042 * be used during the interactive session.
1043 */
1044
1045int
1046packet_read_seqnr(u_int32_t *seqnr_p)
1047{
1048	int type, len, ret, ms_remain, cont;
1049	fd_set *setp;
1050	char buf[8192];
1051	struct timeval timeout, start, *timeoutp = NULL;
1052
1053	DBG(debug("packet_read()"));
1054
1055	setp = (fd_set *)xcalloc(howmany(active_state->connection_in + 1,
1056	    NFDBITS), sizeof(fd_mask));
1057
1058	/* Since we are blocking, ensure that all written packets have been sent. */
1059	packet_write_wait();
1060
1061	/* Stay in the loop until we have received a complete packet. */
1062	for (;;) {
1063		/* Try to read a packet from the buffer. */
1064		type = packet_read_poll_seqnr(seqnr_p);
1065		if (!compat20 && (
1066		    type == SSH_SMSG_SUCCESS
1067		    || type == SSH_SMSG_FAILURE
1068		    || type == SSH_CMSG_EOF
1069		    || type == SSH_CMSG_EXIT_CONFIRMATION))
1070			packet_check_eom();
1071		/* If we got a packet, return it. */
1072		if (type != SSH_MSG_NONE) {
1073			xfree(setp);
1074			return type;
1075		}
1076		/*
1077		 * Otherwise, wait for some data to arrive, add it to the
1078		 * buffer, and try again.
1079		 */
1080		memset(setp, 0, howmany(active_state->connection_in + 1,
1081		    NFDBITS) * sizeof(fd_mask));
1082		FD_SET(active_state->connection_in, setp);
1083
1084		if (active_state->packet_timeout_ms > 0) {
1085			ms_remain = active_state->packet_timeout_ms;
1086			timeoutp = &timeout;
1087		}
1088		/* Wait for some data to arrive. */
1089		for (;;) {
1090			if (active_state->packet_timeout_ms != -1) {
1091				ms_to_timeval(&timeout, ms_remain);
1092				gettimeofday(&start, NULL);
1093			}
1094			if ((ret = select(active_state->connection_in + 1, setp,
1095			    NULL, NULL, timeoutp)) >= 0)
1096				break;
1097			if (errno != EAGAIN && errno != EINTR &&
1098			    errno != EWOULDBLOCK)
1099				break;
1100			if (active_state->packet_timeout_ms == -1)
1101				continue;
1102			ms_subtract_diff(&start, &ms_remain);
1103			if (ms_remain <= 0) {
1104				ret = 0;
1105				break;
1106			}
1107		}
1108		if (ret == 0) {
1109			logit("Connection to %.200s timed out while "
1110			    "waiting to read", get_remote_ipaddr());
1111			cleanup_exit(255);
1112		}
1113		/* Read data from the socket. */
1114		do {
1115			cont = 0;
1116			len = roaming_read(active_state->connection_in, buf,
1117			    sizeof(buf), &cont);
1118		} while (len == 0 && cont);
1119		if (len == 0) {
1120			logit("Connection closed by %.200s", get_remote_ipaddr());
1121			cleanup_exit(255);
1122		}
1123		if (len < 0)
1124			fatal("Read from socket failed: %.100s", strerror(errno));
1125		/* Append it to the buffer. */
1126		packet_process_incoming(buf, len);
1127	}
1128	/* NOTREACHED */
1129}
1130
1131int
1132packet_read(void)
1133{
1134	return packet_read_seqnr(NULL);
1135}
1136
1137/*
1138 * Waits until a packet has been received, verifies that its type matches
1139 * that given, and gives a fatal error and exits if there is a mismatch.
1140 */
1141
1142void
1143packet_read_expect(int expected_type)
1144{
1145	int type;
1146
1147	type = packet_read();
1148	if (type != expected_type)
1149		packet_disconnect("Protocol error: expected packet type %d, got %d",
1150		    expected_type, type);
1151}
1152
1153/* Checks if a full packet is available in the data received so far via
1154 * packet_process_incoming.  If so, reads the packet; otherwise returns
1155 * SSH_MSG_NONE.  This does not wait for data from the connection.
1156 *
1157 * SSH_MSG_DISCONNECT is handled specially here.  Also,
1158 * SSH_MSG_IGNORE messages are skipped by this function and are never returned
1159 * to higher levels.
1160 */
1161
1162static int
1163packet_read_poll1(void)
1164{
1165	u_int len, padded_len;
1166	u_char *cp, type;
1167	u_int checksum, stored_checksum;
1168
1169	/* Check if input size is less than minimum packet size. */
1170	if (buffer_len(&active_state->input) < 4 + 8)
1171		return SSH_MSG_NONE;
1172	/* Get length of incoming packet. */
1173	cp = buffer_ptr(&active_state->input);
1174	len = get_u32(cp);
1175	if (len < 1 + 2 + 2 || len > 256 * 1024)
1176		packet_disconnect("Bad packet length %u.", len);
1177	padded_len = (len + 8) & ~7;
1178
1179	/* Check if the packet has been entirely received. */
1180	if (buffer_len(&active_state->input) < 4 + padded_len)
1181		return SSH_MSG_NONE;
1182
1183	/* The entire packet is in buffer. */
1184
1185	/* Consume packet length. */
1186	buffer_consume(&active_state->input, 4);
1187
1188	/*
1189	 * Cryptographic attack detector for ssh
1190	 * (C)1998 CORE-SDI, Buenos Aires Argentina
1191	 * Ariel Futoransky(futo@core-sdi.com)
1192	 */
1193	if (!active_state->receive_context.plaintext) {
1194		switch (detect_attack(buffer_ptr(&active_state->input),
1195		    padded_len)) {
1196		case DEATTACK_DETECTED:
1197			packet_disconnect("crc32 compensation attack: "
1198			    "network attack detected");
1199		case DEATTACK_DOS_DETECTED:
1200			packet_disconnect("deattack denial of "
1201			    "service detected");
1202		}
1203	}
1204
1205	/* Decrypt data to incoming_packet. */
1206	buffer_clear(&active_state->incoming_packet);
1207	cp = buffer_append_space(&active_state->incoming_packet, padded_len);
1208	cipher_crypt(&active_state->receive_context, cp,
1209	    buffer_ptr(&active_state->input), padded_len, 0, 0);
1210
1211	buffer_consume(&active_state->input, padded_len);
1212
1213#ifdef PACKET_DEBUG
1214	fprintf(stderr, "read_poll plain: ");
1215	buffer_dump(&active_state->incoming_packet);
1216#endif
1217
1218	/* Compute packet checksum. */
1219	checksum = ssh_crc32(buffer_ptr(&active_state->incoming_packet),
1220	    buffer_len(&active_state->incoming_packet) - 4);
1221
1222	/* Skip padding. */
1223	buffer_consume(&active_state->incoming_packet, 8 - len % 8);
1224
1225	/* Test check bytes. */
1226	if (len != buffer_len(&active_state->incoming_packet))
1227		packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
1228		    len, buffer_len(&active_state->incoming_packet));
1229
1230	cp = (u_char *)buffer_ptr(&active_state->incoming_packet) + len - 4;
1231	stored_checksum = get_u32(cp);
1232	if (checksum != stored_checksum)
1233		packet_disconnect("Corrupted check bytes on input.");
1234	buffer_consume_end(&active_state->incoming_packet, 4);
1235
1236	if (active_state->packet_compression) {
1237		buffer_clear(&active_state->compression_buffer);
1238		buffer_uncompress(&active_state->incoming_packet,
1239		    &active_state->compression_buffer);
1240		buffer_clear(&active_state->incoming_packet);
1241		buffer_append(&active_state->incoming_packet,
1242		    buffer_ptr(&active_state->compression_buffer),
1243		    buffer_len(&active_state->compression_buffer));
1244	}
1245	active_state->p_read.packets++;
1246	active_state->p_read.bytes += padded_len + 4;
1247	type = buffer_get_char(&active_state->incoming_packet);
1248	if (type < SSH_MSG_MIN || type > SSH_MSG_MAX)
1249		packet_disconnect("Invalid ssh1 packet type: %d", type);
1250	return type;
1251}
1252
1253static int
1254packet_read_poll2(u_int32_t *seqnr_p)
1255{
1256	u_int padlen, need;
1257	u_char *macbuf = NULL, *cp, type;
1258	u_int maclen, authlen = 0, aadlen = 0, block_size;
1259	Enc *enc   = NULL;
1260	Mac *mac   = NULL;
1261	Comp *comp = NULL;
1262
1263	if (active_state->packet_discard)
1264		return SSH_MSG_NONE;
1265
1266	if (active_state->newkeys[MODE_IN] != NULL) {
1267		enc  = &active_state->newkeys[MODE_IN]->enc;
1268		mac  = &active_state->newkeys[MODE_IN]->mac;
1269		comp = &active_state->newkeys[MODE_IN]->comp;
1270		/* disable mac for authenticated encryption */
1271		if ((authlen = cipher_authlen(enc->cipher)) != 0)
1272			mac = NULL;
1273	}
1274	maclen = mac && mac->enabled ? mac->mac_len : 0;
1275	block_size = enc ? enc->block_size : 8;
1276	aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
1277
1278	if (aadlen && active_state->packlen == 0) {
1279		if (buffer_len(&active_state->input) < 4)
1280			return SSH_MSG_NONE;
1281		cp = buffer_ptr(&active_state->input);
1282		active_state->packlen = get_u32(cp);
1283		if (active_state->packlen < 1 + 4 ||
1284		    active_state->packlen > PACKET_MAX_SIZE) {
1285#ifdef PACKET_DEBUG
1286			buffer_dump(&active_state->input);
1287#endif
1288			logit("Bad packet length %u.", active_state->packlen);
1289			packet_disconnect("Packet corrupt");
1290		}
1291		buffer_clear(&active_state->incoming_packet);
1292	} else if (active_state->packlen == 0) {
1293		/*
1294		 * check if input size is less than the cipher block size,
1295		 * decrypt first block and extract length of incoming packet
1296		 */
1297		if (buffer_len(&active_state->input) < block_size)
1298			return SSH_MSG_NONE;
1299		buffer_clear(&active_state->incoming_packet);
1300		cp = buffer_append_space(&active_state->incoming_packet,
1301		    block_size);
1302		cipher_crypt(&active_state->receive_context, cp,
1303		    buffer_ptr(&active_state->input), block_size, 0, 0);
1304		cp = buffer_ptr(&active_state->incoming_packet);
1305
1306		active_state->packlen = get_u32(cp);
1307		if (active_state->packlen < 1 + 4 ||
1308		    active_state->packlen > PACKET_MAX_SIZE) {
1309#ifdef PACKET_DEBUG
1310			buffer_dump(&active_state->incoming_packet);
1311#endif
1312			logit("Bad packet length %u.", active_state->packlen);
1313			packet_start_discard(enc, mac, active_state->packlen,
1314			    PACKET_MAX_SIZE);
1315			return SSH_MSG_NONE;
1316		}
1317		buffer_consume(&active_state->input, block_size);
1318	}
1319	DBG(debug("input: packet len %u", active_state->packlen+4));
1320	if (aadlen) {
1321		/* only the payload is encrypted */
1322		need = active_state->packlen;
1323	} else {
1324		/*
1325		 * the payload size and the payload are encrypted, but we
1326		 * have a partial packet of block_size bytes
1327		 */
1328		need = 4 + active_state->packlen - block_size;
1329	}
1330	DBG(debug("partial packet: block %d, need %d, maclen %d, authlen %d,"
1331	    " aadlen %d", block_size, need, maclen, authlen, aadlen));
1332	if (need % block_size != 0) {
1333		logit("padding error: need %d block %d mod %d",
1334		    need, block_size, need % block_size);
1335		packet_start_discard(enc, mac, active_state->packlen,
1336		    PACKET_MAX_SIZE - block_size);
1337		return SSH_MSG_NONE;
1338	}
1339	/*
1340	 * check if the entire packet has been received and
1341	 * decrypt into incoming_packet:
1342	 * 'aadlen' bytes are unencrypted, but authenticated.
1343	 * 'need' bytes are encrypted, followed by either
1344	 * 'authlen' bytes of authentication tag or
1345	 * 'maclen' bytes of message authentication code.
1346	 */
1347	if (buffer_len(&active_state->input) < aadlen + need + authlen + maclen)
1348		return SSH_MSG_NONE;
1349#ifdef PACKET_DEBUG
1350	fprintf(stderr, "read_poll enc/full: ");
1351	buffer_dump(&active_state->input);
1352#endif
1353	/* EtM: compute mac over encrypted input */
1354	if (mac && mac->enabled && mac->etm)
1355		macbuf = mac_compute(mac, active_state->p_read.seqnr,
1356		    buffer_ptr(&active_state->input), aadlen + need);
1357	cp = buffer_append_space(&active_state->incoming_packet, aadlen + need);
1358	cipher_crypt(&active_state->receive_context, cp,
1359	    buffer_ptr(&active_state->input), need, aadlen, authlen);
1360	buffer_consume(&active_state->input, aadlen + need + authlen);
1361	/*
1362	 * compute MAC over seqnr and packet,
1363	 * increment sequence number for incoming packet
1364	 */
1365	if (mac && mac->enabled) {
1366		if (!mac->etm)
1367			macbuf = mac_compute(mac, active_state->p_read.seqnr,
1368			    buffer_ptr(&active_state->incoming_packet),
1369			    buffer_len(&active_state->incoming_packet));
1370		if (timingsafe_bcmp(macbuf, buffer_ptr(&active_state->input),
1371		    mac->mac_len) != 0) {
1372			logit("Corrupted MAC on input.");
1373			if (need > PACKET_MAX_SIZE)
1374				fatal("internal error need %d", need);
1375			packet_start_discard(enc, mac, active_state->packlen,
1376			    PACKET_MAX_SIZE - need);
1377			return SSH_MSG_NONE;
1378		}
1379
1380		DBG(debug("MAC #%d ok", active_state->p_read.seqnr));
1381		buffer_consume(&active_state->input, mac->mac_len);
1382	}
1383	/* XXX now it's safe to use fatal/packet_disconnect */
1384	if (seqnr_p != NULL)
1385		*seqnr_p = active_state->p_read.seqnr;
1386	if (++active_state->p_read.seqnr == 0)
1387		logit("incoming seqnr wraps around");
1388	if (++active_state->p_read.packets == 0)
1389		if (!(datafellows & SSH_BUG_NOREKEY))
1390			fatal("XXX too many packets with same key");
1391	active_state->p_read.blocks += (active_state->packlen + 4) / block_size;
1392	active_state->p_read.bytes += active_state->packlen + 4;
1393
1394	/* get padlen */
1395	cp = buffer_ptr(&active_state->incoming_packet);
1396	padlen = cp[4];
1397	DBG(debug("input: padlen %d", padlen));
1398	if (padlen < 4)
1399		packet_disconnect("Corrupted padlen %d on input.", padlen);
1400
1401	/* skip packet size + padlen, discard padding */
1402	buffer_consume(&active_state->incoming_packet, 4 + 1);
1403	buffer_consume_end(&active_state->incoming_packet, padlen);
1404
1405	DBG(debug("input: len before de-compress %d",
1406	    buffer_len(&active_state->incoming_packet)));
1407	if (comp && comp->enabled) {
1408		buffer_clear(&active_state->compression_buffer);
1409		buffer_uncompress(&active_state->incoming_packet,
1410		    &active_state->compression_buffer);
1411		buffer_clear(&active_state->incoming_packet);
1412		buffer_append(&active_state->incoming_packet,
1413		    buffer_ptr(&active_state->compression_buffer),
1414		    buffer_len(&active_state->compression_buffer));
1415		DBG(debug("input: len after de-compress %d",
1416		    buffer_len(&active_state->incoming_packet)));
1417	}
1418	/*
1419	 * get packet type, implies consume.
1420	 * return length of payload (without type field)
1421	 */
1422	type = buffer_get_char(&active_state->incoming_packet);
1423	if (type < SSH2_MSG_MIN || type >= SSH2_MSG_LOCAL_MIN)
1424		packet_disconnect("Invalid ssh2 packet type: %d", type);
1425	if (type == SSH2_MSG_NEWKEYS)
1426		set_newkeys(MODE_IN);
1427	else if (type == SSH2_MSG_USERAUTH_SUCCESS &&
1428	    !active_state->server_side)
1429		packet_enable_delayed_compress();
1430#ifdef PACKET_DEBUG
1431	fprintf(stderr, "read/plain[%d]:\r\n", type);
1432	buffer_dump(&active_state->incoming_packet);
1433#endif
1434	/* reset for next packet */
1435	active_state->packlen = 0;
1436	return type;
1437}
1438
1439int
1440packet_read_poll_seqnr(u_int32_t *seqnr_p)
1441{
1442	u_int reason, seqnr;
1443	u_char type;
1444	char *msg;
1445
1446	for (;;) {
1447		if (compat20) {
1448			type = packet_read_poll2(seqnr_p);
1449			if (type) {
1450				active_state->keep_alive_timeouts = 0;
1451				DBG(debug("received packet type %d", type));
1452			}
1453			switch (type) {
1454			case SSH2_MSG_IGNORE:
1455				debug3("Received SSH2_MSG_IGNORE");
1456				break;
1457			case SSH2_MSG_DEBUG:
1458				packet_get_char();
1459				msg = packet_get_string(NULL);
1460				debug("Remote: %.900s", msg);
1461				xfree(msg);
1462				msg = packet_get_string(NULL);
1463				xfree(msg);
1464				break;
1465			case SSH2_MSG_DISCONNECT:
1466				reason = packet_get_int();
1467				msg = packet_get_string(NULL);
1468				error("Received disconnect from %s: %u: %.400s",
1469				    get_remote_ipaddr(), reason, msg);
1470				xfree(msg);
1471				cleanup_exit(255);
1472				break;
1473			case SSH2_MSG_UNIMPLEMENTED:
1474				seqnr = packet_get_int();
1475				debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1476				    seqnr);
1477				break;
1478			default:
1479				return type;
1480			}
1481		} else {
1482			type = packet_read_poll1();
1483			switch (type) {
1484			case SSH_MSG_IGNORE:
1485				break;
1486			case SSH_MSG_DEBUG:
1487				msg = packet_get_string(NULL);
1488				debug("Remote: %.900s", msg);
1489				xfree(msg);
1490				break;
1491			case SSH_MSG_DISCONNECT:
1492				msg = packet_get_string(NULL);
1493				error("Received disconnect from %s: %.400s",
1494				    get_remote_ipaddr(), msg);
1495				cleanup_exit(255);
1496				break;
1497			default:
1498				if (type)
1499					DBG(debug("received packet type %d", type));
1500				return type;
1501			}
1502		}
1503	}
1504}
1505
1506/*
1507 * Buffers the given amount of input characters.  This is intended to be used
1508 * together with packet_read_poll.
1509 */
1510
1511void
1512packet_process_incoming(const char *buf, u_int len)
1513{
1514	if (active_state->packet_discard) {
1515		active_state->keep_alive_timeouts = 0; /* ?? */
1516		if (len >= active_state->packet_discard)
1517			packet_stop_discard();
1518		active_state->packet_discard -= len;
1519		return;
1520	}
1521	buffer_append(&active_state->input, buf, len);
1522}
1523
1524/* Returns a character from the packet. */
1525
1526u_int
1527packet_get_char(void)
1528{
1529	char ch;
1530
1531	buffer_get(&active_state->incoming_packet, &ch, 1);
1532	return (u_char) ch;
1533}
1534
1535/* Returns an integer from the packet data. */
1536
1537u_int
1538packet_get_int(void)
1539{
1540	return buffer_get_int(&active_state->incoming_packet);
1541}
1542
1543/* Returns an 64 bit integer from the packet data. */
1544
1545u_int64_t
1546packet_get_int64(void)
1547{
1548	return buffer_get_int64(&active_state->incoming_packet);
1549}
1550
1551/*
1552 * Returns an arbitrary precision integer from the packet data.  The integer
1553 * must have been initialized before this call.
1554 */
1555
1556void
1557packet_get_bignum(BIGNUM * value)
1558{
1559	buffer_get_bignum(&active_state->incoming_packet, value);
1560}
1561
1562void
1563packet_get_bignum2(BIGNUM * value)
1564{
1565	buffer_get_bignum2(&active_state->incoming_packet, value);
1566}
1567
1568#ifdef OPENSSL_HAS_ECC
1569void
1570packet_get_ecpoint(const EC_GROUP *curve, EC_POINT *point)
1571{
1572	buffer_get_ecpoint(&active_state->incoming_packet, curve, point);
1573}
1574#endif
1575
1576void *
1577packet_get_raw(u_int *length_ptr)
1578{
1579	u_int bytes = buffer_len(&active_state->incoming_packet);
1580
1581	if (length_ptr != NULL)
1582		*length_ptr = bytes;
1583	return buffer_ptr(&active_state->incoming_packet);
1584}
1585
1586int
1587packet_remaining(void)
1588{
1589	return buffer_len(&active_state->incoming_packet);
1590}
1591
1592/*
1593 * Returns a string from the packet data.  The string is allocated using
1594 * xmalloc; it is the responsibility of the calling program to free it when
1595 * no longer needed.  The length_ptr argument may be NULL, or point to an
1596 * integer into which the length of the string is stored.
1597 */
1598
1599void *
1600packet_get_string(u_int *length_ptr)
1601{
1602	return buffer_get_string(&active_state->incoming_packet, length_ptr);
1603}
1604
1605void *
1606packet_get_string_ptr(u_int *length_ptr)
1607{
1608	return buffer_get_string_ptr(&active_state->incoming_packet, length_ptr);
1609}
1610
1611/* Ensures the returned string has no embedded \0 characters in it. */
1612char *
1613packet_get_cstring(u_int *length_ptr)
1614{
1615	return buffer_get_cstring(&active_state->incoming_packet, length_ptr);
1616}
1617
1618/*
1619 * Sends a diagnostic message from the server to the client.  This message
1620 * can be sent at any time (but not while constructing another message). The
1621 * message is printed immediately, but only if the client is being executed
1622 * in verbose mode.  These messages are primarily intended to ease debugging
1623 * authentication problems.   The length of the formatted message must not
1624 * exceed 1024 bytes.  This will automatically call packet_write_wait.
1625 */
1626
1627void
1628packet_send_debug(const char *fmt,...)
1629{
1630	char buf[1024];
1631	va_list args;
1632
1633	if (compat20 && (datafellows & SSH_BUG_DEBUG))
1634		return;
1635
1636	va_start(args, fmt);
1637	vsnprintf(buf, sizeof(buf), fmt, args);
1638	va_end(args);
1639
1640	if (compat20) {
1641		packet_start(SSH2_MSG_DEBUG);
1642		packet_put_char(0);	/* bool: always display */
1643		packet_put_cstring(buf);
1644		packet_put_cstring("");
1645	} else {
1646		packet_start(SSH_MSG_DEBUG);
1647		packet_put_cstring(buf);
1648	}
1649	packet_send();
1650	packet_write_wait();
1651}
1652
1653/*
1654 * Logs the error plus constructs and sends a disconnect packet, closes the
1655 * connection, and exits.  This function never returns. The error message
1656 * should not contain a newline.  The length of the formatted message must
1657 * not exceed 1024 bytes.
1658 */
1659
1660void
1661packet_disconnect(const char *fmt,...)
1662{
1663	char buf[1024];
1664	va_list args;
1665	static int disconnecting = 0;
1666
1667	if (disconnecting)	/* Guard against recursive invocations. */
1668		fatal("packet_disconnect called recursively.");
1669	disconnecting = 1;
1670
1671	/*
1672	 * Format the message.  Note that the caller must make sure the
1673	 * message is of limited size.
1674	 */
1675	va_start(args, fmt);
1676	vsnprintf(buf, sizeof(buf), fmt, args);
1677	va_end(args);
1678
1679	/* Display the error locally */
1680	logit("Disconnecting: %.100s", buf);
1681
1682	/* Send the disconnect message to the other side, and wait for it to get sent. */
1683	if (compat20) {
1684		packet_start(SSH2_MSG_DISCONNECT);
1685		packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1686		packet_put_cstring(buf);
1687		packet_put_cstring("");
1688	} else {
1689		packet_start(SSH_MSG_DISCONNECT);
1690		packet_put_cstring(buf);
1691	}
1692	packet_send();
1693	packet_write_wait();
1694
1695	/* Stop listening for connections. */
1696	channel_close_all();
1697
1698	/* Close the connection. */
1699	packet_close();
1700	cleanup_exit(255);
1701}
1702
1703/* Checks if there is any buffered output, and tries to write some of the output. */
1704
1705void
1706packet_write_poll(void)
1707{
1708	int len = buffer_len(&active_state->output);
1709	int cont;
1710
1711	if (len > 0) {
1712		cont = 0;
1713		len = roaming_write(active_state->connection_out,
1714		    buffer_ptr(&active_state->output), len, &cont);
1715		if (len == -1) {
1716			if (errno == EINTR || errno == EAGAIN ||
1717			    errno == EWOULDBLOCK)
1718				return;
1719			fatal("Write failed: %.100s", strerror(errno));
1720		}
1721		if (len == 0 && !cont)
1722			fatal("Write connection closed");
1723		buffer_consume(&active_state->output, len);
1724	}
1725}
1726
1727/*
1728 * Calls packet_write_poll repeatedly until all pending output data has been
1729 * written.
1730 */
1731
1732void
1733packet_write_wait(void)
1734{
1735	fd_set *setp;
1736	int ret, ms_remain;
1737	struct timeval start, timeout, *timeoutp = NULL;
1738
1739	setp = (fd_set *)xcalloc(howmany(active_state->connection_out + 1,
1740	    NFDBITS), sizeof(fd_mask));
1741	packet_write_poll();
1742	while (packet_have_data_to_write()) {
1743		memset(setp, 0, howmany(active_state->connection_out + 1,
1744		    NFDBITS) * sizeof(fd_mask));
1745		FD_SET(active_state->connection_out, setp);
1746
1747		if (active_state->packet_timeout_ms > 0) {
1748			ms_remain = active_state->packet_timeout_ms;
1749			timeoutp = &timeout;
1750		}
1751		for (;;) {
1752			if (active_state->packet_timeout_ms != -1) {
1753				ms_to_timeval(&timeout, ms_remain);
1754				gettimeofday(&start, NULL);
1755			}
1756			if ((ret = select(active_state->connection_out + 1,
1757			    NULL, setp, NULL, timeoutp)) >= 0)
1758				break;
1759			if (errno != EAGAIN && errno != EINTR &&
1760			    errno != EWOULDBLOCK)
1761				break;
1762			if (active_state->packet_timeout_ms == -1)
1763				continue;
1764			ms_subtract_diff(&start, &ms_remain);
1765			if (ms_remain <= 0) {
1766				ret = 0;
1767				break;
1768			}
1769		}
1770		if (ret == 0) {
1771			logit("Connection to %.200s timed out while "
1772			    "waiting to write", get_remote_ipaddr());
1773			cleanup_exit(255);
1774		}
1775		packet_write_poll();
1776	}
1777	xfree(setp);
1778}
1779
1780/* Returns true if there is buffered data to write to the connection. */
1781
1782int
1783packet_have_data_to_write(void)
1784{
1785	return buffer_len(&active_state->output) != 0;
1786}
1787
1788/* Returns true if there is not too much data to write to the connection. */
1789
1790int
1791packet_not_very_much_data_to_write(void)
1792{
1793	if (active_state->interactive_mode)
1794		return buffer_len(&active_state->output) < 16384;
1795	else
1796		return buffer_len(&active_state->output) < 128 * 1024;
1797}
1798
1799static void
1800packet_set_tos(int tos)
1801{
1802#ifndef IP_TOS_IS_BROKEN
1803	if (!packet_connection_is_on_socket())
1804		return;
1805	switch (packet_connection_af()) {
1806# ifdef IP_TOS
1807	case AF_INET:
1808		debug3("%s: set IP_TOS 0x%02x", __func__, tos);
1809		if (setsockopt(active_state->connection_in,
1810		    IPPROTO_IP, IP_TOS, &tos, sizeof(tos)) < 0)
1811			error("setsockopt IP_TOS %d: %.100s:",
1812			    tos, strerror(errno));
1813		break;
1814# endif /* IP_TOS */
1815# ifdef IPV6_TCLASS
1816	case AF_INET6:
1817		debug3("%s: set IPV6_TCLASS 0x%02x", __func__, tos);
1818		if (setsockopt(active_state->connection_in,
1819		    IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof(tos)) < 0)
1820			error("setsockopt IPV6_TCLASS %d: %.100s:",
1821			    tos, strerror(errno));
1822		break;
1823# endif /* IPV6_TCLASS */
1824	}
1825#endif /* IP_TOS_IS_BROKEN */
1826}
1827
1828/* Informs that the current session is interactive.  Sets IP flags for that. */
1829
1830void
1831packet_set_interactive(int interactive, int qos_interactive, int qos_bulk)
1832{
1833	if (active_state->set_interactive_called)
1834		return;
1835	active_state->set_interactive_called = 1;
1836
1837	/* Record that we are in interactive mode. */
1838	active_state->interactive_mode = interactive;
1839
1840	/* Only set socket options if using a socket.  */
1841	if (!packet_connection_is_on_socket())
1842		return;
1843	set_nodelay(active_state->connection_in);
1844	packet_set_tos(interactive ? qos_interactive : qos_bulk);
1845}
1846
1847/* Returns true if the current connection is interactive. */
1848
1849int
1850packet_is_interactive(void)
1851{
1852	return active_state->interactive_mode;
1853}
1854
1855int
1856packet_set_maxsize(u_int s)
1857{
1858	if (active_state->set_maxsize_called) {
1859		logit("packet_set_maxsize: called twice: old %d new %d",
1860		    active_state->max_packet_size, s);
1861		return -1;
1862	}
1863	if (s < 4 * 1024 || s > 1024 * 1024) {
1864		logit("packet_set_maxsize: bad size %d", s);
1865		return -1;
1866	}
1867	active_state->set_maxsize_called = 1;
1868	debug("packet_set_maxsize: setting to %d", s);
1869	active_state->max_packet_size = s;
1870	return s;
1871}
1872
1873int
1874packet_inc_alive_timeouts(void)
1875{
1876	return ++active_state->keep_alive_timeouts;
1877}
1878
1879void
1880packet_set_alive_timeouts(int ka)
1881{
1882	active_state->keep_alive_timeouts = ka;
1883}
1884
1885u_int
1886packet_get_maxsize(void)
1887{
1888	return active_state->max_packet_size;
1889}
1890
1891/* roundup current message to pad bytes */
1892void
1893packet_add_padding(u_char pad)
1894{
1895	active_state->extra_pad = pad;
1896}
1897
1898/*
1899 * 9.2.  Ignored Data Message
1900 *
1901 *   byte      SSH_MSG_IGNORE
1902 *   string    data
1903 *
1904 * All implementations MUST understand (and ignore) this message at any
1905 * time (after receiving the protocol version). No implementation is
1906 * required to send them. This message can be used as an additional
1907 * protection measure against advanced traffic analysis techniques.
1908 */
1909void
1910packet_send_ignore(int nbytes)
1911{
1912	u_int32_t rnd = 0;
1913	int i;
1914
1915	packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1916	packet_put_int(nbytes);
1917	for (i = 0; i < nbytes; i++) {
1918		if (i % 4 == 0)
1919			rnd = arc4random();
1920		packet_put_char((u_char)rnd & 0xff);
1921		rnd >>= 8;
1922	}
1923}
1924
1925#ifdef	NONE_CIPHER_ENABLED
1926void
1927packet_request_rekeying(void)
1928{
1929	rekey_requested = 1;
1930}
1931#endif
1932
1933#define MAX_PACKETS	(1U<<31)
1934int
1935packet_need_rekeying(void)
1936{
1937	if (datafellows & SSH_BUG_NOREKEY)
1938		return 0;
1939#ifdef	NONE_CIPHER_ENABLED
1940	if (rekey_requested == 1) {
1941		rekey_requested = 0;
1942		return 1;
1943	}
1944#endif
1945	return
1946	    (active_state->p_send.packets > MAX_PACKETS) ||
1947	    (active_state->p_read.packets > MAX_PACKETS) ||
1948	    (active_state->max_blocks_out &&
1949	        (active_state->p_send.blocks > active_state->max_blocks_out)) ||
1950	    (active_state->max_blocks_in &&
1951	        (active_state->p_read.blocks > active_state->max_blocks_in));
1952}
1953
1954void
1955packet_set_rekey_limit(u_int32_t bytes)
1956{
1957	active_state->rekey_limit = bytes;
1958}
1959
1960void
1961packet_set_server(void)
1962{
1963	active_state->server_side = 1;
1964}
1965
1966void
1967packet_set_authenticated(void)
1968{
1969	active_state->after_authentication = 1;
1970}
1971
1972void *
1973packet_get_input(void)
1974{
1975	return (void *)&active_state->input;
1976}
1977
1978void *
1979packet_get_output(void)
1980{
1981	return (void *)&active_state->output;
1982}
1983
1984void *
1985packet_get_newkeys(int mode)
1986{
1987	return (void *)active_state->newkeys[mode];
1988}
1989
1990/*
1991 * Save the state for the real connection, and use a separate state when
1992 * resuming a suspended connection.
1993 */
1994void
1995packet_backup_state(void)
1996{
1997	struct session_state *tmp;
1998
1999	close(active_state->connection_in);
2000	active_state->connection_in = -1;
2001	close(active_state->connection_out);
2002	active_state->connection_out = -1;
2003	if (backup_state)
2004		tmp = backup_state;
2005	else
2006		tmp = alloc_session_state();
2007	backup_state = active_state;
2008	active_state = tmp;
2009}
2010
2011/*
2012 * Swap in the old state when resuming a connecion.
2013 */
2014void
2015packet_restore_state(void)
2016{
2017	struct session_state *tmp;
2018	void *buf;
2019	u_int len;
2020
2021	tmp = backup_state;
2022	backup_state = active_state;
2023	active_state = tmp;
2024	active_state->connection_in = backup_state->connection_in;
2025	backup_state->connection_in = -1;
2026	active_state->connection_out = backup_state->connection_out;
2027	backup_state->connection_out = -1;
2028	len = buffer_len(&backup_state->input);
2029	if (len > 0) {
2030		buf = buffer_ptr(&backup_state->input);
2031		buffer_append(&active_state->input, buf, len);
2032		buffer_clear(&backup_state->input);
2033		add_recv_bytes(len);
2034	}
2035}
2036
2037#ifdef	NONE_CIPHER_ENABLED
2038int
2039packet_get_authentication_state(void)
2040{
2041	return (active_state->after_authentication);
2042}
2043#endif
2044