Debian Codegraph @

contrib/mod_sftp/packet.c

raw symbols SCIP
1 /*
2 * ProFTPD - mod_sftp packet IO
3 * Copyright (c) 2008-2024 TJ Saunders
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA.
18 *
19 * As a special exemption, TJ Saunders and other respective copyright holders
20 * give permission to link this program with OpenSSL, and distribute the
21 * resulting executable, without including the source code for OpenSSL in the
22 * source distribution.
23 */
24
25 #include "mod_sftp.h"
26 #include "ssh2.h"
27 #include "packet.h"
28 #include "msg.h"
29 #include "disconnect.h"
30 #include "cipher.h"
31 #include "mac.h"
32 #include "compress.h"
33 #include "kex.h"
34 #include "keys.h"
35 #include "service.h"
36 #include "auth.h"
37 #include "channel.h"
38 #include "tap.h"
39
40 #define SFTP_PACKET_IO_RD 5
41 #define SFTP_PACKET_IO_WR 7
42
43 extern pr_response_t *resp_list, *resp_err_list;
44
45 extern module sftp_module;
46
47 /* Customizable callback for handling all SSH2 packets. */
48 static int (*packet_handler)(void *) = NULL;
49
50 static uint32_t packet_client_seqno = 0;
51 static uint32_t packet_server_seqno = 0;
52
53 /* Maximum length of the payload data of an SSH2 packet we're willing to
54 * accept. Any packets reporting a payload length longer than this will be
55 * ignored/dropped.
56 */
57 #define SFTP_PACKET_MAX_PAYLOAD_LEN (256 * 1024)
58
59 /* RFC4344 recommends 2^31 for the client packet sequence number at which
60 * we should request a rekey, and 2^32 for the server packet sequence number.
61 *
62 * However, the uint32_t data type may not be unsigned for some
63 * platforms/compilers. To avoid issues on these platforms, use 2^31-1
64 * for rekeying for both client and server packet sequence numbers.
65 */
66 #define SFTP_PACKET_CLIENT_REKEY_SEQNO_LIMIT 2147483647
67 #define SFTP_PACKET_SERVER_REKEY_SEQNO_LIMIT 2147483647
68
69 static uint32_t rekey_client_seqno = SFTP_PACKET_CLIENT_REKEY_SEQNO_LIMIT;
70 static uint32_t rekey_server_seqno = SFTP_PACKET_SERVER_REKEY_SEQNO_LIMIT;
71
72 static off_t rekey_client_len = 0;
73 static off_t rekey_server_len = 0;
74 static off_t rekey_size = 0;
75
76 static int poll_timeout = -1;
77 static time_t last_recvd, last_sent;
78
79 static const char *server_version = SFTP_ID_DEFAULT_STRING;
80 static const char *version_id = SFTP_ID_DEFAULT_STRING "\r\n";
81 static int sent_version_id = FALSE;
82
83 static void is_client_alive(void);
84
85 /* Count of the number of "client alive" messages sent without a response. */
86 static unsigned int client_alive_max = 0, client_alive_count = 0;
87 static unsigned int client_alive_interval = 0;
88
89 static const char *trace_channel = "ssh2";
90 static const char *timing_channel = "timing";
91
92 /* This is admittedly an arbitrary upper limit on the number of EXT_INFO
93 * extensions we will handle.
94 *
95 * draft-ssh-ext-info-05 currently defines five:
96 *
97 * server-sig-algs
98 * no-flow-control
99 * accept-channels
100 * elevation
101 * delay-compression
102 *
103 * And some implementations, like OpenSSH, will have their own namespaced
104 * extensions.
105 */
106 #define MAX_EXT_INFO_COUNT 32
107 #define MAX_POLL_TIMEOUTS 3
108
109 static int packet_poll(int sockfd, int io) {
110 fd_set rfds, wfds;
111 struct timeval tv, *tvp = NULL;
112 int res, timeout, using_client_alive = FALSE;
113 unsigned int ntimeouts = 0;
114
115 if (poll_timeout == -1) {
116 /* If we have "client alive" timeout interval configured, use that --
117 * but only if we have already done the key exchange, and are not
118 * rekeying.
119 *
120 * Otherwise, we use the default (i.e. TimeoutIdle).
121 */
122
123 if (client_alive_interval > 0 &&
124 (!(sftp_sess_state & SFTP_SESS_STATE_REKEYING) &&
125 (sftp_sess_state & SFTP_SESS_STATE_HAVE_AUTH))) {
126 timeout = client_alive_interval;
127 using_client_alive = TRUE;
128
129 } else {
130 timeout = pr_data_get_timeout(PR_DATA_TIMEOUT_IDLE);
131 }
132
133 } else {
134 timeout = poll_timeout;
135 }
136
137 tv.tv_sec = timeout;
138 tv.tv_usec = 0;
139
140 if (timeout > 0) {
141 tvp = &tv;
142
143 pr_trace_msg(trace_channel, 19,
144 "waiting for max of %lu secs while polling socket %d for %s "
145 "using select(2)", (unsigned long) tv.tv_sec, sockfd,
146 io == SFTP_PACKET_IO_RD ? "reading" : "writing");
147
148 } else {
149 /* If TimeoutIdle was explicitly set to zero, then block indefinitely
150 * until more data arrives, per the documentation for a zero TimeoutIdle
151 * value (Issue #1985).
152 */
153 tvp = NULL;
154
155 pr_trace_msg(trace_channel, 19,
156 "waiting indefinitely while polling socket %d for %s using select(2)",
157 sockfd, io == SFTP_PACKET_IO_RD ? "reading" : "writing");
158 }
159
160 /* Clear any possibly stale pointers. */
161 session.curr_cmd_rec = NULL;
162
163 while (1) {
164 pr_signals_handle();
165
166 FD_ZERO(&rfds);
167 FD_ZERO(&wfds);
168
169 switch (io) {
170 case SFTP_PACKET_IO_RD: {
171 FD_SET(sockfd, &rfds);
172 res = select(sockfd + 1, &rfds, NULL, NULL, tvp);
173 break;
174 }
175
176 case SFTP_PACKET_IO_WR: {
177 FD_SET(sockfd, &wfds);
178 res = select(sockfd + 1, NULL, &wfds, NULL, tvp);
179 break;
180 }
181
182 default:
183 errno = EINVAL;
184 return -1;
185 }
186
187 if (res < 0) {
188 int xerrno = errno;
189
190 if (xerrno == EINTR) {
191 pr_signals_handle();
192 continue;
193 }
194
195 pr_trace_msg(trace_channel, 18, "error calling select(2) on fd %d: %s",
196 sockfd, strerror(xerrno));
197
198 errno = xerrno;
199 return -1;
200
201 } else if (res == 0) {
202 tv.tv_sec = timeout;
203 tv.tv_usec = 0;
204
205 ntimeouts++;
206
207 if (ntimeouts > MAX_POLL_TIMEOUTS) {
208 pr_trace_msg(trace_channel, 18,
209 "polling on socket %d timed out after %lu sec, failing", sockfd,
210 (unsigned long) tv.tv_sec);
211 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
212 "polling on socket %d timed out after %lu sec, failing", sockfd,
213 (unsigned long) tv.tv_sec);
214 errno = ETIMEDOUT;
215 return -1;
216 }
217
218 if (using_client_alive == TRUE) {
219 is_client_alive();
220
221 } else {
222 pr_trace_msg(trace_channel, 18,
223 "polling on socket %d timed out after %lu sec, trying again "
224 "(timeout #%u)", sockfd, (unsigned long) tv.tv_sec, ntimeouts);
225 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
226 "polling on socket %d timed out after %lu sec, trying again "
227 "(timeout #%u)", sockfd, (unsigned long) tv.tv_sec, ntimeouts);
228 }
229
230 continue;
231 }
232
233 break;
234 }
235
236 return 0;
237 }
238
239 /* The purpose of sock_read() is to loop until either we have read in the
240 * requested reqlen from the socket, or the socket gives us an I/O error.
241 * We want to prevent short reads from causing problems elsewhere (e.g.
242 * in the decipher or MAC code).
243 *
244 * It is the caller's responsibility to ensure that buf is large enough to
245 * hold reqlen bytes.
246 */
247 int sftp_ssh2_packet_sock_read(int sockfd, void *buf, size_t reqlen,
248 int flags) {
249 void *ptr;
250 size_t remainlen;
251
252 if (reqlen == 0) {
253 return 0;
254 }
255
256 /* Generate an event for the read poll we're about to do, for listeners
257 * like mod_proxy that always want to do similar polling, as part of this
258 * event loop in mod_sftp.
259 */
260 pr_event_generate("mod_sftp.ssh2.read-poll", NULL);
261
262 errno = 0;
263
264 ptr = buf;
265 remainlen = reqlen;
266
267 while (remainlen > 0) {
268 int res, xerrno;
269
270 res = packet_poll(sockfd, SFTP_PACKET_IO_RD);
271 xerrno = errno;
272
273 if (res < 0) {
274 errno = xerrno;
275 return -1;
276 }
277
278 /* The socket we accept is blocking, thus there's no need to handle
279 * EAGAIN/EWOULDBLOCK errors.
280 */
281 res = read(sockfd, ptr, remainlen);
282 while (res <= 0) {
283 if (res < 0) {
284 xerrno = errno;
285
286 if (xerrno == EINTR) {
287 pr_signals_handle();
288 res = read(sockfd, ptr, remainlen);
289 continue;
290 }
291
292 pr_trace_msg(trace_channel, 16,
293 "error reading from client (fd %d): %s", sockfd, strerror(xerrno));
294 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
295 "error reading from client (fd %d): %s", sockfd, strerror(xerrno));
296
297 errno = xerrno;
298
299 /* We explicitly disconnect the client here, rather than sending
300 * a DISCONNECT message, because the errors below all indicate
301 * a problem with the TCP connection, such that trying to write
302 * more data on that connection would cause problems.
303 */
304 if (errno == ECONNRESET ||
305 errno == ECONNABORTED ||
306 #ifdef ETIMEDOUT
307 errno == ETIMEDOUT ||
308 #endif /* ETIMEDOUT */
309 #ifdef ENOTCONN
310 errno == ENOTCONN ||
311 #endif /* ENOTCONN */
312 #ifdef ESHUTDOWN
313 errno == ESHUTDOWN ||
314 #endif /* ESHUTDOWNN */
315 errno == EPIPE) {
316 xerrno = errno;
317
318 pr_trace_msg(trace_channel, 16,
319 "disconnecting client (%s)", strerror(xerrno));
320 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
321 "disconnecting client (%s)", strerror(xerrno));
322 pr_session_disconnect(&sftp_module, PR_SESS_DISCONNECT_CLIENT_EOF,
323 strerror(xerrno));
324 }
325
326 return -1;
327
328 } else {
329 /* If we read zero bytes here, treat it as an EOF and hang up on
330 * the uncommunicative client.
331 */
332
333 pr_trace_msg(trace_channel, 16, "%s",
334 "disconnecting client (received EOF)");
335 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
336 "disconnecting client (received EOF)");
337 pr_session_disconnect(&sftp_module, PR_SESS_DISCONNECT_CLIENT_EOF,
338 NULL);
339 }
340 }
341
342 /* Generate an event for any interested listeners. Since the data are
343 * probably encrypted and such, and since listeners won't/shouldn't
344 * have the facilities for handling such data, we only pass the
345 * amount of data read in.
346 */
347 pr_event_generate("ssh2.netio-read", &res);
348
349 session.total_raw_in += reqlen;
350 time(&last_recvd);
351
352 if ((size_t) res == remainlen) {
353 break;
354 }
355
356 if (flags & SFTP_PACKET_READ_FL_PESSIMISTIC) {
357 pr_trace_msg(trace_channel, 20, "read %lu bytes, expected %lu bytes; "
358 "pessimistically returning", (unsigned long) res,
359 (unsigned long) remainlen);
360 break;
361 }
362
363 pr_trace_msg(trace_channel, 20, "read %lu bytes, expected %lu bytes; "
364 "reading more", (unsigned long) res, (unsigned long) remainlen);
365 ptr = ((char *) ptr + res);
366 remainlen -= res;
367 }
368
369 return reqlen;
370 }
371
372 static char peek_msg_type(struct ssh2_packet *pkt) {
373 char msg_type;
374
375 memmove(&msg_type, pkt->payload, sizeof(char));
376 return msg_type;
377 }
378
379 static void handle_global_request_msg(struct ssh2_packet *pkt) {
380 unsigned char *buf, *ptr;
381 uint32_t buflen;
382 char *request_name;
383 int want_reply;
384
385 buf = pkt->payload;
386 buflen = pkt->payload_len;
387
388 request_name = sftp_msg_read_string(pkt->pool, &buf, &buflen);
389 want_reply = sftp_msg_read_bool(pkt->pool, &buf, &buflen);
390
391 /* Handle any requests to prove hostkeys, per OpenSSH hostkey rotation,
392 * separately.
393 */
394 if (strcmp(request_name, "[email protected]") == 0) {
395 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
396 "client sent GLOBAL_REQUEST for '%s', handling", request_name);
397 sftp_keys_prove_hostkeys(pkt->pool, want_reply, buf, buflen);
398 destroy_pool(pkt->pool);
399 return;
400 }
401
402 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
403 "client sent GLOBAL_REQUEST for '%s', denying", request_name);
404
405 if (want_reply) {
406 struct ssh2_packet *pkt2;
407 uint32_t bufsz;
408 int res;
409
410 buflen = bufsz = 1024;
411 ptr = buf = palloc(pkt->pool, bufsz);
412
413 sftp_msg_write_byte(&buf, &buflen, SFTP_SSH2_MSG_REQUEST_FAILURE);
414
415 pkt2 = sftp_ssh2_packet_create(pkt->pool);
416 pkt2->payload = ptr;
417 pkt2->payload_len = (bufsz - buflen);
418
419 res = sftp_ssh2_packet_write(sftp_conn->wfd, pkt2);
420 if (res < 0) {
421 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
422 "error writing REQUEST_FAILURE message: %s", strerror(errno));
423 }
424 }
425
426 destroy_pool(pkt->pool);
427 }
428
429 static void handle_unknown_msg(struct ssh2_packet *pkt, char msg_type) {
430 unsigned char *buf, *ptr;
431 struct ssh2_packet *pkt2;
432 uint32_t buflen, bufsz;
433 int res;
434
435 pr_event_generate("ssh2.invalid-packet", pkt);
436
437 /* Per RFC 4253, Section 11.4, we should NOT disconnect the client here
438 * for unknown messages, but instead we MUST respond with
439 * SSH_MSG_UNINMPLEMENTED, and otherwise ignore the message.
440 */
441
442 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
443 "unhandled %s (%d) message, ignoring",
444 sftp_ssh2_packet_get_msg_type_desc(msg_type), msg_type);
445
446 buflen = bufsz = 1024;
447 ptr = buf = palloc(pkt->pool, bufsz);
448
449 sftp_msg_write_byte(&buf, &buflen, SFTP_SSH2_MSG_UNIMPLEMENTED);
450 sftp_msg_write_int(&buf, &buflen, pkt->seqno);
451
452 pkt2 = sftp_ssh2_packet_create(pkt->pool);
453 pkt2->payload = ptr;
454 pkt2->payload_len = (bufsz - buflen);
455
456 res = sftp_ssh2_packet_write(sftp_conn->wfd, pkt2);
457 if (res < 0) {
458 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
459 "error writing UNIMPLEMENTED message: %s", strerror(errno));
460 }
461
462 destroy_pool(pkt->pool);
463 }
464
465 static void handle_client_alive_msg(struct ssh2_packet *pkt, char msg_type) {
466 const char *msg_desc;
467
468 msg_desc = sftp_ssh2_packet_get_msg_type_desc(msg_type);
469
470 pr_trace_msg(trace_channel, 12,
471 "client sent %s message, considering client alive", msg_desc);
472
473 client_alive_count = 0;
474 destroy_pool(pkt->pool);
475 }
476
477 static void is_client_alive(void) {
478 unsigned int count;
479 unsigned char *buf, *ptr;
480 uint32_t bufsz, buflen, channel_id;
481 struct ssh2_packet *pkt;
482 pool *tmp_pool;
483
484 if (++client_alive_count > client_alive_max) {
485 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
486 "SFTPClientAlive threshold (max %u checks, %u sec interval) reached, "
487 "disconnecting client", client_alive_max, client_alive_interval);
488
489 /* XXX Generate an event for this? */
490
491 SFTP_DISCONNECT_CONN(SFTP_SSH2_DISCONNECT_BY_APPLICATION,
492 "client alive threshold reached");
493 }
494
495 /* If we have any opened channels, send a CHANNEL_REQUEST to one of
496 * them. Otherwise, send a GLOBAL_REQUEST.
497 */
498
499 tmp_pool = make_sub_pool(session.pool);
500
501 bufsz = buflen = 64;
502 ptr = buf = palloc(tmp_pool, bufsz);
503
504 count = sftp_channel_opened(&channel_id);
505 if (count > 0) {
506 sftp_msg_write_byte(&buf, &buflen, SFTP_SSH2_MSG_CHANNEL_REQUEST);
507 sftp_msg_write_int(&buf, &buflen, channel_id);
508
509 pr_trace_msg(trace_channel, 9,
510 "sending CHANNEL_REQUEST (remote channel ID %lu, [email protected])",
511 (unsigned long) channel_id);
512
513 } else {
514 sftp_msg_write_byte(&buf, &buflen, SFTP_SSH2_MSG_GLOBAL_REQUEST);
515
516 pr_trace_msg(trace_channel, 9,
517 "sending GLOBAL_REQUEST ([email protected])");
518 }
519
520 sftp_msg_write_string(&buf, &buflen, "[email protected]");
521 sftp_msg_write_bool(&buf, &buflen, TRUE);
522
523 pkt = sftp_ssh2_packet_create(tmp_pool);
524 pkt->payload = ptr;
525 pkt->payload_len = (bufsz - buflen);
526
527 (void) sftp_ssh2_packet_write(sftp_conn->wfd, pkt);
528 destroy_pool(tmp_pool);
529 }
530
531 /* Attempt to read in a random amount of data (up to the maximum amount of
532 * SSH2 packet data we support) from the socket. This is used to help
533 * mitigate the plaintext recovery attack described by CPNI-957037.
534 *
535 * Technically this is only necessary if a CBC mode cipher is in use, but
536 * there should be no harm in using for any cipher; we are going to
537 * disconnect the client after reading this data anyway.
538 */
539 static void read_packet_discard(int sockfd) {
540 size_t buflen;
541
542 buflen = SFTP_MAX_PACKET_LEN -
543 ((int) (SFTP_MAX_PACKET_LEN * (rand() / (RAND_MAX + 1.0))));
544
545 pr_trace_msg(trace_channel, 3, "reading %lu bytes of data for discarding",
546 (unsigned long) buflen);
547
548 if (buflen > 0) {
549 char buf[SFTP_MAX_PACKET_LEN];
550 int flags;
551
552 /* We don't necessarily want to wait for the entire random amount of data
553 * to be read in.
554 */
555 flags = SFTP_PACKET_READ_FL_PESSIMISTIC;
556 sftp_ssh2_packet_sock_read(sockfd, buf, buflen, flags);
557 }
558
559 return;
560 }
561
562 static int read_packet_len(int sockfd, struct ssh2_packet *pkt,
563 unsigned char *buf, size_t *offset, size_t *buflen, size_t bufsz,
564 int etm_mac, int chachapoly) {
565 uint32_t packet_len = 0, len = 0;
566 size_t readsz;
567 int res;
568 unsigned char *ptr = NULL;
569
570 readsz = sftp_cipher_get_read_block_size();
571
572 /* Since the packet length may be encrypted, we need to read in the first
573 * cipher_block_size bytes from the socket, and try to decrypt them, to know
574 * how many more bytes there are in the packet.
575 */
576
577 if (pkt->aad_len > 0) {
578 /* If we are dealing with an authenticated encryption algorithm, or an
579 * ETM mode, read enough to include the AAD. For ETM modes, leave the
580 * first block for later.
581 */
582 if (etm_mac == TRUE ||
583 chachapoly == TRUE) {
584 readsz = pkt->aad_len;
585
586 } else {
587 readsz += pkt->aad_len;
588 }
589 }
590
591 res = sftp_ssh2_packet_sock_read(sockfd, buf, readsz, 0);
592 if (res < 0) {
593 return res;
594 }
595
596 len = res;
597 res = sftp_cipher_read_packet_len(pkt, buf, readsz, &ptr, &len, &packet_len);
598 if (res < 0) {
599 return -1;
600 }
601
602 pkt->packet_len = packet_len;
603
604 /* Copy the remaining unencrypted bytes from the block into the given
605 * buffer.
606 */
607 if (len > 0) {
608 memmove(buf, ptr, len);
609 *buflen = (size_t) len;
610 }
611
612 *offset = 0;
613 return 0;
614 }
615
616 static int read_packet_padding_len(int sockfd, struct ssh2_packet *pkt,
617 unsigned char *buf, size_t *offset, size_t *buflen, size_t bufsz) {
618
619 if (*buflen > sizeof(char)) {
620 /* XXX Assume the data in the buffer is unencrypted, and thus usable. */
621 memmove(&pkt->padding_len, buf + *offset, sizeof(char));
622
623 /* Advance the buffer past the byte we just read off. */
624 *offset += sizeof(char);
625 *buflen -= sizeof(char);
626
627 return 0;
628 }
629
630 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
631 "unable to read padding len: not enough data in buffer (%u bytes)",
632 (unsigned int) *buflen);
633 return -1;
634 }
635
636 static int read_packet_payload(int sockfd, struct ssh2_packet *pkt,
637 unsigned char *buf, size_t *offset, size_t *buflen, size_t bufsz,
638 int etm_mac, int chachapoly) {
639 unsigned char *ptr = NULL;
640 int res;
641 uint32_t payload_len = pkt->payload_len, padding_len = 0, auth_len = 0,
642 data_len, len = 0;
643
644 /* For authenticated encryption or ETM modes, we will NOT have the
645 * pkt->padding_len field yet.
646 *
647 * For authenticated encryption, we need to read in the first block, then
648 * decrypt it, to find the padding.
649 *
650 * For ETM, we only want to find the payload and padding AFTER we've read
651 * the entire (encrypted) payload, MAC'd it, THEN decrypt it. Similarly
652 * for ChaChaPoly.
653 */
654
655 if (pkt->padding_len > 0) {
656 padding_len = pkt->padding_len;
657 }
658
659 auth_len = sftp_cipher_get_read_auth_size();
660
661 if (payload_len + padding_len + auth_len == 0 &&
662 etm_mac == FALSE && chachapoly == FALSE) {
663 return 0;
664 }
665
666 if (payload_len > 0) {
667 /* We don't want to reject the packet outright yet; but we can ignore
668 * the payload data we're going to read in. This packet will fail
669 * eventually anyway.
670 */
671 if (payload_len > SFTP_PACKET_MAX_PAYLOAD_LEN) {
672 pr_trace_msg(trace_channel, 20,
673 "payload len (%lu bytes) exceeds max payload len (%lu), "
674 "ignoring payload", (unsigned long) payload_len,
675 (unsigned long) SFTP_PACKET_MAX_PAYLOAD_LEN);
676
677 pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
678 "client sent buggy/malicious packet payload length, ignoring");
679
680 errno = EPERM;
681 return -1;
682 }
683
684 pkt->payload = palloc(pkt->pool, payload_len);
685 }
686
687 /* If there's data in the buffer we received, it's probably already part
688 * of the payload, unencrypted. That will leave the remaining payload
689 * data, if any, to be read in and decrypted.
690 */
691 if (*buflen > 0) {
692 if (*buflen < payload_len) {
693 memmove(pkt->payload, buf + *offset, *buflen);
694
695 payload_len -= *buflen;
696 *offset = 0;
697 *buflen = 0;
698
699 } else {
700 /* There's enough already for the payload length. Nice. */
701 memmove(pkt->payload, buf + *offset, payload_len);
702
703 *offset += payload_len;
704 *buflen -= payload_len;
705 payload_len = 0;
706 }
707 }
708
709 /* The padding length is required to be greater than zero. However, we may
710 * not know the padding length yet, as for authenticated encryption or ETM
711 * modes.
712 */
713 if (padding_len > 0) {
714 pkt->padding = palloc(pkt->pool, padding_len);
715 }
716
717 /* If there's data in the buffer we received, it's probably already part
718 * of the padding, unencrypted. That will leave the remaining padding
719 * data, if any, to be read in and decrypted.
720 */
721 if (*buflen > 0 &&
722 padding_len > 0) {
723 if (*buflen < padding_len) {
724 memmove(pkt->padding, buf + *offset, *buflen);
725
726 padding_len -= *buflen;
727 *offset = 0;
728 *buflen = 0;
729
730 } else {
731 /* There's enough already for the padding length. Nice. */
732 memmove(pkt->padding, buf + *offset, padding_len);
733
734 *offset += padding_len;
735 *buflen -= padding_len;
736 padding_len = 0;
737 }
738 }
739
740 if (etm_mac == TRUE ||
741 chachapoly == TRUE) {
742 data_len = pkt->packet_len;
743
744 } else {
745 data_len = payload_len + padding_len + auth_len;
746 }
747
748 if (data_len == 0) {
749 return 0;
750 }
751
752 if (data_len > bufsz) {
753 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
754 "remaining packet data (%lu bytes) exceeds packet buffer size (%lu "
755 "bytes)", (unsigned long) data_len, (unsigned long) bufsz);
756 errno = EPERM;
757 return -1;
758 }
759
760 res = sftp_ssh2_packet_sock_read(sockfd, buf + *offset, data_len, 0);
761 if (res < 0) {
762 return res;
763 }
764
765 len = res;
766
767 /* For ETM modes, we do NOT want to decrypt the data yet; we need to read/
768 * compare MACs first. Similarly for ChaChaPoly.
769 */
770
771 if (etm_mac == TRUE ||
772 chachapoly == TRUE) {
773 *buflen = res;
774
775 } else {
776 if (sftp_cipher_read_data(pkt, buf + *offset, data_len, &ptr, &len) < 0) {
777 return -1;
778 }
779
780 if (payload_len > 0) {
781 memmove(pkt->payload + (pkt->payload_len - payload_len), ptr,
782 payload_len);
783 }
784
785 memmove(pkt->padding + (pkt->padding_len - padding_len), ptr + payload_len,
786 padding_len);
787 }
788
789 return 0;
790 }
791
792 static int read_packet_mac(int sockfd, struct ssh2_packet *pkt,
793 unsigned char *buf) {
794 int res;
795 uint32_t mac_len = pkt->mac_len;
796
797 if (mac_len == 0) {
798 return 0;
799 }
800
801 res = sftp_ssh2_packet_sock_read(sockfd, buf, mac_len, 0);
802 if (res < 0) {
803 return res;
804 }
805
806 pkt->mac = palloc(pkt->pool, pkt->mac_len);
807 memmove(pkt->mac, buf, res);
808
809 return 0;
810 }
811
812 struct ssh2_packet *sftp_ssh2_packet_create(pool *p) {
813 pool *tmp_pool;
814 struct ssh2_packet *pkt;
815
816 tmp_pool = make_sub_pool(p);
817 pr_pool_tag(tmp_pool, "SSH2 packet pool");
818
819 pkt = palloc(tmp_pool, sizeof(struct ssh2_packet));
820 pkt->pool = tmp_pool;
821 pkt->m = &sftp_module;
822 pkt->packet_len = 0;
823 pkt->payload = NULL;
824 pkt->payload_len = 0;
825 pkt->padding_len = 0;
826 pkt->aad = NULL;
827 pkt->aad_len = 0;
828 pkt->mac = NULL;
829 pkt->mac_len = 0;
830 pkt->seqno = 0;
831
832 return pkt;
833 }
834
835 int sftp_ssh2_packet_get_last_recvd(time_t *tp) {
836 if (tp == NULL) {
837 errno = EINVAL;
838 return -1;
839 }
840
841 memmove(tp, &last_recvd, sizeof(time_t));
842 return 0;
843 }
844
845 int sftp_ssh2_packet_get_last_sent(time_t *tp) {
846 if (tp == NULL) {
847 errno = EINVAL;
848 return -1;
849 }
850
851 memmove(tp, &last_sent, sizeof(time_t));
852 return 0;
853 }
854
855 char sftp_ssh2_packet_get_msg_type(struct ssh2_packet *pkt) {
856 char msg_type;
857
858 memmove(&msg_type, pkt->payload, sizeof(char));
859 pkt->payload += sizeof(char);
860 pkt->payload_len -= sizeof(char);
861
862 return msg_type;
863 }
864
865 const char *sftp_ssh2_packet_get_msg_type_desc(unsigned char msg_type) {
866 switch (msg_type) {
867 case SFTP_SSH2_MSG_DISCONNECT:
868 return "SSH_MSG_DISCONNECT";
869
870 case SFTP_SSH2_MSG_IGNORE:
871 return "SSH_MSG_IGNORE";
872
873 case SFTP_SSH2_MSG_UNIMPLEMENTED:
874 return "SSH_MSG_UNIMPLEMENTED";
875
876 case SFTP_SSH2_MSG_DEBUG:
877 return "SSH_MSG_DEBUG";
878
879 case SFTP_SSH2_MSG_SERVICE_REQUEST:
880 return "SSH_MSG_SERVICE_REQUEST";
881
882 case SFTP_SSH2_MSG_SERVICE_ACCEPT:
883 return "SSH_MSG_SERVICE_ACCEPT";
884
885 case SFTP_SSH2_MSG_EXT_INFO:
886 return "SSH_MSG_EXT_INFO";
887
888 case SFTP_SSH2_MSG_KEXINIT:
889 return "SSH_MSG_KEXINIT";
890
891 case SFTP_SSH2_MSG_NEWKEYS:
892 return "SSH_MSG_NEWKEYS";
893
894 case SFTP_SSH2_MSG_KEX_DH_INIT:
895 return "SSH_MSG_KEX_DH_INIT";
896
897 case SFTP_SSH2_MSG_KEX_DH_REPLY:
898 return "SSH_MSG_KEX_DH_REPLY";
899
900 case SFTP_SSH2_MSG_KEX_DH_GEX_INIT:
901 return "SSH_MSG_KEX_DH_GEX_INIT";
902
903 case SFTP_SSH2_MSG_KEX_DH_GEX_REPLY:
904 return "SSH_MSG_KEX_DH_GEX_REPLY";
905
906 case SFTP_SSH2_MSG_KEX_DH_GEX_REQUEST:
907 return "SSH_MSG_KEX_DH_GEX_REQUEST";
908
909 case SFTP_SSH2_MSG_USER_AUTH_REQUEST:
910 return "SSH_MSG_USER_AUTH_REQUEST";
911
912 case SFTP_SSH2_MSG_USER_AUTH_FAILURE:
913 return "SSH_MSG_USER_AUTH_FAILURE";
914
915 case SFTP_SSH2_MSG_USER_AUTH_SUCCESS:
916 return "SSH_MSG_USER_AUTH_SUCCESS";
917
918 case SFTP_SSH2_MSG_USER_AUTH_BANNER:
919 return "SSH_MSG_USER_AUTH_BANNER";
920
921 case SFTP_SSH2_MSG_USER_AUTH_PASSWD:
922 return "SSH_MSG_USER_AUTH_PASSWD";
923
924 case SFTP_SSH2_MSG_USER_AUTH_INFO_RESP:
925 return "SSH_MSG_USER_AUTH_INFO_RESP";
926
927 case SFTP_SSH2_MSG_GLOBAL_REQUEST:
928 return "SSH_MSG_GLOBAL_REQUEST";
929
930 case SFTP_SSH2_MSG_REQUEST_SUCCESS:
931 return "SSH_MSG_REQUEST_SUCCESS";
932
933 case SFTP_SSH2_MSG_REQUEST_FAILURE:
934 return "SSH_MSG_REQUEST_FAILURE";
935
936 case SFTP_SSH2_MSG_CHANNEL_OPEN:
937 return "SSH_MSG_CHANNEL_OPEN";
938
939 case SFTP_SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
940 return "SSH_MSG_CHANNEL_OPEN_CONFIRMATION";
941
942 case SFTP_SSH2_MSG_CHANNEL_OPEN_FAILURE:
943 return "SSH_MSG_CHANNEL_OPEN_FAILURE";
944
945 case SFTP_SSH2_MSG_CHANNEL_WINDOW_ADJUST:
946 return "SSH_MSG_CHANNEL_WINDOW_ADJUST";
947
948 case SFTP_SSH2_MSG_CHANNEL_DATA:
949 return "SSH_MSG_CHANNEL_DATA";
950
951 case SFTP_SSH2_MSG_CHANNEL_EXTENDED_DATA:
952 return "SSH_MSG_CHANNEL_EXTENDED_DATA";
953
954 case SFTP_SSH2_MSG_CHANNEL_EOF:
955 return "SSH_MSG_CHANNEL_EOF";
956
957 case SFTP_SSH2_MSG_CHANNEL_CLOSE:
958 return "SSH_MSG_CHANNEL_CLOSE";
959
960 case SFTP_SSH2_MSG_CHANNEL_REQUEST:
961 return "SSH_MSG_CHANNEL_REQUEST";
962
963 case SFTP_SSH2_MSG_CHANNEL_SUCCESS:
964 return "SSH_MSG_CHANNEL_SUCCESS";
965
966 case SFTP_SSH2_MSG_CHANNEL_FAILURE:
967 return "SSH_MSG_CHANNEL_FAILURE";
968 }
969
970 return "(unknown)";
971 }
972
973 int sftp_ssh2_packet_set_poll_timeout(int timeout) {
974 if (timeout <= 0) {
975 poll_timeout = -1;
976
977 } else {
978 poll_timeout = timeout;
979 }
980
981 return 0;
982 }
983
984 int sftp_ssh2_packet_set_client_alive(unsigned int max, unsigned int interval) {
985 client_alive_max = max;
986 client_alive_interval = interval;
987 return 0;
988 }
989
990 int sftp_ssh2_packet_read(int sockfd, struct ssh2_packet *pkt) {
991 unsigned char buf[SFTP_MAX_PACKET_LEN];
992 size_t buflen, bufsz = SFTP_MAX_PACKET_LEN, offset = 0, auth_len = 0;
993 int chachapoly = FALSE, etm_mac = FALSE;
994
995 pr_session_set_idle();
996
997 auth_len = sftp_cipher_get_read_auth_size();
998 if (auth_len > 0) {
999 /* Authenticated encryption ciphers do not encrypt the packet length,
1000 * and instead use it as Additional Authenticated Data (AAD).
1001 *
1002 * Note that OpenSSH's ChaCha/Poly cipher does encrypt the packet length,
1003 * and uses it as AAD.
1004 */
1005 pkt->aad_len = sizeof(uint32_t);
1006 }
1007
1008 etm_mac = sftp_mac_is_read_etm();
1009 if (etm_mac == TRUE) {
1010 /* ETM modes do not encrypt the packet length, and instead use it as
1011 * Additional Authenticated Data (AAD).
1012 */
1013 pkt->aad_len = sizeof(uint32_t);
1014 }
1015
1016 /* OpenSSH's ChaChaPoly acts like an ETM cipher as well. */
1017 chachapoly = sftp_cipher_is_read_chachapoly();
1018
1019 pkt->seqno = packet_client_seqno;
1020
1021 while (TRUE) {
1022 uint32_t encrypted_datasz, req_blocksz;
1023 int res;
1024
1025 pr_signals_handle();
1026
1027 /* This is in a while loop in order to consume any debug/ignore
1028 * messages which the client may send.
1029 */
1030
1031 buflen = 0;
1032
1033 if (read_packet_len(sockfd, pkt, buf, &offset, &buflen, bufsz,
1034 etm_mac, chachapoly) < 0) {
1035 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1036 "no data to be read from socket %d", sockfd);
1037 return -1;
1038 }
1039
1040 pr_trace_msg(trace_channel, 20, "SSH2 packet len = %lu bytes",
1041 (unsigned long) pkt->packet_len);
1042
1043 /* In order to mitigate the plaintext recovery attack described in
1044 * CPNI-957037:
1045 *
1046 * http://www.cpni.gov.uk/Docs/Vulnerability_Advisory_SSH.txt
1047 *
1048 * we do NOT check that the packet length is sane here; we have to
1049 * wait until the MAC check succeeds.
1050 */
1051
1052 /* Note: Checking for the RFC4253-recommended minimum packet length
1053 * of 16 bytes causes KEX to fail (the NEWKEYS packet is 12 bytes).
1054 * Thus that particular check is omitted.
1055 */
1056
1057 if (etm_mac == FALSE &&
1058 chachapoly == FALSE) {
1059 if (read_packet_padding_len(sockfd, pkt, buf, &offset, &buflen,
1060 bufsz) < 0) {
1061 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1062 "no data to be read from socket %d", sockfd);
1063 read_packet_discard(sockfd);
1064 return -1;
1065 }
1066
1067 pr_trace_msg(trace_channel, 20, "SSH2 packet padding len = %u bytes",
1068 (unsigned int) pkt->padding_len);
1069
1070 pkt->payload_len = (pkt->packet_len - pkt->padding_len - 1);
1071 pr_trace_msg(trace_channel, 20, "SSH2 packet payload len = %lu bytes",
1072 (unsigned long) pkt->payload_len);
1073 }
1074
1075 /* Read both payload and padding, since we may need to have both before
1076 * decrypting the data.
1077 */
1078 if (read_packet_payload(sockfd, pkt, buf, &offset, &buflen, bufsz,
1079 etm_mac, chachapoly) < 0) {
1080 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1081 "unable to read payload from socket %d", sockfd);
1082 read_packet_discard(sockfd);
1083 return -1;
1084 }
1085
1086 if (chachapoly == TRUE) {
1087 /* The custom authentication tag for ChaChaPoly is 16 bytes. */
1088 pkt->mac_len = 16;
1089
1090 } else {
1091 pkt->mac_len = sftp_mac_get_block_size();
1092 }
1093
1094 pr_trace_msg(trace_channel, 20, "SSH2 packet MAC len = %lu bytes",
1095 (unsigned long) pkt->mac_len);
1096
1097 if (etm_mac == TRUE ||
1098 chachapoly == TRUE) {
1099 unsigned char *buf2;
1100 size_t buflen2, bufsz2;
1101
1102 bufsz2 = buflen2 = pkt->mac_len;
1103 buf2 = palloc(pkt->pool, bufsz2);
1104
1105 /* The MAC routines assume the presence of the necessary data in
1106 * pkt->payload, so we temporarily put our encrypted packet data there.
1107 */
1108 pkt->payload = buf;
1109 pkt->payload_len = buflen;
1110
1111 if (read_packet_mac(sockfd, pkt, buf2) < 0) {
1112 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1113 "unable to read MAC from socket %d", sockfd);
1114 read_packet_discard(sockfd);
1115 return -1;
1116 }
1117
1118 if (sftp_mac_read_data(pkt) < 0) {
1119 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1120 "unable to verify MAC on packet from socket %d", sockfd);
1121
1122 /* In order to further mitigate CPNI-957037, we will read in a
1123 * random amount of more data from the network before closing
1124 * the connection.
1125 */
1126 read_packet_discard(sockfd);
1127 return -1;
1128 }
1129
1130 /* Now we can decrypt the payload; `buf/buflen` are the encrypted
1131 * packet from read_packet_payload().
1132 */
1133 bufsz2 = buflen2 = SFTP_MAX_PACKET_LEN;
1134 buf2 = palloc(pkt->pool, bufsz2);
1135
1136 if (sftp_cipher_read_data(pkt, buf, buflen, &buf2,
1137 (uint32_t *) &buflen2) < 0) {
1138 return -1;
1139 }
1140
1141 offset = 0;
1142
1143 if (read_packet_padding_len(sockfd, pkt, buf2, &offset, &buflen2,
1144 bufsz2) < 0) {
1145 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1146 "no data to be read from socket %d", sockfd);
1147 read_packet_discard(sockfd);
1148 return -1;
1149 }
1150
1151 pr_trace_msg(trace_channel, 20, "SSH2 packet padding len = %u bytes",
1152 (unsigned int) pkt->padding_len);
1153
1154 if (pkt->packet_len < (pkt->padding_len + 1)) {
1155 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1156 "illegal padding length (%u bytes) exceeds packet length "
1157 "(%lu bytes)", (unsigned int) pkt->padding_len,
1158 (unsigned long) pkt->packet_len);
1159 read_packet_discard(sockfd);
1160 return -1;
1161 }
1162
1163 pkt->payload_len = (pkt->packet_len - pkt->padding_len - 1);
1164 pr_trace_msg(trace_channel, 20, "SSH2 packet payload len = %lu bytes",
1165 (unsigned long) pkt->payload_len);
1166
1167 if (pkt->payload_len > 0) {
1168 pkt->payload = palloc(pkt->pool, pkt->payload_len);
1169 memmove(pkt->payload, buf2 + offset, pkt->payload_len);
1170 }
1171
1172 pkt->padding = palloc(pkt->pool, pkt->padding_len);
1173 memmove(pkt->padding, buf2 + offset + pkt->payload_len, pkt->padding_len);
1174
1175 } else {
1176 if (read_packet_mac(sockfd, pkt, buf) < 0) {
1177 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1178 "unable to read MAC from socket %d", sockfd);
1179 read_packet_discard(sockfd);
1180 return -1;
1181 }
1182
1183 if (sftp_mac_read_data(pkt) < 0) {
1184 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1185 "unable to verify MAC on packet from socket %d", sockfd);
1186
1187 /* In order to further mitigate CPNI-957037, we will read in a
1188 * random amount of more data from the network before closing
1189 * the connection.
1190 */
1191 read_packet_discard(sockfd);
1192 return -1;
1193 }
1194 }
1195
1196 /* Now that the MAC check has passed, we can do sanity checks based
1197 * on the fields we have read in, and trust that those fields are
1198 * correct.
1199 */
1200
1201 if (pkt->packet_len < 5) {
1202 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1203 "packet length too short (%lu), less than minimum packet length (5)",
1204 (unsigned long) pkt->packet_len);
1205 read_packet_discard(sockfd);
1206 return -1;
1207 }
1208
1209 if (pkt->packet_len > SFTP_MAX_PACKET_LEN) {
1210 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1211 "packet length too long (%lu), exceeds maximum packet length (%lu)",
1212 (unsigned long) pkt->packet_len, (unsigned long) SFTP_MAX_PACKET_LEN);
1213 read_packet_discard(sockfd);
1214 return -1;
1215 }
1216
1217 /* Per Section 6 of RFC4253, the minimum padding length is 4, the
1218 * maximum padding length is 255.
1219 */
1220
1221 if (pkt->padding_len < SFTP_MIN_PADDING_LEN) {
1222 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1223 "padding length too short (%u), less than minimum padding length (%u)",
1224 (unsigned int) pkt->padding_len, (unsigned int) SFTP_MIN_PADDING_LEN);
1225 read_packet_discard(sockfd);
1226 return -1;
1227 }
1228
1229 if (pkt->padding_len > pkt->packet_len) {
1230 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1231 "padding length too long (%u), exceeds packet length (%lu)",
1232 (unsigned int) pkt->padding_len, (unsigned long) pkt->packet_len);
1233 read_packet_discard(sockfd);
1234 return -1;
1235 }
1236
1237 /* From RFC4253, Section 6:
1238 *
1239 * random padding
1240 * Arbitrary-length padding, such that the total length of
1241 * (packet_length || padding_length || payload || random padding)
1242 * is a multiple of the cipher block size or 8, whichever is
1243 * larger.
1244 *
1245 * Thus packet_len + sizeof(uint32_t) (for the actual packet length field)
1246 * is that "(packet_length || padding_length || payload || padding)"
1247 * value.
1248 */
1249
1250 req_blocksz = MAX(8, sftp_cipher_get_read_block_size());
1251 encrypted_datasz = pkt->packet_len + sizeof(uint32_t);
1252
1253 /* If AAD bytes are present, they are not encrypted (except for
1254 * ChaCha20).
1255 */
1256 if (pkt->aad_len > 0) {
1257 encrypted_datasz -= pkt->aad_len;
1258 }
1259
1260 if (encrypted_datasz % req_blocksz != 0) {
1261 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1262 "packet length (%lu) not a multiple of the required block size (%lu)",
1263 (unsigned long) encrypted_datasz, (unsigned long) req_blocksz);
1264 read_packet_discard(sockfd);
1265 return -1;
1266 }
1267
1268 /* XXX I'm not so sure about this check; we SHOULD have a maximum
1269 * payload check, but using the max packet length check for the payload
1270 * length seems awkward.
1271 */
1272 if (pkt->payload_len > SFTP_MAX_PACKET_LEN) {
1273 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1274 "payload length too long (%lu), exceeds maximum payload length (%lu) "
1275 "(packet len %lu, padding len %u)", (unsigned long) pkt->payload_len,
1276 (unsigned long) SFTP_MAX_PACKET_LEN, (unsigned long) pkt->packet_len,
1277 (unsigned int) pkt->padding_len);
1278 read_packet_discard(sockfd);
1279 return -1;
1280 }
1281
1282 /* Sanity checks passed; move on to the reading the packet payload. */
1283 if (sftp_compress_read_data(pkt) < 0) {
1284 return -1;
1285 }
1286
1287 packet_client_seqno++;
1288
1289 /* Handle the case where timers might be being processed at the
1290 * moment.
1291 */
1292 res = pr_timer_reset(PR_TIMER_IDLE, ANY_MODULE);
1293 while (res < 0) {
1294 if (errno == EINTR) {
1295 pr_signals_handle();
1296 res = pr_timer_reset(PR_TIMER_IDLE, ANY_MODULE);
1297 }
1298
1299 break;
1300 }
1301
1302 break;
1303 }
1304
1305 if (rekey_size > 0) {
1306 rekey_client_len += pkt->packet_len;
1307
1308 if (rekey_client_len >= rekey_size) {
1309 pr_trace_msg(trace_channel, 17, "client packet bytes recvd (%" PR_LU
1310 ") reached rekey bytes limit (%" PR_LU "), requesting rekey",
1311 (pr_off_t) rekey_client_len, (pr_off_t) rekey_size);
1312 sftp_kex_rekey();
1313 }
1314 }
1315
1316 if (rekey_client_seqno > 0 &&
1317 packet_client_seqno == rekey_client_seqno) {
1318 pr_trace_msg(trace_channel, 17, "client packet sequence number (%lu) "
1319 "reached rekey packet number %lu, requesting rekey",
1320 (unsigned long) packet_client_seqno, (unsigned long) rekey_client_seqno);
1321 sftp_kex_rekey();
1322 }
1323
1324 return 0;
1325 }
1326
1327 static int write_packet_padding(struct ssh2_packet *pkt) {
1328 register unsigned int i;
1329 uint32_t packet_len = 0;
1330 size_t blocksz;
1331
1332 blocksz = sftp_cipher_get_write_block_size();
1333
1334 /* RFC 4253, section 6, says that the random padding is calculated
1335 * as follows:
1336 *
1337 * random padding
1338 * Arbitrary-length padding, such that the total length of
1339 * (packet_length || padding_length || payload || random padding)
1340 * is a multiple of the cipher block size or 8, whichever is
1341 * larger. There MUST be at least four bytes of padding. The
1342 * padding SHOULD consist of random bytes. The maximum amount of
1343 * padding is 255 bytes.
1344 *
1345 * This means:
1346 *
1347 * packet len = sizeof(packet_len field) + sizeof(padding_len field) +
1348 * sizeof(payload field) + sizeof(padding field)
1349 */
1350
1351 packet_len = sizeof(uint32_t) + sizeof(char) + pkt->payload_len;
1352 if (pkt->aad_len > 0) {
1353 /* Packet length is not encrypted for encrypted authentication, or
1354 * Encrypt-Then-MAC modes.
1355 */
1356 packet_len -= pkt->aad_len;
1357 }
1358
1359 pkt->padding_len = (char) (blocksz - (packet_len % blocksz));
1360 if (pkt->padding_len < 4) {
1361 /* As per RFC, there must be at least 4 bytes of padding. So if the
1362 * above calculated less, then we need to add another block's worth
1363 * of padding.
1364 */
1365 pkt->padding_len += blocksz;
1366 }
1367
1368 pr_trace_msg(trace_channel, 20, "adding %u bytes of padding",
1369 pkt->padding_len);
1370 pkt->padding = palloc(pkt->pool, pkt->padding_len);
1371
1372 /* Fill the padding with pseudo-random data. */
1373 for (i = 0; i < pkt->padding_len; i++) {
1374 pkt->padding[i] = (unsigned char) pr_random_next(0, UCHAR_MAX);
1375 }
1376
1377 return 0;
1378 }
1379
1380 #define SFTP_SSH2_PACKET_IOVSZ 12
1381 static struct iovec packet_iov[SFTP_SSH2_PACKET_IOVSZ];
1382 static unsigned int packet_niov = 0;
1383
1384 int sftp_ssh2_packet_send(int sockfd, struct ssh2_packet *pkt) {
1385 unsigned char buf[SFTP_MAX_PACKET_LEN * 2], msg_type;
1386 size_t buflen = 0, bufsz = SFTP_MAX_PACKET_LEN;
1387 uint32_t packet_len = 0, auth_len = 0;
1388 int res, write_len = 0, block_alarms = FALSE, etm_mac = FALSE;
1389
1390 /* No interruptions, please. If, for example, we are interrupted here
1391 * by the SFTPRekey timer, that timer will cause this same function to
1392 * be called -- but the packet_iov/packet_niov values will be different.
1393 * Which in turn leads to malformed packets, and thus badness (Bug#4216).
1394 */
1395
1396 if (sftp_sess_state & SFTP_SESS_STATE_HAVE_AUTH) {
1397 block_alarms = TRUE;
1398 }
1399
1400 if (block_alarms == TRUE) {
1401 pr_alarms_block();
1402 }
1403
1404 auth_len = sftp_cipher_get_write_auth_size();
1405 if (auth_len > 0) {
1406 /* Authenticated encryption ciphers do not encrypt the packet length,
1407 * and instead use it as Additional Authenticated Data (AAD).
1408 *
1409 * The OpenSSH ChaChaPoly cipher does encrypt the packet length, on the
1410 * other hand, and use a separate AAD.
1411 */
1412 pkt->aad_len = sizeof(uint32_t);
1413 pkt->aad = NULL;
1414 }
1415
1416 etm_mac = sftp_mac_is_write_etm();
1417 if (etm_mac == TRUE) {
1418 /* Encrypt-Then-Mac modes do not encrypt the packet length; treat it
1419 * as Additional Authenticated Data (AAD).
1420 */
1421 pkt->aad_len = sizeof(uint32_t);
1422 pkt->aad = NULL;
1423 }
1424
1425 /* Clear the iovec array before sending the data, if possible. */
1426 if (packet_niov == 0) {
1427 memset(packet_iov, 0, sizeof(packet_iov));
1428 }
1429
1430 msg_type = peek_msg_type(pkt);
1431
1432 pr_trace_msg(trace_channel, 20, "sending %lu bytes of %s (%d) payload",
1433 (unsigned long) pkt->payload_len,
1434 sftp_ssh2_packet_get_msg_type_desc(msg_type), msg_type);
1435
1436 if (sftp_compress_write_data(pkt) < 0) {
1437 int xerrno = errno;
1438
1439 if (block_alarms == TRUE) {
1440 pr_alarms_unblock();
1441 }
1442
1443 errno = xerrno;
1444 return -1;
1445 }
1446
1447 if (write_packet_padding(pkt) < 0) {
1448 int xerrno = errno;
1449
1450 if (block_alarms == TRUE) {
1451 pr_alarms_unblock();
1452 }
1453
1454 errno = xerrno;
1455 return -1;
1456 }
1457
1458 /* Packet length: padding len + payload + padding */
1459 pkt->packet_len = packet_len = sizeof(char) + pkt->payload_len +
1460 pkt->padding_len;
1461
1462 pkt->seqno = packet_server_seqno;
1463
1464 buflen = bufsz;
1465
1466 if (etm_mac == TRUE) {
1467 if (sftp_cipher_write_data(pkt, buf, &buflen) < 0) {
1468 int xerrno = errno;
1469
1470 if (block_alarms == TRUE) {
1471 pr_alarms_unblock();
1472 }
1473
1474 errno = xerrno;
1475 return -1;
1476 }
1477
1478 /* Once we have the encrypted data, overwrite the plaintext packet payload
1479 * with it, so that the MAC is calculated from the encrypted data.
1480 */
1481 pkt->payload = buf;
1482 pkt->payload_len = buflen;
1483
1484 if (sftp_mac_write_data(pkt) < 0) {
1485 int xerrno = errno;
1486
1487 if (block_alarms == TRUE) {
1488 pr_alarms_unblock();
1489 }
1490
1491 errno = xerrno;
1492 return -1;
1493 }
1494
1495 } else {
1496 if (sftp_mac_write_data(pkt) < 0) {
1497 int xerrno = errno;
1498
1499 if (block_alarms == TRUE) {
1500 pr_alarms_unblock();
1501 }
1502
1503 errno = xerrno;
1504 return -1;
1505 }
1506
1507 if (sftp_cipher_write_data(pkt, buf, &buflen) < 0) {
1508 int xerrno = errno;
1509
1510 if (block_alarms == TRUE) {
1511 pr_alarms_unblock();
1512 }
1513
1514 errno = xerrno;
1515 return -1;
1516 }
1517 }
1518
1519 if (buflen > 0) {
1520 /* We have encrypted data, which means we don't need as many of the
1521 * iovec slots as for unencrypted data.
1522 */
1523
1524 if (!sent_version_id) {
1525 packet_iov[packet_niov].iov_base = (void *) version_id;
1526 packet_iov[packet_niov].iov_len = strlen(version_id);
1527 write_len += packet_iov[packet_niov].iov_len;
1528 packet_niov++;
1529 }
1530
1531 if (pkt->aad_len > 0) {
1532 pr_trace_msg(trace_channel, 20, "sending %lu bytes of packet AAD data",
1533 (unsigned long) pkt->aad_len);
1534 packet_iov[packet_niov].iov_base = (void *) pkt->aad;
1535 packet_iov[packet_niov].iov_len = pkt->aad_len;
1536 write_len += packet_iov[packet_niov].iov_len;
1537 packet_niov++;
1538 }
1539
1540 pr_trace_msg(trace_channel, 20, "sending %lu bytes of packet payload data",
1541 (unsigned long) buflen);
1542 packet_iov[packet_niov].iov_base = (void *) buf;
1543 packet_iov[packet_niov].iov_len = buflen;
1544 write_len += packet_iov[packet_niov].iov_len;
1545 packet_niov++;
1546
1547 if (pkt->mac_len > 0) {
1548 pr_trace_msg(trace_channel, 20, "sending %lu bytes of packet MAC data",
1549 (unsigned long) pkt->mac_len);
1550 packet_iov[packet_niov].iov_base = (void *) pkt->mac;
1551 packet_iov[packet_niov].iov_len = pkt->mac_len;
1552 write_len += packet_iov[packet_niov].iov_len;
1553 packet_niov++;
1554 }
1555
1556 } else {
1557 /* Don't forget to convert the packet len to network-byte order, since
1558 * this length is sent over the wire.
1559 */
1560 packet_len = htonl(packet_len);
1561
1562 if (!sent_version_id) {
1563 packet_iov[packet_niov].iov_base = (void *) version_id;
1564 packet_iov[packet_niov].iov_len = strlen(version_id);
1565 write_len += packet_iov[packet_niov].iov_len;
1566 packet_niov++;
1567 }
1568
1569 packet_iov[packet_niov].iov_base = (void *) &packet_len;
1570 packet_iov[packet_niov].iov_len = sizeof(uint32_t);
1571 write_len += packet_iov[packet_niov].iov_len;
1572 packet_niov++;
1573
1574 packet_iov[packet_niov].iov_base = (void *) &(pkt->padding_len);
1575 packet_iov[packet_niov].iov_len = sizeof(char);
1576 write_len += packet_iov[packet_niov].iov_len;
1577 packet_niov++;
1578
1579 packet_iov[packet_niov].iov_base = (void *) pkt->payload;
1580 packet_iov[packet_niov].iov_len = pkt->payload_len;
1581 write_len += packet_iov[packet_niov].iov_len;
1582 packet_niov++;
1583
1584 packet_iov[packet_niov].iov_base = (void *) pkt->padding;
1585 packet_iov[packet_niov].iov_len = pkt->padding_len;
1586 write_len += packet_iov[packet_niov].iov_len;
1587 packet_niov++;
1588
1589 if (pkt->mac_len > 0) {
1590 packet_iov[packet_niov].iov_base = (void *) pkt->mac;
1591 packet_iov[packet_niov].iov_len = pkt->mac_len;
1592 write_len += packet_iov[packet_niov].iov_len;
1593 packet_niov++;
1594 }
1595 }
1596
1597 if (packet_poll(sockfd, SFTP_PACKET_IO_WR) < 0) {
1598 int xerrno = errno;
1599
1600 /* Socket not writable? Clear the array, and try again. */
1601 memset(packet_iov, 0, sizeof(packet_iov));
1602 packet_niov = 0;
1603
1604 if (block_alarms == TRUE) {
1605 pr_alarms_unblock();
1606 }
1607
1608 errno = xerrno;
1609 return -1;
1610 }
1611
1612 /* Generate an event for any interested listeners. Since the data are
1613 * probably encrypted and such, and since listeners won't/shouldn't
1614 * have the facilities for handling such data, we only pass the
1615 * amount of data to be written out.
1616 */
1617 pr_event_generate("ssh2.netio-write", &write_len);
1618
1619 /* The socket we accept is blocking, thus there's no need to handle
1620 * EAGAIN/EWOULDBLOCK errors.
1621 */
1622 res = writev(sockfd, packet_iov, packet_niov);
1623 while (res < 0) {
1624 int xerrno = errno;
1625
1626 if (xerrno == EINTR) {
1627 pr_signals_handle();
1628
1629 res = writev(sockfd, packet_iov, packet_niov);
1630 continue;
1631 }
1632
1633 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1634 "error writing packet (fd %d): %s", sockfd, strerror(xerrno));
1635
1636 if (xerrno == ECONNRESET ||
1637 xerrno == ECONNABORTED ||
1638 xerrno == EPIPE) {
1639
1640 if (block_alarms == TRUE) {
1641 pr_alarms_unblock();
1642 }
1643
1644 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1645 "disconnecting client (%s)", strerror(xerrno));
1646 pr_session_disconnect(&sftp_module, PR_SESS_DISCONNECT_BY_APPLICATION,
1647 strerror(xerrno));
1648 }
1649
1650 /* Always clear the iovec array after sending the data. */
1651 memset(packet_iov, 0, sizeof(packet_iov));
1652 packet_niov = 0;
1653
1654 if (block_alarms == TRUE) {
1655 pr_alarms_unblock();
1656 }
1657
1658 errno = xerrno;
1659 return -1;
1660 }
1661
1662 session.total_raw_out += res;
1663
1664 /* Always clear the iovec array after sending the data. */
1665 memset(packet_iov, 0, sizeof(packet_iov));
1666 packet_niov = 0;
1667
1668 if (sent_version_id == FALSE) {
1669 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1670 "sent server version '%s'", server_version);
1671 sent_version_id = TRUE;
1672 }
1673
1674 time(&last_sent);
1675
1676 packet_server_seqno++;
1677
1678 pr_trace_msg(trace_channel, 3, "sent %s (%d) packet (%d bytes)",
1679 sftp_ssh2_packet_get_msg_type_desc(msg_type), msg_type, res);
1680
1681 if (block_alarms == TRUE) {
1682 /* Now that we've written out the packet, we can be interrupted again. */
1683 pr_alarms_unblock();
1684 }
1685
1686 if (rekey_size > 0) {
1687 rekey_server_len += pkt->packet_len;
1688
1689 if (rekey_server_len >= rekey_size) {
1690 pr_trace_msg(trace_channel, 17, "server packet bytes sent (%" PR_LU
1691 ") reached rekey bytes limit (%" PR_LU "), requesting rekey",
1692 (pr_off_t) rekey_server_len, (pr_off_t) rekey_size);
1693 sftp_kex_rekey();
1694 }
1695 }
1696
1697 if (rekey_server_seqno > 0 &&
1698 packet_server_seqno == rekey_server_seqno) {
1699 pr_trace_msg(trace_channel, 17, "server packet sequence number (%lu) "
1700 "reached rekey packet number %lu, requesting rekey",
1701 (unsigned long) packet_server_seqno, (unsigned long) rekey_server_seqno);
1702 sftp_kex_rekey();
1703 }
1704
1705 return 0;
1706 }
1707
1708 int sftp_ssh2_packet_write(int sockfd, struct ssh2_packet *pkt) {
1709 /* For future reference, I tried buffering up the possible TAP message
1710 * and the given message using TCP_CORK/TCP_NOPUSH. I tried this test
1711 * on a Mac OSX 10.5 box. It was for this test that I refactored the
1712 * core pr_inet_* functions, creating pr_inet_set_proto_cork().
1713 *
1714 * Turned out to be a very bad idea. Using sftp(1), the login process
1715 * itself was incredibly slow. mod_sftp was behaving as if the
1716 * "uncorking" call was not causing any flushing of the partially-full
1717 * network buffer to be written out, and instead was waiting until the
1718 * buffer was full before writing it out.
1719 *
1720 * Now, this could be due to a bug in Mac OSX's handling of TCP_NOPUSH;
1721 * there are articles about such a problem in earlier Mac OSX versions.
1722 * I should try this test again, on a Linux (TCP_CORK) and FreeBSD
1723 * (TCP_NOPUSH), to see if this can be done at least on those platforms.
1724 */
1725
1726 if (sent_version_id) {
1727 int res;
1728
1729 res = sftp_tap_send_packet();
1730 if (res < 0) {
1731 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1732 "error sending TAP packet: %s", strerror(errno));
1733 }
1734 }
1735
1736 return sftp_ssh2_packet_send(sockfd, pkt);
1737 }
1738
1739 void sftp_ssh2_packet_handle_debug(struct ssh2_packet *pkt) {
1740 register unsigned int i;
1741 char always_display;
1742 char *str;
1743
1744 always_display = sftp_msg_read_bool(pkt->pool, &pkt->payload,
1745 &pkt->payload_len);
1746 str = sftp_msg_read_string(pkt->pool, &pkt->payload, &pkt->payload_len);
1747
1748 /* Ignore the language tag. */
1749 (void) sftp_msg_read_string(pkt->pool, &pkt->payload, &pkt->payload_len);
1750
1751 /* Sanity-check the message for control (and other non-printable)
1752 * characters.
1753 */
1754 for (i = 0; i < strlen(str); i++) {
1755 if (PR_ISCNTRL(str[i]) ||
1756 !PR_ISPRINT(str[i])) {
1757 str[i] = '?';
1758 }
1759 }
1760
1761 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1762 "client sent SSH_MSG_DEBUG message '%s'", str);
1763
1764 if (always_display) {
1765 pr_log_debug(DEBUG0, MOD_SFTP_VERSION
1766 ": client sent SSH_MSG_DEBUG message '%s'", str);
1767 }
1768
1769 destroy_pool(pkt->pool);
1770 }
1771
1772 void sftp_ssh2_packet_handle_disconnect(struct ssh2_packet *pkt) {
1773 register unsigned int i;
1774 char *explain = NULL, *lang = NULL;
1775 const char *reason_str = NULL;
1776 uint32_t reason_code;
1777
1778 reason_code = sftp_msg_read_int(pkt->pool, &pkt->payload, &pkt->payload_len);
1779 reason_str = sftp_disconnect_get_str(reason_code);
1780 if (reason_str == NULL) {
1781 pr_trace_msg(trace_channel, 9,
1782 "client sent unknown disconnect reason code %lu",
1783 (unsigned long) reason_code);
1784 reason_str = "Unknown reason code";
1785 }
1786
1787 explain = sftp_msg_read_string(pkt->pool, &pkt->payload, &pkt->payload_len);
1788
1789 /* Not all clients send a language tag. */
1790 if (pkt->payload_len > 0) {
1791 lang = sftp_msg_read_string(pkt->pool, &pkt->payload, &pkt->payload_len);
1792 }
1793
1794 /* Sanity-check the message for control characters. */
1795 for (i = 0; i < strlen(explain); i++) {
1796 if (PR_ISCNTRL(explain[i])) {
1797 explain[i] = '?';
1798 }
1799 }
1800
1801 /* XXX Use the language tag somehow, if provided. */
1802 if (lang != NULL) {
1803 pr_trace_msg(trace_channel, 19, "client sent DISCONNECT language tag '%s'",
1804 lang);
1805 }
1806
1807 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1808 "client at %s sent SSH_DISCONNECT message: %s (%s)",
1809 pr_netaddr_get_ipstr(session.c->remote_addr), explain, reason_str);
1810 pr_session_disconnect(&sftp_module, PR_SESS_DISCONNECT_CLIENT_QUIT, explain);
1811 }
1812
1813 void sftp_ssh2_packet_handle_ext_info(struct ssh2_packet *pkt) {
1814 register unsigned int i;
1815 uint32_t ext_count;
1816
1817 ext_count = sftp_msg_read_int(pkt->pool, &pkt->payload, &pkt->payload_len);
1818 pr_trace_msg(trace_channel, 9, "client sent EXT_INFO with %lu %s",
1819 (unsigned long) ext_count, ext_count != 1 ? "extensions" : "extension");
1820
1821 if (ext_count > MAX_EXT_INFO_COUNT) {
1822 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1823 "client sent too many EXT_INFO extensions (%lu, max %lu), ignoring",
1824 (unsigned long) ext_count, (unsigned long) MAX_EXT_INFO_COUNT);
1825 destroy_pool(pkt->pool);
1826 return;
1827 }
1828
1829 for (i = 0; i < ext_count; i++) {
1830 char *ext_name = NULL;
1831 uint32_t ext_datalen = 0;
1832
1833 ext_name = sftp_msg_read_string(pkt->pool, &pkt->payload,
1834 &pkt->payload_len);
1835 ext_datalen = sftp_msg_read_int(pkt->pool, &pkt->payload,
1836 &pkt->payload_len);
1837 (void) sftp_msg_read_data_direct(pkt->pool, &pkt->payload,
1838 &pkt->payload_len, ext_datalen);
1839
1840 pr_trace_msg(trace_channel, 9,
1841 "client extension: %s (value %lu bytes)", ext_name,
1842 (unsigned long) ext_datalen);
1843
1844 /* TODO: Consider supporting the "no-flow-control" extension from
1845 * clients.
1846 */
1847 }
1848
1849 destroy_pool(pkt->pool);
1850 }
1851
1852 void sftp_ssh2_packet_handle_ignore(struct ssh2_packet *pkt) {
1853 char *str;
1854 size_t len;
1855
1856 str = sftp_msg_read_string(pkt->pool, &pkt->payload, &pkt->payload_len);
1857 len = strlen(str);
1858
1859 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1860 "client sent SSH_MSG_IGNORE message (%u bytes)", (unsigned int) len);
1861
1862 destroy_pool(pkt->pool);
1863 }
1864
1865 void sftp_ssh2_packet_handle_unimplemented(struct ssh2_packet *pkt) {
1866 uint32_t seqno;
1867
1868 seqno = sftp_msg_read_int(pkt->pool, &pkt->payload, &pkt->payload_len);
1869
1870 pr_trace_msg(trace_channel, 7, "received SSH_MSG_UNIMPLEMENTED for "
1871 "packet #%lu", (unsigned long) seqno);
1872
1873 destroy_pool(pkt->pool);
1874 }
1875
1876 static int handle_ssh2_packet(void *data) {
1877 struct ssh2_packet *pkt;
1878 char msg_type;
1879
1880 pkt = data;
1881 msg_type = sftp_ssh2_packet_get_msg_type(pkt);
1882 pr_trace_msg(trace_channel, 3, "received %s (%d) packet",
1883 sftp_ssh2_packet_get_msg_type_desc(msg_type), msg_type);
1884
1885 /* Note: Some of the SSH messages will be handled regardless of the
1886 * sftp_sess_state flags; this is intentional, and is the way that
1887 * the protocol is supposed to work.
1888 */
1889
1890 switch (msg_type) {
1891 case SFTP_SSH2_MSG_DEBUG:
1892 sftp_ssh2_packet_handle_debug(pkt);
1893 break;
1894
1895 case SFTP_SSH2_MSG_DISCONNECT:
1896 sftp_ssh2_packet_handle_disconnect(pkt);
1897 break;
1898
1899 case SFTP_SSH2_MSG_GLOBAL_REQUEST:
1900 handle_global_request_msg(pkt);
1901 break;
1902
1903 case SFTP_SSH2_MSG_REQUEST_SUCCESS:
1904 case SFTP_SSH2_MSG_REQUEST_FAILURE:
1905 case SFTP_SSH2_MSG_CHANNEL_SUCCESS:
1906 case SFTP_SSH2_MSG_CHANNEL_FAILURE:
1907 handle_client_alive_msg(pkt, msg_type);
1908 break;
1909
1910 case SFTP_SSH2_MSG_IGNORE:
1911 sftp_ssh2_packet_handle_ignore(pkt);
1912 break;
1913
1914 case SFTP_SSH2_MSG_UNIMPLEMENTED:
1915 sftp_ssh2_packet_handle_unimplemented(pkt);
1916 break;
1917
1918 case SFTP_SSH2_MSG_KEXINIT: {
1919 uint64_t start_ms = 0;
1920
1921 if (pr_trace_get_level(timing_channel) > 0) {
1922 pr_gettimeofday_millis(&start_ms);
1923 }
1924
1925 /* The client might be initiating a rekey; watch for this. */
1926 if (!(sftp_sess_state & SFTP_SESS_STATE_HAVE_KEX)) {
1927 if (pr_trace_get_level(timing_channel)) {
1928 unsigned long elapsed_ms;
1929 uint64_t finish_ms;
1930
1931 pr_gettimeofday_millis(&finish_ms);
1932 elapsed_ms = (unsigned long) (finish_ms - session.connect_time_ms);
1933
1934 pr_trace_msg(timing_channel, 4,
1935 "Time before first SSH key exchange: %lu ms", elapsed_ms);
1936 }
1937 }
1938
1939 sftp_sess_state |= SFTP_SESS_STATE_REKEYING;
1940
1941 /* Clear any current "have KEX" state. */
1942 sftp_sess_state &= ~SFTP_SESS_STATE_HAVE_KEX;
1943
1944 if (sftp_kex_handle(pkt) < 0) {
1945 pr_event_generate("mod_sftp.ssh2.kex.failed", NULL);
1946 SFTP_DISCONNECT_CONN(SFTP_SSH2_DISCONNECT_BY_APPLICATION, NULL);
1947 }
1948
1949 if (pr_trace_get_level(timing_channel)) {
1950 unsigned long elapsed_ms;
1951 uint64_t finish_ms;
1952
1953 pr_gettimeofday_millis(&finish_ms);
1954 elapsed_ms = (unsigned long) (finish_ms - start_ms);
1955
1956 pr_trace_msg(timing_channel, 4,
1957 "SSH key exchange duration: %lu ms", elapsed_ms);
1958 }
1959
1960 sftp_sess_state |= SFTP_SESS_STATE_HAVE_KEX;
1961 pr_event_generate("mod_sftp.ssh2.kex.completed", NULL);
1962
1963 /* If we just finished rekeying, drain any of the pending channel
1964 * data which may have built up during the rekeying exchange.
1965 */
1966 if (sftp_sess_state & SFTP_SESS_STATE_REKEYING) {
1967 sftp_sess_state &= ~SFTP_SESS_STATE_REKEYING;
1968 sftp_channel_drain_data();
1969 }
1970 break;
1971 }
1972
1973 case SFTP_SSH2_MSG_EXT_INFO:
1974 /* We expect any possible EXT_INFO message after NEWKEYS, and before
1975 * anything else.
1976 */
1977 if ((sftp_sess_state & SFTP_SESS_STATE_HAVE_KEX) &&
1978 !(sftp_sess_state & SFTP_SESS_STATE_HAVE_SERVICE) &&
1979 !(sftp_sess_state & SFTP_SESS_STATE_HAVE_EXT_INFO)) {
1980 sftp_ssh2_packet_handle_ext_info(pkt);
1981 sftp_sess_state |= SFTP_SESS_STATE_HAVE_EXT_INFO;
1982
1983 } else {
1984 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1985 "unable to handle %s (%d) message: wrong message order",
1986 sftp_ssh2_packet_get_msg_type_desc(msg_type), msg_type);
1987 }
1988 break;
1989
1990 case SFTP_SSH2_MSG_SERVICE_REQUEST:
1991 if (sftp_sess_state & SFTP_SESS_STATE_HAVE_KEX) {
1992 if (sftp_service_handle(pkt) < 0) {
1993 SFTP_DISCONNECT_CONN(SFTP_SSH2_DISCONNECT_BY_APPLICATION, NULL);
1994 }
1995
1996 sftp_sess_state |= SFTP_SESS_STATE_HAVE_SERVICE;
1997
1998 } else {
1999 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2000 "unable to handle %s (%d) message: Key exchange required",
2001 sftp_ssh2_packet_get_msg_type_desc(msg_type), msg_type);
2002 }
2003 break;
2004
2005 case SFTP_SSH2_MSG_USER_AUTH_REQUEST:
2006 if (sftp_sess_state & SFTP_SESS_STATE_HAVE_SERVICE) {
2007
2008 /* If the client has already authenticated this connection, then
2009 * silently ignore this additional auth request, per recommendation
2010 * in RFC4252.
2011 */
2012 if (sftp_sess_state & SFTP_SESS_STATE_HAVE_AUTH) {
2013 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2014 "ignoring %s (%d) message: Connection already authenticated",
2015 sftp_ssh2_packet_get_msg_type_desc(msg_type), msg_type);
2016
2017 } else {
2018 int ok;
2019
2020 ok = sftp_auth_handle(pkt);
2021 if (ok == 1) {
2022 sftp_sess_state |= SFTP_SESS_STATE_HAVE_AUTH;
2023
2024 } else if (ok < 0) {
2025 SFTP_DISCONNECT_CONN(SFTP_SSH2_DISCONNECT_BY_APPLICATION, NULL);
2026 }
2027 }
2028
2029 } else {
2030 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2031 "unable to handle %s (%d) message: Service request required",
2032 sftp_ssh2_packet_get_msg_type_desc(msg_type), msg_type);
2033 }
2034 break;
2035
2036 case SFTP_SSH2_MSG_CHANNEL_OPEN:
2037 case SFTP_SSH2_MSG_CHANNEL_REQUEST:
2038 case SFTP_SSH2_MSG_CHANNEL_CLOSE:
2039 case SFTP_SSH2_MSG_CHANNEL_DATA:
2040 case SFTP_SSH2_MSG_CHANNEL_EOF:
2041 case SFTP_SSH2_MSG_CHANNEL_WINDOW_ADJUST:
2042 if (sftp_sess_state & SFTP_SESS_STATE_HAVE_AUTH) {
2043 if (sftp_channel_handle(pkt, msg_type) < 0) {
2044 SFTP_DISCONNECT_CONN(SFTP_SSH2_DISCONNECT_BY_APPLICATION, NULL);
2045 }
2046
2047 } else {
2048 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2049 "unable to handle %s (%d) message: User authentication required",
2050 sftp_ssh2_packet_get_msg_type_desc(msg_type), msg_type);
2051 }
2052 break;
2053
2054 default:
2055 handle_unknown_msg(pkt, msg_type);
2056 }
2057
2058 return 0;
2059 }
2060
2061 int sftp_ssh2_packet_process(pool *p) {
2062 struct ssh2_packet *pkt;
2063 int res, xerrno;
2064
2065 pkt = sftp_ssh2_packet_create(p);
2066 res = sftp_ssh2_packet_read(sftp_conn->rfd, pkt);
2067 if (res < 0) {
2068 SFTP_DISCONNECT_CONN(SFTP_SSH2_DISCONNECT_BY_APPLICATION, NULL);
2069 }
2070
2071 pr_response_clear(&resp_list);
2072 pr_response_clear(&resp_err_list);
2073 pr_response_set_pool(pkt->pool);
2074
2075 if (pkt->payload_len == 0 ||
2076 pkt->payload == NULL) {
2077 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2078 "received illegal packet with no payload, disconnecting");
2079 SFTP_DISCONNECT_CONN(SFTP_SSH2_DISCONNECT_BY_APPLICATION, NULL);
2080 }
2081
2082 /* If a custom handler rejects this packet with ENOSYS, it means we need
2083 * to fall back to handling it ourselves. Our own handler never returns
2084 * ENOSYS.
2085 */
2086 res = (packet_handler)((void *) pkt);
2087 xerrno = errno;
2088
2089 if (res < 0 &&
2090 xerrno == ENOSYS) {
2091 (void) handle_ssh2_packet((void *) pkt);
2092 }
2093
2094 pr_response_set_pool(NULL);
2095 return 0;
2096 }
2097
2098 void sftp_ssh2_packet_set_handler(int (*handler)(void *)) {
2099 if (handler == NULL) {
2100 packet_handler = handle_ssh2_packet;
2101
2102 } else {
2103 packet_handler = handler;
2104 }
2105 }
2106
2107 int sftp_ssh2_packet_rekey_reset(void) {
2108 rekey_client_len = 0;
2109 rekey_server_len = 0;
2110
2111 /* Add the rekey seqno limit to the current sequence numbers. */
2112
2113 if (rekey_client_seqno > 0) {
2114 rekey_client_seqno = packet_client_seqno + SFTP_PACKET_CLIENT_REKEY_SEQNO_LIMIT;
2115
2116 if (rekey_client_seqno == 0) {
2117 rekey_client_seqno++;
2118 }
2119 }
2120
2121 if (rekey_server_seqno > 0) {
2122 rekey_server_seqno = packet_client_seqno + SFTP_PACKET_SERVER_REKEY_SEQNO_LIMIT;
2123
2124 if (rekey_server_seqno == 0) {
2125 rekey_server_seqno++;
2126 }
2127 }
2128
2129 return 0;
2130 }
2131
2132 int sftp_ssh2_packet_rekey_set_seqno(uint32_t seqno) {
2133 rekey_client_seqno = seqno;
2134 rekey_server_seqno = seqno;
2135 return 0;
2136 }
2137
2138 int sftp_ssh2_packet_rekey_set_size(off_t size) {
2139 rekey_size = size;
2140 return 0;
2141 }
2142
2143 uint32_t sftp_ssh2_packet_get_client_seqno(void) {
2144 return packet_client_seqno;
2145 }
2146
2147 void sftp_ssh2_packet_reset_client_seqno(void) {
2148 packet_client_seqno = 0;
2149 }
2150
2151 void sftp_ssh2_packet_reset_server_seqno(void) {
2152 packet_server_seqno = 0;
2153 }
2154
2155 int sftp_ssh2_packet_send_version(void) {
2156 if (!sent_version_id) {
2157 int res;
2158 size_t version_len;
2159
2160 version_len = strlen(version_id);
2161
2162 res = write(sftp_conn->wfd, version_id, version_len);
2163 while (res < 0) {
2164 if (errno == EINTR) {
2165 pr_signals_handle();
2166
2167 res = write(sftp_conn->wfd, version_id, version_len);
2168 continue;
2169 }
2170
2171 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2172 "error sending version to client wfd %d: %s", sftp_conn->wfd,
2173 strerror(errno));
2174 return res;
2175 }
2176
2177 sent_version_id = TRUE;
2178 session.total_raw_out += res;
2179
2180 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2181 "sent server version '%s'", server_version);
2182 }
2183
2184 return 0;
2185 }
2186
2187 int sftp_ssh2_packet_set_version(const char *version) {
2188 if (server_version == NULL) {
2189 errno = EINVAL;
2190 return -1;
2191 }
2192
2193 server_version = version;
2194 version_id = pstrcat(sftp_pool, version, "\r\n", NULL);
2195 return 0;
2196 }
2197