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