Debian Codegraph @

clientserver.c

raw symbols SCIP
1 /*
2 * The socket based protocol for setting up a connection with rsyncd.
3 *
4 * Copyright (C) 1998-2001 Andrew Tridgell <[email protected]>
5 * Copyright (C) 2001-2002 Martin Pool <[email protected]>
6 * Copyright (C) 2002-2022 Wayne Davison
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, visit the http://fsf.org website.
20 */
21
22 #include "rsync.h"
23 #include "itypes.h"
24 #include "ifuncs.h"
25
26 extern int quiet;
27 extern int dry_run;
28 extern int output_motd;
29 extern int list_only;
30 extern int am_sender;
31 extern int am_server;
32 extern int am_daemon;
33 extern int am_chrooted;
34 extern int am_root;
35 extern int msgs2stderr;
36 extern int rsync_port;
37 extern int protect_args;
38 extern int ignore_errors;
39 extern int preserve_xattrs;
40 extern int kluge_around_eof;
41 extern int munge_symlinks;
42 extern int use_secure_symlinks;
43 extern int open_noatime;
44 extern int sanitize_paths;
45 extern int daemon_config_filter_file;
46 extern int numeric_ids;
47 extern int filesfrom_fd;
48 extern int remote_protocol;
49 extern int protocol_version;
50 extern int io_timeout;
51 extern int no_detach;
52 extern int write_batch;
53 extern int old_style_args;
54 extern int default_af_hint;
55 extern int logfile_format_has_i;
56 extern int logfile_format_has_o_or_i;
57 extern char *bind_address;
58 extern char *config_file;
59 extern char *logfile_format;
60 extern char *files_from;
61 extern char *tmpdir;
62 extern char *early_input_file;
63 extern struct chmod_mode_struct *chmod_modes;
64 extern filter_rule_list daemon_filter_list;
65 #ifdef ICONV_OPTION
66 extern char *iconv_opt;
67 extern iconv_t ic_send, ic_recv;
68 #endif
69 extern uid_t our_uid;
70 extern gid_t our_gid;
71
72 char *auth_user;
73 char *daemon_auth_choices;
74 /* read_args() enforces MAX_DAEMON_ARGS and reports "too many daemon arguments"
75 * before a daemon client can grow argv without bound. */
76 int read_only = 0;
77 int module_id = -1;
78 int pid_file_fd = -1;
79 int early_input_len = 0;
80 char *early_input = NULL;
81 pid_t namecvt_pid = 0;
82 struct chmod_mode_struct *daemon_chmod_modes;
83
84 #define EARLY_INPUT_CMD "#early_input="
85 #define EARLY_INPUT_CMDLEN (sizeof EARLY_INPUT_CMD - 1)
86
87 /* Fallback bound on each peer-driven daemon handshake phase when no positive
88 * "timeout" is configured. A module value can shorten the pre-auth and
89 * argument-read phases, but cannot extend either beyond this limit. */
90 #define DAEMON_HANDSHAKE_TIMEOUT 60
91
92 static int daemon_handshake_timeout(int module)
93 {
94 int timeout = lp_timeout(module);
95
96 /* "timeout" is parsed with atoi(), so negative values are possible. */
97 if (timeout <= 0 || timeout > DAEMON_HANDSHAKE_TIMEOUT)
98 timeout = DAEMON_HANDSHAKE_TIMEOUT;
99 return timeout;
100 }
101
102 /* module_dirlen is the length of the module_dir string when in daemon
103 * mode and module_dir is not "/"; otherwise 0. (Note that a chroot-
104 * enabled module can have a non-"/" module_dir these days.) */
105 char *module_dir = NULL;
106 unsigned int module_dirlen = 0;
107 /* An fd held open on the served module root, captured while the daemon is still
108 * positioned there (and privileged) -- so the sender's directory scan can be
109 * confined beneath the module by resolving module-relative paths against this fd,
110 * without re-walking (and re-permission-checking) the absolute module path as the
111 * dropped-privilege module uid. -1 when not a daemon or not yet captured. */
112 int module_dirfd = -1;
113
114 char *full_module_path;
115
116 static int rl_nulls = 0;
117 static int namecvt_fd_req = -1, namecvt_fd_ans = -1;
118
119 #ifdef HAVE_SIGACTION
120 static struct sigaction sigact;
121 #endif
122
123 static item_list gid_list = EMPTY_ITEM_LIST;
124
125 /* Used when "reverse lookup" is off. */
126 const char undetermined_hostname[] = "UNDETERMINED";
127
128 /**
129 * Run a client connected to an rsyncd. The alternative to this
130 * function for remote-shell connections is do_cmd().
131 *
132 * After negotiating which module to use and reading the server's
133 * motd, this hands over to client_run(). Telling the server the
134 * module will cause it to chroot/setuid/etc.
135 *
136 * Instead of doing a transfer, the client may at this stage instead
137 * get a listing of remote modules and exit.
138 *
139 * @return -1 for error in startup, or the result of client_run().
140 * Either way, it eventually gets passed to exit_cleanup().
141 **/
142 int start_socket_client(char *host, int remote_argc, char *remote_argv[],
143 int argc, char *argv[])
144 {
145 int fd, ret;
146 char *p, *user = NULL;
147
148 /* This is redundant with code in start_inband_exchange(), but this
149 * short-circuits a problem in the client before we open a socket,
150 * and the extra check won't hurt. */
151 if (**remote_argv == '/') {
152 rprintf(FERROR,
153 "ERROR: The remote path must start with a module name not a /\n");
154 return -1;
155 }
156
157 if ((p = strrchr(host, '@')) != NULL) {
158 user = host;
159 host = p+1;
160 *p = '\0';
161 }
162
163 fd = open_socket_out_wrapped(host, rsync_port, bind_address, default_af_hint);
164 if (fd == -1)
165 exit_cleanup(RERR_SOCKETIO);
166
167 #ifdef ICONV_CONST
168 setup_iconv();
169 #endif
170
171 ret = start_inband_exchange(fd, fd, user, remote_argc, remote_argv);
172
173 return ret ? ret : client_run(fd, fd, -1, argc, argv);
174 }
175
176 static int exchange_protocols(int f_in, int f_out, char *buf, size_t bufsiz, int am_client)
177 {
178 int remote_sub = -1;
179 int our_sub = get_subprotocol_version();
180
181 output_daemon_greeting(f_out, am_client);
182 if (!am_client) {
183 char *motd = lp_motd_file();
184 if (motd && *motd) {
185 /* 'motd file = PATH': motd content is sent to every client, so
186 * a planted symlink would leak the target's bytes. Refuse
187 * symlinks not owned by uid 0 or our euid. */
188 int motd_fd = open_no_attacker_symlinks(motd, O_RDONLY, 0);
189 FILE *f = motd_fd >= 0 ? fdopen(motd_fd, "r") : NULL;
190 if (!f && motd_fd >= 0) close(motd_fd);
191 while (f && !feof(f)) {
192 int len = fread(buf, 1, bufsiz - 1, f);
193 if (len > 0)
194 write_buf(f_out, buf, len);
195 }
196 if (f)
197 fclose(f);
198 write_sbuf(f_out, "\n");
199 }
200 }
201
202 /* This strips the \n. */
203 if (!read_line_old(f_in, buf, bufsiz, 0)) {
204 if (am_client)
205 rprintf(FERROR, "rsync: did not see server greeting\n");
206 return -1;
207 }
208
209 if (sscanf(buf, "@RSYNCD: %d.%d", &remote_protocol, &remote_sub) < 1) {
210 if (am_client)
211 rprintf(FERROR, "rsync: server sent \"%s\" rather than greeting\n", buf);
212 else
213 io_printf(f_out, "@ERROR: protocol startup error\n");
214 return -1;
215 }
216
217 if (remote_sub < 0) {
218 if (remote_protocol >= 30) {
219 if (am_client)
220 rprintf(FERROR, "rsync: the server omitted the subprotocol value: %s\n", buf);
221 else
222 io_printf(f_out, "@ERROR: your client omitted the subprotocol value: %s\n", buf);
223 return -1;
224 }
225 remote_sub = 0;
226 }
227
228 daemon_auth_choices = strchr(buf + 9, ' ');
229 if (daemon_auth_choices) {
230 char *cp;
231 daemon_auth_choices = strdup(daemon_auth_choices + 1);
232 if ((cp = strchr(daemon_auth_choices, '\n')) != NULL)
233 *cp = '\0';
234 } else if (remote_protocol > 31) {
235 if (am_client)
236 rprintf(FERROR, "rsync: the server omitted the digest name list: %s\n", buf);
237 else
238 io_printf(f_out, "@ERROR: your client omitted the digest name list: %s\n", buf);
239 return -1;
240 }
241
242 if (protocol_version > remote_protocol) {
243 protocol_version = remote_protocol;
244 if (remote_sub)
245 protocol_version--;
246 } else if (protocol_version == remote_protocol) {
247 if (remote_sub != our_sub)
248 protocol_version--;
249 }
250 #if SUBPROTOCOL_VERSION != 0
251 else if (protocol_version < remote_protocol) {
252 if (our_sub)
253 protocol_version--;
254 }
255 #endif
256
257 if (protocol_version >= 30)
258 rl_nulls = 1;
259
260 return 0;
261 }
262
263 int start_inband_exchange(int f_in, int f_out, const char *user, int argc, char *argv[])
264 {
265 int i, modlen;
266 char line[BIGPATHBUFLEN];
267 char *sargs[MAX_ARGS];
268 int sargc = 0;
269 char *p, *modname;
270
271 assert(argc > 0 && *argv != NULL);
272
273 if (**argv == '/') {
274 rprintf(FERROR,
275 "ERROR: The remote path must start with a module name\n");
276 return -1;
277 }
278
279 if (!(p = strchr(*argv, '/')))
280 modlen = strlen(*argv);
281 else
282 modlen = p - *argv;
283
284 modname = new_array(char, modlen+1+1); /* room for '/' & '\0' */
285 strlcpy(modname, *argv, modlen + 1);
286 modname[modlen] = '/';
287 modname[modlen+1] = '\0';
288
289 if (!user)
290 user = getenv("USER");
291 if (!user)
292 user = getenv("LOGNAME");
293
294 if (exchange_protocols(f_in, f_out, line, sizeof line, 1) < 0) {
295 free(modname);
296 return -1;
297 }
298
299 if (early_input_file) {
300 STRUCT_STAT st;
301 /* --early-input-file=PATH: refuse symlinks not owned by uid 0 or
302 * our euid anywhere in the path. */
303 int ei_fd = open_no_attacker_symlinks(early_input_file, O_RDONLY, 0);
304 FILE *f = ei_fd >= 0 ? fdopen(ei_fd, "rb") : NULL;
305 if (!f && ei_fd >= 0) close(ei_fd);
306 if (!f || do_fstat(fileno(f), &st) < 0) {
307 rsyserr(FERROR, errno, "failed to open %s", early_input_file);
308 if (f)
309 fclose(f);
310 free(modname);
311 return -1;
312 }
313 early_input_len = st.st_size;
314 if (early_input_len > (int)sizeof line) {
315 rprintf(FERROR, "%s is > %d bytes.\n", early_input_file, (int)sizeof line);
316 fclose(f);
317 free(modname);
318 return -1;
319 }
320 if (early_input_len > 0) {
321 io_printf(f_out, EARLY_INPUT_CMD "%d\n", early_input_len);
322 while (early_input_len > 0) {
323 int len;
324 if (feof(f)) {
325 rprintf(FERROR, "Early EOF in %s\n", early_input_file);
326 fclose(f);
327 free(modname);
328 return -1;
329 }
330 len = fread(line, 1, early_input_len, f);
331 if (len > 0) {
332 write_buf(f_out, line, len);
333 early_input_len -= len;
334 }
335 }
336 }
337 fclose(f);
338 }
339
340 server_options(sargs, &sargc);
341
342 if (sargc >= MAX_ARGS - 2)
343 goto arg_overflow;
344
345 sargs[sargc++] = ".";
346
347 if (!old_style_args)
348 snprintf(line, sizeof line, " %.*s/", modlen, modname);
349
350 while (argc > 0) {
351 if (sargc >= MAX_ARGS - 1) {
352 arg_overflow:
353 rprintf(FERROR, "internal: args[] overflowed in do_cmd()\n");
354 exit_cleanup(RERR_SYNTAX);
355 }
356 if (strncmp(*argv, modname, modlen) == 0 && argv[0][modlen] == '\0')
357 sargs[sargc++] = modname; /* we send "modname/" */
358 else {
359 char *arg = *argv;
360 int extra_chars = *arg == '-' ? 2 : 0; /* a leading dash needs a "./" prefix. */
361 /* If --old-args was not specified, make sure that the arg won't split at a mod name! */
362 if (!old_style_args && (p = strstr(arg, line)) != NULL) {
363 do {
364 extra_chars += 2;
365 } while ((p = strstr(p+1, line)) != NULL);
366 }
367 if (extra_chars) {
368 char *f = arg;
369 char *t = arg = new_array(char, strlen(arg) + extra_chars + 1);
370 if (*f == '-') {
371 *t++ = '.';
372 *t++ = '/';
373 }
374 while (*f) {
375 if (*f == ' ' && strncmp(f, line, modlen+2) == 0) {
376 *t++ = '[';
377 *t++ = *f++;
378 *t++ = ']';
379 } else
380 *t++ = *f++;
381 }
382 *t = '\0';
383 }
384 sargs[sargc++] = arg;
385 }
386 argv++;
387 argc--;
388 }
389
390 sargs[sargc] = NULL;
391
392 if (DEBUG_GTE(CMD, 1))
393 print_child_argv("sending daemon args:", sargs);
394
395 io_printf(f_out, "%.*s\n", modlen, modname);
396
397 /* Old servers may just drop the connection here,
398 rather than sending a proper EXIT command. Yuck. */
399 kluge_around_eof = list_only && protocol_version < 25 ? 1 : 0;
400
401 while (1) {
402 if (!read_line_old(f_in, line, sizeof line, 0)) {
403 rprintf(FERROR, "rsync: didn't get server startup line\n");
404 free(modname);
405 return -1;
406 }
407
408 if (strncmp(line,"@RSYNCD: AUTHREQD ",18) == 0) {
409 auth_client(f_out, user, line+18);
410 continue;
411 }
412
413 if (strcmp(line,"@RSYNCD: OK") == 0)
414 break;
415
416 if (strcmp(line,"@RSYNCD: EXIT") == 0) {
417 /* This is sent by recent versions of the
418 * server to terminate the listing of modules.
419 * We don't want to go on and transfer
420 * anything; just exit. */
421 exit(0);
422 }
423
424 if (strncmp(line, "@ERROR", 6) == 0) {
425 rprintf(FERROR, "%s\n", line);
426 /* This is always fatal; the server will now
427 * close the socket. */
428 free(modname);
429 return -1;
430 }
431
432 /* This might be a MOTD line or a module listing, but there is
433 * no way to differentiate it. The manpage mentions this. */
434 if (output_motd)
435 rprintf(FINFO, "%s\n", line);
436 }
437 kluge_around_eof = 0;
438
439 if (rl_nulls) {
440 for (i = 0; i < sargc; i++) {
441 if (!sargs[i]) /* stop at --secluded-args NULL */
442 break;
443 write_sbuf(f_out, sargs[i]);
444 write_byte(f_out, 0);
445 }
446 write_byte(f_out, 0);
447 } else {
448 for (i = 0; i < sargc; i++)
449 io_printf(f_out, "%s\n", sargs[i]);
450 write_sbuf(f_out, "\n");
451 }
452
453 if (protect_args)
454 send_protected_args(f_out, sargs);
455
456 if (protocol_version < 23) {
457 if (protocol_version == 22 || !am_sender)
458 io_start_multiplex_in(f_in);
459 }
460
461 free(modname);
462
463 return 0;
464 }
465
466 #if defined HAVE_SETENV || defined HAVE_PUTENV
467 static int read_arg_from_pipe(int fd, char *buf, int limit)
468 {
469 char *bp = buf, *eob = buf + limit - 1;
470
471 while (1) {
472 int got = read(fd, bp, 1);
473 if (got != 1) {
474 if (got < 0 && errno == EINTR)
475 continue;
476 return -1;
477 }
478 if (*bp == '\0')
479 break;
480 if (bp < eob)
481 bp++;
482 }
483 *bp = '\0';
484
485 return bp - buf;
486 }
487 #endif
488
489 void set_env_str(const char *var, const char *str)
490 {
491 #ifdef HAVE_SETENV
492 if (setenv(var, str, 1) < 0)
493 out_of_memory("set_env_str");
494 #else
495 #ifdef HAVE_PUTENV
496 char *mem;
497 if (asprintf(&mem, "%s=%s", var, str) < 0)
498 out_of_memory("set_env_str");
499 putenv(mem);
500 #else
501 (void)var;
502 (void)str;
503 #endif
504 #endif
505 }
506
507 #if defined HAVE_SETENV || defined HAVE_PUTENV
508
509 static void set_envN_str(const char *var, int num, const char *str)
510 {
511 #ifdef HAVE_SETENV
512 char buf[128];
513 (void)snprintf(buf, sizeof buf, "%s%d", var, num);
514 if (setenv(buf, str, 1) < 0)
515 out_of_memory("set_env_str");
516 #else
517 #ifdef HAVE_PUTENV
518 char *mem;
519 if (asprintf(&mem, "%s%d=%s", var, num, str) < 0)
520 out_of_memory("set_envN_str");
521 putenv(mem);
522 #endif
523 #endif
524 }
525
526 void set_env_num(const char *var, long num)
527 {
528 #ifdef HAVE_SETENV
529 char val[64];
530 (void)snprintf(val, sizeof val, "%ld", num);
531 if (setenv(var, val, 1) < 0)
532 out_of_memory("set_env_str");
533 #else
534 #ifdef HAVE_PUTENV
535 char *mem;
536 if (asprintf(&mem, "%s=%ld", var, num) < 0)
537 out_of_memory("set_env_num");
538 putenv(mem);
539 #endif
540 #endif
541 }
542
543 /* Used for "early exec", "pre-xfer exec", and the "name converter" script. */
544 static pid_t start_pre_exec(const char *cmd, int *arg_fd_ptr, int *error_fd_ptr)
545 {
546 int arg_fds[2], error_fds[2], arg_fd;
547 pid_t pid;
548
549 if ((error_fd_ptr && pipe(error_fds) < 0) || pipe(arg_fds) < 0 || (pid = fork()) < 0)
550 return (pid_t)-1;
551
552 if (pid == 0) {
553 char buf[BIGPATHBUFLEN];
554 int j, len, status;
555
556 if (error_fd_ptr) {
557 close(error_fds[0]);
558 set_blocking(error_fds[1]);
559 }
560
561 close(arg_fds[1]);
562 arg_fd = arg_fds[0];
563 set_blocking(arg_fd);
564
565 len = read_arg_from_pipe(arg_fd, buf, BIGPATHBUFLEN);
566 if (len <= 0)
567 _exit(1);
568 set_env_str("RSYNC_REQUEST", buf);
569
570 for (j = 0; ; j++) {
571 len = read_arg_from_pipe(arg_fd, buf, BIGPATHBUFLEN);
572 if (len <= 0) {
573 if (!len)
574 break;
575 _exit(1);
576 }
577 set_envN_str("RSYNC_ARG", j, buf);
578 }
579
580 dup2(arg_fd, STDIN_FILENO);
581 close(arg_fd);
582
583 if (error_fd_ptr) {
584 dup2(error_fds[1], STDOUT_FILENO);
585 close(error_fds[1]);
586 }
587
588 status = shell_exec(cmd);
589
590 gcov_flush();
591 if (!WIFEXITED(status))
592 _exit(1);
593 _exit(WEXITSTATUS(status));
594 }
595
596 if (error_fd_ptr) {
597 close(error_fds[1]);
598 *error_fd_ptr = error_fds[0];
599 set_blocking(error_fds[0]);
600 }
601
602 close(arg_fds[0]);
603 arg_fd = *arg_fd_ptr = arg_fds[1];
604 set_blocking(arg_fd);
605
606 return pid;
607 }
608
609 #endif
610
611 static void write_pre_exec_args(int write_fd, char *request, char **early_argv, char **argv, int exec_type)
612 {
613 int j = 0;
614
615 if (!request)
616 request = "(NONE)";
617
618 write_buf(write_fd, request, strlen(request)+1);
619 if (early_argv) {
620 for ( ; *early_argv; early_argv++)
621 write_buf(write_fd, *early_argv, strlen(*early_argv)+1);
622 j = 1; /* Skip arg0 name in argv. */
623 }
624 if (argv) {
625 for ( ; argv[j]; j++)
626 write_buf(write_fd, argv[j], strlen(argv[j])+1);
627 }
628 write_byte(write_fd, 0);
629
630 if (exec_type == 1 && early_input_len)
631 write_buf(write_fd, early_input, early_input_len);
632
633 if (exec_type != 2) /* the name converter needs this left open */
634 close(write_fd);
635 }
636
637 static char *finish_pre_exec(const char *desc, pid_t pid, int read_fd)
638 {
639 char buf[BIGPATHBUFLEN], *bp, *cr;
640 int j, status = -1, msglen = sizeof buf - 1;
641
642 if (read_fd >= 0) {
643 /* Read the stdout from the program. This it is only displayed
644 * to the user if the script also returns an error status. */
645 for (bp = buf, cr = buf; msglen > 0; msglen -= j) {
646 if ((j = read(read_fd, bp, msglen)) <= 0) {
647 if (j == 0)
648 break;
649 if (errno == EINTR)
650 continue;
651 break; /* Just ignore the read error for now... */
652 }
653 bp[j] = '\0';
654 while (1) {
655 if ((cr = strchr(cr, '\r')) == NULL) {
656 cr = bp + j;
657 break;
658 }
659 if (!cr[1])
660 break; /* wait for more data before we decide what to do */
661 if (cr[1] == '\n') {
662 memmove(cr, cr+1, j - (cr - bp));
663 j--;
664 } else
665 cr++;
666 }
667 bp += j;
668 }
669 *bp = '\0';
670
671 close(read_fd);
672 } else
673 *buf = '\0';
674
675 if (wait_process(pid, &status, 0) < 0
676 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
677 char *e;
678 if (asprintf(&e, "%s returned failure (%d)%s%s%s\n%s",
679 desc, status, status < 0 ? ": " : "",
680 status < 0 ? strerror(errno) : "",
681 *buf ? ":" : "", buf) < 0)
682 return "out_of_memory in finish_pre_exec\n";
683 return e;
684 }
685 return NULL;
686 }
687
688 static int path_failure(int f_out, const char *dir, BOOL was_chdir)
689 {
690 if (was_chdir)
691 rsyserr(FLOG, errno, "chdir %s failed", dir);
692 else
693 rprintf(FLOG, "normalize_path(%s) failed\n", dir);
694 io_printf(f_out, "@ERROR: chdir failed\n");
695 return -1;
696 }
697
698 static int add_a_group(int f_out, const char *gname)
699 {
700 gid_t gid, *gid_p;
701 if (!group_to_gid(gname, &gid, True)) {
702 rprintf(FLOG, "Invalid gid %s\n", gname);
703 io_printf(f_out, "@ERROR: invalid gid %s\n", gname);
704 return -1;
705 }
706 gid_p = EXPAND_ITEM_LIST(&gid_list, gid_t, -32);
707 *gid_p = gid;
708 return 0;
709 }
710
711 #ifdef HAVE_GETGROUPLIST
712 static int want_all_groups(int f_out, uid_t uid)
713 {
714 const char *err;
715 if ((err = getallgroups(uid, &gid_list)) != NULL) {
716 rsyserr(FLOG, errno, "%s", err);
717 io_printf(f_out, "@ERROR: %s\n", err);
718 return -1;
719 }
720 return 0;
721 }
722 #elif defined HAVE_INITGROUPS
723 static struct passwd *want_all_groups(int f_out, uid_t uid)
724 {
725 struct passwd *pw;
726 gid_t *gid_p;
727 if ((pw = getpwuid(uid)) == NULL) {
728 rsyserr(FLOG, errno, "getpwuid failed");
729 io_printf(f_out, "@ERROR: getpwuid failed\n");
730 return NULL;
731 }
732 /* Start with the default group and initgroups() will add the rest. */
733 gid_p = EXPAND_ITEM_LIST(&gid_list, gid_t, -32);
734 *gid_p = pw->pw_gid;
735 return pw;
736 }
737 #endif
738
739 static int rsync_module(int f_in, int f_out, int i, const char *addr, const char *host)
740 {
741 int argc;
742 char **argv, **orig_argv, **orig_early_argv, *module_chdir;
743 char line[BIGPATHBUFLEN];
744 #if defined HAVE_INITGROUPS && !defined HAVE_GETGROUPLIST
745 struct passwd *pw = NULL;
746 #endif
747 uid_t uid;
748 int set_uid;
749 char *p, *err_msg = NULL;
750 char *name = lp_name(i);
751 int use_chroot = lp_use_chroot(i); /* might be 1 (yes), 0 (no), or -1 (unset) */
752 int ret, pre_exec_arg_fd = -1, pre_exec_error_fd = -1;
753 int save_munge_symlinks;
754 pid_t pre_exec_pid = 0;
755 char *request = NULL;
756
757 set_env_str("RSYNC_MODULE_NAME", name);
758
759 #ifdef ICONV_OPTION
760 iconv_opt = lp_charset(i);
761 if (*iconv_opt)
762 setup_iconv();
763 iconv_opt = NULL;
764 #endif
765
766 /* If reverse lookup is disabled globally but enabled for this module,
767 * we need to do it now before the access check. */
768 if (host == undetermined_hostname && lp_reverse_lookup(i))
769 host = client_name(client_addr(f_in));
770 set_env_str("RSYNC_HOST_NAME", host);
771 set_env_str("RSYNC_HOST_ADDR", addr);
772
773 if (!allow_access(addr, &host, i)) {
774 rprintf(FLOG, "rsync denied on module %s from %s (%s)\n",
775 name, host, addr);
776 if (!lp_list(i))
777 io_printf(f_out, "@ERROR: Unknown module '%s'\n", name);
778 else {
779 io_printf(f_out,
780 "@ERROR: access denied to %s from %s (%s)\n",
781 name, host, addr);
782 }
783 return -1;
784 }
785
786 if (am_daemon > 0) {
787 rprintf(FLOG, "rsync allowed access on module %s from %s (%s)\n",
788 name, host, addr);
789 }
790
791 if (!claim_connection(lp_lock_file(i), lp_max_connections(i))) {
792 if (errno) {
793 rsyserr(FLOG, errno, "failed to open lock file %s",
794 lp_lock_file(i));
795 io_printf(f_out, "@ERROR: failed to open lock file\n");
796 } else {
797 rprintf(FLOG, "max connections (%d) reached\n",
798 lp_max_connections(i));
799 io_printf(f_out, "@ERROR: max connections (%d) reached -- try again later\n",
800 lp_max_connections(i));
801 }
802 return -1;
803 }
804
805 read_only = lp_read_only(i); /* may also be overridden by auth_server() */
806 /* The module is now known, so its local timeout policy can tighten the
807 * absolute deadline while the claimed slot is awaiting authentication. */
808 set_daemon_handshake_timeout(daemon_handshake_timeout(i));
809 auth_user = auth_server(f_in, f_out, i, host, addr, "@RSYNCD: AUTHREQD ");
810
811 if (!auth_user) {
812 io_printf(f_out, "@ERROR: auth failed on module %s\n", name);
813 return -1;
814 }
815 set_env_str("RSYNC_USER_NAME", auth_user);
816 /* Do not count local setup or operator hooks against a peer's read time.
817 * In particular, the post-xfer parent and pre-xfer/name-converter children
818 * are forked below and must never inherit an armed asynchronous deadline. */
819 set_daemon_handshake_timeout(0);
820
821 module_id = i;
822
823 if (lp_transfer_logging(module_id) && !logfile_format)
824 logfile_format = lp_log_format(module_id);
825 if (log_format_has(logfile_format, 'i'))
826 logfile_format_has_i = 1;
827 if (logfile_format_has_i || log_format_has(logfile_format, 'o'))
828 logfile_format_has_o_or_i = 1;
829
830 uid = MY_UID();
831 am_root = (uid == ROOT_UID);
832
833 p = *lp_uid(module_id) ? lp_uid(module_id) : am_root ? NOBODY_USER : NULL;
834 if (p) {
835 if (!user_to_uid(p, &uid, True)) {
836 rprintf(FLOG, "Invalid uid %s\n", p);
837 io_printf(f_out, "@ERROR: invalid uid %s\n", p);
838 return -1;
839 }
840 set_uid = 1;
841 } else
842 set_uid = 0;
843
844 p = *lp_gid(module_id) ? conf_strtok(lp_gid(module_id)) : NULL;
845 if (p) {
846 /* The "*" gid must be the first item in the list. */
847 if (strcmp(p, "*") == 0) {
848 #ifdef HAVE_GETGROUPLIST
849 if (want_all_groups(f_out, uid) < 0)
850 return -1;
851 #elif defined HAVE_INITGROUPS
852 if ((pw = want_all_groups(f_out, uid)) == NULL)
853 return -1;
854 #else
855 rprintf(FLOG, "This rsync does not support a gid of \"*\"\n");
856 io_printf(f_out, "@ERROR: invalid gid setting.\n");
857 return -1;
858 #endif
859 } else if (add_a_group(f_out, p) < 0)
860 return -1;
861 while ((p = conf_strtok(NULL)) != NULL) {
862 #if defined HAVE_INITGROUPS && !defined HAVE_GETGROUPLIST
863 if (pw) {
864 rprintf(FLOG, "This rsync cannot add groups after \"*\".\n");
865 io_printf(f_out, "@ERROR: invalid gid setting.\n");
866 return -1;
867 }
868 #endif
869 if (add_a_group(f_out, p) < 0)
870 return -1;
871 }
872 } else if (am_root) {
873 if (add_a_group(f_out, NOBODY_GROUP) < 0)
874 return -1;
875 }
876
877 module_dir = lp_path(module_id);
878 if (*module_dir == '\0') {
879 rprintf(FLOG, "No path specified for module %s\n", name);
880 io_printf(f_out, "@ERROR: no path setting.\n");
881 return -1;
882 }
883 if (use_chroot < 0) {
884 if (strstr(module_dir, "/./") != NULL)
885 use_chroot = 1; /* The module is expecting a chroot inner & outer path. */
886 else if (chroot("/") < 0) {
887 rprintf(FLOG, "chroot test failed: %s. "
888 "Switching 'use chroot' from unset to false.\n",
889 strerror(errno));
890 use_chroot = 0;
891 } else {
892 if (chdir("/") < 0)
893 rsyserr(FLOG, errno, "chdir(\"/\") failed");
894 use_chroot = 1;
895 }
896 }
897 if (use_chroot) {
898 if ((p = strstr(module_dir, "/./")) != NULL) {
899 *p = '\0'; /* Temporary... */
900 if (!(module_chdir = normalize_path(module_dir, True, NULL)))
901 return path_failure(f_out, module_dir, False);
902 *p = '/';
903 if (!(p = normalize_path(p + 2, True, &module_dirlen)))
904 return path_failure(f_out, strstr(module_dir, "/./"), False);
905 if (!(full_module_path = normalize_path(module_dir, False, NULL)))
906 full_module_path = module_dir;
907 module_dir = p;
908 } else {
909 if (!(module_chdir = normalize_path(module_dir, False, NULL)))
910 return path_failure(f_out, module_dir, False);
911 full_module_path = module_chdir;
912 module_dir = "/";
913 module_dirlen = 1;
914 }
915 } else {
916 if (!(module_chdir = normalize_path(module_dir, False, &module_dirlen)))
917 return path_failure(f_out, module_dir, False);
918 full_module_path = module_dir = module_chdir;
919 }
920 set_env_str("RSYNC_MODULE_PATH", full_module_path);
921
922 if (module_dirlen == 1) {
923 module_dirlen = 0;
924 set_filter_dir("/", 1);
925 } else
926 set_filter_dir(module_dir, module_dirlen);
927
928 /* Everything loaded from here to the end of the exclude block is the
929 * operator's own configuration, so it keeps the ownership walk without the
930 * module-confinement parse_filter_file() applies to peer-driven merges. */
931 daemon_config_filter_file = 1;
932
933 p = lp_filter(module_id);
934 parse_filter_str(&daemon_filter_list, p, rule_template(FILTRULE_WORD_SPLIT),
935 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3);
936
937 p = lp_include_from(module_id);
938 parse_filter_file(&daemon_filter_list, p, rule_template(FILTRULE_INCLUDE),
939 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES | XFLG_FATAL_ERRORS);
940
941 p = lp_include(module_id);
942 parse_filter_str(&daemon_filter_list, p,
943 rule_template(FILTRULE_INCLUDE | FILTRULE_WORD_SPLIT),
944 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES);
945
946 p = lp_exclude_from(module_id);
947 parse_filter_file(&daemon_filter_list, p, rule_template(0),
948 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES | XFLG_FATAL_ERRORS);
949
950 p = lp_exclude(module_id);
951 parse_filter_str(&daemon_filter_list, p, rule_template(FILTRULE_WORD_SPLIT),
952 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES);
953
954 daemon_config_filter_file = 0;
955
956 log_init(1);
957
958 #if defined HAVE_SETENV || defined HAVE_PUTENV
959 if ((*lp_early_exec(module_id) || *lp_prexfer_exec(module_id)
960 || *lp_postxfer_exec(module_id) || *lp_name_converter(module_id))
961 && !getenv("RSYNC_NO_XFER_EXEC")) {
962 set_env_num("RSYNC_PID", (long)getpid());
963
964 /* For post-xfer exec, fork a new process to run the rsync
965 * daemon while this process waits for the exit status and
966 * runs the indicated command at that point. */
967 if (*lp_postxfer_exec(module_id)) {
968 pid_t pid = fork();
969 if (pid < 0) {
970 rsyserr(FLOG, errno, "fork failed");
971 io_printf(f_out, "@ERROR: fork failed\n");
972 return -1;
973 }
974 if (pid) {
975 int status;
976 close(f_in);
977 if (f_out != f_in)
978 close(f_out);
979 if (wait_process(pid, &status, 0) < 0)
980 status = -1;
981 set_env_num("RSYNC_RAW_STATUS", status);
982 if (WIFEXITED(status))
983 status = WEXITSTATUS(status);
984 else
985 status = -1;
986 set_env_num("RSYNC_EXIT_STATUS", status);
987 if (shell_exec(lp_postxfer_exec(module_id)) < 0)
988 status = -1;
989 gcov_flush();
990 _exit(status);
991 }
992 }
993
994 /* For early exec, fork a child process to run the indicated
995 * command and wait for it to exit. */
996 if (*lp_early_exec(module_id)) {
997 int arg_fd;
998 pid_t pid = start_pre_exec(lp_early_exec(module_id), &arg_fd, NULL);
999 if (pid == (pid_t)-1) {
1000 rsyserr(FLOG, errno, "early exec preparation failed");
1001 io_printf(f_out, "@ERROR: early exec preparation failed\n");
1002 return -1;
1003 }
1004 write_pre_exec_args(arg_fd, NULL, NULL, NULL, 1);
1005 if (finish_pre_exec("early exec", pid, -1) != NULL) {
1006 rsyserr(FLOG, errno, "early exec failed");
1007 io_printf(f_out, "@ERROR: early exec failed\n");
1008 return -1;
1009 }
1010 }
1011
1012 /* For pre-xfer exec, fork a child process to run the indicated
1013 * command, though it first waits for the parent process to
1014 * send us the user's request via a pipe. */
1015 if (*lp_prexfer_exec(module_id)) {
1016 pre_exec_pid = start_pre_exec(lp_prexfer_exec(module_id), &pre_exec_arg_fd, &pre_exec_error_fd);
1017 if (pre_exec_pid == (pid_t)-1) {
1018 rsyserr(FLOG, errno, "pre-xfer exec preparation failed");
1019 io_printf(f_out, "@ERROR: pre-xfer exec preparation failed\n");
1020 return -1;
1021 }
1022 }
1023
1024 if (*lp_name_converter(module_id)) {
1025 namecvt_pid = start_pre_exec(lp_name_converter(module_id), &namecvt_fd_req, &namecvt_fd_ans);
1026 if (namecvt_pid == (pid_t)-1) {
1027 rsyserr(FLOG, errno, "name-converter exec preparation failed");
1028 io_printf(f_out, "@ERROR: name-converter exec preparation failed\n");
1029 return -1;
1030 }
1031 }
1032 }
1033 #endif
1034
1035 if (early_input) {
1036 free(early_input);
1037 early_input = NULL;
1038 }
1039
1040 if (use_chroot) {
1041 /* Cache timezone data before chroot makes /etc/localtime inaccessible */
1042 tzset();
1043 /* Flush gcov counters now: after chroot the build-tree .gcda
1044 * paths are unreachable, so everything this child has executed
1045 * so far (the whole rsync_module() pre-chroot path) would
1046 * otherwise be lost. Post-chroot coverage from this child is
1047 * still unrecordable -- accepted, documented in
1048 * testsuite/COVERAGE.md. */
1049 gcov_flush();
1050 if (chroot(module_chdir)) {
1051 rsyserr(FLOG, errno, "chroot(\"%s\") failed", module_chdir);
1052 io_printf(f_out, "@ERROR: chroot failed\n");
1053 return -1;
1054 }
1055 am_chrooted = 1;
1056 module_chdir = module_dir;
1057 }
1058
1059 if (!change_dir(module_chdir, CD_NORMAL))
1060 return path_failure(f_out, module_chdir, True);
1061 /* Pin the module root by identity now -- cwd is the served root and we are
1062 * still privileged -- so the sender's later directory scans resolve against
1063 * this fd rather than re-walking the absolute module path post-setuid. */
1064 #if defined HAVE_FDOPENDIR && defined O_DIRECTORY
1065 module_dirfd = open(".", O_RDONLY | O_DIRECTORY | O_CLOEXEC);
1066 #endif
1067 if (module_dirlen)
1068 sanitize_paths = 1;
1069
1070 if ((munge_symlinks = lp_munge_symlinks(module_id)) < 0)
1071 munge_symlinks = !use_chroot || module_dirlen;
1072 if (munge_symlinks) {
1073 STRUCT_STAT st;
1074 char prefix[SYMLINK_PREFIX_LEN]; /* NOT +1 ! */
1075 strlcpy(prefix, SYMLINK_PREFIX, sizeof prefix); /* trim the trailing slash */
1076 if (do_stat(prefix, &st) == 0 && S_ISDIR(st.st_mode)) {
1077 rprintf(FLOG, "Symlink munging is unsafe when a %s directory exists.\n",
1078 prefix);
1079 io_printf(f_out, "@ERROR: daemon security issue -- contact admin\n", name);
1080 exit_cleanup(RERR_UNSUPPORTED);
1081 }
1082 }
1083
1084 /* Enable secure symlink handling for any non-chrooted daemon module, and
1085 * for a chroot module with a /./ inner boundary (module_dirlen) -- there
1086 * the kernel chroot confines the outer path but not the inner module, so
1087 * the receiver finish/rename path must still resolve beneath the module
1088 * root. This prevents TOCTOU race attacks where an attacker could switch a
1089 * directory to a symlink between path validation and file open. Match the
1090 * gate in secure_relpath_active() (syscall.c) -- the protection has nothing
1091 * to do with symlink munging, so a module configured with "munge symlinks =
1092 * false" must still get the secure-open path. */
1093 use_secure_symlinks = am_daemon && (!am_chrooted || module_dirlen)
1094 && !symlink_optout_allowed();
1095
1096 if (gid_list.count) {
1097 gid_t *gid_array = gid_list.items;
1098 if (setgid(gid_array[0])) {
1099 rsyserr(FLOG, errno, "setgid %ld failed", (long)gid_array[0]);
1100 io_printf(f_out, "@ERROR: setgid failed\n");
1101 return -1;
1102 }
1103 #ifdef HAVE_SETGROUPS
1104 /* Set the group(s) we want to be active. */
1105 if (setgroups(gid_list.count, gid_array)) {
1106 rsyserr(FLOG, errno, "setgroups failed");
1107 io_printf(f_out, "@ERROR: setgroups failed\n");
1108 return -1;
1109 }
1110 #endif
1111 #if defined HAVE_INITGROUPS && !defined HAVE_GETGROUPLIST
1112 /* pw is set if the user wants all the user's groups. */
1113 if (pw && initgroups(pw->pw_name, pw->pw_gid) < 0) {
1114 rsyserr(FLOG, errno, "initgroups failed");
1115 io_printf(f_out, "@ERROR: initgroups failed\n");
1116 return -1;
1117 }
1118 #endif
1119 our_gid = MY_GID();
1120 }
1121
1122 if (set_uid) {
1123 if (setuid(uid) < 0
1124 #ifdef HAVE_SETEUID
1125 || seteuid(uid) < 0
1126 #endif
1127 ) {
1128 rsyserr(FLOG, errno, "setuid %ld failed", (long)uid);
1129 io_printf(f_out, "@ERROR: setuid failed\n");
1130 return -1;
1131 }
1132
1133 our_uid = MY_UID();
1134 am_root = (our_uid == ROOT_UID);
1135 }
1136
1137 if (lp_temp_dir(module_id) && *lp_temp_dir(module_id)) {
1138 tmpdir = lp_temp_dir(module_id);
1139 if (strlen(tmpdir) >= MAXPATHLEN - 10) {
1140 rprintf(FLOG,
1141 "the 'temp dir' value for %s is WAY too long -- ignoring.\n",
1142 name);
1143 tmpdir = NULL;
1144 }
1145 }
1146
1147 /* This deadline is checked only in the read path, so the preceding local
1148 * setup and hooks can take as long as necessary. Keep one absolute bound
1149 * across both read_args() calls: anonymous modules must not be able to pin
1150 * a max-connections slot by trickling an unterminated argument forever. */
1151 set_daemon_handshake_timeout(daemon_handshake_timeout(module_id));
1152 io_printf(f_out, "@RSYNCD: OK\n");
1153
1154 read_args(f_in, name, line, sizeof line, rl_nulls, 1, &argv, &argc, &request);
1155 orig_argv = argv;
1156
1157 save_munge_symlinks = munge_symlinks;
1158
1159 reset_output_levels(); /* future verbosity is controlled by client options */
1160 ret = parse_arguments(&argc, (const char ***) &argv);
1161 if (protect_args && ret) {
1162 orig_early_argv = orig_argv;
1163 protect_args = 2;
1164 read_args(f_in, name, line, sizeof line, 1, 0, &argv, &argc, &request);
1165 orig_argv = argv;
1166 ret = parse_arguments(&argc, (const char ***) &argv);
1167 } else
1168 orig_early_argv = NULL;
1169 set_daemon_handshake_timeout(0);
1170
1171 /* The default is to use the user's setting unless the module sets True or False. */
1172 if (lp_open_noatime(module_id) >= 0)
1173 open_noatime = lp_open_noatime(module_id);
1174
1175 munge_symlinks = save_munge_symlinks; /* The client mustn't control this. */
1176
1177 if (am_daemon > 0)
1178 msgs2stderr = 0; /* A non-rsh-run daemon doesn't have stderr for msgs. */
1179
1180 if (pre_exec_pid) {
1181 write_pre_exec_args(pre_exec_arg_fd, request, orig_early_argv, orig_argv, 0);
1182 err_msg = finish_pre_exec("pre-xfer exec", pre_exec_pid, pre_exec_error_fd);
1183 }
1184
1185 if (namecvt_pid)
1186 write_pre_exec_args(namecvt_fd_req, request, orig_early_argv, orig_argv, 2);
1187
1188 if (orig_early_argv)
1189 free(orig_early_argv);
1190
1191 am_server = 1; /* Don't let someone try to be tricky. */
1192 quiet = 0;
1193 if (lp_ignore_errors(module_id))
1194 ignore_errors = 1;
1195 if (write_batch < 0)
1196 dry_run = 1;
1197
1198 if (lp_fake_super(module_id)) {
1199 if (preserve_xattrs > 1)
1200 preserve_xattrs = 1;
1201 am_root = -1;
1202 } else if (am_root < 0) /* Treat --fake-super from client as --super. */
1203 am_root = 2;
1204
1205 if (filesfrom_fd == 0)
1206 filesfrom_fd = f_in;
1207
1208 if (request) {
1209 if (*auth_user) {
1210 rprintf(FLOG, "rsync %s %s from %s@%s (%s)\n",
1211 am_sender ? "on" : "to",
1212 request, auth_user, host, addr);
1213 } else {
1214 rprintf(FLOG, "rsync %s %s from %s (%s)\n",
1215 am_sender ? "on" : "to",
1216 request, host, addr);
1217 }
1218 free(request);
1219 }
1220
1221 #ifndef DEBUG
1222 /* don't allow the logs to be flooded too fast */
1223 limit_output_verbosity(lp_max_verbosity(module_id));
1224 #endif
1225
1226 if (protocol_version < 23 && (protocol_version == 22 || am_sender))
1227 io_start_multiplex_out(f_out);
1228 else if (!ret || err_msg) {
1229 /* We have to get I/O multiplexing started so that we can
1230 * get the error back to the client. This means getting
1231 * the protocol setup finished first in later versions. */
1232 setup_protocol(f_out, f_in);
1233 if (!am_sender) {
1234 /* Since we failed in our option parsing, we may not
1235 * have finished parsing that the client sent us a
1236 * --files-from option, so look for it manually.
1237 * Without this, the socket would be in the wrong
1238 * state for the upcoming error message. */
1239 if (!files_from) {
1240 int i;
1241 for (i = 0; i < argc; i++) {
1242 if (strncmp(argv[i], "--files-from", 12) == 0) {
1243 files_from = "";
1244 break;
1245 }
1246 }
1247 }
1248 if (files_from)
1249 write_byte(f_out, 0);
1250 }
1251 io_start_multiplex_out(f_out);
1252 }
1253
1254 if (!ret || err_msg) {
1255 if (err_msg) {
1256 while ((p = strchr(err_msg, '\n')) != NULL) {
1257 int len = p - err_msg + 1;
1258 rwrite(FERROR, err_msg, len, 0);
1259 err_msg += len;
1260 }
1261 if (*err_msg)
1262 rprintf(FERROR, "%s\n", err_msg);
1263 io_flush(MSG_FLUSH);
1264 } else
1265 option_error();
1266 msleep(400);
1267 exit_cleanup(RERR_UNSUPPORTED);
1268 }
1269
1270 #ifdef ICONV_OPTION
1271 if (!iconv_opt) {
1272 if (ic_send != (iconv_t)-1) {
1273 iconv_close(ic_send);
1274 ic_send = (iconv_t)-1;
1275 }
1276 if (ic_recv != (iconv_t)-1) {
1277 iconv_close(ic_recv);
1278 ic_recv = (iconv_t)-1;
1279 }
1280 }
1281 #endif
1282
1283 if (!numeric_ids
1284 && (use_chroot ? lp_numeric_ids(module_id) != False && !*lp_name_converter(module_id)
1285 : lp_numeric_ids(module_id) == True))
1286 numeric_ids = -1; /* Set --numeric-ids w/o breaking protocol. */
1287
1288 if (lp_timeout(module_id) && (!io_timeout || lp_timeout(module_id) < io_timeout))
1289 set_io_timeout(lp_timeout(module_id));
1290
1291 /* If we have some incoming/outgoing chmod changes, append them to
1292 * any user-specified changes (making our changes have priority).
1293 * We also get a pointer to just our changes so that a receiver
1294 * process can use them separately if --perms wasn't specified. */
1295 if (am_sender)
1296 p = lp_outgoing_chmod(module_id);
1297 else
1298 p = lp_incoming_chmod(module_id);
1299 if (*p && !(daemon_chmod_modes = parse_chmod(p, &chmod_modes))) {
1300 rprintf(FLOG, "Invalid \"%sing chmod\" directive: %s\n",
1301 am_sender ? "outgo" : "incom", p);
1302 }
1303
1304 start_server(f_in, f_out, argc, argv);
1305
1306 return 0;
1307 }
1308
1309 static BOOL namecvt_safe_token(const char *s);
1310
1311 BOOL namecvt_call(const char *cmd, const char **name_p, id_t *id_p)
1312 {
1313 char buf[1024];
1314 int got, len;
1315
1316 if (*name_p) {
1317 if (!namecvt_safe_token(*name_p)) {
1318 rprintf(FERROR, "invalid name-converter token: %s\n", *name_p);
1319 return False;
1320 }
1321 len = snprintf(buf, sizeof buf, "%s %s\n", cmd, *name_p);
1322 } else
1323 len = snprintf(buf, sizeof buf, "%s %ld\n", cmd, (long)*id_p);
1324 if (len >= (int)sizeof buf) {
1325 rprintf(FERROR, "namecvt_call() request was too large.\n");
1326 exit_cleanup(RERR_UNSUPPORTED);
1327 }
1328
1329 while ((got = write(namecvt_fd_req, buf, len)) != len) {
1330 if (got < 0 && errno == EINTR)
1331 continue;
1332 rprintf(FERROR, "Connection to name-converter failed.\n");
1333 exit_cleanup(RERR_SOCKETIO);
1334 }
1335
1336 if (!read_line_old(namecvt_fd_ans, buf, sizeof buf, 0))
1337 return False;
1338
1339 if (*name_p) {
1340 /* Name-to-id: an unknown name returns an empty line and atol("")=0
1341 * would map it to root, so validate strictly below (all digits, no
1342 * ERANGE, fits id_t). */
1343 const char *p;
1344 unsigned long v;
1345 if (!*buf)
1346 return False;
1347 for (p = buf; *p; p++) {
1348 if (*p < '0' || *p > '9')
1349 return False;
1350 }
1351 errno = 0;
1352 v = strtoul(buf, NULL, 10);
1353 if (errno == ERANGE || v > (unsigned long)(id_t)-1)
1354 return False;
1355 *id_p = (id_t)v;
1356 } else
1357 *name_p = strdup(buf);
1358
1359 return True;
1360 }
1361
1362 static BOOL namecvt_safe_token(const char *s)
1363 {
1364 for (; *s; s++) {
1365 unsigned char ch = (unsigned char)*s;
1366 if (ch < ' ' || ch == 0x7f)
1367 return False;
1368 }
1369 return True;
1370 }
1371
1372 /* send a list of available modules to the client. Don't list those
1373 with "list = False". */
1374 static void send_listing(int fd)
1375 {
1376 int n = lp_num_modules();
1377 int i;
1378
1379 for (i = 0; i < n; i++) {
1380 if (lp_list(i))
1381 io_printf(fd, "%-15s\t%s\n", lp_name(i), lp_comment(i));
1382 }
1383
1384 if (protocol_version >= 25)
1385 io_printf(fd,"@RSYNCD: EXIT\n");
1386 }
1387
1388 static int proxy_peer_allowed(int fd)
1389 {
1390 const char *host = undetermined_hostname;
1391 const char *addr = client_addr(fd);
1392
1393 if (!allow_proxy_protocol_peer(lp_proxy_protocol_hosts(), addr, &host)) {
1394 rprintf(FLOG, "proxy protocol rejected from untrusted peer %s (%s)\n", host, addr);
1395 return 0;
1396 }
1397 return 1;
1398 }
1399
1400 static int load_config(int globals_only)
1401 {
1402 if (!config_file) {
1403 if (am_daemon < 0 && am_root <= 0)
1404 config_file = RSYNCD_USERCONF;
1405 else
1406 config_file = RSYNCD_SYSCONF;
1407 }
1408 return lp_load(config_file, globals_only);
1409 }
1410
1411 /* this is called when a connection is established to a client
1412 and we want to start talking. The setup of the system is done from
1413 here */
1414 int start_daemon(int f_in, int f_out)
1415 {
1416 char line[1024];
1417 const char *addr, *host;
1418 char *p;
1419 int i;
1420
1421 /* At this point, am_server is only set for a daemon started via rsh.
1422 * Because am_server gets forced on soon, we'll set am_daemon to -1 as
1423 * a flag that can be checked later on to distinguish a normal daemon
1424 * from an rsh-run daemon. */
1425 if (am_server)
1426 am_daemon = -1;
1427
1428 io_set_sock_fds(f_in, f_out);
1429
1430 /* We must load the config file before calling any function that
1431 * might cause log-file output to occur. This ensures that the
1432 * "log file" param gets honored for the 2 non-forked use-cases
1433 * (when rsync is run by init and run by a remote shell). */
1434 if (!load_config(0))
1435 exit_cleanup(RERR_SYNTAX);
1436
1437 /* Bound the handshake before ANY peer input is read -- the PROXY-protocol
1438 * header below is peer-supplied too, and was previously unbounded. An
1439 * rsh-run daemon is not a listener and has no shared slot to exhaust. */
1440 if (am_daemon > 0)
1441 set_daemon_handshake_timeout(daemon_handshake_timeout(-1));
1442
1443 if (lp_proxy_protocol()) {
1444 if (!proxy_peer_allowed(f_in) || !read_proxy_protocol_header(f_in))
1445 return -1;
1446 }
1447
1448 /* Do reverse DNS lookup before chroot/setuid. The result is cached,
1449 * so the later client_name() call will use this cached value. This
1450 * ensures hostname-based ACLs work even when DNS is unavailable
1451 * after chroot.
1452 *
1453 * "reverse lookup" can be set globally OR per-module, so we also
1454 * scan each module: a deployment with "reverse lookup = no" in the
1455 * global section but "reverse lookup = yes" in a specific module
1456 * still triggers a post-chroot lookup at access-check time
1457 * (rsync_module() in this file), which would also fail in the
1458 * chroot and turn hostname-based deny rules into silent bypasses. */
1459 {
1460 int need_reverse = lp_reverse_lookup(-1);
1461 int j, num_modules = lp_num_modules();
1462 for (j = 0; !need_reverse && j < num_modules; j++) {
1463 if (lp_reverse_lookup(j))
1464 need_reverse = 1;
1465 }
1466 if (need_reverse)
1467 (void)client_name(client_addr(f_in));
1468 }
1469
1470 p = lp_daemon_chroot();
1471 if (*p) {
1472 log_init(0); /* Make use we've initialized syslog before chrooting. */
1473 tzset();
1474 if (chroot(p) < 0) {
1475 rsyserr(FLOG, errno, "daemon chroot(\"%s\") failed", p);
1476 return -1;
1477 }
1478 /* Deliberately do NOT set am_chrooted here. am_chrooted
1479 * gates the per-module symlink-race defenses
1480 * (secure_relative_open() and the do_*_at() wrappers in
1481 * syscall.c) and means "the kernel is enforcing path
1482 * confinement at the module boundary". The daemon chroot
1483 * confines path resolution to the daemon-chroot directory,
1484 * not to any individual module path -- modules sharing the
1485 * daemon chroot are still distinguishable filesystem
1486 * subtrees and a sender-controlled symlink in module A
1487 * could redirect a syscall to module B (or to other files
1488 * inside the daemon chroot) without the per-module
1489 * defenses. Leave am_chrooted=0 here so secure_relative_open()
1490 * still fires for "use chroot = no" modules. */
1491 if (chdir("/") < 0) {
1492 rsyserr(FLOG, errno, "daemon chdir(\"/\") failed");
1493 return -1;
1494 }
1495 }
1496 p = lp_daemon_gid();
1497 if (*p) {
1498 gid_t gid;
1499 if (!group_to_gid(p, &gid, True)) {
1500 rprintf(FLOG, "Invalid daemon gid: %s\n", p);
1501 return -1;
1502 }
1503 if (setgid(gid) < 0) {
1504 rsyserr(FLOG, errno, "Unable to set group to daemon gid %ld", (long)gid);
1505 return -1;
1506 }
1507 our_gid = MY_GID();
1508 }
1509 p = lp_daemon_uid();
1510 if (*p) {
1511 uid_t uid;
1512 if (!user_to_uid(p, &uid, True)) {
1513 rprintf(FLOG, "Invalid daemon uid: %s\n", p);
1514 return -1;
1515 }
1516 if (setuid(uid) < 0) {
1517 rsyserr(FLOG, errno, "Unable to set user to daemon uid %ld", (long)uid);
1518 return -1;
1519 }
1520 our_uid = MY_UID();
1521 am_root = (our_uid == ROOT_UID);
1522 }
1523
1524 addr = client_addr(f_in);
1525 host = lp_reverse_lookup(-1) ? client_name(addr) : undetermined_hostname;
1526 rprintf(FLOG, "connect from %s (%s)\n", host, addr);
1527
1528 if (am_daemon > 0) {
1529 set_socket_options(f_in, "SO_KEEPALIVE");
1530 set_nonblocking(f_in);
1531 }
1532
1533
1534 if (exchange_protocols(f_in, f_out, line, sizeof line, 0) < 0)
1535 return -1;
1536
1537 line[0] = 0;
1538 if (!read_line_old(f_in, line, sizeof line, 0))
1539 return -1;
1540
1541 if (strncmp(line, EARLY_INPUT_CMD, EARLY_INPUT_CMDLEN) == 0) {
1542 early_input_len = strtol(line + EARLY_INPUT_CMDLEN, NULL, 10);
1543 if (early_input_len <= 0 || early_input_len > BIGPATHBUFLEN) {
1544 io_printf(f_out, "@ERROR: invalid early_input length\n");
1545 return -1;
1546 }
1547 early_input = new_array(char, early_input_len);
1548 read_buf(f_in, early_input, early_input_len);
1549
1550 if (!read_line_old(f_in, line, sizeof line, 0))
1551 return -1;
1552 }
1553
1554 if (!*line || strcmp(line, "#list") == 0) {
1555 rprintf(FLOG, "module-list request from %s (%s)\n",
1556 host, addr);
1557 send_listing(f_out);
1558 return -1;
1559 }
1560
1561 if (*line == '#') {
1562 /* it's some sort of command that I don't understand */
1563 io_printf(f_out, "@ERROR: Unknown command '%s'\n", line);
1564 return -1;
1565 }
1566
1567 if ((i = lp_number(line)) < 0) {
1568 rprintf(FLOG, "unknown module '%s' tried from %s (%s)\n",
1569 line, host, addr);
1570 io_printf(f_out, "@ERROR: Unknown module '%s'\n", line);
1571 return -1;
1572 }
1573
1574 #ifdef HAVE_SIGACTION
1575 sigact.sa_flags = SA_NOCLDSTOP;
1576 #endif
1577 SIGACTION(SIGCHLD, remember_children);
1578
1579 return rsync_module(f_in, f_out, i, addr, host);
1580 }
1581
1582 static void create_pid_file(void)
1583 {
1584 char *pid_file = lp_pid_file();
1585 char pidbuf[32];
1586 STRUCT_STAT st1, st2;
1587 char *fail = NULL;
1588 const char *base = pid_file;
1589 int pdfd = -1;
1590
1591 if (!pid_file || !*pid_file)
1592 return;
1593
1594 #ifdef O_NOFOLLOW
1595 #define SAFE_NOFOLLOW O_NOFOLLOW
1596 #else
1597 #define SAFE_NOFOLLOW 0
1598 #endif
1599
1600 #ifdef AT_FDCWD
1601 /* Pin the parent directory so the existence check, open and re-stat below
1602 * all resolve the leaf against one stable directory inode, removing the
1603 * lstat->open path race. The parent is operator-configured and trusted, so
1604 * it is opened following symlinks (e.g. a /var/run -> /run); only the leaf
1605 * is opened/checked O_NOFOLLOW (the do_*_atfd wrappers force that). */
1606 {
1607 const char *slash = strrchr(pid_file, '/');
1608 char dirbuf[MAXPATHLEN];
1609 const char *dir = ".";
1610 if (slash) {
1611 size_t dlen = slash == pid_file ? 1 : (size_t)(slash - pid_file);
1612 if (dlen >= sizeof dirbuf) {
1613 rprintf(FLOG, "pid file path is too long: %s\n", pid_file);
1614 exit_cleanup(RERR_FILEIO);
1615 }
1616 memcpy(dirbuf, pid_file, dlen);
1617 dirbuf[dlen] = '\0';
1618 dir = dirbuf;
1619 base = slash + 1;
1620 }
1621 if ((pdfd = do_open(dir, O_RDONLY|O_DIRECTORY, 0)) < 0) {
1622 rsyserr(FLOG, errno, "failed to open pid-file directory \"%s\"", dir);
1623 exit_cleanup(RERR_FILEIO);
1624 }
1625 }
1626 #define PID_LSTAT(stp) do_lstat_atfd(pdfd, base, stp)
1627 #define PID_UNLINK() do_unlink_atfd(pdfd, base, 0)
1628 #define PID_OPEN() do_open_atfd(pdfd, base, O_RDWR|O_CREAT, 0664)
1629 #else
1630 #define PID_LSTAT(stp) do_lstat(base, stp)
1631 #define PID_UNLINK() unlink(base)
1632 #define PID_OPEN() do_open(base, O_RDWR|O_CREAT|SAFE_NOFOLLOW, 0664)
1633 #endif
1634
1635 /* These tests make sure that a temp-style lock dir is handled safely. */
1636 st1.st_mode = 0;
1637 if (PID_LSTAT(&st1) == 0 && !S_ISREG(st1.st_mode) && PID_UNLINK() < 0)
1638 fail = "unlink";
1639 else if ((pid_file_fd = PID_OPEN()) < 0)
1640 fail = S_ISREG(st1.st_mode) ? "open" : "create";
1641 else if (!lock_range(pid_file_fd, 0, 4))
1642 fail = "lock";
1643 else if (do_fstat(pid_file_fd, &st1) < 0)
1644 fail = "fstat opened";
1645 else if (st1.st_size > (int)sizeof pidbuf)
1646 fail = "find small";
1647 else if (PID_LSTAT(&st2) < 0)
1648 fail = "lstat";
1649 else if (!S_ISREG(st1.st_mode))
1650 fail = "avoid file overwrite race for";
1651 else if (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
1652 fail = "verify stat info for";
1653 #ifdef HAVE_FTRUNCATE
1654 else if (do_ftruncate(pid_file_fd, 0) < 0)
1655 fail = "truncate";
1656 #endif
1657 else {
1658 pid_t pid = getpid();
1659 int len = snprintf(pidbuf, sizeof pidbuf, "%d\n", (int)pid);
1660 #ifndef HAVE_FTRUNCATE
1661 /* What can we do with a too-long file and no truncate? I guess we'll add extra newlines. */
1662 while (len < st1.st_size) /* We already verified that st_size chars fits in the buffer. */
1663 pidbuf[len++] = '\n';
1664 /* We don't need the buffer to end in a '\0' (and we may not have room to add it). */
1665 #endif
1666 if (write(pid_file_fd, pidbuf, len) != len)
1667 fail = "write";
1668 cleanup_set_pid(pid); /* Mark the file for removal on exit, even if the write failed. */
1669 }
1670
1671 #undef PID_LSTAT
1672 #undef PID_UNLINK
1673 #undef PID_OPEN
1674 #undef SAFE_NOFOLLOW
1675 if (pdfd >= 0)
1676 close(pdfd);
1677
1678 if (fail) {
1679 char msg[1024];
1680 snprintf(msg, sizeof msg, "failed to %s pid file %s: %s\n",
1681 fail, pid_file, strerror(errno));
1682 fputs(msg, stderr);
1683 rprintf(FLOG, "%s", msg);
1684 exit_cleanup(RERR_FILEIO);
1685 }
1686
1687 /* The file is left open so that the lock remains valid. It is closed in our forked child procs. */
1688 }
1689
1690 /* Become a daemon, discarding the controlling terminal. */
1691 static void become_daemon(void)
1692 {
1693 int i;
1694 pid_t pid = fork();
1695
1696 if (pid) {
1697 if (pid < 0) {
1698 fprintf(stderr, "failed to fork: %s\n", strerror(errno));
1699 exit_cleanup(RERR_FILEIO);
1700 }
1701 gcov_flush();
1702 _exit(0);
1703 }
1704
1705 create_pid_file();
1706
1707 /* detach from the terminal */
1708 #ifdef HAVE_SETSID
1709 setsid();
1710 #elif defined TIOCNOTTY
1711 i = open("/dev/tty", O_RDWR);
1712 if (i >= 0) {
1713 ioctl(i, (int)TIOCNOTTY, (char *)0);
1714 close(i);
1715 }
1716 #endif
1717 /* make sure that stdin, stdout an stderr don't stuff things
1718 * up (library functions, for example) */
1719 for (i = 0; i < 3; i++) {
1720 close(i);
1721 open("/dev/null", O_RDWR);
1722 }
1723 }
1724
1725 int daemon_main(void)
1726 {
1727 if (is_a_socket(STDIN_FILENO)) {
1728 int i;
1729
1730 /* we are running via inetd - close off stdout and
1731 * stderr so that library functions (and getopt) don't
1732 * try to use them. Redirect them to /dev/null */
1733 for (i = 1; i < 3; i++) {
1734 close(i);
1735 open("/dev/null", O_RDWR);
1736 }
1737
1738 return start_daemon(STDIN_FILENO, STDIN_FILENO);
1739 }
1740
1741 if (!load_config(1)) {
1742 fprintf(stderr, "Failed to parse config file: %s\n", config_file);
1743 exit_cleanup(RERR_SYNTAX);
1744 }
1745 set_dparams(0);
1746
1747 /* "proxy protocol = true" with no trusted-proxy list rejects every
1748 * connection as an untrusted proxy peer (fail-closed). That is intended,
1749 * but silent at startup, so warn the operator while stderr is still open. */
1750 if (lp_proxy_protocol()
1751 && (!lp_proxy_protocol_hosts() || !*lp_proxy_protocol_hosts())) {
1752 rprintf(FWARNING,
1753 "\"proxy protocol = true\" but \"proxy protocol hosts\" is unset:"
1754 " all connections will be rejected as untrusted proxy peers."
1755 " Set \"proxy protocol hosts\" to your trusted proxy's address.\n");
1756 }
1757
1758 if (no_detach)
1759 create_pid_file();
1760 else
1761 become_daemon();
1762
1763 if (rsync_port == 0 && (rsync_port = lp_rsync_port()) == 0)
1764 rsync_port = RSYNC_PORT;
1765 if (bind_address == NULL && *lp_bind_address())
1766 bind_address = lp_bind_address();
1767
1768 log_init(0);
1769
1770 rprintf(FLOG, "rsyncd version %s starting, listening on port %d\n",
1771 rsync_version(), rsync_port);
1772 /* TODO: If listening on a particular address, then show that
1773 * address too. In fact, why not just do getnameinfo on the
1774 * local address??? */
1775
1776 start_accept_loop(rsync_port, start_daemon);
1777 return -1;
1778 }