1 /* $OpenBSD: packet.c,v 1.166 2009/06/27 09:29:06 andreas Exp $ */
2 /*
3  * Author: Tatu Ylonen <ylo@cs.hut.fi>
4  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5  *                    All rights reserved
6  * This file contains code implementing the packet protocol and communication
7  * with the other side.  This same code is used both on client and server side.
8  *
9  * As far as I am concerned, the code I have written for this software
10  * can be used freely for any purpose.  Any derived versions of this
11  * software must be clearly marked as such, and if the derived work is
12  * incompatible with the protocol description in the RFC file, it must be
13  * called by a name other than "ssh" or "Secure Shell".
14  *
15  *
16  * SSH2 packet format added by Markus Friedl.
17  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
18  *
19  * Redistribution and use in source and binary forms, with or without
20  * modification, are permitted provided that the following conditions
21  * are met:
22  * 1. Redistributions of source code must retain the above copyright
23  *    notice, this list of conditions and the following disclaimer.
24  * 2. Redistributions in binary form must reproduce the above copyright
25  *    notice, this list of conditions and the following disclaimer in the
26  *    documentation and/or other materials provided with the distribution.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
29  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
30  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
31  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
32  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
33  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
34  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
35  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
36  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
37  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38  */
39 
40 #include <sys/param.h>
41 #include <sys/queue.h>
42 #include <sys/socket.h>
43 #include <sys/time.h>
44 
45 #include <netinet/in_systm.h>
46 #include <netinet/in.h>
47 #include <netinet/ip.h>
48 
49 #include <errno.h>
50 #include <stdarg.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <unistd.h>
55 #include <signal.h>
56 
57 #include "xmalloc.h"
58 #include "buffer.h"
59 #include "packet.h"
60 #include "crc32.h"
61 #include "compress.h"
62 #include "deattack.h"
63 #include "channels.h"
64 #include "compat.h"
65 #include "ssh1.h"
66 #include "ssh2.h"
67 #include "cipher.h"
68 #include "key.h"
69 #include "kex.h"
70 #include "mac.h"
71 #include "log.h"
72 #include "canohost.h"
73 #include "misc.h"
74 #include "ssh.h"
75 #include "roaming.h"
76 
77 __RCSID("$MirOS: src/usr.bin/ssh/packet.c,v 1.17 2010/09/21 21:24:37 tg Exp $");
78 
79 const char NULs[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
80 
81 #ifdef PACKET_DEBUG
82 #define DBG(x) x
83 #else
84 #define DBG(x)
85 #endif
86 
87 #define PACKET_MAX_SIZE (256 * 1024)
88 
89 struct packet_state {
90 	u_int32_t seqnr;
91 	u_int32_t packets;
92 	u_int64_t blocks;
93 	u_int64_t bytes;
94 };
95 
96 struct packet {
97 	TAILQ_ENTRY(packet) next;
98 	u_char type;
99 	Buffer payload;
100 };
101 
102 struct session_state {
103 	/*
104 	 * This variable contains the file descriptors used for
105 	 * communicating with the other side.  connection_in is used for
106 	 * reading; connection_out for writing.  These can be the same
107 	 * descriptor, in which case it is assumed to be a socket.
108 	 */
109 	int connection_in;
110 	int connection_out;
111 
112 	/* Protocol flags for the remote side. */
113 	u_int remote_protocol_flags;
114 
115 	/* Encryption context for receiving data.  Only used for decryption. */
116 	CipherContext receive_context;
117 
118 	/* Encryption context for sending data.  Only used for encryption. */
119 	CipherContext send_context;
120 
121 	/* Buffer for raw input data from the socket. */
122 	Buffer input;
123 
124 	/* Buffer for raw output data going to the socket. */
125 	Buffer output;
126 
127 	/* Buffer for the partial outgoing packet being constructed. */
128 	Buffer outgoing_packet;
129 
130 	/* Buffer for the incoming packet currently being processed. */
131 	Buffer incoming_packet;
132 
133 	/* Scratch buffer for packet compression/decompression. */
134 	Buffer compression_buffer;
135 	int compression_buffer_ready;
136 
137 	/*
138 	 * Flag indicating whether packet compression/decompression is
139 	 * enabled.
140 	 */
141 	int packet_compression;
142 
143 	/* default maximum packet size */
144 	u_int max_packet_size;
145 
146 	/* Flag indicating whether this module has been initialized. */
147 	int initialized;
148 
149 	/* Set to true if the connection is interactive. */
150 	int interactive_mode;
151 
152 	/* Set to true if we are the server side. */
153 	int server_side;
154 
155 	/* Set to true if we are authenticated. */
156 	int after_authentication;
157 
158 	int keep_alive_timeouts;
159 
160 	/* The maximum time that we will wait to send or receive a packet */
161 	int packet_timeout_ms;
162 
163 	/* Session key information for Encryption and MAC */
164 	Newkeys *newkeys[MODE_MAX];
165 	struct packet_state p_read, p_send;
166 
167 	u_int64_t max_blocks_in, max_blocks_out;
168 	u_int32_t rekey_limit;
169 
170 	/* Session key for protocol v1 */
171 	u_char ssh1_key[SSH_SESSION_KEY_LENGTH];
172 	u_int ssh1_keylen;
173 
174 	/* roundup current message to extra_pad bytes */
175 	u_char extra_pad;
176 
177 	/* XXX discard incoming data after MAC error */
178 	u_int packet_discard;
179 	Mac *packet_discard_mac;
180 
181 	/* Used in packet_read_poll2() */
182 	u_int packlen;
183 
184 	/* Used in packet_send2 */
185 	int rekeying;
186 
187 	/* Used in packet_set_interactive */
188 	int set_interactive_called;
189 
190 	/* Used in packet_set_maxsize */
191 	int set_maxsize_called;
192 
193 	TAILQ_HEAD(, packet) outgoing;
194 };
195 
196 static struct session_state *active_state, *backup_state;
197 
198 static struct session_state *
alloc_session_state(void)199 alloc_session_state(void)
200 {
201     struct session_state *s = xcalloc(1, sizeof(*s));
202 
203     s->connection_in = -1;
204     s->connection_out = -1;
205     s->max_packet_size = 32768;
206     s->packet_timeout_ms = -1;
207     return s;
208 }
209 
210 static __dead void packet_stop_discard(void);
211 
212 /* MirOS extension */
213 static void packet_consume_ignoremsg(void);
214 
215 /*
216  * Sets the descriptors used for communication.  Disables encryption until
217  * packet_set_encryption_key is called.
218  */
219 void
packet_set_connection(int fd_in,int fd_out)220 packet_set_connection(int fd_in, int fd_out)
221 {
222 	Cipher *none = cipher_by_name("none");
223 
224 	if (none == NULL)
225 		fatal("packet_set_connection: cannot load cipher 'none'");
226 	if (active_state == NULL)
227 		active_state = alloc_session_state();
228 	active_state->connection_in = fd_in;
229 	active_state->connection_out = fd_out;
230 	cipher_init(&active_state->send_context, none, (const u_char *)&fd_in,
231 	    sizeof(fd_in), NULL, 0, CIPHER_ENCRYPT);
232 	cipher_init(&active_state->receive_context, none, (const u_char *)&fd_out,
233 	    sizeof(fd_out), NULL, 0, CIPHER_DECRYPT);
234 	active_state->newkeys[MODE_IN] = active_state->newkeys[MODE_OUT] = NULL;
235 	if (!active_state->initialized) {
236 		active_state->initialized = 1;
237 		buffer_init(&active_state->input);
238 		buffer_init(&active_state->output);
239 		buffer_init(&active_state->outgoing_packet);
240 		buffer_init(&active_state->incoming_packet);
241 		TAILQ_INIT(&active_state->outgoing);
242 		active_state->p_send.packets = active_state->p_read.packets = 0;
243 	}
244 }
245 
246 void
packet_set_timeout(int timeout,int count)247 packet_set_timeout(int timeout, int count)
248 {
249 	if (timeout == 0 || count == 0) {
250 		active_state->packet_timeout_ms = -1;
251 		return;
252 	}
253 	if ((INT_MAX / 1000) / count < timeout)
254 		active_state->packet_timeout_ms = INT_MAX;
255 	else
256 		active_state->packet_timeout_ms = timeout * count * 1000;
257 }
258 
259 static void
packet_stop_discard(void)260 packet_stop_discard(void)
261 {
262 	if (active_state->packet_discard_mac) {
263 		char buf[1024];
264 
265 		memset(buf, 'a', sizeof(buf));
266 		while (buffer_len(&active_state->incoming_packet) <
267 		    PACKET_MAX_SIZE)
268 			buffer_append(&active_state->incoming_packet, buf,
269 			    sizeof(buf));
270 		(void) mac_compute(active_state->packet_discard_mac,
271 		    active_state->p_read.seqnr,
272 		    buffer_ptr(&active_state->incoming_packet),
273 		    PACKET_MAX_SIZE);
274 	}
275 	logit("Finished discarding for %.200s", get_remote_ipaddr());
276 	cleanup_exit(255);
277 }
278 
279 static void
packet_start_discard(Enc * enc,Mac * mac,u_int packet_length,u_int discard)280 packet_start_discard(Enc *enc, Mac *mac, u_int packet_length, u_int discard)
281 {
282 	if (enc == NULL || !cipher_is_cbc(enc->cipher))
283 		packet_disconnect("Packet corrupt");
284 	if (packet_length != PACKET_MAX_SIZE && mac && mac->enabled)
285 		active_state->packet_discard_mac = mac;
286 	if (buffer_len(&active_state->input) >= discard)
287 		packet_stop_discard();
288 	active_state->packet_discard = discard -
289 	    buffer_len(&active_state->input);
290 }
291 
292 /* Returns 1 if remote host is connected via socket, 0 if not. */
293 
294 int
packet_connection_is_on_socket(void)295 packet_connection_is_on_socket(void)
296 {
297 	struct sockaddr_storage from, to;
298 	socklen_t fromlen, tolen;
299 
300 	/* filedescriptors in and out are the same, so it's a socket */
301 	if (active_state->connection_in == active_state->connection_out)
302 		return 1;
303 	fromlen = sizeof(from);
304 	memset(&from, 0, sizeof(from));
305 	if (getpeername(active_state->connection_in, (struct sockaddr *)&from,
306 	    &fromlen) < 0)
307 		return 0;
308 	tolen = sizeof(to);
309 	memset(&to, 0, sizeof(to));
310 	if (getpeername(active_state->connection_out, (struct sockaddr *)&to,
311 	    &tolen) < 0)
312 		return 0;
313 	if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
314 		return 0;
315 	if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
316 		return 0;
317 	return 1;
318 }
319 
320 /*
321  * Exports an IV from the CipherContext required to export the key
322  * state back from the unprivileged child to the privileged parent
323  * process.
324  */
325 
326 void
packet_get_keyiv(int mode,u_char * iv,u_int len)327 packet_get_keyiv(int mode, u_char *iv, u_int len)
328 {
329 	CipherContext *cc;
330 
331 	if (mode == MODE_OUT)
332 		cc = &active_state->send_context;
333 	else
334 		cc = &active_state->receive_context;
335 
336 	cipher_get_keyiv(cc, iv, len);
337 }
338 
339 int
packet_get_keycontext(int mode,u_char * dat)340 packet_get_keycontext(int mode, u_char *dat)
341 {
342 	CipherContext *cc;
343 
344 	if (mode == MODE_OUT)
345 		cc = &active_state->send_context;
346 	else
347 		cc = &active_state->receive_context;
348 
349 	return (cipher_get_keycontext(cc, dat));
350 }
351 
352 void
packet_set_keycontext(int mode,u_char * dat)353 packet_set_keycontext(int mode, u_char *dat)
354 {
355 	CipherContext *cc;
356 
357 	if (mode == MODE_OUT)
358 		cc = &active_state->send_context;
359 	else
360 		cc = &active_state->receive_context;
361 
362 	cipher_set_keycontext(cc, dat);
363 }
364 
365 int
packet_get_keyiv_len(int mode)366 packet_get_keyiv_len(int mode)
367 {
368 	CipherContext *cc;
369 
370 	if (mode == MODE_OUT)
371 		cc = &active_state->send_context;
372 	else
373 		cc = &active_state->receive_context;
374 
375 	return (cipher_get_keyiv_len(cc));
376 }
377 
378 void
packet_set_iv(int mode,u_char * dat)379 packet_set_iv(int mode, u_char *dat)
380 {
381 	CipherContext *cc;
382 
383 	if (mode == MODE_OUT)
384 		cc = &active_state->send_context;
385 	else
386 		cc = &active_state->receive_context;
387 
388 	cipher_set_keyiv(cc, dat);
389 }
390 
391 int
packet_get_ssh1_cipher(void)392 packet_get_ssh1_cipher(void)
393 {
394 	return (cipher_get_number(active_state->receive_context.cipher));
395 }
396 
397 void
packet_get_state(int mode,u_int32_t * seqnr,u_int64_t * blocks,u_int32_t * packets,u_int64_t * bytes)398 packet_get_state(int mode, u_int32_t *seqnr, u_int64_t *blocks, u_int32_t *packets,
399     u_int64_t *bytes)
400 {
401 	struct packet_state *state;
402 
403 	state = (mode == MODE_IN) ?
404 	    &active_state->p_read : &active_state->p_send;
405 	if (seqnr)
406 		*seqnr = state->seqnr;
407 	if (blocks)
408 		*blocks = state->blocks;
409 	if (packets)
410 		*packets = state->packets;
411 	if (bytes)
412 		*bytes = state->bytes;
413 }
414 
415 void
packet_set_state(int mode,u_int32_t seqnr,u_int64_t blocks,u_int32_t packets,u_int64_t bytes)416 packet_set_state(int mode, u_int32_t seqnr, u_int64_t blocks, u_int32_t packets,
417     u_int64_t bytes)
418 {
419 	struct packet_state *state;
420 
421 	state = (mode == MODE_IN) ?
422 	    &active_state->p_read : &active_state->p_send;
423 	state->seqnr = seqnr;
424 	state->blocks = blocks;
425 	state->packets = packets;
426 	state->bytes = bytes;
427 }
428 
429 /* returns 1 if connection is via ipv4 */
430 
431 int
packet_connection_is_ipv4(void)432 packet_connection_is_ipv4(void)
433 {
434 	struct sockaddr_storage to;
435 	socklen_t tolen = sizeof(to);
436 
437 	memset(&to, 0, sizeof(to));
438 	if (getsockname(active_state->connection_out, (struct sockaddr *)&to,
439 	    &tolen) < 0)
440 		return 0;
441 	if (to.ss_family != AF_INET)
442 		return 0;
443 	return 1;
444 }
445 
446 /* Sets the connection into non-blocking mode. */
447 
448 void
packet_set_nonblocking(void)449 packet_set_nonblocking(void)
450 {
451 	/* Set the socket into non-blocking mode. */
452 	set_nonblock(active_state->connection_in);
453 
454 	if (active_state->connection_out != active_state->connection_in)
455 		set_nonblock(active_state->connection_out);
456 }
457 
458 /* Returns the socket used for reading. */
459 
460 int
packet_get_connection_in(void)461 packet_get_connection_in(void)
462 {
463 	return active_state->connection_in;
464 }
465 
466 /* Returns the descriptor used for writing. */
467 
468 int
packet_get_connection_out(void)469 packet_get_connection_out(void)
470 {
471 	return active_state->connection_out;
472 }
473 
474 /* Closes the connection and clears and frees internal data structures. */
475 
476 void
packet_close(void)477 packet_close(void)
478 {
479 	if (!active_state->initialized)
480 		return;
481 	active_state->initialized = 0;
482 	if (active_state->connection_in == active_state->connection_out) {
483 		shutdown(active_state->connection_out, SHUT_RDWR);
484 		close(active_state->connection_out);
485 	} else {
486 		close(active_state->connection_in);
487 		close(active_state->connection_out);
488 	}
489 	buffer_free(&active_state->input);
490 	buffer_free(&active_state->output);
491 	buffer_free(&active_state->outgoing_packet);
492 	buffer_free(&active_state->incoming_packet);
493 	if (active_state->compression_buffer_ready) {
494 		buffer_free(&active_state->compression_buffer);
495 		buffer_compress_uninit();
496 	}
497 	cipher_cleanup(&active_state->send_context);
498 	cipher_cleanup(&active_state->receive_context);
499 }
500 
501 /* Sets remote side protocol flags. */
502 
503 void
packet_set_protocol_flags(u_int protocol_flags)504 packet_set_protocol_flags(u_int protocol_flags)
505 {
506 	active_state->remote_protocol_flags = protocol_flags;
507 }
508 
509 /* Returns the remote protocol flags set earlier by the above function. */
510 
511 u_int
packet_get_protocol_flags(void)512 packet_get_protocol_flags(void)
513 {
514 	return active_state->remote_protocol_flags;
515 }
516 
517 /*
518  * Starts packet compression from the next packet on in both directions.
519  * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
520  */
521 
522 static void
packet_init_compression(void)523 packet_init_compression(void)
524 {
525 	if (active_state->compression_buffer_ready == 1)
526 		return;
527 	active_state->compression_buffer_ready = 1;
528 	buffer_init(&active_state->compression_buffer);
529 }
530 
531 void
packet_start_compression(int level)532 packet_start_compression(int level)
533 {
534 	if (active_state->packet_compression && !compat20)
535 		fatal("Compression already enabled.");
536 	active_state->packet_compression = 1;
537 	packet_init_compression();
538 	buffer_compress_init_send(level);
539 	buffer_compress_init_recv();
540 }
541 
542 /*
543  * Causes any further packets to be encrypted using the given key.  The same
544  * key is used for both sending and reception.  However, both directions are
545  * encrypted independently of each other.
546  */
547 
548 void
packet_set_encryption_key(const u_char * key,u_int keylen,int number)549 packet_set_encryption_key(const u_char *key, u_int keylen,
550     int number)
551 {
552 	Cipher *cipher = cipher_by_number(number);
553 
554 	if (cipher == NULL)
555 		fatal("packet_set_encryption_key: unknown cipher number %d", number);
556 	if (keylen < 20)
557 		fatal("packet_set_encryption_key: keylen too small: %d", keylen);
558 	if (keylen > SSH_SESSION_KEY_LENGTH)
559 		fatal("packet_set_encryption_key: keylen too big: %d", keylen);
560 	memcpy(active_state->ssh1_key, key, keylen);
561 	active_state->ssh1_keylen = keylen;
562 	cipher_init(&active_state->send_context, cipher, key, keylen, NULL,
563 	    0, CIPHER_ENCRYPT);
564 	cipher_init(&active_state->receive_context, cipher, key, keylen, NULL,
565 	    0, CIPHER_DECRYPT);
566 }
567 
568 u_int
packet_get_encryption_key(u_char * key)569 packet_get_encryption_key(u_char *key)
570 {
571 	if (key == NULL)
572 		return (active_state->ssh1_keylen);
573 	memcpy(key, active_state->ssh1_key, active_state->ssh1_keylen);
574 	return (active_state->ssh1_keylen);
575 }
576 
577 /* Start constructing a packet to send. */
578 void
packet_start(u_char type)579 packet_start(u_char type)
580 {
581 	u_char buf[9];
582 	int len;
583 
584 	DBG(debug("packet_start[%d]", type));
585 	len = compat20 ? 6 : 9;
586 	memset(buf, 0, len - 1);
587 	buf[len - 1] = type;
588 	buffer_clear(&active_state->outgoing_packet);
589 	buffer_append(&active_state->outgoing_packet, buf, len);
590 }
591 
592 /* Append payload. */
593 void
packet_put_char(int value)594 packet_put_char(int value)
595 {
596 	char ch = value;
597 
598 	buffer_append(&active_state->outgoing_packet, &ch, 1);
599 }
600 
601 void
packet_put_int(u_int value)602 packet_put_int(u_int value)
603 {
604 	buffer_put_int(&active_state->outgoing_packet, value);
605 }
606 
607 void
packet_put_int64(u_int64_t value)608 packet_put_int64(u_int64_t value)
609 {
610 	buffer_put_int64(&active_state->outgoing_packet, value);
611 }
612 
613 void
packet_put_string(const void * buf,u_int len)614 packet_put_string(const void *buf, u_int len)
615 {
616 	buffer_put_string(&active_state->outgoing_packet, buf, len);
617 }
618 
619 void
packet_put_cstring(const char * str)620 packet_put_cstring(const char *str)
621 {
622 	buffer_put_cstring(&active_state->outgoing_packet, str);
623 }
624 
625 void
packet_put_raw(const void * buf,u_int len)626 packet_put_raw(const void *buf, u_int len)
627 {
628 	buffer_append(&active_state->outgoing_packet, buf, len);
629 }
630 
631 void
packet_put_bignum(BIGNUM * value)632 packet_put_bignum(BIGNUM * value)
633 {
634 	buffer_put_bignum(&active_state->outgoing_packet, value);
635 }
636 
637 void
packet_put_bignum2(BIGNUM * value)638 packet_put_bignum2(BIGNUM * value)
639 {
640 	buffer_put_bignum2(&active_state->outgoing_packet, value);
641 }
642 
643 /*
644  * Finalizes and sends the packet.  If the encryption key has been set,
645  * encrypts the packet before sending.
646  */
647 
648 static void
packet_send1(void)649 packet_send1(void)
650 {
651 	u_char buf[8], *cp;
652 	int i, padding, len;
653 	u_int checksum;
654 	u_int32_t rnd = 0;
655 
656 	/*
657 	 * If using packet compression, compress the payload of the outgoing
658 	 * packet.
659 	 */
660 	if (active_state->packet_compression) {
661 		buffer_clear(&active_state->compression_buffer);
662 		/* Skip padding. */
663 		buffer_consume(&active_state->outgoing_packet, 8);
664 		/* padding */
665 		buffer_append(&active_state->compression_buffer,
666 		    NULs, 8);
667 		buffer_compress(&active_state->outgoing_packet,
668 		    &active_state->compression_buffer);
669 		buffer_clear(&active_state->outgoing_packet);
670 		buffer_append(&active_state->outgoing_packet,
671 		    buffer_ptr(&active_state->compression_buffer),
672 		    buffer_len(&active_state->compression_buffer));
673 	}
674 	/* Compute packet length without padding (add checksum, remove padding). */
675 	len = buffer_len(&active_state->outgoing_packet) + 4 - 8;
676 
677 	/* Insert padding. Initialized to zero in packet_start1() */
678 	padding = 8 - len % 8;
679 	if (!active_state->send_context.plaintext) {
680 		cp = buffer_ptr(&active_state->outgoing_packet);
681 		for (i = 0; i < padding; i++) {
682 			if (i % 4 == 0)
683 				rnd = arc4random();
684 			cp[7 - i] = rnd & 0xff;
685 			rnd >>= 8;
686 		}
687 	}
688 	buffer_consume(&active_state->outgoing_packet, 8 - padding);
689 
690 	/* Add check bytes. */
691 	checksum = ssh_crc32(buffer_ptr(&active_state->outgoing_packet),
692 	    buffer_len(&active_state->outgoing_packet));
693 	put_u32(buf, checksum);
694 	buffer_append(&active_state->outgoing_packet, buf, 4);
695 
696 #ifdef PACKET_DEBUG
697 	fprintf(stderr, "packet_send plain: ");
698 	buffer_dump(&active_state->outgoing_packet);
699 #endif
700 
701 	/* Append to output. */
702 	put_u32(buf, len);
703 	buffer_append(&active_state->output, buf, 4);
704 	cp = buffer_append_space(&active_state->output,
705 	    buffer_len(&active_state->outgoing_packet));
706 	cipher_crypt(&active_state->send_context, cp,
707 	    buffer_ptr(&active_state->outgoing_packet),
708 	    buffer_len(&active_state->outgoing_packet));
709 
710 #ifdef PACKET_DEBUG
711 	fprintf(stderr, "encrypted: ");
712 	buffer_dump(&active_state->output);
713 #endif
714 	active_state->p_send.packets++;
715 	active_state->p_send.bytes += len +
716 	    buffer_len(&active_state->outgoing_packet);
717 	buffer_clear(&active_state->outgoing_packet);
718 
719 	/*
720 	 * Note that the packet is now only buffered in output.  It won't be
721 	 * actually sent until packet_write_wait or packet_write_poll is
722 	 * called.
723 	 */
724 }
725 
726 void
set_newkeys(int mode)727 set_newkeys(int mode)
728 {
729 	Enc *enc;
730 	Mac *mac;
731 	Comp *comp;
732 	CipherContext *cc;
733 	u_int64_t *max_blocks;
734 	int crypt_type;
735 
736 	debug2("set_newkeys: mode %d", mode);
737 
738 	if (mode == MODE_OUT) {
739 		cc = &active_state->send_context;
740 		crypt_type = CIPHER_ENCRYPT;
741 		active_state->p_send.packets = active_state->p_send.blocks = 0;
742 		max_blocks = &active_state->max_blocks_out;
743 	} else {
744 		cc = &active_state->receive_context;
745 		crypt_type = CIPHER_DECRYPT;
746 		active_state->p_read.packets = active_state->p_read.blocks = 0;
747 		max_blocks = &active_state->max_blocks_in;
748 	}
749 	if (active_state->newkeys[mode] != NULL) {
750 		debug("set_newkeys: rekeying");
751 		cipher_cleanup(cc);
752 		enc  = &active_state->newkeys[mode]->enc;
753 		mac  = &active_state->newkeys[mode]->mac;
754 		comp = &active_state->newkeys[mode]->comp;
755 		mac_clear(mac);
756 		xfree(enc->name);
757 		xfree(enc->iv);
758 		xfree(enc->key);
759 		xfree(mac->name);
760 		xfree(mac->key);
761 		xfree(comp->name);
762 		xfree(active_state->newkeys[mode]);
763 	}
764 	active_state->newkeys[mode] = kex_get_newkeys(mode);
765 	if (active_state->newkeys[mode] == NULL)
766 		fatal("newkeys: no keys for mode %d", mode);
767 	enc  = &active_state->newkeys[mode]->enc;
768 	mac  = &active_state->newkeys[mode]->mac;
769 	comp = &active_state->newkeys[mode]->comp;
770 	if (mac_init(mac) == 0)
771 		mac->enabled = 1;
772 	DBG(debug("cipher_init_context: %d", mode));
773 	cipher_init(cc, enc->cipher, enc->key, enc->key_len,
774 	    enc->iv, enc->block_size, crypt_type);
775 	/* Deleting the keys does not gain extra security */
776 	/* memset(enc->iv,  0, enc->block_size);
777 	   memset(enc->key, 0, enc->key_len);
778 	   memset(mac->key, 0, mac->key_len); */
779 	if ((comp->type == COMP_ZLIB ||
780 	    (comp->type == COMP_DELAYED &&
781 	     active_state->after_authentication)) && comp->enabled == 0) {
782 		packet_init_compression();
783 		if (mode == MODE_OUT)
784 			buffer_compress_init_send(6);
785 		else
786 			buffer_compress_init_recv();
787 		comp->enabled = 1;
788 	}
789 	/*
790 	 * The 2^(blocksize*2) limit is too expensive for 3DES,
791 	 * blowfish, etc, so enforce a 1GB limit for small blocksizes.
792 	 */
793 	if (enc->block_size >= 16)
794 		*max_blocks = (u_int64_t)1 << (enc->block_size*2);
795 	else
796 		*max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
797 	if (active_state->rekey_limit)
798 		*max_blocks = MIN(*max_blocks,
799 		    active_state->rekey_limit / enc->block_size);
800 }
801 
802 /*
803  * Delayed compression for SSH2 is enabled after authentication:
804  * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
805  * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
806  */
807 static void
packet_enable_delayed_compress(void)808 packet_enable_delayed_compress(void)
809 {
810 	Comp *comp = NULL;
811 	int mode;
812 
813 	/*
814 	 * Remember that we are past the authentication step, so rekeying
815 	 * with COMP_DELAYED will turn on compression immediately.
816 	 */
817 	active_state->after_authentication = 1;
818 	for (mode = 0; mode < MODE_MAX; mode++) {
819 		/* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
820 		if (active_state->newkeys[mode] == NULL)
821 			continue;
822 		comp = &active_state->newkeys[mode]->comp;
823 		if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
824 			packet_init_compression();
825 			if (mode == MODE_OUT)
826 				buffer_compress_init_send(6);
827 			else
828 				buffer_compress_init_recv();
829 			comp->enabled = 1;
830 		}
831 	}
832 }
833 
834 /*
835  * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
836  */
837 static void
packet_send2_wrapped(void)838 packet_send2_wrapped(void)
839 {
840 	u_char type, *cp, *macbuf = NULL;
841 	u_char padlen, pad;
842 	u_int packet_length = 0;
843 	u_int len;
844 	Enc *enc   = NULL;
845 	Mac *mac   = NULL;
846 	Comp *comp = NULL;
847 	int block_size;
848 
849 	if (active_state->newkeys[MODE_OUT] != NULL) {
850 		enc  = &active_state->newkeys[MODE_OUT]->enc;
851 		mac  = &active_state->newkeys[MODE_OUT]->mac;
852 		comp = &active_state->newkeys[MODE_OUT]->comp;
853 	}
854 	block_size = enc ? enc->block_size : 8;
855 
856 	cp = buffer_ptr(&active_state->outgoing_packet);
857 	type = cp[5];
858 
859 #ifdef PACKET_DEBUG
860 	fprintf(stderr, "plain:     ");
861 	buffer_dump(&active_state->outgoing_packet);
862 #endif
863 
864 	if (comp && comp->enabled) {
865 		len = buffer_len(&active_state->outgoing_packet);
866 		/* skip header, compress only payload */
867 		buffer_consume(&active_state->outgoing_packet, 5);
868 		buffer_clear(&active_state->compression_buffer);
869 		buffer_compress(&active_state->outgoing_packet,
870 		    &active_state->compression_buffer);
871 		buffer_clear(&active_state->outgoing_packet);
872 		buffer_append(&active_state->outgoing_packet, NULs, 5);
873 		buffer_append(&active_state->outgoing_packet,
874 		    buffer_ptr(&active_state->compression_buffer),
875 		    buffer_len(&active_state->compression_buffer));
876 		DBG(debug("compression: raw %d compressed %d", len,
877 		    buffer_len(&active_state->outgoing_packet)));
878 	}
879 
880 	/* sizeof (packet_len + pad_len + payload) */
881 	len = buffer_len(&active_state->outgoing_packet);
882 
883 	/*
884 	 * calc size of padding, alloc space, get random data,
885 	 * minimum padding is 4 bytes
886 	 */
887 	padlen = block_size - (len % block_size);
888 	if (padlen < 4)
889 		padlen += block_size;
890 	if (active_state->extra_pad) {
891 		/* will wrap if extra_pad+padlen > 255 */
892 		active_state->extra_pad =
893 		    roundup(active_state->extra_pad, block_size);
894 		pad = active_state->extra_pad -
895 		    ((len + padlen) % active_state->extra_pad);
896 		debug3("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
897 		    pad, len, padlen, active_state->extra_pad);
898 		padlen += pad;
899 		active_state->extra_pad = 0;
900 	}
901 	cp = buffer_append_space(&active_state->outgoing_packet, padlen);
902 	if (enc && !active_state->send_context.plaintext) {
903 		/* random padding */
904 		arc4random_buf(cp, padlen);
905 	} else {
906 		/* clear padding */
907 		memset(cp, 0, padlen);
908 	}
909 	/* packet_length includes payload, padding and padding length field */
910 	packet_length = buffer_len(&active_state->outgoing_packet) - 4;
911 	cp = buffer_ptr(&active_state->outgoing_packet);
912 	put_u32(cp, packet_length);
913 	cp[4] = padlen;
914 	DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen));
915 
916 	/* compute MAC over seqnr and packet(length fields, payload, padding) */
917 	if (mac && mac->enabled) {
918 		macbuf = mac_compute(mac, active_state->p_send.seqnr,
919 		    buffer_ptr(&active_state->outgoing_packet),
920 		    buffer_len(&active_state->outgoing_packet));
921 		DBG(debug("done calc MAC out #%d", active_state->p_send.seqnr));
922 	}
923 	/* encrypt packet and append to output buffer. */
924 	cp = buffer_append_space(&active_state->output,
925 	    buffer_len(&active_state->outgoing_packet));
926 	cipher_crypt(&active_state->send_context, cp,
927 	    buffer_ptr(&active_state->outgoing_packet),
928 	    buffer_len(&active_state->outgoing_packet));
929 	/* append unencrypted MAC */
930 	if (mac && mac->enabled)
931 		buffer_append(&active_state->output, macbuf, mac->mac_len);
932 #ifdef PACKET_DEBUG
933 	fprintf(stderr, "encrypted: ");
934 	buffer_dump(&active_state->output);
935 #endif
936 	/* increment sequence number for outgoing packets */
937 	if (++active_state->p_send.seqnr == 0)
938 		logit("outgoing seqnr wraps around");
939 	if (++active_state->p_send.packets == 0)
940 		if (!(datafellows & SSH_BUG_NOREKEY))
941 			fatal("XXX too many packets with same key");
942 	active_state->p_send.blocks += (packet_length + 4) / block_size;
943 	active_state->p_send.bytes += packet_length + 4;
944 	buffer_clear(&active_state->outgoing_packet);
945 
946 	if (type == SSH2_MSG_NEWKEYS)
947 		set_newkeys(MODE_OUT);
948 	else if (type == SSH2_MSG_USERAUTH_SUCCESS && active_state->server_side)
949 		packet_enable_delayed_compress();
950 }
951 
952 static void
packet_send2(void)953 packet_send2(void)
954 {
955 	struct packet *p;
956 	u_char type, *cp;
957 
958 	cp = buffer_ptr(&active_state->outgoing_packet);
959 	type = cp[5];
960 
961 	/* during rekeying we can only send key exchange messages */
962 	if (active_state->rekeying) {
963 		if (!((type >= SSH2_MSG_TRANSPORT_MIN) &&
964 		    (type <= SSH2_MSG_TRANSPORT_MAX))) {
965 			debug("enqueue packet: %u", type);
966 			p = xmalloc(sizeof(*p));
967 			p->type = type;
968 			memcpy(&p->payload, &active_state->outgoing_packet,
969 			    sizeof(Buffer));
970 			buffer_init(&active_state->outgoing_packet);
971 			TAILQ_INSERT_TAIL(&active_state->outgoing, p, next);
972 			return;
973 		}
974 	}
975 
976 	/* rekeying starts with sending KEXINIT */
977 	if (type == SSH2_MSG_KEXINIT)
978 		active_state->rekeying = 1;
979 
980 	packet_send2_wrapped();
981 
982 	/* after a NEWKEYS message we can send the complete queue */
983 	if (type == SSH2_MSG_NEWKEYS) {
984 		active_state->rekeying = 0;
985 		while ((p = TAILQ_FIRST(&active_state->outgoing))) {
986 			type = p->type;
987 			debug("dequeue packet: %u", type);
988 			buffer_free(&active_state->outgoing_packet);
989 			memcpy(&active_state->outgoing_packet, &p->payload,
990 			    sizeof(Buffer));
991 			TAILQ_REMOVE(&active_state->outgoing, p, next);
992 			xfree(p);
993 			packet_send2_wrapped();
994 		}
995 	}
996 }
997 
998 void
packet_send(void)999 packet_send(void)
1000 {
1001 	if (compat20)
1002 		packet_send2();
1003 	else
1004 		packet_send1();
1005 	DBG(debug("packet_send done"));
1006 }
1007 
1008 /*
1009  * Waits until a packet has been received, and returns its type.  Note that
1010  * no other data is processed until this returns, so this function should not
1011  * be used during the interactive session.
1012  */
1013 
1014 int
packet_read_seqnr(u_int32_t * seqnr_p)1015 packet_read_seqnr(u_int32_t *seqnr_p)
1016 {
1017 	int type, len, ret, ms_remain, cont;
1018 	fd_set *setp;
1019 	char buf[8192];
1020 	struct timeval timeout, start, *timeoutp = NULL;
1021 
1022 	DBG(debug("packet_read()"));
1023 
1024 	setp = (fd_set *)xcalloc(howmany(active_state->connection_in + 1,
1025 	    NFDBITS), sizeof(fd_mask));
1026 
1027 	/* Since we are blocking, ensure that all written packets have been sent. */
1028 	packet_write_wait();
1029 
1030 	/* Stay in the loop until we have received a complete packet. */
1031 	for (;;) {
1032 		/* Try to read a packet from the buffer. */
1033 		type = packet_read_poll_seqnr(seqnr_p);
1034 		if (!compat20 && (
1035 		    type == SSH_SMSG_SUCCESS
1036 		    || type == SSH_SMSG_FAILURE
1037 		    || type == SSH_CMSG_EOF
1038 		    || type == SSH_CMSG_EXIT_CONFIRMATION))
1039 			packet_check_eom();
1040 		/* If we got a packet, return it. */
1041 		if (type != SSH_MSG_NONE) {
1042 			xfree(setp);
1043 			return type;
1044 		}
1045 		/*
1046 		 * Otherwise, wait for some data to arrive, add it to the
1047 		 * buffer, and try again.
1048 		 */
1049 		memset(setp, 0, howmany(active_state->connection_in + 1,
1050 		    NFDBITS) * sizeof(fd_mask));
1051 		FD_SET(active_state->connection_in, setp);
1052 
1053 		if (active_state->packet_timeout_ms > 0) {
1054 			ms_remain = active_state->packet_timeout_ms;
1055 			timeoutp = &timeout;
1056 		}
1057 		/* Wait for some data to arrive. */
1058 		for (;;) {
1059 			if (active_state->packet_timeout_ms != -1) {
1060 				ms_to_timeval(&timeout, ms_remain);
1061 				gettimeofday(&start, NULL);
1062 			}
1063 			if ((ret = select(active_state->connection_in + 1, setp,
1064 			    NULL, NULL, timeoutp)) >= 0)
1065 				break;
1066 			if (errno != EAGAIN && errno != EINTR)
1067 				break;
1068 			if (active_state->packet_timeout_ms == -1)
1069 				continue;
1070 			ms_subtract_diff(&start, &ms_remain);
1071 			if (ms_remain <= 0) {
1072 				ret = 0;
1073 				break;
1074 			}
1075 		}
1076 		if (ret == 0) {
1077 			logit("Connection to %.200s timed out while "
1078 			    "waiting to read", get_remote_ipaddr());
1079 			cleanup_exit(255);
1080 		}
1081 		/* Read data from the socket. */
1082 		do {
1083 			cont = 0;
1084 			len = roaming_read(active_state->connection_in, buf,
1085 			    sizeof(buf), &cont);
1086 		} while (len == 0 && cont);
1087 		if (len == 0) {
1088 			logit("Connection closed by %.200s", get_remote_ipaddr());
1089 			cleanup_exit(255);
1090 		}
1091 		if (len < 0)
1092 			fatal("Read from socket failed: %.100s", strerror(errno));
1093 		/* Append it to the buffer. */
1094 		packet_process_incoming(buf, len);
1095 	}
1096 	/* NOTREACHED */
1097 }
1098 
1099 int
packet_read(void)1100 packet_read(void)
1101 {
1102 	return packet_read_seqnr(NULL);
1103 }
1104 
1105 /*
1106  * Waits until a packet has been received, verifies that its type matches
1107  * that given, and gives a fatal error and exits if there is a mismatch.
1108  */
1109 
1110 void
packet_read_expect(int expected_type)1111 packet_read_expect(int expected_type)
1112 {
1113 	int type;
1114 
1115 	type = packet_read();
1116 	if (type != expected_type)
1117 		packet_disconnect("Protocol error: expected packet type %d, got %d",
1118 		    expected_type, type);
1119 }
1120 
1121 /* Checks if a full packet is available in the data received so far via
1122  * packet_process_incoming.  If so, reads the packet; otherwise returns
1123  * SSH_MSG_NONE.  This does not wait for data from the connection.
1124  *
1125  * SSH_MSG_DISCONNECT is handled specially here.  Also,
1126  * SSH_MSG_IGNORE messages are skipped by this function and are never returned
1127  * to higher levels.
1128  */
1129 
1130 static int
packet_read_poll1(void)1131 packet_read_poll1(void)
1132 {
1133 	u_int len, padded_len;
1134 	u_char *cp, type;
1135 	u_int checksum, stored_checksum;
1136 
1137 	/* Check if input size is less than minimum packet size. */
1138 	if (buffer_len(&active_state->input) < 4 + 8)
1139 		return SSH_MSG_NONE;
1140 	/* Get length of incoming packet. */
1141 	cp = buffer_ptr(&active_state->input);
1142 	len = get_u32(cp);
1143 	if (len < 1 + 2 + 2 || len > 256 * 1024)
1144 		packet_disconnect("Bad packet length %u.", len);
1145 	padded_len = (len + 8) & ~7;
1146 
1147 	/* Check if the packet has been entirely received. */
1148 	if (buffer_len(&active_state->input) < 4 + padded_len)
1149 		return SSH_MSG_NONE;
1150 
1151 	/* The entire packet is in buffer. */
1152 
1153 	/* Consume packet length. */
1154 	buffer_consume(&active_state->input, 4);
1155 
1156 	/*
1157 	 * Cryptographic attack detector for ssh
1158 	 * (C)1998 CORE-SDI, Buenos Aires Argentina
1159 	 * Ariel Futoransky(futo@core-sdi.com)
1160 	 */
1161 	if (!active_state->receive_context.plaintext) {
1162 		switch (detect_attack(buffer_ptr(&active_state->input),
1163 		    padded_len)) {
1164 		case DEATTACK_DETECTED:
1165 			packet_disconnect("crc32 compensation attack: "
1166 			    "network attack detected");
1167 		case DEATTACK_DOS_DETECTED:
1168 			packet_disconnect("deattack denial of "
1169 			    "service detected");
1170 		}
1171 	}
1172 
1173 	/* Decrypt data to incoming_packet. */
1174 	buffer_clear(&active_state->incoming_packet);
1175 	cp = buffer_append_space(&active_state->incoming_packet, padded_len);
1176 	cipher_crypt(&active_state->receive_context, cp,
1177 	    buffer_ptr(&active_state->input), padded_len);
1178 
1179 	buffer_consume(&active_state->input, padded_len);
1180 
1181 #ifdef PACKET_DEBUG
1182 	fprintf(stderr, "read_poll plain: ");
1183 	buffer_dump(&active_state->incoming_packet);
1184 #endif
1185 
1186 	/* Compute packet checksum. */
1187 	checksum = ssh_crc32(buffer_ptr(&active_state->incoming_packet),
1188 	    buffer_len(&active_state->incoming_packet) - 4);
1189 
1190 	/* Skip padding. */
1191 	buffer_consume(&active_state->incoming_packet, 8 - len % 8);
1192 
1193 	/* Test check bytes. */
1194 	if (len != buffer_len(&active_state->incoming_packet))
1195 		packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
1196 		    len, buffer_len(&active_state->incoming_packet));
1197 
1198 	cp = (u_char *)buffer_ptr(&active_state->incoming_packet) + len - 4;
1199 	stored_checksum = get_u32(cp);
1200 	if (checksum != stored_checksum)
1201 		packet_disconnect("Corrupted check bytes on input.");
1202 	buffer_consume_end(&active_state->incoming_packet, 4);
1203 
1204 	if (active_state->packet_compression) {
1205 		buffer_clear(&active_state->compression_buffer);
1206 		buffer_uncompress(&active_state->incoming_packet,
1207 		    &active_state->compression_buffer);
1208 		buffer_clear(&active_state->incoming_packet);
1209 		buffer_append(&active_state->incoming_packet,
1210 		    buffer_ptr(&active_state->compression_buffer),
1211 		    buffer_len(&active_state->compression_buffer));
1212 	}
1213 	active_state->p_read.packets++;
1214 	active_state->p_read.bytes += padded_len + 4;
1215 	type = buffer_get_char(&active_state->incoming_packet);
1216 	if (type < SSH_MSG_MIN || type > SSH_MSG_MAX)
1217 		packet_disconnect("Invalid ssh1 packet type: %d", type);
1218 	return type;
1219 }
1220 
1221 static int
packet_read_poll2(u_int32_t * seqnr_p)1222 packet_read_poll2(u_int32_t *seqnr_p)
1223 {
1224 	u_int padlen, need;
1225 	u_char *macbuf, *cp, type;
1226 	u_int maclen, block_size;
1227 	Enc *enc   = NULL;
1228 	Mac *mac   = NULL;
1229 	Comp *comp = NULL;
1230 
1231 	if (active_state->packet_discard)
1232 		return SSH_MSG_NONE;
1233 
1234 	if (active_state->newkeys[MODE_IN] != NULL) {
1235 		enc  = &active_state->newkeys[MODE_IN]->enc;
1236 		mac  = &active_state->newkeys[MODE_IN]->mac;
1237 		comp = &active_state->newkeys[MODE_IN]->comp;
1238 	}
1239 	maclen = mac && mac->enabled ? mac->mac_len : 0;
1240 	block_size = enc ? enc->block_size : 8;
1241 
1242 	if (active_state->packlen == 0) {
1243 		/*
1244 		 * check if input size is less than the cipher block size,
1245 		 * decrypt first block and extract length of incoming packet
1246 		 */
1247 		if (buffer_len(&active_state->input) < block_size)
1248 			return SSH_MSG_NONE;
1249 		buffer_clear(&active_state->incoming_packet);
1250 		cp = buffer_append_space(&active_state->incoming_packet,
1251 		    block_size);
1252 		cipher_crypt(&active_state->receive_context, cp,
1253 		    buffer_ptr(&active_state->input), block_size);
1254 		cp = buffer_ptr(&active_state->incoming_packet);
1255 		active_state->packlen = get_u32(cp);
1256 		if (active_state->packlen < 1 + 4 ||
1257 		    active_state->packlen > PACKET_MAX_SIZE) {
1258 #ifdef PACKET_DEBUG
1259 			buffer_dump(&active_state->incoming_packet);
1260 #endif
1261 			logit("Bad packet length %u.", active_state->packlen);
1262 			packet_start_discard(enc, mac, active_state->packlen,
1263 			    PACKET_MAX_SIZE);
1264 			return SSH_MSG_NONE;
1265 		}
1266 		DBG(debug("input: packet len %u", active_state->packlen+4));
1267 		buffer_consume(&active_state->input, block_size);
1268 	}
1269 	/* we have a partial packet of block_size bytes */
1270 	need = 4 + active_state->packlen - block_size;
1271 	DBG(debug("partial packet %d, need %d, maclen %d", block_size,
1272 	    need, maclen));
1273 	if (need % block_size != 0) {
1274 		logit("padding error: need %d block %d mod %d",
1275 		    need, block_size, need % block_size);
1276 		packet_start_discard(enc, mac, active_state->packlen,
1277 		    PACKET_MAX_SIZE - block_size);
1278 		return SSH_MSG_NONE;
1279 	}
1280 	/*
1281 	 * check if the entire packet has been received and
1282 	 * decrypt into incoming_packet
1283 	 */
1284 	if (buffer_len(&active_state->input) < need + maclen)
1285 		return SSH_MSG_NONE;
1286 #ifdef PACKET_DEBUG
1287 	fprintf(stderr, "read_poll enc/full: ");
1288 	buffer_dump(&active_state->input);
1289 #endif
1290 	cp = buffer_append_space(&active_state->incoming_packet, need);
1291 	cipher_crypt(&active_state->receive_context, cp,
1292 	    buffer_ptr(&active_state->input), need);
1293 	buffer_consume(&active_state->input, need);
1294 	/*
1295 	 * compute MAC over seqnr and packet,
1296 	 * increment sequence number for incoming packet
1297 	 */
1298 	if (mac && mac->enabled) {
1299 		macbuf = mac_compute(mac, active_state->p_read.seqnr,
1300 		    buffer_ptr(&active_state->incoming_packet),
1301 		    buffer_len(&active_state->incoming_packet));
1302 		if (memcmp(macbuf, buffer_ptr(&active_state->input),
1303 		    mac->mac_len) != 0) {
1304 			logit("Corrupted MAC on input.");
1305 			if (need > PACKET_MAX_SIZE)
1306 				fatal("internal error need %d", need);
1307 			packet_start_discard(enc, mac, active_state->packlen,
1308 			    PACKET_MAX_SIZE - need);
1309 			return SSH_MSG_NONE;
1310 		}
1311 
1312 		DBG(debug("MAC #%d ok", active_state->p_read.seqnr));
1313 		buffer_consume(&active_state->input, mac->mac_len);
1314 	}
1315 	/* XXX now it's safe to use fatal/packet_disconnect */
1316 	if (seqnr_p != NULL)
1317 		*seqnr_p = active_state->p_read.seqnr;
1318 	if (++active_state->p_read.seqnr == 0)
1319 		logit("incoming seqnr wraps around");
1320 	if (++active_state->p_read.packets == 0)
1321 		if (!(datafellows & SSH_BUG_NOREKEY))
1322 			fatal("XXX too many packets with same key");
1323 	active_state->p_read.blocks += (active_state->packlen + 4) / block_size;
1324 	active_state->p_read.bytes += active_state->packlen + 4;
1325 
1326 	/* get padlen */
1327 	cp = buffer_ptr(&active_state->incoming_packet);
1328 	padlen = cp[4];
1329 	DBG(debug("input: padlen %d", padlen));
1330 	if (padlen < 4)
1331 		packet_disconnect("Corrupted padlen %d on input.", padlen);
1332 
1333 	/* skip packet size + padlen, discard padding */
1334 	buffer_consume(&active_state->incoming_packet, 4 + 1);
1335 	buffer_consume_end(&active_state->incoming_packet, padlen);
1336 
1337 	DBG(debug("input: len before de-compress %d",
1338 	    buffer_len(&active_state->incoming_packet)));
1339 	if (comp && comp->enabled) {
1340 		buffer_clear(&active_state->compression_buffer);
1341 		buffer_uncompress(&active_state->incoming_packet,
1342 		    &active_state->compression_buffer);
1343 		buffer_clear(&active_state->incoming_packet);
1344 		buffer_append(&active_state->incoming_packet,
1345 		    buffer_ptr(&active_state->compression_buffer),
1346 		    buffer_len(&active_state->compression_buffer));
1347 		DBG(debug("input: len after de-compress %d",
1348 		    buffer_len(&active_state->incoming_packet)));
1349 	}
1350 	/*
1351 	 * get packet type, implies consume.
1352 	 * return length of payload (without type field)
1353 	 */
1354 	type = buffer_get_char(&active_state->incoming_packet);
1355 	if (type < SSH2_MSG_MIN || type >= SSH2_MSG_LOCAL_MIN)
1356 		packet_disconnect("Invalid ssh2 packet type: %d", type);
1357 	if (type == SSH2_MSG_NEWKEYS)
1358 		set_newkeys(MODE_IN);
1359 	else if (type == SSH2_MSG_USERAUTH_SUCCESS &&
1360 	    !active_state->server_side)
1361 		packet_enable_delayed_compress();
1362 #ifdef PACKET_DEBUG
1363 	fprintf(stderr, "read/plain[%d]:\r\n", type);
1364 	buffer_dump(&active_state->incoming_packet);
1365 #endif
1366 	/* reset for next packet */
1367 	active_state->packlen = 0;
1368 	return type;
1369 }
1370 
1371 int
packet_read_poll_seqnr(u_int32_t * seqnr_p)1372 packet_read_poll_seqnr(u_int32_t *seqnr_p)
1373 {
1374 	u_int reason, seqnr;
1375 	u_char type;
1376 	char *msg;
1377 
1378 	for (;;) {
1379 		if (compat20) {
1380 			type = packet_read_poll2(seqnr_p);
1381 			if (type) {
1382 				active_state->keep_alive_timeouts = 0;
1383 				DBG(debug("received packet type %d", type));
1384 			}
1385 			switch (type) {
1386 			case SSH2_MSG_IGNORE:
1387 				packet_consume_ignoremsg();
1388 				debug3("Received SSH2_MSG_IGNORE");
1389 				break;
1390 			case SSH2_MSG_DEBUG:
1391 				packet_get_char();
1392 				msg = packet_get_string(NULL);
1393 				debug("Remote: %.900s", msg);
1394 				xfree(msg);
1395 				msg = packet_get_string(NULL);
1396 				xfree(msg);
1397 				break;
1398 			case SSH2_MSG_DISCONNECT:
1399 				reason = packet_get_int();
1400 				msg = packet_get_string(NULL);
1401 				logit("Received disconnect from %s: %u: %.400s",
1402 				    get_remote_ipaddr(), reason, msg);
1403 				xfree(msg);
1404 				cleanup_exit(255);
1405 				break;
1406 			case SSH2_MSG_UNIMPLEMENTED:
1407 				seqnr = packet_get_int();
1408 				debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1409 				    seqnr);
1410 				break;
1411 			default:
1412 				return type;
1413 			}
1414 		} else {
1415 			type = packet_read_poll1();
1416 			switch (type) {
1417 			case SSH_MSG_IGNORE:
1418 				packet_consume_ignoremsg();
1419 				break;
1420 			case SSH_MSG_DEBUG:
1421 				msg = packet_get_string(NULL);
1422 				debug("Remote: %.900s", msg);
1423 				xfree(msg);
1424 				break;
1425 			case SSH_MSG_DISCONNECT:
1426 				msg = packet_get_string(NULL);
1427 				logit("Received disconnect from %s: %.400s",
1428 				    get_remote_ipaddr(), msg);
1429 				cleanup_exit(255);
1430 				break;
1431 			default:
1432 				if (type) {
1433 					DBG(debug("received packet type %d", type));
1434 				}
1435 				return type;
1436 			}
1437 		}
1438 	}
1439 }
1440 
1441 int
packet_read_poll(void)1442 packet_read_poll(void)
1443 {
1444 	return packet_read_poll_seqnr(NULL);
1445 }
1446 
1447 /*
1448  * Buffers the given amount of input characters.  This is intended to be used
1449  * together with packet_read_poll.
1450  */
1451 
1452 void
packet_process_incoming(const char * buf,u_int len)1453 packet_process_incoming(const char *buf, u_int len)
1454 {
1455 	if (active_state->packet_discard) {
1456 		active_state->keep_alive_timeouts = 0; /* ?? */
1457 		if (len >= active_state->packet_discard)
1458 			packet_stop_discard();
1459 		active_state->packet_discard -= len;
1460 		return;
1461 	}
1462 	buffer_append(&active_state->input, buf, len);
1463 }
1464 
1465 /* Returns a character from the packet. */
1466 
1467 u_int
packet_get_char(void)1468 packet_get_char(void)
1469 {
1470 	char ch;
1471 
1472 	buffer_get(&active_state->incoming_packet, &ch, 1);
1473 	return (u_char) ch;
1474 }
1475 
1476 /* Returns an integer from the packet data. */
1477 
1478 u_int
packet_get_int(void)1479 packet_get_int(void)
1480 {
1481 	return buffer_get_int(&active_state->incoming_packet);
1482 }
1483 
1484 /* Returns an 64 bit integer from the packet data. */
1485 
1486 u_int64_t
packet_get_int64(void)1487 packet_get_int64(void)
1488 {
1489 	return buffer_get_int64(&active_state->incoming_packet);
1490 }
1491 
1492 /*
1493  * Returns an arbitrary precision integer from the packet data.  The integer
1494  * must have been initialized before this call.
1495  */
1496 
1497 void
packet_get_bignum(BIGNUM * value)1498 packet_get_bignum(BIGNUM * value)
1499 {
1500 	buffer_get_bignum(&active_state->incoming_packet, value);
1501 }
1502 
1503 void
packet_get_bignum2(BIGNUM * value)1504 packet_get_bignum2(BIGNUM * value)
1505 {
1506 	buffer_get_bignum2(&active_state->incoming_packet, value);
1507 }
1508 
1509 void *
packet_get_raw(u_int * length_ptr)1510 packet_get_raw(u_int *length_ptr)
1511 {
1512 	u_int bytes = buffer_len(&active_state->incoming_packet);
1513 
1514 	if (length_ptr != NULL)
1515 		*length_ptr = bytes;
1516 	return buffer_ptr(&active_state->incoming_packet);
1517 }
1518 
1519 int
packet_remaining(void)1520 packet_remaining(void)
1521 {
1522 	return buffer_len(&active_state->incoming_packet);
1523 }
1524 
1525 /*
1526  * Returns a string from the packet data.  The string is allocated using
1527  * xmalloc; it is the responsibility of the calling program to free it when
1528  * no longer needed.  The length_ptr argument may be NULL, or point to an
1529  * integer into which the length of the string is stored.
1530  */
1531 
1532 void *
packet_get_string(u_int * length_ptr)1533 packet_get_string(u_int *length_ptr)
1534 {
1535 	return buffer_get_string(&active_state->incoming_packet, length_ptr);
1536 }
1537 
1538 void *
packet_get_string_ptr(u_int * length_ptr)1539 packet_get_string_ptr(u_int *length_ptr)
1540 {
1541 	return buffer_get_string_ptr(&active_state->incoming_packet, length_ptr);
1542 }
1543 
1544 /*
1545  * Sends a diagnostic message from the server to the client.  This message
1546  * can be sent at any time (but not while constructing another message). The
1547  * message is printed immediately, but only if the client is being executed
1548  * in verbose mode.  These messages are primarily intended to ease debugging
1549  * authentication problems.   The length of the formatted message must not
1550  * exceed 1024 bytes.  This will automatically call packet_write_wait.
1551  */
1552 
1553 void
packet_send_debug(const char * fmt,...)1554 packet_send_debug(const char *fmt,...)
1555 {
1556 	char buf[1024];
1557 	va_list args;
1558 
1559 	if (compat20 && (datafellows & SSH_BUG_DEBUG))
1560 		return;
1561 
1562 	va_start(args, fmt);
1563 	vsnprintf(buf, sizeof(buf), fmt, args);
1564 	va_end(args);
1565 
1566 	if (compat20) {
1567 		packet_start(SSH2_MSG_DEBUG);
1568 		packet_put_char(0);	/* bool: always display */
1569 		packet_put_cstring(buf);
1570 		packet_put_cstring("");
1571 	} else {
1572 		packet_start(SSH_MSG_DEBUG);
1573 		packet_put_cstring(buf);
1574 	}
1575 	packet_send();
1576 	packet_write_wait();
1577 }
1578 
1579 /*
1580  * Logs the error plus constructs and sends a disconnect packet, closes the
1581  * connection, and exits.  This function never returns. The error message
1582  * should not contain a newline.  The length of the formatted message must
1583  * not exceed 1024 bytes.
1584  */
1585 
1586 void
packet_disconnect(const char * fmt,...)1587 packet_disconnect(const char *fmt,...)
1588 {
1589 	char buf[1024];
1590 	va_list args;
1591 	static int disconnecting = 0;
1592 
1593 	if (disconnecting)	/* Guard against recursive invocations. */
1594 		fatal("packet_disconnect called recursively.");
1595 	disconnecting = 1;
1596 
1597 	/*
1598 	 * Format the message.  Note that the caller must make sure the
1599 	 * message is of limited size.
1600 	 */
1601 	va_start(args, fmt);
1602 	vsnprintf(buf, sizeof(buf), fmt, args);
1603 	va_end(args);
1604 
1605 	/* Display the error locally */
1606 	logit("Disconnecting: %.100s", buf);
1607 
1608 	/* Send the disconnect message to the other side, and wait for it to get sent. */
1609 	if (compat20) {
1610 		packet_start(SSH2_MSG_DISCONNECT);
1611 		packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1612 		packet_put_cstring(buf);
1613 		packet_put_cstring("");
1614 	} else {
1615 		packet_start(SSH_MSG_DISCONNECT);
1616 		packet_put_cstring(buf);
1617 	}
1618 	packet_send();
1619 	packet_write_wait();
1620 
1621 	/* Stop listening for connections. */
1622 	channel_close_all();
1623 
1624 	/* Close the connection. */
1625 	packet_close();
1626 	cleanup_exit(255);
1627 }
1628 
1629 /* Checks if there is any buffered output, and tries to write some of the output. */
1630 
1631 void
packet_write_poll(void)1632 packet_write_poll(void)
1633 {
1634 	int len = buffer_len(&active_state->output);
1635 	int cont;
1636 
1637 	if (len > 0) {
1638 		cont = 0;
1639 		len = roaming_write(active_state->connection_out,
1640 		    buffer_ptr(&active_state->output), len, &cont);
1641 		if (len == -1) {
1642 			if (errno == EINTR || errno == EAGAIN)
1643 				return;
1644 			fatal("Write failed: %.100s", strerror(errno));
1645 		}
1646 		if (len == 0 && !cont)
1647 			fatal("Write connection closed");
1648 		buffer_consume(&active_state->output, len);
1649 	}
1650 }
1651 
1652 /*
1653  * Calls packet_write_poll repeatedly until all pending output data has been
1654  * written.
1655  */
1656 
1657 void
packet_write_wait(void)1658 packet_write_wait(void)
1659 {
1660 	fd_set *setp;
1661 	int ret, ms_remain;
1662 	struct timeval start, timeout, *timeoutp = NULL;
1663 
1664 	setp = (fd_set *)xcalloc(howmany(active_state->connection_out + 1,
1665 	    NFDBITS), sizeof(fd_mask));
1666 	packet_write_poll();
1667 	while (packet_have_data_to_write()) {
1668 		memset(setp, 0, howmany(active_state->connection_out + 1,
1669 		    NFDBITS) * sizeof(fd_mask));
1670 		FD_SET(active_state->connection_out, setp);
1671 
1672 		if (active_state->packet_timeout_ms > 0) {
1673 			ms_remain = active_state->packet_timeout_ms;
1674 			timeoutp = &timeout;
1675 		}
1676 		for (;;) {
1677 			if (active_state->packet_timeout_ms != -1) {
1678 				ms_to_timeval(&timeout, ms_remain);
1679 				gettimeofday(&start, NULL);
1680 			}
1681 			if ((ret = select(active_state->connection_out + 1,
1682 			    NULL, setp, NULL, timeoutp)) >= 0)
1683 				break;
1684 			if (errno != EAGAIN && errno != EINTR)
1685 				break;
1686 			if (active_state->packet_timeout_ms == -1)
1687 				continue;
1688 			ms_subtract_diff(&start, &ms_remain);
1689 			if (ms_remain <= 0) {
1690 				ret = 0;
1691 				break;
1692 			}
1693 		}
1694 		if (ret == 0) {
1695 			logit("Connection to %.200s timed out while "
1696 			    "waiting to write", get_remote_ipaddr());
1697 			cleanup_exit(255);
1698 		}
1699 		packet_write_poll();
1700 	}
1701 	xfree(setp);
1702 }
1703 
1704 /* Returns true if there is buffered data to write to the connection. */
1705 
1706 int
packet_have_data_to_write(void)1707 packet_have_data_to_write(void)
1708 {
1709 	return buffer_len(&active_state->output) != 0;
1710 }
1711 
1712 /* Returns true if there is not too much data to write to the connection. */
1713 
1714 int
packet_not_very_much_data_to_write(void)1715 packet_not_very_much_data_to_write(void)
1716 {
1717 	if (active_state->interactive_mode)
1718 		return buffer_len(&active_state->output) < 16384;
1719 	else
1720 		return buffer_len(&active_state->output) < 128 * 1024;
1721 }
1722 
1723 static void
packet_set_tos(int interactive)1724 packet_set_tos(int interactive)
1725 {
1726 	int tos = interactive ? IPTOS_LOWDELAY : IPTOS_THROUGHPUT;
1727 
1728 	if (!packet_connection_is_on_socket() ||
1729 	    !packet_connection_is_ipv4())
1730 		return;
1731 	if (setsockopt(active_state->connection_in, IPPROTO_IP, IP_TOS, &tos,
1732 	    sizeof(tos)) < 0)
1733 		error("setsockopt IP_TOS %d: %.100s:",
1734 		    tos, strerror(errno));
1735 }
1736 
1737 /* Informs that the current session is interactive.  Sets IP flags for that. */
1738 
1739 void
packet_set_interactive(int interactive)1740 packet_set_interactive(int interactive)
1741 {
1742 	if (active_state->set_interactive_called)
1743 		return;
1744 	active_state->set_interactive_called = 1;
1745 
1746 	/* Record that we are in interactive mode. */
1747 	active_state->interactive_mode = interactive;
1748 
1749 	/* Only set socket options if using a socket.  */
1750 	if (!packet_connection_is_on_socket())
1751 		return;
1752 	set_nodelay(active_state->connection_in);
1753 	packet_set_tos(interactive);
1754 }
1755 
1756 /* Returns true if the current connection is interactive. */
1757 
1758 int
packet_is_interactive(void)1759 packet_is_interactive(void)
1760 {
1761 	return active_state->interactive_mode;
1762 }
1763 
1764 int
packet_set_maxsize(u_int s)1765 packet_set_maxsize(u_int s)
1766 {
1767 	if (active_state->set_maxsize_called) {
1768 		logit("packet_set_maxsize: called twice: old %d new %d",
1769 		    active_state->max_packet_size, s);
1770 		return -1;
1771 	}
1772 	if (s < 4 * 1024 || s > 1024 * 1024) {
1773 		logit("packet_set_maxsize: bad size %d", s);
1774 		return -1;
1775 	}
1776 	active_state->set_maxsize_called = 1;
1777 	debug("packet_set_maxsize: setting to %d", s);
1778 	active_state->max_packet_size = s;
1779 	return s;
1780 }
1781 
1782 int
packet_inc_alive_timeouts(void)1783 packet_inc_alive_timeouts(void)
1784 {
1785 	return ++active_state->keep_alive_timeouts;
1786 }
1787 
1788 void
packet_set_alive_timeouts(int ka)1789 packet_set_alive_timeouts(int ka)
1790 {
1791 	active_state->keep_alive_timeouts = ka;
1792 }
1793 
1794 u_int
packet_get_maxsize(void)1795 packet_get_maxsize(void)
1796 {
1797 	return active_state->max_packet_size;
1798 }
1799 
1800 /* roundup current message to pad bytes */
1801 void
packet_add_padding(u_char pad)1802 packet_add_padding(u_char pad)
1803 {
1804 	active_state->extra_pad = pad;
1805 }
1806 
1807 /*
1808  * 9.2.  Ignored Data Message
1809  *
1810  *   byte      SSH_MSG_IGNORE
1811  *   string    data
1812  *
1813  * All implementations MUST understand (and ignore) this message at any
1814  * time (after receiving the protocol version). No implementation is
1815  * required to send them. This message can be used as an additional
1816  * protection measure against advanced traffic analysis techniques.
1817  */
1818 void
packet_send_ignore(int nbytes)1819 packet_send_ignore(int nbytes)
1820 {
1821 	u_int32_t rnd = 0;
1822 	int i;
1823 
1824 	packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1825 	packet_put_int(nbytes);
1826 	for (i = 0; i < nbytes; i++) {
1827 		if (i % 4 == 0)
1828 			rnd = arc4random();
1829 		packet_put_char((u_char)rnd & 0xff);
1830 		rnd >>= 8;
1831 	}
1832 }
1833 
1834 #define MAX_PACKETS	(1U<<31)
1835 int
packet_need_rekeying(void)1836 packet_need_rekeying(void)
1837 {
1838 	if (datafellows & SSH_BUG_NOREKEY)
1839 		return 0;
1840 	return
1841 	    (active_state->p_send.packets > MAX_PACKETS) ||
1842 	    (active_state->p_read.packets > MAX_PACKETS) ||
1843 	    (active_state->max_blocks_out &&
1844 	        (active_state->p_send.blocks > active_state->max_blocks_out)) ||
1845 	    (active_state->max_blocks_in &&
1846 	        (active_state->p_read.blocks > active_state->max_blocks_in));
1847 }
1848 
1849 void
packet_set_rekey_limit(u_int32_t bytes)1850 packet_set_rekey_limit(u_int32_t bytes)
1851 {
1852 	active_state->rekey_limit = bytes;
1853 }
1854 
1855 void
packet_set_server(void)1856 packet_set_server(void)
1857 {
1858 	active_state->server_side = 1;
1859 }
1860 
1861 void
packet_set_authenticated(void)1862 packet_set_authenticated(void)
1863 {
1864 	active_state->after_authentication = 1;
1865 }
1866 
1867 void *
packet_get_input(void)1868 packet_get_input(void)
1869 {
1870 	return (void *)&active_state->input;
1871 }
1872 
1873 void *
packet_get_output(void)1874 packet_get_output(void)
1875 {
1876 	return (void *)&active_state->output;
1877 }
1878 
1879 void *
packet_get_newkeys(int mode)1880 packet_get_newkeys(int mode)
1881 {
1882 	return (void *)active_state->newkeys[mode];
1883 }
1884 
1885 /*
1886  * Save the state for the real connection, and use a separate state when
1887  * resuming a suspended connection.
1888  */
1889 void
packet_backup_state(void)1890 packet_backup_state(void)
1891 {
1892 	struct session_state *tmp;
1893 
1894 	close(active_state->connection_in);
1895 	active_state->connection_in = -1;
1896 	close(active_state->connection_out);
1897 	active_state->connection_out = -1;
1898 	if (backup_state)
1899 		tmp = backup_state;
1900 	else
1901 		tmp = alloc_session_state();
1902 	backup_state = active_state;
1903 	active_state = tmp;
1904 }
1905 
1906 /*
1907  * Swap in the old state when resuming a connecion.
1908  */
1909 void
packet_restore_state(void)1910 packet_restore_state(void)
1911 {
1912 	struct session_state *tmp;
1913 	void *buf;
1914 	u_int len;
1915 
1916 	tmp = backup_state;
1917 	backup_state = active_state;
1918 	active_state = tmp;
1919 	active_state->connection_in = backup_state->connection_in;
1920 	backup_state->connection_in = -1;
1921 	active_state->connection_out = backup_state->connection_out;
1922 	backup_state->connection_out = -1;
1923 	len = buffer_len(&backup_state->input);
1924 	if (len > 0) {
1925 		buf = buffer_ptr(&backup_state->input);
1926 		buffer_append(&active_state->input, buf, len);
1927 		buffer_clear(&backup_state->input);
1928 		add_recv_bytes(len);
1929 	}
1930 }
1931 
1932 static void
packet_consume_ignoremsg(void)1933 packet_consume_ignoremsg(void)
1934 {
1935 	u_int n;
1936 	u_int8_t *b;
1937 
1938 	if ((b = packet_get_raw(&n)) == NULL)
1939 		return;
1940 
1941 	arc4random_pushb_fast(b, n);
1942 }
1943