]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - crypto/openssh/packet.c
Upgrade to OpenSSH 7.5p1.
[FreeBSD/FreeBSD.git] / crypto / openssh / packet.c
1 /* $OpenBSD: packet.c,v 1.247 2017/03/11 13:07:35 markus Exp $ */
2 /*
3  * Author: Tatu Ylonen <ylo@cs.hut.fi>
4  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5  *                    All rights reserved
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.
8  *
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".
14  *
15  *
16  * SSH2 packet format added by Markus Friedl.
17  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
18  *
19  * Redistribution and use in source and binary forms, with or without
20  * modification, are permitted provided that the following conditions
21  * are met:
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.
27  *
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.
38  */
39
40 #include "includes.h"
41 __RCSID("$FreeBSD$");
42
43 #include <sys/types.h>
44 #include "openbsd-compat/sys-queue.h"
45 #include <sys/socket.h>
46 #ifdef HAVE_SYS_TIME_H
47 # include <sys/time.h>
48 #endif
49
50 #include <netinet/in.h>
51 #include <netinet/ip.h>
52 #include <arpa/inet.h>
53
54 #include <errno.h>
55 #include <netdb.h>
56 #include <stdarg.h>
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <string.h>
60 #include <unistd.h>
61 #include <limits.h>
62 #include <signal.h>
63 #include <time.h>
64
65 #include <zlib.h>
66
67 #include "buffer.h"     /* typedefs XXX */
68 #include "key.h"        /* typedefs XXX */
69
70 #include "xmalloc.h"
71 #include "crc32.h"
72 #include "deattack.h"
73 #include "compat.h"
74 #include "ssh1.h"
75 #include "ssh2.h"
76 #include "cipher.h"
77 #include "sshkey.h"
78 #include "kex.h"
79 #include "digest.h"
80 #include "mac.h"
81 #include "log.h"
82 #include "canohost.h"
83 #include "misc.h"
84 #include "channels.h"
85 #include "ssh.h"
86 #include "packet.h"
87 #include "ssherr.h"
88 #include "sshbuf.h"
89 #include "blacklist_client.h"
90
91 #ifdef PACKET_DEBUG
92 #define DBG(x) x
93 #else
94 #define DBG(x)
95 #endif
96
97 #define PACKET_MAX_SIZE (256 * 1024)
98
99 struct packet_state {
100         u_int32_t seqnr;
101         u_int32_t packets;
102         u_int64_t blocks;
103         u_int64_t bytes;
104 };
105
106 struct packet {
107         TAILQ_ENTRY(packet) next;
108         u_char type;
109         struct sshbuf *payload;
110 };
111
112 struct session_state {
113         /*
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.
118          */
119         int connection_in;
120         int connection_out;
121
122         /* Protocol flags for the remote side. */
123         u_int remote_protocol_flags;
124
125         /* Encryption context for receiving data.  Only used for decryption. */
126         struct sshcipher_ctx *receive_context;
127
128         /* Encryption context for sending data.  Only used for encryption. */
129         struct sshcipher_ctx *send_context;
130
131         /* Buffer for raw input data from the socket. */
132         struct sshbuf *input;
133
134         /* Buffer for raw output data going to the socket. */
135         struct sshbuf *output;
136
137         /* Buffer for the partial outgoing packet being constructed. */
138         struct sshbuf *outgoing_packet;
139
140         /* Buffer for the incoming packet currently being processed. */
141         struct sshbuf *incoming_packet;
142
143         /* Scratch buffer for packet compression/decompression. */
144         struct sshbuf *compression_buffer;
145
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;
153
154         /*
155          * Flag indicating whether packet compression/decompression is
156          * enabled.
157          */
158         int packet_compression;
159
160         /* default maximum packet size */
161         u_int max_packet_size;
162
163         /* Flag indicating whether this module has been initialized. */
164         int initialized;
165
166         /* Set to true if the connection is interactive. */
167         int interactive_mode;
168
169         /* Set to true if we are the server side. */
170         int server_side;
171
172         /* Set to true if we are authenticated. */
173         int after_authentication;
174
175         int keep_alive_timeouts;
176
177         /* The maximum time that we will wait to send or receive a packet */
178         int packet_timeout_ms;
179
180         /* Session key information for Encryption and MAC */
181         struct newkeys *newkeys[MODE_MAX];
182         struct packet_state p_read, p_send;
183
184         /* Volume-based rekeying */
185         u_int64_t max_blocks_in, max_blocks_out, rekey_limit;
186
187         /* Time-based rekeying */
188         u_int32_t rekey_interval;       /* how often in seconds */
189         time_t rekey_time;      /* time of last rekeying */
190
191         /* Session key for protocol v1 */
192         u_char ssh1_key[SSH_SESSION_KEY_LENGTH];
193         u_int ssh1_keylen;
194
195         /* roundup current message to extra_pad bytes */
196         u_char extra_pad;
197
198         /* XXX discard incoming data after MAC error */
199         u_int packet_discard;
200         size_t packet_discard_mac_already;
201         struct sshmac *packet_discard_mac;
202
203         /* Used in packet_read_poll2() */
204         u_int packlen;
205
206         /* Used in packet_send2 */
207         int rekeying;
208
209         /* Used in ssh_packet_send_mux() */
210         int mux;
211
212         /* Used in packet_set_interactive */
213         int set_interactive_called;
214
215         /* Used in packet_set_maxsize */
216         int set_maxsize_called;
217
218         /* One-off warning about weak ciphers */
219         int cipher_warning_done;
220
221         /* SSH1 CRC compensation attack detector */
222         struct deattack_ctx deattack;
223
224         /* Hook for fuzzing inbound packets */
225         ssh_packet_hook_fn *hook_in;
226         void *hook_in_ctx;
227
228         TAILQ_HEAD(, packet) outgoing;
229 };
230
231 struct ssh *
232 ssh_alloc_session_state(void)
233 {
234         struct ssh *ssh = NULL;
235         struct session_state *state = NULL;
236
237         if ((ssh = calloc(1, sizeof(*ssh))) == NULL ||
238             (state = calloc(1, sizeof(*state))) == NULL ||
239             (state->input = sshbuf_new()) == NULL ||
240             (state->output = sshbuf_new()) == NULL ||
241             (state->outgoing_packet = sshbuf_new()) == NULL ||
242             (state->incoming_packet = sshbuf_new()) == NULL)
243                 goto fail;
244         TAILQ_INIT(&state->outgoing);
245         TAILQ_INIT(&ssh->private_keys);
246         TAILQ_INIT(&ssh->public_keys);
247         state->connection_in = -1;
248         state->connection_out = -1;
249         state->max_packet_size = 32768;
250         state->packet_timeout_ms = -1;
251         state->p_send.packets = state->p_read.packets = 0;
252         state->initialized = 1;
253         /*
254          * ssh_packet_send2() needs to queue packets until
255          * we've done the initial key exchange.
256          */
257         state->rekeying = 1;
258         ssh->state = state;
259         return ssh;
260  fail:
261         if (state) {
262                 sshbuf_free(state->input);
263                 sshbuf_free(state->output);
264                 sshbuf_free(state->incoming_packet);
265                 sshbuf_free(state->outgoing_packet);
266                 free(state);
267         }
268         free(ssh);
269         return NULL;
270 }
271
272 void
273 ssh_packet_set_input_hook(struct ssh *ssh, ssh_packet_hook_fn *hook, void *ctx)
274 {
275         ssh->state->hook_in = hook;
276         ssh->state->hook_in_ctx = ctx;
277 }
278
279 /* Returns nonzero if rekeying is in progress */
280 int
281 ssh_packet_is_rekeying(struct ssh *ssh)
282 {
283         return compat20 &&
284             (ssh->state->rekeying || (ssh->kex != NULL && ssh->kex->done == 0));
285 }
286
287 /*
288  * Sets the descriptors used for communication.  Disables encryption until
289  * packet_set_encryption_key is called.
290  */
291 struct ssh *
292 ssh_packet_set_connection(struct ssh *ssh, int fd_in, int fd_out)
293 {
294         struct session_state *state;
295         const struct sshcipher *none = cipher_by_name("none");
296         int r;
297
298         if (none == NULL) {
299                 error("%s: cannot load cipher 'none'", __func__);
300                 return NULL;
301         }
302         if (ssh == NULL)
303                 ssh = ssh_alloc_session_state();
304         if (ssh == NULL) {
305                 error("%s: cound not allocate state", __func__);
306                 return NULL;
307         }
308         state = ssh->state;
309         state->connection_in = fd_in;
310         state->connection_out = fd_out;
311         if ((r = cipher_init(&state->send_context, none,
312             (const u_char *)"", 0, NULL, 0, CIPHER_ENCRYPT)) != 0 ||
313             (r = cipher_init(&state->receive_context, none,
314             (const u_char *)"", 0, NULL, 0, CIPHER_DECRYPT)) != 0) {
315                 error("%s: cipher_init failed: %s", __func__, ssh_err(r));
316                 free(ssh); /* XXX need ssh_free_session_state? */
317                 return NULL;
318         }
319         state->newkeys[MODE_IN] = state->newkeys[MODE_OUT] = NULL;
320         deattack_init(&state->deattack);
321         /*
322          * Cache the IP address of the remote connection for use in error
323          * messages that might be generated after the connection has closed.
324          */
325         (void)ssh_remote_ipaddr(ssh);
326         return ssh;
327 }
328
329 void
330 ssh_packet_set_timeout(struct ssh *ssh, int timeout, int count)
331 {
332         struct session_state *state = ssh->state;
333
334         if (timeout <= 0 || count <= 0) {
335                 state->packet_timeout_ms = -1;
336                 return;
337         }
338         if ((INT_MAX / 1000) / count < timeout)
339                 state->packet_timeout_ms = INT_MAX;
340         else
341                 state->packet_timeout_ms = timeout * count * 1000;
342 }
343
344 void
345 ssh_packet_set_mux(struct ssh *ssh)
346 {
347         ssh->state->mux = 1;
348         ssh->state->rekeying = 0;
349 }
350
351 int
352 ssh_packet_get_mux(struct ssh *ssh)
353 {
354         return ssh->state->mux;
355 }
356
357 int
358 ssh_packet_set_log_preamble(struct ssh *ssh, const char *fmt, ...)
359 {
360         va_list args;
361         int r;
362
363         free(ssh->log_preamble);
364         if (fmt == NULL)
365                 ssh->log_preamble = NULL;
366         else {
367                 va_start(args, fmt);
368                 r = vasprintf(&ssh->log_preamble, fmt, args);
369                 va_end(args);
370                 if (r < 0 || ssh->log_preamble == NULL)
371                         return SSH_ERR_ALLOC_FAIL;
372         }
373         return 0;
374 }
375
376 int
377 ssh_packet_stop_discard(struct ssh *ssh)
378 {
379         struct session_state *state = ssh->state;
380         int r;
381
382         if (state->packet_discard_mac) {
383                 char buf[1024];
384                 size_t dlen = PACKET_MAX_SIZE;
385
386                 if (dlen > state->packet_discard_mac_already)
387                         dlen -= state->packet_discard_mac_already;
388                 memset(buf, 'a', sizeof(buf));
389                 while (sshbuf_len(state->incoming_packet) < dlen)
390                         if ((r = sshbuf_put(state->incoming_packet, buf,
391                             sizeof(buf))) != 0)
392                                 return r;
393                 (void) mac_compute(state->packet_discard_mac,
394                     state->p_read.seqnr,
395                     sshbuf_ptr(state->incoming_packet), dlen,
396                     NULL, 0);
397         }
398         logit("Finished discarding for %.200s port %d",
399             ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
400         return SSH_ERR_MAC_INVALID;
401 }
402
403 static int
404 ssh_packet_start_discard(struct ssh *ssh, struct sshenc *enc,
405     struct sshmac *mac, size_t mac_already, u_int discard)
406 {
407         struct session_state *state = ssh->state;
408         int r;
409
410         if (enc == NULL || !cipher_is_cbc(enc->cipher) || (mac && mac->etm)) {
411                 if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0)
412                         return r;
413                 return SSH_ERR_MAC_INVALID;
414         }
415         /*
416          * Record number of bytes over which the mac has already
417          * been computed in order to minimize timing attacks.
418          */
419         if (mac && mac->enabled) {
420                 state->packet_discard_mac = mac;
421                 state->packet_discard_mac_already = mac_already;
422         }
423         if (sshbuf_len(state->input) >= discard)
424                 return ssh_packet_stop_discard(ssh);
425         state->packet_discard = discard - sshbuf_len(state->input);
426         return 0;
427 }
428
429 /* Returns 1 if remote host is connected via socket, 0 if not. */
430
431 int
432 ssh_packet_connection_is_on_socket(struct ssh *ssh)
433 {
434         struct session_state *state = ssh->state;
435         struct sockaddr_storage from, to;
436         socklen_t fromlen, tolen;
437
438         if (state->connection_in == -1 || state->connection_out == -1)
439                 return 0;
440
441         /* filedescriptors in and out are the same, so it's a socket */
442         if (state->connection_in == state->connection_out)
443                 return 1;
444         fromlen = sizeof(from);
445         memset(&from, 0, sizeof(from));
446         if (getpeername(state->connection_in, (struct sockaddr *)&from,
447             &fromlen) < 0)
448                 return 0;
449         tolen = sizeof(to);
450         memset(&to, 0, sizeof(to));
451         if (getpeername(state->connection_out, (struct sockaddr *)&to,
452             &tolen) < 0)
453                 return 0;
454         if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
455                 return 0;
456         if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
457                 return 0;
458         return 1;
459 }
460
461 void
462 ssh_packet_get_bytes(struct ssh *ssh, u_int64_t *ibytes, u_int64_t *obytes)
463 {
464         if (ibytes)
465                 *ibytes = ssh->state->p_read.bytes;
466         if (obytes)
467                 *obytes = ssh->state->p_send.bytes;
468 }
469
470 int
471 ssh_packet_connection_af(struct ssh *ssh)
472 {
473         struct sockaddr_storage to;
474         socklen_t tolen = sizeof(to);
475
476         memset(&to, 0, sizeof(to));
477         if (getsockname(ssh->state->connection_out, (struct sockaddr *)&to,
478             &tolen) < 0)
479                 return 0;
480 #ifdef IPV4_IN_IPV6
481         if (to.ss_family == AF_INET6 &&
482             IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&to)->sin6_addr))
483                 return AF_INET;
484 #endif
485         return to.ss_family;
486 }
487
488 /* Sets the connection into non-blocking mode. */
489
490 void
491 ssh_packet_set_nonblocking(struct ssh *ssh)
492 {
493         /* Set the socket into non-blocking mode. */
494         set_nonblock(ssh->state->connection_in);
495
496         if (ssh->state->connection_out != ssh->state->connection_in)
497                 set_nonblock(ssh->state->connection_out);
498 }
499
500 /* Returns the socket used for reading. */
501
502 int
503 ssh_packet_get_connection_in(struct ssh *ssh)
504 {
505         return ssh->state->connection_in;
506 }
507
508 /* Returns the descriptor used for writing. */
509
510 int
511 ssh_packet_get_connection_out(struct ssh *ssh)
512 {
513         return ssh->state->connection_out;
514 }
515
516 /*
517  * Returns the IP-address of the remote host as a string.  The returned
518  * string must not be freed.
519  */
520
521 const char *
522 ssh_remote_ipaddr(struct ssh *ssh)
523 {
524         const int sock = ssh->state->connection_in;
525
526         /* Check whether we have cached the ipaddr. */
527         if (ssh->remote_ipaddr == NULL) {
528                 if (ssh_packet_connection_is_on_socket(ssh)) {
529                         ssh->remote_ipaddr = get_peer_ipaddr(sock);
530                         ssh->remote_port = get_peer_port(sock);
531                         ssh->local_ipaddr = get_local_ipaddr(sock);
532                         ssh->local_port = get_local_port(sock);
533                 } else {
534                         ssh->remote_ipaddr = strdup("UNKNOWN");
535                         ssh->remote_port = 65535;
536                         ssh->local_ipaddr = strdup("UNKNOWN");
537                         ssh->local_port = 65535;
538                 }
539         }
540         return ssh->remote_ipaddr;
541 }
542
543 /* Returns the port number of the remote host. */
544
545 int
546 ssh_remote_port(struct ssh *ssh)
547 {
548         (void)ssh_remote_ipaddr(ssh); /* Will lookup and cache. */
549         return ssh->remote_port;
550 }
551
552 /*
553  * Returns the IP-address of the local host as a string.  The returned
554  * string must not be freed.
555  */
556
557 const char *
558 ssh_local_ipaddr(struct ssh *ssh)
559 {
560         (void)ssh_remote_ipaddr(ssh); /* Will lookup and cache. */
561         return ssh->local_ipaddr;
562 }
563
564 /* Returns the port number of the local host. */
565
566 int
567 ssh_local_port(struct ssh *ssh)
568 {
569         (void)ssh_remote_ipaddr(ssh); /* Will lookup and cache. */
570         return ssh->local_port;
571 }
572
573 /* Closes the connection and clears and frees internal data structures. */
574
575 void
576 ssh_packet_close(struct ssh *ssh)
577 {
578         struct session_state *state = ssh->state;
579         u_int mode;
580
581         if (!state->initialized)
582                 return;
583         state->initialized = 0;
584         if (state->connection_in == state->connection_out) {
585                 shutdown(state->connection_out, SHUT_RDWR);
586                 close(state->connection_out);
587         } else {
588                 close(state->connection_in);
589                 close(state->connection_out);
590         }
591         sshbuf_free(state->input);
592         sshbuf_free(state->output);
593         sshbuf_free(state->outgoing_packet);
594         sshbuf_free(state->incoming_packet);
595         for (mode = 0; mode < MODE_MAX; mode++)
596                 kex_free_newkeys(state->newkeys[mode]);
597         if (state->compression_buffer) {
598                 sshbuf_free(state->compression_buffer);
599                 if (state->compression_out_started) {
600                         z_streamp stream = &state->compression_out_stream;
601                         debug("compress outgoing: "
602                             "raw data %llu, compressed %llu, factor %.2f",
603                                 (unsigned long long)stream->total_in,
604                                 (unsigned long long)stream->total_out,
605                                 stream->total_in == 0 ? 0.0 :
606                                 (double) stream->total_out / stream->total_in);
607                         if (state->compression_out_failures == 0)
608                                 deflateEnd(stream);
609                 }
610                 if (state->compression_in_started) {
611                         z_streamp stream = &state->compression_out_stream;
612                         debug("compress incoming: "
613                             "raw data %llu, compressed %llu, factor %.2f",
614                             (unsigned long long)stream->total_out,
615                             (unsigned long long)stream->total_in,
616                             stream->total_out == 0 ? 0.0 :
617                             (double) stream->total_in / stream->total_out);
618                         if (state->compression_in_failures == 0)
619                                 inflateEnd(stream);
620                 }
621         }
622         cipher_free(state->send_context);
623         cipher_free(state->receive_context);
624         state->send_context = state->receive_context = NULL;
625         free(ssh->remote_ipaddr);
626         ssh->remote_ipaddr = NULL;
627         free(ssh->state);
628         ssh->state = NULL;
629 }
630
631 /* Sets remote side protocol flags. */
632
633 void
634 ssh_packet_set_protocol_flags(struct ssh *ssh, u_int protocol_flags)
635 {
636         ssh->state->remote_protocol_flags = protocol_flags;
637 }
638
639 /* Returns the remote protocol flags set earlier by the above function. */
640
641 u_int
642 ssh_packet_get_protocol_flags(struct ssh *ssh)
643 {
644         return ssh->state->remote_protocol_flags;
645 }
646
647 /*
648  * Starts packet compression from the next packet on in both directions.
649  * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
650  */
651
652 static int
653 ssh_packet_init_compression(struct ssh *ssh)
654 {
655         if (!ssh->state->compression_buffer &&
656            ((ssh->state->compression_buffer = sshbuf_new()) == NULL))
657                 return SSH_ERR_ALLOC_FAIL;
658         return 0;
659 }
660
661 static int
662 start_compression_out(struct ssh *ssh, int level)
663 {
664         if (level < 1 || level > 9)
665                 return SSH_ERR_INVALID_ARGUMENT;
666         debug("Enabling compression at level %d.", level);
667         if (ssh->state->compression_out_started == 1)
668                 deflateEnd(&ssh->state->compression_out_stream);
669         switch (deflateInit(&ssh->state->compression_out_stream, level)) {
670         case Z_OK:
671                 ssh->state->compression_out_started = 1;
672                 break;
673         case Z_MEM_ERROR:
674                 return SSH_ERR_ALLOC_FAIL;
675         default:
676                 return SSH_ERR_INTERNAL_ERROR;
677         }
678         return 0;
679 }
680
681 static int
682 start_compression_in(struct ssh *ssh)
683 {
684         if (ssh->state->compression_in_started == 1)
685                 inflateEnd(&ssh->state->compression_in_stream);
686         switch (inflateInit(&ssh->state->compression_in_stream)) {
687         case Z_OK:
688                 ssh->state->compression_in_started = 1;
689                 break;
690         case Z_MEM_ERROR:
691                 return SSH_ERR_ALLOC_FAIL;
692         default:
693                 return SSH_ERR_INTERNAL_ERROR;
694         }
695         return 0;
696 }
697
698 int
699 ssh_packet_start_compression(struct ssh *ssh, int level)
700 {
701         int r;
702
703         if (ssh->state->packet_compression && !compat20)
704                 return SSH_ERR_INTERNAL_ERROR;
705         ssh->state->packet_compression = 1;
706         if ((r = ssh_packet_init_compression(ssh)) != 0 ||
707             (r = start_compression_in(ssh)) != 0 ||
708             (r = start_compression_out(ssh, level)) != 0)
709                 return r;
710         return 0;
711 }
712
713 /* XXX remove need for separate compression buffer */
714 static int
715 compress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
716 {
717         u_char buf[4096];
718         int r, status;
719
720         if (ssh->state->compression_out_started != 1)
721                 return SSH_ERR_INTERNAL_ERROR;
722
723         /* This case is not handled below. */
724         if (sshbuf_len(in) == 0)
725                 return 0;
726
727         /* Input is the contents of the input buffer. */
728         if ((ssh->state->compression_out_stream.next_in =
729             sshbuf_mutable_ptr(in)) == NULL)
730                 return SSH_ERR_INTERNAL_ERROR;
731         ssh->state->compression_out_stream.avail_in = sshbuf_len(in);
732
733         /* Loop compressing until deflate() returns with avail_out != 0. */
734         do {
735                 /* Set up fixed-size output buffer. */
736                 ssh->state->compression_out_stream.next_out = buf;
737                 ssh->state->compression_out_stream.avail_out = sizeof(buf);
738
739                 /* Compress as much data into the buffer as possible. */
740                 status = deflate(&ssh->state->compression_out_stream,
741                     Z_PARTIAL_FLUSH);
742                 switch (status) {
743                 case Z_MEM_ERROR:
744                         return SSH_ERR_ALLOC_FAIL;
745                 case Z_OK:
746                         /* Append compressed data to output_buffer. */
747                         if ((r = sshbuf_put(out, buf, sizeof(buf) -
748                             ssh->state->compression_out_stream.avail_out)) != 0)
749                                 return r;
750                         break;
751                 case Z_STREAM_ERROR:
752                 default:
753                         ssh->state->compression_out_failures++;
754                         return SSH_ERR_INVALID_FORMAT;
755                 }
756         } while (ssh->state->compression_out_stream.avail_out == 0);
757         return 0;
758 }
759
760 static int
761 uncompress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
762 {
763         u_char buf[4096];
764         int r, status;
765
766         if (ssh->state->compression_in_started != 1)
767                 return SSH_ERR_INTERNAL_ERROR;
768
769         if ((ssh->state->compression_in_stream.next_in =
770             sshbuf_mutable_ptr(in)) == NULL)
771                 return SSH_ERR_INTERNAL_ERROR;
772         ssh->state->compression_in_stream.avail_in = sshbuf_len(in);
773
774         for (;;) {
775                 /* Set up fixed-size output buffer. */
776                 ssh->state->compression_in_stream.next_out = buf;
777                 ssh->state->compression_in_stream.avail_out = sizeof(buf);
778
779                 status = inflate(&ssh->state->compression_in_stream,
780                     Z_PARTIAL_FLUSH);
781                 switch (status) {
782                 case Z_OK:
783                         if ((r = sshbuf_put(out, buf, sizeof(buf) -
784                             ssh->state->compression_in_stream.avail_out)) != 0)
785                                 return r;
786                         break;
787                 case Z_BUF_ERROR:
788                         /*
789                          * Comments in zlib.h say that we should keep calling
790                          * inflate() until we get an error.  This appears to
791                          * be the error that we get.
792                          */
793                         return 0;
794                 case Z_DATA_ERROR:
795                         return SSH_ERR_INVALID_FORMAT;
796                 case Z_MEM_ERROR:
797                         return SSH_ERR_ALLOC_FAIL;
798                 case Z_STREAM_ERROR:
799                 default:
800                         ssh->state->compression_in_failures++;
801                         return SSH_ERR_INTERNAL_ERROR;
802                 }
803         }
804         /* NOTREACHED */
805 }
806
807 /*
808  * Causes any further packets to be encrypted using the given key.  The same
809  * key is used for both sending and reception.  However, both directions are
810  * encrypted independently of each other.
811  */
812
813 void
814 ssh_packet_set_encryption_key(struct ssh *ssh, const u_char *key, u_int keylen, int number)
815 {
816 #ifndef WITH_SSH1
817         fatal("no SSH protocol 1 support");
818 #else /* WITH_SSH1 */
819         struct session_state *state = ssh->state;
820         const struct sshcipher *cipher = cipher_by_number(number);
821         int r;
822         const char *wmsg;
823
824         if (cipher == NULL)
825                 fatal("%s: unknown cipher number %d", __func__, number);
826         if (keylen < 20)
827                 fatal("%s: keylen too small: %d", __func__, keylen);
828         if (keylen > SSH_SESSION_KEY_LENGTH)
829                 fatal("%s: keylen too big: %d", __func__, keylen);
830         memcpy(state->ssh1_key, key, keylen);
831         state->ssh1_keylen = keylen;
832         if ((r = cipher_init(&state->send_context, cipher, key, keylen,
833             NULL, 0, CIPHER_ENCRYPT)) != 0 ||
834             (r = cipher_init(&state->receive_context, cipher, key, keylen,
835             NULL, 0, CIPHER_DECRYPT) != 0))
836                 fatal("%s: cipher_init failed: %s", __func__, ssh_err(r));
837         if (!state->cipher_warning_done &&
838             ((wmsg = cipher_warning_message(state->send_context)) != NULL ||
839             (wmsg = cipher_warning_message(state->send_context)) != NULL)) {
840                 error("Warning: %s", wmsg);
841                 state->cipher_warning_done = 1;
842         }
843 #endif /* WITH_SSH1 */
844 }
845
846 /*
847  * Finalizes and sends the packet.  If the encryption key has been set,
848  * encrypts the packet before sending.
849  */
850
851 int
852 ssh_packet_send1(struct ssh *ssh)
853 {
854         struct session_state *state = ssh->state;
855         u_char buf[8], *cp;
856         int r, padding, len;
857         u_int checksum;
858
859         /*
860          * If using packet compression, compress the payload of the outgoing
861          * packet.
862          */
863         if (state->packet_compression) {
864                 sshbuf_reset(state->compression_buffer);
865                 /* Skip padding. */
866                 if ((r = sshbuf_consume(state->outgoing_packet, 8)) != 0)
867                         goto out;
868                 /* padding */
869                 if ((r = sshbuf_put(state->compression_buffer,
870                     "\0\0\0\0\0\0\0\0", 8)) != 0)
871                         goto out;
872                 if ((r = compress_buffer(ssh, state->outgoing_packet,
873                     state->compression_buffer)) != 0)
874                         goto out;
875                 sshbuf_reset(state->outgoing_packet);
876                 if ((r = sshbuf_putb(state->outgoing_packet,
877                     state->compression_buffer)) != 0)
878                         goto out;
879         }
880         /* Compute packet length without padding (add checksum, remove padding). */
881         len = sshbuf_len(state->outgoing_packet) + 4 - 8;
882
883         /* Insert padding. Initialized to zero in packet_start1() */
884         padding = 8 - len % 8;
885         if (!cipher_ctx_is_plaintext(state->send_context)) {
886                 cp = sshbuf_mutable_ptr(state->outgoing_packet);
887                 if (cp == NULL) {
888                         r = SSH_ERR_INTERNAL_ERROR;
889                         goto out;
890                 }
891                 arc4random_buf(cp + 8 - padding, padding);
892         }
893         if ((r = sshbuf_consume(state->outgoing_packet, 8 - padding)) != 0)
894                 goto out;
895
896         /* Add check bytes. */
897         checksum = ssh_crc32(sshbuf_ptr(state->outgoing_packet),
898             sshbuf_len(state->outgoing_packet));
899         POKE_U32(buf, checksum);
900         if ((r = sshbuf_put(state->outgoing_packet, buf, 4)) != 0)
901                 goto out;
902
903 #ifdef PACKET_DEBUG
904         fprintf(stderr, "packet_send plain: ");
905         sshbuf_dump(state->outgoing_packet, stderr);
906 #endif
907
908         /* Append to output. */
909         POKE_U32(buf, len);
910         if ((r = sshbuf_put(state->output, buf, 4)) != 0)
911                 goto out;
912         if ((r = sshbuf_reserve(state->output,
913             sshbuf_len(state->outgoing_packet), &cp)) != 0)
914                 goto out;
915         if ((r = cipher_crypt(state->send_context, 0, cp,
916             sshbuf_ptr(state->outgoing_packet),
917             sshbuf_len(state->outgoing_packet), 0, 0)) != 0)
918                 goto out;
919
920 #ifdef PACKET_DEBUG
921         fprintf(stderr, "encrypted: ");
922         sshbuf_dump(state->output, stderr);
923 #endif
924         state->p_send.packets++;
925         state->p_send.bytes += len +
926             sshbuf_len(state->outgoing_packet);
927         sshbuf_reset(state->outgoing_packet);
928
929         /*
930          * Note that the packet is now only buffered in output.  It won't be
931          * actually sent until ssh_packet_write_wait or ssh_packet_write_poll
932          * is called.
933          */
934         r = 0;
935  out:
936         return r;
937 }
938
939 int
940 ssh_set_newkeys(struct ssh *ssh, int mode)
941 {
942         struct session_state *state = ssh->state;
943         struct sshenc *enc;
944         struct sshmac *mac;
945         struct sshcomp *comp;
946         struct sshcipher_ctx **ccp;
947         struct packet_state *ps;
948         u_int64_t *max_blocks;
949         const char *wmsg, *dir;
950         int r, crypt_type;
951
952         debug2("set_newkeys: mode %d", mode);
953
954         if (mode == MODE_OUT) {
955                 dir = "output";
956                 ccp = &state->send_context;
957                 crypt_type = CIPHER_ENCRYPT;
958                 ps = &state->p_send;
959                 max_blocks = &state->max_blocks_out;
960         } else {
961                 dir = "input";
962                 ccp = &state->receive_context;
963                 crypt_type = CIPHER_DECRYPT;
964                 ps = &state->p_read;
965                 max_blocks = &state->max_blocks_in;
966         }
967         if (state->newkeys[mode] != NULL) {
968                 debug("%s: rekeying after %llu %s blocks"
969                     " (%llu bytes total)", __func__,
970                     (unsigned long long)ps->blocks, dir,
971                     (unsigned long long)ps->bytes);
972                 cipher_free(*ccp);
973                 *ccp = NULL;
974                 enc  = &state->newkeys[mode]->enc;
975                 mac  = &state->newkeys[mode]->mac;
976                 comp = &state->newkeys[mode]->comp;
977                 mac_clear(mac);
978                 explicit_bzero(enc->iv,  enc->iv_len);
979                 explicit_bzero(enc->key, enc->key_len);
980                 explicit_bzero(mac->key, mac->key_len);
981                 free(enc->name);
982                 free(enc->iv);
983                 free(enc->key);
984                 free(mac->name);
985                 free(mac->key);
986                 free(comp->name);
987                 free(state->newkeys[mode]);
988         }
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)
1000                         return r;
1001         }
1002         mac->enabled = 1;
1003         DBG(debug("cipher_init_context: %d", mode));
1004         if ((r = cipher_init(ccp, enc->cipher, enc->key, enc->key_len,
1005             enc->iv, enc->iv_len, crypt_type)) != 0)
1006                 return r;
1007         if (!state->cipher_warning_done &&
1008             (wmsg = cipher_warning_message(*ccp)) != NULL) {
1009                 error("Warning: %s", wmsg);
1010                 state->cipher_warning_done = 1;
1011         }
1012         /* Deleting the keys does not gain extra security */
1013         /* explicit_bzero(enc->iv,  enc->block_size);
1014            explicit_bzero(enc->key, enc->key_len);
1015            explicit_bzero(mac->key, mac->key_len); */
1016         if ((comp->type == COMP_ZLIB ||
1017             (comp->type == COMP_DELAYED &&
1018              state->after_authentication)) && comp->enabled == 0) {
1019                 if ((r = ssh_packet_init_compression(ssh)) < 0)
1020                         return r;
1021                 if (mode == MODE_OUT) {
1022                         if ((r = start_compression_out(ssh, 6)) != 0)
1023                                 return r;
1024                 } else {
1025                         if ((r = start_compression_in(ssh)) != 0)
1026                                 return r;
1027                 }
1028                 comp->enabled = 1;
1029         }
1030         /*
1031          * The 2^(blocksize*2) limit is too expensive for 3DES,
1032          * blowfish, etc, so enforce a 1GB limit for small blocksizes.
1033          */
1034         if (enc->block_size >= 16)
1035                 *max_blocks = (u_int64_t)1 << (enc->block_size*2);
1036         else
1037                 *max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
1038         if (state->rekey_limit)
1039                 *max_blocks = MINIMUM(*max_blocks,
1040                     state->rekey_limit / enc->block_size);
1041         debug("rekey after %llu blocks", (unsigned long long)*max_blocks);
1042         return 0;
1043 }
1044
1045 #define MAX_PACKETS     (1U<<31)
1046 static int
1047 ssh_packet_need_rekeying(struct ssh *ssh, u_int outbound_packet_len)
1048 {
1049         struct session_state *state = ssh->state;
1050         u_int32_t out_blocks;
1051
1052         /* XXX client can't cope with rekeying pre-auth */
1053         if (!state->after_authentication)
1054                 return 0;
1055
1056         /* Haven't keyed yet or KEX in progress. */
1057         if (ssh->kex == NULL || ssh_packet_is_rekeying(ssh))
1058                 return 0;
1059
1060         /* Peer can't rekey */
1061         if (ssh->compat & SSH_BUG_NOREKEY)
1062                 return 0;
1063
1064         /*
1065          * Permit one packet in or out per rekey - this allows us to
1066          * make progress when rekey limits are very small.
1067          */
1068         if (state->p_send.packets == 0 && state->p_read.packets == 0)
1069                 return 0;
1070
1071         /* Time-based rekeying */
1072         if (state->rekey_interval != 0 &&
1073             (int64_t)state->rekey_time + state->rekey_interval <= monotime())
1074                 return 1;
1075
1076         /* Always rekey when MAX_PACKETS sent in either direction */
1077         if (state->p_send.packets > MAX_PACKETS ||
1078             state->p_read.packets > MAX_PACKETS)
1079                 return 1;
1080
1081         /* Rekey after (cipher-specific) maxiumum blocks */
1082         out_blocks = ROUNDUP(outbound_packet_len,
1083             state->newkeys[MODE_OUT]->enc.block_size);
1084         return (state->max_blocks_out &&
1085             (state->p_send.blocks + out_blocks > state->max_blocks_out)) ||
1086             (state->max_blocks_in &&
1087             (state->p_read.blocks > state->max_blocks_in));
1088 }
1089
1090 /*
1091  * Delayed compression for SSH2 is enabled after authentication:
1092  * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
1093  * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
1094  */
1095 static int
1096 ssh_packet_enable_delayed_compress(struct ssh *ssh)
1097 {
1098         struct session_state *state = ssh->state;
1099         struct sshcomp *comp = NULL;
1100         int r, mode;
1101
1102         /*
1103          * Remember that we are past the authentication step, so rekeying
1104          * with COMP_DELAYED will turn on compression immediately.
1105          */
1106         state->after_authentication = 1;
1107         for (mode = 0; mode < MODE_MAX; mode++) {
1108                 /* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
1109                 if (state->newkeys[mode] == NULL)
1110                         continue;
1111                 comp = &state->newkeys[mode]->comp;
1112                 if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
1113                         if ((r = ssh_packet_init_compression(ssh)) != 0)
1114                                 return r;
1115                         if (mode == MODE_OUT) {
1116                                 if ((r = start_compression_out(ssh, 6)) != 0)
1117                                         return r;
1118                         } else {
1119                                 if ((r = start_compression_in(ssh)) != 0)
1120                                         return r;
1121                         }
1122                         comp->enabled = 1;
1123                 }
1124         }
1125         return 0;
1126 }
1127
1128 /* Used to mute debug logging for noisy packet types */
1129 int
1130 ssh_packet_log_type(u_char type)
1131 {
1132         switch (type) {
1133         case SSH2_MSG_CHANNEL_DATA:
1134         case SSH2_MSG_CHANNEL_EXTENDED_DATA:
1135         case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
1136                 return 0;
1137         default:
1138                 return 1;
1139         }
1140 }
1141
1142 /*
1143  * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
1144  */
1145 int
1146 ssh_packet_send2_wrapped(struct ssh *ssh)
1147 {
1148         struct session_state *state = ssh->state;
1149         u_char type, *cp, macbuf[SSH_DIGEST_MAX_LENGTH];
1150         u_char tmp, padlen, pad = 0;
1151         u_int authlen = 0, aadlen = 0;
1152         u_int len;
1153         struct sshenc *enc   = NULL;
1154         struct sshmac *mac   = NULL;
1155         struct sshcomp *comp = NULL;
1156         int r, block_size;
1157
1158         if (state->newkeys[MODE_OUT] != NULL) {
1159                 enc  = &state->newkeys[MODE_OUT]->enc;
1160                 mac  = &state->newkeys[MODE_OUT]->mac;
1161                 comp = &state->newkeys[MODE_OUT]->comp;
1162                 /* disable mac for authenticated encryption */
1163                 if ((authlen = cipher_authlen(enc->cipher)) != 0)
1164                         mac = NULL;
1165         }
1166         block_size = enc ? enc->block_size : 8;
1167         aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
1168
1169         type = (sshbuf_ptr(state->outgoing_packet))[5];
1170         if (ssh_packet_log_type(type))
1171                 debug3("send packet: type %u", type);
1172 #ifdef PACKET_DEBUG
1173         fprintf(stderr, "plain:     ");
1174         sshbuf_dump(state->outgoing_packet, stderr);
1175 #endif
1176
1177         if (comp && comp->enabled) {
1178                 len = sshbuf_len(state->outgoing_packet);
1179                 /* skip header, compress only payload */
1180                 if ((r = sshbuf_consume(state->outgoing_packet, 5)) != 0)
1181                         goto out;
1182                 sshbuf_reset(state->compression_buffer);
1183                 if ((r = compress_buffer(ssh, state->outgoing_packet,
1184                     state->compression_buffer)) != 0)
1185                         goto out;
1186                 sshbuf_reset(state->outgoing_packet);
1187                 if ((r = sshbuf_put(state->outgoing_packet,
1188                     "\0\0\0\0\0", 5)) != 0 ||
1189                     (r = sshbuf_putb(state->outgoing_packet,
1190                     state->compression_buffer)) != 0)
1191                         goto out;
1192                 DBG(debug("compression: raw %d compressed %zd", len,
1193                     sshbuf_len(state->outgoing_packet)));
1194         }
1195
1196         /* sizeof (packet_len + pad_len + payload) */
1197         len = sshbuf_len(state->outgoing_packet);
1198
1199         /*
1200          * calc size of padding, alloc space, get random data,
1201          * minimum padding is 4 bytes
1202          */
1203         len -= aadlen; /* packet length is not encrypted for EtM modes */
1204         padlen = block_size - (len % block_size);
1205         if (padlen < 4)
1206                 padlen += block_size;
1207         if (state->extra_pad) {
1208                 tmp = state->extra_pad;
1209                 state->extra_pad =
1210                     ROUNDUP(state->extra_pad, block_size);
1211                 /* check if roundup overflowed */
1212                 if (state->extra_pad < tmp)
1213                         return SSH_ERR_INVALID_ARGUMENT;
1214                 tmp = (len + padlen) % state->extra_pad;
1215                 /* Check whether pad calculation below will underflow */
1216                 if (tmp > state->extra_pad)
1217                         return SSH_ERR_INVALID_ARGUMENT;
1218                 pad = state->extra_pad - tmp;
1219                 DBG(debug3("%s: adding %d (len %d padlen %d extra_pad %d)",
1220                     __func__, pad, len, padlen, state->extra_pad));
1221                 tmp = padlen;
1222                 padlen += pad;
1223                 /* Check whether padlen calculation overflowed */
1224                 if (padlen < tmp)
1225                         return SSH_ERR_INVALID_ARGUMENT; /* overflow */
1226                 state->extra_pad = 0;
1227         }
1228         if ((r = sshbuf_reserve(state->outgoing_packet, padlen, &cp)) != 0)
1229                 goto out;
1230         if (enc && !cipher_ctx_is_plaintext(state->send_context)) {
1231                 /* random padding */
1232                 arc4random_buf(cp, padlen);
1233         } else {
1234                 /* clear padding */
1235                 explicit_bzero(cp, padlen);
1236         }
1237         /* sizeof (packet_len + pad_len + payload + padding) */
1238         len = sshbuf_len(state->outgoing_packet);
1239         cp = sshbuf_mutable_ptr(state->outgoing_packet);
1240         if (cp == NULL) {
1241                 r = SSH_ERR_INTERNAL_ERROR;
1242                 goto out;
1243         }
1244         /* packet_length includes payload, padding and padding length field */
1245         POKE_U32(cp, len - 4);
1246         cp[4] = padlen;
1247         DBG(debug("send: len %d (includes padlen %d, aadlen %d)",
1248             len, padlen, aadlen));
1249
1250         /* compute MAC over seqnr and packet(length fields, payload, padding) */
1251         if (mac && mac->enabled && !mac->etm) {
1252                 if ((r = mac_compute(mac, state->p_send.seqnr,
1253                     sshbuf_ptr(state->outgoing_packet), len,
1254                     macbuf, sizeof(macbuf))) != 0)
1255                         goto out;
1256                 DBG(debug("done calc MAC out #%d", state->p_send.seqnr));
1257         }
1258         /* encrypt packet and append to output buffer. */
1259         if ((r = sshbuf_reserve(state->output,
1260             sshbuf_len(state->outgoing_packet) + authlen, &cp)) != 0)
1261                 goto out;
1262         if ((r = cipher_crypt(state->send_context, state->p_send.seqnr, cp,
1263             sshbuf_ptr(state->outgoing_packet),
1264             len - aadlen, aadlen, authlen)) != 0)
1265                 goto out;
1266         /* append unencrypted MAC */
1267         if (mac && mac->enabled) {
1268                 if (mac->etm) {
1269                         /* EtM: compute mac over aadlen + cipher text */
1270                         if ((r = mac_compute(mac, state->p_send.seqnr,
1271                             cp, len, macbuf, sizeof(macbuf))) != 0)
1272                                 goto out;
1273                         DBG(debug("done calc MAC(EtM) out #%d",
1274                             state->p_send.seqnr));
1275                 }
1276                 if ((r = sshbuf_put(state->output, macbuf, mac->mac_len)) != 0)
1277                         goto out;
1278         }
1279 #ifdef PACKET_DEBUG
1280         fprintf(stderr, "encrypted: ");
1281         sshbuf_dump(state->output, stderr);
1282 #endif
1283         /* increment sequence number for outgoing packets */
1284         if (++state->p_send.seqnr == 0)
1285                 logit("outgoing seqnr wraps around");
1286         if (++state->p_send.packets == 0)
1287                 if (!(ssh->compat & SSH_BUG_NOREKEY))
1288                         return SSH_ERR_NEED_REKEY;
1289         state->p_send.blocks += len / block_size;
1290         state->p_send.bytes += len;
1291         sshbuf_reset(state->outgoing_packet);
1292
1293         if (type == SSH2_MSG_NEWKEYS)
1294                 r = ssh_set_newkeys(ssh, MODE_OUT);
1295         else if (type == SSH2_MSG_USERAUTH_SUCCESS && state->server_side)
1296                 r = ssh_packet_enable_delayed_compress(ssh);
1297         else
1298                 r = 0;
1299  out:
1300         return r;
1301 }
1302
1303 /* returns non-zero if the specified packet type is usec by KEX */
1304 static int
1305 ssh_packet_type_is_kex(u_char type)
1306 {
1307         return
1308             type >= SSH2_MSG_TRANSPORT_MIN &&
1309             type <= SSH2_MSG_TRANSPORT_MAX &&
1310             type != SSH2_MSG_SERVICE_REQUEST &&
1311             type != SSH2_MSG_SERVICE_ACCEPT &&
1312             type != SSH2_MSG_EXT_INFO;
1313 }
1314
1315 int
1316 ssh_packet_send2(struct ssh *ssh)
1317 {
1318         struct session_state *state = ssh->state;
1319         struct packet *p;
1320         u_char type;
1321         int r, need_rekey;
1322
1323         if (sshbuf_len(state->outgoing_packet) < 6)
1324                 return SSH_ERR_INTERNAL_ERROR;
1325         type = sshbuf_ptr(state->outgoing_packet)[5];
1326         need_rekey = !ssh_packet_type_is_kex(type) &&
1327             ssh_packet_need_rekeying(ssh, sshbuf_len(state->outgoing_packet));
1328
1329         /*
1330          * During rekeying we can only send key exchange messages.
1331          * Queue everything else.
1332          */
1333         if ((need_rekey || state->rekeying) && !ssh_packet_type_is_kex(type)) {
1334                 if (need_rekey)
1335                         debug3("%s: rekex triggered", __func__);
1336                 debug("enqueue packet: %u", type);
1337                 p = calloc(1, sizeof(*p));
1338                 if (p == NULL)
1339                         return SSH_ERR_ALLOC_FAIL;
1340                 p->type = type;
1341                 p->payload = state->outgoing_packet;
1342                 TAILQ_INSERT_TAIL(&state->outgoing, p, next);
1343                 state->outgoing_packet = sshbuf_new();
1344                 if (state->outgoing_packet == NULL)
1345                         return SSH_ERR_ALLOC_FAIL;
1346                 if (need_rekey) {
1347                         /*
1348                          * This packet triggered a rekey, so send the
1349                          * KEXINIT now.
1350                          * NB. reenters this function via kex_start_rekex().
1351                          */
1352                         return kex_start_rekex(ssh);
1353                 }
1354                 return 0;
1355         }
1356
1357         /* rekeying starts with sending KEXINIT */
1358         if (type == SSH2_MSG_KEXINIT)
1359                 state->rekeying = 1;
1360
1361         if ((r = ssh_packet_send2_wrapped(ssh)) != 0)
1362                 return r;
1363
1364         /* after a NEWKEYS message we can send the complete queue */
1365         if (type == SSH2_MSG_NEWKEYS) {
1366                 state->rekeying = 0;
1367                 state->rekey_time = monotime();
1368                 while ((p = TAILQ_FIRST(&state->outgoing))) {
1369                         type = p->type;
1370                         /*
1371                          * If this packet triggers a rekex, then skip the
1372                          * remaining packets in the queue for now.
1373                          * NB. re-enters this function via kex_start_rekex.
1374                          */
1375                         if (ssh_packet_need_rekeying(ssh,
1376                             sshbuf_len(p->payload))) {
1377                                 debug3("%s: queued packet triggered rekex",
1378                                     __func__);
1379                                 return kex_start_rekex(ssh);
1380                         }
1381                         debug("dequeue packet: %u", type);
1382                         sshbuf_free(state->outgoing_packet);
1383                         state->outgoing_packet = p->payload;
1384                         TAILQ_REMOVE(&state->outgoing, p, next);
1385                         memset(p, 0, sizeof(*p));
1386                         free(p);
1387                         if ((r = ssh_packet_send2_wrapped(ssh)) != 0)
1388                                 return r;
1389                 }
1390         }
1391         return 0;
1392 }
1393
1394 /*
1395  * Waits until a packet has been received, and returns its type.  Note that
1396  * no other data is processed until this returns, so this function should not
1397  * be used during the interactive session.
1398  */
1399
1400 int
1401 ssh_packet_read_seqnr(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1402 {
1403         struct session_state *state = ssh->state;
1404         int len, r, ms_remain;
1405         fd_set *setp;
1406         char buf[8192];
1407         struct timeval timeout, start, *timeoutp = NULL;
1408
1409         DBG(debug("packet_read()"));
1410
1411         setp = calloc(howmany(state->connection_in + 1,
1412             NFDBITS), sizeof(fd_mask));
1413         if (setp == NULL)
1414                 return SSH_ERR_ALLOC_FAIL;
1415
1416         /*
1417          * Since we are blocking, ensure that all written packets have
1418          * been sent.
1419          */
1420         if ((r = ssh_packet_write_wait(ssh)) != 0)
1421                 goto out;
1422
1423         /* Stay in the loop until we have received a complete packet. */
1424         for (;;) {
1425                 /* Try to read a packet from the buffer. */
1426                 r = ssh_packet_read_poll_seqnr(ssh, typep, seqnr_p);
1427                 if (r != 0)
1428                         break;
1429                 if (!compat20 && (
1430                     *typep == SSH_SMSG_SUCCESS
1431                     || *typep == SSH_SMSG_FAILURE
1432                     || *typep == SSH_CMSG_EOF
1433                     || *typep == SSH_CMSG_EXIT_CONFIRMATION))
1434                         if ((r = sshpkt_get_end(ssh)) != 0)
1435                                 break;
1436                 /* If we got a packet, return it. */
1437                 if (*typep != SSH_MSG_NONE)
1438                         break;
1439                 /*
1440                  * Otherwise, wait for some data to arrive, add it to the
1441                  * buffer, and try again.
1442                  */
1443                 memset(setp, 0, howmany(state->connection_in + 1,
1444                     NFDBITS) * sizeof(fd_mask));
1445                 FD_SET(state->connection_in, setp);
1446
1447                 if (state->packet_timeout_ms > 0) {
1448                         ms_remain = state->packet_timeout_ms;
1449                         timeoutp = &timeout;
1450                 }
1451                 /* Wait for some data to arrive. */
1452                 for (;;) {
1453                         if (state->packet_timeout_ms != -1) {
1454                                 ms_to_timeval(&timeout, ms_remain);
1455                                 gettimeofday(&start, NULL);
1456                         }
1457                         if ((r = select(state->connection_in + 1, setp,
1458                             NULL, NULL, timeoutp)) >= 0)
1459                                 break;
1460                         if (errno != EAGAIN && errno != EINTR &&
1461                             errno != EWOULDBLOCK)
1462                                 break;
1463                         if (state->packet_timeout_ms == -1)
1464                                 continue;
1465                         ms_subtract_diff(&start, &ms_remain);
1466                         if (ms_remain <= 0) {
1467                                 r = 0;
1468                                 break;
1469                         }
1470                 }
1471                 if (r == 0) {
1472                         r = SSH_ERR_CONN_TIMEOUT;
1473                         goto out;
1474                 }
1475                 /* Read data from the socket. */
1476                 len = read(state->connection_in, buf, sizeof(buf));
1477                 if (len == 0) {
1478                         r = SSH_ERR_CONN_CLOSED;
1479                         goto out;
1480                 }
1481                 if (len < 0) {
1482                         r = SSH_ERR_SYSTEM_ERROR;
1483                         goto out;
1484                 }
1485
1486                 /* Append it to the buffer. */
1487                 if ((r = ssh_packet_process_incoming(ssh, buf, len)) != 0)
1488                         goto out;
1489         }
1490  out:
1491         free(setp);
1492         return r;
1493 }
1494
1495 int
1496 ssh_packet_read(struct ssh *ssh)
1497 {
1498         u_char type;
1499         int r;
1500
1501         if ((r = ssh_packet_read_seqnr(ssh, &type, NULL)) != 0)
1502                 fatal("%s: %s", __func__, ssh_err(r));
1503         return type;
1504 }
1505
1506 /*
1507  * Waits until a packet has been received, verifies that its type matches
1508  * that given, and gives a fatal error and exits if there is a mismatch.
1509  */
1510
1511 int
1512 ssh_packet_read_expect(struct ssh *ssh, u_int expected_type)
1513 {
1514         int r;
1515         u_char type;
1516
1517         if ((r = ssh_packet_read_seqnr(ssh, &type, NULL)) != 0)
1518                 return r;
1519         if (type != expected_type) {
1520                 if ((r = sshpkt_disconnect(ssh,
1521                     "Protocol error: expected packet type %d, got %d",
1522                     expected_type, type)) != 0)
1523                         return r;
1524                 return SSH_ERR_PROTOCOL_ERROR;
1525         }
1526         return 0;
1527 }
1528
1529 /* Checks if a full packet is available in the data received so far via
1530  * packet_process_incoming.  If so, reads the packet; otherwise returns
1531  * SSH_MSG_NONE.  This does not wait for data from the connection.
1532  *
1533  * SSH_MSG_DISCONNECT is handled specially here.  Also,
1534  * SSH_MSG_IGNORE messages are skipped by this function and are never returned
1535  * to higher levels.
1536  */
1537
1538 int
1539 ssh_packet_read_poll1(struct ssh *ssh, u_char *typep)
1540 {
1541         struct session_state *state = ssh->state;
1542         u_int len, padded_len;
1543         const char *emsg;
1544         const u_char *cp;
1545         u_char *p;
1546         u_int checksum, stored_checksum;
1547         int r;
1548
1549         *typep = SSH_MSG_NONE;
1550
1551         /* Check if input size is less than minimum packet size. */
1552         if (sshbuf_len(state->input) < 4 + 8)
1553                 return 0;
1554         /* Get length of incoming packet. */
1555         len = PEEK_U32(sshbuf_ptr(state->input));
1556         if (len < 1 + 2 + 2 || len > 256 * 1024) {
1557                 if ((r = sshpkt_disconnect(ssh, "Bad packet length %u",
1558                     len)) != 0)
1559                         return r;
1560                 return SSH_ERR_CONN_CORRUPT;
1561         }
1562         padded_len = (len + 8) & ~7;
1563
1564         /* Check if the packet has been entirely received. */
1565         if (sshbuf_len(state->input) < 4 + padded_len)
1566                 return 0;
1567
1568         /* The entire packet is in buffer. */
1569
1570         /* Consume packet length. */
1571         if ((r = sshbuf_consume(state->input, 4)) != 0)
1572                 goto out;
1573
1574         /*
1575          * Cryptographic attack detector for ssh
1576          * (C)1998 CORE-SDI, Buenos Aires Argentina
1577          * Ariel Futoransky(futo@core-sdi.com)
1578          */
1579         if (!cipher_ctx_is_plaintext(state->receive_context)) {
1580                 emsg = NULL;
1581                 switch (detect_attack(&state->deattack,
1582                     sshbuf_ptr(state->input), padded_len)) {
1583                 case DEATTACK_OK:
1584                         break;
1585                 case DEATTACK_DETECTED:
1586                         emsg = "crc32 compensation attack detected";
1587                         break;
1588                 case DEATTACK_DOS_DETECTED:
1589                         emsg = "deattack denial of service detected";
1590                         break;
1591                 default:
1592                         emsg = "deattack error";
1593                         break;
1594                 }
1595                 if (emsg != NULL) {
1596                         error("%s", emsg);
1597                         if ((r = sshpkt_disconnect(ssh, "%s", emsg)) != 0 ||
1598                             (r = ssh_packet_write_wait(ssh)) != 0)
1599                                         return r;
1600                         return SSH_ERR_CONN_CORRUPT;
1601                 }
1602         }
1603
1604         /* Decrypt data to incoming_packet. */
1605         sshbuf_reset(state->incoming_packet);
1606         if ((r = sshbuf_reserve(state->incoming_packet, padded_len, &p)) != 0)
1607                 goto out;
1608         if ((r = cipher_crypt(state->receive_context, 0, p,
1609             sshbuf_ptr(state->input), padded_len, 0, 0)) != 0)
1610                 goto out;
1611
1612         if ((r = sshbuf_consume(state->input, padded_len)) != 0)
1613                 goto out;
1614
1615 #ifdef PACKET_DEBUG
1616         fprintf(stderr, "read_poll plain: ");
1617         sshbuf_dump(state->incoming_packet, stderr);
1618 #endif
1619
1620         /* Compute packet checksum. */
1621         checksum = ssh_crc32(sshbuf_ptr(state->incoming_packet),
1622             sshbuf_len(state->incoming_packet) - 4);
1623
1624         /* Skip padding. */
1625         if ((r = sshbuf_consume(state->incoming_packet, 8 - len % 8)) != 0)
1626                 goto out;
1627
1628         /* Test check bytes. */
1629         if (len != sshbuf_len(state->incoming_packet)) {
1630                 error("%s: len %d != sshbuf_len %zd", __func__,
1631                     len, sshbuf_len(state->incoming_packet));
1632                 if ((r = sshpkt_disconnect(ssh, "invalid packet length")) != 0 ||
1633                     (r = ssh_packet_write_wait(ssh)) != 0)
1634                         return r;
1635                 return SSH_ERR_CONN_CORRUPT;
1636         }
1637
1638         cp = sshbuf_ptr(state->incoming_packet) + len - 4;
1639         stored_checksum = PEEK_U32(cp);
1640         if (checksum != stored_checksum) {
1641                 error("Corrupted check bytes on input");
1642                 if ((r = sshpkt_disconnect(ssh, "connection corrupted")) != 0 ||
1643                     (r = ssh_packet_write_wait(ssh)) != 0)
1644                         return r;
1645                 return SSH_ERR_CONN_CORRUPT;
1646         }
1647         if ((r = sshbuf_consume_end(state->incoming_packet, 4)) < 0)
1648                 goto out;
1649
1650         if (state->packet_compression) {
1651                 sshbuf_reset(state->compression_buffer);
1652                 if ((r = uncompress_buffer(ssh, state->incoming_packet,
1653                     state->compression_buffer)) != 0)
1654                         goto out;
1655                 sshbuf_reset(state->incoming_packet);
1656                 if ((r = sshbuf_putb(state->incoming_packet,
1657                     state->compression_buffer)) != 0)
1658                         goto out;
1659         }
1660         state->p_read.packets++;
1661         state->p_read.bytes += padded_len + 4;
1662         if ((r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
1663                 goto out;
1664         if (*typep < SSH_MSG_MIN || *typep > SSH_MSG_MAX) {
1665                 error("Invalid ssh1 packet type: %d", *typep);
1666                 if ((r = sshpkt_disconnect(ssh, "invalid packet type")) != 0 ||
1667                     (r = ssh_packet_write_wait(ssh)) != 0)
1668                         return r;
1669                 return SSH_ERR_PROTOCOL_ERROR;
1670         }
1671         r = 0;
1672  out:
1673         return r;
1674 }
1675
1676 static int
1677 ssh_packet_read_poll2_mux(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1678 {
1679         struct session_state *state = ssh->state;
1680         const u_char *cp;
1681         size_t need;
1682         int r;
1683
1684         if (ssh->kex)
1685                 return SSH_ERR_INTERNAL_ERROR;
1686         *typep = SSH_MSG_NONE;
1687         cp = sshbuf_ptr(state->input);
1688         if (state->packlen == 0) {
1689                 if (sshbuf_len(state->input) < 4 + 1)
1690                         return 0; /* packet is incomplete */
1691                 state->packlen = PEEK_U32(cp);
1692                 if (state->packlen < 4 + 1 ||
1693                     state->packlen > PACKET_MAX_SIZE)
1694                         return SSH_ERR_MESSAGE_INCOMPLETE;
1695         }
1696         need = state->packlen + 4;
1697         if (sshbuf_len(state->input) < need)
1698                 return 0; /* packet is incomplete */
1699         sshbuf_reset(state->incoming_packet);
1700         if ((r = sshbuf_put(state->incoming_packet, cp + 4,
1701             state->packlen)) != 0 ||
1702             (r = sshbuf_consume(state->input, need)) != 0 ||
1703             (r = sshbuf_get_u8(state->incoming_packet, NULL)) != 0 ||
1704             (r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
1705                 return r;
1706         if (ssh_packet_log_type(*typep))
1707                 debug3("%s: type %u", __func__, *typep);
1708         /* sshbuf_dump(state->incoming_packet, stderr); */
1709         /* reset for next packet */
1710         state->packlen = 0;
1711         return r;
1712 }
1713
1714 int
1715 ssh_packet_read_poll2(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1716 {
1717         struct session_state *state = ssh->state;
1718         u_int padlen, need;
1719         u_char *cp;
1720         u_int maclen, aadlen = 0, authlen = 0, block_size;
1721         struct sshenc *enc   = NULL;
1722         struct sshmac *mac   = NULL;
1723         struct sshcomp *comp = NULL;
1724         int r;
1725
1726         if (state->mux)
1727                 return ssh_packet_read_poll2_mux(ssh, typep, seqnr_p);
1728
1729         *typep = SSH_MSG_NONE;
1730
1731         if (state->packet_discard)
1732                 return 0;
1733
1734         if (state->newkeys[MODE_IN] != NULL) {
1735                 enc  = &state->newkeys[MODE_IN]->enc;
1736                 mac  = &state->newkeys[MODE_IN]->mac;
1737                 comp = &state->newkeys[MODE_IN]->comp;
1738                 /* disable mac for authenticated encryption */
1739                 if ((authlen = cipher_authlen(enc->cipher)) != 0)
1740                         mac = NULL;
1741         }
1742         maclen = mac && mac->enabled ? mac->mac_len : 0;
1743         block_size = enc ? enc->block_size : 8;
1744         aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
1745
1746         if (aadlen && state->packlen == 0) {
1747                 if (cipher_get_length(state->receive_context,
1748                     &state->packlen, state->p_read.seqnr,
1749                     sshbuf_ptr(state->input), sshbuf_len(state->input)) != 0)
1750                         return 0;
1751                 if (state->packlen < 1 + 4 ||
1752                     state->packlen > PACKET_MAX_SIZE) {
1753 #ifdef PACKET_DEBUG
1754                         sshbuf_dump(state->input, stderr);
1755 #endif
1756                         logit("Bad packet length %u.", state->packlen);
1757                         if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0)
1758                                 return r;
1759                         return SSH_ERR_CONN_CORRUPT;
1760                 }
1761                 sshbuf_reset(state->incoming_packet);
1762         } else if (state->packlen == 0) {
1763                 /*
1764                  * check if input size is less than the cipher block size,
1765                  * decrypt first block and extract length of incoming packet
1766                  */
1767                 if (sshbuf_len(state->input) < block_size)
1768                         return 0;
1769                 sshbuf_reset(state->incoming_packet);
1770                 if ((r = sshbuf_reserve(state->incoming_packet, block_size,
1771                     &cp)) != 0)
1772                         goto out;
1773                 if ((r = cipher_crypt(state->receive_context,
1774                     state->p_send.seqnr, cp, sshbuf_ptr(state->input),
1775                     block_size, 0, 0)) != 0)
1776                         goto out;
1777                 state->packlen = PEEK_U32(sshbuf_ptr(state->incoming_packet));
1778                 if (state->packlen < 1 + 4 ||
1779                     state->packlen > PACKET_MAX_SIZE) {
1780 #ifdef PACKET_DEBUG
1781                         fprintf(stderr, "input: \n");
1782                         sshbuf_dump(state->input, stderr);
1783                         fprintf(stderr, "incoming_packet: \n");
1784                         sshbuf_dump(state->incoming_packet, stderr);
1785 #endif
1786                         logit("Bad packet length %u.", state->packlen);
1787                         return ssh_packet_start_discard(ssh, enc, mac, 0,
1788                             PACKET_MAX_SIZE);
1789                 }
1790                 if ((r = sshbuf_consume(state->input, block_size)) != 0)
1791                         goto out;
1792         }
1793         DBG(debug("input: packet len %u", state->packlen+4));
1794
1795         if (aadlen) {
1796                 /* only the payload is encrypted */
1797                 need = state->packlen;
1798         } else {
1799                 /*
1800                  * the payload size and the payload are encrypted, but we
1801                  * have a partial packet of block_size bytes
1802                  */
1803                 need = 4 + state->packlen - block_size;
1804         }
1805         DBG(debug("partial packet: block %d, need %d, maclen %d, authlen %d,"
1806             " aadlen %d", block_size, need, maclen, authlen, aadlen));
1807         if (need % block_size != 0) {
1808                 logit("padding error: need %d block %d mod %d",
1809                     need, block_size, need % block_size);
1810                 return ssh_packet_start_discard(ssh, enc, mac, 0,
1811                     PACKET_MAX_SIZE - block_size);
1812         }
1813         /*
1814          * check if the entire packet has been received and
1815          * decrypt into incoming_packet:
1816          * 'aadlen' bytes are unencrypted, but authenticated.
1817          * 'need' bytes are encrypted, followed by either
1818          * 'authlen' bytes of authentication tag or
1819          * 'maclen' bytes of message authentication code.
1820          */
1821         if (sshbuf_len(state->input) < aadlen + need + authlen + maclen)
1822                 return 0; /* packet is incomplete */
1823 #ifdef PACKET_DEBUG
1824         fprintf(stderr, "read_poll enc/full: ");
1825         sshbuf_dump(state->input, stderr);
1826 #endif
1827         /* EtM: check mac over encrypted input */
1828         if (mac && mac->enabled && mac->etm) {
1829                 if ((r = mac_check(mac, state->p_read.seqnr,
1830                     sshbuf_ptr(state->input), aadlen + need,
1831                     sshbuf_ptr(state->input) + aadlen + need + authlen,
1832                     maclen)) != 0) {
1833                         if (r == SSH_ERR_MAC_INVALID)
1834                                 logit("Corrupted MAC on input.");
1835                         goto out;
1836                 }
1837         }
1838         if ((r = sshbuf_reserve(state->incoming_packet, aadlen + need,
1839             &cp)) != 0)
1840                 goto out;
1841         if ((r = cipher_crypt(state->receive_context, state->p_read.seqnr, cp,
1842             sshbuf_ptr(state->input), need, aadlen, authlen)) != 0)
1843                 goto out;
1844         if ((r = sshbuf_consume(state->input, aadlen + need + authlen)) != 0)
1845                 goto out;
1846         if (mac && mac->enabled) {
1847                 /* Not EtM: check MAC over cleartext */
1848                 if (!mac->etm && (r = mac_check(mac, state->p_read.seqnr,
1849                     sshbuf_ptr(state->incoming_packet),
1850                     sshbuf_len(state->incoming_packet),
1851                     sshbuf_ptr(state->input), maclen)) != 0) {
1852                         if (r != SSH_ERR_MAC_INVALID)
1853                                 goto out;
1854                         logit("Corrupted MAC on input.");
1855                         if (need + block_size > PACKET_MAX_SIZE)
1856                                 return SSH_ERR_INTERNAL_ERROR;
1857                         return ssh_packet_start_discard(ssh, enc, mac,
1858                             sshbuf_len(state->incoming_packet),
1859                             PACKET_MAX_SIZE - need - block_size);
1860                 }
1861                 /* Remove MAC from input buffer */
1862                 DBG(debug("MAC #%d ok", state->p_read.seqnr));
1863                 if ((r = sshbuf_consume(state->input, mac->mac_len)) != 0)
1864                         goto out;
1865         }
1866         if (seqnr_p != NULL)
1867                 *seqnr_p = state->p_read.seqnr;
1868         if (++state->p_read.seqnr == 0)
1869                 logit("incoming seqnr wraps around");
1870         if (++state->p_read.packets == 0)
1871                 if (!(ssh->compat & SSH_BUG_NOREKEY))
1872                         return SSH_ERR_NEED_REKEY;
1873         state->p_read.blocks += (state->packlen + 4) / block_size;
1874         state->p_read.bytes += state->packlen + 4;
1875
1876         /* get padlen */
1877         padlen = sshbuf_ptr(state->incoming_packet)[4];
1878         DBG(debug("input: padlen %d", padlen));
1879         if (padlen < 4) {
1880                 if ((r = sshpkt_disconnect(ssh,
1881                     "Corrupted padlen %d on input.", padlen)) != 0 ||
1882                     (r = ssh_packet_write_wait(ssh)) != 0)
1883                         return r;
1884                 return SSH_ERR_CONN_CORRUPT;
1885         }
1886
1887         /* skip packet size + padlen, discard padding */
1888         if ((r = sshbuf_consume(state->incoming_packet, 4 + 1)) != 0 ||
1889             ((r = sshbuf_consume_end(state->incoming_packet, padlen)) != 0))
1890                 goto out;
1891
1892         DBG(debug("input: len before de-compress %zd",
1893             sshbuf_len(state->incoming_packet)));
1894         if (comp && comp->enabled) {
1895                 sshbuf_reset(state->compression_buffer);
1896                 if ((r = uncompress_buffer(ssh, state->incoming_packet,
1897                     state->compression_buffer)) != 0)
1898                         goto out;
1899                 sshbuf_reset(state->incoming_packet);
1900                 if ((r = sshbuf_putb(state->incoming_packet,
1901                     state->compression_buffer)) != 0)
1902                         goto out;
1903                 DBG(debug("input: len after de-compress %zd",
1904                     sshbuf_len(state->incoming_packet)));
1905         }
1906         /*
1907          * get packet type, implies consume.
1908          * return length of payload (without type field)
1909          */
1910         if ((r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
1911                 goto out;
1912         if (ssh_packet_log_type(*typep))
1913                 debug3("receive packet: type %u", *typep);
1914         if (*typep < SSH2_MSG_MIN || *typep >= SSH2_MSG_LOCAL_MIN) {
1915                 if ((r = sshpkt_disconnect(ssh,
1916                     "Invalid ssh2 packet type: %d", *typep)) != 0 ||
1917                     (r = ssh_packet_write_wait(ssh)) != 0)
1918                         return r;
1919                 return SSH_ERR_PROTOCOL_ERROR;
1920         }
1921         if (state->hook_in != NULL &&
1922             (r = state->hook_in(ssh, state->incoming_packet, typep,
1923             state->hook_in_ctx)) != 0)
1924                 return r;
1925         if (*typep == SSH2_MSG_USERAUTH_SUCCESS && !state->server_side)
1926                 r = ssh_packet_enable_delayed_compress(ssh);
1927         else
1928                 r = 0;
1929 #ifdef PACKET_DEBUG
1930         fprintf(stderr, "read/plain[%d]:\r\n", *typep);
1931         sshbuf_dump(state->incoming_packet, stderr);
1932 #endif
1933         /* reset for next packet */
1934         state->packlen = 0;
1935
1936         /* do we need to rekey? */
1937         if (ssh_packet_need_rekeying(ssh, 0)) {
1938                 debug3("%s: rekex triggered", __func__);
1939                 if ((r = kex_start_rekex(ssh)) != 0)
1940                         return r;
1941         }
1942  out:
1943         return r;
1944 }
1945
1946 int
1947 ssh_packet_read_poll_seqnr(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1948 {
1949         struct session_state *state = ssh->state;
1950         u_int reason, seqnr;
1951         int r;
1952         u_char *msg;
1953
1954         for (;;) {
1955                 msg = NULL;
1956                 if (compat20) {
1957                         r = ssh_packet_read_poll2(ssh, typep, seqnr_p);
1958                         if (r != 0)
1959                                 return r;
1960                         if (*typep) {
1961                                 state->keep_alive_timeouts = 0;
1962                                 DBG(debug("received packet type %d", *typep));
1963                         }
1964                         switch (*typep) {
1965                         case SSH2_MSG_IGNORE:
1966                                 debug3("Received SSH2_MSG_IGNORE");
1967                                 break;
1968                         case SSH2_MSG_DEBUG:
1969                                 if ((r = sshpkt_get_u8(ssh, NULL)) != 0 ||
1970                                     (r = sshpkt_get_string(ssh, &msg, NULL)) != 0 ||
1971                                     (r = sshpkt_get_string(ssh, NULL, NULL)) != 0) {
1972                                         free(msg);
1973                                         return r;
1974                                 }
1975                                 debug("Remote: %.900s", msg);
1976                                 free(msg);
1977                                 break;
1978                         case SSH2_MSG_DISCONNECT:
1979                                 if ((r = sshpkt_get_u32(ssh, &reason)) != 0 ||
1980                                     (r = sshpkt_get_string(ssh, &msg, NULL)) != 0)
1981                                         return r;
1982                                 /* Ignore normal client exit notifications */
1983                                 do_log2(ssh->state->server_side &&
1984                                     reason == SSH2_DISCONNECT_BY_APPLICATION ?
1985                                     SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_ERROR,
1986                                     "Received disconnect from %s port %d:"
1987                                     "%u: %.400s", ssh_remote_ipaddr(ssh),
1988                                     ssh_remote_port(ssh), reason, msg);
1989                                 free(msg);
1990                                 return SSH_ERR_DISCONNECTED;
1991                         case SSH2_MSG_UNIMPLEMENTED:
1992                                 if ((r = sshpkt_get_u32(ssh, &seqnr)) != 0)
1993                                         return r;
1994                                 debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1995                                     seqnr);
1996                                 break;
1997                         default:
1998                                 return 0;
1999                         }
2000                 } else {
2001                         r = ssh_packet_read_poll1(ssh, typep);
2002                         switch (*typep) {
2003                         case SSH_MSG_NONE:
2004                                 return SSH_MSG_NONE;
2005                         case SSH_MSG_IGNORE:
2006                                 break;
2007                         case SSH_MSG_DEBUG:
2008                                 if ((r = sshpkt_get_string(ssh, &msg, NULL)) != 0)
2009                                         return r;
2010                                 debug("Remote: %.900s", msg);
2011                                 free(msg);
2012                                 break;
2013                         case SSH_MSG_DISCONNECT:
2014                                 if ((r = sshpkt_get_string(ssh, &msg, NULL)) != 0)
2015                                         return r;
2016                                 logit("Received disconnect from %s port %d: "
2017                                     "%.400s", ssh_remote_ipaddr(ssh),
2018                                     ssh_remote_port(ssh), msg);
2019                                 free(msg);
2020                                 return SSH_ERR_DISCONNECTED;
2021                         default:
2022                                 DBG(debug("received packet type %d", *typep));
2023                                 return 0;
2024                         }
2025                 }
2026         }
2027 }
2028
2029 /*
2030  * Buffers the given amount of input characters.  This is intended to be used
2031  * together with packet_read_poll.
2032  */
2033
2034 int
2035 ssh_packet_process_incoming(struct ssh *ssh, const char *buf, u_int len)
2036 {
2037         struct session_state *state = ssh->state;
2038         int r;
2039
2040         if (state->packet_discard) {
2041                 state->keep_alive_timeouts = 0; /* ?? */
2042                 if (len >= state->packet_discard) {
2043                         if ((r = ssh_packet_stop_discard(ssh)) != 0)
2044                                 return r;
2045                 }
2046                 state->packet_discard -= len;
2047                 return 0;
2048         }
2049         if ((r = sshbuf_put(ssh->state->input, buf, len)) != 0)
2050                 return r;
2051
2052         return 0;
2053 }
2054
2055 int
2056 ssh_packet_remaining(struct ssh *ssh)
2057 {
2058         return sshbuf_len(ssh->state->incoming_packet);
2059 }
2060
2061 /*
2062  * Sends a diagnostic message from the server to the client.  This message
2063  * can be sent at any time (but not while constructing another message). The
2064  * message is printed immediately, but only if the client is being executed
2065  * in verbose mode.  These messages are primarily intended to ease debugging
2066  * authentication problems.   The length of the formatted message must not
2067  * exceed 1024 bytes.  This will automatically call ssh_packet_write_wait.
2068  */
2069 void
2070 ssh_packet_send_debug(struct ssh *ssh, const char *fmt,...)
2071 {
2072         char buf[1024];
2073         va_list args;
2074         int r;
2075
2076         if (compat20 && (ssh->compat & SSH_BUG_DEBUG))
2077                 return;
2078
2079         va_start(args, fmt);
2080         vsnprintf(buf, sizeof(buf), fmt, args);
2081         va_end(args);
2082
2083         if (compat20) {
2084                 if ((r = sshpkt_start(ssh, SSH2_MSG_DEBUG)) != 0 ||
2085                     (r = sshpkt_put_u8(ssh, 0)) != 0 || /* always display */
2086                     (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
2087                     (r = sshpkt_put_cstring(ssh, "")) != 0 ||
2088                     (r = sshpkt_send(ssh)) != 0)
2089                         fatal("%s: %s", __func__, ssh_err(r));
2090         } else {
2091                 if ((r = sshpkt_start(ssh, SSH_MSG_DEBUG)) != 0 ||
2092                     (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
2093                     (r = sshpkt_send(ssh)) != 0)
2094                         fatal("%s: %s", __func__, ssh_err(r));
2095         }
2096         if ((r = ssh_packet_write_wait(ssh)) != 0)
2097                 fatal("%s: %s", __func__, ssh_err(r));
2098 }
2099
2100 static void
2101 fmt_connection_id(struct ssh *ssh, char *s, size_t l)
2102 {
2103         snprintf(s, l, "%.200s%s%s port %d",
2104             ssh->log_preamble ? ssh->log_preamble : "",
2105             ssh->log_preamble ? " " : "",
2106             ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
2107 }
2108
2109 /*
2110  * Pretty-print connection-terminating errors and exit.
2111  */
2112 void
2113 sshpkt_fatal(struct ssh *ssh, const char *tag, int r)
2114 {
2115         char remote_id[512];
2116
2117         fmt_connection_id(ssh, remote_id, sizeof(remote_id));
2118
2119         switch (r) {
2120         case SSH_ERR_CONN_CLOSED:
2121                 logdie("Connection closed by %s", remote_id);
2122         case SSH_ERR_CONN_TIMEOUT:
2123                 logdie("Connection %s %s timed out",
2124                     ssh->state->server_side ? "from" : "to", remote_id);
2125         case SSH_ERR_DISCONNECTED:
2126                 logdie("Disconnected from %s", remote_id);
2127         case SSH_ERR_SYSTEM_ERROR:
2128                 if (errno == ECONNRESET)
2129                         logdie("Connection reset by %s", remote_id);
2130                 /* FALLTHROUGH */
2131         case SSH_ERR_NO_CIPHER_ALG_MATCH:
2132         case SSH_ERR_NO_MAC_ALG_MATCH:
2133         case SSH_ERR_NO_COMPRESS_ALG_MATCH:
2134         case SSH_ERR_NO_KEX_ALG_MATCH:
2135         case SSH_ERR_NO_HOSTKEY_ALG_MATCH:
2136                 if (ssh && ssh->kex && ssh->kex->failed_choice) {
2137                         BLACKLIST_NOTIFY(BLACKLIST_AUTH_FAIL, "ssh");
2138                         logdie("Unable to negotiate with %s: %s. "
2139                             "Their offer: %s", remote_id, ssh_err(r),
2140                             ssh->kex->failed_choice);
2141                 }
2142                 /* FALLTHROUGH */
2143         default:
2144                 logdie("%s%sConnection %s %s: %s",
2145                     tag != NULL ? tag : "", tag != NULL ? ": " : "",
2146                     ssh->state->server_side ? "from" : "to",
2147                     remote_id, ssh_err(r));
2148         }
2149 }
2150
2151 /*
2152  * Logs the error plus constructs and sends a disconnect packet, closes the
2153  * connection, and exits.  This function never returns. The error message
2154  * should not contain a newline.  The length of the formatted message must
2155  * not exceed 1024 bytes.
2156  */
2157 void
2158 ssh_packet_disconnect(struct ssh *ssh, const char *fmt,...)
2159 {
2160         char buf[1024], remote_id[512];
2161         va_list args;
2162         static int disconnecting = 0;
2163         int r;
2164
2165         if (disconnecting)      /* Guard against recursive invocations. */
2166                 fatal("packet_disconnect called recursively.");
2167         disconnecting = 1;
2168
2169         /*
2170          * Format the message.  Note that the caller must make sure the
2171          * message is of limited size.
2172          */
2173         fmt_connection_id(ssh, remote_id, sizeof(remote_id));
2174         va_start(args, fmt);
2175         vsnprintf(buf, sizeof(buf), fmt, args);
2176         va_end(args);
2177
2178         /* Display the error locally */
2179         logit("Disconnecting %s: %.100s", remote_id, buf);
2180
2181         /*
2182          * Send the disconnect message to the other side, and wait
2183          * for it to get sent.
2184          */
2185         if ((r = sshpkt_disconnect(ssh, "%s", buf)) != 0)
2186                 sshpkt_fatal(ssh, __func__, r);
2187
2188         if ((r = ssh_packet_write_wait(ssh)) != 0)
2189                 sshpkt_fatal(ssh, __func__, r);
2190
2191         /* Close the connection. */
2192         ssh_packet_close(ssh);
2193         cleanup_exit(255);
2194 }
2195
2196 /*
2197  * Checks if there is any buffered output, and tries to write some of
2198  * the output.
2199  */
2200 int
2201 ssh_packet_write_poll(struct ssh *ssh)
2202 {
2203         struct session_state *state = ssh->state;
2204         int len = sshbuf_len(state->output);
2205         int r;
2206
2207         if (len > 0) {
2208                 len = write(state->connection_out,
2209                     sshbuf_ptr(state->output), len);
2210                 if (len == -1) {
2211                         if (errno == EINTR || errno == EAGAIN ||
2212                             errno == EWOULDBLOCK)
2213                                 return 0;
2214                         return SSH_ERR_SYSTEM_ERROR;
2215                 }
2216                 if (len == 0)
2217                         return SSH_ERR_CONN_CLOSED;
2218                 if ((r = sshbuf_consume(state->output, len)) != 0)
2219                         return r;
2220         }
2221         return 0;
2222 }
2223
2224 /*
2225  * Calls packet_write_poll repeatedly until all pending output data has been
2226  * written.
2227  */
2228 int
2229 ssh_packet_write_wait(struct ssh *ssh)
2230 {
2231         fd_set *setp;
2232         int ret, r, ms_remain = 0;
2233         struct timeval start, timeout, *timeoutp = NULL;
2234         struct session_state *state = ssh->state;
2235
2236         setp = calloc(howmany(state->connection_out + 1,
2237             NFDBITS), sizeof(fd_mask));
2238         if (setp == NULL)
2239                 return SSH_ERR_ALLOC_FAIL;
2240         if ((r = ssh_packet_write_poll(ssh)) != 0) {
2241                 free(setp);
2242                 return r;
2243         }
2244         while (ssh_packet_have_data_to_write(ssh)) {
2245                 memset(setp, 0, howmany(state->connection_out + 1,
2246                     NFDBITS) * sizeof(fd_mask));
2247                 FD_SET(state->connection_out, setp);
2248
2249                 if (state->packet_timeout_ms > 0) {
2250                         ms_remain = state->packet_timeout_ms;
2251                         timeoutp = &timeout;
2252                 }
2253                 for (;;) {
2254                         if (state->packet_timeout_ms != -1) {
2255                                 ms_to_timeval(&timeout, ms_remain);
2256                                 gettimeofday(&start, NULL);
2257                         }
2258                         if ((ret = select(state->connection_out + 1,
2259                             NULL, setp, NULL, timeoutp)) >= 0)
2260                                 break;
2261                         if (errno != EAGAIN && errno != EINTR &&
2262                             errno != EWOULDBLOCK)
2263                                 break;
2264                         if (state->packet_timeout_ms == -1)
2265                                 continue;
2266                         ms_subtract_diff(&start, &ms_remain);
2267                         if (ms_remain <= 0) {
2268                                 ret = 0;
2269                                 break;
2270                         }
2271                 }
2272                 if (ret == 0) {
2273                         free(setp);
2274                         return SSH_ERR_CONN_TIMEOUT;
2275                 }
2276                 if ((r = ssh_packet_write_poll(ssh)) != 0) {
2277                         free(setp);
2278                         return r;
2279                 }
2280         }
2281         free(setp);
2282         return 0;
2283 }
2284
2285 /* Returns true if there is buffered data to write to the connection. */
2286
2287 int
2288 ssh_packet_have_data_to_write(struct ssh *ssh)
2289 {
2290         return sshbuf_len(ssh->state->output) != 0;
2291 }
2292
2293 /* Returns true if there is not too much data to write to the connection. */
2294
2295 int
2296 ssh_packet_not_very_much_data_to_write(struct ssh *ssh)
2297 {
2298         if (ssh->state->interactive_mode)
2299                 return sshbuf_len(ssh->state->output) < 16384;
2300         else
2301                 return sshbuf_len(ssh->state->output) < 128 * 1024;
2302 }
2303
2304 void
2305 ssh_packet_set_tos(struct ssh *ssh, int tos)
2306 {
2307 #ifndef IP_TOS_IS_BROKEN
2308         if (!ssh_packet_connection_is_on_socket(ssh))
2309                 return;
2310         switch (ssh_packet_connection_af(ssh)) {
2311 # ifdef IP_TOS
2312         case AF_INET:
2313                 debug3("%s: set IP_TOS 0x%02x", __func__, tos);
2314                 if (setsockopt(ssh->state->connection_in,
2315                     IPPROTO_IP, IP_TOS, &tos, sizeof(tos)) < 0)
2316                         error("setsockopt IP_TOS %d: %.100s:",
2317                             tos, strerror(errno));
2318                 break;
2319 # endif /* IP_TOS */
2320 # ifdef IPV6_TCLASS
2321         case AF_INET6:
2322                 debug3("%s: set IPV6_TCLASS 0x%02x", __func__, tos);
2323                 if (setsockopt(ssh->state->connection_in,
2324                     IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof(tos)) < 0)
2325                         error("setsockopt IPV6_TCLASS %d: %.100s:",
2326                             tos, strerror(errno));
2327                 break;
2328 # endif /* IPV6_TCLASS */
2329         }
2330 #endif /* IP_TOS_IS_BROKEN */
2331 }
2332
2333 /* Informs that the current session is interactive.  Sets IP flags for that. */
2334
2335 void
2336 ssh_packet_set_interactive(struct ssh *ssh, int interactive, int qos_interactive, int qos_bulk)
2337 {
2338         struct session_state *state = ssh->state;
2339
2340         if (state->set_interactive_called)
2341                 return;
2342         state->set_interactive_called = 1;
2343
2344         /* Record that we are in interactive mode. */
2345         state->interactive_mode = interactive;
2346
2347         /* Only set socket options if using a socket.  */
2348         if (!ssh_packet_connection_is_on_socket(ssh))
2349                 return;
2350         set_nodelay(state->connection_in);
2351         ssh_packet_set_tos(ssh, interactive ? qos_interactive :
2352             qos_bulk);
2353 }
2354
2355 /* Returns true if the current connection is interactive. */
2356
2357 int
2358 ssh_packet_is_interactive(struct ssh *ssh)
2359 {
2360         return ssh->state->interactive_mode;
2361 }
2362
2363 int
2364 ssh_packet_set_maxsize(struct ssh *ssh, u_int s)
2365 {
2366         struct session_state *state = ssh->state;
2367
2368         if (state->set_maxsize_called) {
2369                 logit("packet_set_maxsize: called twice: old %d new %d",
2370                     state->max_packet_size, s);
2371                 return -1;
2372         }
2373         if (s < 4 * 1024 || s > 1024 * 1024) {
2374                 logit("packet_set_maxsize: bad size %d", s);
2375                 return -1;
2376         }
2377         state->set_maxsize_called = 1;
2378         debug("packet_set_maxsize: setting to %d", s);
2379         state->max_packet_size = s;
2380         return s;
2381 }
2382
2383 int
2384 ssh_packet_inc_alive_timeouts(struct ssh *ssh)
2385 {
2386         return ++ssh->state->keep_alive_timeouts;
2387 }
2388
2389 void
2390 ssh_packet_set_alive_timeouts(struct ssh *ssh, int ka)
2391 {
2392         ssh->state->keep_alive_timeouts = ka;
2393 }
2394
2395 u_int
2396 ssh_packet_get_maxsize(struct ssh *ssh)
2397 {
2398         return ssh->state->max_packet_size;
2399 }
2400
2401 /*
2402  * 9.2.  Ignored Data Message
2403  *
2404  *   byte      SSH_MSG_IGNORE
2405  *   string    data
2406  *
2407  * All implementations MUST understand (and ignore) this message at any
2408  * time (after receiving the protocol version). No implementation is
2409  * required to send them. This message can be used as an additional
2410  * protection measure against advanced traffic analysis techniques.
2411  */
2412 void
2413 ssh_packet_send_ignore(struct ssh *ssh, int nbytes)
2414 {
2415         u_int32_t rnd = 0;
2416         int r, i;
2417
2418         if ((r = sshpkt_start(ssh, compat20 ?
2419             SSH2_MSG_IGNORE : SSH_MSG_IGNORE)) != 0 ||
2420             (r = sshpkt_put_u32(ssh, nbytes)) != 0)
2421                 fatal("%s: %s", __func__, ssh_err(r));
2422         for (i = 0; i < nbytes; i++) {
2423                 if (i % 4 == 0)
2424                         rnd = arc4random();
2425                 if ((r = sshpkt_put_u8(ssh, (u_char)rnd & 0xff)) != 0)
2426                         fatal("%s: %s", __func__, ssh_err(r));
2427                 rnd >>= 8;
2428         }
2429 }
2430
2431 void
2432 ssh_packet_set_rekey_limits(struct ssh *ssh, u_int64_t bytes, u_int32_t seconds)
2433 {
2434         debug3("rekey after %llu bytes, %u seconds", (unsigned long long)bytes,
2435             (unsigned int)seconds);
2436         ssh->state->rekey_limit = bytes;
2437         ssh->state->rekey_interval = seconds;
2438 }
2439
2440 time_t
2441 ssh_packet_get_rekey_timeout(struct ssh *ssh)
2442 {
2443         time_t seconds;
2444
2445         seconds = ssh->state->rekey_time + ssh->state->rekey_interval -
2446             monotime();
2447         return (seconds <= 0 ? 1 : seconds);
2448 }
2449
2450 void
2451 ssh_packet_set_server(struct ssh *ssh)
2452 {
2453         ssh->state->server_side = 1;
2454 }
2455
2456 void
2457 ssh_packet_set_authenticated(struct ssh *ssh)
2458 {
2459         ssh->state->after_authentication = 1;
2460 }
2461
2462 void *
2463 ssh_packet_get_input(struct ssh *ssh)
2464 {
2465         return (void *)ssh->state->input;
2466 }
2467
2468 void *
2469 ssh_packet_get_output(struct ssh *ssh)
2470 {
2471         return (void *)ssh->state->output;
2472 }
2473
2474 /* Reset after_authentication and reset compression in post-auth privsep */
2475 static int
2476 ssh_packet_set_postauth(struct ssh *ssh)
2477 {
2478         int r;
2479
2480         debug("%s: called", __func__);
2481         /* This was set in net child, but is not visible in user child */
2482         ssh->state->after_authentication = 1;
2483         ssh->state->rekeying = 0;
2484         if ((r = ssh_packet_enable_delayed_compress(ssh)) != 0)
2485                 return r;
2486         return 0;
2487 }
2488
2489 /* Packet state (de-)serialization for privsep */
2490
2491 /* turn kex into a blob for packet state serialization */
2492 static int
2493 kex_to_blob(struct sshbuf *m, struct kex *kex)
2494 {
2495         int r;
2496
2497         if ((r = sshbuf_put_string(m, kex->session_id,
2498             kex->session_id_len)) != 0 ||
2499             (r = sshbuf_put_u32(m, kex->we_need)) != 0 ||
2500             (r = sshbuf_put_u32(m, kex->hostkey_type)) != 0 ||
2501             (r = sshbuf_put_u32(m, kex->kex_type)) != 0 ||
2502             (r = sshbuf_put_stringb(m, kex->my)) != 0 ||
2503             (r = sshbuf_put_stringb(m, kex->peer)) != 0 ||
2504             (r = sshbuf_put_u32(m, kex->flags)) != 0 ||
2505             (r = sshbuf_put_cstring(m, kex->client_version_string)) != 0 ||
2506             (r = sshbuf_put_cstring(m, kex->server_version_string)) != 0)
2507                 return r;
2508         return 0;
2509 }
2510
2511 /* turn key exchange results into a blob for packet state serialization */
2512 static int
2513 newkeys_to_blob(struct sshbuf *m, struct ssh *ssh, int mode)
2514 {
2515         struct sshbuf *b;
2516         struct sshcipher_ctx *cc;
2517         struct sshcomp *comp;
2518         struct sshenc *enc;
2519         struct sshmac *mac;
2520         struct newkeys *newkey;
2521         int r;
2522
2523         if ((newkey = ssh->state->newkeys[mode]) == NULL)
2524                 return SSH_ERR_INTERNAL_ERROR;
2525         enc = &newkey->enc;
2526         mac = &newkey->mac;
2527         comp = &newkey->comp;
2528         cc = (mode == MODE_OUT) ? ssh->state->send_context :
2529             ssh->state->receive_context;
2530         if ((r = cipher_get_keyiv(cc, enc->iv, enc->iv_len)) != 0)
2531                 return r;
2532         if ((b = sshbuf_new()) == NULL)
2533                 return SSH_ERR_ALLOC_FAIL;
2534         /* The cipher struct is constant and shared, you export pointer */
2535         if ((r = sshbuf_put_cstring(b, enc->name)) != 0 ||
2536             (r = sshbuf_put(b, &enc->cipher, sizeof(enc->cipher))) != 0 ||
2537             (r = sshbuf_put_u32(b, enc->enabled)) != 0 ||
2538             (r = sshbuf_put_u32(b, enc->block_size)) != 0 ||
2539             (r = sshbuf_put_string(b, enc->key, enc->key_len)) != 0 ||
2540             (r = sshbuf_put_string(b, enc->iv, enc->iv_len)) != 0)
2541                 goto out;
2542         if (cipher_authlen(enc->cipher) == 0) {
2543                 if ((r = sshbuf_put_cstring(b, mac->name)) != 0 ||
2544                     (r = sshbuf_put_u32(b, mac->enabled)) != 0 ||
2545                     (r = sshbuf_put_string(b, mac->key, mac->key_len)) != 0)
2546                         goto out;
2547         }
2548         if ((r = sshbuf_put_u32(b, comp->type)) != 0 ||
2549             (r = sshbuf_put_cstring(b, comp->name)) != 0)
2550                 goto out;
2551         r = sshbuf_put_stringb(m, b);
2552  out:
2553         sshbuf_free(b);
2554         return r;
2555 }
2556
2557 /* serialize packet state into a blob */
2558 int
2559 ssh_packet_get_state(struct ssh *ssh, struct sshbuf *m)
2560 {
2561         struct session_state *state = ssh->state;
2562         u_char *p;
2563         size_t slen, rlen;
2564         int r, ssh1cipher;
2565
2566         if (!compat20) {
2567                 ssh1cipher = cipher_ctx_get_number(state->receive_context);
2568                 slen = cipher_get_keyiv_len(state->send_context);
2569                 rlen = cipher_get_keyiv_len(state->receive_context);
2570                 if ((r = sshbuf_put_u32(m, state->remote_protocol_flags)) != 0 ||
2571                     (r = sshbuf_put_u32(m, ssh1cipher)) != 0 ||
2572                     (r = sshbuf_put_string(m, state->ssh1_key, state->ssh1_keylen)) != 0 ||
2573                     (r = sshbuf_put_u32(m, slen)) != 0 ||
2574                     (r = sshbuf_reserve(m, slen, &p)) != 0 ||
2575                     (r = cipher_get_keyiv(state->send_context, p, slen)) != 0 ||
2576                     (r = sshbuf_put_u32(m, rlen)) != 0 ||
2577                     (r = sshbuf_reserve(m, rlen, &p)) != 0 ||
2578                     (r = cipher_get_keyiv(state->receive_context, p, rlen)) != 0)
2579                         return r;
2580         } else {
2581                 if ((r = kex_to_blob(m, ssh->kex)) != 0 ||
2582                     (r = newkeys_to_blob(m, ssh, MODE_OUT)) != 0 ||
2583                     (r = newkeys_to_blob(m, ssh, MODE_IN)) != 0 ||
2584                     (r = sshbuf_put_u64(m, state->rekey_limit)) != 0 ||
2585                     (r = sshbuf_put_u32(m, state->rekey_interval)) != 0 ||
2586                     (r = sshbuf_put_u32(m, state->p_send.seqnr)) != 0 ||
2587                     (r = sshbuf_put_u64(m, state->p_send.blocks)) != 0 ||
2588                     (r = sshbuf_put_u32(m, state->p_send.packets)) != 0 ||
2589                     (r = sshbuf_put_u64(m, state->p_send.bytes)) != 0 ||
2590                     (r = sshbuf_put_u32(m, state->p_read.seqnr)) != 0 ||
2591                     (r = sshbuf_put_u64(m, state->p_read.blocks)) != 0 ||
2592                     (r = sshbuf_put_u32(m, state->p_read.packets)) != 0 ||
2593                     (r = sshbuf_put_u64(m, state->p_read.bytes)) != 0)
2594                         return r;
2595         }
2596
2597         slen = cipher_get_keycontext(state->send_context, NULL);
2598         rlen = cipher_get_keycontext(state->receive_context, NULL);
2599         if ((r = sshbuf_put_u32(m, slen)) != 0 ||
2600             (r = sshbuf_reserve(m, slen, &p)) != 0)
2601                 return r;
2602         if (cipher_get_keycontext(state->send_context, p) != (int)slen)
2603                 return SSH_ERR_INTERNAL_ERROR;
2604         if ((r = sshbuf_put_u32(m, rlen)) != 0 ||
2605             (r = sshbuf_reserve(m, rlen, &p)) != 0)
2606                 return r;
2607         if (cipher_get_keycontext(state->receive_context, p) != (int)rlen)
2608                 return SSH_ERR_INTERNAL_ERROR;
2609         if ((r = sshbuf_put_stringb(m, state->input)) != 0 ||
2610             (r = sshbuf_put_stringb(m, state->output)) != 0)
2611                 return r;
2612
2613         return 0;
2614 }
2615
2616 /* restore key exchange results from blob for packet state de-serialization */
2617 static int
2618 newkeys_from_blob(struct sshbuf *m, struct ssh *ssh, int mode)
2619 {
2620         struct sshbuf *b = NULL;
2621         struct sshcomp *comp;
2622         struct sshenc *enc;
2623         struct sshmac *mac;
2624         struct newkeys *newkey = NULL;
2625         size_t keylen, ivlen, maclen;
2626         int r;
2627
2628         if ((newkey = calloc(1, sizeof(*newkey))) == NULL) {
2629                 r = SSH_ERR_ALLOC_FAIL;
2630                 goto out;
2631         }
2632         if ((r = sshbuf_froms(m, &b)) != 0)
2633                 goto out;
2634 #ifdef DEBUG_PK
2635         sshbuf_dump(b, stderr);
2636 #endif
2637         enc = &newkey->enc;
2638         mac = &newkey->mac;
2639         comp = &newkey->comp;
2640
2641         if ((r = sshbuf_get_cstring(b, &enc->name, NULL)) != 0 ||
2642             (r = sshbuf_get(b, &enc->cipher, sizeof(enc->cipher))) != 0 ||
2643             (r = sshbuf_get_u32(b, (u_int *)&enc->enabled)) != 0 ||
2644             (r = sshbuf_get_u32(b, &enc->block_size)) != 0 ||
2645             (r = sshbuf_get_string(b, &enc->key, &keylen)) != 0 ||
2646             (r = sshbuf_get_string(b, &enc->iv, &ivlen)) != 0)
2647                 goto out;
2648         if (cipher_authlen(enc->cipher) == 0) {
2649                 if ((r = sshbuf_get_cstring(b, &mac->name, NULL)) != 0)
2650                         goto out;
2651                 if ((r = mac_setup(mac, mac->name)) != 0)
2652                         goto out;
2653                 if ((r = sshbuf_get_u32(b, (u_int *)&mac->enabled)) != 0 ||
2654                     (r = sshbuf_get_string(b, &mac->key, &maclen)) != 0)
2655                         goto out;
2656                 if (maclen > mac->key_len) {
2657                         r = SSH_ERR_INVALID_FORMAT;
2658                         goto out;
2659                 }
2660                 mac->key_len = maclen;
2661         }
2662         if ((r = sshbuf_get_u32(b, &comp->type)) != 0 ||
2663             (r = sshbuf_get_cstring(b, &comp->name, NULL)) != 0)
2664                 goto out;
2665         if (enc->name == NULL ||
2666             cipher_by_name(enc->name) != enc->cipher) {
2667                 r = SSH_ERR_INVALID_FORMAT;
2668                 goto out;
2669         }
2670         if (sshbuf_len(b) != 0) {
2671                 r = SSH_ERR_INVALID_FORMAT;
2672                 goto out;
2673         }
2674         enc->key_len = keylen;
2675         enc->iv_len = ivlen;
2676         ssh->kex->newkeys[mode] = newkey;
2677         newkey = NULL;
2678         r = 0;
2679  out:
2680         free(newkey);
2681         sshbuf_free(b);
2682         return r;
2683 }
2684
2685 /* restore kex from blob for packet state de-serialization */
2686 static int
2687 kex_from_blob(struct sshbuf *m, struct kex **kexp)
2688 {
2689         struct kex *kex;
2690         int r;
2691
2692         if ((kex = calloc(1, sizeof(struct kex))) == NULL ||
2693             (kex->my = sshbuf_new()) == NULL ||
2694             (kex->peer = sshbuf_new()) == NULL) {
2695                 r = SSH_ERR_ALLOC_FAIL;
2696                 goto out;
2697         }
2698         if ((r = sshbuf_get_string(m, &kex->session_id, &kex->session_id_len)) != 0 ||
2699             (r = sshbuf_get_u32(m, &kex->we_need)) != 0 ||
2700             (r = sshbuf_get_u32(m, (u_int *)&kex->hostkey_type)) != 0 ||
2701             (r = sshbuf_get_u32(m, &kex->kex_type)) != 0 ||
2702             (r = sshbuf_get_stringb(m, kex->my)) != 0 ||
2703             (r = sshbuf_get_stringb(m, kex->peer)) != 0 ||
2704             (r = sshbuf_get_u32(m, &kex->flags)) != 0 ||
2705             (r = sshbuf_get_cstring(m, &kex->client_version_string, NULL)) != 0 ||
2706             (r = sshbuf_get_cstring(m, &kex->server_version_string, NULL)) != 0)
2707                 goto out;
2708         kex->server = 1;
2709         kex->done = 1;
2710         r = 0;
2711  out:
2712         if (r != 0 || kexp == NULL) {
2713                 if (kex != NULL) {
2714                         sshbuf_free(kex->my);
2715                         sshbuf_free(kex->peer);
2716                         free(kex);
2717                 }
2718                 if (kexp != NULL)
2719                         *kexp = NULL;
2720         } else {
2721                 *kexp = kex;
2722         }
2723         return r;
2724 }
2725
2726 /*
2727  * Restore packet state from content of blob 'm' (de-serialization).
2728  * Note that 'm' will be partially consumed on parsing or any other errors.
2729  */
2730 int
2731 ssh_packet_set_state(struct ssh *ssh, struct sshbuf *m)
2732 {
2733         struct session_state *state = ssh->state;
2734         const u_char *ssh1key, *ivin, *ivout, *keyin, *keyout, *input, *output;
2735         size_t ssh1keylen, rlen, slen, ilen, olen;
2736         int r;
2737         u_int ssh1cipher = 0;
2738
2739         if (!compat20) {
2740                 if ((r = sshbuf_get_u32(m, &state->remote_protocol_flags)) != 0 ||
2741                     (r = sshbuf_get_u32(m, &ssh1cipher)) != 0 ||
2742                     (r = sshbuf_get_string_direct(m, &ssh1key, &ssh1keylen)) != 0 ||
2743                     (r = sshbuf_get_string_direct(m, &ivout, &slen)) != 0 ||
2744                     (r = sshbuf_get_string_direct(m, &ivin, &rlen)) != 0)
2745                         return r;
2746                 if (ssh1cipher > INT_MAX)
2747                         return SSH_ERR_KEY_UNKNOWN_CIPHER;
2748                 ssh_packet_set_encryption_key(ssh, ssh1key, ssh1keylen,
2749                     (int)ssh1cipher);
2750                 if (cipher_get_keyiv_len(state->send_context) != (int)slen ||
2751                     cipher_get_keyiv_len(state->receive_context) != (int)rlen)
2752                         return SSH_ERR_INVALID_FORMAT;
2753                 if ((r = cipher_set_keyiv(state->send_context, ivout)) != 0 ||
2754                     (r = cipher_set_keyiv(state->receive_context, ivin)) != 0)
2755                         return r;
2756         } else {
2757                 if ((r = kex_from_blob(m, &ssh->kex)) != 0 ||
2758                     (r = newkeys_from_blob(m, ssh, MODE_OUT)) != 0 ||
2759                     (r = newkeys_from_blob(m, ssh, MODE_IN)) != 0 ||
2760                     (r = sshbuf_get_u64(m, &state->rekey_limit)) != 0 ||
2761                     (r = sshbuf_get_u32(m, &state->rekey_interval)) != 0 ||
2762                     (r = sshbuf_get_u32(m, &state->p_send.seqnr)) != 0 ||
2763                     (r = sshbuf_get_u64(m, &state->p_send.blocks)) != 0 ||
2764                     (r = sshbuf_get_u32(m, &state->p_send.packets)) != 0 ||
2765                     (r = sshbuf_get_u64(m, &state->p_send.bytes)) != 0 ||
2766                     (r = sshbuf_get_u32(m, &state->p_read.seqnr)) != 0 ||
2767                     (r = sshbuf_get_u64(m, &state->p_read.blocks)) != 0 ||
2768                     (r = sshbuf_get_u32(m, &state->p_read.packets)) != 0 ||
2769                     (r = sshbuf_get_u64(m, &state->p_read.bytes)) != 0)
2770                         return r;
2771                 /*
2772                  * We set the time here so that in post-auth privsep slave we
2773                  * count from the completion of the authentication.
2774                  */
2775                 state->rekey_time = monotime();
2776                 /* XXX ssh_set_newkeys overrides p_read.packets? XXX */
2777                 if ((r = ssh_set_newkeys(ssh, MODE_IN)) != 0 ||
2778                     (r = ssh_set_newkeys(ssh, MODE_OUT)) != 0)
2779                         return r;
2780         }
2781         if ((r = sshbuf_get_string_direct(m, &keyout, &slen)) != 0 ||
2782             (r = sshbuf_get_string_direct(m, &keyin, &rlen)) != 0)
2783                 return r;
2784         if (cipher_get_keycontext(state->send_context, NULL) != (int)slen ||
2785             cipher_get_keycontext(state->receive_context, NULL) != (int)rlen)
2786                 return SSH_ERR_INVALID_FORMAT;
2787         cipher_set_keycontext(state->send_context, keyout);
2788         cipher_set_keycontext(state->receive_context, keyin);
2789
2790         if ((r = ssh_packet_set_postauth(ssh)) != 0)
2791                 return r;
2792
2793         sshbuf_reset(state->input);
2794         sshbuf_reset(state->output);
2795         if ((r = sshbuf_get_string_direct(m, &input, &ilen)) != 0 ||
2796             (r = sshbuf_get_string_direct(m, &output, &olen)) != 0 ||
2797             (r = sshbuf_put(state->input, input, ilen)) != 0 ||
2798             (r = sshbuf_put(state->output, output, olen)) != 0)
2799                 return r;
2800
2801         if (sshbuf_len(m))
2802                 return SSH_ERR_INVALID_FORMAT;
2803         debug3("%s: done", __func__);
2804         return 0;
2805 }
2806
2807 /* NEW API */
2808
2809 /* put data to the outgoing packet */
2810
2811 int
2812 sshpkt_put(struct ssh *ssh, const void *v, size_t len)
2813 {
2814         return sshbuf_put(ssh->state->outgoing_packet, v, len);
2815 }
2816
2817 int
2818 sshpkt_putb(struct ssh *ssh, const struct sshbuf *b)
2819 {
2820         return sshbuf_putb(ssh->state->outgoing_packet, b);
2821 }
2822
2823 int
2824 sshpkt_put_u8(struct ssh *ssh, u_char val)
2825 {
2826         return sshbuf_put_u8(ssh->state->outgoing_packet, val);
2827 }
2828
2829 int
2830 sshpkt_put_u32(struct ssh *ssh, u_int32_t val)
2831 {
2832         return sshbuf_put_u32(ssh->state->outgoing_packet, val);
2833 }
2834
2835 int
2836 sshpkt_put_u64(struct ssh *ssh, u_int64_t val)
2837 {
2838         return sshbuf_put_u64(ssh->state->outgoing_packet, val);
2839 }
2840
2841 int
2842 sshpkt_put_string(struct ssh *ssh, const void *v, size_t len)
2843 {
2844         return sshbuf_put_string(ssh->state->outgoing_packet, v, len);
2845 }
2846
2847 int
2848 sshpkt_put_cstring(struct ssh *ssh, const void *v)
2849 {
2850         return sshbuf_put_cstring(ssh->state->outgoing_packet, v);
2851 }
2852
2853 int
2854 sshpkt_put_stringb(struct ssh *ssh, const struct sshbuf *v)
2855 {
2856         return sshbuf_put_stringb(ssh->state->outgoing_packet, v);
2857 }
2858
2859 #ifdef WITH_OPENSSL
2860 #ifdef OPENSSL_HAS_ECC
2861 int
2862 sshpkt_put_ec(struct ssh *ssh, const EC_POINT *v, const EC_GROUP *g)
2863 {
2864         return sshbuf_put_ec(ssh->state->outgoing_packet, v, g);
2865 }
2866 #endif /* OPENSSL_HAS_ECC */
2867
2868 #ifdef WITH_SSH1
2869 int
2870 sshpkt_put_bignum1(struct ssh *ssh, const BIGNUM *v)
2871 {
2872         return sshbuf_put_bignum1(ssh->state->outgoing_packet, v);
2873 }
2874 #endif /* WITH_SSH1 */
2875
2876 int
2877 sshpkt_put_bignum2(struct ssh *ssh, const BIGNUM *v)
2878 {
2879         return sshbuf_put_bignum2(ssh->state->outgoing_packet, v);
2880 }
2881 #endif /* WITH_OPENSSL */
2882
2883 /* fetch data from the incoming packet */
2884
2885 int
2886 sshpkt_get(struct ssh *ssh, void *valp, size_t len)
2887 {
2888         return sshbuf_get(ssh->state->incoming_packet, valp, len);
2889 }
2890
2891 int
2892 sshpkt_get_u8(struct ssh *ssh, u_char *valp)
2893 {
2894         return sshbuf_get_u8(ssh->state->incoming_packet, valp);
2895 }
2896
2897 int
2898 sshpkt_get_u32(struct ssh *ssh, u_int32_t *valp)
2899 {
2900         return sshbuf_get_u32(ssh->state->incoming_packet, valp);
2901 }
2902
2903 int
2904 sshpkt_get_u64(struct ssh *ssh, u_int64_t *valp)
2905 {
2906         return sshbuf_get_u64(ssh->state->incoming_packet, valp);
2907 }
2908
2909 int
2910 sshpkt_get_string(struct ssh *ssh, u_char **valp, size_t *lenp)
2911 {
2912         return sshbuf_get_string(ssh->state->incoming_packet, valp, lenp);
2913 }
2914
2915 int
2916 sshpkt_get_string_direct(struct ssh *ssh, const u_char **valp, size_t *lenp)
2917 {
2918         return sshbuf_get_string_direct(ssh->state->incoming_packet, valp, lenp);
2919 }
2920
2921 int
2922 sshpkt_get_cstring(struct ssh *ssh, char **valp, size_t *lenp)
2923 {
2924         return sshbuf_get_cstring(ssh->state->incoming_packet, valp, lenp);
2925 }
2926
2927 #ifdef WITH_OPENSSL
2928 #ifdef OPENSSL_HAS_ECC
2929 int
2930 sshpkt_get_ec(struct ssh *ssh, EC_POINT *v, const EC_GROUP *g)
2931 {
2932         return sshbuf_get_ec(ssh->state->incoming_packet, v, g);
2933 }
2934 #endif /* OPENSSL_HAS_ECC */
2935
2936 #ifdef WITH_SSH1
2937 int
2938 sshpkt_get_bignum1(struct ssh *ssh, BIGNUM *v)
2939 {
2940         return sshbuf_get_bignum1(ssh->state->incoming_packet, v);
2941 }
2942 #endif /* WITH_SSH1 */
2943
2944 int
2945 sshpkt_get_bignum2(struct ssh *ssh, BIGNUM *v)
2946 {
2947         return sshbuf_get_bignum2(ssh->state->incoming_packet, v);
2948 }
2949 #endif /* WITH_OPENSSL */
2950
2951 int
2952 sshpkt_get_end(struct ssh *ssh)
2953 {
2954         if (sshbuf_len(ssh->state->incoming_packet) > 0)
2955                 return SSH_ERR_UNEXPECTED_TRAILING_DATA;
2956         return 0;
2957 }
2958
2959 const u_char *
2960 sshpkt_ptr(struct ssh *ssh, size_t *lenp)
2961 {
2962         if (lenp != NULL)
2963                 *lenp = sshbuf_len(ssh->state->incoming_packet);
2964         return sshbuf_ptr(ssh->state->incoming_packet);
2965 }
2966
2967 /* start a new packet */
2968
2969 int
2970 sshpkt_start(struct ssh *ssh, u_char type)
2971 {
2972         u_char buf[9];
2973         int len;
2974
2975         DBG(debug("packet_start[%d]", type));
2976         len = compat20 ? 6 : 9;
2977         memset(buf, 0, len - 1);
2978         buf[len - 1] = type;
2979         sshbuf_reset(ssh->state->outgoing_packet);
2980         return sshbuf_put(ssh->state->outgoing_packet, buf, len);
2981 }
2982
2983 static int
2984 ssh_packet_send_mux(struct ssh *ssh)
2985 {
2986         struct session_state *state = ssh->state;
2987         u_char type, *cp;
2988         size_t len;
2989         int r;
2990
2991         if (ssh->kex)
2992                 return SSH_ERR_INTERNAL_ERROR;
2993         len = sshbuf_len(state->outgoing_packet);
2994         if (len < 6)
2995                 return SSH_ERR_INTERNAL_ERROR;
2996         cp = sshbuf_mutable_ptr(state->outgoing_packet);
2997         type = cp[5];
2998         if (ssh_packet_log_type(type))
2999                 debug3("%s: type %u", __func__, type);
3000         /* drop everything, but the connection protocol */
3001         if (type >= SSH2_MSG_CONNECTION_MIN &&
3002             type <= SSH2_MSG_CONNECTION_MAX) {
3003                 POKE_U32(cp, len - 4);
3004                 if ((r = sshbuf_putb(state->output,
3005                     state->outgoing_packet)) != 0)
3006                         return r;
3007                 /* sshbuf_dump(state->output, stderr); */
3008         }
3009         sshbuf_reset(state->outgoing_packet);
3010         return 0;
3011 }
3012
3013 /* send it */
3014
3015 int
3016 sshpkt_send(struct ssh *ssh)
3017 {
3018         if (ssh->state && ssh->state->mux)
3019                 return ssh_packet_send_mux(ssh);
3020         if (compat20)
3021                 return ssh_packet_send2(ssh);
3022         else
3023                 return ssh_packet_send1(ssh);
3024 }
3025
3026 int
3027 sshpkt_disconnect(struct ssh *ssh, const char *fmt,...)
3028 {
3029         char buf[1024];
3030         va_list args;
3031         int r;
3032
3033         va_start(args, fmt);
3034         vsnprintf(buf, sizeof(buf), fmt, args);
3035         va_end(args);
3036
3037         if (compat20) {
3038                 if ((r = sshpkt_start(ssh, SSH2_MSG_DISCONNECT)) != 0 ||
3039                     (r = sshpkt_put_u32(ssh, SSH2_DISCONNECT_PROTOCOL_ERROR)) != 0 ||
3040                     (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
3041                     (r = sshpkt_put_cstring(ssh, "")) != 0 ||
3042                     (r = sshpkt_send(ssh)) != 0)
3043                         return r;
3044         } else {
3045                 if ((r = sshpkt_start(ssh, SSH_MSG_DISCONNECT)) != 0 ||
3046                     (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
3047                     (r = sshpkt_send(ssh)) != 0)
3048                         return r;
3049         }
3050         return 0;
3051 }
3052
3053 /* roundup current message to pad bytes */
3054 int
3055 sshpkt_add_padding(struct ssh *ssh, u_char pad)
3056 {
3057         ssh->state->extra_pad = pad;
3058         return 0;
3059 }