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