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