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