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