xref: /freebsd/crypto/openssh/packet.c (revision 09e8dea79366f1e5b3a73e8a271b26e4b6bf2e6a)
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 #include "includes.h"
40 RCSID("$OpenBSD: packet.c,v 1.95 2002/06/19 18:01:00 markus Exp $");
41 
42 #include "xmalloc.h"
43 #include "buffer.h"
44 #include "packet.h"
45 #include "bufaux.h"
46 #include "crc32.h"
47 #include "getput.h"
48 
49 #include "compress.h"
50 #include "deattack.h"
51 #include "channels.h"
52 
53 #include "compat.h"
54 #include "ssh1.h"
55 #include "ssh2.h"
56 
57 #include "cipher.h"
58 #include "kex.h"
59 #include "mac.h"
60 #include "log.h"
61 #include "canohost.h"
62 #include "misc.h"
63 #include "ssh.h"
64 
65 #ifdef PACKET_DEBUG
66 #define DBG(x) x
67 #else
68 #define DBG(x)
69 #endif
70 
71 /*
72  * This variable contains the file descriptors used for communicating with
73  * the other side.  connection_in is used for reading; connection_out for
74  * writing.  These can be the same descriptor, in which case it is assumed to
75  * be a socket.
76  */
77 static int connection_in = -1;
78 static int connection_out = -1;
79 
80 /* Protocol flags for the remote side. */
81 static u_int remote_protocol_flags = 0;
82 
83 /* Encryption context for receiving data.  This is only used for decryption. */
84 static CipherContext receive_context;
85 
86 /* Encryption context for sending data.  This is only used for encryption. */
87 static CipherContext send_context;
88 
89 /* Buffer for raw input data from the socket. */
90 Buffer input;
91 
92 /* Buffer for raw output data going to the socket. */
93 Buffer output;
94 
95 /* Buffer for the partial outgoing packet being constructed. */
96 static Buffer outgoing_packet;
97 
98 /* Buffer for the incoming packet currently being processed. */
99 static Buffer incoming_packet;
100 
101 /* Scratch buffer for packet compression/decompression. */
102 static Buffer compression_buffer;
103 static int compression_buffer_ready = 0;
104 
105 /* Flag indicating whether packet compression/decompression is enabled. */
106 static int packet_compression = 0;
107 
108 /* default maximum packet size */
109 int max_packet_size = 32768;
110 
111 /* Flag indicating whether this module has been initialized. */
112 static int initialized = 0;
113 
114 /* Set to true if the connection is interactive. */
115 static int interactive_mode = 0;
116 
117 /* Session key information for Encryption and MAC */
118 Newkeys *newkeys[MODE_MAX];
119 static u_int32_t read_seqnr = 0;
120 static u_int32_t send_seqnr = 0;
121 
122 /* Session key for protocol v1 */
123 static u_char ssh1_key[SSH_SESSION_KEY_LENGTH];
124 static u_int ssh1_keylen;
125 
126 /* roundup current message to extra_pad bytes */
127 static u_char extra_pad = 0;
128 
129 /*
130  * Sets the descriptors used for communication.  Disables encryption until
131  * packet_set_encryption_key is called.
132  */
133 void
134 packet_set_connection(int fd_in, int fd_out)
135 {
136 	Cipher *none = cipher_by_name("none");
137 	if (none == NULL)
138 		fatal("packet_set_connection: cannot load cipher 'none'");
139 	connection_in = fd_in;
140 	connection_out = fd_out;
141 	cipher_init(&send_context, none, "", 0, NULL, 0, CIPHER_ENCRYPT);
142 	cipher_init(&receive_context, none, "", 0, NULL, 0, CIPHER_DECRYPT);
143 	newkeys[MODE_IN] = newkeys[MODE_OUT] = NULL;
144 	if (!initialized) {
145 		initialized = 1;
146 		buffer_init(&input);
147 		buffer_init(&output);
148 		buffer_init(&outgoing_packet);
149 		buffer_init(&incoming_packet);
150 	}
151 	/* Kludge: arrange the close function to be called from fatal(). */
152 	fatal_add_cleanup((void (*) (void *)) packet_close, NULL);
153 }
154 
155 /* Returns 1 if remote host is connected via socket, 0 if not. */
156 
157 int
158 packet_connection_is_on_socket(void)
159 {
160 	struct sockaddr_storage from, to;
161 	socklen_t fromlen, tolen;
162 
163 	/* filedescriptors in and out are the same, so it's a socket */
164 	if (connection_in == connection_out)
165 		return 1;
166 	fromlen = sizeof(from);
167 	memset(&from, 0, sizeof(from));
168 	if (getpeername(connection_in, (struct sockaddr *)&from, &fromlen) < 0)
169 		return 0;
170 	tolen = sizeof(to);
171 	memset(&to, 0, sizeof(to));
172 	if (getpeername(connection_out, (struct sockaddr *)&to, &tolen) < 0)
173 		return 0;
174 	if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
175 		return 0;
176 	if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
177 		return 0;
178 	return 1;
179 }
180 
181 /*
182  * Exports an IV from the CipherContext required to export the key
183  * state back from the unprivileged child to the privileged parent
184  * process.
185  */
186 
187 void
188 packet_get_keyiv(int mode, u_char *iv, u_int len)
189 {
190 	CipherContext *cc;
191 
192 	if (mode == MODE_OUT)
193 		cc = &send_context;
194 	else
195 		cc = &receive_context;
196 
197 	cipher_get_keyiv(cc, iv, len);
198 }
199 
200 int
201 packet_get_keycontext(int mode, u_char *dat)
202 {
203 	CipherContext *cc;
204 
205 	if (mode == MODE_OUT)
206 		cc = &send_context;
207 	else
208 		cc = &receive_context;
209 
210 	return (cipher_get_keycontext(cc, dat));
211 }
212 
213 void
214 packet_set_keycontext(int mode, u_char *dat)
215 {
216 	CipherContext *cc;
217 
218 	if (mode == MODE_OUT)
219 		cc = &send_context;
220 	else
221 		cc = &receive_context;
222 
223 	cipher_set_keycontext(cc, dat);
224 }
225 
226 int
227 packet_get_keyiv_len(int mode)
228 {
229 	CipherContext *cc;
230 
231 	if (mode == MODE_OUT)
232 		cc = &send_context;
233 	else
234 		cc = &receive_context;
235 
236 	return (cipher_get_keyiv_len(cc));
237 }
238 void
239 packet_set_iv(int mode, u_char *dat)
240 {
241 	CipherContext *cc;
242 
243 	if (mode == MODE_OUT)
244 		cc = &send_context;
245 	else
246 		cc = &receive_context;
247 
248 	cipher_set_keyiv(cc, dat);
249 }
250 int
251 packet_get_ssh1_cipher()
252 {
253 	return (cipher_get_number(receive_context.cipher));
254 }
255 
256 
257 u_int32_t
258 packet_get_seqnr(int mode)
259 {
260 	return (mode == MODE_IN ? read_seqnr : send_seqnr);
261 }
262 
263 void
264 packet_set_seqnr(int mode, u_int32_t seqnr)
265 {
266 	if (mode == MODE_IN)
267 		read_seqnr = seqnr;
268 	else if (mode == MODE_OUT)
269 		send_seqnr = seqnr;
270 	else
271 		fatal("packet_set_seqnr: bad mode %d", mode);
272 }
273 
274 /* returns 1 if connection is via ipv4 */
275 
276 int
277 packet_connection_is_ipv4(void)
278 {
279 	struct sockaddr_storage to;
280 	socklen_t tolen = sizeof(to);
281 
282 	memset(&to, 0, sizeof(to));
283 	if (getsockname(connection_out, (struct sockaddr *)&to, &tolen) < 0)
284 		return 0;
285 	if (to.ss_family != AF_INET)
286 		return 0;
287 	return 1;
288 }
289 
290 /* Sets the connection into non-blocking mode. */
291 
292 void
293 packet_set_nonblocking(void)
294 {
295 	/* Set the socket into non-blocking mode. */
296 	if (fcntl(connection_in, F_SETFL, O_NONBLOCK) < 0)
297 		error("fcntl O_NONBLOCK: %.100s", strerror(errno));
298 
299 	if (connection_out != connection_in) {
300 		if (fcntl(connection_out, F_SETFL, O_NONBLOCK) < 0)
301 			error("fcntl O_NONBLOCK: %.100s", strerror(errno));
302 	}
303 }
304 
305 /* Returns the socket used for reading. */
306 
307 int
308 packet_get_connection_in(void)
309 {
310 	return connection_in;
311 }
312 
313 /* Returns the descriptor used for writing. */
314 
315 int
316 packet_get_connection_out(void)
317 {
318 	return connection_out;
319 }
320 
321 /* Closes the connection and clears and frees internal data structures. */
322 
323 void
324 packet_close(void)
325 {
326 	if (!initialized)
327 		return;
328 	initialized = 0;
329 	if (connection_in == connection_out) {
330 		shutdown(connection_out, SHUT_RDWR);
331 		close(connection_out);
332 	} else {
333 		close(connection_in);
334 		close(connection_out);
335 	}
336 	buffer_free(&input);
337 	buffer_free(&output);
338 	buffer_free(&outgoing_packet);
339 	buffer_free(&incoming_packet);
340 	if (compression_buffer_ready) {
341 		buffer_free(&compression_buffer);
342 		buffer_compress_uninit();
343 	}
344 	cipher_cleanup(&send_context);
345 	cipher_cleanup(&receive_context);
346 }
347 
348 /* Sets remote side protocol flags. */
349 
350 void
351 packet_set_protocol_flags(u_int protocol_flags)
352 {
353 	remote_protocol_flags = protocol_flags;
354 }
355 
356 /* Returns the remote protocol flags set earlier by the above function. */
357 
358 u_int
359 packet_get_protocol_flags(void)
360 {
361 	return remote_protocol_flags;
362 }
363 
364 /*
365  * Starts packet compression from the next packet on in both directions.
366  * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
367  */
368 
369 static void
370 packet_init_compression(void)
371 {
372 	if (compression_buffer_ready == 1)
373 		return;
374 	compression_buffer_ready = 1;
375 	buffer_init(&compression_buffer);
376 }
377 
378 void
379 packet_start_compression(int level)
380 {
381 	if (packet_compression && !compat20)
382 		fatal("Compression already enabled.");
383 	packet_compression = 1;
384 	packet_init_compression();
385 	buffer_compress_init_send(level);
386 	buffer_compress_init_recv();
387 }
388 
389 /*
390  * Causes any further packets to be encrypted using the given key.  The same
391  * key is used for both sending and reception.  However, both directions are
392  * encrypted independently of each other.
393  */
394 
395 void
396 packet_set_encryption_key(const u_char *key, u_int keylen,
397     int number)
398 {
399 	Cipher *cipher = cipher_by_number(number);
400 	if (cipher == NULL)
401 		fatal("packet_set_encryption_key: unknown cipher number %d", number);
402 	if (keylen < 20)
403 		fatal("packet_set_encryption_key: keylen too small: %d", keylen);
404 	if (keylen > SSH_SESSION_KEY_LENGTH)
405 		fatal("packet_set_encryption_key: keylen too big: %d", keylen);
406 	memcpy(ssh1_key, key, keylen);
407 	ssh1_keylen = keylen;
408 	cipher_init(&send_context, cipher, key, keylen, NULL, 0, CIPHER_ENCRYPT);
409 	cipher_init(&receive_context, cipher, key, keylen, NULL, 0, CIPHER_DECRYPT);
410 }
411 
412 u_int
413 packet_get_encryption_key(u_char *key)
414 {
415 	if (key == NULL)
416 		return (ssh1_keylen);
417 	memcpy(key, ssh1_key, ssh1_keylen);
418 	return (ssh1_keylen);
419 }
420 
421 /* Start constructing a packet to send. */
422 void
423 packet_start(u_char type)
424 {
425 	u_char buf[9];
426 	int len;
427 
428 	DBG(debug("packet_start[%d]", type));
429 	len = compat20 ? 6 : 9;
430 	memset(buf, 0, len - 1);
431 	buf[len - 1] = type;
432 	buffer_clear(&outgoing_packet);
433 	buffer_append(&outgoing_packet, buf, len);
434 }
435 
436 /* Append payload. */
437 void
438 packet_put_char(int value)
439 {
440 	char ch = value;
441 	buffer_append(&outgoing_packet, &ch, 1);
442 }
443 void
444 packet_put_int(u_int value)
445 {
446 	buffer_put_int(&outgoing_packet, value);
447 }
448 void
449 packet_put_string(const void *buf, u_int len)
450 {
451 	buffer_put_string(&outgoing_packet, buf, len);
452 }
453 void
454 packet_put_cstring(const char *str)
455 {
456 	buffer_put_cstring(&outgoing_packet, str);
457 }
458 void
459 packet_put_raw(const void *buf, u_int len)
460 {
461 	buffer_append(&outgoing_packet, buf, len);
462 }
463 void
464 packet_put_bignum(BIGNUM * value)
465 {
466 	buffer_put_bignum(&outgoing_packet, value);
467 }
468 void
469 packet_put_bignum2(BIGNUM * value)
470 {
471 	buffer_put_bignum2(&outgoing_packet, value);
472 }
473 
474 /*
475  * Finalizes and sends the packet.  If the encryption key has been set,
476  * encrypts the packet before sending.
477  */
478 
479 static void
480 packet_send1(void)
481 {
482 	u_char buf[8], *cp;
483 	int i, padding, len;
484 	u_int checksum;
485 	u_int32_t rand = 0;
486 
487 	/*
488 	 * If using packet compression, compress the payload of the outgoing
489 	 * packet.
490 	 */
491 	if (packet_compression) {
492 		buffer_clear(&compression_buffer);
493 		/* Skip padding. */
494 		buffer_consume(&outgoing_packet, 8);
495 		/* padding */
496 		buffer_append(&compression_buffer, "\0\0\0\0\0\0\0\0", 8);
497 		buffer_compress(&outgoing_packet, &compression_buffer);
498 		buffer_clear(&outgoing_packet);
499 		buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
500 		    buffer_len(&compression_buffer));
501 	}
502 	/* Compute packet length without padding (add checksum, remove padding). */
503 	len = buffer_len(&outgoing_packet) + 4 - 8;
504 
505 	/* Insert padding. Initialized to zero in packet_start1() */
506 	padding = 8 - len % 8;
507 	if (!send_context.plaintext) {
508 		cp = buffer_ptr(&outgoing_packet);
509 		for (i = 0; i < padding; i++) {
510 			if (i % 4 == 0)
511 				rand = arc4random();
512 			cp[7 - i] = rand & 0xff;
513 			rand >>= 8;
514 		}
515 	}
516 	buffer_consume(&outgoing_packet, 8 - padding);
517 
518 	/* Add check bytes. */
519 	checksum = ssh_crc32(buffer_ptr(&outgoing_packet),
520 	    buffer_len(&outgoing_packet));
521 	PUT_32BIT(buf, checksum);
522 	buffer_append(&outgoing_packet, buf, 4);
523 
524 #ifdef PACKET_DEBUG
525 	fprintf(stderr, "packet_send plain: ");
526 	buffer_dump(&outgoing_packet);
527 #endif
528 
529 	/* Append to output. */
530 	PUT_32BIT(buf, len);
531 	buffer_append(&output, buf, 4);
532 	cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
533 	cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
534 	    buffer_len(&outgoing_packet));
535 
536 #ifdef PACKET_DEBUG
537 	fprintf(stderr, "encrypted: ");
538 	buffer_dump(&output);
539 #endif
540 
541 	buffer_clear(&outgoing_packet);
542 
543 	/*
544 	 * Note that the packet is now only buffered in output.  It won\'t be
545 	 * actually sent until packet_write_wait or packet_write_poll is
546 	 * called.
547 	 */
548 }
549 
550 void
551 set_newkeys(int mode)
552 {
553 	Enc *enc;
554 	Mac *mac;
555 	Comp *comp;
556 	CipherContext *cc;
557 	int encrypt;
558 
559 	debug("newkeys: mode %d", mode);
560 
561 	if (mode == MODE_OUT) {
562 		cc = &send_context;
563 		encrypt = CIPHER_ENCRYPT;
564 	} else {
565 		cc = &receive_context;
566 		encrypt = CIPHER_DECRYPT;
567 	}
568 	if (newkeys[mode] != NULL) {
569 		debug("newkeys: rekeying");
570 		cipher_cleanup(cc);
571 		enc  = &newkeys[mode]->enc;
572 		mac  = &newkeys[mode]->mac;
573 		comp = &newkeys[mode]->comp;
574 		memset(mac->key, 0, mac->key_len);
575 		xfree(enc->name);
576 		xfree(enc->iv);
577 		xfree(enc->key);
578 		xfree(mac->name);
579 		xfree(mac->key);
580 		xfree(comp->name);
581 		xfree(newkeys[mode]);
582 	}
583 	newkeys[mode] = kex_get_newkeys(mode);
584 	if (newkeys[mode] == NULL)
585 		fatal("newkeys: no keys for mode %d", mode);
586 	enc  = &newkeys[mode]->enc;
587 	mac  = &newkeys[mode]->mac;
588 	comp = &newkeys[mode]->comp;
589 	if (mac->md != NULL)
590 		mac->enabled = 1;
591 	DBG(debug("cipher_init_context: %d", mode));
592 	cipher_init(cc, enc->cipher, enc->key, enc->key_len,
593 	    enc->iv, enc->block_size, encrypt);
594 	/* Deleting the keys does not gain extra security */
595 	/* memset(enc->iv,  0, enc->block_size);
596 	   memset(enc->key, 0, enc->key_len); */
597 	if (comp->type != 0 && comp->enabled == 0) {
598 		packet_init_compression();
599 		if (mode == MODE_OUT)
600 			buffer_compress_init_send(6);
601 		else
602 			buffer_compress_init_recv();
603 		comp->enabled = 1;
604 	}
605 }
606 
607 /*
608  * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
609  */
610 static void
611 packet_send2(void)
612 {
613 	u_char type, *cp, *macbuf = NULL;
614 	u_char padlen, pad;
615 	u_int packet_length = 0;
616 	u_int i, len;
617 	u_int32_t rand = 0;
618 	Enc *enc   = NULL;
619 	Mac *mac   = NULL;
620 	Comp *comp = NULL;
621 	int block_size;
622 
623 	if (newkeys[MODE_OUT] != NULL) {
624 		enc  = &newkeys[MODE_OUT]->enc;
625 		mac  = &newkeys[MODE_OUT]->mac;
626 		comp = &newkeys[MODE_OUT]->comp;
627 	}
628 	block_size = enc ? enc->block_size : 8;
629 
630 	cp = buffer_ptr(&outgoing_packet);
631 	type = cp[5];
632 
633 #ifdef PACKET_DEBUG
634 	fprintf(stderr, "plain:     ");
635 	buffer_dump(&outgoing_packet);
636 #endif
637 
638 	if (comp && comp->enabled) {
639 		len = buffer_len(&outgoing_packet);
640 		/* skip header, compress only payload */
641 		buffer_consume(&outgoing_packet, 5);
642 		buffer_clear(&compression_buffer);
643 		buffer_compress(&outgoing_packet, &compression_buffer);
644 		buffer_clear(&outgoing_packet);
645 		buffer_append(&outgoing_packet, "\0\0\0\0\0", 5);
646 		buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
647 		    buffer_len(&compression_buffer));
648 		DBG(debug("compression: raw %d compressed %d", len,
649 		    buffer_len(&outgoing_packet)));
650 	}
651 
652 	/* sizeof (packet_len + pad_len + payload) */
653 	len = buffer_len(&outgoing_packet);
654 
655 	/*
656 	 * calc size of padding, alloc space, get random data,
657 	 * minimum padding is 4 bytes
658 	 */
659 	padlen = block_size - (len % block_size);
660 	if (padlen < 4)
661 		padlen += block_size;
662 	if (extra_pad) {
663 		/* will wrap if extra_pad+padlen > 255 */
664 		extra_pad  = roundup(extra_pad, block_size);
665 		pad = extra_pad - ((len + padlen) % extra_pad);
666 		debug3("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
667 		    pad, len, padlen, extra_pad);
668 		padlen += pad;
669 		extra_pad = 0;
670 	}
671 	cp = buffer_append_space(&outgoing_packet, padlen);
672 	if (enc && !send_context.plaintext) {
673 		/* random padding */
674 		for (i = 0; i < padlen; i++) {
675 			if (i % 4 == 0)
676 				rand = arc4random();
677 			cp[i] = rand & 0xff;
678 			rand >>= 8;
679 		}
680 	} else {
681 		/* clear padding */
682 		memset(cp, 0, padlen);
683 	}
684 	/* packet_length includes payload, padding and padding length field */
685 	packet_length = buffer_len(&outgoing_packet) - 4;
686 	cp = buffer_ptr(&outgoing_packet);
687 	PUT_32BIT(cp, packet_length);
688 	cp[4] = padlen;
689 	DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen));
690 
691 	/* compute MAC over seqnr and packet(length fields, payload, padding) */
692 	if (mac && mac->enabled) {
693 		macbuf = mac_compute(mac, send_seqnr,
694 		    buffer_ptr(&outgoing_packet),
695 		    buffer_len(&outgoing_packet));
696 		DBG(debug("done calc MAC out #%d", send_seqnr));
697 	}
698 	/* encrypt packet and append to output buffer. */
699 	cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
700 	cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
701 	    buffer_len(&outgoing_packet));
702 	/* append unencrypted MAC */
703 	if (mac && mac->enabled)
704 		buffer_append(&output, (char *)macbuf, mac->mac_len);
705 #ifdef PACKET_DEBUG
706 	fprintf(stderr, "encrypted: ");
707 	buffer_dump(&output);
708 #endif
709 	/* increment sequence number for outgoing packets */
710 	if (++send_seqnr == 0)
711 		log("outgoing seqnr wraps around");
712 	buffer_clear(&outgoing_packet);
713 
714 	if (type == SSH2_MSG_NEWKEYS)
715 		set_newkeys(MODE_OUT);
716 }
717 
718 void
719 packet_send(void)
720 {
721 	if (compat20)
722 		packet_send2();
723 	else
724 		packet_send1();
725 	DBG(debug("packet_send done"));
726 }
727 
728 /*
729  * Waits until a packet has been received, and returns its type.  Note that
730  * no other data is processed until this returns, so this function should not
731  * be used during the interactive session.
732  */
733 
734 int
735 packet_read_seqnr(u_int32_t *seqnr_p)
736 {
737 	int type, len;
738 	fd_set *setp;
739 	char buf[8192];
740 	DBG(debug("packet_read()"));
741 
742 	setp = (fd_set *)xmalloc(howmany(connection_in+1, NFDBITS) *
743 	    sizeof(fd_mask));
744 
745 	/* Since we are blocking, ensure that all written packets have been sent. */
746 	packet_write_wait();
747 
748 	/* Stay in the loop until we have received a complete packet. */
749 	for (;;) {
750 		/* Try to read a packet from the buffer. */
751 		type = packet_read_poll_seqnr(seqnr_p);
752 		if (!compat20 && (
753 		    type == SSH_SMSG_SUCCESS
754 		    || type == SSH_SMSG_FAILURE
755 		    || type == SSH_CMSG_EOF
756 		    || type == SSH_CMSG_EXIT_CONFIRMATION))
757 			packet_check_eom();
758 		/* If we got a packet, return it. */
759 		if (type != SSH_MSG_NONE) {
760 			xfree(setp);
761 			return type;
762 		}
763 		/*
764 		 * Otherwise, wait for some data to arrive, add it to the
765 		 * buffer, and try again.
766 		 */
767 		memset(setp, 0, howmany(connection_in + 1, NFDBITS) *
768 		    sizeof(fd_mask));
769 		FD_SET(connection_in, setp);
770 
771 		/* Wait for some data to arrive. */
772 		while (select(connection_in + 1, setp, NULL, NULL, NULL) == -1 &&
773 		    (errno == EAGAIN || errno == EINTR))
774 			;
775 
776 		/* Read data from the socket. */
777 		len = read(connection_in, buf, sizeof(buf));
778 		if (len == 0) {
779 			log("Connection closed by %.200s", get_remote_ipaddr());
780 			fatal_cleanup();
781 		}
782 		if (len < 0)
783 			fatal("Read from socket failed: %.100s", strerror(errno));
784 		/* Append it to the buffer. */
785 		packet_process_incoming(buf, len);
786 	}
787 	/* NOTREACHED */
788 }
789 
790 int
791 packet_read(void)
792 {
793 	return packet_read_seqnr(NULL);
794 }
795 
796 /*
797  * Waits until a packet has been received, verifies that its type matches
798  * that given, and gives a fatal error and exits if there is a mismatch.
799  */
800 
801 void
802 packet_read_expect(int expected_type)
803 {
804 	int type;
805 
806 	type = packet_read();
807 	if (type != expected_type)
808 		packet_disconnect("Protocol error: expected packet type %d, got %d",
809 		    expected_type, type);
810 }
811 
812 /* Checks if a full packet is available in the data received so far via
813  * packet_process_incoming.  If so, reads the packet; otherwise returns
814  * SSH_MSG_NONE.  This does not wait for data from the connection.
815  *
816  * SSH_MSG_DISCONNECT is handled specially here.  Also,
817  * SSH_MSG_IGNORE messages are skipped by this function and are never returned
818  * to higher levels.
819  */
820 
821 static int
822 packet_read_poll1(void)
823 {
824 	u_int len, padded_len;
825 	u_char *cp, type;
826 	u_int checksum, stored_checksum;
827 
828 	/* Check if input size is less than minimum packet size. */
829 	if (buffer_len(&input) < 4 + 8)
830 		return SSH_MSG_NONE;
831 	/* Get length of incoming packet. */
832 	cp = buffer_ptr(&input);
833 	len = GET_32BIT(cp);
834 	if (len < 1 + 2 + 2 || len > 256 * 1024)
835 		packet_disconnect("Bad packet length %d.", len);
836 	padded_len = (len + 8) & ~7;
837 
838 	/* Check if the packet has been entirely received. */
839 	if (buffer_len(&input) < 4 + padded_len)
840 		return SSH_MSG_NONE;
841 
842 	/* The entire packet is in buffer. */
843 
844 	/* Consume packet length. */
845 	buffer_consume(&input, 4);
846 
847 	/*
848 	 * Cryptographic attack detector for ssh
849 	 * (C)1998 CORE-SDI, Buenos Aires Argentina
850 	 * Ariel Futoransky(futo@core-sdi.com)
851 	 */
852 	if (!receive_context.plaintext &&
853 	    detect_attack(buffer_ptr(&input), padded_len, NULL) == DEATTACK_DETECTED)
854 		packet_disconnect("crc32 compensation attack: network attack detected");
855 
856 	/* Decrypt data to incoming_packet. */
857 	buffer_clear(&incoming_packet);
858 	cp = buffer_append_space(&incoming_packet, padded_len);
859 	cipher_crypt(&receive_context, cp, buffer_ptr(&input), padded_len);
860 
861 	buffer_consume(&input, padded_len);
862 
863 #ifdef PACKET_DEBUG
864 	fprintf(stderr, "read_poll plain: ");
865 	buffer_dump(&incoming_packet);
866 #endif
867 
868 	/* Compute packet checksum. */
869 	checksum = ssh_crc32(buffer_ptr(&incoming_packet),
870 	    buffer_len(&incoming_packet) - 4);
871 
872 	/* Skip padding. */
873 	buffer_consume(&incoming_packet, 8 - len % 8);
874 
875 	/* Test check bytes. */
876 	if (len != buffer_len(&incoming_packet))
877 		packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
878 		    len, buffer_len(&incoming_packet));
879 
880 	cp = (u_char *)buffer_ptr(&incoming_packet) + len - 4;
881 	stored_checksum = GET_32BIT(cp);
882 	if (checksum != stored_checksum)
883 		packet_disconnect("Corrupted check bytes on input.");
884 	buffer_consume_end(&incoming_packet, 4);
885 
886 	if (packet_compression) {
887 		buffer_clear(&compression_buffer);
888 		buffer_uncompress(&incoming_packet, &compression_buffer);
889 		buffer_clear(&incoming_packet);
890 		buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
891 		    buffer_len(&compression_buffer));
892 	}
893 	type = buffer_get_char(&incoming_packet);
894 	return type;
895 }
896 
897 static int
898 packet_read_poll2(u_int32_t *seqnr_p)
899 {
900 	static u_int packet_length = 0;
901 	u_int padlen, need;
902 	u_char *macbuf, *cp, type;
903 	int maclen, block_size;
904 	Enc *enc   = NULL;
905 	Mac *mac   = NULL;
906 	Comp *comp = NULL;
907 
908 	if (newkeys[MODE_IN] != NULL) {
909 		enc  = &newkeys[MODE_IN]->enc;
910 		mac  = &newkeys[MODE_IN]->mac;
911 		comp = &newkeys[MODE_IN]->comp;
912 	}
913 	maclen = mac && mac->enabled ? mac->mac_len : 0;
914 	block_size = enc ? enc->block_size : 8;
915 
916 	if (packet_length == 0) {
917 		/*
918 		 * check if input size is less than the cipher block size,
919 		 * decrypt first block and extract length of incoming packet
920 		 */
921 		if (buffer_len(&input) < block_size)
922 			return SSH_MSG_NONE;
923 		buffer_clear(&incoming_packet);
924 		cp = buffer_append_space(&incoming_packet, block_size);
925 		cipher_crypt(&receive_context, cp, buffer_ptr(&input),
926 		    block_size);
927 		cp = buffer_ptr(&incoming_packet);
928 		packet_length = GET_32BIT(cp);
929 		if (packet_length < 1 + 4 || packet_length > 256 * 1024) {
930 			buffer_dump(&incoming_packet);
931 			packet_disconnect("Bad packet length %d.", packet_length);
932 		}
933 		DBG(debug("input: packet len %d", packet_length+4));
934 		buffer_consume(&input, block_size);
935 	}
936 	/* we have a partial packet of block_size bytes */
937 	need = 4 + packet_length - block_size;
938 	DBG(debug("partial packet %d, need %d, maclen %d", block_size,
939 	    need, maclen));
940 	if (need % block_size != 0)
941 		fatal("padding error: need %d block %d mod %d",
942 		    need, block_size, need % block_size);
943 	/*
944 	 * check if the entire packet has been received and
945 	 * decrypt into incoming_packet
946 	 */
947 	if (buffer_len(&input) < need + maclen)
948 		return SSH_MSG_NONE;
949 #ifdef PACKET_DEBUG
950 	fprintf(stderr, "read_poll enc/full: ");
951 	buffer_dump(&input);
952 #endif
953 	cp = buffer_append_space(&incoming_packet, need);
954 	cipher_crypt(&receive_context, cp, buffer_ptr(&input), need);
955 	buffer_consume(&input, need);
956 	/*
957 	 * compute MAC over seqnr and packet,
958 	 * increment sequence number for incoming packet
959 	 */
960 	if (mac && mac->enabled) {
961 		macbuf = mac_compute(mac, read_seqnr,
962 		    buffer_ptr(&incoming_packet),
963 		    buffer_len(&incoming_packet));
964 		if (memcmp(macbuf, buffer_ptr(&input), mac->mac_len) != 0)
965 			packet_disconnect("Corrupted MAC on input.");
966 		DBG(debug("MAC #%d ok", read_seqnr));
967 		buffer_consume(&input, mac->mac_len);
968 	}
969 	if (seqnr_p != NULL)
970 		*seqnr_p = read_seqnr;
971 	if (++read_seqnr == 0)
972 		log("incoming seqnr wraps around");
973 
974 	/* get padlen */
975 	cp = buffer_ptr(&incoming_packet);
976 	padlen = cp[4];
977 	DBG(debug("input: padlen %d", padlen));
978 	if (padlen < 4)
979 		packet_disconnect("Corrupted padlen %d on input.", padlen);
980 
981 	/* skip packet size + padlen, discard padding */
982 	buffer_consume(&incoming_packet, 4 + 1);
983 	buffer_consume_end(&incoming_packet, padlen);
984 
985 	DBG(debug("input: len before de-compress %d", buffer_len(&incoming_packet)));
986 	if (comp && comp->enabled) {
987 		buffer_clear(&compression_buffer);
988 		buffer_uncompress(&incoming_packet, &compression_buffer);
989 		buffer_clear(&incoming_packet);
990 		buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
991 		    buffer_len(&compression_buffer));
992 		DBG(debug("input: len after de-compress %d", buffer_len(&incoming_packet)));
993 	}
994 	/*
995 	 * get packet type, implies consume.
996 	 * return length of payload (without type field)
997 	 */
998 	type = buffer_get_char(&incoming_packet);
999 	if (type == SSH2_MSG_NEWKEYS)
1000 		set_newkeys(MODE_IN);
1001 #ifdef PACKET_DEBUG
1002 	fprintf(stderr, "read/plain[%d]:\r\n", type);
1003 	buffer_dump(&incoming_packet);
1004 #endif
1005 	/* reset for next packet */
1006 	packet_length = 0;
1007 	return type;
1008 }
1009 
1010 int
1011 packet_read_poll_seqnr(u_int32_t *seqnr_p)
1012 {
1013 	int reason, seqnr;
1014 	u_char type;
1015 	char *msg;
1016 
1017 	for (;;) {
1018 		if (compat20) {
1019 			type = packet_read_poll2(seqnr_p);
1020 			if (type)
1021 				DBG(debug("received packet type %d", type));
1022 			switch (type) {
1023 			case SSH2_MSG_IGNORE:
1024 				break;
1025 			case SSH2_MSG_DEBUG:
1026 				packet_get_char();
1027 				msg = packet_get_string(NULL);
1028 				debug("Remote: %.900s", msg);
1029 				xfree(msg);
1030 				msg = packet_get_string(NULL);
1031 				xfree(msg);
1032 				break;
1033 			case SSH2_MSG_DISCONNECT:
1034 				reason = packet_get_int();
1035 				msg = packet_get_string(NULL);
1036 				log("Received disconnect from %s: %d: %.400s", get_remote_ipaddr(),
1037 					reason, msg);
1038 				xfree(msg);
1039 				fatal_cleanup();
1040 				break;
1041 			case SSH2_MSG_UNIMPLEMENTED:
1042 				seqnr = packet_get_int();
1043 				debug("Received SSH2_MSG_UNIMPLEMENTED for %d", seqnr);
1044 				break;
1045 			default:
1046 				return type;
1047 				break;
1048 			}
1049 		} else {
1050 			type = packet_read_poll1();
1051 			switch (type) {
1052 			case SSH_MSG_IGNORE:
1053 				break;
1054 			case SSH_MSG_DEBUG:
1055 				msg = packet_get_string(NULL);
1056 				debug("Remote: %.900s", msg);
1057 				xfree(msg);
1058 				break;
1059 			case SSH_MSG_DISCONNECT:
1060 				msg = packet_get_string(NULL);
1061 				log("Received disconnect from %s: %.400s", get_remote_ipaddr(),
1062 					msg);
1063 				fatal_cleanup();
1064 				xfree(msg);
1065 				break;
1066 			default:
1067 				if (type)
1068 					DBG(debug("received packet type %d", type));
1069 				return type;
1070 				break;
1071 			}
1072 		}
1073 	}
1074 }
1075 
1076 int
1077 packet_read_poll(void)
1078 {
1079 	return packet_read_poll_seqnr(NULL);
1080 }
1081 
1082 /*
1083  * Buffers the given amount of input characters.  This is intended to be used
1084  * together with packet_read_poll.
1085  */
1086 
1087 void
1088 packet_process_incoming(const char *buf, u_int len)
1089 {
1090 	buffer_append(&input, buf, len);
1091 }
1092 
1093 /* Returns a character from the packet. */
1094 
1095 u_int
1096 packet_get_char(void)
1097 {
1098 	char ch;
1099 	buffer_get(&incoming_packet, &ch, 1);
1100 	return (u_char) ch;
1101 }
1102 
1103 /* Returns an integer from the packet data. */
1104 
1105 u_int
1106 packet_get_int(void)
1107 {
1108 	return buffer_get_int(&incoming_packet);
1109 }
1110 
1111 /*
1112  * Returns an arbitrary precision integer from the packet data.  The integer
1113  * must have been initialized before this call.
1114  */
1115 
1116 void
1117 packet_get_bignum(BIGNUM * value)
1118 {
1119 	buffer_get_bignum(&incoming_packet, value);
1120 }
1121 
1122 void
1123 packet_get_bignum2(BIGNUM * value)
1124 {
1125 	buffer_get_bignum2(&incoming_packet, value);
1126 }
1127 
1128 void *
1129 packet_get_raw(int *length_ptr)
1130 {
1131 	int bytes = buffer_len(&incoming_packet);
1132 	if (length_ptr != NULL)
1133 		*length_ptr = bytes;
1134 	return buffer_ptr(&incoming_packet);
1135 }
1136 
1137 int
1138 packet_remaining(void)
1139 {
1140 	return buffer_len(&incoming_packet);
1141 }
1142 
1143 /*
1144  * Returns a string from the packet data.  The string is allocated using
1145  * xmalloc; it is the responsibility of the calling program to free it when
1146  * no longer needed.  The length_ptr argument may be NULL, or point to an
1147  * integer into which the length of the string is stored.
1148  */
1149 
1150 void *
1151 packet_get_string(u_int *length_ptr)
1152 {
1153 	return buffer_get_string(&incoming_packet, length_ptr);
1154 }
1155 
1156 /*
1157  * Sends a diagnostic message from the server to the client.  This message
1158  * can be sent at any time (but not while constructing another message). The
1159  * message is printed immediately, but only if the client is being executed
1160  * in verbose mode.  These messages are primarily intended to ease debugging
1161  * authentication problems.   The length of the formatted message must not
1162  * exceed 1024 bytes.  This will automatically call packet_write_wait.
1163  */
1164 
1165 void
1166 packet_send_debug(const char *fmt,...)
1167 {
1168 	char buf[1024];
1169 	va_list args;
1170 
1171 	if (compat20 && (datafellows & SSH_BUG_DEBUG))
1172 		return;
1173 
1174 	va_start(args, fmt);
1175 	vsnprintf(buf, sizeof(buf), fmt, args);
1176 	va_end(args);
1177 
1178 	if (compat20) {
1179 		packet_start(SSH2_MSG_DEBUG);
1180 		packet_put_char(0);	/* bool: always display */
1181 		packet_put_cstring(buf);
1182 		packet_put_cstring("");
1183 	} else {
1184 		packet_start(SSH_MSG_DEBUG);
1185 		packet_put_cstring(buf);
1186 	}
1187 	packet_send();
1188 	packet_write_wait();
1189 }
1190 
1191 /*
1192  * Logs the error plus constructs and sends a disconnect packet, closes the
1193  * connection, and exits.  This function never returns. The error message
1194  * should not contain a newline.  The length of the formatted message must
1195  * not exceed 1024 bytes.
1196  */
1197 
1198 void
1199 packet_disconnect(const char *fmt,...)
1200 {
1201 	char buf[1024];
1202 	va_list args;
1203 	static int disconnecting = 0;
1204 	if (disconnecting)	/* Guard against recursive invocations. */
1205 		fatal("packet_disconnect called recursively.");
1206 	disconnecting = 1;
1207 
1208 	/*
1209 	 * Format the message.  Note that the caller must make sure the
1210 	 * message is of limited size.
1211 	 */
1212 	va_start(args, fmt);
1213 	vsnprintf(buf, sizeof(buf), fmt, args);
1214 	va_end(args);
1215 
1216 	/* Send the disconnect message to the other side, and wait for it to get sent. */
1217 	if (compat20) {
1218 		packet_start(SSH2_MSG_DISCONNECT);
1219 		packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1220 		packet_put_cstring(buf);
1221 		packet_put_cstring("");
1222 	} else {
1223 		packet_start(SSH_MSG_DISCONNECT);
1224 		packet_put_cstring(buf);
1225 	}
1226 	packet_send();
1227 	packet_write_wait();
1228 
1229 	/* Stop listening for connections. */
1230 	channel_close_all();
1231 
1232 	/* Close the connection. */
1233 	packet_close();
1234 
1235 	/* Display the error locally and exit. */
1236 	log("Disconnecting: %.100s", buf);
1237 	fatal_cleanup();
1238 }
1239 
1240 /* Checks if there is any buffered output, and tries to write some of the output. */
1241 
1242 void
1243 packet_write_poll(void)
1244 {
1245 	int len = buffer_len(&output);
1246 	if (len > 0) {
1247 		len = write(connection_out, buffer_ptr(&output), len);
1248 		if (len <= 0) {
1249 			if (errno == EAGAIN)
1250 				return;
1251 			else
1252 				fatal("Write failed: %.100s", strerror(errno));
1253 		}
1254 		buffer_consume(&output, len);
1255 	}
1256 }
1257 
1258 /*
1259  * Calls packet_write_poll repeatedly until all pending output data has been
1260  * written.
1261  */
1262 
1263 void
1264 packet_write_wait(void)
1265 {
1266 	fd_set *setp;
1267 
1268 	setp = (fd_set *)xmalloc(howmany(connection_out + 1, NFDBITS) *
1269 	    sizeof(fd_mask));
1270 	packet_write_poll();
1271 	while (packet_have_data_to_write()) {
1272 		memset(setp, 0, howmany(connection_out + 1, NFDBITS) *
1273 		    sizeof(fd_mask));
1274 		FD_SET(connection_out, setp);
1275 		while (select(connection_out + 1, NULL, setp, NULL, NULL) == -1 &&
1276 		    (errno == EAGAIN || errno == EINTR))
1277 			;
1278 		packet_write_poll();
1279 	}
1280 	xfree(setp);
1281 }
1282 
1283 /* Returns true if there is buffered data to write to the connection. */
1284 
1285 int
1286 packet_have_data_to_write(void)
1287 {
1288 	return buffer_len(&output) != 0;
1289 }
1290 
1291 /* Returns true if there is not too much data to write to the connection. */
1292 
1293 int
1294 packet_not_very_much_data_to_write(void)
1295 {
1296 	if (interactive_mode)
1297 		return buffer_len(&output) < 16384;
1298 	else
1299 		return buffer_len(&output) < 128 * 1024;
1300 }
1301 
1302 /* Informs that the current session is interactive.  Sets IP flags for that. */
1303 
1304 void
1305 packet_set_interactive(int interactive)
1306 {
1307 	static int called = 0;
1308 	int lowdelay = IPTOS_LOWDELAY;
1309 	int throughput = IPTOS_THROUGHPUT;
1310 
1311 	if (called)
1312 		return;
1313 	called = 1;
1314 
1315 	/* Record that we are in interactive mode. */
1316 	interactive_mode = interactive;
1317 
1318 	/* Only set socket options if using a socket.  */
1319 	if (!packet_connection_is_on_socket())
1320 		return;
1321 	/*
1322 	 * IPTOS_LOWDELAY and IPTOS_THROUGHPUT are IPv4 only
1323 	 */
1324 	if (interactive) {
1325 		/*
1326 		 * Set IP options for an interactive connection.  Use
1327 		 * IPTOS_LOWDELAY and TCP_NODELAY.
1328 		 */
1329 		if (packet_connection_is_ipv4()) {
1330 			if (setsockopt(connection_in, IPPROTO_IP, IP_TOS,
1331 			    &lowdelay, sizeof(lowdelay)) < 0)
1332 				error("setsockopt IPTOS_LOWDELAY: %.100s",
1333 				    strerror(errno));
1334 		}
1335 		set_nodelay(connection_in);
1336 	} else if (packet_connection_is_ipv4()) {
1337 		/*
1338 		 * Set IP options for a non-interactive connection.  Use
1339 		 * IPTOS_THROUGHPUT.
1340 		 */
1341 		if (setsockopt(connection_in, IPPROTO_IP, IP_TOS, &throughput,
1342 		    sizeof(throughput)) < 0)
1343 			error("setsockopt IPTOS_THROUGHPUT: %.100s", strerror(errno));
1344 	}
1345 }
1346 
1347 /* Returns true if the current connection is interactive. */
1348 
1349 int
1350 packet_is_interactive(void)
1351 {
1352 	return interactive_mode;
1353 }
1354 
1355 int
1356 packet_set_maxsize(int s)
1357 {
1358 	static int called = 0;
1359 	if (called) {
1360 		log("packet_set_maxsize: called twice: old %d new %d",
1361 		    max_packet_size, s);
1362 		return -1;
1363 	}
1364 	if (s < 4 * 1024 || s > 1024 * 1024) {
1365 		log("packet_set_maxsize: bad size %d", s);
1366 		return -1;
1367 	}
1368 	called = 1;
1369 	debug("packet_set_maxsize: setting to %d", s);
1370 	max_packet_size = s;
1371 	return s;
1372 }
1373 
1374 /* roundup current message to pad bytes */
1375 void
1376 packet_add_padding(u_char pad)
1377 {
1378 	extra_pad = pad;
1379 }
1380 
1381 /*
1382  * 9.2.  Ignored Data Message
1383  *
1384  *   byte      SSH_MSG_IGNORE
1385  *   string    data
1386  *
1387  * All implementations MUST understand (and ignore) this message at any
1388  * time (after receiving the protocol version). No implementation is
1389  * required to send them. This message can be used as an additional
1390  * protection measure against advanced traffic analysis techniques.
1391  */
1392 void
1393 packet_send_ignore(int nbytes)
1394 {
1395 	u_int32_t rand = 0;
1396 	int i;
1397 
1398 	packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1399 	packet_put_int(nbytes);
1400 	for (i = 0; i < nbytes; i++) {
1401 		if (i % 4 == 0)
1402 			rand = arc4random();
1403 		packet_put_char(rand & 0xff);
1404 		rand >>= 8;
1405 	}
1406 }
1407