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.
42 #include <sys/param.h> /* MIN roundup */
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>
66 #include "buffer.h" /* typedefs XXX */
67 #include "key.h" /* typedefs XXX */
95 #define PACKET_MAX_SIZE (256 * 1024)
105 TAILQ_ENTRY(packet) next;
107 struct sshbuf *payload;
110 struct session_state {
112 * This variable contains the file descriptors used for
113 * communicating with the other side. connection_in is used for
114 * reading; connection_out for writing. These can be the same
115 * descriptor, in which case it is assumed to be a socket.
120 /* Protocol flags for the remote side. */
121 u_int remote_protocol_flags;
123 /* Encryption context for receiving data. Only used for decryption. */
124 struct sshcipher_ctx receive_context;
126 /* Encryption context for sending data. Only used for encryption. */
127 struct sshcipher_ctx send_context;
129 /* Buffer for raw input data from the socket. */
130 struct sshbuf *input;
132 /* Buffer for raw output data going to the socket. */
133 struct sshbuf *output;
135 /* Buffer for the partial outgoing packet being constructed. */
136 struct sshbuf *outgoing_packet;
138 /* Buffer for the incoming packet currently being processed. */
139 struct sshbuf *incoming_packet;
141 /* Scratch buffer for packet compression/decompression. */
142 struct sshbuf *compression_buffer;
144 /* Incoming/outgoing compression dictionaries */
145 z_stream compression_in_stream;
146 z_stream compression_out_stream;
147 int compression_in_started;
148 int compression_out_started;
149 int compression_in_failures;
150 int compression_out_failures;
153 * Flag indicating whether packet compression/decompression is
156 int packet_compression;
158 /* default maximum packet size */
159 u_int max_packet_size;
161 /* Flag indicating whether this module has been initialized. */
164 /* Set to true if the connection is interactive. */
165 int interactive_mode;
167 /* Set to true if we are the server side. */
170 /* Set to true if we are authenticated. */
171 int after_authentication;
173 int keep_alive_timeouts;
175 /* The maximum time that we will wait to send or receive a packet */
176 int packet_timeout_ms;
178 /* Session key information for Encryption and MAC */
179 struct newkeys *newkeys[MODE_MAX];
180 struct packet_state p_read, p_send;
182 /* Volume-based rekeying */
183 u_int64_t max_blocks_in, max_blocks_out, rekey_limit;
185 /* Time-based rekeying */
186 u_int32_t rekey_interval; /* how often in seconds */
187 time_t rekey_time; /* time of last rekeying */
189 /* Session key for protocol v1 */
190 u_char ssh1_key[SSH_SESSION_KEY_LENGTH];
193 /* roundup current message to extra_pad bytes */
196 /* XXX discard incoming data after MAC error */
197 u_int packet_discard;
198 struct sshmac *packet_discard_mac;
200 /* Used in packet_read_poll2() */
203 /* Used in packet_send2 */
206 /* Used in packet_set_interactive */
207 int set_interactive_called;
209 /* Used in packet_set_maxsize */
210 int set_maxsize_called;
212 /* One-off warning about weak ciphers */
213 int cipher_warning_done;
215 /* SSH1 CRC compensation attack detector */
216 struct deattack_ctx deattack;
218 TAILQ_HEAD(, packet) outgoing;
222 ssh_alloc_session_state(void)
224 struct ssh *ssh = NULL;
225 struct session_state *state = NULL;
227 if ((ssh = calloc(1, sizeof(*ssh))) == NULL ||
228 (state = calloc(1, sizeof(*state))) == NULL ||
229 (state->input = sshbuf_new()) == NULL ||
230 (state->output = sshbuf_new()) == NULL ||
231 (state->outgoing_packet = sshbuf_new()) == NULL ||
232 (state->incoming_packet = sshbuf_new()) == NULL)
234 TAILQ_INIT(&state->outgoing);
235 TAILQ_INIT(&ssh->private_keys);
236 TAILQ_INIT(&ssh->public_keys);
237 state->connection_in = -1;
238 state->connection_out = -1;
239 state->max_packet_size = 32768;
240 state->packet_timeout_ms = -1;
241 state->p_send.packets = state->p_read.packets = 0;
242 state->initialized = 1;
244 * ssh_packet_send2() needs to queue packets until
245 * we've done the initial key exchange.
252 sshbuf_free(state->input);
253 sshbuf_free(state->output);
254 sshbuf_free(state->incoming_packet);
255 sshbuf_free(state->outgoing_packet);
262 /* Returns nonzero if rekeying is in progress */
264 ssh_packet_is_rekeying(struct ssh *ssh)
267 (ssh->state->rekeying || (ssh->kex != NULL && ssh->kex->done == 0));
271 * Sets the descriptors used for communication. Disables encryption until
272 * packet_set_encryption_key is called.
275 ssh_packet_set_connection(struct ssh *ssh, int fd_in, int fd_out)
277 struct session_state *state;
278 const struct sshcipher *none = cipher_by_name("none");
282 error("%s: cannot load cipher 'none'", __func__);
286 ssh = ssh_alloc_session_state();
288 error("%s: cound not allocate state", __func__);
292 state->connection_in = fd_in;
293 state->connection_out = fd_out;
294 if ((r = cipher_init(&state->send_context, none,
295 (const u_char *)"", 0, NULL, 0, CIPHER_ENCRYPT)) != 0 ||
296 (r = cipher_init(&state->receive_context, none,
297 (const u_char *)"", 0, NULL, 0, CIPHER_DECRYPT)) != 0) {
298 error("%s: cipher_init failed: %s", __func__, ssh_err(r));
302 state->newkeys[MODE_IN] = state->newkeys[MODE_OUT] = NULL;
303 deattack_init(&state->deattack);
305 * Cache the IP address of the remote connection for use in error
306 * messages that might be generated after the connection has closed.
308 (void)ssh_remote_ipaddr(ssh);
313 ssh_packet_set_timeout(struct ssh *ssh, int timeout, int count)
315 struct session_state *state = ssh->state;
317 if (timeout <= 0 || count <= 0) {
318 state->packet_timeout_ms = -1;
321 if ((INT_MAX / 1000) / count < timeout)
322 state->packet_timeout_ms = INT_MAX;
324 state->packet_timeout_ms = timeout * count * 1000;
328 ssh_packet_stop_discard(struct ssh *ssh)
330 struct session_state *state = ssh->state;
333 if (state->packet_discard_mac) {
336 memset(buf, 'a', sizeof(buf));
337 while (sshbuf_len(state->incoming_packet) <
339 if ((r = sshbuf_put(state->incoming_packet, buf,
342 (void) mac_compute(state->packet_discard_mac,
344 sshbuf_ptr(state->incoming_packet), PACKET_MAX_SIZE,
347 logit("Finished discarding for %.200s port %d",
348 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
349 return SSH_ERR_MAC_INVALID;
353 ssh_packet_start_discard(struct ssh *ssh, struct sshenc *enc,
354 struct sshmac *mac, u_int packet_length, u_int discard)
356 struct session_state *state = ssh->state;
359 if (enc == NULL || !cipher_is_cbc(enc->cipher) || (mac && mac->etm)) {
360 if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0)
362 return SSH_ERR_MAC_INVALID;
364 if (packet_length != PACKET_MAX_SIZE && mac && mac->enabled)
365 state->packet_discard_mac = mac;
366 if (sshbuf_len(state->input) >= discard &&
367 (r = ssh_packet_stop_discard(ssh)) != 0)
369 state->packet_discard = discard - sshbuf_len(state->input);
373 /* Returns 1 if remote host is connected via socket, 0 if not. */
376 ssh_packet_connection_is_on_socket(struct ssh *ssh)
378 struct session_state *state = ssh->state;
379 struct sockaddr_storage from, to;
380 socklen_t fromlen, tolen;
382 /* filedescriptors in and out are the same, so it's a socket */
383 if (state->connection_in == state->connection_out)
385 fromlen = sizeof(from);
386 memset(&from, 0, sizeof(from));
387 if (getpeername(state->connection_in, (struct sockaddr *)&from,
391 memset(&to, 0, sizeof(to));
392 if (getpeername(state->connection_out, (struct sockaddr *)&to,
395 if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
397 if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
403 ssh_packet_get_bytes(struct ssh *ssh, u_int64_t *ibytes, u_int64_t *obytes)
406 *ibytes = ssh->state->p_read.bytes;
408 *obytes = ssh->state->p_send.bytes;
412 ssh_packet_connection_af(struct ssh *ssh)
414 struct sockaddr_storage to;
415 socklen_t tolen = sizeof(to);
417 memset(&to, 0, sizeof(to));
418 if (getsockname(ssh->state->connection_out, (struct sockaddr *)&to,
422 if (to.ss_family == AF_INET6 &&
423 IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&to)->sin6_addr))
429 /* Sets the connection into non-blocking mode. */
432 ssh_packet_set_nonblocking(struct ssh *ssh)
434 /* Set the socket into non-blocking mode. */
435 set_nonblock(ssh->state->connection_in);
437 if (ssh->state->connection_out != ssh->state->connection_in)
438 set_nonblock(ssh->state->connection_out);
441 /* Returns the socket used for reading. */
444 ssh_packet_get_connection_in(struct ssh *ssh)
446 return ssh->state->connection_in;
449 /* Returns the descriptor used for writing. */
452 ssh_packet_get_connection_out(struct ssh *ssh)
454 return ssh->state->connection_out;
458 * Returns the IP-address of the remote host as a string. The returned
459 * string must not be freed.
463 ssh_remote_ipaddr(struct ssh *ssh)
465 const int sock = ssh->state->connection_in;
467 /* Check whether we have cached the ipaddr. */
468 if (ssh->remote_ipaddr == NULL) {
469 if (ssh_packet_connection_is_on_socket(ssh)) {
470 ssh->remote_ipaddr = get_peer_ipaddr(sock);
471 ssh->remote_port = get_sock_port(sock, 0);
473 ssh->remote_ipaddr = strdup("UNKNOWN");
474 ssh->remote_port = 0;
477 return ssh->remote_ipaddr;
480 /* Returns the port number of the remote host. */
483 ssh_remote_port(struct ssh *ssh)
485 (void)ssh_remote_ipaddr(ssh); /* Will lookup and cache. */
486 return ssh->remote_port;
489 /* Closes the connection and clears and frees internal data structures. */
492 ssh_packet_close(struct ssh *ssh)
494 struct session_state *state = ssh->state;
498 if (!state->initialized)
500 state->initialized = 0;
501 if (state->connection_in == state->connection_out) {
502 shutdown(state->connection_out, SHUT_RDWR);
503 close(state->connection_out);
505 close(state->connection_in);
506 close(state->connection_out);
508 sshbuf_free(state->input);
509 sshbuf_free(state->output);
510 sshbuf_free(state->outgoing_packet);
511 sshbuf_free(state->incoming_packet);
512 for (mode = 0; mode < MODE_MAX; mode++)
513 kex_free_newkeys(state->newkeys[mode]);
514 if (state->compression_buffer) {
515 sshbuf_free(state->compression_buffer);
516 if (state->compression_out_started) {
517 z_streamp stream = &state->compression_out_stream;
518 debug("compress outgoing: "
519 "raw data %llu, compressed %llu, factor %.2f",
520 (unsigned long long)stream->total_in,
521 (unsigned long long)stream->total_out,
522 stream->total_in == 0 ? 0.0 :
523 (double) stream->total_out / stream->total_in);
524 if (state->compression_out_failures == 0)
527 if (state->compression_in_started) {
528 z_streamp stream = &state->compression_out_stream;
529 debug("compress incoming: "
530 "raw data %llu, compressed %llu, factor %.2f",
531 (unsigned long long)stream->total_out,
532 (unsigned long long)stream->total_in,
533 stream->total_out == 0 ? 0.0 :
534 (double) stream->total_in / stream->total_out);
535 if (state->compression_in_failures == 0)
539 if ((r = cipher_cleanup(&state->send_context)) != 0)
540 error("%s: cipher_cleanup failed: %s", __func__, ssh_err(r));
541 if ((r = cipher_cleanup(&state->receive_context)) != 0)
542 error("%s: cipher_cleanup failed: %s", __func__, ssh_err(r));
543 free(ssh->remote_ipaddr);
544 ssh->remote_ipaddr = NULL;
549 /* Sets remote side protocol flags. */
552 ssh_packet_set_protocol_flags(struct ssh *ssh, u_int protocol_flags)
554 ssh->state->remote_protocol_flags = protocol_flags;
557 /* Returns the remote protocol flags set earlier by the above function. */
560 ssh_packet_get_protocol_flags(struct ssh *ssh)
562 return ssh->state->remote_protocol_flags;
566 * Starts packet compression from the next packet on in both directions.
567 * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
571 ssh_packet_init_compression(struct ssh *ssh)
573 if (!ssh->state->compression_buffer &&
574 ((ssh->state->compression_buffer = sshbuf_new()) == NULL))
575 return SSH_ERR_ALLOC_FAIL;
580 start_compression_out(struct ssh *ssh, int level)
582 if (level < 1 || level > 9)
583 return SSH_ERR_INVALID_ARGUMENT;
584 debug("Enabling compression at level %d.", level);
585 if (ssh->state->compression_out_started == 1)
586 deflateEnd(&ssh->state->compression_out_stream);
587 switch (deflateInit(&ssh->state->compression_out_stream, level)) {
589 ssh->state->compression_out_started = 1;
592 return SSH_ERR_ALLOC_FAIL;
594 return SSH_ERR_INTERNAL_ERROR;
600 start_compression_in(struct ssh *ssh)
602 if (ssh->state->compression_in_started == 1)
603 inflateEnd(&ssh->state->compression_in_stream);
604 switch (inflateInit(&ssh->state->compression_in_stream)) {
606 ssh->state->compression_in_started = 1;
609 return SSH_ERR_ALLOC_FAIL;
611 return SSH_ERR_INTERNAL_ERROR;
617 ssh_packet_start_compression(struct ssh *ssh, int level)
621 if (ssh->state->packet_compression && !compat20)
622 return SSH_ERR_INTERNAL_ERROR;
623 ssh->state->packet_compression = 1;
624 if ((r = ssh_packet_init_compression(ssh)) != 0 ||
625 (r = start_compression_in(ssh)) != 0 ||
626 (r = start_compression_out(ssh, level)) != 0)
631 /* XXX remove need for separate compression buffer */
633 compress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
638 if (ssh->state->compression_out_started != 1)
639 return SSH_ERR_INTERNAL_ERROR;
641 /* This case is not handled below. */
642 if (sshbuf_len(in) == 0)
645 /* Input is the contents of the input buffer. */
646 if ((ssh->state->compression_out_stream.next_in =
647 sshbuf_mutable_ptr(in)) == NULL)
648 return SSH_ERR_INTERNAL_ERROR;
649 ssh->state->compression_out_stream.avail_in = sshbuf_len(in);
651 /* Loop compressing until deflate() returns with avail_out != 0. */
653 /* Set up fixed-size output buffer. */
654 ssh->state->compression_out_stream.next_out = buf;
655 ssh->state->compression_out_stream.avail_out = sizeof(buf);
657 /* Compress as much data into the buffer as possible. */
658 status = deflate(&ssh->state->compression_out_stream,
662 return SSH_ERR_ALLOC_FAIL;
664 /* Append compressed data to output_buffer. */
665 if ((r = sshbuf_put(out, buf, sizeof(buf) -
666 ssh->state->compression_out_stream.avail_out)) != 0)
671 ssh->state->compression_out_failures++;
672 return SSH_ERR_INVALID_FORMAT;
674 } while (ssh->state->compression_out_stream.avail_out == 0);
679 uncompress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
684 if (ssh->state->compression_in_started != 1)
685 return SSH_ERR_INTERNAL_ERROR;
687 if ((ssh->state->compression_in_stream.next_in =
688 sshbuf_mutable_ptr(in)) == NULL)
689 return SSH_ERR_INTERNAL_ERROR;
690 ssh->state->compression_in_stream.avail_in = sshbuf_len(in);
693 /* Set up fixed-size output buffer. */
694 ssh->state->compression_in_stream.next_out = buf;
695 ssh->state->compression_in_stream.avail_out = sizeof(buf);
697 status = inflate(&ssh->state->compression_in_stream,
701 if ((r = sshbuf_put(out, buf, sizeof(buf) -
702 ssh->state->compression_in_stream.avail_out)) != 0)
707 * Comments in zlib.h say that we should keep calling
708 * inflate() until we get an error. This appears to
709 * be the error that we get.
713 return SSH_ERR_INVALID_FORMAT;
715 return SSH_ERR_ALLOC_FAIL;
718 ssh->state->compression_in_failures++;
719 return SSH_ERR_INTERNAL_ERROR;
725 /* Serialise compression state into a blob for privsep */
727 ssh_packet_get_compress_state(struct sshbuf *m, struct ssh *ssh)
729 struct session_state *state = ssh->state;
733 if ((b = sshbuf_new()) == NULL)
734 return SSH_ERR_ALLOC_FAIL;
735 if (state->compression_in_started) {
736 if ((r = sshbuf_put_string(b, &state->compression_in_stream,
737 sizeof(state->compression_in_stream))) != 0)
739 } else if ((r = sshbuf_put_string(b, NULL, 0)) != 0)
741 if (state->compression_out_started) {
742 if ((r = sshbuf_put_string(b, &state->compression_out_stream,
743 sizeof(state->compression_out_stream))) != 0)
745 } else if ((r = sshbuf_put_string(b, NULL, 0)) != 0)
747 r = sshbuf_put_stringb(m, b);
753 /* Deserialise compression state from a blob for privsep */
755 ssh_packet_set_compress_state(struct ssh *ssh, struct sshbuf *m)
757 struct session_state *state = ssh->state;
758 struct sshbuf *b = NULL;
760 const u_char *inblob, *outblob;
763 if ((r = sshbuf_froms(m, &b)) != 0)
765 if ((r = sshbuf_get_string_direct(b, &inblob, &inl)) != 0 ||
766 (r = sshbuf_get_string_direct(b, &outblob, &outl)) != 0)
769 state->compression_in_started = 0;
770 else if (inl != sizeof(state->compression_in_stream)) {
771 r = SSH_ERR_INTERNAL_ERROR;
774 state->compression_in_started = 1;
775 memcpy(&state->compression_in_stream, inblob, inl);
778 state->compression_out_started = 0;
779 else if (outl != sizeof(state->compression_out_stream)) {
780 r = SSH_ERR_INTERNAL_ERROR;
783 state->compression_out_started = 1;
784 memcpy(&state->compression_out_stream, outblob, outl);
793 ssh_packet_set_compress_hooks(struct ssh *ssh, void *ctx,
794 void *(*allocfunc)(void *, u_int, u_int),
795 void (*freefunc)(void *, void *))
797 ssh->state->compression_out_stream.zalloc = (alloc_func)allocfunc;
798 ssh->state->compression_out_stream.zfree = (free_func)freefunc;
799 ssh->state->compression_out_stream.opaque = ctx;
800 ssh->state->compression_in_stream.zalloc = (alloc_func)allocfunc;
801 ssh->state->compression_in_stream.zfree = (free_func)freefunc;
802 ssh->state->compression_in_stream.opaque = ctx;
806 * Causes any further packets to be encrypted using the given key. The same
807 * key is used for both sending and reception. However, both directions are
808 * encrypted independently of each other.
812 ssh_packet_set_encryption_key(struct ssh *ssh, const u_char *key, u_int keylen, int number)
815 fatal("no SSH protocol 1 support");
816 #else /* WITH_SSH1 */
817 struct session_state *state = ssh->state;
818 const struct sshcipher *cipher = cipher_by_number(number);
823 fatal("%s: unknown cipher number %d", __func__, number);
825 fatal("%s: keylen too small: %d", __func__, keylen);
826 if (keylen > SSH_SESSION_KEY_LENGTH)
827 fatal("%s: keylen too big: %d", __func__, keylen);
828 memcpy(state->ssh1_key, key, keylen);
829 state->ssh1_keylen = keylen;
830 if ((r = cipher_init(&state->send_context, cipher, key, keylen,
831 NULL, 0, CIPHER_ENCRYPT)) != 0 ||
832 (r = cipher_init(&state->receive_context, cipher, key, keylen,
833 NULL, 0, CIPHER_DECRYPT) != 0))
834 fatal("%s: cipher_init failed: %s", __func__, ssh_err(r));
835 if (!state->cipher_warning_done &&
836 ((wmsg = cipher_warning_message(&state->send_context)) != NULL ||
837 (wmsg = cipher_warning_message(&state->send_context)) != NULL)) {
838 error("Warning: %s", wmsg);
839 state->cipher_warning_done = 1;
841 #endif /* WITH_SSH1 */
845 * Finalizes and sends the packet. If the encryption key has been set,
846 * encrypts the packet before sending.
850 ssh_packet_send1(struct ssh *ssh)
852 struct session_state *state = ssh->state;
858 * If using packet compression, compress the payload of the outgoing
861 if (state->packet_compression) {
862 sshbuf_reset(state->compression_buffer);
864 if ((r = sshbuf_consume(state->outgoing_packet, 8)) != 0)
867 if ((r = sshbuf_put(state->compression_buffer,
868 "\0\0\0\0\0\0\0\0", 8)) != 0)
870 if ((r = compress_buffer(ssh, state->outgoing_packet,
871 state->compression_buffer)) != 0)
873 sshbuf_reset(state->outgoing_packet);
874 if ((r = sshbuf_putb(state->outgoing_packet,
875 state->compression_buffer)) != 0)
878 /* Compute packet length without padding (add checksum, remove padding). */
879 len = sshbuf_len(state->outgoing_packet) + 4 - 8;
881 /* Insert padding. Initialized to zero in packet_start1() */
882 padding = 8 - len % 8;
883 if (!state->send_context.plaintext) {
884 cp = sshbuf_mutable_ptr(state->outgoing_packet);
886 r = SSH_ERR_INTERNAL_ERROR;
889 arc4random_buf(cp + 8 - padding, padding);
891 if ((r = sshbuf_consume(state->outgoing_packet, 8 - padding)) != 0)
894 /* Add check bytes. */
895 checksum = ssh_crc32(sshbuf_ptr(state->outgoing_packet),
896 sshbuf_len(state->outgoing_packet));
897 POKE_U32(buf, checksum);
898 if ((r = sshbuf_put(state->outgoing_packet, buf, 4)) != 0)
902 fprintf(stderr, "packet_send plain: ");
903 sshbuf_dump(state->outgoing_packet, stderr);
906 /* Append to output. */
908 if ((r = sshbuf_put(state->output, buf, 4)) != 0)
910 if ((r = sshbuf_reserve(state->output,
911 sshbuf_len(state->outgoing_packet), &cp)) != 0)
913 if ((r = cipher_crypt(&state->send_context, 0, cp,
914 sshbuf_ptr(state->outgoing_packet),
915 sshbuf_len(state->outgoing_packet), 0, 0)) != 0)
919 fprintf(stderr, "encrypted: ");
920 sshbuf_dump(state->output, stderr);
922 state->p_send.packets++;
923 state->p_send.bytes += len +
924 sshbuf_len(state->outgoing_packet);
925 sshbuf_reset(state->outgoing_packet);
928 * Note that the packet is now only buffered in output. It won't be
929 * actually sent until ssh_packet_write_wait or ssh_packet_write_poll
938 ssh_set_newkeys(struct ssh *ssh, int mode)
940 struct session_state *state = ssh->state;
943 struct sshcomp *comp;
944 struct sshcipher_ctx *cc;
945 u_int64_t *max_blocks;
949 debug2("set_newkeys: mode %d", mode);
951 if (mode == MODE_OUT) {
952 cc = &state->send_context;
953 crypt_type = CIPHER_ENCRYPT;
954 state->p_send.packets = state->p_send.blocks = 0;
955 max_blocks = &state->max_blocks_out;
957 cc = &state->receive_context;
958 crypt_type = CIPHER_DECRYPT;
959 state->p_read.packets = state->p_read.blocks = 0;
960 max_blocks = &state->max_blocks_in;
962 if (state->newkeys[mode] != NULL) {
963 debug("set_newkeys: rekeying, input %llu bytes %llu blocks, "
964 "output %llu bytes %llu blocks",
965 (unsigned long long)state->p_read.bytes,
966 (unsigned long long)state->p_read.blocks,
967 (unsigned long long)state->p_send.bytes,
968 (unsigned long long)state->p_send.blocks);
969 if ((r = cipher_cleanup(cc)) != 0)
971 enc = &state->newkeys[mode]->enc;
972 mac = &state->newkeys[mode]->mac;
973 comp = &state->newkeys[mode]->comp;
975 explicit_bzero(enc->iv, enc->iv_len);
976 explicit_bzero(enc->key, enc->key_len);
977 explicit_bzero(mac->key, mac->key_len);
984 free(state->newkeys[mode]);
986 /* move newkeys from kex to state */
987 if ((state->newkeys[mode] = ssh->kex->newkeys[mode]) == NULL)
988 return SSH_ERR_INTERNAL_ERROR;
989 ssh->kex->newkeys[mode] = NULL;
990 enc = &state->newkeys[mode]->enc;
991 mac = &state->newkeys[mode]->mac;
992 comp = &state->newkeys[mode]->comp;
993 if (cipher_authlen(enc->cipher) == 0) {
994 if ((r = mac_init(mac)) != 0)
998 DBG(debug("cipher_init_context: %d", mode));
999 if ((r = cipher_init(cc, enc->cipher, enc->key, enc->key_len,
1000 enc->iv, enc->iv_len, crypt_type)) != 0)
1002 if (!state->cipher_warning_done &&
1003 (wmsg = cipher_warning_message(cc)) != NULL) {
1004 error("Warning: %s", wmsg);
1005 state->cipher_warning_done = 1;
1007 /* Deleting the keys does not gain extra security */
1008 /* explicit_bzero(enc->iv, enc->block_size);
1009 explicit_bzero(enc->key, enc->key_len);
1010 explicit_bzero(mac->key, mac->key_len); */
1011 if ((comp->type == COMP_ZLIB ||
1012 (comp->type == COMP_DELAYED &&
1013 state->after_authentication)) && comp->enabled == 0) {
1014 if ((r = ssh_packet_init_compression(ssh)) < 0)
1016 if (mode == MODE_OUT) {
1017 if ((r = start_compression_out(ssh, 6)) != 0)
1020 if ((r = start_compression_in(ssh)) != 0)
1026 * The 2^(blocksize*2) limit is too expensive for 3DES,
1027 * blowfish, etc, so enforce a 1GB limit for small blocksizes.
1029 if (enc->block_size >= 16)
1030 *max_blocks = (u_int64_t)1 << (enc->block_size*2);
1032 *max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
1033 if (state->rekey_limit)
1034 *max_blocks = MIN(*max_blocks,
1035 state->rekey_limit / enc->block_size);
1036 debug("rekey after %llu blocks", (unsigned long long)*max_blocks);
1040 #define MAX_PACKETS (1U<<31)
1042 ssh_packet_need_rekeying(struct ssh *ssh, u_int outbound_packet_len)
1044 struct session_state *state = ssh->state;
1045 u_int32_t out_blocks;
1047 /* XXX client can't cope with rekeying pre-auth */
1048 if (!state->after_authentication)
1051 /* Haven't keyed yet or KEX in progress. */
1052 if (ssh->kex == NULL || ssh_packet_is_rekeying(ssh))
1055 /* Peer can't rekey */
1056 if (ssh->compat & SSH_BUG_NOREKEY)
1060 * Permit one packet in or out per rekey - this allows us to
1061 * make progress when rekey limits are very small.
1063 if (state->p_send.packets == 0 && state->p_read.packets == 0)
1066 /* Time-based rekeying */
1067 if (state->rekey_interval != 0 &&
1068 state->rekey_time + state->rekey_interval <= monotime())
1071 /* Always rekey when MAX_PACKETS sent in either direction */
1072 if (state->p_send.packets > MAX_PACKETS ||
1073 state->p_read.packets > MAX_PACKETS)
1076 /* Rekey after (cipher-specific) maxiumum blocks */
1077 out_blocks = roundup(outbound_packet_len,
1078 state->newkeys[MODE_OUT]->enc.block_size);
1079 return (state->max_blocks_out &&
1080 (state->p_send.blocks + out_blocks > state->max_blocks_out)) ||
1081 (state->max_blocks_in &&
1082 (state->p_read.blocks > state->max_blocks_in));
1086 * Delayed compression for SSH2 is enabled after authentication:
1087 * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
1088 * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
1091 ssh_packet_enable_delayed_compress(struct ssh *ssh)
1093 struct session_state *state = ssh->state;
1094 struct sshcomp *comp = NULL;
1098 * Remember that we are past the authentication step, so rekeying
1099 * with COMP_DELAYED will turn on compression immediately.
1101 state->after_authentication = 1;
1102 for (mode = 0; mode < MODE_MAX; mode++) {
1103 /* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
1104 if (state->newkeys[mode] == NULL)
1106 comp = &state->newkeys[mode]->comp;
1107 if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
1108 if ((r = ssh_packet_init_compression(ssh)) != 0)
1110 if (mode == MODE_OUT) {
1111 if ((r = start_compression_out(ssh, 6)) != 0)
1114 if ((r = start_compression_in(ssh)) != 0)
1123 /* Used to mute debug logging for noisy packet types */
1125 ssh_packet_log_type(u_char type)
1128 case SSH2_MSG_CHANNEL_DATA:
1129 case SSH2_MSG_CHANNEL_EXTENDED_DATA:
1130 case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
1138 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
1141 ssh_packet_send2_wrapped(struct ssh *ssh)
1143 struct session_state *state = ssh->state;
1144 u_char type, *cp, macbuf[SSH_DIGEST_MAX_LENGTH];
1145 u_char padlen, pad = 0;
1146 u_int authlen = 0, aadlen = 0;
1148 struct sshenc *enc = NULL;
1149 struct sshmac *mac = NULL;
1150 struct sshcomp *comp = NULL;
1153 if (state->newkeys[MODE_OUT] != NULL) {
1154 enc = &state->newkeys[MODE_OUT]->enc;
1155 mac = &state->newkeys[MODE_OUT]->mac;
1156 comp = &state->newkeys[MODE_OUT]->comp;
1157 /* disable mac for authenticated encryption */
1158 if ((authlen = cipher_authlen(enc->cipher)) != 0)
1161 block_size = enc ? enc->block_size : 8;
1162 aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
1164 type = (sshbuf_ptr(state->outgoing_packet))[5];
1165 if (ssh_packet_log_type(type))
1166 debug3("send packet: type %u", type);
1168 fprintf(stderr, "plain: ");
1169 sshbuf_dump(state->outgoing_packet, stderr);
1172 if (comp && comp->enabled) {
1173 len = sshbuf_len(state->outgoing_packet);
1174 /* skip header, compress only payload */
1175 if ((r = sshbuf_consume(state->outgoing_packet, 5)) != 0)
1177 sshbuf_reset(state->compression_buffer);
1178 if ((r = compress_buffer(ssh, state->outgoing_packet,
1179 state->compression_buffer)) != 0)
1181 sshbuf_reset(state->outgoing_packet);
1182 if ((r = sshbuf_put(state->outgoing_packet,
1183 "\0\0\0\0\0", 5)) != 0 ||
1184 (r = sshbuf_putb(state->outgoing_packet,
1185 state->compression_buffer)) != 0)
1187 DBG(debug("compression: raw %d compressed %zd", len,
1188 sshbuf_len(state->outgoing_packet)));
1191 /* sizeof (packet_len + pad_len + payload) */
1192 len = sshbuf_len(state->outgoing_packet);
1195 * calc size of padding, alloc space, get random data,
1196 * minimum padding is 4 bytes
1198 len -= aadlen; /* packet length is not encrypted for EtM modes */
1199 padlen = block_size - (len % block_size);
1201 padlen += block_size;
1202 if (state->extra_pad) {
1203 /* will wrap if extra_pad+padlen > 255 */
1205 roundup(state->extra_pad, block_size);
1206 pad = state->extra_pad -
1207 ((len + padlen) % state->extra_pad);
1208 DBG(debug3("%s: adding %d (len %d padlen %d extra_pad %d)",
1209 __func__, pad, len, padlen, state->extra_pad));
1211 state->extra_pad = 0;
1213 if ((r = sshbuf_reserve(state->outgoing_packet, padlen, &cp)) != 0)
1215 if (enc && !state->send_context.plaintext) {
1216 /* random padding */
1217 arc4random_buf(cp, padlen);
1220 explicit_bzero(cp, padlen);
1222 /* sizeof (packet_len + pad_len + payload + padding) */
1223 len = sshbuf_len(state->outgoing_packet);
1224 cp = sshbuf_mutable_ptr(state->outgoing_packet);
1226 r = SSH_ERR_INTERNAL_ERROR;
1229 /* packet_length includes payload, padding and padding length field */
1230 POKE_U32(cp, len - 4);
1232 DBG(debug("send: len %d (includes padlen %d, aadlen %d)",
1233 len, padlen, aadlen));
1235 /* compute MAC over seqnr and packet(length fields, payload, padding) */
1236 if (mac && mac->enabled && !mac->etm) {
1237 if ((r = mac_compute(mac, state->p_send.seqnr,
1238 sshbuf_ptr(state->outgoing_packet), len,
1239 macbuf, sizeof(macbuf))) != 0)
1241 DBG(debug("done calc MAC out #%d", state->p_send.seqnr));
1243 /* encrypt packet and append to output buffer. */
1244 if ((r = sshbuf_reserve(state->output,
1245 sshbuf_len(state->outgoing_packet) + authlen, &cp)) != 0)
1247 if ((r = cipher_crypt(&state->send_context, state->p_send.seqnr, cp,
1248 sshbuf_ptr(state->outgoing_packet),
1249 len - aadlen, aadlen, authlen)) != 0)
1251 /* append unencrypted MAC */
1252 if (mac && mac->enabled) {
1254 /* EtM: compute mac over aadlen + cipher text */
1255 if ((r = mac_compute(mac, state->p_send.seqnr,
1256 cp, len, macbuf, sizeof(macbuf))) != 0)
1258 DBG(debug("done calc MAC(EtM) out #%d",
1259 state->p_send.seqnr));
1261 if ((r = sshbuf_put(state->output, macbuf, mac->mac_len)) != 0)
1265 fprintf(stderr, "encrypted: ");
1266 sshbuf_dump(state->output, stderr);
1268 /* increment sequence number for outgoing packets */
1269 if (++state->p_send.seqnr == 0)
1270 logit("outgoing seqnr wraps around");
1271 if (++state->p_send.packets == 0)
1272 if (!(ssh->compat & SSH_BUG_NOREKEY))
1273 return SSH_ERR_NEED_REKEY;
1274 state->p_send.blocks += len / block_size;
1275 state->p_send.bytes += len;
1276 sshbuf_reset(state->outgoing_packet);
1278 if (type == SSH2_MSG_NEWKEYS)
1279 r = ssh_set_newkeys(ssh, MODE_OUT);
1280 else if (type == SSH2_MSG_USERAUTH_SUCCESS && state->server_side)
1281 r = ssh_packet_enable_delayed_compress(ssh);
1288 /* returns non-zero if the specified packet type is usec by KEX */
1290 ssh_packet_type_is_kex(u_char type)
1293 type >= SSH2_MSG_TRANSPORT_MIN &&
1294 type <= SSH2_MSG_TRANSPORT_MAX &&
1295 type != SSH2_MSG_SERVICE_REQUEST &&
1296 type != SSH2_MSG_SERVICE_ACCEPT &&
1297 type != SSH2_MSG_EXT_INFO;
1301 ssh_packet_send2(struct ssh *ssh)
1303 struct session_state *state = ssh->state;
1308 if (sshbuf_len(state->outgoing_packet) < 6)
1309 return SSH_ERR_INTERNAL_ERROR;
1310 type = sshbuf_ptr(state->outgoing_packet)[5];
1311 need_rekey = !ssh_packet_type_is_kex(type) &&
1312 ssh_packet_need_rekeying(ssh, sshbuf_len(state->outgoing_packet));
1315 * During rekeying we can only send key exchange messages.
1316 * Queue everything else.
1318 if ((need_rekey || state->rekeying) && !ssh_packet_type_is_kex(type)) {
1320 debug3("%s: rekex triggered", __func__);
1321 debug("enqueue packet: %u", type);
1322 p = calloc(1, sizeof(*p));
1324 return SSH_ERR_ALLOC_FAIL;
1326 p->payload = state->outgoing_packet;
1327 TAILQ_INSERT_TAIL(&state->outgoing, p, next);
1328 state->outgoing_packet = sshbuf_new();
1329 if (state->outgoing_packet == NULL)
1330 return SSH_ERR_ALLOC_FAIL;
1333 * This packet triggered a rekey, so send the
1335 * NB. reenters this function via kex_start_rekex().
1337 return kex_start_rekex(ssh);
1342 /* rekeying starts with sending KEXINIT */
1343 if (type == SSH2_MSG_KEXINIT)
1344 state->rekeying = 1;
1346 if ((r = ssh_packet_send2_wrapped(ssh)) != 0)
1349 /* after a NEWKEYS message we can send the complete queue */
1350 if (type == SSH2_MSG_NEWKEYS) {
1351 state->rekeying = 0;
1352 state->rekey_time = monotime();
1353 while ((p = TAILQ_FIRST(&state->outgoing))) {
1356 * If this packet triggers a rekex, then skip the
1357 * remaining packets in the queue for now.
1358 * NB. re-enters this function via kex_start_rekex.
1360 if (ssh_packet_need_rekeying(ssh,
1361 sshbuf_len(p->payload))) {
1362 debug3("%s: queued packet triggered rekex",
1364 return kex_start_rekex(ssh);
1366 debug("dequeue packet: %u", type);
1367 sshbuf_free(state->outgoing_packet);
1368 state->outgoing_packet = p->payload;
1369 TAILQ_REMOVE(&state->outgoing, p, next);
1370 memset(p, 0, sizeof(*p));
1372 if ((r = ssh_packet_send2_wrapped(ssh)) != 0)
1380 * Waits until a packet has been received, and returns its type. Note that
1381 * no other data is processed until this returns, so this function should not
1382 * be used during the interactive session.
1386 ssh_packet_read_seqnr(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1388 struct session_state *state = ssh->state;
1389 int len, r, ms_remain;
1392 struct timeval timeout, start, *timeoutp = NULL;
1394 DBG(debug("packet_read()"));
1396 setp = calloc(howmany(state->connection_in + 1,
1397 NFDBITS), sizeof(fd_mask));
1399 return SSH_ERR_ALLOC_FAIL;
1402 * Since we are blocking, ensure that all written packets have
1405 if ((r = ssh_packet_write_wait(ssh)) != 0)
1408 /* Stay in the loop until we have received a complete packet. */
1410 /* Try to read a packet from the buffer. */
1411 r = ssh_packet_read_poll_seqnr(ssh, typep, seqnr_p);
1415 *typep == SSH_SMSG_SUCCESS
1416 || *typep == SSH_SMSG_FAILURE
1417 || *typep == SSH_CMSG_EOF
1418 || *typep == SSH_CMSG_EXIT_CONFIRMATION))
1419 if ((r = sshpkt_get_end(ssh)) != 0)
1421 /* If we got a packet, return it. */
1422 if (*typep != SSH_MSG_NONE)
1425 * Otherwise, wait for some data to arrive, add it to the
1426 * buffer, and try again.
1428 memset(setp, 0, howmany(state->connection_in + 1,
1429 NFDBITS) * sizeof(fd_mask));
1430 FD_SET(state->connection_in, setp);
1432 if (state->packet_timeout_ms > 0) {
1433 ms_remain = state->packet_timeout_ms;
1434 timeoutp = &timeout;
1436 /* Wait for some data to arrive. */
1438 if (state->packet_timeout_ms != -1) {
1439 ms_to_timeval(&timeout, ms_remain);
1440 gettimeofday(&start, NULL);
1442 if ((r = select(state->connection_in + 1, setp,
1443 NULL, NULL, timeoutp)) >= 0)
1445 if (errno != EAGAIN && errno != EINTR &&
1446 errno != EWOULDBLOCK)
1448 if (state->packet_timeout_ms == -1)
1450 ms_subtract_diff(&start, &ms_remain);
1451 if (ms_remain <= 0) {
1457 return SSH_ERR_CONN_TIMEOUT;
1458 /* Read data from the socket. */
1459 len = read(state->connection_in, buf, sizeof(buf));
1461 r = SSH_ERR_CONN_CLOSED;
1465 r = SSH_ERR_SYSTEM_ERROR;
1469 /* Append it to the buffer. */
1470 if ((r = ssh_packet_process_incoming(ssh, buf, len)) != 0)
1479 ssh_packet_read(struct ssh *ssh)
1484 if ((r = ssh_packet_read_seqnr(ssh, &type, NULL)) != 0)
1485 fatal("%s: %s", __func__, ssh_err(r));
1490 * Waits until a packet has been received, verifies that its type matches
1491 * that given, and gives a fatal error and exits if there is a mismatch.
1495 ssh_packet_read_expect(struct ssh *ssh, u_int expected_type)
1500 if ((r = ssh_packet_read_seqnr(ssh, &type, NULL)) != 0)
1502 if (type != expected_type) {
1503 if ((r = sshpkt_disconnect(ssh,
1504 "Protocol error: expected packet type %d, got %d",
1505 expected_type, type)) != 0)
1507 return SSH_ERR_PROTOCOL_ERROR;
1512 /* Checks if a full packet is available in the data received so far via
1513 * packet_process_incoming. If so, reads the packet; otherwise returns
1514 * SSH_MSG_NONE. This does not wait for data from the connection.
1516 * SSH_MSG_DISCONNECT is handled specially here. Also,
1517 * SSH_MSG_IGNORE messages are skipped by this function and are never returned
1522 ssh_packet_read_poll1(struct ssh *ssh, u_char *typep)
1524 struct session_state *state = ssh->state;
1525 u_int len, padded_len;
1529 u_int checksum, stored_checksum;
1532 *typep = SSH_MSG_NONE;
1534 /* Check if input size is less than minimum packet size. */
1535 if (sshbuf_len(state->input) < 4 + 8)
1537 /* Get length of incoming packet. */
1538 len = PEEK_U32(sshbuf_ptr(state->input));
1539 if (len < 1 + 2 + 2 || len > 256 * 1024) {
1540 if ((r = sshpkt_disconnect(ssh, "Bad packet length %u",
1543 return SSH_ERR_CONN_CORRUPT;
1545 padded_len = (len + 8) & ~7;
1547 /* Check if the packet has been entirely received. */
1548 if (sshbuf_len(state->input) < 4 + padded_len)
1551 /* The entire packet is in buffer. */
1553 /* Consume packet length. */
1554 if ((r = sshbuf_consume(state->input, 4)) != 0)
1558 * Cryptographic attack detector for ssh
1559 * (C)1998 CORE-SDI, Buenos Aires Argentina
1560 * Ariel Futoransky(futo@core-sdi.com)
1562 if (!state->receive_context.plaintext) {
1564 switch (detect_attack(&state->deattack,
1565 sshbuf_ptr(state->input), padded_len)) {
1568 case DEATTACK_DETECTED:
1569 emsg = "crc32 compensation attack detected";
1571 case DEATTACK_DOS_DETECTED:
1572 emsg = "deattack denial of service detected";
1575 emsg = "deattack error";
1580 if ((r = sshpkt_disconnect(ssh, "%s", emsg)) != 0 ||
1581 (r = ssh_packet_write_wait(ssh)) != 0)
1583 return SSH_ERR_CONN_CORRUPT;
1587 /* Decrypt data to incoming_packet. */
1588 sshbuf_reset(state->incoming_packet);
1589 if ((r = sshbuf_reserve(state->incoming_packet, padded_len, &p)) != 0)
1591 if ((r = cipher_crypt(&state->receive_context, 0, p,
1592 sshbuf_ptr(state->input), padded_len, 0, 0)) != 0)
1595 if ((r = sshbuf_consume(state->input, padded_len)) != 0)
1599 fprintf(stderr, "read_poll plain: ");
1600 sshbuf_dump(state->incoming_packet, stderr);
1603 /* Compute packet checksum. */
1604 checksum = ssh_crc32(sshbuf_ptr(state->incoming_packet),
1605 sshbuf_len(state->incoming_packet) - 4);
1608 if ((r = sshbuf_consume(state->incoming_packet, 8 - len % 8)) != 0)
1611 /* Test check bytes. */
1612 if (len != sshbuf_len(state->incoming_packet)) {
1613 error("%s: len %d != sshbuf_len %zd", __func__,
1614 len, sshbuf_len(state->incoming_packet));
1615 if ((r = sshpkt_disconnect(ssh, "invalid packet length")) != 0 ||
1616 (r = ssh_packet_write_wait(ssh)) != 0)
1618 return SSH_ERR_CONN_CORRUPT;
1621 cp = sshbuf_ptr(state->incoming_packet) + len - 4;
1622 stored_checksum = PEEK_U32(cp);
1623 if (checksum != stored_checksum) {
1624 error("Corrupted check bytes on input");
1625 if ((r = sshpkt_disconnect(ssh, "connection corrupted")) != 0 ||
1626 (r = ssh_packet_write_wait(ssh)) != 0)
1628 return SSH_ERR_CONN_CORRUPT;
1630 if ((r = sshbuf_consume_end(state->incoming_packet, 4)) < 0)
1633 if (state->packet_compression) {
1634 sshbuf_reset(state->compression_buffer);
1635 if ((r = uncompress_buffer(ssh, state->incoming_packet,
1636 state->compression_buffer)) != 0)
1638 sshbuf_reset(state->incoming_packet);
1639 if ((r = sshbuf_putb(state->incoming_packet,
1640 state->compression_buffer)) != 0)
1643 state->p_read.packets++;
1644 state->p_read.bytes += padded_len + 4;
1645 if ((r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
1647 if (*typep < SSH_MSG_MIN || *typep > SSH_MSG_MAX) {
1648 error("Invalid ssh1 packet type: %d", *typep);
1649 if ((r = sshpkt_disconnect(ssh, "invalid packet type")) != 0 ||
1650 (r = ssh_packet_write_wait(ssh)) != 0)
1652 return SSH_ERR_PROTOCOL_ERROR;
1660 ssh_packet_read_poll2(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1662 struct session_state *state = ssh->state;
1664 u_char *cp, macbuf[SSH_DIGEST_MAX_LENGTH];
1665 u_int maclen, aadlen = 0, authlen = 0, block_size;
1666 struct sshenc *enc = NULL;
1667 struct sshmac *mac = NULL;
1668 struct sshcomp *comp = NULL;
1671 *typep = SSH_MSG_NONE;
1673 if (state->packet_discard)
1676 if (state->newkeys[MODE_IN] != NULL) {
1677 enc = &state->newkeys[MODE_IN]->enc;
1678 mac = &state->newkeys[MODE_IN]->mac;
1679 comp = &state->newkeys[MODE_IN]->comp;
1680 /* disable mac for authenticated encryption */
1681 if ((authlen = cipher_authlen(enc->cipher)) != 0)
1684 maclen = mac && mac->enabled ? mac->mac_len : 0;
1685 block_size = enc ? enc->block_size : 8;
1686 aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
1688 if (aadlen && state->packlen == 0) {
1689 if (cipher_get_length(&state->receive_context,
1690 &state->packlen, state->p_read.seqnr,
1691 sshbuf_ptr(state->input), sshbuf_len(state->input)) != 0)
1693 if (state->packlen < 1 + 4 ||
1694 state->packlen > PACKET_MAX_SIZE) {
1696 sshbuf_dump(state->input, stderr);
1698 logit("Bad packet length %u.", state->packlen);
1699 if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0)
1701 return SSH_ERR_CONN_CORRUPT;
1703 sshbuf_reset(state->incoming_packet);
1704 } else if (state->packlen == 0) {
1706 * check if input size is less than the cipher block size,
1707 * decrypt first block and extract length of incoming packet
1709 if (sshbuf_len(state->input) < block_size)
1711 sshbuf_reset(state->incoming_packet);
1712 if ((r = sshbuf_reserve(state->incoming_packet, block_size,
1715 if ((r = cipher_crypt(&state->receive_context,
1716 state->p_send.seqnr, cp, sshbuf_ptr(state->input),
1717 block_size, 0, 0)) != 0)
1719 state->packlen = PEEK_U32(sshbuf_ptr(state->incoming_packet));
1720 if (state->packlen < 1 + 4 ||
1721 state->packlen > PACKET_MAX_SIZE) {
1723 fprintf(stderr, "input: \n");
1724 sshbuf_dump(state->input, stderr);
1725 fprintf(stderr, "incoming_packet: \n");
1726 sshbuf_dump(state->incoming_packet, stderr);
1728 logit("Bad packet length %u.", state->packlen);
1729 return ssh_packet_start_discard(ssh, enc, mac,
1730 state->packlen, PACKET_MAX_SIZE);
1732 if ((r = sshbuf_consume(state->input, block_size)) != 0)
1735 DBG(debug("input: packet len %u", state->packlen+4));
1738 /* only the payload is encrypted */
1739 need = state->packlen;
1742 * the payload size and the payload are encrypted, but we
1743 * have a partial packet of block_size bytes
1745 need = 4 + state->packlen - block_size;
1747 DBG(debug("partial packet: block %d, need %d, maclen %d, authlen %d,"
1748 " aadlen %d", block_size, need, maclen, authlen, aadlen));
1749 if (need % block_size != 0) {
1750 logit("padding error: need %d block %d mod %d",
1751 need, block_size, need % block_size);
1752 return ssh_packet_start_discard(ssh, enc, mac,
1753 state->packlen, PACKET_MAX_SIZE - block_size);
1756 * check if the entire packet has been received and
1757 * decrypt into incoming_packet:
1758 * 'aadlen' bytes are unencrypted, but authenticated.
1759 * 'need' bytes are encrypted, followed by either
1760 * 'authlen' bytes of authentication tag or
1761 * 'maclen' bytes of message authentication code.
1763 if (sshbuf_len(state->input) < aadlen + need + authlen + maclen)
1766 fprintf(stderr, "read_poll enc/full: ");
1767 sshbuf_dump(state->input, stderr);
1769 /* EtM: compute mac over encrypted input */
1770 if (mac && mac->enabled && mac->etm) {
1771 if ((r = mac_compute(mac, state->p_read.seqnr,
1772 sshbuf_ptr(state->input), aadlen + need,
1773 macbuf, sizeof(macbuf))) != 0)
1776 if ((r = sshbuf_reserve(state->incoming_packet, aadlen + need,
1779 if ((r = cipher_crypt(&state->receive_context, state->p_read.seqnr, cp,
1780 sshbuf_ptr(state->input), need, aadlen, authlen)) != 0)
1782 if ((r = sshbuf_consume(state->input, aadlen + need + authlen)) != 0)
1785 * compute MAC over seqnr and packet,
1786 * increment sequence number for incoming packet
1788 if (mac && mac->enabled) {
1790 if ((r = mac_compute(mac, state->p_read.seqnr,
1791 sshbuf_ptr(state->incoming_packet),
1792 sshbuf_len(state->incoming_packet),
1793 macbuf, sizeof(macbuf))) != 0)
1795 if (timingsafe_bcmp(macbuf, sshbuf_ptr(state->input),
1796 mac->mac_len) != 0) {
1797 logit("Corrupted MAC on input.");
1798 if (need > PACKET_MAX_SIZE)
1799 return SSH_ERR_INTERNAL_ERROR;
1800 return ssh_packet_start_discard(ssh, enc, mac,
1801 state->packlen, PACKET_MAX_SIZE - need);
1804 DBG(debug("MAC #%d ok", state->p_read.seqnr));
1805 if ((r = sshbuf_consume(state->input, mac->mac_len)) != 0)
1808 if (seqnr_p != NULL)
1809 *seqnr_p = state->p_read.seqnr;
1810 if (++state->p_read.seqnr == 0)
1811 logit("incoming seqnr wraps around");
1812 if (++state->p_read.packets == 0)
1813 if (!(ssh->compat & SSH_BUG_NOREKEY))
1814 return SSH_ERR_NEED_REKEY;
1815 state->p_read.blocks += (state->packlen + 4) / block_size;
1816 state->p_read.bytes += state->packlen + 4;
1819 padlen = sshbuf_ptr(state->incoming_packet)[4];
1820 DBG(debug("input: padlen %d", padlen));
1822 if ((r = sshpkt_disconnect(ssh,
1823 "Corrupted padlen %d on input.", padlen)) != 0 ||
1824 (r = ssh_packet_write_wait(ssh)) != 0)
1826 return SSH_ERR_CONN_CORRUPT;
1829 /* skip packet size + padlen, discard padding */
1830 if ((r = sshbuf_consume(state->incoming_packet, 4 + 1)) != 0 ||
1831 ((r = sshbuf_consume_end(state->incoming_packet, padlen)) != 0))
1834 DBG(debug("input: len before de-compress %zd",
1835 sshbuf_len(state->incoming_packet)));
1836 if (comp && comp->enabled) {
1837 sshbuf_reset(state->compression_buffer);
1838 if ((r = uncompress_buffer(ssh, state->incoming_packet,
1839 state->compression_buffer)) != 0)
1841 sshbuf_reset(state->incoming_packet);
1842 if ((r = sshbuf_putb(state->incoming_packet,
1843 state->compression_buffer)) != 0)
1845 DBG(debug("input: len after de-compress %zd",
1846 sshbuf_len(state->incoming_packet)));
1849 * get packet type, implies consume.
1850 * return length of payload (without type field)
1852 if ((r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
1854 if (ssh_packet_log_type(*typep))
1855 debug3("receive packet: type %u", *typep);
1856 if (*typep < SSH2_MSG_MIN || *typep >= SSH2_MSG_LOCAL_MIN) {
1857 if ((r = sshpkt_disconnect(ssh,
1858 "Invalid ssh2 packet type: %d", *typep)) != 0 ||
1859 (r = ssh_packet_write_wait(ssh)) != 0)
1861 return SSH_ERR_PROTOCOL_ERROR;
1863 if (*typep == SSH2_MSG_NEWKEYS)
1864 r = ssh_set_newkeys(ssh, MODE_IN);
1865 else if (*typep == SSH2_MSG_USERAUTH_SUCCESS && !state->server_side)
1866 r = ssh_packet_enable_delayed_compress(ssh);
1870 fprintf(stderr, "read/plain[%d]:\r\n", *typep);
1871 sshbuf_dump(state->incoming_packet, stderr);
1873 /* reset for next packet */
1876 /* do we need to rekey? */
1877 if (ssh_packet_need_rekeying(ssh, 0)) {
1878 debug3("%s: rekex triggered", __func__);
1879 if ((r = kex_start_rekex(ssh)) != 0)
1887 ssh_packet_read_poll_seqnr(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1889 struct session_state *state = ssh->state;
1890 u_int reason, seqnr;
1897 r = ssh_packet_read_poll2(ssh, typep, seqnr_p);
1901 state->keep_alive_timeouts = 0;
1902 DBG(debug("received packet type %d", *typep));
1905 case SSH2_MSG_IGNORE:
1906 debug3("Received SSH2_MSG_IGNORE");
1908 case SSH2_MSG_DEBUG:
1909 if ((r = sshpkt_get_u8(ssh, NULL)) != 0 ||
1910 (r = sshpkt_get_string(ssh, &msg, NULL)) != 0 ||
1911 (r = sshpkt_get_string(ssh, NULL, NULL)) != 0) {
1915 debug("Remote: %.900s", msg);
1918 case SSH2_MSG_DISCONNECT:
1919 if ((r = sshpkt_get_u32(ssh, &reason)) != 0 ||
1920 (r = sshpkt_get_string(ssh, &msg, NULL)) != 0)
1922 /* Ignore normal client exit notifications */
1923 do_log2(ssh->state->server_side &&
1924 reason == SSH2_DISCONNECT_BY_APPLICATION ?
1925 SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_ERROR,
1926 "Received disconnect from %s port %d:"
1927 "%u: %.400s", ssh_remote_ipaddr(ssh),
1928 ssh_remote_port(ssh), reason, msg);
1930 return SSH_ERR_DISCONNECTED;
1931 case SSH2_MSG_UNIMPLEMENTED:
1932 if ((r = sshpkt_get_u32(ssh, &seqnr)) != 0)
1934 debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1941 r = ssh_packet_read_poll1(ssh, typep);
1944 return SSH_MSG_NONE;
1945 case SSH_MSG_IGNORE:
1948 if ((r = sshpkt_get_string(ssh, &msg, NULL)) != 0)
1950 debug("Remote: %.900s", msg);
1953 case SSH_MSG_DISCONNECT:
1954 if ((r = sshpkt_get_string(ssh, &msg, NULL)) != 0)
1956 error("Received disconnect from %s port %d: "
1957 "%.400s", ssh_remote_ipaddr(ssh),
1958 ssh_remote_port(ssh), msg);
1960 return SSH_ERR_DISCONNECTED;
1962 DBG(debug("received packet type %d", *typep));
1970 * Buffers the given amount of input characters. This is intended to be used
1971 * together with packet_read_poll.
1975 ssh_packet_process_incoming(struct ssh *ssh, const char *buf, u_int len)
1977 struct session_state *state = ssh->state;
1980 if (state->packet_discard) {
1981 state->keep_alive_timeouts = 0; /* ?? */
1982 if (len >= state->packet_discard) {
1983 if ((r = ssh_packet_stop_discard(ssh)) != 0)
1986 state->packet_discard -= len;
1989 if ((r = sshbuf_put(ssh->state->input, buf, len)) != 0)
1996 ssh_packet_remaining(struct ssh *ssh)
1998 return sshbuf_len(ssh->state->incoming_packet);
2002 * Sends a diagnostic message from the server to the client. This message
2003 * can be sent at any time (but not while constructing another message). The
2004 * message is printed immediately, but only if the client is being executed
2005 * in verbose mode. These messages are primarily intended to ease debugging
2006 * authentication problems. The length of the formatted message must not
2007 * exceed 1024 bytes. This will automatically call ssh_packet_write_wait.
2010 ssh_packet_send_debug(struct ssh *ssh, const char *fmt,...)
2016 if (compat20 && (ssh->compat & SSH_BUG_DEBUG))
2019 va_start(args, fmt);
2020 vsnprintf(buf, sizeof(buf), fmt, args);
2024 if ((r = sshpkt_start(ssh, SSH2_MSG_DEBUG)) != 0 ||
2025 (r = sshpkt_put_u8(ssh, 0)) != 0 || /* always display */
2026 (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
2027 (r = sshpkt_put_cstring(ssh, "")) != 0 ||
2028 (r = sshpkt_send(ssh)) != 0)
2029 fatal("%s: %s", __func__, ssh_err(r));
2031 if ((r = sshpkt_start(ssh, SSH_MSG_DEBUG)) != 0 ||
2032 (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
2033 (r = sshpkt_send(ssh)) != 0)
2034 fatal("%s: %s", __func__, ssh_err(r));
2036 if ((r = ssh_packet_write_wait(ssh)) != 0)
2037 fatal("%s: %s", __func__, ssh_err(r));
2041 * Pretty-print connection-terminating errors and exit.
2044 sshpkt_fatal(struct ssh *ssh, const char *tag, int r)
2047 case SSH_ERR_CONN_CLOSED:
2048 logit("Connection closed by %.200s port %d",
2049 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
2051 case SSH_ERR_CONN_TIMEOUT:
2052 logit("Connection %s %.200s port %d timed out",
2053 ssh->state->server_side ? "from" : "to",
2054 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
2056 case SSH_ERR_DISCONNECTED:
2057 logit("Disconnected from %.200s port %d",
2058 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
2060 case SSH_ERR_SYSTEM_ERROR:
2061 if (errno == ECONNRESET) {
2062 logit("Connection reset by %.200s port %d",
2063 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
2067 case SSH_ERR_NO_CIPHER_ALG_MATCH:
2068 case SSH_ERR_NO_MAC_ALG_MATCH:
2069 case SSH_ERR_NO_COMPRESS_ALG_MATCH:
2070 case SSH_ERR_NO_KEX_ALG_MATCH:
2071 case SSH_ERR_NO_HOSTKEY_ALG_MATCH:
2072 if (ssh && ssh->kex && ssh->kex->failed_choice) {
2073 fatal("Unable to negotiate with %.200s port %d: %s. "
2074 "Their offer: %s", ssh_remote_ipaddr(ssh),
2075 ssh_remote_port(ssh), ssh_err(r),
2076 ssh->kex->failed_choice);
2080 fatal("%s%sConnection %s %.200s port %d: %s",
2081 tag != NULL ? tag : "", tag != NULL ? ": " : "",
2082 ssh->state->server_side ? "from" : "to",
2083 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), ssh_err(r));
2088 * Logs the error plus constructs and sends a disconnect packet, closes the
2089 * connection, and exits. This function never returns. The error message
2090 * should not contain a newline. The length of the formatted message must
2091 * not exceed 1024 bytes.
2094 ssh_packet_disconnect(struct ssh *ssh, const char *fmt,...)
2098 static int disconnecting = 0;
2101 if (disconnecting) /* Guard against recursive invocations. */
2102 fatal("packet_disconnect called recursively.");
2106 * Format the message. Note that the caller must make sure the
2107 * message is of limited size.
2109 va_start(args, fmt);
2110 vsnprintf(buf, sizeof(buf), fmt, args);
2113 /* Display the error locally */
2114 logit("Disconnecting: %.100s", buf);
2117 * Send the disconnect message to the other side, and wait
2118 * for it to get sent.
2120 if ((r = sshpkt_disconnect(ssh, "%s", buf)) != 0)
2121 sshpkt_fatal(ssh, __func__, r);
2123 if ((r = ssh_packet_write_wait(ssh)) != 0)
2124 sshpkt_fatal(ssh, __func__, r);
2126 /* Close the connection. */
2127 ssh_packet_close(ssh);
2132 * Checks if there is any buffered output, and tries to write some of
2136 ssh_packet_write_poll(struct ssh *ssh)
2138 struct session_state *state = ssh->state;
2139 int len = sshbuf_len(state->output);
2143 len = write(state->connection_out,
2144 sshbuf_ptr(state->output), len);
2146 if (errno == EINTR || errno == EAGAIN ||
2147 errno == EWOULDBLOCK)
2149 return SSH_ERR_SYSTEM_ERROR;
2152 return SSH_ERR_CONN_CLOSED;
2153 if ((r = sshbuf_consume(state->output, len)) != 0)
2160 * Calls packet_write_poll repeatedly until all pending output data has been
2164 ssh_packet_write_wait(struct ssh *ssh)
2167 int ret, r, ms_remain = 0;
2168 struct timeval start, timeout, *timeoutp = NULL;
2169 struct session_state *state = ssh->state;
2171 setp = calloc(howmany(state->connection_out + 1,
2172 NFDBITS), sizeof(fd_mask));
2174 return SSH_ERR_ALLOC_FAIL;
2175 if ((r = ssh_packet_write_poll(ssh)) != 0) {
2179 while (ssh_packet_have_data_to_write(ssh)) {
2180 memset(setp, 0, howmany(state->connection_out + 1,
2181 NFDBITS) * sizeof(fd_mask));
2182 FD_SET(state->connection_out, setp);
2184 if (state->packet_timeout_ms > 0) {
2185 ms_remain = state->packet_timeout_ms;
2186 timeoutp = &timeout;
2189 if (state->packet_timeout_ms != -1) {
2190 ms_to_timeval(&timeout, ms_remain);
2191 gettimeofday(&start, NULL);
2193 if ((ret = select(state->connection_out + 1,
2194 NULL, setp, NULL, timeoutp)) >= 0)
2196 if (errno != EAGAIN && errno != EINTR &&
2197 errno != EWOULDBLOCK)
2199 if (state->packet_timeout_ms == -1)
2201 ms_subtract_diff(&start, &ms_remain);
2202 if (ms_remain <= 0) {
2209 return SSH_ERR_CONN_TIMEOUT;
2211 if ((r = ssh_packet_write_poll(ssh)) != 0) {
2220 /* Returns true if there is buffered data to write to the connection. */
2223 ssh_packet_have_data_to_write(struct ssh *ssh)
2225 return sshbuf_len(ssh->state->output) != 0;
2228 /* Returns true if there is not too much data to write to the connection. */
2231 ssh_packet_not_very_much_data_to_write(struct ssh *ssh)
2233 if (ssh->state->interactive_mode)
2234 return sshbuf_len(ssh->state->output) < 16384;
2236 return sshbuf_len(ssh->state->output) < 128 * 1024;
2240 ssh_packet_set_tos(struct ssh *ssh, int tos)
2242 #ifndef IP_TOS_IS_BROKEN
2243 if (!ssh_packet_connection_is_on_socket(ssh))
2245 switch (ssh_packet_connection_af(ssh)) {
2248 debug3("%s: set IP_TOS 0x%02x", __func__, tos);
2249 if (setsockopt(ssh->state->connection_in,
2250 IPPROTO_IP, IP_TOS, &tos, sizeof(tos)) < 0)
2251 error("setsockopt IP_TOS %d: %.100s:",
2252 tos, strerror(errno));
2254 # endif /* IP_TOS */
2257 debug3("%s: set IPV6_TCLASS 0x%02x", __func__, tos);
2258 if (setsockopt(ssh->state->connection_in,
2259 IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof(tos)) < 0)
2260 error("setsockopt IPV6_TCLASS %d: %.100s:",
2261 tos, strerror(errno));
2263 # endif /* IPV6_TCLASS */
2265 #endif /* IP_TOS_IS_BROKEN */
2268 /* Informs that the current session is interactive. Sets IP flags for that. */
2271 ssh_packet_set_interactive(struct ssh *ssh, int interactive, int qos_interactive, int qos_bulk)
2273 struct session_state *state = ssh->state;
2275 if (state->set_interactive_called)
2277 state->set_interactive_called = 1;
2279 /* Record that we are in interactive mode. */
2280 state->interactive_mode = interactive;
2282 /* Only set socket options if using a socket. */
2283 if (!ssh_packet_connection_is_on_socket(ssh))
2285 set_nodelay(state->connection_in);
2286 ssh_packet_set_tos(ssh, interactive ? qos_interactive :
2290 /* Returns true if the current connection is interactive. */
2293 ssh_packet_is_interactive(struct ssh *ssh)
2295 return ssh->state->interactive_mode;
2299 ssh_packet_set_maxsize(struct ssh *ssh, u_int s)
2301 struct session_state *state = ssh->state;
2303 if (state->set_maxsize_called) {
2304 logit("packet_set_maxsize: called twice: old %d new %d",
2305 state->max_packet_size, s);
2308 if (s < 4 * 1024 || s > 1024 * 1024) {
2309 logit("packet_set_maxsize: bad size %d", s);
2312 state->set_maxsize_called = 1;
2313 debug("packet_set_maxsize: setting to %d", s);
2314 state->max_packet_size = s;
2319 ssh_packet_inc_alive_timeouts(struct ssh *ssh)
2321 return ++ssh->state->keep_alive_timeouts;
2325 ssh_packet_set_alive_timeouts(struct ssh *ssh, int ka)
2327 ssh->state->keep_alive_timeouts = ka;
2331 ssh_packet_get_maxsize(struct ssh *ssh)
2333 return ssh->state->max_packet_size;
2337 * 9.2. Ignored Data Message
2339 * byte SSH_MSG_IGNORE
2342 * All implementations MUST understand (and ignore) this message at any
2343 * time (after receiving the protocol version). No implementation is
2344 * required to send them. This message can be used as an additional
2345 * protection measure against advanced traffic analysis techniques.
2348 ssh_packet_send_ignore(struct ssh *ssh, int nbytes)
2353 if ((r = sshpkt_start(ssh, compat20 ?
2354 SSH2_MSG_IGNORE : SSH_MSG_IGNORE)) != 0 ||
2355 (r = sshpkt_put_u32(ssh, nbytes)) != 0)
2356 fatal("%s: %s", __func__, ssh_err(r));
2357 for (i = 0; i < nbytes; i++) {
2360 if ((r = sshpkt_put_u8(ssh, (u_char)rnd & 0xff)) != 0)
2361 fatal("%s: %s", __func__, ssh_err(r));
2367 ssh_packet_set_rekey_limits(struct ssh *ssh, u_int64_t bytes, time_t seconds)
2369 debug3("rekey after %llu bytes, %d seconds", (unsigned long long)bytes,
2371 ssh->state->rekey_limit = bytes;
2372 ssh->state->rekey_interval = seconds;
2376 ssh_packet_get_rekey_timeout(struct ssh *ssh)
2380 seconds = ssh->state->rekey_time + ssh->state->rekey_interval -
2382 return (seconds <= 0 ? 1 : seconds);
2386 ssh_packet_set_server(struct ssh *ssh)
2388 ssh->state->server_side = 1;
2392 ssh_packet_set_authenticated(struct ssh *ssh)
2394 ssh->state->after_authentication = 1;
2398 ssh_packet_get_input(struct ssh *ssh)
2400 return (void *)ssh->state->input;
2404 ssh_packet_get_output(struct ssh *ssh)
2406 return (void *)ssh->state->output;
2409 /* Reset after_authentication and reset compression in post-auth privsep */
2411 ssh_packet_set_postauth(struct ssh *ssh)
2413 struct sshcomp *comp;
2416 debug("%s: called", __func__);
2417 /* This was set in net child, but is not visible in user child */
2418 ssh->state->after_authentication = 1;
2419 ssh->state->rekeying = 0;
2420 for (mode = 0; mode < MODE_MAX; mode++) {
2421 if (ssh->state->newkeys[mode] == NULL)
2423 comp = &ssh->state->newkeys[mode]->comp;
2424 if (comp && comp->enabled &&
2425 (r = ssh_packet_init_compression(ssh)) != 0)
2431 /* Packet state (de-)serialization for privsep */
2433 /* turn kex into a blob for packet state serialization */
2435 kex_to_blob(struct sshbuf *m, struct kex *kex)
2439 if ((r = sshbuf_put_string(m, kex->session_id,
2440 kex->session_id_len)) != 0 ||
2441 (r = sshbuf_put_u32(m, kex->we_need)) != 0 ||
2442 (r = sshbuf_put_u32(m, kex->hostkey_type)) != 0 ||
2443 (r = sshbuf_put_u32(m, kex->kex_type)) != 0 ||
2444 (r = sshbuf_put_stringb(m, kex->my)) != 0 ||
2445 (r = sshbuf_put_stringb(m, kex->peer)) != 0 ||
2446 (r = sshbuf_put_u32(m, kex->flags)) != 0 ||
2447 (r = sshbuf_put_cstring(m, kex->client_version_string)) != 0 ||
2448 (r = sshbuf_put_cstring(m, kex->server_version_string)) != 0)
2453 /* turn key exchange results into a blob for packet state serialization */
2455 newkeys_to_blob(struct sshbuf *m, struct ssh *ssh, int mode)
2458 struct sshcipher_ctx *cc;
2459 struct sshcomp *comp;
2462 struct newkeys *newkey;
2465 if ((newkey = ssh->state->newkeys[mode]) == NULL)
2466 return SSH_ERR_INTERNAL_ERROR;
2469 comp = &newkey->comp;
2470 cc = (mode == MODE_OUT) ? &ssh->state->send_context :
2471 &ssh->state->receive_context;
2472 if ((r = cipher_get_keyiv(cc, enc->iv, enc->iv_len)) != 0)
2474 if ((b = sshbuf_new()) == NULL)
2475 return SSH_ERR_ALLOC_FAIL;
2476 /* The cipher struct is constant and shared, you export pointer */
2477 if ((r = sshbuf_put_cstring(b, enc->name)) != 0 ||
2478 (r = sshbuf_put(b, &enc->cipher, sizeof(enc->cipher))) != 0 ||
2479 (r = sshbuf_put_u32(b, enc->enabled)) != 0 ||
2480 (r = sshbuf_put_u32(b, enc->block_size)) != 0 ||
2481 (r = sshbuf_put_string(b, enc->key, enc->key_len)) != 0 ||
2482 (r = sshbuf_put_string(b, enc->iv, enc->iv_len)) != 0)
2484 if (cipher_authlen(enc->cipher) == 0) {
2485 if ((r = sshbuf_put_cstring(b, mac->name)) != 0 ||
2486 (r = sshbuf_put_u32(b, mac->enabled)) != 0 ||
2487 (r = sshbuf_put_string(b, mac->key, mac->key_len)) != 0)
2490 if ((r = sshbuf_put_u32(b, comp->type)) != 0 ||
2491 (r = sshbuf_put_u32(b, comp->enabled)) != 0 ||
2492 (r = sshbuf_put_cstring(b, comp->name)) != 0)
2494 r = sshbuf_put_stringb(m, b);
2500 /* serialize packet state into a blob */
2502 ssh_packet_get_state(struct ssh *ssh, struct sshbuf *m)
2504 struct session_state *state = ssh->state;
2510 ssh1cipher = cipher_get_number(state->receive_context.cipher);
2511 slen = cipher_get_keyiv_len(&state->send_context);
2512 rlen = cipher_get_keyiv_len(&state->receive_context);
2513 if ((r = sshbuf_put_u32(m, state->remote_protocol_flags)) != 0 ||
2514 (r = sshbuf_put_u32(m, ssh1cipher)) != 0 ||
2515 (r = sshbuf_put_string(m, state->ssh1_key, state->ssh1_keylen)) != 0 ||
2516 (r = sshbuf_put_u32(m, slen)) != 0 ||
2517 (r = sshbuf_reserve(m, slen, &p)) != 0 ||
2518 (r = cipher_get_keyiv(&state->send_context, p, slen)) != 0 ||
2519 (r = sshbuf_put_u32(m, rlen)) != 0 ||
2520 (r = sshbuf_reserve(m, rlen, &p)) != 0 ||
2521 (r = cipher_get_keyiv(&state->receive_context, p, rlen)) != 0)
2524 if ((r = kex_to_blob(m, ssh->kex)) != 0 ||
2525 (r = newkeys_to_blob(m, ssh, MODE_OUT)) != 0 ||
2526 (r = newkeys_to_blob(m, ssh, MODE_IN)) != 0 ||
2527 (r = sshbuf_put_u64(m, state->rekey_limit)) != 0 ||
2528 (r = sshbuf_put_u32(m, state->rekey_interval)) != 0 ||
2529 (r = sshbuf_put_u32(m, state->p_send.seqnr)) != 0 ||
2530 (r = sshbuf_put_u64(m, state->p_send.blocks)) != 0 ||
2531 (r = sshbuf_put_u32(m, state->p_send.packets)) != 0 ||
2532 (r = sshbuf_put_u64(m, state->p_send.bytes)) != 0 ||
2533 (r = sshbuf_put_u32(m, state->p_read.seqnr)) != 0 ||
2534 (r = sshbuf_put_u64(m, state->p_read.blocks)) != 0 ||
2535 (r = sshbuf_put_u32(m, state->p_read.packets)) != 0 ||
2536 (r = sshbuf_put_u64(m, state->p_read.bytes)) != 0)
2540 slen = cipher_get_keycontext(&state->send_context, NULL);
2541 rlen = cipher_get_keycontext(&state->receive_context, NULL);
2542 if ((r = sshbuf_put_u32(m, slen)) != 0 ||
2543 (r = sshbuf_reserve(m, slen, &p)) != 0)
2545 if (cipher_get_keycontext(&state->send_context, p) != (int)slen)
2546 return SSH_ERR_INTERNAL_ERROR;
2547 if ((r = sshbuf_put_u32(m, rlen)) != 0 ||
2548 (r = sshbuf_reserve(m, rlen, &p)) != 0)
2550 if (cipher_get_keycontext(&state->receive_context, p) != (int)rlen)
2551 return SSH_ERR_INTERNAL_ERROR;
2553 if ((r = ssh_packet_get_compress_state(m, ssh)) != 0 ||
2554 (r = sshbuf_put_stringb(m, state->input)) != 0 ||
2555 (r = sshbuf_put_stringb(m, state->output)) != 0)
2561 /* restore key exchange results from blob for packet state de-serialization */
2563 newkeys_from_blob(struct sshbuf *m, struct ssh *ssh, int mode)
2565 struct sshbuf *b = NULL;
2566 struct sshcomp *comp;
2569 struct newkeys *newkey = NULL;
2570 size_t keylen, ivlen, maclen;
2573 if ((newkey = calloc(1, sizeof(*newkey))) == NULL) {
2574 r = SSH_ERR_ALLOC_FAIL;
2577 if ((r = sshbuf_froms(m, &b)) != 0)
2580 sshbuf_dump(b, stderr);
2584 comp = &newkey->comp;
2586 if ((r = sshbuf_get_cstring(b, &enc->name, NULL)) != 0 ||
2587 (r = sshbuf_get(b, &enc->cipher, sizeof(enc->cipher))) != 0 ||
2588 (r = sshbuf_get_u32(b, (u_int *)&enc->enabled)) != 0 ||
2589 (r = sshbuf_get_u32(b, &enc->block_size)) != 0 ||
2590 (r = sshbuf_get_string(b, &enc->key, &keylen)) != 0 ||
2591 (r = sshbuf_get_string(b, &enc->iv, &ivlen)) != 0)
2593 if (cipher_authlen(enc->cipher) == 0) {
2594 if ((r = sshbuf_get_cstring(b, &mac->name, NULL)) != 0)
2596 if ((r = mac_setup(mac, mac->name)) != 0)
2598 if ((r = sshbuf_get_u32(b, (u_int *)&mac->enabled)) != 0 ||
2599 (r = sshbuf_get_string(b, &mac->key, &maclen)) != 0)
2601 if (maclen > mac->key_len) {
2602 r = SSH_ERR_INVALID_FORMAT;
2605 mac->key_len = maclen;
2607 if ((r = sshbuf_get_u32(b, &comp->type)) != 0 ||
2608 (r = sshbuf_get_u32(b, (u_int *)&comp->enabled)) != 0 ||
2609 (r = sshbuf_get_cstring(b, &comp->name, NULL)) != 0)
2611 if (enc->name == NULL ||
2612 cipher_by_name(enc->name) != enc->cipher) {
2613 r = SSH_ERR_INVALID_FORMAT;
2616 if (sshbuf_len(b) != 0) {
2617 r = SSH_ERR_INVALID_FORMAT;
2620 enc->key_len = keylen;
2621 enc->iv_len = ivlen;
2622 ssh->kex->newkeys[mode] = newkey;
2631 /* restore kex from blob for packet state de-serialization */
2633 kex_from_blob(struct sshbuf *m, struct kex **kexp)
2638 if ((kex = calloc(1, sizeof(struct kex))) == NULL ||
2639 (kex->my = sshbuf_new()) == NULL ||
2640 (kex->peer = sshbuf_new()) == NULL) {
2641 r = SSH_ERR_ALLOC_FAIL;
2644 if ((r = sshbuf_get_string(m, &kex->session_id, &kex->session_id_len)) != 0 ||
2645 (r = sshbuf_get_u32(m, &kex->we_need)) != 0 ||
2646 (r = sshbuf_get_u32(m, (u_int *)&kex->hostkey_type)) != 0 ||
2647 (r = sshbuf_get_u32(m, &kex->kex_type)) != 0 ||
2648 (r = sshbuf_get_stringb(m, kex->my)) != 0 ||
2649 (r = sshbuf_get_stringb(m, kex->peer)) != 0 ||
2650 (r = sshbuf_get_u32(m, &kex->flags)) != 0 ||
2651 (r = sshbuf_get_cstring(m, &kex->client_version_string, NULL)) != 0 ||
2652 (r = sshbuf_get_cstring(m, &kex->server_version_string, NULL)) != 0)
2658 if (r != 0 || kexp == NULL) {
2660 sshbuf_free(kex->my);
2661 sshbuf_free(kex->peer);
2673 * Restore packet state from content of blob 'm' (de-serialization).
2674 * Note that 'm' will be partially consumed on parsing or any other errors.
2677 ssh_packet_set_state(struct ssh *ssh, struct sshbuf *m)
2679 struct session_state *state = ssh->state;
2680 const u_char *ssh1key, *ivin, *ivout, *keyin, *keyout, *input, *output;
2681 size_t ssh1keylen, rlen, slen, ilen, olen;
2683 u_int ssh1cipher = 0;
2686 if ((r = sshbuf_get_u32(m, &state->remote_protocol_flags)) != 0 ||
2687 (r = sshbuf_get_u32(m, &ssh1cipher)) != 0 ||
2688 (r = sshbuf_get_string_direct(m, &ssh1key, &ssh1keylen)) != 0 ||
2689 (r = sshbuf_get_string_direct(m, &ivout, &slen)) != 0 ||
2690 (r = sshbuf_get_string_direct(m, &ivin, &rlen)) != 0)
2692 if (ssh1cipher > INT_MAX)
2693 return SSH_ERR_KEY_UNKNOWN_CIPHER;
2694 ssh_packet_set_encryption_key(ssh, ssh1key, ssh1keylen,
2696 if (cipher_get_keyiv_len(&state->send_context) != (int)slen ||
2697 cipher_get_keyiv_len(&state->receive_context) != (int)rlen)
2698 return SSH_ERR_INVALID_FORMAT;
2699 if ((r = cipher_set_keyiv(&state->send_context, ivout)) != 0 ||
2700 (r = cipher_set_keyiv(&state->receive_context, ivin)) != 0)
2703 if ((r = kex_from_blob(m, &ssh->kex)) != 0 ||
2704 (r = newkeys_from_blob(m, ssh, MODE_OUT)) != 0 ||
2705 (r = newkeys_from_blob(m, ssh, MODE_IN)) != 0 ||
2706 (r = sshbuf_get_u64(m, &state->rekey_limit)) != 0 ||
2707 (r = sshbuf_get_u32(m, &state->rekey_interval)) != 0 ||
2708 (r = sshbuf_get_u32(m, &state->p_send.seqnr)) != 0 ||
2709 (r = sshbuf_get_u64(m, &state->p_send.blocks)) != 0 ||
2710 (r = sshbuf_get_u32(m, &state->p_send.packets)) != 0 ||
2711 (r = sshbuf_get_u64(m, &state->p_send.bytes)) != 0 ||
2712 (r = sshbuf_get_u32(m, &state->p_read.seqnr)) != 0 ||
2713 (r = sshbuf_get_u64(m, &state->p_read.blocks)) != 0 ||
2714 (r = sshbuf_get_u32(m, &state->p_read.packets)) != 0 ||
2715 (r = sshbuf_get_u64(m, &state->p_read.bytes)) != 0)
2718 * We set the time here so that in post-auth privsep slave we
2719 * count from the completion of the authentication.
2721 state->rekey_time = monotime();
2722 /* XXX ssh_set_newkeys overrides p_read.packets? XXX */
2723 if ((r = ssh_set_newkeys(ssh, MODE_IN)) != 0 ||
2724 (r = ssh_set_newkeys(ssh, MODE_OUT)) != 0)
2727 if ((r = sshbuf_get_string_direct(m, &keyout, &slen)) != 0 ||
2728 (r = sshbuf_get_string_direct(m, &keyin, &rlen)) != 0)
2730 if (cipher_get_keycontext(&state->send_context, NULL) != (int)slen ||
2731 cipher_get_keycontext(&state->receive_context, NULL) != (int)rlen)
2732 return SSH_ERR_INVALID_FORMAT;
2733 cipher_set_keycontext(&state->send_context, keyout);
2734 cipher_set_keycontext(&state->receive_context, keyin);
2736 if ((r = ssh_packet_set_compress_state(ssh, m)) != 0 ||
2737 (r = ssh_packet_set_postauth(ssh)) != 0)
2740 sshbuf_reset(state->input);
2741 sshbuf_reset(state->output);
2742 if ((r = sshbuf_get_string_direct(m, &input, &ilen)) != 0 ||
2743 (r = sshbuf_get_string_direct(m, &output, &olen)) != 0 ||
2744 (r = sshbuf_put(state->input, input, ilen)) != 0 ||
2745 (r = sshbuf_put(state->output, output, olen)) != 0)
2749 return SSH_ERR_INVALID_FORMAT;
2750 debug3("%s: done", __func__);
2756 /* put data to the outgoing packet */
2759 sshpkt_put(struct ssh *ssh, const void *v, size_t len)
2761 return sshbuf_put(ssh->state->outgoing_packet, v, len);
2765 sshpkt_putb(struct ssh *ssh, const struct sshbuf *b)
2767 return sshbuf_putb(ssh->state->outgoing_packet, b);
2771 sshpkt_put_u8(struct ssh *ssh, u_char val)
2773 return sshbuf_put_u8(ssh->state->outgoing_packet, val);
2777 sshpkt_put_u32(struct ssh *ssh, u_int32_t val)
2779 return sshbuf_put_u32(ssh->state->outgoing_packet, val);
2783 sshpkt_put_u64(struct ssh *ssh, u_int64_t val)
2785 return sshbuf_put_u64(ssh->state->outgoing_packet, val);
2789 sshpkt_put_string(struct ssh *ssh, const void *v, size_t len)
2791 return sshbuf_put_string(ssh->state->outgoing_packet, v, len);
2795 sshpkt_put_cstring(struct ssh *ssh, const void *v)
2797 return sshbuf_put_cstring(ssh->state->outgoing_packet, v);
2801 sshpkt_put_stringb(struct ssh *ssh, const struct sshbuf *v)
2803 return sshbuf_put_stringb(ssh->state->outgoing_packet, v);
2807 #ifdef OPENSSL_HAS_ECC
2809 sshpkt_put_ec(struct ssh *ssh, const EC_POINT *v, const EC_GROUP *g)
2811 return sshbuf_put_ec(ssh->state->outgoing_packet, v, g);
2813 #endif /* OPENSSL_HAS_ECC */
2817 sshpkt_put_bignum1(struct ssh *ssh, const BIGNUM *v)
2819 return sshbuf_put_bignum1(ssh->state->outgoing_packet, v);
2821 #endif /* WITH_SSH1 */
2824 sshpkt_put_bignum2(struct ssh *ssh, const BIGNUM *v)
2826 return sshbuf_put_bignum2(ssh->state->outgoing_packet, v);
2828 #endif /* WITH_OPENSSL */
2830 /* fetch data from the incoming packet */
2833 sshpkt_get(struct ssh *ssh, void *valp, size_t len)
2835 return sshbuf_get(ssh->state->incoming_packet, valp, len);
2839 sshpkt_get_u8(struct ssh *ssh, u_char *valp)
2841 return sshbuf_get_u8(ssh->state->incoming_packet, valp);
2845 sshpkt_get_u32(struct ssh *ssh, u_int32_t *valp)
2847 return sshbuf_get_u32(ssh->state->incoming_packet, valp);
2851 sshpkt_get_u64(struct ssh *ssh, u_int64_t *valp)
2853 return sshbuf_get_u64(ssh->state->incoming_packet, valp);
2857 sshpkt_get_string(struct ssh *ssh, u_char **valp, size_t *lenp)
2859 return sshbuf_get_string(ssh->state->incoming_packet, valp, lenp);
2863 sshpkt_get_string_direct(struct ssh *ssh, const u_char **valp, size_t *lenp)
2865 return sshbuf_get_string_direct(ssh->state->incoming_packet, valp, lenp);
2869 sshpkt_get_cstring(struct ssh *ssh, char **valp, size_t *lenp)
2871 return sshbuf_get_cstring(ssh->state->incoming_packet, valp, lenp);
2875 #ifdef OPENSSL_HAS_ECC
2877 sshpkt_get_ec(struct ssh *ssh, EC_POINT *v, const EC_GROUP *g)
2879 return sshbuf_get_ec(ssh->state->incoming_packet, v, g);
2881 #endif /* OPENSSL_HAS_ECC */
2885 sshpkt_get_bignum1(struct ssh *ssh, BIGNUM *v)
2887 return sshbuf_get_bignum1(ssh->state->incoming_packet, v);
2889 #endif /* WITH_SSH1 */
2892 sshpkt_get_bignum2(struct ssh *ssh, BIGNUM *v)
2894 return sshbuf_get_bignum2(ssh->state->incoming_packet, v);
2896 #endif /* WITH_OPENSSL */
2899 sshpkt_get_end(struct ssh *ssh)
2901 if (sshbuf_len(ssh->state->incoming_packet) > 0)
2902 return SSH_ERR_UNEXPECTED_TRAILING_DATA;
2907 sshpkt_ptr(struct ssh *ssh, size_t *lenp)
2910 *lenp = sshbuf_len(ssh->state->incoming_packet);
2911 return sshbuf_ptr(ssh->state->incoming_packet);
2914 /* start a new packet */
2917 sshpkt_start(struct ssh *ssh, u_char type)
2922 DBG(debug("packet_start[%d]", type));
2923 len = compat20 ? 6 : 9;
2924 memset(buf, 0, len - 1);
2925 buf[len - 1] = type;
2926 sshbuf_reset(ssh->state->outgoing_packet);
2927 return sshbuf_put(ssh->state->outgoing_packet, buf, len);
2933 sshpkt_send(struct ssh *ssh)
2936 return ssh_packet_send2(ssh);
2938 return ssh_packet_send1(ssh);
2942 sshpkt_disconnect(struct ssh *ssh, const char *fmt,...)
2948 va_start(args, fmt);
2949 vsnprintf(buf, sizeof(buf), fmt, args);
2953 if ((r = sshpkt_start(ssh, SSH2_MSG_DISCONNECT)) != 0 ||
2954 (r = sshpkt_put_u32(ssh, SSH2_DISCONNECT_PROTOCOL_ERROR)) != 0 ||
2955 (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
2956 (r = sshpkt_put_cstring(ssh, "")) != 0 ||
2957 (r = sshpkt_send(ssh)) != 0)
2960 if ((r = sshpkt_start(ssh, SSH_MSG_DISCONNECT)) != 0 ||
2961 (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
2962 (r = sshpkt_send(ssh)) != 0)
2968 /* roundup current message to pad bytes */
2970 sshpkt_add_padding(struct ssh *ssh, u_char pad)
2972 ssh->state->extra_pad = pad;