1 /* $OpenBSD: sftp-server.c,v 1.103 2014/01/17 06:23:24 dtucker Exp $ */
3 * Copyright (c) 2000-2004 Markus Friedl. All rights reserved.
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.
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.
20 #include <sys/types.h>
21 #include <sys/param.h>
23 #ifdef HAVE_SYS_TIME_H
24 # include <sys/time.h>
26 #ifdef HAVE_SYS_MOUNT_H
27 #include <sys/mount.h>
29 #ifdef HAVE_SYS_STATVFS_H
30 #include <sys/statvfs.h>
53 #include "sftp-common.h"
56 #define get_int64() buffer_get_int64(&iqueue);
57 #define get_int() buffer_get_int(&iqueue);
58 #define get_string(lenp) buffer_get_string(&iqueue, lenp);
61 static LogLevel log_level = SYSLOG_LEVEL_ERROR;
64 static struct passwd *pw = NULL;
65 static char *client_addr = NULL;
67 /* input and output queue */
71 /* Version of client */
74 /* SSH2_FXP_INIT received */
80 /* Requests that are allowed/denied */
81 static char *request_whitelist, *request_blacklist;
83 /* portable attributes, etc. */
84 typedef struct Stat Stat;
93 static void process_open(u_int32_t id);
94 static void process_close(u_int32_t id);
95 static void process_read(u_int32_t id);
96 static void process_write(u_int32_t id);
97 static void process_stat(u_int32_t id);
98 static void process_lstat(u_int32_t id);
99 static void process_fstat(u_int32_t id);
100 static void process_setstat(u_int32_t id);
101 static void process_fsetstat(u_int32_t id);
102 static void process_opendir(u_int32_t id);
103 static void process_readdir(u_int32_t id);
104 static void process_remove(u_int32_t id);
105 static void process_mkdir(u_int32_t id);
106 static void process_rmdir(u_int32_t id);
107 static void process_realpath(u_int32_t id);
108 static void process_rename(u_int32_t id);
109 static void process_readlink(u_int32_t id);
110 static void process_symlink(u_int32_t id);
111 static void process_extended_posix_rename(u_int32_t id);
112 static void process_extended_statvfs(u_int32_t id);
113 static void process_extended_fstatvfs(u_int32_t id);
114 static void process_extended_hardlink(u_int32_t id);
115 static void process_extended_fsync(u_int32_t id);
116 static void process_extended(u_int32_t id);
118 struct sftp_handler {
119 const char *name; /* user-visible name for fine-grained perms */
120 const char *ext_name; /* extended request name */
121 u_int type; /* packet type, for non extended packets */
122 void (*handler)(u_int32_t);
123 int does_write; /* if nonzero, banned for readonly mode */
126 struct sftp_handler handlers[] = {
127 /* NB. SSH2_FXP_OPEN does the readonly check in the handler itself */
128 { "open", NULL, SSH2_FXP_OPEN, process_open, 0 },
129 { "close", NULL, SSH2_FXP_CLOSE, process_close, 0 },
130 { "read", NULL, SSH2_FXP_READ, process_read, 0 },
131 { "write", NULL, SSH2_FXP_WRITE, process_write, 1 },
132 { "lstat", NULL, SSH2_FXP_LSTAT, process_lstat, 0 },
133 { "fstat", NULL, SSH2_FXP_FSTAT, process_fstat, 0 },
134 { "setstat", NULL, SSH2_FXP_SETSTAT, process_setstat, 1 },
135 { "fsetstat", NULL, SSH2_FXP_FSETSTAT, process_fsetstat, 1 },
136 { "opendir", NULL, SSH2_FXP_OPENDIR, process_opendir, 0 },
137 { "readdir", NULL, SSH2_FXP_READDIR, process_readdir, 0 },
138 { "remove", NULL, SSH2_FXP_REMOVE, process_remove, 1 },
139 { "mkdir", NULL, SSH2_FXP_MKDIR, process_mkdir, 1 },
140 { "rmdir", NULL, SSH2_FXP_RMDIR, process_rmdir, 1 },
141 { "realpath", NULL, SSH2_FXP_REALPATH, process_realpath, 0 },
142 { "stat", NULL, SSH2_FXP_STAT, process_stat, 0 },
143 { "rename", NULL, SSH2_FXP_RENAME, process_rename, 1 },
144 { "readlink", NULL, SSH2_FXP_READLINK, process_readlink, 0 },
145 { "symlink", NULL, SSH2_FXP_SYMLINK, process_symlink, 1 },
146 { NULL, NULL, 0, NULL, 0 }
149 /* SSH2_FXP_EXTENDED submessages */
150 struct sftp_handler extended_handlers[] = {
151 { "posix-rename", "posix-rename@openssh.com", 0,
152 process_extended_posix_rename, 1 },
153 { "statvfs", "statvfs@openssh.com", 0, process_extended_statvfs, 0 },
154 { "fstatvfs", "fstatvfs@openssh.com", 0, process_extended_fstatvfs, 0 },
155 { "hardlink", "hardlink@openssh.com", 0, process_extended_hardlink, 1 },
156 { "fsync", "fsync@openssh.com", 0, process_extended_fsync, 1 },
157 { NULL, NULL, 0, NULL, 0 }
161 request_permitted(struct sftp_handler *h)
165 if (readonly && h->does_write) {
166 verbose("Refusing %s request in read-only mode", h->name);
169 if (request_blacklist != NULL &&
170 ((result = match_list(h->name, request_blacklist, NULL))) != NULL) {
172 verbose("Refusing blacklisted %s request", h->name);
175 if (request_whitelist != NULL &&
176 ((result = match_list(h->name, request_whitelist, NULL))) != NULL) {
178 debug2("Permitting whitelisted %s request", h->name);
181 if (request_whitelist != NULL) {
182 verbose("Refusing non-whitelisted %s request", h->name);
189 errno_to_portable(int unixerrno)
201 ret = SSH2_FX_NO_SUCH_FILE;
206 ret = SSH2_FX_PERMISSION_DENIED;
210 ret = SSH2_FX_BAD_MESSAGE;
213 ret = SSH2_FX_OP_UNSUPPORTED;
216 ret = SSH2_FX_FAILURE;
223 flags_from_portable(int pflags)
227 if ((pflags & SSH2_FXF_READ) &&
228 (pflags & SSH2_FXF_WRITE)) {
230 } else if (pflags & SSH2_FXF_READ) {
232 } else if (pflags & SSH2_FXF_WRITE) {
235 if (pflags & SSH2_FXF_APPEND)
237 if (pflags & SSH2_FXF_CREAT)
239 if (pflags & SSH2_FXF_TRUNC)
241 if (pflags & SSH2_FXF_EXCL)
247 string_from_portable(int pflags)
249 static char ret[128];
253 #define PAPPEND(str) { \
255 strlcat(ret, ",", sizeof(ret)); \
256 strlcat(ret, str, sizeof(ret)); \
259 if (pflags & SSH2_FXF_READ)
261 if (pflags & SSH2_FXF_WRITE)
263 if (pflags & SSH2_FXF_APPEND)
265 if (pflags & SSH2_FXF_CREAT)
267 if (pflags & SSH2_FXF_TRUNC)
269 if (pflags & SSH2_FXF_EXCL)
278 return decode_attrib(&iqueue);
283 typedef struct Handle Handle;
290 u_int64_t bytes_read, bytes_write;
300 Handle *handles = NULL;
301 u_int num_handles = 0;
302 int first_unused_handle = -1;
304 static void handle_unused(int i)
306 handles[i].use = HANDLE_UNUSED;
307 handles[i].next_unused = first_unused_handle;
308 first_unused_handle = i;
312 handle_new(int use, const char *name, int fd, int flags, DIR *dirp)
316 if (first_unused_handle == -1) {
317 if (num_handles + 1 <= num_handles)
320 handles = xrealloc(handles, num_handles, sizeof(Handle));
321 handle_unused(num_handles - 1);
324 i = first_unused_handle;
325 first_unused_handle = handles[i].next_unused;
327 handles[i].use = use;
328 handles[i].dirp = dirp;
330 handles[i].flags = flags;
331 handles[i].name = xstrdup(name);
332 handles[i].bytes_read = handles[i].bytes_write = 0;
338 handle_is_ok(int i, int type)
340 return i >= 0 && (u_int)i < num_handles && handles[i].use == type;
344 handle_to_string(int handle, char **stringp, int *hlenp)
346 if (stringp == NULL || hlenp == NULL)
348 *stringp = xmalloc(sizeof(int32_t));
349 put_u32(*stringp, handle);
350 *hlenp = sizeof(int32_t);
355 handle_from_string(const char *handle, u_int hlen)
359 if (hlen != sizeof(int32_t))
361 val = get_u32(handle);
362 if (handle_is_ok(val, HANDLE_FILE) ||
363 handle_is_ok(val, HANDLE_DIR))
369 handle_to_name(int handle)
371 if (handle_is_ok(handle, HANDLE_DIR)||
372 handle_is_ok(handle, HANDLE_FILE))
373 return handles[handle].name;
378 handle_to_dir(int handle)
380 if (handle_is_ok(handle, HANDLE_DIR))
381 return handles[handle].dirp;
386 handle_to_fd(int handle)
388 if (handle_is_ok(handle, HANDLE_FILE))
389 return handles[handle].fd;
394 handle_to_flags(int handle)
396 if (handle_is_ok(handle, HANDLE_FILE))
397 return handles[handle].flags;
402 handle_update_read(int handle, ssize_t bytes)
404 if (handle_is_ok(handle, HANDLE_FILE) && bytes > 0)
405 handles[handle].bytes_read += bytes;
409 handle_update_write(int handle, ssize_t bytes)
411 if (handle_is_ok(handle, HANDLE_FILE) && bytes > 0)
412 handles[handle].bytes_write += bytes;
416 handle_bytes_read(int handle)
418 if (handle_is_ok(handle, HANDLE_FILE))
419 return (handles[handle].bytes_read);
424 handle_bytes_write(int handle)
426 if (handle_is_ok(handle, HANDLE_FILE))
427 return (handles[handle].bytes_write);
432 handle_close(int handle)
436 if (handle_is_ok(handle, HANDLE_FILE)) {
437 ret = close(handles[handle].fd);
438 free(handles[handle].name);
439 handle_unused(handle);
440 } else if (handle_is_ok(handle, HANDLE_DIR)) {
441 ret = closedir(handles[handle].dirp);
442 free(handles[handle].name);
443 handle_unused(handle);
451 handle_log_close(int handle, char *emsg)
453 if (handle_is_ok(handle, HANDLE_FILE)) {
454 logit("%s%sclose \"%s\" bytes read %llu written %llu",
455 emsg == NULL ? "" : emsg, emsg == NULL ? "" : " ",
456 handle_to_name(handle),
457 (unsigned long long)handle_bytes_read(handle),
458 (unsigned long long)handle_bytes_write(handle));
460 logit("%s%sclosedir \"%s\"",
461 emsg == NULL ? "" : emsg, emsg == NULL ? "" : " ",
462 handle_to_name(handle));
467 handle_log_exit(void)
471 for (i = 0; i < num_handles; i++)
472 if (handles[i].use != HANDLE_UNUSED)
473 handle_log_close(i, "forced");
483 handle = get_string(&hlen);
485 val = handle_from_string(handle, hlen);
495 int mlen = buffer_len(m);
497 buffer_put_int(&oqueue, mlen);
498 buffer_append(&oqueue, buffer_ptr(m), mlen);
499 buffer_consume(m, mlen);
503 status_to_message(u_int32_t status)
505 const char *status_messages[] = {
506 "Success", /* SSH_FX_OK */
507 "End of file", /* SSH_FX_EOF */
508 "No such file", /* SSH_FX_NO_SUCH_FILE */
509 "Permission denied", /* SSH_FX_PERMISSION_DENIED */
510 "Failure", /* SSH_FX_FAILURE */
511 "Bad message", /* SSH_FX_BAD_MESSAGE */
512 "No connection", /* SSH_FX_NO_CONNECTION */
513 "Connection lost", /* SSH_FX_CONNECTION_LOST */
514 "Operation unsupported", /* SSH_FX_OP_UNSUPPORTED */
515 "Unknown error" /* Others */
517 return (status_messages[MIN(status,SSH2_FX_MAX)]);
521 send_status(u_int32_t id, u_int32_t status)
525 debug3("request %u: sent status %u", id, status);
526 if (log_level > SYSLOG_LEVEL_VERBOSE ||
527 (status != SSH2_FX_OK && status != SSH2_FX_EOF))
528 logit("sent status %s", status_to_message(status));
530 buffer_put_char(&msg, SSH2_FXP_STATUS);
531 buffer_put_int(&msg, id);
532 buffer_put_int(&msg, status);
534 buffer_put_cstring(&msg, status_to_message(status));
535 buffer_put_cstring(&msg, "");
541 send_data_or_handle(char type, u_int32_t id, const char *data, int dlen)
546 buffer_put_char(&msg, type);
547 buffer_put_int(&msg, id);
548 buffer_put_string(&msg, data, dlen);
554 send_data(u_int32_t id, const char *data, int dlen)
556 debug("request %u: sent data len %d", id, dlen);
557 send_data_or_handle(SSH2_FXP_DATA, id, data, dlen);
561 send_handle(u_int32_t id, int handle)
566 handle_to_string(handle, &string, &hlen);
567 debug("request %u: sent handle handle %d", id, handle);
568 send_data_or_handle(SSH2_FXP_HANDLE, id, string, hlen);
573 send_names(u_int32_t id, int count, const Stat *stats)
579 buffer_put_char(&msg, SSH2_FXP_NAME);
580 buffer_put_int(&msg, id);
581 buffer_put_int(&msg, count);
582 debug("request %u: sent names count %d", id, count);
583 for (i = 0; i < count; i++) {
584 buffer_put_cstring(&msg, stats[i].name);
585 buffer_put_cstring(&msg, stats[i].long_name);
586 encode_attrib(&msg, &stats[i].attrib);
593 send_attrib(u_int32_t id, const Attrib *a)
597 debug("request %u: sent attrib have 0x%x", id, a->flags);
599 buffer_put_char(&msg, SSH2_FXP_ATTRS);
600 buffer_put_int(&msg, id);
601 encode_attrib(&msg, a);
607 send_statvfs(u_int32_t id, struct statvfs *st)
612 flag = (st->f_flag & ST_RDONLY) ? SSH2_FXE_STATVFS_ST_RDONLY : 0;
613 flag |= (st->f_flag & ST_NOSUID) ? SSH2_FXE_STATVFS_ST_NOSUID : 0;
616 buffer_put_char(&msg, SSH2_FXP_EXTENDED_REPLY);
617 buffer_put_int(&msg, id);
618 buffer_put_int64(&msg, st->f_bsize);
619 buffer_put_int64(&msg, st->f_frsize);
620 buffer_put_int64(&msg, st->f_blocks);
621 buffer_put_int64(&msg, st->f_bfree);
622 buffer_put_int64(&msg, st->f_bavail);
623 buffer_put_int64(&msg, st->f_files);
624 buffer_put_int64(&msg, st->f_ffree);
625 buffer_put_int64(&msg, st->f_favail);
626 buffer_put_int64(&msg, FSID_TO_ULONG(st->f_fsid));
627 buffer_put_int64(&msg, flag);
628 buffer_put_int64(&msg, st->f_namemax);
641 verbose("received client version %u", version);
643 buffer_put_char(&msg, SSH2_FXP_VERSION);
644 buffer_put_int(&msg, SSH2_FILEXFER_VERSION);
645 /* POSIX rename extension */
646 buffer_put_cstring(&msg, "posix-rename@openssh.com");
647 buffer_put_cstring(&msg, "1"); /* version */
648 /* statvfs extension */
649 buffer_put_cstring(&msg, "statvfs@openssh.com");
650 buffer_put_cstring(&msg, "2"); /* version */
651 /* fstatvfs extension */
652 buffer_put_cstring(&msg, "fstatvfs@openssh.com");
653 buffer_put_cstring(&msg, "2"); /* version */
654 /* hardlink extension */
655 buffer_put_cstring(&msg, "hardlink@openssh.com");
656 buffer_put_cstring(&msg, "1"); /* version */
657 /* fsync extension */
658 buffer_put_cstring(&msg, "fsync@openssh.com");
659 buffer_put_cstring(&msg, "1"); /* version */
665 process_open(u_int32_t id)
670 int handle, fd, flags, mode, status = SSH2_FX_FAILURE;
672 name = get_string(NULL);
673 pflags = get_int(); /* portable flags */
674 debug3("request %u: open flags %d", id, pflags);
676 flags = flags_from_portable(pflags);
677 mode = (a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) ? a->perm : 0666;
678 logit("open \"%s\" flags %s mode 0%o",
679 name, string_from_portable(pflags), mode);
681 ((flags & O_ACCMODE) == O_WRONLY ||
682 (flags & O_ACCMODE) == O_RDWR)) {
683 verbose("Refusing open request in read-only mode");
684 status = SSH2_FX_PERMISSION_DENIED;
686 fd = open(name, flags, mode);
688 status = errno_to_portable(errno);
690 handle = handle_new(HANDLE_FILE, name, fd, flags, NULL);
694 send_handle(id, handle);
699 if (status != SSH2_FX_OK)
700 send_status(id, status);
705 process_close(u_int32_t id)
707 int handle, ret, status = SSH2_FX_FAILURE;
709 handle = get_handle();
710 debug3("request %u: close handle %u", id, handle);
711 handle_log_close(handle, NULL);
712 ret = handle_close(handle);
713 status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
714 send_status(id, status);
718 process_read(u_int32_t id)
722 int handle, fd, ret, status = SSH2_FX_FAILURE;
725 handle = get_handle();
729 debug("request %u: read \"%s\" (handle %d) off %llu len %d",
730 id, handle_to_name(handle), handle, (unsigned long long)off, len);
731 if (len > sizeof buf) {
733 debug2("read change len %d", len);
735 fd = handle_to_fd(handle);
737 if (lseek(fd, off, SEEK_SET) < 0) {
738 error("process_read: seek failed");
739 status = errno_to_portable(errno);
741 ret = read(fd, buf, len);
743 status = errno_to_portable(errno);
744 } else if (ret == 0) {
745 status = SSH2_FX_EOF;
747 send_data(id, buf, ret);
749 handle_update_read(handle, ret);
753 if (status != SSH2_FX_OK)
754 send_status(id, status);
758 process_write(u_int32_t id)
762 int handle, fd, ret, status;
765 handle = get_handle();
767 data = get_string(&len);
769 debug("request %u: write \"%s\" (handle %d) off %llu len %d",
770 id, handle_to_name(handle), handle, (unsigned long long)off, len);
771 fd = handle_to_fd(handle);
774 status = SSH2_FX_FAILURE;
776 if (!(handle_to_flags(handle) & O_APPEND) &&
777 lseek(fd, off, SEEK_SET) < 0) {
778 status = errno_to_portable(errno);
779 error("process_write: seek failed");
782 ret = write(fd, data, len);
784 error("process_write: write failed");
785 status = errno_to_portable(errno);
786 } else if ((size_t)ret == len) {
788 handle_update_write(handle, ret);
790 debug2("nothing at all written");
791 status = SSH2_FX_FAILURE;
795 send_status(id, status);
800 process_do_stat(u_int32_t id, int do_lstat)
805 int ret, status = SSH2_FX_FAILURE;
807 name = get_string(NULL);
808 debug3("request %u: %sstat", id, do_lstat ? "l" : "");
809 verbose("%sstat name \"%s\"", do_lstat ? "l" : "", name);
810 ret = do_lstat ? lstat(name, &st) : stat(name, &st);
812 status = errno_to_portable(errno);
814 stat_to_attrib(&st, &a);
818 if (status != SSH2_FX_OK)
819 send_status(id, status);
824 process_stat(u_int32_t id)
826 process_do_stat(id, 0);
830 process_lstat(u_int32_t id)
832 process_do_stat(id, 1);
836 process_fstat(u_int32_t id)
840 int fd, ret, handle, status = SSH2_FX_FAILURE;
842 handle = get_handle();
843 debug("request %u: fstat \"%s\" (handle %u)",
844 id, handle_to_name(handle), handle);
845 fd = handle_to_fd(handle);
847 ret = fstat(fd, &st);
849 status = errno_to_portable(errno);
851 stat_to_attrib(&st, &a);
856 if (status != SSH2_FX_OK)
857 send_status(id, status);
860 static struct timeval *
861 attrib_to_tv(const Attrib *a)
863 static struct timeval tv[2];
865 tv[0].tv_sec = a->atime;
867 tv[1].tv_sec = a->mtime;
873 process_setstat(u_int32_t id)
877 int status = SSH2_FX_OK, ret;
879 name = get_string(NULL);
881 debug("request %u: setstat name \"%s\"", id, name);
882 if (a->flags & SSH2_FILEXFER_ATTR_SIZE) {
883 logit("set \"%s\" size %llu",
884 name, (unsigned long long)a->size);
885 ret = truncate(name, a->size);
887 status = errno_to_portable(errno);
889 if (a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) {
890 logit("set \"%s\" mode %04o", name, a->perm);
891 ret = chmod(name, a->perm & 07777);
893 status = errno_to_portable(errno);
895 if (a->flags & SSH2_FILEXFER_ATTR_ACMODTIME) {
899 strftime(buf, sizeof(buf), "%Y%m%d-%H:%M:%S",
901 logit("set \"%s\" modtime %s", name, buf);
902 ret = utimes(name, attrib_to_tv(a));
904 status = errno_to_portable(errno);
906 if (a->flags & SSH2_FILEXFER_ATTR_UIDGID) {
907 logit("set \"%s\" owner %lu group %lu", name,
908 (u_long)a->uid, (u_long)a->gid);
909 ret = chown(name, a->uid, a->gid);
911 status = errno_to_portable(errno);
913 send_status(id, status);
918 process_fsetstat(u_int32_t id)
922 int status = SSH2_FX_OK;
924 handle = get_handle();
926 debug("request %u: fsetstat handle %d", id, handle);
927 fd = handle_to_fd(handle);
929 status = SSH2_FX_FAILURE;
931 char *name = handle_to_name(handle);
933 if (a->flags & SSH2_FILEXFER_ATTR_SIZE) {
934 logit("set \"%s\" size %llu",
935 name, (unsigned long long)a->size);
936 ret = ftruncate(fd, a->size);
938 status = errno_to_portable(errno);
940 if (a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) {
941 logit("set \"%s\" mode %04o", name, a->perm);
943 ret = fchmod(fd, a->perm & 07777);
945 ret = chmod(name, a->perm & 07777);
948 status = errno_to_portable(errno);
950 if (a->flags & SSH2_FILEXFER_ATTR_ACMODTIME) {
954 strftime(buf, sizeof(buf), "%Y%m%d-%H:%M:%S",
956 logit("set \"%s\" modtime %s", name, buf);
958 ret = futimes(fd, attrib_to_tv(a));
960 ret = utimes(name, attrib_to_tv(a));
963 status = errno_to_portable(errno);
965 if (a->flags & SSH2_FILEXFER_ATTR_UIDGID) {
966 logit("set \"%s\" owner %lu group %lu", name,
967 (u_long)a->uid, (u_long)a->gid);
969 ret = fchown(fd, a->uid, a->gid);
971 ret = chown(name, a->uid, a->gid);
974 status = errno_to_portable(errno);
977 send_status(id, status);
981 process_opendir(u_int32_t id)
985 int handle, status = SSH2_FX_FAILURE;
987 path = get_string(NULL);
988 debug3("request %u: opendir", id);
989 logit("opendir \"%s\"", path);
990 dirp = opendir(path);
992 status = errno_to_portable(errno);
994 handle = handle_new(HANDLE_DIR, path, 0, 0, dirp);
998 send_handle(id, handle);
1003 if (status != SSH2_FX_OK)
1004 send_status(id, status);
1009 process_readdir(u_int32_t id)
1016 handle = get_handle();
1017 debug("request %u: readdir \"%s\" (handle %d)", id,
1018 handle_to_name(handle), handle);
1019 dirp = handle_to_dir(handle);
1020 path = handle_to_name(handle);
1021 if (dirp == NULL || path == NULL) {
1022 send_status(id, SSH2_FX_FAILURE);
1025 char pathname[MAXPATHLEN];
1027 int nstats = 10, count = 0, i;
1029 stats = xcalloc(nstats, sizeof(Stat));
1030 while ((dp = readdir(dirp)) != NULL) {
1031 if (count >= nstats) {
1033 stats = xrealloc(stats, nstats, sizeof(Stat));
1035 /* XXX OVERFLOW ? */
1036 snprintf(pathname, sizeof pathname, "%s%s%s", path,
1037 strcmp(path, "/") ? "/" : "", dp->d_name);
1038 if (lstat(pathname, &st) < 0)
1040 stat_to_attrib(&st, &(stats[count].attrib));
1041 stats[count].name = xstrdup(dp->d_name);
1042 stats[count].long_name = ls_file(dp->d_name, &st, 0, 0);
1044 /* send up to 100 entries in one message */
1045 /* XXX check packet size instead */
1050 send_names(id, count, stats);
1051 for (i = 0; i < count; i++) {
1052 free(stats[i].name);
1053 free(stats[i].long_name);
1056 send_status(id, SSH2_FX_EOF);
1063 process_remove(u_int32_t id)
1066 int status = SSH2_FX_FAILURE;
1069 name = get_string(NULL);
1070 debug3("request %u: remove", id);
1071 logit("remove name \"%s\"", name);
1073 status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1074 send_status(id, status);
1079 process_mkdir(u_int32_t id)
1083 int ret, mode, status = SSH2_FX_FAILURE;
1085 name = get_string(NULL);
1087 mode = (a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) ?
1088 a->perm & 07777 : 0777;
1089 debug3("request %u: mkdir", id);
1090 logit("mkdir name \"%s\" mode 0%o", name, mode);
1091 ret = mkdir(name, mode);
1092 status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1093 send_status(id, status);
1098 process_rmdir(u_int32_t id)
1103 name = get_string(NULL);
1104 debug3("request %u: rmdir", id);
1105 logit("rmdir name \"%s\"", name);
1107 status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1108 send_status(id, status);
1113 process_realpath(u_int32_t id)
1115 char resolvedname[MAXPATHLEN];
1118 path = get_string(NULL);
1119 if (path[0] == '\0') {
1121 path = xstrdup(".");
1123 debug3("request %u: realpath", id);
1124 verbose("realpath \"%s\"", path);
1125 if (realpath(path, resolvedname) == NULL) {
1126 send_status(id, errno_to_portable(errno));
1129 attrib_clear(&s.attrib);
1130 s.name = s.long_name = resolvedname;
1131 send_names(id, 1, &s);
1137 process_rename(u_int32_t id)
1139 char *oldpath, *newpath;
1143 oldpath = get_string(NULL);
1144 newpath = get_string(NULL);
1145 debug3("request %u: rename", id);
1146 logit("rename old \"%s\" new \"%s\"", oldpath, newpath);
1147 status = SSH2_FX_FAILURE;
1148 if (lstat(oldpath, &sb) == -1)
1149 status = errno_to_portable(errno);
1150 else if (S_ISREG(sb.st_mode)) {
1151 /* Race-free rename of regular files */
1152 if (link(oldpath, newpath) == -1) {
1153 if (errno == EOPNOTSUPP || errno == ENOSYS
1157 #ifdef LINK_OPNOTSUPP_ERRNO
1158 || errno == LINK_OPNOTSUPP_ERRNO
1164 * fs doesn't support links, so fall back to
1165 * stat+rename. This is racy.
1167 if (stat(newpath, &st) == -1) {
1168 if (rename(oldpath, newpath) == -1)
1170 errno_to_portable(errno);
1172 status = SSH2_FX_OK;
1175 status = errno_to_portable(errno);
1177 } else if (unlink(oldpath) == -1) {
1178 status = errno_to_portable(errno);
1179 /* clean spare link */
1182 status = SSH2_FX_OK;
1183 } else if (stat(newpath, &sb) == -1) {
1184 if (rename(oldpath, newpath) == -1)
1185 status = errno_to_portable(errno);
1187 status = SSH2_FX_OK;
1189 send_status(id, status);
1195 process_readlink(u_int32_t id)
1198 char buf[MAXPATHLEN];
1201 path = get_string(NULL);
1202 debug3("request %u: readlink", id);
1203 verbose("readlink \"%s\"", path);
1204 if ((len = readlink(path, buf, sizeof(buf) - 1)) == -1)
1205 send_status(id, errno_to_portable(errno));
1210 attrib_clear(&s.attrib);
1211 s.name = s.long_name = buf;
1212 send_names(id, 1, &s);
1218 process_symlink(u_int32_t id)
1220 char *oldpath, *newpath;
1223 oldpath = get_string(NULL);
1224 newpath = get_string(NULL);
1225 debug3("request %u: symlink", id);
1226 logit("symlink old \"%s\" new \"%s\"", oldpath, newpath);
1227 /* this will fail if 'newpath' exists */
1228 ret = symlink(oldpath, newpath);
1229 status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1230 send_status(id, status);
1236 process_extended_posix_rename(u_int32_t id)
1238 char *oldpath, *newpath;
1241 oldpath = get_string(NULL);
1242 newpath = get_string(NULL);
1243 debug3("request %u: posix-rename", id);
1244 logit("posix-rename old \"%s\" new \"%s\"", oldpath, newpath);
1245 ret = rename(oldpath, newpath);
1246 status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1247 send_status(id, status);
1253 process_extended_statvfs(u_int32_t id)
1258 path = get_string(NULL);
1259 debug3("request %u: statvfs", id);
1260 logit("statvfs \"%s\"", path);
1262 if (statvfs(path, &st) != 0)
1263 send_status(id, errno_to_portable(errno));
1265 send_statvfs(id, &st);
1270 process_extended_fstatvfs(u_int32_t id)
1275 handle = get_handle();
1276 debug("request %u: fstatvfs \"%s\" (handle %u)",
1277 id, handle_to_name(handle), handle);
1278 if ((fd = handle_to_fd(handle)) < 0) {
1279 send_status(id, SSH2_FX_FAILURE);
1282 if (fstatvfs(fd, &st) != 0)
1283 send_status(id, errno_to_portable(errno));
1285 send_statvfs(id, &st);
1289 process_extended_hardlink(u_int32_t id)
1291 char *oldpath, *newpath;
1294 oldpath = get_string(NULL);
1295 newpath = get_string(NULL);
1296 debug3("request %u: hardlink", id);
1297 logit("hardlink old \"%s\" new \"%s\"", oldpath, newpath);
1298 ret = link(oldpath, newpath);
1299 status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1300 send_status(id, status);
1306 process_extended_fsync(u_int32_t id)
1308 int handle, fd, ret, status = SSH2_FX_OP_UNSUPPORTED;
1310 handle = get_handle();
1311 debug3("request %u: fsync (handle %u)", id, handle);
1312 verbose("fsync \"%s\"", handle_to_name(handle));
1313 if ((fd = handle_to_fd(handle)) < 0)
1314 status = SSH2_FX_NO_SUCH_FILE;
1315 else if (handle_is_ok(handle, HANDLE_FILE)) {
1317 status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1319 send_status(id, status);
1323 process_extended(u_int32_t id)
1328 request = get_string(NULL);
1329 for (i = 0; extended_handlers[i].handler != NULL; i++) {
1330 if (strcmp(request, extended_handlers[i].ext_name) == 0) {
1331 if (!request_permitted(&extended_handlers[i]))
1332 send_status(id, SSH2_FX_PERMISSION_DENIED);
1334 extended_handlers[i].handler(id);
1338 if (extended_handlers[i].handler == NULL) {
1339 error("Unknown extended request \"%.100s\"", request);
1340 send_status(id, SSH2_FX_OP_UNSUPPORTED); /* MUST */
1345 /* stolen from ssh-agent */
1350 u_int msg_len, buf_len, consumed, type, i;
1354 buf_len = buffer_len(&iqueue);
1356 return; /* Incomplete message. */
1357 cp = buffer_ptr(&iqueue);
1358 msg_len = get_u32(cp);
1359 if (msg_len > SFTP_MAX_MSG_LENGTH) {
1360 error("bad message from %s local user %s",
1361 client_addr, pw->pw_name);
1362 sftp_server_cleanup_exit(11);
1364 if (buf_len < msg_len + 4)
1366 buffer_consume(&iqueue, 4);
1368 type = buffer_get_char(&iqueue);
1375 case SSH2_FXP_EXTENDED:
1377 fatal("Received extended request before init");
1379 process_extended(id);
1383 fatal("Received %u request before init", type);
1385 for (i = 0; handlers[i].handler != NULL; i++) {
1386 if (type == handlers[i].type) {
1387 if (!request_permitted(&handlers[i])) {
1389 SSH2_FX_PERMISSION_DENIED);
1391 handlers[i].handler(id);
1396 if (handlers[i].handler == NULL)
1397 error("Unknown message %u", type);
1399 /* discard the remaining bytes from the current packet */
1400 if (buf_len < buffer_len(&iqueue)) {
1401 error("iqueue grew unexpectedly");
1402 sftp_server_cleanup_exit(255);
1404 consumed = buf_len - buffer_len(&iqueue);
1405 if (msg_len < consumed) {
1406 error("msg_len %u < consumed %u", msg_len, consumed);
1407 sftp_server_cleanup_exit(255);
1409 if (msg_len > consumed)
1410 buffer_consume(&iqueue, msg_len - consumed);
1413 /* Cleanup handler that logs active handles upon normal exit */
1415 sftp_server_cleanup_exit(int i)
1417 if (pw != NULL && client_addr != NULL) {
1419 logit("session closed for local user %s from [%s]",
1420 pw->pw_name, client_addr);
1426 sftp_server_usage(void)
1428 extern char *__progname;
1431 "usage: %s [-ehR] [-d start_directory] [-f log_facility] "
1432 "[-l log_level]\n\t[-P blacklisted_requests] "
1433 "[-p whitelisted_requests] [-u umask]\n"
1434 " %s -Q protocol_feature\n",
1435 __progname, __progname);
1440 sftp_server_main(int argc, char **argv, struct passwd *user_pw)
1442 fd_set *rset, *wset;
1443 int i, in, out, max, ch, skipargs = 0, log_stderr = 0;
1444 ssize_t len, olen, set_size;
1445 SyslogFacility log_facility = SYSLOG_FACILITY_AUTH;
1446 char *cp, *homedir = NULL, buf[4*4096];
1449 extern char *optarg;
1450 extern char *__progname;
1452 __progname = ssh_get_progname(argv[0]);
1453 log_init(__progname, log_level, log_facility, log_stderr);
1455 pw = pwcopy(user_pw);
1457 while (!skipargs && (ch = getopt(argc, argv,
1458 "d:f:l:P:p:Q:u:cehR")) != -1) {
1461 if (strcasecmp(optarg, "requests") != 0) {
1462 fprintf(stderr, "Invalid query type\n");
1465 for (i = 0; handlers[i].handler != NULL; i++)
1466 printf("%s\n", handlers[i].name);
1467 for (i = 0; extended_handlers[i].handler != NULL; i++)
1468 printf("%s\n", extended_handlers[i].name);
1476 * Ignore all arguments if we are invoked as a
1477 * shell using "sftp-server -c command"
1485 log_level = log_level_number(optarg);
1486 if (log_level == SYSLOG_LEVEL_NOT_SET)
1487 error("Invalid log level \"%s\"", optarg);
1490 log_facility = log_facility_number(optarg);
1491 if (log_facility == SYSLOG_FACILITY_NOT_SET)
1492 error("Invalid log facility \"%s\"", optarg);
1495 cp = tilde_expand_filename(optarg, user_pw->pw_uid);
1496 homedir = percent_expand(cp, "d", user_pw->pw_dir,
1497 "u", user_pw->pw_name, (char *)NULL);
1501 if (request_whitelist != NULL)
1502 fatal("Permitted requests already set");
1503 request_whitelist = xstrdup(optarg);
1506 if (request_blacklist != NULL)
1507 fatal("Refused requests already set");
1508 request_blacklist = xstrdup(optarg);
1512 mask = strtol(optarg, &cp, 8);
1513 if (mask < 0 || mask > 0777 || *cp != '\0' ||
1514 cp == optarg || (mask == 0 && errno != 0))
1515 fatal("Invalid umask \"%s\"", optarg);
1516 (void)umask((mode_t)mask);
1520 sftp_server_usage();
1524 log_init(__progname, log_level, log_facility, log_stderr);
1526 if ((cp = getenv("SSH_CONNECTION")) != NULL) {
1527 client_addr = xstrdup(cp);
1528 if ((cp = strchr(client_addr, ' ')) == NULL) {
1529 error("Malformed SSH_CONNECTION variable: \"%s\"",
1530 getenv("SSH_CONNECTION"));
1531 sftp_server_cleanup_exit(255);
1535 client_addr = xstrdup("UNKNOWN");
1537 logit("session opened for local user %s from [%s]",
1538 pw->pw_name, client_addr);
1541 out = STDOUT_FILENO;
1544 setmode(in, O_BINARY);
1545 setmode(out, O_BINARY);
1554 buffer_init(&iqueue);
1555 buffer_init(&oqueue);
1557 set_size = howmany(max + 1, NFDBITS) * sizeof(fd_mask);
1558 rset = (fd_set *)xmalloc(set_size);
1559 wset = (fd_set *)xmalloc(set_size);
1561 if (homedir != NULL) {
1562 if (chdir(homedir) != 0) {
1563 error("chdir to \"%s\" failed: %s", homedir,
1569 memset(rset, 0, set_size);
1570 memset(wset, 0, set_size);
1573 * Ensure that we can read a full buffer and handle
1574 * the worst-case length packet it can generate,
1575 * otherwise apply backpressure by stopping reads.
1577 if (buffer_check_alloc(&iqueue, sizeof(buf)) &&
1578 buffer_check_alloc(&oqueue, SFTP_MAX_MSG_LENGTH))
1581 olen = buffer_len(&oqueue);
1585 if (select(max+1, rset, wset, NULL, NULL) < 0) {
1588 error("select: %s", strerror(errno));
1589 sftp_server_cleanup_exit(2);
1592 /* copy stdin to iqueue */
1593 if (FD_ISSET(in, rset)) {
1594 len = read(in, buf, sizeof buf);
1597 sftp_server_cleanup_exit(0);
1598 } else if (len < 0) {
1599 error("read: %s", strerror(errno));
1600 sftp_server_cleanup_exit(1);
1602 buffer_append(&iqueue, buf, len);
1605 /* send oqueue to stdout */
1606 if (FD_ISSET(out, wset)) {
1607 len = write(out, buffer_ptr(&oqueue), olen);
1609 error("write: %s", strerror(errno));
1610 sftp_server_cleanup_exit(1);
1612 buffer_consume(&oqueue, len);
1617 * Process requests from client if we can fit the results
1618 * into the output buffer, otherwise stop processing input
1619 * and let the output queue drain.
1621 if (buffer_check_alloc(&oqueue, SFTP_MAX_MSG_LENGTH))