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