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