- jmc@cvs.openbsd.org 2006/07/18 08:03:09
[openssh-git.git] / packet.c
blobce652cfd80dc483c0128e4fa63f3acc9e345aa1f
1 /* $OpenBSD: packet.c,v 1.136 2006/07/17 01:31:09 stevesk Exp $ */
2 /*
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * All rights reserved
6 * This file contains code implementing the packet protocol and communication
7 * with the other side. This same code is used both on client and server side.
9 * As far as I am concerned, the code I have written for this software
10 * can be used freely for any purpose. Any derived versions of this
11 * software must be clearly marked as such, and if the derived work is
12 * incompatible with the protocol description in the RFC file, it must be
13 * called by a name other than "ssh" or "Secure Shell".
16 * SSH2 packet format added by Markus Friedl.
17 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
19 * Redistribution and use in source and binary forms, with or without
20 * modification, are permitted provided that the following conditions
21 * are met:
22 * 1. Redistributions of source code must retain the above copyright
23 * notice, this list of conditions and the following disclaimer.
24 * 2. Redistributions in binary form must reproduce the above copyright
25 * notice, this list of conditions and the following disclaimer in the
26 * documentation and/or other materials provided with the distribution.
28 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
29 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
30 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
31 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
32 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
33 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
34 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
35 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
36 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
37 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 #include "includes.h"
42 #include <sys/types.h>
43 #include "openbsd-compat/sys-queue.h"
44 #include <sys/socket.h>
46 #include <netinet/in_systm.h>
47 #include <netinet/in.h>
48 #include <netinet/ip.h>
50 #include <errno.h>
51 #include <stdarg.h>
52 #include <unistd.h>
54 #include "xmalloc.h"
55 #include "buffer.h"
56 #include "packet.h"
57 #include "bufaux.h"
58 #include "crc32.h"
60 #include "compress.h"
61 #include "deattack.h"
62 #include "channels.h"
64 #include "compat.h"
65 #include "ssh1.h"
66 #include "ssh2.h"
68 #include "cipher.h"
69 #include "kex.h"
70 #include "mac.h"
71 #include "log.h"
72 #include "canohost.h"
73 #include "misc.h"
74 #include "ssh.h"
76 #ifdef PACKET_DEBUG
77 #define DBG(x) x
78 #else
79 #define DBG(x)
80 #endif
83 * This variable contains the file descriptors used for communicating with
84 * the other side. connection_in is used for reading; connection_out for
85 * writing. These can be the same descriptor, in which case it is assumed to
86 * be a socket.
88 static int connection_in = -1;
89 static int connection_out = -1;
91 /* Protocol flags for the remote side. */
92 static u_int remote_protocol_flags = 0;
94 /* Encryption context for receiving data. This is only used for decryption. */
95 static CipherContext receive_context;
97 /* Encryption context for sending data. This is only used for encryption. */
98 static CipherContext send_context;
100 /* Buffer for raw input data from the socket. */
101 Buffer input;
103 /* Buffer for raw output data going to the socket. */
104 Buffer output;
106 /* Buffer for the partial outgoing packet being constructed. */
107 static Buffer outgoing_packet;
109 /* Buffer for the incoming packet currently being processed. */
110 static Buffer incoming_packet;
112 /* Scratch buffer for packet compression/decompression. */
113 static Buffer compression_buffer;
114 static int compression_buffer_ready = 0;
116 /* Flag indicating whether packet compression/decompression is enabled. */
117 static int packet_compression = 0;
119 /* default maximum packet size */
120 u_int max_packet_size = 32768;
122 /* Flag indicating whether this module has been initialized. */
123 static int initialized = 0;
125 /* Set to true if the connection is interactive. */
126 static int interactive_mode = 0;
128 /* Set to true if we are the server side. */
129 static int server_side = 0;
131 /* Set to true if we are authenticated. */
132 static int after_authentication = 0;
134 /* Session key information for Encryption and MAC */
135 Newkeys *newkeys[MODE_MAX];
136 static struct packet_state {
137 u_int32_t seqnr;
138 u_int32_t packets;
139 u_int64_t blocks;
140 } p_read, p_send;
142 static u_int64_t max_blocks_in, max_blocks_out;
143 static u_int32_t rekey_limit;
145 /* Session key for protocol v1 */
146 static u_char ssh1_key[SSH_SESSION_KEY_LENGTH];
147 static u_int ssh1_keylen;
149 /* roundup current message to extra_pad bytes */
150 static u_char extra_pad = 0;
152 struct packet {
153 TAILQ_ENTRY(packet) next;
154 u_char type;
155 Buffer payload;
157 TAILQ_HEAD(, packet) outgoing;
160 * Sets the descriptors used for communication. Disables encryption until
161 * packet_set_encryption_key is called.
163 void
164 packet_set_connection(int fd_in, int fd_out)
166 Cipher *none = cipher_by_name("none");
168 if (none == NULL)
169 fatal("packet_set_connection: cannot load cipher 'none'");
170 connection_in = fd_in;
171 connection_out = fd_out;
172 cipher_init(&send_context, none, (const u_char *)"",
173 0, NULL, 0, CIPHER_ENCRYPT);
174 cipher_init(&receive_context, none, (const u_char *)"",
175 0, NULL, 0, CIPHER_DECRYPT);
176 newkeys[MODE_IN] = newkeys[MODE_OUT] = NULL;
177 if (!initialized) {
178 initialized = 1;
179 buffer_init(&input);
180 buffer_init(&output);
181 buffer_init(&outgoing_packet);
182 buffer_init(&incoming_packet);
183 TAILQ_INIT(&outgoing);
187 /* Returns 1 if remote host is connected via socket, 0 if not. */
190 packet_connection_is_on_socket(void)
192 struct sockaddr_storage from, to;
193 socklen_t fromlen, tolen;
195 /* filedescriptors in and out are the same, so it's a socket */
196 if (connection_in == connection_out)
197 return 1;
198 fromlen = sizeof(from);
199 memset(&from, 0, sizeof(from));
200 if (getpeername(connection_in, (struct sockaddr *)&from, &fromlen) < 0)
201 return 0;
202 tolen = sizeof(to);
203 memset(&to, 0, sizeof(to));
204 if (getpeername(connection_out, (struct sockaddr *)&to, &tolen) < 0)
205 return 0;
206 if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
207 return 0;
208 if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
209 return 0;
210 return 1;
214 * Exports an IV from the CipherContext required to export the key
215 * state back from the unprivileged child to the privileged parent
216 * process.
219 void
220 packet_get_keyiv(int mode, u_char *iv, u_int len)
222 CipherContext *cc;
224 if (mode == MODE_OUT)
225 cc = &send_context;
226 else
227 cc = &receive_context;
229 cipher_get_keyiv(cc, iv, len);
233 packet_get_keycontext(int mode, u_char *dat)
235 CipherContext *cc;
237 if (mode == MODE_OUT)
238 cc = &send_context;
239 else
240 cc = &receive_context;
242 return (cipher_get_keycontext(cc, dat));
245 void
246 packet_set_keycontext(int mode, u_char *dat)
248 CipherContext *cc;
250 if (mode == MODE_OUT)
251 cc = &send_context;
252 else
253 cc = &receive_context;
255 cipher_set_keycontext(cc, dat);
259 packet_get_keyiv_len(int mode)
261 CipherContext *cc;
263 if (mode == MODE_OUT)
264 cc = &send_context;
265 else
266 cc = &receive_context;
268 return (cipher_get_keyiv_len(cc));
271 void
272 packet_set_iv(int mode, u_char *dat)
274 CipherContext *cc;
276 if (mode == MODE_OUT)
277 cc = &send_context;
278 else
279 cc = &receive_context;
281 cipher_set_keyiv(cc, dat);
285 packet_get_ssh1_cipher(void)
287 return (cipher_get_number(receive_context.cipher));
290 void
291 packet_get_state(int mode, u_int32_t *seqnr, u_int64_t *blocks, u_int32_t *packets)
293 struct packet_state *state;
295 state = (mode == MODE_IN) ? &p_read : &p_send;
296 *seqnr = state->seqnr;
297 *blocks = state->blocks;
298 *packets = state->packets;
301 void
302 packet_set_state(int mode, u_int32_t seqnr, u_int64_t blocks, u_int32_t packets)
304 struct packet_state *state;
306 state = (mode == MODE_IN) ? &p_read : &p_send;
307 state->seqnr = seqnr;
308 state->blocks = blocks;
309 state->packets = packets;
312 /* returns 1 if connection is via ipv4 */
315 packet_connection_is_ipv4(void)
317 struct sockaddr_storage to;
318 socklen_t tolen = sizeof(to);
320 memset(&to, 0, sizeof(to));
321 if (getsockname(connection_out, (struct sockaddr *)&to, &tolen) < 0)
322 return 0;
323 if (to.ss_family == AF_INET)
324 return 1;
325 #ifdef IPV4_IN_IPV6
326 if (to.ss_family == AF_INET6 &&
327 IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&to)->sin6_addr))
328 return 1;
329 #endif
330 return 0;
333 /* Sets the connection into non-blocking mode. */
335 void
336 packet_set_nonblocking(void)
338 /* Set the socket into non-blocking mode. */
339 set_nonblock(connection_in);
341 if (connection_out != connection_in)
342 set_nonblock(connection_out);
345 /* Returns the socket used for reading. */
348 packet_get_connection_in(void)
350 return connection_in;
353 /* Returns the descriptor used for writing. */
356 packet_get_connection_out(void)
358 return connection_out;
361 /* Closes the connection and clears and frees internal data structures. */
363 void
364 packet_close(void)
366 if (!initialized)
367 return;
368 initialized = 0;
369 if (connection_in == connection_out) {
370 shutdown(connection_out, SHUT_RDWR);
371 close(connection_out);
372 } else {
373 close(connection_in);
374 close(connection_out);
376 buffer_free(&input);
377 buffer_free(&output);
378 buffer_free(&outgoing_packet);
379 buffer_free(&incoming_packet);
380 if (compression_buffer_ready) {
381 buffer_free(&compression_buffer);
382 buffer_compress_uninit();
384 cipher_cleanup(&send_context);
385 cipher_cleanup(&receive_context);
388 /* Sets remote side protocol flags. */
390 void
391 packet_set_protocol_flags(u_int protocol_flags)
393 remote_protocol_flags = protocol_flags;
396 /* Returns the remote protocol flags set earlier by the above function. */
398 u_int
399 packet_get_protocol_flags(void)
401 return remote_protocol_flags;
405 * Starts packet compression from the next packet on in both directions.
406 * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
409 static void
410 packet_init_compression(void)
412 if (compression_buffer_ready == 1)
413 return;
414 compression_buffer_ready = 1;
415 buffer_init(&compression_buffer);
418 void
419 packet_start_compression(int level)
421 if (packet_compression && !compat20)
422 fatal("Compression already enabled.");
423 packet_compression = 1;
424 packet_init_compression();
425 buffer_compress_init_send(level);
426 buffer_compress_init_recv();
430 * Causes any further packets to be encrypted using the given key. The same
431 * key is used for both sending and reception. However, both directions are
432 * encrypted independently of each other.
435 void
436 packet_set_encryption_key(const u_char *key, u_int keylen,
437 int number)
439 Cipher *cipher = cipher_by_number(number);
441 if (cipher == NULL)
442 fatal("packet_set_encryption_key: unknown cipher number %d", number);
443 if (keylen < 20)
444 fatal("packet_set_encryption_key: keylen too small: %d", keylen);
445 if (keylen > SSH_SESSION_KEY_LENGTH)
446 fatal("packet_set_encryption_key: keylen too big: %d", keylen);
447 memcpy(ssh1_key, key, keylen);
448 ssh1_keylen = keylen;
449 cipher_init(&send_context, cipher, key, keylen, NULL, 0, CIPHER_ENCRYPT);
450 cipher_init(&receive_context, cipher, key, keylen, NULL, 0, CIPHER_DECRYPT);
453 u_int
454 packet_get_encryption_key(u_char *key)
456 if (key == NULL)
457 return (ssh1_keylen);
458 memcpy(key, ssh1_key, ssh1_keylen);
459 return (ssh1_keylen);
462 /* Start constructing a packet to send. */
463 void
464 packet_start(u_char type)
466 u_char buf[9];
467 int len;
469 DBG(debug("packet_start[%d]", type));
470 len = compat20 ? 6 : 9;
471 memset(buf, 0, len - 1);
472 buf[len - 1] = type;
473 buffer_clear(&outgoing_packet);
474 buffer_append(&outgoing_packet, buf, len);
477 /* Append payload. */
478 void
479 packet_put_char(int value)
481 char ch = value;
483 buffer_append(&outgoing_packet, &ch, 1);
486 void
487 packet_put_int(u_int value)
489 buffer_put_int(&outgoing_packet, value);
492 void
493 packet_put_string(const void *buf, u_int len)
495 buffer_put_string(&outgoing_packet, buf, len);
498 void
499 packet_put_cstring(const char *str)
501 buffer_put_cstring(&outgoing_packet, str);
504 void
505 packet_put_raw(const void *buf, u_int len)
507 buffer_append(&outgoing_packet, buf, len);
510 void
511 packet_put_bignum(BIGNUM * value)
513 buffer_put_bignum(&outgoing_packet, value);
516 void
517 packet_put_bignum2(BIGNUM * value)
519 buffer_put_bignum2(&outgoing_packet, value);
523 * Finalizes and sends the packet. If the encryption key has been set,
524 * encrypts the packet before sending.
527 static void
528 packet_send1(void)
530 u_char buf[8], *cp;
531 int i, padding, len;
532 u_int checksum;
533 u_int32_t rnd = 0;
536 * If using packet compression, compress the payload of the outgoing
537 * packet.
539 if (packet_compression) {
540 buffer_clear(&compression_buffer);
541 /* Skip padding. */
542 buffer_consume(&outgoing_packet, 8);
543 /* padding */
544 buffer_append(&compression_buffer, "\0\0\0\0\0\0\0\0", 8);
545 buffer_compress(&outgoing_packet, &compression_buffer);
546 buffer_clear(&outgoing_packet);
547 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
548 buffer_len(&compression_buffer));
550 /* Compute packet length without padding (add checksum, remove padding). */
551 len = buffer_len(&outgoing_packet) + 4 - 8;
553 /* Insert padding. Initialized to zero in packet_start1() */
554 padding = 8 - len % 8;
555 if (!send_context.plaintext) {
556 cp = buffer_ptr(&outgoing_packet);
557 for (i = 0; i < padding; i++) {
558 if (i % 4 == 0)
559 rnd = arc4random();
560 cp[7 - i] = rnd & 0xff;
561 rnd >>= 8;
564 buffer_consume(&outgoing_packet, 8 - padding);
566 /* Add check bytes. */
567 checksum = ssh_crc32(buffer_ptr(&outgoing_packet),
568 buffer_len(&outgoing_packet));
569 put_u32(buf, checksum);
570 buffer_append(&outgoing_packet, buf, 4);
572 #ifdef PACKET_DEBUG
573 fprintf(stderr, "packet_send plain: ");
574 buffer_dump(&outgoing_packet);
575 #endif
577 /* Append to output. */
578 put_u32(buf, len);
579 buffer_append(&output, buf, 4);
580 cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
581 cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
582 buffer_len(&outgoing_packet));
584 #ifdef PACKET_DEBUG
585 fprintf(stderr, "encrypted: ");
586 buffer_dump(&output);
587 #endif
589 buffer_clear(&outgoing_packet);
592 * Note that the packet is now only buffered in output. It won't be
593 * actually sent until packet_write_wait or packet_write_poll is
594 * called.
598 void
599 set_newkeys(int mode)
601 Enc *enc;
602 Mac *mac;
603 Comp *comp;
604 CipherContext *cc;
605 u_int64_t *max_blocks;
606 int crypt_type;
608 debug2("set_newkeys: mode %d", mode);
610 if (mode == MODE_OUT) {
611 cc = &send_context;
612 crypt_type = CIPHER_ENCRYPT;
613 p_send.packets = p_send.blocks = 0;
614 max_blocks = &max_blocks_out;
615 } else {
616 cc = &receive_context;
617 crypt_type = CIPHER_DECRYPT;
618 p_read.packets = p_read.blocks = 0;
619 max_blocks = &max_blocks_in;
621 if (newkeys[mode] != NULL) {
622 debug("set_newkeys: rekeying");
623 cipher_cleanup(cc);
624 enc = &newkeys[mode]->enc;
625 mac = &newkeys[mode]->mac;
626 comp = &newkeys[mode]->comp;
627 memset(mac->key, 0, mac->key_len);
628 xfree(enc->name);
629 xfree(enc->iv);
630 xfree(enc->key);
631 xfree(mac->name);
632 xfree(mac->key);
633 xfree(comp->name);
634 xfree(newkeys[mode]);
636 newkeys[mode] = kex_get_newkeys(mode);
637 if (newkeys[mode] == NULL)
638 fatal("newkeys: no keys for mode %d", mode);
639 enc = &newkeys[mode]->enc;
640 mac = &newkeys[mode]->mac;
641 comp = &newkeys[mode]->comp;
642 if (mac->md != NULL)
643 mac->enabled = 1;
644 DBG(debug("cipher_init_context: %d", mode));
645 cipher_init(cc, enc->cipher, enc->key, enc->key_len,
646 enc->iv, enc->block_size, crypt_type);
647 /* Deleting the keys does not gain extra security */
648 /* memset(enc->iv, 0, enc->block_size);
649 memset(enc->key, 0, enc->key_len); */
650 if ((comp->type == COMP_ZLIB ||
651 (comp->type == COMP_DELAYED && after_authentication)) &&
652 comp->enabled == 0) {
653 packet_init_compression();
654 if (mode == MODE_OUT)
655 buffer_compress_init_send(6);
656 else
657 buffer_compress_init_recv();
658 comp->enabled = 1;
661 * The 2^(blocksize*2) limit is too expensive for 3DES,
662 * blowfish, etc, so enforce a 1GB limit for small blocksizes.
664 if (enc->block_size >= 16)
665 *max_blocks = (u_int64_t)1 << (enc->block_size*2);
666 else
667 *max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
668 if (rekey_limit)
669 *max_blocks = MIN(*max_blocks, rekey_limit / enc->block_size);
673 * Delayed compression for SSH2 is enabled after authentication:
674 * This happans on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
675 * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
677 static void
678 packet_enable_delayed_compress(void)
680 Comp *comp = NULL;
681 int mode;
684 * Remember that we are past the authentication step, so rekeying
685 * with COMP_DELAYED will turn on compression immediately.
687 after_authentication = 1;
688 for (mode = 0; mode < MODE_MAX; mode++) {
689 comp = &newkeys[mode]->comp;
690 if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
691 packet_init_compression();
692 if (mode == MODE_OUT)
693 buffer_compress_init_send(6);
694 else
695 buffer_compress_init_recv();
696 comp->enabled = 1;
702 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
704 static void
705 packet_send2_wrapped(void)
707 u_char type, *cp, *macbuf = NULL;
708 u_char padlen, pad;
709 u_int packet_length = 0;
710 u_int i, len;
711 u_int32_t rnd = 0;
712 Enc *enc = NULL;
713 Mac *mac = NULL;
714 Comp *comp = NULL;
715 int block_size;
717 if (newkeys[MODE_OUT] != NULL) {
718 enc = &newkeys[MODE_OUT]->enc;
719 mac = &newkeys[MODE_OUT]->mac;
720 comp = &newkeys[MODE_OUT]->comp;
722 block_size = enc ? enc->block_size : 8;
724 cp = buffer_ptr(&outgoing_packet);
725 type = cp[5];
727 #ifdef PACKET_DEBUG
728 fprintf(stderr, "plain: ");
729 buffer_dump(&outgoing_packet);
730 #endif
732 if (comp && comp->enabled) {
733 len = buffer_len(&outgoing_packet);
734 /* skip header, compress only payload */
735 buffer_consume(&outgoing_packet, 5);
736 buffer_clear(&compression_buffer);
737 buffer_compress(&outgoing_packet, &compression_buffer);
738 buffer_clear(&outgoing_packet);
739 buffer_append(&outgoing_packet, "\0\0\0\0\0", 5);
740 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
741 buffer_len(&compression_buffer));
742 DBG(debug("compression: raw %d compressed %d", len,
743 buffer_len(&outgoing_packet)));
746 /* sizeof (packet_len + pad_len + payload) */
747 len = buffer_len(&outgoing_packet);
750 * calc size of padding, alloc space, get random data,
751 * minimum padding is 4 bytes
753 padlen = block_size - (len % block_size);
754 if (padlen < 4)
755 padlen += block_size;
756 if (extra_pad) {
757 /* will wrap if extra_pad+padlen > 255 */
758 extra_pad = roundup(extra_pad, block_size);
759 pad = extra_pad - ((len + padlen) % extra_pad);
760 debug3("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
761 pad, len, padlen, extra_pad);
762 padlen += pad;
763 extra_pad = 0;
765 cp = buffer_append_space(&outgoing_packet, padlen);
766 if (enc && !send_context.plaintext) {
767 /* random padding */
768 for (i = 0; i < padlen; i++) {
769 if (i % 4 == 0)
770 rnd = arc4random();
771 cp[i] = rnd & 0xff;
772 rnd >>= 8;
774 } else {
775 /* clear padding */
776 memset(cp, 0, padlen);
778 /* packet_length includes payload, padding and padding length field */
779 packet_length = buffer_len(&outgoing_packet) - 4;
780 cp = buffer_ptr(&outgoing_packet);
781 put_u32(cp, packet_length);
782 cp[4] = padlen;
783 DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen));
785 /* compute MAC over seqnr and packet(length fields, payload, padding) */
786 if (mac && mac->enabled) {
787 macbuf = mac_compute(mac, p_send.seqnr,
788 buffer_ptr(&outgoing_packet),
789 buffer_len(&outgoing_packet));
790 DBG(debug("done calc MAC out #%d", p_send.seqnr));
792 /* encrypt packet and append to output buffer. */
793 cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
794 cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
795 buffer_len(&outgoing_packet));
796 /* append unencrypted MAC */
797 if (mac && mac->enabled)
798 buffer_append(&output, macbuf, mac->mac_len);
799 #ifdef PACKET_DEBUG
800 fprintf(stderr, "encrypted: ");
801 buffer_dump(&output);
802 #endif
803 /* increment sequence number for outgoing packets */
804 if (++p_send.seqnr == 0)
805 logit("outgoing seqnr wraps around");
806 if (++p_send.packets == 0)
807 if (!(datafellows & SSH_BUG_NOREKEY))
808 fatal("XXX too many packets with same key");
809 p_send.blocks += (packet_length + 4) / block_size;
810 buffer_clear(&outgoing_packet);
812 if (type == SSH2_MSG_NEWKEYS)
813 set_newkeys(MODE_OUT);
814 else if (type == SSH2_MSG_USERAUTH_SUCCESS && server_side)
815 packet_enable_delayed_compress();
818 static void
819 packet_send2(void)
821 static int rekeying = 0;
822 struct packet *p;
823 u_char type, *cp;
825 cp = buffer_ptr(&outgoing_packet);
826 type = cp[5];
828 /* during rekeying we can only send key exchange messages */
829 if (rekeying) {
830 if (!((type >= SSH2_MSG_TRANSPORT_MIN) &&
831 (type <= SSH2_MSG_TRANSPORT_MAX))) {
832 debug("enqueue packet: %u", type);
833 p = xmalloc(sizeof(*p));
834 p->type = type;
835 memcpy(&p->payload, &outgoing_packet, sizeof(Buffer));
836 buffer_init(&outgoing_packet);
837 TAILQ_INSERT_TAIL(&outgoing, p, next);
838 return;
842 /* rekeying starts with sending KEXINIT */
843 if (type == SSH2_MSG_KEXINIT)
844 rekeying = 1;
846 packet_send2_wrapped();
848 /* after a NEWKEYS message we can send the complete queue */
849 if (type == SSH2_MSG_NEWKEYS) {
850 rekeying = 0;
851 while ((p = TAILQ_FIRST(&outgoing))) {
852 type = p->type;
853 debug("dequeue packet: %u", type);
854 buffer_free(&outgoing_packet);
855 memcpy(&outgoing_packet, &p->payload,
856 sizeof(Buffer));
857 TAILQ_REMOVE(&outgoing, p, next);
858 xfree(p);
859 packet_send2_wrapped();
864 void
865 packet_send(void)
867 if (compat20)
868 packet_send2();
869 else
870 packet_send1();
871 DBG(debug("packet_send done"));
875 * Waits until a packet has been received, and returns its type. Note that
876 * no other data is processed until this returns, so this function should not
877 * be used during the interactive session.
881 packet_read_seqnr(u_int32_t *seqnr_p)
883 int type, len;
884 fd_set *setp;
885 char buf[8192];
886 DBG(debug("packet_read()"));
888 setp = (fd_set *)xcalloc(howmany(connection_in+1, NFDBITS),
889 sizeof(fd_mask));
891 /* Since we are blocking, ensure that all written packets have been sent. */
892 packet_write_wait();
894 /* Stay in the loop until we have received a complete packet. */
895 for (;;) {
896 /* Try to read a packet from the buffer. */
897 type = packet_read_poll_seqnr(seqnr_p);
898 if (!compat20 && (
899 type == SSH_SMSG_SUCCESS
900 || type == SSH_SMSG_FAILURE
901 || type == SSH_CMSG_EOF
902 || type == SSH_CMSG_EXIT_CONFIRMATION))
903 packet_check_eom();
904 /* If we got a packet, return it. */
905 if (type != SSH_MSG_NONE) {
906 xfree(setp);
907 return type;
910 * Otherwise, wait for some data to arrive, add it to the
911 * buffer, and try again.
913 memset(setp, 0, howmany(connection_in + 1, NFDBITS) *
914 sizeof(fd_mask));
915 FD_SET(connection_in, setp);
917 /* Wait for some data to arrive. */
918 while (select(connection_in + 1, setp, NULL, NULL, NULL) == -1 &&
919 (errno == EAGAIN || errno == EINTR))
922 /* Read data from the socket. */
923 len = read(connection_in, buf, sizeof(buf));
924 if (len == 0) {
925 logit("Connection closed by %.200s", get_remote_ipaddr());
926 cleanup_exit(255);
928 if (len < 0)
929 fatal("Read from socket failed: %.100s", strerror(errno));
930 /* Append it to the buffer. */
931 packet_process_incoming(buf, len);
933 /* NOTREACHED */
937 packet_read(void)
939 return packet_read_seqnr(NULL);
943 * Waits until a packet has been received, verifies that its type matches
944 * that given, and gives a fatal error and exits if there is a mismatch.
947 void
948 packet_read_expect(int expected_type)
950 int type;
952 type = packet_read();
953 if (type != expected_type)
954 packet_disconnect("Protocol error: expected packet type %d, got %d",
955 expected_type, type);
958 /* Checks if a full packet is available in the data received so far via
959 * packet_process_incoming. If so, reads the packet; otherwise returns
960 * SSH_MSG_NONE. This does not wait for data from the connection.
962 * SSH_MSG_DISCONNECT is handled specially here. Also,
963 * SSH_MSG_IGNORE messages are skipped by this function and are never returned
964 * to higher levels.
967 static int
968 packet_read_poll1(void)
970 u_int len, padded_len;
971 u_char *cp, type;
972 u_int checksum, stored_checksum;
974 /* Check if input size is less than minimum packet size. */
975 if (buffer_len(&input) < 4 + 8)
976 return SSH_MSG_NONE;
977 /* Get length of incoming packet. */
978 cp = buffer_ptr(&input);
979 len = get_u32(cp);
980 if (len < 1 + 2 + 2 || len > 256 * 1024)
981 packet_disconnect("Bad packet length %u.", len);
982 padded_len = (len + 8) & ~7;
984 /* Check if the packet has been entirely received. */
985 if (buffer_len(&input) < 4 + padded_len)
986 return SSH_MSG_NONE;
988 /* The entire packet is in buffer. */
990 /* Consume packet length. */
991 buffer_consume(&input, 4);
994 * Cryptographic attack detector for ssh
995 * (C)1998 CORE-SDI, Buenos Aires Argentina
996 * Ariel Futoransky(futo@core-sdi.com)
998 if (!receive_context.plaintext &&
999 detect_attack(buffer_ptr(&input), padded_len) == DEATTACK_DETECTED)
1000 packet_disconnect("crc32 compensation attack: network attack detected");
1002 /* Decrypt data to incoming_packet. */
1003 buffer_clear(&incoming_packet);
1004 cp = buffer_append_space(&incoming_packet, padded_len);
1005 cipher_crypt(&receive_context, cp, buffer_ptr(&input), padded_len);
1007 buffer_consume(&input, padded_len);
1009 #ifdef PACKET_DEBUG
1010 fprintf(stderr, "read_poll plain: ");
1011 buffer_dump(&incoming_packet);
1012 #endif
1014 /* Compute packet checksum. */
1015 checksum = ssh_crc32(buffer_ptr(&incoming_packet),
1016 buffer_len(&incoming_packet) - 4);
1018 /* Skip padding. */
1019 buffer_consume(&incoming_packet, 8 - len % 8);
1021 /* Test check bytes. */
1022 if (len != buffer_len(&incoming_packet))
1023 packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
1024 len, buffer_len(&incoming_packet));
1026 cp = (u_char *)buffer_ptr(&incoming_packet) + len - 4;
1027 stored_checksum = get_u32(cp);
1028 if (checksum != stored_checksum)
1029 packet_disconnect("Corrupted check bytes on input.");
1030 buffer_consume_end(&incoming_packet, 4);
1032 if (packet_compression) {
1033 buffer_clear(&compression_buffer);
1034 buffer_uncompress(&incoming_packet, &compression_buffer);
1035 buffer_clear(&incoming_packet);
1036 buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
1037 buffer_len(&compression_buffer));
1039 type = buffer_get_char(&incoming_packet);
1040 if (type < SSH_MSG_MIN || type > SSH_MSG_MAX)
1041 packet_disconnect("Invalid ssh1 packet type: %d", type);
1042 return type;
1045 static int
1046 packet_read_poll2(u_int32_t *seqnr_p)
1048 static u_int packet_length = 0;
1049 u_int padlen, need;
1050 u_char *macbuf, *cp, type;
1051 u_int maclen, block_size;
1052 Enc *enc = NULL;
1053 Mac *mac = NULL;
1054 Comp *comp = NULL;
1056 if (newkeys[MODE_IN] != NULL) {
1057 enc = &newkeys[MODE_IN]->enc;
1058 mac = &newkeys[MODE_IN]->mac;
1059 comp = &newkeys[MODE_IN]->comp;
1061 maclen = mac && mac->enabled ? mac->mac_len : 0;
1062 block_size = enc ? enc->block_size : 8;
1064 if (packet_length == 0) {
1066 * check if input size is less than the cipher block size,
1067 * decrypt first block and extract length of incoming packet
1069 if (buffer_len(&input) < block_size)
1070 return SSH_MSG_NONE;
1071 buffer_clear(&incoming_packet);
1072 cp = buffer_append_space(&incoming_packet, block_size);
1073 cipher_crypt(&receive_context, cp, buffer_ptr(&input),
1074 block_size);
1075 cp = buffer_ptr(&incoming_packet);
1076 packet_length = get_u32(cp);
1077 if (packet_length < 1 + 4 || packet_length > 256 * 1024) {
1078 #ifdef PACKET_DEBUG
1079 buffer_dump(&incoming_packet);
1080 #endif
1081 packet_disconnect("Bad packet length %u.", packet_length);
1083 DBG(debug("input: packet len %u", packet_length+4));
1084 buffer_consume(&input, block_size);
1086 /* we have a partial packet of block_size bytes */
1087 need = 4 + packet_length - block_size;
1088 DBG(debug("partial packet %d, need %d, maclen %d", block_size,
1089 need, maclen));
1090 if (need % block_size != 0)
1091 fatal("padding error: need %d block %d mod %d",
1092 need, block_size, need % block_size);
1094 * check if the entire packet has been received and
1095 * decrypt into incoming_packet
1097 if (buffer_len(&input) < need + maclen)
1098 return SSH_MSG_NONE;
1099 #ifdef PACKET_DEBUG
1100 fprintf(stderr, "read_poll enc/full: ");
1101 buffer_dump(&input);
1102 #endif
1103 cp = buffer_append_space(&incoming_packet, need);
1104 cipher_crypt(&receive_context, cp, buffer_ptr(&input), need);
1105 buffer_consume(&input, need);
1107 * compute MAC over seqnr and packet,
1108 * increment sequence number for incoming packet
1110 if (mac && mac->enabled) {
1111 macbuf = mac_compute(mac, p_read.seqnr,
1112 buffer_ptr(&incoming_packet),
1113 buffer_len(&incoming_packet));
1114 if (memcmp(macbuf, buffer_ptr(&input), mac->mac_len) != 0)
1115 packet_disconnect("Corrupted MAC on input.");
1116 DBG(debug("MAC #%d ok", p_read.seqnr));
1117 buffer_consume(&input, mac->mac_len);
1119 if (seqnr_p != NULL)
1120 *seqnr_p = p_read.seqnr;
1121 if (++p_read.seqnr == 0)
1122 logit("incoming seqnr wraps around");
1123 if (++p_read.packets == 0)
1124 if (!(datafellows & SSH_BUG_NOREKEY))
1125 fatal("XXX too many packets with same key");
1126 p_read.blocks += (packet_length + 4) / block_size;
1128 /* get padlen */
1129 cp = buffer_ptr(&incoming_packet);
1130 padlen = cp[4];
1131 DBG(debug("input: padlen %d", padlen));
1132 if (padlen < 4)
1133 packet_disconnect("Corrupted padlen %d on input.", padlen);
1135 /* skip packet size + padlen, discard padding */
1136 buffer_consume(&incoming_packet, 4 + 1);
1137 buffer_consume_end(&incoming_packet, padlen);
1139 DBG(debug("input: len before de-compress %d", buffer_len(&incoming_packet)));
1140 if (comp && comp->enabled) {
1141 buffer_clear(&compression_buffer);
1142 buffer_uncompress(&incoming_packet, &compression_buffer);
1143 buffer_clear(&incoming_packet);
1144 buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
1145 buffer_len(&compression_buffer));
1146 DBG(debug("input: len after de-compress %d",
1147 buffer_len(&incoming_packet)));
1150 * get packet type, implies consume.
1151 * return length of payload (without type field)
1153 type = buffer_get_char(&incoming_packet);
1154 if (type < SSH2_MSG_MIN || type >= SSH2_MSG_LOCAL_MIN)
1155 packet_disconnect("Invalid ssh2 packet type: %d", type);
1156 if (type == SSH2_MSG_NEWKEYS)
1157 set_newkeys(MODE_IN);
1158 else if (type == SSH2_MSG_USERAUTH_SUCCESS && !server_side)
1159 packet_enable_delayed_compress();
1160 #ifdef PACKET_DEBUG
1161 fprintf(stderr, "read/plain[%d]:\r\n", type);
1162 buffer_dump(&incoming_packet);
1163 #endif
1164 /* reset for next packet */
1165 packet_length = 0;
1166 return type;
1170 packet_read_poll_seqnr(u_int32_t *seqnr_p)
1172 u_int reason, seqnr;
1173 u_char type;
1174 char *msg;
1176 for (;;) {
1177 if (compat20) {
1178 type = packet_read_poll2(seqnr_p);
1179 if (type)
1180 DBG(debug("received packet type %d", type));
1181 switch (type) {
1182 case SSH2_MSG_IGNORE:
1183 break;
1184 case SSH2_MSG_DEBUG:
1185 packet_get_char();
1186 msg = packet_get_string(NULL);
1187 debug("Remote: %.900s", msg);
1188 xfree(msg);
1189 msg = packet_get_string(NULL);
1190 xfree(msg);
1191 break;
1192 case SSH2_MSG_DISCONNECT:
1193 reason = packet_get_int();
1194 msg = packet_get_string(NULL);
1195 logit("Received disconnect from %s: %u: %.400s",
1196 get_remote_ipaddr(), reason, msg);
1197 xfree(msg);
1198 cleanup_exit(255);
1199 break;
1200 case SSH2_MSG_UNIMPLEMENTED:
1201 seqnr = packet_get_int();
1202 debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1203 seqnr);
1204 break;
1205 default:
1206 return type;
1208 } else {
1209 type = packet_read_poll1();
1210 switch (type) {
1211 case SSH_MSG_IGNORE:
1212 break;
1213 case SSH_MSG_DEBUG:
1214 msg = packet_get_string(NULL);
1215 debug("Remote: %.900s", msg);
1216 xfree(msg);
1217 break;
1218 case SSH_MSG_DISCONNECT:
1219 msg = packet_get_string(NULL);
1220 logit("Received disconnect from %s: %.400s",
1221 get_remote_ipaddr(), msg);
1222 cleanup_exit(255);
1223 xfree(msg);
1224 break;
1225 default:
1226 if (type)
1227 DBG(debug("received packet type %d", type));
1228 return type;
1235 packet_read_poll(void)
1237 return packet_read_poll_seqnr(NULL);
1241 * Buffers the given amount of input characters. This is intended to be used
1242 * together with packet_read_poll.
1245 void
1246 packet_process_incoming(const char *buf, u_int len)
1248 buffer_append(&input, buf, len);
1251 /* Returns a character from the packet. */
1253 u_int
1254 packet_get_char(void)
1256 char ch;
1258 buffer_get(&incoming_packet, &ch, 1);
1259 return (u_char) ch;
1262 /* Returns an integer from the packet data. */
1264 u_int
1265 packet_get_int(void)
1267 return buffer_get_int(&incoming_packet);
1271 * Returns an arbitrary precision integer from the packet data. The integer
1272 * must have been initialized before this call.
1275 void
1276 packet_get_bignum(BIGNUM * value)
1278 buffer_get_bignum(&incoming_packet, value);
1281 void
1282 packet_get_bignum2(BIGNUM * value)
1284 buffer_get_bignum2(&incoming_packet, value);
1287 void *
1288 packet_get_raw(u_int *length_ptr)
1290 u_int bytes = buffer_len(&incoming_packet);
1292 if (length_ptr != NULL)
1293 *length_ptr = bytes;
1294 return buffer_ptr(&incoming_packet);
1298 packet_remaining(void)
1300 return buffer_len(&incoming_packet);
1304 * Returns a string from the packet data. The string is allocated using
1305 * xmalloc; it is the responsibility of the calling program to free it when
1306 * no longer needed. The length_ptr argument may be NULL, or point to an
1307 * integer into which the length of the string is stored.
1310 void *
1311 packet_get_string(u_int *length_ptr)
1313 return buffer_get_string(&incoming_packet, length_ptr);
1317 * Sends a diagnostic message from the server to the client. This message
1318 * can be sent at any time (but not while constructing another message). The
1319 * message is printed immediately, but only if the client is being executed
1320 * in verbose mode. These messages are primarily intended to ease debugging
1321 * authentication problems. The length of the formatted message must not
1322 * exceed 1024 bytes. This will automatically call packet_write_wait.
1325 void
1326 packet_send_debug(const char *fmt,...)
1328 char buf[1024];
1329 va_list args;
1331 if (compat20 && (datafellows & SSH_BUG_DEBUG))
1332 return;
1334 va_start(args, fmt);
1335 vsnprintf(buf, sizeof(buf), fmt, args);
1336 va_end(args);
1338 if (compat20) {
1339 packet_start(SSH2_MSG_DEBUG);
1340 packet_put_char(0); /* bool: always display */
1341 packet_put_cstring(buf);
1342 packet_put_cstring("");
1343 } else {
1344 packet_start(SSH_MSG_DEBUG);
1345 packet_put_cstring(buf);
1347 packet_send();
1348 packet_write_wait();
1352 * Logs the error plus constructs and sends a disconnect packet, closes the
1353 * connection, and exits. This function never returns. The error message
1354 * should not contain a newline. The length of the formatted message must
1355 * not exceed 1024 bytes.
1358 void
1359 packet_disconnect(const char *fmt,...)
1361 char buf[1024];
1362 va_list args;
1363 static int disconnecting = 0;
1365 if (disconnecting) /* Guard against recursive invocations. */
1366 fatal("packet_disconnect called recursively.");
1367 disconnecting = 1;
1370 * Format the message. Note that the caller must make sure the
1371 * message is of limited size.
1373 va_start(args, fmt);
1374 vsnprintf(buf, sizeof(buf), fmt, args);
1375 va_end(args);
1377 /* Display the error locally */
1378 logit("Disconnecting: %.100s", buf);
1380 /* Send the disconnect message to the other side, and wait for it to get sent. */
1381 if (compat20) {
1382 packet_start(SSH2_MSG_DISCONNECT);
1383 packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1384 packet_put_cstring(buf);
1385 packet_put_cstring("");
1386 } else {
1387 packet_start(SSH_MSG_DISCONNECT);
1388 packet_put_cstring(buf);
1390 packet_send();
1391 packet_write_wait();
1393 /* Stop listening for connections. */
1394 channel_close_all();
1396 /* Close the connection. */
1397 packet_close();
1398 cleanup_exit(255);
1401 /* Checks if there is any buffered output, and tries to write some of the output. */
1403 void
1404 packet_write_poll(void)
1406 int len = buffer_len(&output);
1408 if (len > 0) {
1409 len = write(connection_out, buffer_ptr(&output), len);
1410 if (len <= 0) {
1411 if (errno == EAGAIN)
1412 return;
1413 else
1414 fatal("Write failed: %.100s", strerror(errno));
1416 buffer_consume(&output, len);
1421 * Calls packet_write_poll repeatedly until all pending output data has been
1422 * written.
1425 void
1426 packet_write_wait(void)
1428 fd_set *setp;
1430 setp = (fd_set *)xcalloc(howmany(connection_out + 1, NFDBITS),
1431 sizeof(fd_mask));
1432 packet_write_poll();
1433 while (packet_have_data_to_write()) {
1434 memset(setp, 0, howmany(connection_out + 1, NFDBITS) *
1435 sizeof(fd_mask));
1436 FD_SET(connection_out, setp);
1437 while (select(connection_out + 1, NULL, setp, NULL, NULL) == -1 &&
1438 (errno == EAGAIN || errno == EINTR))
1440 packet_write_poll();
1442 xfree(setp);
1445 /* Returns true if there is buffered data to write to the connection. */
1448 packet_have_data_to_write(void)
1450 return buffer_len(&output) != 0;
1453 /* Returns true if there is not too much data to write to the connection. */
1456 packet_not_very_much_data_to_write(void)
1458 if (interactive_mode)
1459 return buffer_len(&output) < 16384;
1460 else
1461 return buffer_len(&output) < 128 * 1024;
1465 static void
1466 packet_set_tos(int interactive)
1468 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1469 int tos = interactive ? IPTOS_LOWDELAY : IPTOS_THROUGHPUT;
1471 if (!packet_connection_is_on_socket() ||
1472 !packet_connection_is_ipv4())
1473 return;
1474 if (setsockopt(connection_in, IPPROTO_IP, IP_TOS, &tos,
1475 sizeof(tos)) < 0)
1476 error("setsockopt IP_TOS %d: %.100s:",
1477 tos, strerror(errno));
1478 #endif
1481 /* Informs that the current session is interactive. Sets IP flags for that. */
1483 void
1484 packet_set_interactive(int interactive)
1486 static int called = 0;
1488 if (called)
1489 return;
1490 called = 1;
1492 /* Record that we are in interactive mode. */
1493 interactive_mode = interactive;
1495 /* Only set socket options if using a socket. */
1496 if (!packet_connection_is_on_socket())
1497 return;
1498 set_nodelay(connection_in);
1499 packet_set_tos(interactive);
1502 /* Returns true if the current connection is interactive. */
1505 packet_is_interactive(void)
1507 return interactive_mode;
1511 packet_set_maxsize(u_int s)
1513 static int called = 0;
1515 if (called) {
1516 logit("packet_set_maxsize: called twice: old %d new %d",
1517 max_packet_size, s);
1518 return -1;
1520 if (s < 4 * 1024 || s > 1024 * 1024) {
1521 logit("packet_set_maxsize: bad size %d", s);
1522 return -1;
1524 called = 1;
1525 debug("packet_set_maxsize: setting to %d", s);
1526 max_packet_size = s;
1527 return s;
1530 /* roundup current message to pad bytes */
1531 void
1532 packet_add_padding(u_char pad)
1534 extra_pad = pad;
1538 * 9.2. Ignored Data Message
1540 * byte SSH_MSG_IGNORE
1541 * string data
1543 * All implementations MUST understand (and ignore) this message at any
1544 * time (after receiving the protocol version). No implementation is
1545 * required to send them. This message can be used as an additional
1546 * protection measure against advanced traffic analysis techniques.
1548 void
1549 packet_send_ignore(int nbytes)
1551 u_int32_t rnd = 0;
1552 int i;
1554 packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1555 packet_put_int(nbytes);
1556 for (i = 0; i < nbytes; i++) {
1557 if (i % 4 == 0)
1558 rnd = arc4random();
1559 packet_put_char((u_char)rnd & 0xff);
1560 rnd >>= 8;
1564 #define MAX_PACKETS (1U<<31)
1566 packet_need_rekeying(void)
1568 if (datafellows & SSH_BUG_NOREKEY)
1569 return 0;
1570 return
1571 (p_send.packets > MAX_PACKETS) ||
1572 (p_read.packets > MAX_PACKETS) ||
1573 (max_blocks_out && (p_send.blocks > max_blocks_out)) ||
1574 (max_blocks_in && (p_read.blocks > max_blocks_in));
1577 void
1578 packet_set_rekey_limit(u_int32_t bytes)
1580 rekey_limit = bytes;
1583 void
1584 packet_set_server(void)
1586 server_side = 1;
1589 void
1590 packet_set_authenticated(void)
1592 after_authentication = 1;