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