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