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