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