1 /* $OpenBSD: packet.c,v 1.247 2017/03/11 13:07:35 markus Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * This file contains code implementing the packet protocol and communication
7 * with the other side. This same code is used both on client and server side.
9 * As far as I am concerned, the code I have written for this software
10 * can be used freely for any purpose. Any derived versions of this
11 * software must be clearly marked as such, and if the derived work is
12 * incompatible with the protocol description in the RFC file, it must be
13 * called by a name other than "ssh" or "Secure Shell".
16 * SSH2 packet format added by Markus Friedl.
17 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
19 * Redistribution and use in source and binary forms, with or without
20 * modification, are permitted provided that the following conditions
22 * 1. Redistributions of source code must retain the above copyright
23 * notice, this list of conditions and the following disclaimer.
24 * 2. Redistributions in binary form must reproduce the above copyright
25 * notice, this list of conditions and the following disclaimer in the
26 * documentation and/or other materials provided with the distribution.
28 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
29 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
30 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
31 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
32 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
33 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
34 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
35 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
36 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
37 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
43 #include <sys/types.h>
44 #include "openbsd-compat/sys-queue.h"
45 #include <sys/socket.h>
46 #ifdef HAVE_SYS_TIME_H
47 # include <sys/time.h>
50 #include <netinet/in.h>
51 #include <netinet/ip.h>
52 #include <arpa/inet.h>
67 #include "buffer.h" /* typedefs XXX */
68 #include "key.h" /* typedefs XXX */
89 #include "blacklist_client.h"
97 #define PACKET_MAX_SIZE (256 * 1024)
107 TAILQ_ENTRY(packet) next;
109 struct sshbuf *payload;
112 struct session_state {
114 * This variable contains the file descriptors used for
115 * communicating with the other side. connection_in is used for
116 * reading; connection_out for writing. These can be the same
117 * descriptor, in which case it is assumed to be a socket.
122 /* Protocol flags for the remote side. */
123 u_int remote_protocol_flags;
125 /* Encryption context for receiving data. Only used for decryption. */
126 struct sshcipher_ctx *receive_context;
128 /* Encryption context for sending data. Only used for encryption. */
129 struct sshcipher_ctx *send_context;
131 /* Buffer for raw input data from the socket. */
132 struct sshbuf *input;
134 /* Buffer for raw output data going to the socket. */
135 struct sshbuf *output;
137 /* Buffer for the partial outgoing packet being constructed. */
138 struct sshbuf *outgoing_packet;
140 /* Buffer for the incoming packet currently being processed. */
141 struct sshbuf *incoming_packet;
143 /* Scratch buffer for packet compression/decompression. */
144 struct sshbuf *compression_buffer;
146 /* Incoming/outgoing compression dictionaries */
147 z_stream compression_in_stream;
148 z_stream compression_out_stream;
149 int compression_in_started;
150 int compression_out_started;
151 int compression_in_failures;
152 int compression_out_failures;
155 * Flag indicating whether packet compression/decompression is
158 int packet_compression;
160 /* default maximum packet size */
161 u_int max_packet_size;
163 /* Flag indicating whether this module has been initialized. */
166 /* Set to true if the connection is interactive. */
167 int interactive_mode;
169 /* Set to true if we are the server side. */
172 /* Set to true if we are authenticated. */
173 int after_authentication;
175 int keep_alive_timeouts;
177 /* The maximum time that we will wait to send or receive a packet */
178 int packet_timeout_ms;
180 /* Session key information for Encryption and MAC */
181 struct newkeys *newkeys[MODE_MAX];
182 struct packet_state p_read, p_send;
184 /* Volume-based rekeying */
185 u_int64_t max_blocks_in, max_blocks_out, rekey_limit;
187 /* Time-based rekeying */
188 u_int32_t rekey_interval; /* how often in seconds */
189 time_t rekey_time; /* time of last rekeying */
191 /* Session key for protocol v1 */
192 u_char ssh1_key[SSH_SESSION_KEY_LENGTH];
195 /* roundup current message to extra_pad bytes */
198 /* XXX discard incoming data after MAC error */
199 u_int packet_discard;
200 size_t packet_discard_mac_already;
201 struct sshmac *packet_discard_mac;
203 /* Used in packet_read_poll2() */
206 /* Used in packet_send2 */
209 /* Used in ssh_packet_send_mux() */
212 /* Used in packet_set_interactive */
213 int set_interactive_called;
215 /* Used in packet_set_maxsize */
216 int set_maxsize_called;
218 /* One-off warning about weak ciphers */
219 int cipher_warning_done;
221 /* SSH1 CRC compensation attack detector */
222 struct deattack_ctx deattack;
224 /* Hook for fuzzing inbound packets */
225 ssh_packet_hook_fn *hook_in;
228 TAILQ_HEAD(, packet) outgoing;
232 ssh_alloc_session_state(void)
234 struct ssh *ssh = NULL;
235 struct session_state *state = NULL;
237 if ((ssh = calloc(1, sizeof(*ssh))) == NULL ||
238 (state = calloc(1, sizeof(*state))) == NULL ||
239 (state->input = sshbuf_new()) == NULL ||
240 (state->output = sshbuf_new()) == NULL ||
241 (state->outgoing_packet = sshbuf_new()) == NULL ||
242 (state->incoming_packet = sshbuf_new()) == NULL)
244 TAILQ_INIT(&state->outgoing);
245 TAILQ_INIT(&ssh->private_keys);
246 TAILQ_INIT(&ssh->public_keys);
247 state->connection_in = -1;
248 state->connection_out = -1;
249 state->max_packet_size = 32768;
250 state->packet_timeout_ms = -1;
251 state->p_send.packets = state->p_read.packets = 0;
252 state->initialized = 1;
254 * ssh_packet_send2() needs to queue packets until
255 * we've done the initial key exchange.
262 sshbuf_free(state->input);
263 sshbuf_free(state->output);
264 sshbuf_free(state->incoming_packet);
265 sshbuf_free(state->outgoing_packet);
273 ssh_packet_set_input_hook(struct ssh *ssh, ssh_packet_hook_fn *hook, void *ctx)
275 ssh->state->hook_in = hook;
276 ssh->state->hook_in_ctx = ctx;
279 /* Returns nonzero if rekeying is in progress */
281 ssh_packet_is_rekeying(struct ssh *ssh)
284 (ssh->state->rekeying || (ssh->kex != NULL && ssh->kex->done == 0));
288 * Sets the descriptors used for communication. Disables encryption until
289 * packet_set_encryption_key is called.
292 ssh_packet_set_connection(struct ssh *ssh, int fd_in, int fd_out)
294 struct session_state *state;
295 const struct sshcipher *none = cipher_by_name("none");
299 error("%s: cannot load cipher 'none'", __func__);
303 ssh = ssh_alloc_session_state();
305 error("%s: cound not allocate state", __func__);
309 state->connection_in = fd_in;
310 state->connection_out = fd_out;
311 if ((r = cipher_init(&state->send_context, none,
312 (const u_char *)"", 0, NULL, 0, CIPHER_ENCRYPT)) != 0 ||
313 (r = cipher_init(&state->receive_context, none,
314 (const u_char *)"", 0, NULL, 0, CIPHER_DECRYPT)) != 0) {
315 error("%s: cipher_init failed: %s", __func__, ssh_err(r));
316 free(ssh); /* XXX need ssh_free_session_state? */
319 state->newkeys[MODE_IN] = state->newkeys[MODE_OUT] = NULL;
320 deattack_init(&state->deattack);
322 * Cache the IP address of the remote connection for use in error
323 * messages that might be generated after the connection has closed.
325 (void)ssh_remote_ipaddr(ssh);
330 ssh_packet_set_timeout(struct ssh *ssh, int timeout, int count)
332 struct session_state *state = ssh->state;
334 if (timeout <= 0 || count <= 0) {
335 state->packet_timeout_ms = -1;
338 if ((INT_MAX / 1000) / count < timeout)
339 state->packet_timeout_ms = INT_MAX;
341 state->packet_timeout_ms = timeout * count * 1000;
345 ssh_packet_set_mux(struct ssh *ssh)
348 ssh->state->rekeying = 0;
352 ssh_packet_get_mux(struct ssh *ssh)
354 return ssh->state->mux;
358 ssh_packet_set_log_preamble(struct ssh *ssh, const char *fmt, ...)
363 free(ssh->log_preamble);
365 ssh->log_preamble = NULL;
368 r = vasprintf(&ssh->log_preamble, fmt, args);
370 if (r < 0 || ssh->log_preamble == NULL)
371 return SSH_ERR_ALLOC_FAIL;
377 ssh_packet_stop_discard(struct ssh *ssh)
379 struct session_state *state = ssh->state;
382 if (state->packet_discard_mac) {
384 size_t dlen = PACKET_MAX_SIZE;
386 if (dlen > state->packet_discard_mac_already)
387 dlen -= state->packet_discard_mac_already;
388 memset(buf, 'a', sizeof(buf));
389 while (sshbuf_len(state->incoming_packet) < dlen)
390 if ((r = sshbuf_put(state->incoming_packet, buf,
393 (void) mac_compute(state->packet_discard_mac,
395 sshbuf_ptr(state->incoming_packet), dlen,
398 logit("Finished discarding for %.200s port %d",
399 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
400 return SSH_ERR_MAC_INVALID;
404 ssh_packet_start_discard(struct ssh *ssh, struct sshenc *enc,
405 struct sshmac *mac, size_t mac_already, u_int discard)
407 struct session_state *state = ssh->state;
410 if (enc == NULL || !cipher_is_cbc(enc->cipher) || (mac && mac->etm)) {
411 if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0)
413 return SSH_ERR_MAC_INVALID;
416 * Record number of bytes over which the mac has already
417 * been computed in order to minimize timing attacks.
419 if (mac && mac->enabled) {
420 state->packet_discard_mac = mac;
421 state->packet_discard_mac_already = mac_already;
423 if (sshbuf_len(state->input) >= discard)
424 return ssh_packet_stop_discard(ssh);
425 state->packet_discard = discard - sshbuf_len(state->input);
429 /* Returns 1 if remote host is connected via socket, 0 if not. */
432 ssh_packet_connection_is_on_socket(struct ssh *ssh)
434 struct session_state *state = ssh->state;
435 struct sockaddr_storage from, to;
436 socklen_t fromlen, tolen;
438 if (state->connection_in == -1 || state->connection_out == -1)
441 /* filedescriptors in and out are the same, so it's a socket */
442 if (state->connection_in == state->connection_out)
444 fromlen = sizeof(from);
445 memset(&from, 0, sizeof(from));
446 if (getpeername(state->connection_in, (struct sockaddr *)&from,
450 memset(&to, 0, sizeof(to));
451 if (getpeername(state->connection_out, (struct sockaddr *)&to,
454 if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
456 if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
462 ssh_packet_get_bytes(struct ssh *ssh, u_int64_t *ibytes, u_int64_t *obytes)
465 *ibytes = ssh->state->p_read.bytes;
467 *obytes = ssh->state->p_send.bytes;
471 ssh_packet_connection_af(struct ssh *ssh)
473 struct sockaddr_storage to;
474 socklen_t tolen = sizeof(to);
476 memset(&to, 0, sizeof(to));
477 if (getsockname(ssh->state->connection_out, (struct sockaddr *)&to,
481 if (to.ss_family == AF_INET6 &&
482 IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&to)->sin6_addr))
488 /* Sets the connection into non-blocking mode. */
491 ssh_packet_set_nonblocking(struct ssh *ssh)
493 /* Set the socket into non-blocking mode. */
494 set_nonblock(ssh->state->connection_in);
496 if (ssh->state->connection_out != ssh->state->connection_in)
497 set_nonblock(ssh->state->connection_out);
500 /* Returns the socket used for reading. */
503 ssh_packet_get_connection_in(struct ssh *ssh)
505 return ssh->state->connection_in;
508 /* Returns the descriptor used for writing. */
511 ssh_packet_get_connection_out(struct ssh *ssh)
513 return ssh->state->connection_out;
517 * Returns the IP-address of the remote host as a string. The returned
518 * string must not be freed.
522 ssh_remote_ipaddr(struct ssh *ssh)
524 const int sock = ssh->state->connection_in;
526 /* Check whether we have cached the ipaddr. */
527 if (ssh->remote_ipaddr == NULL) {
528 if (ssh_packet_connection_is_on_socket(ssh)) {
529 ssh->remote_ipaddr = get_peer_ipaddr(sock);
530 ssh->remote_port = get_peer_port(sock);
531 ssh->local_ipaddr = get_local_ipaddr(sock);
532 ssh->local_port = get_local_port(sock);
534 ssh->remote_ipaddr = strdup("UNKNOWN");
535 ssh->remote_port = 65535;
536 ssh->local_ipaddr = strdup("UNKNOWN");
537 ssh->local_port = 65535;
540 return ssh->remote_ipaddr;
543 /* Returns the port number of the remote host. */
546 ssh_remote_port(struct ssh *ssh)
548 (void)ssh_remote_ipaddr(ssh); /* Will lookup and cache. */
549 return ssh->remote_port;
553 * Returns the IP-address of the local host as a string. The returned
554 * string must not be freed.
558 ssh_local_ipaddr(struct ssh *ssh)
560 (void)ssh_remote_ipaddr(ssh); /* Will lookup and cache. */
561 return ssh->local_ipaddr;
564 /* Returns the port number of the local host. */
567 ssh_local_port(struct ssh *ssh)
569 (void)ssh_remote_ipaddr(ssh); /* Will lookup and cache. */
570 return ssh->local_port;
573 /* Closes the connection and clears and frees internal data structures. */
576 ssh_packet_close(struct ssh *ssh)
578 struct session_state *state = ssh->state;
581 if (!state->initialized)
583 state->initialized = 0;
584 if (state->connection_in == state->connection_out) {
585 shutdown(state->connection_out, SHUT_RDWR);
586 close(state->connection_out);
588 close(state->connection_in);
589 close(state->connection_out);
591 sshbuf_free(state->input);
592 sshbuf_free(state->output);
593 sshbuf_free(state->outgoing_packet);
594 sshbuf_free(state->incoming_packet);
595 for (mode = 0; mode < MODE_MAX; mode++)
596 kex_free_newkeys(state->newkeys[mode]);
597 if (state->compression_buffer) {
598 sshbuf_free(state->compression_buffer);
599 if (state->compression_out_started) {
600 z_streamp stream = &state->compression_out_stream;
601 debug("compress outgoing: "
602 "raw data %llu, compressed %llu, factor %.2f",
603 (unsigned long long)stream->total_in,
604 (unsigned long long)stream->total_out,
605 stream->total_in == 0 ? 0.0 :
606 (double) stream->total_out / stream->total_in);
607 if (state->compression_out_failures == 0)
610 if (state->compression_in_started) {
611 z_streamp stream = &state->compression_out_stream;
612 debug("compress incoming: "
613 "raw data %llu, compressed %llu, factor %.2f",
614 (unsigned long long)stream->total_out,
615 (unsigned long long)stream->total_in,
616 stream->total_out == 0 ? 0.0 :
617 (double) stream->total_in / stream->total_out);
618 if (state->compression_in_failures == 0)
622 cipher_free(state->send_context);
623 cipher_free(state->receive_context);
624 state->send_context = state->receive_context = NULL;
625 free(ssh->remote_ipaddr);
626 ssh->remote_ipaddr = NULL;
631 /* Sets remote side protocol flags. */
634 ssh_packet_set_protocol_flags(struct ssh *ssh, u_int protocol_flags)
636 ssh->state->remote_protocol_flags = protocol_flags;
639 /* Returns the remote protocol flags set earlier by the above function. */
642 ssh_packet_get_protocol_flags(struct ssh *ssh)
644 return ssh->state->remote_protocol_flags;
648 * Starts packet compression from the next packet on in both directions.
649 * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
653 ssh_packet_init_compression(struct ssh *ssh)
655 if (!ssh->state->compression_buffer &&
656 ((ssh->state->compression_buffer = sshbuf_new()) == NULL))
657 return SSH_ERR_ALLOC_FAIL;
662 start_compression_out(struct ssh *ssh, int level)
664 if (level < 1 || level > 9)
665 return SSH_ERR_INVALID_ARGUMENT;
666 debug("Enabling compression at level %d.", level);
667 if (ssh->state->compression_out_started == 1)
668 deflateEnd(&ssh->state->compression_out_stream);
669 switch (deflateInit(&ssh->state->compression_out_stream, level)) {
671 ssh->state->compression_out_started = 1;
674 return SSH_ERR_ALLOC_FAIL;
676 return SSH_ERR_INTERNAL_ERROR;
682 start_compression_in(struct ssh *ssh)
684 if (ssh->state->compression_in_started == 1)
685 inflateEnd(&ssh->state->compression_in_stream);
686 switch (inflateInit(&ssh->state->compression_in_stream)) {
688 ssh->state->compression_in_started = 1;
691 return SSH_ERR_ALLOC_FAIL;
693 return SSH_ERR_INTERNAL_ERROR;
699 ssh_packet_start_compression(struct ssh *ssh, int level)
703 if (ssh->state->packet_compression && !compat20)
704 return SSH_ERR_INTERNAL_ERROR;
705 ssh->state->packet_compression = 1;
706 if ((r = ssh_packet_init_compression(ssh)) != 0 ||
707 (r = start_compression_in(ssh)) != 0 ||
708 (r = start_compression_out(ssh, level)) != 0)
713 /* XXX remove need for separate compression buffer */
715 compress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
720 if (ssh->state->compression_out_started != 1)
721 return SSH_ERR_INTERNAL_ERROR;
723 /* This case is not handled below. */
724 if (sshbuf_len(in) == 0)
727 /* Input is the contents of the input buffer. */
728 if ((ssh->state->compression_out_stream.next_in =
729 sshbuf_mutable_ptr(in)) == NULL)
730 return SSH_ERR_INTERNAL_ERROR;
731 ssh->state->compression_out_stream.avail_in = sshbuf_len(in);
733 /* Loop compressing until deflate() returns with avail_out != 0. */
735 /* Set up fixed-size output buffer. */
736 ssh->state->compression_out_stream.next_out = buf;
737 ssh->state->compression_out_stream.avail_out = sizeof(buf);
739 /* Compress as much data into the buffer as possible. */
740 status = deflate(&ssh->state->compression_out_stream,
744 return SSH_ERR_ALLOC_FAIL;
746 /* Append compressed data to output_buffer. */
747 if ((r = sshbuf_put(out, buf, sizeof(buf) -
748 ssh->state->compression_out_stream.avail_out)) != 0)
753 ssh->state->compression_out_failures++;
754 return SSH_ERR_INVALID_FORMAT;
756 } while (ssh->state->compression_out_stream.avail_out == 0);
761 uncompress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
766 if (ssh->state->compression_in_started != 1)
767 return SSH_ERR_INTERNAL_ERROR;
769 if ((ssh->state->compression_in_stream.next_in =
770 sshbuf_mutable_ptr(in)) == NULL)
771 return SSH_ERR_INTERNAL_ERROR;
772 ssh->state->compression_in_stream.avail_in = sshbuf_len(in);
775 /* Set up fixed-size output buffer. */
776 ssh->state->compression_in_stream.next_out = buf;
777 ssh->state->compression_in_stream.avail_out = sizeof(buf);
779 status = inflate(&ssh->state->compression_in_stream,
783 if ((r = sshbuf_put(out, buf, sizeof(buf) -
784 ssh->state->compression_in_stream.avail_out)) != 0)
789 * Comments in zlib.h say that we should keep calling
790 * inflate() until we get an error. This appears to
791 * be the error that we get.
795 return SSH_ERR_INVALID_FORMAT;
797 return SSH_ERR_ALLOC_FAIL;
800 ssh->state->compression_in_failures++;
801 return SSH_ERR_INTERNAL_ERROR;
808 * Causes any further packets to be encrypted using the given key. The same
809 * key is used for both sending and reception. However, both directions are
810 * encrypted independently of each other.
814 ssh_packet_set_encryption_key(struct ssh *ssh, const u_char *key, u_int keylen, int number)
817 fatal("no SSH protocol 1 support");
818 #else /* WITH_SSH1 */
819 struct session_state *state = ssh->state;
820 const struct sshcipher *cipher = cipher_by_number(number);
825 fatal("%s: unknown cipher number %d", __func__, number);
827 fatal("%s: keylen too small: %d", __func__, keylen);
828 if (keylen > SSH_SESSION_KEY_LENGTH)
829 fatal("%s: keylen too big: %d", __func__, keylen);
830 memcpy(state->ssh1_key, key, keylen);
831 state->ssh1_keylen = keylen;
832 if ((r = cipher_init(&state->send_context, cipher, key, keylen,
833 NULL, 0, CIPHER_ENCRYPT)) != 0 ||
834 (r = cipher_init(&state->receive_context, cipher, key, keylen,
835 NULL, 0, CIPHER_DECRYPT) != 0))
836 fatal("%s: cipher_init failed: %s", __func__, ssh_err(r));
837 if (!state->cipher_warning_done &&
838 ((wmsg = cipher_warning_message(state->send_context)) != NULL ||
839 (wmsg = cipher_warning_message(state->send_context)) != NULL)) {
840 error("Warning: %s", wmsg);
841 state->cipher_warning_done = 1;
843 #endif /* WITH_SSH1 */
847 * Finalizes and sends the packet. If the encryption key has been set,
848 * encrypts the packet before sending.
852 ssh_packet_send1(struct ssh *ssh)
854 struct session_state *state = ssh->state;
860 * If using packet compression, compress the payload of the outgoing
863 if (state->packet_compression) {
864 sshbuf_reset(state->compression_buffer);
866 if ((r = sshbuf_consume(state->outgoing_packet, 8)) != 0)
869 if ((r = sshbuf_put(state->compression_buffer,
870 "\0\0\0\0\0\0\0\0", 8)) != 0)
872 if ((r = compress_buffer(ssh, state->outgoing_packet,
873 state->compression_buffer)) != 0)
875 sshbuf_reset(state->outgoing_packet);
876 if ((r = sshbuf_putb(state->outgoing_packet,
877 state->compression_buffer)) != 0)
880 /* Compute packet length without padding (add checksum, remove padding). */
881 len = sshbuf_len(state->outgoing_packet) + 4 - 8;
883 /* Insert padding. Initialized to zero in packet_start1() */
884 padding = 8 - len % 8;
885 if (!cipher_ctx_is_plaintext(state->send_context)) {
886 cp = sshbuf_mutable_ptr(state->outgoing_packet);
888 r = SSH_ERR_INTERNAL_ERROR;
891 arc4random_buf(cp + 8 - padding, padding);
893 if ((r = sshbuf_consume(state->outgoing_packet, 8 - padding)) != 0)
896 /* Add check bytes. */
897 checksum = ssh_crc32(sshbuf_ptr(state->outgoing_packet),
898 sshbuf_len(state->outgoing_packet));
899 POKE_U32(buf, checksum);
900 if ((r = sshbuf_put(state->outgoing_packet, buf, 4)) != 0)
904 fprintf(stderr, "packet_send plain: ");
905 sshbuf_dump(state->outgoing_packet, stderr);
908 /* Append to output. */
910 if ((r = sshbuf_put(state->output, buf, 4)) != 0)
912 if ((r = sshbuf_reserve(state->output,
913 sshbuf_len(state->outgoing_packet), &cp)) != 0)
915 if ((r = cipher_crypt(state->send_context, 0, cp,
916 sshbuf_ptr(state->outgoing_packet),
917 sshbuf_len(state->outgoing_packet), 0, 0)) != 0)
921 fprintf(stderr, "encrypted: ");
922 sshbuf_dump(state->output, stderr);
924 state->p_send.packets++;
925 state->p_send.bytes += len +
926 sshbuf_len(state->outgoing_packet);
927 sshbuf_reset(state->outgoing_packet);
930 * Note that the packet is now only buffered in output. It won't be
931 * actually sent until ssh_packet_write_wait or ssh_packet_write_poll
940 ssh_set_newkeys(struct ssh *ssh, int mode)
942 struct session_state *state = ssh->state;
945 struct sshcomp *comp;
946 struct sshcipher_ctx **ccp;
947 struct packet_state *ps;
948 u_int64_t *max_blocks;
949 const char *wmsg, *dir;
952 debug2("set_newkeys: mode %d", mode);
954 if (mode == MODE_OUT) {
956 ccp = &state->send_context;
957 crypt_type = CIPHER_ENCRYPT;
959 max_blocks = &state->max_blocks_out;
962 ccp = &state->receive_context;
963 crypt_type = CIPHER_DECRYPT;
965 max_blocks = &state->max_blocks_in;
967 if (state->newkeys[mode] != NULL) {
968 debug("%s: rekeying after %llu %s blocks"
969 " (%llu bytes total)", __func__,
970 (unsigned long long)ps->blocks, dir,
971 (unsigned long long)ps->bytes);
974 enc = &state->newkeys[mode]->enc;
975 mac = &state->newkeys[mode]->mac;
976 comp = &state->newkeys[mode]->comp;
978 explicit_bzero(enc->iv, enc->iv_len);
979 explicit_bzero(enc->key, enc->key_len);
980 explicit_bzero(mac->key, mac->key_len);
987 free(state->newkeys[mode]);
989 /* note that both bytes and the seqnr are not reset */
990 ps->packets = ps->blocks = 0;
991 /* move newkeys from kex to state */
992 if ((state->newkeys[mode] = ssh->kex->newkeys[mode]) == NULL)
993 return SSH_ERR_INTERNAL_ERROR;
994 ssh->kex->newkeys[mode] = NULL;
995 enc = &state->newkeys[mode]->enc;
996 mac = &state->newkeys[mode]->mac;
997 comp = &state->newkeys[mode]->comp;
998 if (cipher_authlen(enc->cipher) == 0) {
999 if ((r = mac_init(mac)) != 0)
1003 DBG(debug("cipher_init_context: %d", mode));
1004 if ((r = cipher_init(ccp, enc->cipher, enc->key, enc->key_len,
1005 enc->iv, enc->iv_len, crypt_type)) != 0)
1007 if (!state->cipher_warning_done &&
1008 (wmsg = cipher_warning_message(*ccp)) != NULL) {
1009 error("Warning: %s", wmsg);
1010 state->cipher_warning_done = 1;
1012 /* Deleting the keys does not gain extra security */
1013 /* explicit_bzero(enc->iv, enc->block_size);
1014 explicit_bzero(enc->key, enc->key_len);
1015 explicit_bzero(mac->key, mac->key_len); */
1016 if ((comp->type == COMP_ZLIB ||
1017 (comp->type == COMP_DELAYED &&
1018 state->after_authentication)) && comp->enabled == 0) {
1019 if ((r = ssh_packet_init_compression(ssh)) < 0)
1021 if (mode == MODE_OUT) {
1022 if ((r = start_compression_out(ssh, 6)) != 0)
1025 if ((r = start_compression_in(ssh)) != 0)
1031 * The 2^(blocksize*2) limit is too expensive for 3DES,
1032 * blowfish, etc, so enforce a 1GB limit for small blocksizes.
1034 if (enc->block_size >= 16)
1035 *max_blocks = (u_int64_t)1 << (enc->block_size*2);
1037 *max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
1038 if (state->rekey_limit)
1039 *max_blocks = MINIMUM(*max_blocks,
1040 state->rekey_limit / enc->block_size);
1041 debug("rekey after %llu blocks", (unsigned long long)*max_blocks);
1045 #define MAX_PACKETS (1U<<31)
1047 ssh_packet_need_rekeying(struct ssh *ssh, u_int outbound_packet_len)
1049 struct session_state *state = ssh->state;
1050 u_int32_t out_blocks;
1052 /* XXX client can't cope with rekeying pre-auth */
1053 if (!state->after_authentication)
1056 /* Haven't keyed yet or KEX in progress. */
1057 if (ssh->kex == NULL || ssh_packet_is_rekeying(ssh))
1060 /* Peer can't rekey */
1061 if (ssh->compat & SSH_BUG_NOREKEY)
1065 * Permit one packet in or out per rekey - this allows us to
1066 * make progress when rekey limits are very small.
1068 if (state->p_send.packets == 0 && state->p_read.packets == 0)
1071 /* Time-based rekeying */
1072 if (state->rekey_interval != 0 &&
1073 (int64_t)state->rekey_time + state->rekey_interval <= monotime())
1076 /* Always rekey when MAX_PACKETS sent in either direction */
1077 if (state->p_send.packets > MAX_PACKETS ||
1078 state->p_read.packets > MAX_PACKETS)
1081 /* Rekey after (cipher-specific) maxiumum blocks */
1082 out_blocks = ROUNDUP(outbound_packet_len,
1083 state->newkeys[MODE_OUT]->enc.block_size);
1084 return (state->max_blocks_out &&
1085 (state->p_send.blocks + out_blocks > state->max_blocks_out)) ||
1086 (state->max_blocks_in &&
1087 (state->p_read.blocks > state->max_blocks_in));
1091 * Delayed compression for SSH2 is enabled after authentication:
1092 * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
1093 * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
1096 ssh_packet_enable_delayed_compress(struct ssh *ssh)
1098 struct session_state *state = ssh->state;
1099 struct sshcomp *comp = NULL;
1103 * Remember that we are past the authentication step, so rekeying
1104 * with COMP_DELAYED will turn on compression immediately.
1106 state->after_authentication = 1;
1107 for (mode = 0; mode < MODE_MAX; mode++) {
1108 /* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
1109 if (state->newkeys[mode] == NULL)
1111 comp = &state->newkeys[mode]->comp;
1112 if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
1113 if ((r = ssh_packet_init_compression(ssh)) != 0)
1115 if (mode == MODE_OUT) {
1116 if ((r = start_compression_out(ssh, 6)) != 0)
1119 if ((r = start_compression_in(ssh)) != 0)
1128 /* Used to mute debug logging for noisy packet types */
1130 ssh_packet_log_type(u_char type)
1133 case SSH2_MSG_CHANNEL_DATA:
1134 case SSH2_MSG_CHANNEL_EXTENDED_DATA:
1135 case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
1143 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
1146 ssh_packet_send2_wrapped(struct ssh *ssh)
1148 struct session_state *state = ssh->state;
1149 u_char type, *cp, macbuf[SSH_DIGEST_MAX_LENGTH];
1150 u_char tmp, padlen, pad = 0;
1151 u_int authlen = 0, aadlen = 0;
1153 struct sshenc *enc = NULL;
1154 struct sshmac *mac = NULL;
1155 struct sshcomp *comp = NULL;
1158 if (state->newkeys[MODE_OUT] != NULL) {
1159 enc = &state->newkeys[MODE_OUT]->enc;
1160 mac = &state->newkeys[MODE_OUT]->mac;
1161 comp = &state->newkeys[MODE_OUT]->comp;
1162 /* disable mac for authenticated encryption */
1163 if ((authlen = cipher_authlen(enc->cipher)) != 0)
1166 block_size = enc ? enc->block_size : 8;
1167 aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
1169 type = (sshbuf_ptr(state->outgoing_packet))[5];
1170 if (ssh_packet_log_type(type))
1171 debug3("send packet: type %u", type);
1173 fprintf(stderr, "plain: ");
1174 sshbuf_dump(state->outgoing_packet, stderr);
1177 if (comp && comp->enabled) {
1178 len = sshbuf_len(state->outgoing_packet);
1179 /* skip header, compress only payload */
1180 if ((r = sshbuf_consume(state->outgoing_packet, 5)) != 0)
1182 sshbuf_reset(state->compression_buffer);
1183 if ((r = compress_buffer(ssh, state->outgoing_packet,
1184 state->compression_buffer)) != 0)
1186 sshbuf_reset(state->outgoing_packet);
1187 if ((r = sshbuf_put(state->outgoing_packet,
1188 "\0\0\0\0\0", 5)) != 0 ||
1189 (r = sshbuf_putb(state->outgoing_packet,
1190 state->compression_buffer)) != 0)
1192 DBG(debug("compression: raw %d compressed %zd", len,
1193 sshbuf_len(state->outgoing_packet)));
1196 /* sizeof (packet_len + pad_len + payload) */
1197 len = sshbuf_len(state->outgoing_packet);
1200 * calc size of padding, alloc space, get random data,
1201 * minimum padding is 4 bytes
1203 len -= aadlen; /* packet length is not encrypted for EtM modes */
1204 padlen = block_size - (len % block_size);
1206 padlen += block_size;
1207 if (state->extra_pad) {
1208 tmp = state->extra_pad;
1210 ROUNDUP(state->extra_pad, block_size);
1211 /* check if roundup overflowed */
1212 if (state->extra_pad < tmp)
1213 return SSH_ERR_INVALID_ARGUMENT;
1214 tmp = (len + padlen) % state->extra_pad;
1215 /* Check whether pad calculation below will underflow */
1216 if (tmp > state->extra_pad)
1217 return SSH_ERR_INVALID_ARGUMENT;
1218 pad = state->extra_pad - tmp;
1219 DBG(debug3("%s: adding %d (len %d padlen %d extra_pad %d)",
1220 __func__, pad, len, padlen, state->extra_pad));
1223 /* Check whether padlen calculation overflowed */
1225 return SSH_ERR_INVALID_ARGUMENT; /* overflow */
1226 state->extra_pad = 0;
1228 if ((r = sshbuf_reserve(state->outgoing_packet, padlen, &cp)) != 0)
1230 if (enc && !cipher_ctx_is_plaintext(state->send_context)) {
1231 /* random padding */
1232 arc4random_buf(cp, padlen);
1235 explicit_bzero(cp, padlen);
1237 /* sizeof (packet_len + pad_len + payload + padding) */
1238 len = sshbuf_len(state->outgoing_packet);
1239 cp = sshbuf_mutable_ptr(state->outgoing_packet);
1241 r = SSH_ERR_INTERNAL_ERROR;
1244 /* packet_length includes payload, padding and padding length field */
1245 POKE_U32(cp, len - 4);
1247 DBG(debug("send: len %d (includes padlen %d, aadlen %d)",
1248 len, padlen, aadlen));
1250 /* compute MAC over seqnr and packet(length fields, payload, padding) */
1251 if (mac && mac->enabled && !mac->etm) {
1252 if ((r = mac_compute(mac, state->p_send.seqnr,
1253 sshbuf_ptr(state->outgoing_packet), len,
1254 macbuf, sizeof(macbuf))) != 0)
1256 DBG(debug("done calc MAC out #%d", state->p_send.seqnr));
1258 /* encrypt packet and append to output buffer. */
1259 if ((r = sshbuf_reserve(state->output,
1260 sshbuf_len(state->outgoing_packet) + authlen, &cp)) != 0)
1262 if ((r = cipher_crypt(state->send_context, state->p_send.seqnr, cp,
1263 sshbuf_ptr(state->outgoing_packet),
1264 len - aadlen, aadlen, authlen)) != 0)
1266 /* append unencrypted MAC */
1267 if (mac && mac->enabled) {
1269 /* EtM: compute mac over aadlen + cipher text */
1270 if ((r = mac_compute(mac, state->p_send.seqnr,
1271 cp, len, macbuf, sizeof(macbuf))) != 0)
1273 DBG(debug("done calc MAC(EtM) out #%d",
1274 state->p_send.seqnr));
1276 if ((r = sshbuf_put(state->output, macbuf, mac->mac_len)) != 0)
1280 fprintf(stderr, "encrypted: ");
1281 sshbuf_dump(state->output, stderr);
1283 /* increment sequence number for outgoing packets */
1284 if (++state->p_send.seqnr == 0)
1285 logit("outgoing seqnr wraps around");
1286 if (++state->p_send.packets == 0)
1287 if (!(ssh->compat & SSH_BUG_NOREKEY))
1288 return SSH_ERR_NEED_REKEY;
1289 state->p_send.blocks += len / block_size;
1290 state->p_send.bytes += len;
1291 sshbuf_reset(state->outgoing_packet);
1293 if (type == SSH2_MSG_NEWKEYS)
1294 r = ssh_set_newkeys(ssh, MODE_OUT);
1295 else if (type == SSH2_MSG_USERAUTH_SUCCESS && state->server_side)
1296 r = ssh_packet_enable_delayed_compress(ssh);
1303 /* returns non-zero if the specified packet type is usec by KEX */
1305 ssh_packet_type_is_kex(u_char type)
1308 type >= SSH2_MSG_TRANSPORT_MIN &&
1309 type <= SSH2_MSG_TRANSPORT_MAX &&
1310 type != SSH2_MSG_SERVICE_REQUEST &&
1311 type != SSH2_MSG_SERVICE_ACCEPT &&
1312 type != SSH2_MSG_EXT_INFO;
1316 ssh_packet_send2(struct ssh *ssh)
1318 struct session_state *state = ssh->state;
1323 if (sshbuf_len(state->outgoing_packet) < 6)
1324 return SSH_ERR_INTERNAL_ERROR;
1325 type = sshbuf_ptr(state->outgoing_packet)[5];
1326 need_rekey = !ssh_packet_type_is_kex(type) &&
1327 ssh_packet_need_rekeying(ssh, sshbuf_len(state->outgoing_packet));
1330 * During rekeying we can only send key exchange messages.
1331 * Queue everything else.
1333 if ((need_rekey || state->rekeying) && !ssh_packet_type_is_kex(type)) {
1335 debug3("%s: rekex triggered", __func__);
1336 debug("enqueue packet: %u", type);
1337 p = calloc(1, sizeof(*p));
1339 return SSH_ERR_ALLOC_FAIL;
1341 p->payload = state->outgoing_packet;
1342 TAILQ_INSERT_TAIL(&state->outgoing, p, next);
1343 state->outgoing_packet = sshbuf_new();
1344 if (state->outgoing_packet == NULL)
1345 return SSH_ERR_ALLOC_FAIL;
1348 * This packet triggered a rekey, so send the
1350 * NB. reenters this function via kex_start_rekex().
1352 return kex_start_rekex(ssh);
1357 /* rekeying starts with sending KEXINIT */
1358 if (type == SSH2_MSG_KEXINIT)
1359 state->rekeying = 1;
1361 if ((r = ssh_packet_send2_wrapped(ssh)) != 0)
1364 /* after a NEWKEYS message we can send the complete queue */
1365 if (type == SSH2_MSG_NEWKEYS) {
1366 state->rekeying = 0;
1367 state->rekey_time = monotime();
1368 while ((p = TAILQ_FIRST(&state->outgoing))) {
1371 * If this packet triggers a rekex, then skip the
1372 * remaining packets in the queue for now.
1373 * NB. re-enters this function via kex_start_rekex.
1375 if (ssh_packet_need_rekeying(ssh,
1376 sshbuf_len(p->payload))) {
1377 debug3("%s: queued packet triggered rekex",
1379 return kex_start_rekex(ssh);
1381 debug("dequeue packet: %u", type);
1382 sshbuf_free(state->outgoing_packet);
1383 state->outgoing_packet = p->payload;
1384 TAILQ_REMOVE(&state->outgoing, p, next);
1385 memset(p, 0, sizeof(*p));
1387 if ((r = ssh_packet_send2_wrapped(ssh)) != 0)
1395 * Waits until a packet has been received, and returns its type. Note that
1396 * no other data is processed until this returns, so this function should not
1397 * be used during the interactive session.
1401 ssh_packet_read_seqnr(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1403 struct session_state *state = ssh->state;
1404 int len, r, ms_remain;
1407 struct timeval timeout, start, *timeoutp = NULL;
1409 DBG(debug("packet_read()"));
1411 setp = calloc(howmany(state->connection_in + 1,
1412 NFDBITS), sizeof(fd_mask));
1414 return SSH_ERR_ALLOC_FAIL;
1417 * Since we are blocking, ensure that all written packets have
1420 if ((r = ssh_packet_write_wait(ssh)) != 0)
1423 /* Stay in the loop until we have received a complete packet. */
1425 /* Try to read a packet from the buffer. */
1426 r = ssh_packet_read_poll_seqnr(ssh, typep, seqnr_p);
1430 *typep == SSH_SMSG_SUCCESS
1431 || *typep == SSH_SMSG_FAILURE
1432 || *typep == SSH_CMSG_EOF
1433 || *typep == SSH_CMSG_EXIT_CONFIRMATION))
1434 if ((r = sshpkt_get_end(ssh)) != 0)
1436 /* If we got a packet, return it. */
1437 if (*typep != SSH_MSG_NONE)
1440 * Otherwise, wait for some data to arrive, add it to the
1441 * buffer, and try again.
1443 memset(setp, 0, howmany(state->connection_in + 1,
1444 NFDBITS) * sizeof(fd_mask));
1445 FD_SET(state->connection_in, setp);
1447 if (state->packet_timeout_ms > 0) {
1448 ms_remain = state->packet_timeout_ms;
1449 timeoutp = &timeout;
1451 /* Wait for some data to arrive. */
1453 if (state->packet_timeout_ms != -1) {
1454 ms_to_timeval(&timeout, ms_remain);
1455 gettimeofday(&start, NULL);
1457 if ((r = select(state->connection_in + 1, setp,
1458 NULL, NULL, timeoutp)) >= 0)
1460 if (errno != EAGAIN && errno != EINTR &&
1461 errno != EWOULDBLOCK)
1463 if (state->packet_timeout_ms == -1)
1465 ms_subtract_diff(&start, &ms_remain);
1466 if (ms_remain <= 0) {
1472 r = SSH_ERR_CONN_TIMEOUT;
1475 /* Read data from the socket. */
1476 len = read(state->connection_in, buf, sizeof(buf));
1478 r = SSH_ERR_CONN_CLOSED;
1482 r = SSH_ERR_SYSTEM_ERROR;
1486 /* Append it to the buffer. */
1487 if ((r = ssh_packet_process_incoming(ssh, buf, len)) != 0)
1496 ssh_packet_read(struct ssh *ssh)
1501 if ((r = ssh_packet_read_seqnr(ssh, &type, NULL)) != 0)
1502 fatal("%s: %s", __func__, ssh_err(r));
1507 * Waits until a packet has been received, verifies that its type matches
1508 * that given, and gives a fatal error and exits if there is a mismatch.
1512 ssh_packet_read_expect(struct ssh *ssh, u_int expected_type)
1517 if ((r = ssh_packet_read_seqnr(ssh, &type, NULL)) != 0)
1519 if (type != expected_type) {
1520 if ((r = sshpkt_disconnect(ssh,
1521 "Protocol error: expected packet type %d, got %d",
1522 expected_type, type)) != 0)
1524 return SSH_ERR_PROTOCOL_ERROR;
1529 /* Checks if a full packet is available in the data received so far via
1530 * packet_process_incoming. If so, reads the packet; otherwise returns
1531 * SSH_MSG_NONE. This does not wait for data from the connection.
1533 * SSH_MSG_DISCONNECT is handled specially here. Also,
1534 * SSH_MSG_IGNORE messages are skipped by this function and are never returned
1539 ssh_packet_read_poll1(struct ssh *ssh, u_char *typep)
1541 struct session_state *state = ssh->state;
1542 u_int len, padded_len;
1546 u_int checksum, stored_checksum;
1549 *typep = SSH_MSG_NONE;
1551 /* Check if input size is less than minimum packet size. */
1552 if (sshbuf_len(state->input) < 4 + 8)
1554 /* Get length of incoming packet. */
1555 len = PEEK_U32(sshbuf_ptr(state->input));
1556 if (len < 1 + 2 + 2 || len > 256 * 1024) {
1557 if ((r = sshpkt_disconnect(ssh, "Bad packet length %u",
1560 return SSH_ERR_CONN_CORRUPT;
1562 padded_len = (len + 8) & ~7;
1564 /* Check if the packet has been entirely received. */
1565 if (sshbuf_len(state->input) < 4 + padded_len)
1568 /* The entire packet is in buffer. */
1570 /* Consume packet length. */
1571 if ((r = sshbuf_consume(state->input, 4)) != 0)
1575 * Cryptographic attack detector for ssh
1576 * (C)1998 CORE-SDI, Buenos Aires Argentina
1577 * Ariel Futoransky(futo@core-sdi.com)
1579 if (!cipher_ctx_is_plaintext(state->receive_context)) {
1581 switch (detect_attack(&state->deattack,
1582 sshbuf_ptr(state->input), padded_len)) {
1585 case DEATTACK_DETECTED:
1586 emsg = "crc32 compensation attack detected";
1588 case DEATTACK_DOS_DETECTED:
1589 emsg = "deattack denial of service detected";
1592 emsg = "deattack error";
1597 if ((r = sshpkt_disconnect(ssh, "%s", emsg)) != 0 ||
1598 (r = ssh_packet_write_wait(ssh)) != 0)
1600 return SSH_ERR_CONN_CORRUPT;
1604 /* Decrypt data to incoming_packet. */
1605 sshbuf_reset(state->incoming_packet);
1606 if ((r = sshbuf_reserve(state->incoming_packet, padded_len, &p)) != 0)
1608 if ((r = cipher_crypt(state->receive_context, 0, p,
1609 sshbuf_ptr(state->input), padded_len, 0, 0)) != 0)
1612 if ((r = sshbuf_consume(state->input, padded_len)) != 0)
1616 fprintf(stderr, "read_poll plain: ");
1617 sshbuf_dump(state->incoming_packet, stderr);
1620 /* Compute packet checksum. */
1621 checksum = ssh_crc32(sshbuf_ptr(state->incoming_packet),
1622 sshbuf_len(state->incoming_packet) - 4);
1625 if ((r = sshbuf_consume(state->incoming_packet, 8 - len % 8)) != 0)
1628 /* Test check bytes. */
1629 if (len != sshbuf_len(state->incoming_packet)) {
1630 error("%s: len %d != sshbuf_len %zd", __func__,
1631 len, sshbuf_len(state->incoming_packet));
1632 if ((r = sshpkt_disconnect(ssh, "invalid packet length")) != 0 ||
1633 (r = ssh_packet_write_wait(ssh)) != 0)
1635 return SSH_ERR_CONN_CORRUPT;
1638 cp = sshbuf_ptr(state->incoming_packet) + len - 4;
1639 stored_checksum = PEEK_U32(cp);
1640 if (checksum != stored_checksum) {
1641 error("Corrupted check bytes on input");
1642 if ((r = sshpkt_disconnect(ssh, "connection corrupted")) != 0 ||
1643 (r = ssh_packet_write_wait(ssh)) != 0)
1645 return SSH_ERR_CONN_CORRUPT;
1647 if ((r = sshbuf_consume_end(state->incoming_packet, 4)) < 0)
1650 if (state->packet_compression) {
1651 sshbuf_reset(state->compression_buffer);
1652 if ((r = uncompress_buffer(ssh, state->incoming_packet,
1653 state->compression_buffer)) != 0)
1655 sshbuf_reset(state->incoming_packet);
1656 if ((r = sshbuf_putb(state->incoming_packet,
1657 state->compression_buffer)) != 0)
1660 state->p_read.packets++;
1661 state->p_read.bytes += padded_len + 4;
1662 if ((r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
1664 if (*typep < SSH_MSG_MIN || *typep > SSH_MSG_MAX) {
1665 error("Invalid ssh1 packet type: %d", *typep);
1666 if ((r = sshpkt_disconnect(ssh, "invalid packet type")) != 0 ||
1667 (r = ssh_packet_write_wait(ssh)) != 0)
1669 return SSH_ERR_PROTOCOL_ERROR;
1677 ssh_packet_read_poll2_mux(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1679 struct session_state *state = ssh->state;
1685 return SSH_ERR_INTERNAL_ERROR;
1686 *typep = SSH_MSG_NONE;
1687 cp = sshbuf_ptr(state->input);
1688 if (state->packlen == 0) {
1689 if (sshbuf_len(state->input) < 4 + 1)
1690 return 0; /* packet is incomplete */
1691 state->packlen = PEEK_U32(cp);
1692 if (state->packlen < 4 + 1 ||
1693 state->packlen > PACKET_MAX_SIZE)
1694 return SSH_ERR_MESSAGE_INCOMPLETE;
1696 need = state->packlen + 4;
1697 if (sshbuf_len(state->input) < need)
1698 return 0; /* packet is incomplete */
1699 sshbuf_reset(state->incoming_packet);
1700 if ((r = sshbuf_put(state->incoming_packet, cp + 4,
1701 state->packlen)) != 0 ||
1702 (r = sshbuf_consume(state->input, need)) != 0 ||
1703 (r = sshbuf_get_u8(state->incoming_packet, NULL)) != 0 ||
1704 (r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
1706 if (ssh_packet_log_type(*typep))
1707 debug3("%s: type %u", __func__, *typep);
1708 /* sshbuf_dump(state->incoming_packet, stderr); */
1709 /* reset for next packet */
1715 ssh_packet_read_poll2(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1717 struct session_state *state = ssh->state;
1720 u_int maclen, aadlen = 0, authlen = 0, block_size;
1721 struct sshenc *enc = NULL;
1722 struct sshmac *mac = NULL;
1723 struct sshcomp *comp = NULL;
1727 return ssh_packet_read_poll2_mux(ssh, typep, seqnr_p);
1729 *typep = SSH_MSG_NONE;
1731 if (state->packet_discard)
1734 if (state->newkeys[MODE_IN] != NULL) {
1735 enc = &state->newkeys[MODE_IN]->enc;
1736 mac = &state->newkeys[MODE_IN]->mac;
1737 comp = &state->newkeys[MODE_IN]->comp;
1738 /* disable mac for authenticated encryption */
1739 if ((authlen = cipher_authlen(enc->cipher)) != 0)
1742 maclen = mac && mac->enabled ? mac->mac_len : 0;
1743 block_size = enc ? enc->block_size : 8;
1744 aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
1746 if (aadlen && state->packlen == 0) {
1747 if (cipher_get_length(state->receive_context,
1748 &state->packlen, state->p_read.seqnr,
1749 sshbuf_ptr(state->input), sshbuf_len(state->input)) != 0)
1751 if (state->packlen < 1 + 4 ||
1752 state->packlen > PACKET_MAX_SIZE) {
1754 sshbuf_dump(state->input, stderr);
1756 logit("Bad packet length %u.", state->packlen);
1757 if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0)
1759 return SSH_ERR_CONN_CORRUPT;
1761 sshbuf_reset(state->incoming_packet);
1762 } else if (state->packlen == 0) {
1764 * check if input size is less than the cipher block size,
1765 * decrypt first block and extract length of incoming packet
1767 if (sshbuf_len(state->input) < block_size)
1769 sshbuf_reset(state->incoming_packet);
1770 if ((r = sshbuf_reserve(state->incoming_packet, block_size,
1773 if ((r = cipher_crypt(state->receive_context,
1774 state->p_send.seqnr, cp, sshbuf_ptr(state->input),
1775 block_size, 0, 0)) != 0)
1777 state->packlen = PEEK_U32(sshbuf_ptr(state->incoming_packet));
1778 if (state->packlen < 1 + 4 ||
1779 state->packlen > PACKET_MAX_SIZE) {
1781 fprintf(stderr, "input: \n");
1782 sshbuf_dump(state->input, stderr);
1783 fprintf(stderr, "incoming_packet: \n");
1784 sshbuf_dump(state->incoming_packet, stderr);
1786 logit("Bad packet length %u.", state->packlen);
1787 return ssh_packet_start_discard(ssh, enc, mac, 0,
1790 if ((r = sshbuf_consume(state->input, block_size)) != 0)
1793 DBG(debug("input: packet len %u", state->packlen+4));
1796 /* only the payload is encrypted */
1797 need = state->packlen;
1800 * the payload size and the payload are encrypted, but we
1801 * have a partial packet of block_size bytes
1803 need = 4 + state->packlen - block_size;
1805 DBG(debug("partial packet: block %d, need %d, maclen %d, authlen %d,"
1806 " aadlen %d", block_size, need, maclen, authlen, aadlen));
1807 if (need % block_size != 0) {
1808 logit("padding error: need %d block %d mod %d",
1809 need, block_size, need % block_size);
1810 return ssh_packet_start_discard(ssh, enc, mac, 0,
1811 PACKET_MAX_SIZE - block_size);
1814 * check if the entire packet has been received and
1815 * decrypt into incoming_packet:
1816 * 'aadlen' bytes are unencrypted, but authenticated.
1817 * 'need' bytes are encrypted, followed by either
1818 * 'authlen' bytes of authentication tag or
1819 * 'maclen' bytes of message authentication code.
1821 if (sshbuf_len(state->input) < aadlen + need + authlen + maclen)
1822 return 0; /* packet is incomplete */
1824 fprintf(stderr, "read_poll enc/full: ");
1825 sshbuf_dump(state->input, stderr);
1827 /* EtM: check mac over encrypted input */
1828 if (mac && mac->enabled && mac->etm) {
1829 if ((r = mac_check(mac, state->p_read.seqnr,
1830 sshbuf_ptr(state->input), aadlen + need,
1831 sshbuf_ptr(state->input) + aadlen + need + authlen,
1833 if (r == SSH_ERR_MAC_INVALID)
1834 logit("Corrupted MAC on input.");
1838 if ((r = sshbuf_reserve(state->incoming_packet, aadlen + need,
1841 if ((r = cipher_crypt(state->receive_context, state->p_read.seqnr, cp,
1842 sshbuf_ptr(state->input), need, aadlen, authlen)) != 0)
1844 if ((r = sshbuf_consume(state->input, aadlen + need + authlen)) != 0)
1846 if (mac && mac->enabled) {
1847 /* Not EtM: check MAC over cleartext */
1848 if (!mac->etm && (r = mac_check(mac, state->p_read.seqnr,
1849 sshbuf_ptr(state->incoming_packet),
1850 sshbuf_len(state->incoming_packet),
1851 sshbuf_ptr(state->input), maclen)) != 0) {
1852 if (r != SSH_ERR_MAC_INVALID)
1854 logit("Corrupted MAC on input.");
1855 if (need + block_size > PACKET_MAX_SIZE)
1856 return SSH_ERR_INTERNAL_ERROR;
1857 return ssh_packet_start_discard(ssh, enc, mac,
1858 sshbuf_len(state->incoming_packet),
1859 PACKET_MAX_SIZE - need - block_size);
1861 /* Remove MAC from input buffer */
1862 DBG(debug("MAC #%d ok", state->p_read.seqnr));
1863 if ((r = sshbuf_consume(state->input, mac->mac_len)) != 0)
1866 if (seqnr_p != NULL)
1867 *seqnr_p = state->p_read.seqnr;
1868 if (++state->p_read.seqnr == 0)
1869 logit("incoming seqnr wraps around");
1870 if (++state->p_read.packets == 0)
1871 if (!(ssh->compat & SSH_BUG_NOREKEY))
1872 return SSH_ERR_NEED_REKEY;
1873 state->p_read.blocks += (state->packlen + 4) / block_size;
1874 state->p_read.bytes += state->packlen + 4;
1877 padlen = sshbuf_ptr(state->incoming_packet)[4];
1878 DBG(debug("input: padlen %d", padlen));
1880 if ((r = sshpkt_disconnect(ssh,
1881 "Corrupted padlen %d on input.", padlen)) != 0 ||
1882 (r = ssh_packet_write_wait(ssh)) != 0)
1884 return SSH_ERR_CONN_CORRUPT;
1887 /* skip packet size + padlen, discard padding */
1888 if ((r = sshbuf_consume(state->incoming_packet, 4 + 1)) != 0 ||
1889 ((r = sshbuf_consume_end(state->incoming_packet, padlen)) != 0))
1892 DBG(debug("input: len before de-compress %zd",
1893 sshbuf_len(state->incoming_packet)));
1894 if (comp && comp->enabled) {
1895 sshbuf_reset(state->compression_buffer);
1896 if ((r = uncompress_buffer(ssh, state->incoming_packet,
1897 state->compression_buffer)) != 0)
1899 sshbuf_reset(state->incoming_packet);
1900 if ((r = sshbuf_putb(state->incoming_packet,
1901 state->compression_buffer)) != 0)
1903 DBG(debug("input: len after de-compress %zd",
1904 sshbuf_len(state->incoming_packet)));
1907 * get packet type, implies consume.
1908 * return length of payload (without type field)
1910 if ((r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
1912 if (ssh_packet_log_type(*typep))
1913 debug3("receive packet: type %u", *typep);
1914 if (*typep < SSH2_MSG_MIN || *typep >= SSH2_MSG_LOCAL_MIN) {
1915 if ((r = sshpkt_disconnect(ssh,
1916 "Invalid ssh2 packet type: %d", *typep)) != 0 ||
1917 (r = ssh_packet_write_wait(ssh)) != 0)
1919 return SSH_ERR_PROTOCOL_ERROR;
1921 if (state->hook_in != NULL &&
1922 (r = state->hook_in(ssh, state->incoming_packet, typep,
1923 state->hook_in_ctx)) != 0)
1925 if (*typep == SSH2_MSG_USERAUTH_SUCCESS && !state->server_side)
1926 r = ssh_packet_enable_delayed_compress(ssh);
1930 fprintf(stderr, "read/plain[%d]:\r\n", *typep);
1931 sshbuf_dump(state->incoming_packet, stderr);
1933 /* reset for next packet */
1936 /* do we need to rekey? */
1937 if (ssh_packet_need_rekeying(ssh, 0)) {
1938 debug3("%s: rekex triggered", __func__);
1939 if ((r = kex_start_rekex(ssh)) != 0)
1947 ssh_packet_read_poll_seqnr(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1949 struct session_state *state = ssh->state;
1950 u_int reason, seqnr;
1957 r = ssh_packet_read_poll2(ssh, typep, seqnr_p);
1961 state->keep_alive_timeouts = 0;
1962 DBG(debug("received packet type %d", *typep));
1965 case SSH2_MSG_IGNORE:
1966 debug3("Received SSH2_MSG_IGNORE");
1968 case SSH2_MSG_DEBUG:
1969 if ((r = sshpkt_get_u8(ssh, NULL)) != 0 ||
1970 (r = sshpkt_get_string(ssh, &msg, NULL)) != 0 ||
1971 (r = sshpkt_get_string(ssh, NULL, NULL)) != 0) {
1975 debug("Remote: %.900s", msg);
1978 case SSH2_MSG_DISCONNECT:
1979 if ((r = sshpkt_get_u32(ssh, &reason)) != 0 ||
1980 (r = sshpkt_get_string(ssh, &msg, NULL)) != 0)
1982 /* Ignore normal client exit notifications */
1983 do_log2(ssh->state->server_side &&
1984 reason == SSH2_DISCONNECT_BY_APPLICATION ?
1985 SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_ERROR,
1986 "Received disconnect from %s port %d:"
1987 "%u: %.400s", ssh_remote_ipaddr(ssh),
1988 ssh_remote_port(ssh), reason, msg);
1990 return SSH_ERR_DISCONNECTED;
1991 case SSH2_MSG_UNIMPLEMENTED:
1992 if ((r = sshpkt_get_u32(ssh, &seqnr)) != 0)
1994 debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
2001 r = ssh_packet_read_poll1(ssh, typep);
2004 return SSH_MSG_NONE;
2005 case SSH_MSG_IGNORE:
2008 if ((r = sshpkt_get_string(ssh, &msg, NULL)) != 0)
2010 debug("Remote: %.900s", msg);
2013 case SSH_MSG_DISCONNECT:
2014 if ((r = sshpkt_get_string(ssh, &msg, NULL)) != 0)
2016 logit("Received disconnect from %s port %d: "
2017 "%.400s", ssh_remote_ipaddr(ssh),
2018 ssh_remote_port(ssh), msg);
2020 return SSH_ERR_DISCONNECTED;
2022 DBG(debug("received packet type %d", *typep));
2030 * Buffers the given amount of input characters. This is intended to be used
2031 * together with packet_read_poll.
2035 ssh_packet_process_incoming(struct ssh *ssh, const char *buf, u_int len)
2037 struct session_state *state = ssh->state;
2040 if (state->packet_discard) {
2041 state->keep_alive_timeouts = 0; /* ?? */
2042 if (len >= state->packet_discard) {
2043 if ((r = ssh_packet_stop_discard(ssh)) != 0)
2046 state->packet_discard -= len;
2049 if ((r = sshbuf_put(ssh->state->input, buf, len)) != 0)
2056 ssh_packet_remaining(struct ssh *ssh)
2058 return sshbuf_len(ssh->state->incoming_packet);
2062 * Sends a diagnostic message from the server to the client. This message
2063 * can be sent at any time (but not while constructing another message). The
2064 * message is printed immediately, but only if the client is being executed
2065 * in verbose mode. These messages are primarily intended to ease debugging
2066 * authentication problems. The length of the formatted message must not
2067 * exceed 1024 bytes. This will automatically call ssh_packet_write_wait.
2070 ssh_packet_send_debug(struct ssh *ssh, const char *fmt,...)
2076 if (compat20 && (ssh->compat & SSH_BUG_DEBUG))
2079 va_start(args, fmt);
2080 vsnprintf(buf, sizeof(buf), fmt, args);
2084 if ((r = sshpkt_start(ssh, SSH2_MSG_DEBUG)) != 0 ||
2085 (r = sshpkt_put_u8(ssh, 0)) != 0 || /* always display */
2086 (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
2087 (r = sshpkt_put_cstring(ssh, "")) != 0 ||
2088 (r = sshpkt_send(ssh)) != 0)
2089 fatal("%s: %s", __func__, ssh_err(r));
2091 if ((r = sshpkt_start(ssh, SSH_MSG_DEBUG)) != 0 ||
2092 (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
2093 (r = sshpkt_send(ssh)) != 0)
2094 fatal("%s: %s", __func__, ssh_err(r));
2096 if ((r = ssh_packet_write_wait(ssh)) != 0)
2097 fatal("%s: %s", __func__, ssh_err(r));
2101 fmt_connection_id(struct ssh *ssh, char *s, size_t l)
2103 snprintf(s, l, "%.200s%s%s port %d",
2104 ssh->log_preamble ? ssh->log_preamble : "",
2105 ssh->log_preamble ? " " : "",
2106 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
2110 * Pretty-print connection-terminating errors and exit.
2113 sshpkt_fatal(struct ssh *ssh, const char *tag, int r)
2115 char remote_id[512];
2117 fmt_connection_id(ssh, remote_id, sizeof(remote_id));
2120 case SSH_ERR_CONN_CLOSED:
2121 logdie("Connection closed by %s", remote_id);
2122 case SSH_ERR_CONN_TIMEOUT:
2123 logdie("Connection %s %s timed out",
2124 ssh->state->server_side ? "from" : "to", remote_id);
2125 case SSH_ERR_DISCONNECTED:
2126 logdie("Disconnected from %s", remote_id);
2127 case SSH_ERR_SYSTEM_ERROR:
2128 if (errno == ECONNRESET)
2129 logdie("Connection reset by %s", remote_id);
2131 case SSH_ERR_NO_CIPHER_ALG_MATCH:
2132 case SSH_ERR_NO_MAC_ALG_MATCH:
2133 case SSH_ERR_NO_COMPRESS_ALG_MATCH:
2134 case SSH_ERR_NO_KEX_ALG_MATCH:
2135 case SSH_ERR_NO_HOSTKEY_ALG_MATCH:
2136 if (ssh && ssh->kex && ssh->kex->failed_choice) {
2137 BLACKLIST_NOTIFY(BLACKLIST_AUTH_FAIL, "ssh");
2138 logdie("Unable to negotiate with %s: %s. "
2139 "Their offer: %s", remote_id, ssh_err(r),
2140 ssh->kex->failed_choice);
2144 logdie("%s%sConnection %s %s: %s",
2145 tag != NULL ? tag : "", tag != NULL ? ": " : "",
2146 ssh->state->server_side ? "from" : "to",
2147 remote_id, ssh_err(r));
2152 * Logs the error plus constructs and sends a disconnect packet, closes the
2153 * connection, and exits. This function never returns. The error message
2154 * should not contain a newline. The length of the formatted message must
2155 * not exceed 1024 bytes.
2158 ssh_packet_disconnect(struct ssh *ssh, const char *fmt,...)
2160 char buf[1024], remote_id[512];
2162 static int disconnecting = 0;
2165 if (disconnecting) /* Guard against recursive invocations. */
2166 fatal("packet_disconnect called recursively.");
2170 * Format the message. Note that the caller must make sure the
2171 * message is of limited size.
2173 fmt_connection_id(ssh, remote_id, sizeof(remote_id));
2174 va_start(args, fmt);
2175 vsnprintf(buf, sizeof(buf), fmt, args);
2178 /* Display the error locally */
2179 logit("Disconnecting %s: %.100s", remote_id, buf);
2182 * Send the disconnect message to the other side, and wait
2183 * for it to get sent.
2185 if ((r = sshpkt_disconnect(ssh, "%s", buf)) != 0)
2186 sshpkt_fatal(ssh, __func__, r);
2188 if ((r = ssh_packet_write_wait(ssh)) != 0)
2189 sshpkt_fatal(ssh, __func__, r);
2191 /* Close the connection. */
2192 ssh_packet_close(ssh);
2197 * Checks if there is any buffered output, and tries to write some of
2201 ssh_packet_write_poll(struct ssh *ssh)
2203 struct session_state *state = ssh->state;
2204 int len = sshbuf_len(state->output);
2208 len = write(state->connection_out,
2209 sshbuf_ptr(state->output), len);
2211 if (errno == EINTR || errno == EAGAIN ||
2212 errno == EWOULDBLOCK)
2214 return SSH_ERR_SYSTEM_ERROR;
2217 return SSH_ERR_CONN_CLOSED;
2218 if ((r = sshbuf_consume(state->output, len)) != 0)
2225 * Calls packet_write_poll repeatedly until all pending output data has been
2229 ssh_packet_write_wait(struct ssh *ssh)
2232 int ret, r, ms_remain = 0;
2233 struct timeval start, timeout, *timeoutp = NULL;
2234 struct session_state *state = ssh->state;
2236 setp = calloc(howmany(state->connection_out + 1,
2237 NFDBITS), sizeof(fd_mask));
2239 return SSH_ERR_ALLOC_FAIL;
2240 if ((r = ssh_packet_write_poll(ssh)) != 0) {
2244 while (ssh_packet_have_data_to_write(ssh)) {
2245 memset(setp, 0, howmany(state->connection_out + 1,
2246 NFDBITS) * sizeof(fd_mask));
2247 FD_SET(state->connection_out, setp);
2249 if (state->packet_timeout_ms > 0) {
2250 ms_remain = state->packet_timeout_ms;
2251 timeoutp = &timeout;
2254 if (state->packet_timeout_ms != -1) {
2255 ms_to_timeval(&timeout, ms_remain);
2256 gettimeofday(&start, NULL);
2258 if ((ret = select(state->connection_out + 1,
2259 NULL, setp, NULL, timeoutp)) >= 0)
2261 if (errno != EAGAIN && errno != EINTR &&
2262 errno != EWOULDBLOCK)
2264 if (state->packet_timeout_ms == -1)
2266 ms_subtract_diff(&start, &ms_remain);
2267 if (ms_remain <= 0) {
2274 return SSH_ERR_CONN_TIMEOUT;
2276 if ((r = ssh_packet_write_poll(ssh)) != 0) {
2285 /* Returns true if there is buffered data to write to the connection. */
2288 ssh_packet_have_data_to_write(struct ssh *ssh)
2290 return sshbuf_len(ssh->state->output) != 0;
2293 /* Returns true if there is not too much data to write to the connection. */
2296 ssh_packet_not_very_much_data_to_write(struct ssh *ssh)
2298 if (ssh->state->interactive_mode)
2299 return sshbuf_len(ssh->state->output) < 16384;
2301 return sshbuf_len(ssh->state->output) < 128 * 1024;
2305 ssh_packet_set_tos(struct ssh *ssh, int tos)
2307 #ifndef IP_TOS_IS_BROKEN
2308 if (!ssh_packet_connection_is_on_socket(ssh))
2310 switch (ssh_packet_connection_af(ssh)) {
2313 debug3("%s: set IP_TOS 0x%02x", __func__, tos);
2314 if (setsockopt(ssh->state->connection_in,
2315 IPPROTO_IP, IP_TOS, &tos, sizeof(tos)) < 0)
2316 error("setsockopt IP_TOS %d: %.100s:",
2317 tos, strerror(errno));
2319 # endif /* IP_TOS */
2322 debug3("%s: set IPV6_TCLASS 0x%02x", __func__, tos);
2323 if (setsockopt(ssh->state->connection_in,
2324 IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof(tos)) < 0)
2325 error("setsockopt IPV6_TCLASS %d: %.100s:",
2326 tos, strerror(errno));
2328 # endif /* IPV6_TCLASS */
2330 #endif /* IP_TOS_IS_BROKEN */
2333 /* Informs that the current session is interactive. Sets IP flags for that. */
2336 ssh_packet_set_interactive(struct ssh *ssh, int interactive, int qos_interactive, int qos_bulk)
2338 struct session_state *state = ssh->state;
2340 if (state->set_interactive_called)
2342 state->set_interactive_called = 1;
2344 /* Record that we are in interactive mode. */
2345 state->interactive_mode = interactive;
2347 /* Only set socket options if using a socket. */
2348 if (!ssh_packet_connection_is_on_socket(ssh))
2350 set_nodelay(state->connection_in);
2351 ssh_packet_set_tos(ssh, interactive ? qos_interactive :
2355 /* Returns true if the current connection is interactive. */
2358 ssh_packet_is_interactive(struct ssh *ssh)
2360 return ssh->state->interactive_mode;
2364 ssh_packet_set_maxsize(struct ssh *ssh, u_int s)
2366 struct session_state *state = ssh->state;
2368 if (state->set_maxsize_called) {
2369 logit("packet_set_maxsize: called twice: old %d new %d",
2370 state->max_packet_size, s);
2373 if (s < 4 * 1024 || s > 1024 * 1024) {
2374 logit("packet_set_maxsize: bad size %d", s);
2377 state->set_maxsize_called = 1;
2378 debug("packet_set_maxsize: setting to %d", s);
2379 state->max_packet_size = s;
2384 ssh_packet_inc_alive_timeouts(struct ssh *ssh)
2386 return ++ssh->state->keep_alive_timeouts;
2390 ssh_packet_set_alive_timeouts(struct ssh *ssh, int ka)
2392 ssh->state->keep_alive_timeouts = ka;
2396 ssh_packet_get_maxsize(struct ssh *ssh)
2398 return ssh->state->max_packet_size;
2402 * 9.2. Ignored Data Message
2404 * byte SSH_MSG_IGNORE
2407 * All implementations MUST understand (and ignore) this message at any
2408 * time (after receiving the protocol version). No implementation is
2409 * required to send them. This message can be used as an additional
2410 * protection measure against advanced traffic analysis techniques.
2413 ssh_packet_send_ignore(struct ssh *ssh, int nbytes)
2418 if ((r = sshpkt_start(ssh, compat20 ?
2419 SSH2_MSG_IGNORE : SSH_MSG_IGNORE)) != 0 ||
2420 (r = sshpkt_put_u32(ssh, nbytes)) != 0)
2421 fatal("%s: %s", __func__, ssh_err(r));
2422 for (i = 0; i < nbytes; i++) {
2425 if ((r = sshpkt_put_u8(ssh, (u_char)rnd & 0xff)) != 0)
2426 fatal("%s: %s", __func__, ssh_err(r));
2432 ssh_packet_set_rekey_limits(struct ssh *ssh, u_int64_t bytes, u_int32_t seconds)
2434 debug3("rekey after %llu bytes, %u seconds", (unsigned long long)bytes,
2435 (unsigned int)seconds);
2436 ssh->state->rekey_limit = bytes;
2437 ssh->state->rekey_interval = seconds;
2441 ssh_packet_get_rekey_timeout(struct ssh *ssh)
2445 seconds = ssh->state->rekey_time + ssh->state->rekey_interval -
2447 return (seconds <= 0 ? 1 : seconds);
2451 ssh_packet_set_server(struct ssh *ssh)
2453 ssh->state->server_side = 1;
2457 ssh_packet_set_authenticated(struct ssh *ssh)
2459 ssh->state->after_authentication = 1;
2463 ssh_packet_get_input(struct ssh *ssh)
2465 return (void *)ssh->state->input;
2469 ssh_packet_get_output(struct ssh *ssh)
2471 return (void *)ssh->state->output;
2474 /* Reset after_authentication and reset compression in post-auth privsep */
2476 ssh_packet_set_postauth(struct ssh *ssh)
2480 debug("%s: called", __func__);
2481 /* This was set in net child, but is not visible in user child */
2482 ssh->state->after_authentication = 1;
2483 ssh->state->rekeying = 0;
2484 if ((r = ssh_packet_enable_delayed_compress(ssh)) != 0)
2489 /* Packet state (de-)serialization for privsep */
2491 /* turn kex into a blob for packet state serialization */
2493 kex_to_blob(struct sshbuf *m, struct kex *kex)
2497 if ((r = sshbuf_put_string(m, kex->session_id,
2498 kex->session_id_len)) != 0 ||
2499 (r = sshbuf_put_u32(m, kex->we_need)) != 0 ||
2500 (r = sshbuf_put_u32(m, kex->hostkey_type)) != 0 ||
2501 (r = sshbuf_put_u32(m, kex->kex_type)) != 0 ||
2502 (r = sshbuf_put_stringb(m, kex->my)) != 0 ||
2503 (r = sshbuf_put_stringb(m, kex->peer)) != 0 ||
2504 (r = sshbuf_put_u32(m, kex->flags)) != 0 ||
2505 (r = sshbuf_put_cstring(m, kex->client_version_string)) != 0 ||
2506 (r = sshbuf_put_cstring(m, kex->server_version_string)) != 0)
2511 /* turn key exchange results into a blob for packet state serialization */
2513 newkeys_to_blob(struct sshbuf *m, struct ssh *ssh, int mode)
2516 struct sshcipher_ctx *cc;
2517 struct sshcomp *comp;
2520 struct newkeys *newkey;
2523 if ((newkey = ssh->state->newkeys[mode]) == NULL)
2524 return SSH_ERR_INTERNAL_ERROR;
2527 comp = &newkey->comp;
2528 cc = (mode == MODE_OUT) ? ssh->state->send_context :
2529 ssh->state->receive_context;
2530 if ((r = cipher_get_keyiv(cc, enc->iv, enc->iv_len)) != 0)
2532 if ((b = sshbuf_new()) == NULL)
2533 return SSH_ERR_ALLOC_FAIL;
2534 /* The cipher struct is constant and shared, you export pointer */
2535 if ((r = sshbuf_put_cstring(b, enc->name)) != 0 ||
2536 (r = sshbuf_put(b, &enc->cipher, sizeof(enc->cipher))) != 0 ||
2537 (r = sshbuf_put_u32(b, enc->enabled)) != 0 ||
2538 (r = sshbuf_put_u32(b, enc->block_size)) != 0 ||
2539 (r = sshbuf_put_string(b, enc->key, enc->key_len)) != 0 ||
2540 (r = sshbuf_put_string(b, enc->iv, enc->iv_len)) != 0)
2542 if (cipher_authlen(enc->cipher) == 0) {
2543 if ((r = sshbuf_put_cstring(b, mac->name)) != 0 ||
2544 (r = sshbuf_put_u32(b, mac->enabled)) != 0 ||
2545 (r = sshbuf_put_string(b, mac->key, mac->key_len)) != 0)
2548 if ((r = sshbuf_put_u32(b, comp->type)) != 0 ||
2549 (r = sshbuf_put_cstring(b, comp->name)) != 0)
2551 r = sshbuf_put_stringb(m, b);
2557 /* serialize packet state into a blob */
2559 ssh_packet_get_state(struct ssh *ssh, struct sshbuf *m)
2561 struct session_state *state = ssh->state;
2567 ssh1cipher = cipher_ctx_get_number(state->receive_context);
2568 slen = cipher_get_keyiv_len(state->send_context);
2569 rlen = cipher_get_keyiv_len(state->receive_context);
2570 if ((r = sshbuf_put_u32(m, state->remote_protocol_flags)) != 0 ||
2571 (r = sshbuf_put_u32(m, ssh1cipher)) != 0 ||
2572 (r = sshbuf_put_string(m, state->ssh1_key, state->ssh1_keylen)) != 0 ||
2573 (r = sshbuf_put_u32(m, slen)) != 0 ||
2574 (r = sshbuf_reserve(m, slen, &p)) != 0 ||
2575 (r = cipher_get_keyiv(state->send_context, p, slen)) != 0 ||
2576 (r = sshbuf_put_u32(m, rlen)) != 0 ||
2577 (r = sshbuf_reserve(m, rlen, &p)) != 0 ||
2578 (r = cipher_get_keyiv(state->receive_context, p, rlen)) != 0)
2581 if ((r = kex_to_blob(m, ssh->kex)) != 0 ||
2582 (r = newkeys_to_blob(m, ssh, MODE_OUT)) != 0 ||
2583 (r = newkeys_to_blob(m, ssh, MODE_IN)) != 0 ||
2584 (r = sshbuf_put_u64(m, state->rekey_limit)) != 0 ||
2585 (r = sshbuf_put_u32(m, state->rekey_interval)) != 0 ||
2586 (r = sshbuf_put_u32(m, state->p_send.seqnr)) != 0 ||
2587 (r = sshbuf_put_u64(m, state->p_send.blocks)) != 0 ||
2588 (r = sshbuf_put_u32(m, state->p_send.packets)) != 0 ||
2589 (r = sshbuf_put_u64(m, state->p_send.bytes)) != 0 ||
2590 (r = sshbuf_put_u32(m, state->p_read.seqnr)) != 0 ||
2591 (r = sshbuf_put_u64(m, state->p_read.blocks)) != 0 ||
2592 (r = sshbuf_put_u32(m, state->p_read.packets)) != 0 ||
2593 (r = sshbuf_put_u64(m, state->p_read.bytes)) != 0)
2597 slen = cipher_get_keycontext(state->send_context, NULL);
2598 rlen = cipher_get_keycontext(state->receive_context, NULL);
2599 if ((r = sshbuf_put_u32(m, slen)) != 0 ||
2600 (r = sshbuf_reserve(m, slen, &p)) != 0)
2602 if (cipher_get_keycontext(state->send_context, p) != (int)slen)
2603 return SSH_ERR_INTERNAL_ERROR;
2604 if ((r = sshbuf_put_u32(m, rlen)) != 0 ||
2605 (r = sshbuf_reserve(m, rlen, &p)) != 0)
2607 if (cipher_get_keycontext(state->receive_context, p) != (int)rlen)
2608 return SSH_ERR_INTERNAL_ERROR;
2609 if ((r = sshbuf_put_stringb(m, state->input)) != 0 ||
2610 (r = sshbuf_put_stringb(m, state->output)) != 0)
2616 /* restore key exchange results from blob for packet state de-serialization */
2618 newkeys_from_blob(struct sshbuf *m, struct ssh *ssh, int mode)
2620 struct sshbuf *b = NULL;
2621 struct sshcomp *comp;
2624 struct newkeys *newkey = NULL;
2625 size_t keylen, ivlen, maclen;
2628 if ((newkey = calloc(1, sizeof(*newkey))) == NULL) {
2629 r = SSH_ERR_ALLOC_FAIL;
2632 if ((r = sshbuf_froms(m, &b)) != 0)
2635 sshbuf_dump(b, stderr);
2639 comp = &newkey->comp;
2641 if ((r = sshbuf_get_cstring(b, &enc->name, NULL)) != 0 ||
2642 (r = sshbuf_get(b, &enc->cipher, sizeof(enc->cipher))) != 0 ||
2643 (r = sshbuf_get_u32(b, (u_int *)&enc->enabled)) != 0 ||
2644 (r = sshbuf_get_u32(b, &enc->block_size)) != 0 ||
2645 (r = sshbuf_get_string(b, &enc->key, &keylen)) != 0 ||
2646 (r = sshbuf_get_string(b, &enc->iv, &ivlen)) != 0)
2648 if (cipher_authlen(enc->cipher) == 0) {
2649 if ((r = sshbuf_get_cstring(b, &mac->name, NULL)) != 0)
2651 if ((r = mac_setup(mac, mac->name)) != 0)
2653 if ((r = sshbuf_get_u32(b, (u_int *)&mac->enabled)) != 0 ||
2654 (r = sshbuf_get_string(b, &mac->key, &maclen)) != 0)
2656 if (maclen > mac->key_len) {
2657 r = SSH_ERR_INVALID_FORMAT;
2660 mac->key_len = maclen;
2662 if ((r = sshbuf_get_u32(b, &comp->type)) != 0 ||
2663 (r = sshbuf_get_cstring(b, &comp->name, NULL)) != 0)
2665 if (enc->name == NULL ||
2666 cipher_by_name(enc->name) != enc->cipher) {
2667 r = SSH_ERR_INVALID_FORMAT;
2670 if (sshbuf_len(b) != 0) {
2671 r = SSH_ERR_INVALID_FORMAT;
2674 enc->key_len = keylen;
2675 enc->iv_len = ivlen;
2676 ssh->kex->newkeys[mode] = newkey;
2685 /* restore kex from blob for packet state de-serialization */
2687 kex_from_blob(struct sshbuf *m, struct kex **kexp)
2692 if ((kex = calloc(1, sizeof(struct kex))) == NULL ||
2693 (kex->my = sshbuf_new()) == NULL ||
2694 (kex->peer = sshbuf_new()) == NULL) {
2695 r = SSH_ERR_ALLOC_FAIL;
2698 if ((r = sshbuf_get_string(m, &kex->session_id, &kex->session_id_len)) != 0 ||
2699 (r = sshbuf_get_u32(m, &kex->we_need)) != 0 ||
2700 (r = sshbuf_get_u32(m, (u_int *)&kex->hostkey_type)) != 0 ||
2701 (r = sshbuf_get_u32(m, &kex->kex_type)) != 0 ||
2702 (r = sshbuf_get_stringb(m, kex->my)) != 0 ||
2703 (r = sshbuf_get_stringb(m, kex->peer)) != 0 ||
2704 (r = sshbuf_get_u32(m, &kex->flags)) != 0 ||
2705 (r = sshbuf_get_cstring(m, &kex->client_version_string, NULL)) != 0 ||
2706 (r = sshbuf_get_cstring(m, &kex->server_version_string, NULL)) != 0)
2712 if (r != 0 || kexp == NULL) {
2714 sshbuf_free(kex->my);
2715 sshbuf_free(kex->peer);
2727 * Restore packet state from content of blob 'm' (de-serialization).
2728 * Note that 'm' will be partially consumed on parsing or any other errors.
2731 ssh_packet_set_state(struct ssh *ssh, struct sshbuf *m)
2733 struct session_state *state = ssh->state;
2734 const u_char *ssh1key, *ivin, *ivout, *keyin, *keyout, *input, *output;
2735 size_t ssh1keylen, rlen, slen, ilen, olen;
2737 u_int ssh1cipher = 0;
2740 if ((r = sshbuf_get_u32(m, &state->remote_protocol_flags)) != 0 ||
2741 (r = sshbuf_get_u32(m, &ssh1cipher)) != 0 ||
2742 (r = sshbuf_get_string_direct(m, &ssh1key, &ssh1keylen)) != 0 ||
2743 (r = sshbuf_get_string_direct(m, &ivout, &slen)) != 0 ||
2744 (r = sshbuf_get_string_direct(m, &ivin, &rlen)) != 0)
2746 if (ssh1cipher > INT_MAX)
2747 return SSH_ERR_KEY_UNKNOWN_CIPHER;
2748 ssh_packet_set_encryption_key(ssh, ssh1key, ssh1keylen,
2750 if (cipher_get_keyiv_len(state->send_context) != (int)slen ||
2751 cipher_get_keyiv_len(state->receive_context) != (int)rlen)
2752 return SSH_ERR_INVALID_FORMAT;
2753 if ((r = cipher_set_keyiv(state->send_context, ivout)) != 0 ||
2754 (r = cipher_set_keyiv(state->receive_context, ivin)) != 0)
2757 if ((r = kex_from_blob(m, &ssh->kex)) != 0 ||
2758 (r = newkeys_from_blob(m, ssh, MODE_OUT)) != 0 ||
2759 (r = newkeys_from_blob(m, ssh, MODE_IN)) != 0 ||
2760 (r = sshbuf_get_u64(m, &state->rekey_limit)) != 0 ||
2761 (r = sshbuf_get_u32(m, &state->rekey_interval)) != 0 ||
2762 (r = sshbuf_get_u32(m, &state->p_send.seqnr)) != 0 ||
2763 (r = sshbuf_get_u64(m, &state->p_send.blocks)) != 0 ||
2764 (r = sshbuf_get_u32(m, &state->p_send.packets)) != 0 ||
2765 (r = sshbuf_get_u64(m, &state->p_send.bytes)) != 0 ||
2766 (r = sshbuf_get_u32(m, &state->p_read.seqnr)) != 0 ||
2767 (r = sshbuf_get_u64(m, &state->p_read.blocks)) != 0 ||
2768 (r = sshbuf_get_u32(m, &state->p_read.packets)) != 0 ||
2769 (r = sshbuf_get_u64(m, &state->p_read.bytes)) != 0)
2772 * We set the time here so that in post-auth privsep slave we
2773 * count from the completion of the authentication.
2775 state->rekey_time = monotime();
2776 /* XXX ssh_set_newkeys overrides p_read.packets? XXX */
2777 if ((r = ssh_set_newkeys(ssh, MODE_IN)) != 0 ||
2778 (r = ssh_set_newkeys(ssh, MODE_OUT)) != 0)
2781 if ((r = sshbuf_get_string_direct(m, &keyout, &slen)) != 0 ||
2782 (r = sshbuf_get_string_direct(m, &keyin, &rlen)) != 0)
2784 if (cipher_get_keycontext(state->send_context, NULL) != (int)slen ||
2785 cipher_get_keycontext(state->receive_context, NULL) != (int)rlen)
2786 return SSH_ERR_INVALID_FORMAT;
2787 cipher_set_keycontext(state->send_context, keyout);
2788 cipher_set_keycontext(state->receive_context, keyin);
2790 if ((r = ssh_packet_set_postauth(ssh)) != 0)
2793 sshbuf_reset(state->input);
2794 sshbuf_reset(state->output);
2795 if ((r = sshbuf_get_string_direct(m, &input, &ilen)) != 0 ||
2796 (r = sshbuf_get_string_direct(m, &output, &olen)) != 0 ||
2797 (r = sshbuf_put(state->input, input, ilen)) != 0 ||
2798 (r = sshbuf_put(state->output, output, olen)) != 0)
2802 return SSH_ERR_INVALID_FORMAT;
2803 debug3("%s: done", __func__);
2809 /* put data to the outgoing packet */
2812 sshpkt_put(struct ssh *ssh, const void *v, size_t len)
2814 return sshbuf_put(ssh->state->outgoing_packet, v, len);
2818 sshpkt_putb(struct ssh *ssh, const struct sshbuf *b)
2820 return sshbuf_putb(ssh->state->outgoing_packet, b);
2824 sshpkt_put_u8(struct ssh *ssh, u_char val)
2826 return sshbuf_put_u8(ssh->state->outgoing_packet, val);
2830 sshpkt_put_u32(struct ssh *ssh, u_int32_t val)
2832 return sshbuf_put_u32(ssh->state->outgoing_packet, val);
2836 sshpkt_put_u64(struct ssh *ssh, u_int64_t val)
2838 return sshbuf_put_u64(ssh->state->outgoing_packet, val);
2842 sshpkt_put_string(struct ssh *ssh, const void *v, size_t len)
2844 return sshbuf_put_string(ssh->state->outgoing_packet, v, len);
2848 sshpkt_put_cstring(struct ssh *ssh, const void *v)
2850 return sshbuf_put_cstring(ssh->state->outgoing_packet, v);
2854 sshpkt_put_stringb(struct ssh *ssh, const struct sshbuf *v)
2856 return sshbuf_put_stringb(ssh->state->outgoing_packet, v);
2860 #ifdef OPENSSL_HAS_ECC
2862 sshpkt_put_ec(struct ssh *ssh, const EC_POINT *v, const EC_GROUP *g)
2864 return sshbuf_put_ec(ssh->state->outgoing_packet, v, g);
2866 #endif /* OPENSSL_HAS_ECC */
2870 sshpkt_put_bignum1(struct ssh *ssh, const BIGNUM *v)
2872 return sshbuf_put_bignum1(ssh->state->outgoing_packet, v);
2874 #endif /* WITH_SSH1 */
2877 sshpkt_put_bignum2(struct ssh *ssh, const BIGNUM *v)
2879 return sshbuf_put_bignum2(ssh->state->outgoing_packet, v);
2881 #endif /* WITH_OPENSSL */
2883 /* fetch data from the incoming packet */
2886 sshpkt_get(struct ssh *ssh, void *valp, size_t len)
2888 return sshbuf_get(ssh->state->incoming_packet, valp, len);
2892 sshpkt_get_u8(struct ssh *ssh, u_char *valp)
2894 return sshbuf_get_u8(ssh->state->incoming_packet, valp);
2898 sshpkt_get_u32(struct ssh *ssh, u_int32_t *valp)
2900 return sshbuf_get_u32(ssh->state->incoming_packet, valp);
2904 sshpkt_get_u64(struct ssh *ssh, u_int64_t *valp)
2906 return sshbuf_get_u64(ssh->state->incoming_packet, valp);
2910 sshpkt_get_string(struct ssh *ssh, u_char **valp, size_t *lenp)
2912 return sshbuf_get_string(ssh->state->incoming_packet, valp, lenp);
2916 sshpkt_get_string_direct(struct ssh *ssh, const u_char **valp, size_t *lenp)
2918 return sshbuf_get_string_direct(ssh->state->incoming_packet, valp, lenp);
2922 sshpkt_get_cstring(struct ssh *ssh, char **valp, size_t *lenp)
2924 return sshbuf_get_cstring(ssh->state->incoming_packet, valp, lenp);
2928 #ifdef OPENSSL_HAS_ECC
2930 sshpkt_get_ec(struct ssh *ssh, EC_POINT *v, const EC_GROUP *g)
2932 return sshbuf_get_ec(ssh->state->incoming_packet, v, g);
2934 #endif /* OPENSSL_HAS_ECC */
2938 sshpkt_get_bignum1(struct ssh *ssh, BIGNUM *v)
2940 return sshbuf_get_bignum1(ssh->state->incoming_packet, v);
2942 #endif /* WITH_SSH1 */
2945 sshpkt_get_bignum2(struct ssh *ssh, BIGNUM *v)
2947 return sshbuf_get_bignum2(ssh->state->incoming_packet, v);
2949 #endif /* WITH_OPENSSL */
2952 sshpkt_get_end(struct ssh *ssh)
2954 if (sshbuf_len(ssh->state->incoming_packet) > 0)
2955 return SSH_ERR_UNEXPECTED_TRAILING_DATA;
2960 sshpkt_ptr(struct ssh *ssh, size_t *lenp)
2963 *lenp = sshbuf_len(ssh->state->incoming_packet);
2964 return sshbuf_ptr(ssh->state->incoming_packet);
2967 /* start a new packet */
2970 sshpkt_start(struct ssh *ssh, u_char type)
2975 DBG(debug("packet_start[%d]", type));
2976 len = compat20 ? 6 : 9;
2977 memset(buf, 0, len - 1);
2978 buf[len - 1] = type;
2979 sshbuf_reset(ssh->state->outgoing_packet);
2980 return sshbuf_put(ssh->state->outgoing_packet, buf, len);
2984 ssh_packet_send_mux(struct ssh *ssh)
2986 struct session_state *state = ssh->state;
2992 return SSH_ERR_INTERNAL_ERROR;
2993 len = sshbuf_len(state->outgoing_packet);
2995 return SSH_ERR_INTERNAL_ERROR;
2996 cp = sshbuf_mutable_ptr(state->outgoing_packet);
2998 if (ssh_packet_log_type(type))
2999 debug3("%s: type %u", __func__, type);
3000 /* drop everything, but the connection protocol */
3001 if (type >= SSH2_MSG_CONNECTION_MIN &&
3002 type <= SSH2_MSG_CONNECTION_MAX) {
3003 POKE_U32(cp, len - 4);
3004 if ((r = sshbuf_putb(state->output,
3005 state->outgoing_packet)) != 0)
3007 /* sshbuf_dump(state->output, stderr); */
3009 sshbuf_reset(state->outgoing_packet);
3016 sshpkt_send(struct ssh *ssh)
3018 if (ssh->state && ssh->state->mux)
3019 return ssh_packet_send_mux(ssh);
3021 return ssh_packet_send2(ssh);
3023 return ssh_packet_send1(ssh);
3027 sshpkt_disconnect(struct ssh *ssh, const char *fmt,...)
3033 va_start(args, fmt);
3034 vsnprintf(buf, sizeof(buf), fmt, args);
3038 if ((r = sshpkt_start(ssh, SSH2_MSG_DISCONNECT)) != 0 ||
3039 (r = sshpkt_put_u32(ssh, SSH2_DISCONNECT_PROTOCOL_ERROR)) != 0 ||
3040 (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
3041 (r = sshpkt_put_cstring(ssh, "")) != 0 ||
3042 (r = sshpkt_send(ssh)) != 0)
3045 if ((r = sshpkt_start(ssh, SSH_MSG_DISCONNECT)) != 0 ||
3046 (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
3047 (r = sshpkt_send(ssh)) != 0)
3053 /* roundup current message to pad bytes */
3055 sshpkt_add_padding(struct ssh *ssh, u_char pad)
3057 ssh->state->extra_pad = pad;