5 * Author: Tatu Ylonen <ylo@cs.hut.fi>
7 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
10 * Created: Sat Mar 18 02:40:40 1995 ylo
12 * This file contains code implementing the packet protocol and communication
13 * with the other side. This same code is used both on client and server side.
15 * SSH2 packet format added by Markus Friedl.
38 #include <openssl/bn.h>
39 #include <openssl/dh.h>
40 #include <openssl/hmac.h>
52 * This variable contains the file descriptors used for communicating with
53 * the other side. connection_in is used for reading; connection_out for
54 * writing. These can be the same descriptor, in which case it is assumed to
57 static int connection_in = -1;
58 static int connection_out = -1;
61 * Cipher type. This value is only used to determine whether to pad the
62 * packets with zeroes or random data.
64 static int cipher_type = SSH_CIPHER_NONE;
66 /* Protocol flags for the remote side. */
67 static unsigned int remote_protocol_flags = 0;
69 /* Encryption context for receiving data. This is only used for decryption. */
70 static CipherContext receive_context;
72 /* Encryption context for sending data. This is only used for encryption. */
73 static CipherContext send_context;
75 /* Buffer for raw input data from the socket. */
78 /* Buffer for raw output data going to the socket. */
81 /* Buffer for the partial outgoing packet being constructed. */
82 static Buffer outgoing_packet;
84 /* Buffer for the incoming packet currently being processed. */
85 static Buffer incoming_packet;
87 /* Scratch buffer for packet compression/decompression. */
88 static Buffer compression_buffer;
90 /* Flag indicating whether packet compression/decompression is enabled. */
91 static int packet_compression = 0;
93 /* default maximum packet size */
94 int max_packet_size = 32768;
96 /* Flag indicating whether this module has been initialized. */
97 static int initialized = 0;
99 /* Set to true if the connection is interactive. */
100 static int interactive_mode = 0;
102 /* True if SSH2 packet format is used */
103 int use_ssh2_packet_format = 0;
105 /* Session key information for Encryption and MAC */
109 packet_set_kex(Kex *k)
111 if( k->mac[MODE_IN ].key == NULL ||
112 k->enc[MODE_IN ].key == NULL ||
113 k->enc[MODE_IN ].iv == NULL ||
114 k->mac[MODE_OUT].key == NULL ||
115 k->enc[MODE_OUT].key == NULL ||
116 k->enc[MODE_OUT].iv == NULL)
121 clear_enc_keys(Enc *enc, int len)
123 memset(enc->iv, 0, len);
124 memset(enc->key, 0, len);
131 packet_set_ssh2_format(void)
133 DBG(debug("use_ssh2_packet_format"));
134 use_ssh2_packet_format = 1;
138 * Sets the descriptors used for communication. Disables encryption until
139 * packet_set_encryption_key is called.
142 packet_set_connection(int fd_in, int fd_out)
144 connection_in = fd_in;
145 connection_out = fd_out;
146 cipher_type = SSH_CIPHER_NONE;
147 cipher_set_key(&send_context, SSH_CIPHER_NONE, (unsigned char *) "", 0);
148 cipher_set_key(&receive_context, SSH_CIPHER_NONE, (unsigned char *) "", 0);
152 buffer_init(&output);
153 buffer_init(&outgoing_packet);
154 buffer_init(&incoming_packet);
156 /* Kludge: arrange the close function to be called from fatal(). */
157 fatal_add_cleanup((void (*) (void *)) packet_close, NULL);
160 /* Returns 1 if remote host is connected via socket, 0 if not. */
163 packet_connection_is_on_socket()
165 struct sockaddr_storage from, to;
166 socklen_t fromlen, tolen;
168 /* filedescriptors in and out are the same, so it's a socket */
169 if (connection_in == connection_out)
171 fromlen = sizeof(from);
172 memset(&from, 0, sizeof(from));
173 if (getpeername(connection_in, (struct sockaddr *)&from, &fromlen) < 0)
176 memset(&to, 0, sizeof(to));
177 if (getpeername(connection_out, (struct sockaddr *)&to, &tolen) < 0)
179 if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
181 if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
186 /* returns 1 if connection is via ipv4 */
189 packet_connection_is_ipv4()
191 struct sockaddr_storage to;
192 socklen_t tolen = sizeof(to);
194 memset(&to, 0, sizeof(to));
195 if (getsockname(connection_out, (struct sockaddr *)&to, &tolen) < 0)
197 if (to.ss_family != AF_INET)
202 /* Sets the connection into non-blocking mode. */
205 packet_set_nonblocking()
207 /* Set the socket into non-blocking mode. */
208 if (fcntl(connection_in, F_SETFL, O_NONBLOCK) < 0)
209 error("fcntl O_NONBLOCK: %.100s", strerror(errno));
211 if (connection_out != connection_in) {
212 if (fcntl(connection_out, F_SETFL, O_NONBLOCK) < 0)
213 error("fcntl O_NONBLOCK: %.100s", strerror(errno));
217 /* Returns the socket used for reading. */
220 packet_get_connection_in()
222 return connection_in;
225 /* Returns the descriptor used for writing. */
228 packet_get_connection_out()
230 return connection_out;
233 /* Closes the connection and clears and frees internal data structures. */
241 if (connection_in == connection_out) {
242 shutdown(connection_out, SHUT_RDWR);
243 close(connection_out);
245 close(connection_in);
246 close(connection_out);
249 buffer_free(&output);
250 buffer_free(&outgoing_packet);
251 buffer_free(&incoming_packet);
252 if (packet_compression) {
253 buffer_free(&compression_buffer);
254 buffer_compress_uninit();
258 /* Sets remote side protocol flags. */
261 packet_set_protocol_flags(unsigned int protocol_flags)
263 remote_protocol_flags = protocol_flags;
264 channel_set_options((protocol_flags & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) != 0);
267 /* Returns the remote protocol flags set earlier by the above function. */
270 packet_get_protocol_flags()
272 return remote_protocol_flags;
276 * Starts packet compression from the next packet on in both directions.
277 * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
280 /*** XXXXX todo: kex means re-init */
282 packet_start_compression(int level)
284 if (packet_compression)
285 fatal("Compression already enabled.");
286 packet_compression = 1;
287 buffer_init(&compression_buffer);
288 buffer_compress_init(level);
292 * Encrypts the given number of bytes, copying from src to dest. bytes is
293 * known to be a multiple of 8.
297 packet_encrypt(CipherContext * cc, void *dest, void *src,
300 cipher_encrypt(cc, dest, src, bytes);
304 * Decrypts the given number of bytes, copying from src to dest. bytes is
305 * known to be a multiple of 8.
309 packet_decrypt(CipherContext * cc, void *dest, void *src,
314 if ((bytes % 8) != 0)
315 fatal("packet_decrypt: bad ciphertext length %d", bytes);
318 * Cryptographic attack detector for ssh - Modifications for packet.c
319 * (C)1998 CORE-SDI, Buenos Aires Argentina Ariel Futoransky(futo@core-sdi.com)
322 if (cc->type == SSH_CIPHER_NONE || compat20) {
325 i = detect_attack(src, bytes, NULL);
327 if (i == DEATTACK_DETECTED)
328 packet_disconnect("crc32 compensation attack: network attack detected");
330 cipher_decrypt(cc, dest, src, bytes);
334 * Causes any further packets to be encrypted using the given key. The same
335 * key is used for both sending and reception. However, both directions are
336 * encrypted independently of each other.
340 packet_set_encryption_key(const unsigned char *key, unsigned int keylen,
344 fatal("keylen too small: %d", keylen);
346 /* All other ciphers use the same key in both directions for now. */
347 cipher_set_key(&receive_context, cipher, key, keylen);
348 cipher_set_key(&send_context, cipher, key, keylen);
351 /* Starts constructing a packet to send. */
354 packet_start1(int type)
358 buffer_clear(&outgoing_packet);
361 buffer_append(&outgoing_packet, buf, 9);
365 packet_start2(int type)
369 buffer_clear(&outgoing_packet);
370 memset(buf, 0, sizeof buf);
371 /* buf[0..3] = payload_len; */
372 /* buf[4] = pad_len; */
373 buf[5] = type & 0xff;
374 buffer_append(&outgoing_packet, buf, sizeof buf);
378 packet_start(int type)
380 DBG(debug("packet_start[%d]",type));
381 if (use_ssh2_packet_format)
387 /* Appends a character to the packet data. */
390 packet_put_char(int value)
393 buffer_append(&outgoing_packet, &ch, 1);
396 /* Appends an integer to the packet data. */
399 packet_put_int(unsigned int value)
401 buffer_put_int(&outgoing_packet, value);
404 /* Appends a string to packet data. */
407 packet_put_string(const char *buf, unsigned int len)
409 buffer_put_string(&outgoing_packet, buf, len);
412 packet_put_cstring(const char *str)
414 buffer_put_string(&outgoing_packet, str, strlen(str));
418 packet_put_raw(const char *buf, unsigned int len)
420 buffer_append(&outgoing_packet, buf, len);
424 /* Appends an arbitrary precision integer to packet data. */
427 packet_put_bignum(BIGNUM * value)
429 buffer_put_bignum(&outgoing_packet, value);
432 packet_put_bignum2(BIGNUM * value)
434 buffer_put_bignum2(&outgoing_packet, value);
438 * Finalizes and sends the packet. If the encryption key has been set,
439 * encrypts the packet before sending.
447 unsigned int checksum;
451 * If using packet compression, compress the payload of the outgoing
454 if (packet_compression) {
455 buffer_clear(&compression_buffer);
457 buffer_consume(&outgoing_packet, 8);
459 buffer_append(&compression_buffer, "\0\0\0\0\0\0\0\0", 8);
460 buffer_compress(&outgoing_packet, &compression_buffer);
461 buffer_clear(&outgoing_packet);
462 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
463 buffer_len(&compression_buffer));
465 /* Compute packet length without padding (add checksum, remove padding). */
466 len = buffer_len(&outgoing_packet) + 4 - 8;
468 /* Insert padding. */
469 padding = 8 - len % 8;
470 if (cipher_type != SSH_CIPHER_NONE) {
471 cp = buffer_ptr(&outgoing_packet);
472 for (i = 0; i < padding; i++) {
475 cp[7 - i] = rand & 0xff;
479 buffer_consume(&outgoing_packet, 8 - padding);
481 /* Add check bytes. */
482 checksum = crc32((unsigned char *) buffer_ptr(&outgoing_packet),
483 buffer_len(&outgoing_packet));
484 PUT_32BIT(buf, checksum);
485 buffer_append(&outgoing_packet, buf, 4);
488 fprintf(stderr, "packet_send plain: ");
489 buffer_dump(&outgoing_packet);
492 /* Append to output. */
494 buffer_append(&output, buf, 4);
495 buffer_append_space(&output, &cp, buffer_len(&outgoing_packet));
496 packet_encrypt(&send_context, cp, buffer_ptr(&outgoing_packet),
497 buffer_len(&outgoing_packet));
500 fprintf(stderr, "encrypted: ");
501 buffer_dump(&output);
504 buffer_clear(&outgoing_packet);
507 * Note that the packet is now only buffered in output. It won\'t be
508 * actually sent until packet_write_wait or packet_write_poll is
514 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
519 unsigned char *macbuf = NULL;
521 unsigned int packet_length = 0;
522 unsigned int i, padlen, len;
524 static unsigned int seqnr = 0;
532 enc = &kex->enc[MODE_OUT];
533 mac = &kex->mac[MODE_OUT];
534 comp = &kex->comp[MODE_OUT];
536 block_size = enc ? enc->block_size : 8;
538 cp = buffer_ptr(&outgoing_packet);
542 fprintf(stderr, "plain: ");
543 buffer_dump(&outgoing_packet);
546 if (comp && comp->enabled) {
547 len = buffer_len(&outgoing_packet);
548 /* skip header, compress only payload */
549 buffer_consume(&outgoing_packet, 5);
550 buffer_clear(&compression_buffer);
551 buffer_compress(&outgoing_packet, &compression_buffer);
552 buffer_clear(&outgoing_packet);
553 buffer_append(&outgoing_packet, "\0\0\0\0\0", 5);
554 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
555 buffer_len(&compression_buffer));
556 DBG(debug("compression: raw %d compressed %d", len,
557 buffer_len(&outgoing_packet)));
560 /* sizeof (packet_len + pad_len + payload) */
561 len = buffer_len(&outgoing_packet);
564 * calc size of padding, alloc space, get random data,
565 * minimum padding is 4 bytes
567 padlen = block_size - (len % block_size);
569 padlen += block_size;
570 buffer_append_space(&outgoing_packet, &cp, padlen);
571 if (enc && enc->type != SSH_CIPHER_NONE) {
572 for (i = 0; i < padlen; i++) {
579 /* packet_length includes payload, padding and padding length field */
580 packet_length = buffer_len(&outgoing_packet) - 4;
581 cp = buffer_ptr(&outgoing_packet);
582 PUT_32BIT(cp, packet_length);
583 cp[4] = padlen & 0xff;
584 DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen));
586 /* compute MAC over seqnr and packet(length fields, payload, padding) */
587 if (mac && mac->enabled) {
588 macbuf = hmac( mac->md, seqnr,
589 (unsigned char *) buffer_ptr(&outgoing_packet),
590 buffer_len(&outgoing_packet),
591 mac->key, mac->key_len
593 DBG(debug("done calc HMAC out #%d", seqnr));
595 /* encrypt packet and append to output buffer. */
596 buffer_append_space(&output, &cp, buffer_len(&outgoing_packet));
597 packet_encrypt(&send_context, cp, buffer_ptr(&outgoing_packet),
598 buffer_len(&outgoing_packet));
599 /* append unencrypted MAC */
600 if (mac && mac->enabled)
601 buffer_append(&output, (char *)macbuf, mac->mac_len);
603 fprintf(stderr, "encrypted: ");
604 buffer_dump(&output);
606 /* increment sequence number for outgoing packets */
608 log("outgoing seqnr wraps around");
609 buffer_clear(&outgoing_packet);
611 if (type == SSH2_MSG_NEWKEYS) {
612 if (kex==NULL || mac==NULL || enc==NULL || comp==NULL)
613 fatal("packet_send2: no KEX");
616 DBG(debug("cipher_set_key_iv send_context"));
617 cipher_set_key_iv(&send_context, enc->type,
618 enc->key, enc->key_len,
619 enc->iv, enc->iv_len);
620 clear_enc_keys(enc, kex->we_need);
621 if (comp->type != 0 && comp->enabled == 0) {
623 if (! packet_compression)
624 packet_start_compression(6);
632 if (use_ssh2_packet_format)
636 DBG(debug("packet_send done"));
640 * Waits until a packet has been received, and returns its type. Note that
641 * no other data is processed until this returns, so this function should not
642 * be used during the interactive session.
646 packet_read(int *payload_len_ptr)
651 DBG(debug("packet_read()"));
653 /* Since we are blocking, ensure that all written packets have been sent. */
656 /* Stay in the loop until we have received a complete packet. */
658 /* Try to read a packet from the buffer. */
659 type = packet_read_poll(payload_len_ptr);
660 if (type == SSH_SMSG_SUCCESS
661 || type == SSH_SMSG_FAILURE
662 || type == SSH_CMSG_EOF
663 || type == SSH_CMSG_EXIT_CONFIRMATION)
664 packet_integrity_check(*payload_len_ptr, 0, type);
665 /* If we got a packet, return it. */
666 if (type != SSH_MSG_NONE)
669 * Otherwise, wait for some data to arrive, add it to the
670 * buffer, and try again.
673 FD_SET(connection_in, &set);
675 /* Wait for some data to arrive. */
676 select(connection_in + 1, &set, NULL, NULL, NULL);
678 /* Read data from the socket. */
679 len = read(connection_in, buf, sizeof(buf));
681 log("Connection closed by %.200s", get_remote_ipaddr());
685 fatal("Read from socket failed: %.100s", strerror(errno));
686 /* Append it to the buffer. */
687 packet_process_incoming(buf, len);
693 * Waits until a packet has been received, verifies that its type matches
694 * that given, and gives a fatal error and exits if there is a mismatch.
698 packet_read_expect(int *payload_len_ptr, int expected_type)
702 type = packet_read(payload_len_ptr);
703 if (type != expected_type)
704 packet_disconnect("Protocol error: expected packet type %d, got %d",
705 expected_type, type);
708 /* Checks if a full packet is available in the data received so far via
709 * packet_process_incoming. If so, reads the packet; otherwise returns
710 * SSH_MSG_NONE. This does not wait for data from the connection.
712 * SSH_MSG_DISCONNECT is handled specially here. Also,
713 * SSH_MSG_IGNORE messages are skipped by this function and are never returned
716 * The returned payload_len does include space consumed by:
724 packet_read_poll1(int *payload_len_ptr)
726 unsigned int len, padded_len;
729 unsigned int checksum, stored_checksum;
731 /* Check if input size is less than minimum packet size. */
732 if (buffer_len(&input) < 4 + 8)
734 /* Get length of incoming packet. */
735 ucp = (unsigned char *) buffer_ptr(&input);
736 len = GET_32BIT(ucp);
737 if (len < 1 + 2 + 2 || len > 256 * 1024)
738 packet_disconnect("Bad packet length %d.", len);
739 padded_len = (len + 8) & ~7;
741 /* Check if the packet has been entirely received. */
742 if (buffer_len(&input) < 4 + padded_len)
745 /* The entire packet is in buffer. */
747 /* Consume packet length. */
748 buffer_consume(&input, 4);
750 /* Copy data to incoming_packet. */
751 buffer_clear(&incoming_packet);
752 buffer_append_space(&incoming_packet, &cp, padded_len);
753 packet_decrypt(&receive_context, cp, buffer_ptr(&input), padded_len);
754 buffer_consume(&input, padded_len);
757 fprintf(stderr, "read_poll plain: ");
758 buffer_dump(&incoming_packet);
761 /* Compute packet checksum. */
762 checksum = crc32((unsigned char *) buffer_ptr(&incoming_packet),
763 buffer_len(&incoming_packet) - 4);
766 buffer_consume(&incoming_packet, 8 - len % 8);
768 /* Test check bytes. */
770 if (len != buffer_len(&incoming_packet))
771 packet_disconnect("packet_read_poll: len %d != buffer_len %d.",
772 len, buffer_len(&incoming_packet));
774 ucp = (unsigned char *) buffer_ptr(&incoming_packet) + len - 4;
775 stored_checksum = GET_32BIT(ucp);
776 if (checksum != stored_checksum)
777 packet_disconnect("Corrupted check bytes on input.");
778 buffer_consume_end(&incoming_packet, 4);
780 /* If using packet compression, decompress the packet. */
781 if (packet_compression) {
782 buffer_clear(&compression_buffer);
783 buffer_uncompress(&incoming_packet, &compression_buffer);
784 buffer_clear(&incoming_packet);
785 buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
786 buffer_len(&compression_buffer));
788 /* Get packet type. */
789 buffer_get(&incoming_packet, &buf[0], 1);
791 /* Return length of payload (without type field). */
792 *payload_len_ptr = buffer_len(&incoming_packet);
795 return (unsigned char) buf[0];
799 packet_read_poll2(int *payload_len_ptr)
801 unsigned int padlen, need;
802 unsigned char buf[8], *macbuf;
805 static unsigned int packet_length = 0;
806 static unsigned int seqnr = 0;
808 int maclen, block_size;
814 enc = &kex->enc[MODE_IN];
815 mac = &kex->mac[MODE_IN];
816 comp = &kex->comp[MODE_IN];
818 maclen = mac && mac->enabled ? mac->mac_len : 0;
819 block_size = enc ? enc->block_size : 8;
821 if (packet_length == 0) {
823 * check if input size is less than the cipher block size,
824 * decrypt first block and extract length of incoming packet
826 if (buffer_len(&input) < block_size)
828 buffer_clear(&incoming_packet);
829 buffer_append_space(&incoming_packet, &cp, block_size);
830 packet_decrypt(&receive_context, cp, buffer_ptr(&input),
832 ucp = (unsigned char *) buffer_ptr(&incoming_packet);
833 packet_length = GET_32BIT(ucp);
834 if (packet_length < 1 + 4 || packet_length > 256 * 1024) {
835 buffer_dump(&incoming_packet);
836 packet_disconnect("Bad packet length %d.", packet_length);
838 DBG(debug("input: packet len %d", packet_length+4));
839 buffer_consume(&input, block_size);
841 /* we have a partial packet of block_size bytes */
842 need = 4 + packet_length - block_size;
843 DBG(debug("partial packet %d, need %d, maclen %d", block_size,
845 if (need % block_size != 0)
846 fatal("padding error: need %d block %d mod %d",
847 need, block_size, need % block_size);
849 * check if the entire packet has been received and
850 * decrypt into incoming_packet
852 if (buffer_len(&input) < need + maclen)
855 fprintf(stderr, "read_poll enc/full: ");
858 buffer_append_space(&incoming_packet, &cp, need);
859 packet_decrypt(&receive_context, cp, buffer_ptr(&input), need);
860 buffer_consume(&input, need);
862 * compute MAC over seqnr and packet,
863 * increment sequence number for incoming packet
865 if (mac && mac->enabled) {
866 macbuf = hmac( mac->md, seqnr,
867 (unsigned char *) buffer_ptr(&incoming_packet),
868 buffer_len(&incoming_packet),
869 mac->key, mac->key_len
871 if (memcmp(macbuf, buffer_ptr(&input), mac->mac_len) != 0)
872 packet_disconnect("Corrupted HMAC on input.");
873 DBG(debug("HMAC #%d ok", seqnr));
874 buffer_consume(&input, mac->mac_len);
877 log("incoming seqnr wraps around");
880 cp = buffer_ptr(&incoming_packet) + 4;
882 DBG(debug("input: padlen %d", padlen));
884 packet_disconnect("Corrupted padlen %d on input.", padlen);
886 /* skip packet size + padlen, discard padding */
887 buffer_consume(&incoming_packet, 4 + 1);
888 buffer_consume_end(&incoming_packet, padlen);
890 DBG(debug("input: len before de-compress %d", buffer_len(&incoming_packet)));
891 if (comp && comp->enabled) {
892 buffer_clear(&compression_buffer);
893 buffer_uncompress(&incoming_packet, &compression_buffer);
894 buffer_clear(&incoming_packet);
895 buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
896 buffer_len(&compression_buffer));
897 DBG(debug("input: len after de-compress %d", buffer_len(&incoming_packet)));
900 * get packet type, implies consume.
901 * return length of payload (without type field)
903 buffer_get(&incoming_packet, (char *)&buf[0], 1);
904 *payload_len_ptr = buffer_len(&incoming_packet);
906 /* reset for next packet */
909 /* extract packet type */
910 type = (unsigned char)buf[0];
912 if (type == SSH2_MSG_NEWKEYS) {
913 if (kex==NULL || mac==NULL || enc==NULL || comp==NULL)
914 fatal("packet_read_poll2: no KEX");
917 DBG(debug("cipher_set_key_iv receive_context"));
918 cipher_set_key_iv(&receive_context, enc->type,
919 enc->key, enc->key_len,
920 enc->iv, enc->iv_len);
921 clear_enc_keys(enc, kex->we_need);
922 if (comp->type != 0 && comp->enabled == 0) {
924 if (! packet_compression)
925 packet_start_compression(6);
930 fprintf(stderr, "read/plain[%d]:\r\n",type);
931 buffer_dump(&incoming_packet);
933 return (unsigned char)type;
937 packet_read_poll(int *payload_len_ptr)
941 int type = use_ssh2_packet_format ?
942 packet_read_poll2(payload_len_ptr):
943 packet_read_poll1(payload_len_ptr);
948 DBG(debug("received packet type %d", type));
950 case SSH2_MSG_IGNORE:
954 msg = packet_get_string(NULL);
955 debug("Remote: %.900s", msg);
957 msg = packet_get_string(NULL);
960 case SSH2_MSG_DISCONNECT:
961 reason = packet_get_int();
962 msg = packet_get_string(NULL);
963 log("Received disconnect: %d: %.900s", reason, msg);
976 msg = packet_get_string(NULL);
977 debug("Remote: %.900s", msg);
980 case SSH_MSG_DISCONNECT:
981 msg = packet_get_string(NULL);
982 log("Received disconnect: %.900s", msg);
988 DBG(debug("received packet type %d", type));
997 * Buffers the given amount of input characters. This is intended to be used
998 * together with packet_read_poll.
1002 packet_process_incoming(const char *buf, unsigned int len)
1004 buffer_append(&input, buf, len);
1007 /* Returns a character from the packet. */
1013 buffer_get(&incoming_packet, &ch, 1);
1014 return (unsigned char) ch;
1017 /* Returns an integer from the packet data. */
1022 return buffer_get_int(&incoming_packet);
1026 * Returns an arbitrary precision integer from the packet data. The integer
1027 * must have been initialized before this call.
1031 packet_get_bignum(BIGNUM * value, int *length_ptr)
1033 *length_ptr = buffer_get_bignum(&incoming_packet, value);
1037 packet_get_bignum2(BIGNUM * value, int *length_ptr)
1039 *length_ptr = buffer_get_bignum2(&incoming_packet, value);
1043 packet_get_raw(int *length_ptr)
1045 int bytes = buffer_len(&incoming_packet);
1046 if (length_ptr != NULL)
1047 *length_ptr = bytes;
1048 return buffer_ptr(&incoming_packet);
1052 packet_remaining(void)
1054 return buffer_len(&incoming_packet);
1058 * Returns a string from the packet data. The string is allocated using
1059 * xmalloc; it is the responsibility of the calling program to free it when
1060 * no longer needed. The length_ptr argument may be NULL, or point to an
1061 * integer into which the length of the string is stored.
1065 packet_get_string(unsigned int *length_ptr)
1067 return buffer_get_string(&incoming_packet, length_ptr);
1071 * Sends a diagnostic message from the server to the client. This message
1072 * can be sent at any time (but not while constructing another message). The
1073 * message is printed immediately, but only if the client is being executed
1074 * in verbose mode. These messages are primarily intended to ease debugging
1075 * authentication problems. The length of the formatted message must not
1076 * exceed 1024 bytes. This will automatically call packet_write_wait.
1080 packet_send_debug(const char *fmt,...)
1085 va_start(args, fmt);
1086 vsnprintf(buf, sizeof(buf), fmt, args);
1090 packet_start(SSH2_MSG_DEBUG);
1091 packet_put_char(0); /* bool: always display */
1092 packet_put_cstring(buf);
1093 packet_put_cstring("");
1095 packet_start(SSH_MSG_DEBUG);
1096 packet_put_cstring(buf);
1099 packet_write_wait();
1103 * Logs the error plus constructs and sends a disconnect packet, closes the
1104 * connection, and exits. This function never returns. The error message
1105 * should not contain a newline. The length of the formatted message must
1106 * not exceed 1024 bytes.
1110 packet_disconnect(const char *fmt,...)
1114 static int disconnecting = 0;
1115 if (disconnecting) /* Guard against recursive invocations. */
1116 fatal("packet_disconnect called recursively.");
1120 * Format the message. Note that the caller must make sure the
1121 * message is of limited size.
1123 va_start(args, fmt);
1124 vsnprintf(buf, sizeof(buf), fmt, args);
1127 /* Send the disconnect message to the other side, and wait for it to get sent. */
1129 packet_start(SSH2_MSG_DISCONNECT);
1130 packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1131 packet_put_cstring(buf);
1132 packet_put_cstring("");
1134 packet_start(SSH_MSG_DISCONNECT);
1135 packet_put_string(buf, strlen(buf));
1138 packet_write_wait();
1140 /* Stop listening for connections. */
1141 channel_stop_listening();
1143 /* Close the connection. */
1146 /* Display the error locally and exit. */
1147 log("Disconnecting: %.100s", buf);
1151 /* Checks if there is any buffered output, and tries to write some of the output. */
1156 int len = buffer_len(&output);
1158 len = write(connection_out, buffer_ptr(&output), len);
1160 if (errno == EAGAIN)
1163 fatal("Write failed: %.100s", strerror(errno));
1165 buffer_consume(&output, len);
1170 * Calls packet_write_poll repeatedly until all pending output data has been
1177 packet_write_poll();
1178 while (packet_have_data_to_write()) {
1181 FD_SET(connection_out, &set);
1182 select(connection_out + 1, NULL, &set, NULL, NULL);
1183 packet_write_poll();
1187 /* Returns true if there is buffered data to write to the connection. */
1190 packet_have_data_to_write()
1192 return buffer_len(&output) != 0;
1195 /* Returns true if there is not too much data to write to the connection. */
1198 packet_not_very_much_data_to_write()
1200 if (interactive_mode)
1201 return buffer_len(&output) < 16384;
1203 return buffer_len(&output) < 128 * 1024;
1206 /* Informs that the current session is interactive. Sets IP flags for that. */
1209 packet_set_interactive(int interactive, int keepalives)
1213 /* Record that we are in interactive mode. */
1214 interactive_mode = interactive;
1216 /* Only set socket options if using a socket. */
1217 if (!packet_connection_is_on_socket())
1220 /* Set keepalives if requested. */
1221 if (setsockopt(connection_in, SOL_SOCKET, SO_KEEPALIVE, (void *) &on,
1223 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1226 * IPTOS_LOWDELAY, TCP_NODELAY and IPTOS_THROUGHPUT are IPv4 only
1228 if (!packet_connection_is_ipv4())
1232 * Set IP options for an interactive connection. Use
1233 * IPTOS_LOWDELAY and TCP_NODELAY.
1235 int lowdelay = IPTOS_LOWDELAY;
1236 if (setsockopt(connection_in, IPPROTO_IP, IP_TOS, (void *) &lowdelay,
1237 sizeof(lowdelay)) < 0)
1238 error("setsockopt IPTOS_LOWDELAY: %.100s", strerror(errno));
1239 if (setsockopt(connection_in, IPPROTO_TCP, TCP_NODELAY, (void *) &on,
1241 error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
1244 * Set IP options for a non-interactive connection. Use
1247 int throughput = IPTOS_THROUGHPUT;
1248 if (setsockopt(connection_in, IPPROTO_IP, IP_TOS, (void *) &throughput,
1249 sizeof(throughput)) < 0)
1250 error("setsockopt IPTOS_THROUGHPUT: %.100s", strerror(errno));
1254 /* Returns true if the current connection is interactive. */
1257 packet_is_interactive()
1259 return interactive_mode;
1263 packet_set_maxsize(int s)
1265 static int called = 0;
1267 log("packet_set_maxsize: called twice: old %d new %d",
1268 max_packet_size, s);
1271 if (s < 4 * 1024 || s > 1024 * 1024) {
1272 log("packet_set_maxsize: bad size %d", s);
1275 log("packet_set_maxsize: setting to %d", s);
1276 max_packet_size = s;