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