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