packet.c revision 113908
11541Srgrimes/*
21541Srgrimes * Author: Tatu Ylonen <ylo@cs.hut.fi>
350477Speter * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
41541Srgrimes *                    All rights reserved
51541Srgrimes * This file contains code implementing the packet protocol and communication
61541Srgrimes * with the other side.  This same code is used both on client and server side.
799854Salfred *
81541Srgrimes * As far as I am concerned, the code I have written for this software
999854Salfred * can be used freely for any purpose.  Any derived versions of this
10171208Speter * software must be clearly marked as such, and if the derived work is
11194833Sjhb * incompatible with the protocol description in the RFC file, it must be
121541Srgrimes * called by a name other than "ssh" or "Secure Shell".
131541Srgrimes *
141541Srgrimes *
1510905Sbde * SSH2 packet format added by Markus Friedl.
1610905Sbde * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
171541Srgrimes *
1834354Sjb * Redistribution and use in source and binary forms, with or without
191541Srgrimes * modification, are permitted provided that the following conditions
2011294Sswallace * are met:
2111294Sswallace * 1. Redistributions of source code must retain the above copyright
2211294Sswallace *    notice, this list of conditions and the following disclaimer.
23160942Sjb * 2. Redistributions in binary form must reproduce the above copyright
241541Srgrimes *    notice, this list of conditions and the following disclaimer in the
251541Srgrimes *    documentation and/or other materials provided with the distribution.
26161327Sjhb *
2731627Sjmg * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
2831627Sjmg * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
2931627Sjmg * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
3099854Salfred * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
3199854Salfred * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
32171208Speter * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
33171208Speter * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
34194833Sjhb * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
35194833Sjhb * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
3631627Sjmg * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3731627Sjmg */
3831627Sjmg
3999854Salfred#include "includes.h"
40177656SjbRCSID("$OpenBSD: packet.c,v 1.104 2003/04/01 10:22:21 markus Exp $");
411541Srgrimes
42219131Srwatson#include "xmalloc.h"
43219131Srwatson#include "buffer.h"
44219131Srwatson#include "packet.h"
45219131Srwatson#include "bufaux.h"
46219131Srwatson#include "crc32.h"
47219131Srwatson#include "getput.h"
48219131Srwatson
49194833Sjhb#include "compress.h"
501541Srgrimes#include "deattack.h"
51194833Sjhb#include "channels.h"
5224373Speter
531541Srgrimes#include "compat.h"
5495258Sdes#include "ssh1.h"
551541Srgrimes#include "ssh2.h"
561541Srgrimes
571541Srgrimes#include "cipher.h"
581541Srgrimes#include "kex.h"
5936735Sdfr#include "mac.h"
6011294Sswallace#include "log.h"
6111294Sswallace#include "canohost.h"
6211294Sswallace#include "misc.h"
6311294Sswallace#include "ssh.h"
6411294Sswallace
6511294Sswallace#ifdef PACKET_DEBUG
6611294Sswallace#define DBG(x) x
6711294Sswallace#else
6811294Sswallace#define DBG(x)
6911294Sswallace#endif
7011294Sswallace
7111294Sswallace/*
7211294Sswallace * This variable contains the file descriptors used for communicating with
7311294Sswallace * the other side.  connection_in is used for reading; connection_out for
7411294Sswallace * writing.  These can be the same descriptor, in which case it is assumed to
7511294Sswallace * be a socket.
761541Srgrimes */
77161327Sjhbstatic int connection_in = -1;
781541Srgrimesstatic int connection_out = -1;
7910905Sbde
8099854Salfred/* Protocol flags for the remote side. */
8110905Sbdestatic u_int remote_protocol_flags = 0;
821541Srgrimes
8311294Sswallace/* Encryption context for receiving data.  This is only used for decryption. */
8499854Salfredstatic CipherContext receive_context;
8599854Salfred
86171208Speter/* Encryption context for sending data.  This is only used for encryption. */
87171208Speterstatic CipherContext send_context;
88194833Sjhb
89194833Sjhb/* Buffer for raw input data from the socket. */
901541SrgrimesBuffer input;
9136782Sbde
9211294Sswallace/* Buffer for raw output data going to the socket. */
9311294SswallaceBuffer output;
941541Srgrimes
951541Srgrimes/* Buffer for the partial outgoing packet being constructed. */
9634354Sjbstatic Buffer outgoing_packet;
97160942Sjb
98177656Sjb/* Buffer for the incoming packet currently being processed. */
991541Srgrimesstatic Buffer incoming_packet;
10099854Salfred
101171208Speter/* Scratch buffer for packet compression/decompression. */
102194833Sjhbstatic Buffer compression_buffer;
10311294Sswallacestatic int compression_buffer_ready = 0;
10411294Sswallace
10511294Sswallace/* Flag indicating whether packet compression/decompression is enabled. */
1061541Srgrimesstatic int packet_compression = 0;
107219131Srwatson
1081541Srgrimes/* default maximum packet size */
1091541Srgrimesint max_packet_size = 32768;
110219131Srwatson
111219131Srwatson/* Flag indicating whether this module has been initialized. */
11236782Sbdestatic int initialized = 0;
11336782Sbde
11489977Sbde/* Set to true if the connection is interactive. */
11510905Sbdestatic int interactive_mode = 0;
11611294Sswallace
11711294Sswallace/* Session key information for Encryption and MAC */
11889977SbdeNewkeys *newkeys[MODE_MAX];
1191541Srgrimesstatic u_int32_t read_seqnr = 0;
12031785Seivindstatic u_int32_t send_seqnr = 0;
12199854Salfred
122171208Speter/* Session key for protocol v1 */
123194833Sjhbstatic u_char ssh1_key[SSH_SESSION_KEY_LENGTH];
1241541Srgrimesstatic u_int ssh1_keylen;
1251541Srgrimes
1261541Srgrimes/* roundup current message to extra_pad bytes */
12789977Sbdestatic u_char extra_pad = 0;
1281541Srgrimes
1291541Srgrimes/*
1301541Srgrimes * Sets the descriptors used for communication.  Disables encryption until
13189977Sbde * packet_set_encryption_key is called.
13234354Sjb */
13334354Sjbvoid
13489984Sbdepacket_set_connection(int fd_in, int fd_out)
135160942Sjb{
136160942Sjb	Cipher *none = cipher_by_name("none");
137160942Sjb
138160942Sjb	if (none == NULL)
1391541Srgrimes		fatal("packet_set_connection: cannot load cipher 'none'");
1401541Srgrimes	connection_in = fd_in;
14150478Speter	connection_out = fd_out;
14210906Sbde	cipher_init(&send_context, none, "", 0, NULL, 0, CIPHER_ENCRYPT);
14311294Sswallace	cipher_init(&receive_context, none, "", 0, NULL, 0, CIPHER_DECRYPT);
14436782Sbde	newkeys[MODE_IN] = newkeys[MODE_OUT] = NULL;
14511294Sswallace	if (!initialized) {
14636782Sbde		initialized = 1;
14711294Sswallace		buffer_init(&input);
14810905Sbde		buffer_init(&output);
14911294Sswallace		buffer_init(&outgoing_packet);
15033039Sbde		buffer_init(&incoming_packet);
15133039Sbde	}
152103574Salfred	/* Kludge: arrange the close function to be called from fatal(). */
153103574Salfred	fatal_add_cleanup((void (*) (void *)) packet_close, NULL);
154177597Sru}
155164184Strhodes
156258106Sjhb/* Returns 1 if remote host is connected via socket, 0 if not. */
157258106Sjhb
158161327Sjhbint
15933039Sbdepacket_connection_is_on_socket(void)
16083366Sjulian{
16136770Sbde	struct sockaddr_storage from, to;
16236770Sbde	socklen_t fromlen, tolen;
16382149Stmm
16482149Stmm	/* filedescriptors in and out are the same, so it's a socket */
16582149Stmm	if (connection_in == connection_out)
16682149Stmm		return 1;
16782149Stmm	fromlen = sizeof(from);
16882149Stmm	memset(&from, 0, sizeof(from));
16982149Stmm	if (getpeername(connection_in, (struct sockaddr *)&from, &fromlen) < 0)
1701541Srgrimes		return 0;
1711541Srgrimes	tolen = sizeof(to);
172106149Sdwmalone	memset(&to, 0, sizeof(to));
1731541Srgrimes	if (getpeername(connection_out, (struct sockaddr *)&to, &tolen) < 0)
1741541Srgrimes		return 0;
1752700Swollman	if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
17634354Sjb		return 0;
17734354Sjb	if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
178160942Sjb		return 0;
179209390Sed	return 1;
180160942Sjb}
181160942Sjb
182160942Sjb/*
183177656Sjb * Exports an IV from the CipherContext required to export the key
184177656Sjb * state back from the unprivileged child to the privileged parent
185177656Sjb * process.
1861541Srgrimes */
1871541Srgrimes
1881541Srgrimesvoid
1891541Srgrimespacket_get_keyiv(int mode, u_char *iv, u_int len)
1901541Srgrimes{
19111294Sswallace	CipherContext *cc;
19211294Sswallace
19311294Sswallace	if (mode == MODE_OUT)
19411294Sswallace		cc = &send_context;
1951541Srgrimes	else
1961541Srgrimes		cc = &receive_context;
1971541Srgrimes
19811294Sswallace	cipher_get_keyiv(cc, iv, len);
1991541Srgrimes}
20099854Salfred
201171208Speterint
202194833Sjhbpacket_get_keycontext(int mode, u_char *dat)
2031541Srgrimes{
204219559Savg	CipherContext *cc;
205219559Savg
2061541Srgrimes	if (mode == MODE_OUT)
2071541Srgrimes		cc = &send_context;
2081541Srgrimes	else
2091541Srgrimes		cc = &receive_context;
2101541Srgrimes
2111541Srgrimes	return (cipher_get_keycontext(cc, dat));
21211294Sswallace}
2131541Srgrimes
21499854Salfredvoid
215171208Speterpacket_set_keycontext(int mode, u_char *dat)
216194833Sjhb{
2171541Srgrimes	CipherContext *cc;
218219559Savg
219219559Savg	if (mode == MODE_OUT)
2201541Srgrimes		cc = &send_context;
2211541Srgrimes	else
2221541Srgrimes		cc = &receive_context;
2231541Srgrimes
2241541Srgrimes	cipher_set_keycontext(cc, dat);
2251541Srgrimes}
22611294Sswallace
2271541Srgrimesint
22899854Salfredpacket_get_keyiv_len(int mode)
229171208Speter{
230194833Sjhb	CipherContext *cc;
2311541Srgrimes
232219559Savg	if (mode == MODE_OUT)
233219559Savg		cc = &send_context;
2341541Srgrimes	else
2351541Srgrimes		cc = &receive_context;
2361541Srgrimes
23736770Sbde	return (cipher_get_keyiv_len(cc));
23836770Sbde}
2391541Srgrimesvoid
2401541Srgrimespacket_set_iv(int mode, u_char *dat)
2411541Srgrimes{
2421541Srgrimes	CipherContext *cc;
243194390Sjhb
244194390Sjhb	if (mode == MODE_OUT)
245194390Sjhb		cc = &send_context;
246194390Sjhb	else
247194390Sjhb		cc = &receive_context;
248194390Sjhb
249194390Sjhb	cipher_set_keyiv(cc, dat);
250194390Sjhb}
251194390Sjhbint
252194390Sjhbpacket_get_ssh1_cipher()
253194390Sjhb{
254194390Sjhb	return (cipher_get_number(receive_context.cipher));
255194390Sjhb}
25660287Sbde
25760287Sbde
25860287Sbdeu_int32_t
25960287Sbdepacket_get_seqnr(int mode)
26060287Sbde{
26160287Sbde	return (mode == MODE_IN ? read_seqnr : send_seqnr);
26260287Sbde}
26360287Sbde
26411294Sswallacevoid
26536770Sbdepacket_set_seqnr(int mode, u_int32_t seqnr)
26611294Sswallace{
26711294Sswallace	if (mode == MODE_IN)
26811294Sswallace		read_seqnr = seqnr;
26911294Sswallace	else if (mode == MODE_OUT)
270146806Srwatson		send_seqnr = seqnr;
27111294Sswallace	else
27260287Sbde		fatal("packet_set_seqnr: bad mode %d", mode);
273209579Skib}
274209579Skib
275209579Skib/* returns 1 if connection is via ipv4 */
276209579Skib
27711294Sswallaceint
27811294Sswallacepacket_connection_is_ipv4(void)
27911294Sswallace{
28011294Sswallace	struct sockaddr_storage to;
28111294Sswallace	socklen_t tolen = sizeof(to);
28211294Sswallace
28311294Sswallace	memset(&to, 0, sizeof(to));
28411294Sswallace	if (getsockname(connection_out, (struct sockaddr *)&to, &tolen) < 0)
28511294Sswallace		return 0;
28611294Sswallace	if (to.ss_family == AF_INET)
28710905Sbde		return 1;
288194390Sjhb#ifdef IPV4_IN_IPV6
289146806Srwatson	if (to.ss_family == AF_INET6 &&
290146806Srwatson	    IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&to)->sin6_addr))
291146806Srwatson		return 1;
29211294Sswallace#endif
29311294Sswallace	return 0;
29411294Sswallace}
29511294Sswallace
29611294Sswallace/* Sets the connection into non-blocking mode. */
29711294Sswallace
29811294Sswallacevoid
29911294Sswallacepacket_set_nonblocking(void)
30011294Sswallace{
30111294Sswallace	/* Set the socket into non-blocking mode. */
30211294Sswallace	if (fcntl(connection_in, F_SETFL, O_NONBLOCK) < 0)
30311294Sswallace		error("fcntl O_NONBLOCK: %.100s", strerror(errno));
30411294Sswallace
30511294Sswallace	if (connection_out != connection_in) {
30611294Sswallace		if (fcntl(connection_out, F_SETFL, O_NONBLOCK) < 0)
30711294Sswallace			error("fcntl O_NONBLOCK: %.100s", strerror(errno));
30811294Sswallace	}
30911294Sswallace}
310219131Srwatson
311219131Srwatson/* Returns the socket used for reading. */
312219131Srwatson
313219131Srwatsonint
314219131Srwatsonpacket_get_connection_in(void)
315219131Srwatson{
316219131Srwatson	return connection_in;
317219131Srwatson}
318219131Srwatson
319219131Srwatson/* Returns the descriptor used for writing. */
320219131Srwatson
321219131Srwatsonint
32211294Sswallacepacket_get_connection_out(void)
32311294Sswallace{
32411294Sswallace	return connection_out;
32511294Sswallace}
326194390Sjhb
32711330Sswallace/* Closes the connection and clears and frees internal data structures. */
328194390Sjhb
32999854Salfredvoid
330194390Sjhbpacket_close(void)
331171208Speter{
332194833Sjhb	if (!initialized)
333194833Sjhb		return;
33411294Sswallace	initialized = 0;
33511294Sswallace	if (connection_in == connection_out) {
33611294Sswallace		shutdown(connection_out, SHUT_RDWR);
33711294Sswallace		close(connection_out);
33811294Sswallace	} else {
33911294Sswallace		close(connection_in);
34011294Sswallace		close(connection_out);
34111294Sswallace	}
34211294Sswallace	buffer_free(&input);
34311294Sswallace	buffer_free(&output);
34411294Sswallace	buffer_free(&outgoing_packet);
34511294Sswallace	buffer_free(&incoming_packet);
34611294Sswallace	if (compression_buffer_ready) {
34711294Sswallace		buffer_free(&compression_buffer);
34811294Sswallace		buffer_compress_uninit();
34911294Sswallace	}
35011294Sswallace	cipher_cleanup(&send_context);
35111294Sswallace	cipher_cleanup(&receive_context);
35211294Sswallace}
35311294Sswallace
35411294Sswallace/* Sets remote side protocol flags. */
35511294Sswallace
35611294Sswallacevoid
35711294Sswallacepacket_set_protocol_flags(u_int protocol_flags)
35811294Sswallace{
35911294Sswallace	remote_protocol_flags = protocol_flags;
36011294Sswallace}
36111294Sswallace
36211294Sswallace/* Returns the remote protocol flags set earlier by the above function. */
36360287Sbde
36460287Sbdeu_int
3651541Srgrimespacket_get_protocol_flags(void)
366146806Srwatson{
367146806Srwatson	return remote_protocol_flags;
368146806Srwatson}
36911294Sswallace
37011294Sswallace/*
37182585Sdillon * Starts packet compression from the next packet on in both directions.
372146806Srwatson * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
373146806Srwatson */
374146806Srwatson
375146806Srwatsonstatic void
376146806Srwatsonpacket_init_compression(void)
377146806Srwatson{
378146806Srwatson	if (compression_buffer_ready == 1)
379193234Srwatson		return;
380219131Srwatson	compression_buffer_ready = 1;
381193234Srwatson	buffer_init(&compression_buffer);
382193234Srwatson}
383193234Srwatson
384193234Srwatsonvoid
385193234Srwatsonpacket_start_compression(int level)
386194390Sjhb{
387194390Sjhb	if (packet_compression && !compat20)
38811294Sswallace		fatal("Compression already enabled.");
389160942Sjb	packet_compression = 1;
390177656Sjb	packet_init_compression();
391160942Sjb	buffer_compress_init_send(level);
392177656Sjb	buffer_compress_init_recv();
393160942Sjb}
394160942Sjb
395262034Savg/*
396262034Savg * Causes any further packets to be encrypted using the given key.  The same
397262034Savg * key is used for both sending and reception.  However, both directions are
398262034Savg * encrypted independently of each other.
399160942Sjb */
400160942Sjb
401262034Savgvoid
402262034Savgpacket_set_encryption_key(const u_char *key, u_int keylen,
403160942Sjb    int number)
404160942Sjb{
405262034Savg	Cipher *cipher = cipher_by_number(number);
406160942Sjb
407160942Sjb	if (cipher == NULL)
408160942Sjb		fatal("packet_set_encryption_key: unknown cipher number %d", number);
409262034Savg	if (keylen < 20)
410160942Sjb		fatal("packet_set_encryption_key: keylen too small: %d", keylen);
411177656Sjb	if (keylen > SSH_SESSION_KEY_LENGTH)
412160942Sjb		fatal("packet_set_encryption_key: keylen too big: %d", keylen);
413160942Sjb	memcpy(ssh1_key, key, keylen);
414177656Sjb	ssh1_keylen = keylen;
415194390Sjhb	cipher_init(&send_context, cipher, key, keylen, NULL, 0, CIPHER_ENCRYPT);
416194390Sjhb	cipher_init(&receive_context, cipher, key, keylen, NULL, 0, CIPHER_DECRYPT);
417183361Sjhb}
418183361Sjhb
419183361Sjhbu_int
420183361Sjhbpacket_get_encryption_key(u_char *key)
421183361Sjhb{
422183361Sjhb	if (key == NULL)
423183361Sjhb		return (ssh1_keylen);
424183361Sjhb	memcpy(key, ssh1_key, ssh1_keylen);
42510905Sbde	return (ssh1_keylen);
426194390Sjhb}
427183361Sjhb
428183361Sjhb/* Start constructing a packet to send. */
429194390Sjhbvoid
430225617Skmacypacket_start(u_char type)
431225617Skmacy{
432225617Skmacy	u_char buf[9];
433225617Skmacy	int len;
434225617Skmacy
435225617Skmacy	DBG(debug("packet_start[%d]", type));
436225617Skmacy	len = compat20 ? 6 : 9;
437225617Skmacy	memset(buf, 0, len - 1);
438225617Skmacy	buf[len - 1] = type;
439225617Skmacy	buffer_clear(&outgoing_packet);
44018277Sbde	buffer_append(&outgoing_packet, buf, len);
441161327Sjhb}
442161327Sjhb
44311330Sswallace/* Append payload. */
444160798Sjhbvoid
445160798Sjhbpacket_put_char(int value)
446194390Sjhb{
447209579Skib	char ch = value;
448193234Srwatson
44969445Salfred	buffer_append(&outgoing_packet, &ch, 1);
450225617Skmacy}
451225617Skmacyvoid
452225617Skmacypacket_put_int(u_int value)
453225617Skmacy{
454225617Skmacy	buffer_put_int(&outgoing_packet, value);
455225617Skmacy}
456225617Skmacyvoid
457225617Skmacypacket_put_string(const void *buf, u_int len)
458225617Skmacy{
459225617Skmacy	buffer_put_string(&outgoing_packet, buf, len);
46069445Salfred}
46160287Sbdevoid
46258963Salfredpacket_put_cstring(const char *str)
46336770Sbde{
46411294Sswallace	buffer_put_cstring(&outgoing_packet, str);
465194390Sjhb}
46636770Sbdevoid
46711294Sswallacepacket_put_raw(const void *buf, u_int len)
46834354Sjb{
46934354Sjb	buffer_append(&outgoing_packet, buf, len);
4701541Srgrimes}
4711541Srgrimesvoid
4721541Srgrimespacket_put_bignum(BIGNUM * value)
473194833Sjhb{
474194833Sjhb	buffer_put_bignum(&outgoing_packet, value);
475194390Sjhb}
47699854Salfredvoid
47799854Salfredpacket_put_bignum2(BIGNUM * value)
47899854Salfred{
47999854Salfred	buffer_put_bignum2(&outgoing_packet, value);
48099854Salfred}
481194390Sjhb
482194390Sjhb/*
48399854Salfred * Finalizes and sends the packet.  If the encryption key has been set,
48499854Salfred * encrypts the packet before sending.
48599854Salfred */
48699854Salfred
48799854Salfredstatic void
488194390Sjhbpacket_send1(void)
489194390Sjhb{
490171208Speter	u_char buf[8], *cp;
491171208Speter	int i, padding, len;
492171208Speter	u_int checksum;
493171208Speter	u_int32_t rand = 0;
494171208Speter
495194390Sjhb	/*
496194833Sjhb	 * If using packet compression, compress the payload of the outgoing
497194833Sjhb	 * packet.
498194833Sjhb	 */
499194833Sjhb	if (packet_compression) {
500194833Sjhb		buffer_clear(&compression_buffer);
501194833Sjhb		/* Skip padding. */
502194833Sjhb		buffer_consume(&outgoing_packet, 8);
50399854Salfred		/* padding */
50411294Sswallace		buffer_append(&compression_buffer, "\0\0\0\0\0\0\0\0", 8);
505194390Sjhb		buffer_compress(&outgoing_packet, &compression_buffer);
506194390Sjhb		buffer_clear(&outgoing_packet);
50799854Salfred		buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
50811294Sswallace		    buffer_len(&compression_buffer));
50982149Stmm	}
51082149Stmm	/* Compute packet length without padding (add checksum, remove padding). */
51182149Stmm	len = buffer_len(&outgoing_packet) + 4 - 8;
51236735Sdfr
51399854Salfred	/* Insert padding. Initialized to zero in packet_start1() */
51499854Salfred	padding = 8 - len % 8;
51511294Sswallace	if (!send_context.plaintext) {
516194390Sjhb		cp = buffer_ptr(&outgoing_packet);
51783046Sobrien		for (i = 0; i < padding; i++) {
51836770Sbde			if (i % 4 == 0)
519194390Sjhb				rand = arc4random();
520194390Sjhb			cp[7 - i] = rand & 0xff;
521194390Sjhb			rand >>= 8;
522194646Sjhb		}
523194646Sjhb	}
524194390Sjhb	buffer_consume(&outgoing_packet, 8 - padding);
525194390Sjhb
526209579Skib	/* Add check bytes. */
527194390Sjhb	checksum = ssh_crc32(buffer_ptr(&outgoing_packet),
528194390Sjhb	    buffer_len(&outgoing_packet));
529194390Sjhb	PUT_32BIT(buf, checksum);
530194390Sjhb	buffer_append(&outgoing_packet, buf, 4);
531209579Skib
532209579Skib#ifdef PACKET_DEBUG
533194390Sjhb	fprintf(stderr, "packet_send plain: ");
534194390Sjhb	buffer_dump(&outgoing_packet);
535194390Sjhb#endif
536194390Sjhb
537194390Sjhb	/* Append to output. */
538194390Sjhb	PUT_32BIT(buf, len);
539194390Sjhb	buffer_append(&output, buf, 4);
540194390Sjhb	cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
541171208Speter	cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
542171208Speter	    buffer_len(&outgoing_packet));
543194390Sjhb
544171208Speter#ifdef PACKET_DEBUG
545171208Speter	fprintf(stderr, "encrypted: ");
546171208Speter	buffer_dump(&output);
547171208Speter#endif
5481541Srgrimes
5491541Srgrimes	buffer_clear(&outgoing_packet);
5501541Srgrimes
551194390Sjhb	/*
552209579Skib	 * Note that the packet is now only buffered in output.  It won\'t be
55360287Sbde	 * actually sent until packet_write_wait or packet_write_poll is
55460287Sbde	 * called.
55536770Sbde	 */
556146806Srwatson}
55736770Sbde
5581541Srgrimesvoid
5591541Srgrimesset_newkeys(int mode)
5601541Srgrimes{
5611541Srgrimes	Enc *enc;
562194390Sjhb	Mac *mac;
563209579Skib	Comp *comp;
5641541Srgrimes	CipherContext *cc;
56536770Sbde	int encrypt;
5661541Srgrimes
5671541Srgrimes	debug2("set_newkeys: mode %d", mode);
5681541Srgrimes
5691541Srgrimes	if (mode == MODE_OUT) {
5701541Srgrimes		cc = &send_context;
571146806Srwatson		encrypt = CIPHER_ENCRYPT;
5721541Srgrimes	} else {
5731541Srgrimes		cc = &receive_context;
5741541Srgrimes		encrypt = CIPHER_DECRYPT;
57560287Sbde	}
57699854Salfred	if (newkeys[mode] != NULL) {
577194833Sjhb		debug("set_newkeys: rekeying");
57899854Salfred		cipher_cleanup(cc);
57999854Salfred		enc  = &newkeys[mode]->enc;
58036782Sbde		mac  = &newkeys[mode]->mac;
58136782Sbde		comp = &newkeys[mode]->comp;
58236782Sbde		memset(mac->key, 0, mac->key_len);
58336782Sbde		xfree(enc->name);
58436782Sbde		xfree(enc->iv);
58536782Sbde		xfree(enc->key);
58636782Sbde		xfree(mac->name);
58736782Sbde		xfree(mac->key);
58899854Salfred		xfree(comp->name);
58999854Salfred		xfree(newkeys[mode]);
59099854Salfred	}
59199854Salfred	newkeys[mode] = kex_get_newkeys(mode);
59299854Salfred	if (newkeys[mode] == NULL)
59399854Salfred		fatal("newkeys: no keys for mode %d", mode);
59499854Salfred	enc  = &newkeys[mode]->enc;
59599854Salfred	mac  = &newkeys[mode]->mac;
596171208Speter	comp = &newkeys[mode]->comp;
597171208Speter	if (mac->md != NULL)
598171208Speter		mac->enabled = 1;
599171208Speter	DBG(debug("cipher_init_context: %d", mode));
600171208Speter	cipher_init(cc, enc->cipher, enc->key, enc->key_len,
601171208Speter	    enc->iv, enc->block_size, encrypt);
602171208Speter	/* Deleting the keys does not gain extra security */
603171208Speter	/* memset(enc->iv,  0, enc->block_size);
604194833Sjhb	   memset(enc->key, 0, enc->key_len); */
605194833Sjhb	if (comp->type != 0 && comp->enabled == 0) {
606194833Sjhb		packet_init_compression();
607194833Sjhb		if (mode == MODE_OUT)
608194833Sjhb			buffer_compress_init_send(6);
609194833Sjhb		else
610194833Sjhb			buffer_compress_init_recv();
611194833Sjhb		comp->enabled = 1;
61236735Sdfr	}
61399854Salfred}
614171208Speter
615194833Sjhb/*
61699854Salfred * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
617161327Sjhb */
61899854Salfredstatic void
61999854Salfredpacket_send2(void)
62099854Salfred{
62199854Salfred	u_char type, *cp, *macbuf = NULL;
62237227Sphk	u_char padlen, pad;
62314331Speter	u_int packet_length = 0;
6241541Srgrimes	u_int i, len;
62511294Sswallace	u_int32_t rand = 0;
62636770Sbde	Enc *enc   = NULL;
627160942Sjb	Mac *mac   = NULL;
628177656Sjb	Comp *comp = NULL;
6291541Srgrimes	int block_size;
6301541Srgrimes
63136782Sbde	if (newkeys[MODE_OUT] != NULL) {
63299854Salfred		enc  = &newkeys[MODE_OUT]->enc;
63399854Salfred		mac  = &newkeys[MODE_OUT]->mac;
63499854Salfred		comp = &newkeys[MODE_OUT]->comp;
635171208Speter	}
636194833Sjhb	block_size = enc ? enc->block_size : 8;
637161327Sjhb
638177656Sjb	cp = buffer_ptr(&outgoing_packet);
63999854Salfred	type = cp[5];
640
641#ifdef PACKET_DEBUG
642	fprintf(stderr, "plain:     ");
643	buffer_dump(&outgoing_packet);
644#endif
645
646	if (comp && comp->enabled) {
647		len = buffer_len(&outgoing_packet);
648		/* skip header, compress only payload */
649		buffer_consume(&outgoing_packet, 5);
650		buffer_clear(&compression_buffer);
651		buffer_compress(&outgoing_packet, &compression_buffer);
652		buffer_clear(&outgoing_packet);
653		buffer_append(&outgoing_packet, "\0\0\0\0\0", 5);
654		buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
655		    buffer_len(&compression_buffer));
656		DBG(debug("compression: raw %d compressed %d", len,
657		    buffer_len(&outgoing_packet)));
658	}
659
660	/* sizeof (packet_len + pad_len + payload) */
661	len = buffer_len(&outgoing_packet);
662
663	/*
664	 * calc size of padding, alloc space, get random data,
665	 * minimum padding is 4 bytes
666	 */
667	padlen = block_size - (len % block_size);
668	if (padlen < 4)
669		padlen += block_size;
670	if (extra_pad) {
671		/* will wrap if extra_pad+padlen > 255 */
672		extra_pad  = roundup(extra_pad, block_size);
673		pad = extra_pad - ((len + padlen) % extra_pad);
674		debug3("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
675		    pad, len, padlen, extra_pad);
676		padlen += pad;
677		extra_pad = 0;
678	}
679	cp = buffer_append_space(&outgoing_packet, padlen);
680	if (enc && !send_context.plaintext) {
681		/* random padding */
682		for (i = 0; i < padlen; i++) {
683			if (i % 4 == 0)
684				rand = arc4random();
685			cp[i] = rand & 0xff;
686			rand >>= 8;
687		}
688	} else {
689		/* clear padding */
690		memset(cp, 0, padlen);
691	}
692	/* packet_length includes payload, padding and padding length field */
693	packet_length = buffer_len(&outgoing_packet) - 4;
694	cp = buffer_ptr(&outgoing_packet);
695	PUT_32BIT(cp, packet_length);
696	cp[4] = padlen;
697	DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen));
698
699	/* compute MAC over seqnr and packet(length fields, payload, padding) */
700	if (mac && mac->enabled) {
701		macbuf = mac_compute(mac, send_seqnr,
702		    buffer_ptr(&outgoing_packet),
703		    buffer_len(&outgoing_packet));
704		DBG(debug("done calc MAC out #%d", send_seqnr));
705	}
706	/* encrypt packet and append to output buffer. */
707	cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
708	cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
709	    buffer_len(&outgoing_packet));
710	/* append unencrypted MAC */
711	if (mac && mac->enabled)
712		buffer_append(&output, (char *)macbuf, mac->mac_len);
713#ifdef PACKET_DEBUG
714	fprintf(stderr, "encrypted: ");
715	buffer_dump(&output);
716#endif
717	/* increment sequence number for outgoing packets */
718	if (++send_seqnr == 0)
719		log("outgoing seqnr wraps around");
720	buffer_clear(&outgoing_packet);
721
722	if (type == SSH2_MSG_NEWKEYS)
723		set_newkeys(MODE_OUT);
724}
725
726void
727packet_send(void)
728{
729	if (compat20)
730		packet_send2();
731	else
732		packet_send1();
733	DBG(debug("packet_send done"));
734}
735
736/*
737 * Waits until a packet has been received, and returns its type.  Note that
738 * no other data is processed until this returns, so this function should not
739 * be used during the interactive session.
740 */
741
742int
743packet_read_seqnr(u_int32_t *seqnr_p)
744{
745	int type, len;
746	fd_set *setp;
747	char buf[8192];
748	DBG(debug("packet_read()"));
749
750	setp = (fd_set *)xmalloc(howmany(connection_in+1, NFDBITS) *
751	    sizeof(fd_mask));
752
753	/* Since we are blocking, ensure that all written packets have been sent. */
754	packet_write_wait();
755
756	/* Stay in the loop until we have received a complete packet. */
757	for (;;) {
758		/* Try to read a packet from the buffer. */
759		type = packet_read_poll_seqnr(seqnr_p);
760		if (!compat20 && (
761		    type == SSH_SMSG_SUCCESS
762		    || type == SSH_SMSG_FAILURE
763		    || type == SSH_CMSG_EOF
764		    || type == SSH_CMSG_EXIT_CONFIRMATION))
765			packet_check_eom();
766		/* If we got a packet, return it. */
767		if (type != SSH_MSG_NONE) {
768			xfree(setp);
769			return type;
770		}
771		/*
772		 * Otherwise, wait for some data to arrive, add it to the
773		 * buffer, and try again.
774		 */
775		memset(setp, 0, howmany(connection_in + 1, NFDBITS) *
776		    sizeof(fd_mask));
777		FD_SET(connection_in, setp);
778
779		/* Wait for some data to arrive. */
780		while (select(connection_in + 1, setp, NULL, NULL, NULL) == -1 &&
781		    (errno == EAGAIN || errno == EINTR))
782			;
783
784		/* Read data from the socket. */
785		len = read(connection_in, buf, sizeof(buf));
786		if (len == 0) {
787			log("Connection closed by %.200s", get_remote_ipaddr());
788			fatal_cleanup();
789		}
790		if (len < 0)
791			fatal("Read from socket failed: %.100s", strerror(errno));
792		/* Append it to the buffer. */
793		packet_process_incoming(buf, len);
794	}
795	/* NOTREACHED */
796}
797
798int
799packet_read(void)
800{
801	return packet_read_seqnr(NULL);
802}
803
804/*
805 * Waits until a packet has been received, verifies that its type matches
806 * that given, and gives a fatal error and exits if there is a mismatch.
807 */
808
809void
810packet_read_expect(int expected_type)
811{
812	int type;
813
814	type = packet_read();
815	if (type != expected_type)
816		packet_disconnect("Protocol error: expected packet type %d, got %d",
817		    expected_type, type);
818}
819
820/* Checks if a full packet is available in the data received so far via
821 * packet_process_incoming.  If so, reads the packet; otherwise returns
822 * SSH_MSG_NONE.  This does not wait for data from the connection.
823 *
824 * SSH_MSG_DISCONNECT is handled specially here.  Also,
825 * SSH_MSG_IGNORE messages are skipped by this function and are never returned
826 * to higher levels.
827 */
828
829static int
830packet_read_poll1(void)
831{
832	u_int len, padded_len;
833	u_char *cp, type;
834	u_int checksum, stored_checksum;
835
836	/* Check if input size is less than minimum packet size. */
837	if (buffer_len(&input) < 4 + 8)
838		return SSH_MSG_NONE;
839	/* Get length of incoming packet. */
840	cp = buffer_ptr(&input);
841	len = GET_32BIT(cp);
842	if (len < 1 + 2 + 2 || len > 256 * 1024)
843		packet_disconnect("Bad packet length %u.", len);
844	padded_len = (len + 8) & ~7;
845
846	/* Check if the packet has been entirely received. */
847	if (buffer_len(&input) < 4 + padded_len)
848		return SSH_MSG_NONE;
849
850	/* The entire packet is in buffer. */
851
852	/* Consume packet length. */
853	buffer_consume(&input, 4);
854
855	/*
856	 * Cryptographic attack detector for ssh
857	 * (C)1998 CORE-SDI, Buenos Aires Argentina
858	 * Ariel Futoransky(futo@core-sdi.com)
859	 */
860	if (!receive_context.plaintext &&
861	    detect_attack(buffer_ptr(&input), padded_len, NULL) == DEATTACK_DETECTED)
862		packet_disconnect("crc32 compensation attack: network attack detected");
863
864	/* Decrypt data to incoming_packet. */
865	buffer_clear(&incoming_packet);
866	cp = buffer_append_space(&incoming_packet, padded_len);
867	cipher_crypt(&receive_context, cp, buffer_ptr(&input), padded_len);
868
869	buffer_consume(&input, padded_len);
870
871#ifdef PACKET_DEBUG
872	fprintf(stderr, "read_poll plain: ");
873	buffer_dump(&incoming_packet);
874#endif
875
876	/* Compute packet checksum. */
877	checksum = ssh_crc32(buffer_ptr(&incoming_packet),
878	    buffer_len(&incoming_packet) - 4);
879
880	/* Skip padding. */
881	buffer_consume(&incoming_packet, 8 - len % 8);
882
883	/* Test check bytes. */
884	if (len != buffer_len(&incoming_packet))
885		packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
886		    len, buffer_len(&incoming_packet));
887
888	cp = (u_char *)buffer_ptr(&incoming_packet) + len - 4;
889	stored_checksum = GET_32BIT(cp);
890	if (checksum != stored_checksum)
891		packet_disconnect("Corrupted check bytes on input.");
892	buffer_consume_end(&incoming_packet, 4);
893
894	if (packet_compression) {
895		buffer_clear(&compression_buffer);
896		buffer_uncompress(&incoming_packet, &compression_buffer);
897		buffer_clear(&incoming_packet);
898		buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
899		    buffer_len(&compression_buffer));
900	}
901	type = buffer_get_char(&incoming_packet);
902	return type;
903}
904
905static int
906packet_read_poll2(u_int32_t *seqnr_p)
907{
908	static u_int packet_length = 0;
909	u_int padlen, need;
910	u_char *macbuf, *cp, type;
911	int maclen, block_size;
912	Enc *enc   = NULL;
913	Mac *mac   = NULL;
914	Comp *comp = NULL;
915
916	if (newkeys[MODE_IN] != NULL) {
917		enc  = &newkeys[MODE_IN]->enc;
918		mac  = &newkeys[MODE_IN]->mac;
919		comp = &newkeys[MODE_IN]->comp;
920	}
921	maclen = mac && mac->enabled ? mac->mac_len : 0;
922	block_size = enc ? enc->block_size : 8;
923
924	if (packet_length == 0) {
925		/*
926		 * check if input size is less than the cipher block size,
927		 * decrypt first block and extract length of incoming packet
928		 */
929		if (buffer_len(&input) < block_size)
930			return SSH_MSG_NONE;
931		buffer_clear(&incoming_packet);
932		cp = buffer_append_space(&incoming_packet, block_size);
933		cipher_crypt(&receive_context, cp, buffer_ptr(&input),
934		    block_size);
935		cp = buffer_ptr(&incoming_packet);
936		packet_length = GET_32BIT(cp);
937		if (packet_length < 1 + 4 || packet_length > 256 * 1024) {
938			buffer_dump(&incoming_packet);
939			packet_disconnect("Bad packet length %u.", packet_length);
940		}
941		DBG(debug("input: packet len %u", packet_length+4));
942		buffer_consume(&input, block_size);
943	}
944	/* we have a partial packet of block_size bytes */
945	need = 4 + packet_length - block_size;
946	DBG(debug("partial packet %d, need %d, maclen %d", block_size,
947	    need, maclen));
948	if (need % block_size != 0)
949		fatal("padding error: need %d block %d mod %d",
950		    need, block_size, need % block_size);
951	/*
952	 * check if the entire packet has been received and
953	 * decrypt into incoming_packet
954	 */
955	if (buffer_len(&input) < need + maclen)
956		return SSH_MSG_NONE;
957#ifdef PACKET_DEBUG
958	fprintf(stderr, "read_poll enc/full: ");
959	buffer_dump(&input);
960#endif
961	cp = buffer_append_space(&incoming_packet, need);
962	cipher_crypt(&receive_context, cp, buffer_ptr(&input), need);
963	buffer_consume(&input, need);
964	/*
965	 * compute MAC over seqnr and packet,
966	 * increment sequence number for incoming packet
967	 */
968	if (mac && mac->enabled) {
969		macbuf = mac_compute(mac, read_seqnr,
970		    buffer_ptr(&incoming_packet),
971		    buffer_len(&incoming_packet));
972		if (memcmp(macbuf, buffer_ptr(&input), mac->mac_len) != 0)
973			packet_disconnect("Corrupted MAC on input.");
974		DBG(debug("MAC #%d ok", read_seqnr));
975		buffer_consume(&input, mac->mac_len);
976	}
977	if (seqnr_p != NULL)
978		*seqnr_p = read_seqnr;
979	if (++read_seqnr == 0)
980		log("incoming seqnr wraps around");
981
982	/* get padlen */
983	cp = buffer_ptr(&incoming_packet);
984	padlen = cp[4];
985	DBG(debug("input: padlen %d", padlen));
986	if (padlen < 4)
987		packet_disconnect("Corrupted padlen %d on input.", padlen);
988
989	/* skip packet size + padlen, discard padding */
990	buffer_consume(&incoming_packet, 4 + 1);
991	buffer_consume_end(&incoming_packet, padlen);
992
993	DBG(debug("input: len before de-compress %d", buffer_len(&incoming_packet)));
994	if (comp && comp->enabled) {
995		buffer_clear(&compression_buffer);
996		buffer_uncompress(&incoming_packet, &compression_buffer);
997		buffer_clear(&incoming_packet);
998		buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
999		    buffer_len(&compression_buffer));
1000		DBG(debug("input: len after de-compress %d",
1001		    buffer_len(&incoming_packet)));
1002	}
1003	/*
1004	 * get packet type, implies consume.
1005	 * return length of payload (without type field)
1006	 */
1007	type = buffer_get_char(&incoming_packet);
1008	if (type == SSH2_MSG_NEWKEYS)
1009		set_newkeys(MODE_IN);
1010#ifdef PACKET_DEBUG
1011	fprintf(stderr, "read/plain[%d]:\r\n", type);
1012	buffer_dump(&incoming_packet);
1013#endif
1014	/* reset for next packet */
1015	packet_length = 0;
1016	return type;
1017}
1018
1019int
1020packet_read_poll_seqnr(u_int32_t *seqnr_p)
1021{
1022	u_int reason, seqnr;
1023	u_char type;
1024	char *msg;
1025
1026	for (;;) {
1027		if (compat20) {
1028			type = packet_read_poll2(seqnr_p);
1029			if (type)
1030				DBG(debug("received packet type %d", type));
1031			switch (type) {
1032			case SSH2_MSG_IGNORE:
1033				break;
1034			case SSH2_MSG_DEBUG:
1035				packet_get_char();
1036				msg = packet_get_string(NULL);
1037				debug("Remote: %.900s", msg);
1038				xfree(msg);
1039				msg = packet_get_string(NULL);
1040				xfree(msg);
1041				break;
1042			case SSH2_MSG_DISCONNECT:
1043				reason = packet_get_int();
1044				msg = packet_get_string(NULL);
1045				log("Received disconnect from %s: %u: %.400s",
1046				    get_remote_ipaddr(), reason, msg);
1047				xfree(msg);
1048				fatal_cleanup();
1049				break;
1050			case SSH2_MSG_UNIMPLEMENTED:
1051				seqnr = packet_get_int();
1052				debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1053				    seqnr);
1054				break;
1055			default:
1056				return type;
1057				break;
1058			}
1059		} else {
1060			type = packet_read_poll1();
1061			switch (type) {
1062			case SSH_MSG_IGNORE:
1063				break;
1064			case SSH_MSG_DEBUG:
1065				msg = packet_get_string(NULL);
1066				debug("Remote: %.900s", msg);
1067				xfree(msg);
1068				break;
1069			case SSH_MSG_DISCONNECT:
1070				msg = packet_get_string(NULL);
1071				log("Received disconnect from %s: %.400s",
1072				    get_remote_ipaddr(), msg);
1073				fatal_cleanup();
1074				xfree(msg);
1075				break;
1076			default:
1077				if (type)
1078					DBG(debug("received packet type %d", type));
1079				return type;
1080				break;
1081			}
1082		}
1083	}
1084}
1085
1086int
1087packet_read_poll(void)
1088{
1089	return packet_read_poll_seqnr(NULL);
1090}
1091
1092/*
1093 * Buffers the given amount of input characters.  This is intended to be used
1094 * together with packet_read_poll.
1095 */
1096
1097void
1098packet_process_incoming(const char *buf, u_int len)
1099{
1100	buffer_append(&input, buf, len);
1101}
1102
1103/* Returns a character from the packet. */
1104
1105u_int
1106packet_get_char(void)
1107{
1108	char ch;
1109
1110	buffer_get(&incoming_packet, &ch, 1);
1111	return (u_char) ch;
1112}
1113
1114/* Returns an integer from the packet data. */
1115
1116u_int
1117packet_get_int(void)
1118{
1119	return buffer_get_int(&incoming_packet);
1120}
1121
1122/*
1123 * Returns an arbitrary precision integer from the packet data.  The integer
1124 * must have been initialized before this call.
1125 */
1126
1127void
1128packet_get_bignum(BIGNUM * value)
1129{
1130	buffer_get_bignum(&incoming_packet, value);
1131}
1132
1133void
1134packet_get_bignum2(BIGNUM * value)
1135{
1136	buffer_get_bignum2(&incoming_packet, value);
1137}
1138
1139void *
1140packet_get_raw(int *length_ptr)
1141{
1142	int bytes = buffer_len(&incoming_packet);
1143
1144	if (length_ptr != NULL)
1145		*length_ptr = bytes;
1146	return buffer_ptr(&incoming_packet);
1147}
1148
1149int
1150packet_remaining(void)
1151{
1152	return buffer_len(&incoming_packet);
1153}
1154
1155/*
1156 * Returns a string from the packet data.  The string is allocated using
1157 * xmalloc; it is the responsibility of the calling program to free it when
1158 * no longer needed.  The length_ptr argument may be NULL, or point to an
1159 * integer into which the length of the string is stored.
1160 */
1161
1162void *
1163packet_get_string(u_int *length_ptr)
1164{
1165	return buffer_get_string(&incoming_packet, length_ptr);
1166}
1167
1168/*
1169 * Sends a diagnostic message from the server to the client.  This message
1170 * can be sent at any time (but not while constructing another message). The
1171 * message is printed immediately, but only if the client is being executed
1172 * in verbose mode.  These messages are primarily intended to ease debugging
1173 * authentication problems.   The length of the formatted message must not
1174 * exceed 1024 bytes.  This will automatically call packet_write_wait.
1175 */
1176
1177void
1178packet_send_debug(const char *fmt,...)
1179{
1180	char buf[1024];
1181	va_list args;
1182
1183	if (compat20 && (datafellows & SSH_BUG_DEBUG))
1184		return;
1185
1186	va_start(args, fmt);
1187	vsnprintf(buf, sizeof(buf), fmt, args);
1188	va_end(args);
1189
1190	if (compat20) {
1191		packet_start(SSH2_MSG_DEBUG);
1192		packet_put_char(0);	/* bool: always display */
1193		packet_put_cstring(buf);
1194		packet_put_cstring("");
1195	} else {
1196		packet_start(SSH_MSG_DEBUG);
1197		packet_put_cstring(buf);
1198	}
1199	packet_send();
1200	packet_write_wait();
1201}
1202
1203/*
1204 * Logs the error plus constructs and sends a disconnect packet, closes the
1205 * connection, and exits.  This function never returns. The error message
1206 * should not contain a newline.  The length of the formatted message must
1207 * not exceed 1024 bytes.
1208 */
1209
1210void
1211packet_disconnect(const char *fmt,...)
1212{
1213	char buf[1024];
1214	va_list args;
1215	static int disconnecting = 0;
1216
1217	if (disconnecting)	/* Guard against recursive invocations. */
1218		fatal("packet_disconnect called recursively.");
1219	disconnecting = 1;
1220
1221	/*
1222	 * Format the message.  Note that the caller must make sure the
1223	 * message is of limited size.
1224	 */
1225	va_start(args, fmt);
1226	vsnprintf(buf, sizeof(buf), fmt, args);
1227	va_end(args);
1228
1229	/* Display the error locally */
1230	log("Disconnecting: %.100s", buf);
1231
1232	/* Send the disconnect message to the other side, and wait for it to get sent. */
1233	if (compat20) {
1234		packet_start(SSH2_MSG_DISCONNECT);
1235		packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1236		packet_put_cstring(buf);
1237		packet_put_cstring("");
1238	} else {
1239		packet_start(SSH_MSG_DISCONNECT);
1240		packet_put_cstring(buf);
1241	}
1242	packet_send();
1243	packet_write_wait();
1244
1245	/* Stop listening for connections. */
1246	channel_close_all();
1247
1248	/* Close the connection. */
1249	packet_close();
1250
1251	fatal_cleanup();
1252}
1253
1254/* Checks if there is any buffered output, and tries to write some of the output. */
1255
1256void
1257packet_write_poll(void)
1258{
1259	int len = buffer_len(&output);
1260
1261	if (len > 0) {
1262		len = write(connection_out, buffer_ptr(&output), len);
1263		if (len <= 0) {
1264			if (errno == EAGAIN)
1265				return;
1266			else
1267				fatal("Write failed: %.100s", strerror(errno));
1268		}
1269		buffer_consume(&output, len);
1270	}
1271}
1272
1273/*
1274 * Calls packet_write_poll repeatedly until all pending output data has been
1275 * written.
1276 */
1277
1278void
1279packet_write_wait(void)
1280{
1281	fd_set *setp;
1282
1283	setp = (fd_set *)xmalloc(howmany(connection_out + 1, NFDBITS) *
1284	    sizeof(fd_mask));
1285	packet_write_poll();
1286	while (packet_have_data_to_write()) {
1287		memset(setp, 0, howmany(connection_out + 1, NFDBITS) *
1288		    sizeof(fd_mask));
1289		FD_SET(connection_out, setp);
1290		while (select(connection_out + 1, NULL, setp, NULL, NULL) == -1 &&
1291		    (errno == EAGAIN || errno == EINTR))
1292			;
1293		packet_write_poll();
1294	}
1295	xfree(setp);
1296}
1297
1298/* Returns true if there is buffered data to write to the connection. */
1299
1300int
1301packet_have_data_to_write(void)
1302{
1303	return buffer_len(&output) != 0;
1304}
1305
1306/* Returns true if there is not too much data to write to the connection. */
1307
1308int
1309packet_not_very_much_data_to_write(void)
1310{
1311	if (interactive_mode)
1312		return buffer_len(&output) < 16384;
1313	else
1314		return buffer_len(&output) < 128 * 1024;
1315}
1316
1317static void
1318packet_set_tos(int interactive)
1319{
1320	int tos = interactive ? IPTOS_LOWDELAY : IPTOS_THROUGHPUT;
1321
1322	if (!packet_connection_is_on_socket() ||
1323	    !packet_connection_is_ipv4())
1324		return;
1325	if (setsockopt(connection_in, IPPROTO_IP, IP_TOS, &tos,
1326	    sizeof(tos)) < 0)
1327		error("setsockopt IP_TOS %d: %.100s:",
1328		    tos, strerror(errno));
1329}
1330
1331/* Informs that the current session is interactive.  Sets IP flags for that. */
1332
1333void
1334packet_set_interactive(int interactive)
1335{
1336	static int called = 0;
1337
1338	if (called)
1339		return;
1340	called = 1;
1341
1342	/* Record that we are in interactive mode. */
1343	interactive_mode = interactive;
1344
1345	/* Only set socket options if using a socket.  */
1346	if (!packet_connection_is_on_socket())
1347	if (interactive)
1348		set_nodelay(connection_in);
1349#if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1350	packet_set_tos(interactive);
1351#endif
1352
1353}
1354
1355/* Returns true if the current connection is interactive. */
1356
1357int
1358packet_is_interactive(void)
1359{
1360	return interactive_mode;
1361}
1362
1363int
1364packet_set_maxsize(int s)
1365{
1366	static int called = 0;
1367
1368	if (called) {
1369		log("packet_set_maxsize: called twice: old %d new %d",
1370		    max_packet_size, s);
1371		return -1;
1372	}
1373	if (s < 4 * 1024 || s > 1024 * 1024) {
1374		log("packet_set_maxsize: bad size %d", s);
1375		return -1;
1376	}
1377	called = 1;
1378	debug("packet_set_maxsize: setting to %d", s);
1379	max_packet_size = s;
1380	return s;
1381}
1382
1383/* roundup current message to pad bytes */
1384void
1385packet_add_padding(u_char pad)
1386{
1387	extra_pad = pad;
1388}
1389
1390/*
1391 * 9.2.  Ignored Data Message
1392 *
1393 *   byte      SSH_MSG_IGNORE
1394 *   string    data
1395 *
1396 * All implementations MUST understand (and ignore) this message at any
1397 * time (after receiving the protocol version). No implementation is
1398 * required to send them. This message can be used as an additional
1399 * protection measure against advanced traffic analysis techniques.
1400 */
1401void
1402packet_send_ignore(int nbytes)
1403{
1404	u_int32_t rand = 0;
1405	int i;
1406
1407	packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1408	packet_put_int(nbytes);
1409	for (i = 0; i < nbytes; i++) {
1410		if (i % 4 == 0)
1411			rand = arc4random();
1412		packet_put_char(rand & 0xff);
1413		rand >>= 8;
1414	}
1415}
1416