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.
23 # include <openssl/bn.h>
24 # include <openssl/dh.h>
25 # include <openssl/hmac.h>
26 #endif /* HAVE_OPENSSL */
30 # include <ssl/hmac.h>
60 * This variable contains the file descriptors used for communicating with
61 * the other side. connection_in is used for reading; connection_out for
62 * writing. These can be the same descriptor, in which case it is assumed to
65 static int connection_in = -1;
66 static int connection_out = -1;
69 * Cipher type. This value is only used to determine whether to pad the
70 * packets with zeroes or random data.
72 static int cipher_type = SSH_CIPHER_NONE;
74 /* Protocol flags for the remote side. */
75 static unsigned int remote_protocol_flags = 0;
77 /* Encryption context for receiving data. This is only used for decryption. */
78 static CipherContext receive_context;
80 /* Encryption context for sending data. This is only used for encryption. */
81 static CipherContext send_context;
83 /* Buffer for raw input data from the socket. */
86 /* Buffer for raw output data going to the socket. */
89 /* Buffer for the partial outgoing packet being constructed. */
90 static Buffer outgoing_packet;
92 /* Buffer for the incoming packet currently being processed. */
93 static Buffer incoming_packet;
95 /* Scratch buffer for packet compression/decompression. */
96 static Buffer compression_buffer;
98 /* Flag indicating whether packet compression/decompression is enabled. */
99 static int packet_compression = 0;
101 /* default maximum packet size */
102 int max_packet_size = 32768;
104 /* Flag indicating whether this module has been initialized. */
105 static int initialized = 0;
107 /* Set to true if the connection is interactive. */
108 static int interactive_mode = 0;
110 /* True if SSH2 packet format is used */
111 int use_ssh2_packet_format = 0;
113 /* Session key information for Encryption and MAC */
117 packet_set_kex(Kex *k)
119 if( k->mac[MODE_IN ].key == NULL ||
120 k->enc[MODE_IN ].key == NULL ||
121 k->enc[MODE_IN ].iv == NULL ||
122 k->mac[MODE_OUT].key == NULL ||
123 k->enc[MODE_OUT].key == NULL ||
124 k->enc[MODE_OUT].iv == NULL)
129 clear_enc_keys(Enc *enc, int len)
131 memset(enc->iv, 0, len);
132 memset(enc->key, 0, len);
139 packet_set_ssh2_format(void)
141 debug("use_ssh2_packet_format");
142 use_ssh2_packet_format = 1;
146 * Sets the descriptors used for communication. Disables encryption until
147 * packet_set_encryption_key is called.
150 packet_set_connection(int fd_in, int fd_out)
152 connection_in = fd_in;
153 connection_out = fd_out;
154 cipher_type = SSH_CIPHER_NONE;
155 cipher_set_key(&send_context, SSH_CIPHER_NONE, (unsigned char *) "", 0);
156 cipher_set_key(&receive_context, SSH_CIPHER_NONE, (unsigned char *) "", 0);
160 buffer_init(&output);
161 buffer_init(&outgoing_packet);
162 buffer_init(&incoming_packet);
164 /* Kludge: arrange the close function to be called from fatal(). */
165 fatal_add_cleanup((void (*) (void *)) packet_close, NULL);
168 /* Returns 1 if remote host is connected via socket, 0 if not. */
171 packet_connection_is_on_socket()
173 struct sockaddr_storage from, to;
174 socklen_t fromlen, tolen;
176 /* filedescriptors in and out are the same, so it's a socket */
177 if (connection_in == connection_out)
179 fromlen = sizeof(from);
180 memset(&from, 0, sizeof(from));
181 if (getpeername(connection_in, (struct sockaddr *)&from, &fromlen) < 0)
184 memset(&to, 0, sizeof(to));
185 if (getpeername(connection_out, (struct sockaddr *)&to, &tolen) < 0)
187 if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
189 if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
194 /* returns 1 if connection is via ipv4 */
197 packet_connection_is_ipv4()
199 struct sockaddr_storage to;
200 socklen_t tolen = sizeof(to);
202 memset(&to, 0, sizeof(to));
203 if (getsockname(connection_out, (struct sockaddr *)&to, &tolen) < 0)
205 if (to.ss_family != AF_INET)
210 /* Sets the connection into non-blocking mode. */
213 packet_set_nonblocking()
215 /* Set the socket into non-blocking mode. */
216 if (fcntl(connection_in, F_SETFL, O_NONBLOCK) < 0)
217 error("fcntl O_NONBLOCK: %.100s", strerror(errno));
219 if (connection_out != connection_in) {
220 if (fcntl(connection_out, F_SETFL, O_NONBLOCK) < 0)
221 error("fcntl O_NONBLOCK: %.100s", strerror(errno));
225 /* Returns the socket used for reading. */
228 packet_get_connection_in()
230 return connection_in;
233 /* Returns the descriptor used for writing. */
236 packet_get_connection_out()
238 return connection_out;
241 /* Closes the connection and clears and frees internal data structures. */
249 if (connection_in == connection_out) {
250 shutdown(connection_out, SHUT_RDWR);
251 close(connection_out);
253 close(connection_in);
254 close(connection_out);
257 buffer_free(&output);
258 buffer_free(&outgoing_packet);
259 buffer_free(&incoming_packet);
260 if (packet_compression) {
261 buffer_free(&compression_buffer);
262 buffer_compress_uninit();
266 /* Sets remote side protocol flags. */
269 packet_set_protocol_flags(unsigned int protocol_flags)
271 remote_protocol_flags = protocol_flags;
272 channel_set_options((protocol_flags & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) != 0);
275 /* Returns the remote protocol flags set earlier by the above function. */
278 packet_get_protocol_flags()
280 return remote_protocol_flags;
284 * Starts packet compression from the next packet on in both directions.
285 * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
288 /*** XXXXX todo: kex means re-init */
290 packet_start_compression(int level)
292 if (packet_compression)
293 fatal("Compression already enabled.");
294 packet_compression = 1;
295 buffer_init(&compression_buffer);
296 buffer_compress_init(level);
300 * Encrypts the given number of bytes, copying from src to dest. bytes is
301 * known to be a multiple of 8.
305 packet_encrypt(CipherContext * cc, void *dest, void *src,
308 cipher_encrypt(cc, dest, src, bytes);
312 * Decrypts the given number of bytes, copying from src to dest. bytes is
313 * known to be a multiple of 8.
317 packet_decrypt(CipherContext * cc, void *dest, void *src,
322 if ((bytes % 8) != 0)
323 fatal("packet_decrypt: bad ciphertext length %d", bytes);
326 * Cryptographic attack detector for ssh - Modifications for packet.c
327 * (C)1998 CORE-SDI, Buenos Aires Argentina Ariel Futoransky(futo@core-sdi.com)
330 if (cc->type == SSH_CIPHER_NONE || compat20) {
333 i = detect_attack(src, bytes, NULL);
335 if (i == DEATTACK_DETECTED)
336 packet_disconnect("crc32 compensation attack: network attack detected");
338 cipher_decrypt(cc, dest, src, bytes);
342 * Causes any further packets to be encrypted using the given key. The same
343 * key is used for both sending and reception. However, both directions are
344 * encrypted independently of each other.
348 packet_set_encryption_key(const unsigned char *key, unsigned int keylen,
352 fatal("keylen too small: %d", keylen);
354 /* All other ciphers use the same key in both directions for now. */
355 cipher_set_key(&receive_context, cipher, key, keylen);
356 cipher_set_key(&send_context, cipher, key, keylen);
359 /* Starts constructing a packet to send. */
362 packet_start1(int type)
366 buffer_clear(&outgoing_packet);
369 buffer_append(&outgoing_packet, buf, 9);
373 packet_start2(int type)
377 buffer_clear(&outgoing_packet);
378 memset(buf, 0, sizeof buf);
379 /* buf[0..3] = payload_len; */
380 /* buf[4] = pad_len; */
381 buf[5] = type & 0xff;
382 buffer_append(&outgoing_packet, buf, sizeof buf);
386 packet_start(int type)
388 DBG(debug("packet_start[%d]",type));
389 if (use_ssh2_packet_format)
395 /* Appends a character to the packet data. */
398 packet_put_char(int value)
401 buffer_append(&outgoing_packet, &ch, 1);
404 /* Appends an integer to the packet data. */
407 packet_put_int(unsigned int value)
409 buffer_put_int(&outgoing_packet, value);
412 /* Appends a string to packet data. */
415 packet_put_string(const char *buf, unsigned int len)
417 buffer_put_string(&outgoing_packet, buf, len);
420 packet_put_cstring(const char *str)
422 buffer_put_string(&outgoing_packet, str, strlen(str));
426 packet_put_raw(const char *buf, unsigned int len)
428 buffer_append(&outgoing_packet, buf, len);
432 /* Appends an arbitrary precision integer to packet data. */
435 packet_put_bignum(BIGNUM * value)
437 buffer_put_bignum(&outgoing_packet, value);
440 packet_put_bignum2(BIGNUM * value)
442 buffer_put_bignum2(&outgoing_packet, value);
446 * Finalizes and sends the packet. If the encryption key has been set,
447 * encrypts the packet before sending.
455 unsigned int checksum;
459 * If using packet compression, compress the payload of the outgoing
462 if (packet_compression) {
463 buffer_clear(&compression_buffer);
465 buffer_consume(&outgoing_packet, 8);
467 buffer_append(&compression_buffer, "\0\0\0\0\0\0\0\0", 8);
468 buffer_compress(&outgoing_packet, &compression_buffer);
469 buffer_clear(&outgoing_packet);
470 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
471 buffer_len(&compression_buffer));
473 /* Compute packet length without padding (add checksum, remove padding). */
474 len = buffer_len(&outgoing_packet) + 4 - 8;
476 /* Insert padding. */
477 padding = 8 - len % 8;
478 if (cipher_type != SSH_CIPHER_NONE) {
479 cp = buffer_ptr(&outgoing_packet);
480 for (i = 0; i < padding; i++) {
483 cp[7 - i] = rand & 0xff;
487 buffer_consume(&outgoing_packet, 8 - padding);
489 /* Add check bytes. */
490 checksum = crc32((unsigned char *) buffer_ptr(&outgoing_packet),
491 buffer_len(&outgoing_packet));
492 PUT_32BIT(buf, checksum);
493 buffer_append(&outgoing_packet, buf, 4);
496 fprintf(stderr, "packet_send plain: ");
497 buffer_dump(&outgoing_packet);
500 /* Append to output. */
502 buffer_append(&output, buf, 4);
503 buffer_append_space(&output, &cp, buffer_len(&outgoing_packet));
504 packet_encrypt(&send_context, cp, buffer_ptr(&outgoing_packet),
505 buffer_len(&outgoing_packet));
508 fprintf(stderr, "encrypted: ");
509 buffer_dump(&output);
512 buffer_clear(&outgoing_packet);
515 * Note that the packet is now only buffered in output. It won\'t be
516 * actually sent until packet_write_wait or packet_write_poll is
522 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
527 unsigned char *macbuf = NULL;
529 unsigned int packet_length = 0;
530 unsigned int i, padlen, len;
532 static unsigned int seqnr = 0;
540 enc = &kex->enc[MODE_OUT];
541 mac = &kex->mac[MODE_OUT];
542 comp = &kex->comp[MODE_OUT];
544 block_size = enc ? enc->block_size : 8;
546 cp = buffer_ptr(&outgoing_packet);
550 fprintf(stderr, "plain: ");
551 buffer_dump(&outgoing_packet);
554 if (comp && comp->enabled) {
555 len = buffer_len(&outgoing_packet);
556 /* skip header, compress only payload */
557 buffer_consume(&outgoing_packet, 5);
558 buffer_clear(&compression_buffer);
559 buffer_compress(&outgoing_packet, &compression_buffer);
560 buffer_clear(&outgoing_packet);
561 buffer_append(&outgoing_packet, "\0\0\0\0\0", 5);
562 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
563 buffer_len(&compression_buffer));
564 DBG(debug("compression: raw %d compressed %d", len,
565 buffer_len(&outgoing_packet)));
568 /* sizeof (packet_len + pad_len + payload) */
569 len = buffer_len(&outgoing_packet);
572 * calc size of padding, alloc space, get random data,
573 * minimum padding is 4 bytes
575 padlen = block_size - (len % block_size);
577 padlen += block_size;
578 buffer_append_space(&outgoing_packet, &cp, padlen);
579 if (enc && enc->type != SSH_CIPHER_NONE) {
580 for (i = 0; i < padlen; i++) {
587 /* packet_length includes payload, padding and padding length field */
588 packet_length = buffer_len(&outgoing_packet) - 4;
589 cp = buffer_ptr(&outgoing_packet);
590 PUT_32BIT(cp, packet_length);
591 cp[4] = padlen & 0xff;
592 DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen));
594 /* compute MAC over seqnr and packet(length fields, payload, padding) */
595 if (mac && mac->enabled) {
596 macbuf = hmac( mac->md, seqnr,
597 (unsigned char *) buffer_ptr(&outgoing_packet),
598 buffer_len(&outgoing_packet),
599 mac->key, mac->key_len
601 DBG(debug("done calc HMAC out #%d", seqnr));
603 /* encrypt packet and append to output buffer. */
604 buffer_append_space(&output, &cp, buffer_len(&outgoing_packet));
605 packet_encrypt(&send_context, cp, buffer_ptr(&outgoing_packet),
606 buffer_len(&outgoing_packet));
607 /* append unencrypted MAC */
608 if (mac && mac->enabled)
609 buffer_append(&output, (char *)macbuf, mac->mac_len);
611 fprintf(stderr, "encrypted: ");
612 buffer_dump(&output);
614 /* increment sequence number for outgoing packets */
616 log("outgoing seqnr wraps around");
617 buffer_clear(&outgoing_packet);
619 if (type == SSH2_MSG_NEWKEYS) {
620 if (kex==NULL || mac==NULL || enc==NULL || comp==NULL)
621 fatal("packet_send2: no KEX");
624 debug("cipher_set_key_iv send_context");
625 cipher_set_key_iv(&send_context, enc->type,
626 enc->key, enc->key_len,
627 enc->iv, enc->iv_len);
628 clear_enc_keys(enc, kex->we_need);
629 if (comp->type != 0 && comp->enabled == 0) {
631 if (! packet_compression)
632 packet_start_compression(6);
640 if (use_ssh2_packet_format)
644 DBG(debug("packet_send done"));
648 packet_send_and_wait()
655 * Waits until a packet has been received, and returns its type. Note that
656 * no other data is processed until this returns, so this function should not
657 * be used during the interactive session.
661 packet_read(int *payload_len_ptr)
666 DBG(debug("packet_read()"));
668 /* Since we are blocking, ensure that all written packets have been sent. */
671 /* Stay in the loop until we have received a complete packet. */
673 /* Try to read a packet from the buffer. */
674 type = packet_read_poll(payload_len_ptr);
675 if (type == SSH_SMSG_SUCCESS
676 || type == SSH_SMSG_FAILURE
677 || type == SSH_CMSG_EOF
678 || type == SSH_CMSG_EXIT_CONFIRMATION)
679 packet_integrity_check(*payload_len_ptr, 0, type);
680 /* If we got a packet, return it. */
681 if (type != SSH_MSG_NONE)
684 * Otherwise, wait for some data to arrive, add it to the
685 * buffer, and try again.
688 FD_SET(connection_in, &set);
690 /* Wait for some data to arrive. */
691 select(connection_in + 1, &set, NULL, NULL, NULL);
693 /* Read data from the socket. */
694 len = read(connection_in, buf, sizeof(buf));
696 log("Connection closed by %.200s", get_remote_ipaddr());
700 fatal("Read from socket failed: %.100s", strerror(errno));
701 /* Append it to the buffer. */
702 packet_process_incoming(buf, len);
708 * Waits until a packet has been received, verifies that its type matches
709 * that given, and gives a fatal error and exits if there is a mismatch.
713 packet_read_expect(int *payload_len_ptr, int expected_type)
717 type = packet_read(payload_len_ptr);
718 if (type != expected_type)
719 packet_disconnect("Protocol error: expected packet type %d, got %d",
720 expected_type, type);
723 /* Checks if a full packet is available in the data received so far via
724 * packet_process_incoming. If so, reads the packet; otherwise returns
725 * SSH_MSG_NONE. This does not wait for data from the connection.
727 * SSH_MSG_DISCONNECT is handled specially here. Also,
728 * SSH_MSG_IGNORE messages are skipped by this function and are never returned
731 * The returned payload_len does include space consumed by:
739 packet_read_poll1(int *payload_len_ptr)
741 unsigned int len, padded_len;
744 unsigned int checksum, stored_checksum;
746 /* Check if input size is less than minimum packet size. */
747 if (buffer_len(&input) < 4 + 8)
749 /* Get length of incoming packet. */
750 ucp = (unsigned char *) buffer_ptr(&input);
751 len = GET_32BIT(ucp);
752 if (len < 1 + 2 + 2 || len > 256 * 1024)
753 packet_disconnect("Bad packet length %d.", len);
754 padded_len = (len + 8) & ~7;
756 /* Check if the packet has been entirely received. */
757 if (buffer_len(&input) < 4 + padded_len)
760 /* The entire packet is in buffer. */
762 /* Consume packet length. */
763 buffer_consume(&input, 4);
765 /* Copy data to incoming_packet. */
766 buffer_clear(&incoming_packet);
767 buffer_append_space(&incoming_packet, &cp, padded_len);
768 packet_decrypt(&receive_context, cp, buffer_ptr(&input), padded_len);
769 buffer_consume(&input, padded_len);
772 fprintf(stderr, "read_poll plain: ");
773 buffer_dump(&incoming_packet);
776 /* Compute packet checksum. */
777 checksum = crc32((unsigned char *) buffer_ptr(&incoming_packet),
778 buffer_len(&incoming_packet) - 4);
781 buffer_consume(&incoming_packet, 8 - len % 8);
783 /* Test check bytes. */
785 if (len != buffer_len(&incoming_packet))
786 packet_disconnect("packet_read_poll: len %d != buffer_len %d.",
787 len, buffer_len(&incoming_packet));
789 ucp = (unsigned char *) buffer_ptr(&incoming_packet) + len - 4;
790 stored_checksum = GET_32BIT(ucp);
791 if (checksum != stored_checksum)
792 packet_disconnect("Corrupted check bytes on input.");
793 buffer_consume_end(&incoming_packet, 4);
795 /* If using packet compression, decompress the packet. */
796 if (packet_compression) {
797 buffer_clear(&compression_buffer);
798 buffer_uncompress(&incoming_packet, &compression_buffer);
799 buffer_clear(&incoming_packet);
800 buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
801 buffer_len(&compression_buffer));
803 /* Get packet type. */
804 buffer_get(&incoming_packet, &buf[0], 1);
806 /* Return length of payload (without type field). */
807 *payload_len_ptr = buffer_len(&incoming_packet);
810 return (unsigned char) buf[0];
814 packet_read_poll2(int *payload_len_ptr)
816 unsigned int padlen, need;
817 unsigned char buf[8], *macbuf;
820 static unsigned int packet_length = 0;
821 static unsigned int seqnr = 0;
823 int maclen, block_size;
829 enc = &kex->enc[MODE_IN];
830 mac = &kex->mac[MODE_IN];
831 comp = &kex->comp[MODE_IN];
833 maclen = mac && mac->enabled ? mac->mac_len : 0;
834 block_size = enc ? enc->block_size : 8;
836 if (packet_length == 0) {
838 * check if input size is less than the cipher block size,
839 * decrypt first block and extract length of incoming packet
841 if (buffer_len(&input) < block_size)
843 buffer_clear(&incoming_packet);
844 buffer_append_space(&incoming_packet, &cp, block_size);
845 packet_decrypt(&receive_context, cp, buffer_ptr(&input),
847 ucp = (unsigned char *) buffer_ptr(&incoming_packet);
848 packet_length = GET_32BIT(ucp);
849 if (packet_length < 1 + 4 || packet_length > 256 * 1024) {
850 buffer_dump(&incoming_packet);
851 packet_disconnect("Bad packet length %d.", packet_length);
853 DBG(debug("input: packet len %d", packet_length+4));
854 buffer_consume(&input, block_size);
856 /* we have a partial packet of block_size bytes */
857 need = 4 + packet_length - block_size;
858 DBG(debug("partial packet %d, need %d, maclen %d", block_size,
860 if (need % block_size != 0)
861 fatal("padding error: need %d block %d mod %d",
862 need, block_size, need % block_size);
864 * check if the entire packet has been received and
865 * decrypt into incoming_packet
867 if (buffer_len(&input) < need + maclen)
870 fprintf(stderr, "read_poll enc/full: ");
873 buffer_append_space(&incoming_packet, &cp, need);
874 packet_decrypt(&receive_context, cp, buffer_ptr(&input), need);
875 buffer_consume(&input, need);
877 * compute MAC over seqnr and packet,
878 * increment sequence number for incoming packet
880 if (mac && mac->enabled) {
881 macbuf = hmac( mac->md, seqnr,
882 (unsigned char *) buffer_ptr(&incoming_packet),
883 buffer_len(&incoming_packet),
884 mac->key, mac->key_len
886 if (memcmp(macbuf, buffer_ptr(&input), mac->mac_len) != 0)
887 packet_disconnect("Corrupted HMAC on input.");
888 DBG(debug("HMAC #%d ok", seqnr));
889 buffer_consume(&input, mac->mac_len);
892 log("incoming seqnr wraps around");
895 cp = buffer_ptr(&incoming_packet) + 4;
897 DBG(debug("input: padlen %d", padlen));
899 packet_disconnect("Corrupted padlen %d on input.", padlen);
901 /* skip packet size + padlen, discard padding */
902 buffer_consume(&incoming_packet, 4 + 1);
903 buffer_consume_end(&incoming_packet, padlen);
905 DBG(debug("input: len before de-compress %d", buffer_len(&incoming_packet)));
906 if (comp && comp->enabled) {
907 buffer_clear(&compression_buffer);
908 buffer_uncompress(&incoming_packet, &compression_buffer);
909 buffer_clear(&incoming_packet);
910 buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
911 buffer_len(&compression_buffer));
912 DBG(debug("input: len after de-compress %d", buffer_len(&incoming_packet)));
915 * get packet type, implies consume.
916 * return length of payload (without type field)
918 buffer_get(&incoming_packet, (char *)&buf[0], 1);
919 *payload_len_ptr = buffer_len(&incoming_packet);
921 /* reset for next packet */
924 /* extract packet type */
925 type = (unsigned char)buf[0];
927 if (type == SSH2_MSG_NEWKEYS) {
928 if (kex==NULL || mac==NULL || enc==NULL || comp==NULL)
929 fatal("packet_read_poll2: no KEX");
932 debug("cipher_set_key_iv receive_context");
933 cipher_set_key_iv(&receive_context, enc->type,
934 enc->key, enc->key_len,
935 enc->iv, enc->iv_len);
936 clear_enc_keys(enc, kex->we_need);
937 if (comp->type != 0 && comp->enabled == 0) {
939 if (! packet_compression)
940 packet_start_compression(6);
945 fprintf(stderr, "read/plain[%d]:\r\n",type);
946 buffer_dump(&incoming_packet);
948 return (unsigned char)type;
952 packet_read_poll(int *payload_len_ptr)
956 int type = use_ssh2_packet_format ?
957 packet_read_poll2(payload_len_ptr):
958 packet_read_poll1(payload_len_ptr);
963 DBG(debug("received packet type %d", type));
965 case SSH2_MSG_IGNORE:
969 msg = packet_get_string(NULL);
970 debug("Remote: %.900s", msg);
972 msg = packet_get_string(NULL);
975 case SSH2_MSG_DISCONNECT:
976 reason = packet_get_int();
977 msg = packet_get_string(NULL);
978 log("Received disconnect: %d: %.900s", reason, msg);
991 msg = packet_get_string(NULL);
992 debug("Remote: %.900s", msg);
995 case SSH_MSG_DISCONNECT:
996 msg = packet_get_string(NULL);
997 log("Received disconnect: %.900s", msg);
1003 DBG(debug("received packet type %d", type));
1012 * Buffers the given amount of input characters. This is intended to be used
1013 * together with packet_read_poll.
1017 packet_process_incoming(const char *buf, unsigned int len)
1019 buffer_append(&input, buf, len);
1022 /* Returns a character from the packet. */
1028 buffer_get(&incoming_packet, &ch, 1);
1029 return (unsigned char) ch;
1032 /* Returns an integer from the packet data. */
1037 return buffer_get_int(&incoming_packet);
1041 * Returns an arbitrary precision integer from the packet data. The integer
1042 * must have been initialized before this call.
1046 packet_get_bignum(BIGNUM * value, int *length_ptr)
1048 *length_ptr = buffer_get_bignum(&incoming_packet, value);
1052 packet_get_bignum2(BIGNUM * value, int *length_ptr)
1054 *length_ptr = buffer_get_bignum2(&incoming_packet, value);
1058 packet_get_raw(int *length_ptr)
1060 int bytes = buffer_len(&incoming_packet);
1061 if (length_ptr != NULL)
1062 *length_ptr = bytes;
1063 return buffer_ptr(&incoming_packet);
1067 * Returns a string from the packet data. The string is allocated using
1068 * xmalloc; it is the responsibility of the calling program to free it when
1069 * no longer needed. The length_ptr argument may be NULL, or point to an
1070 * integer into which the length of the string is stored.
1074 packet_get_string(unsigned int *length_ptr)
1076 return buffer_get_string(&incoming_packet, length_ptr);
1080 * Sends a diagnostic message from the server to the client. This message
1081 * can be sent at any time (but not while constructing another message). The
1082 * message is printed immediately, but only if the client is being executed
1083 * in verbose mode. These messages are primarily intended to ease debugging
1084 * authentication problems. The length of the formatted message must not
1085 * exceed 1024 bytes. This will automatically call packet_write_wait.
1089 packet_send_debug(const char *fmt,...)
1094 va_start(args, fmt);
1095 vsnprintf(buf, sizeof(buf), fmt, args);
1098 packet_start(SSH_MSG_DEBUG);
1099 packet_put_string(buf, strlen(buf));
1101 packet_write_wait();
1105 * Logs the error plus constructs and sends a disconnect packet, closes the
1106 * connection, and exits. This function never returns. The error message
1107 * should not contain a newline. The length of the formatted message must
1108 * not exceed 1024 bytes.
1112 packet_disconnect(const char *fmt,...)
1116 static int disconnecting = 0;
1117 if (disconnecting) /* Guard against recursive invocations. */
1118 fatal("packet_disconnect called recursively.");
1122 * Format the message. Note that the caller must make sure the
1123 * message is of limited size.
1125 va_start(args, fmt);
1126 vsnprintf(buf, sizeof(buf), fmt, args);
1129 /* Send the disconnect message to the other side, and wait for it to get sent. */
1131 packet_start(SSH2_MSG_DISCONNECT);
1132 packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1133 packet_put_cstring(buf);
1134 packet_put_cstring("");
1136 packet_start(SSH_MSG_DISCONNECT);
1137 packet_put_string(buf, strlen(buf));
1140 packet_write_wait();
1142 /* Stop listening for connections. */
1143 channel_stop_listening();
1145 /* Close the connection. */
1148 /* Display the error locally and exit. */
1149 log("Disconnecting: %.100s", buf);
1153 /* Checks if there is any buffered output, and tries to write some of the output. */
1158 int len = buffer_len(&output);
1160 len = write(connection_out, buffer_ptr(&output), len);
1162 if (errno == EAGAIN)
1165 fatal("Write failed: %.100s", strerror(errno));
1167 buffer_consume(&output, len);
1172 * Calls packet_write_poll repeatedly until all pending output data has been
1179 packet_write_poll();
1180 while (packet_have_data_to_write()) {
1183 FD_SET(connection_out, &set);
1184 select(connection_out + 1, NULL, &set, NULL, NULL);
1185 packet_write_poll();
1189 /* Returns true if there is buffered data to write to the connection. */
1192 packet_have_data_to_write()
1194 return buffer_len(&output) != 0;
1197 /* Returns true if there is not too much data to write to the connection. */
1200 packet_not_very_much_data_to_write()
1202 if (interactive_mode)
1203 return buffer_len(&output) < 16384;
1205 return buffer_len(&output) < 128 * 1024;
1208 /* Informs that the current session is interactive. Sets IP flags for that. */
1211 packet_set_interactive(int interactive, int keepalives)
1215 /* Record that we are in interactive mode. */
1216 interactive_mode = interactive;
1218 /* Only set socket options if using a socket. */
1219 if (!packet_connection_is_on_socket())
1222 /* Set keepalives if requested. */
1223 if (setsockopt(connection_in, SOL_SOCKET, SO_KEEPALIVE, (void *) &on,
1225 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1228 * IPTOS_LOWDELAY, TCP_NODELAY and IPTOS_THROUGHPUT are IPv4 only
1230 if (!packet_connection_is_ipv4())
1234 * Set IP options for an interactive connection. Use
1235 * IPTOS_LOWDELAY and TCP_NODELAY.
1237 int lowdelay = IPTOS_LOWDELAY;
1238 if (setsockopt(connection_in, IPPROTO_IP, IP_TOS, (void *) &lowdelay,
1239 sizeof(lowdelay)) < 0)
1240 error("setsockopt IPTOS_LOWDELAY: %.100s", strerror(errno));
1241 if (setsockopt(connection_in, IPPROTO_TCP, TCP_NODELAY, (void *) &on,
1243 error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
1246 * Set IP options for a non-interactive connection. Use
1249 int throughput = IPTOS_THROUGHPUT;
1250 if (setsockopt(connection_in, IPPROTO_IP, IP_TOS, (void *) &throughput,
1251 sizeof(throughput)) < 0)
1252 error("setsockopt IPTOS_THROUGHPUT: %.100s", strerror(errno));
1256 /* Returns true if the current connection is interactive. */
1259 packet_is_interactive()
1261 return interactive_mode;
1265 packet_set_maxsize(int s)
1267 static int called = 0;
1269 log("packet_set_maxsize: called twice: old %d new %d",
1270 max_packet_size, s);
1273 if (s < 4 * 1024 || s > 1024 * 1024) {
1274 log("packet_set_maxsize: bad size %d", s);
1277 log("packet_set_maxsize: setting to %d", s);
1278 max_packet_size = s;