1 /* $OpenBSD: packet.c,v 1.229 2016/02/17 22:20:14 djm 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/param.h> /* MIN roundup */
44 #include <sys/types.h>
45 #include "openbsd-compat/sys-queue.h"
46 #include <sys/socket.h>
47 #ifdef HAVE_SYS_TIME_H
48 # include <sys/time.h>
51 #include <netinet/in.h>
52 #include <netinet/ip.h>
53 #include <arpa/inet.h>
67 #include "buffer.h" /* typedefs XXX */
68 #include "key.h" /* typedefs XXX */
96 #define PACKET_MAX_SIZE (256 * 1024)
106 TAILQ_ENTRY(packet) next;
108 struct sshbuf *payload;
111 struct session_state {
113 * This variable contains the file descriptors used for
114 * communicating with the other side. connection_in is used for
115 * reading; connection_out for writing. These can be the same
116 * descriptor, in which case it is assumed to be a socket.
121 /* Protocol flags for the remote side. */
122 u_int remote_protocol_flags;
124 /* Encryption context for receiving data. Only used for decryption. */
125 struct sshcipher_ctx receive_context;
127 /* Encryption context for sending data. Only used for encryption. */
128 struct sshcipher_ctx send_context;
130 /* Buffer for raw input data from the socket. */
131 struct sshbuf *input;
133 /* Buffer for raw output data going to the socket. */
134 struct sshbuf *output;
136 /* Buffer for the partial outgoing packet being constructed. */
137 struct sshbuf *outgoing_packet;
139 /* Buffer for the incoming packet currently being processed. */
140 struct sshbuf *incoming_packet;
142 /* Scratch buffer for packet compression/decompression. */
143 struct sshbuf *compression_buffer;
145 /* Incoming/outgoing compression dictionaries */
146 z_stream compression_in_stream;
147 z_stream compression_out_stream;
148 int compression_in_started;
149 int compression_out_started;
150 int compression_in_failures;
151 int compression_out_failures;
154 * Flag indicating whether packet compression/decompression is
157 int packet_compression;
159 /* default maximum packet size */
160 u_int max_packet_size;
162 /* Flag indicating whether this module has been initialized. */
165 /* Set to true if the connection is interactive. */
166 int interactive_mode;
168 /* Set to true if we are the server side. */
171 /* Set to true if we are authenticated. */
172 int after_authentication;
174 int keep_alive_timeouts;
176 /* The maximum time that we will wait to send or receive a packet */
177 int packet_timeout_ms;
179 /* Session key information for Encryption and MAC */
180 struct newkeys *newkeys[MODE_MAX];
181 struct packet_state p_read, p_send;
183 /* Volume-based rekeying */
184 u_int64_t max_blocks_in, max_blocks_out, rekey_limit;
186 /* Time-based rekeying */
187 u_int32_t rekey_interval; /* how often in seconds */
188 time_t rekey_time; /* time of last rekeying */
190 /* Session key for protocol v1 */
191 u_char ssh1_key[SSH_SESSION_KEY_LENGTH];
194 /* roundup current message to extra_pad bytes */
197 /* XXX discard incoming data after MAC error */
198 u_int packet_discard;
199 struct sshmac *packet_discard_mac;
201 /* Used in packet_read_poll2() */
204 /* Used in packet_send2 */
207 /* Used in packet_set_interactive */
208 int set_interactive_called;
210 /* Used in packet_set_maxsize */
211 int set_maxsize_called;
213 /* One-off warning about weak ciphers */
214 int cipher_warning_done;
216 /* SSH1 CRC compensation attack detector */
217 struct deattack_ctx deattack;
219 TAILQ_HEAD(, packet) outgoing;
223 ssh_alloc_session_state(void)
225 struct ssh *ssh = NULL;
226 struct session_state *state = NULL;
228 if ((ssh = calloc(1, sizeof(*ssh))) == NULL ||
229 (state = calloc(1, sizeof(*state))) == NULL ||
230 (state->input = sshbuf_new()) == NULL ||
231 (state->output = sshbuf_new()) == NULL ||
232 (state->outgoing_packet = sshbuf_new()) == NULL ||
233 (state->incoming_packet = sshbuf_new()) == NULL)
235 TAILQ_INIT(&state->outgoing);
236 TAILQ_INIT(&ssh->private_keys);
237 TAILQ_INIT(&ssh->public_keys);
238 state->connection_in = -1;
239 state->connection_out = -1;
240 state->max_packet_size = 32768;
241 state->packet_timeout_ms = -1;
242 state->p_send.packets = state->p_read.packets = 0;
243 state->initialized = 1;
245 * ssh_packet_send2() needs to queue packets until
246 * we've done the initial key exchange.
253 sshbuf_free(state->input);
254 sshbuf_free(state->output);
255 sshbuf_free(state->incoming_packet);
256 sshbuf_free(state->outgoing_packet);
263 /* Returns nonzero if rekeying is in progress */
265 ssh_packet_is_rekeying(struct ssh *ssh)
268 (ssh->state->rekeying || (ssh->kex != NULL && ssh->kex->done == 0));
272 * Sets the descriptors used for communication. Disables encryption until
273 * packet_set_encryption_key is called.
276 ssh_packet_set_connection(struct ssh *ssh, int fd_in, int fd_out)
278 struct session_state *state;
279 const struct sshcipher *none = cipher_by_name("none");
283 error("%s: cannot load cipher 'none'", __func__);
287 ssh = ssh_alloc_session_state();
289 error("%s: cound not allocate state", __func__);
293 state->connection_in = fd_in;
294 state->connection_out = fd_out;
295 if ((r = cipher_init(&state->send_context, none,
296 (const u_char *)"", 0, NULL, 0, CIPHER_ENCRYPT)) != 0 ||
297 (r = cipher_init(&state->receive_context, none,
298 (const u_char *)"", 0, NULL, 0, CIPHER_DECRYPT)) != 0) {
299 error("%s: cipher_init failed: %s", __func__, ssh_err(r));
303 state->newkeys[MODE_IN] = state->newkeys[MODE_OUT] = NULL;
304 deattack_init(&state->deattack);
306 * Cache the IP address of the remote connection for use in error
307 * messages that might be generated after the connection has closed.
309 (void)ssh_remote_ipaddr(ssh);
314 ssh_packet_set_timeout(struct ssh *ssh, int timeout, int count)
316 struct session_state *state = ssh->state;
318 if (timeout <= 0 || count <= 0) {
319 state->packet_timeout_ms = -1;
322 if ((INT_MAX / 1000) / count < timeout)
323 state->packet_timeout_ms = INT_MAX;
325 state->packet_timeout_ms = timeout * count * 1000;
329 ssh_packet_stop_discard(struct ssh *ssh)
331 struct session_state *state = ssh->state;
334 if (state->packet_discard_mac) {
337 memset(buf, 'a', sizeof(buf));
338 while (sshbuf_len(state->incoming_packet) <
340 if ((r = sshbuf_put(state->incoming_packet, buf,
343 (void) mac_compute(state->packet_discard_mac,
345 sshbuf_ptr(state->incoming_packet), PACKET_MAX_SIZE,
348 logit("Finished discarding for %.200s port %d",
349 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
350 return SSH_ERR_MAC_INVALID;
354 ssh_packet_start_discard(struct ssh *ssh, struct sshenc *enc,
355 struct sshmac *mac, u_int packet_length, u_int discard)
357 struct session_state *state = ssh->state;
360 if (enc == NULL || !cipher_is_cbc(enc->cipher) || (mac && mac->etm)) {
361 if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0)
363 return SSH_ERR_MAC_INVALID;
365 if (packet_length != PACKET_MAX_SIZE && mac && mac->enabled)
366 state->packet_discard_mac = mac;
367 if (sshbuf_len(state->input) >= discard &&
368 (r = ssh_packet_stop_discard(ssh)) != 0)
370 state->packet_discard = discard - sshbuf_len(state->input);
374 /* Returns 1 if remote host is connected via socket, 0 if not. */
377 ssh_packet_connection_is_on_socket(struct ssh *ssh)
379 struct session_state *state = ssh->state;
380 struct sockaddr_storage from, to;
381 socklen_t fromlen, tolen;
383 /* filedescriptors in and out are the same, so it's a socket */
384 if (state->connection_in == state->connection_out)
386 fromlen = sizeof(from);
387 memset(&from, 0, sizeof(from));
388 if (getpeername(state->connection_in, (struct sockaddr *)&from,
392 memset(&to, 0, sizeof(to));
393 if (getpeername(state->connection_out, (struct sockaddr *)&to,
396 if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
398 if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
404 ssh_packet_get_bytes(struct ssh *ssh, u_int64_t *ibytes, u_int64_t *obytes)
407 *ibytes = ssh->state->p_read.bytes;
409 *obytes = ssh->state->p_send.bytes;
413 ssh_packet_connection_af(struct ssh *ssh)
415 struct sockaddr_storage to;
416 socklen_t tolen = sizeof(to);
418 memset(&to, 0, sizeof(to));
419 if (getsockname(ssh->state->connection_out, (struct sockaddr *)&to,
423 if (to.ss_family == AF_INET6 &&
424 IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&to)->sin6_addr))
430 /* Sets the connection into non-blocking mode. */
433 ssh_packet_set_nonblocking(struct ssh *ssh)
435 /* Set the socket into non-blocking mode. */
436 set_nonblock(ssh->state->connection_in);
438 if (ssh->state->connection_out != ssh->state->connection_in)
439 set_nonblock(ssh->state->connection_out);
442 /* Returns the socket used for reading. */
445 ssh_packet_get_connection_in(struct ssh *ssh)
447 return ssh->state->connection_in;
450 /* Returns the descriptor used for writing. */
453 ssh_packet_get_connection_out(struct ssh *ssh)
455 return ssh->state->connection_out;
459 * Returns the IP-address of the remote host as a string. The returned
460 * string must not be freed.
464 ssh_remote_ipaddr(struct ssh *ssh)
466 const int sock = ssh->state->connection_in;
468 /* Check whether we have cached the ipaddr. */
469 if (ssh->remote_ipaddr == NULL) {
470 if (ssh_packet_connection_is_on_socket(ssh)) {
471 ssh->remote_ipaddr = get_peer_ipaddr(sock);
472 ssh->remote_port = get_sock_port(sock, 0);
474 ssh->remote_ipaddr = strdup("UNKNOWN");
475 ssh->remote_port = 0;
478 return ssh->remote_ipaddr;
481 /* Returns the port number of the remote host. */
484 ssh_remote_port(struct ssh *ssh)
486 (void)ssh_remote_ipaddr(ssh); /* Will lookup and cache. */
487 return ssh->remote_port;
490 /* Closes the connection and clears and frees internal data structures. */
493 ssh_packet_close(struct ssh *ssh)
495 struct session_state *state = ssh->state;
499 if (!state->initialized)
501 state->initialized = 0;
502 if (state->connection_in == state->connection_out) {
503 shutdown(state->connection_out, SHUT_RDWR);
504 close(state->connection_out);
506 close(state->connection_in);
507 close(state->connection_out);
509 sshbuf_free(state->input);
510 sshbuf_free(state->output);
511 sshbuf_free(state->outgoing_packet);
512 sshbuf_free(state->incoming_packet);
513 for (mode = 0; mode < MODE_MAX; mode++)
514 kex_free_newkeys(state->newkeys[mode]);
515 if (state->compression_buffer) {
516 sshbuf_free(state->compression_buffer);
517 if (state->compression_out_started) {
518 z_streamp stream = &state->compression_out_stream;
519 debug("compress outgoing: "
520 "raw data %llu, compressed %llu, factor %.2f",
521 (unsigned long long)stream->total_in,
522 (unsigned long long)stream->total_out,
523 stream->total_in == 0 ? 0.0 :
524 (double) stream->total_out / stream->total_in);
525 if (state->compression_out_failures == 0)
528 if (state->compression_in_started) {
529 z_streamp stream = &state->compression_out_stream;
530 debug("compress incoming: "
531 "raw data %llu, compressed %llu, factor %.2f",
532 (unsigned long long)stream->total_out,
533 (unsigned long long)stream->total_in,
534 stream->total_out == 0 ? 0.0 :
535 (double) stream->total_in / stream->total_out);
536 if (state->compression_in_failures == 0)
540 if ((r = cipher_cleanup(&state->send_context)) != 0)
541 error("%s: cipher_cleanup failed: %s", __func__, ssh_err(r));
542 if ((r = cipher_cleanup(&state->receive_context)) != 0)
543 error("%s: cipher_cleanup failed: %s", __func__, ssh_err(r));
544 free(ssh->remote_ipaddr);
545 ssh->remote_ipaddr = NULL;
550 /* Sets remote side protocol flags. */
553 ssh_packet_set_protocol_flags(struct ssh *ssh, u_int protocol_flags)
555 ssh->state->remote_protocol_flags = protocol_flags;
558 /* Returns the remote protocol flags set earlier by the above function. */
561 ssh_packet_get_protocol_flags(struct ssh *ssh)
563 return ssh->state->remote_protocol_flags;
567 * Starts packet compression from the next packet on in both directions.
568 * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
572 ssh_packet_init_compression(struct ssh *ssh)
574 if (!ssh->state->compression_buffer &&
575 ((ssh->state->compression_buffer = sshbuf_new()) == NULL))
576 return SSH_ERR_ALLOC_FAIL;
581 start_compression_out(struct ssh *ssh, int level)
583 if (level < 1 || level > 9)
584 return SSH_ERR_INVALID_ARGUMENT;
585 debug("Enabling compression at level %d.", level);
586 if (ssh->state->compression_out_started == 1)
587 deflateEnd(&ssh->state->compression_out_stream);
588 switch (deflateInit(&ssh->state->compression_out_stream, level)) {
590 ssh->state->compression_out_started = 1;
593 return SSH_ERR_ALLOC_FAIL;
595 return SSH_ERR_INTERNAL_ERROR;
601 start_compression_in(struct ssh *ssh)
603 if (ssh->state->compression_in_started == 1)
604 inflateEnd(&ssh->state->compression_in_stream);
605 switch (inflateInit(&ssh->state->compression_in_stream)) {
607 ssh->state->compression_in_started = 1;
610 return SSH_ERR_ALLOC_FAIL;
612 return SSH_ERR_INTERNAL_ERROR;
618 ssh_packet_start_compression(struct ssh *ssh, int level)
622 if (ssh->state->packet_compression && !compat20)
623 return SSH_ERR_INTERNAL_ERROR;
624 ssh->state->packet_compression = 1;
625 if ((r = ssh_packet_init_compression(ssh)) != 0 ||
626 (r = start_compression_in(ssh)) != 0 ||
627 (r = start_compression_out(ssh, level)) != 0)
632 /* XXX remove need for separate compression buffer */
634 compress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
639 if (ssh->state->compression_out_started != 1)
640 return SSH_ERR_INTERNAL_ERROR;
642 /* This case is not handled below. */
643 if (sshbuf_len(in) == 0)
646 /* Input is the contents of the input buffer. */
647 if ((ssh->state->compression_out_stream.next_in =
648 sshbuf_mutable_ptr(in)) == NULL)
649 return SSH_ERR_INTERNAL_ERROR;
650 ssh->state->compression_out_stream.avail_in = sshbuf_len(in);
652 /* Loop compressing until deflate() returns with avail_out != 0. */
654 /* Set up fixed-size output buffer. */
655 ssh->state->compression_out_stream.next_out = buf;
656 ssh->state->compression_out_stream.avail_out = sizeof(buf);
658 /* Compress as much data into the buffer as possible. */
659 status = deflate(&ssh->state->compression_out_stream,
663 return SSH_ERR_ALLOC_FAIL;
665 /* Append compressed data to output_buffer. */
666 if ((r = sshbuf_put(out, buf, sizeof(buf) -
667 ssh->state->compression_out_stream.avail_out)) != 0)
672 ssh->state->compression_out_failures++;
673 return SSH_ERR_INVALID_FORMAT;
675 } while (ssh->state->compression_out_stream.avail_out == 0);
680 uncompress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
685 if (ssh->state->compression_in_started != 1)
686 return SSH_ERR_INTERNAL_ERROR;
688 if ((ssh->state->compression_in_stream.next_in =
689 sshbuf_mutable_ptr(in)) == NULL)
690 return SSH_ERR_INTERNAL_ERROR;
691 ssh->state->compression_in_stream.avail_in = sshbuf_len(in);
694 /* Set up fixed-size output buffer. */
695 ssh->state->compression_in_stream.next_out = buf;
696 ssh->state->compression_in_stream.avail_out = sizeof(buf);
698 status = inflate(&ssh->state->compression_in_stream,
702 if ((r = sshbuf_put(out, buf, sizeof(buf) -
703 ssh->state->compression_in_stream.avail_out)) != 0)
708 * Comments in zlib.h say that we should keep calling
709 * inflate() until we get an error. This appears to
710 * be the error that we get.
714 return SSH_ERR_INVALID_FORMAT;
716 return SSH_ERR_ALLOC_FAIL;
719 ssh->state->compression_in_failures++;
720 return SSH_ERR_INTERNAL_ERROR;
726 /* Serialise compression state into a blob for privsep */
728 ssh_packet_get_compress_state(struct sshbuf *m, struct ssh *ssh)
730 struct session_state *state = ssh->state;
734 if ((b = sshbuf_new()) == NULL)
735 return SSH_ERR_ALLOC_FAIL;
736 if (state->compression_in_started) {
737 if ((r = sshbuf_put_string(b, &state->compression_in_stream,
738 sizeof(state->compression_in_stream))) != 0)
740 } else if ((r = sshbuf_put_string(b, NULL, 0)) != 0)
742 if (state->compression_out_started) {
743 if ((r = sshbuf_put_string(b, &state->compression_out_stream,
744 sizeof(state->compression_out_stream))) != 0)
746 } else if ((r = sshbuf_put_string(b, NULL, 0)) != 0)
748 r = sshbuf_put_stringb(m, b);
754 /* Deserialise compression state from a blob for privsep */
756 ssh_packet_set_compress_state(struct ssh *ssh, struct sshbuf *m)
758 struct session_state *state = ssh->state;
759 struct sshbuf *b = NULL;
761 const u_char *inblob, *outblob;
764 if ((r = sshbuf_froms(m, &b)) != 0)
766 if ((r = sshbuf_get_string_direct(b, &inblob, &inl)) != 0 ||
767 (r = sshbuf_get_string_direct(b, &outblob, &outl)) != 0)
770 state->compression_in_started = 0;
771 else if (inl != sizeof(state->compression_in_stream)) {
772 r = SSH_ERR_INTERNAL_ERROR;
775 state->compression_in_started = 1;
776 memcpy(&state->compression_in_stream, inblob, inl);
779 state->compression_out_started = 0;
780 else if (outl != sizeof(state->compression_out_stream)) {
781 r = SSH_ERR_INTERNAL_ERROR;
784 state->compression_out_started = 1;
785 memcpy(&state->compression_out_stream, outblob, outl);
794 ssh_packet_set_compress_hooks(struct ssh *ssh, void *ctx,
795 void *(*allocfunc)(void *, u_int, u_int),
796 void (*freefunc)(void *, void *))
798 ssh->state->compression_out_stream.zalloc = (alloc_func)allocfunc;
799 ssh->state->compression_out_stream.zfree = (free_func)freefunc;
800 ssh->state->compression_out_stream.opaque = ctx;
801 ssh->state->compression_in_stream.zalloc = (alloc_func)allocfunc;
802 ssh->state->compression_in_stream.zfree = (free_func)freefunc;
803 ssh->state->compression_in_stream.opaque = ctx;
807 * Causes any further packets to be encrypted using the given key. The same
808 * key is used for both sending and reception. However, both directions are
809 * encrypted independently of each other.
813 ssh_packet_set_encryption_key(struct ssh *ssh, const u_char *key, u_int keylen, int number)
816 fatal("no SSH protocol 1 support");
817 #else /* WITH_SSH1 */
818 struct session_state *state = ssh->state;
819 const struct sshcipher *cipher = cipher_by_number(number);
824 fatal("%s: unknown cipher number %d", __func__, number);
826 fatal("%s: keylen too small: %d", __func__, keylen);
827 if (keylen > SSH_SESSION_KEY_LENGTH)
828 fatal("%s: keylen too big: %d", __func__, keylen);
829 memcpy(state->ssh1_key, key, keylen);
830 state->ssh1_keylen = keylen;
831 if ((r = cipher_init(&state->send_context, cipher, key, keylen,
832 NULL, 0, CIPHER_ENCRYPT)) != 0 ||
833 (r = cipher_init(&state->receive_context, cipher, key, keylen,
834 NULL, 0, CIPHER_DECRYPT) != 0))
835 fatal("%s: cipher_init failed: %s", __func__, ssh_err(r));
836 if (!state->cipher_warning_done &&
837 ((wmsg = cipher_warning_message(&state->send_context)) != NULL ||
838 (wmsg = cipher_warning_message(&state->send_context)) != NULL)) {
839 error("Warning: %s", wmsg);
840 state->cipher_warning_done = 1;
842 #endif /* WITH_SSH1 */
846 * Finalizes and sends the packet. If the encryption key has been set,
847 * encrypts the packet before sending.
851 ssh_packet_send1(struct ssh *ssh)
853 struct session_state *state = ssh->state;
859 * If using packet compression, compress the payload of the outgoing
862 if (state->packet_compression) {
863 sshbuf_reset(state->compression_buffer);
865 if ((r = sshbuf_consume(state->outgoing_packet, 8)) != 0)
868 if ((r = sshbuf_put(state->compression_buffer,
869 "\0\0\0\0\0\0\0\0", 8)) != 0)
871 if ((r = compress_buffer(ssh, state->outgoing_packet,
872 state->compression_buffer)) != 0)
874 sshbuf_reset(state->outgoing_packet);
875 if ((r = sshbuf_putb(state->outgoing_packet,
876 state->compression_buffer)) != 0)
879 /* Compute packet length without padding (add checksum, remove padding). */
880 len = sshbuf_len(state->outgoing_packet) + 4 - 8;
882 /* Insert padding. Initialized to zero in packet_start1() */
883 padding = 8 - len % 8;
884 if (!state->send_context.plaintext) {
885 cp = sshbuf_mutable_ptr(state->outgoing_packet);
887 r = SSH_ERR_INTERNAL_ERROR;
890 arc4random_buf(cp + 8 - padding, padding);
892 if ((r = sshbuf_consume(state->outgoing_packet, 8 - padding)) != 0)
895 /* Add check bytes. */
896 checksum = ssh_crc32(sshbuf_ptr(state->outgoing_packet),
897 sshbuf_len(state->outgoing_packet));
898 POKE_U32(buf, checksum);
899 if ((r = sshbuf_put(state->outgoing_packet, buf, 4)) != 0)
903 fprintf(stderr, "packet_send plain: ");
904 sshbuf_dump(state->outgoing_packet, stderr);
907 /* Append to output. */
909 if ((r = sshbuf_put(state->output, buf, 4)) != 0)
911 if ((r = sshbuf_reserve(state->output,
912 sshbuf_len(state->outgoing_packet), &cp)) != 0)
914 if ((r = cipher_crypt(&state->send_context, 0, cp,
915 sshbuf_ptr(state->outgoing_packet),
916 sshbuf_len(state->outgoing_packet), 0, 0)) != 0)
920 fprintf(stderr, "encrypted: ");
921 sshbuf_dump(state->output, stderr);
923 state->p_send.packets++;
924 state->p_send.bytes += len +
925 sshbuf_len(state->outgoing_packet);
926 sshbuf_reset(state->outgoing_packet);
929 * Note that the packet is now only buffered in output. It won't be
930 * actually sent until ssh_packet_write_wait or ssh_packet_write_poll
939 ssh_set_newkeys(struct ssh *ssh, int mode)
941 struct session_state *state = ssh->state;
944 struct sshcomp *comp;
945 struct sshcipher_ctx *cc;
946 u_int64_t *max_blocks;
950 debug2("set_newkeys: mode %d", mode);
952 if (mode == MODE_OUT) {
953 cc = &state->send_context;
954 crypt_type = CIPHER_ENCRYPT;
955 state->p_send.packets = state->p_send.blocks = 0;
956 max_blocks = &state->max_blocks_out;
958 cc = &state->receive_context;
959 crypt_type = CIPHER_DECRYPT;
960 state->p_read.packets = state->p_read.blocks = 0;
961 max_blocks = &state->max_blocks_in;
963 if (state->newkeys[mode] != NULL) {
964 debug("set_newkeys: rekeying, input %llu bytes %llu blocks, "
965 "output %llu bytes %llu blocks",
966 (unsigned long long)state->p_read.bytes,
967 (unsigned long long)state->p_read.blocks,
968 (unsigned long long)state->p_send.bytes,
969 (unsigned long long)state->p_send.blocks);
970 if ((r = cipher_cleanup(cc)) != 0)
972 enc = &state->newkeys[mode]->enc;
973 mac = &state->newkeys[mode]->mac;
974 comp = &state->newkeys[mode]->comp;
976 explicit_bzero(enc->iv, enc->iv_len);
977 explicit_bzero(enc->key, enc->key_len);
978 explicit_bzero(mac->key, mac->key_len);
985 free(state->newkeys[mode]);
987 /* move newkeys from kex to state */
988 if ((state->newkeys[mode] = ssh->kex->newkeys[mode]) == NULL)
989 return SSH_ERR_INTERNAL_ERROR;
990 ssh->kex->newkeys[mode] = NULL;
991 enc = &state->newkeys[mode]->enc;
992 mac = &state->newkeys[mode]->mac;
993 comp = &state->newkeys[mode]->comp;
994 if (cipher_authlen(enc->cipher) == 0) {
995 if ((r = mac_init(mac)) != 0)
999 DBG(debug("cipher_init_context: %d", mode));
1000 if ((r = cipher_init(cc, enc->cipher, enc->key, enc->key_len,
1001 enc->iv, enc->iv_len, crypt_type)) != 0)
1003 if (!state->cipher_warning_done &&
1004 (wmsg = cipher_warning_message(cc)) != NULL) {
1005 error("Warning: %s", wmsg);
1006 state->cipher_warning_done = 1;
1008 /* Deleting the keys does not gain extra security */
1009 /* explicit_bzero(enc->iv, enc->block_size);
1010 explicit_bzero(enc->key, enc->key_len);
1011 explicit_bzero(mac->key, mac->key_len); */
1012 if ((comp->type == COMP_ZLIB ||
1013 (comp->type == COMP_DELAYED &&
1014 state->after_authentication)) && comp->enabled == 0) {
1015 if ((r = ssh_packet_init_compression(ssh)) < 0)
1017 if (mode == MODE_OUT) {
1018 if ((r = start_compression_out(ssh, 6)) != 0)
1021 if ((r = start_compression_in(ssh)) != 0)
1027 * The 2^(blocksize*2) limit is too expensive for 3DES,
1028 * blowfish, etc, so enforce a 1GB limit for small blocksizes.
1030 if (enc->block_size >= 16)
1031 *max_blocks = (u_int64_t)1 << (enc->block_size*2);
1033 *max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
1034 if (state->rekey_limit)
1035 *max_blocks = MIN(*max_blocks,
1036 state->rekey_limit / enc->block_size);
1037 debug("rekey after %llu blocks", (unsigned long long)*max_blocks);
1041 #define MAX_PACKETS (1U<<31)
1043 ssh_packet_need_rekeying(struct ssh *ssh, u_int outbound_packet_len)
1045 struct session_state *state = ssh->state;
1046 u_int32_t out_blocks;
1048 /* XXX client can't cope with rekeying pre-auth */
1049 if (!state->after_authentication)
1052 /* Haven't keyed yet or KEX in progress. */
1053 if (ssh->kex == NULL || ssh_packet_is_rekeying(ssh))
1056 /* Peer can't rekey */
1057 if (ssh->compat & SSH_BUG_NOREKEY)
1061 * Permit one packet in or out per rekey - this allows us to
1062 * make progress when rekey limits are very small.
1064 if (state->p_send.packets == 0 && state->p_read.packets == 0)
1067 /* Time-based rekeying */
1068 if (state->rekey_interval != 0 &&
1069 state->rekey_time + state->rekey_interval <= monotime())
1072 /* Always rekey when MAX_PACKETS sent in either direction */
1073 if (state->p_send.packets > MAX_PACKETS ||
1074 state->p_read.packets > MAX_PACKETS)
1077 /* Rekey after (cipher-specific) maxiumum blocks */
1078 out_blocks = roundup(outbound_packet_len,
1079 state->newkeys[MODE_OUT]->enc.block_size);
1080 return (state->max_blocks_out &&
1081 (state->p_send.blocks + out_blocks > state->max_blocks_out)) ||
1082 (state->max_blocks_in &&
1083 (state->p_read.blocks > state->max_blocks_in));
1087 * Delayed compression for SSH2 is enabled after authentication:
1088 * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
1089 * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
1092 ssh_packet_enable_delayed_compress(struct ssh *ssh)
1094 struct session_state *state = ssh->state;
1095 struct sshcomp *comp = NULL;
1099 * Remember that we are past the authentication step, so rekeying
1100 * with COMP_DELAYED will turn on compression immediately.
1102 state->after_authentication = 1;
1103 for (mode = 0; mode < MODE_MAX; mode++) {
1104 /* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
1105 if (state->newkeys[mode] == NULL)
1107 comp = &state->newkeys[mode]->comp;
1108 if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
1109 if ((r = ssh_packet_init_compression(ssh)) != 0)
1111 if (mode == MODE_OUT) {
1112 if ((r = start_compression_out(ssh, 6)) != 0)
1115 if ((r = start_compression_in(ssh)) != 0)
1124 /* Used to mute debug logging for noisy packet types */
1126 ssh_packet_log_type(u_char type)
1129 case SSH2_MSG_CHANNEL_DATA:
1130 case SSH2_MSG_CHANNEL_EXTENDED_DATA:
1131 case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
1139 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
1142 ssh_packet_send2_wrapped(struct ssh *ssh)
1144 struct session_state *state = ssh->state;
1145 u_char type, *cp, macbuf[SSH_DIGEST_MAX_LENGTH];
1146 u_char padlen, pad = 0;
1147 u_int authlen = 0, aadlen = 0;
1149 struct sshenc *enc = NULL;
1150 struct sshmac *mac = NULL;
1151 struct sshcomp *comp = NULL;
1154 if (state->newkeys[MODE_OUT] != NULL) {
1155 enc = &state->newkeys[MODE_OUT]->enc;
1156 mac = &state->newkeys[MODE_OUT]->mac;
1157 comp = &state->newkeys[MODE_OUT]->comp;
1158 /* disable mac for authenticated encryption */
1159 if ((authlen = cipher_authlen(enc->cipher)) != 0)
1162 block_size = enc ? enc->block_size : 8;
1163 aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
1165 type = (sshbuf_ptr(state->outgoing_packet))[5];
1166 if (ssh_packet_log_type(type))
1167 debug3("send packet: type %u", type);
1169 fprintf(stderr, "plain: ");
1170 sshbuf_dump(state->outgoing_packet, stderr);
1173 if (comp && comp->enabled) {
1174 len = sshbuf_len(state->outgoing_packet);
1175 /* skip header, compress only payload */
1176 if ((r = sshbuf_consume(state->outgoing_packet, 5)) != 0)
1178 sshbuf_reset(state->compression_buffer);
1179 if ((r = compress_buffer(ssh, state->outgoing_packet,
1180 state->compression_buffer)) != 0)
1182 sshbuf_reset(state->outgoing_packet);
1183 if ((r = sshbuf_put(state->outgoing_packet,
1184 "\0\0\0\0\0", 5)) != 0 ||
1185 (r = sshbuf_putb(state->outgoing_packet,
1186 state->compression_buffer)) != 0)
1188 DBG(debug("compression: raw %d compressed %zd", len,
1189 sshbuf_len(state->outgoing_packet)));
1192 /* sizeof (packet_len + pad_len + payload) */
1193 len = sshbuf_len(state->outgoing_packet);
1196 * calc size of padding, alloc space, get random data,
1197 * minimum padding is 4 bytes
1199 len -= aadlen; /* packet length is not encrypted for EtM modes */
1200 padlen = block_size - (len % block_size);
1202 padlen += block_size;
1203 if (state->extra_pad) {
1204 /* will wrap if extra_pad+padlen > 255 */
1206 roundup(state->extra_pad, block_size);
1207 pad = state->extra_pad -
1208 ((len + padlen) % state->extra_pad);
1209 DBG(debug3("%s: adding %d (len %d padlen %d extra_pad %d)",
1210 __func__, pad, len, padlen, state->extra_pad));
1212 state->extra_pad = 0;
1214 if ((r = sshbuf_reserve(state->outgoing_packet, padlen, &cp)) != 0)
1216 if (enc && !state->send_context.plaintext) {
1217 /* random padding */
1218 arc4random_buf(cp, padlen);
1221 explicit_bzero(cp, padlen);
1223 /* sizeof (packet_len + pad_len + payload + padding) */
1224 len = sshbuf_len(state->outgoing_packet);
1225 cp = sshbuf_mutable_ptr(state->outgoing_packet);
1227 r = SSH_ERR_INTERNAL_ERROR;
1230 /* packet_length includes payload, padding and padding length field */
1231 POKE_U32(cp, len - 4);
1233 DBG(debug("send: len %d (includes padlen %d, aadlen %d)",
1234 len, padlen, aadlen));
1236 /* compute MAC over seqnr and packet(length fields, payload, padding) */
1237 if (mac && mac->enabled && !mac->etm) {
1238 if ((r = mac_compute(mac, state->p_send.seqnr,
1239 sshbuf_ptr(state->outgoing_packet), len,
1240 macbuf, sizeof(macbuf))) != 0)
1242 DBG(debug("done calc MAC out #%d", state->p_send.seqnr));
1244 /* encrypt packet and append to output buffer. */
1245 if ((r = sshbuf_reserve(state->output,
1246 sshbuf_len(state->outgoing_packet) + authlen, &cp)) != 0)
1248 if ((r = cipher_crypt(&state->send_context, state->p_send.seqnr, cp,
1249 sshbuf_ptr(state->outgoing_packet),
1250 len - aadlen, aadlen, authlen)) != 0)
1252 /* append unencrypted MAC */
1253 if (mac && mac->enabled) {
1255 /* EtM: compute mac over aadlen + cipher text */
1256 if ((r = mac_compute(mac, state->p_send.seqnr,
1257 cp, len, macbuf, sizeof(macbuf))) != 0)
1259 DBG(debug("done calc MAC(EtM) out #%d",
1260 state->p_send.seqnr));
1262 if ((r = sshbuf_put(state->output, macbuf, mac->mac_len)) != 0)
1266 fprintf(stderr, "encrypted: ");
1267 sshbuf_dump(state->output, stderr);
1269 /* increment sequence number for outgoing packets */
1270 if (++state->p_send.seqnr == 0)
1271 logit("outgoing seqnr wraps around");
1272 if (++state->p_send.packets == 0)
1273 if (!(ssh->compat & SSH_BUG_NOREKEY))
1274 return SSH_ERR_NEED_REKEY;
1275 state->p_send.blocks += len / block_size;
1276 state->p_send.bytes += len;
1277 sshbuf_reset(state->outgoing_packet);
1279 if (type == SSH2_MSG_NEWKEYS)
1280 r = ssh_set_newkeys(ssh, MODE_OUT);
1281 else if (type == SSH2_MSG_USERAUTH_SUCCESS && state->server_side)
1282 r = ssh_packet_enable_delayed_compress(ssh);
1289 /* returns non-zero if the specified packet type is usec by KEX */
1291 ssh_packet_type_is_kex(u_char type)
1294 type >= SSH2_MSG_TRANSPORT_MIN &&
1295 type <= SSH2_MSG_TRANSPORT_MAX &&
1296 type != SSH2_MSG_SERVICE_REQUEST &&
1297 type != SSH2_MSG_SERVICE_ACCEPT &&
1298 type != SSH2_MSG_EXT_INFO;
1302 ssh_packet_send2(struct ssh *ssh)
1304 struct session_state *state = ssh->state;
1309 if (sshbuf_len(state->outgoing_packet) < 6)
1310 return SSH_ERR_INTERNAL_ERROR;
1311 type = sshbuf_ptr(state->outgoing_packet)[5];
1312 need_rekey = !ssh_packet_type_is_kex(type) &&
1313 ssh_packet_need_rekeying(ssh, sshbuf_len(state->outgoing_packet));
1316 * During rekeying we can only send key exchange messages.
1317 * Queue everything else.
1319 if ((need_rekey || state->rekeying) && !ssh_packet_type_is_kex(type)) {
1321 debug3("%s: rekex triggered", __func__);
1322 debug("enqueue packet: %u", type);
1323 p = calloc(1, sizeof(*p));
1325 return SSH_ERR_ALLOC_FAIL;
1327 p->payload = state->outgoing_packet;
1328 TAILQ_INSERT_TAIL(&state->outgoing, p, next);
1329 state->outgoing_packet = sshbuf_new();
1330 if (state->outgoing_packet == NULL)
1331 return SSH_ERR_ALLOC_FAIL;
1334 * This packet triggered a rekey, so send the
1336 * NB. reenters this function via kex_start_rekex().
1338 return kex_start_rekex(ssh);
1343 /* rekeying starts with sending KEXINIT */
1344 if (type == SSH2_MSG_KEXINIT)
1345 state->rekeying = 1;
1347 if ((r = ssh_packet_send2_wrapped(ssh)) != 0)
1350 /* after a NEWKEYS message we can send the complete queue */
1351 if (type == SSH2_MSG_NEWKEYS) {
1352 state->rekeying = 0;
1353 state->rekey_time = monotime();
1354 while ((p = TAILQ_FIRST(&state->outgoing))) {
1357 * If this packet triggers a rekex, then skip the
1358 * remaining packets in the queue for now.
1359 * NB. re-enters this function via kex_start_rekex.
1361 if (ssh_packet_need_rekeying(ssh,
1362 sshbuf_len(p->payload))) {
1363 debug3("%s: queued packet triggered rekex",
1365 return kex_start_rekex(ssh);
1367 debug("dequeue packet: %u", type);
1368 sshbuf_free(state->outgoing_packet);
1369 state->outgoing_packet = p->payload;
1370 TAILQ_REMOVE(&state->outgoing, p, next);
1371 memset(p, 0, sizeof(*p));
1373 if ((r = ssh_packet_send2_wrapped(ssh)) != 0)
1381 * Waits until a packet has been received, and returns its type. Note that
1382 * no other data is processed until this returns, so this function should not
1383 * be used during the interactive session.
1387 ssh_packet_read_seqnr(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1389 struct session_state *state = ssh->state;
1390 int len, r, ms_remain;
1393 struct timeval timeout, start, *timeoutp = NULL;
1395 DBG(debug("packet_read()"));
1397 setp = calloc(howmany(state->connection_in + 1,
1398 NFDBITS), sizeof(fd_mask));
1400 return SSH_ERR_ALLOC_FAIL;
1403 * Since we are blocking, ensure that all written packets have
1406 if ((r = ssh_packet_write_wait(ssh)) != 0)
1409 /* Stay in the loop until we have received a complete packet. */
1411 /* Try to read a packet from the buffer. */
1412 r = ssh_packet_read_poll_seqnr(ssh, typep, seqnr_p);
1416 *typep == SSH_SMSG_SUCCESS
1417 || *typep == SSH_SMSG_FAILURE
1418 || *typep == SSH_CMSG_EOF
1419 || *typep == SSH_CMSG_EXIT_CONFIRMATION))
1420 if ((r = sshpkt_get_end(ssh)) != 0)
1422 /* If we got a packet, return it. */
1423 if (*typep != SSH_MSG_NONE)
1426 * Otherwise, wait for some data to arrive, add it to the
1427 * buffer, and try again.
1429 memset(setp, 0, howmany(state->connection_in + 1,
1430 NFDBITS) * sizeof(fd_mask));
1431 FD_SET(state->connection_in, setp);
1433 if (state->packet_timeout_ms > 0) {
1434 ms_remain = state->packet_timeout_ms;
1435 timeoutp = &timeout;
1437 /* Wait for some data to arrive. */
1439 if (state->packet_timeout_ms != -1) {
1440 ms_to_timeval(&timeout, ms_remain);
1441 gettimeofday(&start, NULL);
1443 if ((r = select(state->connection_in + 1, setp,
1444 NULL, NULL, timeoutp)) >= 0)
1446 if (errno != EAGAIN && errno != EINTR &&
1447 errno != EWOULDBLOCK)
1449 if (state->packet_timeout_ms == -1)
1451 ms_subtract_diff(&start, &ms_remain);
1452 if (ms_remain <= 0) {
1458 return SSH_ERR_CONN_TIMEOUT;
1459 /* Read data from the socket. */
1460 len = read(state->connection_in, buf, sizeof(buf));
1462 r = SSH_ERR_CONN_CLOSED;
1466 r = SSH_ERR_SYSTEM_ERROR;
1470 /* Append it to the buffer. */
1471 if ((r = ssh_packet_process_incoming(ssh, buf, len)) != 0)
1480 ssh_packet_read(struct ssh *ssh)
1485 if ((r = ssh_packet_read_seqnr(ssh, &type, NULL)) != 0)
1486 fatal("%s: %s", __func__, ssh_err(r));
1491 * Waits until a packet has been received, verifies that its type matches
1492 * that given, and gives a fatal error and exits if there is a mismatch.
1496 ssh_packet_read_expect(struct ssh *ssh, u_int expected_type)
1501 if ((r = ssh_packet_read_seqnr(ssh, &type, NULL)) != 0)
1503 if (type != expected_type) {
1504 if ((r = sshpkt_disconnect(ssh,
1505 "Protocol error: expected packet type %d, got %d",
1506 expected_type, type)) != 0)
1508 return SSH_ERR_PROTOCOL_ERROR;
1513 /* Checks if a full packet is available in the data received so far via
1514 * packet_process_incoming. If so, reads the packet; otherwise returns
1515 * SSH_MSG_NONE. This does not wait for data from the connection.
1517 * SSH_MSG_DISCONNECT is handled specially here. Also,
1518 * SSH_MSG_IGNORE messages are skipped by this function and are never returned
1523 ssh_packet_read_poll1(struct ssh *ssh, u_char *typep)
1525 struct session_state *state = ssh->state;
1526 u_int len, padded_len;
1530 u_int checksum, stored_checksum;
1533 *typep = SSH_MSG_NONE;
1535 /* Check if input size is less than minimum packet size. */
1536 if (sshbuf_len(state->input) < 4 + 8)
1538 /* Get length of incoming packet. */
1539 len = PEEK_U32(sshbuf_ptr(state->input));
1540 if (len < 1 + 2 + 2 || len > 256 * 1024) {
1541 if ((r = sshpkt_disconnect(ssh, "Bad packet length %u",
1544 return SSH_ERR_CONN_CORRUPT;
1546 padded_len = (len + 8) & ~7;
1548 /* Check if the packet has been entirely received. */
1549 if (sshbuf_len(state->input) < 4 + padded_len)
1552 /* The entire packet is in buffer. */
1554 /* Consume packet length. */
1555 if ((r = sshbuf_consume(state->input, 4)) != 0)
1559 * Cryptographic attack detector for ssh
1560 * (C)1998 CORE-SDI, Buenos Aires Argentina
1561 * Ariel Futoransky(futo@core-sdi.com)
1563 if (!state->receive_context.plaintext) {
1565 switch (detect_attack(&state->deattack,
1566 sshbuf_ptr(state->input), padded_len)) {
1569 case DEATTACK_DETECTED:
1570 emsg = "crc32 compensation attack detected";
1572 case DEATTACK_DOS_DETECTED:
1573 emsg = "deattack denial of service detected";
1576 emsg = "deattack error";
1581 if ((r = sshpkt_disconnect(ssh, "%s", emsg)) != 0 ||
1582 (r = ssh_packet_write_wait(ssh)) != 0)
1584 return SSH_ERR_CONN_CORRUPT;
1588 /* Decrypt data to incoming_packet. */
1589 sshbuf_reset(state->incoming_packet);
1590 if ((r = sshbuf_reserve(state->incoming_packet, padded_len, &p)) != 0)
1592 if ((r = cipher_crypt(&state->receive_context, 0, p,
1593 sshbuf_ptr(state->input), padded_len, 0, 0)) != 0)
1596 if ((r = sshbuf_consume(state->input, padded_len)) != 0)
1600 fprintf(stderr, "read_poll plain: ");
1601 sshbuf_dump(state->incoming_packet, stderr);
1604 /* Compute packet checksum. */
1605 checksum = ssh_crc32(sshbuf_ptr(state->incoming_packet),
1606 sshbuf_len(state->incoming_packet) - 4);
1609 if ((r = sshbuf_consume(state->incoming_packet, 8 - len % 8)) != 0)
1612 /* Test check bytes. */
1613 if (len != sshbuf_len(state->incoming_packet)) {
1614 error("%s: len %d != sshbuf_len %zd", __func__,
1615 len, sshbuf_len(state->incoming_packet));
1616 if ((r = sshpkt_disconnect(ssh, "invalid packet length")) != 0 ||
1617 (r = ssh_packet_write_wait(ssh)) != 0)
1619 return SSH_ERR_CONN_CORRUPT;
1622 cp = sshbuf_ptr(state->incoming_packet) + len - 4;
1623 stored_checksum = PEEK_U32(cp);
1624 if (checksum != stored_checksum) {
1625 error("Corrupted check bytes on input");
1626 if ((r = sshpkt_disconnect(ssh, "connection corrupted")) != 0 ||
1627 (r = ssh_packet_write_wait(ssh)) != 0)
1629 return SSH_ERR_CONN_CORRUPT;
1631 if ((r = sshbuf_consume_end(state->incoming_packet, 4)) < 0)
1634 if (state->packet_compression) {
1635 sshbuf_reset(state->compression_buffer);
1636 if ((r = uncompress_buffer(ssh, state->incoming_packet,
1637 state->compression_buffer)) != 0)
1639 sshbuf_reset(state->incoming_packet);
1640 if ((r = sshbuf_putb(state->incoming_packet,
1641 state->compression_buffer)) != 0)
1644 state->p_read.packets++;
1645 state->p_read.bytes += padded_len + 4;
1646 if ((r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
1648 if (*typep < SSH_MSG_MIN || *typep > SSH_MSG_MAX) {
1649 error("Invalid ssh1 packet type: %d", *typep);
1650 if ((r = sshpkt_disconnect(ssh, "invalid packet type")) != 0 ||
1651 (r = ssh_packet_write_wait(ssh)) != 0)
1653 return SSH_ERR_PROTOCOL_ERROR;
1661 ssh_packet_read_poll2(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1663 struct session_state *state = ssh->state;
1665 u_char *cp, macbuf[SSH_DIGEST_MAX_LENGTH];
1666 u_int maclen, aadlen = 0, authlen = 0, block_size;
1667 struct sshenc *enc = NULL;
1668 struct sshmac *mac = NULL;
1669 struct sshcomp *comp = NULL;
1672 *typep = SSH_MSG_NONE;
1674 if (state->packet_discard)
1677 if (state->newkeys[MODE_IN] != NULL) {
1678 enc = &state->newkeys[MODE_IN]->enc;
1679 mac = &state->newkeys[MODE_IN]->mac;
1680 comp = &state->newkeys[MODE_IN]->comp;
1681 /* disable mac for authenticated encryption */
1682 if ((authlen = cipher_authlen(enc->cipher)) != 0)
1685 maclen = mac && mac->enabled ? mac->mac_len : 0;
1686 block_size = enc ? enc->block_size : 8;
1687 aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
1689 if (aadlen && state->packlen == 0) {
1690 if (cipher_get_length(&state->receive_context,
1691 &state->packlen, state->p_read.seqnr,
1692 sshbuf_ptr(state->input), sshbuf_len(state->input)) != 0)
1694 if (state->packlen < 1 + 4 ||
1695 state->packlen > PACKET_MAX_SIZE) {
1697 sshbuf_dump(state->input, stderr);
1699 logit("Bad packet length %u.", state->packlen);
1700 if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0)
1702 return SSH_ERR_CONN_CORRUPT;
1704 sshbuf_reset(state->incoming_packet);
1705 } else if (state->packlen == 0) {
1707 * check if input size is less than the cipher block size,
1708 * decrypt first block and extract length of incoming packet
1710 if (sshbuf_len(state->input) < block_size)
1712 sshbuf_reset(state->incoming_packet);
1713 if ((r = sshbuf_reserve(state->incoming_packet, block_size,
1716 if ((r = cipher_crypt(&state->receive_context,
1717 state->p_send.seqnr, cp, sshbuf_ptr(state->input),
1718 block_size, 0, 0)) != 0)
1720 state->packlen = PEEK_U32(sshbuf_ptr(state->incoming_packet));
1721 if (state->packlen < 1 + 4 ||
1722 state->packlen > PACKET_MAX_SIZE) {
1724 fprintf(stderr, "input: \n");
1725 sshbuf_dump(state->input, stderr);
1726 fprintf(stderr, "incoming_packet: \n");
1727 sshbuf_dump(state->incoming_packet, stderr);
1729 logit("Bad packet length %u.", state->packlen);
1730 return ssh_packet_start_discard(ssh, enc, mac,
1731 state->packlen, PACKET_MAX_SIZE);
1733 if ((r = sshbuf_consume(state->input, block_size)) != 0)
1736 DBG(debug("input: packet len %u", state->packlen+4));
1739 /* only the payload is encrypted */
1740 need = state->packlen;
1743 * the payload size and the payload are encrypted, but we
1744 * have a partial packet of block_size bytes
1746 need = 4 + state->packlen - block_size;
1748 DBG(debug("partial packet: block %d, need %d, maclen %d, authlen %d,"
1749 " aadlen %d", block_size, need, maclen, authlen, aadlen));
1750 if (need % block_size != 0) {
1751 logit("padding error: need %d block %d mod %d",
1752 need, block_size, need % block_size);
1753 return ssh_packet_start_discard(ssh, enc, mac,
1754 state->packlen, PACKET_MAX_SIZE - block_size);
1757 * check if the entire packet has been received and
1758 * decrypt into incoming_packet:
1759 * 'aadlen' bytes are unencrypted, but authenticated.
1760 * 'need' bytes are encrypted, followed by either
1761 * 'authlen' bytes of authentication tag or
1762 * 'maclen' bytes of message authentication code.
1764 if (sshbuf_len(state->input) < aadlen + need + authlen + maclen)
1767 fprintf(stderr, "read_poll enc/full: ");
1768 sshbuf_dump(state->input, stderr);
1770 /* EtM: compute mac over encrypted input */
1771 if (mac && mac->enabled && mac->etm) {
1772 if ((r = mac_compute(mac, state->p_read.seqnr,
1773 sshbuf_ptr(state->input), aadlen + need,
1774 macbuf, sizeof(macbuf))) != 0)
1777 if ((r = sshbuf_reserve(state->incoming_packet, aadlen + need,
1780 if ((r = cipher_crypt(&state->receive_context, state->p_read.seqnr, cp,
1781 sshbuf_ptr(state->input), need, aadlen, authlen)) != 0)
1783 if ((r = sshbuf_consume(state->input, aadlen + need + authlen)) != 0)
1786 * compute MAC over seqnr and packet,
1787 * increment sequence number for incoming packet
1789 if (mac && mac->enabled) {
1791 if ((r = mac_compute(mac, state->p_read.seqnr,
1792 sshbuf_ptr(state->incoming_packet),
1793 sshbuf_len(state->incoming_packet),
1794 macbuf, sizeof(macbuf))) != 0)
1796 if (timingsafe_bcmp(macbuf, sshbuf_ptr(state->input),
1797 mac->mac_len) != 0) {
1798 logit("Corrupted MAC on input.");
1799 if (need > PACKET_MAX_SIZE)
1800 return SSH_ERR_INTERNAL_ERROR;
1801 return ssh_packet_start_discard(ssh, enc, mac,
1802 state->packlen, PACKET_MAX_SIZE - need);
1805 DBG(debug("MAC #%d ok", state->p_read.seqnr));
1806 if ((r = sshbuf_consume(state->input, mac->mac_len)) != 0)
1809 if (seqnr_p != NULL)
1810 *seqnr_p = state->p_read.seqnr;
1811 if (++state->p_read.seqnr == 0)
1812 logit("incoming seqnr wraps around");
1813 if (++state->p_read.packets == 0)
1814 if (!(ssh->compat & SSH_BUG_NOREKEY))
1815 return SSH_ERR_NEED_REKEY;
1816 state->p_read.blocks += (state->packlen + 4) / block_size;
1817 state->p_read.bytes += state->packlen + 4;
1820 padlen = sshbuf_ptr(state->incoming_packet)[4];
1821 DBG(debug("input: padlen %d", padlen));
1823 if ((r = sshpkt_disconnect(ssh,
1824 "Corrupted padlen %d on input.", padlen)) != 0 ||
1825 (r = ssh_packet_write_wait(ssh)) != 0)
1827 return SSH_ERR_CONN_CORRUPT;
1830 /* skip packet size + padlen, discard padding */
1831 if ((r = sshbuf_consume(state->incoming_packet, 4 + 1)) != 0 ||
1832 ((r = sshbuf_consume_end(state->incoming_packet, padlen)) != 0))
1835 DBG(debug("input: len before de-compress %zd",
1836 sshbuf_len(state->incoming_packet)));
1837 if (comp && comp->enabled) {
1838 sshbuf_reset(state->compression_buffer);
1839 if ((r = uncompress_buffer(ssh, state->incoming_packet,
1840 state->compression_buffer)) != 0)
1842 sshbuf_reset(state->incoming_packet);
1843 if ((r = sshbuf_putb(state->incoming_packet,
1844 state->compression_buffer)) != 0)
1846 DBG(debug("input: len after de-compress %zd",
1847 sshbuf_len(state->incoming_packet)));
1850 * get packet type, implies consume.
1851 * return length of payload (without type field)
1853 if ((r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
1855 if (ssh_packet_log_type(*typep))
1856 debug3("receive packet: type %u", *typep);
1857 if (*typep < SSH2_MSG_MIN || *typep >= SSH2_MSG_LOCAL_MIN) {
1858 if ((r = sshpkt_disconnect(ssh,
1859 "Invalid ssh2 packet type: %d", *typep)) != 0 ||
1860 (r = ssh_packet_write_wait(ssh)) != 0)
1862 return SSH_ERR_PROTOCOL_ERROR;
1864 if (*typep == SSH2_MSG_NEWKEYS)
1865 r = ssh_set_newkeys(ssh, MODE_IN);
1866 else if (*typep == SSH2_MSG_USERAUTH_SUCCESS && !state->server_side)
1867 r = ssh_packet_enable_delayed_compress(ssh);
1871 fprintf(stderr, "read/plain[%d]:\r\n", *typep);
1872 sshbuf_dump(state->incoming_packet, stderr);
1874 /* reset for next packet */
1877 /* do we need to rekey? */
1878 if (ssh_packet_need_rekeying(ssh, 0)) {
1879 debug3("%s: rekex triggered", __func__);
1880 if ((r = kex_start_rekex(ssh)) != 0)
1888 ssh_packet_read_poll_seqnr(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1890 struct session_state *state = ssh->state;
1891 u_int reason, seqnr;
1898 r = ssh_packet_read_poll2(ssh, typep, seqnr_p);
1902 state->keep_alive_timeouts = 0;
1903 DBG(debug("received packet type %d", *typep));
1906 case SSH2_MSG_IGNORE:
1907 debug3("Received SSH2_MSG_IGNORE");
1909 case SSH2_MSG_DEBUG:
1910 if ((r = sshpkt_get_u8(ssh, NULL)) != 0 ||
1911 (r = sshpkt_get_string(ssh, &msg, NULL)) != 0 ||
1912 (r = sshpkt_get_string(ssh, NULL, NULL)) != 0) {
1916 debug("Remote: %.900s", msg);
1919 case SSH2_MSG_DISCONNECT:
1920 if ((r = sshpkt_get_u32(ssh, &reason)) != 0 ||
1921 (r = sshpkt_get_string(ssh, &msg, NULL)) != 0)
1923 /* Ignore normal client exit notifications */
1924 do_log2(ssh->state->server_side &&
1925 reason == SSH2_DISCONNECT_BY_APPLICATION ?
1926 SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_ERROR,
1927 "Received disconnect from %s port %d:"
1928 "%u: %.400s", ssh_remote_ipaddr(ssh),
1929 ssh_remote_port(ssh), reason, msg);
1931 return SSH_ERR_DISCONNECTED;
1932 case SSH2_MSG_UNIMPLEMENTED:
1933 if ((r = sshpkt_get_u32(ssh, &seqnr)) != 0)
1935 debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1942 r = ssh_packet_read_poll1(ssh, typep);
1945 return SSH_MSG_NONE;
1946 case SSH_MSG_IGNORE:
1949 if ((r = sshpkt_get_string(ssh, &msg, NULL)) != 0)
1951 debug("Remote: %.900s", msg);
1954 case SSH_MSG_DISCONNECT:
1955 if ((r = sshpkt_get_string(ssh, &msg, NULL)) != 0)
1957 logit("Received disconnect from %s port %d: "
1958 "%.400s", ssh_remote_ipaddr(ssh),
1959 ssh_remote_port(ssh), msg);
1961 return SSH_ERR_DISCONNECTED;
1963 DBG(debug("received packet type %d", *typep));
1971 * Buffers the given amount of input characters. This is intended to be used
1972 * together with packet_read_poll.
1976 ssh_packet_process_incoming(struct ssh *ssh, const char *buf, u_int len)
1978 struct session_state *state = ssh->state;
1981 if (state->packet_discard) {
1982 state->keep_alive_timeouts = 0; /* ?? */
1983 if (len >= state->packet_discard) {
1984 if ((r = ssh_packet_stop_discard(ssh)) != 0)
1987 state->packet_discard -= len;
1990 if ((r = sshbuf_put(ssh->state->input, buf, len)) != 0)
1997 ssh_packet_remaining(struct ssh *ssh)
1999 return sshbuf_len(ssh->state->incoming_packet);
2003 * Sends a diagnostic message from the server to the client. This message
2004 * can be sent at any time (but not while constructing another message). The
2005 * message is printed immediately, but only if the client is being executed
2006 * in verbose mode. These messages are primarily intended to ease debugging
2007 * authentication problems. The length of the formatted message must not
2008 * exceed 1024 bytes. This will automatically call ssh_packet_write_wait.
2011 ssh_packet_send_debug(struct ssh *ssh, const char *fmt,...)
2017 if (compat20 && (ssh->compat & SSH_BUG_DEBUG))
2020 va_start(args, fmt);
2021 vsnprintf(buf, sizeof(buf), fmt, args);
2025 if ((r = sshpkt_start(ssh, SSH2_MSG_DEBUG)) != 0 ||
2026 (r = sshpkt_put_u8(ssh, 0)) != 0 || /* always display */
2027 (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
2028 (r = sshpkt_put_cstring(ssh, "")) != 0 ||
2029 (r = sshpkt_send(ssh)) != 0)
2030 fatal("%s: %s", __func__, ssh_err(r));
2032 if ((r = sshpkt_start(ssh, SSH_MSG_DEBUG)) != 0 ||
2033 (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
2034 (r = sshpkt_send(ssh)) != 0)
2035 fatal("%s: %s", __func__, ssh_err(r));
2037 if ((r = ssh_packet_write_wait(ssh)) != 0)
2038 fatal("%s: %s", __func__, ssh_err(r));
2042 * Pretty-print connection-terminating errors and exit.
2045 sshpkt_fatal(struct ssh *ssh, const char *tag, int r)
2048 case SSH_ERR_CONN_CLOSED:
2049 logit("Connection closed by %.200s port %d",
2050 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
2052 case SSH_ERR_CONN_TIMEOUT:
2053 logit("Connection %s %.200s port %d timed out",
2054 ssh->state->server_side ? "from" : "to",
2055 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
2057 case SSH_ERR_DISCONNECTED:
2058 logit("Disconnected from %.200s port %d",
2059 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
2061 case SSH_ERR_SYSTEM_ERROR:
2062 if (errno == ECONNRESET) {
2063 logit("Connection reset by %.200s port %d",
2064 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
2068 case SSH_ERR_NO_CIPHER_ALG_MATCH:
2069 case SSH_ERR_NO_MAC_ALG_MATCH:
2070 case SSH_ERR_NO_COMPRESS_ALG_MATCH:
2071 case SSH_ERR_NO_KEX_ALG_MATCH:
2072 case SSH_ERR_NO_HOSTKEY_ALG_MATCH:
2073 if (ssh && ssh->kex && ssh->kex->failed_choice) {
2074 fatal("Unable to negotiate with %.200s port %d: %s. "
2075 "Their offer: %s", ssh_remote_ipaddr(ssh),
2076 ssh_remote_port(ssh), ssh_err(r),
2077 ssh->kex->failed_choice);
2081 fatal("%s%sConnection %s %.200s port %d: %s",
2082 tag != NULL ? tag : "", tag != NULL ? ": " : "",
2083 ssh->state->server_side ? "from" : "to",
2084 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), ssh_err(r));
2089 * Logs the error plus constructs and sends a disconnect packet, closes the
2090 * connection, and exits. This function never returns. The error message
2091 * should not contain a newline. The length of the formatted message must
2092 * not exceed 1024 bytes.
2095 ssh_packet_disconnect(struct ssh *ssh, const char *fmt,...)
2099 static int disconnecting = 0;
2102 if (disconnecting) /* Guard against recursive invocations. */
2103 fatal("packet_disconnect called recursively.");
2107 * Format the message. Note that the caller must make sure the
2108 * message is of limited size.
2110 va_start(args, fmt);
2111 vsnprintf(buf, sizeof(buf), fmt, args);
2114 /* Display the error locally */
2115 logit("Disconnecting: %.100s", buf);
2118 * Send the disconnect message to the other side, and wait
2119 * for it to get sent.
2121 if ((r = sshpkt_disconnect(ssh, "%s", buf)) != 0)
2122 sshpkt_fatal(ssh, __func__, r);
2124 if ((r = ssh_packet_write_wait(ssh)) != 0)
2125 sshpkt_fatal(ssh, __func__, r);
2127 /* Close the connection. */
2128 ssh_packet_close(ssh);
2133 * Checks if there is any buffered output, and tries to write some of
2137 ssh_packet_write_poll(struct ssh *ssh)
2139 struct session_state *state = ssh->state;
2140 int len = sshbuf_len(state->output);
2144 len = write(state->connection_out,
2145 sshbuf_ptr(state->output), len);
2147 if (errno == EINTR || errno == EAGAIN ||
2148 errno == EWOULDBLOCK)
2150 return SSH_ERR_SYSTEM_ERROR;
2153 return SSH_ERR_CONN_CLOSED;
2154 if ((r = sshbuf_consume(state->output, len)) != 0)
2161 * Calls packet_write_poll repeatedly until all pending output data has been
2165 ssh_packet_write_wait(struct ssh *ssh)
2168 int ret, r, ms_remain = 0;
2169 struct timeval start, timeout, *timeoutp = NULL;
2170 struct session_state *state = ssh->state;
2172 setp = calloc(howmany(state->connection_out + 1,
2173 NFDBITS), sizeof(fd_mask));
2175 return SSH_ERR_ALLOC_FAIL;
2176 if ((r = ssh_packet_write_poll(ssh)) != 0) {
2180 while (ssh_packet_have_data_to_write(ssh)) {
2181 memset(setp, 0, howmany(state->connection_out + 1,
2182 NFDBITS) * sizeof(fd_mask));
2183 FD_SET(state->connection_out, setp);
2185 if (state->packet_timeout_ms > 0) {
2186 ms_remain = state->packet_timeout_ms;
2187 timeoutp = &timeout;
2190 if (state->packet_timeout_ms != -1) {
2191 ms_to_timeval(&timeout, ms_remain);
2192 gettimeofday(&start, NULL);
2194 if ((ret = select(state->connection_out + 1,
2195 NULL, setp, NULL, timeoutp)) >= 0)
2197 if (errno != EAGAIN && errno != EINTR &&
2198 errno != EWOULDBLOCK)
2200 if (state->packet_timeout_ms == -1)
2202 ms_subtract_diff(&start, &ms_remain);
2203 if (ms_remain <= 0) {
2210 return SSH_ERR_CONN_TIMEOUT;
2212 if ((r = ssh_packet_write_poll(ssh)) != 0) {
2221 /* Returns true if there is buffered data to write to the connection. */
2224 ssh_packet_have_data_to_write(struct ssh *ssh)
2226 return sshbuf_len(ssh->state->output) != 0;
2229 /* Returns true if there is not too much data to write to the connection. */
2232 ssh_packet_not_very_much_data_to_write(struct ssh *ssh)
2234 if (ssh->state->interactive_mode)
2235 return sshbuf_len(ssh->state->output) < 16384;
2237 return sshbuf_len(ssh->state->output) < 128 * 1024;
2241 ssh_packet_set_tos(struct ssh *ssh, int tos)
2243 #ifndef IP_TOS_IS_BROKEN
2244 if (!ssh_packet_connection_is_on_socket(ssh))
2246 switch (ssh_packet_connection_af(ssh)) {
2249 debug3("%s: set IP_TOS 0x%02x", __func__, tos);
2250 if (setsockopt(ssh->state->connection_in,
2251 IPPROTO_IP, IP_TOS, &tos, sizeof(tos)) < 0)
2252 error("setsockopt IP_TOS %d: %.100s:",
2253 tos, strerror(errno));
2255 # endif /* IP_TOS */
2258 debug3("%s: set IPV6_TCLASS 0x%02x", __func__, tos);
2259 if (setsockopt(ssh->state->connection_in,
2260 IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof(tos)) < 0)
2261 error("setsockopt IPV6_TCLASS %d: %.100s:",
2262 tos, strerror(errno));
2264 # endif /* IPV6_TCLASS */
2266 #endif /* IP_TOS_IS_BROKEN */
2269 /* Informs that the current session is interactive. Sets IP flags for that. */
2272 ssh_packet_set_interactive(struct ssh *ssh, int interactive, int qos_interactive, int qos_bulk)
2274 struct session_state *state = ssh->state;
2276 if (state->set_interactive_called)
2278 state->set_interactive_called = 1;
2280 /* Record that we are in interactive mode. */
2281 state->interactive_mode = interactive;
2283 /* Only set socket options if using a socket. */
2284 if (!ssh_packet_connection_is_on_socket(ssh))
2286 set_nodelay(state->connection_in);
2287 ssh_packet_set_tos(ssh, interactive ? qos_interactive :
2291 /* Returns true if the current connection is interactive. */
2294 ssh_packet_is_interactive(struct ssh *ssh)
2296 return ssh->state->interactive_mode;
2300 ssh_packet_set_maxsize(struct ssh *ssh, u_int s)
2302 struct session_state *state = ssh->state;
2304 if (state->set_maxsize_called) {
2305 logit("packet_set_maxsize: called twice: old %d new %d",
2306 state->max_packet_size, s);
2309 if (s < 4 * 1024 || s > 1024 * 1024) {
2310 logit("packet_set_maxsize: bad size %d", s);
2313 state->set_maxsize_called = 1;
2314 debug("packet_set_maxsize: setting to %d", s);
2315 state->max_packet_size = s;
2320 ssh_packet_inc_alive_timeouts(struct ssh *ssh)
2322 return ++ssh->state->keep_alive_timeouts;
2326 ssh_packet_set_alive_timeouts(struct ssh *ssh, int ka)
2328 ssh->state->keep_alive_timeouts = ka;
2332 ssh_packet_get_maxsize(struct ssh *ssh)
2334 return ssh->state->max_packet_size;
2338 * 9.2. Ignored Data Message
2340 * byte SSH_MSG_IGNORE
2343 * All implementations MUST understand (and ignore) this message at any
2344 * time (after receiving the protocol version). No implementation is
2345 * required to send them. This message can be used as an additional
2346 * protection measure against advanced traffic analysis techniques.
2349 ssh_packet_send_ignore(struct ssh *ssh, int nbytes)
2354 if ((r = sshpkt_start(ssh, compat20 ?
2355 SSH2_MSG_IGNORE : SSH_MSG_IGNORE)) != 0 ||
2356 (r = sshpkt_put_u32(ssh, nbytes)) != 0)
2357 fatal("%s: %s", __func__, ssh_err(r));
2358 for (i = 0; i < nbytes; i++) {
2361 if ((r = sshpkt_put_u8(ssh, (u_char)rnd & 0xff)) != 0)
2362 fatal("%s: %s", __func__, ssh_err(r));
2368 ssh_packet_set_rekey_limits(struct ssh *ssh, u_int64_t bytes, time_t seconds)
2370 debug3("rekey after %llu bytes, %d seconds", (unsigned long long)bytes,
2372 ssh->state->rekey_limit = bytes;
2373 ssh->state->rekey_interval = seconds;
2377 ssh_packet_get_rekey_timeout(struct ssh *ssh)
2381 seconds = ssh->state->rekey_time + ssh->state->rekey_interval -
2383 return (seconds <= 0 ? 1 : seconds);
2387 ssh_packet_set_server(struct ssh *ssh)
2389 ssh->state->server_side = 1;
2393 ssh_packet_set_authenticated(struct ssh *ssh)
2395 ssh->state->after_authentication = 1;
2399 ssh_packet_get_input(struct ssh *ssh)
2401 return (void *)ssh->state->input;
2405 ssh_packet_get_output(struct ssh *ssh)
2407 return (void *)ssh->state->output;
2410 /* Reset after_authentication and reset compression in post-auth privsep */
2412 ssh_packet_set_postauth(struct ssh *ssh)
2414 struct sshcomp *comp;
2417 debug("%s: called", __func__);
2418 /* This was set in net child, but is not visible in user child */
2419 ssh->state->after_authentication = 1;
2420 ssh->state->rekeying = 0;
2421 for (mode = 0; mode < MODE_MAX; mode++) {
2422 if (ssh->state->newkeys[mode] == NULL)
2424 comp = &ssh->state->newkeys[mode]->comp;
2425 if (comp && comp->enabled &&
2426 (r = ssh_packet_init_compression(ssh)) != 0)
2432 /* Packet state (de-)serialization for privsep */
2434 /* turn kex into a blob for packet state serialization */
2436 kex_to_blob(struct sshbuf *m, struct kex *kex)
2440 if ((r = sshbuf_put_string(m, kex->session_id,
2441 kex->session_id_len)) != 0 ||
2442 (r = sshbuf_put_u32(m, kex->we_need)) != 0 ||
2443 (r = sshbuf_put_u32(m, kex->hostkey_type)) != 0 ||
2444 (r = sshbuf_put_u32(m, kex->kex_type)) != 0 ||
2445 (r = sshbuf_put_stringb(m, kex->my)) != 0 ||
2446 (r = sshbuf_put_stringb(m, kex->peer)) != 0 ||
2447 (r = sshbuf_put_u32(m, kex->flags)) != 0 ||
2448 (r = sshbuf_put_cstring(m, kex->client_version_string)) != 0 ||
2449 (r = sshbuf_put_cstring(m, kex->server_version_string)) != 0)
2454 /* turn key exchange results into a blob for packet state serialization */
2456 newkeys_to_blob(struct sshbuf *m, struct ssh *ssh, int mode)
2459 struct sshcipher_ctx *cc;
2460 struct sshcomp *comp;
2463 struct newkeys *newkey;
2466 if ((newkey = ssh->state->newkeys[mode]) == NULL)
2467 return SSH_ERR_INTERNAL_ERROR;
2470 comp = &newkey->comp;
2471 cc = (mode == MODE_OUT) ? &ssh->state->send_context :
2472 &ssh->state->receive_context;
2473 if ((r = cipher_get_keyiv(cc, enc->iv, enc->iv_len)) != 0)
2475 if ((b = sshbuf_new()) == NULL)
2476 return SSH_ERR_ALLOC_FAIL;
2477 /* The cipher struct is constant and shared, you export pointer */
2478 if ((r = sshbuf_put_cstring(b, enc->name)) != 0 ||
2479 (r = sshbuf_put(b, &enc->cipher, sizeof(enc->cipher))) != 0 ||
2480 (r = sshbuf_put_u32(b, enc->enabled)) != 0 ||
2481 (r = sshbuf_put_u32(b, enc->block_size)) != 0 ||
2482 (r = sshbuf_put_string(b, enc->key, enc->key_len)) != 0 ||
2483 (r = sshbuf_put_string(b, enc->iv, enc->iv_len)) != 0)
2485 if (cipher_authlen(enc->cipher) == 0) {
2486 if ((r = sshbuf_put_cstring(b, mac->name)) != 0 ||
2487 (r = sshbuf_put_u32(b, mac->enabled)) != 0 ||
2488 (r = sshbuf_put_string(b, mac->key, mac->key_len)) != 0)
2491 if ((r = sshbuf_put_u32(b, comp->type)) != 0 ||
2492 (r = sshbuf_put_u32(b, comp->enabled)) != 0 ||
2493 (r = sshbuf_put_cstring(b, comp->name)) != 0)
2495 r = sshbuf_put_stringb(m, b);
2501 /* serialize packet state into a blob */
2503 ssh_packet_get_state(struct ssh *ssh, struct sshbuf *m)
2505 struct session_state *state = ssh->state;
2511 ssh1cipher = cipher_get_number(state->receive_context.cipher);
2512 slen = cipher_get_keyiv_len(&state->send_context);
2513 rlen = cipher_get_keyiv_len(&state->receive_context);
2514 if ((r = sshbuf_put_u32(m, state->remote_protocol_flags)) != 0 ||
2515 (r = sshbuf_put_u32(m, ssh1cipher)) != 0 ||
2516 (r = sshbuf_put_string(m, state->ssh1_key, state->ssh1_keylen)) != 0 ||
2517 (r = sshbuf_put_u32(m, slen)) != 0 ||
2518 (r = sshbuf_reserve(m, slen, &p)) != 0 ||
2519 (r = cipher_get_keyiv(&state->send_context, p, slen)) != 0 ||
2520 (r = sshbuf_put_u32(m, rlen)) != 0 ||
2521 (r = sshbuf_reserve(m, rlen, &p)) != 0 ||
2522 (r = cipher_get_keyiv(&state->receive_context, p, rlen)) != 0)
2525 if ((r = kex_to_blob(m, ssh->kex)) != 0 ||
2526 (r = newkeys_to_blob(m, ssh, MODE_OUT)) != 0 ||
2527 (r = newkeys_to_blob(m, ssh, MODE_IN)) != 0 ||
2528 (r = sshbuf_put_u64(m, state->rekey_limit)) != 0 ||
2529 (r = sshbuf_put_u32(m, state->rekey_interval)) != 0 ||
2530 (r = sshbuf_put_u32(m, state->p_send.seqnr)) != 0 ||
2531 (r = sshbuf_put_u64(m, state->p_send.blocks)) != 0 ||
2532 (r = sshbuf_put_u32(m, state->p_send.packets)) != 0 ||
2533 (r = sshbuf_put_u64(m, state->p_send.bytes)) != 0 ||
2534 (r = sshbuf_put_u32(m, state->p_read.seqnr)) != 0 ||
2535 (r = sshbuf_put_u64(m, state->p_read.blocks)) != 0 ||
2536 (r = sshbuf_put_u32(m, state->p_read.packets)) != 0 ||
2537 (r = sshbuf_put_u64(m, state->p_read.bytes)) != 0)
2541 slen = cipher_get_keycontext(&state->send_context, NULL);
2542 rlen = cipher_get_keycontext(&state->receive_context, NULL);
2543 if ((r = sshbuf_put_u32(m, slen)) != 0 ||
2544 (r = sshbuf_reserve(m, slen, &p)) != 0)
2546 if (cipher_get_keycontext(&state->send_context, p) != (int)slen)
2547 return SSH_ERR_INTERNAL_ERROR;
2548 if ((r = sshbuf_put_u32(m, rlen)) != 0 ||
2549 (r = sshbuf_reserve(m, rlen, &p)) != 0)
2551 if (cipher_get_keycontext(&state->receive_context, p) != (int)rlen)
2552 return SSH_ERR_INTERNAL_ERROR;
2554 if ((r = ssh_packet_get_compress_state(m, ssh)) != 0 ||
2555 (r = sshbuf_put_stringb(m, state->input)) != 0 ||
2556 (r = sshbuf_put_stringb(m, state->output)) != 0)
2562 /* restore key exchange results from blob for packet state de-serialization */
2564 newkeys_from_blob(struct sshbuf *m, struct ssh *ssh, int mode)
2566 struct sshbuf *b = NULL;
2567 struct sshcomp *comp;
2570 struct newkeys *newkey = NULL;
2571 size_t keylen, ivlen, maclen;
2574 if ((newkey = calloc(1, sizeof(*newkey))) == NULL) {
2575 r = SSH_ERR_ALLOC_FAIL;
2578 if ((r = sshbuf_froms(m, &b)) != 0)
2581 sshbuf_dump(b, stderr);
2585 comp = &newkey->comp;
2587 if ((r = sshbuf_get_cstring(b, &enc->name, NULL)) != 0 ||
2588 (r = sshbuf_get(b, &enc->cipher, sizeof(enc->cipher))) != 0 ||
2589 (r = sshbuf_get_u32(b, (u_int *)&enc->enabled)) != 0 ||
2590 (r = sshbuf_get_u32(b, &enc->block_size)) != 0 ||
2591 (r = sshbuf_get_string(b, &enc->key, &keylen)) != 0 ||
2592 (r = sshbuf_get_string(b, &enc->iv, &ivlen)) != 0)
2594 if (cipher_authlen(enc->cipher) == 0) {
2595 if ((r = sshbuf_get_cstring(b, &mac->name, NULL)) != 0)
2597 if ((r = mac_setup(mac, mac->name)) != 0)
2599 if ((r = sshbuf_get_u32(b, (u_int *)&mac->enabled)) != 0 ||
2600 (r = sshbuf_get_string(b, &mac->key, &maclen)) != 0)
2602 if (maclen > mac->key_len) {
2603 r = SSH_ERR_INVALID_FORMAT;
2606 mac->key_len = maclen;
2608 if ((r = sshbuf_get_u32(b, &comp->type)) != 0 ||
2609 (r = sshbuf_get_u32(b, (u_int *)&comp->enabled)) != 0 ||
2610 (r = sshbuf_get_cstring(b, &comp->name, NULL)) != 0)
2612 if (enc->name == NULL ||
2613 cipher_by_name(enc->name) != enc->cipher) {
2614 r = SSH_ERR_INVALID_FORMAT;
2617 if (sshbuf_len(b) != 0) {
2618 r = SSH_ERR_INVALID_FORMAT;
2621 enc->key_len = keylen;
2622 enc->iv_len = ivlen;
2623 ssh->kex->newkeys[mode] = newkey;
2632 /* restore kex from blob for packet state de-serialization */
2634 kex_from_blob(struct sshbuf *m, struct kex **kexp)
2639 if ((kex = calloc(1, sizeof(struct kex))) == NULL ||
2640 (kex->my = sshbuf_new()) == NULL ||
2641 (kex->peer = sshbuf_new()) == NULL) {
2642 r = SSH_ERR_ALLOC_FAIL;
2645 if ((r = sshbuf_get_string(m, &kex->session_id, &kex->session_id_len)) != 0 ||
2646 (r = sshbuf_get_u32(m, &kex->we_need)) != 0 ||
2647 (r = sshbuf_get_u32(m, (u_int *)&kex->hostkey_type)) != 0 ||
2648 (r = sshbuf_get_u32(m, &kex->kex_type)) != 0 ||
2649 (r = sshbuf_get_stringb(m, kex->my)) != 0 ||
2650 (r = sshbuf_get_stringb(m, kex->peer)) != 0 ||
2651 (r = sshbuf_get_u32(m, &kex->flags)) != 0 ||
2652 (r = sshbuf_get_cstring(m, &kex->client_version_string, NULL)) != 0 ||
2653 (r = sshbuf_get_cstring(m, &kex->server_version_string, NULL)) != 0)
2659 if (r != 0 || kexp == NULL) {
2661 sshbuf_free(kex->my);
2662 sshbuf_free(kex->peer);
2674 * Restore packet state from content of blob 'm' (de-serialization).
2675 * Note that 'm' will be partially consumed on parsing or any other errors.
2678 ssh_packet_set_state(struct ssh *ssh, struct sshbuf *m)
2680 struct session_state *state = ssh->state;
2681 const u_char *ssh1key, *ivin, *ivout, *keyin, *keyout, *input, *output;
2682 size_t ssh1keylen, rlen, slen, ilen, olen;
2684 u_int ssh1cipher = 0;
2687 if ((r = sshbuf_get_u32(m, &state->remote_protocol_flags)) != 0 ||
2688 (r = sshbuf_get_u32(m, &ssh1cipher)) != 0 ||
2689 (r = sshbuf_get_string_direct(m, &ssh1key, &ssh1keylen)) != 0 ||
2690 (r = sshbuf_get_string_direct(m, &ivout, &slen)) != 0 ||
2691 (r = sshbuf_get_string_direct(m, &ivin, &rlen)) != 0)
2693 if (ssh1cipher > INT_MAX)
2694 return SSH_ERR_KEY_UNKNOWN_CIPHER;
2695 ssh_packet_set_encryption_key(ssh, ssh1key, ssh1keylen,
2697 if (cipher_get_keyiv_len(&state->send_context) != (int)slen ||
2698 cipher_get_keyiv_len(&state->receive_context) != (int)rlen)
2699 return SSH_ERR_INVALID_FORMAT;
2700 if ((r = cipher_set_keyiv(&state->send_context, ivout)) != 0 ||
2701 (r = cipher_set_keyiv(&state->receive_context, ivin)) != 0)
2704 if ((r = kex_from_blob(m, &ssh->kex)) != 0 ||
2705 (r = newkeys_from_blob(m, ssh, MODE_OUT)) != 0 ||
2706 (r = newkeys_from_blob(m, ssh, MODE_IN)) != 0 ||
2707 (r = sshbuf_get_u64(m, &state->rekey_limit)) != 0 ||
2708 (r = sshbuf_get_u32(m, &state->rekey_interval)) != 0 ||
2709 (r = sshbuf_get_u32(m, &state->p_send.seqnr)) != 0 ||
2710 (r = sshbuf_get_u64(m, &state->p_send.blocks)) != 0 ||
2711 (r = sshbuf_get_u32(m, &state->p_send.packets)) != 0 ||
2712 (r = sshbuf_get_u64(m, &state->p_send.bytes)) != 0 ||
2713 (r = sshbuf_get_u32(m, &state->p_read.seqnr)) != 0 ||
2714 (r = sshbuf_get_u64(m, &state->p_read.blocks)) != 0 ||
2715 (r = sshbuf_get_u32(m, &state->p_read.packets)) != 0 ||
2716 (r = sshbuf_get_u64(m, &state->p_read.bytes)) != 0)
2719 * We set the time here so that in post-auth privsep slave we
2720 * count from the completion of the authentication.
2722 state->rekey_time = monotime();
2723 /* XXX ssh_set_newkeys overrides p_read.packets? XXX */
2724 if ((r = ssh_set_newkeys(ssh, MODE_IN)) != 0 ||
2725 (r = ssh_set_newkeys(ssh, MODE_OUT)) != 0)
2728 if ((r = sshbuf_get_string_direct(m, &keyout, &slen)) != 0 ||
2729 (r = sshbuf_get_string_direct(m, &keyin, &rlen)) != 0)
2731 if (cipher_get_keycontext(&state->send_context, NULL) != (int)slen ||
2732 cipher_get_keycontext(&state->receive_context, NULL) != (int)rlen)
2733 return SSH_ERR_INVALID_FORMAT;
2734 cipher_set_keycontext(&state->send_context, keyout);
2735 cipher_set_keycontext(&state->receive_context, keyin);
2737 if ((r = ssh_packet_set_compress_state(ssh, m)) != 0 ||
2738 (r = ssh_packet_set_postauth(ssh)) != 0)
2741 sshbuf_reset(state->input);
2742 sshbuf_reset(state->output);
2743 if ((r = sshbuf_get_string_direct(m, &input, &ilen)) != 0 ||
2744 (r = sshbuf_get_string_direct(m, &output, &olen)) != 0 ||
2745 (r = sshbuf_put(state->input, input, ilen)) != 0 ||
2746 (r = sshbuf_put(state->output, output, olen)) != 0)
2750 return SSH_ERR_INVALID_FORMAT;
2751 debug3("%s: done", __func__);
2757 /* put data to the outgoing packet */
2760 sshpkt_put(struct ssh *ssh, const void *v, size_t len)
2762 return sshbuf_put(ssh->state->outgoing_packet, v, len);
2766 sshpkt_putb(struct ssh *ssh, const struct sshbuf *b)
2768 return sshbuf_putb(ssh->state->outgoing_packet, b);
2772 sshpkt_put_u8(struct ssh *ssh, u_char val)
2774 return sshbuf_put_u8(ssh->state->outgoing_packet, val);
2778 sshpkt_put_u32(struct ssh *ssh, u_int32_t val)
2780 return sshbuf_put_u32(ssh->state->outgoing_packet, val);
2784 sshpkt_put_u64(struct ssh *ssh, u_int64_t val)
2786 return sshbuf_put_u64(ssh->state->outgoing_packet, val);
2790 sshpkt_put_string(struct ssh *ssh, const void *v, size_t len)
2792 return sshbuf_put_string(ssh->state->outgoing_packet, v, len);
2796 sshpkt_put_cstring(struct ssh *ssh, const void *v)
2798 return sshbuf_put_cstring(ssh->state->outgoing_packet, v);
2802 sshpkt_put_stringb(struct ssh *ssh, const struct sshbuf *v)
2804 return sshbuf_put_stringb(ssh->state->outgoing_packet, v);
2808 #ifdef OPENSSL_HAS_ECC
2810 sshpkt_put_ec(struct ssh *ssh, const EC_POINT *v, const EC_GROUP *g)
2812 return sshbuf_put_ec(ssh->state->outgoing_packet, v, g);
2814 #endif /* OPENSSL_HAS_ECC */
2818 sshpkt_put_bignum1(struct ssh *ssh, const BIGNUM *v)
2820 return sshbuf_put_bignum1(ssh->state->outgoing_packet, v);
2822 #endif /* WITH_SSH1 */
2825 sshpkt_put_bignum2(struct ssh *ssh, const BIGNUM *v)
2827 return sshbuf_put_bignum2(ssh->state->outgoing_packet, v);
2829 #endif /* WITH_OPENSSL */
2831 /* fetch data from the incoming packet */
2834 sshpkt_get(struct ssh *ssh, void *valp, size_t len)
2836 return sshbuf_get(ssh->state->incoming_packet, valp, len);
2840 sshpkt_get_u8(struct ssh *ssh, u_char *valp)
2842 return sshbuf_get_u8(ssh->state->incoming_packet, valp);
2846 sshpkt_get_u32(struct ssh *ssh, u_int32_t *valp)
2848 return sshbuf_get_u32(ssh->state->incoming_packet, valp);
2852 sshpkt_get_u64(struct ssh *ssh, u_int64_t *valp)
2854 return sshbuf_get_u64(ssh->state->incoming_packet, valp);
2858 sshpkt_get_string(struct ssh *ssh, u_char **valp, size_t *lenp)
2860 return sshbuf_get_string(ssh->state->incoming_packet, valp, lenp);
2864 sshpkt_get_string_direct(struct ssh *ssh, const u_char **valp, size_t *lenp)
2866 return sshbuf_get_string_direct(ssh->state->incoming_packet, valp, lenp);
2870 sshpkt_get_cstring(struct ssh *ssh, char **valp, size_t *lenp)
2872 return sshbuf_get_cstring(ssh->state->incoming_packet, valp, lenp);
2876 #ifdef OPENSSL_HAS_ECC
2878 sshpkt_get_ec(struct ssh *ssh, EC_POINT *v, const EC_GROUP *g)
2880 return sshbuf_get_ec(ssh->state->incoming_packet, v, g);
2882 #endif /* OPENSSL_HAS_ECC */
2886 sshpkt_get_bignum1(struct ssh *ssh, BIGNUM *v)
2888 return sshbuf_get_bignum1(ssh->state->incoming_packet, v);
2890 #endif /* WITH_SSH1 */
2893 sshpkt_get_bignum2(struct ssh *ssh, BIGNUM *v)
2895 return sshbuf_get_bignum2(ssh->state->incoming_packet, v);
2897 #endif /* WITH_OPENSSL */
2900 sshpkt_get_end(struct ssh *ssh)
2902 if (sshbuf_len(ssh->state->incoming_packet) > 0)
2903 return SSH_ERR_UNEXPECTED_TRAILING_DATA;
2908 sshpkt_ptr(struct ssh *ssh, size_t *lenp)
2911 *lenp = sshbuf_len(ssh->state->incoming_packet);
2912 return sshbuf_ptr(ssh->state->incoming_packet);
2915 /* start a new packet */
2918 sshpkt_start(struct ssh *ssh, u_char type)
2923 DBG(debug("packet_start[%d]", type));
2924 len = compat20 ? 6 : 9;
2925 memset(buf, 0, len - 1);
2926 buf[len - 1] = type;
2927 sshbuf_reset(ssh->state->outgoing_packet);
2928 return sshbuf_put(ssh->state->outgoing_packet, buf, len);
2934 sshpkt_send(struct ssh *ssh)
2937 return ssh_packet_send2(ssh);
2939 return ssh_packet_send1(ssh);
2943 sshpkt_disconnect(struct ssh *ssh, const char *fmt,...)
2949 va_start(args, fmt);
2950 vsnprintf(buf, sizeof(buf), fmt, args);
2954 if ((r = sshpkt_start(ssh, SSH2_MSG_DISCONNECT)) != 0 ||
2955 (r = sshpkt_put_u32(ssh, SSH2_DISCONNECT_PROTOCOL_ERROR)) != 0 ||
2956 (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
2957 (r = sshpkt_put_cstring(ssh, "")) != 0 ||
2958 (r = sshpkt_send(ssh)) != 0)
2961 if ((r = sshpkt_start(ssh, SSH_MSG_DISCONNECT)) != 0 ||
2962 (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
2963 (r = sshpkt_send(ssh)) != 0)
2969 /* roundup current message to pad bytes */
2971 sshpkt_add_padding(struct ssh *ssh, u_char pad)
2973 ssh->state->extra_pad = pad;