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