packet.c revision 248619
1148871Scperciva/* $OpenBSD: packet.c,v 1.181 2013/02/10 23:35:24 djm Exp $ */
2148871Scperciva/* $FreeBSD: head/crypto/openssh/packet.c 248619 2013-03-22 17:55:38Z des $ */
3148871Scperciva/*
4148871Scperciva * Author: Tatu Ylonen <ylo@cs.hut.fi>
5148871Scperciva * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6148871Scperciva *                    All rights reserved
7148871Scperciva * This file contains code implementing the packet protocol and communication
8148871Scperciva * with the other side.  This same code is used both on client and server side.
9148871Scperciva *
10148871Scperciva * As far as I am concerned, the code I have written for this software
11148871Scperciva * can be used freely for any purpose.  Any derived versions of this
12148871Scperciva * software must be clearly marked as such, and if the derived work is
13148871Scperciva * incompatible with the protocol description in the RFC file, it must be
14148871Scperciva * called by a name other than "ssh" or "Secure Shell".
15148871Scperciva *
16148871Scperciva *
17148871Scperciva * SSH2 packet format added by Markus Friedl.
18148871Scperciva * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
19148871Scperciva *
20148871Scperciva * Redistribution and use in source and binary forms, with or without
21148871Scperciva * modification, are permitted provided that the following conditions
22148871Scperciva * are met:
23148871Scperciva * 1. Redistributions of source code must retain the above copyright
24148871Scperciva *    notice, this list of conditions and the following disclaimer.
25148871Scperciva * 2. Redistributions in binary form must reproduce the above copyright
26148871Scperciva *    notice, this list of conditions and the following disclaimer in the
27148871Scperciva *    documentation and/or other materials provided with the distribution.
28148871Scperciva *
29148871Scperciva * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
30148871Scperciva * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
31148871Scperciva * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
32148871Scperciva * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
33148871Scperciva * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
34148871Scperciva * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35148871Scperciva * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36148871Scperciva * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37149027Scperciva * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
38148871Scperciva * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39148871Scperciva */
40148871Scperciva
41148871Scperciva#include "includes.h"
42148871Scperciva
43148871Scperciva#include <sys/types.h>
44148871Scperciva#include "openbsd-compat/sys-queue.h"
45148871Scperciva#include <sys/param.h>
46148871Scperciva#include <sys/socket.h>
47148871Scperciva#ifdef HAVE_SYS_TIME_H
48148871Scperciva# include <sys/time.h>
49148871Scperciva#endif
50148871Scperciva
51148871Scperciva#include <netinet/in.h>
52148871Scperciva#include <netinet/ip.h>
53148871Scperciva#include <arpa/inet.h>
54148871Scperciva
55148871Scperciva#include <errno.h>
56148871Scperciva#include <stdarg.h>
57148871Scperciva#include <stdio.h>
58148871Scperciva#include <stdlib.h>
59148871Scperciva#include <string.h>
60148871Scperciva#include <unistd.h>
61148871Scperciva#include <signal.h>
62148871Scperciva
63148871Scperciva#include "xmalloc.h"
64148871Scperciva#include "buffer.h"
65148871Scperciva#include "packet.h"
66148871Scperciva#include "crc32.h"
67148871Scperciva#include "compress.h"
68148871Scperciva#include "deattack.h"
69148871Scperciva#include "channels.h"
70148871Scperciva#include "compat.h"
71148871Scperciva#include "ssh1.h"
72148871Scperciva#include "ssh2.h"
73148871Scperciva#include "cipher.h"
74148871Scperciva#include "key.h"
75149027Scperciva#include "kex.h"
76148871Scperciva#include "mac.h"
77148871Scperciva#include "log.h"
78148871Scperciva#include "canohost.h"
79148879Scperciva#include "misc.h"
80148871Scperciva#include "ssh.h"
81148871Scperciva#include "roaming.h"
82148871Scperciva
83148871Scperciva#ifdef PACKET_DEBUG
84148871Scperciva#define DBG(x) x
85148871Scperciva#else
86148871Scperciva#define DBG(x)
87148871Scperciva#endif
88148871Scperciva
89148871Scperciva#define PACKET_MAX_SIZE (256 * 1024)
90148871Scperciva
91148871Scpercivastruct packet_state {
92148871Scperciva	u_int32_t seqnr;
93148871Scperciva	u_int32_t packets;
94148871Scperciva	u_int64_t blocks;
95148871Scperciva	u_int64_t bytes;
96148871Scperciva};
97148871Scperciva
98148871Scpercivastruct packet {
99148871Scperciva	TAILQ_ENTRY(packet) next;
100148879Scperciva	u_char type;
101148871Scperciva	Buffer payload;
102148871Scperciva};
103148871Scperciva
104148871Scpercivastruct session_state {
105148871Scperciva	/*
106148871Scperciva	 * This variable contains the file descriptors used for
107148871Scperciva	 * communicating with the other side.  connection_in is used for
108148871Scperciva	 * reading; connection_out for writing.  These can be the same
109148871Scperciva	 * descriptor, in which case it is assumed to be a socket.
110148871Scperciva	 */
111148871Scperciva	int connection_in;
112148871Scperciva	int connection_out;
113148871Scperciva
114148871Scperciva	/* Protocol flags for the remote side. */
115148871Scperciva	u_int remote_protocol_flags;
116148871Scperciva
117148871Scperciva	/* Encryption context for receiving data.  Only used for decryption. */
118148871Scperciva	CipherContext receive_context;
119148871Scperciva
120148871Scperciva	/* Encryption context for sending data.  Only used for encryption. */
121148871Scperciva	CipherContext send_context;
122148871Scperciva
123148871Scperciva	/* Buffer for raw input data from the socket. */
124148871Scperciva	Buffer input;
125148871Scperciva
126148871Scperciva	/* Buffer for raw output data going to the socket. */
127148871Scperciva	Buffer output;
128148871Scperciva
129148871Scperciva	/* Buffer for the partial outgoing packet being constructed. */
130148871Scperciva	Buffer outgoing_packet;
131148871Scperciva
132148871Scperciva	/* Buffer for the incoming packet currently being processed. */
133148871Scperciva	Buffer incoming_packet;
134148871Scperciva
135148871Scperciva	/* Scratch buffer for packet compression/decompression. */
136149027Scperciva	Buffer compression_buffer;
137148871Scperciva	int compression_buffer_ready;
138148871Scperciva
139148871Scperciva	/*
140149027Scperciva	 * Flag indicating whether packet compression/decompression is
141149027Scperciva	 * enabled.
142149027Scperciva	 */
143148871Scperciva	int packet_compression;
144148871Scperciva
145148871Scperciva	/* default maximum packet size */
146148871Scperciva	u_int max_packet_size;
147148871Scperciva
148148871Scperciva	/* Flag indicating whether this module has been initialized. */
149149027Scperciva	int initialized;
150148871Scperciva
151148871Scperciva	/* Set to true if the connection is interactive. */
152148871Scperciva	int interactive_mode;
153148871Scperciva
154148871Scperciva	/* Set to true if we are the server side. */
155148871Scperciva	int server_side;
156148871Scperciva
157148871Scperciva	/* Set to true if we are authenticated. */
158148871Scperciva	int after_authentication;
159148871Scperciva
160148871Scperciva	int keep_alive_timeouts;
161148871Scperciva
162148871Scperciva	/* The maximum time that we will wait to send or receive a packet */
163148871Scperciva	int packet_timeout_ms;
164148871Scperciva
165148871Scperciva	/* Session key information for Encryption and MAC */
166148871Scperciva	Newkeys *newkeys[MODE_MAX];
167148871Scperciva	struct packet_state p_read, p_send;
168148871Scperciva
169148871Scperciva	u_int64_t max_blocks_in, max_blocks_out;
170148871Scperciva	u_int32_t rekey_limit;
171148871Scperciva
172148871Scperciva	/* Session key for protocol v1 */
173148871Scperciva	u_char ssh1_key[SSH_SESSION_KEY_LENGTH];
174148871Scperciva	u_int ssh1_keylen;
175148871Scperciva
176148871Scperciva	/* roundup current message to extra_pad bytes */
177148871Scperciva	u_char extra_pad;
178148871Scperciva
179148871Scperciva	/* XXX discard incoming data after MAC error */
180148871Scperciva	u_int packet_discard;
181148871Scperciva	Mac *packet_discard_mac;
182148871Scperciva
183148871Scperciva	/* Used in packet_read_poll2() */
184148871Scperciva	u_int packlen;
185148871Scperciva
186148871Scperciva	/* Used in packet_send2 */
187148871Scperciva	int rekeying;
188148871Scperciva
189148871Scperciva	/* Used in packet_set_interactive */
190148871Scperciva	int set_interactive_called;
191148871Scperciva
192148871Scperciva	/* Used in packet_set_maxsize */
193148871Scperciva	int set_maxsize_called;
194148871Scperciva
195148871Scperciva	TAILQ_HEAD(, packet) outgoing;
196148871Scperciva};
197148871Scperciva
198148871Scpercivastatic struct session_state *active_state, *backup_state;
199148871Scperciva#ifdef	NONE_CIPHER_ENABLED
200148871Scpercivastatic int rekey_requested = 0;
201148871Scperciva#endif
202148871Scperciva
203148871Scpercivastatic struct session_state *
204148871Scpercivaalloc_session_state(void)
205148871Scperciva{
206148871Scperciva	struct session_state *s = xcalloc(1, sizeof(*s));
207148871Scperciva
208148871Scperciva	s->connection_in = -1;
209148871Scperciva	s->connection_out = -1;
210148871Scperciva	s->max_packet_size = 32768;
211148871Scperciva	s->packet_timeout_ms = -1;
212148871Scperciva	return s;
213148871Scperciva}
214148871Scperciva
215148871Scperciva/*
216148871Scperciva * Sets the descriptors used for communication.  Disables encryption until
217148871Scperciva * packet_set_encryption_key is called.
218148871Scperciva */
219148871Scpercivavoid
220148871Scpercivapacket_set_connection(int fd_in, int fd_out)
221148871Scperciva{
222148871Scperciva	Cipher *none = cipher_by_name("none");
223148871Scperciva
224148871Scperciva	if (none == NULL)
225148871Scperciva		fatal("packet_set_connection: cannot load cipher 'none'");
226148871Scperciva	if (active_state == NULL)
227148871Scperciva		active_state = alloc_session_state();
228148871Scperciva	active_state->connection_in = fd_in;
229148871Scperciva	active_state->connection_out = fd_out;
230148871Scperciva	cipher_init(&active_state->send_context, none, (const u_char *)"",
231148871Scperciva	    0, NULL, 0, CIPHER_ENCRYPT);
232148871Scperciva	cipher_init(&active_state->receive_context, none, (const u_char *)"",
233148871Scperciva	    0, NULL, 0, CIPHER_DECRYPT);
234148871Scperciva	active_state->newkeys[MODE_IN] = active_state->newkeys[MODE_OUT] = NULL;
235148871Scperciva	if (!active_state->initialized) {
236148871Scperciva		active_state->initialized = 1;
237148871Scperciva		buffer_init(&active_state->input);
238148871Scperciva		buffer_init(&active_state->output);
239148871Scperciva		buffer_init(&active_state->outgoing_packet);
240148871Scperciva		buffer_init(&active_state->incoming_packet);
241148871Scperciva		TAILQ_INIT(&active_state->outgoing);
242148871Scperciva		active_state->p_send.packets = active_state->p_read.packets = 0;
243148871Scperciva	}
244148871Scperciva}
245148871Scperciva
246148871Scpercivavoid
247148871Scpercivapacket_set_timeout(int timeout, int count)
248148871Scperciva{
249148871Scperciva	if (timeout <= 0 || count <= 0) {
250148871Scperciva		active_state->packet_timeout_ms = -1;
251148871Scperciva		return;
252148871Scperciva	}
253148871Scperciva	if ((INT_MAX / 1000) / count < timeout)
254148871Scperciva		active_state->packet_timeout_ms = INT_MAX;
255148871Scperciva	else
256148871Scperciva		active_state->packet_timeout_ms = timeout * count * 1000;
257148871Scperciva}
258148871Scperciva
259148871Scpercivastatic void
260148871Scpercivapacket_stop_discard(void)
261148871Scperciva{
262148871Scperciva	if (active_state->packet_discard_mac) {
263148871Scperciva		char buf[1024];
264148871Scperciva
265148871Scperciva		memset(buf, 'a', sizeof(buf));
266148871Scperciva		while (buffer_len(&active_state->incoming_packet) <
267148871Scperciva		    PACKET_MAX_SIZE)
268148871Scperciva			buffer_append(&active_state->incoming_packet, buf,
269148871Scperciva			    sizeof(buf));
270148871Scperciva		(void) mac_compute(active_state->packet_discard_mac,
271148871Scperciva		    active_state->p_read.seqnr,
272148871Scperciva		    buffer_ptr(&active_state->incoming_packet),
273148871Scperciva		    PACKET_MAX_SIZE);
274148871Scperciva	}
275148871Scperciva	logit("Finished discarding for %.200s", get_remote_ipaddr());
276148871Scperciva	cleanup_exit(255);
277148871Scperciva}
278148871Scperciva
279148871Scpercivastatic void
280148871Scpercivapacket_start_discard(Enc *enc, Mac *mac, u_int packet_length, u_int discard)
281148871Scperciva{
282148871Scperciva	if (enc == NULL || !cipher_is_cbc(enc->cipher) || (mac && mac->etm))
283148871Scperciva		packet_disconnect("Packet corrupt");
284148871Scperciva	if (packet_length != PACKET_MAX_SIZE && mac && mac->enabled)
285148871Scperciva		active_state->packet_discard_mac = mac;
286148871Scperciva	if (buffer_len(&active_state->input) >= discard)
287148871Scperciva		packet_stop_discard();
288148871Scperciva	active_state->packet_discard = discard -
289148871Scperciva	    buffer_len(&active_state->input);
290148871Scperciva}
291148871Scperciva
292148871Scperciva/* Returns 1 if remote host is connected via socket, 0 if not. */
293148871Scperciva
294148871Scpercivaint
295148871Scpercivapacket_connection_is_on_socket(void)
296148871Scperciva{
297148871Scperciva	struct sockaddr_storage from, to;
298148871Scperciva	socklen_t fromlen, tolen;
299148871Scperciva
300148871Scperciva	/* filedescriptors in and out are the same, so it's a socket */
301148871Scperciva	if (active_state->connection_in == active_state->connection_out)
302148871Scperciva		return 1;
303148871Scperciva	fromlen = sizeof(from);
304148871Scperciva	memset(&from, 0, sizeof(from));
305148871Scperciva	if (getpeername(active_state->connection_in, (struct sockaddr *)&from,
306148871Scperciva	    &fromlen) < 0)
307148871Scperciva		return 0;
308148871Scperciva	tolen = sizeof(to);
309148871Scperciva	memset(&to, 0, sizeof(to));
310148871Scperciva	if (getpeername(active_state->connection_out, (struct sockaddr *)&to,
311148871Scperciva	    &tolen) < 0)
312148871Scperciva		return 0;
313148871Scperciva	if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
314148871Scperciva		return 0;
315148871Scperciva	if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
316148871Scperciva		return 0;
317148871Scperciva	return 1;
318148871Scperciva}
319148871Scperciva
320148871Scperciva/*
321148871Scperciva * Exports an IV from the CipherContext required to export the key
322148871Scperciva * state back from the unprivileged child to the privileged parent
323148871Scperciva * process.
324148871Scperciva */
325148871Scperciva
326148871Scpercivavoid
327148871Scpercivapacket_get_keyiv(int mode, u_char *iv, u_int len)
328148871Scperciva{
329148871Scperciva	CipherContext *cc;
330148871Scperciva
331148871Scperciva	if (mode == MODE_OUT)
332148871Scperciva		cc = &active_state->send_context;
333148871Scperciva	else
334148871Scperciva		cc = &active_state->receive_context;
335148871Scperciva
336148871Scperciva	cipher_get_keyiv(cc, iv, len);
337148871Scperciva}
338148871Scperciva
339148871Scpercivaint
340148871Scpercivapacket_get_keycontext(int mode, u_char *dat)
341148871Scperciva{
342148871Scperciva	CipherContext *cc;
343148871Scperciva
344148871Scperciva	if (mode == MODE_OUT)
345148871Scperciva		cc = &active_state->send_context;
346148871Scperciva	else
347148871Scperciva		cc = &active_state->receive_context;
348148871Scperciva
349148871Scperciva	return (cipher_get_keycontext(cc, dat));
350148871Scperciva}
351148871Scperciva
352148871Scpercivavoid
353148871Scpercivapacket_set_keycontext(int mode, u_char *dat)
354148871Scperciva{
355148871Scperciva	CipherContext *cc;
356148871Scperciva
357148871Scperciva	if (mode == MODE_OUT)
358148871Scperciva		cc = &active_state->send_context;
359148871Scperciva	else
360148871Scperciva		cc = &active_state->receive_context;
361148871Scperciva
362148871Scperciva	cipher_set_keycontext(cc, dat);
363148871Scperciva}
364148871Scperciva
365148871Scpercivaint
366148871Scpercivapacket_get_keyiv_len(int mode)
367148871Scperciva{
368148871Scperciva	CipherContext *cc;
369148871Scperciva
370148871Scperciva	if (mode == MODE_OUT)
371148871Scperciva		cc = &active_state->send_context;
372148871Scperciva	else
373148871Scperciva		cc = &active_state->receive_context;
374148871Scperciva
375148871Scperciva	return (cipher_get_keyiv_len(cc));
376148871Scperciva}
377148871Scperciva
378148871Scpercivavoid
379148871Scpercivapacket_set_iv(int mode, u_char *dat)
380148871Scperciva{
381148871Scperciva	CipherContext *cc;
382148871Scperciva
383148871Scperciva	if (mode == MODE_OUT)
384148871Scperciva		cc = &active_state->send_context;
385148871Scperciva	else
386148871Scperciva		cc = &active_state->receive_context;
387148871Scperciva
388148871Scperciva	cipher_set_keyiv(cc, dat);
389148871Scperciva}
390148871Scperciva
391148871Scpercivaint
392148871Scpercivapacket_get_ssh1_cipher(void)
393148871Scperciva{
394148871Scperciva	return (cipher_get_number(active_state->receive_context.cipher));
395148871Scperciva}
396148871Scperciva
397148871Scpercivavoid
398148871Scpercivapacket_get_state(int mode, u_int32_t *seqnr, u_int64_t *blocks,
399148871Scperciva    u_int32_t *packets, u_int64_t *bytes)
400148871Scperciva{
401148871Scperciva	struct packet_state *state;
402148871Scperciva
403148871Scperciva	state = (mode == MODE_IN) ?
404148871Scperciva	    &active_state->p_read : &active_state->p_send;
405148871Scperciva	if (seqnr)
406148871Scperciva		*seqnr = state->seqnr;
407148871Scperciva	if (blocks)
408148871Scperciva		*blocks = state->blocks;
409148871Scperciva	if (packets)
410148871Scperciva		*packets = state->packets;
411148871Scperciva	if (bytes)
412148871Scperciva		*bytes = state->bytes;
413148871Scperciva}
414148871Scperciva
415148871Scpercivavoid
416148871Scpercivapacket_set_state(int mode, u_int32_t seqnr, u_int64_t blocks, u_int32_t packets,
417148871Scperciva    u_int64_t bytes)
418148871Scperciva{
419148871Scperciva	struct packet_state *state;
420148871Scperciva
421148871Scperciva	state = (mode == MODE_IN) ?
422148871Scperciva	    &active_state->p_read : &active_state->p_send;
423148871Scperciva	state->seqnr = seqnr;
424148871Scperciva	state->blocks = blocks;
425148871Scperciva	state->packets = packets;
426148871Scperciva	state->bytes = bytes;
427148871Scperciva}
428148871Scperciva
429148871Scpercivastatic int
430148871Scpercivapacket_connection_af(void)
431148871Scperciva{
432148871Scperciva	struct sockaddr_storage to;
433148871Scperciva	socklen_t tolen = sizeof(to);
434148871Scperciva
435148871Scperciva	memset(&to, 0, sizeof(to));
436148871Scperciva	if (getsockname(active_state->connection_out, (struct sockaddr *)&to,
437148871Scperciva	    &tolen) < 0)
438148871Scperciva		return 0;
439148871Scperciva#ifdef IPV4_IN_IPV6
440148871Scperciva	if (to.ss_family == AF_INET6 &&
441148871Scperciva	    IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&to)->sin6_addr))
442148879Scperciva		return AF_INET;
443148871Scperciva#endif
444148871Scperciva	return to.ss_family;
445148871Scperciva}
446148871Scperciva
447148871Scperciva/* Sets the connection into non-blocking mode. */
448148871Scperciva
449148871Scpercivavoid
450148871Scpercivapacket_set_nonblocking(void)
451148871Scperciva{
452148871Scperciva	/* Set the socket into non-blocking mode. */
453148871Scperciva	set_nonblock(active_state->connection_in);
454148871Scperciva
455148871Scperciva	if (active_state->connection_out != active_state->connection_in)
456148871Scperciva		set_nonblock(active_state->connection_out);
457148871Scperciva}
458148871Scperciva
459148871Scperciva/* Returns the socket used for reading. */
460148871Scperciva
461148871Scpercivaint
462148871Scpercivapacket_get_connection_in(void)
463148871Scperciva{
464148871Scperciva	return active_state->connection_in;
465148871Scperciva}
466148871Scperciva
467148871Scperciva/* Returns the descriptor used for writing. */
468148871Scperciva
469148871Scpercivaint
470148871Scpercivapacket_get_connection_out(void)
471148871Scperciva{
472148871Scperciva	return active_state->connection_out;
473148871Scperciva}
474148871Scperciva
475148871Scperciva/* Closes the connection and clears and frees internal data structures. */
476148871Scperciva
477148871Scpercivavoid
478148871Scpercivapacket_close(void)
479148871Scperciva{
480148871Scperciva	if (!active_state->initialized)
481148871Scperciva		return;
482148871Scperciva	active_state->initialized = 0;
483148871Scperciva	if (active_state->connection_in == active_state->connection_out) {
484148871Scperciva		shutdown(active_state->connection_out, SHUT_RDWR);
485148871Scperciva		close(active_state->connection_out);
486148871Scperciva	} else {
487148871Scperciva		close(active_state->connection_in);
488148871Scperciva		close(active_state->connection_out);
489148871Scperciva	}
490148871Scperciva	buffer_free(&active_state->input);
491148871Scperciva	buffer_free(&active_state->output);
492148871Scperciva	buffer_free(&active_state->outgoing_packet);
493148871Scperciva	buffer_free(&active_state->incoming_packet);
494148871Scperciva	if (active_state->compression_buffer_ready) {
495148871Scperciva		buffer_free(&active_state->compression_buffer);
496148871Scperciva		buffer_compress_uninit();
497148871Scperciva	}
498148871Scperciva	cipher_cleanup(&active_state->send_context);
499148871Scperciva	cipher_cleanup(&active_state->receive_context);
500148871Scperciva}
501148871Scperciva
502148871Scperciva/* Sets remote side protocol flags. */
503148871Scperciva
504148871Scpercivavoid
505148871Scpercivapacket_set_protocol_flags(u_int protocol_flags)
506148871Scperciva{
507148871Scperciva	active_state->remote_protocol_flags = protocol_flags;
508148871Scperciva}
509148871Scperciva
510148871Scperciva/* Returns the remote protocol flags set earlier by the above function. */
511148871Scperciva
512148871Scpercivau_int
513148871Scpercivapacket_get_protocol_flags(void)
514148871Scperciva{
515148871Scperciva	return active_state->remote_protocol_flags;
516148871Scperciva}
517148871Scperciva
518148871Scperciva/*
519148871Scperciva * Starts packet compression from the next packet on in both directions.
520148871Scperciva * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
521148871Scperciva */
522149023Scperciva
523148871Scpercivastatic void
524148871Scpercivapacket_init_compression(void)
525148871Scperciva{
526148871Scperciva	if (active_state->compression_buffer_ready == 1)
527148871Scperciva		return;
528148871Scperciva	active_state->compression_buffer_ready = 1;
529148871Scperciva	buffer_init(&active_state->compression_buffer);
530148871Scperciva}
531148871Scperciva
532148871Scpercivavoid
533148871Scpercivapacket_start_compression(int level)
534148871Scperciva{
535148871Scperciva	if (active_state->packet_compression && !compat20)
536148871Scperciva		fatal("Compression already enabled.");
537148871Scperciva	active_state->packet_compression = 1;
538148871Scperciva	packet_init_compression();
539148871Scperciva	buffer_compress_init_send(level);
540148871Scperciva	buffer_compress_init_recv();
541148871Scperciva}
542148871Scperciva
543148871Scperciva/*
544148871Scperciva * Causes any further packets to be encrypted using the given key.  The same
545148871Scperciva * key is used for both sending and reception.  However, both directions are
546148871Scperciva * encrypted independently of each other.
547148871Scperciva */
548148871Scperciva
549148871Scpercivavoid
550148871Scpercivapacket_set_encryption_key(const u_char *key, u_int keylen, int number)
551148871Scperciva{
552148871Scperciva	Cipher *cipher = cipher_by_number(number);
553148871Scperciva
554148871Scperciva	if (cipher == NULL)
555148871Scperciva		fatal("packet_set_encryption_key: unknown cipher number %d", number);
556148871Scperciva	if (keylen < 20)
557148871Scperciva		fatal("packet_set_encryption_key: keylen too small: %d", keylen);
558148871Scperciva	if (keylen > SSH_SESSION_KEY_LENGTH)
559148871Scperciva		fatal("packet_set_encryption_key: keylen too big: %d", keylen);
560148871Scperciva	memcpy(active_state->ssh1_key, key, keylen);
561148871Scperciva	active_state->ssh1_keylen = keylen;
562148871Scperciva	cipher_init(&active_state->send_context, cipher, key, keylen, NULL,
563148871Scperciva	    0, CIPHER_ENCRYPT);
564148871Scperciva	cipher_init(&active_state->receive_context, cipher, key, keylen, NULL,
565148871Scperciva	    0, CIPHER_DECRYPT);
566148871Scperciva}
567148871Scperciva
568148871Scpercivau_int
569148871Scpercivapacket_get_encryption_key(u_char *key)
570148871Scperciva{
571148871Scperciva	if (key == NULL)
572148871Scperciva		return (active_state->ssh1_keylen);
573148871Scperciva	memcpy(key, active_state->ssh1_key, active_state->ssh1_keylen);
574148871Scperciva	return (active_state->ssh1_keylen);
575148871Scperciva}
576148871Scperciva
577148871Scperciva/* Start constructing a packet to send. */
578148871Scpercivavoid
579148871Scpercivapacket_start(u_char type)
580148871Scperciva{
581148871Scperciva	u_char buf[9];
582148871Scperciva	int len;
583148871Scperciva
584148871Scperciva	DBG(debug("packet_start[%d]", type));
585148871Scperciva	len = compat20 ? 6 : 9;
586148871Scperciva	memset(buf, 0, len - 1);
587148871Scperciva	buf[len - 1] = type;
588148871Scperciva	buffer_clear(&active_state->outgoing_packet);
589148871Scperciva	buffer_append(&active_state->outgoing_packet, buf, len);
590148871Scperciva}
591148871Scperciva
592148871Scperciva/* Append payload. */
593148871Scpercivavoid
594148871Scpercivapacket_put_char(int value)
595148871Scperciva{
596148871Scperciva	char ch = value;
597148871Scperciva
598148871Scperciva	buffer_append(&active_state->outgoing_packet, &ch, 1);
599148871Scperciva}
600148871Scperciva
601148871Scpercivavoid
602148871Scpercivapacket_put_int(u_int value)
603148871Scperciva{
604148871Scperciva	buffer_put_int(&active_state->outgoing_packet, value);
605148871Scperciva}
606148871Scperciva
607148871Scpercivavoid
608148871Scpercivapacket_put_int64(u_int64_t value)
609148871Scperciva{
610148871Scperciva	buffer_put_int64(&active_state->outgoing_packet, value);
611148871Scperciva}
612148871Scperciva
613148871Scpercivavoid
614148871Scpercivapacket_put_string(const void *buf, u_int len)
615148871Scperciva{
616148871Scperciva	buffer_put_string(&active_state->outgoing_packet, buf, len);
617148871Scperciva}
618148871Scperciva
619148879Scpercivavoid
620148871Scpercivapacket_put_cstring(const char *str)
621148871Scperciva{
622148871Scperciva	buffer_put_cstring(&active_state->outgoing_packet, str);
623148871Scperciva}
624148871Scperciva
625148871Scpercivavoid
626148871Scpercivapacket_put_raw(const void *buf, u_int len)
627148871Scperciva{
628148871Scperciva	buffer_append(&active_state->outgoing_packet, buf, len);
629148871Scperciva}
630148871Scperciva
631148871Scpercivavoid
632148871Scpercivapacket_put_bignum(BIGNUM * value)
633148871Scperciva{
634148871Scperciva	buffer_put_bignum(&active_state->outgoing_packet, value);
635148871Scperciva}
636148871Scperciva
637148871Scpercivavoid
638148871Scpercivapacket_put_bignum2(BIGNUM * value)
639148871Scperciva{
640148871Scperciva	buffer_put_bignum2(&active_state->outgoing_packet, value);
641148871Scperciva}
642148871Scperciva
643148871Scperciva#ifdef OPENSSL_HAS_ECC
644148871Scpercivavoid
645148871Scpercivapacket_put_ecpoint(const EC_GROUP *curve, const EC_POINT *point)
646148871Scperciva{
647148871Scperciva	buffer_put_ecpoint(&active_state->outgoing_packet, curve, point);
648148871Scperciva}
649148871Scperciva#endif
650148871Scperciva
651148871Scperciva/*
652148871Scperciva * Finalizes and sends the packet.  If the encryption key has been set,
653148879Scperciva * encrypts the packet before sending.
654148871Scperciva */
655148871Scperciva
656148871Scpercivastatic void
657148871Scpercivapacket_send1(void)
658148871Scperciva{
659148871Scperciva	u_char buf[8], *cp;
660148871Scperciva	int i, padding, len;
661148871Scperciva	u_int checksum;
662148871Scperciva	u_int32_t rnd = 0;
663148871Scperciva
664148871Scperciva	/*
665148871Scperciva	 * If using packet compression, compress the payload of the outgoing
666148871Scperciva	 * packet.
667148871Scperciva	 */
668148871Scperciva	if (active_state->packet_compression) {
669148871Scperciva		buffer_clear(&active_state->compression_buffer);
670148871Scperciva		/* Skip padding. */
671148871Scperciva		buffer_consume(&active_state->outgoing_packet, 8);
672148871Scperciva		/* padding */
673148871Scperciva		buffer_append(&active_state->compression_buffer,
674148871Scperciva		    "\0\0\0\0\0\0\0\0", 8);
675148871Scperciva		buffer_compress(&active_state->outgoing_packet,
676148871Scperciva		    &active_state->compression_buffer);
677148871Scperciva		buffer_clear(&active_state->outgoing_packet);
678148871Scperciva		buffer_append(&active_state->outgoing_packet,
679148879Scperciva		    buffer_ptr(&active_state->compression_buffer),
680148871Scperciva		    buffer_len(&active_state->compression_buffer));
681148871Scperciva	}
682148871Scperciva	/* Compute packet length without padding (add checksum, remove padding). */
683148871Scperciva	len = buffer_len(&active_state->outgoing_packet) + 4 - 8;
684148871Scperciva
685148871Scperciva	/* Insert padding. Initialized to zero in packet_start1() */
686148871Scperciva	padding = 8 - len % 8;
687148871Scperciva	if (!active_state->send_context.plaintext) {
688148871Scperciva		cp = buffer_ptr(&active_state->outgoing_packet);
689148871Scperciva		for (i = 0; i < padding; i++) {
690148871Scperciva			if (i % 4 == 0)
691148871Scperciva				rnd = arc4random();
692148871Scperciva			cp[7 - i] = rnd & 0xff;
693148871Scperciva			rnd >>= 8;
694148871Scperciva		}
695148871Scperciva	}
696148871Scperciva	buffer_consume(&active_state->outgoing_packet, 8 - padding);
697148871Scperciva
698148871Scperciva	/* Add check bytes. */
699148871Scperciva	checksum = ssh_crc32(buffer_ptr(&active_state->outgoing_packet),
700148871Scperciva	    buffer_len(&active_state->outgoing_packet));
701148871Scperciva	put_u32(buf, checksum);
702148871Scperciva	buffer_append(&active_state->outgoing_packet, buf, 4);
703148871Scperciva
704148871Scperciva#ifdef PACKET_DEBUG
705148871Scperciva	fprintf(stderr, "packet_send plain: ");
706148871Scperciva	buffer_dump(&active_state->outgoing_packet);
707148871Scperciva#endif
708148871Scperciva
709148871Scperciva	/* Append to output. */
710148879Scperciva	put_u32(buf, len);
711148871Scperciva	buffer_append(&active_state->output, buf, 4);
712148871Scperciva	cp = buffer_append_space(&active_state->output,
713148871Scperciva	    buffer_len(&active_state->outgoing_packet));
714148871Scperciva	cipher_crypt(&active_state->send_context, cp,
715148871Scperciva	    buffer_ptr(&active_state->outgoing_packet),
716148871Scperciva	    buffer_len(&active_state->outgoing_packet), 0, 0);
717148871Scperciva
718148871Scperciva#ifdef PACKET_DEBUG
719148871Scperciva	fprintf(stderr, "encrypted: ");
720148871Scperciva	buffer_dump(&active_state->output);
721148871Scperciva#endif
722148871Scperciva	active_state->p_send.packets++;
723148871Scperciva	active_state->p_send.bytes += len +
724148871Scperciva	    buffer_len(&active_state->outgoing_packet);
725148871Scperciva	buffer_clear(&active_state->outgoing_packet);
726148871Scperciva
727148871Scperciva	/*
728148871Scperciva	 * Note that the packet is now only buffered in output.  It won't be
729148871Scperciva	 * actually sent until packet_write_wait or packet_write_poll is
730148871Scperciva	 * called.
731148871Scperciva	 */
732148871Scperciva}
733148871Scperciva
734148871Scpercivavoid
735148871Scpercivaset_newkeys(int mode)
736148871Scperciva{
737148871Scperciva	Enc *enc;
738148871Scperciva	Mac *mac;
739148871Scperciva	Comp *comp;
740148871Scperciva	CipherContext *cc;
741148871Scperciva	u_int64_t *max_blocks;
742148871Scperciva	int crypt_type;
743148871Scperciva
744148871Scperciva	debug2("set_newkeys: mode %d", mode);
745148871Scperciva
746148871Scperciva	if (mode == MODE_OUT) {
747148871Scperciva		cc = &active_state->send_context;
748148871Scperciva		crypt_type = CIPHER_ENCRYPT;
749148871Scperciva		active_state->p_send.packets = active_state->p_send.blocks = 0;
750148871Scperciva		max_blocks = &active_state->max_blocks_out;
751148871Scperciva	} else {
752148871Scperciva		cc = &active_state->receive_context;
753148871Scperciva		crypt_type = CIPHER_DECRYPT;
754148871Scperciva		active_state->p_read.packets = active_state->p_read.blocks = 0;
755148871Scperciva		max_blocks = &active_state->max_blocks_in;
756148871Scperciva	}
757148871Scperciva	if (active_state->newkeys[mode] != NULL) {
758148871Scperciva		debug("set_newkeys: rekeying");
759148871Scperciva		cipher_cleanup(cc);
760148871Scperciva		enc  = &active_state->newkeys[mode]->enc;
761148871Scperciva		mac  = &active_state->newkeys[mode]->mac;
762148871Scperciva		comp = &active_state->newkeys[mode]->comp;
763148871Scperciva		mac_clear(mac);
764148871Scperciva		memset(enc->iv,  0, enc->iv_len);
765148871Scperciva		memset(enc->key, 0, enc->key_len);
766148871Scperciva		memset(mac->key, 0, mac->key_len);
767148871Scperciva		xfree(enc->name);
768148871Scperciva		xfree(enc->iv);
769148871Scperciva		xfree(enc->key);
770148871Scperciva		xfree(mac->name);
771149041Scperciva		xfree(mac->key);
772148871Scperciva		xfree(comp->name);
773148871Scperciva		xfree(active_state->newkeys[mode]);
774148871Scperciva	}
775148871Scperciva	active_state->newkeys[mode] = kex_get_newkeys(mode);
776148871Scperciva	if (active_state->newkeys[mode] == NULL)
777148871Scperciva		fatal("newkeys: no keys for mode %d", mode);
778148871Scperciva	enc  = &active_state->newkeys[mode]->enc;
779148871Scperciva	mac  = &active_state->newkeys[mode]->mac;
780148871Scperciva	comp = &active_state->newkeys[mode]->comp;
781148871Scperciva	if (cipher_authlen(enc->cipher) == 0 && mac_init(mac) == 0)
782148871Scperciva		mac->enabled = 1;
783148871Scperciva	DBG(debug("cipher_init_context: %d", mode));
784148871Scperciva	cipher_init(cc, enc->cipher, enc->key, enc->key_len,
785148871Scperciva	    enc->iv, enc->iv_len, crypt_type);
786148871Scperciva	/* Deleting the keys does not gain extra security */
787148871Scperciva	/* memset(enc->iv,  0, enc->block_size);
788148871Scperciva	   memset(enc->key, 0, enc->key_len);
789148871Scperciva	   memset(mac->key, 0, mac->key_len); */
790148871Scperciva	if ((comp->type == COMP_ZLIB ||
791148871Scperciva	    (comp->type == COMP_DELAYED &&
792149041Scperciva	     active_state->after_authentication)) && comp->enabled == 0) {
793149041Scperciva		packet_init_compression();
794149041Scperciva		if (mode == MODE_OUT)
795148871Scperciva			buffer_compress_init_send(6);
796148871Scperciva		else
797148871Scperciva			buffer_compress_init_recv();
798148871Scperciva		comp->enabled = 1;
799148871Scperciva	}
800148871Scperciva	/*
801148871Scperciva	 * The 2^(blocksize*2) limit is too expensive for 3DES,
802148871Scperciva	 * blowfish, etc, so enforce a 1GB limit for small blocksizes.
803148871Scperciva	 */
804148871Scperciva	if (enc->block_size >= 16)
805148871Scperciva		*max_blocks = (u_int64_t)1 << (enc->block_size*2);
806148871Scperciva	else
807148871Scperciva		*max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
808148871Scperciva	if (active_state->rekey_limit)
809148871Scperciva		*max_blocks = MIN(*max_blocks,
810148981Scperciva		    active_state->rekey_limit / enc->block_size);
811148981Scperciva}
812148958Scperciva
813148958Scperciva/*
814148958Scperciva * Delayed compression for SSH2 is enabled after authentication:
815148958Scperciva * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
816148871Scperciva * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
817148871Scperciva */
818148871Scpercivastatic void
819148871Scpercivapacket_enable_delayed_compress(void)
820148871Scperciva{
821148871Scperciva	Comp *comp = NULL;
822148871Scperciva	int mode;
823149041Scperciva
824149041Scperciva	/*
825148871Scperciva	 * Remember that we are past the authentication step, so rekeying
826148871Scperciva	 * with COMP_DELAYED will turn on compression immediately.
827148871Scperciva	 */
828148871Scperciva	active_state->after_authentication = 1;
829148871Scperciva	for (mode = 0; mode < MODE_MAX; mode++) {
830148871Scperciva		/* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
831148871Scperciva		if (active_state->newkeys[mode] == NULL)
832148871Scperciva			continue;
833148871Scperciva		comp = &active_state->newkeys[mode]->comp;
834148871Scperciva		if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
835148871Scperciva			packet_init_compression();
836148871Scperciva			if (mode == MODE_OUT)
837148871Scperciva				buffer_compress_init_send(6);
838148871Scperciva			else
839148871Scperciva				buffer_compress_init_recv();
840148871Scperciva			comp->enabled = 1;
841148871Scperciva		}
842148871Scperciva	}
843148871Scperciva}
844149041Scperciva
845149041Scperciva/*
846149041Scperciva * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
847148871Scperciva */
848148871Scpercivastatic void
849148871Scpercivapacket_send2_wrapped(void)
850148871Scperciva{
851148871Scperciva	u_char type, *cp, *macbuf = NULL;
852148871Scperciva	u_char padlen, pad = 0;
853148871Scperciva	u_int i, len, authlen = 0, aadlen = 0;
854148871Scperciva	u_int32_t rnd = 0;
855148871Scperciva	Enc *enc   = NULL;
856148871Scperciva	Mac *mac   = NULL;
857148871Scperciva	Comp *comp = NULL;
858148871Scperciva	int block_size;
859148871Scperciva
860148871Scperciva	if (active_state->newkeys[MODE_OUT] != NULL) {
861148871Scperciva		enc  = &active_state->newkeys[MODE_OUT]->enc;
862148871Scperciva		mac  = &active_state->newkeys[MODE_OUT]->mac;
863148871Scperciva		comp = &active_state->newkeys[MODE_OUT]->comp;
864148871Scperciva		/* disable mac for authenticated encryption */
865148871Scperciva		if ((authlen = cipher_authlen(enc->cipher)) != 0)
866148871Scperciva			mac = NULL;
867148871Scperciva	}
868148871Scperciva	block_size = enc ? enc->block_size : 8;
869148871Scperciva	aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
870148871Scperciva
871148871Scperciva	cp = buffer_ptr(&active_state->outgoing_packet);
872148871Scperciva	type = cp[5];
873148871Scperciva
874148871Scperciva#ifdef PACKET_DEBUG
875148871Scperciva	fprintf(stderr, "plain:     ");
876148871Scperciva	buffer_dump(&active_state->outgoing_packet);
877148871Scperciva#endif
878148871Scperciva
879148871Scperciva	if (comp && comp->enabled) {
880148871Scperciva		len = buffer_len(&active_state->outgoing_packet);
881148871Scperciva		/* skip header, compress only payload */
882148871Scperciva		buffer_consume(&active_state->outgoing_packet, 5);
883148871Scperciva		buffer_clear(&active_state->compression_buffer);
884148871Scperciva		buffer_compress(&active_state->outgoing_packet,
885148871Scperciva		    &active_state->compression_buffer);
886148871Scperciva		buffer_clear(&active_state->outgoing_packet);
887148871Scperciva		buffer_append(&active_state->outgoing_packet, "\0\0\0\0\0", 5);
888148871Scperciva		buffer_append(&active_state->outgoing_packet,
889148871Scperciva		    buffer_ptr(&active_state->compression_buffer),
890148871Scperciva		    buffer_len(&active_state->compression_buffer));
891148871Scperciva		DBG(debug("compression: raw %d compressed %d", len,
892148871Scperciva		    buffer_len(&active_state->outgoing_packet)));
893148871Scperciva	}
894148871Scperciva
895148871Scperciva	/* sizeof (packet_len + pad_len + payload) */
896148871Scperciva	len = buffer_len(&active_state->outgoing_packet);
897148871Scperciva
898148871Scperciva	/*
899148871Scperciva	 * calc size of padding, alloc space, get random data,
900148871Scperciva	 * minimum padding is 4 bytes
901148871Scperciva	 */
902148871Scperciva	len -= aadlen; /* packet length is not encrypted for EtM modes */
903148871Scperciva	padlen = block_size - (len % block_size);
904148871Scperciva	if (padlen < 4)
905148871Scperciva		padlen += block_size;
906148871Scperciva	if (active_state->extra_pad) {
907148871Scperciva		/* will wrap if extra_pad+padlen > 255 */
908148871Scperciva		active_state->extra_pad =
909148871Scperciva		    roundup(active_state->extra_pad, block_size);
910148871Scperciva		pad = active_state->extra_pad -
911148871Scperciva		    ((len + padlen) % active_state->extra_pad);
912148871Scperciva		debug3("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
913148871Scperciva		    pad, len, padlen, active_state->extra_pad);
914148871Scperciva		padlen += pad;
915148871Scperciva		active_state->extra_pad = 0;
916149027Scperciva	}
917149027Scperciva	cp = buffer_append_space(&active_state->outgoing_packet, padlen);
918149027Scperciva	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