1 /* $OpenBSD: packet.c,v 1.214 2015/08/20 22:32:42 deraadt 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 */
97 #define PACKET_MAX_SIZE (256 * 1024)
107 TAILQ_ENTRY(packet) next;
109 struct sshbuf *payload;
112 struct session_state {
114 * This variable contains the file descriptors used for
115 * communicating with the other side. connection_in is used for
116 * reading; connection_out for writing. These can be the same
117 * descriptor, in which case it is assumed to be a socket.
122 /* Protocol flags for the remote side. */
123 u_int remote_protocol_flags;
125 /* Encryption context for receiving data. Only used for decryption. */
126 struct sshcipher_ctx receive_context;
128 /* Encryption context for sending data. Only used for encryption. */
129 struct sshcipher_ctx send_context;
131 /* Buffer for raw input data from the socket. */
132 struct sshbuf *input;
134 /* Buffer for raw output data going to the socket. */
135 struct sshbuf *output;
137 /* Buffer for the partial outgoing packet being constructed. */
138 struct sshbuf *outgoing_packet;
140 /* Buffer for the incoming packet currently being processed. */
141 struct sshbuf *incoming_packet;
143 /* Scratch buffer for packet compression/decompression. */
144 struct sshbuf *compression_buffer;
146 /* Incoming/outgoing compression dictionaries */
147 z_stream compression_in_stream;
148 z_stream compression_out_stream;
149 int compression_in_started;
150 int compression_out_started;
151 int compression_in_failures;
152 int compression_out_failures;
155 * Flag indicating whether packet compression/decompression is
158 int packet_compression;
160 /* default maximum packet size */
161 u_int max_packet_size;
163 /* Flag indicating whether this module has been initialized. */
166 /* Set to true if the connection is interactive. */
167 int interactive_mode;
169 /* Set to true if we are the server side. */
172 /* Set to true if we are authenticated. */
173 int after_authentication;
175 int keep_alive_timeouts;
177 /* The maximum time that we will wait to send or receive a packet */
178 int packet_timeout_ms;
180 /* Session key information for Encryption and MAC */
181 struct newkeys *newkeys[MODE_MAX];
182 struct packet_state p_read, p_send;
184 /* Volume-based rekeying */
185 u_int64_t max_blocks_in, max_blocks_out;
186 u_int32_t rekey_limit;
188 /* Time-based rekeying */
189 u_int32_t rekey_interval; /* how often in seconds */
190 time_t rekey_time; /* time of last rekeying */
192 /* Session key for protocol v1 */
193 u_char ssh1_key[SSH_SESSION_KEY_LENGTH];
196 /* roundup current message to extra_pad bytes */
199 /* XXX discard incoming data after MAC error */
200 u_int packet_discard;
201 struct sshmac *packet_discard_mac;
203 /* Used in packet_read_poll2() */
206 /* Used in packet_send2 */
209 /* Used in packet_set_interactive */
210 int set_interactive_called;
212 /* Used in packet_set_maxsize */
213 int set_maxsize_called;
215 /* One-off warning about weak ciphers */
216 int cipher_warning_done;
218 /* SSH1 CRC compensation attack detector */
219 struct deattack_ctx deattack;
221 TAILQ_HEAD(, packet) outgoing;
225 ssh_alloc_session_state(void)
227 struct ssh *ssh = NULL;
228 struct session_state *state = NULL;
230 if ((ssh = calloc(1, sizeof(*ssh))) == NULL ||
231 (state = calloc(1, sizeof(*state))) == NULL ||
232 (state->input = sshbuf_new()) == NULL ||
233 (state->output = sshbuf_new()) == NULL ||
234 (state->outgoing_packet = sshbuf_new()) == NULL ||
235 (state->incoming_packet = sshbuf_new()) == NULL)
237 TAILQ_INIT(&state->outgoing);
238 TAILQ_INIT(&ssh->private_keys);
239 TAILQ_INIT(&ssh->public_keys);
240 state->connection_in = -1;
241 state->connection_out = -1;
242 state->max_packet_size = 32768;
243 state->packet_timeout_ms = -1;
244 state->p_send.packets = state->p_read.packets = 0;
245 state->initialized = 1;
247 * ssh_packet_send2() needs to queue packets until
248 * we've done the initial key exchange.
255 sshbuf_free(state->input);
256 sshbuf_free(state->output);
257 sshbuf_free(state->incoming_packet);
258 sshbuf_free(state->outgoing_packet);
266 * Sets the descriptors used for communication. Disables encryption until
267 * packet_set_encryption_key is called.
270 ssh_packet_set_connection(struct ssh *ssh, int fd_in, int fd_out)
272 struct session_state *state;
273 const struct sshcipher *none = cipher_by_name("none");
277 error("%s: cannot load cipher 'none'", __func__);
281 ssh = ssh_alloc_session_state();
283 error("%s: cound not allocate state", __func__);
287 state->connection_in = fd_in;
288 state->connection_out = fd_out;
289 if ((r = cipher_init(&state->send_context, none,
290 (const u_char *)"", 0, NULL, 0, CIPHER_ENCRYPT)) != 0 ||
291 (r = cipher_init(&state->receive_context, none,
292 (const u_char *)"", 0, NULL, 0, CIPHER_DECRYPT)) != 0) {
293 error("%s: cipher_init failed: %s", __func__, ssh_err(r));
297 state->newkeys[MODE_IN] = state->newkeys[MODE_OUT] = NULL;
298 deattack_init(&state->deattack);
300 * Cache the IP address of the remote connection for use in error
301 * messages that might be generated after the connection has closed.
303 (void)ssh_remote_ipaddr(ssh);
308 ssh_packet_set_timeout(struct ssh *ssh, int timeout, int count)
310 struct session_state *state = ssh->state;
312 if (timeout <= 0 || count <= 0) {
313 state->packet_timeout_ms = -1;
316 if ((INT_MAX / 1000) / count < timeout)
317 state->packet_timeout_ms = INT_MAX;
319 state->packet_timeout_ms = timeout * count * 1000;
323 ssh_packet_stop_discard(struct ssh *ssh)
325 struct session_state *state = ssh->state;
328 if (state->packet_discard_mac) {
331 memset(buf, 'a', sizeof(buf));
332 while (sshbuf_len(state->incoming_packet) <
334 if ((r = sshbuf_put(state->incoming_packet, buf,
337 (void) mac_compute(state->packet_discard_mac,
339 sshbuf_ptr(state->incoming_packet), PACKET_MAX_SIZE,
342 logit("Finished discarding for %.200s", ssh_remote_ipaddr(ssh));
343 return SSH_ERR_MAC_INVALID;
347 ssh_packet_start_discard(struct ssh *ssh, struct sshenc *enc,
348 struct sshmac *mac, u_int packet_length, u_int discard)
350 struct session_state *state = ssh->state;
353 if (enc == NULL || !cipher_is_cbc(enc->cipher) || (mac && mac->etm)) {
354 if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0)
356 return SSH_ERR_MAC_INVALID;
358 if (packet_length != PACKET_MAX_SIZE && mac && mac->enabled)
359 state->packet_discard_mac = mac;
360 if (sshbuf_len(state->input) >= discard &&
361 (r = ssh_packet_stop_discard(ssh)) != 0)
363 state->packet_discard = discard - sshbuf_len(state->input);
367 /* Returns 1 if remote host is connected via socket, 0 if not. */
370 ssh_packet_connection_is_on_socket(struct ssh *ssh)
372 struct session_state *state = ssh->state;
373 struct sockaddr_storage from, to;
374 socklen_t fromlen, tolen;
376 /* filedescriptors in and out are the same, so it's a socket */
377 if (state->connection_in == state->connection_out)
379 fromlen = sizeof(from);
380 memset(&from, 0, sizeof(from));
381 if (getpeername(state->connection_in, (struct sockaddr *)&from,
385 memset(&to, 0, sizeof(to));
386 if (getpeername(state->connection_out, (struct sockaddr *)&to,
389 if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
391 if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
397 ssh_packet_get_bytes(struct ssh *ssh, u_int64_t *ibytes, u_int64_t *obytes)
400 *ibytes = ssh->state->p_read.bytes;
402 *obytes = ssh->state->p_send.bytes;
406 ssh_packet_connection_af(struct ssh *ssh)
408 struct sockaddr_storage to;
409 socklen_t tolen = sizeof(to);
411 memset(&to, 0, sizeof(to));
412 if (getsockname(ssh->state->connection_out, (struct sockaddr *)&to,
416 if (to.ss_family == AF_INET6 &&
417 IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&to)->sin6_addr))
423 /* Sets the connection into non-blocking mode. */
426 ssh_packet_set_nonblocking(struct ssh *ssh)
428 /* Set the socket into non-blocking mode. */
429 set_nonblock(ssh->state->connection_in);
431 if (ssh->state->connection_out != ssh->state->connection_in)
432 set_nonblock(ssh->state->connection_out);
435 /* Returns the socket used for reading. */
438 ssh_packet_get_connection_in(struct ssh *ssh)
440 return ssh->state->connection_in;
443 /* Returns the descriptor used for writing. */
446 ssh_packet_get_connection_out(struct ssh *ssh)
448 return ssh->state->connection_out;
452 * Returns the IP-address of the remote host as a string. The returned
453 * string must not be freed.
457 ssh_remote_ipaddr(struct ssh *ssh)
459 /* Check whether we have cached the ipaddr. */
460 if (ssh->remote_ipaddr == NULL)
461 ssh->remote_ipaddr = ssh_packet_connection_is_on_socket(ssh) ?
462 get_peer_ipaddr(ssh->state->connection_in) :
464 if (ssh->remote_ipaddr == NULL)
466 return ssh->remote_ipaddr;
469 /* Closes the connection and clears and frees internal data structures. */
472 ssh_packet_close(struct ssh *ssh)
474 struct session_state *state = ssh->state;
478 if (!state->initialized)
480 state->initialized = 0;
481 if (state->connection_in == state->connection_out) {
482 shutdown(state->connection_out, SHUT_RDWR);
483 close(state->connection_out);
485 close(state->connection_in);
486 close(state->connection_out);
488 sshbuf_free(state->input);
489 sshbuf_free(state->output);
490 sshbuf_free(state->outgoing_packet);
491 sshbuf_free(state->incoming_packet);
492 for (mode = 0; mode < MODE_MAX; mode++)
493 kex_free_newkeys(state->newkeys[mode]);
494 if (state->compression_buffer) {
495 sshbuf_free(state->compression_buffer);
496 if (state->compression_out_started) {
497 z_streamp stream = &state->compression_out_stream;
498 debug("compress outgoing: "
499 "raw data %llu, compressed %llu, factor %.2f",
500 (unsigned long long)stream->total_in,
501 (unsigned long long)stream->total_out,
502 stream->total_in == 0 ? 0.0 :
503 (double) stream->total_out / stream->total_in);
504 if (state->compression_out_failures == 0)
507 if (state->compression_in_started) {
508 z_streamp stream = &state->compression_out_stream;
509 debug("compress incoming: "
510 "raw data %llu, compressed %llu, factor %.2f",
511 (unsigned long long)stream->total_out,
512 (unsigned long long)stream->total_in,
513 stream->total_out == 0 ? 0.0 :
514 (double) stream->total_in / stream->total_out);
515 if (state->compression_in_failures == 0)
519 if ((r = cipher_cleanup(&state->send_context)) != 0)
520 error("%s: cipher_cleanup failed: %s", __func__, ssh_err(r));
521 if ((r = cipher_cleanup(&state->receive_context)) != 0)
522 error("%s: cipher_cleanup failed: %s", __func__, ssh_err(r));
523 if (ssh->remote_ipaddr) {
524 free(ssh->remote_ipaddr);
525 ssh->remote_ipaddr = NULL;
531 /* Sets remote side protocol flags. */
534 ssh_packet_set_protocol_flags(struct ssh *ssh, u_int protocol_flags)
536 ssh->state->remote_protocol_flags = protocol_flags;
539 /* Returns the remote protocol flags set earlier by the above function. */
542 ssh_packet_get_protocol_flags(struct ssh *ssh)
544 return ssh->state->remote_protocol_flags;
548 * Starts packet compression from the next packet on in both directions.
549 * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
553 ssh_packet_init_compression(struct ssh *ssh)
555 if (!ssh->state->compression_buffer &&
556 ((ssh->state->compression_buffer = sshbuf_new()) == NULL))
557 return SSH_ERR_ALLOC_FAIL;
562 start_compression_out(struct ssh *ssh, int level)
564 if (level < 1 || level > 9)
565 return SSH_ERR_INVALID_ARGUMENT;
566 debug("Enabling compression at level %d.", level);
567 if (ssh->state->compression_out_started == 1)
568 deflateEnd(&ssh->state->compression_out_stream);
569 switch (deflateInit(&ssh->state->compression_out_stream, level)) {
571 ssh->state->compression_out_started = 1;
574 return SSH_ERR_ALLOC_FAIL;
576 return SSH_ERR_INTERNAL_ERROR;
582 start_compression_in(struct ssh *ssh)
584 if (ssh->state->compression_in_started == 1)
585 inflateEnd(&ssh->state->compression_in_stream);
586 switch (inflateInit(&ssh->state->compression_in_stream)) {
588 ssh->state->compression_in_started = 1;
591 return SSH_ERR_ALLOC_FAIL;
593 return SSH_ERR_INTERNAL_ERROR;
599 ssh_packet_start_compression(struct ssh *ssh, int level)
603 if (ssh->state->packet_compression && !compat20)
604 return SSH_ERR_INTERNAL_ERROR;
605 ssh->state->packet_compression = 1;
606 if ((r = ssh_packet_init_compression(ssh)) != 0 ||
607 (r = start_compression_in(ssh)) != 0 ||
608 (r = start_compression_out(ssh, level)) != 0)
613 /* XXX remove need for separate compression buffer */
615 compress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
620 if (ssh->state->compression_out_started != 1)
621 return SSH_ERR_INTERNAL_ERROR;
623 /* This case is not handled below. */
624 if (sshbuf_len(in) == 0)
627 /* Input is the contents of the input buffer. */
628 if ((ssh->state->compression_out_stream.next_in =
629 sshbuf_mutable_ptr(in)) == NULL)
630 return SSH_ERR_INTERNAL_ERROR;
631 ssh->state->compression_out_stream.avail_in = sshbuf_len(in);
633 /* Loop compressing until deflate() returns with avail_out != 0. */
635 /* Set up fixed-size output buffer. */
636 ssh->state->compression_out_stream.next_out = buf;
637 ssh->state->compression_out_stream.avail_out = sizeof(buf);
639 /* Compress as much data into the buffer as possible. */
640 status = deflate(&ssh->state->compression_out_stream,
644 return SSH_ERR_ALLOC_FAIL;
646 /* Append compressed data to output_buffer. */
647 if ((r = sshbuf_put(out, buf, sizeof(buf) -
648 ssh->state->compression_out_stream.avail_out)) != 0)
653 ssh->state->compression_out_failures++;
654 return SSH_ERR_INVALID_FORMAT;
656 } while (ssh->state->compression_out_stream.avail_out == 0);
661 uncompress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
666 if (ssh->state->compression_in_started != 1)
667 return SSH_ERR_INTERNAL_ERROR;
669 if ((ssh->state->compression_in_stream.next_in =
670 sshbuf_mutable_ptr(in)) == NULL)
671 return SSH_ERR_INTERNAL_ERROR;
672 ssh->state->compression_in_stream.avail_in = sshbuf_len(in);
675 /* Set up fixed-size output buffer. */
676 ssh->state->compression_in_stream.next_out = buf;
677 ssh->state->compression_in_stream.avail_out = sizeof(buf);
679 status = inflate(&ssh->state->compression_in_stream,
683 if ((r = sshbuf_put(out, buf, sizeof(buf) -
684 ssh->state->compression_in_stream.avail_out)) != 0)
689 * Comments in zlib.h say that we should keep calling
690 * inflate() until we get an error. This appears to
691 * be the error that we get.
695 return SSH_ERR_INVALID_FORMAT;
697 return SSH_ERR_ALLOC_FAIL;
700 ssh->state->compression_in_failures++;
701 return SSH_ERR_INTERNAL_ERROR;
707 /* Serialise compression state into a blob for privsep */
709 ssh_packet_get_compress_state(struct sshbuf *m, struct ssh *ssh)
711 struct session_state *state = ssh->state;
715 if ((b = sshbuf_new()) == NULL)
716 return SSH_ERR_ALLOC_FAIL;
717 if (state->compression_in_started) {
718 if ((r = sshbuf_put_string(b, &state->compression_in_stream,
719 sizeof(state->compression_in_stream))) != 0)
721 } else if ((r = sshbuf_put_string(b, NULL, 0)) != 0)
723 if (state->compression_out_started) {
724 if ((r = sshbuf_put_string(b, &state->compression_out_stream,
725 sizeof(state->compression_out_stream))) != 0)
727 } else if ((r = sshbuf_put_string(b, NULL, 0)) != 0)
729 r = sshbuf_put_stringb(m, b);
735 /* Deserialise compression state from a blob for privsep */
737 ssh_packet_set_compress_state(struct ssh *ssh, struct sshbuf *m)
739 struct session_state *state = ssh->state;
740 struct sshbuf *b = NULL;
742 const u_char *inblob, *outblob;
745 if ((r = sshbuf_froms(m, &b)) != 0)
747 if ((r = sshbuf_get_string_direct(b, &inblob, &inl)) != 0 ||
748 (r = sshbuf_get_string_direct(b, &outblob, &outl)) != 0)
751 state->compression_in_started = 0;
752 else if (inl != sizeof(state->compression_in_stream)) {
753 r = SSH_ERR_INTERNAL_ERROR;
756 state->compression_in_started = 1;
757 memcpy(&state->compression_in_stream, inblob, inl);
760 state->compression_out_started = 0;
761 else if (outl != sizeof(state->compression_out_stream)) {
762 r = SSH_ERR_INTERNAL_ERROR;
765 state->compression_out_started = 1;
766 memcpy(&state->compression_out_stream, outblob, outl);
775 ssh_packet_set_compress_hooks(struct ssh *ssh, void *ctx,
776 void *(*allocfunc)(void *, u_int, u_int),
777 void (*freefunc)(void *, void *))
779 ssh->state->compression_out_stream.zalloc = (alloc_func)allocfunc;
780 ssh->state->compression_out_stream.zfree = (free_func)freefunc;
781 ssh->state->compression_out_stream.opaque = ctx;
782 ssh->state->compression_in_stream.zalloc = (alloc_func)allocfunc;
783 ssh->state->compression_in_stream.zfree = (free_func)freefunc;
784 ssh->state->compression_in_stream.opaque = ctx;
788 * Causes any further packets to be encrypted using the given key. The same
789 * key is used for both sending and reception. However, both directions are
790 * encrypted independently of each other.
794 ssh_packet_set_encryption_key(struct ssh *ssh, const u_char *key, u_int keylen, int number)
797 fatal("no SSH protocol 1 support");
798 #else /* WITH_SSH1 */
799 struct session_state *state = ssh->state;
800 const struct sshcipher *cipher = cipher_by_number(number);
805 fatal("%s: unknown cipher number %d", __func__, number);
807 fatal("%s: keylen too small: %d", __func__, keylen);
808 if (keylen > SSH_SESSION_KEY_LENGTH)
809 fatal("%s: keylen too big: %d", __func__, keylen);
810 memcpy(state->ssh1_key, key, keylen);
811 state->ssh1_keylen = keylen;
812 if ((r = cipher_init(&state->send_context, cipher, key, keylen,
813 NULL, 0, CIPHER_ENCRYPT)) != 0 ||
814 (r = cipher_init(&state->receive_context, cipher, key, keylen,
815 NULL, 0, CIPHER_DECRYPT) != 0))
816 fatal("%s: cipher_init failed: %s", __func__, ssh_err(r));
817 if (!state->cipher_warning_done &&
818 ((wmsg = cipher_warning_message(&state->send_context)) != NULL ||
819 (wmsg = cipher_warning_message(&state->send_context)) != NULL)) {
820 error("Warning: %s", wmsg);
821 state->cipher_warning_done = 1;
823 #endif /* WITH_SSH1 */
827 * Finalizes and sends the packet. If the encryption key has been set,
828 * encrypts the packet before sending.
832 ssh_packet_send1(struct ssh *ssh)
834 struct session_state *state = ssh->state;
840 * If using packet compression, compress the payload of the outgoing
843 if (state->packet_compression) {
844 sshbuf_reset(state->compression_buffer);
846 if ((r = sshbuf_consume(state->outgoing_packet, 8)) != 0)
849 if ((r = sshbuf_put(state->compression_buffer,
850 "\0\0\0\0\0\0\0\0", 8)) != 0)
852 if ((r = compress_buffer(ssh, state->outgoing_packet,
853 state->compression_buffer)) != 0)
855 sshbuf_reset(state->outgoing_packet);
856 if ((r = sshbuf_putb(state->outgoing_packet,
857 state->compression_buffer)) != 0)
860 /* Compute packet length without padding (add checksum, remove padding). */
861 len = sshbuf_len(state->outgoing_packet) + 4 - 8;
863 /* Insert padding. Initialized to zero in packet_start1() */
864 padding = 8 - len % 8;
865 if (!state->send_context.plaintext) {
866 cp = sshbuf_mutable_ptr(state->outgoing_packet);
868 r = SSH_ERR_INTERNAL_ERROR;
871 arc4random_buf(cp + 8 - padding, padding);
873 if ((r = sshbuf_consume(state->outgoing_packet, 8 - padding)) != 0)
876 /* Add check bytes. */
877 checksum = ssh_crc32(sshbuf_ptr(state->outgoing_packet),
878 sshbuf_len(state->outgoing_packet));
879 POKE_U32(buf, checksum);
880 if ((r = sshbuf_put(state->outgoing_packet, buf, 4)) != 0)
884 fprintf(stderr, "packet_send plain: ");
885 sshbuf_dump(state->outgoing_packet, stderr);
888 /* Append to output. */
890 if ((r = sshbuf_put(state->output, buf, 4)) != 0)
892 if ((r = sshbuf_reserve(state->output,
893 sshbuf_len(state->outgoing_packet), &cp)) != 0)
895 if ((r = cipher_crypt(&state->send_context, 0, cp,
896 sshbuf_ptr(state->outgoing_packet),
897 sshbuf_len(state->outgoing_packet), 0, 0)) != 0)
901 fprintf(stderr, "encrypted: ");
902 sshbuf_dump(state->output, stderr);
904 state->p_send.packets++;
905 state->p_send.bytes += len +
906 sshbuf_len(state->outgoing_packet);
907 sshbuf_reset(state->outgoing_packet);
910 * Note that the packet is now only buffered in output. It won't be
911 * actually sent until ssh_packet_write_wait or ssh_packet_write_poll
920 ssh_set_newkeys(struct ssh *ssh, int mode)
922 struct session_state *state = ssh->state;
925 struct sshcomp *comp;
926 struct sshcipher_ctx *cc;
927 u_int64_t *max_blocks;
931 debug2("set_newkeys: mode %d", mode);
933 if (mode == MODE_OUT) {
934 cc = &state->send_context;
935 crypt_type = CIPHER_ENCRYPT;
936 state->p_send.packets = state->p_send.blocks = 0;
937 max_blocks = &state->max_blocks_out;
939 cc = &state->receive_context;
940 crypt_type = CIPHER_DECRYPT;
941 state->p_read.packets = state->p_read.blocks = 0;
942 max_blocks = &state->max_blocks_in;
944 if (state->newkeys[mode] != NULL) {
945 debug("set_newkeys: rekeying");
946 if ((r = cipher_cleanup(cc)) != 0)
948 enc = &state->newkeys[mode]->enc;
949 mac = &state->newkeys[mode]->mac;
950 comp = &state->newkeys[mode]->comp;
952 explicit_bzero(enc->iv, enc->iv_len);
953 explicit_bzero(enc->key, enc->key_len);
954 explicit_bzero(mac->key, mac->key_len);
961 free(state->newkeys[mode]);
963 /* move newkeys from kex to state */
964 if ((state->newkeys[mode] = ssh->kex->newkeys[mode]) == NULL)
965 return SSH_ERR_INTERNAL_ERROR;
966 ssh->kex->newkeys[mode] = NULL;
967 enc = &state->newkeys[mode]->enc;
968 mac = &state->newkeys[mode]->mac;
969 comp = &state->newkeys[mode]->comp;
970 if (cipher_authlen(enc->cipher) == 0) {
971 if ((r = mac_init(mac)) != 0)
975 DBG(debug("cipher_init_context: %d", mode));
976 if ((r = cipher_init(cc, enc->cipher, enc->key, enc->key_len,
977 enc->iv, enc->iv_len, crypt_type)) != 0)
979 if (!state->cipher_warning_done &&
980 (wmsg = cipher_warning_message(cc)) != NULL) {
981 error("Warning: %s", wmsg);
982 state->cipher_warning_done = 1;
984 /* Deleting the keys does not gain extra security */
985 /* explicit_bzero(enc->iv, enc->block_size);
986 explicit_bzero(enc->key, enc->key_len);
987 explicit_bzero(mac->key, mac->key_len); */
988 if ((comp->type == COMP_ZLIB ||
989 (comp->type == COMP_DELAYED &&
990 state->after_authentication)) && comp->enabled == 0) {
991 if ((r = ssh_packet_init_compression(ssh)) < 0)
993 if (mode == MODE_OUT) {
994 if ((r = start_compression_out(ssh, 6)) != 0)
997 if ((r = start_compression_in(ssh)) != 0)
1003 * The 2^(blocksize*2) limit is too expensive for 3DES,
1004 * blowfish, etc, so enforce a 1GB limit for small blocksizes.
1006 if (enc->block_size >= 16)
1007 *max_blocks = (u_int64_t)1 << (enc->block_size*2);
1009 *max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
1010 if (state->rekey_limit)
1011 *max_blocks = MIN(*max_blocks,
1012 state->rekey_limit / enc->block_size);
1017 * Delayed compression for SSH2 is enabled after authentication:
1018 * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
1019 * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
1022 ssh_packet_enable_delayed_compress(struct ssh *ssh)
1024 struct session_state *state = ssh->state;
1025 struct sshcomp *comp = NULL;
1029 * Remember that we are past the authentication step, so rekeying
1030 * with COMP_DELAYED will turn on compression immediately.
1032 state->after_authentication = 1;
1033 for (mode = 0; mode < MODE_MAX; mode++) {
1034 /* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
1035 if (state->newkeys[mode] == NULL)
1037 comp = &state->newkeys[mode]->comp;
1038 if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
1039 if ((r = ssh_packet_init_compression(ssh)) != 0)
1041 if (mode == MODE_OUT) {
1042 if ((r = start_compression_out(ssh, 6)) != 0)
1045 if ((r = start_compression_in(ssh)) != 0)
1055 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
1058 ssh_packet_send2_wrapped(struct ssh *ssh)
1060 struct session_state *state = ssh->state;
1061 u_char type, *cp, macbuf[SSH_DIGEST_MAX_LENGTH];
1062 u_char padlen, pad = 0;
1063 u_int authlen = 0, aadlen = 0;
1065 struct sshenc *enc = NULL;
1066 struct sshmac *mac = NULL;
1067 struct sshcomp *comp = NULL;
1070 if (state->newkeys[MODE_OUT] != NULL) {
1071 enc = &state->newkeys[MODE_OUT]->enc;
1072 mac = &state->newkeys[MODE_OUT]->mac;
1073 comp = &state->newkeys[MODE_OUT]->comp;
1074 /* disable mac for authenticated encryption */
1075 if ((authlen = cipher_authlen(enc->cipher)) != 0)
1078 block_size = enc ? enc->block_size : 8;
1079 aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
1081 type = (sshbuf_ptr(state->outgoing_packet))[5];
1084 fprintf(stderr, "plain: ");
1085 sshbuf_dump(state->outgoing_packet, stderr);
1088 if (comp && comp->enabled) {
1089 len = sshbuf_len(state->outgoing_packet);
1090 /* skip header, compress only payload */
1091 if ((r = sshbuf_consume(state->outgoing_packet, 5)) != 0)
1093 sshbuf_reset(state->compression_buffer);
1094 if ((r = compress_buffer(ssh, state->outgoing_packet,
1095 state->compression_buffer)) != 0)
1097 sshbuf_reset(state->outgoing_packet);
1098 if ((r = sshbuf_put(state->outgoing_packet,
1099 "\0\0\0\0\0", 5)) != 0 ||
1100 (r = sshbuf_putb(state->outgoing_packet,
1101 state->compression_buffer)) != 0)
1103 DBG(debug("compression: raw %d compressed %zd", len,
1104 sshbuf_len(state->outgoing_packet)));
1107 /* sizeof (packet_len + pad_len + payload) */
1108 len = sshbuf_len(state->outgoing_packet);
1111 * calc size of padding, alloc space, get random data,
1112 * minimum padding is 4 bytes
1114 len -= aadlen; /* packet length is not encrypted for EtM modes */
1115 padlen = block_size - (len % block_size);
1117 padlen += block_size;
1118 if (state->extra_pad) {
1119 /* will wrap if extra_pad+padlen > 255 */
1121 roundup(state->extra_pad, block_size);
1122 pad = state->extra_pad -
1123 ((len + padlen) % state->extra_pad);
1124 DBG(debug3("%s: adding %d (len %d padlen %d extra_pad %d)",
1125 __func__, pad, len, padlen, state->extra_pad));
1127 state->extra_pad = 0;
1129 if ((r = sshbuf_reserve(state->outgoing_packet, padlen, &cp)) != 0)
1131 if (enc && !state->send_context.plaintext) {
1132 /* random padding */
1133 arc4random_buf(cp, padlen);
1136 explicit_bzero(cp, padlen);
1138 /* sizeof (packet_len + pad_len + payload + padding) */
1139 len = sshbuf_len(state->outgoing_packet);
1140 cp = sshbuf_mutable_ptr(state->outgoing_packet);
1142 r = SSH_ERR_INTERNAL_ERROR;
1145 /* packet_length includes payload, padding and padding length field */
1146 POKE_U32(cp, len - 4);
1148 DBG(debug("send: len %d (includes padlen %d, aadlen %d)",
1149 len, padlen, aadlen));
1151 /* compute MAC over seqnr and packet(length fields, payload, padding) */
1152 if (mac && mac->enabled && !mac->etm) {
1153 if ((r = mac_compute(mac, state->p_send.seqnr,
1154 sshbuf_ptr(state->outgoing_packet), len,
1155 macbuf, sizeof(macbuf))) != 0)
1157 DBG(debug("done calc MAC out #%d", state->p_send.seqnr));
1159 /* encrypt packet and append to output buffer. */
1160 if ((r = sshbuf_reserve(state->output,
1161 sshbuf_len(state->outgoing_packet) + authlen, &cp)) != 0)
1163 if ((r = cipher_crypt(&state->send_context, state->p_send.seqnr, cp,
1164 sshbuf_ptr(state->outgoing_packet),
1165 len - aadlen, aadlen, authlen)) != 0)
1167 /* append unencrypted MAC */
1168 if (mac && mac->enabled) {
1170 /* EtM: compute mac over aadlen + cipher text */
1171 if ((r = mac_compute(mac, state->p_send.seqnr,
1172 cp, len, macbuf, sizeof(macbuf))) != 0)
1174 DBG(debug("done calc MAC(EtM) out #%d",
1175 state->p_send.seqnr));
1177 if ((r = sshbuf_put(state->output, macbuf, mac->mac_len)) != 0)
1181 fprintf(stderr, "encrypted: ");
1182 sshbuf_dump(state->output, stderr);
1184 /* increment sequence number for outgoing packets */
1185 if (++state->p_send.seqnr == 0)
1186 logit("outgoing seqnr wraps around");
1187 if (++state->p_send.packets == 0)
1188 if (!(ssh->compat & SSH_BUG_NOREKEY))
1189 return SSH_ERR_NEED_REKEY;
1190 state->p_send.blocks += len / block_size;
1191 state->p_send.bytes += len;
1192 sshbuf_reset(state->outgoing_packet);
1194 if (type == SSH2_MSG_NEWKEYS)
1195 r = ssh_set_newkeys(ssh, MODE_OUT);
1196 else if (type == SSH2_MSG_USERAUTH_SUCCESS && state->server_side)
1197 r = ssh_packet_enable_delayed_compress(ssh);
1205 ssh_packet_send2(struct ssh *ssh)
1207 struct session_state *state = ssh->state;
1212 type = sshbuf_ptr(state->outgoing_packet)[5];
1214 /* during rekeying we can only send key exchange messages */
1215 if (state->rekeying) {
1216 if ((type < SSH2_MSG_TRANSPORT_MIN) ||
1217 (type > SSH2_MSG_TRANSPORT_MAX) ||
1218 (type == SSH2_MSG_SERVICE_REQUEST) ||
1219 (type == SSH2_MSG_SERVICE_ACCEPT)) {
1220 debug("enqueue packet: %u", type);
1221 p = calloc(1, sizeof(*p));
1223 return SSH_ERR_ALLOC_FAIL;
1225 p->payload = state->outgoing_packet;
1226 TAILQ_INSERT_TAIL(&state->outgoing, p, next);
1227 state->outgoing_packet = sshbuf_new();
1228 if (state->outgoing_packet == NULL)
1229 return SSH_ERR_ALLOC_FAIL;
1234 /* rekeying starts with sending KEXINIT */
1235 if (type == SSH2_MSG_KEXINIT)
1236 state->rekeying = 1;
1238 if ((r = ssh_packet_send2_wrapped(ssh)) != 0)
1241 /* after a NEWKEYS message we can send the complete queue */
1242 if (type == SSH2_MSG_NEWKEYS) {
1243 state->rekeying = 0;
1244 state->rekey_time = monotime();
1245 while ((p = TAILQ_FIRST(&state->outgoing))) {
1247 debug("dequeue packet: %u", type);
1248 sshbuf_free(state->outgoing_packet);
1249 state->outgoing_packet = p->payload;
1250 TAILQ_REMOVE(&state->outgoing, p, next);
1252 if ((r = ssh_packet_send2_wrapped(ssh)) != 0)
1260 * Waits until a packet has been received, and returns its type. Note that
1261 * no other data is processed until this returns, so this function should not
1262 * be used during the interactive session.
1266 ssh_packet_read_seqnr(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1268 struct session_state *state = ssh->state;
1269 int len, r, ms_remain, cont;
1272 struct timeval timeout, start, *timeoutp = NULL;
1274 DBG(debug("packet_read()"));
1276 setp = calloc(howmany(state->connection_in + 1,
1277 NFDBITS), sizeof(fd_mask));
1279 return SSH_ERR_ALLOC_FAIL;
1282 * Since we are blocking, ensure that all written packets have
1285 if ((r = ssh_packet_write_wait(ssh)) != 0)
1288 /* Stay in the loop until we have received a complete packet. */
1290 /* Try to read a packet from the buffer. */
1291 r = ssh_packet_read_poll_seqnr(ssh, typep, seqnr_p);
1295 *typep == SSH_SMSG_SUCCESS
1296 || *typep == SSH_SMSG_FAILURE
1297 || *typep == SSH_CMSG_EOF
1298 || *typep == SSH_CMSG_EXIT_CONFIRMATION))
1299 if ((r = sshpkt_get_end(ssh)) != 0)
1301 /* If we got a packet, return it. */
1302 if (*typep != SSH_MSG_NONE)
1305 * Otherwise, wait for some data to arrive, add it to the
1306 * buffer, and try again.
1308 memset(setp, 0, howmany(state->connection_in + 1,
1309 NFDBITS) * sizeof(fd_mask));
1310 FD_SET(state->connection_in, setp);
1312 if (state->packet_timeout_ms > 0) {
1313 ms_remain = state->packet_timeout_ms;
1314 timeoutp = &timeout;
1316 /* Wait for some data to arrive. */
1318 if (state->packet_timeout_ms != -1) {
1319 ms_to_timeval(&timeout, ms_remain);
1320 gettimeofday(&start, NULL);
1322 if ((r = select(state->connection_in + 1, setp,
1323 NULL, NULL, timeoutp)) >= 0)
1325 if (errno != EAGAIN && errno != EINTR &&
1326 errno != EWOULDBLOCK)
1328 if (state->packet_timeout_ms == -1)
1330 ms_subtract_diff(&start, &ms_remain);
1331 if (ms_remain <= 0) {
1337 return SSH_ERR_CONN_TIMEOUT;
1338 /* Read data from the socket. */
1341 len = roaming_read(state->connection_in, buf,
1342 sizeof(buf), &cont);
1343 } while (len == 0 && cont);
1345 r = SSH_ERR_CONN_CLOSED;
1349 r = SSH_ERR_SYSTEM_ERROR;
1353 /* Append it to the buffer. */
1354 if ((r = ssh_packet_process_incoming(ssh, buf, len)) != 0)
1363 ssh_packet_read(struct ssh *ssh)
1368 if ((r = ssh_packet_read_seqnr(ssh, &type, NULL)) != 0)
1369 fatal("%s: %s", __func__, ssh_err(r));
1374 * Waits until a packet has been received, verifies that its type matches
1375 * that given, and gives a fatal error and exits if there is a mismatch.
1379 ssh_packet_read_expect(struct ssh *ssh, u_int expected_type)
1384 if ((r = ssh_packet_read_seqnr(ssh, &type, NULL)) != 0)
1386 if (type != expected_type) {
1387 if ((r = sshpkt_disconnect(ssh,
1388 "Protocol error: expected packet type %d, got %d",
1389 expected_type, type)) != 0)
1391 return SSH_ERR_PROTOCOL_ERROR;
1396 /* Checks if a full packet is available in the data received so far via
1397 * packet_process_incoming. If so, reads the packet; otherwise returns
1398 * SSH_MSG_NONE. This does not wait for data from the connection.
1400 * SSH_MSG_DISCONNECT is handled specially here. Also,
1401 * SSH_MSG_IGNORE messages are skipped by this function and are never returned
1406 ssh_packet_read_poll1(struct ssh *ssh, u_char *typep)
1408 struct session_state *state = ssh->state;
1409 u_int len, padded_len;
1413 u_int checksum, stored_checksum;
1416 *typep = SSH_MSG_NONE;
1418 /* Check if input size is less than minimum packet size. */
1419 if (sshbuf_len(state->input) < 4 + 8)
1421 /* Get length of incoming packet. */
1422 len = PEEK_U32(sshbuf_ptr(state->input));
1423 if (len < 1 + 2 + 2 || len > 256 * 1024) {
1424 if ((r = sshpkt_disconnect(ssh, "Bad packet length %u",
1427 return SSH_ERR_CONN_CORRUPT;
1429 padded_len = (len + 8) & ~7;
1431 /* Check if the packet has been entirely received. */
1432 if (sshbuf_len(state->input) < 4 + padded_len)
1435 /* The entire packet is in buffer. */
1437 /* Consume packet length. */
1438 if ((r = sshbuf_consume(state->input, 4)) != 0)
1442 * Cryptographic attack detector for ssh
1443 * (C)1998 CORE-SDI, Buenos Aires Argentina
1444 * Ariel Futoransky(futo@core-sdi.com)
1446 if (!state->receive_context.plaintext) {
1448 switch (detect_attack(&state->deattack,
1449 sshbuf_ptr(state->input), padded_len)) {
1452 case DEATTACK_DETECTED:
1453 emsg = "crc32 compensation attack detected";
1455 case DEATTACK_DOS_DETECTED:
1456 emsg = "deattack denial of service detected";
1459 emsg = "deattack error";
1464 if ((r = sshpkt_disconnect(ssh, "%s", emsg)) != 0 ||
1465 (r = ssh_packet_write_wait(ssh)) != 0)
1467 return SSH_ERR_CONN_CORRUPT;
1471 /* Decrypt data to incoming_packet. */
1472 sshbuf_reset(state->incoming_packet);
1473 if ((r = sshbuf_reserve(state->incoming_packet, padded_len, &p)) != 0)
1475 if ((r = cipher_crypt(&state->receive_context, 0, p,
1476 sshbuf_ptr(state->input), padded_len, 0, 0)) != 0)
1479 if ((r = sshbuf_consume(state->input, padded_len)) != 0)
1483 fprintf(stderr, "read_poll plain: ");
1484 sshbuf_dump(state->incoming_packet, stderr);
1487 /* Compute packet checksum. */
1488 checksum = ssh_crc32(sshbuf_ptr(state->incoming_packet),
1489 sshbuf_len(state->incoming_packet) - 4);
1492 if ((r = sshbuf_consume(state->incoming_packet, 8 - len % 8)) != 0)
1495 /* Test check bytes. */
1496 if (len != sshbuf_len(state->incoming_packet)) {
1497 error("%s: len %d != sshbuf_len %zd", __func__,
1498 len, sshbuf_len(state->incoming_packet));
1499 if ((r = sshpkt_disconnect(ssh, "invalid packet length")) != 0 ||
1500 (r = ssh_packet_write_wait(ssh)) != 0)
1502 return SSH_ERR_CONN_CORRUPT;
1505 cp = sshbuf_ptr(state->incoming_packet) + len - 4;
1506 stored_checksum = PEEK_U32(cp);
1507 if (checksum != stored_checksum) {
1508 error("Corrupted check bytes on input");
1509 if ((r = sshpkt_disconnect(ssh, "connection corrupted")) != 0 ||
1510 (r = ssh_packet_write_wait(ssh)) != 0)
1512 return SSH_ERR_CONN_CORRUPT;
1514 if ((r = sshbuf_consume_end(state->incoming_packet, 4)) < 0)
1517 if (state->packet_compression) {
1518 sshbuf_reset(state->compression_buffer);
1519 if ((r = uncompress_buffer(ssh, state->incoming_packet,
1520 state->compression_buffer)) != 0)
1522 sshbuf_reset(state->incoming_packet);
1523 if ((r = sshbuf_putb(state->incoming_packet,
1524 state->compression_buffer)) != 0)
1527 state->p_read.packets++;
1528 state->p_read.bytes += padded_len + 4;
1529 if ((r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
1531 if (*typep < SSH_MSG_MIN || *typep > SSH_MSG_MAX) {
1532 error("Invalid ssh1 packet type: %d", *typep);
1533 if ((r = sshpkt_disconnect(ssh, "invalid packet type")) != 0 ||
1534 (r = ssh_packet_write_wait(ssh)) != 0)
1536 return SSH_ERR_PROTOCOL_ERROR;
1544 ssh_packet_read_poll2(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1546 struct session_state *state = ssh->state;
1548 u_char *cp, macbuf[SSH_DIGEST_MAX_LENGTH];
1549 u_int maclen, aadlen = 0, authlen = 0, block_size;
1550 struct sshenc *enc = NULL;
1551 struct sshmac *mac = NULL;
1552 struct sshcomp *comp = NULL;
1555 *typep = SSH_MSG_NONE;
1557 if (state->packet_discard)
1560 if (state->newkeys[MODE_IN] != NULL) {
1561 enc = &state->newkeys[MODE_IN]->enc;
1562 mac = &state->newkeys[MODE_IN]->mac;
1563 comp = &state->newkeys[MODE_IN]->comp;
1564 /* disable mac for authenticated encryption */
1565 if ((authlen = cipher_authlen(enc->cipher)) != 0)
1568 maclen = mac && mac->enabled ? mac->mac_len : 0;
1569 block_size = enc ? enc->block_size : 8;
1570 aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
1572 if (aadlen && state->packlen == 0) {
1573 if (cipher_get_length(&state->receive_context,
1574 &state->packlen, state->p_read.seqnr,
1575 sshbuf_ptr(state->input), sshbuf_len(state->input)) != 0)
1577 if (state->packlen < 1 + 4 ||
1578 state->packlen > PACKET_MAX_SIZE) {
1580 sshbuf_dump(state->input, stderr);
1582 logit("Bad packet length %u.", state->packlen);
1583 if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0)
1585 return SSH_ERR_CONN_CORRUPT;
1587 sshbuf_reset(state->incoming_packet);
1588 } else if (state->packlen == 0) {
1590 * check if input size is less than the cipher block size,
1591 * decrypt first block and extract length of incoming packet
1593 if (sshbuf_len(state->input) < block_size)
1595 sshbuf_reset(state->incoming_packet);
1596 if ((r = sshbuf_reserve(state->incoming_packet, block_size,
1599 if ((r = cipher_crypt(&state->receive_context,
1600 state->p_send.seqnr, cp, sshbuf_ptr(state->input),
1601 block_size, 0, 0)) != 0)
1603 state->packlen = PEEK_U32(sshbuf_ptr(state->incoming_packet));
1604 if (state->packlen < 1 + 4 ||
1605 state->packlen > PACKET_MAX_SIZE) {
1607 fprintf(stderr, "input: \n");
1608 sshbuf_dump(state->input, stderr);
1609 fprintf(stderr, "incoming_packet: \n");
1610 sshbuf_dump(state->incoming_packet, stderr);
1612 logit("Bad packet length %u.", state->packlen);
1613 return ssh_packet_start_discard(ssh, enc, mac,
1614 state->packlen, PACKET_MAX_SIZE);
1616 if ((r = sshbuf_consume(state->input, block_size)) != 0)
1619 DBG(debug("input: packet len %u", state->packlen+4));
1622 /* only the payload is encrypted */
1623 need = state->packlen;
1626 * the payload size and the payload are encrypted, but we
1627 * have a partial packet of block_size bytes
1629 need = 4 + state->packlen - block_size;
1631 DBG(debug("partial packet: block %d, need %d, maclen %d, authlen %d,"
1632 " aadlen %d", block_size, need, maclen, authlen, aadlen));
1633 if (need % block_size != 0) {
1634 logit("padding error: need %d block %d mod %d",
1635 need, block_size, need % block_size);
1636 return ssh_packet_start_discard(ssh, enc, mac,
1637 state->packlen, PACKET_MAX_SIZE - block_size);
1640 * check if the entire packet has been received and
1641 * decrypt into incoming_packet:
1642 * 'aadlen' bytes are unencrypted, but authenticated.
1643 * 'need' bytes are encrypted, followed by either
1644 * 'authlen' bytes of authentication tag or
1645 * 'maclen' bytes of message authentication code.
1647 if (sshbuf_len(state->input) < aadlen + need + authlen + maclen)
1650 fprintf(stderr, "read_poll enc/full: ");
1651 sshbuf_dump(state->input, stderr);
1653 /* EtM: compute mac over encrypted input */
1654 if (mac && mac->enabled && mac->etm) {
1655 if ((r = mac_compute(mac, state->p_read.seqnr,
1656 sshbuf_ptr(state->input), aadlen + need,
1657 macbuf, sizeof(macbuf))) != 0)
1660 if ((r = sshbuf_reserve(state->incoming_packet, aadlen + need,
1663 if ((r = cipher_crypt(&state->receive_context, state->p_read.seqnr, cp,
1664 sshbuf_ptr(state->input), need, aadlen, authlen)) != 0)
1666 if ((r = sshbuf_consume(state->input, aadlen + need + authlen)) != 0)
1669 * compute MAC over seqnr and packet,
1670 * increment sequence number for incoming packet
1672 if (mac && mac->enabled) {
1674 if ((r = mac_compute(mac, state->p_read.seqnr,
1675 sshbuf_ptr(state->incoming_packet),
1676 sshbuf_len(state->incoming_packet),
1677 macbuf, sizeof(macbuf))) != 0)
1679 if (timingsafe_bcmp(macbuf, sshbuf_ptr(state->input),
1680 mac->mac_len) != 0) {
1681 logit("Corrupted MAC on input.");
1682 if (need > PACKET_MAX_SIZE)
1683 return SSH_ERR_INTERNAL_ERROR;
1684 return ssh_packet_start_discard(ssh, enc, mac,
1685 state->packlen, PACKET_MAX_SIZE - need);
1688 DBG(debug("MAC #%d ok", state->p_read.seqnr));
1689 if ((r = sshbuf_consume(state->input, mac->mac_len)) != 0)
1692 if (seqnr_p != NULL)
1693 *seqnr_p = state->p_read.seqnr;
1694 if (++state->p_read.seqnr == 0)
1695 logit("incoming seqnr wraps around");
1696 if (++state->p_read.packets == 0)
1697 if (!(ssh->compat & SSH_BUG_NOREKEY))
1698 return SSH_ERR_NEED_REKEY;
1699 state->p_read.blocks += (state->packlen + 4) / block_size;
1700 state->p_read.bytes += state->packlen + 4;
1703 padlen = sshbuf_ptr(state->incoming_packet)[4];
1704 DBG(debug("input: padlen %d", padlen));
1706 if ((r = sshpkt_disconnect(ssh,
1707 "Corrupted padlen %d on input.", padlen)) != 0 ||
1708 (r = ssh_packet_write_wait(ssh)) != 0)
1710 return SSH_ERR_CONN_CORRUPT;
1713 /* skip packet size + padlen, discard padding */
1714 if ((r = sshbuf_consume(state->incoming_packet, 4 + 1)) != 0 ||
1715 ((r = sshbuf_consume_end(state->incoming_packet, padlen)) != 0))
1718 DBG(debug("input: len before de-compress %zd",
1719 sshbuf_len(state->incoming_packet)));
1720 if (comp && comp->enabled) {
1721 sshbuf_reset(state->compression_buffer);
1722 if ((r = uncompress_buffer(ssh, state->incoming_packet,
1723 state->compression_buffer)) != 0)
1725 sshbuf_reset(state->incoming_packet);
1726 if ((r = sshbuf_putb(state->incoming_packet,
1727 state->compression_buffer)) != 0)
1729 DBG(debug("input: len after de-compress %zd",
1730 sshbuf_len(state->incoming_packet)));
1733 * get packet type, implies consume.
1734 * return length of payload (without type field)
1736 if ((r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
1738 if (*typep < SSH2_MSG_MIN || *typep >= SSH2_MSG_LOCAL_MIN) {
1739 if ((r = sshpkt_disconnect(ssh,
1740 "Invalid ssh2 packet type: %d", *typep)) != 0 ||
1741 (r = ssh_packet_write_wait(ssh)) != 0)
1743 return SSH_ERR_PROTOCOL_ERROR;
1745 if (*typep == SSH2_MSG_NEWKEYS)
1746 r = ssh_set_newkeys(ssh, MODE_IN);
1747 else if (*typep == SSH2_MSG_USERAUTH_SUCCESS && !state->server_side)
1748 r = ssh_packet_enable_delayed_compress(ssh);
1752 fprintf(stderr, "read/plain[%d]:\r\n", *typep);
1753 sshbuf_dump(state->incoming_packet, stderr);
1755 /* reset for next packet */
1762 ssh_packet_read_poll_seqnr(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1764 struct session_state *state = ssh->state;
1765 u_int reason, seqnr;
1772 r = ssh_packet_read_poll2(ssh, typep, seqnr_p);
1776 state->keep_alive_timeouts = 0;
1777 DBG(debug("received packet type %d", *typep));
1780 case SSH2_MSG_IGNORE:
1781 debug3("Received SSH2_MSG_IGNORE");
1783 case SSH2_MSG_DEBUG:
1784 if ((r = sshpkt_get_u8(ssh, NULL)) != 0 ||
1785 (r = sshpkt_get_string(ssh, &msg, NULL)) != 0 ||
1786 (r = sshpkt_get_string(ssh, NULL, NULL)) != 0) {
1791 debug("Remote: %.900s", msg);
1794 case SSH2_MSG_DISCONNECT:
1795 if ((r = sshpkt_get_u32(ssh, &reason)) != 0 ||
1796 (r = sshpkt_get_string(ssh, &msg, NULL)) != 0)
1798 /* Ignore normal client exit notifications */
1799 do_log2(ssh->state->server_side &&
1800 reason == SSH2_DISCONNECT_BY_APPLICATION ?
1801 SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_ERROR,
1802 "Received disconnect from %s: %u: %.400s",
1803 ssh_remote_ipaddr(ssh), reason, msg);
1805 return SSH_ERR_DISCONNECTED;
1806 case SSH2_MSG_UNIMPLEMENTED:
1807 if ((r = sshpkt_get_u32(ssh, &seqnr)) != 0)
1809 debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1816 r = ssh_packet_read_poll1(ssh, typep);
1819 return SSH_MSG_NONE;
1820 case SSH_MSG_IGNORE:
1823 if ((r = sshpkt_get_string(ssh, &msg, NULL)) != 0)
1825 debug("Remote: %.900s", msg);
1828 case SSH_MSG_DISCONNECT:
1829 if ((r = sshpkt_get_string(ssh, &msg, NULL)) != 0)
1831 logit("Received disconnect from %s: %.400s",
1832 ssh_remote_ipaddr(ssh), msg);
1834 return SSH_ERR_DISCONNECTED;
1836 DBG(debug("received packet type %d", *typep));
1844 * Buffers the given amount of input characters. This is intended to be used
1845 * together with packet_read_poll.
1849 ssh_packet_process_incoming(struct ssh *ssh, const char *buf, u_int len)
1851 struct session_state *state = ssh->state;
1854 if (state->packet_discard) {
1855 state->keep_alive_timeouts = 0; /* ?? */
1856 if (len >= state->packet_discard) {
1857 if ((r = ssh_packet_stop_discard(ssh)) != 0)
1860 state->packet_discard -= len;
1863 if ((r = sshbuf_put(ssh->state->input, buf, len)) != 0)
1870 ssh_packet_remaining(struct ssh *ssh)
1872 return sshbuf_len(ssh->state->incoming_packet);
1876 * Sends a diagnostic message from the server to the client. This message
1877 * can be sent at any time (but not while constructing another message). The
1878 * message is printed immediately, but only if the client is being executed
1879 * in verbose mode. These messages are primarily intended to ease debugging
1880 * authentication problems. The length of the formatted message must not
1881 * exceed 1024 bytes. This will automatically call ssh_packet_write_wait.
1884 ssh_packet_send_debug(struct ssh *ssh, const char *fmt,...)
1890 if (compat20 && (ssh->compat & SSH_BUG_DEBUG))
1893 va_start(args, fmt);
1894 vsnprintf(buf, sizeof(buf), fmt, args);
1898 if ((r = sshpkt_start(ssh, SSH2_MSG_DEBUG)) != 0 ||
1899 (r = sshpkt_put_u8(ssh, 0)) != 0 || /* always display */
1900 (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
1901 (r = sshpkt_put_cstring(ssh, "")) != 0 ||
1902 (r = sshpkt_send(ssh)) != 0)
1903 fatal("%s: %s", __func__, ssh_err(r));
1905 if ((r = sshpkt_start(ssh, SSH_MSG_DEBUG)) != 0 ||
1906 (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
1907 (r = sshpkt_send(ssh)) != 0)
1908 fatal("%s: %s", __func__, ssh_err(r));
1910 if ((r = ssh_packet_write_wait(ssh)) != 0)
1911 fatal("%s: %s", __func__, ssh_err(r));
1915 * Pretty-print connection-terminating errors and exit.
1918 sshpkt_fatal(struct ssh *ssh, const char *tag, int r)
1921 case SSH_ERR_CONN_CLOSED:
1922 logit("Connection closed by %.200s", ssh_remote_ipaddr(ssh));
1924 case SSH_ERR_CONN_TIMEOUT:
1925 logit("Connection to %.200s timed out", ssh_remote_ipaddr(ssh));
1927 case SSH_ERR_DISCONNECTED:
1928 logit("Disconnected from %.200s",
1929 ssh_remote_ipaddr(ssh));
1931 case SSH_ERR_SYSTEM_ERROR:
1932 if (errno == ECONNRESET) {
1933 logit("Connection reset by %.200s",
1934 ssh_remote_ipaddr(ssh));
1938 case SSH_ERR_NO_CIPHER_ALG_MATCH:
1939 case SSH_ERR_NO_MAC_ALG_MATCH:
1940 case SSH_ERR_NO_COMPRESS_ALG_MATCH:
1941 case SSH_ERR_NO_KEX_ALG_MATCH:
1942 case SSH_ERR_NO_HOSTKEY_ALG_MATCH:
1943 if (ssh && ssh->kex && ssh->kex->failed_choice) {
1944 fatal("Unable to negotiate with %.200s: %s. "
1945 "Their offer: %s", ssh_remote_ipaddr(ssh),
1946 ssh_err(r), ssh->kex->failed_choice);
1950 fatal("%s%sConnection to %.200s: %s",
1951 tag != NULL ? tag : "", tag != NULL ? ": " : "",
1952 ssh_remote_ipaddr(ssh), ssh_err(r));
1957 * Logs the error plus constructs and sends a disconnect packet, closes the
1958 * connection, and exits. This function never returns. The error message
1959 * should not contain a newline. The length of the formatted message must
1960 * not exceed 1024 bytes.
1963 ssh_packet_disconnect(struct ssh *ssh, const char *fmt,...)
1967 static int disconnecting = 0;
1970 if (disconnecting) /* Guard against recursive invocations. */
1971 fatal("packet_disconnect called recursively.");
1975 * Format the message. Note that the caller must make sure the
1976 * message is of limited size.
1978 va_start(args, fmt);
1979 vsnprintf(buf, sizeof(buf), fmt, args);
1982 /* Display the error locally */
1983 logit("Disconnecting: %.100s", buf);
1986 * Send the disconnect message to the other side, and wait
1987 * for it to get sent.
1989 if ((r = sshpkt_disconnect(ssh, "%s", buf)) != 0)
1990 sshpkt_fatal(ssh, __func__, r);
1992 if ((r = ssh_packet_write_wait(ssh)) != 0)
1993 sshpkt_fatal(ssh, __func__, r);
1995 /* Close the connection. */
1996 ssh_packet_close(ssh);
2001 * Checks if there is any buffered output, and tries to write some of
2005 ssh_packet_write_poll(struct ssh *ssh)
2007 struct session_state *state = ssh->state;
2008 int len = sshbuf_len(state->output);
2013 len = roaming_write(state->connection_out,
2014 sshbuf_ptr(state->output), len, &cont);
2016 if (errno == EINTR || errno == EAGAIN ||
2017 errno == EWOULDBLOCK)
2019 return SSH_ERR_SYSTEM_ERROR;
2021 if (len == 0 && !cont)
2022 return SSH_ERR_CONN_CLOSED;
2023 if ((r = sshbuf_consume(state->output, len)) != 0)
2030 * Calls packet_write_poll repeatedly until all pending output data has been
2034 ssh_packet_write_wait(struct ssh *ssh)
2037 int ret, r, ms_remain = 0;
2038 struct timeval start, timeout, *timeoutp = NULL;
2039 struct session_state *state = ssh->state;
2041 setp = calloc(howmany(state->connection_out + 1,
2042 NFDBITS), sizeof(fd_mask));
2044 return SSH_ERR_ALLOC_FAIL;
2045 ssh_packet_write_poll(ssh);
2046 while (ssh_packet_have_data_to_write(ssh)) {
2047 memset(setp, 0, howmany(state->connection_out + 1,
2048 NFDBITS) * sizeof(fd_mask));
2049 FD_SET(state->connection_out, setp);
2051 if (state->packet_timeout_ms > 0) {
2052 ms_remain = state->packet_timeout_ms;
2053 timeoutp = &timeout;
2056 if (state->packet_timeout_ms != -1) {
2057 ms_to_timeval(&timeout, ms_remain);
2058 gettimeofday(&start, NULL);
2060 if ((ret = select(state->connection_out + 1,
2061 NULL, setp, NULL, timeoutp)) >= 0)
2063 if (errno != EAGAIN && errno != EINTR &&
2064 errno != EWOULDBLOCK)
2066 if (state->packet_timeout_ms == -1)
2068 ms_subtract_diff(&start, &ms_remain);
2069 if (ms_remain <= 0) {
2076 return SSH_ERR_CONN_TIMEOUT;
2078 if ((r = ssh_packet_write_poll(ssh)) != 0) {
2087 /* Returns true if there is buffered data to write to the connection. */
2090 ssh_packet_have_data_to_write(struct ssh *ssh)
2092 return sshbuf_len(ssh->state->output) != 0;
2095 /* Returns true if there is not too much data to write to the connection. */
2098 ssh_packet_not_very_much_data_to_write(struct ssh *ssh)
2100 if (ssh->state->interactive_mode)
2101 return sshbuf_len(ssh->state->output) < 16384;
2103 return sshbuf_len(ssh->state->output) < 128 * 1024;
2107 ssh_packet_set_tos(struct ssh *ssh, int tos)
2109 #ifndef IP_TOS_IS_BROKEN
2110 if (!ssh_packet_connection_is_on_socket(ssh))
2112 switch (ssh_packet_connection_af(ssh)) {
2115 debug3("%s: set IP_TOS 0x%02x", __func__, tos);
2116 if (setsockopt(ssh->state->connection_in,
2117 IPPROTO_IP, IP_TOS, &tos, sizeof(tos)) < 0)
2118 error("setsockopt IP_TOS %d: %.100s:",
2119 tos, strerror(errno));
2121 # endif /* IP_TOS */
2124 debug3("%s: set IPV6_TCLASS 0x%02x", __func__, tos);
2125 if (setsockopt(ssh->state->connection_in,
2126 IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof(tos)) < 0)
2127 error("setsockopt IPV6_TCLASS %d: %.100s:",
2128 tos, strerror(errno));
2130 # endif /* IPV6_TCLASS */
2132 #endif /* IP_TOS_IS_BROKEN */
2135 /* Informs that the current session is interactive. Sets IP flags for that. */
2138 ssh_packet_set_interactive(struct ssh *ssh, int interactive, int qos_interactive, int qos_bulk)
2140 struct session_state *state = ssh->state;
2142 if (state->set_interactive_called)
2144 state->set_interactive_called = 1;
2146 /* Record that we are in interactive mode. */
2147 state->interactive_mode = interactive;
2149 /* Only set socket options if using a socket. */
2150 if (!ssh_packet_connection_is_on_socket(ssh))
2152 set_nodelay(state->connection_in);
2153 ssh_packet_set_tos(ssh, interactive ? qos_interactive :
2157 /* Returns true if the current connection is interactive. */
2160 ssh_packet_is_interactive(struct ssh *ssh)
2162 return ssh->state->interactive_mode;
2166 ssh_packet_set_maxsize(struct ssh *ssh, u_int s)
2168 struct session_state *state = ssh->state;
2170 if (state->set_maxsize_called) {
2171 logit("packet_set_maxsize: called twice: old %d new %d",
2172 state->max_packet_size, s);
2175 if (s < 4 * 1024 || s > 1024 * 1024) {
2176 logit("packet_set_maxsize: bad size %d", s);
2179 state->set_maxsize_called = 1;
2180 debug("packet_set_maxsize: setting to %d", s);
2181 state->max_packet_size = s;
2186 ssh_packet_inc_alive_timeouts(struct ssh *ssh)
2188 return ++ssh->state->keep_alive_timeouts;
2192 ssh_packet_set_alive_timeouts(struct ssh *ssh, int ka)
2194 ssh->state->keep_alive_timeouts = ka;
2198 ssh_packet_get_maxsize(struct ssh *ssh)
2200 return ssh->state->max_packet_size;
2204 * 9.2. Ignored Data Message
2206 * byte SSH_MSG_IGNORE
2209 * All implementations MUST understand (and ignore) this message at any
2210 * time (after receiving the protocol version). No implementation is
2211 * required to send them. This message can be used as an additional
2212 * protection measure against advanced traffic analysis techniques.
2215 ssh_packet_send_ignore(struct ssh *ssh, int nbytes)
2220 if ((r = sshpkt_start(ssh, compat20 ?
2221 SSH2_MSG_IGNORE : SSH_MSG_IGNORE)) != 0 ||
2222 (r = sshpkt_put_u32(ssh, nbytes)) != 0)
2223 fatal("%s: %s", __func__, ssh_err(r));
2224 for (i = 0; i < nbytes; i++) {
2227 if ((r = sshpkt_put_u8(ssh, (u_char)rnd & 0xff)) != 0)
2228 fatal("%s: %s", __func__, ssh_err(r));
2233 #define MAX_PACKETS (1U<<31)
2235 ssh_packet_need_rekeying(struct ssh *ssh)
2237 struct session_state *state = ssh->state;
2239 if (ssh->compat & SSH_BUG_NOREKEY)
2242 (state->p_send.packets > MAX_PACKETS) ||
2243 (state->p_read.packets > MAX_PACKETS) ||
2244 (state->max_blocks_out &&
2245 (state->p_send.blocks > state->max_blocks_out)) ||
2246 (state->max_blocks_in &&
2247 (state->p_read.blocks > state->max_blocks_in)) ||
2248 (state->rekey_interval != 0 && state->rekey_time +
2249 state->rekey_interval <= monotime());
2253 ssh_packet_set_rekey_limits(struct ssh *ssh, u_int32_t bytes, time_t seconds)
2255 debug3("rekey after %lld bytes, %d seconds", (long long)bytes,
2257 ssh->state->rekey_limit = bytes;
2258 ssh->state->rekey_interval = seconds;
2262 ssh_packet_get_rekey_timeout(struct ssh *ssh)
2266 seconds = ssh->state->rekey_time + ssh->state->rekey_interval -
2268 return (seconds <= 0 ? 1 : seconds);
2272 ssh_packet_set_server(struct ssh *ssh)
2274 ssh->state->server_side = 1;
2278 ssh_packet_set_authenticated(struct ssh *ssh)
2280 ssh->state->after_authentication = 1;
2284 ssh_packet_get_input(struct ssh *ssh)
2286 return (void *)ssh->state->input;
2290 ssh_packet_get_output(struct ssh *ssh)
2292 return (void *)ssh->state->output;
2295 /* XXX TODO update roaming to new API (does not work anyway) */
2297 * Save the state for the real connection, and use a separate state when
2298 * resuming a suspended connection.
2301 ssh_packet_backup_state(struct ssh *ssh,
2302 struct ssh *backup_state)
2306 close(ssh->state->connection_in);
2307 ssh->state->connection_in = -1;
2308 close(ssh->state->connection_out);
2309 ssh->state->connection_out = -1;
2313 tmp = ssh_alloc_session_state();
2318 /* XXX FIXME FIXME FIXME */
2320 * Swap in the old state when resuming a connecion.
2323 ssh_packet_restore_state(struct ssh *ssh,
2324 struct ssh *backup_state)
2333 ssh->state->connection_in = backup_state->state->connection_in;
2334 backup_state->state->connection_in = -1;
2335 ssh->state->connection_out = backup_state->state->connection_out;
2336 backup_state->state->connection_out = -1;
2337 len = sshbuf_len(backup_state->state->input);
2339 if ((r = sshbuf_putb(ssh->state->input,
2340 backup_state->state->input)) != 0)
2341 fatal("%s: %s", __func__, ssh_err(r));
2342 sshbuf_reset(backup_state->state->input);
2343 add_recv_bytes(len);
2347 /* Reset after_authentication and reset compression in post-auth privsep */
2349 ssh_packet_set_postauth(struct ssh *ssh)
2351 struct sshcomp *comp;
2354 debug("%s: called", __func__);
2355 /* This was set in net child, but is not visible in user child */
2356 ssh->state->after_authentication = 1;
2357 ssh->state->rekeying = 0;
2358 for (mode = 0; mode < MODE_MAX; mode++) {
2359 if (ssh->state->newkeys[mode] == NULL)
2361 comp = &ssh->state->newkeys[mode]->comp;
2362 if (comp && comp->enabled &&
2363 (r = ssh_packet_init_compression(ssh)) != 0)
2369 /* Packet state (de-)serialization for privsep */
2371 /* turn kex into a blob for packet state serialization */
2373 kex_to_blob(struct sshbuf *m, struct kex *kex)
2377 if ((r = sshbuf_put_string(m, kex->session_id,
2378 kex->session_id_len)) != 0 ||
2379 (r = sshbuf_put_u32(m, kex->we_need)) != 0 ||
2380 (r = sshbuf_put_u32(m, kex->hostkey_type)) != 0 ||
2381 (r = sshbuf_put_u32(m, kex->kex_type)) != 0 ||
2382 (r = sshbuf_put_stringb(m, kex->my)) != 0 ||
2383 (r = sshbuf_put_stringb(m, kex->peer)) != 0 ||
2384 (r = sshbuf_put_u32(m, kex->flags)) != 0 ||
2385 (r = sshbuf_put_cstring(m, kex->client_version_string)) != 0 ||
2386 (r = sshbuf_put_cstring(m, kex->server_version_string)) != 0)
2391 /* turn key exchange results into a blob for packet state serialization */
2393 newkeys_to_blob(struct sshbuf *m, struct ssh *ssh, int mode)
2396 struct sshcipher_ctx *cc;
2397 struct sshcomp *comp;
2400 struct newkeys *newkey;
2403 if ((newkey = ssh->state->newkeys[mode]) == NULL)
2404 return SSH_ERR_INTERNAL_ERROR;
2407 comp = &newkey->comp;
2408 cc = (mode == MODE_OUT) ? &ssh->state->send_context :
2409 &ssh->state->receive_context;
2410 if ((r = cipher_get_keyiv(cc, enc->iv, enc->iv_len)) != 0)
2412 if ((b = sshbuf_new()) == NULL)
2413 return SSH_ERR_ALLOC_FAIL;
2414 /* The cipher struct is constant and shared, you export pointer */
2415 if ((r = sshbuf_put_cstring(b, enc->name)) != 0 ||
2416 (r = sshbuf_put(b, &enc->cipher, sizeof(enc->cipher))) != 0 ||
2417 (r = sshbuf_put_u32(b, enc->enabled)) != 0 ||
2418 (r = sshbuf_put_u32(b, enc->block_size)) != 0 ||
2419 (r = sshbuf_put_string(b, enc->key, enc->key_len)) != 0 ||
2420 (r = sshbuf_put_string(b, enc->iv, enc->iv_len)) != 0)
2422 if (cipher_authlen(enc->cipher) == 0) {
2423 if ((r = sshbuf_put_cstring(b, mac->name)) != 0 ||
2424 (r = sshbuf_put_u32(b, mac->enabled)) != 0 ||
2425 (r = sshbuf_put_string(b, mac->key, mac->key_len)) != 0)
2428 if ((r = sshbuf_put_u32(b, comp->type)) != 0 ||
2429 (r = sshbuf_put_u32(b, comp->enabled)) != 0 ||
2430 (r = sshbuf_put_cstring(b, comp->name)) != 0)
2432 r = sshbuf_put_stringb(m, b);
2439 /* serialize packet state into a blob */
2441 ssh_packet_get_state(struct ssh *ssh, struct sshbuf *m)
2443 struct session_state *state = ssh->state;
2449 ssh1cipher = cipher_get_number(state->receive_context.cipher);
2450 slen = cipher_get_keyiv_len(&state->send_context);
2451 rlen = cipher_get_keyiv_len(&state->receive_context);
2452 if ((r = sshbuf_put_u32(m, state->remote_protocol_flags)) != 0 ||
2453 (r = sshbuf_put_u32(m, ssh1cipher)) != 0 ||
2454 (r = sshbuf_put_string(m, state->ssh1_key, state->ssh1_keylen)) != 0 ||
2455 (r = sshbuf_put_u32(m, slen)) != 0 ||
2456 (r = sshbuf_reserve(m, slen, &p)) != 0 ||
2457 (r = cipher_get_keyiv(&state->send_context, p, slen)) != 0 ||
2458 (r = sshbuf_put_u32(m, rlen)) != 0 ||
2459 (r = sshbuf_reserve(m, rlen, &p)) != 0 ||
2460 (r = cipher_get_keyiv(&state->receive_context, p, rlen)) != 0)
2463 if ((r = kex_to_blob(m, ssh->kex)) != 0 ||
2464 (r = newkeys_to_blob(m, ssh, MODE_OUT)) != 0 ||
2465 (r = newkeys_to_blob(m, ssh, MODE_IN)) != 0 ||
2466 (r = sshbuf_put_u32(m, state->rekey_limit)) != 0 ||
2467 (r = sshbuf_put_u32(m, state->rekey_interval)) != 0 ||
2468 (r = sshbuf_put_u32(m, state->p_send.seqnr)) != 0 ||
2469 (r = sshbuf_put_u64(m, state->p_send.blocks)) != 0 ||
2470 (r = sshbuf_put_u32(m, state->p_send.packets)) != 0 ||
2471 (r = sshbuf_put_u64(m, state->p_send.bytes)) != 0 ||
2472 (r = sshbuf_put_u32(m, state->p_read.seqnr)) != 0 ||
2473 (r = sshbuf_put_u64(m, state->p_read.blocks)) != 0 ||
2474 (r = sshbuf_put_u32(m, state->p_read.packets)) != 0 ||
2475 (r = sshbuf_put_u64(m, state->p_read.bytes)) != 0)
2479 slen = cipher_get_keycontext(&state->send_context, NULL);
2480 rlen = cipher_get_keycontext(&state->receive_context, NULL);
2481 if ((r = sshbuf_put_u32(m, slen)) != 0 ||
2482 (r = sshbuf_reserve(m, slen, &p)) != 0)
2484 if (cipher_get_keycontext(&state->send_context, p) != (int)slen)
2485 return SSH_ERR_INTERNAL_ERROR;
2486 if ((r = sshbuf_put_u32(m, rlen)) != 0 ||
2487 (r = sshbuf_reserve(m, rlen, &p)) != 0)
2489 if (cipher_get_keycontext(&state->receive_context, p) != (int)rlen)
2490 return SSH_ERR_INTERNAL_ERROR;
2492 if ((r = ssh_packet_get_compress_state(m, ssh)) != 0 ||
2493 (r = sshbuf_put_stringb(m, state->input)) != 0 ||
2494 (r = sshbuf_put_stringb(m, state->output)) != 0)
2498 if ((r = sshbuf_put_u64(m, get_sent_bytes())) != 0 ||
2499 (r = sshbuf_put_u64(m, get_recv_bytes())) != 0)
2505 /* restore key exchange results from blob for packet state de-serialization */
2507 newkeys_from_blob(struct sshbuf *m, struct ssh *ssh, int mode)
2509 struct sshbuf *b = NULL;
2510 struct sshcomp *comp;
2513 struct newkeys *newkey = NULL;
2514 size_t keylen, ivlen, maclen;
2517 if ((newkey = calloc(1, sizeof(*newkey))) == NULL) {
2518 r = SSH_ERR_ALLOC_FAIL;
2521 if ((r = sshbuf_froms(m, &b)) != 0)
2524 sshbuf_dump(b, stderr);
2528 comp = &newkey->comp;
2530 if ((r = sshbuf_get_cstring(b, &enc->name, NULL)) != 0 ||
2531 (r = sshbuf_get(b, &enc->cipher, sizeof(enc->cipher))) != 0 ||
2532 (r = sshbuf_get_u32(b, (u_int *)&enc->enabled)) != 0 ||
2533 (r = sshbuf_get_u32(b, &enc->block_size)) != 0 ||
2534 (r = sshbuf_get_string(b, &enc->key, &keylen)) != 0 ||
2535 (r = sshbuf_get_string(b, &enc->iv, &ivlen)) != 0)
2537 if (cipher_authlen(enc->cipher) == 0) {
2538 if ((r = sshbuf_get_cstring(b, &mac->name, NULL)) != 0)
2540 if ((r = mac_setup(mac, mac->name)) != 0)
2542 if ((r = sshbuf_get_u32(b, (u_int *)&mac->enabled)) != 0 ||
2543 (r = sshbuf_get_string(b, &mac->key, &maclen)) != 0)
2545 if (maclen > mac->key_len) {
2546 r = SSH_ERR_INVALID_FORMAT;
2549 mac->key_len = maclen;
2551 if ((r = sshbuf_get_u32(b, &comp->type)) != 0 ||
2552 (r = sshbuf_get_u32(b, (u_int *)&comp->enabled)) != 0 ||
2553 (r = sshbuf_get_cstring(b, &comp->name, NULL)) != 0)
2555 if (enc->name == NULL ||
2556 cipher_by_name(enc->name) != enc->cipher) {
2557 r = SSH_ERR_INVALID_FORMAT;
2560 if (sshbuf_len(b) != 0) {
2561 r = SSH_ERR_INVALID_FORMAT;
2564 enc->key_len = keylen;
2565 enc->iv_len = ivlen;
2566 ssh->kex->newkeys[mode] = newkey;
2577 /* restore kex from blob for packet state de-serialization */
2579 kex_from_blob(struct sshbuf *m, struct kex **kexp)
2584 if ((kex = calloc(1, sizeof(struct kex))) == NULL ||
2585 (kex->my = sshbuf_new()) == NULL ||
2586 (kex->peer = sshbuf_new()) == NULL) {
2587 r = SSH_ERR_ALLOC_FAIL;
2590 if ((r = sshbuf_get_string(m, &kex->session_id, &kex->session_id_len)) != 0 ||
2591 (r = sshbuf_get_u32(m, &kex->we_need)) != 0 ||
2592 (r = sshbuf_get_u32(m, (u_int *)&kex->hostkey_type)) != 0 ||
2593 (r = sshbuf_get_u32(m, &kex->kex_type)) != 0 ||
2594 (r = sshbuf_get_stringb(m, kex->my)) != 0 ||
2595 (r = sshbuf_get_stringb(m, kex->peer)) != 0 ||
2596 (r = sshbuf_get_u32(m, &kex->flags)) != 0 ||
2597 (r = sshbuf_get_cstring(m, &kex->client_version_string, NULL)) != 0 ||
2598 (r = sshbuf_get_cstring(m, &kex->server_version_string, NULL)) != 0)
2604 if (r != 0 || kexp == NULL) {
2606 if (kex->my != NULL)
2607 sshbuf_free(kex->my);
2608 if (kex->peer != NULL)
2609 sshbuf_free(kex->peer);
2621 * Restore packet state from content of blob 'm' (de-serialization).
2622 * Note that 'm' will be partially consumed on parsing or any other errors.
2625 ssh_packet_set_state(struct ssh *ssh, struct sshbuf *m)
2627 struct session_state *state = ssh->state;
2628 const u_char *ssh1key, *ivin, *ivout, *keyin, *keyout, *input, *output;
2629 size_t ssh1keylen, rlen, slen, ilen, olen;
2631 u_int ssh1cipher = 0;
2632 u_int64_t sent_bytes = 0, recv_bytes = 0;
2635 if ((r = sshbuf_get_u32(m, &state->remote_protocol_flags)) != 0 ||
2636 (r = sshbuf_get_u32(m, &ssh1cipher)) != 0 ||
2637 (r = sshbuf_get_string_direct(m, &ssh1key, &ssh1keylen)) != 0 ||
2638 (r = sshbuf_get_string_direct(m, &ivout, &slen)) != 0 ||
2639 (r = sshbuf_get_string_direct(m, &ivin, &rlen)) != 0)
2641 if (ssh1cipher > INT_MAX)
2642 return SSH_ERR_KEY_UNKNOWN_CIPHER;
2643 ssh_packet_set_encryption_key(ssh, ssh1key, ssh1keylen,
2645 if (cipher_get_keyiv_len(&state->send_context) != (int)slen ||
2646 cipher_get_keyiv_len(&state->receive_context) != (int)rlen)
2647 return SSH_ERR_INVALID_FORMAT;
2648 if ((r = cipher_set_keyiv(&state->send_context, ivout)) != 0 ||
2649 (r = cipher_set_keyiv(&state->receive_context, ivin)) != 0)
2652 if ((r = kex_from_blob(m, &ssh->kex)) != 0 ||
2653 (r = newkeys_from_blob(m, ssh, MODE_OUT)) != 0 ||
2654 (r = newkeys_from_blob(m, ssh, MODE_IN)) != 0 ||
2655 (r = sshbuf_get_u32(m, &state->rekey_limit)) != 0 ||
2656 (r = sshbuf_get_u32(m, &state->rekey_interval)) != 0 ||
2657 (r = sshbuf_get_u32(m, &state->p_send.seqnr)) != 0 ||
2658 (r = sshbuf_get_u64(m, &state->p_send.blocks)) != 0 ||
2659 (r = sshbuf_get_u32(m, &state->p_send.packets)) != 0 ||
2660 (r = sshbuf_get_u64(m, &state->p_send.bytes)) != 0 ||
2661 (r = sshbuf_get_u32(m, &state->p_read.seqnr)) != 0 ||
2662 (r = sshbuf_get_u64(m, &state->p_read.blocks)) != 0 ||
2663 (r = sshbuf_get_u32(m, &state->p_read.packets)) != 0 ||
2664 (r = sshbuf_get_u64(m, &state->p_read.bytes)) != 0)
2667 * We set the time here so that in post-auth privsep slave we
2668 * count from the completion of the authentication.
2670 state->rekey_time = monotime();
2671 /* XXX ssh_set_newkeys overrides p_read.packets? XXX */
2672 if ((r = ssh_set_newkeys(ssh, MODE_IN)) != 0 ||
2673 (r = ssh_set_newkeys(ssh, MODE_OUT)) != 0)
2676 if ((r = sshbuf_get_string_direct(m, &keyout, &slen)) != 0 ||
2677 (r = sshbuf_get_string_direct(m, &keyin, &rlen)) != 0)
2679 if (cipher_get_keycontext(&state->send_context, NULL) != (int)slen ||
2680 cipher_get_keycontext(&state->receive_context, NULL) != (int)rlen)
2681 return SSH_ERR_INVALID_FORMAT;
2682 cipher_set_keycontext(&state->send_context, keyout);
2683 cipher_set_keycontext(&state->receive_context, keyin);
2685 if ((r = ssh_packet_set_compress_state(ssh, m)) != 0 ||
2686 (r = ssh_packet_set_postauth(ssh)) != 0)
2689 sshbuf_reset(state->input);
2690 sshbuf_reset(state->output);
2691 if ((r = sshbuf_get_string_direct(m, &input, &ilen)) != 0 ||
2692 (r = sshbuf_get_string_direct(m, &output, &olen)) != 0 ||
2693 (r = sshbuf_put(state->input, input, ilen)) != 0 ||
2694 (r = sshbuf_put(state->output, output, olen)) != 0)
2698 if ((r = sshbuf_get_u64(m, &sent_bytes)) != 0 ||
2699 (r = sshbuf_get_u64(m, &recv_bytes)) != 0)
2701 roam_set_bytes(sent_bytes, recv_bytes);
2704 return SSH_ERR_INVALID_FORMAT;
2705 debug3("%s: done", __func__);
2711 /* put data to the outgoing packet */
2714 sshpkt_put(struct ssh *ssh, const void *v, size_t len)
2716 return sshbuf_put(ssh->state->outgoing_packet, v, len);
2720 sshpkt_putb(struct ssh *ssh, const struct sshbuf *b)
2722 return sshbuf_putb(ssh->state->outgoing_packet, b);
2726 sshpkt_put_u8(struct ssh *ssh, u_char val)
2728 return sshbuf_put_u8(ssh->state->outgoing_packet, val);
2732 sshpkt_put_u32(struct ssh *ssh, u_int32_t val)
2734 return sshbuf_put_u32(ssh->state->outgoing_packet, val);
2738 sshpkt_put_u64(struct ssh *ssh, u_int64_t val)
2740 return sshbuf_put_u64(ssh->state->outgoing_packet, val);
2744 sshpkt_put_string(struct ssh *ssh, const void *v, size_t len)
2746 return sshbuf_put_string(ssh->state->outgoing_packet, v, len);
2750 sshpkt_put_cstring(struct ssh *ssh, const void *v)
2752 return sshbuf_put_cstring(ssh->state->outgoing_packet, v);
2756 sshpkt_put_stringb(struct ssh *ssh, const struct sshbuf *v)
2758 return sshbuf_put_stringb(ssh->state->outgoing_packet, v);
2762 #ifdef OPENSSL_HAS_ECC
2764 sshpkt_put_ec(struct ssh *ssh, const EC_POINT *v, const EC_GROUP *g)
2766 return sshbuf_put_ec(ssh->state->outgoing_packet, v, g);
2768 #endif /* OPENSSL_HAS_ECC */
2772 sshpkt_put_bignum1(struct ssh *ssh, const BIGNUM *v)
2774 return sshbuf_put_bignum1(ssh->state->outgoing_packet, v);
2776 #endif /* WITH_SSH1 */
2779 sshpkt_put_bignum2(struct ssh *ssh, const BIGNUM *v)
2781 return sshbuf_put_bignum2(ssh->state->outgoing_packet, v);
2783 #endif /* WITH_OPENSSL */
2785 /* fetch data from the incoming packet */
2788 sshpkt_get(struct ssh *ssh, void *valp, size_t len)
2790 return sshbuf_get(ssh->state->incoming_packet, valp, len);
2794 sshpkt_get_u8(struct ssh *ssh, u_char *valp)
2796 return sshbuf_get_u8(ssh->state->incoming_packet, valp);
2800 sshpkt_get_u32(struct ssh *ssh, u_int32_t *valp)
2802 return sshbuf_get_u32(ssh->state->incoming_packet, valp);
2806 sshpkt_get_u64(struct ssh *ssh, u_int64_t *valp)
2808 return sshbuf_get_u64(ssh->state->incoming_packet, valp);
2812 sshpkt_get_string(struct ssh *ssh, u_char **valp, size_t *lenp)
2814 return sshbuf_get_string(ssh->state->incoming_packet, valp, lenp);
2818 sshpkt_get_string_direct(struct ssh *ssh, const u_char **valp, size_t *lenp)
2820 return sshbuf_get_string_direct(ssh->state->incoming_packet, valp, lenp);
2824 sshpkt_get_cstring(struct ssh *ssh, char **valp, size_t *lenp)
2826 return sshbuf_get_cstring(ssh->state->incoming_packet, valp, lenp);
2830 #ifdef OPENSSL_HAS_ECC
2832 sshpkt_get_ec(struct ssh *ssh, EC_POINT *v, const EC_GROUP *g)
2834 return sshbuf_get_ec(ssh->state->incoming_packet, v, g);
2836 #endif /* OPENSSL_HAS_ECC */
2840 sshpkt_get_bignum1(struct ssh *ssh, BIGNUM *v)
2842 return sshbuf_get_bignum1(ssh->state->incoming_packet, v);
2844 #endif /* WITH_SSH1 */
2847 sshpkt_get_bignum2(struct ssh *ssh, BIGNUM *v)
2849 return sshbuf_get_bignum2(ssh->state->incoming_packet, v);
2851 #endif /* WITH_OPENSSL */
2854 sshpkt_get_end(struct ssh *ssh)
2856 if (sshbuf_len(ssh->state->incoming_packet) > 0)
2857 return SSH_ERR_UNEXPECTED_TRAILING_DATA;
2862 sshpkt_ptr(struct ssh *ssh, size_t *lenp)
2865 *lenp = sshbuf_len(ssh->state->incoming_packet);
2866 return sshbuf_ptr(ssh->state->incoming_packet);
2869 /* start a new packet */
2872 sshpkt_start(struct ssh *ssh, u_char type)
2877 DBG(debug("packet_start[%d]", type));
2878 len = compat20 ? 6 : 9;
2879 memset(buf, 0, len - 1);
2880 buf[len - 1] = type;
2881 sshbuf_reset(ssh->state->outgoing_packet);
2882 return sshbuf_put(ssh->state->outgoing_packet, buf, len);
2888 sshpkt_send(struct ssh *ssh)
2891 return ssh_packet_send2(ssh);
2893 return ssh_packet_send1(ssh);
2897 sshpkt_disconnect(struct ssh *ssh, const char *fmt,...)
2903 va_start(args, fmt);
2904 vsnprintf(buf, sizeof(buf), fmt, args);
2908 if ((r = sshpkt_start(ssh, SSH2_MSG_DISCONNECT)) != 0 ||
2909 (r = sshpkt_put_u32(ssh, SSH2_DISCONNECT_PROTOCOL_ERROR)) != 0 ||
2910 (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
2911 (r = sshpkt_put_cstring(ssh, "")) != 0 ||
2912 (r = sshpkt_send(ssh)) != 0)
2915 if ((r = sshpkt_start(ssh, SSH_MSG_DISCONNECT)) != 0 ||
2916 (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
2917 (r = sshpkt_send(ssh)) != 0)
2923 /* roundup current message to pad bytes */
2925 sshpkt_add_padding(struct ssh *ssh, u_char pad)
2927 ssh->state->extra_pad = pad;