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.87 2002/01/24 21:13:23 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];
119 /* roundup current message to extra_pad bytes */
120 static u_char extra_pad = 0;
123 * Sets the descriptors used for communication. Disables encryption until
124 * packet_set_encryption_key is called.
127 packet_set_connection(int fd_in, int fd_out)
129 Cipher *none = cipher_by_name("none");
131 fatal("packet_set_connection: cannot load cipher 'none'");
132 connection_in = fd_in;
133 connection_out = fd_out;
134 cipher_init(&send_context, none, "", 0, NULL, 0);
135 cipher_init(&receive_context, none, "", 0, NULL, 0);
136 newkeys[MODE_IN] = newkeys[MODE_OUT] = NULL;
140 buffer_init(&output);
141 buffer_init(&outgoing_packet);
142 buffer_init(&incoming_packet);
144 /* Kludge: arrange the close function to be called from fatal(). */
145 fatal_add_cleanup((void (*) (void *)) packet_close, NULL);
148 /* Returns 1 if remote host is connected via socket, 0 if not. */
151 packet_connection_is_on_socket(void)
153 struct sockaddr_storage from, to;
154 socklen_t fromlen, tolen;
156 /* filedescriptors in and out are the same, so it's a socket */
157 if (connection_in == connection_out)
159 fromlen = sizeof(from);
160 memset(&from, 0, sizeof(from));
161 if (getpeername(connection_in, (struct sockaddr *)&from, &fromlen) < 0)
164 memset(&to, 0, sizeof(to));
165 if (getpeername(connection_out, (struct sockaddr *)&to, &tolen) < 0)
167 if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
169 if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
174 /* returns 1 if connection is via ipv4 */
177 packet_connection_is_ipv4(void)
179 struct sockaddr_storage to;
180 socklen_t tolen = sizeof(to);
182 memset(&to, 0, sizeof(to));
183 if (getsockname(connection_out, (struct sockaddr *)&to, &tolen) < 0)
185 if (to.ss_family != AF_INET)
190 /* Sets the connection into non-blocking mode. */
193 packet_set_nonblocking(void)
195 /* Set the socket into non-blocking mode. */
196 if (fcntl(connection_in, F_SETFL, O_NONBLOCK) < 0)
197 error("fcntl O_NONBLOCK: %.100s", strerror(errno));
199 if (connection_out != connection_in) {
200 if (fcntl(connection_out, F_SETFL, O_NONBLOCK) < 0)
201 error("fcntl O_NONBLOCK: %.100s", strerror(errno));
205 /* Returns the socket used for reading. */
208 packet_get_connection_in(void)
210 return connection_in;
213 /* Returns the descriptor used for writing. */
216 packet_get_connection_out(void)
218 return connection_out;
221 /* Closes the connection and clears and frees internal data structures. */
229 if (connection_in == connection_out) {
230 shutdown(connection_out, SHUT_RDWR);
231 close(connection_out);
233 close(connection_in);
234 close(connection_out);
237 buffer_free(&output);
238 buffer_free(&outgoing_packet);
239 buffer_free(&incoming_packet);
240 if (compression_buffer_ready) {
241 buffer_free(&compression_buffer);
242 buffer_compress_uninit();
246 /* Sets remote side protocol flags. */
249 packet_set_protocol_flags(u_int protocol_flags)
251 remote_protocol_flags = protocol_flags;
254 /* Returns the remote protocol flags set earlier by the above function. */
257 packet_get_protocol_flags(void)
259 return remote_protocol_flags;
263 * Starts packet compression from the next packet on in both directions.
264 * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
268 packet_init_compression(void)
270 if (compression_buffer_ready == 1)
272 compression_buffer_ready = 1;
273 buffer_init(&compression_buffer);
277 packet_start_compression(int level)
279 if (packet_compression && !compat20)
280 fatal("Compression already enabled.");
281 packet_compression = 1;
282 packet_init_compression();
283 buffer_compress_init_send(level);
284 buffer_compress_init_recv();
288 * Causes any further packets to be encrypted using the given key. The same
289 * key is used for both sending and reception. However, both directions are
290 * encrypted independently of each other.
293 packet_set_encryption_key(const u_char *key, u_int keylen,
296 Cipher *cipher = cipher_by_number(number);
298 fatal("packet_set_encryption_key: unknown cipher number %d", number);
300 fatal("packet_set_encryption_key: keylen too small: %d", keylen);
301 cipher_init(&receive_context, cipher, key, keylen, NULL, 0);
302 cipher_init(&send_context, cipher, key, keylen, NULL, 0);
305 /* Start constructing a packet to send. */
307 packet_start(u_char type)
312 DBG(debug("packet_start[%d]", type));
313 len = compat20 ? 6 : 9;
314 memset(buf, 0, len - 1);
316 buffer_clear(&outgoing_packet);
317 buffer_append(&outgoing_packet, buf, len);
320 /* Append payload. */
322 packet_put_char(int value)
325 buffer_append(&outgoing_packet, &ch, 1);
328 packet_put_int(u_int value)
330 buffer_put_int(&outgoing_packet, value);
333 packet_put_string(const void *buf, u_int len)
335 buffer_put_string(&outgoing_packet, buf, len);
338 packet_put_cstring(const char *str)
340 buffer_put_cstring(&outgoing_packet, str);
343 packet_put_raw(const void *buf, u_int len)
345 buffer_append(&outgoing_packet, buf, len);
348 packet_put_bignum(BIGNUM * value)
350 buffer_put_bignum(&outgoing_packet, value);
353 packet_put_bignum2(BIGNUM * value)
355 buffer_put_bignum2(&outgoing_packet, value);
359 * Finalizes and sends the packet. If the encryption key has been set,
360 * encrypts the packet before sending.
372 * If using packet compression, compress the payload of the outgoing
375 if (packet_compression) {
376 buffer_clear(&compression_buffer);
378 buffer_consume(&outgoing_packet, 8);
380 buffer_append(&compression_buffer, "\0\0\0\0\0\0\0\0", 8);
381 buffer_compress(&outgoing_packet, &compression_buffer);
382 buffer_clear(&outgoing_packet);
383 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
384 buffer_len(&compression_buffer));
386 /* Compute packet length without padding (add checksum, remove padding). */
387 len = buffer_len(&outgoing_packet) + 4 - 8;
389 /* Insert padding. Initialized to zero in packet_start1() */
390 padding = 8 - len % 8;
391 if (send_context.cipher->number != SSH_CIPHER_NONE) {
392 cp = buffer_ptr(&outgoing_packet);
393 for (i = 0; i < padding; i++) {
396 cp[7 - i] = rand & 0xff;
400 buffer_consume(&outgoing_packet, 8 - padding);
402 /* Add check bytes. */
403 checksum = ssh_crc32(buffer_ptr(&outgoing_packet),
404 buffer_len(&outgoing_packet));
405 PUT_32BIT(buf, checksum);
406 buffer_append(&outgoing_packet, buf, 4);
409 fprintf(stderr, "packet_send plain: ");
410 buffer_dump(&outgoing_packet);
413 /* Append to output. */
415 buffer_append(&output, buf, 4);
416 cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
417 cipher_encrypt(&send_context, cp, buffer_ptr(&outgoing_packet),
418 buffer_len(&outgoing_packet));
421 fprintf(stderr, "encrypted: ");
422 buffer_dump(&output);
425 buffer_clear(&outgoing_packet);
428 * Note that the packet is now only buffered in output. It won\'t be
429 * actually sent until packet_write_wait or packet_write_poll is
435 set_newkeys(int mode)
442 debug("newkeys: mode %d", mode);
444 cc = (mode == MODE_OUT) ? &send_context : &receive_context;
445 if (newkeys[mode] != NULL) {
446 debug("newkeys: rekeying");
447 /* todo: free old keys, reset compression/cipher-ctxt; */
448 memset(cc, 0, sizeof(*cc));
449 enc = &newkeys[mode]->enc;
450 mac = &newkeys[mode]->mac;
451 comp = &newkeys[mode]->comp;
452 memset(mac->key, 0, mac->key_len);
459 xfree(newkeys[mode]);
461 newkeys[mode] = kex_get_newkeys(mode);
462 if (newkeys[mode] == NULL)
463 fatal("newkeys: no keys for mode %d", mode);
464 enc = &newkeys[mode]->enc;
465 mac = &newkeys[mode]->mac;
466 comp = &newkeys[mode]->comp;
469 DBG(debug("cipher_init_context: %d", mode));
470 cipher_init(cc, enc->cipher, enc->key, enc->cipher->key_len,
471 enc->iv, enc->cipher->block_size);
472 memset(enc->iv, 0, enc->cipher->block_size);
473 memset(enc->key, 0, enc->cipher->key_len);
474 if (comp->type != 0 && comp->enabled == 0) {
475 packet_init_compression();
476 if (mode == MODE_OUT)
477 buffer_compress_init_send(6);
479 buffer_compress_init_recv();
485 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
490 static u_int32_t seqnr = 0;
491 u_char type, *ucp, *macbuf = NULL;
494 u_int packet_length = 0;
502 if (newkeys[MODE_OUT] != NULL) {
503 enc = &newkeys[MODE_OUT]->enc;
504 mac = &newkeys[MODE_OUT]->mac;
505 comp = &newkeys[MODE_OUT]->comp;
507 block_size = enc ? enc->cipher->block_size : 8;
509 ucp = buffer_ptr(&outgoing_packet);
513 fprintf(stderr, "plain: ");
514 buffer_dump(&outgoing_packet);
517 if (comp && comp->enabled) {
518 len = buffer_len(&outgoing_packet);
519 /* skip header, compress only payload */
520 buffer_consume(&outgoing_packet, 5);
521 buffer_clear(&compression_buffer);
522 buffer_compress(&outgoing_packet, &compression_buffer);
523 buffer_clear(&outgoing_packet);
524 buffer_append(&outgoing_packet, "\0\0\0\0\0", 5);
525 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
526 buffer_len(&compression_buffer));
527 DBG(debug("compression: raw %d compressed %d", len,
528 buffer_len(&outgoing_packet)));
531 /* sizeof (packet_len + pad_len + payload) */
532 len = buffer_len(&outgoing_packet);
535 * calc size of padding, alloc space, get random data,
536 * minimum padding is 4 bytes
538 padlen = block_size - (len % block_size);
540 padlen += block_size;
542 /* will wrap if extra_pad+padlen > 255 */
543 extra_pad = roundup(extra_pad, block_size);
544 pad = extra_pad - ((len + padlen) % extra_pad);
545 debug("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
546 pad, len, padlen, extra_pad);
550 cp = buffer_append_space(&outgoing_packet, padlen);
551 if (enc && enc->cipher->number != SSH_CIPHER_NONE) {
553 for (i = 0; i < padlen; i++) {
561 memset(cp, 0, padlen);
563 /* packet_length includes payload, padding and padding length field */
564 packet_length = buffer_len(&outgoing_packet) - 4;
565 ucp = buffer_ptr(&outgoing_packet);
566 PUT_32BIT(ucp, packet_length);
568 DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen));
570 /* compute MAC over seqnr and packet(length fields, payload, padding) */
571 if (mac && mac->enabled) {
572 macbuf = mac_compute(mac, seqnr,
573 buffer_ptr(&outgoing_packet),
574 buffer_len(&outgoing_packet));
575 DBG(debug("done calc MAC out #%d", seqnr));
577 /* encrypt packet and append to output buffer. */
578 cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
579 cipher_encrypt(&send_context, cp, buffer_ptr(&outgoing_packet),
580 buffer_len(&outgoing_packet));
581 /* append unencrypted MAC */
582 if (mac && mac->enabled)
583 buffer_append(&output, (char *)macbuf, mac->mac_len);
585 fprintf(stderr, "encrypted: ");
586 buffer_dump(&output);
588 /* increment sequence number for outgoing packets */
590 log("outgoing seqnr wraps around");
591 buffer_clear(&outgoing_packet);
593 if (type == SSH2_MSG_NEWKEYS)
594 set_newkeys(MODE_OUT);
604 DBG(debug("packet_send done"));
608 * Waits until a packet has been received, and returns its type. Note that
609 * no other data is processed until this returns, so this function should not
610 * be used during the interactive session.
614 packet_read_seqnr(u_int32_t *seqnr_p)
619 DBG(debug("packet_read()"));
621 setp = (fd_set *)xmalloc(howmany(connection_in+1, NFDBITS) *
624 /* Since we are blocking, ensure that all written packets have been sent. */
627 /* Stay in the loop until we have received a complete packet. */
629 /* Try to read a packet from the buffer. */
630 type = packet_read_poll_seqnr(seqnr_p);
632 type == SSH_SMSG_SUCCESS
633 || type == SSH_SMSG_FAILURE
634 || type == SSH_CMSG_EOF
635 || type == SSH_CMSG_EXIT_CONFIRMATION))
637 /* If we got a packet, return it. */
638 if (type != SSH_MSG_NONE) {
643 * Otherwise, wait for some data to arrive, add it to the
644 * buffer, and try again.
646 memset(setp, 0, howmany(connection_in + 1, NFDBITS) *
648 FD_SET(connection_in, setp);
650 /* Wait for some data to arrive. */
651 while (select(connection_in + 1, setp, NULL, NULL, NULL) == -1 &&
652 (errno == EAGAIN || errno == EINTR))
655 /* Read data from the socket. */
656 len = read(connection_in, buf, sizeof(buf));
658 log("Connection closed by %.200s", get_remote_ipaddr());
662 fatal("Read from socket failed: %.100s", strerror(errno));
663 /* Append it to the buffer. */
664 packet_process_incoming(buf, len);
672 return packet_read_seqnr(NULL);
676 * Waits until a packet has been received, verifies that its type matches
677 * that given, and gives a fatal error and exits if there is a mismatch.
681 packet_read_expect(int expected_type)
685 type = packet_read();
686 if (type != expected_type)
687 packet_disconnect("Protocol error: expected packet type %d, got %d",
688 expected_type, type);
691 /* Checks if a full packet is available in the data received so far via
692 * packet_process_incoming. If so, reads the packet; otherwise returns
693 * SSH_MSG_NONE. This does not wait for data from the connection.
695 * SSH_MSG_DISCONNECT is handled specially here. Also,
696 * SSH_MSG_IGNORE messages are skipped by this function and are never returned
701 packet_read_poll1(void)
703 u_int len, padded_len;
706 u_int checksum, stored_checksum;
708 /* Check if input size is less than minimum packet size. */
709 if (buffer_len(&input) < 4 + 8)
711 /* Get length of incoming packet. */
712 ucp = buffer_ptr(&input);
713 len = GET_32BIT(ucp);
714 if (len < 1 + 2 + 2 || len > 256 * 1024)
715 packet_disconnect("Bad packet length %d.", len);
716 padded_len = (len + 8) & ~7;
718 /* Check if the packet has been entirely received. */
719 if (buffer_len(&input) < 4 + padded_len)
722 /* The entire packet is in buffer. */
724 /* Consume packet length. */
725 buffer_consume(&input, 4);
728 * Cryptographic attack detector for ssh
729 * (C)1998 CORE-SDI, Buenos Aires Argentina
730 * Ariel Futoransky(futo@core-sdi.com)
732 if (receive_context.cipher->number != SSH_CIPHER_NONE &&
733 detect_attack(buffer_ptr(&input), padded_len, NULL) == DEATTACK_DETECTED)
734 packet_disconnect("crc32 compensation attack: network attack detected");
736 /* Decrypt data to incoming_packet. */
737 buffer_clear(&incoming_packet);
738 cp = buffer_append_space(&incoming_packet, padded_len);
739 cipher_decrypt(&receive_context, cp, buffer_ptr(&input), padded_len);
741 buffer_consume(&input, padded_len);
744 fprintf(stderr, "read_poll plain: ");
745 buffer_dump(&incoming_packet);
748 /* Compute packet checksum. */
749 checksum = ssh_crc32(buffer_ptr(&incoming_packet),
750 buffer_len(&incoming_packet) - 4);
753 buffer_consume(&incoming_packet, 8 - len % 8);
755 /* Test check bytes. */
756 if (len != buffer_len(&incoming_packet))
757 packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
758 len, buffer_len(&incoming_packet));
760 ucp = (u_char *)buffer_ptr(&incoming_packet) + len - 4;
761 stored_checksum = GET_32BIT(ucp);
762 if (checksum != stored_checksum)
763 packet_disconnect("Corrupted check bytes on input.");
764 buffer_consume_end(&incoming_packet, 4);
766 if (packet_compression) {
767 buffer_clear(&compression_buffer);
768 buffer_uncompress(&incoming_packet, &compression_buffer);
769 buffer_clear(&incoming_packet);
770 buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
771 buffer_len(&compression_buffer));
773 type = buffer_get_char(&incoming_packet);
778 packet_read_poll2(u_int32_t *seqnr_p)
780 static u_int32_t seqnr = 0;
781 static u_int packet_length = 0;
783 u_char *macbuf, *ucp, type;
785 int maclen, block_size;
790 if (newkeys[MODE_IN] != NULL) {
791 enc = &newkeys[MODE_IN]->enc;
792 mac = &newkeys[MODE_IN]->mac;
793 comp = &newkeys[MODE_IN]->comp;
795 maclen = mac && mac->enabled ? mac->mac_len : 0;
796 block_size = enc ? enc->cipher->block_size : 8;
798 if (packet_length == 0) {
800 * check if input size is less than the cipher block size,
801 * decrypt first block and extract length of incoming packet
803 if (buffer_len(&input) < block_size)
805 buffer_clear(&incoming_packet);
806 cp = buffer_append_space(&incoming_packet, block_size);
807 cipher_decrypt(&receive_context, cp, buffer_ptr(&input),
809 ucp = buffer_ptr(&incoming_packet);
810 packet_length = GET_32BIT(ucp);
811 if (packet_length < 1 + 4 || packet_length > 256 * 1024) {
812 buffer_dump(&incoming_packet);
813 packet_disconnect("Bad packet length %d.", packet_length);
815 DBG(debug("input: packet len %d", packet_length+4));
816 buffer_consume(&input, block_size);
818 /* we have a partial packet of block_size bytes */
819 need = 4 + packet_length - block_size;
820 DBG(debug("partial packet %d, need %d, maclen %d", block_size,
822 if (need % block_size != 0)
823 fatal("padding error: need %d block %d mod %d",
824 need, block_size, need % block_size);
826 * check if the entire packet has been received and
827 * decrypt into incoming_packet
829 if (buffer_len(&input) < need + maclen)
832 fprintf(stderr, "read_poll enc/full: ");
835 cp = buffer_append_space(&incoming_packet, need);
836 cipher_decrypt(&receive_context, cp, buffer_ptr(&input), need);
837 buffer_consume(&input, need);
839 * compute MAC over seqnr and packet,
840 * increment sequence number for incoming packet
842 if (mac && mac->enabled) {
843 macbuf = mac_compute(mac, seqnr,
844 buffer_ptr(&incoming_packet),
845 buffer_len(&incoming_packet));
846 if (memcmp(macbuf, buffer_ptr(&input), mac->mac_len) != 0)
847 packet_disconnect("Corrupted MAC on input.");
848 DBG(debug("MAC #%d ok", seqnr));
849 buffer_consume(&input, mac->mac_len);
854 log("incoming seqnr wraps around");
857 cp = buffer_ptr(&incoming_packet);
859 padlen = (u_char) *cp;
860 DBG(debug("input: padlen %d", padlen));
862 packet_disconnect("Corrupted padlen %d on input.", padlen);
864 /* skip packet size + padlen, discard padding */
865 buffer_consume(&incoming_packet, 4 + 1);
866 buffer_consume_end(&incoming_packet, padlen);
868 DBG(debug("input: len before de-compress %d", buffer_len(&incoming_packet)));
869 if (comp && comp->enabled) {
870 buffer_clear(&compression_buffer);
871 buffer_uncompress(&incoming_packet, &compression_buffer);
872 buffer_clear(&incoming_packet);
873 buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
874 buffer_len(&compression_buffer));
875 DBG(debug("input: len after de-compress %d", buffer_len(&incoming_packet)));
878 * get packet type, implies consume.
879 * return length of payload (without type field)
881 type = buffer_get_char(&incoming_packet);
882 if (type == SSH2_MSG_NEWKEYS)
883 set_newkeys(MODE_IN);
885 fprintf(stderr, "read/plain[%d]:\r\n", type);
886 buffer_dump(&incoming_packet);
888 /* reset for next packet */
894 packet_read_poll_seqnr(u_int32_t *seqnr_p)
902 type = packet_read_poll2(seqnr_p);
904 DBG(debug("received packet type %d", type));
906 case SSH2_MSG_IGNORE:
910 msg = packet_get_string(NULL);
911 debug("Remote: %.900s", msg);
913 msg = packet_get_string(NULL);
916 case SSH2_MSG_DISCONNECT:
917 reason = packet_get_int();
918 msg = packet_get_string(NULL);
919 log("Received disconnect from %s: %d: %.400s", get_remote_ipaddr(),
924 case SSH2_MSG_UNIMPLEMENTED:
925 seqnr = packet_get_int();
926 debug("Received SSH2_MSG_UNIMPLEMENTED for %d", seqnr);
933 type = packet_read_poll1();
938 msg = packet_get_string(NULL);
939 debug("Remote: %.900s", msg);
942 case SSH_MSG_DISCONNECT:
943 msg = packet_get_string(NULL);
944 log("Received disconnect from %s: %.400s", get_remote_ipaddr(),
951 DBG(debug("received packet type %d", type));
960 packet_read_poll(void)
962 return packet_read_poll_seqnr(NULL);
966 * Buffers the given amount of input characters. This is intended to be used
967 * together with packet_read_poll.
971 packet_process_incoming(const char *buf, u_int len)
973 buffer_append(&input, buf, len);
976 /* Returns a character from the packet. */
979 packet_get_char(void)
982 buffer_get(&incoming_packet, &ch, 1);
986 /* Returns an integer from the packet data. */
991 return buffer_get_int(&incoming_packet);
995 * Returns an arbitrary precision integer from the packet data. The integer
996 * must have been initialized before this call.
1000 packet_get_bignum(BIGNUM * value)
1002 buffer_get_bignum(&incoming_packet, value);
1006 packet_get_bignum2(BIGNUM * value)
1008 buffer_get_bignum2(&incoming_packet, value);
1012 packet_get_raw(int *length_ptr)
1014 int bytes = buffer_len(&incoming_packet);
1015 if (length_ptr != NULL)
1016 *length_ptr = bytes;
1017 return buffer_ptr(&incoming_packet);
1021 packet_remaining(void)
1023 return buffer_len(&incoming_packet);
1027 * Returns a string from the packet data. The string is allocated using
1028 * xmalloc; it is the responsibility of the calling program to free it when
1029 * no longer needed. The length_ptr argument may be NULL, or point to an
1030 * integer into which the length of the string is stored.
1034 packet_get_string(u_int *length_ptr)
1036 return buffer_get_string(&incoming_packet, length_ptr);
1040 * Sends a diagnostic message from the server to the client. This message
1041 * can be sent at any time (but not while constructing another message). The
1042 * message is printed immediately, but only if the client is being executed
1043 * in verbose mode. These messages are primarily intended to ease debugging
1044 * authentication problems. The length of the formatted message must not
1045 * exceed 1024 bytes. This will automatically call packet_write_wait.
1049 packet_send_debug(const char *fmt,...)
1054 if (compat20 && (datafellows & SSH_BUG_DEBUG))
1057 va_start(args, fmt);
1058 vsnprintf(buf, sizeof(buf), fmt, args);
1062 packet_start(SSH2_MSG_DEBUG);
1063 packet_put_char(0); /* bool: always display */
1064 packet_put_cstring(buf);
1065 packet_put_cstring("");
1067 packet_start(SSH_MSG_DEBUG);
1068 packet_put_cstring(buf);
1071 packet_write_wait();
1075 * Logs the error plus constructs and sends a disconnect packet, closes the
1076 * connection, and exits. This function never returns. The error message
1077 * should not contain a newline. The length of the formatted message must
1078 * not exceed 1024 bytes.
1082 packet_disconnect(const char *fmt,...)
1086 static int disconnecting = 0;
1087 if (disconnecting) /* Guard against recursive invocations. */
1088 fatal("packet_disconnect called recursively.");
1092 * Format the message. Note that the caller must make sure the
1093 * message is of limited size.
1095 va_start(args, fmt);
1096 vsnprintf(buf, sizeof(buf), fmt, args);
1099 /* Send the disconnect message to the other side, and wait for it to get sent. */
1101 packet_start(SSH2_MSG_DISCONNECT);
1102 packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1103 packet_put_cstring(buf);
1104 packet_put_cstring("");
1106 packet_start(SSH_MSG_DISCONNECT);
1107 packet_put_cstring(buf);
1110 packet_write_wait();
1112 /* Stop listening for connections. */
1113 channel_close_all();
1115 /* Close the connection. */
1118 /* Display the error locally and exit. */
1119 log("Disconnecting: %.100s", buf);
1123 /* Checks if there is any buffered output, and tries to write some of the output. */
1126 packet_write_poll(void)
1128 int len = buffer_len(&output);
1130 len = write(connection_out, buffer_ptr(&output), len);
1132 if (errno == EAGAIN)
1135 fatal("Write failed: %.100s", strerror(errno));
1137 buffer_consume(&output, len);
1142 * Calls packet_write_poll repeatedly until all pending output data has been
1147 packet_write_wait(void)
1151 setp = (fd_set *)xmalloc(howmany(connection_out + 1, NFDBITS) *
1153 packet_write_poll();
1154 while (packet_have_data_to_write()) {
1155 memset(setp, 0, howmany(connection_out + 1, NFDBITS) *
1157 FD_SET(connection_out, setp);
1158 while (select(connection_out + 1, NULL, setp, NULL, NULL) == -1 &&
1159 (errno == EAGAIN || errno == EINTR))
1161 packet_write_poll();
1166 /* Returns true if there is buffered data to write to the connection. */
1169 packet_have_data_to_write(void)
1171 return buffer_len(&output) != 0;
1174 /* Returns true if there is not too much data to write to the connection. */
1177 packet_not_very_much_data_to_write(void)
1179 if (interactive_mode)
1180 return buffer_len(&output) < 16384;
1182 return buffer_len(&output) < 128 * 1024;
1185 /* Informs that the current session is interactive. Sets IP flags for that. */
1188 packet_set_interactive(int interactive)
1190 static int called = 0;
1191 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1192 int lowdelay = IPTOS_LOWDELAY;
1193 int throughput = IPTOS_THROUGHPUT;
1200 /* Record that we are in interactive mode. */
1201 interactive_mode = interactive;
1203 /* Only set socket options if using a socket. */
1204 if (!packet_connection_is_on_socket())
1207 * IPTOS_LOWDELAY and IPTOS_THROUGHPUT are IPv4 only
1211 * Set IP options for an interactive connection. Use
1212 * IPTOS_LOWDELAY and TCP_NODELAY.
1214 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1215 if (packet_connection_is_ipv4()) {
1216 if (setsockopt(connection_in, IPPROTO_IP, IP_TOS,
1217 (void *) &lowdelay, sizeof(lowdelay)) < 0)
1218 error("setsockopt IPTOS_LOWDELAY: %.100s",
1222 set_nodelay(connection_in);
1223 } else if (packet_connection_is_ipv4()) {
1225 * Set IP options for a non-interactive connection. Use
1228 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1229 if (setsockopt(connection_in, IPPROTO_IP, IP_TOS, (void *) &throughput,
1230 sizeof(throughput)) < 0)
1231 error("setsockopt IPTOS_THROUGHPUT: %.100s", strerror(errno));
1236 /* Returns true if the current connection is interactive. */
1239 packet_is_interactive(void)
1241 return interactive_mode;
1245 packet_set_maxsize(int s)
1247 static int called = 0;
1249 log("packet_set_maxsize: called twice: old %d new %d",
1250 max_packet_size, s);
1253 if (s < 4 * 1024 || s > 1024 * 1024) {
1254 log("packet_set_maxsize: bad size %d", s);
1258 debug("packet_set_maxsize: setting to %d", s);
1259 max_packet_size = s;
1263 /* roundup current message to pad bytes */
1265 packet_add_padding(u_char pad)
1271 * 9.2. Ignored Data Message
1273 * byte SSH_MSG_IGNORE
1276 * All implementations MUST understand (and ignore) this message at any
1277 * time (after receiving the protocol version). No implementation is
1278 * required to send them. This message can be used as an additional
1279 * protection measure against advanced traffic analysis techniques.
1282 packet_send_ignore(int nbytes)
1287 packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1288 packet_put_int(nbytes);
1289 for (i = 0; i < nbytes; i++) {
1291 rand = arc4random();
1292 packet_put_char(rand & 0xff);