2 * Author: Tatu Ylonen <ylo@cs.hut.fi>
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
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.
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".
15 * SSH2 packet format added by Markus Friedl.
16 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions
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.
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.
40 RCSID("$OpenBSD: packet.c,v 1.90 2002/02/27 21:23:13 stevesk Exp $");
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
76 static int connection_in = -1;
77 static int connection_out = -1;
79 /* Protocol flags for the remote side. */
80 static u_int remote_protocol_flags = 0;
82 /* Encryption context for receiving data. This is only used for decryption. */
83 static CipherContext receive_context;
85 /* Encryption context for sending data. This is only used for encryption. */
86 static CipherContext send_context;
88 /* Buffer for raw input data from the socket. */
91 /* Buffer for raw output data going to the socket. */
94 /* Buffer for the partial outgoing packet being constructed. */
95 static Buffer outgoing_packet;
97 /* Buffer for the incoming packet currently being processed. */
98 static Buffer incoming_packet;
100 /* Scratch buffer for packet compression/decompression. */
101 static Buffer compression_buffer;
102 static int compression_buffer_ready = 0;
104 /* Flag indicating whether packet compression/decompression is enabled. */
105 static int packet_compression = 0;
107 /* default maximum packet size */
108 int max_packet_size = 32768;
110 /* Flag indicating whether this module has been initialized. */
111 static int initialized = 0;
113 /* Set to true if the connection is interactive. */
114 static int interactive_mode = 0;
116 /* Session key information for Encryption and MAC */
117 Newkeys *newkeys[MODE_MAX];
118 static u_int32_t read_seqnr = 0;
119 static u_int32_t send_seqnr = 0;
121 /* roundup current message to extra_pad bytes */
122 static u_char extra_pad = 0;
125 * Sets the descriptors used for communication. Disables encryption until
126 * packet_set_encryption_key is called.
129 packet_set_connection(int fd_in, int fd_out)
131 Cipher *none = cipher_by_name("none");
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;
142 buffer_init(&output);
143 buffer_init(&outgoing_packet);
144 buffer_init(&incoming_packet);
146 /* Kludge: arrange the close function to be called from fatal(). */
147 fatal_add_cleanup((void (*) (void *)) packet_close, NULL);
150 /* Returns 1 if remote host is connected via socket, 0 if not. */
153 packet_connection_is_on_socket(void)
155 struct sockaddr_storage from, to;
156 socklen_t fromlen, tolen;
158 /* filedescriptors in and out are the same, so it's a socket */
159 if (connection_in == connection_out)
161 fromlen = sizeof(from);
162 memset(&from, 0, sizeof(from));
163 if (getpeername(connection_in, (struct sockaddr *)&from, &fromlen) < 0)
166 memset(&to, 0, sizeof(to));
167 if (getpeername(connection_out, (struct sockaddr *)&to, &tolen) < 0)
169 if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
171 if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
177 * Exports an IV from the CipherContext required to export the key
178 * state back from the unprivileged child to the privileged parent
183 packet_get_keyiv(int mode, u_char *iv, u_int len)
187 if (mode == MODE_OUT)
190 cc = &receive_context;
192 cipher_get_keyiv(cc, iv, len);
196 packet_get_keycontext(int mode, u_char *dat)
201 if (mode == MODE_OUT)
204 cc = &receive_context;
206 #if OPENSSL_VERSION_NUMBER < 0x00907000L
207 plen = sizeof(cc->evp.c);
209 plen = cc->evp.cipher->ctx_size;
215 #if OPENSSL_VERSION_NUMBER < 0x00907000L
216 memcpy(dat, &cc->evp.c, sizeof(cc->evp.c));
218 memcpy(dat, &cc->evp.cipher_data, plen);
224 packet_set_keycontext(int mode, u_char *dat)
228 if (mode == MODE_OUT)
231 cc = &receive_context;
233 #if OPENSSL_VERSION_NUMBER < 0x00907000L
234 memcpy(&cc->evp.c, dat, sizeof(cc->evp.c));
236 memcpy(&cc->evp.cipher_data, dat, cc->evp.cipher->ctx_size);
241 packet_get_seqnr(int mode)
243 return (mode == MODE_IN ? read_seqnr : send_seqnr);
247 packet_set_seqnr(int mode, u_int32_t seqnr)
251 else if (mode == MODE_OUT)
254 fatal("%s: bad mode %d", __FUNCTION__, mode);
257 /* returns 1 if connection is via ipv4 */
260 packet_connection_is_ipv4(void)
262 struct sockaddr_storage to;
263 socklen_t tolen = sizeof(to);
265 memset(&to, 0, sizeof(to));
266 if (getsockname(connection_out, (struct sockaddr *)&to, &tolen) < 0)
268 if (to.ss_family != AF_INET)
273 /* Sets the connection into non-blocking mode. */
276 packet_set_nonblocking(void)
278 /* Set the socket into non-blocking mode. */
279 if (fcntl(connection_in, F_SETFL, O_NONBLOCK) < 0)
280 error("fcntl O_NONBLOCK: %.100s", strerror(errno));
282 if (connection_out != connection_in) {
283 if (fcntl(connection_out, F_SETFL, O_NONBLOCK) < 0)
284 error("fcntl O_NONBLOCK: %.100s", strerror(errno));
288 /* Returns the socket used for reading. */
291 packet_get_connection_in(void)
293 return connection_in;
296 /* Returns the descriptor used for writing. */
299 packet_get_connection_out(void)
301 return connection_out;
304 /* Closes the connection and clears and frees internal data structures. */
312 if (connection_in == connection_out) {
313 shutdown(connection_out, SHUT_RDWR);
314 close(connection_out);
316 close(connection_in);
317 close(connection_out);
320 buffer_free(&output);
321 buffer_free(&outgoing_packet);
322 buffer_free(&incoming_packet);
323 if (compression_buffer_ready) {
324 buffer_free(&compression_buffer);
325 buffer_compress_uninit();
327 cipher_cleanup(&send_context);
328 cipher_cleanup(&receive_context);
331 /* Sets remote side protocol flags. */
334 packet_set_protocol_flags(u_int protocol_flags)
336 remote_protocol_flags = protocol_flags;
339 /* Returns the remote protocol flags set earlier by the above function. */
342 packet_get_protocol_flags(void)
344 return remote_protocol_flags;
348 * Starts packet compression from the next packet on in both directions.
349 * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
353 packet_init_compression(void)
355 if (compression_buffer_ready == 1)
357 compression_buffer_ready = 1;
358 buffer_init(&compression_buffer);
362 packet_start_compression(int level)
364 if (packet_compression && !compat20)
365 fatal("Compression already enabled.");
366 packet_compression = 1;
367 packet_init_compression();
368 buffer_compress_init_send(level);
369 buffer_compress_init_recv();
373 * Causes any further packets to be encrypted using the given key. The same
374 * key is used for both sending and reception. However, both directions are
375 * encrypted independently of each other.
378 packet_set_encryption_key(const u_char *key, u_int keylen,
381 Cipher *cipher = cipher_by_number(number);
383 fatal("packet_set_encryption_key: unknown cipher number %d", number);
385 fatal("packet_set_encryption_key: keylen too small: %d", keylen);
386 cipher_init(&send_context, cipher, key, keylen, NULL, 0, CIPHER_ENCRYPT);
387 cipher_init(&receive_context, cipher, key, keylen, NULL, 0, CIPHER_DECRYPT);
390 /* Start constructing a packet to send. */
392 packet_start(u_char type)
397 DBG(debug("packet_start[%d]", type));
398 len = compat20 ? 6 : 9;
399 memset(buf, 0, len - 1);
401 buffer_clear(&outgoing_packet);
402 buffer_append(&outgoing_packet, buf, len);
405 /* Append payload. */
407 packet_put_char(int value)
410 buffer_append(&outgoing_packet, &ch, 1);
413 packet_put_int(u_int value)
415 buffer_put_int(&outgoing_packet, value);
418 packet_put_string(const void *buf, u_int len)
420 buffer_put_string(&outgoing_packet, buf, len);
423 packet_put_cstring(const char *str)
425 buffer_put_cstring(&outgoing_packet, str);
428 packet_put_raw(const void *buf, u_int len)
430 buffer_append(&outgoing_packet, buf, len);
433 packet_put_bignum(BIGNUM * value)
435 buffer_put_bignum(&outgoing_packet, value);
438 packet_put_bignum2(BIGNUM * value)
440 buffer_put_bignum2(&outgoing_packet, value);
444 * Finalizes and sends the packet. If the encryption key has been set,
445 * encrypts the packet before sending.
457 * If using packet compression, compress the payload of the outgoing
460 if (packet_compression) {
461 buffer_clear(&compression_buffer);
463 buffer_consume(&outgoing_packet, 8);
465 buffer_append(&compression_buffer, "\0\0\0\0\0\0\0\0", 8);
466 buffer_compress(&outgoing_packet, &compression_buffer);
467 buffer_clear(&outgoing_packet);
468 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
469 buffer_len(&compression_buffer));
471 /* Compute packet length without padding (add checksum, remove padding). */
472 len = buffer_len(&outgoing_packet) + 4 - 8;
474 /* Insert padding. Initialized to zero in packet_start1() */
475 padding = 8 - len % 8;
476 if (!send_context.plaintext) {
477 cp = buffer_ptr(&outgoing_packet);
478 for (i = 0; i < padding; i++) {
481 cp[7 - i] = rand & 0xff;
485 buffer_consume(&outgoing_packet, 8 - padding);
487 /* Add check bytes. */
488 checksum = ssh_crc32(buffer_ptr(&outgoing_packet),
489 buffer_len(&outgoing_packet));
490 PUT_32BIT(buf, checksum);
491 buffer_append(&outgoing_packet, buf, 4);
494 fprintf(stderr, "packet_send plain: ");
495 buffer_dump(&outgoing_packet);
498 /* Append to output. */
500 buffer_append(&output, buf, 4);
501 cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
502 cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
503 buffer_len(&outgoing_packet));
506 fprintf(stderr, "encrypted: ");
507 buffer_dump(&output);
510 buffer_clear(&outgoing_packet);
513 * Note that the packet is now only buffered in output. It won\'t be
514 * actually sent until packet_write_wait or packet_write_poll is
520 set_newkeys(int mode)
528 debug("newkeys: mode %d", mode);
530 if (mode == MODE_OUT) {
532 encrypt = CIPHER_ENCRYPT;
534 cc = &receive_context;
535 encrypt = CIPHER_DECRYPT;
537 if (newkeys[mode] != NULL) {
538 debug("newkeys: rekeying");
540 enc = &newkeys[mode]->enc;
541 mac = &newkeys[mode]->mac;
542 comp = &newkeys[mode]->comp;
543 memset(mac->key, 0, mac->key_len);
550 xfree(newkeys[mode]);
552 newkeys[mode] = kex_get_newkeys(mode);
553 if (newkeys[mode] == NULL)
554 fatal("newkeys: no keys for mode %d", mode);
555 enc = &newkeys[mode]->enc;
556 mac = &newkeys[mode]->mac;
557 comp = &newkeys[mode]->comp;
560 DBG(debug("cipher_init_context: %d", mode));
561 cipher_init(cc, enc->cipher, enc->key, enc->key_len,
562 enc->iv, enc->block_size, encrypt);
563 /* Deleting the keys does not gain extra security */
564 /* memset(enc->iv, 0, enc->block_size);
565 memset(enc->key, 0, enc->key_len); */
566 if (comp->type != 0 && comp->enabled == 0) {
567 packet_init_compression();
568 if (mode == MODE_OUT)
569 buffer_compress_init_send(6);
571 buffer_compress_init_recv();
577 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
582 u_char type, *cp, *macbuf = NULL;
584 u_int packet_length = 0;
592 if (newkeys[MODE_OUT] != NULL) {
593 enc = &newkeys[MODE_OUT]->enc;
594 mac = &newkeys[MODE_OUT]->mac;
595 comp = &newkeys[MODE_OUT]->comp;
597 block_size = enc ? enc->block_size : 8;
599 cp = buffer_ptr(&outgoing_packet);
603 fprintf(stderr, "plain: ");
604 buffer_dump(&outgoing_packet);
607 if (comp && comp->enabled) {
608 len = buffer_len(&outgoing_packet);
609 /* skip header, compress only payload */
610 buffer_consume(&outgoing_packet, 5);
611 buffer_clear(&compression_buffer);
612 buffer_compress(&outgoing_packet, &compression_buffer);
613 buffer_clear(&outgoing_packet);
614 buffer_append(&outgoing_packet, "\0\0\0\0\0", 5);
615 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
616 buffer_len(&compression_buffer));
617 DBG(debug("compression: raw %d compressed %d", len,
618 buffer_len(&outgoing_packet)));
621 /* sizeof (packet_len + pad_len + payload) */
622 len = buffer_len(&outgoing_packet);
625 * calc size of padding, alloc space, get random data,
626 * minimum padding is 4 bytes
628 padlen = block_size - (len % block_size);
630 padlen += block_size;
632 /* will wrap if extra_pad+padlen > 255 */
633 extra_pad = roundup(extra_pad, block_size);
634 pad = extra_pad - ((len + padlen) % extra_pad);
635 debug("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
636 pad, len, padlen, extra_pad);
640 cp = buffer_append_space(&outgoing_packet, padlen);
641 if (enc && !send_context.plaintext) {
643 for (i = 0; i < padlen; i++) {
651 memset(cp, 0, padlen);
653 /* packet_length includes payload, padding and padding length field */
654 packet_length = buffer_len(&outgoing_packet) - 4;
655 cp = buffer_ptr(&outgoing_packet);
656 PUT_32BIT(cp, packet_length);
658 DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen));
660 /* compute MAC over seqnr and packet(length fields, payload, padding) */
661 if (mac && mac->enabled) {
662 macbuf = mac_compute(mac, send_seqnr,
663 buffer_ptr(&outgoing_packet),
664 buffer_len(&outgoing_packet));
665 DBG(debug("done calc MAC out #%d", send_seqnr));
667 /* encrypt packet and append to output buffer. */
668 cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
669 cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
670 buffer_len(&outgoing_packet));
671 /* append unencrypted MAC */
672 if (mac && mac->enabled)
673 buffer_append(&output, (char *)macbuf, mac->mac_len);
675 fprintf(stderr, "encrypted: ");
676 buffer_dump(&output);
678 /* increment sequence number for outgoing packets */
679 if (++send_seqnr == 0)
680 log("outgoing seqnr wraps around");
681 buffer_clear(&outgoing_packet);
683 if (type == SSH2_MSG_NEWKEYS)
684 set_newkeys(MODE_OUT);
694 DBG(debug("packet_send done"));
698 * Waits until a packet has been received, and returns its type. Note that
699 * no other data is processed until this returns, so this function should not
700 * be used during the interactive session.
704 packet_read_seqnr(u_int32_t *seqnr_p)
709 DBG(debug("packet_read()"));
711 setp = (fd_set *)xmalloc(howmany(connection_in+1, NFDBITS) *
714 /* Since we are blocking, ensure that all written packets have been sent. */
717 /* Stay in the loop until we have received a complete packet. */
719 /* Try to read a packet from the buffer. */
720 type = packet_read_poll_seqnr(seqnr_p);
722 type == SSH_SMSG_SUCCESS
723 || type == SSH_SMSG_FAILURE
724 || type == SSH_CMSG_EOF
725 || type == SSH_CMSG_EXIT_CONFIRMATION))
727 /* If we got a packet, return it. */
728 if (type != SSH_MSG_NONE) {
733 * Otherwise, wait for some data to arrive, add it to the
734 * buffer, and try again.
736 memset(setp, 0, howmany(connection_in + 1, NFDBITS) *
738 FD_SET(connection_in, setp);
740 /* Wait for some data to arrive. */
741 while (select(connection_in + 1, setp, NULL, NULL, NULL) == -1 &&
742 (errno == EAGAIN || errno == EINTR))
745 /* Read data from the socket. */
746 len = read(connection_in, buf, sizeof(buf));
748 log("Connection closed by %.200s", get_remote_ipaddr());
752 fatal("Read from socket failed: %.100s", strerror(errno));
753 /* Append it to the buffer. */
754 packet_process_incoming(buf, len);
762 return packet_read_seqnr(NULL);
766 * Waits until a packet has been received, verifies that its type matches
767 * that given, and gives a fatal error and exits if there is a mismatch.
771 packet_read_expect(int expected_type)
775 type = packet_read();
776 if (type != expected_type)
777 packet_disconnect("Protocol error: expected packet type %d, got %d",
778 expected_type, type);
781 /* Checks if a full packet is available in the data received so far via
782 * packet_process_incoming. If so, reads the packet; otherwise returns
783 * SSH_MSG_NONE. This does not wait for data from the connection.
785 * SSH_MSG_DISCONNECT is handled specially here. Also,
786 * SSH_MSG_IGNORE messages are skipped by this function and are never returned
791 packet_read_poll1(void)
793 u_int len, padded_len;
795 u_int checksum, stored_checksum;
797 /* Check if input size is less than minimum packet size. */
798 if (buffer_len(&input) < 4 + 8)
800 /* Get length of incoming packet. */
801 cp = buffer_ptr(&input);
803 if (len < 1 + 2 + 2 || len > 256 * 1024)
804 packet_disconnect("Bad packet length %d.", len);
805 padded_len = (len + 8) & ~7;
807 /* Check if the packet has been entirely received. */
808 if (buffer_len(&input) < 4 + padded_len)
811 /* The entire packet is in buffer. */
813 /* Consume packet length. */
814 buffer_consume(&input, 4);
817 * Cryptographic attack detector for ssh
818 * (C)1998 CORE-SDI, Buenos Aires Argentina
819 * Ariel Futoransky(futo@core-sdi.com)
821 if (!receive_context.plaintext &&
822 detect_attack(buffer_ptr(&input), padded_len, NULL) == DEATTACK_DETECTED)
823 packet_disconnect("crc32 compensation attack: network attack detected");
825 /* Decrypt data to incoming_packet. */
826 buffer_clear(&incoming_packet);
827 cp = buffer_append_space(&incoming_packet, padded_len);
828 cipher_crypt(&receive_context, cp, buffer_ptr(&input), padded_len);
830 buffer_consume(&input, padded_len);
833 fprintf(stderr, "read_poll plain: ");
834 buffer_dump(&incoming_packet);
837 /* Compute packet checksum. */
838 checksum = ssh_crc32(buffer_ptr(&incoming_packet),
839 buffer_len(&incoming_packet) - 4);
842 buffer_consume(&incoming_packet, 8 - len % 8);
844 /* Test check bytes. */
845 if (len != buffer_len(&incoming_packet))
846 packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
847 len, buffer_len(&incoming_packet));
849 cp = (u_char *)buffer_ptr(&incoming_packet) + len - 4;
850 stored_checksum = GET_32BIT(cp);
851 if (checksum != stored_checksum)
852 packet_disconnect("Corrupted check bytes on input.");
853 buffer_consume_end(&incoming_packet, 4);
855 if (packet_compression) {
856 buffer_clear(&compression_buffer);
857 buffer_uncompress(&incoming_packet, &compression_buffer);
858 buffer_clear(&incoming_packet);
859 buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
860 buffer_len(&compression_buffer));
862 type = buffer_get_char(&incoming_packet);
867 packet_read_poll2(u_int32_t *seqnr_p)
869 static u_int packet_length = 0;
871 u_char *macbuf, *cp, type;
872 int maclen, block_size;
877 if (newkeys[MODE_IN] != NULL) {
878 enc = &newkeys[MODE_IN]->enc;
879 mac = &newkeys[MODE_IN]->mac;
880 comp = &newkeys[MODE_IN]->comp;
882 maclen = mac && mac->enabled ? mac->mac_len : 0;
883 block_size = enc ? enc->block_size : 8;
885 if (packet_length == 0) {
887 * check if input size is less than the cipher block size,
888 * decrypt first block and extract length of incoming packet
890 if (buffer_len(&input) < block_size)
892 buffer_clear(&incoming_packet);
893 cp = buffer_append_space(&incoming_packet, block_size);
894 cipher_crypt(&receive_context, cp, buffer_ptr(&input),
896 cp = buffer_ptr(&incoming_packet);
897 packet_length = GET_32BIT(cp);
898 if (packet_length < 1 + 4 || packet_length > 256 * 1024) {
899 buffer_dump(&incoming_packet);
900 packet_disconnect("Bad packet length %d.", packet_length);
902 DBG(debug("input: packet len %d", packet_length+4));
903 buffer_consume(&input, block_size);
905 /* we have a partial packet of block_size bytes */
906 need = 4 + packet_length - block_size;
907 DBG(debug("partial packet %d, need %d, maclen %d", block_size,
909 if (need % block_size != 0)
910 fatal("padding error: need %d block %d mod %d",
911 need, block_size, need % block_size);
913 * check if the entire packet has been received and
914 * decrypt into incoming_packet
916 if (buffer_len(&input) < need + maclen)
919 fprintf(stderr, "read_poll enc/full: ");
922 cp = buffer_append_space(&incoming_packet, need);
923 cipher_crypt(&receive_context, cp, buffer_ptr(&input), need);
924 buffer_consume(&input, need);
926 * compute MAC over seqnr and packet,
927 * increment sequence number for incoming packet
929 if (mac && mac->enabled) {
930 macbuf = mac_compute(mac, read_seqnr,
931 buffer_ptr(&incoming_packet),
932 buffer_len(&incoming_packet));
933 if (memcmp(macbuf, buffer_ptr(&input), mac->mac_len) != 0)
934 packet_disconnect("Corrupted MAC on input.");
935 DBG(debug("MAC #%d ok", read_seqnr));
936 buffer_consume(&input, mac->mac_len);
939 *seqnr_p = read_seqnr;
940 if (++read_seqnr == 0)
941 log("incoming seqnr wraps around");
944 cp = buffer_ptr(&incoming_packet);
946 DBG(debug("input: padlen %d", padlen));
948 packet_disconnect("Corrupted padlen %d on input.", padlen);
950 /* skip packet size + padlen, discard padding */
951 buffer_consume(&incoming_packet, 4 + 1);
952 buffer_consume_end(&incoming_packet, padlen);
954 DBG(debug("input: len before de-compress %d", buffer_len(&incoming_packet)));
955 if (comp && comp->enabled) {
956 buffer_clear(&compression_buffer);
957 buffer_uncompress(&incoming_packet, &compression_buffer);
958 buffer_clear(&incoming_packet);
959 buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
960 buffer_len(&compression_buffer));
961 DBG(debug("input: len after de-compress %d", buffer_len(&incoming_packet)));
964 * get packet type, implies consume.
965 * return length of payload (without type field)
967 type = buffer_get_char(&incoming_packet);
968 if (type == SSH2_MSG_NEWKEYS)
969 set_newkeys(MODE_IN);
971 fprintf(stderr, "read/plain[%d]:\r\n", type);
972 buffer_dump(&incoming_packet);
974 /* reset for next packet */
980 packet_read_poll_seqnr(u_int32_t *seqnr_p)
988 type = packet_read_poll2(seqnr_p);
990 DBG(debug("received packet type %d", type));
992 case SSH2_MSG_IGNORE:
996 msg = packet_get_string(NULL);
997 debug("Remote: %.900s", msg);
999 msg = packet_get_string(NULL);
1002 case SSH2_MSG_DISCONNECT:
1003 reason = packet_get_int();
1004 msg = packet_get_string(NULL);
1005 log("Received disconnect from %s: %d: %.400s", get_remote_ipaddr(),
1010 case SSH2_MSG_UNIMPLEMENTED:
1011 seqnr = packet_get_int();
1012 debug("Received SSH2_MSG_UNIMPLEMENTED for %d", seqnr);
1019 type = packet_read_poll1();
1021 case SSH_MSG_IGNORE:
1024 msg = packet_get_string(NULL);
1025 debug("Remote: %.900s", msg);
1028 case SSH_MSG_DISCONNECT:
1029 msg = packet_get_string(NULL);
1030 log("Received disconnect from %s: %.400s", get_remote_ipaddr(),
1037 DBG(debug("received packet type %d", type));
1046 packet_read_poll(void)
1048 return packet_read_poll_seqnr(NULL);
1052 * Buffers the given amount of input characters. This is intended to be used
1053 * together with packet_read_poll.
1057 packet_process_incoming(const char *buf, u_int len)
1059 buffer_append(&input, buf, len);
1062 /* Returns a character from the packet. */
1065 packet_get_char(void)
1068 buffer_get(&incoming_packet, &ch, 1);
1072 /* Returns an integer from the packet data. */
1075 packet_get_int(void)
1077 return buffer_get_int(&incoming_packet);
1081 * Returns an arbitrary precision integer from the packet data. The integer
1082 * must have been initialized before this call.
1086 packet_get_bignum(BIGNUM * value)
1088 buffer_get_bignum(&incoming_packet, value);
1092 packet_get_bignum2(BIGNUM * value)
1094 buffer_get_bignum2(&incoming_packet, value);
1098 packet_get_raw(int *length_ptr)
1100 int bytes = buffer_len(&incoming_packet);
1101 if (length_ptr != NULL)
1102 *length_ptr = bytes;
1103 return buffer_ptr(&incoming_packet);
1107 packet_remaining(void)
1109 return buffer_len(&incoming_packet);
1113 * Returns a string from the packet data. The string is allocated using
1114 * xmalloc; it is the responsibility of the calling program to free it when
1115 * no longer needed. The length_ptr argument may be NULL, or point to an
1116 * integer into which the length of the string is stored.
1120 packet_get_string(u_int *length_ptr)
1122 return buffer_get_string(&incoming_packet, length_ptr);
1126 * Sends a diagnostic message from the server to the client. This message
1127 * can be sent at any time (but not while constructing another message). The
1128 * message is printed immediately, but only if the client is being executed
1129 * in verbose mode. These messages are primarily intended to ease debugging
1130 * authentication problems. The length of the formatted message must not
1131 * exceed 1024 bytes. This will automatically call packet_write_wait.
1135 packet_send_debug(const char *fmt,...)
1140 if (compat20 && (datafellows & SSH_BUG_DEBUG))
1143 va_start(args, fmt);
1144 vsnprintf(buf, sizeof(buf), fmt, args);
1148 packet_start(SSH2_MSG_DEBUG);
1149 packet_put_char(0); /* bool: always display */
1150 packet_put_cstring(buf);
1151 packet_put_cstring("");
1153 packet_start(SSH_MSG_DEBUG);
1154 packet_put_cstring(buf);
1157 packet_write_wait();
1161 * Logs the error plus constructs and sends a disconnect packet, closes the
1162 * connection, and exits. This function never returns. The error message
1163 * should not contain a newline. The length of the formatted message must
1164 * not exceed 1024 bytes.
1168 packet_disconnect(const char *fmt,...)
1172 static int disconnecting = 0;
1173 if (disconnecting) /* Guard against recursive invocations. */
1174 fatal("packet_disconnect called recursively.");
1178 * Format the message. Note that the caller must make sure the
1179 * message is of limited size.
1181 va_start(args, fmt);
1182 vsnprintf(buf, sizeof(buf), fmt, args);
1185 /* Send the disconnect message to the other side, and wait for it to get sent. */
1187 packet_start(SSH2_MSG_DISCONNECT);
1188 packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1189 packet_put_cstring(buf);
1190 packet_put_cstring("");
1192 packet_start(SSH_MSG_DISCONNECT);
1193 packet_put_cstring(buf);
1196 packet_write_wait();
1198 /* Stop listening for connections. */
1199 channel_close_all();
1201 /* Close the connection. */
1204 /* Display the error locally and exit. */
1205 log("Disconnecting: %.100s", buf);
1209 /* Checks if there is any buffered output, and tries to write some of the output. */
1212 packet_write_poll(void)
1214 int len = buffer_len(&output);
1216 len = write(connection_out, buffer_ptr(&output), len);
1218 if (errno == EAGAIN)
1221 fatal("Write failed: %.100s", strerror(errno));
1223 buffer_consume(&output, len);
1228 * Calls packet_write_poll repeatedly until all pending output data has been
1233 packet_write_wait(void)
1237 setp = (fd_set *)xmalloc(howmany(connection_out + 1, NFDBITS) *
1239 packet_write_poll();
1240 while (packet_have_data_to_write()) {
1241 memset(setp, 0, howmany(connection_out + 1, NFDBITS) *
1243 FD_SET(connection_out, setp);
1244 while (select(connection_out + 1, NULL, setp, NULL, NULL) == -1 &&
1245 (errno == EAGAIN || errno == EINTR))
1247 packet_write_poll();
1252 /* Returns true if there is buffered data to write to the connection. */
1255 packet_have_data_to_write(void)
1257 return buffer_len(&output) != 0;
1260 /* Returns true if there is not too much data to write to the connection. */
1263 packet_not_very_much_data_to_write(void)
1265 if (interactive_mode)
1266 return buffer_len(&output) < 16384;
1268 return buffer_len(&output) < 128 * 1024;
1271 /* Informs that the current session is interactive. Sets IP flags for that. */
1274 packet_set_interactive(int interactive)
1276 static int called = 0;
1277 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1278 int lowdelay = IPTOS_LOWDELAY;
1279 int throughput = IPTOS_THROUGHPUT;
1286 /* Record that we are in interactive mode. */
1287 interactive_mode = interactive;
1289 /* Only set socket options if using a socket. */
1290 if (!packet_connection_is_on_socket())
1293 * IPTOS_LOWDELAY and IPTOS_THROUGHPUT are IPv4 only
1297 * Set IP options for an interactive connection. Use
1298 * IPTOS_LOWDELAY and TCP_NODELAY.
1300 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1301 if (packet_connection_is_ipv4()) {
1302 if (setsockopt(connection_in, IPPROTO_IP, IP_TOS,
1303 &lowdelay, sizeof(lowdelay)) < 0)
1304 error("setsockopt IPTOS_LOWDELAY: %.100s",
1308 set_nodelay(connection_in);
1309 } else if (packet_connection_is_ipv4()) {
1311 * Set IP options for a non-interactive connection. Use
1314 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1315 if (setsockopt(connection_in, IPPROTO_IP, IP_TOS, &throughput,
1316 sizeof(throughput)) < 0)
1317 error("setsockopt IPTOS_THROUGHPUT: %.100s", strerror(errno));
1322 /* Returns true if the current connection is interactive. */
1325 packet_is_interactive(void)
1327 return interactive_mode;
1331 packet_set_maxsize(int s)
1333 static int called = 0;
1335 log("packet_set_maxsize: called twice: old %d new %d",
1336 max_packet_size, s);
1339 if (s < 4 * 1024 || s > 1024 * 1024) {
1340 log("packet_set_maxsize: bad size %d", s);
1344 debug("packet_set_maxsize: setting to %d", s);
1345 max_packet_size = s;
1349 /* roundup current message to pad bytes */
1351 packet_add_padding(u_char pad)
1357 * 9.2. Ignored Data Message
1359 * byte SSH_MSG_IGNORE
1362 * All implementations MUST understand (and ignore) this message at any
1363 * time (after receiving the protocol version). No implementation is
1364 * required to send them. This message can be used as an additional
1365 * protection measure against advanced traffic analysis techniques.
1368 packet_send_ignore(int nbytes)
1373 packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1374 packet_put_int(nbytes);
1375 for (i = 0; i < nbytes; i++) {
1377 rand = arc4random();
1378 packet_put_char(rand & 0xff);