1 /* $OpenBSD: packet.c,v 1.317 2024/08/23 04:51:00 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.
42 #include <sys/types.h>
43 #include "openbsd-compat/sys-queue.h"
44 #include <sys/socket.h>
45 #ifdef HAVE_SYS_TIME_H
46 # include <sys/time.h>
49 #include <netinet/in.h>
50 #include <netinet/ip.h>
51 #include <arpa/inet.h>
68 * Explicitly include OpenSSL before zlib as some versions of OpenSSL have
69 * "free_func" in their headers, which zlib typedefs.
72 # include <openssl/bn.h>
73 # include <openssl/evp.h>
74 # ifdef OPENSSL_HAS_ECC
75 # include <openssl/ec.h>
106 #define PACKET_MAX_SIZE (256 * 1024)
108 struct packet_state
{
116 TAILQ_ENTRY(packet
) next
;
118 struct sshbuf
*payload
;
121 struct session_state
{
123 * This variable contains the file descriptors used for
124 * communicating with the other side. connection_in is used for
125 * reading; connection_out for writing. These can be the same
126 * descriptor, in which case it is assumed to be a socket.
131 /* Protocol flags for the remote side. */
132 u_int remote_protocol_flags
;
134 /* Encryption context for receiving data. Only used for decryption. */
135 struct sshcipher_ctx
*receive_context
;
137 /* Encryption context for sending data. Only used for encryption. */
138 struct sshcipher_ctx
*send_context
;
140 /* Buffer for raw input data from the socket. */
141 struct sshbuf
*input
;
143 /* Buffer for raw output data going to the socket. */
144 struct sshbuf
*output
;
146 /* Buffer for the partial outgoing packet being constructed. */
147 struct sshbuf
*outgoing_packet
;
149 /* Buffer for the incoming packet currently being processed. */
150 struct sshbuf
*incoming_packet
;
152 /* Scratch buffer for packet compression/decompression. */
153 struct sshbuf
*compression_buffer
;
156 /* Incoming/outgoing compression dictionaries */
157 z_stream compression_in_stream
;
158 z_stream compression_out_stream
;
160 int compression_in_started
;
161 int compression_out_started
;
162 int compression_in_failures
;
163 int compression_out_failures
;
165 /* default maximum packet size */
166 u_int max_packet_size
;
168 /* Flag indicating whether this module has been initialized. */
171 /* Set to true if the connection is interactive. */
172 int interactive_mode
;
174 /* Set to true if we are the server side. */
177 /* Set to true if we are authenticated. */
178 int after_authentication
;
180 int keep_alive_timeouts
;
182 /* The maximum time that we will wait to send or receive a packet */
183 int packet_timeout_ms
;
185 /* Session key information for Encryption and MAC */
186 struct newkeys
*newkeys
[MODE_MAX
];
187 struct packet_state p_read
, p_send
;
189 /* Volume-based rekeying */
190 u_int64_t max_blocks_in
, max_blocks_out
, rekey_limit
;
192 /* Time-based rekeying */
193 u_int32_t rekey_interval
; /* how often in seconds */
194 time_t rekey_time
; /* time of last rekeying */
196 /* roundup current message to extra_pad bytes */
199 /* XXX discard incoming data after MAC error */
200 u_int packet_discard
;
201 size_t packet_discard_mac_already
;
202 struct sshmac
*packet_discard_mac
;
204 /* Used in packet_read_poll2() */
207 /* Used in packet_send2 */
210 /* Used in ssh_packet_send_mux() */
213 /* Used in packet_set_interactive */
214 int set_interactive_called
;
216 /* Used in packet_set_maxsize */
217 int set_maxsize_called
;
219 /* One-off warning about weak ciphers */
220 int cipher_warning_done
;
222 /* Hook for fuzzing inbound packets */
223 ssh_packet_hook_fn
*hook_in
;
226 TAILQ_HEAD(, packet
) outgoing
;
230 ssh_alloc_session_state(void)
232 struct ssh
*ssh
= NULL
;
233 struct session_state
*state
= NULL
;
235 if ((ssh
= calloc(1, sizeof(*ssh
))) == NULL
||
236 (state
= calloc(1, sizeof(*state
))) == NULL
||
237 (ssh
->kex
= kex_new()) == NULL
||
238 (state
->input
= sshbuf_new()) == NULL
||
239 (state
->output
= sshbuf_new()) == NULL
||
240 (state
->outgoing_packet
= sshbuf_new()) == NULL
||
241 (state
->incoming_packet
= sshbuf_new()) == NULL
)
243 TAILQ_INIT(&state
->outgoing
);
244 TAILQ_INIT(&ssh
->private_keys
);
245 TAILQ_INIT(&ssh
->public_keys
);
246 state
->connection_in
= -1;
247 state
->connection_out
= -1;
248 state
->max_packet_size
= 32768;
249 state
->packet_timeout_ms
= -1;
250 state
->p_send
.packets
= state
->p_read
.packets
= 0;
251 state
->initialized
= 1;
253 * ssh_packet_send2() needs to queue packets until
254 * we've done the initial key exchange.
265 sshbuf_free(state
->input
);
266 sshbuf_free(state
->output
);
267 sshbuf_free(state
->incoming_packet
);
268 sshbuf_free(state
->outgoing_packet
);
275 ssh_packet_set_input_hook(struct ssh
*ssh
, ssh_packet_hook_fn
*hook
, void *ctx
)
277 ssh
->state
->hook_in
= hook
;
278 ssh
->state
->hook_in_ctx
= ctx
;
281 /* Returns nonzero if rekeying is in progress */
283 ssh_packet_is_rekeying(struct ssh
*ssh
)
285 return ssh
->state
->rekeying
||
286 (ssh
->kex
!= NULL
&& ssh
->kex
->done
== 0);
290 * Sets the descriptors used for communication.
293 ssh_packet_set_connection(struct ssh
*ssh
, int fd_in
, int fd_out
)
295 struct session_state
*state
;
296 const struct sshcipher
*none
= cipher_by_name("none");
300 error_f("cannot load cipher 'none'");
304 ssh
= ssh_alloc_session_state();
306 error_f("could not allocate state");
310 state
->connection_in
= fd_in
;
311 state
->connection_out
= fd_out
;
312 if ((r
= cipher_init(&state
->send_context
, none
,
313 (const u_char
*)"", 0, NULL
, 0, CIPHER_ENCRYPT
)) != 0 ||
314 (r
= cipher_init(&state
->receive_context
, none
,
315 (const u_char
*)"", 0, NULL
, 0, CIPHER_DECRYPT
)) != 0) {
316 error_fr(r
, "cipher_init failed");
317 free(ssh
); /* XXX need ssh_free_session_state? */
320 state
->newkeys
[MODE_IN
] = state
->newkeys
[MODE_OUT
] = NULL
;
322 * Cache the IP address of the remote connection for use in error
323 * messages that might be generated after the connection has closed.
325 (void)ssh_remote_ipaddr(ssh
);
330 ssh_packet_set_timeout(struct ssh
*ssh
, int timeout
, int count
)
332 struct session_state
*state
= ssh
->state
;
334 if (timeout
<= 0 || count
<= 0) {
335 state
->packet_timeout_ms
= -1;
338 if ((INT_MAX
/ 1000) / count
< timeout
)
339 state
->packet_timeout_ms
= INT_MAX
;
341 state
->packet_timeout_ms
= timeout
* count
* 1000;
345 ssh_packet_set_mux(struct ssh
*ssh
)
348 ssh
->state
->rekeying
= 0;
354 ssh_packet_get_mux(struct ssh
*ssh
)
356 return ssh
->state
->mux
;
360 ssh_packet_set_log_preamble(struct ssh
*ssh
, const char *fmt
, ...)
365 free(ssh
->log_preamble
);
367 ssh
->log_preamble
= NULL
;
370 r
= vasprintf(&ssh
->log_preamble
, fmt
, args
);
372 if (r
< 0 || ssh
->log_preamble
== NULL
)
373 return SSH_ERR_ALLOC_FAIL
;
379 ssh_packet_stop_discard(struct ssh
*ssh
)
381 struct session_state
*state
= ssh
->state
;
384 if (state
->packet_discard_mac
) {
386 size_t dlen
= PACKET_MAX_SIZE
;
388 if (dlen
> state
->packet_discard_mac_already
)
389 dlen
-= state
->packet_discard_mac_already
;
390 memset(buf
, 'a', sizeof(buf
));
391 while (sshbuf_len(state
->incoming_packet
) < dlen
)
392 if ((r
= sshbuf_put(state
->incoming_packet
, buf
,
395 (void) mac_compute(state
->packet_discard_mac
,
397 sshbuf_ptr(state
->incoming_packet
), dlen
,
400 logit("Finished discarding for %.200s port %d",
401 ssh_remote_ipaddr(ssh
), ssh_remote_port(ssh
));
402 return SSH_ERR_MAC_INVALID
;
406 ssh_packet_start_discard(struct ssh
*ssh
, struct sshenc
*enc
,
407 struct sshmac
*mac
, size_t mac_already
, u_int discard
)
409 struct session_state
*state
= ssh
->state
;
412 if (enc
== NULL
|| !cipher_is_cbc(enc
->cipher
) || (mac
&& mac
->etm
)) {
413 if ((r
= sshpkt_disconnect(ssh
, "Packet corrupt")) != 0)
415 return SSH_ERR_MAC_INVALID
;
418 * Record number of bytes over which the mac has already
419 * been computed in order to minimize timing attacks.
421 if (mac
&& mac
->enabled
) {
422 state
->packet_discard_mac
= mac
;
423 state
->packet_discard_mac_already
= mac_already
;
425 if (sshbuf_len(state
->input
) >= discard
)
426 return ssh_packet_stop_discard(ssh
);
427 state
->packet_discard
= discard
- sshbuf_len(state
->input
);
431 /* Returns 1 if remote host is connected via socket, 0 if not. */
434 ssh_packet_connection_is_on_socket(struct ssh
*ssh
)
436 struct session_state
*state
;
437 struct sockaddr_storage from
, to
;
438 socklen_t fromlen
, tolen
;
440 if (ssh
== NULL
|| ssh
->state
== NULL
)
444 if (state
->connection_in
== -1 || state
->connection_out
== -1)
446 /* filedescriptors in and out are the same, so it's a socket */
447 if (state
->connection_in
== state
->connection_out
)
449 fromlen
= sizeof(from
);
450 memset(&from
, 0, sizeof(from
));
451 if (getpeername(state
->connection_in
, (struct sockaddr
*)&from
,
455 memset(&to
, 0, sizeof(to
));
456 if (getpeername(state
->connection_out
, (struct sockaddr
*)&to
,
459 if (fromlen
!= tolen
|| memcmp(&from
, &to
, fromlen
) != 0)
461 if (from
.ss_family
!= AF_INET
&& from
.ss_family
!= AF_INET6
)
467 ssh_packet_get_bytes(struct ssh
*ssh
, u_int64_t
*ibytes
, u_int64_t
*obytes
)
470 *ibytes
= ssh
->state
->p_read
.bytes
;
472 *obytes
= ssh
->state
->p_send
.bytes
;
476 ssh_packet_connection_af(struct ssh
*ssh
)
478 return get_sock_af(ssh
->state
->connection_out
);
481 /* Sets the connection into non-blocking mode. */
484 ssh_packet_set_nonblocking(struct ssh
*ssh
)
486 /* Set the socket into non-blocking mode. */
487 set_nonblock(ssh
->state
->connection_in
);
489 if (ssh
->state
->connection_out
!= ssh
->state
->connection_in
)
490 set_nonblock(ssh
->state
->connection_out
);
493 /* Returns the socket used for reading. */
496 ssh_packet_get_connection_in(struct ssh
*ssh
)
498 return ssh
->state
->connection_in
;
501 /* Returns the descriptor used for writing. */
504 ssh_packet_get_connection_out(struct ssh
*ssh
)
506 return ssh
->state
->connection_out
;
510 * Returns the IP-address of the remote host as a string. The returned
511 * string must not be freed.
515 ssh_remote_ipaddr(struct ssh
*ssh
)
519 /* Check whether we have cached the ipaddr. */
520 if (ssh
->remote_ipaddr
== NULL
) {
521 if (ssh_packet_connection_is_on_socket(ssh
)) {
522 sock
= ssh
->state
->connection_in
;
523 ssh
->remote_ipaddr
= get_peer_ipaddr(sock
);
524 ssh
->remote_port
= get_peer_port(sock
);
525 ssh
->local_ipaddr
= get_local_ipaddr(sock
);
526 ssh
->local_port
= get_local_port(sock
);
528 ssh
->remote_ipaddr
= xstrdup("UNKNOWN");
529 ssh
->remote_port
= 65535;
530 ssh
->local_ipaddr
= xstrdup("UNKNOWN");
531 ssh
->local_port
= 65535;
534 return ssh
->remote_ipaddr
;
538 * Returns the remote DNS hostname as a string. The returned string must not
539 * be freed. NB. this will usually trigger a DNS query. Return value is on
540 * heap and no caching is performed.
541 * This function does additional checks on the hostname to mitigate some
542 * attacks based on conflation of hostnames and addresses and will
543 * fall back to returning an address on error.
547 ssh_remote_hostname(struct ssh
*ssh
)
549 struct sockaddr_storage from
;
551 struct addrinfo hints
, *ai
, *aitop
;
552 char name
[NI_MAXHOST
], ntop2
[NI_MAXHOST
];
553 const char *ntop
= ssh_remote_ipaddr(ssh
);
555 /* Get IP address of client. */
556 fromlen
= sizeof(from
);
557 memset(&from
, 0, sizeof(from
));
558 if (getpeername(ssh_packet_get_connection_in(ssh
),
559 (struct sockaddr
*)&from
, &fromlen
) == -1) {
560 debug_f("getpeername failed: %.100s", strerror(errno
));
561 return xstrdup(ntop
);
564 ipv64_normalise_mapped(&from
, &fromlen
);
565 if (from
.ss_family
== AF_INET6
)
566 fromlen
= sizeof(struct sockaddr_in6
);
568 debug3("trying to reverse map address %.100s.", ntop
);
569 /* Map the IP address to a host name. */
570 if (getnameinfo((struct sockaddr
*)&from
, fromlen
, name
, sizeof(name
),
571 NULL
, 0, NI_NAMEREQD
) != 0) {
572 /* Host name not found. Use ip address. */
573 return xstrdup(ntop
);
577 * if reverse lookup result looks like a numeric hostname,
578 * someone is trying to trick us by PTR record like following:
579 * 1.1.1.10.in-addr.arpa. IN PTR 2.3.4.5
581 memset(&hints
, 0, sizeof(hints
));
582 hints
.ai_socktype
= SOCK_DGRAM
; /*dummy*/
583 hints
.ai_flags
= AI_NUMERICHOST
;
584 if (getaddrinfo(name
, NULL
, &hints
, &ai
) == 0) {
585 logit("Nasty PTR record \"%s\" is set up for %s, ignoring",
588 return xstrdup(ntop
);
591 /* Names are stored in lowercase. */
595 * Map it back to an IP address and check that the given
596 * address actually is an address of this host. This is
597 * necessary because anyone with access to a name server can
598 * define arbitrary names for an IP address. Mapping from
599 * name to IP address can be trusted better (but can still be
600 * fooled if the intruder has access to the name server of
603 memset(&hints
, 0, sizeof(hints
));
604 hints
.ai_family
= from
.ss_family
;
605 hints
.ai_socktype
= SOCK_STREAM
;
606 if (getaddrinfo(name
, NULL
, &hints
, &aitop
) != 0) {
607 logit("reverse mapping checking getaddrinfo for %.700s "
608 "[%s] failed.", name
, ntop
);
609 return xstrdup(ntop
);
611 /* Look for the address from the list of addresses. */
612 for (ai
= aitop
; ai
; ai
= ai
->ai_next
) {
613 if (getnameinfo(ai
->ai_addr
, ai
->ai_addrlen
, ntop2
,
614 sizeof(ntop2
), NULL
, 0, NI_NUMERICHOST
) == 0 &&
615 (strcmp(ntop
, ntop2
) == 0))
619 /* If we reached the end of the list, the address was not there. */
621 /* Address not found for the host name. */
622 logit("Address %.100s maps to %.600s, but this does not "
623 "map back to the address.", ntop
, name
);
624 return xstrdup(ntop
);
626 return xstrdup(name
);
629 /* Returns the port number of the remote host. */
632 ssh_remote_port(struct ssh
*ssh
)
634 (void)ssh_remote_ipaddr(ssh
); /* Will lookup and cache. */
635 return ssh
->remote_port
;
639 * Returns the IP-address of the local host as a string. The returned
640 * string must not be freed.
644 ssh_local_ipaddr(struct ssh
*ssh
)
646 (void)ssh_remote_ipaddr(ssh
); /* Will lookup and cache. */
647 return ssh
->local_ipaddr
;
650 /* Returns the port number of the local host. */
653 ssh_local_port(struct ssh
*ssh
)
655 (void)ssh_remote_ipaddr(ssh
); /* Will lookup and cache. */
656 return ssh
->local_port
;
659 /* Returns the routing domain of the input socket, or NULL if unavailable */
661 ssh_packet_rdomain_in(struct ssh
*ssh
)
663 if (ssh
->rdomain_in
!= NULL
)
664 return ssh
->rdomain_in
;
665 if (!ssh_packet_connection_is_on_socket(ssh
))
667 ssh
->rdomain_in
= get_rdomain(ssh
->state
->connection_in
);
668 return ssh
->rdomain_in
;
671 /* Closes the connection and clears and frees internal data structures. */
674 ssh_packet_close_internal(struct ssh
*ssh
, int do_close
)
676 struct session_state
*state
= ssh
->state
;
679 if (!state
->initialized
)
681 state
->initialized
= 0;
683 if (state
->connection_in
== state
->connection_out
) {
684 close(state
->connection_out
);
686 close(state
->connection_in
);
687 close(state
->connection_out
);
690 sshbuf_free(state
->input
);
691 sshbuf_free(state
->output
);
692 sshbuf_free(state
->outgoing_packet
);
693 sshbuf_free(state
->incoming_packet
);
694 for (mode
= 0; mode
< MODE_MAX
; mode
++) {
695 kex_free_newkeys(state
->newkeys
[mode
]); /* current keys */
696 state
->newkeys
[mode
] = NULL
;
697 ssh_clear_newkeys(ssh
, mode
); /* next keys */
700 /* compression state is in shared mem, so we can only release it once */
701 if (do_close
&& state
->compression_buffer
) {
702 sshbuf_free(state
->compression_buffer
);
703 if (state
->compression_out_started
) {
704 z_streamp stream
= &state
->compression_out_stream
;
705 debug("compress outgoing: "
706 "raw data %llu, compressed %llu, factor %.2f",
707 (unsigned long long)stream
->total_in
,
708 (unsigned long long)stream
->total_out
,
709 stream
->total_in
== 0 ? 0.0 :
710 (double) stream
->total_out
/ stream
->total_in
);
711 if (state
->compression_out_failures
== 0)
714 if (state
->compression_in_started
) {
715 z_streamp stream
= &state
->compression_in_stream
;
716 debug("compress incoming: "
717 "raw data %llu, compressed %llu, factor %.2f",
718 (unsigned long long)stream
->total_out
,
719 (unsigned long long)stream
->total_in
,
720 stream
->total_out
== 0 ? 0.0 :
721 (double) stream
->total_in
/ stream
->total_out
);
722 if (state
->compression_in_failures
== 0)
726 #endif /* WITH_ZLIB */
727 cipher_free(state
->send_context
);
728 cipher_free(state
->receive_context
);
729 state
->send_context
= state
->receive_context
= NULL
;
731 free(ssh
->local_ipaddr
);
732 ssh
->local_ipaddr
= NULL
;
733 free(ssh
->remote_ipaddr
);
734 ssh
->remote_ipaddr
= NULL
;
743 ssh_packet_close(struct ssh
*ssh
)
745 ssh_packet_close_internal(ssh
, 1);
749 ssh_packet_clear_keys(struct ssh
*ssh
)
751 ssh_packet_close_internal(ssh
, 0);
754 /* Sets remote side protocol flags. */
757 ssh_packet_set_protocol_flags(struct ssh
*ssh
, u_int protocol_flags
)
759 ssh
->state
->remote_protocol_flags
= protocol_flags
;
762 /* Returns the remote protocol flags set earlier by the above function. */
765 ssh_packet_get_protocol_flags(struct ssh
*ssh
)
767 return ssh
->state
->remote_protocol_flags
;
771 * Starts packet compression from the next packet on in both directions.
772 * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
776 ssh_packet_init_compression(struct ssh
*ssh
)
778 if (!ssh
->state
->compression_buffer
&&
779 ((ssh
->state
->compression_buffer
= sshbuf_new()) == NULL
))
780 return SSH_ERR_ALLOC_FAIL
;
786 start_compression_out(struct ssh
*ssh
, int level
)
788 if (level
< 1 || level
> 9)
789 return SSH_ERR_INVALID_ARGUMENT
;
790 debug("Enabling compression at level %d.", level
);
791 if (ssh
->state
->compression_out_started
== 1)
792 deflateEnd(&ssh
->state
->compression_out_stream
);
793 switch (deflateInit(&ssh
->state
->compression_out_stream
, level
)) {
795 ssh
->state
->compression_out_started
= 1;
798 return SSH_ERR_ALLOC_FAIL
;
800 return SSH_ERR_INTERNAL_ERROR
;
806 start_compression_in(struct ssh
*ssh
)
808 if (ssh
->state
->compression_in_started
== 1)
809 inflateEnd(&ssh
->state
->compression_in_stream
);
810 switch (inflateInit(&ssh
->state
->compression_in_stream
)) {
812 ssh
->state
->compression_in_started
= 1;
815 return SSH_ERR_ALLOC_FAIL
;
817 return SSH_ERR_INTERNAL_ERROR
;
822 /* XXX remove need for separate compression buffer */
824 compress_buffer(struct ssh
*ssh
, struct sshbuf
*in
, struct sshbuf
*out
)
829 if (ssh
->state
->compression_out_started
!= 1)
830 return SSH_ERR_INTERNAL_ERROR
;
832 /* This case is not handled below. */
833 if (sshbuf_len(in
) == 0)
836 /* Input is the contents of the input buffer. */
837 if ((ssh
->state
->compression_out_stream
.next_in
=
838 sshbuf_mutable_ptr(in
)) == NULL
)
839 return SSH_ERR_INTERNAL_ERROR
;
840 ssh
->state
->compression_out_stream
.avail_in
= sshbuf_len(in
);
842 /* Loop compressing until deflate() returns with avail_out != 0. */
844 /* Set up fixed-size output buffer. */
845 ssh
->state
->compression_out_stream
.next_out
= buf
;
846 ssh
->state
->compression_out_stream
.avail_out
= sizeof(buf
);
848 /* Compress as much data into the buffer as possible. */
849 status
= deflate(&ssh
->state
->compression_out_stream
,
853 return SSH_ERR_ALLOC_FAIL
;
855 /* Append compressed data to output_buffer. */
856 if ((r
= sshbuf_put(out
, buf
, sizeof(buf
) -
857 ssh
->state
->compression_out_stream
.avail_out
)) != 0)
862 ssh
->state
->compression_out_failures
++;
863 return SSH_ERR_INVALID_FORMAT
;
865 } while (ssh
->state
->compression_out_stream
.avail_out
== 0);
870 uncompress_buffer(struct ssh
*ssh
, struct sshbuf
*in
, struct sshbuf
*out
)
875 if (ssh
->state
->compression_in_started
!= 1)
876 return SSH_ERR_INTERNAL_ERROR
;
878 if ((ssh
->state
->compression_in_stream
.next_in
=
879 sshbuf_mutable_ptr(in
)) == NULL
)
880 return SSH_ERR_INTERNAL_ERROR
;
881 ssh
->state
->compression_in_stream
.avail_in
= sshbuf_len(in
);
884 /* Set up fixed-size output buffer. */
885 ssh
->state
->compression_in_stream
.next_out
= buf
;
886 ssh
->state
->compression_in_stream
.avail_out
= sizeof(buf
);
888 status
= inflate(&ssh
->state
->compression_in_stream
,
892 if ((r
= sshbuf_put(out
, buf
, sizeof(buf
) -
893 ssh
->state
->compression_in_stream
.avail_out
)) != 0)
898 * Comments in zlib.h say that we should keep calling
899 * inflate() until we get an error. This appears to
900 * be the error that we get.
904 return SSH_ERR_INVALID_FORMAT
;
906 return SSH_ERR_ALLOC_FAIL
;
909 ssh
->state
->compression_in_failures
++;
910 return SSH_ERR_INTERNAL_ERROR
;
916 #else /* WITH_ZLIB */
919 start_compression_out(struct ssh
*ssh
, int level
)
921 return SSH_ERR_INTERNAL_ERROR
;
925 start_compression_in(struct ssh
*ssh
)
927 return SSH_ERR_INTERNAL_ERROR
;
931 compress_buffer(struct ssh
*ssh
, struct sshbuf
*in
, struct sshbuf
*out
)
933 return SSH_ERR_INTERNAL_ERROR
;
937 uncompress_buffer(struct ssh
*ssh
, struct sshbuf
*in
, struct sshbuf
*out
)
939 return SSH_ERR_INTERNAL_ERROR
;
941 #endif /* WITH_ZLIB */
944 ssh_clear_newkeys(struct ssh
*ssh
, int mode
)
946 if (ssh
->kex
&& ssh
->kex
->newkeys
[mode
]) {
947 kex_free_newkeys(ssh
->kex
->newkeys
[mode
]);
948 ssh
->kex
->newkeys
[mode
] = NULL
;
953 ssh_set_newkeys(struct ssh
*ssh
, int mode
)
955 struct session_state
*state
= ssh
->state
;
958 struct sshcomp
*comp
;
959 struct sshcipher_ctx
**ccp
;
960 struct packet_state
*ps
;
961 u_int64_t
*max_blocks
;
964 const char *dir
= mode
== MODE_OUT
? "out" : "in";
966 debug2_f("mode %d", mode
);
968 if (mode
== MODE_OUT
) {
969 ccp
= &state
->send_context
;
970 crypt_type
= CIPHER_ENCRYPT
;
972 max_blocks
= &state
->max_blocks_out
;
974 ccp
= &state
->receive_context
;
975 crypt_type
= CIPHER_DECRYPT
;
977 max_blocks
= &state
->max_blocks_in
;
979 if (state
->newkeys
[mode
] != NULL
) {
980 debug_f("rekeying %s, input %llu bytes %llu blocks, "
981 "output %llu bytes %llu blocks", dir
,
982 (unsigned long long)state
->p_read
.bytes
,
983 (unsigned long long)state
->p_read
.blocks
,
984 (unsigned long long)state
->p_send
.bytes
,
985 (unsigned long long)state
->p_send
.blocks
);
986 kex_free_newkeys(state
->newkeys
[mode
]);
987 state
->newkeys
[mode
] = NULL
;
989 /* note that both bytes and the seqnr are not reset */
990 ps
->packets
= ps
->blocks
= 0;
991 /* move newkeys from kex to state */
992 if ((state
->newkeys
[mode
] = ssh
->kex
->newkeys
[mode
]) == NULL
)
993 return SSH_ERR_INTERNAL_ERROR
;
994 ssh
->kex
->newkeys
[mode
] = NULL
;
995 enc
= &state
->newkeys
[mode
]->enc
;
996 mac
= &state
->newkeys
[mode
]->mac
;
997 comp
= &state
->newkeys
[mode
]->comp
;
998 if (cipher_authlen(enc
->cipher
) == 0) {
999 if ((r
= mac_init(mac
)) != 0)
1003 DBG(debug_f("cipher_init: %s", dir
));
1006 if ((r
= cipher_init(ccp
, enc
->cipher
, enc
->key
, enc
->key_len
,
1007 enc
->iv
, enc
->iv_len
, crypt_type
)) != 0)
1009 if (!state
->cipher_warning_done
&&
1010 (wmsg
= cipher_warning_message(*ccp
)) != NULL
) {
1011 error("Warning: %s", wmsg
);
1012 state
->cipher_warning_done
= 1;
1014 /* Deleting the keys does not gain extra security */
1015 /* explicit_bzero(enc->iv, enc->block_size);
1016 explicit_bzero(enc->key, enc->key_len);
1017 explicit_bzero(mac->key, mac->key_len); */
1018 if (((comp
->type
== COMP_DELAYED
&& state
->after_authentication
)) &&
1019 comp
->enabled
== 0) {
1020 if ((r
= ssh_packet_init_compression(ssh
)) < 0)
1022 if (mode
== MODE_OUT
) {
1023 if ((r
= start_compression_out(ssh
, 6)) != 0)
1026 if ((r
= start_compression_in(ssh
)) != 0)
1032 * The 2^(blocksize*2) limit is too expensive for 3DES,
1033 * so enforce a 1GB limit for small blocksizes.
1034 * See RFC4344 section 3.2.
1036 if (enc
->block_size
>= 16)
1037 *max_blocks
= (u_int64_t
)1 << (enc
->block_size
*2);
1039 *max_blocks
= ((u_int64_t
)1 << 30) / enc
->block_size
;
1040 if (state
->rekey_limit
)
1041 *max_blocks
= MINIMUM(*max_blocks
,
1042 state
->rekey_limit
/ enc
->block_size
);
1043 debug("rekey %s after %llu blocks", dir
,
1044 (unsigned long long)*max_blocks
);
1048 #define MAX_PACKETS (1U<<31)
1050 ssh_packet_need_rekeying(struct ssh
*ssh
, u_int outbound_packet_len
)
1052 struct session_state
*state
= ssh
->state
;
1053 u_int32_t out_blocks
;
1055 /* XXX client can't cope with rekeying pre-auth */
1056 if (!state
->after_authentication
)
1059 /* Haven't keyed yet or KEX in progress. */
1060 if (ssh_packet_is_rekeying(ssh
))
1063 /* Peer can't rekey */
1064 if (ssh
->compat
& SSH_BUG_NOREKEY
)
1068 * Permit one packet in or out per rekey - this allows us to
1069 * make progress when rekey limits are very small.
1071 if (state
->p_send
.packets
== 0 && state
->p_read
.packets
== 0)
1074 /* Time-based rekeying */
1075 if (state
->rekey_interval
!= 0 &&
1076 (int64_t)state
->rekey_time
+ state
->rekey_interval
<= monotime())
1080 * Always rekey when MAX_PACKETS sent in either direction
1081 * As per RFC4344 section 3.1 we do this after 2^31 packets.
1083 if (state
->p_send
.packets
> MAX_PACKETS
||
1084 state
->p_read
.packets
> MAX_PACKETS
)
1087 /* Rekey after (cipher-specific) maximum blocks */
1088 out_blocks
= ROUNDUP(outbound_packet_len
,
1089 state
->newkeys
[MODE_OUT
]->enc
.block_size
);
1090 return (state
->max_blocks_out
&&
1091 (state
->p_send
.blocks
+ out_blocks
> state
->max_blocks_out
)) ||
1092 (state
->max_blocks_in
&&
1093 (state
->p_read
.blocks
> state
->max_blocks_in
));
1097 ssh_packet_check_rekey(struct ssh
*ssh
)
1099 if (!ssh_packet_need_rekeying(ssh
, 0))
1101 debug3_f("rekex triggered");
1102 return kex_start_rekex(ssh
);
1106 * Delayed compression for SSH2 is enabled after authentication:
1107 * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
1108 * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
1111 ssh_packet_enable_delayed_compress(struct ssh
*ssh
)
1113 struct session_state
*state
= ssh
->state
;
1114 struct sshcomp
*comp
= NULL
;
1118 * Remember that we are past the authentication step, so rekeying
1119 * with COMP_DELAYED will turn on compression immediately.
1121 state
->after_authentication
= 1;
1122 for (mode
= 0; mode
< MODE_MAX
; mode
++) {
1123 /* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
1124 if (state
->newkeys
[mode
] == NULL
)
1126 comp
= &state
->newkeys
[mode
]->comp
;
1127 if (comp
&& !comp
->enabled
&& comp
->type
== COMP_DELAYED
) {
1128 if ((r
= ssh_packet_init_compression(ssh
)) != 0)
1130 if (mode
== MODE_OUT
) {
1131 if ((r
= start_compression_out(ssh
, 6)) != 0)
1134 if ((r
= start_compression_in(ssh
)) != 0)
1143 /* Used to mute debug logging for noisy packet types */
1145 ssh_packet_log_type(u_char type
)
1150 case SSH2_MSG_CHANNEL_DATA
:
1151 case SSH2_MSG_CHANNEL_EXTENDED_DATA
:
1152 case SSH2_MSG_CHANNEL_WINDOW_ADJUST
:
1160 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
1163 ssh_packet_send2_wrapped(struct ssh
*ssh
)
1165 struct session_state
*state
= ssh
->state
;
1166 u_char type
, *cp
, macbuf
[SSH_DIGEST_MAX_LENGTH
];
1167 u_char tmp
, padlen
, pad
= 0;
1168 u_int authlen
= 0, aadlen
= 0;
1170 struct sshenc
*enc
= NULL
;
1171 struct sshmac
*mac
= NULL
;
1172 struct sshcomp
*comp
= NULL
;
1175 if (state
->newkeys
[MODE_OUT
] != NULL
) {
1176 enc
= &state
->newkeys
[MODE_OUT
]->enc
;
1177 mac
= &state
->newkeys
[MODE_OUT
]->mac
;
1178 comp
= &state
->newkeys
[MODE_OUT
]->comp
;
1179 /* disable mac for authenticated encryption */
1180 if ((authlen
= cipher_authlen(enc
->cipher
)) != 0)
1183 block_size
= enc
? enc
->block_size
: 8;
1184 aadlen
= (mac
&& mac
->enabled
&& mac
->etm
) || authlen
? 4 : 0;
1186 type
= (sshbuf_ptr(state
->outgoing_packet
))[5];
1187 if (ssh_packet_log_type(type
))
1188 debug3("send packet: type %u", type
);
1190 fprintf(stderr
, "plain: ");
1191 sshbuf_dump(state
->outgoing_packet
, stderr
);
1194 if (comp
&& comp
->enabled
) {
1195 len
= sshbuf_len(state
->outgoing_packet
);
1196 /* skip header, compress only payload */
1197 if ((r
= sshbuf_consume(state
->outgoing_packet
, 5)) != 0)
1199 sshbuf_reset(state
->compression_buffer
);
1200 if ((r
= compress_buffer(ssh
, state
->outgoing_packet
,
1201 state
->compression_buffer
)) != 0)
1203 sshbuf_reset(state
->outgoing_packet
);
1204 if ((r
= sshbuf_put(state
->outgoing_packet
,
1205 "\0\0\0\0\0", 5)) != 0 ||
1206 (r
= sshbuf_putb(state
->outgoing_packet
,
1207 state
->compression_buffer
)) != 0)
1209 DBG(debug("compression: raw %d compressed %zd", len
,
1210 sshbuf_len(state
->outgoing_packet
)));
1213 /* sizeof (packet_len + pad_len + payload) */
1214 len
= sshbuf_len(state
->outgoing_packet
);
1217 * calc size of padding, alloc space, get random data,
1218 * minimum padding is 4 bytes
1220 len
-= aadlen
; /* packet length is not encrypted for EtM modes */
1221 padlen
= block_size
- (len
% block_size
);
1223 padlen
+= block_size
;
1224 if (state
->extra_pad
) {
1225 tmp
= state
->extra_pad
;
1227 ROUNDUP(state
->extra_pad
, block_size
);
1228 /* check if roundup overflowed */
1229 if (state
->extra_pad
< tmp
)
1230 return SSH_ERR_INVALID_ARGUMENT
;
1231 tmp
= (len
+ padlen
) % state
->extra_pad
;
1232 /* Check whether pad calculation below will underflow */
1233 if (tmp
> state
->extra_pad
)
1234 return SSH_ERR_INVALID_ARGUMENT
;
1235 pad
= state
->extra_pad
- tmp
;
1236 DBG(debug3_f("adding %d (len %d padlen %d extra_pad %d)",
1237 pad
, len
, padlen
, state
->extra_pad
));
1240 /* Check whether padlen calculation overflowed */
1242 return SSH_ERR_INVALID_ARGUMENT
; /* overflow */
1243 state
->extra_pad
= 0;
1245 if ((r
= sshbuf_reserve(state
->outgoing_packet
, padlen
, &cp
)) != 0)
1247 if (enc
&& !cipher_ctx_is_plaintext(state
->send_context
)) {
1248 /* random padding */
1249 arc4random_buf(cp
, padlen
);
1252 explicit_bzero(cp
, padlen
);
1254 /* sizeof (packet_len + pad_len + payload + padding) */
1255 len
= sshbuf_len(state
->outgoing_packet
);
1256 cp
= sshbuf_mutable_ptr(state
->outgoing_packet
);
1258 r
= SSH_ERR_INTERNAL_ERROR
;
1261 /* packet_length includes payload, padding and padding length field */
1262 POKE_U32(cp
, len
- 4);
1264 DBG(debug("send: len %d (includes padlen %d, aadlen %d)",
1265 len
, padlen
, aadlen
));
1267 /* compute MAC over seqnr and packet(length fields, payload, padding) */
1268 if (mac
&& mac
->enabled
&& !mac
->etm
) {
1269 if ((r
= mac_compute(mac
, state
->p_send
.seqnr
,
1270 sshbuf_ptr(state
->outgoing_packet
), len
,
1271 macbuf
, sizeof(macbuf
))) != 0)
1273 DBG(debug("done calc MAC out #%d", state
->p_send
.seqnr
));
1275 /* encrypt packet and append to output buffer. */
1276 if ((r
= sshbuf_reserve(state
->output
,
1277 sshbuf_len(state
->outgoing_packet
) + authlen
, &cp
)) != 0)
1279 if ((r
= cipher_crypt(state
->send_context
, state
->p_send
.seqnr
, cp
,
1280 sshbuf_ptr(state
->outgoing_packet
),
1281 len
- aadlen
, aadlen
, authlen
)) != 0)
1283 /* append unencrypted MAC */
1284 if (mac
&& mac
->enabled
) {
1286 /* EtM: compute mac over aadlen + cipher text */
1287 if ((r
= mac_compute(mac
, state
->p_send
.seqnr
,
1288 cp
, len
, macbuf
, sizeof(macbuf
))) != 0)
1290 DBG(debug("done calc MAC(EtM) out #%d",
1291 state
->p_send
.seqnr
));
1293 if ((r
= sshbuf_put(state
->output
, macbuf
, mac
->mac_len
)) != 0)
1297 fprintf(stderr
, "encrypted: ");
1298 sshbuf_dump(state
->output
, stderr
);
1300 /* increment sequence number for outgoing packets */
1301 if (++state
->p_send
.seqnr
== 0) {
1302 if ((ssh
->kex
->flags
& KEX_INITIAL
) != 0) {
1303 ssh_packet_disconnect(ssh
, "outgoing sequence number "
1304 "wrapped during initial key exchange");
1306 logit("outgoing seqnr wraps around");
1308 if (++state
->p_send
.packets
== 0)
1309 if (!(ssh
->compat
& SSH_BUG_NOREKEY
))
1310 return SSH_ERR_NEED_REKEY
;
1311 state
->p_send
.blocks
+= len
/ block_size
;
1312 state
->p_send
.bytes
+= len
;
1313 sshbuf_reset(state
->outgoing_packet
);
1315 if (type
== SSH2_MSG_NEWKEYS
&& ssh
->kex
->kex_strict
) {
1316 debug_f("resetting send seqnr %u", state
->p_send
.seqnr
);
1317 state
->p_send
.seqnr
= 0;
1320 if (type
== SSH2_MSG_NEWKEYS
)
1321 r
= ssh_set_newkeys(ssh
, MODE_OUT
);
1322 else if (type
== SSH2_MSG_USERAUTH_SUCCESS
&& state
->server_side
)
1323 r
= ssh_packet_enable_delayed_compress(ssh
);
1330 /* returns non-zero if the specified packet type is usec by KEX */
1332 ssh_packet_type_is_kex(u_char type
)
1335 type
>= SSH2_MSG_TRANSPORT_MIN
&&
1336 type
<= SSH2_MSG_TRANSPORT_MAX
&&
1337 type
!= SSH2_MSG_SERVICE_REQUEST
&&
1338 type
!= SSH2_MSG_SERVICE_ACCEPT
&&
1339 type
!= SSH2_MSG_EXT_INFO
;
1343 ssh_packet_send2(struct ssh
*ssh
)
1345 struct session_state
*state
= ssh
->state
;
1350 if (sshbuf_len(state
->outgoing_packet
) < 6)
1351 return SSH_ERR_INTERNAL_ERROR
;
1352 type
= sshbuf_ptr(state
->outgoing_packet
)[5];
1353 need_rekey
= !ssh_packet_type_is_kex(type
) &&
1354 ssh_packet_need_rekeying(ssh
, sshbuf_len(state
->outgoing_packet
));
1357 * During rekeying we can only send key exchange messages.
1358 * Queue everything else.
1360 if ((need_rekey
|| state
->rekeying
) && !ssh_packet_type_is_kex(type
)) {
1362 debug3_f("rekex triggered");
1363 debug("enqueue packet: %u", type
);
1364 p
= calloc(1, sizeof(*p
));
1366 return SSH_ERR_ALLOC_FAIL
;
1368 p
->payload
= state
->outgoing_packet
;
1369 TAILQ_INSERT_TAIL(&state
->outgoing
, p
, next
);
1370 state
->outgoing_packet
= sshbuf_new();
1371 if (state
->outgoing_packet
== NULL
)
1372 return SSH_ERR_ALLOC_FAIL
;
1375 * This packet triggered a rekey, so send the
1377 * NB. reenters this function via kex_start_rekex().
1379 return kex_start_rekex(ssh
);
1384 /* rekeying starts with sending KEXINIT */
1385 if (type
== SSH2_MSG_KEXINIT
)
1386 state
->rekeying
= 1;
1388 if ((r
= ssh_packet_send2_wrapped(ssh
)) != 0)
1391 /* after a NEWKEYS message we can send the complete queue */
1392 if (type
== SSH2_MSG_NEWKEYS
) {
1393 state
->rekeying
= 0;
1394 state
->rekey_time
= monotime();
1395 while ((p
= TAILQ_FIRST(&state
->outgoing
))) {
1398 * If this packet triggers a rekex, then skip the
1399 * remaining packets in the queue for now.
1400 * NB. re-enters this function via kex_start_rekex.
1402 if (ssh_packet_need_rekeying(ssh
,
1403 sshbuf_len(p
->payload
))) {
1404 debug3_f("queued packet triggered rekex");
1405 return kex_start_rekex(ssh
);
1407 debug("dequeue packet: %u", type
);
1408 sshbuf_free(state
->outgoing_packet
);
1409 state
->outgoing_packet
= p
->payload
;
1410 TAILQ_REMOVE(&state
->outgoing
, p
, next
);
1411 memset(p
, 0, sizeof(*p
));
1413 if ((r
= ssh_packet_send2_wrapped(ssh
)) != 0)
1421 * Waits until a packet has been received, and returns its type. Note that
1422 * no other data is processed until this returns, so this function should not
1423 * be used during the interactive session.
1427 ssh_packet_read_seqnr(struct ssh
*ssh
, u_char
*typep
, u_int32_t
*seqnr_p
)
1429 struct session_state
*state
= ssh
->state
;
1430 int len
, r
, ms_remain
= 0;
1433 struct timeval start
;
1434 struct timespec timespec
, *timespecp
= NULL
;
1436 DBG(debug("packet_read()"));
1439 * Since we are blocking, ensure that all written packets have
1442 if ((r
= ssh_packet_write_wait(ssh
)) != 0)
1445 /* Stay in the loop until we have received a complete packet. */
1447 /* Try to read a packet from the buffer. */
1448 if ((r
= ssh_packet_read_poll_seqnr(ssh
, typep
, seqnr_p
)) != 0)
1450 /* If we got a packet, return it. */
1451 if (*typep
!= SSH_MSG_NONE
)
1454 * Otherwise, wait for some data to arrive, add it to the
1455 * buffer, and try again.
1457 pfd
.fd
= state
->connection_in
;
1458 pfd
.events
= POLLIN
;
1460 if (state
->packet_timeout_ms
> 0) {
1461 ms_remain
= state
->packet_timeout_ms
;
1462 timespecp
= ×pec
;
1464 /* Wait for some data to arrive. */
1466 if (state
->packet_timeout_ms
> 0) {
1467 ms_to_timespec(×pec
, ms_remain
);
1468 monotime_tv(&start
);
1470 if ((r
= ppoll(&pfd
, 1, timespecp
, NULL
)) >= 0)
1472 if (errno
!= EAGAIN
&& errno
!= EINTR
&&
1473 errno
!= EWOULDBLOCK
) {
1474 r
= SSH_ERR_SYSTEM_ERROR
;
1477 if (state
->packet_timeout_ms
<= 0)
1479 ms_subtract_diff(&start
, &ms_remain
);
1480 if (ms_remain
<= 0) {
1486 r
= SSH_ERR_CONN_TIMEOUT
;
1489 /* Read data from the socket. */
1490 len
= read(state
->connection_in
, buf
, sizeof(buf
));
1492 r
= SSH_ERR_CONN_CLOSED
;
1496 r
= SSH_ERR_SYSTEM_ERROR
;
1500 /* Append it to the buffer. */
1501 if ((r
= ssh_packet_process_incoming(ssh
, buf
, len
)) != 0)
1509 ssh_packet_read(struct ssh
*ssh
)
1514 if ((r
= ssh_packet_read_seqnr(ssh
, &type
, NULL
)) != 0)
1515 fatal_fr(r
, "read");
1520 ssh_packet_read_poll2_mux(struct ssh
*ssh
, u_char
*typep
, u_int32_t
*seqnr_p
)
1522 struct session_state
*state
= ssh
->state
;
1528 return SSH_ERR_INTERNAL_ERROR
;
1529 *typep
= SSH_MSG_NONE
;
1530 cp
= sshbuf_ptr(state
->input
);
1531 if (state
->packlen
== 0) {
1532 if (sshbuf_len(state
->input
) < 4 + 1)
1533 return 0; /* packet is incomplete */
1534 state
->packlen
= PEEK_U32(cp
);
1535 if (state
->packlen
< 4 + 1 ||
1536 state
->packlen
> PACKET_MAX_SIZE
)
1537 return SSH_ERR_MESSAGE_INCOMPLETE
;
1539 need
= state
->packlen
+ 4;
1540 if (sshbuf_len(state
->input
) < need
)
1541 return 0; /* packet is incomplete */
1542 sshbuf_reset(state
->incoming_packet
);
1543 if ((r
= sshbuf_put(state
->incoming_packet
, cp
+ 4,
1544 state
->packlen
)) != 0 ||
1545 (r
= sshbuf_consume(state
->input
, need
)) != 0 ||
1546 (r
= sshbuf_get_u8(state
->incoming_packet
, NULL
)) != 0 ||
1547 (r
= sshbuf_get_u8(state
->incoming_packet
, typep
)) != 0)
1549 if (ssh_packet_log_type(*typep
))
1550 debug3_f("type %u", *typep
);
1551 /* sshbuf_dump(state->incoming_packet, stderr); */
1552 /* reset for next packet */
1558 ssh_packet_read_poll2(struct ssh
*ssh
, u_char
*typep
, u_int32_t
*seqnr_p
)
1560 struct session_state
*state
= ssh
->state
;
1563 u_int maclen
, aadlen
= 0, authlen
= 0, block_size
;
1564 struct sshenc
*enc
= NULL
;
1565 struct sshmac
*mac
= NULL
;
1566 struct sshcomp
*comp
= NULL
;
1570 return ssh_packet_read_poll2_mux(ssh
, typep
, seqnr_p
);
1572 *typep
= SSH_MSG_NONE
;
1574 if (state
->packet_discard
)
1577 if (state
->newkeys
[MODE_IN
] != NULL
) {
1578 enc
= &state
->newkeys
[MODE_IN
]->enc
;
1579 mac
= &state
->newkeys
[MODE_IN
]->mac
;
1580 comp
= &state
->newkeys
[MODE_IN
]->comp
;
1581 /* disable mac for authenticated encryption */
1582 if ((authlen
= cipher_authlen(enc
->cipher
)) != 0)
1585 maclen
= mac
&& mac
->enabled
? mac
->mac_len
: 0;
1586 block_size
= enc
? enc
->block_size
: 8;
1587 aadlen
= (mac
&& mac
->enabled
&& mac
->etm
) || authlen
? 4 : 0;
1589 if (aadlen
&& state
->packlen
== 0) {
1590 if (cipher_get_length(state
->receive_context
,
1591 &state
->packlen
, state
->p_read
.seqnr
,
1592 sshbuf_ptr(state
->input
), sshbuf_len(state
->input
)) != 0)
1594 if (state
->packlen
< 1 + 4 ||
1595 state
->packlen
> PACKET_MAX_SIZE
) {
1597 sshbuf_dump(state
->input
, stderr
);
1599 logit("Bad packet length %u.", state
->packlen
);
1600 if ((r
= sshpkt_disconnect(ssh
, "Packet corrupt")) != 0)
1602 return SSH_ERR_CONN_CORRUPT
;
1604 sshbuf_reset(state
->incoming_packet
);
1605 } else if (state
->packlen
== 0) {
1607 * check if input size is less than the cipher block size,
1608 * decrypt first block and extract length of incoming packet
1610 if (sshbuf_len(state
->input
) < block_size
)
1612 sshbuf_reset(state
->incoming_packet
);
1613 if ((r
= sshbuf_reserve(state
->incoming_packet
, block_size
,
1616 if ((r
= cipher_crypt(state
->receive_context
,
1617 state
->p_send
.seqnr
, cp
, sshbuf_ptr(state
->input
),
1618 block_size
, 0, 0)) != 0)
1620 state
->packlen
= PEEK_U32(sshbuf_ptr(state
->incoming_packet
));
1621 if (state
->packlen
< 1 + 4 ||
1622 state
->packlen
> PACKET_MAX_SIZE
) {
1624 fprintf(stderr
, "input: \n");
1625 sshbuf_dump(state
->input
, stderr
);
1626 fprintf(stderr
, "incoming_packet: \n");
1627 sshbuf_dump(state
->incoming_packet
, stderr
);
1629 logit("Bad packet length %u.", state
->packlen
);
1630 return ssh_packet_start_discard(ssh
, enc
, mac
, 0,
1633 if ((r
= sshbuf_consume(state
->input
, block_size
)) != 0)
1636 DBG(debug("input: packet len %u", state
->packlen
+4));
1639 /* only the payload is encrypted */
1640 need
= state
->packlen
;
1643 * the payload size and the payload are encrypted, but we
1644 * have a partial packet of block_size bytes
1646 need
= 4 + state
->packlen
- block_size
;
1648 DBG(debug("partial packet: block %d, need %d, maclen %d, authlen %d,"
1649 " aadlen %d", block_size
, need
, maclen
, authlen
, aadlen
));
1650 if (need
% block_size
!= 0) {
1651 logit("padding error: need %d block %d mod %d",
1652 need
, block_size
, need
% block_size
);
1653 return ssh_packet_start_discard(ssh
, enc
, mac
, 0,
1654 PACKET_MAX_SIZE
- block_size
);
1657 * check if the entire packet has been received and
1658 * decrypt into incoming_packet:
1659 * 'aadlen' bytes are unencrypted, but authenticated.
1660 * 'need' bytes are encrypted, followed by either
1661 * 'authlen' bytes of authentication tag or
1662 * 'maclen' bytes of message authentication code.
1664 if (sshbuf_len(state
->input
) < aadlen
+ need
+ authlen
+ maclen
)
1665 return 0; /* packet is incomplete */
1667 fprintf(stderr
, "read_poll enc/full: ");
1668 sshbuf_dump(state
->input
, stderr
);
1670 /* EtM: check mac over encrypted input */
1671 if (mac
&& mac
->enabled
&& mac
->etm
) {
1672 if ((r
= mac_check(mac
, state
->p_read
.seqnr
,
1673 sshbuf_ptr(state
->input
), aadlen
+ need
,
1674 sshbuf_ptr(state
->input
) + aadlen
+ need
+ authlen
,
1676 if (r
== SSH_ERR_MAC_INVALID
)
1677 logit("Corrupted MAC on input.");
1681 if ((r
= sshbuf_reserve(state
->incoming_packet
, aadlen
+ need
,
1684 if ((r
= cipher_crypt(state
->receive_context
, state
->p_read
.seqnr
, cp
,
1685 sshbuf_ptr(state
->input
), need
, aadlen
, authlen
)) != 0)
1687 if ((r
= sshbuf_consume(state
->input
, aadlen
+ need
+ authlen
)) != 0)
1689 if (mac
&& mac
->enabled
) {
1690 /* Not EtM: check MAC over cleartext */
1691 if (!mac
->etm
&& (r
= mac_check(mac
, state
->p_read
.seqnr
,
1692 sshbuf_ptr(state
->incoming_packet
),
1693 sshbuf_len(state
->incoming_packet
),
1694 sshbuf_ptr(state
->input
), maclen
)) != 0) {
1695 if (r
!= SSH_ERR_MAC_INVALID
)
1697 logit("Corrupted MAC on input.");
1698 if (need
+ block_size
> PACKET_MAX_SIZE
)
1699 return SSH_ERR_INTERNAL_ERROR
;
1700 return ssh_packet_start_discard(ssh
, enc
, mac
,
1701 sshbuf_len(state
->incoming_packet
),
1702 PACKET_MAX_SIZE
- need
- block_size
);
1704 /* Remove MAC from input buffer */
1705 DBG(debug("MAC #%d ok", state
->p_read
.seqnr
));
1706 if ((r
= sshbuf_consume(state
->input
, mac
->mac_len
)) != 0)
1710 if (seqnr_p
!= NULL
)
1711 *seqnr_p
= state
->p_read
.seqnr
;
1712 if (++state
->p_read
.seqnr
== 0) {
1713 if ((ssh
->kex
->flags
& KEX_INITIAL
) != 0) {
1714 ssh_packet_disconnect(ssh
, "incoming sequence number "
1715 "wrapped during initial key exchange");
1717 logit("incoming seqnr wraps around");
1719 if (++state
->p_read
.packets
== 0)
1720 if (!(ssh
->compat
& SSH_BUG_NOREKEY
))
1721 return SSH_ERR_NEED_REKEY
;
1722 state
->p_read
.blocks
+= (state
->packlen
+ 4) / block_size
;
1723 state
->p_read
.bytes
+= state
->packlen
+ 4;
1726 padlen
= sshbuf_ptr(state
->incoming_packet
)[4];
1727 DBG(debug("input: padlen %d", padlen
));
1729 if ((r
= sshpkt_disconnect(ssh
,
1730 "Corrupted padlen %d on input.", padlen
)) != 0 ||
1731 (r
= ssh_packet_write_wait(ssh
)) != 0)
1733 return SSH_ERR_CONN_CORRUPT
;
1736 /* skip packet size + padlen, discard padding */
1737 if ((r
= sshbuf_consume(state
->incoming_packet
, 4 + 1)) != 0 ||
1738 ((r
= sshbuf_consume_end(state
->incoming_packet
, padlen
)) != 0))
1741 DBG(debug("input: len before de-compress %zd",
1742 sshbuf_len(state
->incoming_packet
)));
1743 if (comp
&& comp
->enabled
) {
1744 sshbuf_reset(state
->compression_buffer
);
1745 if ((r
= uncompress_buffer(ssh
, state
->incoming_packet
,
1746 state
->compression_buffer
)) != 0)
1748 sshbuf_reset(state
->incoming_packet
);
1749 if ((r
= sshbuf_putb(state
->incoming_packet
,
1750 state
->compression_buffer
)) != 0)
1752 DBG(debug("input: len after de-compress %zd",
1753 sshbuf_len(state
->incoming_packet
)));
1756 * get packet type, implies consume.
1757 * return length of payload (without type field)
1759 if ((r
= sshbuf_get_u8(state
->incoming_packet
, typep
)) != 0)
1761 if (ssh_packet_log_type(*typep
))
1762 debug3("receive packet: type %u", *typep
);
1763 if (*typep
< SSH2_MSG_MIN
) {
1764 if ((r
= sshpkt_disconnect(ssh
,
1765 "Invalid ssh2 packet type: %d", *typep
)) != 0 ||
1766 (r
= ssh_packet_write_wait(ssh
)) != 0)
1768 return SSH_ERR_PROTOCOL_ERROR
;
1770 if (state
->hook_in
!= NULL
&&
1771 (r
= state
->hook_in(ssh
, state
->incoming_packet
, typep
,
1772 state
->hook_in_ctx
)) != 0)
1774 if (*typep
== SSH2_MSG_USERAUTH_SUCCESS
&& !state
->server_side
)
1775 r
= ssh_packet_enable_delayed_compress(ssh
);
1779 fprintf(stderr
, "read/plain[%d]:\r\n", *typep
);
1780 sshbuf_dump(state
->incoming_packet
, stderr
);
1782 /* reset for next packet */
1784 if (*typep
== SSH2_MSG_NEWKEYS
&& ssh
->kex
->kex_strict
) {
1785 debug_f("resetting read seqnr %u", state
->p_read
.seqnr
);
1786 state
->p_read
.seqnr
= 0;
1789 if ((r
= ssh_packet_check_rekey(ssh
)) != 0)
1796 ssh_packet_read_poll_seqnr(struct ssh
*ssh
, u_char
*typep
, u_int32_t
*seqnr_p
)
1798 struct session_state
*state
= ssh
->state
;
1799 u_int reason
, seqnr
;
1807 r
= ssh_packet_read_poll2(ssh
, typep
, seqnr_p
);
1811 /* no message ready */
1814 state
->keep_alive_timeouts
= 0;
1815 DBG(debug("received packet type %d", *typep
));
1817 /* Always process disconnect messages */
1818 if (*typep
== SSH2_MSG_DISCONNECT
) {
1819 if ((r
= sshpkt_get_u32(ssh
, &reason
)) != 0 ||
1820 (r
= sshpkt_get_string(ssh
, &msg
, NULL
)) != 0)
1822 /* Ignore normal client exit notifications */
1823 do_log2(ssh
->state
->server_side
&&
1824 reason
== SSH2_DISCONNECT_BY_APPLICATION
?
1825 SYSLOG_LEVEL_INFO
: SYSLOG_LEVEL_ERROR
,
1826 "Received disconnect from %s port %d:"
1827 "%u: %.400s", ssh_remote_ipaddr(ssh
),
1828 ssh_remote_port(ssh
), reason
, msg
);
1830 return SSH_ERR_DISCONNECTED
;
1834 * Do not implicitly handle any messages here during initial
1835 * KEX when in strict mode. They will be need to be allowed
1836 * explicitly by the KEX dispatch table or they will generate
1839 if (ssh
->kex
!= NULL
&&
1840 (ssh
->kex
->flags
& KEX_INITIAL
) && ssh
->kex
->kex_strict
)
1842 /* Implicitly handle transport-level messages */
1844 case SSH2_MSG_IGNORE
:
1845 debug3("Received SSH2_MSG_IGNORE");
1847 case SSH2_MSG_DEBUG
:
1848 if ((r
= sshpkt_get_u8(ssh
, NULL
)) != 0 ||
1849 (r
= sshpkt_get_string(ssh
, &msg
, NULL
)) != 0 ||
1850 (r
= sshpkt_get_string(ssh
, NULL
, NULL
)) != 0) {
1854 debug("Remote: %.900s", msg
);
1857 case SSH2_MSG_UNIMPLEMENTED
:
1858 if ((r
= sshpkt_get_u32(ssh
, &seqnr
)) != 0)
1860 debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1864 if ((r
= sshpkt_get_string_direct(ssh
, &d
, &len
)) != 0)
1866 DBG(debug("Received SSH2_MSG_PING len %zu", len
));
1867 if ((r
= sshpkt_start(ssh
, SSH2_MSG_PONG
)) != 0 ||
1868 (r
= sshpkt_put_string(ssh
, d
, len
)) != 0 ||
1869 (r
= sshpkt_send(ssh
)) != 0)
1873 if ((r
= sshpkt_get_string_direct(ssh
,
1876 DBG(debug("Received SSH2_MSG_PONG len %zu", len
));
1885 * Buffers the supplied input data. This is intended to be used together
1886 * with packet_read_poll().
1889 ssh_packet_process_incoming(struct ssh
*ssh
, const char *buf
, u_int len
)
1891 struct session_state
*state
= ssh
->state
;
1894 if (state
->packet_discard
) {
1895 state
->keep_alive_timeouts
= 0; /* ?? */
1896 if (len
>= state
->packet_discard
) {
1897 if ((r
= ssh_packet_stop_discard(ssh
)) != 0)
1900 state
->packet_discard
-= len
;
1903 if ((r
= sshbuf_put(state
->input
, buf
, len
)) != 0)
1909 /* Reads and buffers data from the specified fd */
1911 ssh_packet_process_read(struct ssh
*ssh
, int fd
)
1913 struct session_state
*state
= ssh
->state
;
1917 if ((r
= sshbuf_read(fd
, state
->input
, PACKET_MAX_SIZE
, &rlen
)) != 0)
1920 if (state
->packet_discard
) {
1921 if ((r
= sshbuf_consume_end(state
->input
, rlen
)) != 0)
1923 state
->keep_alive_timeouts
= 0; /* ?? */
1924 if (rlen
>= state
->packet_discard
) {
1925 if ((r
= ssh_packet_stop_discard(ssh
)) != 0)
1928 state
->packet_discard
-= rlen
;
1935 ssh_packet_remaining(struct ssh
*ssh
)
1937 return sshbuf_len(ssh
->state
->incoming_packet
);
1941 * Sends a diagnostic message from the server to the client. This message
1942 * can be sent at any time (but not while constructing another message). The
1943 * message is printed immediately, but only if the client is being executed
1944 * in verbose mode. These messages are primarily intended to ease debugging
1945 * authentication problems. The length of the formatted message must not
1946 * exceed 1024 bytes. This will automatically call ssh_packet_write_wait.
1949 ssh_packet_send_debug(struct ssh
*ssh
, const char *fmt
,...)
1955 if ((ssh
->compat
& SSH_BUG_DEBUG
))
1958 va_start(args
, fmt
);
1959 vsnprintf(buf
, sizeof(buf
), fmt
, args
);
1962 debug3("sending debug message: %s", buf
);
1964 if ((r
= sshpkt_start(ssh
, SSH2_MSG_DEBUG
)) != 0 ||
1965 (r
= sshpkt_put_u8(ssh
, 0)) != 0 || /* always display */
1966 (r
= sshpkt_put_cstring(ssh
, buf
)) != 0 ||
1967 (r
= sshpkt_put_cstring(ssh
, "")) != 0 ||
1968 (r
= sshpkt_send(ssh
)) != 0 ||
1969 (r
= ssh_packet_write_wait(ssh
)) != 0)
1970 fatal_fr(r
, "send DEBUG");
1974 sshpkt_fmt_connection_id(struct ssh
*ssh
, char *s
, size_t l
)
1976 snprintf(s
, l
, "%.200s%s%s port %d",
1977 ssh
->log_preamble
? ssh
->log_preamble
: "",
1978 ssh
->log_preamble
? " " : "",
1979 ssh_remote_ipaddr(ssh
), ssh_remote_port(ssh
));
1983 * Pretty-print connection-terminating errors and exit.
1986 sshpkt_vfatal(struct ssh
*ssh
, int r
, const char *fmt
, va_list ap
)
1988 char *tag
= NULL
, remote_id
[512];
1991 sshpkt_fmt_connection_id(ssh
, remote_id
, sizeof(remote_id
));
1994 case SSH_ERR_CONN_CLOSED
:
1995 ssh_packet_clear_keys(ssh
);
1996 logdie("Connection closed by %s", remote_id
);
1997 case SSH_ERR_CONN_TIMEOUT
:
1998 ssh_packet_clear_keys(ssh
);
1999 logdie("Connection %s %s timed out",
2000 ssh
->state
->server_side
? "from" : "to", remote_id
);
2001 case SSH_ERR_DISCONNECTED
:
2002 ssh_packet_clear_keys(ssh
);
2003 logdie("Disconnected from %s", remote_id
);
2004 case SSH_ERR_SYSTEM_ERROR
:
2005 if (errno
== ECONNRESET
) {
2006 ssh_packet_clear_keys(ssh
);
2007 logdie("Connection reset by %s", remote_id
);
2010 case SSH_ERR_NO_CIPHER_ALG_MATCH
:
2011 case SSH_ERR_NO_MAC_ALG_MATCH
:
2012 case SSH_ERR_NO_COMPRESS_ALG_MATCH
:
2013 case SSH_ERR_NO_KEX_ALG_MATCH
:
2014 case SSH_ERR_NO_HOSTKEY_ALG_MATCH
:
2015 if (ssh
->kex
&& ssh
->kex
->failed_choice
) {
2016 ssh_packet_clear_keys(ssh
);
2018 logdie("Unable to negotiate with %s: %s. "
2019 "Their offer: %s", remote_id
, ssh_err(r
),
2020 ssh
->kex
->failed_choice
);
2024 if (vasprintf(&tag
, fmt
, ap
) == -1) {
2025 ssh_packet_clear_keys(ssh
);
2026 logdie_f("could not allocate failure message");
2028 ssh_packet_clear_keys(ssh
);
2030 logdie_r(r
, "%s%sConnection %s %s",
2031 tag
!= NULL
? tag
: "", tag
!= NULL
? ": " : "",
2032 ssh
->state
->server_side
? "from" : "to", remote_id
);
2037 sshpkt_fatal(struct ssh
*ssh
, int r
, const char *fmt
, ...)
2042 sshpkt_vfatal(ssh
, r
, fmt
, ap
);
2045 logdie_f("should have exited");
2049 * Logs the error plus constructs and sends a disconnect packet, closes the
2050 * connection, and exits. This function never returns. The error message
2051 * should not contain a newline. The length of the formatted message must
2052 * not exceed 1024 bytes.
2055 ssh_packet_disconnect(struct ssh
*ssh
, const char *fmt
,...)
2057 char buf
[1024], remote_id
[512];
2059 static int disconnecting
= 0;
2062 if (disconnecting
) /* Guard against recursive invocations. */
2063 fatal("packet_disconnect called recursively.");
2067 * Format the message. Note that the caller must make sure the
2068 * message is of limited size.
2070 sshpkt_fmt_connection_id(ssh
, remote_id
, sizeof(remote_id
));
2071 va_start(args
, fmt
);
2072 vsnprintf(buf
, sizeof(buf
), fmt
, args
);
2075 /* Display the error locally */
2076 logit("Disconnecting %s: %.100s", remote_id
, buf
);
2079 * Send the disconnect message to the other side, and wait
2080 * for it to get sent.
2082 if ((r
= sshpkt_disconnect(ssh
, "%s", buf
)) != 0)
2083 sshpkt_fatal(ssh
, r
, "%s", __func__
);
2085 if ((r
= ssh_packet_write_wait(ssh
)) != 0)
2086 sshpkt_fatal(ssh
, r
, "%s", __func__
);
2088 /* Close the connection. */
2089 ssh_packet_close(ssh
);
2094 * Checks if there is any buffered output, and tries to write some of
2098 ssh_packet_write_poll(struct ssh
*ssh
)
2100 struct session_state
*state
= ssh
->state
;
2101 int len
= sshbuf_len(state
->output
);
2105 len
= write(state
->connection_out
,
2106 sshbuf_ptr(state
->output
), len
);
2108 if (errno
== EINTR
|| errno
== EAGAIN
||
2109 errno
== EWOULDBLOCK
)
2111 return SSH_ERR_SYSTEM_ERROR
;
2114 return SSH_ERR_CONN_CLOSED
;
2115 if ((r
= sshbuf_consume(state
->output
, len
)) != 0)
2122 * Calls packet_write_poll repeatedly until all pending output data has been
2126 ssh_packet_write_wait(struct ssh
*ssh
)
2128 int ret
, r
, ms_remain
= 0;
2129 struct timeval start
;
2130 struct timespec timespec
, *timespecp
= NULL
;
2131 struct session_state
*state
= ssh
->state
;
2134 if ((r
= ssh_packet_write_poll(ssh
)) != 0)
2136 while (ssh_packet_have_data_to_write(ssh
)) {
2137 pfd
.fd
= state
->connection_out
;
2138 pfd
.events
= POLLOUT
;
2140 if (state
->packet_timeout_ms
> 0) {
2141 ms_remain
= state
->packet_timeout_ms
;
2142 timespecp
= ×pec
;
2145 if (state
->packet_timeout_ms
> 0) {
2146 ms_to_timespec(×pec
, ms_remain
);
2147 monotime_tv(&start
);
2149 if ((ret
= ppoll(&pfd
, 1, timespecp
, NULL
)) >= 0)
2151 if (errno
!= EAGAIN
&& errno
!= EINTR
&&
2152 errno
!= EWOULDBLOCK
)
2154 if (state
->packet_timeout_ms
<= 0)
2156 ms_subtract_diff(&start
, &ms_remain
);
2157 if (ms_remain
<= 0) {
2163 return SSH_ERR_CONN_TIMEOUT
;
2164 if ((r
= ssh_packet_write_poll(ssh
)) != 0)
2170 /* Returns true if there is buffered data to write to the connection. */
2173 ssh_packet_have_data_to_write(struct ssh
*ssh
)
2175 return sshbuf_len(ssh
->state
->output
) != 0;
2178 /* Returns true if there is not too much data to write to the connection. */
2181 ssh_packet_not_very_much_data_to_write(struct ssh
*ssh
)
2183 if (ssh
->state
->interactive_mode
)
2184 return sshbuf_len(ssh
->state
->output
) < 16384;
2186 return sshbuf_len(ssh
->state
->output
) < 128 * 1024;
2190 * returns true when there are at most a few keystrokes of data to write
2191 * and the connection is in interactive mode.
2195 ssh_packet_interactive_data_to_write(struct ssh
*ssh
)
2197 return ssh
->state
->interactive_mode
&&
2198 sshbuf_len(ssh
->state
->output
) < 256;
2202 ssh_packet_set_tos(struct ssh
*ssh
, int tos
)
2204 if (!ssh_packet_connection_is_on_socket(ssh
) || tos
== INT_MAX
)
2206 set_sock_tos(ssh
->state
->connection_in
, tos
);
2209 /* Informs that the current session is interactive. Sets IP flags for that. */
2212 ssh_packet_set_interactive(struct ssh
*ssh
, int interactive
, int qos_interactive
, int qos_bulk
)
2214 struct session_state
*state
= ssh
->state
;
2216 if (state
->set_interactive_called
)
2218 state
->set_interactive_called
= 1;
2220 /* Record that we are in interactive mode. */
2221 state
->interactive_mode
= interactive
;
2223 /* Only set socket options if using a socket. */
2224 if (!ssh_packet_connection_is_on_socket(ssh
))
2226 set_nodelay(state
->connection_in
);
2227 ssh_packet_set_tos(ssh
, interactive
? qos_interactive
: qos_bulk
);
2230 /* Returns true if the current connection is interactive. */
2233 ssh_packet_is_interactive(struct ssh
*ssh
)
2235 return ssh
->state
->interactive_mode
;
2239 ssh_packet_set_maxsize(struct ssh
*ssh
, u_int s
)
2241 struct session_state
*state
= ssh
->state
;
2243 if (state
->set_maxsize_called
) {
2244 logit_f("called twice: old %d new %d",
2245 state
->max_packet_size
, s
);
2248 if (s
< 4 * 1024 || s
> 1024 * 1024) {
2249 logit_f("bad size %d", s
);
2252 state
->set_maxsize_called
= 1;
2253 debug_f("setting to %d", s
);
2254 state
->max_packet_size
= s
;
2259 ssh_packet_inc_alive_timeouts(struct ssh
*ssh
)
2261 return ++ssh
->state
->keep_alive_timeouts
;
2265 ssh_packet_set_alive_timeouts(struct ssh
*ssh
, int ka
)
2267 ssh
->state
->keep_alive_timeouts
= ka
;
2271 ssh_packet_get_maxsize(struct ssh
*ssh
)
2273 return ssh
->state
->max_packet_size
;
2277 ssh_packet_set_rekey_limits(struct ssh
*ssh
, u_int64_t bytes
, u_int32_t seconds
)
2279 debug3("rekey after %llu bytes, %u seconds", (unsigned long long)bytes
,
2280 (unsigned int)seconds
);
2281 ssh
->state
->rekey_limit
= bytes
;
2282 ssh
->state
->rekey_interval
= seconds
;
2286 ssh_packet_get_rekey_timeout(struct ssh
*ssh
)
2290 seconds
= ssh
->state
->rekey_time
+ ssh
->state
->rekey_interval
-
2292 return (seconds
<= 0 ? 1 : seconds
);
2296 ssh_packet_set_server(struct ssh
*ssh
)
2298 ssh
->state
->server_side
= 1;
2299 ssh
->kex
->server
= 1; /* XXX unify? */
2303 ssh_packet_set_authenticated(struct ssh
*ssh
)
2305 ssh
->state
->after_authentication
= 1;
2309 ssh_packet_get_input(struct ssh
*ssh
)
2311 return (void *)ssh
->state
->input
;
2315 ssh_packet_get_output(struct ssh
*ssh
)
2317 return (void *)ssh
->state
->output
;
2320 /* Reset after_authentication and reset compression in post-auth privsep */
2322 ssh_packet_set_postauth(struct ssh
*ssh
)
2327 /* This was set in net child, but is not visible in user child */
2328 ssh
->state
->after_authentication
= 1;
2329 ssh
->state
->rekeying
= 0;
2330 if ((r
= ssh_packet_enable_delayed_compress(ssh
)) != 0)
2335 /* Packet state (de-)serialization for privsep */
2337 /* turn kex into a blob for packet state serialization */
2339 kex_to_blob(struct sshbuf
*m
, struct kex
*kex
)
2343 if ((r
= sshbuf_put_u32(m
, kex
->we_need
)) != 0 ||
2344 (r
= sshbuf_put_cstring(m
, kex
->hostkey_alg
)) != 0 ||
2345 (r
= sshbuf_put_u32(m
, kex
->hostkey_type
)) != 0 ||
2346 (r
= sshbuf_put_u32(m
, kex
->hostkey_nid
)) != 0 ||
2347 (r
= sshbuf_put_u32(m
, kex
->kex_type
)) != 0 ||
2348 (r
= sshbuf_put_u32(m
, kex
->kex_strict
)) != 0 ||
2349 (r
= sshbuf_put_stringb(m
, kex
->my
)) != 0 ||
2350 (r
= sshbuf_put_stringb(m
, kex
->peer
)) != 0 ||
2351 (r
= sshbuf_put_stringb(m
, kex
->client_version
)) != 0 ||
2352 (r
= sshbuf_put_stringb(m
, kex
->server_version
)) != 0 ||
2353 (r
= sshbuf_put_stringb(m
, kex
->session_id
)) != 0 ||
2354 (r
= sshbuf_put_u32(m
, kex
->flags
)) != 0)
2359 /* turn key exchange results into a blob for packet state serialization */
2361 newkeys_to_blob(struct sshbuf
*m
, struct ssh
*ssh
, int mode
)
2364 struct sshcipher_ctx
*cc
;
2365 struct sshcomp
*comp
;
2368 struct newkeys
*newkey
;
2371 if ((newkey
= ssh
->state
->newkeys
[mode
]) == NULL
)
2372 return SSH_ERR_INTERNAL_ERROR
;
2375 comp
= &newkey
->comp
;
2376 cc
= (mode
== MODE_OUT
) ? ssh
->state
->send_context
:
2377 ssh
->state
->receive_context
;
2378 if ((r
= cipher_get_keyiv(cc
, enc
->iv
, enc
->iv_len
)) != 0)
2380 if ((b
= sshbuf_new()) == NULL
)
2381 return SSH_ERR_ALLOC_FAIL
;
2382 if ((r
= sshbuf_put_cstring(b
, enc
->name
)) != 0 ||
2383 (r
= sshbuf_put_u32(b
, enc
->enabled
)) != 0 ||
2384 (r
= sshbuf_put_u32(b
, enc
->block_size
)) != 0 ||
2385 (r
= sshbuf_put_string(b
, enc
->key
, enc
->key_len
)) != 0 ||
2386 (r
= sshbuf_put_string(b
, enc
->iv
, enc
->iv_len
)) != 0)
2388 if (cipher_authlen(enc
->cipher
) == 0) {
2389 if ((r
= sshbuf_put_cstring(b
, mac
->name
)) != 0 ||
2390 (r
= sshbuf_put_u32(b
, mac
->enabled
)) != 0 ||
2391 (r
= sshbuf_put_string(b
, mac
->key
, mac
->key_len
)) != 0)
2394 if ((r
= sshbuf_put_u32(b
, comp
->type
)) != 0 ||
2395 (r
= sshbuf_put_cstring(b
, comp
->name
)) != 0)
2397 r
= sshbuf_put_stringb(m
, b
);
2403 /* serialize packet state into a blob */
2405 ssh_packet_get_state(struct ssh
*ssh
, struct sshbuf
*m
)
2407 struct session_state
*state
= ssh
->state
;
2410 if ((r
= kex_to_blob(m
, ssh
->kex
)) != 0 ||
2411 (r
= newkeys_to_blob(m
, ssh
, MODE_OUT
)) != 0 ||
2412 (r
= newkeys_to_blob(m
, ssh
, MODE_IN
)) != 0 ||
2413 (r
= sshbuf_put_u64(m
, state
->rekey_limit
)) != 0 ||
2414 (r
= sshbuf_put_u32(m
, state
->rekey_interval
)) != 0 ||
2415 (r
= sshbuf_put_u32(m
, state
->p_send
.seqnr
)) != 0 ||
2416 (r
= sshbuf_put_u64(m
, state
->p_send
.blocks
)) != 0 ||
2417 (r
= sshbuf_put_u32(m
, state
->p_send
.packets
)) != 0 ||
2418 (r
= sshbuf_put_u64(m
, state
->p_send
.bytes
)) != 0 ||
2419 (r
= sshbuf_put_u32(m
, state
->p_read
.seqnr
)) != 0 ||
2420 (r
= sshbuf_put_u64(m
, state
->p_read
.blocks
)) != 0 ||
2421 (r
= sshbuf_put_u32(m
, state
->p_read
.packets
)) != 0 ||
2422 (r
= sshbuf_put_u64(m
, state
->p_read
.bytes
)) != 0 ||
2423 (r
= sshbuf_put_stringb(m
, state
->input
)) != 0 ||
2424 (r
= sshbuf_put_stringb(m
, state
->output
)) != 0)
2430 /* restore key exchange results from blob for packet state de-serialization */
2432 newkeys_from_blob(struct sshbuf
*m
, struct ssh
*ssh
, int mode
)
2434 struct sshbuf
*b
= NULL
;
2435 struct sshcomp
*comp
;
2438 struct newkeys
*newkey
= NULL
;
2439 size_t keylen
, ivlen
, maclen
;
2442 if ((newkey
= calloc(1, sizeof(*newkey
))) == NULL
) {
2443 r
= SSH_ERR_ALLOC_FAIL
;
2446 if ((r
= sshbuf_froms(m
, &b
)) != 0)
2449 sshbuf_dump(b
, stderr
);
2453 comp
= &newkey
->comp
;
2455 if ((r
= sshbuf_get_cstring(b
, &enc
->name
, NULL
)) != 0 ||
2456 (r
= sshbuf_get_u32(b
, (u_int
*)&enc
->enabled
)) != 0 ||
2457 (r
= sshbuf_get_u32(b
, &enc
->block_size
)) != 0 ||
2458 (r
= sshbuf_get_string(b
, &enc
->key
, &keylen
)) != 0 ||
2459 (r
= sshbuf_get_string(b
, &enc
->iv
, &ivlen
)) != 0)
2461 if ((enc
->cipher
= cipher_by_name(enc
->name
)) == NULL
) {
2462 r
= SSH_ERR_INVALID_FORMAT
;
2465 if (cipher_authlen(enc
->cipher
) == 0) {
2466 if ((r
= sshbuf_get_cstring(b
, &mac
->name
, NULL
)) != 0)
2468 if ((r
= mac_setup(mac
, mac
->name
)) != 0)
2470 if ((r
= sshbuf_get_u32(b
, (u_int
*)&mac
->enabled
)) != 0 ||
2471 (r
= sshbuf_get_string(b
, &mac
->key
, &maclen
)) != 0)
2473 if (maclen
> mac
->key_len
) {
2474 r
= SSH_ERR_INVALID_FORMAT
;
2477 mac
->key_len
= maclen
;
2479 if ((r
= sshbuf_get_u32(b
, &comp
->type
)) != 0 ||
2480 (r
= sshbuf_get_cstring(b
, &comp
->name
, NULL
)) != 0)
2482 if (sshbuf_len(b
) != 0) {
2483 r
= SSH_ERR_INVALID_FORMAT
;
2486 enc
->key_len
= keylen
;
2487 enc
->iv_len
= ivlen
;
2488 ssh
->kex
->newkeys
[mode
] = newkey
;
2497 /* restore kex from blob for packet state de-serialization */
2499 kex_from_blob(struct sshbuf
*m
, struct kex
**kexp
)
2504 if ((kex
= kex_new()) == NULL
)
2505 return SSH_ERR_ALLOC_FAIL
;
2506 if ((r
= sshbuf_get_u32(m
, &kex
->we_need
)) != 0 ||
2507 (r
= sshbuf_get_cstring(m
, &kex
->hostkey_alg
, NULL
)) != 0 ||
2508 (r
= sshbuf_get_u32(m
, (u_int
*)&kex
->hostkey_type
)) != 0 ||
2509 (r
= sshbuf_get_u32(m
, (u_int
*)&kex
->hostkey_nid
)) != 0 ||
2510 (r
= sshbuf_get_u32(m
, &kex
->kex_type
)) != 0 ||
2511 (r
= sshbuf_get_u32(m
, &kex
->kex_strict
)) != 0 ||
2512 (r
= sshbuf_get_stringb(m
, kex
->my
)) != 0 ||
2513 (r
= sshbuf_get_stringb(m
, kex
->peer
)) != 0 ||
2514 (r
= sshbuf_get_stringb(m
, kex
->client_version
)) != 0 ||
2515 (r
= sshbuf_get_stringb(m
, kex
->server_version
)) != 0 ||
2516 (r
= sshbuf_get_stringb(m
, kex
->session_id
)) != 0 ||
2517 (r
= sshbuf_get_u32(m
, &kex
->flags
)) != 0)
2523 if (r
!= 0 || kexp
== NULL
) {
2535 * Restore packet state from content of blob 'm' (de-serialization).
2536 * Note that 'm' will be partially consumed on parsing or any other errors.
2539 ssh_packet_set_state(struct ssh
*ssh
, struct sshbuf
*m
)
2541 struct session_state
*state
= ssh
->state
;
2542 const u_char
*input
, *output
;
2546 if ((r
= kex_from_blob(m
, &ssh
->kex
)) != 0 ||
2547 (r
= newkeys_from_blob(m
, ssh
, MODE_OUT
)) != 0 ||
2548 (r
= newkeys_from_blob(m
, ssh
, MODE_IN
)) != 0 ||
2549 (r
= sshbuf_get_u64(m
, &state
->rekey_limit
)) != 0 ||
2550 (r
= sshbuf_get_u32(m
, &state
->rekey_interval
)) != 0 ||
2551 (r
= sshbuf_get_u32(m
, &state
->p_send
.seqnr
)) != 0 ||
2552 (r
= sshbuf_get_u64(m
, &state
->p_send
.blocks
)) != 0 ||
2553 (r
= sshbuf_get_u32(m
, &state
->p_send
.packets
)) != 0 ||
2554 (r
= sshbuf_get_u64(m
, &state
->p_send
.bytes
)) != 0 ||
2555 (r
= sshbuf_get_u32(m
, &state
->p_read
.seqnr
)) != 0 ||
2556 (r
= sshbuf_get_u64(m
, &state
->p_read
.blocks
)) != 0 ||
2557 (r
= sshbuf_get_u32(m
, &state
->p_read
.packets
)) != 0 ||
2558 (r
= sshbuf_get_u64(m
, &state
->p_read
.bytes
)) != 0)
2561 * We set the time here so that in post-auth privsep child we
2562 * count from the completion of the authentication.
2564 state
->rekey_time
= monotime();
2565 /* XXX ssh_set_newkeys overrides p_read.packets? XXX */
2566 if ((r
= ssh_set_newkeys(ssh
, MODE_IN
)) != 0 ||
2567 (r
= ssh_set_newkeys(ssh
, MODE_OUT
)) != 0)
2570 if ((r
= ssh_packet_set_postauth(ssh
)) != 0)
2573 sshbuf_reset(state
->input
);
2574 sshbuf_reset(state
->output
);
2575 if ((r
= sshbuf_get_string_direct(m
, &input
, &ilen
)) != 0 ||
2576 (r
= sshbuf_get_string_direct(m
, &output
, &olen
)) != 0 ||
2577 (r
= sshbuf_put(state
->input
, input
, ilen
)) != 0 ||
2578 (r
= sshbuf_put(state
->output
, output
, olen
)) != 0)
2582 return SSH_ERR_INVALID_FORMAT
;
2589 /* put data to the outgoing packet */
2592 sshpkt_put(struct ssh
*ssh
, const void *v
, size_t len
)
2594 return sshbuf_put(ssh
->state
->outgoing_packet
, v
, len
);
2598 sshpkt_putb(struct ssh
*ssh
, const struct sshbuf
*b
)
2600 return sshbuf_putb(ssh
->state
->outgoing_packet
, b
);
2604 sshpkt_put_u8(struct ssh
*ssh
, u_char val
)
2606 return sshbuf_put_u8(ssh
->state
->outgoing_packet
, val
);
2610 sshpkt_put_u32(struct ssh
*ssh
, u_int32_t val
)
2612 return sshbuf_put_u32(ssh
->state
->outgoing_packet
, val
);
2616 sshpkt_put_u64(struct ssh
*ssh
, u_int64_t val
)
2618 return sshbuf_put_u64(ssh
->state
->outgoing_packet
, val
);
2622 sshpkt_put_string(struct ssh
*ssh
, const void *v
, size_t len
)
2624 return sshbuf_put_string(ssh
->state
->outgoing_packet
, v
, len
);
2628 sshpkt_put_cstring(struct ssh
*ssh
, const void *v
)
2630 return sshbuf_put_cstring(ssh
->state
->outgoing_packet
, v
);
2634 sshpkt_put_stringb(struct ssh
*ssh
, const struct sshbuf
*v
)
2636 return sshbuf_put_stringb(ssh
->state
->outgoing_packet
, v
);
2640 #ifdef OPENSSL_HAS_ECC
2642 sshpkt_put_ec(struct ssh
*ssh
, const EC_POINT
*v
, const EC_GROUP
*g
)
2644 return sshbuf_put_ec(ssh
->state
->outgoing_packet
, v
, g
);
2648 sshpkt_put_ec_pkey(struct ssh
*ssh
, EVP_PKEY
*pkey
)
2650 return sshbuf_put_ec_pkey(ssh
->state
->outgoing_packet
, pkey
);
2652 #endif /* OPENSSL_HAS_ECC */
2655 sshpkt_put_bignum2(struct ssh
*ssh
, const BIGNUM
*v
)
2657 return sshbuf_put_bignum2(ssh
->state
->outgoing_packet
, v
);
2659 #endif /* WITH_OPENSSL */
2661 /* fetch data from the incoming packet */
2664 sshpkt_get(struct ssh
*ssh
, void *valp
, size_t len
)
2666 return sshbuf_get(ssh
->state
->incoming_packet
, valp
, len
);
2670 sshpkt_get_u8(struct ssh
*ssh
, u_char
*valp
)
2672 return sshbuf_get_u8(ssh
->state
->incoming_packet
, valp
);
2676 sshpkt_get_u32(struct ssh
*ssh
, u_int32_t
*valp
)
2678 return sshbuf_get_u32(ssh
->state
->incoming_packet
, valp
);
2682 sshpkt_get_u64(struct ssh
*ssh
, u_int64_t
*valp
)
2684 return sshbuf_get_u64(ssh
->state
->incoming_packet
, valp
);
2688 sshpkt_get_string(struct ssh
*ssh
, u_char
**valp
, size_t *lenp
)
2690 return sshbuf_get_string(ssh
->state
->incoming_packet
, valp
, lenp
);
2694 sshpkt_get_string_direct(struct ssh
*ssh
, const u_char
**valp
, size_t *lenp
)
2696 return sshbuf_get_string_direct(ssh
->state
->incoming_packet
, valp
, lenp
);
2700 sshpkt_peek_string_direct(struct ssh
*ssh
, const u_char
**valp
, size_t *lenp
)
2702 return sshbuf_peek_string_direct(ssh
->state
->incoming_packet
, valp
, lenp
);
2706 sshpkt_get_cstring(struct ssh
*ssh
, char **valp
, size_t *lenp
)
2708 return sshbuf_get_cstring(ssh
->state
->incoming_packet
, valp
, lenp
);
2712 sshpkt_getb_froms(struct ssh
*ssh
, struct sshbuf
**valp
)
2714 return sshbuf_froms(ssh
->state
->incoming_packet
, valp
);
2718 #ifdef OPENSSL_HAS_ECC
2720 sshpkt_get_ec(struct ssh
*ssh
, EC_POINT
*v
, const EC_GROUP
*g
)
2722 return sshbuf_get_ec(ssh
->state
->incoming_packet
, v
, g
);
2724 #endif /* OPENSSL_HAS_ECC */
2727 sshpkt_get_bignum2(struct ssh
*ssh
, BIGNUM
**valp
)
2729 return sshbuf_get_bignum2(ssh
->state
->incoming_packet
, valp
);
2731 #endif /* WITH_OPENSSL */
2734 sshpkt_get_end(struct ssh
*ssh
)
2736 if (sshbuf_len(ssh
->state
->incoming_packet
) > 0)
2737 return SSH_ERR_UNEXPECTED_TRAILING_DATA
;
2742 sshpkt_ptr(struct ssh
*ssh
, size_t *lenp
)
2745 *lenp
= sshbuf_len(ssh
->state
->incoming_packet
);
2746 return sshbuf_ptr(ssh
->state
->incoming_packet
);
2749 /* start a new packet */
2752 sshpkt_start(struct ssh
*ssh
, u_char type
)
2754 u_char buf
[6]; /* u32 packet length, u8 pad len, u8 type */
2756 DBG(debug("packet_start[%d]", type
));
2757 memset(buf
, 0, sizeof(buf
));
2758 buf
[sizeof(buf
) - 1] = type
;
2759 sshbuf_reset(ssh
->state
->outgoing_packet
);
2760 return sshbuf_put(ssh
->state
->outgoing_packet
, buf
, sizeof(buf
));
2764 ssh_packet_send_mux(struct ssh
*ssh
)
2766 struct session_state
*state
= ssh
->state
;
2772 return SSH_ERR_INTERNAL_ERROR
;
2773 len
= sshbuf_len(state
->outgoing_packet
);
2775 return SSH_ERR_INTERNAL_ERROR
;
2776 cp
= sshbuf_mutable_ptr(state
->outgoing_packet
);
2778 if (ssh_packet_log_type(type
))
2779 debug3_f("type %u", type
);
2780 /* drop everything, but the connection protocol */
2781 if (type
>= SSH2_MSG_CONNECTION_MIN
&&
2782 type
<= SSH2_MSG_CONNECTION_MAX
) {
2783 POKE_U32(cp
, len
- 4);
2784 if ((r
= sshbuf_putb(state
->output
,
2785 state
->outgoing_packet
)) != 0)
2787 /* sshbuf_dump(state->output, stderr); */
2789 sshbuf_reset(state
->outgoing_packet
);
2794 * 9.2. Ignored Data Message
2796 * byte SSH_MSG_IGNORE
2799 * All implementations MUST understand (and ignore) this message at any
2800 * time (after receiving the protocol version). No implementation is
2801 * required to send them. This message can be used as an additional
2802 * protection measure against advanced traffic analysis techniques.
2805 sshpkt_msg_ignore(struct ssh
*ssh
, u_int nbytes
)
2811 if ((r
= sshpkt_start(ssh
, SSH2_MSG_IGNORE
)) != 0 ||
2812 (r
= sshpkt_put_u32(ssh
, nbytes
)) != 0)
2814 for (i
= 0; i
< nbytes
; i
++) {
2817 if ((r
= sshpkt_put_u8(ssh
, (u_char
)rnd
& 0xff)) != 0)
2827 sshpkt_send(struct ssh
*ssh
)
2829 if (ssh
->state
&& ssh
->state
->mux
)
2830 return ssh_packet_send_mux(ssh
);
2831 return ssh_packet_send2(ssh
);
2835 sshpkt_disconnect(struct ssh
*ssh
, const char *fmt
,...)
2841 va_start(args
, fmt
);
2842 vsnprintf(buf
, sizeof(buf
), fmt
, args
);
2845 debug2_f("sending SSH2_MSG_DISCONNECT: %s", buf
);
2846 if ((r
= sshpkt_start(ssh
, SSH2_MSG_DISCONNECT
)) != 0 ||
2847 (r
= sshpkt_put_u32(ssh
, SSH2_DISCONNECT_PROTOCOL_ERROR
)) != 0 ||
2848 (r
= sshpkt_put_cstring(ssh
, buf
)) != 0 ||
2849 (r
= sshpkt_put_cstring(ssh
, "")) != 0 ||
2850 (r
= sshpkt_send(ssh
)) != 0)
2855 /* roundup current message to pad bytes */
2857 sshpkt_add_padding(struct ssh
*ssh
, u_char pad
)
2859 ssh
->state
->extra_pad
= pad
;