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