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