]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - crypto/openssh/packet.c
MFC 241730: Correct the order of the MFU and MRU labels.
[FreeBSD/stable/8.git] / crypto / openssh / packet.c
1 /* $OpenBSD: packet.c,v 1.166 2009/06/27 09:29:06 andreas Exp $ */
2 /* $FreeBSD$ */
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))
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, u_int32_t *packets,
399     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 /* returns 1 if connection is via ipv4 */
430
431 int
432 packet_connection_is_ipv4(void)
433 {
434         struct sockaddr_storage to;
435         socklen_t tolen = sizeof(to);
436
437         memset(&to, 0, sizeof(to));
438         if (getsockname(active_state->connection_out, (struct sockaddr *)&to,
439             &tolen) < 0)
440                 return 0;
441         if (to.ss_family == AF_INET)
442                 return 1;
443 #ifdef IPV4_IN_IPV6
444         if (to.ss_family == AF_INET6 &&
445             IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&to)->sin6_addr))
446                 return 1;
447 #endif
448         return 0;
449 }
450
451 /* Sets the connection into non-blocking mode. */
452
453 void
454 packet_set_nonblocking(void)
455 {
456         /* Set the socket into non-blocking mode. */
457         set_nonblock(active_state->connection_in);
458
459         if (active_state->connection_out != active_state->connection_in)
460                 set_nonblock(active_state->connection_out);
461 }
462
463 /* Returns the socket used for reading. */
464
465 int
466 packet_get_connection_in(void)
467 {
468         return active_state->connection_in;
469 }
470
471 /* Returns the descriptor used for writing. */
472
473 int
474 packet_get_connection_out(void)
475 {
476         return active_state->connection_out;
477 }
478
479 /* Closes the connection and clears and frees internal data structures. */
480
481 void
482 packet_close(void)
483 {
484         if (!active_state->initialized)
485                 return;
486         active_state->initialized = 0;
487         if (active_state->connection_in == active_state->connection_out) {
488                 shutdown(active_state->connection_out, SHUT_RDWR);
489                 close(active_state->connection_out);
490         } else {
491                 close(active_state->connection_in);
492                 close(active_state->connection_out);
493         }
494         buffer_free(&active_state->input);
495         buffer_free(&active_state->output);
496         buffer_free(&active_state->outgoing_packet);
497         buffer_free(&active_state->incoming_packet);
498         if (active_state->compression_buffer_ready) {
499                 buffer_free(&active_state->compression_buffer);
500                 buffer_compress_uninit();
501         }
502         cipher_cleanup(&active_state->send_context);
503         cipher_cleanup(&active_state->receive_context);
504 }
505
506 /* Sets remote side protocol flags. */
507
508 void
509 packet_set_protocol_flags(u_int protocol_flags)
510 {
511         active_state->remote_protocol_flags = protocol_flags;
512 }
513
514 /* Returns the remote protocol flags set earlier by the above function. */
515
516 u_int
517 packet_get_protocol_flags(void)
518 {
519         return active_state->remote_protocol_flags;
520 }
521
522 /*
523  * Starts packet compression from the next packet on in both directions.
524  * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
525  */
526
527 static void
528 packet_init_compression(void)
529 {
530         if (active_state->compression_buffer_ready == 1)
531                 return;
532         active_state->compression_buffer_ready = 1;
533         buffer_init(&active_state->compression_buffer);
534 }
535
536 void
537 packet_start_compression(int level)
538 {
539         if (active_state->packet_compression && !compat20)
540                 fatal("Compression already enabled.");
541         active_state->packet_compression = 1;
542         packet_init_compression();
543         buffer_compress_init_send(level);
544         buffer_compress_init_recv();
545 }
546
547 /*
548  * Causes any further packets to be encrypted using the given key.  The same
549  * key is used for both sending and reception.  However, both directions are
550  * encrypted independently of each other.
551  */
552
553 void
554 packet_set_encryption_key(const u_char *key, u_int keylen,
555     int number)
556 {
557         Cipher *cipher = cipher_by_number(number);
558
559         if (cipher == NULL)
560                 fatal("packet_set_encryption_key: unknown cipher number %d", number);
561         if (keylen < 20)
562                 fatal("packet_set_encryption_key: keylen too small: %d", keylen);
563         if (keylen > SSH_SESSION_KEY_LENGTH)
564                 fatal("packet_set_encryption_key: keylen too big: %d", keylen);
565         memcpy(active_state->ssh1_key, key, keylen);
566         active_state->ssh1_keylen = keylen;
567         cipher_init(&active_state->send_context, cipher, key, keylen, NULL,
568             0, CIPHER_ENCRYPT);
569         cipher_init(&active_state->receive_context, cipher, key, keylen, NULL,
570             0, CIPHER_DECRYPT);
571 }
572
573 u_int
574 packet_get_encryption_key(u_char *key)
575 {
576         if (key == NULL)
577                 return (active_state->ssh1_keylen);
578         memcpy(key, active_state->ssh1_key, active_state->ssh1_keylen);
579         return (active_state->ssh1_keylen);
580 }
581
582 /* Start constructing a packet to send. */
583 void
584 packet_start(u_char type)
585 {
586         u_char buf[9];
587         int len;
588
589         DBG(debug("packet_start[%d]", type));
590         len = compat20 ? 6 : 9;
591         memset(buf, 0, len - 1);
592         buf[len - 1] = type;
593         buffer_clear(&active_state->outgoing_packet);
594         buffer_append(&active_state->outgoing_packet, buf, len);
595 }
596
597 /* Append payload. */
598 void
599 packet_put_char(int value)
600 {
601         char ch = value;
602
603         buffer_append(&active_state->outgoing_packet, &ch, 1);
604 }
605
606 void
607 packet_put_int(u_int value)
608 {
609         buffer_put_int(&active_state->outgoing_packet, value);
610 }
611
612 void
613 packet_put_int64(u_int64_t value)
614 {
615         buffer_put_int64(&active_state->outgoing_packet, value);
616 }
617
618 void
619 packet_put_string(const void *buf, u_int len)
620 {
621         buffer_put_string(&active_state->outgoing_packet, buf, len);
622 }
623
624 void
625 packet_put_cstring(const char *str)
626 {
627         buffer_put_cstring(&active_state->outgoing_packet, str);
628 }
629
630 void
631 packet_put_raw(const void *buf, u_int len)
632 {
633         buffer_append(&active_state->outgoing_packet, buf, len);
634 }
635
636 void
637 packet_put_bignum(BIGNUM * value)
638 {
639         buffer_put_bignum(&active_state->outgoing_packet, value);
640 }
641
642 void
643 packet_put_bignum2(BIGNUM * value)
644 {
645         buffer_put_bignum2(&active_state->outgoing_packet, value);
646 }
647
648 /*
649  * Finalizes and sends the packet.  If the encryption key has been set,
650  * encrypts the packet before sending.
651  */
652
653 static void
654 packet_send1(void)
655 {
656         u_char buf[8], *cp;
657         int i, padding, len;
658         u_int checksum;
659         u_int32_t rnd = 0;
660
661         /*
662          * If using packet compression, compress the payload of the outgoing
663          * packet.
664          */
665         if (active_state->packet_compression) {
666                 buffer_clear(&active_state->compression_buffer);
667                 /* Skip padding. */
668                 buffer_consume(&active_state->outgoing_packet, 8);
669                 /* padding */
670                 buffer_append(&active_state->compression_buffer,
671                     "\0\0\0\0\0\0\0\0", 8);
672                 buffer_compress(&active_state->outgoing_packet,
673                     &active_state->compression_buffer);
674                 buffer_clear(&active_state->outgoing_packet);
675                 buffer_append(&active_state->outgoing_packet,
676                     buffer_ptr(&active_state->compression_buffer),
677                     buffer_len(&active_state->compression_buffer));
678         }
679         /* Compute packet length without padding (add checksum, remove padding). */
680         len = buffer_len(&active_state->outgoing_packet) + 4 - 8;
681
682         /* Insert padding. Initialized to zero in packet_start1() */
683         padding = 8 - len % 8;
684         if (!active_state->send_context.plaintext) {
685                 cp = buffer_ptr(&active_state->outgoing_packet);
686                 for (i = 0; i < padding; i++) {
687                         if (i % 4 == 0)
688                                 rnd = arc4random();
689                         cp[7 - i] = rnd & 0xff;
690                         rnd >>= 8;
691                 }
692         }
693         buffer_consume(&active_state->outgoing_packet, 8 - padding);
694
695         /* Add check bytes. */
696         checksum = ssh_crc32(buffer_ptr(&active_state->outgoing_packet),
697             buffer_len(&active_state->outgoing_packet));
698         put_u32(buf, checksum);
699         buffer_append(&active_state->outgoing_packet, buf, 4);
700
701 #ifdef PACKET_DEBUG
702         fprintf(stderr, "packet_send plain: ");
703         buffer_dump(&active_state->outgoing_packet);
704 #endif
705
706         /* Append to output. */
707         put_u32(buf, len);
708         buffer_append(&active_state->output, buf, 4);
709         cp = buffer_append_space(&active_state->output,
710             buffer_len(&active_state->outgoing_packet));
711         cipher_crypt(&active_state->send_context, cp,
712             buffer_ptr(&active_state->outgoing_packet),
713             buffer_len(&active_state->outgoing_packet));
714
715 #ifdef PACKET_DEBUG
716         fprintf(stderr, "encrypted: ");
717         buffer_dump(&active_state->output);
718 #endif
719         active_state->p_send.packets++;
720         active_state->p_send.bytes += len +
721             buffer_len(&active_state->outgoing_packet);
722         buffer_clear(&active_state->outgoing_packet);
723
724         /*
725          * Note that the packet is now only buffered in output.  It won't be
726          * actually sent until packet_write_wait or packet_write_poll is
727          * called.
728          */
729 }
730
731 void
732 set_newkeys(int mode)
733 {
734         Enc *enc;
735         Mac *mac;
736         Comp *comp;
737         CipherContext *cc;
738         u_int64_t *max_blocks;
739         int crypt_type;
740
741         debug2("set_newkeys: mode %d", mode);
742
743         if (mode == MODE_OUT) {
744                 cc = &active_state->send_context;
745                 crypt_type = CIPHER_ENCRYPT;
746                 active_state->p_send.packets = active_state->p_send.blocks = 0;
747                 max_blocks = &active_state->max_blocks_out;
748         } else {
749                 cc = &active_state->receive_context;
750                 crypt_type = CIPHER_DECRYPT;
751                 active_state->p_read.packets = active_state->p_read.blocks = 0;
752                 max_blocks = &active_state->max_blocks_in;
753         }
754         if (active_state->newkeys[mode] != NULL) {
755                 debug("set_newkeys: rekeying");
756                 cipher_cleanup(cc);
757                 enc  = &active_state->newkeys[mode]->enc;
758                 mac  = &active_state->newkeys[mode]->mac;
759                 comp = &active_state->newkeys[mode]->comp;
760                 mac_clear(mac);
761                 xfree(enc->name);
762                 xfree(enc->iv);
763                 xfree(enc->key);
764                 xfree(mac->name);
765                 xfree(mac->key);
766                 xfree(comp->name);
767                 xfree(active_state->newkeys[mode]);
768         }
769         active_state->newkeys[mode] = kex_get_newkeys(mode);
770         if (active_state->newkeys[mode] == NULL)
771                 fatal("newkeys: no keys for mode %d", mode);
772         enc  = &active_state->newkeys[mode]->enc;
773         mac  = &active_state->newkeys[mode]->mac;
774         comp = &active_state->newkeys[mode]->comp;
775         if (mac_init(mac) == 0)
776                 mac->enabled = 1;
777         DBG(debug("cipher_init_context: %d", mode));
778         cipher_init(cc, enc->cipher, enc->key, enc->key_len,
779             enc->iv, enc->block_size, crypt_type);
780         /* Deleting the keys does not gain extra security */
781         /* memset(enc->iv,  0, enc->block_size);
782            memset(enc->key, 0, enc->key_len);
783            memset(mac->key, 0, mac->key_len); */
784         if ((comp->type == COMP_ZLIB ||
785             (comp->type == COMP_DELAYED &&
786              active_state->after_authentication)) && comp->enabled == 0) {
787                 packet_init_compression();
788                 if (mode == MODE_OUT)
789                         buffer_compress_init_send(6);
790                 else
791                         buffer_compress_init_recv();
792                 comp->enabled = 1;
793         }
794         /*
795          * The 2^(blocksize*2) limit is too expensive for 3DES,
796          * blowfish, etc, so enforce a 1GB limit for small blocksizes.
797          */
798         if (enc->block_size >= 16)
799                 *max_blocks = (u_int64_t)1 << (enc->block_size*2);
800         else
801                 *max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
802         if (active_state->rekey_limit)
803                 *max_blocks = MIN(*max_blocks,
804                     active_state->rekey_limit / enc->block_size);
805 }
806
807 /*
808  * Delayed compression for SSH2 is enabled after authentication:
809  * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
810  * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
811  */
812 static void
813 packet_enable_delayed_compress(void)
814 {
815         Comp *comp = NULL;
816         int mode;
817
818         /*
819          * Remember that we are past the authentication step, so rekeying
820          * with COMP_DELAYED will turn on compression immediately.
821          */
822         active_state->after_authentication = 1;
823         for (mode = 0; mode < MODE_MAX; mode++) {
824                 /* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
825                 if (active_state->newkeys[mode] == NULL)
826                         continue;
827                 comp = &active_state->newkeys[mode]->comp;
828                 if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
829                         packet_init_compression();
830                         if (mode == MODE_OUT)
831                                 buffer_compress_init_send(6);
832                         else
833                                 buffer_compress_init_recv();
834                         comp->enabled = 1;
835                 }
836         }
837 }
838
839 /*
840  * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
841  */
842 static void
843 packet_send2_wrapped(void)
844 {
845         u_char type, *cp, *macbuf = NULL;
846         u_char padlen, pad;
847         u_int packet_length = 0;
848         u_int i, len;
849         u_int32_t rnd = 0;
850         Enc *enc   = NULL;
851         Mac *mac   = NULL;
852         Comp *comp = NULL;
853         int block_size;
854
855         if (active_state->newkeys[MODE_OUT] != NULL) {
856                 enc  = &active_state->newkeys[MODE_OUT]->enc;
857                 mac  = &active_state->newkeys[MODE_OUT]->mac;
858                 comp = &active_state->newkeys[MODE_OUT]->comp;
859         }
860         block_size = enc ? enc->block_size : 8;
861
862         cp = buffer_ptr(&active_state->outgoing_packet);
863         type = cp[5];
864
865 #ifdef PACKET_DEBUG
866         fprintf(stderr, "plain:     ");
867         buffer_dump(&active_state->outgoing_packet);
868 #endif
869
870         if (comp && comp->enabled) {
871                 len = buffer_len(&active_state->outgoing_packet);
872                 /* skip header, compress only payload */
873                 buffer_consume(&active_state->outgoing_packet, 5);
874                 buffer_clear(&active_state->compression_buffer);
875                 buffer_compress(&active_state->outgoing_packet,
876                     &active_state->compression_buffer);
877                 buffer_clear(&active_state->outgoing_packet);
878                 buffer_append(&active_state->outgoing_packet, "\0\0\0\0\0", 5);
879                 buffer_append(&active_state->outgoing_packet,
880                     buffer_ptr(&active_state->compression_buffer),
881                     buffer_len(&active_state->compression_buffer));
882                 DBG(debug("compression: raw %d compressed %d", len,
883                     buffer_len(&active_state->outgoing_packet)));
884         }
885
886         /* sizeof (packet_len + pad_len + payload) */
887         len = buffer_len(&active_state->outgoing_packet);
888
889         /*
890          * calc size of padding, alloc space, get random data,
891          * minimum padding is 4 bytes
892          */
893         padlen = block_size - (len % block_size);
894         if (padlen < 4)
895                 padlen += block_size;
896         if (active_state->extra_pad) {
897                 /* will wrap if extra_pad+padlen > 255 */
898                 active_state->extra_pad =
899                     roundup(active_state->extra_pad, block_size);
900                 pad = active_state->extra_pad -
901                     ((len + padlen) % active_state->extra_pad);
902                 debug3("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
903                     pad, len, padlen, active_state->extra_pad);
904                 padlen += pad;
905                 active_state->extra_pad = 0;
906         }
907         cp = buffer_append_space(&active_state->outgoing_packet, padlen);
908         if (enc && !active_state->send_context.plaintext) {
909                 /* random padding */
910                 for (i = 0; i < padlen; i++) {
911                         if (i % 4 == 0)
912                                 rnd = arc4random();
913                         cp[i] = rnd & 0xff;
914                         rnd >>= 8;
915                 }
916         } else {
917                 /* clear padding */
918                 memset(cp, 0, padlen);
919         }
920         /* packet_length includes payload, padding and padding length field */
921         packet_length = buffer_len(&active_state->outgoing_packet) - 4;
922         cp = buffer_ptr(&active_state->outgoing_packet);
923         put_u32(cp, packet_length);
924         cp[4] = padlen;
925         DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen));
926
927         /* compute MAC over seqnr and packet(length fields, payload, padding) */
928         if (mac && mac->enabled) {
929                 macbuf = mac_compute(mac, active_state->p_send.seqnr,
930                     buffer_ptr(&active_state->outgoing_packet),
931                     buffer_len(&active_state->outgoing_packet));
932                 DBG(debug("done calc MAC out #%d", active_state->p_send.seqnr));
933         }
934         /* encrypt packet and append to output buffer. */
935         cp = buffer_append_space(&active_state->output,
936             buffer_len(&active_state->outgoing_packet));
937         cipher_crypt(&active_state->send_context, cp,
938             buffer_ptr(&active_state->outgoing_packet),
939             buffer_len(&active_state->outgoing_packet));
940         /* append unencrypted MAC */
941         if (mac && mac->enabled)
942                 buffer_append(&active_state->output, macbuf, mac->mac_len);
943 #ifdef PACKET_DEBUG
944         fprintf(stderr, "encrypted: ");
945         buffer_dump(&active_state->output);
946 #endif
947         /* increment sequence number for outgoing packets */
948         if (++active_state->p_send.seqnr == 0)
949                 logit("outgoing seqnr wraps around");
950         if (++active_state->p_send.packets == 0)
951                 if (!(datafellows & SSH_BUG_NOREKEY))
952                         fatal("XXX too many packets with same key");
953         active_state->p_send.blocks += (packet_length + 4) / block_size;
954         active_state->p_send.bytes += packet_length + 4;
955         buffer_clear(&active_state->outgoing_packet);
956
957         if (type == SSH2_MSG_NEWKEYS)
958                 set_newkeys(MODE_OUT);
959         else if (type == SSH2_MSG_USERAUTH_SUCCESS && active_state->server_side)
960                 packet_enable_delayed_compress();
961 }
962
963 static void
964 packet_send2(void)
965 {
966         struct packet *p;
967         u_char type, *cp;
968
969         cp = buffer_ptr(&active_state->outgoing_packet);
970         type = cp[5];
971
972         /* during rekeying we can only send key exchange messages */
973         if (active_state->rekeying) {
974                 if (!((type >= SSH2_MSG_TRANSPORT_MIN) &&
975                     (type <= SSH2_MSG_TRANSPORT_MAX))) {
976                         debug("enqueue packet: %u", type);
977                         p = xmalloc(sizeof(*p));
978                         p->type = type;
979                         memcpy(&p->payload, &active_state->outgoing_packet,
980                             sizeof(Buffer));
981                         buffer_init(&active_state->outgoing_packet);
982                         TAILQ_INSERT_TAIL(&active_state->outgoing, p, next);
983                         return;
984                 }
985         }
986
987         /* rekeying starts with sending KEXINIT */
988         if (type == SSH2_MSG_KEXINIT)
989                 active_state->rekeying = 1;
990
991         packet_send2_wrapped();
992
993         /* after a NEWKEYS message we can send the complete queue */
994         if (type == SSH2_MSG_NEWKEYS) {
995                 active_state->rekeying = 0;
996                 while ((p = TAILQ_FIRST(&active_state->outgoing))) {
997                         type = p->type;
998                         debug("dequeue packet: %u", type);
999                         buffer_free(&active_state->outgoing_packet);
1000                         memcpy(&active_state->outgoing_packet, &p->payload,
1001                             sizeof(Buffer));
1002                         TAILQ_REMOVE(&active_state->outgoing, p, next);
1003                         xfree(p);
1004                         packet_send2_wrapped();
1005                 }
1006         }
1007 }
1008
1009 void
1010 packet_send(void)
1011 {
1012         if (compat20)
1013                 packet_send2();
1014         else
1015                 packet_send1();
1016         DBG(debug("packet_send done"));
1017 }
1018
1019 /*
1020  * Waits until a packet has been received, and returns its type.  Note that
1021  * no other data is processed until this returns, so this function should not
1022  * be used during the interactive session.
1023  */
1024
1025 int
1026 packet_read_seqnr(u_int32_t *seqnr_p)
1027 {
1028         int type, len, ret, ms_remain, cont;
1029         fd_set *setp;
1030         char buf[8192];
1031         struct timeval timeout, start, *timeoutp = NULL;
1032
1033         DBG(debug("packet_read()"));
1034
1035         setp = (fd_set *)xcalloc(howmany(active_state->connection_in + 1,
1036             NFDBITS), sizeof(fd_mask));
1037
1038         /* Since we are blocking, ensure that all written packets have been sent. */
1039         packet_write_wait();
1040
1041         /* Stay in the loop until we have received a complete packet. */
1042         for (;;) {
1043                 /* Try to read a packet from the buffer. */
1044                 type = packet_read_poll_seqnr(seqnr_p);
1045                 if (!compat20 && (
1046                     type == SSH_SMSG_SUCCESS
1047                     || type == SSH_SMSG_FAILURE
1048                     || type == SSH_CMSG_EOF
1049                     || type == SSH_CMSG_EXIT_CONFIRMATION))
1050                         packet_check_eom();
1051                 /* If we got a packet, return it. */
1052                 if (type != SSH_MSG_NONE) {
1053                         xfree(setp);
1054                         return type;
1055                 }
1056                 /*
1057                  * Otherwise, wait for some data to arrive, add it to the
1058                  * buffer, and try again.
1059                  */
1060                 memset(setp, 0, howmany(active_state->connection_in + 1,
1061                     NFDBITS) * sizeof(fd_mask));
1062                 FD_SET(active_state->connection_in, setp);
1063
1064                 if (active_state->packet_timeout_ms > 0) {
1065                         ms_remain = active_state->packet_timeout_ms;
1066                         timeoutp = &timeout;
1067                 }
1068                 /* Wait for some data to arrive. */
1069                 for (;;) {
1070                         if (active_state->packet_timeout_ms != -1) {
1071                                 ms_to_timeval(&timeout, ms_remain);
1072                                 gettimeofday(&start, NULL);
1073                         }
1074                         if ((ret = select(active_state->connection_in + 1, setp,
1075                             NULL, NULL, timeoutp)) >= 0)
1076                                 break;
1077                         if (errno != EAGAIN && errno != EINTR &&
1078                             errno != EWOULDBLOCK)
1079                                 break;
1080                         if (active_state->packet_timeout_ms == -1)
1081                                 continue;
1082                         ms_subtract_diff(&start, &ms_remain);
1083                         if (ms_remain <= 0) {
1084                                 ret = 0;
1085                                 break;
1086                         }
1087                 }
1088                 if (ret == 0) {
1089                         logit("Connection to %.200s timed out while "
1090                             "waiting to read", get_remote_ipaddr());
1091                         cleanup_exit(255);
1092                 }
1093                 /* Read data from the socket. */
1094                 do {
1095                         cont = 0;
1096                         len = roaming_read(active_state->connection_in, buf,
1097                             sizeof(buf), &cont);
1098                 } while (len == 0 && cont);
1099                 if (len == 0) {
1100                         logit("Connection closed by %.200s", get_remote_ipaddr());
1101                         cleanup_exit(255);
1102                 }
1103                 if (len < 0)
1104                         fatal("Read from socket failed: %.100s", strerror(errno));
1105                 /* Append it to the buffer. */
1106                 packet_process_incoming(buf, len);
1107         }
1108         /* NOTREACHED */
1109 }
1110
1111 int
1112 packet_read(void)
1113 {
1114         return packet_read_seqnr(NULL);
1115 }
1116
1117 /*
1118  * Waits until a packet has been received, verifies that its type matches
1119  * that given, and gives a fatal error and exits if there is a mismatch.
1120  */
1121
1122 void
1123 packet_read_expect(int expected_type)
1124 {
1125         int type;
1126
1127         type = packet_read();
1128         if (type != expected_type)
1129                 packet_disconnect("Protocol error: expected packet type %d, got %d",
1130                     expected_type, type);
1131 }
1132
1133 /* Checks if a full packet is available in the data received so far via
1134  * packet_process_incoming.  If so, reads the packet; otherwise returns
1135  * SSH_MSG_NONE.  This does not wait for data from the connection.
1136  *
1137  * SSH_MSG_DISCONNECT is handled specially here.  Also,
1138  * SSH_MSG_IGNORE messages are skipped by this function and are never returned
1139  * to higher levels.
1140  */
1141
1142 static int
1143 packet_read_poll1(void)
1144 {
1145         u_int len, padded_len;
1146         u_char *cp, type;
1147         u_int checksum, stored_checksum;
1148
1149         /* Check if input size is less than minimum packet size. */
1150         if (buffer_len(&active_state->input) < 4 + 8)
1151                 return SSH_MSG_NONE;
1152         /* Get length of incoming packet. */
1153         cp = buffer_ptr(&active_state->input);
1154         len = get_u32(cp);
1155         if (len < 1 + 2 + 2 || len > 256 * 1024)
1156                 packet_disconnect("Bad packet length %u.", len);
1157         padded_len = (len + 8) & ~7;
1158
1159         /* Check if the packet has been entirely received. */
1160         if (buffer_len(&active_state->input) < 4 + padded_len)
1161                 return SSH_MSG_NONE;
1162
1163         /* The entire packet is in buffer. */
1164
1165         /* Consume packet length. */
1166         buffer_consume(&active_state->input, 4);
1167
1168         /*
1169          * Cryptographic attack detector for ssh
1170          * (C)1998 CORE-SDI, Buenos Aires Argentina
1171          * Ariel Futoransky(futo@core-sdi.com)
1172          */
1173         if (!active_state->receive_context.plaintext) {
1174                 switch (detect_attack(buffer_ptr(&active_state->input),
1175                     padded_len)) {
1176                 case DEATTACK_DETECTED:
1177                         packet_disconnect("crc32 compensation attack: "
1178                             "network attack detected");
1179                 case DEATTACK_DOS_DETECTED:
1180                         packet_disconnect("deattack denial of "
1181                             "service detected");
1182                 }
1183         }
1184
1185         /* Decrypt data to incoming_packet. */
1186         buffer_clear(&active_state->incoming_packet);
1187         cp = buffer_append_space(&active_state->incoming_packet, padded_len);
1188         cipher_crypt(&active_state->receive_context, cp,
1189             buffer_ptr(&active_state->input), padded_len);
1190
1191         buffer_consume(&active_state->input, padded_len);
1192
1193 #ifdef PACKET_DEBUG
1194         fprintf(stderr, "read_poll plain: ");
1195         buffer_dump(&active_state->incoming_packet);
1196 #endif
1197
1198         /* Compute packet checksum. */
1199         checksum = ssh_crc32(buffer_ptr(&active_state->incoming_packet),
1200             buffer_len(&active_state->incoming_packet) - 4);
1201
1202         /* Skip padding. */
1203         buffer_consume(&active_state->incoming_packet, 8 - len % 8);
1204
1205         /* Test check bytes. */
1206         if (len != buffer_len(&active_state->incoming_packet))
1207                 packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
1208                     len, buffer_len(&active_state->incoming_packet));
1209
1210         cp = (u_char *)buffer_ptr(&active_state->incoming_packet) + len - 4;
1211         stored_checksum = get_u32(cp);
1212         if (checksum != stored_checksum)
1213                 packet_disconnect("Corrupted check bytes on input.");
1214         buffer_consume_end(&active_state->incoming_packet, 4);
1215
1216         if (active_state->packet_compression) {
1217                 buffer_clear(&active_state->compression_buffer);
1218                 buffer_uncompress(&active_state->incoming_packet,
1219                     &active_state->compression_buffer);
1220                 buffer_clear(&active_state->incoming_packet);
1221                 buffer_append(&active_state->incoming_packet,
1222                     buffer_ptr(&active_state->compression_buffer),
1223                     buffer_len(&active_state->compression_buffer));
1224         }
1225         active_state->p_read.packets++;
1226         active_state->p_read.bytes += padded_len + 4;
1227         type = buffer_get_char(&active_state->incoming_packet);
1228         if (type < SSH_MSG_MIN || type > SSH_MSG_MAX)
1229                 packet_disconnect("Invalid ssh1 packet type: %d", type);
1230         return type;
1231 }
1232
1233 static int
1234 packet_read_poll2(u_int32_t *seqnr_p)
1235 {
1236         u_int padlen, need;
1237         u_char *macbuf, *cp, type;
1238         u_int maclen, block_size;
1239         Enc *enc   = NULL;
1240         Mac *mac   = NULL;
1241         Comp *comp = NULL;
1242
1243         if (active_state->packet_discard)
1244                 return SSH_MSG_NONE;
1245
1246         if (active_state->newkeys[MODE_IN] != NULL) {
1247                 enc  = &active_state->newkeys[MODE_IN]->enc;
1248                 mac  = &active_state->newkeys[MODE_IN]->mac;
1249                 comp = &active_state->newkeys[MODE_IN]->comp;
1250         }
1251         maclen = mac && mac->enabled ? mac->mac_len : 0;
1252         block_size = enc ? enc->block_size : 8;
1253
1254         if (active_state->packlen == 0) {
1255                 /*
1256                  * check if input size is less than the cipher block size,
1257                  * decrypt first block and extract length of incoming packet
1258                  */
1259                 if (buffer_len(&active_state->input) < block_size)
1260                         return SSH_MSG_NONE;
1261                 buffer_clear(&active_state->incoming_packet);
1262                 cp = buffer_append_space(&active_state->incoming_packet,
1263                     block_size);
1264                 cipher_crypt(&active_state->receive_context, cp,
1265                     buffer_ptr(&active_state->input), block_size);
1266                 cp = buffer_ptr(&active_state->incoming_packet);
1267                 active_state->packlen = get_u32(cp);
1268                 if (active_state->packlen < 1 + 4 ||
1269                     active_state->packlen > PACKET_MAX_SIZE) {
1270 #ifdef PACKET_DEBUG
1271                         buffer_dump(&active_state->incoming_packet);
1272 #endif
1273                         logit("Bad packet length %u.", active_state->packlen);
1274                         packet_start_discard(enc, mac, active_state->packlen,
1275                             PACKET_MAX_SIZE);
1276                         return SSH_MSG_NONE;
1277                 }
1278                 DBG(debug("input: packet len %u", active_state->packlen+4));
1279                 buffer_consume(&active_state->input, block_size);
1280         }
1281         /* we have a partial packet of block_size bytes */
1282         need = 4 + active_state->packlen - block_size;
1283         DBG(debug("partial packet %d, need %d, maclen %d", block_size,
1284             need, maclen));
1285         if (need % block_size != 0) {
1286                 logit("padding error: need %d block %d mod %d",
1287                     need, block_size, need % block_size);
1288                 packet_start_discard(enc, mac, active_state->packlen,
1289                     PACKET_MAX_SIZE - block_size);
1290                 return SSH_MSG_NONE;
1291         }
1292         /*
1293          * check if the entire packet has been received and
1294          * decrypt into incoming_packet
1295          */
1296         if (buffer_len(&active_state->input) < need + maclen)
1297                 return SSH_MSG_NONE;
1298 #ifdef PACKET_DEBUG
1299         fprintf(stderr, "read_poll enc/full: ");
1300         buffer_dump(&active_state->input);
1301 #endif
1302         cp = buffer_append_space(&active_state->incoming_packet, need);
1303         cipher_crypt(&active_state->receive_context, cp,
1304             buffer_ptr(&active_state->input), need);
1305         buffer_consume(&active_state->input, need);
1306         /*
1307          * compute MAC over seqnr and packet,
1308          * increment sequence number for incoming packet
1309          */
1310         if (mac && mac->enabled) {
1311                 macbuf = mac_compute(mac, active_state->p_read.seqnr,
1312                     buffer_ptr(&active_state->incoming_packet),
1313                     buffer_len(&active_state->incoming_packet));
1314                 if (memcmp(macbuf, buffer_ptr(&active_state->input),
1315                     mac->mac_len) != 0) {
1316                         logit("Corrupted MAC on input.");
1317                         if (need > PACKET_MAX_SIZE)
1318                                 fatal("internal error need %d", need);
1319                         packet_start_discard(enc, mac, active_state->packlen,
1320                             PACKET_MAX_SIZE - need);
1321                         return SSH_MSG_NONE;
1322                 }
1323                                 
1324                 DBG(debug("MAC #%d ok", active_state->p_read.seqnr));
1325                 buffer_consume(&active_state->input, mac->mac_len);
1326         }
1327         /* XXX now it's safe to use fatal/packet_disconnect */
1328         if (seqnr_p != NULL)
1329                 *seqnr_p = active_state->p_read.seqnr;
1330         if (++active_state->p_read.seqnr == 0)
1331                 logit("incoming seqnr wraps around");
1332         if (++active_state->p_read.packets == 0)
1333                 if (!(datafellows & SSH_BUG_NOREKEY))
1334                         fatal("XXX too many packets with same key");
1335         active_state->p_read.blocks += (active_state->packlen + 4) / block_size;
1336         active_state->p_read.bytes += active_state->packlen + 4;
1337
1338         /* get padlen */
1339         cp = buffer_ptr(&active_state->incoming_packet);
1340         padlen = cp[4];
1341         DBG(debug("input: padlen %d", padlen));
1342         if (padlen < 4)
1343                 packet_disconnect("Corrupted padlen %d on input.", padlen);
1344
1345         /* skip packet size + padlen, discard padding */
1346         buffer_consume(&active_state->incoming_packet, 4 + 1);
1347         buffer_consume_end(&active_state->incoming_packet, padlen);
1348
1349         DBG(debug("input: len before de-compress %d",
1350             buffer_len(&active_state->incoming_packet)));
1351         if (comp && comp->enabled) {
1352                 buffer_clear(&active_state->compression_buffer);
1353                 buffer_uncompress(&active_state->incoming_packet,
1354                     &active_state->compression_buffer);
1355                 buffer_clear(&active_state->incoming_packet);
1356                 buffer_append(&active_state->incoming_packet,
1357                     buffer_ptr(&active_state->compression_buffer),
1358                     buffer_len(&active_state->compression_buffer));
1359                 DBG(debug("input: len after de-compress %d",
1360                     buffer_len(&active_state->incoming_packet)));
1361         }
1362         /*
1363          * get packet type, implies consume.
1364          * return length of payload (without type field)
1365          */
1366         type = buffer_get_char(&active_state->incoming_packet);
1367         if (type < SSH2_MSG_MIN || type >= SSH2_MSG_LOCAL_MIN)
1368                 packet_disconnect("Invalid ssh2 packet type: %d", type);
1369         if (type == SSH2_MSG_NEWKEYS)
1370                 set_newkeys(MODE_IN);
1371         else if (type == SSH2_MSG_USERAUTH_SUCCESS &&
1372             !active_state->server_side)
1373                 packet_enable_delayed_compress();
1374 #ifdef PACKET_DEBUG
1375         fprintf(stderr, "read/plain[%d]:\r\n", type);
1376         buffer_dump(&active_state->incoming_packet);
1377 #endif
1378         /* reset for next packet */
1379         active_state->packlen = 0;
1380         return type;
1381 }
1382
1383 int
1384 packet_read_poll_seqnr(u_int32_t *seqnr_p)
1385 {
1386         u_int reason, seqnr;
1387         u_char type;
1388         char *msg;
1389
1390         for (;;) {
1391                 if (compat20) {
1392                         type = packet_read_poll2(seqnr_p);
1393                         if (type) {
1394                                 active_state->keep_alive_timeouts = 0;
1395                                 DBG(debug("received packet type %d", type));
1396                         }
1397                         switch (type) {
1398                         case SSH2_MSG_IGNORE:
1399                                 debug3("Received SSH2_MSG_IGNORE");
1400                                 break;
1401                         case SSH2_MSG_DEBUG:
1402                                 packet_get_char();
1403                                 msg = packet_get_string(NULL);
1404                                 debug("Remote: %.900s", msg);
1405                                 xfree(msg);
1406                                 msg = packet_get_string(NULL);
1407                                 xfree(msg);
1408                                 break;
1409                         case SSH2_MSG_DISCONNECT:
1410                                 reason = packet_get_int();
1411                                 msg = packet_get_string(NULL);
1412                                 logit("Received disconnect from %s: %u: %.400s",
1413                                     get_remote_ipaddr(), reason, msg);
1414                                 xfree(msg);
1415                                 cleanup_exit(255);
1416                                 break;
1417                         case SSH2_MSG_UNIMPLEMENTED:
1418                                 seqnr = packet_get_int();
1419                                 debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1420                                     seqnr);
1421                                 break;
1422                         default:
1423                                 return type;
1424                         }
1425                 } else {
1426                         type = packet_read_poll1();
1427                         switch (type) {
1428                         case SSH_MSG_IGNORE:
1429                                 break;
1430                         case SSH_MSG_DEBUG:
1431                                 msg = packet_get_string(NULL);
1432                                 debug("Remote: %.900s", msg);
1433                                 xfree(msg);
1434                                 break;
1435                         case SSH_MSG_DISCONNECT:
1436                                 msg = packet_get_string(NULL);
1437                                 logit("Received disconnect from %s: %.400s",
1438                                     get_remote_ipaddr(), msg);
1439                                 cleanup_exit(255);
1440                                 break;
1441                         default:
1442                                 if (type)
1443                                         DBG(debug("received packet type %d", type));
1444                                 return type;
1445                         }
1446                 }
1447         }
1448 }
1449
1450 int
1451 packet_read_poll(void)
1452 {
1453         return packet_read_poll_seqnr(NULL);
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 void *
1519 packet_get_raw(u_int *length_ptr)
1520 {
1521         u_int bytes = buffer_len(&active_state->incoming_packet);
1522
1523         if (length_ptr != NULL)
1524                 *length_ptr = bytes;
1525         return buffer_ptr(&active_state->incoming_packet);
1526 }
1527
1528 int
1529 packet_remaining(void)
1530 {
1531         return buffer_len(&active_state->incoming_packet);
1532 }
1533
1534 /*
1535  * Returns a string from the packet data.  The string is allocated using
1536  * xmalloc; it is the responsibility of the calling program to free it when
1537  * no longer needed.  The length_ptr argument may be NULL, or point to an
1538  * integer into which the length of the string is stored.
1539  */
1540
1541 void *
1542 packet_get_string(u_int *length_ptr)
1543 {
1544         return buffer_get_string(&active_state->incoming_packet, length_ptr);
1545 }
1546
1547 void *
1548 packet_get_string_ptr(u_int *length_ptr)
1549 {
1550         return buffer_get_string_ptr(&active_state->incoming_packet, length_ptr);
1551 }
1552
1553 /*
1554  * Sends a diagnostic message from the server to the client.  This message
1555  * can be sent at any time (but not while constructing another message). The
1556  * message is printed immediately, but only if the client is being executed
1557  * in verbose mode.  These messages are primarily intended to ease debugging
1558  * authentication problems.   The length of the formatted message must not
1559  * exceed 1024 bytes.  This will automatically call packet_write_wait.
1560  */
1561
1562 void
1563 packet_send_debug(const char *fmt,...)
1564 {
1565         char buf[1024];
1566         va_list args;
1567
1568         if (compat20 && (datafellows & SSH_BUG_DEBUG))
1569                 return;
1570
1571         va_start(args, fmt);
1572         vsnprintf(buf, sizeof(buf), fmt, args);
1573         va_end(args);
1574
1575         if (compat20) {
1576                 packet_start(SSH2_MSG_DEBUG);
1577                 packet_put_char(0);     /* bool: always display */
1578                 packet_put_cstring(buf);
1579                 packet_put_cstring("");
1580         } else {
1581                 packet_start(SSH_MSG_DEBUG);
1582                 packet_put_cstring(buf);
1583         }
1584         packet_send();
1585         packet_write_wait();
1586 }
1587
1588 /*
1589  * Logs the error plus constructs and sends a disconnect packet, closes the
1590  * connection, and exits.  This function never returns. The error message
1591  * should not contain a newline.  The length of the formatted message must
1592  * not exceed 1024 bytes.
1593  */
1594
1595 void
1596 packet_disconnect(const char *fmt,...)
1597 {
1598         char buf[1024];
1599         va_list args;
1600         static int disconnecting = 0;
1601
1602         if (disconnecting)      /* Guard against recursive invocations. */
1603                 fatal("packet_disconnect called recursively.");
1604         disconnecting = 1;
1605
1606         /*
1607          * Format the message.  Note that the caller must make sure the
1608          * message is of limited size.
1609          */
1610         va_start(args, fmt);
1611         vsnprintf(buf, sizeof(buf), fmt, args);
1612         va_end(args);
1613
1614         /* Display the error locally */
1615         logit("Disconnecting: %.100s", buf);
1616
1617         /* Send the disconnect message to the other side, and wait for it to get sent. */
1618         if (compat20) {
1619                 packet_start(SSH2_MSG_DISCONNECT);
1620                 packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1621                 packet_put_cstring(buf);
1622                 packet_put_cstring("");
1623         } else {
1624                 packet_start(SSH_MSG_DISCONNECT);
1625                 packet_put_cstring(buf);
1626         }
1627         packet_send();
1628         packet_write_wait();
1629
1630         /* Stop listening for connections. */
1631         channel_close_all();
1632
1633         /* Close the connection. */
1634         packet_close();
1635         cleanup_exit(255);
1636 }
1637
1638 /* Checks if there is any buffered output, and tries to write some of the output. */
1639
1640 void
1641 packet_write_poll(void)
1642 {
1643         int len = buffer_len(&active_state->output);
1644         int cont;
1645
1646         if (len > 0) {
1647                 cont = 0;
1648                 len = roaming_write(active_state->connection_out,
1649                     buffer_ptr(&active_state->output), len, &cont);
1650                 if (len == -1) {
1651                         if (errno == EINTR || errno == EAGAIN ||
1652                             errno == EWOULDBLOCK)
1653                                 return;
1654                         fatal("Write failed: %.100s", strerror(errno));
1655                 }
1656                 if (len == 0 && !cont)
1657                         fatal("Write connection closed");
1658                 buffer_consume(&active_state->output, len);
1659         }
1660 }
1661
1662 /*
1663  * Calls packet_write_poll repeatedly until all pending output data has been
1664  * written.
1665  */
1666
1667 void
1668 packet_write_wait(void)
1669 {
1670         fd_set *setp;
1671         int ret, ms_remain;
1672         struct timeval start, timeout, *timeoutp = NULL;
1673
1674         setp = (fd_set *)xcalloc(howmany(active_state->connection_out + 1,
1675             NFDBITS), sizeof(fd_mask));
1676         packet_write_poll();
1677         while (packet_have_data_to_write()) {
1678                 memset(setp, 0, howmany(active_state->connection_out + 1,
1679                     NFDBITS) * sizeof(fd_mask));
1680                 FD_SET(active_state->connection_out, setp);
1681
1682                 if (active_state->packet_timeout_ms > 0) {
1683                         ms_remain = active_state->packet_timeout_ms;
1684                         timeoutp = &timeout;
1685                 }
1686                 for (;;) {
1687                         if (active_state->packet_timeout_ms != -1) {
1688                                 ms_to_timeval(&timeout, ms_remain);
1689                                 gettimeofday(&start, NULL);
1690                         }
1691                         if ((ret = select(active_state->connection_out + 1,
1692                             NULL, setp, NULL, timeoutp)) >= 0)
1693                                 break;
1694                         if (errno != EAGAIN && errno != EINTR &&
1695                             errno != EWOULDBLOCK)
1696                                 break;
1697                         if (active_state->packet_timeout_ms == -1)
1698                                 continue;
1699                         ms_subtract_diff(&start, &ms_remain);
1700                         if (ms_remain <= 0) {
1701                                 ret = 0;
1702                                 break;
1703                         }
1704                 }
1705                 if (ret == 0) {
1706                         logit("Connection to %.200s timed out while "
1707                             "waiting to write", get_remote_ipaddr());
1708                         cleanup_exit(255);
1709                 }
1710                 packet_write_poll();
1711         }
1712         xfree(setp);
1713 }
1714
1715 /* Returns true if there is buffered data to write to the connection. */
1716
1717 int
1718 packet_have_data_to_write(void)
1719 {
1720         return buffer_len(&active_state->output) != 0;
1721 }
1722
1723 /* Returns true if there is not too much data to write to the connection. */
1724
1725 int
1726 packet_not_very_much_data_to_write(void)
1727 {
1728         if (active_state->interactive_mode)
1729                 return buffer_len(&active_state->output) < 16384;
1730         else
1731                 return buffer_len(&active_state->output) < 128 * 1024;
1732 }
1733
1734 static void
1735 packet_set_tos(int interactive)
1736 {
1737 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1738         int tos = interactive ? IPTOS_LOWDELAY : IPTOS_THROUGHPUT;
1739
1740         if (!packet_connection_is_on_socket() ||
1741             !packet_connection_is_ipv4())
1742                 return;
1743         if (setsockopt(active_state->connection_in, IPPROTO_IP, IP_TOS, &tos,
1744             sizeof(tos)) < 0)
1745                 error("setsockopt IP_TOS %d: %.100s:",
1746                     tos, strerror(errno));
1747 #endif
1748 }
1749
1750 /* Informs that the current session is interactive.  Sets IP flags for that. */
1751
1752 void
1753 packet_set_interactive(int interactive)
1754 {
1755         if (active_state->set_interactive_called)
1756                 return;
1757         active_state->set_interactive_called = 1;
1758
1759         /* Record that we are in interactive mode. */
1760         active_state->interactive_mode = interactive;
1761
1762         /* Only set socket options if using a socket.  */
1763         if (!packet_connection_is_on_socket())
1764                 return;
1765         set_nodelay(active_state->connection_in);
1766         packet_set_tos(interactive);
1767 }
1768
1769 /* Returns true if the current connection is interactive. */
1770
1771 int
1772 packet_is_interactive(void)
1773 {
1774         return active_state->interactive_mode;
1775 }
1776
1777 int
1778 packet_set_maxsize(u_int s)
1779 {
1780         if (active_state->set_maxsize_called) {
1781                 logit("packet_set_maxsize: called twice: old %d new %d",
1782                     active_state->max_packet_size, s);
1783                 return -1;
1784         }
1785         if (s < 4 * 1024 || s > 1024 * 1024) {
1786                 logit("packet_set_maxsize: bad size %d", s);
1787                 return -1;
1788         }
1789         active_state->set_maxsize_called = 1;
1790         debug("packet_set_maxsize: setting to %d", s);
1791         active_state->max_packet_size = s;
1792         return s;
1793 }
1794
1795 int
1796 packet_inc_alive_timeouts(void)
1797 {
1798         return ++active_state->keep_alive_timeouts;
1799 }
1800
1801 void
1802 packet_set_alive_timeouts(int ka)
1803 {
1804         active_state->keep_alive_timeouts = ka;
1805 }
1806
1807 u_int
1808 packet_get_maxsize(void)
1809 {
1810         return active_state->max_packet_size;
1811 }
1812
1813 /* roundup current message to pad bytes */
1814 void
1815 packet_add_padding(u_char pad)
1816 {
1817         active_state->extra_pad = pad;
1818 }
1819
1820 /*
1821  * 9.2.  Ignored Data Message
1822  *
1823  *   byte      SSH_MSG_IGNORE
1824  *   string    data
1825  *
1826  * All implementations MUST understand (and ignore) this message at any
1827  * time (after receiving the protocol version). No implementation is
1828  * required to send them. This message can be used as an additional
1829  * protection measure against advanced traffic analysis techniques.
1830  */
1831 void
1832 packet_send_ignore(int nbytes)
1833 {
1834         u_int32_t rnd = 0;
1835         int i;
1836
1837         packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1838         packet_put_int(nbytes);
1839         for (i = 0; i < nbytes; i++) {
1840                 if (i % 4 == 0)
1841                         rnd = arc4random();
1842                 packet_put_char((u_char)rnd & 0xff);
1843                 rnd >>= 8;
1844         }
1845 }
1846
1847 #ifdef  NONE_CIPHER_ENABLED
1848 void
1849 packet_request_rekeying(void)
1850 {
1851         rekey_requested = 1;
1852 }
1853 #endif
1854
1855 #define MAX_PACKETS     (1U<<31)
1856 int
1857 packet_need_rekeying(void)
1858 {
1859         if (datafellows & SSH_BUG_NOREKEY)
1860                 return 0;
1861 #ifdef  NONE_CIPHER_ENABLED
1862         if (rekey_requested == 1) {
1863                 rekey_requested = 0;
1864                 return 1;
1865         }
1866 #endif
1867         return
1868             (active_state->p_send.packets > MAX_PACKETS) ||
1869             (active_state->p_read.packets > MAX_PACKETS) ||
1870             (active_state->max_blocks_out &&
1871                 (active_state->p_send.blocks > active_state->max_blocks_out)) ||
1872             (active_state->max_blocks_in &&
1873                 (active_state->p_read.blocks > active_state->max_blocks_in));
1874 }
1875
1876 void
1877 packet_set_rekey_limit(u_int32_t bytes)
1878 {
1879         active_state->rekey_limit = bytes;
1880 }
1881
1882 void
1883 packet_set_server(void)
1884 {
1885         active_state->server_side = 1;
1886 }
1887
1888 void
1889 packet_set_authenticated(void)
1890 {
1891         active_state->after_authentication = 1;
1892 }
1893
1894 void *
1895 packet_get_input(void)
1896 {
1897         return (void *)&active_state->input;
1898 }
1899
1900 void *
1901 packet_get_output(void)
1902 {
1903         return (void *)&active_state->output;
1904 }
1905
1906 void *
1907 packet_get_newkeys(int mode)
1908 {
1909         return (void *)active_state->newkeys[mode];
1910 }
1911
1912 /*
1913  * Save the state for the real connection, and use a separate state when
1914  * resuming a suspended connection.
1915  */
1916 void
1917 packet_backup_state(void)
1918 {
1919         struct session_state *tmp;
1920
1921         close(active_state->connection_in);
1922         active_state->connection_in = -1;
1923         close(active_state->connection_out);
1924         active_state->connection_out = -1;
1925         if (backup_state)
1926                 tmp = backup_state;
1927         else
1928                 tmp = alloc_session_state();
1929         backup_state = active_state;
1930         active_state = tmp;
1931 }
1932
1933 /*
1934  * Swap in the old state when resuming a connecion.
1935  */
1936 void
1937 packet_restore_state(void)
1938 {
1939         struct session_state *tmp;
1940         void *buf;
1941         u_int len;
1942
1943         tmp = backup_state;
1944         backup_state = active_state;
1945         active_state = tmp;
1946         active_state->connection_in = backup_state->connection_in;
1947         backup_state->connection_in = -1;
1948         active_state->connection_out = backup_state->connection_out;
1949         backup_state->connection_out = -1;
1950         len = buffer_len(&backup_state->input);
1951         if (len > 0) {
1952                 buf = buffer_ptr(&backup_state->input);
1953                 buffer_append(&active_state->input, buf, len);
1954                 buffer_clear(&backup_state->input);
1955                 add_recv_bytes(len);
1956         }
1957 }
1958
1959 #ifdef  NONE_CIPHER_ENABLED
1960 int
1961 packet_get_authentication_state(void)
1962 {
1963         return (active_state->after_authentication);
1964 }
1965 #endif