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