packet.c revision 162853
1148871Scperciva/* $OpenBSD: packet.c,v 1.145 2006/09/19 21:14:08 markus Exp $ */
2148871Scperciva/*
3148871Scperciva * Author: Tatu Ylonen <ylo@cs.hut.fi>
4148871Scperciva * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5148871Scperciva *                    All rights reserved
6148871Scperciva * This file contains code implementing the packet protocol and communication
7148871Scperciva * with the other side.  This same code is used both on client and server side.
8148871Scperciva *
9148871Scperciva * As far as I am concerned, the code I have written for this software
10148871Scperciva * can be used freely for any purpose.  Any derived versions of this
11148871Scperciva * software must be clearly marked as such, and if the derived work is
12148871Scperciva * incompatible with the protocol description in the RFC file, it must be
13148871Scperciva * called by a name other than "ssh" or "Secure Shell".
14148871Scperciva *
15148871Scperciva *
16148871Scperciva * SSH2 packet format added by Markus Friedl.
17148871Scperciva * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
18148871Scperciva *
19148871Scperciva * Redistribution and use in source and binary forms, with or without
20148871Scperciva * modification, are permitted provided that the following conditions
21148871Scperciva * are met:
22148871Scperciva * 1. Redistributions of source code must retain the above copyright
23148871Scperciva *    notice, this list of conditions and the following disclaimer.
24148871Scperciva * 2. Redistributions in binary form must reproduce the above copyright
25148871Scperciva *    notice, this list of conditions and the following disclaimer in the
26148871Scperciva *    documentation and/or other materials provided with the distribution.
27148871Scperciva *
28148871Scperciva * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
29148871Scperciva * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
30148871Scperciva * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
31148871Scperciva * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
32148871Scperciva * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
33148871Scperciva * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
34148871Scperciva * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
35148871Scperciva * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
36148871Scperciva * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
37149027Scperciva * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38148871Scperciva */
39148871Scperciva
40148871Scperciva#include "includes.h"
41148871Scperciva
42148871Scperciva#include <sys/types.h>
43148871Scperciva#include "openbsd-compat/sys-queue.h"
44148871Scperciva#include <sys/param.h>
45148871Scperciva#include <sys/socket.h>
46158523Scperciva#ifdef HAVE_SYS_TIME_H
47148871Scperciva# include <sys/time.h>
48148871Scperciva#endif
49148871Scperciva
50148871Scperciva#include <netinet/in_systm.h>
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"
75148871Scperciva#include "kex.h"
76149027Scperciva#include "mac.h"
77148871Scperciva#include "log.h"
78148871Scperciva#include "canohost.h"
79148871Scperciva#include "misc.h"
80148879Scperciva#include "ssh.h"
81148871Scperciva
82148871Scperciva#ifdef PACKET_DEBUG
83148871Scperciva#define DBG(x) x
84148871Scperciva#else
85149824Scperciva#define DBG(x)
86158523Scperciva#endif
87148871Scperciva
88148871Scperciva/*
89148871Scperciva * This variable contains the file descriptors used for communicating with
90148871Scperciva * the other side.  connection_in is used for reading; connection_out for
91148871Scperciva * writing.  These can be the same descriptor, in which case it is assumed to
92148871Scperciva * be a socket.
93148871Scperciva */
94148871Scpercivastatic int connection_in = -1;
95148871Scpercivastatic int connection_out = -1;
96148871Scperciva
97148871Scperciva/* Protocol flags for the remote side. */
98148871Scpercivastatic u_int remote_protocol_flags = 0;
99148871Scperciva
100148871Scperciva/* Encryption context for receiving data.  This is only used for decryption. */
101148871Scpercivastatic CipherContext receive_context;
102148871Scperciva
103148879Scperciva/* Encryption context for sending data.  This is only used for encryption. */
104148871Scpercivastatic CipherContext send_context;
105148871Scperciva
106148871Scperciva/* Buffer for raw input data from the socket. */
107148871ScpercivaBuffer input;
108148871Scperciva
109148871Scperciva/* Buffer for raw output data going to the socket. */
110148871ScpercivaBuffer output;
111148871Scperciva
112148871Scperciva/* Buffer for the partial outgoing packet being constructed. */
113148871Scpercivastatic Buffer outgoing_packet;
114148871Scperciva
115148871Scperciva/* Buffer for the incoming packet currently being processed. */
116148871Scpercivastatic Buffer incoming_packet;
117148871Scperciva
118148871Scperciva/* Scratch buffer for packet compression/decompression. */
119148871Scpercivastatic Buffer compression_buffer;
120148871Scpercivastatic int compression_buffer_ready = 0;
121148871Scperciva
122158523Scperciva/* Flag indicating whether packet compression/decompression is enabled. */
123158523Scpercivastatic int packet_compression = 0;
124158523Scperciva
125158523Scperciva/* default maximum packet size */
126158523Scpercivau_int max_packet_size = 32768;
127148871Scperciva
128148871Scperciva/* Flag indicating whether this module has been initialized. */
129148871Scpercivastatic int initialized = 0;
130148871Scperciva
131148871Scperciva/* Set to true if the connection is interactive. */
132148871Scpercivastatic int interactive_mode = 0;
133148871Scperciva
134148871Scperciva/* Set to true if we are the server side. */
135148871Scpercivastatic int server_side = 0;
136148871Scperciva
137148871Scperciva/* Set to true if we are authenticated. */
138148871Scpercivastatic int after_authentication = 0;
139148871Scperciva
140148871Scperciva/* Session key information for Encryption and MAC */
141148871ScpercivaNewkeys *newkeys[MODE_MAX];
142148871Scpercivastatic struct packet_state {
143201251Scperciva	u_int32_t seqnr;
144149027Scperciva	u_int32_t packets;
145148871Scperciva	u_int64_t blocks;
146235310Seadler} p_read, p_send;
147235310Seadler
148235310Seadlerstatic u_int64_t max_blocks_in, max_blocks_out;
149148871Scpercivastatic u_int32_t rekey_limit;
150148871Scperciva
151149027Scperciva/* Session key for protocol v1 */
152149027Scpercivastatic u_char ssh1_key[SSH_SESSION_KEY_LENGTH];
153149027Scpercivastatic u_int ssh1_keylen;
154148871Scperciva
155148871Scperciva/* roundup current message to extra_pad bytes */
156148871Scpercivastatic u_char extra_pad = 0;
157148871Scperciva
158148871Scpercivastruct packet {
159148871Scperciva	TAILQ_ENTRY(packet) next;
160149027Scperciva	u_char type;
161148871Scperciva	Buffer payload;
162148871Scperciva};
163148871ScpercivaTAILQ_HEAD(, packet) outgoing;
164148871Scperciva
165148871Scperciva/*
166148871Scperciva * Sets the descriptors used for communication.  Disables encryption until
167148871Scperciva * packet_set_encryption_key is called.
168148871Scperciva */
169148871Scpercivavoid
170148871Scpercivapacket_set_connection(int fd_in, int fd_out)
171148871Scperciva{
172148871Scperciva	Cipher *none = cipher_by_name("none");
173148871Scperciva
174148871Scperciva	if (none == NULL)
175148871Scperciva		fatal("packet_set_connection: cannot load cipher 'none'");
176148871Scperciva	connection_in = fd_in;
177148871Scperciva	connection_out = fd_out;
178148871Scperciva	cipher_init(&send_context, none, (const u_char *)"",
179148871Scperciva	    0, NULL, 0, CIPHER_ENCRYPT);
180148871Scperciva	cipher_init(&receive_context, none, (const u_char *)"",
181148871Scperciva	    0, NULL, 0, CIPHER_DECRYPT);
182148871Scperciva	newkeys[MODE_IN] = newkeys[MODE_OUT] = NULL;
183148871Scperciva	if (!initialized) {
184148871Scperciva		initialized = 1;
185148871Scperciva		buffer_init(&input);
186148871Scperciva		buffer_init(&output);
187149824Scperciva		buffer_init(&outgoing_packet);
188149824Scperciva		buffer_init(&incoming_packet);
189148871Scperciva		TAILQ_INIT(&outgoing);
190148871Scperciva	}
191148871Scperciva}
192148871Scperciva
193148871Scperciva/* Returns 1 if remote host is connected via socket, 0 if not. */
194148871Scperciva
195148871Scpercivaint
196148871Scpercivapacket_connection_is_on_socket(void)
197148871Scperciva{
198149824Scperciva	struct sockaddr_storage from, to;
199149824Scperciva	socklen_t fromlen, tolen;
200149824Scperciva
201149824Scperciva	/* filedescriptors in and out are the same, so it's a socket */
202149824Scperciva	if (connection_in == connection_out)
203149824Scperciva		return 1;
204149824Scperciva	fromlen = sizeof(from);
205179073Scperciva	memset(&from, 0, sizeof(from));
206179073Scperciva	if (getpeername(connection_in, (struct sockaddr *)&from, &fromlen) < 0)
207179073Scperciva		return 0;
208179073Scperciva	tolen = sizeof(to);
209179073Scperciva	memset(&to, 0, sizeof(to));
210179073Scperciva	if (getpeername(connection_out, (struct sockaddr *)&to, &tolen) < 0)
211148871Scperciva		return 0;
212148871Scperciva	if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
213148871Scperciva		return 0;
214148871Scperciva	if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
215148871Scperciva		return 0;
216148871Scperciva	return 1;
217148871Scperciva}
218148871Scperciva
219148871Scperciva/*
220148871Scperciva * Exports an IV from the CipherContext required to export the key
221148871Scperciva * state back from the unprivileged child to the privileged parent
222158523Scperciva * process.
223158523Scperciva */
224158523Scperciva
225148871Scpercivavoid
226148871Scpercivapacket_get_keyiv(int mode, u_char *iv, u_int len)
227148871Scperciva{
228148871Scperciva	CipherContext *cc;
229148871Scperciva
230148871Scperciva	if (mode == MODE_OUT)
231148871Scperciva		cc = &send_context;
232148871Scperciva	else
233148871Scperciva		cc = &receive_context;
234148871Scperciva
235148871Scperciva	cipher_get_keyiv(cc, iv, len);
236148871Scperciva}
237148871Scperciva
238148871Scpercivaint
239148871Scpercivapacket_get_keycontext(int mode, u_char *dat)
240148871Scperciva{
241148871Scperciva	CipherContext *cc;
242148871Scperciva
243148871Scperciva	if (mode == MODE_OUT)
244148871Scperciva		cc = &send_context;
245148871Scperciva	else
246148871Scperciva		cc = &receive_context;
247148871Scperciva
248148871Scperciva	return (cipher_get_keycontext(cc, dat));
249148871Scperciva}
250148871Scperciva
251148871Scpercivavoid
252148871Scpercivapacket_set_keycontext(int mode, u_char *dat)
253148871Scperciva{
254148871Scperciva	CipherContext *cc;
255148871Scperciva
256148871Scperciva	if (mode == MODE_OUT)
257148871Scperciva		cc = &send_context;
258148871Scperciva	else
259148871Scperciva		cc = &receive_context;
260148871Scperciva
261148871Scperciva	cipher_set_keycontext(cc, dat);
262148871Scperciva}
263148871Scperciva
264148871Scpercivaint
265148871Scpercivapacket_get_keyiv_len(int mode)
266148871Scperciva{
267148871Scperciva	CipherContext *cc;
268148871Scperciva
269148871Scperciva	if (mode == MODE_OUT)
270148871Scperciva		cc = &send_context;
271148871Scperciva	else
272148871Scperciva		cc = &receive_context;
273148871Scperciva
274148871Scperciva	return (cipher_get_keyiv_len(cc));
275148871Scperciva}
276154088Scperciva
277154088Scpercivavoid
278148871Scpercivapacket_set_iv(int mode, u_char *dat)
279148871Scperciva{
280154088Scperciva	CipherContext *cc;
281148871Scperciva
282148871Scperciva	if (mode == MODE_OUT)
283148871Scperciva		cc = &send_context;
284148871Scperciva	else
285148871Scperciva		cc = &receive_context;
286148871Scperciva
287148871Scperciva	cipher_set_keyiv(cc, dat);
288154088Scperciva}
289148871Scperciva
290148871Scpercivaint
291148871Scpercivapacket_get_ssh1_cipher(void)
292148871Scperciva{
293148871Scperciva	return (cipher_get_number(receive_context.cipher));
294148871Scperciva}
295148871Scperciva
296148871Scpercivavoid
297148871Scpercivapacket_get_state(int mode, u_int32_t *seqnr, u_int64_t *blocks, u_int32_t *packets)
298148871Scperciva{
299148871Scperciva	struct packet_state *state;
300148871Scperciva
301148871Scperciva	state = (mode == MODE_IN) ? &p_read : &p_send;
302148871Scperciva	*seqnr = state->seqnr;
303148871Scperciva	*blocks = state->blocks;
304148871Scperciva	*packets = state->packets;
305148871Scperciva}
306148871Scperciva
307148871Scpercivavoid
308148871Scpercivapacket_set_state(int mode, u_int32_t seqnr, u_int64_t blocks, u_int32_t packets)
309148871Scperciva{
310148871Scperciva	struct packet_state *state;
311148871Scperciva
312148871Scperciva	state = (mode == MODE_IN) ? &p_read : &p_send;
313148871Scperciva	state->seqnr = seqnr;
314148871Scperciva	state->blocks = blocks;
315148871Scperciva	state->packets = packets;
316148871Scperciva}
317148871Scperciva
318148871Scperciva/* returns 1 if connection is via ipv4 */
319148871Scperciva
320148871Scpercivaint
321148871Scpercivapacket_connection_is_ipv4(void)
322148871Scperciva{
323148871Scperciva	struct sockaddr_storage to;
324148871Scperciva	socklen_t tolen = sizeof(to);
325148871Scperciva
326148871Scperciva	memset(&to, 0, sizeof(to));
327148871Scperciva	if (getsockname(connection_out, (struct sockaddr *)&to, &tolen) < 0)
328148871Scperciva		return 0;
329148871Scperciva	if (to.ss_family == AF_INET)
330158273Scperciva		return 1;
331158273Scperciva#ifdef IPV4_IN_IPV6
332158273Scperciva	if (to.ss_family == AF_INET6 &&
333158273Scperciva	    IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&to)->sin6_addr))
334158273Scperciva		return 1;
335158273Scperciva#endif
336158273Scperciva	return 0;
337150159Scperciva}
338156813Sru
339150159Scperciva/* Sets the connection into non-blocking mode. */
340158273Scperciva
341158273Scpercivavoid
342150159Scpercivapacket_set_nonblocking(void)
343150159Scperciva{
344158273Scperciva	/* Set the socket into non-blocking mode. */
345148871Scperciva	set_nonblock(connection_in);
346148871Scperciva
347158245Scperciva	if (connection_out != connection_in)
348158245Scperciva		set_nonblock(connection_out);
349158245Scperciva}
350158245Scperciva
351265753Sdelphij/* Returns the socket used for reading. */
352158245Scperciva
353158273Scpercivaint
354158273Scpercivapacket_get_connection_in(void)
355148871Scperciva{
356148871Scperciva	return connection_in;
357158273Scperciva}
358158273Scperciva
359158273Scperciva/* Returns the descriptor used for writing. */
360158273Scperciva
361158273Scpercivaint
362158273Scpercivapacket_get_connection_out(void)
363158273Scperciva{
364158274Scperciva	return connection_out;
365158274Scperciva}
366158274Scperciva
367158274Scperciva/* Closes the connection and clears and frees internal data structures. */
368158301Scperciva
369158301Scpercivavoid
370158274Scpercivapacket_close(void)
371158274Scperciva{
372158274Scperciva	if (!initialized)
373158274Scperciva		return;
374158274Scperciva	initialized = 0;
375158273Scperciva	if (connection_in == connection_out) {
376158273Scperciva		shutdown(connection_out, SHUT_RDWR);
377158273Scperciva		close(connection_out);
378158273Scperciva	} else {
379158273Scperciva		close(connection_in);
380158273Scperciva		close(connection_out);
381158273Scperciva	}
382158273Scperciva	buffer_free(&input);
383158273Scperciva	buffer_free(&output);
384148871Scperciva	buffer_free(&outgoing_packet);
385158273Scperciva	buffer_free(&incoming_packet);
386158273Scperciva	if (compression_buffer_ready) {
387148871Scperciva		buffer_free(&compression_buffer);
388148871Scperciva		buffer_compress_uninit();
389148871Scperciva	}
390148871Scperciva	cipher_cleanup(&send_context);
391148871Scperciva	cipher_cleanup(&receive_context);
392148871Scperciva}
393148871Scperciva
394148871Scperciva/* Sets remote side protocol flags. */
395148871Scperciva
396148871Scpercivavoid
397148871Scpercivapacket_set_protocol_flags(u_int protocol_flags)
398148871Scperciva{
399148871Scperciva	remote_protocol_flags = protocol_flags;
400148871Scperciva}
401148871Scperciva
402148871Scperciva/* Returns the remote protocol flags set earlier by the above function. */
403148871Scperciva
404148871Scpercivau_int
405148871Scpercivapacket_get_protocol_flags(void)
406148871Scperciva{
407148871Scperciva	return remote_protocol_flags;
408148871Scperciva}
409148871Scperciva
410148871Scperciva/*
411158274Scperciva * Starts packet compression from the next packet on in both directions.
412158274Scperciva * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
413148871Scperciva */
414158273Scperciva
415158273Scpercivastatic void
416158273Scpercivapacket_init_compression(void)
417148871Scperciva{
418148871Scperciva	if (compression_buffer_ready == 1)
419148871Scperciva		return;
420148871Scperciva	compression_buffer_ready = 1;
421148871Scperciva	buffer_init(&compression_buffer);
422158274Scperciva}
423148871Scperciva
424158273Scpercivavoid
425148871Scpercivapacket_start_compression(int level)
426148871Scperciva{
427148871Scperciva	if (packet_compression && !compat20)
428148871Scperciva		fatal("Compression already enabled.");
429148871Scperciva	packet_compression = 1;
430148871Scperciva	packet_init_compression();
431148871Scperciva	buffer_compress_init_send(level);
432148871Scperciva	buffer_compress_init_recv();
433148871Scperciva}
434148871Scperciva
435158273Scperciva/*
436158273Scperciva * Causes any further packets to be encrypted using the given key.  The same
437148871Scperciva * key is used for both sending and reception.  However, both directions are
438148871Scperciva * encrypted independently of each other.
439158273Scperciva */
440148871Scperciva
441148871Scpercivavoid
442158273Scpercivapacket_set_encryption_key(const u_char *key, u_int keylen,
443148871Scperciva    int number)
444148871Scperciva{
445148871Scperciva	Cipher *cipher = cipher_by_number(number);
446148871Scperciva
447148871Scperciva	if (cipher == NULL)
448148871Scperciva		fatal("packet_set_encryption_key: unknown cipher number %d", number);
449148871Scperciva	if (keylen < 20)
450148871Scperciva		fatal("packet_set_encryption_key: keylen too small: %d", keylen);
451148871Scperciva	if (keylen > SSH_SESSION_KEY_LENGTH)
452148871Scperciva		fatal("packet_set_encryption_key: keylen too big: %d", keylen);
453148871Scperciva	memcpy(ssh1_key, key, keylen);
454148871Scperciva	ssh1_keylen = keylen;
455148871Scperciva	cipher_init(&send_context, cipher, key, keylen, NULL, 0, CIPHER_ENCRYPT);
456148871Scperciva	cipher_init(&receive_context, cipher, key, keylen, NULL, 0, CIPHER_DECRYPT);
457148871Scperciva}
458148871Scperciva
459148871Scpercivau_int
460148871Scpercivapacket_get_encryption_key(u_char *key)
461148871Scperciva{
462158273Scperciva	if (key == NULL)
463158273Scperciva		return (ssh1_keylen);
464148871Scperciva	memcpy(key, ssh1_key, ssh1_keylen);
465148871Scperciva	return (ssh1_keylen);
466148871Scperciva}
467148871Scperciva
468148871Scperciva/* Start constructing a packet to send. */
469148871Scpercivavoid
470148871Scpercivapacket_start(u_char type)
471148871Scperciva{
472148871Scperciva	u_char buf[9];
473148871Scperciva	int len;
474148871Scperciva
475148871Scperciva	DBG(debug("packet_start[%d]", type));
476148871Scperciva	len = compat20 ? 6 : 9;
477148871Scperciva	memset(buf, 0, len - 1);
478148871Scperciva	buf[len - 1] = type;
479148871Scperciva	buffer_clear(&outgoing_packet);
480148871Scperciva	buffer_append(&outgoing_packet, buf, len);
481148871Scperciva}
482148871Scperciva
483148871Scperciva/* Append payload. */
484148871Scpercivavoid
485148871Scpercivapacket_put_char(int value)
486148871Scperciva{
487148871Scperciva	char ch = value;
488148871Scperciva
489148871Scperciva	buffer_append(&outgoing_packet, &ch, 1);
490148871Scperciva}
491149868Scperciva
492148871Scpercivavoid
493148871Scpercivapacket_put_int(u_int value)
494148871Scperciva{
495148871Scperciva	buffer_put_int(&outgoing_packet, value);
496148871Scperciva}
497148871Scperciva
498148871Scpercivavoid
499148871Scpercivapacket_put_string(const void *buf, u_int len)
500148871Scperciva{
501148871Scperciva	buffer_put_string(&outgoing_packet, buf, len);
502148871Scperciva}
503148871Scperciva
504148871Scpercivavoid
505148871Scpercivapacket_put_cstring(const char *str)
506148871Scperciva{
507148871Scperciva	buffer_put_cstring(&outgoing_packet, str);
508148871Scperciva}
509148871Scperciva
510148871Scpercivavoid
511148871Scpercivapacket_put_raw(const void *buf, u_int len)
512148879Scperciva{
513148871Scperciva	buffer_append(&outgoing_packet, buf, len);
514148871Scperciva}
515148871Scperciva
516148871Scpercivavoid
517148871Scpercivapacket_put_bignum(BIGNUM * value)
518148871Scperciva{
519148871Scperciva	buffer_put_bignum(&outgoing_packet, value);
520148871Scperciva}
521148871Scperciva
522148871Scpercivavoid
523148871Scpercivapacket_put_bignum2(BIGNUM * value)
524148871Scperciva{
525148871Scperciva	buffer_put_bignum2(&outgoing_packet, value);
526148871Scperciva}
527148871Scperciva
528148871Scperciva/*
529148871Scperciva * Finalizes and sends the packet.  If the encryption key has been set,
530148871Scperciva * encrypts the packet before sending.
531148871Scperciva */
532148871Scperciva
533148871Scpercivastatic void
534148871Scpercivapacket_send1(void)
535148871Scperciva{
536148871Scperciva	u_char buf[8], *cp;
537148871Scperciva	int i, padding, len;
538148871Scperciva	u_int checksum;
539148871Scperciva	u_int32_t rnd = 0;
540148871Scperciva
541148871Scperciva	/*
542226312Sjilles	 * If using packet compression, compress the payload of the outgoing
543148871Scperciva	 * packet.
544226312Sjilles	 */
545148871Scperciva	if (packet_compression) {
546148871Scperciva		buffer_clear(&compression_buffer);
547148871Scperciva		/* Skip padding. */
548148871Scperciva		buffer_consume(&outgoing_packet, 8);
549148871Scperciva		/* padding */
550148871Scperciva		buffer_append(&compression_buffer, "\0\0\0\0\0\0\0\0", 8);
551148871Scperciva		buffer_compress(&outgoing_packet, &compression_buffer);
552148871Scperciva		buffer_clear(&outgoing_packet);
553148871Scperciva		buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
554148871Scperciva		    buffer_len(&compression_buffer));
555148871Scperciva	}
556148871Scperciva	/* Compute packet length without padding (add checksum, remove padding). */
557148871Scperciva	len = buffer_len(&outgoing_packet) + 4 - 8;
558148871Scperciva
559148871Scperciva	/* Insert padding. Initialized to zero in packet_start1() */
560148871Scperciva	padding = 8 - len % 8;
561148871Scperciva	if (!send_context.plaintext) {
562148871Scperciva		cp = buffer_ptr(&outgoing_packet);
563148871Scperciva		for (i = 0; i < padding; i++) {
564148871Scperciva			if (i % 4 == 0)
565148871Scperciva				rnd = arc4random();
566148871Scperciva			cp[7 - i] = rnd & 0xff;
567148871Scperciva			rnd >>= 8;
568148871Scperciva		}
569148871Scperciva	}
570148871Scperciva	buffer_consume(&outgoing_packet, 8 - padding);
571148871Scperciva
572148871Scperciva	/* Add check bytes. */
573148871Scperciva	checksum = ssh_crc32(buffer_ptr(&outgoing_packet),
574148871Scperciva	    buffer_len(&outgoing_packet));
575148871Scperciva	put_u32(buf, checksum);
576148871Scperciva	buffer_append(&outgoing_packet, buf, 4);
577148871Scperciva
578148871Scperciva#ifdef PACKET_DEBUG
579148871Scperciva	fprintf(stderr, "packet_send plain: ");
580148871Scperciva	buffer_dump(&outgoing_packet);
581148871Scperciva#endif
582148871Scperciva
583148871Scperciva	/* Append to output. */
584148871Scperciva	put_u32(buf, len);
585148871Scperciva	buffer_append(&output, buf, 4);
586148871Scperciva	cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
587148871Scperciva	cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
588148871Scperciva	    buffer_len(&outgoing_packet));
589148871Scperciva
590148871Scperciva#ifdef PACKET_DEBUG
591148871Scperciva	fprintf(stderr, "encrypted: ");
592149023Scperciva	buffer_dump(&output);
593148871Scperciva#endif
594148871Scperciva
595148871Scperciva	buffer_clear(&outgoing_packet);
596148871Scperciva
597148871Scperciva	/*
598148871Scperciva	 * Note that the packet is now only buffered in output.  It won't be
599148871Scperciva	 * actually sent until packet_write_wait or packet_write_poll is
600148871Scperciva	 * called.
601148871Scperciva	 */
602148871Scperciva}
603148871Scperciva
604148871Scpercivavoid
605148871Scpercivaset_newkeys(int mode)
606148871Scperciva{
607148871Scperciva	Enc *enc;
608148871Scperciva	Mac *mac;
609148871Scperciva	Comp *comp;
610148871Scperciva	CipherContext *cc;
611148871Scperciva	u_int64_t *max_blocks;
612226312Sjilles	int crypt_type;
613148871Scperciva
614148871Scperciva	debug2("set_newkeys: mode %d", mode);
615148871Scperciva
616148871Scperciva	if (mode == MODE_OUT) {
617148871Scperciva		cc = &send_context;
618148871Scperciva		crypt_type = CIPHER_ENCRYPT;
619148871Scperciva		p_send.packets = p_send.blocks = 0;
620148871Scperciva		max_blocks = &max_blocks_out;
621148871Scperciva	} else {
622158273Scperciva		cc = &receive_context;
623158273Scperciva		crypt_type = CIPHER_DECRYPT;
624158273Scperciva		p_read.packets = p_read.blocks = 0;
625148871Scperciva		max_blocks = &max_blocks_in;
626148871Scperciva	}
627148871Scperciva	if (newkeys[mode] != NULL) {
628148871Scperciva		debug("set_newkeys: rekeying");
629148871Scperciva		cipher_cleanup(cc);
630148871Scperciva		enc  = &newkeys[mode]->enc;
631148871Scperciva		mac  = &newkeys[mode]->mac;
632148871Scperciva		comp = &newkeys[mode]->comp;
633148871Scperciva		memset(mac->key, 0, mac->key_len);
634148871Scperciva		xfree(enc->name);
635154693Scperciva		xfree(enc->iv);
636148871Scperciva		xfree(enc->key);
637148871Scperciva		xfree(mac->name);
638216575Ssimon		xfree(mac->key);
639148871Scperciva		xfree(comp->name);
640148871Scperciva		xfree(newkeys[mode]);
641148871Scperciva	}
642148871Scperciva	newkeys[mode] = kex_get_newkeys(mode);
643148871Scperciva	if (newkeys[mode] == NULL)
644148871Scperciva		fatal("newkeys: no keys for mode %d", mode);
645148871Scperciva	enc  = &newkeys[mode]->enc;
646148871Scperciva	mac  = &newkeys[mode]->mac;
647148871Scperciva	comp = &newkeys[mode]->comp;
648148871Scperciva	if (mac->md != NULL)
649148871Scperciva		mac->enabled = 1;
650148871Scperciva	DBG(debug("cipher_init_context: %d", mode));
651148871Scperciva	cipher_init(cc, enc->cipher, enc->key, enc->key_len,
652148871Scperciva	    enc->iv, enc->block_size, crypt_type);
653148871Scperciva	/* Deleting the keys does not gain extra security */
654148871Scperciva	/* memset(enc->iv,  0, enc->block_size);
655148871Scperciva	   memset(enc->key, 0, enc->key_len); */
656148871Scperciva	if ((comp->type == COMP_ZLIB ||
657148871Scperciva	    (comp->type == COMP_DELAYED && after_authentication)) &&
658148871Scperciva	    comp->enabled == 0) {
659148871Scperciva		packet_init_compression();
660148871Scperciva		if (mode == MODE_OUT)
661148871Scperciva			buffer_compress_init_send(6);
662148871Scperciva		else
663148871Scperciva			buffer_compress_init_recv();
664148871Scperciva		comp->enabled = 1;
665148871Scperciva	}
666148871Scperciva	/*
667148871Scperciva	 * The 2^(blocksize*2) limit is too expensive for 3DES,
668148871Scperciva	 * blowfish, etc, so enforce a 1GB limit for small blocksizes.
669148871Scperciva	 */
670148871Scperciva	if (enc->block_size >= 16)
671148871Scperciva		*max_blocks = (u_int64_t)1 << (enc->block_size*2);
672158273Scperciva	else
673158273Scperciva		*max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
674158273Scperciva	if (rekey_limit)
675148871Scperciva		*max_blocks = MIN(*max_blocks, rekey_limit / enc->block_size);
676148871Scperciva}
677148871Scperciva
678148871Scperciva/*
679148871Scperciva * Delayed compression for SSH2 is enabled after authentication:
680148871Scperciva * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
681148871Scperciva * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
682148871Scperciva */
683148871Scpercivastatic void
684148871Scpercivapacket_enable_delayed_compress(void)
685148871Scperciva{
686148871Scperciva	Comp *comp = NULL;
687148871Scperciva	int mode;
688148871Scperciva
689148871Scperciva	/*
690148871Scperciva	 * Remember that we are past the authentication step, so rekeying
691148871Scperciva	 * with COMP_DELAYED will turn on compression immediately.
692148879Scperciva	 */
693148871Scperciva	after_authentication = 1;
694148871Scperciva	for (mode = 0; mode < MODE_MAX; mode++) {
695148871Scperciva		/* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
696148871Scperciva		if (newkeys[mode] == NULL)
697148871Scperciva			continue;
698148871Scperciva		comp = &newkeys[mode]->comp;
699148871Scperciva		if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
700148871Scperciva			packet_init_compression();
701148871Scperciva			if (mode == MODE_OUT)
702148871Scperciva				buffer_compress_init_send(6);
703148871Scperciva			else
704148871Scperciva				buffer_compress_init_recv();
705148871Scperciva			comp->enabled = 1;
706148871Scperciva		}
707148871Scperciva	}
708148871Scperciva}
709148871Scperciva
710148871Scperciva/*
711148871Scperciva * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
712148871Scperciva */
713148871Scpercivastatic void
714148871Scpercivapacket_send2_wrapped(void)
715148871Scperciva{
716148871Scperciva	u_char type, *cp, *macbuf = NULL;
717148871Scperciva	u_char padlen, pad;
718148871Scperciva	u_int packet_length = 0;
719148871Scperciva	u_int i, len;
720148871Scperciva	u_int32_t rnd = 0;
721148871Scperciva	Enc *enc   = NULL;
722148871Scperciva	Mac *mac   = NULL;
723148871Scperciva	Comp *comp = NULL;
724148871Scperciva	int block_size;
725148871Scperciva
726148879Scperciva	if (newkeys[MODE_OUT] != NULL) {
727148871Scperciva		enc  = &newkeys[MODE_OUT]->enc;
728148871Scperciva		mac  = &newkeys[MODE_OUT]->mac;
729148871Scperciva		comp = &newkeys[MODE_OUT]->comp;
730148871Scperciva	}
731148871Scperciva	block_size = enc ? enc->block_size : 8;
732148871Scperciva
733148871Scperciva	cp = buffer_ptr(&outgoing_packet);
734148871Scperciva	type = cp[5];
735148871Scperciva
736148871Scperciva#ifdef PACKET_DEBUG
737148871Scperciva	fprintf(stderr, "plain:     ");
738148871Scperciva	buffer_dump(&outgoing_packet);
739148871Scperciva#endif
740148871Scperciva
741148871Scperciva	if (comp && comp->enabled) {
742148871Scperciva		len = buffer_len(&outgoing_packet);
743148871Scperciva		/* skip header, compress only payload */
744149824Scperciva		buffer_consume(&outgoing_packet, 5);
745149824Scperciva		buffer_clear(&compression_buffer);
746149824Scperciva		buffer_compress(&outgoing_packet, &compression_buffer);
747149824Scperciva		buffer_clear(&outgoing_packet);
748149824Scperciva		buffer_append(&outgoing_packet, "\0\0\0\0\0", 5);
749149824Scperciva		buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
750149824Scperciva		    buffer_len(&compression_buffer));
751149824Scperciva		DBG(debug("compression: raw %d compressed %d", len,
752149824Scperciva		    buffer_len(&outgoing_packet)));
753149824Scperciva	}
754149824Scperciva
755149824Scperciva	/* sizeof (packet_len + pad_len + payload) */
756149824Scperciva	len = buffer_len(&outgoing_packet);
757149824Scperciva
758149824Scperciva	/*
759148871Scperciva	 * calc size of padding, alloc space, get random data,
760148871Scperciva	 * minimum padding is 4 bytes
761148871Scperciva	 */
762148871Scperciva	padlen = block_size - (len % block_size);
763148871Scperciva	if (padlen < 4)
764148871Scperciva		padlen += block_size;
765148871Scperciva	if (extra_pad) {
766148871Scperciva		/* will wrap if extra_pad+padlen > 255 */
767148879Scperciva		extra_pad  = roundup(extra_pad, block_size);
768148871Scperciva		pad = extra_pad - ((len + padlen) % extra_pad);
769148871Scperciva		debug3("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
770148871Scperciva		    pad, len, padlen, extra_pad);
771148871Scperciva		padlen += pad;
772148871Scperciva		extra_pad = 0;
773148871Scperciva	}
774148871Scperciva	cp = buffer_append_space(&outgoing_packet, padlen);
775148871Scperciva	if (enc && !send_context.plaintext) {
776148871Scperciva		/* random padding */
777148871Scperciva		for (i = 0; i < padlen; i++) {
778148871Scperciva			if (i % 4 == 0)
779148871Scperciva				rnd = arc4random();
780148871Scperciva			cp[i] = rnd & 0xff;
781148871Scperciva			rnd >>= 8;
782148871Scperciva		}
783148871Scperciva	} else {
784148871Scperciva		/* clear padding */
785148871Scperciva		memset(cp, 0, padlen);
786148871Scperciva	}
787148871Scperciva	/* packet_length includes payload, padding and padding length field */
788148871Scperciva	packet_length = buffer_len(&outgoing_packet) - 4;
789148871Scperciva	cp = buffer_ptr(&outgoing_packet);
790148871Scperciva	put_u32(cp, packet_length);
791148871Scperciva	cp[4] = padlen;
792148871Scperciva	DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen));
793148871Scperciva
794148871Scperciva	/* compute MAC over seqnr and packet(length fields, payload, padding) */
795148871Scperciva	if (mac && mac->enabled) {
796148871Scperciva		macbuf = mac_compute(mac, p_send.seqnr,
797148871Scperciva		    buffer_ptr(&outgoing_packet),
798148879Scperciva		    buffer_len(&outgoing_packet));
799148871Scperciva		DBG(debug("done calc MAC out #%d", p_send.seqnr));
800148871Scperciva	}
801148871Scperciva	/* encrypt packet and append to output buffer. */
802148871Scperciva	cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
803148871Scperciva	cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
804148871Scperciva	    buffer_len(&outgoing_packet));
805148871Scperciva	/* append unencrypted MAC */
806148871Scperciva	if (mac && mac->enabled)
807148871Scperciva		buffer_append(&output, macbuf, mac->mac_len);
808148871Scperciva#ifdef PACKET_DEBUG
809148871Scperciva	fprintf(stderr, "encrypted: ");
810148871Scperciva	buffer_dump(&output);
811148871Scperciva#endif
812253337Scperciva	/* increment sequence number for outgoing packets */
813253337Scperciva	if (++p_send.seqnr == 0)
814148871Scperciva		logit("outgoing seqnr wraps around");
815148871Scperciva	if (++p_send.packets == 0)
816148871Scperciva		if (!(datafellows & SSH_BUG_NOREKEY))
817148871Scperciva			fatal("XXX too many packets with same key");
818148871Scperciva	p_send.blocks += (packet_length + 4) / block_size;
819148871Scperciva	buffer_clear(&outgoing_packet);
820148871Scperciva
821148871Scperciva	if (type == SSH2_MSG_NEWKEYS)
822148871Scperciva		set_newkeys(MODE_OUT);
823148871Scperciva	else if (type == SSH2_MSG_USERAUTH_SUCCESS && server_side)
824148871Scperciva		packet_enable_delayed_compress();
825148871Scperciva}
826148871Scperciva
827158273Scpercivastatic void
828148871Scpercivapacket_send2(void)
829158273Scperciva{
830158273Scperciva	static int rekeying = 0;
831158273Scperciva	struct packet *p;
832148871Scperciva	u_char type, *cp;
833148871Scperciva
834148871Scperciva	cp = buffer_ptr(&outgoing_packet);
835148871Scperciva	type = cp[5];
836148871Scperciva
837148871Scperciva	/* during rekeying we can only send key exchange messages */
838148871Scperciva	if (rekeying) {
839148871Scperciva		if (!((type >= SSH2_MSG_TRANSPORT_MIN) &&
840148871Scperciva		    (type <= SSH2_MSG_TRANSPORT_MAX))) {
841179073Scperciva			debug("enqueue packet: %u", type);
842179073Scperciva			p = xmalloc(sizeof(*p));
843179073Scperciva			p->type = type;
844179073Scperciva			memcpy(&p->payload, &outgoing_packet, sizeof(Buffer));
845148871Scperciva			buffer_init(&outgoing_packet);
846158523Scperciva			TAILQ_INSERT_TAIL(&outgoing, p, next);
847158523Scperciva			return;
848158523Scperciva		}
849179073Scperciva	}
850148871Scperciva
851148871Scperciva	/* rekeying starts with sending KEXINIT */
852148871Scperciva	if (type == SSH2_MSG_KEXINIT)
853148871Scperciva		rekeying = 1;
854148871Scperciva
855179073Scperciva	packet_send2_wrapped();
856179073Scperciva
857179073Scperciva	/* after a NEWKEYS message we can send the complete queue */
858179073Scperciva	if (type == SSH2_MSG_NEWKEYS) {
859179073Scperciva		rekeying = 0;
860148871Scperciva		while ((p = TAILQ_FIRST(&outgoing))) {
861148871Scperciva			type = p->type;
862148871Scperciva			debug("dequeue packet: %u", type);
863149824Scperciva			buffer_free(&outgoing_packet);
864149824Scperciva			memcpy(&outgoing_packet, &p->payload,
865148871Scperciva			    sizeof(Buffer));
866149824Scperciva			TAILQ_REMOVE(&outgoing, p, next);
867149984Scperciva			xfree(p);
868149824Scperciva			packet_send2_wrapped();
869149824Scperciva		}
870149824Scperciva	}
871149824Scperciva}
872149824Scperciva
873149824Scpercivavoid
874149824Scpercivapacket_send(void)
875149824Scperciva{
876149824Scperciva	if (compat20)
877149824Scperciva		packet_send2();
878149824Scperciva	else
879148871Scperciva		packet_send1();
880148871Scperciva	DBG(debug("packet_send done"));
881148871Scperciva}
882148871Scperciva
883154088Scperciva/*
884154088Scperciva * Waits until a packet has been received, and returns its type.  Note that
885149824Scperciva * no other data is processed until this returns, so this function should not
886149824Scperciva * be used during the interactive session.
887149824Scperciva */
888149824Scperciva
889149824Scpercivaint
890149824Scpercivapacket_read_seqnr(u_int32_t *seqnr_p)
891149824Scperciva{
892159062Scperciva	int type, len;
893148871Scperciva	fd_set *setp;
894148871Scperciva	char buf[8192];
895148871Scperciva	DBG(debug("packet_read()"));
896148871Scperciva
897148871Scperciva	setp = (fd_set *)xcalloc(howmany(connection_in+1, NFDBITS),
898148871Scperciva	    sizeof(fd_mask));
899148871Scperciva
900159062Scperciva	/* Since we are blocking, ensure that all written packets have been sent. */
901148871Scperciva	packet_write_wait();
902216575Ssimon
903148871Scperciva	/* Stay in the loop until we have received a complete packet. */
904148871Scperciva	for (;;) {
905148871Scperciva		/* Try to read a packet from the buffer. */
906148871Scperciva		type = packet_read_poll_seqnr(seqnr_p);
907216575Ssimon		if (!compat20 && (
908148871Scperciva		    type == SSH_SMSG_SUCCESS
909148871Scperciva		    || type == SSH_SMSG_FAILURE
910148871Scperciva		    || type == SSH_CMSG_EOF
911149041Scperciva		    || type == SSH_CMSG_EXIT_CONFIRMATION))
912149041Scperciva			packet_check_eom();
913149041Scperciva		/* If we got a packet, return it. */
914148871Scperciva		if (type != SSH_MSG_NONE) {
915148871Scperciva			xfree(setp);
916148871Scperciva			return type;
917148871Scperciva		}
918148871Scperciva		/*
919148871Scperciva		 * Otherwise, wait for some data to arrive, add it to the
920148871Scperciva		 * buffer, and try again.
921148871Scperciva		 */
922148871Scperciva		memset(setp, 0, howmany(connection_in + 1, NFDBITS) *
923148871Scperciva		    sizeof(fd_mask));
924148871Scperciva		FD_SET(connection_in, setp);
925148871Scperciva
926148871Scperciva		/* Wait for some data to arrive. */
927148871Scperciva		while (select(connection_in + 1, setp, NULL, NULL, NULL) == -1 &&
928148871Scperciva		    (errno == EAGAIN || errno == EINTR))
929148981Scperciva			;
930149042Scperciva
931148958Scperciva		/* Read data from the socket. */
932148958Scperciva		len = read(connection_in, buf, sizeof(buf));
933148958Scperciva		if (len == 0) {
934148958Scperciva			logit("Connection closed by %.200s", get_remote_ipaddr());
935149824Scperciva			cleanup_exit(255);
936149824Scperciva		}
937148871Scperciva		if (len < 0)
938149824Scperciva			fatal("Read from socket failed: %.100s", strerror(errno));
939149824Scperciva		/* Append it to the buffer. */
940149824Scperciva		packet_process_incoming(buf, len);
941149824Scperciva	}
942158473Scperciva	/* NOTREACHED */
943158473Scperciva}
944149824Scperciva
945149824Scpercivaint
946149824Scpercivapacket_read(void)
947158473Scperciva{
948158473Scperciva	return packet_read_seqnr(NULL);
949149824Scperciva}
950148871Scperciva
951148871Scperciva/*
952148871Scperciva * Waits until a packet has been received, verifies that its type matches
953148871Scperciva * that given, and gives a fatal error and exits if there is a mismatch.
954149824Scperciva */
955149824Scperciva
956149824Scpercivavoid
957149824Scpercivapacket_read_expect(int expected_type)
958149824Scperciva{
959149824Scperciva	int type;
960149041Scperciva
961148871Scperciva	type = packet_read();
962148871Scperciva	if (type != expected_type)
963148871Scperciva		packet_disconnect("Protocol error: expected packet type %d, got %d",
964148871Scperciva		    expected_type, type);
965148871Scperciva}
966148871Scperciva
967148871Scperciva/* Checks if a full packet is available in the data received so far via
968148871Scperciva * packet_process_incoming.  If so, reads the packet; otherwise returns
969148871Scperciva * SSH_MSG_NONE.  This does not wait for data from the connection.
970148871Scperciva *
971148871Scperciva * SSH_MSG_DISCONNECT is handled specially here.  Also,
972216575Ssimon * SSH_MSG_IGNORE messages are skipped by this function and are never returned
973148871Scperciva * to higher levels.
974148871Scperciva */
975148871Scperciva
976216575Ssimonstatic int
977148871Scpercivapacket_read_poll1(void)
978148871Scperciva{
979148871Scperciva	u_int len, padded_len;
980149041Scperciva	u_char *cp, type;
981149041Scperciva	u_int checksum, stored_checksum;
982149041Scperciva
983148871Scperciva	/* Check if input size is less than minimum packet size. */
984148871Scperciva	if (buffer_len(&input) < 4 + 8)
985148871Scperciva		return SSH_MSG_NONE;
986148871Scperciva	/* Get length of incoming packet. */
987148871Scperciva	cp = buffer_ptr(&input);
988148871Scperciva	len = get_u32(cp);
989148871Scperciva	if (len < 1 + 2 + 2 || len > 256 * 1024)
990148871Scperciva		packet_disconnect("Bad packet length %u.", len);
991148871Scperciva	padded_len = (len + 8) & ~7;
992148871Scperciva
993148871Scperciva	/* Check if the packet has been entirely received. */
994148871Scperciva	if (buffer_len(&input) < 4 + padded_len)
995148871Scperciva		return SSH_MSG_NONE;
996148871Scperciva
997148871Scperciva	/* The entire packet is in buffer. */
998148871Scperciva
999148871Scperciva	/* Consume packet length. */
1000148871Scperciva	buffer_consume(&input, 4);
1001148871Scperciva
1002148871Scperciva	/*
1003148871Scperciva	 * Cryptographic attack detector for ssh
1004148871Scperciva	 * (C)1998 CORE-SDI, Buenos Aires Argentina
1005148871Scperciva	 * Ariel Futoransky(futo@core-sdi.com)
1006148871Scperciva	 */
1007148871Scperciva	if (!receive_context.plaintext) {
1008148871Scperciva		switch (detect_attack(buffer_ptr(&input), padded_len)) {
1009148871Scperciva		case DEATTACK_DETECTED:
1010148871Scperciva			packet_disconnect("crc32 compensation attack: "
1011148871Scperciva			    "network attack detected");
1012148871Scperciva		case DEATTACK_DOS_DETECTED:
1013148871Scperciva			packet_disconnect("deattack denial of "
1014148871Scperciva			    "service detected");
1015148871Scperciva		}
1016148871Scperciva	}
1017148871Scperciva
1018148871Scperciva	/* Decrypt data to incoming_packet. */
1019148871Scperciva	buffer_clear(&incoming_packet);
1020148871Scperciva	cp = buffer_append_space(&incoming_packet, padded_len);
1021148871Scperciva	cipher_crypt(&receive_context, cp, buffer_ptr(&input), padded_len);
1022148871Scperciva
1023148871Scperciva	buffer_consume(&input, padded_len);
1024148871Scperciva
1025148871Scperciva#ifdef PACKET_DEBUG
1026148871Scperciva	fprintf(stderr, "read_poll plain: ");
1027148871Scperciva	buffer_dump(&incoming_packet);
1028148871Scperciva#endif
1029148871Scperciva
1030148871Scperciva	/* Compute packet checksum. */
1031148871Scperciva	checksum = ssh_crc32(buffer_ptr(&incoming_packet),
1032148871Scperciva	    buffer_len(&incoming_packet) - 4);
1033148871Scperciva
1034148871Scperciva	/* Skip padding. */
1035148871Scperciva	buffer_consume(&incoming_packet, 8 - len % 8);
1036148871Scperciva
1037148871Scperciva	/* Test check bytes. */
1038148871Scperciva	if (len != buffer_len(&incoming_packet))
1039148871Scperciva		packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
1040148871Scperciva		    len, buffer_len(&incoming_packet));
1041148871Scperciva
1042148871Scperciva	cp = (u_char *)buffer_ptr(&incoming_packet) + len - 4;
1043148871Scperciva	stored_checksum = get_u32(cp);
1044148871Scperciva	if (checksum != stored_checksum)
1045148871Scperciva		packet_disconnect("Corrupted check bytes on input.");
1046201251Scperciva	buffer_consume_end(&incoming_packet, 4);
1047201251Scperciva
1048201251Scperciva	if (packet_compression) {
1049201251Scperciva		buffer_clear(&compression_buffer);
1050201251Scperciva		buffer_uncompress(&incoming_packet, &compression_buffer);
1051201251Scperciva		buffer_clear(&incoming_packet);
1052201251Scperciva		buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
1053201251Scperciva		    buffer_len(&compression_buffer));
1054201251Scperciva	}
1055201251Scperciva	type = buffer_get_char(&incoming_packet);
1056201251Scperciva	if (type < SSH_MSG_MIN || type > SSH_MSG_MAX)
1057201251Scperciva		packet_disconnect("Invalid ssh1 packet type: %d", type);
1058201251Scperciva	return type;
1059201251Scperciva}
1060201251Scperciva
1061201251Scpercivastatic int
1062148871Scpercivapacket_read_poll2(u_int32_t *seqnr_p)
1063148871Scperciva{
1064148871Scperciva	static u_int packet_length = 0;
1065148871Scperciva	u_int padlen, need;
1066148871Scperciva	u_char *macbuf, *cp, type;
1067163564Scperciva	u_int maclen, block_size;
1068163564Scperciva	Enc *enc   = NULL;
1069163564Scperciva	Mac *mac   = NULL;
1070148871Scperciva	Comp *comp = NULL;
1071149027Scperciva
1072149027Scperciva	if (newkeys[MODE_IN] != NULL) {
1073149027Scperciva		enc  = &newkeys[MODE_IN]->enc;
1074		mac  = &newkeys[MODE_IN]->mac;
1075		comp = &newkeys[MODE_IN]->comp;
1076	}
1077	maclen = mac && mac->enabled ? mac->mac_len : 0;
1078	block_size = enc ? enc->block_size : 8;
1079
1080	if (packet_length == 0) {
1081		/*
1082		 * check if input size is less than the cipher block size,
1083		 * decrypt first block and extract length of incoming packet
1084		 */
1085		if (buffer_len(&input) < block_size)
1086			return SSH_MSG_NONE;
1087		buffer_clear(&incoming_packet);
1088		cp = buffer_append_space(&incoming_packet, block_size);
1089		cipher_crypt(&receive_context, cp, buffer_ptr(&input),
1090		    block_size);
1091		cp = buffer_ptr(&incoming_packet);
1092		packet_length = get_u32(cp);
1093		if (packet_length < 1 + 4 || packet_length > 256 * 1024) {
1094#ifdef PACKET_DEBUG
1095			buffer_dump(&incoming_packet);
1096#endif
1097			packet_disconnect("Bad packet length %u.", packet_length);
1098		}
1099		DBG(debug("input: packet len %u", packet_length+4));
1100		buffer_consume(&input, block_size);
1101	}
1102	/* we have a partial packet of block_size bytes */
1103	need = 4 + packet_length - block_size;
1104	DBG(debug("partial packet %d, need %d, maclen %d", block_size,
1105	    need, maclen));
1106	if (need % block_size != 0)
1107		fatal("padding error: need %d block %d mod %d",
1108		    need, block_size, need % block_size);
1109	/*
1110	 * check if the entire packet has been received and
1111	 * decrypt into incoming_packet
1112	 */
1113	if (buffer_len(&input) < need + maclen)
1114		return SSH_MSG_NONE;
1115#ifdef PACKET_DEBUG
1116	fprintf(stderr, "read_poll enc/full: ");
1117	buffer_dump(&input);
1118#endif
1119	cp = buffer_append_space(&incoming_packet, need);
1120	cipher_crypt(&receive_context, cp, buffer_ptr(&input), need);
1121	buffer_consume(&input, need);
1122	/*
1123	 * compute MAC over seqnr and packet,
1124	 * increment sequence number for incoming packet
1125	 */
1126	if (mac && mac->enabled) {
1127		macbuf = mac_compute(mac, p_read.seqnr,
1128		    buffer_ptr(&incoming_packet),
1129		    buffer_len(&incoming_packet));
1130		if (memcmp(macbuf, buffer_ptr(&input), mac->mac_len) != 0)
1131			packet_disconnect("Corrupted MAC on input.");
1132		DBG(debug("MAC #%d ok", p_read.seqnr));
1133		buffer_consume(&input, mac->mac_len);
1134	}
1135	if (seqnr_p != NULL)
1136		*seqnr_p = p_read.seqnr;
1137	if (++p_read.seqnr == 0)
1138		logit("incoming seqnr wraps around");
1139	if (++p_read.packets == 0)
1140		if (!(datafellows & SSH_BUG_NOREKEY))
1141			fatal("XXX too many packets with same key");
1142	p_read.blocks += (packet_length + 4) / block_size;
1143
1144	/* get padlen */
1145	cp = buffer_ptr(&incoming_packet);
1146	padlen = cp[4];
1147	DBG(debug("input: padlen %d", padlen));
1148	if (padlen < 4)
1149		packet_disconnect("Corrupted padlen %d on input.", padlen);
1150
1151	/* skip packet size + padlen, discard padding */
1152	buffer_consume(&incoming_packet, 4 + 1);
1153	buffer_consume_end(&incoming_packet, padlen);
1154
1155	DBG(debug("input: len before de-compress %d", buffer_len(&incoming_packet)));
1156	if (comp && comp->enabled) {
1157		buffer_clear(&compression_buffer);
1158		buffer_uncompress(&incoming_packet, &compression_buffer);
1159		buffer_clear(&incoming_packet);
1160		buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
1161		    buffer_len(&compression_buffer));
1162		DBG(debug("input: len after de-compress %d",
1163		    buffer_len(&incoming_packet)));
1164	}
1165	/*
1166	 * get packet type, implies consume.
1167	 * return length of payload (without type field)
1168	 */
1169	type = buffer_get_char(&incoming_packet);
1170	if (type < SSH2_MSG_MIN || type >= SSH2_MSG_LOCAL_MIN)
1171		packet_disconnect("Invalid ssh2 packet type: %d", type);
1172	if (type == SSH2_MSG_NEWKEYS)
1173		set_newkeys(MODE_IN);
1174	else if (type == SSH2_MSG_USERAUTH_SUCCESS && !server_side)
1175		packet_enable_delayed_compress();
1176#ifdef PACKET_DEBUG
1177	fprintf(stderr, "read/plain[%d]:\r\n", type);
1178	buffer_dump(&incoming_packet);
1179#endif
1180	/* reset for next packet */
1181	packet_length = 0;
1182	return type;
1183}
1184
1185int
1186packet_read_poll_seqnr(u_int32_t *seqnr_p)
1187{
1188	u_int reason, seqnr;
1189	u_char type;
1190	char *msg;
1191
1192	for (;;) {
1193		if (compat20) {
1194			type = packet_read_poll2(seqnr_p);
1195			if (type)
1196				DBG(debug("received packet type %d", type));
1197			switch (type) {
1198			case SSH2_MSG_IGNORE:
1199				break;
1200			case SSH2_MSG_DEBUG:
1201				packet_get_char();
1202				msg = packet_get_string(NULL);
1203				debug("Remote: %.900s", msg);
1204				xfree(msg);
1205				msg = packet_get_string(NULL);
1206				xfree(msg);
1207				break;
1208			case SSH2_MSG_DISCONNECT:
1209				reason = packet_get_int();
1210				msg = packet_get_string(NULL);
1211				logit("Received disconnect from %s: %u: %.400s",
1212				    get_remote_ipaddr(), reason, msg);
1213				xfree(msg);
1214				cleanup_exit(255);
1215				break;
1216			case SSH2_MSG_UNIMPLEMENTED:
1217				seqnr = packet_get_int();
1218				debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1219				    seqnr);
1220				break;
1221			default:
1222				return type;
1223			}
1224		} else {
1225			type = packet_read_poll1();
1226			switch (type) {
1227			case SSH_MSG_IGNORE:
1228				break;
1229			case SSH_MSG_DEBUG:
1230				msg = packet_get_string(NULL);
1231				debug("Remote: %.900s", msg);
1232				xfree(msg);
1233				break;
1234			case SSH_MSG_DISCONNECT:
1235				msg = packet_get_string(NULL);
1236				logit("Received disconnect from %s: %.400s",
1237				    get_remote_ipaddr(), msg);
1238				cleanup_exit(255);
1239				xfree(msg);
1240				break;
1241			default:
1242				if (type)
1243					DBG(debug("received packet type %d", type));
1244				return type;
1245			}
1246		}
1247	}
1248}
1249
1250int
1251packet_read_poll(void)
1252{
1253	return packet_read_poll_seqnr(NULL);
1254}
1255
1256/*
1257 * Buffers the given amount of input characters.  This is intended to be used
1258 * together with packet_read_poll.
1259 */
1260
1261void
1262packet_process_incoming(const char *buf, u_int len)
1263{
1264	buffer_append(&input, buf, len);
1265}
1266
1267/* Returns a character from the packet. */
1268
1269u_int
1270packet_get_char(void)
1271{
1272	char ch;
1273
1274	buffer_get(&incoming_packet, &ch, 1);
1275	return (u_char) ch;
1276}
1277
1278/* Returns an integer from the packet data. */
1279
1280u_int
1281packet_get_int(void)
1282{
1283	return buffer_get_int(&incoming_packet);
1284}
1285
1286/*
1287 * Returns an arbitrary precision integer from the packet data.  The integer
1288 * must have been initialized before this call.
1289 */
1290
1291void
1292packet_get_bignum(BIGNUM * value)
1293{
1294	buffer_get_bignum(&incoming_packet, value);
1295}
1296
1297void
1298packet_get_bignum2(BIGNUM * value)
1299{
1300	buffer_get_bignum2(&incoming_packet, value);
1301}
1302
1303void *
1304packet_get_raw(u_int *length_ptr)
1305{
1306	u_int bytes = buffer_len(&incoming_packet);
1307
1308	if (length_ptr != NULL)
1309		*length_ptr = bytes;
1310	return buffer_ptr(&incoming_packet);
1311}
1312
1313int
1314packet_remaining(void)
1315{
1316	return buffer_len(&incoming_packet);
1317}
1318
1319/*
1320 * Returns a string from the packet data.  The string is allocated using
1321 * xmalloc; it is the responsibility of the calling program to free it when
1322 * no longer needed.  The length_ptr argument may be NULL, or point to an
1323 * integer into which the length of the string is stored.
1324 */
1325
1326void *
1327packet_get_string(u_int *length_ptr)
1328{
1329	return buffer_get_string(&incoming_packet, length_ptr);
1330}
1331
1332/*
1333 * Sends a diagnostic message from the server to the client.  This message
1334 * can be sent at any time (but not while constructing another message). The
1335 * message is printed immediately, but only if the client is being executed
1336 * in verbose mode.  These messages are primarily intended to ease debugging
1337 * authentication problems.   The length of the formatted message must not
1338 * exceed 1024 bytes.  This will automatically call packet_write_wait.
1339 */
1340
1341void
1342packet_send_debug(const char *fmt,...)
1343{
1344	char buf[1024];
1345	va_list args;
1346
1347	if (compat20 && (datafellows & SSH_BUG_DEBUG))
1348		return;
1349
1350	va_start(args, fmt);
1351	vsnprintf(buf, sizeof(buf), fmt, args);
1352	va_end(args);
1353
1354	if (compat20) {
1355		packet_start(SSH2_MSG_DEBUG);
1356		packet_put_char(0);	/* bool: always display */
1357		packet_put_cstring(buf);
1358		packet_put_cstring("");
1359	} else {
1360		packet_start(SSH_MSG_DEBUG);
1361		packet_put_cstring(buf);
1362	}
1363	packet_send();
1364	packet_write_wait();
1365}
1366
1367/*
1368 * Logs the error plus constructs and sends a disconnect packet, closes the
1369 * connection, and exits.  This function never returns. The error message
1370 * should not contain a newline.  The length of the formatted message must
1371 * not exceed 1024 bytes.
1372 */
1373
1374void
1375packet_disconnect(const char *fmt,...)
1376{
1377	char buf[1024];
1378	va_list args;
1379	static int disconnecting = 0;
1380
1381	if (disconnecting)	/* Guard against recursive invocations. */
1382		fatal("packet_disconnect called recursively.");
1383	disconnecting = 1;
1384
1385	/*
1386	 * Format the message.  Note that the caller must make sure the
1387	 * message is of limited size.
1388	 */
1389	va_start(args, fmt);
1390	vsnprintf(buf, sizeof(buf), fmt, args);
1391	va_end(args);
1392
1393	/* Display the error locally */
1394	logit("Disconnecting: %.100s", buf);
1395
1396	/* Send the disconnect message to the other side, and wait for it to get sent. */
1397	if (compat20) {
1398		packet_start(SSH2_MSG_DISCONNECT);
1399		packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1400		packet_put_cstring(buf);
1401		packet_put_cstring("");
1402	} else {
1403		packet_start(SSH_MSG_DISCONNECT);
1404		packet_put_cstring(buf);
1405	}
1406	packet_send();
1407	packet_write_wait();
1408
1409	/* Stop listening for connections. */
1410	channel_close_all();
1411
1412	/* Close the connection. */
1413	packet_close();
1414	cleanup_exit(255);
1415}
1416
1417/* Checks if there is any buffered output, and tries to write some of the output. */
1418
1419void
1420packet_write_poll(void)
1421{
1422	int len = buffer_len(&output);
1423
1424	if (len > 0) {
1425		len = write(connection_out, buffer_ptr(&output), len);
1426		if (len <= 0) {
1427			if (errno == EAGAIN)
1428				return;
1429			else
1430				fatal("Write failed: %.100s", strerror(errno));
1431		}
1432		buffer_consume(&output, len);
1433	}
1434}
1435
1436/*
1437 * Calls packet_write_poll repeatedly until all pending output data has been
1438 * written.
1439 */
1440
1441void
1442packet_write_wait(void)
1443{
1444	fd_set *setp;
1445
1446	setp = (fd_set *)xcalloc(howmany(connection_out + 1, NFDBITS),
1447	    sizeof(fd_mask));
1448	packet_write_poll();
1449	while (packet_have_data_to_write()) {
1450		memset(setp, 0, howmany(connection_out + 1, NFDBITS) *
1451		    sizeof(fd_mask));
1452		FD_SET(connection_out, setp);
1453		while (select(connection_out + 1, NULL, setp, NULL, NULL) == -1 &&
1454		    (errno == EAGAIN || errno == EINTR))
1455			;
1456		packet_write_poll();
1457	}
1458	xfree(setp);
1459}
1460
1461/* Returns true if there is buffered data to write to the connection. */
1462
1463int
1464packet_have_data_to_write(void)
1465{
1466	return buffer_len(&output) != 0;
1467}
1468
1469/* Returns true if there is not too much data to write to the connection. */
1470
1471int
1472packet_not_very_much_data_to_write(void)
1473{
1474	if (interactive_mode)
1475		return buffer_len(&output) < 16384;
1476	else
1477		return buffer_len(&output) < 128 * 1024;
1478}
1479
1480
1481static void
1482packet_set_tos(int interactive)
1483{
1484#if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1485	int tos = interactive ? IPTOS_LOWDELAY : IPTOS_THROUGHPUT;
1486
1487	if (!packet_connection_is_on_socket() ||
1488	    !packet_connection_is_ipv4())
1489		return;
1490	if (setsockopt(connection_in, IPPROTO_IP, IP_TOS, &tos,
1491	    sizeof(tos)) < 0)
1492		error("setsockopt IP_TOS %d: %.100s:",
1493		    tos, strerror(errno));
1494#endif
1495}
1496
1497/* Informs that the current session is interactive.  Sets IP flags for that. */
1498
1499void
1500packet_set_interactive(int interactive)
1501{
1502	static int called = 0;
1503
1504	if (called)
1505		return;
1506	called = 1;
1507
1508	/* Record that we are in interactive mode. */
1509	interactive_mode = interactive;
1510
1511	/* Only set socket options if using a socket.  */
1512	if (!packet_connection_is_on_socket())
1513		return;
1514	set_nodelay(connection_in);
1515	packet_set_tos(interactive);
1516}
1517
1518/* Returns true if the current connection is interactive. */
1519
1520int
1521packet_is_interactive(void)
1522{
1523	return interactive_mode;
1524}
1525
1526int
1527packet_set_maxsize(u_int s)
1528{
1529	static int called = 0;
1530
1531	if (called) {
1532		logit("packet_set_maxsize: called twice: old %d new %d",
1533		    max_packet_size, s);
1534		return -1;
1535	}
1536	if (s < 4 * 1024 || s > 1024 * 1024) {
1537		logit("packet_set_maxsize: bad size %d", s);
1538		return -1;
1539	}
1540	called = 1;
1541	debug("packet_set_maxsize: setting to %d", s);
1542	max_packet_size = s;
1543	return s;
1544}
1545
1546/* roundup current message to pad bytes */
1547void
1548packet_add_padding(u_char pad)
1549{
1550	extra_pad = pad;
1551}
1552
1553/*
1554 * 9.2.  Ignored Data Message
1555 *
1556 *   byte      SSH_MSG_IGNORE
1557 *   string    data
1558 *
1559 * All implementations MUST understand (and ignore) this message at any
1560 * time (after receiving the protocol version). No implementation is
1561 * required to send them. This message can be used as an additional
1562 * protection measure against advanced traffic analysis techniques.
1563 */
1564void
1565packet_send_ignore(int nbytes)
1566{
1567	u_int32_t rnd = 0;
1568	int i;
1569
1570	packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1571	packet_put_int(nbytes);
1572	for (i = 0; i < nbytes; i++) {
1573		if (i % 4 == 0)
1574			rnd = arc4random();
1575		packet_put_char((u_char)rnd & 0xff);
1576		rnd >>= 8;
1577	}
1578}
1579
1580#define MAX_PACKETS	(1U<<31)
1581int
1582packet_need_rekeying(void)
1583{
1584	if (datafellows & SSH_BUG_NOREKEY)
1585		return 0;
1586	return
1587	    (p_send.packets > MAX_PACKETS) ||
1588	    (p_read.packets > MAX_PACKETS) ||
1589	    (max_blocks_out && (p_send.blocks > max_blocks_out)) ||
1590	    (max_blocks_in  && (p_read.blocks > max_blocks_in));
1591}
1592
1593void
1594packet_set_rekey_limit(u_int32_t bytes)
1595{
1596	rekey_limit = bytes;
1597}
1598
1599void
1600packet_set_server(void)
1601{
1602	server_side = 1;
1603}
1604
1605void
1606packet_set_authenticated(void)
1607{
1608	after_authentication = 1;
1609}
1610