1 /* $OpenBSD: sftp-server.c,v 1.153 2026/03/03 09:57:25 dtucker Exp $ */
2 /*
3 * Copyright (c) 2000-2004 Markus Friedl. All rights reserved.
4 *
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
8 *
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16 */
17
18 #include "includes.h"
19
20 #include <sys/types.h>
21 #include <sys/resource.h>
22 #include <sys/stat.h>
23 #include <sys/time.h>
24 #include <sys/statvfs.h>
25
26 #include <dirent.h>
27 #include <errno.h>
28 #include <fcntl.h>
29 #include <limits.h>
30 #include <poll.h>
31 #include <pwd.h>
32 #include <grp.h>
33 #include <stdlib.h>
34 #include <stdio.h>
35 #include <string.h>
36 #include <time.h>
37 #include <unistd.h>
38 #include <stdarg.h>
39
40 #include "atomicio.h"
41 #include "xmalloc.h"
42 #include "sshbuf.h"
43 #include "ssherr.h"
44 #include "log.h"
45 #include "misc.h"
46 #include "match.h"
47 #include "uidswap.h"
48
49 #include "sftp.h"
50 #include "sftp-common.h"
51
52 char *sftp_realpath(const char *, char *); /* sftp-realpath.c */
53
54 /* Maximum data read that we are willing to accept */
55 #define SFTP_MAX_READ_LENGTH (SFTP_MAX_MSG_LENGTH - 1024)
56
57 /* Our verbosity */
58 static LogLevel log_level = SYSLOG_LEVEL_ERROR;
59
60 /* Our client */
61 static struct passwd *pw = NULL;
62 static char *client_addr = NULL;
63
64 /* input and output queue */
65 struct sshbuf *iqueue;
66 struct sshbuf *oqueue;
67
68 /* Version of client */
69 static u_int version;
70
71 /* SSH2_FXP_INIT received */
72 static int init_done;
73
74 /* Disable writes */
75 static int readonly;
76
77 /* Requests that are allowed/denied */
78 static char *request_allowlist, *request_denylist;
79
80 /* portable attributes, etc. */
81 typedef struct Stat Stat;
82
83 struct Stat {
84 char *name;
85 char *long_name;
86 Attrib attrib;
87 };
88
89 /* Packet handlers */
90 static void process_open(uint32_t id);
91 static void process_close(uint32_t id);
92 static void process_read(uint32_t id);
93 static void process_write(uint32_t id);
94 static void process_stat(uint32_t id);
95 static void process_lstat(uint32_t id);
96 static void process_fstat(uint32_t id);
97 static void process_setstat(uint32_t id);
98 static void process_fsetstat(uint32_t id);
99 static void process_opendir(uint32_t id);
100 static void process_readdir(uint32_t id);
101 static void process_remove(uint32_t id);
102 static void process_mkdir(uint32_t id);
103 static void process_rmdir(uint32_t id);
104 static void process_realpath(uint32_t id);
105 static void process_rename(uint32_t id);
106 static void process_readlink(uint32_t id);
107 static void process_symlink(uint32_t id);
108 static void process_extended_posix_rename(uint32_t id);
109 static void process_extended_statvfs(uint32_t id);
110 static void process_extended_fstatvfs(uint32_t id);
111 static void process_extended_hardlink(uint32_t id);
112 static void process_extended_fsync(uint32_t id);
113 static void process_extended_lsetstat(uint32_t id);
114 static void process_extended_limits(uint32_t id);
115 static void process_extended_expand(uint32_t id);
116 static void process_extended_copy_data(uint32_t id);
117 static void process_extended_home_directory(uint32_t id);
118 static void process_extended_get_users_groups_by_id(uint32_t id);
119 static void process_extended(uint32_t id);
120
121 struct sftp_handler {
122 const char *name; /* user-visible name for fine-grained perms */
123 const char *ext_name; /* extended request name */
124 u_int type; /* packet type, for non extended packets */
125 void (*handler)(uint32_t);
126 int does_write; /* if nonzero, banned for readonly mode */
127 };
128
129 static const struct sftp_handler handlers[] = {
130 /* NB. SSH2_FXP_OPEN does the readonly check in the handler itself */
131 { "open", NULL, SSH2_FXP_OPEN, process_open, 0 },
132 { "close", NULL, SSH2_FXP_CLOSE, process_close, 0 },
133 { "read", NULL, SSH2_FXP_READ, process_read, 0 },
134 { "write", NULL, SSH2_FXP_WRITE, process_write, 1 },
135 { "lstat", NULL, SSH2_FXP_LSTAT, process_lstat, 0 },
136 { "fstat", NULL, SSH2_FXP_FSTAT, process_fstat, 0 },
137 { "setstat", NULL, SSH2_FXP_SETSTAT, process_setstat, 1 },
138 { "fsetstat", NULL, SSH2_FXP_FSETSTAT, process_fsetstat, 1 },
139 { "opendir", NULL, SSH2_FXP_OPENDIR, process_opendir, 0 },
140 { "readdir", NULL, SSH2_FXP_READDIR, process_readdir, 0 },
141 { "remove", NULL, SSH2_FXP_REMOVE, process_remove, 1 },
142 { "mkdir", NULL, SSH2_FXP_MKDIR, process_mkdir, 1 },
143 { "rmdir", NULL, SSH2_FXP_RMDIR, process_rmdir, 1 },
144 { "realpath", NULL, SSH2_FXP_REALPATH, process_realpath, 0 },
145 { "stat", NULL, SSH2_FXP_STAT, process_stat, 0 },
146 { "rename", NULL, SSH2_FXP_RENAME, process_rename, 1 },
147 { "readlink", NULL, SSH2_FXP_READLINK, process_readlink, 0 },
148 { "symlink", NULL, SSH2_FXP_SYMLINK, process_symlink, 1 },
149 { NULL, NULL, 0, NULL, 0 }
150 };
151
152 /* SSH2_FXP_EXTENDED submessages */
153 static const struct sftp_handler extended_handlers[] = {
154 { "posix-rename", "posix-rename@openssh.com", 0,
155 process_extended_posix_rename, 1 },
156 { "statvfs", "statvfs@openssh.com", 0, process_extended_statvfs, 0 },
157 { "fstatvfs", "fstatvfs@openssh.com", 0, process_extended_fstatvfs, 0 },
158 { "hardlink", "hardlink@openssh.com", 0, process_extended_hardlink, 1 },
159 { "fsync", "fsync@openssh.com", 0, process_extended_fsync, 1 },
160 { "lsetstat", "lsetstat@openssh.com", 0, process_extended_lsetstat, 1 },
161 { "limits", "limits@openssh.com", 0, process_extended_limits, 0 },
162 { "expand-path", "expand-path@openssh.com", 0,
163 process_extended_expand, 0 },
164 { "copy-data", "copy-data", 0, process_extended_copy_data, 1 },
165 { "home-directory", "home-directory", 0,
166 process_extended_home_directory, 0 },
167 { "users-groups-by-id", "users-groups-by-id@openssh.com", 0,
168 process_extended_get_users_groups_by_id, 0 },
169 { NULL, NULL, 0, NULL, 0 }
170 };
171
172 static const struct sftp_handler *
extended_handler_byname(const char * name)173 extended_handler_byname(const char *name)
174 {
175 int i;
176
177 for (i = 0; extended_handlers[i].handler != NULL; i++) {
178 if (strcmp(name, extended_handlers[i].ext_name) == 0)
179 return &extended_handlers[i];
180 }
181 return NULL;
182 }
183
184 static int
request_permitted(const struct sftp_handler * h)185 request_permitted(const struct sftp_handler *h)
186 {
187 char *result;
188
189 if (readonly && h->does_write) {
190 verbose("Refusing %s request in read-only mode", h->name);
191 return 0;
192 }
193 if (request_denylist != NULL &&
194 ((result = match_list(h->name, request_denylist, NULL))) != NULL) {
195 free(result);
196 verbose("Refusing denylisted %s request", h->name);
197 return 0;
198 }
199 if (request_allowlist != NULL &&
200 ((result = match_list(h->name, request_allowlist, NULL))) != NULL) {
201 free(result);
202 debug2("Permitting allowlisted %s request", h->name);
203 return 1;
204 }
205 if (request_allowlist != NULL) {
206 verbose("Refusing non-allowlisted %s request", h->name);
207 return 0;
208 }
209 return 1;
210 }
211
212 static int
errno_to_portable(int unixerrno)213 errno_to_portable(int unixerrno)
214 {
215 int ret = 0;
216
217 switch (unixerrno) {
218 case 0:
219 ret = SSH2_FX_OK;
220 break;
221 case ENOENT:
222 case ENOTDIR:
223 case EBADF:
224 case ELOOP:
225 ret = SSH2_FX_NO_SUCH_FILE;
226 break;
227 case EPERM:
228 case EACCES:
229 case EFAULT:
230 ret = SSH2_FX_PERMISSION_DENIED;
231 break;
232 case ENAMETOOLONG:
233 case EINVAL:
234 ret = SSH2_FX_BAD_MESSAGE;
235 break;
236 case ENOSYS:
237 ret = SSH2_FX_OP_UNSUPPORTED;
238 break;
239 default:
240 ret = SSH2_FX_FAILURE;
241 break;
242 }
243 return ret;
244 }
245
246 static int
flags_from_portable(int pflags)247 flags_from_portable(int pflags)
248 {
249 int flags = 0;
250
251 if ((pflags & SSH2_FXF_READ) &&
252 (pflags & SSH2_FXF_WRITE)) {
253 flags = O_RDWR;
254 } else if (pflags & SSH2_FXF_READ) {
255 flags = O_RDONLY;
256 } else if (pflags & SSH2_FXF_WRITE) {
257 flags = O_WRONLY;
258 }
259 if (pflags & SSH2_FXF_APPEND)
260 flags |= O_APPEND;
261 if (pflags & SSH2_FXF_CREAT)
262 flags |= O_CREAT;
263 if (pflags & SSH2_FXF_TRUNC)
264 flags |= O_TRUNC;
265 if (pflags & SSH2_FXF_EXCL)
266 flags |= O_EXCL;
267 return flags;
268 }
269
270 static const char *
string_from_portable(int pflags)271 string_from_portable(int pflags)
272 {
273 static char ret[128];
274
275 *ret = '\0';
276
277 #define PAPPEND(str) { \
278 if (*ret != '\0') \
279 strlcat(ret, ",", sizeof(ret)); \
280 strlcat(ret, str, sizeof(ret)); \
281 }
282
283 if (pflags & SSH2_FXF_READ)
284 PAPPEND("READ")
285 if (pflags & SSH2_FXF_WRITE)
286 PAPPEND("WRITE")
287 if (pflags & SSH2_FXF_APPEND)
288 PAPPEND("APPEND")
289 if (pflags & SSH2_FXF_CREAT)
290 PAPPEND("CREATE")
291 if (pflags & SSH2_FXF_TRUNC)
292 PAPPEND("TRUNCATE")
293 if (pflags & SSH2_FXF_EXCL)
294 PAPPEND("EXCL")
295
296 return ret;
297 }
298
299 /* handle handles */
300
301 typedef struct Handle Handle;
302 struct Handle {
303 int use;
304 DIR *dirp;
305 int fd;
306 int flags;
307 char *name;
308 uint64_t bytes_read, bytes_write;
309 int next_unused;
310 };
311
312 enum {
313 HANDLE_UNUSED,
314 HANDLE_DIR,
315 HANDLE_FILE
316 };
317
318 static Handle *handles = NULL;
319 static u_int num_handles = 0;
320 static int first_unused_handle = -1;
321
handle_unused(int i)322 static void handle_unused(int i)
323 {
324 handles[i].use = HANDLE_UNUSED;
325 handles[i].next_unused = first_unused_handle;
326 first_unused_handle = i;
327 }
328
329 static int
handle_new(int use,const char * name,int fd,int flags,DIR * dirp)330 handle_new(int use, const char *name, int fd, int flags, DIR *dirp)
331 {
332 int i;
333
334 if (first_unused_handle == -1) {
335 if (num_handles + 1 <= num_handles)
336 return -1;
337 num_handles++;
338 handles = xreallocarray(handles, num_handles, sizeof(Handle));
339 handle_unused(num_handles - 1);
340 }
341
342 i = first_unused_handle;
343 first_unused_handle = handles[i].next_unused;
344
345 handles[i].use = use;
346 handles[i].dirp = dirp;
347 handles[i].fd = fd;
348 handles[i].flags = flags;
349 handles[i].name = xstrdup(name);
350 handles[i].bytes_read = handles[i].bytes_write = 0;
351
352 return i;
353 }
354
355 static int
handle_is_ok(int i,int type)356 handle_is_ok(int i, int type)
357 {
358 return i >= 0 && (u_int)i < num_handles && handles[i].use == type;
359 }
360
361 static int
handle_to_string(int handle,u_char ** stringp,int * hlenp)362 handle_to_string(int handle, u_char **stringp, int *hlenp)
363 {
364 if (stringp == NULL || hlenp == NULL)
365 return -1;
366 *stringp = xmalloc(sizeof(int32_t));
367 put_u32(*stringp, handle);
368 *hlenp = sizeof(int32_t);
369 return 0;
370 }
371
372 static int
handle_from_string(const u_char * handle,u_int hlen)373 handle_from_string(const u_char *handle, u_int hlen)
374 {
375 int val;
376
377 if (hlen != sizeof(int32_t))
378 return -1;
379 val = get_u32(handle);
380 if (handle_is_ok(val, HANDLE_FILE) ||
381 handle_is_ok(val, HANDLE_DIR))
382 return val;
383 return -1;
384 }
385
386 static char *
handle_to_name(int handle)387 handle_to_name(int handle)
388 {
389 if (handle_is_ok(handle, HANDLE_DIR)||
390 handle_is_ok(handle, HANDLE_FILE))
391 return handles[handle].name;
392 return NULL;
393 }
394
395 static DIR *
handle_to_dir(int handle)396 handle_to_dir(int handle)
397 {
398 if (handle_is_ok(handle, HANDLE_DIR))
399 return handles[handle].dirp;
400 return NULL;
401 }
402
403 static int
handle_to_fd(int handle)404 handle_to_fd(int handle)
405 {
406 if (handle_is_ok(handle, HANDLE_FILE))
407 return handles[handle].fd;
408 return -1;
409 }
410
411 static int
handle_to_flags(int handle)412 handle_to_flags(int handle)
413 {
414 if (handle_is_ok(handle, HANDLE_FILE))
415 return handles[handle].flags;
416 return 0;
417 }
418
419 static void
handle_update_read(int handle,ssize_t bytes)420 handle_update_read(int handle, ssize_t bytes)
421 {
422 if (handle_is_ok(handle, HANDLE_FILE) && bytes > 0)
423 handles[handle].bytes_read += bytes;
424 }
425
426 static void
handle_update_write(int handle,ssize_t bytes)427 handle_update_write(int handle, ssize_t bytes)
428 {
429 if (handle_is_ok(handle, HANDLE_FILE) && bytes > 0)
430 handles[handle].bytes_write += bytes;
431 }
432
433 static uint64_t
handle_bytes_read(int handle)434 handle_bytes_read(int handle)
435 {
436 if (handle_is_ok(handle, HANDLE_FILE))
437 return (handles[handle].bytes_read);
438 return 0;
439 }
440
441 static uint64_t
handle_bytes_write(int handle)442 handle_bytes_write(int handle)
443 {
444 if (handle_is_ok(handle, HANDLE_FILE))
445 return (handles[handle].bytes_write);
446 return 0;
447 }
448
449 static int
handle_close(int handle)450 handle_close(int handle)
451 {
452 int ret = -1;
453
454 if (handle_is_ok(handle, HANDLE_FILE)) {
455 ret = close(handles[handle].fd);
456 free(handles[handle].name);
457 handle_unused(handle);
458 } else if (handle_is_ok(handle, HANDLE_DIR)) {
459 ret = closedir(handles[handle].dirp);
460 free(handles[handle].name);
461 handle_unused(handle);
462 } else {
463 errno = ENOENT;
464 }
465 return ret;
466 }
467
468 static void
handle_log_close(int handle,char * emsg)469 handle_log_close(int handle, char *emsg)
470 {
471 if (handle_is_ok(handle, HANDLE_FILE)) {
472 logit("%s%sclose \"%s\" bytes read %llu written %llu",
473 emsg == NULL ? "" : emsg, emsg == NULL ? "" : " ",
474 handle_to_name(handle),
475 (unsigned long long)handle_bytes_read(handle),
476 (unsigned long long)handle_bytes_write(handle));
477 } else {
478 logit("%s%sclosedir \"%s\"",
479 emsg == NULL ? "" : emsg, emsg == NULL ? "" : " ",
480 handle_to_name(handle));
481 }
482 }
483
484 static void
handle_log_exit(void)485 handle_log_exit(void)
486 {
487 u_int i;
488
489 for (i = 0; i < num_handles; i++)
490 if (handles[i].use != HANDLE_UNUSED)
491 handle_log_close(i, "forced");
492 }
493
494 static int
get_handle(struct sshbuf * queue,int * hp)495 get_handle(struct sshbuf *queue, int *hp)
496 {
497 u_char *handle;
498 int r;
499 size_t hlen;
500
501 *hp = -1;
502 if ((r = sshbuf_get_string(queue, &handle, &hlen)) != 0)
503 return r;
504 if (hlen < 256)
505 *hp = handle_from_string(handle, hlen);
506 free(handle);
507 return 0;
508 }
509
510 /* send replies */
511
512 static void
send_msg(struct sshbuf * m)513 send_msg(struct sshbuf *m)
514 {
515 int r;
516
517 if ((r = sshbuf_put_stringb(oqueue, m)) != 0)
518 fatal_fr(r, "enqueue");
519 sshbuf_reset(m);
520 }
521
522 static const char *
status_to_message(uint32_t status)523 status_to_message(uint32_t status)
524 {
525 static const char * const status_messages[] = {
526 "Success", /* SSH_FX_OK */
527 "End of file", /* SSH_FX_EOF */
528 "No such file", /* SSH_FX_NO_SUCH_FILE */
529 "Permission denied", /* SSH_FX_PERMISSION_DENIED */
530 "Failure", /* SSH_FX_FAILURE */
531 "Bad message", /* SSH_FX_BAD_MESSAGE */
532 "No connection", /* SSH_FX_NO_CONNECTION */
533 "Connection lost", /* SSH_FX_CONNECTION_LOST */
534 "Operation unsupported", /* SSH_FX_OP_UNSUPPORTED */
535 "Unknown error" /* Others */
536 };
537 return (status_messages[MINIMUM(status,SSH2_FX_MAX)]);
538 }
539
540 static void
send_status_errmsg(uint32_t id,uint32_t status,const char * errmsg)541 send_status_errmsg(uint32_t id, uint32_t status, const char *errmsg)
542 {
543 struct sshbuf *msg;
544 int r;
545
546 debug3("request %u: sent status %u", id, status);
547 if (log_level > SYSLOG_LEVEL_VERBOSE ||
548 (status != SSH2_FX_OK && status != SSH2_FX_EOF))
549 logit("sent status %s", status_to_message(status));
550 if ((msg = sshbuf_new()) == NULL)
551 fatal_f("sshbuf_new failed");
552 if ((r = sshbuf_put_u8(msg, SSH2_FXP_STATUS)) != 0 ||
553 (r = sshbuf_put_u32(msg, id)) != 0 ||
554 (r = sshbuf_put_u32(msg, status)) != 0)
555 fatal_fr(r, "compose");
556 if (version >= 3) {
557 if ((r = sshbuf_put_cstring(msg, errmsg == NULL ?
558 status_to_message(status) : errmsg)) != 0 ||
559 (r = sshbuf_put_cstring(msg, "")) != 0)
560 fatal_fr(r, "compose message");
561 }
562 send_msg(msg);
563 sshbuf_free(msg);
564 }
565
566 static void
send_status(uint32_t id,uint32_t status)567 send_status(uint32_t id, uint32_t status)
568 {
569 send_status_errmsg(id, status, NULL);
570 }
571
572 static void
send_data_or_handle(char type,uint32_t id,const u_char * data,int dlen)573 send_data_or_handle(char type, uint32_t id, const u_char *data, int dlen)
574 {
575 struct sshbuf *msg;
576 int r;
577
578 if ((msg = sshbuf_new()) == NULL)
579 fatal_f("sshbuf_new failed");
580 if ((r = sshbuf_put_u8(msg, type)) != 0 ||
581 (r = sshbuf_put_u32(msg, id)) != 0 ||
582 (r = sshbuf_put_string(msg, data, dlen)) != 0)
583 fatal_fr(r, "compose");
584 send_msg(msg);
585 sshbuf_free(msg);
586 }
587
588 static void
send_data(uint32_t id,const u_char * data,int dlen)589 send_data(uint32_t id, const u_char *data, int dlen)
590 {
591 debug("request %u: sent data len %d", id, dlen);
592 send_data_or_handle(SSH2_FXP_DATA, id, data, dlen);
593 }
594
595 static void
send_handle(uint32_t id,int handle)596 send_handle(uint32_t id, int handle)
597 {
598 u_char *string;
599 int hlen;
600
601 handle_to_string(handle, &string, &hlen);
602 debug("request %u: sent handle %d", id, handle);
603 send_data_or_handle(SSH2_FXP_HANDLE, id, string, hlen);
604 free(string);
605 }
606
607 static void
send_names(uint32_t id,int count,const Stat * stats)608 send_names(uint32_t id, int count, const Stat *stats)
609 {
610 struct sshbuf *msg;
611 int i, r;
612
613 if ((msg = sshbuf_new()) == NULL)
614 fatal_f("sshbuf_new failed");
615 if ((r = sshbuf_put_u8(msg, SSH2_FXP_NAME)) != 0 ||
616 (r = sshbuf_put_u32(msg, id)) != 0 ||
617 (r = sshbuf_put_u32(msg, count)) != 0)
618 fatal_fr(r, "compose");
619 debug("request %u: sent names count %d", id, count);
620 for (i = 0; i < count; i++) {
621 if ((r = sshbuf_put_cstring(msg, stats[i].name)) != 0 ||
622 (r = sshbuf_put_cstring(msg, stats[i].long_name)) != 0 ||
623 (r = encode_attrib(msg, &stats[i].attrib)) != 0)
624 fatal_fr(r, "compose filenames/attrib");
625 }
626 send_msg(msg);
627 sshbuf_free(msg);
628 }
629
630 static void
send_attrib(uint32_t id,const Attrib * a)631 send_attrib(uint32_t id, const Attrib *a)
632 {
633 struct sshbuf *msg;
634 int r;
635
636 debug("request %u: sent attrib have 0x%x", id, a->flags);
637 if ((msg = sshbuf_new()) == NULL)
638 fatal_f("sshbuf_new failed");
639 if ((r = sshbuf_put_u8(msg, SSH2_FXP_ATTRS)) != 0 ||
640 (r = sshbuf_put_u32(msg, id)) != 0 ||
641 (r = encode_attrib(msg, a)) != 0)
642 fatal_fr(r, "compose");
643 send_msg(msg);
644 sshbuf_free(msg);
645 }
646
647 static void
send_statvfs(uint32_t id,struct statvfs * st)648 send_statvfs(uint32_t id, struct statvfs *st)
649 {
650 struct sshbuf *msg;
651 uint64_t flag;
652 int r;
653
654 flag = (st->f_flag & ST_RDONLY) ? SSH2_FXE_STATVFS_ST_RDONLY : 0;
655 flag |= (st->f_flag & ST_NOSUID) ? SSH2_FXE_STATVFS_ST_NOSUID : 0;
656
657 if ((msg = sshbuf_new()) == NULL)
658 fatal_f("sshbuf_new failed");
659 if ((r = sshbuf_put_u8(msg, SSH2_FXP_EXTENDED_REPLY)) != 0 ||
660 (r = sshbuf_put_u32(msg, id)) != 0 ||
661 (r = sshbuf_put_u64(msg, st->f_bsize)) != 0 ||
662 (r = sshbuf_put_u64(msg, st->f_frsize)) != 0 ||
663 (r = sshbuf_put_u64(msg, st->f_blocks)) != 0 ||
664 (r = sshbuf_put_u64(msg, st->f_bfree)) != 0 ||
665 (r = sshbuf_put_u64(msg, st->f_bavail)) != 0 ||
666 (r = sshbuf_put_u64(msg, st->f_files)) != 0 ||
667 (r = sshbuf_put_u64(msg, st->f_ffree)) != 0 ||
668 (r = sshbuf_put_u64(msg, st->f_favail)) != 0 ||
669 (r = sshbuf_put_u64(msg, FSID_TO_ULONG(st->f_fsid))) != 0 ||
670 (r = sshbuf_put_u64(msg, flag)) != 0 ||
671 (r = sshbuf_put_u64(msg, st->f_namemax)) != 0)
672 fatal_fr(r, "compose");
673 send_msg(msg);
674 sshbuf_free(msg);
675 }
676
677 /*
678 * Prepare SSH2_FXP_VERSION extension advertisement for a single extension.
679 * The extension is checked for permission prior to advertisement.
680 */
681 static int
compose_extension(struct sshbuf * msg,const char * name,const char * ver)682 compose_extension(struct sshbuf *msg, const char *name, const char *ver)
683 {
684 int r;
685 const struct sftp_handler *exthnd;
686
687 if ((exthnd = extended_handler_byname(name)) == NULL)
688 fatal_f("internal error: no handler for %s", name);
689 if (!request_permitted(exthnd)) {
690 debug2_f("refusing to advertise disallowed extension %s", name);
691 return 0;
692 }
693 if ((r = sshbuf_put_cstring(msg, name)) != 0 ||
694 (r = sshbuf_put_cstring(msg, ver)) != 0)
695 fatal_fr(r, "compose %s", name);
696 return 0;
697 }
698
699 /* parse incoming */
700
701 static void
process_init(void)702 process_init(void)
703 {
704 struct sshbuf *msg;
705 int r;
706
707 if ((r = sshbuf_get_u32(iqueue, &version)) != 0)
708 fatal_fr(r, "parse");
709 verbose("received client version %u", version);
710 if ((msg = sshbuf_new()) == NULL)
711 fatal_f("sshbuf_new failed");
712 if ((r = sshbuf_put_u8(msg, SSH2_FXP_VERSION)) != 0 ||
713 (r = sshbuf_put_u32(msg, SSH2_FILEXFER_VERSION)) != 0)
714 fatal_fr(r, "compose");
715
716 /* extension advertisements */
717 compose_extension(msg, "posix-rename@openssh.com", "1");
718 compose_extension(msg, "statvfs@openssh.com", "2");
719 compose_extension(msg, "fstatvfs@openssh.com", "2");
720 compose_extension(msg, "hardlink@openssh.com", "1");
721 compose_extension(msg, "fsync@openssh.com", "1");
722 compose_extension(msg, "lsetstat@openssh.com", "1");
723 compose_extension(msg, "limits@openssh.com", "1");
724 compose_extension(msg, "expand-path@openssh.com", "1");
725 compose_extension(msg, "copy-data", "1");
726 compose_extension(msg, "home-directory", "1");
727 compose_extension(msg, "users-groups-by-id@openssh.com", "1");
728
729 send_msg(msg);
730 sshbuf_free(msg);
731 }
732
733 static void
process_open(uint32_t id)734 process_open(uint32_t id)
735 {
736 uint32_t pflags;
737 Attrib a;
738 char *name;
739 int r, handle, fd, flags, mode, status = SSH2_FX_FAILURE;
740
741 if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0 ||
742 (r = sshbuf_get_u32(iqueue, &pflags)) != 0 || /* portable flags */
743 (r = decode_attrib(iqueue, &a)) != 0)
744 fatal_fr(r, "parse");
745
746 debug3("request %u: open flags %d", id, pflags);
747 flags = flags_from_portable(pflags);
748 mode = (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) ? a.perm : 0666;
749 logit("open \"%s\" flags %s mode 0%o",
750 name, string_from_portable(pflags), mode);
751 if (readonly &&
752 ((flags & O_ACCMODE) != O_RDONLY ||
753 (flags & (O_CREAT|O_TRUNC)) != 0)) {
754 verbose("Refusing open request in read-only mode");
755 status = SSH2_FX_PERMISSION_DENIED;
756 } else {
757 fd = open(name, flags, mode);
758 if (fd == -1) {
759 status = errno_to_portable(errno);
760 } else {
761 handle = handle_new(HANDLE_FILE, name, fd, flags, NULL);
762 if (handle < 0) {
763 close(fd);
764 } else {
765 send_handle(id, handle);
766 status = SSH2_FX_OK;
767 }
768 }
769 }
770 if (status != SSH2_FX_OK)
771 send_status(id, status);
772 free(name);
773 }
774
775 static void
process_close(uint32_t id)776 process_close(uint32_t id)
777 {
778 int r, handle, ret, status = SSH2_FX_FAILURE;
779
780 if ((r = get_handle(iqueue, &handle)) != 0)
781 fatal_fr(r, "parse");
782
783 debug3("request %u: close handle %u", id, handle);
784 handle_log_close(handle, NULL);
785 ret = handle_close(handle);
786 status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
787 send_status(id, status);
788 }
789
790 static void
process_read(uint32_t id)791 process_read(uint32_t id)
792 {
793 static u_char *buf;
794 static size_t buflen;
795 uint32_t len;
796 int r, handle, fd, ret, status = SSH2_FX_FAILURE;
797 uint64_t off;
798
799 if ((r = get_handle(iqueue, &handle)) != 0 ||
800 (r = sshbuf_get_u64(iqueue, &off)) != 0 ||
801 (r = sshbuf_get_u32(iqueue, &len)) != 0)
802 fatal_fr(r, "parse");
803
804 debug("request %u: read \"%s\" (handle %d) off %llu len %u",
805 id, handle_to_name(handle), handle, (unsigned long long)off, len);
806 if ((fd = handle_to_fd(handle)) == -1)
807 goto out;
808 if (len > SFTP_MAX_READ_LENGTH) {
809 debug2("read change len %u to %u", len, SFTP_MAX_READ_LENGTH);
810 len = SFTP_MAX_READ_LENGTH;
811 }
812 if (len > buflen) {
813 debug3_f("allocate %zu => %u", buflen, len);
814 if ((buf = realloc(buf, len)) == NULL)
815 fatal_f("realloc failed");
816 buflen = len;
817 }
818 if (lseek(fd, off, SEEK_SET) == -1) {
819 status = errno_to_portable(errno);
820 error_f("seek \"%.100s\": %s", handle_to_name(handle),
821 strerror(errno));
822 goto out;
823 }
824 if (len == 0) {
825 /* weird, but not strictly disallowed */
826 ret = 0;
827 } else if ((ret = read(fd, buf, len)) == -1) {
828 status = errno_to_portable(errno);
829 error_f("read \"%.100s\": %s", handle_to_name(handle),
830 strerror(errno));
831 goto out;
832 } else if (ret == 0) {
833 status = SSH2_FX_EOF;
834 goto out;
835 }
836 send_data(id, buf, ret);
837 handle_update_read(handle, ret);
838 /* success */
839 status = SSH2_FX_OK;
840 out:
841 if (status != SSH2_FX_OK)
842 send_status(id, status);
843 }
844
845 static void
process_write(uint32_t id)846 process_write(uint32_t id)
847 {
848 uint64_t off;
849 size_t len;
850 int r, handle, fd, ret, status;
851 u_char *data;
852
853 if ((r = get_handle(iqueue, &handle)) != 0 ||
854 (r = sshbuf_get_u64(iqueue, &off)) != 0 ||
855 (r = sshbuf_get_string(iqueue, &data, &len)) != 0)
856 fatal_fr(r, "parse");
857
858 debug("request %u: write \"%s\" (handle %d) off %llu len %zu",
859 id, handle_to_name(handle), handle, (unsigned long long)off, len);
860 fd = handle_to_fd(handle);
861
862 if (fd < 0)
863 status = SSH2_FX_FAILURE;
864 else {
865 if (!(handle_to_flags(handle) & O_APPEND) &&
866 lseek(fd, off, SEEK_SET) == -1) {
867 status = errno_to_portable(errno);
868 error_f("seek \"%.100s\": %s", handle_to_name(handle),
869 strerror(errno));
870 } else {
871 /* XXX ATOMICIO ? */
872 ret = write(fd, data, len);
873 if (ret == -1) {
874 status = errno_to_portable(errno);
875 error_f("write \"%.100s\": %s",
876 handle_to_name(handle), strerror(errno));
877 } else if ((size_t)ret == len) {
878 status = SSH2_FX_OK;
879 handle_update_write(handle, ret);
880 } else {
881 debug2_f("nothing at all written");
882 status = SSH2_FX_FAILURE;
883 }
884 }
885 }
886 send_status(id, status);
887 free(data);
888 }
889
890 static void
process_do_stat(uint32_t id,int do_lstat)891 process_do_stat(uint32_t id, int do_lstat)
892 {
893 Attrib a;
894 struct stat st;
895 char *name;
896 int r, status = SSH2_FX_FAILURE;
897
898 if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0)
899 fatal_fr(r, "parse");
900
901 debug3("request %u: %sstat", id, do_lstat ? "l" : "");
902 verbose("%sstat name \"%s\"", do_lstat ? "l" : "", name);
903 r = do_lstat ? lstat(name, &st) : stat(name, &st);
904 if (r == -1) {
905 status = errno_to_portable(errno);
906 } else {
907 stat_to_attrib(&st, &a);
908 send_attrib(id, &a);
909 status = SSH2_FX_OK;
910 }
911 if (status != SSH2_FX_OK)
912 send_status(id, status);
913 free(name);
914 }
915
916 static void
process_stat(uint32_t id)917 process_stat(uint32_t id)
918 {
919 process_do_stat(id, 0);
920 }
921
922 static void
process_lstat(uint32_t id)923 process_lstat(uint32_t id)
924 {
925 process_do_stat(id, 1);
926 }
927
928 static void
process_fstat(uint32_t id)929 process_fstat(uint32_t id)
930 {
931 Attrib a;
932 struct stat st;
933 int fd, r, handle, status = SSH2_FX_FAILURE;
934
935 if ((r = get_handle(iqueue, &handle)) != 0)
936 fatal_fr(r, "parse");
937 debug("request %u: fstat \"%s\" (handle %u)",
938 id, handle_to_name(handle), handle);
939 fd = handle_to_fd(handle);
940 if (fd >= 0) {
941 r = fstat(fd, &st);
942 if (r == -1) {
943 status = errno_to_portable(errno);
944 } else {
945 stat_to_attrib(&st, &a);
946 send_attrib(id, &a);
947 status = SSH2_FX_OK;
948 }
949 }
950 if (status != SSH2_FX_OK)
951 send_status(id, status);
952 }
953
954 static struct timeval *
attrib_to_tv(const Attrib * a)955 attrib_to_tv(const Attrib *a)
956 {
957 static struct timeval tv[2];
958
959 tv[0].tv_sec = a->atime;
960 tv[0].tv_usec = 0;
961 tv[1].tv_sec = a->mtime;
962 tv[1].tv_usec = 0;
963 return tv;
964 }
965
966 static struct timespec *
attrib_to_ts(const Attrib * a)967 attrib_to_ts(const Attrib *a)
968 {
969 static struct timespec ts[2];
970
971 ts[0].tv_sec = a->atime;
972 ts[0].tv_nsec = 0;
973 ts[1].tv_sec = a->mtime;
974 ts[1].tv_nsec = 0;
975 return ts;
976 }
977
978 static void
process_setstat(uint32_t id)979 process_setstat(uint32_t id)
980 {
981 Attrib a;
982 char *name;
983 int r, status = SSH2_FX_OK;
984
985 if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0 ||
986 (r = decode_attrib(iqueue, &a)) != 0)
987 fatal_fr(r, "parse");
988
989 debug("request %u: setstat name \"%s\"", id, name);
990 if (a.flags & SSH2_FILEXFER_ATTR_SIZE) {
991 logit("set \"%s\" size %llu",
992 name, (unsigned long long)a.size);
993 r = truncate(name, a.size);
994 if (r == -1)
995 status = errno_to_portable(errno);
996 }
997 if (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) {
998 logit("set \"%s\" mode %04o", name, a.perm);
999 r = chmod(name, a.perm & 07777);
1000 if (r == -1)
1001 status = errno_to_portable(errno);
1002 }
1003 if (a.flags & SSH2_FILEXFER_ATTR_ACMODTIME) {
1004 char buf[64];
1005 time_t t = a.mtime;
1006
1007 strftime(buf, sizeof(buf), "%Y%m%d-%H:%M:%S",
1008 localtime(&t));
1009 logit("set \"%s\" modtime %s", name, buf);
1010 r = utimes(name, attrib_to_tv(&a));
1011 if (r == -1)
1012 status = errno_to_portable(errno);
1013 }
1014 if (a.flags & SSH2_FILEXFER_ATTR_UIDGID) {
1015 logit("set \"%s\" owner %lu group %lu", name,
1016 (u_long)a.uid, (u_long)a.gid);
1017 r = chown(name, a.uid, a.gid);
1018 if (r == -1)
1019 status = errno_to_portable(errno);
1020 }
1021 send_status(id, status);
1022 free(name);
1023 }
1024
1025 static void
process_fsetstat(uint32_t id)1026 process_fsetstat(uint32_t id)
1027 {
1028 Attrib a;
1029 int handle, fd, r;
1030 int status = SSH2_FX_OK;
1031
1032 if ((r = get_handle(iqueue, &handle)) != 0 ||
1033 (r = decode_attrib(iqueue, &a)) != 0)
1034 fatal_fr(r, "parse");
1035
1036 debug("request %u: fsetstat handle %d", id, handle);
1037 fd = handle_to_fd(handle);
1038 if (fd < 0)
1039 status = SSH2_FX_FAILURE;
1040 else {
1041 char *name = handle_to_name(handle);
1042
1043 if (a.flags & SSH2_FILEXFER_ATTR_SIZE) {
1044 logit("set \"%s\" size %llu",
1045 name, (unsigned long long)a.size);
1046 r = ftruncate(fd, a.size);
1047 if (r == -1)
1048 status = errno_to_portable(errno);
1049 }
1050 if (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) {
1051 logit("set \"%s\" mode %04o", name, a.perm);
1052 #ifdef HAVE_FCHMOD
1053 r = fchmod(fd, a.perm & 07777);
1054 #else
1055 r = chmod(name, a.perm & 07777);
1056 #endif
1057 if (r == -1)
1058 status = errno_to_portable(errno);
1059 }
1060 if (a.flags & SSH2_FILEXFER_ATTR_ACMODTIME) {
1061 char buf[64];
1062 time_t t = a.mtime;
1063
1064 strftime(buf, sizeof(buf), "%Y%m%d-%H:%M:%S",
1065 localtime(&t));
1066 logit("set \"%s\" modtime %s", name, buf);
1067 #ifdef HAVE_FUTIMES
1068 r = futimes(fd, attrib_to_tv(&a));
1069 #else
1070 r = utimes(name, attrib_to_tv(&a));
1071 #endif
1072 if (r == -1)
1073 status = errno_to_portable(errno);
1074 }
1075 if (a.flags & SSH2_FILEXFER_ATTR_UIDGID) {
1076 logit("set \"%s\" owner %lu group %lu", name,
1077 (u_long)a.uid, (u_long)a.gid);
1078 #ifdef HAVE_FCHOWN
1079 r = fchown(fd, a.uid, a.gid);
1080 #else
1081 r = chown(name, a.uid, a.gid);
1082 #endif
1083 if (r == -1)
1084 status = errno_to_portable(errno);
1085 }
1086 }
1087 send_status(id, status);
1088 }
1089
1090 static void
process_opendir(uint32_t id)1091 process_opendir(uint32_t id)
1092 {
1093 DIR *dirp = NULL;
1094 char *path;
1095 int r, handle, status = SSH2_FX_FAILURE;
1096
1097 if ((r = sshbuf_get_cstring(iqueue, &path, NULL)) != 0)
1098 fatal_fr(r, "parse");
1099
1100 debug3("request %u: opendir", id);
1101 logit("opendir \"%s\"", path);
1102 dirp = opendir(path);
1103 if (dirp == NULL) {
1104 status = errno_to_portable(errno);
1105 } else {
1106 handle = handle_new(HANDLE_DIR, path, 0, 0, dirp);
1107 if (handle < 0) {
1108 closedir(dirp);
1109 } else {
1110 send_handle(id, handle);
1111 status = SSH2_FX_OK;
1112 }
1113
1114 }
1115 if (status != SSH2_FX_OK)
1116 send_status(id, status);
1117 free(path);
1118 }
1119
1120 static void
process_readdir(uint32_t id)1121 process_readdir(uint32_t id)
1122 {
1123 DIR *dirp;
1124 struct dirent *dp;
1125 char *path;
1126 int r, handle;
1127
1128 if ((r = get_handle(iqueue, &handle)) != 0)
1129 fatal_fr(r, "parse");
1130
1131 debug("request %u: readdir \"%s\" (handle %d)", id,
1132 handle_to_name(handle), handle);
1133 dirp = handle_to_dir(handle);
1134 path = handle_to_name(handle);
1135 if (dirp == NULL || path == NULL) {
1136 send_status(id, SSH2_FX_FAILURE);
1137 } else {
1138 struct stat st;
1139 char pathname[PATH_MAX];
1140 Stat *stats;
1141 int nstats = 10, count = 0, i;
1142
1143 stats = xcalloc(nstats, sizeof(Stat));
1144 while ((dp = readdir(dirp)) != NULL) {
1145 if (count >= nstats) {
1146 nstats *= 2;
1147 stats = xreallocarray(stats, nstats, sizeof(Stat));
1148 }
1149 /* XXX OVERFLOW ? */
1150 snprintf(pathname, sizeof pathname, "%s%s%s", path,
1151 strcmp(path, "/") ? "/" : "", dp->d_name);
1152 if (lstat(pathname, &st) == -1)
1153 continue;
1154 stat_to_attrib(&st, &(stats[count].attrib));
1155 stats[count].name = xstrdup(dp->d_name);
1156 stats[count].long_name = ls_file(dp->d_name, &st,
1157 0, 0, NULL, NULL);
1158 count++;
1159 /* send up to 100 entries in one message */
1160 /* XXX check packet size instead */
1161 if (count == 100)
1162 break;
1163 }
1164 if (count > 0) {
1165 send_names(id, count, stats);
1166 for (i = 0; i < count; i++) {
1167 free(stats[i].name);
1168 free(stats[i].long_name);
1169 }
1170 } else {
1171 send_status(id, SSH2_FX_EOF);
1172 }
1173 free(stats);
1174 }
1175 }
1176
1177 static void
process_remove(uint32_t id)1178 process_remove(uint32_t id)
1179 {
1180 char *name;
1181 int r, status = SSH2_FX_FAILURE;
1182
1183 if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0)
1184 fatal_fr(r, "parse");
1185
1186 debug3("request %u: remove", id);
1187 logit("remove name \"%s\"", name);
1188 r = unlink(name);
1189 status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1190 send_status(id, status);
1191 free(name);
1192 }
1193
1194 static void
process_mkdir(uint32_t id)1195 process_mkdir(uint32_t id)
1196 {
1197 Attrib a;
1198 char *name;
1199 int r, mode, status = SSH2_FX_FAILURE;
1200
1201 if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0 ||
1202 (r = decode_attrib(iqueue, &a)) != 0)
1203 fatal_fr(r, "parse");
1204
1205 mode = (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) ?
1206 a.perm & 07777 : 0777;
1207 debug3("request %u: mkdir", id);
1208 logit("mkdir name \"%s\" mode 0%o", name, mode);
1209 r = mkdir(name, mode);
1210 status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1211 send_status(id, status);
1212 free(name);
1213 }
1214
1215 static void
process_rmdir(uint32_t id)1216 process_rmdir(uint32_t id)
1217 {
1218 char *name;
1219 int r, status;
1220
1221 if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0)
1222 fatal_fr(r, "parse");
1223
1224 debug3("request %u: rmdir", id);
1225 logit("rmdir name \"%s\"", name);
1226 r = rmdir(name);
1227 status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1228 send_status(id, status);
1229 free(name);
1230 }
1231
1232 static void
process_realpath(uint32_t id)1233 process_realpath(uint32_t id)
1234 {
1235 char resolvedname[PATH_MAX];
1236 char *path;
1237 int r;
1238
1239 if ((r = sshbuf_get_cstring(iqueue, &path, NULL)) != 0)
1240 fatal_fr(r, "parse");
1241
1242 if (path[0] == '\0') {
1243 free(path);
1244 path = xstrdup(".");
1245 }
1246 debug3("request %u: realpath", id);
1247 verbose("realpath \"%s\"", path);
1248 if (sftp_realpath(path, resolvedname) == NULL) {
1249 send_status(id, errno_to_portable(errno));
1250 } else {
1251 Stat s;
1252 attrib_clear(&s.attrib);
1253 s.name = s.long_name = resolvedname;
1254 send_names(id, 1, &s);
1255 }
1256 free(path);
1257 }
1258
1259 static void
process_rename(uint32_t id)1260 process_rename(uint32_t id)
1261 {
1262 char *oldpath, *newpath;
1263 int r, status;
1264 struct stat sb;
1265
1266 if ((r = sshbuf_get_cstring(iqueue, &oldpath, NULL)) != 0 ||
1267 (r = sshbuf_get_cstring(iqueue, &newpath, NULL)) != 0)
1268 fatal_fr(r, "parse");
1269
1270 debug3("request %u: rename", id);
1271 logit("rename old \"%s\" new \"%s\"", oldpath, newpath);
1272 status = SSH2_FX_FAILURE;
1273 if (lstat(oldpath, &sb) == -1)
1274 status = errno_to_portable(errno);
1275 else if (S_ISREG(sb.st_mode)) {
1276 /* Race-free rename of regular files */
1277 if (link(oldpath, newpath) == -1) {
1278 if (errno == EOPNOTSUPP || errno == ENOSYS
1279 #ifdef EXDEV
1280 || errno == EXDEV
1281 #endif
1282 #ifdef LINK_OPNOTSUPP_ERRNO
1283 || errno == LINK_OPNOTSUPP_ERRNO
1284 #endif
1285 ) {
1286 struct stat st;
1287
1288 /*
1289 * fs doesn't support links, so fall back to
1290 * stat+rename. This is racy.
1291 */
1292 if (stat(newpath, &st) == -1) {
1293 if (rename(oldpath, newpath) == -1)
1294 status =
1295 errno_to_portable(errno);
1296 else
1297 status = SSH2_FX_OK;
1298 }
1299 } else {
1300 status = errno_to_portable(errno);
1301 }
1302 } else if (unlink(oldpath) == -1) {
1303 status = errno_to_portable(errno);
1304 /* clean spare link */
1305 unlink(newpath);
1306 } else
1307 status = SSH2_FX_OK;
1308 } else if (stat(newpath, &sb) == -1) {
1309 if (rename(oldpath, newpath) == -1)
1310 status = errno_to_portable(errno);
1311 else
1312 status = SSH2_FX_OK;
1313 }
1314 send_status(id, status);
1315 free(oldpath);
1316 free(newpath);
1317 }
1318
1319 static void
process_readlink(uint32_t id)1320 process_readlink(uint32_t id)
1321 {
1322 int r, len;
1323 char buf[PATH_MAX];
1324 char *path;
1325
1326 if ((r = sshbuf_get_cstring(iqueue, &path, NULL)) != 0)
1327 fatal_fr(r, "parse");
1328
1329 debug3("request %u: readlink", id);
1330 verbose("readlink \"%s\"", path);
1331 if ((len = readlink(path, buf, sizeof(buf) - 1)) == -1)
1332 send_status(id, errno_to_portable(errno));
1333 else {
1334 Stat s;
1335
1336 buf[len] = '\0';
1337 attrib_clear(&s.attrib);
1338 s.name = s.long_name = buf;
1339 send_names(id, 1, &s);
1340 }
1341 free(path);
1342 }
1343
1344 static void
process_symlink(uint32_t id)1345 process_symlink(uint32_t id)
1346 {
1347 char *oldpath, *newpath;
1348 int r, status;
1349
1350 if ((r = sshbuf_get_cstring(iqueue, &oldpath, NULL)) != 0 ||
1351 (r = sshbuf_get_cstring(iqueue, &newpath, NULL)) != 0)
1352 fatal_fr(r, "parse");
1353
1354 debug3("request %u: symlink", id);
1355 logit("symlink old \"%s\" new \"%s\"", oldpath, newpath);
1356 /* this will fail if 'newpath' exists */
1357 r = symlink(oldpath, newpath);
1358 status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1359 send_status(id, status);
1360 free(oldpath);
1361 free(newpath);
1362 }
1363
1364 static void
process_extended_posix_rename(uint32_t id)1365 process_extended_posix_rename(uint32_t id)
1366 {
1367 char *oldpath, *newpath;
1368 int r, status;
1369
1370 if ((r = sshbuf_get_cstring(iqueue, &oldpath, NULL)) != 0 ||
1371 (r = sshbuf_get_cstring(iqueue, &newpath, NULL)) != 0)
1372 fatal_fr(r, "parse");
1373
1374 debug3("request %u: posix-rename", id);
1375 logit("posix-rename old \"%s\" new \"%s\"", oldpath, newpath);
1376 r = rename(oldpath, newpath);
1377 status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1378 send_status(id, status);
1379 free(oldpath);
1380 free(newpath);
1381 }
1382
1383 static void
process_extended_statvfs(uint32_t id)1384 process_extended_statvfs(uint32_t id)
1385 {
1386 char *path;
1387 struct statvfs st;
1388 int r;
1389
1390 if ((r = sshbuf_get_cstring(iqueue, &path, NULL)) != 0)
1391 fatal_fr(r, "parse");
1392 debug3("request %u: statvfs", id);
1393 logit("statvfs \"%s\"", path);
1394
1395 if (statvfs(path, &st) != 0)
1396 send_status(id, errno_to_portable(errno));
1397 else
1398 send_statvfs(id, &st);
1399 free(path);
1400 }
1401
1402 static void
process_extended_fstatvfs(uint32_t id)1403 process_extended_fstatvfs(uint32_t id)
1404 {
1405 int r, handle, fd;
1406 struct statvfs st;
1407
1408 if ((r = get_handle(iqueue, &handle)) != 0)
1409 fatal_fr(r, "parse");
1410 debug("request %u: fstatvfs \"%s\" (handle %u)",
1411 id, handle_to_name(handle), handle);
1412 if ((fd = handle_to_fd(handle)) < 0) {
1413 send_status(id, SSH2_FX_FAILURE);
1414 return;
1415 }
1416 if (fstatvfs(fd, &st) != 0)
1417 send_status(id, errno_to_portable(errno));
1418 else
1419 send_statvfs(id, &st);
1420 }
1421
1422 static void
process_extended_hardlink(uint32_t id)1423 process_extended_hardlink(uint32_t id)
1424 {
1425 char *oldpath, *newpath;
1426 int r, status;
1427
1428 if ((r = sshbuf_get_cstring(iqueue, &oldpath, NULL)) != 0 ||
1429 (r = sshbuf_get_cstring(iqueue, &newpath, NULL)) != 0)
1430 fatal_fr(r, "parse");
1431
1432 debug3("request %u: hardlink", id);
1433 logit("hardlink old \"%s\" new \"%s\"", oldpath, newpath);
1434 r = link(oldpath, newpath);
1435 status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1436 send_status(id, status);
1437 free(oldpath);
1438 free(newpath);
1439 }
1440
1441 static void
process_extended_fsync(uint32_t id)1442 process_extended_fsync(uint32_t id)
1443 {
1444 int handle, fd, r, status = SSH2_FX_OP_UNSUPPORTED;
1445
1446 if ((r = get_handle(iqueue, &handle)) != 0)
1447 fatal_fr(r, "parse");
1448 debug3("request %u: fsync (handle %u)", id, handle);
1449 verbose("fsync \"%s\"", handle_to_name(handle));
1450 if ((fd = handle_to_fd(handle)) < 0)
1451 status = SSH2_FX_NO_SUCH_FILE;
1452 else if (handle_is_ok(handle, HANDLE_FILE)) {
1453 r = fsync(fd);
1454 status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1455 }
1456 send_status(id, status);
1457 }
1458
1459 static void
process_extended_lsetstat(uint32_t id)1460 process_extended_lsetstat(uint32_t id)
1461 {
1462 Attrib a;
1463 char *name;
1464 int r, status = SSH2_FX_OK;
1465
1466 if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0 ||
1467 (r = decode_attrib(iqueue, &a)) != 0)
1468 fatal_fr(r, "parse");
1469
1470 debug("request %u: lsetstat name \"%s\"", id, name);
1471 if (a.flags & SSH2_FILEXFER_ATTR_SIZE) {
1472 /* nonsensical for links */
1473 status = SSH2_FX_BAD_MESSAGE;
1474 goto out;
1475 }
1476 if (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) {
1477 logit("set \"%s\" mode %04o", name, a.perm);
1478 r = fchmodat(AT_FDCWD, name,
1479 a.perm & 07777, AT_SYMLINK_NOFOLLOW);
1480 if (r == -1)
1481 status = errno_to_portable(errno);
1482 }
1483 if (a.flags & SSH2_FILEXFER_ATTR_ACMODTIME) {
1484 char buf[64];
1485 time_t t = a.mtime;
1486
1487 strftime(buf, sizeof(buf), "%Y%m%d-%H:%M:%S",
1488 localtime(&t));
1489 logit("set \"%s\" modtime %s", name, buf);
1490 r = utimensat(AT_FDCWD, name,
1491 attrib_to_ts(&a), AT_SYMLINK_NOFOLLOW);
1492 if (r == -1)
1493 status = errno_to_portable(errno);
1494 }
1495 if (a.flags & SSH2_FILEXFER_ATTR_UIDGID) {
1496 logit("set \"%s\" owner %lu group %lu", name,
1497 (u_long)a.uid, (u_long)a.gid);
1498 r = fchownat(AT_FDCWD, name, a.uid, a.gid,
1499 AT_SYMLINK_NOFOLLOW);
1500 if (r == -1)
1501 status = errno_to_portable(errno);
1502 }
1503 out:
1504 send_status(id, status);
1505 free(name);
1506 }
1507
1508 static void
process_extended_limits(uint32_t id)1509 process_extended_limits(uint32_t id)
1510 {
1511 struct sshbuf *msg;
1512 int r;
1513 uint64_t nfiles = 0;
1514 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE)
1515 struct rlimit rlim;
1516 #endif
1517
1518 debug("request %u: limits", id);
1519
1520 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE)
1521 if (getrlimit(RLIMIT_NOFILE, &rlim) != -1 && rlim.rlim_cur > 5)
1522 nfiles = rlim.rlim_cur - 5; /* stdio(3) + syslog + spare */
1523 #endif
1524
1525 if ((msg = sshbuf_new()) == NULL)
1526 fatal_f("sshbuf_new failed");
1527 if ((r = sshbuf_put_u8(msg, SSH2_FXP_EXTENDED_REPLY)) != 0 ||
1528 (r = sshbuf_put_u32(msg, id)) != 0 ||
1529 /* max-packet-length */
1530 (r = sshbuf_put_u64(msg, SFTP_MAX_MSG_LENGTH)) != 0 ||
1531 /* max-read-length */
1532 (r = sshbuf_put_u64(msg, SFTP_MAX_READ_LENGTH)) != 0 ||
1533 /* max-write-length */
1534 (r = sshbuf_put_u64(msg, SFTP_MAX_MSG_LENGTH - 1024)) != 0 ||
1535 /* max-open-handles */
1536 (r = sshbuf_put_u64(msg, nfiles)) != 0)
1537 fatal_fr(r, "compose");
1538 send_msg(msg);
1539 sshbuf_free(msg);
1540 }
1541
1542 static void
process_extended_expand(uint32_t id)1543 process_extended_expand(uint32_t id)
1544 {
1545 char cwd[PATH_MAX], resolvedname[PATH_MAX];
1546 char *path, *npath;
1547 int r;
1548 Stat s;
1549
1550 if ((r = sshbuf_get_cstring(iqueue, &path, NULL)) != 0)
1551 fatal_fr(r, "parse");
1552 if (getcwd(cwd, sizeof(cwd)) == NULL) {
1553 send_status(id, errno_to_portable(errno));
1554 goto out;
1555 }
1556
1557 debug3("request %u: expand, original \"%s\"", id, path);
1558 if (path[0] == '\0') {
1559 /* empty path */
1560 free(path);
1561 path = xstrdup(".");
1562 } else if (*path == '~') {
1563 /* ~ expand path */
1564 /* Special-case for "~" and "~/" to respect homedir flag */
1565 if (strcmp(path, "~") == 0) {
1566 free(path);
1567 path = xstrdup(cwd);
1568 } else if (strncmp(path, "~/", 2) == 0) {
1569 npath = xstrdup(path + 2);
1570 free(path);
1571 xasprintf(&path, "%s/%s", cwd, npath);
1572 free(npath);
1573 } else {
1574 /* ~user expansions */
1575 if (tilde_expand(path, pw->pw_uid, &npath) != 0) {
1576 send_status_errmsg(id,
1577 errno_to_portable(ENOENT), "no such user");
1578 goto out;
1579 }
1580 free(path);
1581 path = npath;
1582 }
1583 } else if (*path != '/') {
1584 /* relative path */
1585 xasprintf(&npath, "%s/%s", cwd, path);
1586 free(path);
1587 path = npath;
1588 }
1589 verbose("expand \"%s\"", path);
1590 if (sftp_realpath(path, resolvedname) == NULL) {
1591 send_status(id, errno_to_portable(errno));
1592 goto out;
1593 }
1594 attrib_clear(&s.attrib);
1595 s.name = s.long_name = resolvedname;
1596 send_names(id, 1, &s);
1597 out:
1598 free(path);
1599 }
1600
1601 static void
process_extended_copy_data(uint32_t id)1602 process_extended_copy_data(uint32_t id)
1603 {
1604 u_char buf[64*1024];
1605 int read_handle, read_fd, write_handle, write_fd;
1606 uint64_t len, read_off, read_len, write_off;
1607 int r, copy_until_eof, status = SSH2_FX_OP_UNSUPPORTED;
1608 size_t ret;
1609
1610 if ((r = get_handle(iqueue, &read_handle)) != 0 ||
1611 (r = sshbuf_get_u64(iqueue, &read_off)) != 0 ||
1612 (r = sshbuf_get_u64(iqueue, &read_len)) != 0 ||
1613 (r = get_handle(iqueue, &write_handle)) != 0 ||
1614 (r = sshbuf_get_u64(iqueue, &write_off)) != 0)
1615 fatal_fr(r, "buffer error");
1616
1617 debug("request %u: copy-data from \"%s\" (handle %d) off %llu len %llu "
1618 "to \"%s\" (handle %d) off %llu",
1619 id, handle_to_name(read_handle), read_handle,
1620 (unsigned long long)read_off, (unsigned long long)read_len,
1621 handle_to_name(write_handle), write_handle,
1622 (unsigned long long)write_off);
1623
1624 /* For read length of 0, we read until EOF. */
1625 if (read_len == 0) {
1626 read_len = (uint64_t)-1 - read_off;
1627 copy_until_eof = 1;
1628 } else
1629 copy_until_eof = 0;
1630
1631 read_fd = handle_to_fd(read_handle);
1632 write_fd = handle_to_fd(write_handle);
1633
1634 /* Disallow reading & writing to the same handle or same path or dirs */
1635 if (read_handle == write_handle || read_fd < 0 || write_fd < 0 ||
1636 !strcmp(handle_to_name(read_handle), handle_to_name(write_handle))) {
1637 status = SSH2_FX_FAILURE;
1638 goto out;
1639 }
1640
1641 if (lseek(read_fd, read_off, SEEK_SET) < 0) {
1642 status = errno_to_portable(errno);
1643 error_f("read_seek failed");
1644 goto out;
1645 }
1646
1647 if ((handle_to_flags(write_handle) & O_APPEND) == 0 &&
1648 lseek(write_fd, write_off, SEEK_SET) < 0) {
1649 status = errno_to_portable(errno);
1650 error_f("write_seek failed");
1651 goto out;
1652 }
1653
1654 /* Process the request in chunks. */
1655 while (read_len > 0 || copy_until_eof) {
1656 len = MINIMUM(sizeof(buf), read_len);
1657 read_len -= len;
1658
1659 ret = atomicio(read, read_fd, buf, len);
1660 if (ret == 0 && errno == EPIPE) {
1661 status = copy_until_eof ? SSH2_FX_OK : SSH2_FX_EOF;
1662 break;
1663 } else if (ret == 0) {
1664 status = errno_to_portable(errno);
1665 error_f("read failed: %s", strerror(errno));
1666 break;
1667 }
1668 len = ret;
1669 handle_update_read(read_handle, len);
1670
1671 ret = atomicio(vwrite, write_fd, buf, len);
1672 if (ret != len) {
1673 status = errno_to_portable(errno);
1674 error("%s: write failed: %llu != %llu: %s", __func__,
1675 (unsigned long long)ret, (unsigned long long)len,
1676 strerror(errno));
1677 break;
1678 }
1679 handle_update_write(write_handle, len);
1680 }
1681
1682 if (read_len == 0)
1683 status = SSH2_FX_OK;
1684
1685 out:
1686 send_status(id, status);
1687 }
1688
1689 static void
process_extended_home_directory(uint32_t id)1690 process_extended_home_directory(uint32_t id)
1691 {
1692 char *username;
1693 struct passwd *user_pw;
1694 int r;
1695 Stat s;
1696
1697 if ((r = sshbuf_get_cstring(iqueue, &username, NULL)) != 0)
1698 fatal_fr(r, "parse");
1699
1700 debug3("request %u: home-directory \"%s\"", id, username);
1701 if (username[0] == '\0') {
1702 user_pw = pw;
1703 } else if ((user_pw = getpwnam(username)) == NULL) {
1704 send_status(id, SSH2_FX_FAILURE);
1705 goto out;
1706 }
1707
1708 verbose("home-directory \"%s\"", user_pw->pw_dir);
1709 attrib_clear(&s.attrib);
1710 s.name = s.long_name = user_pw->pw_dir;
1711 send_names(id, 1, &s);
1712 out:
1713 free(username);
1714 }
1715
1716 static void
process_extended_get_users_groups_by_id(uint32_t id)1717 process_extended_get_users_groups_by_id(uint32_t id)
1718 {
1719 struct passwd *user_pw;
1720 struct group *gr;
1721 struct sshbuf *uids, *gids, *usernames, *groupnames, *msg;
1722 int r;
1723 u_int n, nusers = 0, ngroups = 0;
1724 const char *name;
1725
1726 if ((usernames = sshbuf_new()) == NULL ||
1727 (groupnames = sshbuf_new()) == NULL ||
1728 (msg = sshbuf_new()) == NULL)
1729 fatal_f("sshbuf_new failed");
1730 if ((r = sshbuf_froms(iqueue, &uids)) != 0 ||
1731 (r = sshbuf_froms(iqueue, &gids)) != 0)
1732 fatal_fr(r, "parse");
1733 debug_f("uids len = %zu, gids len = %zu",
1734 sshbuf_len(uids), sshbuf_len(gids));
1735 while (sshbuf_len(uids) != 0) {
1736 if ((r = sshbuf_get_u32(uids, &n)) != 0)
1737 fatal_fr(r, "parse inner uid");
1738 user_pw = getpwuid((uid_t)n);
1739 name = user_pw == NULL ? "" : user_pw->pw_name;
1740 debug3_f("uid %u => \"%s\"", n, name);
1741 if ((r = sshbuf_put_cstring(usernames, name)) != 0)
1742 fatal_fr(r, "assemble uid reply");
1743 nusers++;
1744 }
1745 while (sshbuf_len(gids) != 0) {
1746 if ((r = sshbuf_get_u32(gids, &n)) != 0)
1747 fatal_fr(r, "parse inner gid");
1748 gr = getgrgid((gid_t)n);
1749 name = gr == NULL ? "" : gr->gr_name;
1750 debug3_f("gid %u => \"%s\"", n, name);
1751 if ((r = sshbuf_put_cstring(groupnames, name)) != 0)
1752 fatal_fr(r, "assemble gid reply");
1753 ngroups++;
1754 }
1755 verbose("users-groups-by-id: %u users, %u groups", nusers, ngroups);
1756
1757 if ((r = sshbuf_put_u8(msg, SSH2_FXP_EXTENDED_REPLY)) != 0 ||
1758 (r = sshbuf_put_u32(msg, id)) != 0 ||
1759 (r = sshbuf_put_stringb(msg, usernames)) != 0 ||
1760 (r = sshbuf_put_stringb(msg, groupnames)) != 0)
1761 fatal_fr(r, "compose");
1762 send_msg(msg);
1763
1764 sshbuf_free(uids);
1765 sshbuf_free(gids);
1766 sshbuf_free(usernames);
1767 sshbuf_free(groupnames);
1768 sshbuf_free(msg);
1769 }
1770
1771 static void
process_extended(uint32_t id)1772 process_extended(uint32_t id)
1773 {
1774 char *request;
1775 int r;
1776 const struct sftp_handler *exthand;
1777
1778 if ((r = sshbuf_get_cstring(iqueue, &request, NULL)) != 0)
1779 fatal_fr(r, "parse");
1780 if ((exthand = extended_handler_byname(request)) == NULL) {
1781 error("Unknown extended request \"%.100s\"", request);
1782 send_status(id, SSH2_FX_OP_UNSUPPORTED); /* MUST */
1783 } else {
1784 if (!request_permitted(exthand))
1785 send_status(id, SSH2_FX_PERMISSION_DENIED);
1786 else
1787 exthand->handler(id);
1788 }
1789 free(request);
1790 }
1791
1792 /* stolen from ssh-agent */
1793
1794 static void
process(void)1795 process(void)
1796 {
1797 u_int msg_len;
1798 u_int buf_len;
1799 u_int consumed;
1800 u_char type;
1801 const u_char *cp;
1802 int i, r;
1803 uint32_t id;
1804
1805 buf_len = sshbuf_len(iqueue);
1806 if (buf_len < 5)
1807 return; /* Incomplete message. */
1808 cp = sshbuf_ptr(iqueue);
1809 msg_len = get_u32(cp);
1810 if (msg_len > SFTP_MAX_MSG_LENGTH) {
1811 error("bad message from %s local user %s",
1812 client_addr, pw->pw_name);
1813 sftp_server_cleanup_exit(11);
1814 }
1815 if (buf_len < msg_len + 4)
1816 return;
1817 if ((r = sshbuf_consume(iqueue, 4)) != 0)
1818 fatal_fr(r, "consume");
1819 buf_len -= 4;
1820 if ((r = sshbuf_get_u8(iqueue, &type)) != 0)
1821 fatal_fr(r, "parse type");
1822
1823 switch (type) {
1824 case SSH2_FXP_INIT:
1825 process_init();
1826 init_done = 1;
1827 break;
1828 case SSH2_FXP_EXTENDED:
1829 if (!init_done)
1830 fatal("Received extended request before init");
1831 if ((r = sshbuf_get_u32(iqueue, &id)) != 0)
1832 fatal_fr(r, "parse extended ID");
1833 process_extended(id);
1834 break;
1835 default:
1836 if (!init_done)
1837 fatal("Received %u request before init", type);
1838 if ((r = sshbuf_get_u32(iqueue, &id)) != 0)
1839 fatal_fr(r, "parse ID");
1840 for (i = 0; handlers[i].handler != NULL; i++) {
1841 if (type == handlers[i].type) {
1842 if (!request_permitted(&handlers[i])) {
1843 send_status(id,
1844 SSH2_FX_PERMISSION_DENIED);
1845 } else {
1846 handlers[i].handler(id);
1847 }
1848 break;
1849 }
1850 }
1851 if (handlers[i].handler == NULL)
1852 error("Unknown message %u", type);
1853 }
1854 /* discard the remaining bytes from the current packet */
1855 if (buf_len < sshbuf_len(iqueue)) {
1856 error("iqueue grew unexpectedly");
1857 sftp_server_cleanup_exit(255);
1858 }
1859 consumed = buf_len - sshbuf_len(iqueue);
1860 if (msg_len < consumed) {
1861 error("msg_len %u < consumed %u", msg_len, consumed);
1862 sftp_server_cleanup_exit(255);
1863 }
1864 if (msg_len > consumed &&
1865 (r = sshbuf_consume(iqueue, msg_len - consumed)) != 0)
1866 fatal_fr(r, "consume");
1867 }
1868
1869 /* Cleanup handler that logs active handles upon normal exit */
1870 void
sftp_server_cleanup_exit(int i)1871 sftp_server_cleanup_exit(int i)
1872 {
1873 if (pw != NULL && client_addr != NULL) {
1874 handle_log_exit();
1875 logit("session closed for local user %s from [%s]",
1876 pw->pw_name, client_addr);
1877 }
1878 _exit(i);
1879 }
1880
1881 static void
sftp_server_usage(void)1882 sftp_server_usage(void)
1883 {
1884 extern char *__progname;
1885
1886 fprintf(stderr,
1887 "usage: %s [-ehR] [-d start_directory] [-f log_facility] "
1888 "[-l log_level]\n\t[-P denied_requests] "
1889 "[-p allowed_requests] [-u umask]\n"
1890 " %s -Q protocol_feature\n",
1891 __progname, __progname);
1892 exit(1);
1893 }
1894
1895 int
sftp_server_main(int argc,char ** argv,struct passwd * user_pw)1896 sftp_server_main(int argc, char **argv, struct passwd *user_pw)
1897 {
1898 int i, r, in, out, ch, skipargs = 0, log_stderr = 0;
1899 ssize_t len, olen;
1900 SyslogFacility log_facility = SYSLOG_FACILITY_AUTH;
1901 char *cp, *homedir = NULL, uidstr[32], buf[4*4096];
1902 long mask;
1903
1904 extern char *optarg;
1905 extern char *__progname;
1906
1907 __progname = ssh_get_progname(argv[0]);
1908 log_init(__progname, log_level, log_facility, log_stderr);
1909
1910 pw = pwcopy(user_pw);
1911
1912 while (!skipargs && (ch = getopt(argc, argv,
1913 "d:f:l:P:p:Q:u:cehR")) != -1) {
1914 switch (ch) {
1915 case 'Q':
1916 if (strcasecmp(optarg, "requests") != 0) {
1917 fprintf(stderr, "Invalid query type\n");
1918 exit(1);
1919 }
1920 for (i = 0; handlers[i].handler != NULL; i++)
1921 printf("%s\n", handlers[i].name);
1922 for (i = 0; extended_handlers[i].handler != NULL; i++)
1923 printf("%s\n", extended_handlers[i].name);
1924 exit(0);
1925 break;
1926 case 'R':
1927 readonly = 1;
1928 break;
1929 case 'c':
1930 /*
1931 * Ignore all arguments if we are invoked as a
1932 * shell using "sftp-server -c command"
1933 */
1934 skipargs = 1;
1935 break;
1936 case 'e':
1937 log_stderr = 1;
1938 break;
1939 case 'l':
1940 log_level = log_level_number(optarg);
1941 if (log_level == SYSLOG_LEVEL_NOT_SET)
1942 error("Invalid log level \"%s\"", optarg);
1943 break;
1944 case 'f':
1945 log_facility = log_facility_number(optarg);
1946 if (log_facility == SYSLOG_FACILITY_NOT_SET)
1947 error("Invalid log facility \"%s\"", optarg);
1948 break;
1949 case 'd':
1950 cp = tilde_expand_filename(optarg, user_pw->pw_uid);
1951 snprintf(uidstr, sizeof(uidstr), "%llu",
1952 (unsigned long long)pw->pw_uid);
1953 homedir = percent_expand(cp, "d", user_pw->pw_dir,
1954 "u", user_pw->pw_name, "U", uidstr, (char *)NULL);
1955 free(cp);
1956 break;
1957 case 'p':
1958 if (request_allowlist != NULL)
1959 fatal("Permitted requests already set");
1960 request_allowlist = xstrdup(optarg);
1961 break;
1962 case 'P':
1963 if (request_denylist != NULL)
1964 fatal("Refused requests already set");
1965 request_denylist = xstrdup(optarg);
1966 break;
1967 case 'u':
1968 errno = 0;
1969 mask = strtol(optarg, &cp, 8);
1970 if (mask < 0 || mask > 0777 || *cp != '\0' ||
1971 cp == optarg || (mask == 0 && errno != 0))
1972 fatal("Invalid umask \"%s\"", optarg);
1973 (void)umask((mode_t)mask);
1974 break;
1975 case 'h':
1976 default:
1977 sftp_server_usage();
1978 }
1979 }
1980
1981 log_init(__progname, log_level, log_facility, log_stderr);
1982
1983 /*
1984 * On platforms where we can, avoid making /proc/self/{mem,maps}
1985 * available to the user so that sftp access doesn't automatically
1986 * imply arbitrary code execution access that will break
1987 * restricted configurations.
1988 */
1989 platform_disable_tracing(1); /* strict */
1990
1991 /* Drop any fine-grained privileges we don't need */
1992 platform_pledge_sftp_server();
1993
1994 if ((cp = getenv("SSH_CONNECTION")) != NULL) {
1995 client_addr = xstrdup(cp);
1996 if ((cp = strchr(client_addr, ' ')) == NULL) {
1997 error("Malformed SSH_CONNECTION variable: \"%s\"",
1998 getenv("SSH_CONNECTION"));
1999 sftp_server_cleanup_exit(255);
2000 }
2001 *cp = '\0';
2002 } else
2003 client_addr = xstrdup("UNKNOWN");
2004
2005 logit("session opened for local user %s from [%s]",
2006 pw->pw_name, client_addr);
2007
2008 in = STDIN_FILENO;
2009 out = STDOUT_FILENO;
2010
2011 #ifdef HAVE_CYGWIN
2012 setmode(in, O_BINARY);
2013 setmode(out, O_BINARY);
2014 #endif
2015
2016 if ((iqueue = sshbuf_new()) == NULL)
2017 fatal_f("sshbuf_new failed");
2018 if ((oqueue = sshbuf_new()) == NULL)
2019 fatal_f("sshbuf_new failed");
2020
2021 if (homedir != NULL) {
2022 if (chdir(homedir) != 0) {
2023 error("chdir to \"%s\" failed: %s", homedir,
2024 strerror(errno));
2025 }
2026 }
2027
2028 for (;;) {
2029 struct pollfd pfd[2];
2030
2031 memset(pfd, 0, sizeof pfd);
2032 pfd[0].fd = pfd[1].fd = -1;
2033
2034 /*
2035 * Ensure that we can read a full buffer and handle
2036 * the worst-case length packet it can generate,
2037 * otherwise apply backpressure by stopping reads.
2038 */
2039 if ((r = sshbuf_check_reserve(iqueue, sizeof(buf))) == 0 &&
2040 (r = sshbuf_check_reserve(oqueue,
2041 SFTP_MAX_MSG_LENGTH)) == 0) {
2042 pfd[0].fd = in;
2043 pfd[0].events = POLLIN;
2044 }
2045 else if (r != SSH_ERR_NO_BUFFER_SPACE)
2046 fatal_fr(r, "reserve");
2047
2048 olen = sshbuf_len(oqueue);
2049 if (olen > 0) {
2050 pfd[1].fd = out;
2051 pfd[1].events = POLLOUT;
2052 }
2053
2054 if (poll(pfd, 2, -1) == -1) {
2055 if (errno == EINTR)
2056 continue;
2057 error("poll: %s", strerror(errno));
2058 sftp_server_cleanup_exit(2);
2059 }
2060
2061 /* copy stdin to iqueue */
2062 if (pfd[0].revents & (POLLIN|POLLHUP)) {
2063 len = read(in, buf, sizeof buf);
2064 if (len == 0) {
2065 debug("read eof");
2066 sftp_server_cleanup_exit(0);
2067 } else if (len == -1) {
2068 if (errno != EAGAIN && errno != EINTR) {
2069 error("read: %s", strerror(errno));
2070 sftp_server_cleanup_exit(1);
2071 }
2072 } else if ((r = sshbuf_put(iqueue, buf, len)) != 0)
2073 fatal_fr(r, "sshbuf_put");
2074 }
2075 /* send oqueue to stdout */
2076 if (pfd[1].revents & (POLLOUT|POLLHUP)) {
2077 len = write(out, sshbuf_ptr(oqueue), olen);
2078 if (len == 0 || (len == -1 && errno == EPIPE)) {
2079 debug("write eof");
2080 sftp_server_cleanup_exit(0);
2081 } else if (len == -1) {
2082 sftp_server_cleanup_exit(1);
2083 if (errno != EAGAIN && errno != EINTR) {
2084 error("write: %s", strerror(errno));
2085 sftp_server_cleanup_exit(1);
2086 }
2087 } else if ((r = sshbuf_consume(oqueue, len)) != 0)
2088 fatal_fr(r, "consume");
2089 }
2090
2091 /*
2092 * Process requests from client if we can fit the results
2093 * into the output buffer, otherwise stop processing input
2094 * and let the output queue drain.
2095 */
2096 r = sshbuf_check_reserve(oqueue, SFTP_MAX_MSG_LENGTH);
2097 if (r == 0)
2098 process();
2099 else if (r != SSH_ERR_NO_BUFFER_SPACE)
2100 fatal_fr(r, "reserve");
2101 }
2102 }
2103