xref: /titanic_44/usr/src/cmd/ssh/libssh/common/packet.c (revision 5bbb4db2c3f208d12bf0fd11769728f9e5ba66a2)
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 2009 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_utf8_cstring(const char *str)
451 {
452 	if (datafellows & SSH_BUG_STRING_ENCODING)
453 		buffer_put_cstring(&outgoing_packet, str);
454 	else
455 		buffer_put_utf8_cstring(&outgoing_packet, str);
456 }
457 
458 void
459 packet_put_utf8_string(const char *str, uint_t len)
460 {
461 	if (datafellows & SSH_BUG_STRING_ENCODING)
462 		buffer_put_string(&outgoing_packet, str, len);
463 	else
464 		buffer_put_utf8_string(&outgoing_packet, str, len);
465 }
466 
467 void
468 packet_put_raw(const void *buf, u_int len)
469 {
470 	buffer_append(&outgoing_packet, buf, len);
471 }
472 
473 void
474 packet_put_bignum(BIGNUM * value)
475 {
476 	buffer_put_bignum(&outgoing_packet, value);
477 }
478 
479 void
480 packet_put_bignum2(BIGNUM * value)
481 {
482 	buffer_put_bignum2(&outgoing_packet, value);
483 }
484 
485 /*
486  * Finalizes and sends the packet.  If the encryption key has been set,
487  * encrypts the packet before sending.
488  */
489 
490 static void
491 packet_send1(void)
492 {
493 	u_char buf[8], *cp;
494 	int i, padding, len;
495 	u_int checksum;
496 	u_int32_t rnd = 0;
497 
498 	/*
499 	 * If using packet compression, compress the payload of the outgoing
500 	 * packet.
501 	 */
502 	if (packet_compression) {
503 		buffer_clear(&compression_buffer);
504 		/* Skip padding. */
505 		buffer_consume(&outgoing_packet, 8);
506 		/* padding */
507 		buffer_append(&compression_buffer, "\0\0\0\0\0\0\0\0", 8);
508 		buffer_compress(&outgoing_packet, &compression_buffer);
509 		buffer_clear(&outgoing_packet);
510 		buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
511 		    buffer_len(&compression_buffer));
512 	}
513 	/* Compute packet length without padding (add checksum, remove padding). */
514 	len = buffer_len(&outgoing_packet) + 4 - 8;
515 
516 	/* Insert padding. Initialized to zero in packet_start1() */
517 	padding = 8 - len % 8;
518 	if (!send_context.plaintext) {
519 		cp = buffer_ptr(&outgoing_packet);
520 		for (i = 0; i < padding; i++) {
521 			if (i % 4 == 0)
522 				rnd = arc4random();
523 			cp[7 - i] = rnd & 0xff;
524 			rnd >>= 8;
525 		}
526 	}
527 	buffer_consume(&outgoing_packet, 8 - padding);
528 
529 	/* Add check bytes. */
530 	checksum = ssh_crc32(buffer_ptr(&outgoing_packet),
531 	    buffer_len(&outgoing_packet));
532 	PUT_32BIT(buf, checksum);
533 	buffer_append(&outgoing_packet, buf, 4);
534 
535 #ifdef PACKET_DEBUG
536 	fprintf(stderr, "packet_send plain: ");
537 	buffer_dump(&outgoing_packet);
538 #endif
539 
540 	/* Append to output. */
541 	PUT_32BIT(buf, len);
542 	buffer_append(&output, buf, 4);
543 	cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
544 	cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
545 	    buffer_len(&outgoing_packet));
546 
547 #ifdef PACKET_DEBUG
548 	debug("encrypted output queue now contains (%d bytes):\n",
549 	    buffer_len(&output));
550 	buffer_dump(&output);
551 #endif
552 
553 	buffer_clear(&outgoing_packet);
554 
555 	/*
556 	 * Note that the packet is now only buffered in output.  It won\'t be
557 	 * actually sent until packet_write_wait or packet_write_poll is
558 	 * called.
559 	 */
560 }
561 
562 void
563 set_newkeys(int mode)
564 {
565 	Enc *enc;
566 	Mac *mac;
567 	Comp *comp;
568 	CipherContext *cc;
569 	u_int64_t *max_blocks;
570 	int crypt_type;
571 
572 	debug2("set_newkeys: mode %d", mode);
573 
574 	if (mode == MODE_OUT) {
575 		cc = &send_context;
576 		crypt_type = CIPHER_ENCRYPT;
577 		p_send.packets = p_send.blocks = 0;
578 		max_blocks = &max_blocks_out;
579 	} else {
580 		cc = &receive_context;
581 		crypt_type = CIPHER_DECRYPT;
582 		p_read.packets = p_read.blocks = 0;
583 		max_blocks = &max_blocks_in;
584 	}
585 
586 	debug("set_newkeys: setting new keys for '%s' mode",
587 	    mode == MODE_IN ? "in" : "out");
588 
589 	if (newkeys[mode] != NULL) {
590 		cipher_cleanup(cc);
591 		free_keys(newkeys[mode]);
592 	}
593 
594 	newkeys[mode] = kex_get_newkeys(mode);
595 	if (newkeys[mode] == NULL)
596 		fatal("newkeys: no keys for mode %d", mode);
597 	enc  = &newkeys[mode]->enc;
598 	mac  = &newkeys[mode]->mac;
599 	comp = &newkeys[mode]->comp;
600 	if (mac_init(mac) == 0)
601 		mac->enabled = 1;
602 #ifdef	PACKET_DEBUG
603 	debug("new encryption key:\n");
604 	data_dump(enc->key, enc->key_len);
605 	debug("new encryption IV:\n");
606 	data_dump(enc->iv, enc->block_size);
607 	debug("new MAC key:\n");
608 	data_dump(mac->key, mac->key_len);
609 #endif
610 	cipher_init(cc, enc->cipher, enc->key, enc->key_len,
611 	    enc->iv, enc->block_size, crypt_type);
612 	/* Deleting the keys does not gain extra security */
613 	/* memset(enc->iv,  0, enc->block_size);
614 	   memset(enc->key, 0, enc->key_len); */
615 	if (comp->type != 0 && comp->enabled == 0) {
616 		packet_init_compression();
617 		if (mode == MODE_OUT)
618 			buffer_compress_init_send(6);
619 		else
620 			buffer_compress_init_recv();
621 		comp->enabled = 1;
622 	}
623 
624 	/*
625 	 * In accordance to the RFCs listed below we enforce the key
626 	 * re-exchange for:
627 	 *
628 	 * - every 1GB of transmitted data if the selected cipher block size
629 	 *   is less than 16 bytes (3DES, Blowfish)
630 	 * - every 2^(2*B) cipher blocks transmitted (B is block size in bytes)
631 	 *   if the cipher block size is greater than or equal to 16 bytes (AES)
632 	 * - and we never send more than 2^32 SSH packets using the same keys.
633 	 *   The recommendation of 2^31 packets is not enforced here but in
634 	 *   packet_need_rekeying(). There is also a hard check in
635 	 *   packet_send2_wrapped() that we don't send more than 2^32 packets.
636 	 *
637 	 * Note that if the SSH_BUG_NOREKEY compatibility flag is set then no
638 	 * automatic rekeying is performed nor do we enforce the 3rd rule.
639 	 * This means that we can be always forced by the opposite side to never
640 	 * initiate automatic key re-exchange. This might change in the future.
641 	 *
642 	 * The RekeyLimit option keyword may only enforce more frequent key
643 	 * renegotiation, never less. For more information on key renegotiation,
644 	 * see:
645 	 *
646 	 * - RFC 4253 (SSH Transport Layer Protocol), section "9. Key
647 	 *   Re-Exchange"
648 	 * - RFC 4344 (SSH Transport Layer Encryption Modes), sections "3.
649 	 *   Rekeying" and "6.1 Rekeying Considerations"
650 	 */
651 	if (enc->block_size >= 16)
652 		*max_blocks = (u_int64_t)1 << (enc->block_size * 2);
653 	else
654 		*max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
655 
656 	if (rekey_limit)
657 		*max_blocks = MIN(*max_blocks, rekey_limit / enc->block_size);
658 }
659 
660 void
661 free_keys(Newkeys *keys)
662 {
663 	Enc *enc;
664 	Mac *mac;
665 	Comp *comp;
666 
667 	enc  = &keys->enc;
668 	mac  = &keys->mac;
669 	comp = &keys->comp;
670 	xfree(enc->name);
671 	xfree(enc->iv);
672 	xfree(enc->key);
673 
674 	memset(mac->key, 0, mac->key_len);
675 	xfree(mac->key);
676 	xfree(mac->name);
677 	mac_clear(mac);
678 
679 	xfree(comp->name);
680 	xfree(keys);
681 }
682 
683 /*
684  * Process SSH2_MSG_NEWKEYS message. If we are using the engine we must have
685  * both SSH2_MSG_NEWKEYS processed before we can finish the engine, fork, and
686  * reinitialize the crypto contexts. We can't fork before processing the 2nd
687  * message otherwise we couldn't encrypt/decrypt that message at all - note that
688  * parent's PKCS#11 sessions are useless after the fork and we must process
689  * both SSH2_MSG_NEWKEYS messages using the old keys.
690  */
691 void
692 process_newkeys(int mode)
693 {
694 	/* this function is for the client only */
695 	if (packet_is_server() != 0)
696 		return;
697 
698 	if (will_daemonize == FIRST_NEWKEYS_PROCESSED) {
699 		debug3("both SSH2_MSG_NEWKEYS processed, will daemonize now");
700 		cipher_cleanup(&send_context);
701 		cipher_cleanup(&receive_context);
702 		pkcs11_engine_finish(e);
703 		if (daemon(1, 1) < 0) {
704 			fatal("daemon() failed: %.200s",
705 			    strerror(errno));
706 		}
707 		e = pkcs11_engine_load(e != NULL ? 1 : 0);
708 
709 		set_newkeys(MODE_OUT);
710 		set_newkeys(MODE_IN);
711 		will_daemonize = SECOND_NEWKEYS_PROCESSED;
712 		packet_send2();
713 	} else {
714 		if (will_daemonize == DAEMONIZING_REQUESTED)
715 			will_daemonize = FIRST_NEWKEYS_PROCESSED;
716 		else
717 			set_newkeys(mode);
718 	}
719 }
720 
721 /*
722  * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
723  */
724 static void
725 packet_send2_wrapped(void)
726 {
727 	u_char type, *cp, *macbuf = NULL;
728 	u_char padlen, pad;
729 	u_int packet_length = 0;
730 	u_int i, len;
731 	u_int32_t rnd = 0;
732 	Enc *enc   = NULL;
733 	Mac *mac   = NULL;
734 	Comp *comp = NULL;
735 	int block_size;
736 
737 	if (newkeys[MODE_OUT] != NULL) {
738 		enc  = &newkeys[MODE_OUT]->enc;
739 		mac  = &newkeys[MODE_OUT]->mac;
740 		comp = &newkeys[MODE_OUT]->comp;
741 	}
742 	block_size = enc ? enc->block_size : 8;
743 
744 	cp = buffer_ptr(&outgoing_packet);
745 	type = cp[5];
746 
747 #ifdef PACKET_DEBUG
748 	debug("plain output packet to be processed (%d bytes):\n",
749 	    buffer_len(&outgoing_packet));
750 	buffer_dump(&outgoing_packet);
751 #endif
752 
753 	if (comp && comp->enabled) {
754 		len = buffer_len(&outgoing_packet);
755 		/* skip header, compress only payload */
756 		buffer_consume(&outgoing_packet, 5);
757 		buffer_clear(&compression_buffer);
758 		buffer_compress(&outgoing_packet, &compression_buffer);
759 		buffer_clear(&outgoing_packet);
760 		buffer_append(&outgoing_packet, "\0\0\0\0\0", 5);
761 		buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
762 		    buffer_len(&compression_buffer));
763 		DBG(debug("compression: raw %d compressed %d", len,
764 		    buffer_len(&outgoing_packet)));
765 	}
766 
767 	/* sizeof (packet_len + pad_len + payload) */
768 	len = buffer_len(&outgoing_packet);
769 
770 	/*
771 	 * calc size of padding, alloc space, get random data,
772 	 * minimum padding is 4 bytes
773 	 */
774 	padlen = block_size - (len % block_size);
775 	if (padlen < 4)
776 		padlen += block_size;
777 	if (extra_pad) {
778 		/* will wrap if extra_pad+padlen > 255 */
779 		extra_pad  = roundup(extra_pad, block_size);
780 		pad = extra_pad - ((len + padlen) % extra_pad);
781 		debug3("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
782 		    pad, len, padlen, extra_pad);
783 		padlen += pad;
784 		extra_pad = 0;
785 	}
786 	cp = buffer_append_space(&outgoing_packet, padlen);
787 	if (enc && !send_context.plaintext) {
788 		/* random padding */
789 		for (i = 0; i < padlen; i++) {
790 			if (i % 4 == 0)
791 				rnd = arc4random();
792 			cp[i] = rnd & 0xff;
793 			rnd >>= 8;
794 		}
795 	} else {
796 		/* clear padding */
797 		memset(cp, 0, padlen);
798 	}
799 	/* packet_length includes payload, padding and padding length field */
800 	packet_length = buffer_len(&outgoing_packet) - 4;
801 	cp = buffer_ptr(&outgoing_packet);
802 	PUT_32BIT(cp, packet_length);
803 	cp[4] = padlen;
804 	DBG(debug("will send %d bytes (includes padlen %d)",
805 	    packet_length + 4, padlen));
806 
807 	/* compute MAC over seqnr and packet(length fields, payload, padding) */
808 	if (mac && mac->enabled) {
809 		macbuf = mac_compute(mac, p_send.seqnr,
810 		    buffer_ptr(&outgoing_packet),
811 		    buffer_len(&outgoing_packet));
812 		DBG(debug("done calc MAC out #%d", p_send.seqnr));
813 	}
814 	/* encrypt packet and append to output buffer. */
815 	cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
816 	cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
817 	    buffer_len(&outgoing_packet));
818 	/* append unencrypted MAC */
819 	if (mac && mac->enabled)
820 		buffer_append(&output, (char *)macbuf, mac->mac_len);
821 #ifdef PACKET_DEBUG
822 	debug("encrypted output queue now contains (%d bytes):\n",
823 	    buffer_len(&output));
824 	buffer_dump(&output);
825 #endif
826 	/* increment sequence number for outgoing packets */
827 	if (++p_send.seqnr == 0)
828 		log("outgoing seqnr wraps around");
829 
830 	/*
831 	 * RFC 4344: 3.1. First Rekeying Recommendation
832 	 *
833 	 * "Because of possible information leakage through the MAC tag after a
834 	 * key exchange, .... an SSH implementation SHOULD NOT send more than
835 	 * 2**32 packets before rekeying again."
836 	 *
837 	 * The code below is a hard check so that we are sure we don't go across
838 	 * the suggestion. However, since the largest cipher block size we have
839 	 * (AES) is 16 bytes we can't reach 2^32 SSH packets encrypted with the
840 	 * same key while performing periodic rekeying.
841 	 */
842 	if (++p_send.packets == 0)
843 		if (!(datafellows & SSH_BUG_NOREKEY))
844 			fatal("too many packets encrypted with same key");
845 	p_send.blocks += (packet_length + 4) / block_size;
846 	buffer_clear(&outgoing_packet);
847 
848 	if (type == SSH2_MSG_NEWKEYS) {
849 		/*
850 		 * set_newkeys(MODE_OUT) in the client. Note that in the
851 		 * unprivileged child, set_newkeys() for MODE_OUT are set after
852 		 * SSH2_MSG_NEWKEYS is read from the monitor and forwarded to
853 		 * the client side.
854 		 */
855 		process_newkeys(MODE_OUT);
856 	}
857 }
858 
859 /*
860  * Packets we deal with here are plain until we encrypt them in
861  * packet_send2_wrapped().
862  *
863  * As already mentioned in a comment at process_newkeys() function we must not
864  * fork() until both SSH2_MSG_NEWKEYS packets were processed. Until this is done
865  * we must queue all packets so that they can be encrypted with the new keys and
866  * then sent to the other side. However, what can happen here is that we get
867  * SSH2_MSG_NEWKEYS after we sent it. In that situation we must call
868  * packet_send2() anyway to empty the queue, and set the rekey flag to the
869  * finished state. If we didn't do that we would just hang and enqueue data.
870  */
871 static void
872 packet_send2(void)
873 {
874 	static int rekeying = 0;
875 	struct packet *p;
876 	u_char type, *cp;
877 
878 	if (will_daemonize != SECOND_NEWKEYS_PROCESSED) {
879 		cp = buffer_ptr(&outgoing_packet);
880 		type = cp[5];
881 
882 		/* during rekeying we can only send key exchange messages */
883 		if (rekeying) {
884 			if (!((type >= SSH2_MSG_TRANSPORT_MIN) &&
885 			    (type <= SSH2_MSG_TRANSPORT_MAX))) {
886 				debug("enqueue a plain packet because rekex in "
887 				    "progress [type %u]", type);
888 				p = xmalloc(sizeof(*p));
889 				p->type = type;
890 				memcpy(&p->payload, &outgoing_packet, sizeof(Buffer));
891 				buffer_init(&outgoing_packet);
892 				TAILQ_INSERT_TAIL(&outgoing, p, next);
893 				return;
894 			}
895 		}
896 
897 		/* rekeying starts with sending KEXINIT */
898 		if (type == SSH2_MSG_KEXINIT)
899 			rekeying = 1;
900 
901 		packet_send2_wrapped();
902 	}
903 
904 	/* after rekex is done we can process the queue of plain packets */
905 	if (will_daemonize == SECOND_NEWKEYS_PROCESSED ||
906 	    (will_daemonize == NOT_DAEMONIZING && type == SSH2_MSG_NEWKEYS)) {
907 		rekeying = 0;
908 		will_daemonize = NOT_DAEMONIZING;
909 		while ((p = TAILQ_FIRST(&outgoing)) != NULL) {
910 			type = p->type;
911 			debug("dequeuing a plain packet since rekex is over "
912 			    "[type %u]", type);
913 			buffer_free(&outgoing_packet);
914 			memcpy(&outgoing_packet, &p->payload, sizeof(Buffer));
915 			TAILQ_REMOVE(&outgoing, p, next);
916 			xfree(p);
917 			packet_send2_wrapped();
918 		}
919 	}
920 }
921 
922 void
923 packet_send(void)
924 {
925 	if (compat20)
926 		packet_send2();
927 	else
928 		packet_send1();
929 	DBG(debug("packet_send done"));
930 }
931 
932 /*
933  * Waits until a packet has been received, and returns its type.  Note that
934  * no other data is processed until this returns, so this function should not
935  * be used during the interactive session.
936  *
937  * The function is also used in the monitor to read the authentication context
938  * in aps_read_auth_context() via packet_read_seqnr(), before the monitor enters
939  * aps_monitor_loop() and starts using the process_input() function.
940  */
941 int
942 packet_read_seqnr(u_int32_t *seqnr_p)
943 {
944 	int type, len;
945 	fd_set *setp;
946 	char buf[8192];
947 	DBG(debug("packet_read()"));
948 
949 	setp = (fd_set *)xmalloc(howmany(connection_in+1, NFDBITS) *
950 	    sizeof(fd_mask));
951 
952 	/* Since we are blocking, ensure that all written packets have been sent. */
953 	packet_write_wait();
954 
955 	/* Stay in the loop until we have received a complete packet. */
956 	for (;;) {
957 		/* Try to read a packet from the buffer. */
958 		type = packet_read_poll_seqnr(seqnr_p);
959 		if (!compat20 && (
960 		    type == SSH_SMSG_SUCCESS
961 		    || type == SSH_SMSG_FAILURE
962 		    || type == SSH_CMSG_EOF
963 		    || type == SSH_CMSG_EXIT_CONFIRMATION))
964 			packet_check_eom();
965 		/* If we got a packet, return it. */
966 		if (type != SSH_MSG_NONE) {
967 			xfree(setp);
968 			return type;
969 		}
970 		/*
971 		 * Otherwise, wait for some data to arrive, add it to the
972 		 * buffer, and try again.
973 		 */
974 		memset(setp, 0, howmany(connection_in + 1, NFDBITS) *
975 		    sizeof(fd_mask));
976 		FD_SET(connection_in, setp);
977 
978 		/* Wait for some data to arrive. */
979 		while (select(connection_in + 1, setp, NULL, NULL, NULL) == -1 &&
980 		    (errno == EAGAIN || errno == EINTR))
981 			;
982 
983 		/* Read data from the socket. */
984 		len = read(connection_in, buf, sizeof(buf));
985 		if (len == 0) {
986 			if (packet_connection_is_on_socket())
987 				log("Connection closed by %.200s",
988 				    get_remote_ipaddr());
989 			else
990 				debug("child closed the communication pipe "
991 				    "before user auth was finished");
992 			fatal_cleanup();
993 		}
994 		if (len < 0) {
995 			if (packet_connection_is_on_socket())
996 				fatal("Read from socket failed: %.100s",
997 				    strerror(errno));
998 			else
999 				fatal("Read from communication pipe failed: "
1000 				    "%.100s", strerror(errno));
1001 		}
1002 		/* Append it to the buffer. */
1003 		packet_process_incoming(buf, len);
1004 	}
1005 	/* NOTREACHED */
1006 }
1007 
1008 int
1009 packet_read(void)
1010 {
1011 	return packet_read_seqnr(NULL);
1012 }
1013 
1014 /*
1015  * Waits until a packet has been received, verifies that its type matches
1016  * that given, and gives a fatal error and exits if there is a mismatch.
1017  */
1018 
1019 void
1020 packet_read_expect(int expected_type)
1021 {
1022 	int type;
1023 
1024 	type = packet_read();
1025 	if (type != expected_type)
1026 		packet_disconnect("Protocol error: expected packet type %d, got %d",
1027 		    expected_type, type);
1028 }
1029 
1030 /* Checks if a full packet is available in the data received so far via
1031  * packet_process_incoming.  If so, reads the packet; otherwise returns
1032  * SSH_MSG_NONE.  This does not wait for data from the connection.
1033  *
1034  * SSH_MSG_DISCONNECT is handled specially here.  Also,
1035  * SSH_MSG_IGNORE messages are skipped by this function and are never returned
1036  * to higher levels.
1037  */
1038 
1039 static int
1040 packet_read_poll1(void)
1041 {
1042 	u_int len, padded_len;
1043 	u_char *cp, type;
1044 	u_int checksum, stored_checksum;
1045 
1046 	/* Check if input size is less than minimum packet size. */
1047 	if (buffer_len(&input) < 4 + 8)
1048 		return SSH_MSG_NONE;
1049 	/* Get length of incoming packet. */
1050 	cp = buffer_ptr(&input);
1051 	len = GET_32BIT(cp);
1052 	if (len < 1 + 2 + 2 || len > 256 * 1024)
1053 		packet_disconnect("Bad packet length %d.", len);
1054 	padded_len = (len + 8) & ~7;
1055 
1056 	/* Check if the packet has been entirely received. */
1057 	if (buffer_len(&input) < 4 + padded_len)
1058 		return SSH_MSG_NONE;
1059 
1060 	/* The entire packet is in buffer. */
1061 
1062 	/* Consume packet length. */
1063 	buffer_consume(&input, 4);
1064 
1065 	/*
1066 	 * Cryptographic attack detector for ssh
1067 	 * (C)1998 CORE-SDI, Buenos Aires Argentina
1068 	 * Ariel Futoransky(futo@core-sdi.com)
1069 	 */
1070 	if (!receive_context.plaintext) {
1071 		switch (detect_attack(buffer_ptr(&input), padded_len, NULL)) {
1072 		case DEATTACK_DETECTED:
1073 			packet_disconnect("crc32 compensation attack: "
1074 			    "network attack detected");
1075 			break;
1076 		case DEATTACK_DOS_DETECTED:
1077 			packet_disconnect("deattack denial of "
1078 			    "service detected");
1079 			break;
1080 		}
1081 	}
1082 
1083 	/* Decrypt data to incoming_packet. */
1084 	buffer_clear(&incoming_packet);
1085 	cp = buffer_append_space(&incoming_packet, padded_len);
1086 	cipher_crypt(&receive_context, cp, buffer_ptr(&input), padded_len);
1087 
1088 	buffer_consume(&input, padded_len);
1089 
1090 #ifdef PACKET_DEBUG
1091 	debug("read_poll plain/full:\n");
1092 	buffer_dump(&incoming_packet);
1093 #endif
1094 
1095 	/* Compute packet checksum. */
1096 	checksum = ssh_crc32(buffer_ptr(&incoming_packet),
1097 	    buffer_len(&incoming_packet) - 4);
1098 
1099 	/* Skip padding. */
1100 	buffer_consume(&incoming_packet, 8 - len % 8);
1101 
1102 	/* Test check bytes. */
1103 	if (len != buffer_len(&incoming_packet))
1104 		packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
1105 		    len, buffer_len(&incoming_packet));
1106 
1107 	cp = (u_char *)buffer_ptr(&incoming_packet) + len - 4;
1108 	stored_checksum = GET_32BIT(cp);
1109 	if (checksum != stored_checksum)
1110 		packet_disconnect("Corrupted check bytes on input.");
1111 	buffer_consume_end(&incoming_packet, 4);
1112 
1113 	if (packet_compression) {
1114 		buffer_clear(&compression_buffer);
1115 		buffer_uncompress(&incoming_packet, &compression_buffer);
1116 		buffer_clear(&incoming_packet);
1117 		buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
1118 		    buffer_len(&compression_buffer));
1119 	}
1120 	type = buffer_get_char(&incoming_packet);
1121 	return type;
1122 }
1123 
1124 static int
1125 packet_read_poll2(u_int32_t *seqnr_p)
1126 {
1127 	static u_int packet_length = 0;
1128 	u_int padlen, need;
1129 	u_char *macbuf, *cp, type;
1130 	int maclen, block_size;
1131 	Enc *enc   = NULL;
1132 	Mac *mac   = NULL;
1133 	Comp *comp = NULL;
1134 
1135 	if (newkeys[MODE_IN] != NULL) {
1136 		enc  = &newkeys[MODE_IN]->enc;
1137 		mac  = &newkeys[MODE_IN]->mac;
1138 		comp = &newkeys[MODE_IN]->comp;
1139 	}
1140 	maclen = mac && mac->enabled ? mac->mac_len : 0;
1141 	block_size = enc ? enc->block_size : 8;
1142 
1143 	if (packet_length == 0) {
1144 		/*
1145 		 * check if input size is less than the cipher block size,
1146 		 * decrypt first block and extract length of incoming packet
1147 		 */
1148 		if (buffer_len(&input) < block_size)
1149 			return SSH_MSG_NONE;
1150 #ifdef PACKET_DEBUG
1151 		debug("encrypted data we have in read queue (%d bytes):\n",
1152 		    buffer_len(&input));
1153 		buffer_dump(&input);
1154 #endif
1155 		buffer_clear(&incoming_packet);
1156 		cp = buffer_append_space(&incoming_packet, block_size);
1157 		cipher_crypt(&receive_context, cp, buffer_ptr(&input),
1158 		    block_size);
1159 		cp = buffer_ptr(&incoming_packet);
1160 		packet_length = GET_32BIT(cp);
1161 		if (packet_length < 1 + 4 || packet_length > 256 * 1024) {
1162 			packet_disconnect("Bad packet length.");
1163 		}
1164 		DBG(debug("input: packet len %u", packet_length + 4));
1165 		buffer_consume(&input, block_size);
1166 	}
1167 	/* we have a partial packet of block_size bytes */
1168 	need = 4 + packet_length - block_size;
1169 	DBG(debug("partial packet %d, still need %d, maclen %d", block_size,
1170 	    need, maclen));
1171 	if (need % block_size != 0)
1172 		packet_disconnect("Bad packet length.");
1173 	/*
1174 	 * check if the entire packet has been received and
1175 	 * decrypt into incoming_packet
1176 	 */
1177 	if (buffer_len(&input) < need + maclen)
1178 		return SSH_MSG_NONE;
1179 #ifdef PACKET_DEBUG
1180 	debug("in read_poll, the encrypted input queue now contains "
1181 	    "(%d bytes):\n", buffer_len(&input));
1182 	buffer_dump(&input);
1183 #endif
1184 	cp = buffer_append_space(&incoming_packet, need);
1185 	cipher_crypt(&receive_context, cp, buffer_ptr(&input), need);
1186 	buffer_consume(&input, need);
1187 	/*
1188 	 * compute MAC over seqnr and packet,
1189 	 * increment sequence number for incoming packet
1190 	 */
1191 	if (mac && mac->enabled) {
1192 		macbuf = mac_compute(mac, p_read.seqnr,
1193 		    buffer_ptr(&incoming_packet),
1194 		    buffer_len(&incoming_packet));
1195 		if (memcmp(macbuf, buffer_ptr(&input), mac->mac_len) != 0)
1196 			packet_disconnect("Corrupted MAC on input.");
1197 		DBG(debug("MAC #%d ok", p_read.seqnr));
1198 		buffer_consume(&input, mac->mac_len);
1199 	}
1200 	if (seqnr_p != NULL)
1201 		*seqnr_p = p_read.seqnr;
1202 	if (++p_read.seqnr == 0)
1203 		log("incoming seqnr wraps around");
1204 
1205 	/* see above for the comment on "First Rekeying Recommendation" */
1206 	if (++p_read.packets == 0)
1207 		if (!(datafellows & SSH_BUG_NOREKEY))
1208 			fatal("too many packets with same key");
1209 	p_read.blocks += (packet_length + 4) / block_size;
1210 
1211 	/* get padlen */
1212 	cp = buffer_ptr(&incoming_packet);
1213 	padlen = cp[4];
1214 	DBG(debug("input: padlen %d", padlen));
1215 	if (padlen < 4)
1216 		packet_disconnect("Corrupted padlen %d on input.", padlen);
1217 
1218 	/* skip packet size + padlen, discard padding */
1219 	buffer_consume(&incoming_packet, 4 + 1);
1220 	buffer_consume_end(&incoming_packet, padlen);
1221 
1222 	DBG(debug("input: len before de-compress %d", buffer_len(&incoming_packet)));
1223 	if (comp && comp->enabled) {
1224 		buffer_clear(&compression_buffer);
1225 		buffer_uncompress(&incoming_packet, &compression_buffer);
1226 		buffer_clear(&incoming_packet);
1227 		buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
1228 		    buffer_len(&compression_buffer));
1229 		DBG(debug("input: len after de-compress %d",
1230 		    buffer_len(&incoming_packet)));
1231 	}
1232 	/*
1233 	 * get packet type, implies consume.
1234 	 * return length of payload (without type field)
1235 	 */
1236 	type = buffer_get_char(&incoming_packet);
1237 	if (type == SSH2_MSG_NEWKEYS) {
1238 		/*
1239 		 * set_newkeys(MODE_IN) in the client because it doesn't have a
1240 		 * dispatch function for SSH2_MSG_NEWKEYS in contrast to the
1241 		 * server processes. Note that in the unprivileged child,
1242 		 * set_newkeys() for MODE_IN are set in dispatch function
1243 		 * altprivsep_rekey() after SSH2_MSG_NEWKEYS packet is received
1244 		 * from the client.
1245 		 */
1246 		process_newkeys(MODE_IN);
1247 	}
1248 
1249 #ifdef PACKET_DEBUG
1250 	debug("decrypted input packet [type %d]:\n", type);
1251 	buffer_dump(&incoming_packet);
1252 #endif
1253 	/* reset for next packet */
1254 	packet_length = 0;
1255 	return type;
1256 }
1257 
1258 /*
1259  * This tries to read a packet from the buffer of received data. Note that it
1260  * doesn't read() anything from the network socket.
1261  */
1262 int
1263 packet_read_poll_seqnr(u_int32_t *seqnr_p)
1264 {
1265 	u_int reason, seqnr;
1266 	u_char type;
1267 	char *msg;
1268 
1269 	for (;;) {
1270 		if (compat20) {
1271 			type = packet_read_poll2(seqnr_p);
1272 			DBG(debug("received packet type %d", type));
1273 			switch (type) {
1274 			case SSH2_MSG_IGNORE:
1275 				break;
1276 			case SSH2_MSG_DEBUG:
1277 				packet_get_char();
1278 				msg = packet_get_utf8_string(NULL);
1279 				msg = g11n_filter_string(msg);
1280 				debug("Remote: %.900s", msg);
1281 				xfree(msg);
1282 				msg = packet_get_string(NULL);
1283 				xfree(msg);
1284 				break;
1285 			case SSH2_MSG_DISCONNECT:
1286 				reason = packet_get_int();
1287 				msg = packet_get_utf8_string(NULL);
1288 				msg = g11n_filter_string(msg);
1289 				log("Received disconnect from %s: %u: %.400s",
1290 				    get_remote_ipaddr(), reason, msg);
1291 				xfree(msg);
1292 				fatal_cleanup();
1293 				break;
1294 			case SSH2_MSG_UNIMPLEMENTED:
1295 				seqnr = packet_get_int();
1296 				debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1297 				    seqnr);
1298 				break;
1299 			default:
1300 				return type;
1301 				break;
1302 			}
1303 		} else {
1304 			type = packet_read_poll1();
1305 			DBG(debug("received packet type %d", type));
1306 			switch (type) {
1307 			case SSH_MSG_IGNORE:
1308 				break;
1309 			case SSH_MSG_DEBUG:
1310 				msg = packet_get_string(NULL);
1311 				debug("Remote: %.900s", msg);
1312 				xfree(msg);
1313 				break;
1314 			case SSH_MSG_DISCONNECT:
1315 				msg = packet_get_string(NULL);
1316 				log("Received disconnect from %s: %.400s",
1317 				    get_remote_ipaddr(), msg);
1318 				fatal_cleanup();
1319 				xfree(msg);
1320 				break;
1321 			default:
1322 				return type;
1323 				break;
1324 			}
1325 		}
1326 	}
1327 }
1328 
1329 int
1330 packet_read_poll(void)
1331 {
1332 	return packet_read_poll_seqnr(NULL);
1333 }
1334 
1335 /*
1336  * Buffers the given amount of input characters.  This is intended to be used
1337  * together with packet_read_poll.
1338  */
1339 
1340 void
1341 packet_process_incoming(const char *buf, u_int len)
1342 {
1343 	buffer_append(&input, buf, len);
1344 }
1345 
1346 /* Returns a character from the packet. */
1347 
1348 u_int
1349 packet_get_char(void)
1350 {
1351 	char ch;
1352 
1353 	buffer_get(&incoming_packet, &ch, 1);
1354 	return (u_char) ch;
1355 }
1356 
1357 /* Returns an integer from the packet data. */
1358 
1359 u_int
1360 packet_get_int(void)
1361 {
1362 	return buffer_get_int(&incoming_packet);
1363 }
1364 
1365 /*
1366  * Returns an arbitrary precision integer from the packet data.  The integer
1367  * must have been initialized before this call.
1368  */
1369 
1370 void
1371 packet_get_bignum(BIGNUM * value)
1372 {
1373 	buffer_get_bignum(&incoming_packet, value);
1374 }
1375 
1376 void
1377 packet_get_bignum2(BIGNUM * value)
1378 {
1379 	buffer_get_bignum2(&incoming_packet, value);
1380 }
1381 
1382 void *
1383 packet_get_raw(u_int *length_ptr)
1384 {
1385 	u_int bytes = buffer_len(&incoming_packet);
1386 
1387 	if (length_ptr != NULL)
1388 		*length_ptr = bytes;
1389 	return buffer_ptr(&incoming_packet);
1390 }
1391 
1392 int
1393 packet_remaining(void)
1394 {
1395 	return buffer_len(&incoming_packet);
1396 }
1397 
1398 /*
1399  * Returns a string from the packet data.  The string is allocated using
1400  * xmalloc; it is the responsibility of the calling program to free it when
1401  * no longer needed.  The length_ptr argument may be NULL, or point to an
1402  * integer into which the length of the string is stored.
1403  */
1404 
1405 void *
1406 packet_get_string(u_int *length_ptr)
1407 {
1408 	return buffer_get_string(&incoming_packet, length_ptr);
1409 }
1410 
1411 char *
1412 packet_get_utf8_string(uint_t *length_ptr)
1413 {
1414 	if (datafellows & SSH_BUG_STRING_ENCODING)
1415 		return (buffer_get_string(&incoming_packet, length_ptr));
1416 	else
1417 		return (buffer_get_utf8_string(&incoming_packet, length_ptr));
1418 }
1419 
1420 /*
1421  * Sends a diagnostic message from the server to the client.  This message
1422  * can be sent at any time (but not while constructing another message). The
1423  * message is printed immediately, but only if the client is being executed
1424  * in verbose mode.  These messages are primarily intended to ease debugging
1425  * authentication problems.   The length of the formatted message must not
1426  * exceed 1024 bytes.  This will automatically call packet_write_wait.
1427  */
1428 
1429 void
1430 packet_send_debug(const char *fmt,...)
1431 {
1432 	char buf[1024];
1433 	va_list args;
1434 
1435 	if (compat20 && (datafellows & SSH_BUG_DEBUG))
1436 		return;
1437 
1438 	va_start(args, fmt);
1439 	vsnprintf(buf, sizeof(buf), gettext(fmt), args);
1440 	va_end(args);
1441 
1442 #ifdef ALTPRIVSEP
1443 	/* shouldn't happen */
1444 	if (packet_monitor) {
1445 		debug("packet_send_debug: %s", buf);
1446 		return;
1447 	}
1448 #endif /* ALTPRIVSEP */
1449 
1450 	if (compat20) {
1451 		packet_start(SSH2_MSG_DEBUG);
1452 		packet_put_char(0);	/* bool: always display */
1453 		packet_put_utf8_cstring(buf);
1454 		packet_put_cstring("");
1455 	} else {
1456 		packet_start(SSH_MSG_DEBUG);
1457 		packet_put_cstring(buf);
1458 	}
1459 	packet_send();
1460 	packet_write_wait();
1461 }
1462 
1463 /*
1464  * Logs the error plus constructs and sends a disconnect packet, closes the
1465  * connection, and exits.  This function never returns. The error message
1466  * should not contain a newline.  The length of the formatted message must
1467  * not exceed 1024 bytes.
1468  */
1469 
1470 void
1471 packet_disconnect(const char *fmt,...)
1472 {
1473 	char buf[1024];
1474 	va_list args;
1475 	static int disconnecting = 0;
1476 
1477 	if (disconnecting)	/* Guard against recursive invocations. */
1478 		fatal("packet_disconnect called recursively.");
1479 	disconnecting = 1;
1480 
1481 	/*
1482 	 * Format the message.  Note that the caller must make sure the
1483 	 * message is of limited size.
1484 	 */
1485 	va_start(args, fmt);
1486 	vsnprintf(buf, sizeof(buf), fmt, args);
1487 	va_end(args);
1488 
1489 #ifdef ALTPRIVSEP
1490 	/*
1491 	 * If we packet_disconnect() in the monitor the fatal cleanups will take
1492 	 * care of the child.  See main() in sshd.c.  We don't send the packet
1493 	 * disconnect message here because: a) the child might not be looking
1494 	 * for it and b) because we don't really know if the child is compat20
1495 	 * or not as we lost that information when packet_set_monitor() was
1496 	 * called.
1497 	 */
1498 	if (packet_monitor)
1499 		goto close_stuff;
1500 #endif /* ALTPRIVSEP */
1501 
1502 	/* Send the disconnect message to the other side, and wait for it to get sent. */
1503 	if (compat20) {
1504 		packet_start(SSH2_MSG_DISCONNECT);
1505 		packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1506 		packet_put_utf8_cstring(buf);
1507 		packet_put_cstring("");
1508 	} else {
1509 		packet_start(SSH_MSG_DISCONNECT);
1510 		packet_put_cstring(buf);
1511 	}
1512 	packet_send();
1513 	packet_write_wait();
1514 
1515 #ifdef ALTPRIVSEP
1516 close_stuff:
1517 #endif /* ALTPRIVSEP */
1518 	/* Stop listening for connections. */
1519 	channel_close_all();
1520 
1521 	/* Close the connection. */
1522 	packet_close();
1523 
1524 	/* Display the error locally and exit. */
1525 	log("Disconnecting: %.100s", buf);
1526 	fatal_cleanup();
1527 }
1528 
1529 /* Checks if there is any buffered output, and tries to write some of the output. */
1530 
1531 void
1532 packet_write_poll(void)
1533 {
1534 	int len = buffer_len(&output);
1535 
1536 	if (len > 0) {
1537 		len = write(connection_out, buffer_ptr(&output), len);
1538 		if (len <= 0) {
1539 			if (errno == EAGAIN)
1540 				return;
1541 			else
1542 				fatal("Write failed: %.100s", strerror(errno));
1543 		}
1544 #ifdef PACKET_DEBUG
1545 		debug("in packet_write_poll, %d bytes just sent to the "
1546 		    "remote side", len);
1547 #endif
1548 		buffer_consume(&output, len);
1549 	}
1550 }
1551 
1552 /*
1553  * Calls packet_write_poll repeatedly until all pending output data has been
1554  * written.
1555  */
1556 
1557 void
1558 packet_write_wait(void)
1559 {
1560 	fd_set *setp;
1561 
1562 	setp = (fd_set *)xmalloc(howmany(connection_out + 1, NFDBITS) *
1563 	    sizeof(fd_mask));
1564 	packet_write_poll();
1565 	while (packet_have_data_to_write()) {
1566 		memset(setp, 0, howmany(connection_out + 1, NFDBITS) *
1567 		    sizeof(fd_mask));
1568 		FD_SET(connection_out, setp);
1569 		while (select(connection_out + 1, NULL, setp, NULL, NULL) == -1 &&
1570 		    (errno == EAGAIN || errno == EINTR))
1571 			;
1572 		packet_write_poll();
1573 	}
1574 	xfree(setp);
1575 }
1576 
1577 /* Returns true if there is buffered data to write to the connection. */
1578 
1579 int
1580 packet_have_data_to_write(void)
1581 {
1582 	return buffer_len(&output) != 0;
1583 }
1584 
1585 /* Returns true if there is not too much data to write to the connection. */
1586 
1587 int
1588 packet_not_very_much_data_to_write(void)
1589 {
1590 	if (interactive_mode)
1591 		return buffer_len(&output) < 16384;
1592 	else
1593 		return buffer_len(&output) < 128 * 1024;
1594 }
1595 
1596 /* Informs that the current session is interactive.  Sets IP flags for that. */
1597 
1598 void
1599 packet_set_interactive(int interactive)
1600 {
1601 	static int called = 0;
1602 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1603 	int lowdelay = IPTOS_LOWDELAY;
1604 	int throughput = IPTOS_THROUGHPUT;
1605 #endif
1606 
1607 	if (called)
1608 		return;
1609 	called = 1;
1610 
1611 	/* Record that we are in interactive mode. */
1612 	interactive_mode = interactive;
1613 
1614 	/* Only set socket options if using a socket.  */
1615 	if (!packet_connection_is_on_socket())
1616 		return;
1617 	/*
1618 	 * IPTOS_LOWDELAY and IPTOS_THROUGHPUT are IPv4 only
1619 	 */
1620 	if (interactive) {
1621 		/*
1622 		 * Set IP options for an interactive connection.  Use
1623 		 * IPTOS_LOWDELAY and TCP_NODELAY.
1624 		 */
1625 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1626 		if (packet_connection_is_ipv4()) {
1627 			if (setsockopt(connection_in, IPPROTO_IP, IP_TOS,
1628 			    &lowdelay, sizeof(lowdelay)) < 0)
1629 				error("setsockopt IPTOS_LOWDELAY: %.100s",
1630 				    strerror(errno));
1631 		}
1632 #endif
1633 		set_nodelay(connection_in);
1634 	}
1635 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1636 	else if (packet_connection_is_ipv4()) {
1637 		/*
1638 		 * Set IP options for a non-interactive connection.  Use
1639 		 * IPTOS_THROUGHPUT.
1640 		 */
1641 		if (setsockopt(connection_in, IPPROTO_IP, IP_TOS, &throughput,
1642 		    sizeof(throughput)) < 0)
1643 			error("setsockopt IPTOS_THROUGHPUT: %.100s", strerror(errno));
1644 	}
1645 #endif
1646 }
1647 
1648 /* Returns true if the current connection is interactive. */
1649 
1650 int
1651 packet_is_interactive(void)
1652 {
1653 	return interactive_mode;
1654 }
1655 
1656 int
1657 packet_set_maxsize(int s)
1658 {
1659 	static int called = 0;
1660 
1661 	if (called) {
1662 		log("packet_set_maxsize: called twice: old %d new %d",
1663 		    max_packet_size, s);
1664 		return -1;
1665 	}
1666 	if (s < 4 * 1024 || s > 1024 * 1024) {
1667 		log("packet_set_maxsize: bad size %d", s);
1668 		return -1;
1669 	}
1670 	called = 1;
1671 	debug("packet_set_maxsize: setting to %d", s);
1672 	max_packet_size = s;
1673 	return s;
1674 }
1675 
1676 /* roundup current message to pad bytes */
1677 void
1678 packet_add_padding(u_char pad)
1679 {
1680 	extra_pad = pad;
1681 }
1682 
1683 /*
1684  * 9.2.  Ignored Data Message
1685  *
1686  *   byte      SSH_MSG_IGNORE
1687  *   string    data
1688  *
1689  * All implementations MUST understand (and ignore) this message at any
1690  * time (after receiving the protocol version). No implementation is
1691  * required to send them. This message can be used as an additional
1692  * protection measure against advanced traffic analysis techniques.
1693  */
1694 void
1695 packet_send_ignore(int nbytes)
1696 {
1697 	u_int32_t rnd = 0;
1698 	int i;
1699 
1700 #ifdef ALTPRIVSEP
1701 	/* shouldn't happen -- see packet_set_monitor() */
1702 	if (packet_monitor)
1703 		return;
1704 #endif /* ALTPRIVSEP */
1705 
1706 	packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1707 	packet_put_int(nbytes);
1708 	for (i = 0; i < nbytes; i++) {
1709 		if (i % 4 == 0)
1710 			rnd = arc4random();
1711 		packet_put_char((u_char)rnd & 0xff);
1712 		rnd >>= 8;
1713 	}
1714 }
1715 
1716 #define MAX_PACKETS	(1U<<31)
1717 int
1718 packet_need_rekeying(void)
1719 {
1720 	if (datafellows & SSH_BUG_NOREKEY)
1721 		return 0;
1722 	return
1723 	    (p_send.packets > MAX_PACKETS) ||
1724 	    (p_read.packets > MAX_PACKETS) ||
1725 	    (max_blocks_out && (p_send.blocks > max_blocks_out)) ||
1726 	    (max_blocks_in  && (p_read.blocks > max_blocks_in));
1727 }
1728 
1729 void
1730 packet_set_rekey_limit(u_int32_t bytes)
1731 {
1732 	rekey_limit = bytes;
1733 }
1734 
1735 #ifdef ALTPRIVSEP
1736 void
1737 packet_set_server(void)
1738 {
1739 	packet_server = 1;
1740 }
1741 
1742 int
1743 packet_is_server(void)
1744 {
1745 	return (packet_server);
1746 }
1747 
1748 void
1749 packet_set_monitor(int pipe)
1750 {
1751 	int dup_fd;
1752 
1753 	packet_server = 1;
1754 	packet_monitor = 1;
1755 
1756 	/*
1757 	 * Awful hack follows.
1758 	 *
1759 	 * For SSHv1 the monitor does not process any SSHv1 packets, only
1760 	 * ALTPRIVSEP packets.  We take advantage of that here to keep changes
1761 	 * to packet.c to a minimum by using the SSHv2 binary packet protocol,
1762 	 * with cipher "none," mac "none" and compression alg "none," as the
1763 	 * basis for the monitor protocol.  And so to force packet.c to treat
1764 	 * packets as SSHv2 we force compat20 == 1 here.
1765 	 *
1766 	 * For completeness and to help future developers catch this we also
1767 	 * force compat20 == 1 in the monitor loop, in serverloop.c.
1768 	 */
1769 	compat20 = 1;
1770 
1771 	/*
1772 	 * NOTE:  Assumptions below!
1773 	 *
1774 	 *  - lots of packet.c code assumes that (connection_in ==
1775 	 *  connection_out) -> connection is socket
1776 	 *
1777 	 *  - packet_close() does not shutdown() the connection fildes
1778 	 *  if connection_in != connection_out
1779 	 *
1780 	 *  - other code assumes the connection is a socket if
1781 	 *  connection_in == connection_out
1782 	 */
1783 
1784 	if ((dup_fd = dup(pipe)) < 0)
1785 		fatal("Monitor failed to start: %s", strerror(errno));
1786 
1787 	/*
1788 	 * make sure that the monitor's child's socket is not shutdown(3SOCKET)
1789 	 * when we packet_close(). Setting connection_out to -1 will take care
1790 	 * of that.
1791 	 */
1792 	if (packet_connection_is_on_socket())
1793 		connection_out = -1;
1794 
1795 	/*
1796 	 * Now clean up the state related to the server socket. As a side
1797 	 * effect, we also clean up existing cipher contexts that were
1798 	 * initialized with 'none' cipher in packet_set_connection(). That
1799 	 * function was called in the child server process shortly after the
1800 	 * master SSH process forked. However, all of that is reinialized again
1801 	 * by another packet_set_connection() call right below.
1802 	 */
1803 	packet_close();
1804 
1805 	/*
1806 	 * Now make the monitor pipe look like the ssh connection which means
1807 	 * that connection_in and connection_out will be set to the
1808 	 * communication pipe descriptors.
1809 	 */
1810 	packet_set_connection(pipe, dup_fd);
1811 }
1812 
1813 /*
1814  * We temporarily need to set connection_in and connection_out descriptors so
1815  * that we can make use of existing code that gets the IP address and hostname
1816  * of the peer to write a login/logout record. It's not nice but we would have
1817  * to change more code when implementing the PKCS#11 engine support.
1818  */
1819 void
1820 packet_set_fds(int fd, int restore)
1821 {
1822 	static int stored_fd;
1823 
1824 	if (stored_fd == 0 && restore == 0) {
1825 		debug3("packet_set_fds: saving %d, installing %d",
1826 		    connection_in, fd);
1827 		stored_fd = connection_in;
1828 		/* we don't have a socket in inetd mode */
1829 		if (fd != -1)
1830 			connection_in = connection_out = fd;
1831 		return;
1832 	}
1833 
1834 	if (restore == 1) {
1835 		debug3("restoring %d to connection_in/out", stored_fd);
1836 		connection_in = connection_out = stored_fd;
1837 	}
1838 }
1839 
1840 int
1841 packet_is_monitor(void)
1842 {
1843 	return (packet_monitor);
1844 }
1845 #endif /* ALTPRIVSEP */
1846