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