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