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