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