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.80 2001/12/28 13:57:33 markus Exp $");
70 * This variable contains the file descriptors used for communicating with
71 * the other side. connection_in is used for reading; connection_out for
72 * writing. These can be the same descriptor, in which case it is assumed to
75 static int connection_in = -1;
76 static int connection_out = -1;
78 /* Protocol flags for the remote side. */
79 static u_int remote_protocol_flags = 0;
81 /* Encryption context for receiving data. This is only used for decryption. */
82 static CipherContext receive_context;
84 /* Encryption context for sending data. This is only used for encryption. */
85 static CipherContext send_context;
87 /* Buffer for raw input data from the socket. */
90 /* Buffer for raw output data going to the socket. */
93 /* Buffer for the partial outgoing packet being constructed. */
94 static Buffer outgoing_packet;
96 /* Buffer for the incoming packet currently being processed. */
97 static Buffer incoming_packet;
99 /* Scratch buffer for packet compression/decompression. */
100 static Buffer compression_buffer;
101 static int compression_buffer_ready = 0;
103 /* Flag indicating whether packet compression/decompression is enabled. */
104 static int packet_compression = 0;
106 /* default maximum packet size */
107 int max_packet_size = 32768;
109 /* Flag indicating whether this module has been initialized. */
110 static int initialized = 0;
112 /* Set to true if the connection is interactive. */
113 static int interactive_mode = 0;
115 /* Session key information for Encryption and MAC */
116 Newkeys *newkeys[MODE_MAX];
118 /* roundup current message to extra_pad bytes */
119 static u_char extra_pad = 0;
122 * Sets the descriptors used for communication. Disables encryption until
123 * packet_set_encryption_key is called.
126 packet_set_connection(int fd_in, int fd_out)
128 Cipher *none = cipher_by_name("none");
130 fatal("packet_set_connection: cannot load cipher 'none'");
131 connection_in = fd_in;
132 connection_out = fd_out;
133 cipher_init(&send_context, none, (u_char *) "", 0, NULL, 0);
134 cipher_init(&receive_context, none, (u_char *) "", 0, NULL, 0);
135 newkeys[MODE_IN] = newkeys[MODE_OUT] = NULL;
139 buffer_init(&output);
140 buffer_init(&outgoing_packet);
141 buffer_init(&incoming_packet);
143 /* Kludge: arrange the close function to be called from fatal(). */
144 fatal_add_cleanup((void (*) (void *)) packet_close, NULL);
147 /* Returns 1 if remote host is connected via socket, 0 if not. */
150 packet_connection_is_on_socket(void)
152 struct sockaddr_storage from, to;
153 socklen_t fromlen, tolen;
155 /* filedescriptors in and out are the same, so it's a socket */
156 if (connection_in == connection_out)
158 fromlen = sizeof(from);
159 memset(&from, 0, sizeof(from));
160 if (getpeername(connection_in, (struct sockaddr *)&from, &fromlen) < 0)
163 memset(&to, 0, sizeof(to));
164 if (getpeername(connection_out, (struct sockaddr *)&to, &tolen) < 0)
166 if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
168 if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
173 /* returns 1 if connection is via ipv4 */
176 packet_connection_is_ipv4(void)
178 struct sockaddr_storage to;
179 socklen_t tolen = sizeof(to);
181 memset(&to, 0, sizeof(to));
182 if (getsockname(connection_out, (struct sockaddr *)&to, &tolen) < 0)
184 if (to.ss_family != AF_INET)
189 /* Sets the connection into non-blocking mode. */
192 packet_set_nonblocking(void)
194 /* Set the socket into non-blocking mode. */
195 if (fcntl(connection_in, F_SETFL, O_NONBLOCK) < 0)
196 error("fcntl O_NONBLOCK: %.100s", strerror(errno));
198 if (connection_out != connection_in) {
199 if (fcntl(connection_out, F_SETFL, O_NONBLOCK) < 0)
200 error("fcntl O_NONBLOCK: %.100s", strerror(errno));
204 /* Returns the socket used for reading. */
207 packet_get_connection_in(void)
209 return connection_in;
212 /* Returns the descriptor used for writing. */
215 packet_get_connection_out(void)
217 return connection_out;
220 /* Closes the connection and clears and frees internal data structures. */
228 if (connection_in == connection_out) {
229 shutdown(connection_out, SHUT_RDWR);
230 close(connection_out);
232 close(connection_in);
233 close(connection_out);
236 buffer_free(&output);
237 buffer_free(&outgoing_packet);
238 buffer_free(&incoming_packet);
239 if (compression_buffer_ready) {
240 buffer_free(&compression_buffer);
241 buffer_compress_uninit();
245 /* Sets remote side protocol flags. */
248 packet_set_protocol_flags(u_int protocol_flags)
250 remote_protocol_flags = protocol_flags;
253 /* Returns the remote protocol flags set earlier by the above function. */
256 packet_get_protocol_flags(void)
258 return remote_protocol_flags;
262 * Starts packet compression from the next packet on in both directions.
263 * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
267 packet_init_compression(void)
269 if (compression_buffer_ready == 1)
271 compression_buffer_ready = 1;
272 buffer_init(&compression_buffer);
276 packet_start_compression(int level)
278 if (packet_compression && !compat20)
279 fatal("Compression already enabled.");
280 packet_compression = 1;
281 packet_init_compression();
282 buffer_compress_init_send(level);
283 buffer_compress_init_recv();
287 * Causes any further packets to be encrypted using the given key. The same
288 * key is used for both sending and reception. However, both directions are
289 * encrypted independently of each other.
292 packet_set_encryption_key(const u_char *key, u_int keylen,
295 Cipher *cipher = cipher_by_number(number);
297 fatal("packet_set_encryption_key: unknown cipher number %d", number);
299 fatal("packet_set_encryption_key: keylen too small: %d", keylen);
300 cipher_init(&receive_context, cipher, key, keylen, NULL, 0);
301 cipher_init(&send_context, cipher, key, keylen, NULL, 0);
304 /* Start constructing a packet to send. */
306 packet_start(u_char type)
311 DBG(debug("packet_start[%d]", type));
312 len = compat20 ? 6 : 9;
313 memset(buf, 0, len - 1);
315 buffer_clear(&outgoing_packet);
316 buffer_append(&outgoing_packet, buf, len);
319 /* Append payload. */
321 packet_put_char(int value)
324 buffer_append(&outgoing_packet, &ch, 1);
327 packet_put_int(u_int value)
329 buffer_put_int(&outgoing_packet, value);
332 packet_put_string(const void *buf, u_int len)
334 buffer_put_string(&outgoing_packet, buf, len);
337 packet_put_cstring(const char *str)
339 buffer_put_cstring(&outgoing_packet, str);
342 packet_put_raw(const void *buf, u_int len)
344 buffer_append(&outgoing_packet, buf, len);
347 packet_put_bignum(BIGNUM * value)
349 buffer_put_bignum(&outgoing_packet, value);
352 packet_put_bignum2(BIGNUM * value)
354 buffer_put_bignum2(&outgoing_packet, value);
358 * Finalizes and sends the packet. If the encryption key has been set,
359 * encrypts the packet before sending.
371 * If using packet compression, compress the payload of the outgoing
374 if (packet_compression) {
375 buffer_clear(&compression_buffer);
377 buffer_consume(&outgoing_packet, 8);
379 buffer_append(&compression_buffer, "\0\0\0\0\0\0\0\0", 8);
380 buffer_compress(&outgoing_packet, &compression_buffer);
381 buffer_clear(&outgoing_packet);
382 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
383 buffer_len(&compression_buffer));
385 /* Compute packet length without padding (add checksum, remove padding). */
386 len = buffer_len(&outgoing_packet) + 4 - 8;
388 /* Insert padding. Initialized to zero in packet_start1() */
389 padding = 8 - len % 8;
390 if (send_context.cipher->number != SSH_CIPHER_NONE) {
391 cp = buffer_ptr(&outgoing_packet);
392 for (i = 0; i < padding; i++) {
395 cp[7 - i] = rand & 0xff;
399 buffer_consume(&outgoing_packet, 8 - padding);
401 /* Add check bytes. */
402 checksum = ssh_crc32((u_char *) buffer_ptr(&outgoing_packet),
403 buffer_len(&outgoing_packet));
404 PUT_32BIT(buf, checksum);
405 buffer_append(&outgoing_packet, buf, 4);
408 fprintf(stderr, "packet_send plain: ");
409 buffer_dump(&outgoing_packet);
412 /* Append to output. */
414 buffer_append(&output, buf, 4);
415 cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
416 cipher_encrypt(&send_context, cp, buffer_ptr(&outgoing_packet),
417 buffer_len(&outgoing_packet));
420 fprintf(stderr, "encrypted: ");
421 buffer_dump(&output);
424 buffer_clear(&outgoing_packet);
427 * Note that the packet is now only buffered in output. It won\'t be
428 * actually sent until packet_write_wait or packet_write_poll is
434 set_newkeys(int mode)
441 debug("newkeys: mode %d", mode);
443 cc = (mode == MODE_OUT) ? &send_context : &receive_context;
444 if (newkeys[mode] != NULL) {
445 debug("newkeys: rekeying");
446 /* todo: free old keys, reset compression/cipher-ctxt; */
447 memset(cc, 0, sizeof(*cc));
448 enc = &newkeys[mode]->enc;
449 mac = &newkeys[mode]->mac;
450 comp = &newkeys[mode]->comp;
451 memset(mac->key, 0, mac->key_len);
458 xfree(newkeys[mode]);
460 newkeys[mode] = kex_get_newkeys(mode);
461 if (newkeys[mode] == NULL)
462 fatal("newkeys: no keys for mode %d", mode);
463 enc = &newkeys[mode]->enc;
464 mac = &newkeys[mode]->mac;
465 comp = &newkeys[mode]->comp;
468 DBG(debug("cipher_init_context: %d", mode));
469 cipher_init(cc, enc->cipher, enc->key, enc->cipher->key_len,
470 enc->iv, enc->cipher->block_size);
471 memset(enc->iv, 0, enc->cipher->block_size);
472 memset(enc->key, 0, enc->cipher->key_len);
473 if (comp->type != 0 && comp->enabled == 0) {
474 packet_init_compression();
475 if (mode == MODE_OUT)
476 buffer_compress_init_send(6);
478 buffer_compress_init_recv();
484 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
489 static u_int32_t seqnr = 0;
490 u_char type, *ucp, *macbuf = NULL;
493 u_int packet_length = 0;
501 if (newkeys[MODE_OUT] != NULL) {
502 enc = &newkeys[MODE_OUT]->enc;
503 mac = &newkeys[MODE_OUT]->mac;
504 comp = &newkeys[MODE_OUT]->comp;
506 block_size = enc ? enc->cipher->block_size : 8;
508 ucp = (u_char *) buffer_ptr(&outgoing_packet);
512 fprintf(stderr, "plain: ");
513 buffer_dump(&outgoing_packet);
516 if (comp && comp->enabled) {
517 len = buffer_len(&outgoing_packet);
518 /* skip header, compress only payload */
519 buffer_consume(&outgoing_packet, 5);
520 buffer_clear(&compression_buffer);
521 buffer_compress(&outgoing_packet, &compression_buffer);
522 buffer_clear(&outgoing_packet);
523 buffer_append(&outgoing_packet, "\0\0\0\0\0", 5);
524 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
525 buffer_len(&compression_buffer));
526 DBG(debug("compression: raw %d compressed %d", len,
527 buffer_len(&outgoing_packet)));
530 /* sizeof (packet_len + pad_len + payload) */
531 len = buffer_len(&outgoing_packet);
534 * calc size of padding, alloc space, get random data,
535 * minimum padding is 4 bytes
537 padlen = block_size - (len % block_size);
539 padlen += block_size;
541 /* will wrap if extra_pad+padlen > 255 */
542 extra_pad = roundup(extra_pad, block_size);
543 pad = extra_pad - ((len + padlen) % extra_pad);
544 debug("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
545 pad, len, padlen, extra_pad);
549 cp = buffer_append_space(&outgoing_packet, padlen);
550 if (enc && enc->cipher->number != SSH_CIPHER_NONE) {
552 for (i = 0; i < padlen; i++) {
560 memset(cp, 0, padlen);
562 /* packet_length includes payload, padding and padding length field */
563 packet_length = buffer_len(&outgoing_packet) - 4;
564 ucp = (u_char *)buffer_ptr(&outgoing_packet);
565 PUT_32BIT(ucp, packet_length);
567 DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen));
569 /* compute MAC over seqnr and packet(length fields, payload, padding) */
570 if (mac && mac->enabled) {
571 macbuf = mac_compute(mac, seqnr,
572 (u_char *) buffer_ptr(&outgoing_packet),
573 buffer_len(&outgoing_packet));
574 DBG(debug("done calc MAC out #%d", seqnr));
576 /* encrypt packet and append to output buffer. */
577 cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
578 cipher_encrypt(&send_context, cp, buffer_ptr(&outgoing_packet),
579 buffer_len(&outgoing_packet));
580 /* append unencrypted MAC */
581 if (mac && mac->enabled)
582 buffer_append(&output, (char *)macbuf, mac->mac_len);
584 fprintf(stderr, "encrypted: ");
585 buffer_dump(&output);
587 /* increment sequence number for outgoing packets */
589 log("outgoing seqnr wraps around");
590 buffer_clear(&outgoing_packet);
592 if (type == SSH2_MSG_NEWKEYS)
593 set_newkeys(MODE_OUT);
603 DBG(debug("packet_send done"));
607 * Waits until a packet has been received, and returns its type. Note that
608 * no other data is processed until this returns, so this function should not
609 * be used during the interactive session.
613 packet_read_seqnr(int *payload_len_ptr, u_int32_t *seqnr_p)
618 DBG(debug("packet_read()"));
620 setp = (fd_set *)xmalloc(howmany(connection_in+1, NFDBITS) *
623 /* Since we are blocking, ensure that all written packets have been sent. */
626 /* Stay in the loop until we have received a complete packet. */
628 /* Try to read a packet from the buffer. */
629 type = packet_read_poll_seqnr(payload_len_ptr, seqnr_p);
631 type == SSH_SMSG_SUCCESS
632 || type == SSH_SMSG_FAILURE
633 || type == SSH_CMSG_EOF
634 || type == SSH_CMSG_EXIT_CONFIRMATION))
636 /* If we got a packet, return it. */
637 if (type != SSH_MSG_NONE) {
642 * Otherwise, wait for some data to arrive, add it to the
643 * buffer, and try again.
645 memset(setp, 0, howmany(connection_in + 1, NFDBITS) *
647 FD_SET(connection_in, setp);
649 /* Wait for some data to arrive. */
650 while (select(connection_in + 1, setp, NULL, NULL, NULL) == -1 &&
651 (errno == EAGAIN || errno == EINTR))
654 /* Read data from the socket. */
655 len = read(connection_in, buf, sizeof(buf));
657 log("Connection closed by %.200s", get_remote_ipaddr());
661 fatal("Read from socket failed: %.100s", strerror(errno));
662 /* Append it to the buffer. */
663 packet_process_incoming(buf, len);
669 packet_read(int *payload_len_ptr)
671 return packet_read_seqnr(payload_len_ptr, NULL);
675 * Waits until a packet has been received, verifies that its type matches
676 * that given, and gives a fatal error and exits if there is a mismatch.
680 packet_read_expect(int *payload_len_ptr, int expected_type)
684 type = packet_read(payload_len_ptr);
685 if (type != expected_type)
686 packet_disconnect("Protocol error: expected packet type %d, got %d",
687 expected_type, type);
690 /* Checks if a full packet is available in the data received so far via
691 * packet_process_incoming. If so, reads the packet; otherwise returns
692 * SSH_MSG_NONE. This does not wait for data from the connection.
694 * SSH_MSG_DISCONNECT is handled specially here. Also,
695 * SSH_MSG_IGNORE messages are skipped by this function and are never returned
698 * The returned payload_len does include space consumed by:
706 packet_read_poll1(int *payload_len_ptr)
708 u_int len, padded_len;
711 u_int checksum, stored_checksum;
713 /* Check if input size is less than minimum packet size. */
714 if (buffer_len(&input) < 4 + 8)
716 /* Get length of incoming packet. */
717 ucp = (u_char *) buffer_ptr(&input);
718 len = GET_32BIT(ucp);
719 if (len < 1 + 2 + 2 || len > 256 * 1024)
720 packet_disconnect("Bad packet length %d.", len);
721 padded_len = (len + 8) & ~7;
723 /* Check if the packet has been entirely received. */
724 if (buffer_len(&input) < 4 + padded_len)
727 /* The entire packet is in buffer. */
729 /* Consume packet length. */
730 buffer_consume(&input, 4);
733 * Cryptographic attack detector for ssh
734 * (C)1998 CORE-SDI, Buenos Aires Argentina
735 * Ariel Futoransky(futo@core-sdi.com)
737 if (receive_context.cipher->number != SSH_CIPHER_NONE &&
738 detect_attack(buffer_ptr(&input), padded_len, NULL) == DEATTACK_DETECTED)
739 packet_disconnect("crc32 compensation attack: network attack detected");
741 /* Decrypt data to incoming_packet. */
742 buffer_clear(&incoming_packet);
743 cp = buffer_append_space(&incoming_packet, padded_len);
744 cipher_decrypt(&receive_context, cp, buffer_ptr(&input), padded_len);
746 buffer_consume(&input, padded_len);
749 fprintf(stderr, "read_poll plain: ");
750 buffer_dump(&incoming_packet);
753 /* Compute packet checksum. */
754 checksum = ssh_crc32((u_char *) buffer_ptr(&incoming_packet),
755 buffer_len(&incoming_packet) - 4);
758 buffer_consume(&incoming_packet, 8 - len % 8);
760 /* Test check bytes. */
761 if (len != buffer_len(&incoming_packet))
762 packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
763 len, buffer_len(&incoming_packet));
765 ucp = (u_char *) buffer_ptr(&incoming_packet) + len - 4;
766 stored_checksum = GET_32BIT(ucp);
767 if (checksum != stored_checksum)
768 packet_disconnect("Corrupted check bytes on input.");
769 buffer_consume_end(&incoming_packet, 4);
771 if (packet_compression) {
772 buffer_clear(&compression_buffer);
773 buffer_uncompress(&incoming_packet, &compression_buffer);
774 buffer_clear(&incoming_packet);
775 buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
776 buffer_len(&compression_buffer));
778 type = buffer_get_char(&incoming_packet);
779 *payload_len_ptr = buffer_len(&incoming_packet);
784 packet_read_poll2(int *payload_len_ptr, u_int32_t *seqnr_p)
786 static u_int32_t seqnr = 0;
787 static u_int packet_length = 0;
789 u_char *macbuf, *ucp, type;
791 int maclen, block_size;
796 if (newkeys[MODE_IN] != NULL) {
797 enc = &newkeys[MODE_IN]->enc;
798 mac = &newkeys[MODE_IN]->mac;
799 comp = &newkeys[MODE_IN]->comp;
801 maclen = mac && mac->enabled ? mac->mac_len : 0;
802 block_size = enc ? enc->cipher->block_size : 8;
804 if (packet_length == 0) {
806 * check if input size is less than the cipher block size,
807 * decrypt first block and extract length of incoming packet
809 if (buffer_len(&input) < block_size)
811 buffer_clear(&incoming_packet);
812 cp = buffer_append_space(&incoming_packet, block_size);
813 cipher_decrypt(&receive_context, cp, buffer_ptr(&input),
815 ucp = (u_char *) buffer_ptr(&incoming_packet);
816 packet_length = GET_32BIT(ucp);
817 if (packet_length < 1 + 4 || packet_length > 256 * 1024) {
818 buffer_dump(&incoming_packet);
819 packet_disconnect("Bad packet length %d.", packet_length);
821 DBG(debug("input: packet len %d", packet_length+4));
822 buffer_consume(&input, block_size);
824 /* we have a partial packet of block_size bytes */
825 need = 4 + packet_length - block_size;
826 DBG(debug("partial packet %d, need %d, maclen %d", block_size,
828 if (need % block_size != 0)
829 fatal("padding error: need %d block %d mod %d",
830 need, block_size, need % block_size);
832 * check if the entire packet has been received and
833 * decrypt into incoming_packet
835 if (buffer_len(&input) < need + maclen)
838 fprintf(stderr, "read_poll enc/full: ");
841 cp = buffer_append_space(&incoming_packet, need);
842 cipher_decrypt(&receive_context, cp, buffer_ptr(&input), need);
843 buffer_consume(&input, need);
845 * compute MAC over seqnr and packet,
846 * increment sequence number for incoming packet
848 if (mac && mac->enabled) {
849 macbuf = mac_compute(mac, seqnr,
850 (u_char *) buffer_ptr(&incoming_packet),
851 buffer_len(&incoming_packet));
852 if (memcmp(macbuf, buffer_ptr(&input), mac->mac_len) != 0)
853 packet_disconnect("Corrupted MAC on input.");
854 DBG(debug("MAC #%d ok", seqnr));
855 buffer_consume(&input, mac->mac_len);
860 log("incoming seqnr wraps around");
863 cp = buffer_ptr(&incoming_packet);
865 padlen = (u_char) *cp;
866 DBG(debug("input: padlen %d", padlen));
868 packet_disconnect("Corrupted padlen %d on input.", padlen);
870 /* skip packet size + padlen, discard padding */
871 buffer_consume(&incoming_packet, 4 + 1);
872 buffer_consume_end(&incoming_packet, padlen);
874 DBG(debug("input: len before de-compress %d", buffer_len(&incoming_packet)));
875 if (comp && comp->enabled) {
876 buffer_clear(&compression_buffer);
877 buffer_uncompress(&incoming_packet, &compression_buffer);
878 buffer_clear(&incoming_packet);
879 buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
880 buffer_len(&compression_buffer));
881 DBG(debug("input: len after de-compress %d", buffer_len(&incoming_packet)));
884 * get packet type, implies consume.
885 * return length of payload (without type field)
887 type = buffer_get_char(&incoming_packet);
888 if (type == SSH2_MSG_NEWKEYS)
889 set_newkeys(MODE_IN);
890 *payload_len_ptr = buffer_len(&incoming_packet);
892 fprintf(stderr, "read/plain[%d]:\r\n", type);
893 buffer_dump(&incoming_packet);
895 /* reset for next packet */
901 packet_read_poll_seqnr(int *payload_len_ptr, u_int32_t *seqnr_p)
909 type = packet_read_poll2(payload_len_ptr, seqnr_p);
911 DBG(debug("received packet type %d", type));
913 case SSH2_MSG_IGNORE:
917 msg = packet_get_string(NULL);
918 debug("Remote: %.900s", msg);
920 msg = packet_get_string(NULL);
923 case SSH2_MSG_DISCONNECT:
924 reason = packet_get_int();
925 msg = packet_get_string(NULL);
926 log("Received disconnect from %s: %d: %.400s", get_remote_ipaddr(),
936 type = packet_read_poll1(payload_len_ptr);
941 msg = packet_get_string(NULL);
942 debug("Remote: %.900s", msg);
945 case SSH_MSG_DISCONNECT:
946 msg = packet_get_string(NULL);
947 log("Received disconnect from %s: %.400s", get_remote_ipaddr(),
954 DBG(debug("received packet type %d", type));
963 packet_read_poll(int *payload_len_ptr)
965 return packet_read_poll_seqnr(payload_len_ptr, NULL);
969 * Buffers the given amount of input characters. This is intended to be used
970 * together with packet_read_poll.
974 packet_process_incoming(const char *buf, u_int len)
976 buffer_append(&input, buf, len);
979 /* Returns a character from the packet. */
982 packet_get_char(void)
985 buffer_get(&incoming_packet, &ch, 1);
989 /* Returns an integer from the packet data. */
994 return buffer_get_int(&incoming_packet);
998 * Returns an arbitrary precision integer from the packet data. The integer
999 * must have been initialized before this call.
1003 packet_get_bignum(BIGNUM * value)
1005 (void)buffer_get_bignum(&incoming_packet, value);
1009 packet_get_bignum2(BIGNUM * value)
1011 (void)buffer_get_bignum2(&incoming_packet, value);
1015 packet_get_raw(int *length_ptr)
1017 int bytes = buffer_len(&incoming_packet);
1018 if (length_ptr != NULL)
1019 *length_ptr = bytes;
1020 return buffer_ptr(&incoming_packet);
1024 packet_remaining(void)
1026 return buffer_len(&incoming_packet);
1030 * Returns a string from the packet data. The string is allocated using
1031 * xmalloc; it is the responsibility of the calling program to free it when
1032 * no longer needed. The length_ptr argument may be NULL, or point to an
1033 * integer into which the length of the string is stored.
1037 packet_get_string(u_int *length_ptr)
1039 return buffer_get_string(&incoming_packet, length_ptr);
1043 * Sends a diagnostic message from the server to the client. This message
1044 * can be sent at any time (but not while constructing another message). The
1045 * message is printed immediately, but only if the client is being executed
1046 * in verbose mode. These messages are primarily intended to ease debugging
1047 * authentication problems. The length of the formatted message must not
1048 * exceed 1024 bytes. This will automatically call packet_write_wait.
1052 packet_send_debug(const char *fmt,...)
1057 if (compat20 && (datafellows & SSH_BUG_DEBUG))
1060 va_start(args, fmt);
1061 vsnprintf(buf, sizeof(buf), fmt, args);
1065 packet_start(SSH2_MSG_DEBUG);
1066 packet_put_char(0); /* bool: always display */
1067 packet_put_cstring(buf);
1068 packet_put_cstring("");
1070 packet_start(SSH_MSG_DEBUG);
1071 packet_put_cstring(buf);
1074 packet_write_wait();
1078 * Logs the error plus constructs and sends a disconnect packet, closes the
1079 * connection, and exits. This function never returns. The error message
1080 * should not contain a newline. The length of the formatted message must
1081 * not exceed 1024 bytes.
1085 packet_disconnect(const char *fmt,...)
1089 static int disconnecting = 0;
1090 if (disconnecting) /* Guard against recursive invocations. */
1091 fatal("packet_disconnect called recursively.");
1095 * Format the message. Note that the caller must make sure the
1096 * message is of limited size.
1098 va_start(args, fmt);
1099 vsnprintf(buf, sizeof(buf), fmt, args);
1102 /* Send the disconnect message to the other side, and wait for it to get sent. */
1104 packet_start(SSH2_MSG_DISCONNECT);
1105 packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1106 packet_put_cstring(buf);
1107 packet_put_cstring("");
1109 packet_start(SSH_MSG_DISCONNECT);
1110 packet_put_cstring(buf);
1113 packet_write_wait();
1115 /* Stop listening for connections. */
1116 channel_close_all();
1118 /* Close the connection. */
1121 /* Display the error locally and exit. */
1122 log("Disconnecting: %.100s", buf);
1126 /* Checks if there is any buffered output, and tries to write some of the output. */
1129 packet_write_poll(void)
1131 int len = buffer_len(&output);
1133 len = write(connection_out, buffer_ptr(&output), len);
1135 if (errno == EAGAIN)
1138 fatal("Write failed: %.100s", strerror(errno));
1140 buffer_consume(&output, len);
1145 * Calls packet_write_poll repeatedly until all pending output data has been
1150 packet_write_wait(void)
1154 setp = (fd_set *)xmalloc(howmany(connection_out + 1, NFDBITS) *
1156 packet_write_poll();
1157 while (packet_have_data_to_write()) {
1158 memset(setp, 0, howmany(connection_out + 1, NFDBITS) *
1160 FD_SET(connection_out, setp);
1161 while (select(connection_out + 1, NULL, setp, NULL, NULL) == -1 &&
1162 (errno == EAGAIN || errno == EINTR))
1164 packet_write_poll();
1169 /* Returns true if there is buffered data to write to the connection. */
1172 packet_have_data_to_write(void)
1174 return buffer_len(&output) != 0;
1177 /* Returns true if there is not too much data to write to the connection. */
1180 packet_not_very_much_data_to_write(void)
1182 if (interactive_mode)
1183 return buffer_len(&output) < 16384;
1185 return buffer_len(&output) < 128 * 1024;
1188 /* Informs that the current session is interactive. Sets IP flags for that. */
1191 packet_set_interactive(int interactive)
1193 static int called = 0;
1194 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1195 int lowdelay = IPTOS_LOWDELAY;
1196 int throughput = IPTOS_THROUGHPUT;
1204 /* Record that we are in interactive mode. */
1205 interactive_mode = interactive;
1207 /* Only set socket options if using a socket. */
1208 if (!packet_connection_is_on_socket())
1211 * IPTOS_LOWDELAY and IPTOS_THROUGHPUT are IPv4 only
1215 * Set IP options for an interactive connection. Use
1216 * IPTOS_LOWDELAY and TCP_NODELAY.
1218 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1219 if (packet_connection_is_ipv4()) {
1220 if (setsockopt(connection_in, IPPROTO_IP, IP_TOS,
1221 (void *) &lowdelay, sizeof(lowdelay)) < 0)
1222 error("setsockopt IPTOS_LOWDELAY: %.100s",
1226 if (setsockopt(connection_in, IPPROTO_TCP, TCP_NODELAY, (void *) &on,
1228 error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
1229 } else if (packet_connection_is_ipv4()) {
1231 * Set IP options for a non-interactive connection. Use
1234 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1235 if (setsockopt(connection_in, IPPROTO_IP, IP_TOS, (void *) &throughput,
1236 sizeof(throughput)) < 0)
1237 error("setsockopt IPTOS_THROUGHPUT: %.100s", strerror(errno));
1242 /* Returns true if the current connection is interactive. */
1245 packet_is_interactive(void)
1247 return interactive_mode;
1251 packet_set_maxsize(int s)
1253 static int called = 0;
1255 log("packet_set_maxsize: called twice: old %d new %d",
1256 max_packet_size, s);
1259 if (s < 4 * 1024 || s > 1024 * 1024) {
1260 log("packet_set_maxsize: bad size %d", s);
1264 debug("packet_set_maxsize: setting to %d", s);
1265 max_packet_size = s;
1269 /* roundup current message to pad bytes */
1271 packet_add_padding(u_char pad)
1277 * 9.2. Ignored Data Message
1279 * byte SSH_MSG_IGNORE
1282 * All implementations MUST understand (and ignore) this message at any
1283 * time (after receiving the protocol version). No implementation is
1284 * required to send them. This message can be used as an additional
1285 * protection measure against advanced traffic analysis techniques.
1288 packet_send_ignore(int nbytes)
1293 packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1294 packet_put_int(nbytes);
1295 for (i = 0; i < nbytes; i++) {
1297 rand = arc4random();
1298 packet_put_char(rand & 0xff);