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