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