xref: /freebsd/crypto/openssh/sftp-server.c (revision bb5c77e9d281d6def6835d48249898764bc6a5fe)
1 /* $OpenBSD: sftp-server.c,v 1.156 2026/07/01 00:52:23 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;
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 			xasprintf(&pathname, "%s%s%s", path,
1150 			    strcmp(path, "/") ? "/" : "", dp->d_name);
1151 			r = lstat(pathname, &st);
1152 			free(pathname);
1153 			if (r == -1)
1154 				continue;
1155 			stat_to_attrib(&st, &(stats[count].attrib));
1156 			stats[count].name = xstrdup(dp->d_name);
1157 			stats[count].long_name = ls_file(dp->d_name, &st,
1158 			    0, 0, NULL, NULL);
1159 			count++;
1160 			/* send up to 100 entries in one message */
1161 			/* XXX check packet size instead */
1162 			if (count == 100)
1163 				break;
1164 		}
1165 		if (count > 0) {
1166 			send_names(id, count, stats);
1167 			for (i = 0; i < count; i++) {
1168 				free(stats[i].name);
1169 				free(stats[i].long_name);
1170 			}
1171 		} else {
1172 			send_status(id, SSH2_FX_EOF);
1173 		}
1174 		free(stats);
1175 	}
1176 }
1177 
1178 static void
process_remove(uint32_t id)1179 process_remove(uint32_t id)
1180 {
1181 	char *name;
1182 	int r, status = SSH2_FX_FAILURE;
1183 
1184 	if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0)
1185 		fatal_fr(r, "parse");
1186 
1187 	debug3("request %u: remove", id);
1188 	logit("remove name \"%s\"", name);
1189 	r = unlink(name);
1190 	status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1191 	send_status(id, status);
1192 	free(name);
1193 }
1194 
1195 static void
process_mkdir(uint32_t id)1196 process_mkdir(uint32_t id)
1197 {
1198 	Attrib a;
1199 	char *name;
1200 	int r, mode, status = SSH2_FX_FAILURE;
1201 
1202 	if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0 ||
1203 	    (r = decode_attrib(iqueue, &a)) != 0)
1204 		fatal_fr(r, "parse");
1205 
1206 	mode = (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) ?
1207 	    a.perm & 07777 : 0777;
1208 	debug3("request %u: mkdir", id);
1209 	logit("mkdir name \"%s\" mode 0%o", name, mode);
1210 	r = mkdir(name, mode);
1211 	status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1212 	send_status(id, status);
1213 	free(name);
1214 }
1215 
1216 static void
process_rmdir(uint32_t id)1217 process_rmdir(uint32_t id)
1218 {
1219 	char *name;
1220 	int r, status;
1221 
1222 	if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0)
1223 		fatal_fr(r, "parse");
1224 
1225 	debug3("request %u: rmdir", id);
1226 	logit("rmdir name \"%s\"", name);
1227 	r = rmdir(name);
1228 	status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1229 	send_status(id, status);
1230 	free(name);
1231 }
1232 
1233 static void
process_realpath(uint32_t id)1234 process_realpath(uint32_t id)
1235 {
1236 	char resolvedname[PATH_MAX];
1237 	char *path;
1238 	int r;
1239 
1240 	if ((r = sshbuf_get_cstring(iqueue, &path, NULL)) != 0)
1241 		fatal_fr(r, "parse");
1242 
1243 	if (path[0] == '\0') {
1244 		free(path);
1245 		path = xstrdup(".");
1246 	}
1247 	debug3("request %u: realpath", id);
1248 	verbose("realpath \"%s\"", path);
1249 	if (sftp_realpath(path, resolvedname) == NULL) {
1250 		send_status(id, errno_to_portable(errno));
1251 	} else {
1252 		Stat s;
1253 		attrib_clear(&s.attrib);
1254 		s.name = s.long_name = resolvedname;
1255 		send_names(id, 1, &s);
1256 	}
1257 	free(path);
1258 }
1259 
1260 static void
process_rename(uint32_t id)1261 process_rename(uint32_t id)
1262 {
1263 	char *oldpath, *newpath;
1264 	int r, status;
1265 	struct stat sb;
1266 
1267 	if ((r = sshbuf_get_cstring(iqueue, &oldpath, NULL)) != 0 ||
1268 	    (r = sshbuf_get_cstring(iqueue, &newpath, NULL)) != 0)
1269 		fatal_fr(r, "parse");
1270 
1271 	debug3("request %u: rename", id);
1272 	logit("rename old \"%s\" new \"%s\"", oldpath, newpath);
1273 	status = SSH2_FX_FAILURE;
1274 	if (lstat(oldpath, &sb) == -1)
1275 		status = errno_to_portable(errno);
1276 	else if (S_ISREG(sb.st_mode)) {
1277 		/* Race-free rename of regular files */
1278 		if (link(oldpath, newpath) == -1) {
1279 			if (errno == EOPNOTSUPP || errno == ENOSYS
1280 #ifdef EXDEV
1281 			    || errno == EXDEV
1282 #endif
1283 #ifdef LINK_OPNOTSUPP_ERRNO
1284 			    || errno == LINK_OPNOTSUPP_ERRNO
1285 #endif
1286 			    ) {
1287 				struct stat st;
1288 
1289 				/*
1290 				 * fs doesn't support links, so fall back to
1291 				 * stat+rename.  This is racy.
1292 				 */
1293 				if (stat(newpath, &st) == -1) {
1294 					if (rename(oldpath, newpath) == -1)
1295 						status =
1296 						    errno_to_portable(errno);
1297 					else
1298 						status = SSH2_FX_OK;
1299 				}
1300 			} else {
1301 				status = errno_to_portable(errno);
1302 			}
1303 		} else if (unlink(oldpath) == -1) {
1304 			status = errno_to_portable(errno);
1305 			/* clean spare link */
1306 			unlink(newpath);
1307 		} else
1308 			status = SSH2_FX_OK;
1309 	} else if (stat(newpath, &sb) == -1) {
1310 		if (rename(oldpath, newpath) == -1)
1311 			status = errno_to_portable(errno);
1312 		else
1313 			status = SSH2_FX_OK;
1314 	}
1315 	send_status(id, status);
1316 	free(oldpath);
1317 	free(newpath);
1318 }
1319 
1320 static void
process_readlink(uint32_t id)1321 process_readlink(uint32_t id)
1322 {
1323 	int r, len;
1324 	char buf[PATH_MAX];
1325 	char *path;
1326 
1327 	if ((r = sshbuf_get_cstring(iqueue, &path, NULL)) != 0)
1328 		fatal_fr(r, "parse");
1329 
1330 	debug3("request %u: readlink", id);
1331 	verbose("readlink \"%s\"", path);
1332 	if ((len = readlink(path, buf, sizeof(buf) - 1)) == -1)
1333 		send_status(id, errno_to_portable(errno));
1334 	else {
1335 		Stat s;
1336 
1337 		buf[len] = '\0';
1338 		attrib_clear(&s.attrib);
1339 		s.name = s.long_name = buf;
1340 		send_names(id, 1, &s);
1341 	}
1342 	free(path);
1343 }
1344 
1345 static void
process_symlink(uint32_t id)1346 process_symlink(uint32_t id)
1347 {
1348 	char *oldpath, *newpath;
1349 	int r, status;
1350 
1351 	if ((r = sshbuf_get_cstring(iqueue, &oldpath, NULL)) != 0 ||
1352 	    (r = sshbuf_get_cstring(iqueue, &newpath, NULL)) != 0)
1353 		fatal_fr(r, "parse");
1354 
1355 	debug3("request %u: symlink", id);
1356 	logit("symlink old \"%s\" new \"%s\"", oldpath, newpath);
1357 	/* this will fail if 'newpath' exists */
1358 	r = symlink(oldpath, newpath);
1359 	status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1360 	send_status(id, status);
1361 	free(oldpath);
1362 	free(newpath);
1363 }
1364 
1365 static void
process_extended_posix_rename(uint32_t id)1366 process_extended_posix_rename(uint32_t id)
1367 {
1368 	char *oldpath, *newpath;
1369 	int r, status;
1370 
1371 	if ((r = sshbuf_get_cstring(iqueue, &oldpath, NULL)) != 0 ||
1372 	    (r = sshbuf_get_cstring(iqueue, &newpath, NULL)) != 0)
1373 		fatal_fr(r, "parse");
1374 
1375 	debug3("request %u: posix-rename", id);
1376 	logit("posix-rename old \"%s\" new \"%s\"", oldpath, newpath);
1377 	r = rename(oldpath, newpath);
1378 	status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1379 	send_status(id, status);
1380 	free(oldpath);
1381 	free(newpath);
1382 }
1383 
1384 static void
process_extended_statvfs(uint32_t id)1385 process_extended_statvfs(uint32_t id)
1386 {
1387 	char *path;
1388 	struct statvfs st;
1389 	int r;
1390 
1391 	if ((r = sshbuf_get_cstring(iqueue, &path, NULL)) != 0)
1392 		fatal_fr(r, "parse");
1393 	debug3("request %u: statvfs", id);
1394 	logit("statvfs \"%s\"", path);
1395 
1396 	if (statvfs(path, &st) != 0)
1397 		send_status(id, errno_to_portable(errno));
1398 	else
1399 		send_statvfs(id, &st);
1400 	free(path);
1401 }
1402 
1403 static void
process_extended_fstatvfs(uint32_t id)1404 process_extended_fstatvfs(uint32_t id)
1405 {
1406 	int r, handle, fd;
1407 	struct statvfs st;
1408 
1409 	if ((r = get_handle(iqueue, &handle)) != 0)
1410 		fatal_fr(r, "parse");
1411 	debug("request %u: fstatvfs \"%s\" (handle %u)",
1412 	    id, handle_to_name(handle), handle);
1413 	if ((fd = handle_to_fd(handle)) < 0) {
1414 		send_status(id, SSH2_FX_FAILURE);
1415 		return;
1416 	}
1417 	if (fstatvfs(fd, &st) != 0)
1418 		send_status(id, errno_to_portable(errno));
1419 	else
1420 		send_statvfs(id, &st);
1421 }
1422 
1423 static void
process_extended_hardlink(uint32_t id)1424 process_extended_hardlink(uint32_t id)
1425 {
1426 	char *oldpath, *newpath;
1427 	int r, status;
1428 
1429 	if ((r = sshbuf_get_cstring(iqueue, &oldpath, NULL)) != 0 ||
1430 	    (r = sshbuf_get_cstring(iqueue, &newpath, NULL)) != 0)
1431 		fatal_fr(r, "parse");
1432 
1433 	debug3("request %u: hardlink", id);
1434 	logit("hardlink old \"%s\" new \"%s\"", oldpath, newpath);
1435 	r = link(oldpath, newpath);
1436 	status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1437 	send_status(id, status);
1438 	free(oldpath);
1439 	free(newpath);
1440 }
1441 
1442 static void
process_extended_fsync(uint32_t id)1443 process_extended_fsync(uint32_t id)
1444 {
1445 	int handle, fd, r, status = SSH2_FX_OP_UNSUPPORTED;
1446 
1447 	if ((r = get_handle(iqueue, &handle)) != 0)
1448 		fatal_fr(r, "parse");
1449 	debug3("request %u: fsync (handle %u)", id, handle);
1450 	verbose("fsync \"%s\"", handle_to_name(handle));
1451 	if ((fd = handle_to_fd(handle)) < 0)
1452 		status = SSH2_FX_NO_SUCH_FILE;
1453 	else if (handle_is_ok(handle, HANDLE_FILE)) {
1454 		r = fsync(fd);
1455 		status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1456 	}
1457 	send_status(id, status);
1458 }
1459 
1460 static void
process_extended_lsetstat(uint32_t id)1461 process_extended_lsetstat(uint32_t id)
1462 {
1463 	Attrib a;
1464 	char *name;
1465 	int r, status = SSH2_FX_OK;
1466 
1467 	if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0 ||
1468 	    (r = decode_attrib(iqueue, &a)) != 0)
1469 		fatal_fr(r, "parse");
1470 
1471 	debug("request %u: lsetstat name \"%s\"", id, name);
1472 	if (a.flags & SSH2_FILEXFER_ATTR_SIZE) {
1473 		/* nonsensical for links */
1474 		status = SSH2_FX_BAD_MESSAGE;
1475 		goto out;
1476 	}
1477 	if (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) {
1478 		logit("set \"%s\" mode %04o", name, a.perm);
1479 		r = fchmodat(AT_FDCWD, name,
1480 		    a.perm & 07777, AT_SYMLINK_NOFOLLOW);
1481 		if (r == -1)
1482 			status = errno_to_portable(errno);
1483 	}
1484 	if (a.flags & SSH2_FILEXFER_ATTR_ACMODTIME) {
1485 		char buf[64];
1486 		time_t t = a.mtime;
1487 
1488 		strftime(buf, sizeof(buf), "%Y%m%d-%H:%M:%S",
1489 		    localtime(&t));
1490 		logit("set \"%s\" modtime %s", name, buf);
1491 		r = utimensat(AT_FDCWD, name,
1492 		    attrib_to_ts(&a), AT_SYMLINK_NOFOLLOW);
1493 		if (r == -1)
1494 			status = errno_to_portable(errno);
1495 	}
1496 	if (a.flags & SSH2_FILEXFER_ATTR_UIDGID) {
1497 		logit("set \"%s\" owner %lu group %lu", name,
1498 		    (u_long)a.uid, (u_long)a.gid);
1499 		r = fchownat(AT_FDCWD, name, a.uid, a.gid,
1500 		    AT_SYMLINK_NOFOLLOW);
1501 		if (r == -1)
1502 			status = errno_to_portable(errno);
1503 	}
1504  out:
1505 	send_status(id, status);
1506 	free(name);
1507 }
1508 
1509 static void
process_extended_limits(uint32_t id)1510 process_extended_limits(uint32_t id)
1511 {
1512 	struct sshbuf *msg;
1513 	int r;
1514 	uint64_t nfiles = 0;
1515 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE)
1516 	struct rlimit rlim;
1517 #endif
1518 
1519 	debug("request %u: limits", id);
1520 
1521 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE)
1522 	if (getrlimit(RLIMIT_NOFILE, &rlim) != -1 && rlim.rlim_cur > 5)
1523 		nfiles = rlim.rlim_cur - 5; /* stdio(3) + syslog + spare */
1524 #endif
1525 
1526 	if ((msg = sshbuf_new()) == NULL)
1527 		fatal_f("sshbuf_new failed");
1528 	if ((r = sshbuf_put_u8(msg, SSH2_FXP_EXTENDED_REPLY)) != 0 ||
1529 	    (r = sshbuf_put_u32(msg, id)) != 0 ||
1530 	    /* max-packet-length */
1531 	    (r = sshbuf_put_u64(msg, SFTP_MAX_MSG_LENGTH)) != 0 ||
1532 	    /* max-read-length */
1533 	    (r = sshbuf_put_u64(msg, SFTP_MAX_READ_LENGTH)) != 0 ||
1534 	    /* max-write-length */
1535 	    (r = sshbuf_put_u64(msg, SFTP_MAX_MSG_LENGTH - 1024)) != 0 ||
1536 	    /* max-open-handles */
1537 	    (r = sshbuf_put_u64(msg, nfiles)) != 0)
1538 		fatal_fr(r, "compose");
1539 	send_msg(msg);
1540 	sshbuf_free(msg);
1541 }
1542 
1543 static void
process_extended_expand(uint32_t id)1544 process_extended_expand(uint32_t id)
1545 {
1546 	char cwd[PATH_MAX], resolvedname[PATH_MAX];
1547 	char *path, *npath;
1548 	int r;
1549 	Stat s;
1550 
1551 	if ((r = sshbuf_get_cstring(iqueue, &path, NULL)) != 0)
1552 		fatal_fr(r, "parse");
1553 	if (getcwd(cwd, sizeof(cwd)) == NULL) {
1554 		send_status(id, errno_to_portable(errno));
1555 		goto out;
1556 	}
1557 
1558 	debug3("request %u: expand, original \"%s\"", id, path);
1559 	if (path[0] == '\0') {
1560 		/* empty path */
1561 		free(path);
1562 		path = xstrdup(".");
1563 	} else if (*path == '~') {
1564 		/* ~ expand path */
1565 		/* Special-case for "~" and "~/" to respect homedir flag */
1566 		if (strcmp(path, "~") == 0) {
1567 			free(path);
1568 			path = xstrdup(cwd);
1569 		} else if (strncmp(path, "~/", 2) == 0) {
1570 			npath = xstrdup(path + 2);
1571 			free(path);
1572 			xasprintf(&path, "%s/%s", cwd, npath);
1573 			free(npath);
1574 		} else {
1575 			/* ~user expansions */
1576 			if (tilde_expand(path, pw->pw_uid, &npath) != 0) {
1577 				send_status_errmsg(id,
1578 				    errno_to_portable(ENOENT), "no such user");
1579 				goto out;
1580 			}
1581 			free(path);
1582 			path = npath;
1583 		}
1584 	} else if (*path != '/') {
1585 		/* relative path */
1586 		xasprintf(&npath, "%s/%s", cwd, path);
1587 		free(path);
1588 		path = npath;
1589 	}
1590 	verbose("expand \"%s\"", path);
1591 	if (sftp_realpath(path, resolvedname) == NULL) {
1592 		send_status(id, errno_to_portable(errno));
1593 		goto out;
1594 	}
1595 	attrib_clear(&s.attrib);
1596 	s.name = s.long_name = resolvedname;
1597 	send_names(id, 1, &s);
1598  out:
1599 	free(path);
1600 }
1601 
1602 static void
process_extended_copy_data(uint32_t id)1603 process_extended_copy_data(uint32_t id)
1604 {
1605 	u_char buf[64*1024];
1606 	int read_handle, read_fd, write_handle, write_fd;
1607 	uint64_t len, read_off, read_len, write_off;
1608 	int r, copy_until_eof, status = SSH2_FX_OP_UNSUPPORTED;
1609 	size_t ret;
1610 	struct stat st_read, st_write;
1611 
1612 	if ((r = get_handle(iqueue, &read_handle)) != 0 ||
1613 	    (r = sshbuf_get_u64(iqueue, &read_off)) != 0 ||
1614 	    (r = sshbuf_get_u64(iqueue, &read_len)) != 0 ||
1615 	    (r = get_handle(iqueue, &write_handle)) != 0 ||
1616 	    (r = sshbuf_get_u64(iqueue, &write_off)) != 0)
1617 		fatal_fr(r, "buffer error");
1618 
1619 	debug("request %u: copy-data from \"%s\" (handle %d) off %llu len %llu "
1620 	    "to \"%s\" (handle %d) off %llu",
1621 	    id, handle_to_name(read_handle), read_handle,
1622 	    (unsigned long long)read_off, (unsigned long long)read_len,
1623 	    handle_to_name(write_handle), write_handle,
1624 	    (unsigned long long)write_off);
1625 
1626 	/* For read length of 0, we read until EOF. */
1627 	if (read_len == 0) {
1628 		read_len = (uint64_t)-1 - read_off;
1629 		copy_until_eof = 1;
1630 	} else
1631 		copy_until_eof = 0;
1632 
1633 	/* Disallow reading & writing to the same handle, path or inode */
1634 	read_fd = handle_to_fd(read_handle);
1635 	write_fd = handle_to_fd(write_handle);
1636 	if (read_fd < 0 || write_fd < 0) {
1637 		error_f("bad read or write fd");
1638 		status = errno_to_portable(EBADF);
1639 		goto out;
1640 	}
1641 	if (fstat(read_fd, &st_read) != 0) {
1642 		status = errno_to_portable(errno);
1643 		error_f("fstat read_fd failed: %s", strerror(errno));
1644 		goto out;
1645 	}
1646 	if (fstat(write_fd, &st_write) != 0) {
1647 		status = errno_to_portable(errno);
1648 		error_f("fstat write_fd failed: %s", strerror(errno));
1649 		goto out;
1650 	}
1651 	if (read_handle == write_handle ||
1652 	    !strcmp(handle_to_name(read_handle), handle_to_name(write_handle)) ||
1653 	    (st_read.st_dev != 0 && st_read.st_ino != 0 &&
1654 	    st_read.st_dev == st_write.st_dev &&
1655 	    st_read.st_ino == st_write.st_ino)) {
1656 		error_f("refusing to read/write same file: "
1657 		    "read \"%s\" dev %lu ino %lu, write \"%s\" dev %lu ino %lu",
1658 		    handle_to_name(read_handle),
1659 		    (u_long)st_read.st_dev, (u_long)st_read.st_ino,
1660 		    handle_to_name(write_handle),
1661 		    (u_long)st_write.st_dev, (u_long)st_write.st_ino);
1662 		status = SSH2_FX_FAILURE;
1663 		goto out;
1664 	}
1665 
1666 	if (lseek(read_fd, read_off, SEEK_SET) < 0) {
1667 		status = errno_to_portable(errno);
1668 		error_f("read_seek failed");
1669 		goto out;
1670 	}
1671 
1672 	if ((handle_to_flags(write_handle) & O_APPEND) == 0 &&
1673 	    lseek(write_fd, write_off, SEEK_SET) < 0) {
1674 		status = errno_to_portable(errno);
1675 		error_f("write_seek failed");
1676 		goto out;
1677 	}
1678 
1679 	/* Process the request in chunks. */
1680 	while (read_len > 0 || copy_until_eof) {
1681 		len = MINIMUM(sizeof(buf), read_len);
1682 		read_len -= len;
1683 
1684 		ret = atomicio(read, read_fd, buf, len);
1685 		if (ret == 0 && errno == EPIPE) {
1686 			status = copy_until_eof ? SSH2_FX_OK : SSH2_FX_EOF;
1687 			break;
1688 		} else if (ret == 0) {
1689 			status = errno_to_portable(errno);
1690 			error_f("read failed: %s", strerror(errno));
1691 			break;
1692 		}
1693 		len = ret;
1694 		handle_update_read(read_handle, len);
1695 
1696 		ret = atomicio(vwrite, write_fd, buf, len);
1697 		if (ret != len) {
1698 			status = errno_to_portable(errno);
1699 			error("%s: write failed: %llu != %llu: %s", __func__,
1700 			    (unsigned long long)ret, (unsigned long long)len,
1701 			    strerror(errno));
1702 			break;
1703 		}
1704 		handle_update_write(write_handle, len);
1705 	}
1706 
1707 	if (read_len == 0)
1708 		status = SSH2_FX_OK;
1709 
1710  out:
1711 	send_status(id, status);
1712 }
1713 
1714 static void
process_extended_home_directory(uint32_t id)1715 process_extended_home_directory(uint32_t id)
1716 {
1717 	char *username;
1718 	struct passwd *user_pw;
1719 	int r;
1720 	Stat s;
1721 
1722 	if ((r = sshbuf_get_cstring(iqueue, &username, NULL)) != 0)
1723 		fatal_fr(r, "parse");
1724 
1725 	debug3("request %u: home-directory \"%s\"", id, username);
1726 	if (username[0] == '\0') {
1727 		user_pw = pw;
1728 	} else if ((user_pw = getpwnam(username)) == NULL) {
1729 		send_status(id, SSH2_FX_FAILURE);
1730 		goto out;
1731 	}
1732 
1733 	verbose("home-directory \"%s\"", user_pw->pw_dir);
1734 	attrib_clear(&s.attrib);
1735 	s.name = s.long_name = user_pw->pw_dir;
1736 	send_names(id, 1, &s);
1737  out:
1738 	free(username);
1739 }
1740 
1741 static void
process_extended_get_users_groups_by_id(uint32_t id)1742 process_extended_get_users_groups_by_id(uint32_t id)
1743 {
1744 	struct passwd *user_pw;
1745 	struct group *gr;
1746 	struct sshbuf *uids, *gids, *usernames, *groupnames, *msg;
1747 	int r;
1748 	u_int n, nusers = 0, ngroups = 0;
1749 	const char *name;
1750 
1751 	if ((usernames = sshbuf_new()) == NULL ||
1752 	    (groupnames = sshbuf_new()) == NULL ||
1753 	    (msg = sshbuf_new()) == NULL)
1754 		fatal_f("sshbuf_new failed");
1755 	if ((r = sshbuf_froms(iqueue, &uids)) != 0 ||
1756 	    (r = sshbuf_froms(iqueue, &gids)) != 0)
1757 		fatal_fr(r, "parse");
1758 	debug_f("uids len = %zu, gids len = %zu",
1759 	    sshbuf_len(uids), sshbuf_len(gids));
1760 	while (sshbuf_len(uids) != 0) {
1761 		if ((r = sshbuf_get_u32(uids, &n)) != 0)
1762 			fatal_fr(r, "parse inner uid");
1763 		user_pw = getpwuid((uid_t)n);
1764 		name = user_pw == NULL ? "" : user_pw->pw_name;
1765 		debug3_f("uid %u => \"%s\"", n, name);
1766 		if ((r = sshbuf_put_cstring(usernames, name)) != 0)
1767 			fatal_fr(r, "assemble uid reply");
1768 		nusers++;
1769 	}
1770 	while (sshbuf_len(gids) != 0) {
1771 		if ((r = sshbuf_get_u32(gids, &n)) != 0)
1772 			fatal_fr(r, "parse inner gid");
1773 		gr = getgrgid((gid_t)n);
1774 		name = gr == NULL ? "" : gr->gr_name;
1775 		debug3_f("gid %u => \"%s\"", n, name);
1776 		if ((r = sshbuf_put_cstring(groupnames, name)) != 0)
1777 			fatal_fr(r, "assemble gid reply");
1778 		ngroups++;
1779 	}
1780 	verbose("users-groups-by-id: %u users, %u groups", nusers, ngroups);
1781 
1782 	if ((r = sshbuf_put_u8(msg, SSH2_FXP_EXTENDED_REPLY)) != 0 ||
1783 	    (r = sshbuf_put_u32(msg, id)) != 0 ||
1784 	    (r = sshbuf_put_stringb(msg, usernames)) != 0 ||
1785 	    (r = sshbuf_put_stringb(msg, groupnames)) != 0)
1786 		fatal_fr(r, "compose");
1787 	send_msg(msg);
1788 
1789 	sshbuf_free(uids);
1790 	sshbuf_free(gids);
1791 	sshbuf_free(usernames);
1792 	sshbuf_free(groupnames);
1793 	sshbuf_free(msg);
1794 }
1795 
1796 static void
process_extended(uint32_t id)1797 process_extended(uint32_t id)
1798 {
1799 	char *request;
1800 	int r;
1801 	const struct sftp_handler *exthand;
1802 
1803 	if ((r = sshbuf_get_cstring(iqueue, &request, NULL)) != 0)
1804 		fatal_fr(r, "parse");
1805 	if ((exthand = extended_handler_byname(request)) == NULL) {
1806 		error("Unknown extended request \"%.100s\"", request);
1807 		send_status(id, SSH2_FX_OP_UNSUPPORTED);	/* MUST */
1808 	} else {
1809 		if (!request_permitted(exthand))
1810 			send_status(id, SSH2_FX_PERMISSION_DENIED);
1811 		else
1812 			exthand->handler(id);
1813 	}
1814 	free(request);
1815 }
1816 
1817 /* stolen from ssh-agent */
1818 
1819 static void
process(void)1820 process(void)
1821 {
1822 	u_int msg_len;
1823 	u_int buf_len;
1824 	u_int consumed;
1825 	u_char type;
1826 	const u_char *cp;
1827 	int i, r;
1828 	uint32_t id;
1829 
1830 	buf_len = sshbuf_len(iqueue);
1831 	if (buf_len < 5)
1832 		return;		/* Incomplete message. */
1833 	cp = sshbuf_ptr(iqueue);
1834 	msg_len = get_u32(cp);
1835 	if (msg_len > SFTP_MAX_MSG_LENGTH) {
1836 		error("bad message from %s local user %s",
1837 		    client_addr, pw->pw_name);
1838 		sftp_server_cleanup_exit(11);
1839 	}
1840 	if (buf_len < msg_len + 4)
1841 		return;
1842 	if ((r = sshbuf_consume(iqueue, 4)) != 0)
1843 		fatal_fr(r, "consume");
1844 	buf_len -= 4;
1845 	if ((r = sshbuf_get_u8(iqueue, &type)) != 0)
1846 		fatal_fr(r, "parse type");
1847 
1848 	switch (type) {
1849 	case SSH2_FXP_INIT:
1850 		process_init();
1851 		init_done = 1;
1852 		break;
1853 	case SSH2_FXP_EXTENDED:
1854 		if (!init_done)
1855 			fatal("Received extended request before init");
1856 		if ((r = sshbuf_get_u32(iqueue, &id)) != 0)
1857 			fatal_fr(r, "parse extended ID");
1858 		process_extended(id);
1859 		break;
1860 	default:
1861 		if (!init_done)
1862 			fatal("Received %u request before init", type);
1863 		if ((r = sshbuf_get_u32(iqueue, &id)) != 0)
1864 			fatal_fr(r, "parse ID");
1865 		for (i = 0; handlers[i].handler != NULL; i++) {
1866 			if (type == handlers[i].type) {
1867 				if (!request_permitted(&handlers[i])) {
1868 					send_status(id,
1869 					    SSH2_FX_PERMISSION_DENIED);
1870 				} else {
1871 					handlers[i].handler(id);
1872 				}
1873 				break;
1874 			}
1875 		}
1876 		if (handlers[i].handler == NULL)
1877 			error("Unknown message %u", type);
1878 	}
1879 	/* discard the remaining bytes from the current packet */
1880 	if (buf_len < sshbuf_len(iqueue)) {
1881 		error("iqueue grew unexpectedly");
1882 		sftp_server_cleanup_exit(255);
1883 	}
1884 	consumed = buf_len - sshbuf_len(iqueue);
1885 	if (msg_len < consumed) {
1886 		error("msg_len %u < consumed %u", msg_len, consumed);
1887 		sftp_server_cleanup_exit(255);
1888 	}
1889 	if (msg_len > consumed &&
1890 	    (r = sshbuf_consume(iqueue, msg_len - consumed)) != 0)
1891 		fatal_fr(r, "consume");
1892 }
1893 
1894 /* Cleanup handler that logs active handles upon normal exit */
1895 void
sftp_server_cleanup_exit(int i)1896 sftp_server_cleanup_exit(int i)
1897 {
1898 	if (pw != NULL && client_addr != NULL) {
1899 		handle_log_exit();
1900 		logit("session closed for local user %s from [%s]",
1901 		    pw->pw_name, client_addr);
1902 	}
1903 	_exit(i);
1904 }
1905 
1906 static void
sftp_server_usage(void)1907 sftp_server_usage(void)
1908 {
1909 	extern char *__progname;
1910 
1911 	fprintf(stderr,
1912 	    "usage: %s [-ehR] [-d start_directory] [-f log_facility] "
1913 	    "[-l log_level]\n\t[-P denied_requests] "
1914 	    "[-p allowed_requests] [-u umask]\n"
1915 	    "       %s -Q protocol_feature\n",
1916 	    __progname, __progname);
1917 	exit(1);
1918 }
1919 
1920 int
sftp_server_main(int argc,char ** argv,struct passwd * user_pw)1921 sftp_server_main(int argc, char **argv, struct passwd *user_pw)
1922 {
1923 	int i, r, in, out, ch, skipargs = 0, log_stderr = 0;
1924 	ssize_t len, olen;
1925 	SyslogFacility log_facility = SYSLOG_FACILITY_AUTH;
1926 	char *cp, *homedir = NULL, uidstr[32], buf[4*4096];
1927 	long mask;
1928 
1929 	extern char *optarg;
1930 	extern char *__progname;
1931 
1932 	__progname = ssh_get_progname(argv[0]);
1933 	log_init(__progname, log_level, log_facility, log_stderr);
1934 
1935 	pw = pwcopy(user_pw);
1936 
1937 	while (!skipargs && (ch = getopt(argc, argv,
1938 	    "d:f:l:P:p:Q:u:cehR")) != -1) {
1939 		switch (ch) {
1940 		case 'Q':
1941 			if (strcasecmp(optarg, "requests") != 0) {
1942 				fprintf(stderr, "Invalid query type\n");
1943 				exit(1);
1944 			}
1945 			for (i = 0; handlers[i].handler != NULL; i++)
1946 				printf("%s\n", handlers[i].name);
1947 			for (i = 0; extended_handlers[i].handler != NULL; i++)
1948 				printf("%s\n", extended_handlers[i].name);
1949 			exit(0);
1950 			break;
1951 		case 'R':
1952 			readonly = 1;
1953 			break;
1954 		case 'c':
1955 			/*
1956 			 * Ignore all arguments if we are invoked as a
1957 			 * shell using "sftp-server -c command"
1958 			 */
1959 			skipargs = 1;
1960 			break;
1961 		case 'e':
1962 			log_stderr = 1;
1963 			break;
1964 		case 'l':
1965 			log_level = log_level_number(optarg);
1966 			if (log_level == SYSLOG_LEVEL_NOT_SET)
1967 				error("Invalid log level \"%s\"", optarg);
1968 			break;
1969 		case 'f':
1970 			log_facility = log_facility_number(optarg);
1971 			if (log_facility == SYSLOG_FACILITY_NOT_SET)
1972 				error("Invalid log facility \"%s\"", optarg);
1973 			break;
1974 		case 'd':
1975 			cp = tilde_expand_filename(optarg, user_pw->pw_uid);
1976 			snprintf(uidstr, sizeof(uidstr), "%llu",
1977 			    (unsigned long long)pw->pw_uid);
1978 			homedir = percent_expand(cp, "d", user_pw->pw_dir,
1979 			    "u", user_pw->pw_name, "U", uidstr, (char *)NULL);
1980 			free(cp);
1981 			break;
1982 		case 'p':
1983 			if (request_allowlist != NULL)
1984 				fatal("Permitted requests already set");
1985 			request_allowlist = xstrdup(optarg);
1986 			break;
1987 		case 'P':
1988 			if (request_denylist != NULL)
1989 				fatal("Refused requests already set");
1990 			request_denylist = xstrdup(optarg);
1991 			break;
1992 		case 'u':
1993 			errno = 0;
1994 			mask = strtol(optarg, &cp, 8);
1995 			if (mask < 0 || mask > 0777 || *cp != '\0' ||
1996 			    cp == optarg || (mask == 0 && errno != 0))
1997 				fatal("Invalid umask \"%s\"", optarg);
1998 			(void)umask((mode_t)mask);
1999 			break;
2000 		case 'h':
2001 		default:
2002 			sftp_server_usage();
2003 		}
2004 	}
2005 
2006 	log_init(__progname, log_level, log_facility, log_stderr);
2007 
2008 	/*
2009 	 * On platforms where we can, avoid making /proc/self/{mem,maps}
2010 	 * available to the user so that sftp access doesn't automatically
2011 	 * imply arbitrary code execution access that will break
2012 	 * restricted configurations.
2013 	 */
2014 	platform_disable_tracing(1);	/* strict */
2015 
2016 	/* Drop any fine-grained privileges we don't need */
2017 	platform_pledge_sftp_server();
2018 
2019 	if ((cp = getenv("SSH_CONNECTION")) != NULL) {
2020 		client_addr = xstrdup(cp);
2021 		if ((cp = strchr(client_addr, ' ')) == NULL) {
2022 			error("Malformed SSH_CONNECTION variable: \"%s\"",
2023 			    getenv("SSH_CONNECTION"));
2024 			sftp_server_cleanup_exit(255);
2025 		}
2026 		*cp = '\0';
2027 	} else
2028 		client_addr = xstrdup("UNKNOWN");
2029 
2030 	logit("session opened for local user %s from [%s]",
2031 	    pw->pw_name, client_addr);
2032 
2033 	in = STDIN_FILENO;
2034 	out = STDOUT_FILENO;
2035 
2036 #ifdef HAVE_CYGWIN
2037 	setmode(in, O_BINARY);
2038 	setmode(out, O_BINARY);
2039 #endif
2040 
2041 	if ((iqueue = sshbuf_new()) == NULL)
2042 		fatal_f("sshbuf_new failed");
2043 	if ((oqueue = sshbuf_new()) == NULL)
2044 		fatal_f("sshbuf_new failed");
2045 
2046 	if (homedir != NULL) {
2047 		if (chdir(homedir) != 0) {
2048 			error("chdir to \"%s\" failed: %s", homedir,
2049 			    strerror(errno));
2050 		}
2051 	}
2052 
2053 	for (;;) {
2054 		struct pollfd pfd[2];
2055 
2056 		memset(pfd, 0, sizeof pfd);
2057 		pfd[0].fd = pfd[1].fd = -1;
2058 
2059 		/*
2060 		 * Ensure that we can read a full buffer and handle
2061 		 * the worst-case length packet it can generate,
2062 		 * otherwise apply backpressure by stopping reads.
2063 		 */
2064 		if ((r = sshbuf_check_reserve(iqueue, sizeof(buf))) == 0 &&
2065 		    (r = sshbuf_check_reserve(oqueue,
2066 		    SFTP_MAX_MSG_LENGTH)) == 0) {
2067 			pfd[0].fd = in;
2068 			pfd[0].events = POLLIN;
2069 		}
2070 		else if (r != SSH_ERR_NO_BUFFER_SPACE)
2071 			fatal_fr(r, "reserve");
2072 
2073 		olen = sshbuf_len(oqueue);
2074 		if (olen > 0) {
2075 			pfd[1].fd = out;
2076 			pfd[1].events = POLLOUT;
2077 		}
2078 
2079 		if (poll(pfd, 2, -1) == -1) {
2080 			if (errno == EINTR)
2081 				continue;
2082 			error("poll: %s", strerror(errno));
2083 			sftp_server_cleanup_exit(2);
2084 		}
2085 
2086 		/* copy stdin to iqueue */
2087 		if (pfd[0].revents & (POLLIN|POLLHUP)) {
2088 			len = read(in, buf, sizeof buf);
2089 			if (len == 0) {
2090 				debug("read eof");
2091 				sftp_server_cleanup_exit(0);
2092 			} else if (len == -1) {
2093 				if (errno != EAGAIN && errno != EINTR) {
2094 					error("read: %s", strerror(errno));
2095 					sftp_server_cleanup_exit(1);
2096 				}
2097 			} else if ((r = sshbuf_put(iqueue, buf, len)) != 0)
2098 				fatal_fr(r, "sshbuf_put");
2099 		}
2100 		/* send oqueue to stdout */
2101 		if (pfd[1].revents & (POLLOUT|POLLHUP)) {
2102 			len = write(out, sshbuf_ptr(oqueue), olen);
2103 			if (len == 0 || (len == -1 && errno == EPIPE)) {
2104 				debug("write eof");
2105 				sftp_server_cleanup_exit(0);
2106 			} else if (len == -1) {
2107 				sftp_server_cleanup_exit(1);
2108 				if (errno != EAGAIN && errno != EINTR) {
2109 					error("write: %s", strerror(errno));
2110 					sftp_server_cleanup_exit(1);
2111 				}
2112 			} else if ((r = sshbuf_consume(oqueue, len)) != 0)
2113 				fatal_fr(r, "consume");
2114 		}
2115 
2116 		/*
2117 		 * Process requests from client if we can fit the results
2118 		 * into the output buffer, otherwise stop processing input
2119 		 * and let the output queue drain.
2120 		 */
2121 		r = sshbuf_check_reserve(oqueue, SFTP_MAX_MSG_LENGTH);
2122 		if (r == 0)
2123 			process();
2124 		else if (r != SSH_ERR_NO_BUFFER_SPACE)
2125 			fatal_fr(r, "reserve");
2126 	}
2127 }
2128