diff --git a/NEWS.md b/NEWS.md index 0c72e47a3..035fbba32 100644 --- a/NEWS.md +++ b/NEWS.md @@ -4,6 +4,9 @@ - Allow daemon modules to apply PAM account policy after rsync authentication. Both build-time support and the module setting are disabled by default. +- Let rrsync administrators require a server-side transfer log outside the + restricted directory with `-log FILE`. Refuse transfers when the log cannot + be opened and report later log write failures. - Reduce directory lookups when linking unchanged regular files with non-daemon `--link-dest` transfers. Reuse checked receiver and basis directories. - Reuse checked directories for ordinary scans and file reads beneath a diff --git a/log.c b/log.c index be6299edf..a875353ec 100644 --- a/log.c +++ b/log.c @@ -59,6 +59,7 @@ extern char *auth_user; extern char *stdout_format; extern char *logfile_format; extern char *logfile_name; +extern char *rrsync_logfile_name; #ifdef ICONV_CONST extern iconv_t ic_chck; #endif @@ -162,7 +163,8 @@ static void exit_log_write_error(FILE *stream, int error) if (len > 0 && (size_t)len < sizeof message) { if (logfile_fp && stream != logfile_fp && !ferror(logfile_fp)) logit(LOG_ERR, message, (size_t)len); - else if (stream != stderr && !am_server && !am_daemon) + else if (stream != stderr + && ((!am_server && !am_daemon) || (rrsync_logfile_name && stream == logfile_fp))) fputs(message, stderr); } exit_cleanup(RERR_MESSAGEIO); @@ -254,8 +256,8 @@ static void logfile_open(void) * attacker-writable dirs; a planted symlink could redirect root's log * into e.g. /root/.ssh/authorized_keys. Refuse symlinks not owned by * uid 0 or our euid. */ - int fd = open_no_attacker_symlinks(logfile_name, - O_WRONLY | O_APPEND | O_CREAT, 0644); + int fd = rrsync_logfile_name ? open_rrsync_logfile(logfile_name) + : open_no_attacker_symlinks(logfile_name, O_WRONLY | O_APPEND | O_CREAT, 0644); int open_errno; logfile_fp = fd >= 0 && do_fstat(fd, &st) == 0 ? fdopen(fd, "a") : NULL; @@ -266,6 +268,10 @@ static void logfile_open(void) if (logfile_fp) { logfile_regular = S_ISREG(st.st_mode); logfile_filter = select_logfile_filter(); + } else if (rrsync_logfile_name) { + logfile_name = logfile_format = NULL; + rsyserr(FERROR, open_errno, "failed to open required log file"); + exit_cleanup(RERR_MESSAGEIO); } else { /* Rsync falls back to using syslog on failure. */ syslog_init(); diff --git a/options.c b/options.c index 637dcd9e8..79dd9f271 100644 --- a/options.c +++ b/options.c @@ -198,6 +198,7 @@ char *basis_dir[MAX_BASIS_DIRS+1]; char *config_file = NULL; char *shell_cmd = NULL; char *logfile_name = NULL; +char *rrsync_logfile_name = NULL; char *logfile_format = NULL; char *stdout_format = NULL; char *password_file = NULL; @@ -805,6 +806,7 @@ static struct poptOption long_options[] = { {"no-prune-empty-dirs",0,POPT_ARG_VAL, &prune_empty_dirs, 0, 0, 0 }, {"no-m", 0, POPT_ARG_VAL, &prune_empty_dirs, 0, 0, 0 }, {"log-file", 0, POPT_ARG_STRING, &logfile_name, 0, 0, 0 }, + {"rrsync-log-file", 0, POPT_ARG_STRING | POPT_ARGFLAG_DOC_HIDDEN, &rrsync_logfile_name, 0, 0, 0 }, {"log-file-format", 0, POPT_ARG_STRING, &logfile_format, 0, 0, 0 }, {"out-format", 0, POPT_ARG_STRING, &stdout_format, 0, 0, 0 }, {"log-format", 0, POPT_ARG_STRING, &stdout_format, 0, 0, 0 }, /* DEPRECATED */ @@ -2635,6 +2637,15 @@ int parse_arguments(int *argc_p, const char ***argv_p) if (stdout_format_has_i || log_format_has(stdout_format, 'o')) stdout_format_has_o_or_i = 1; + if (rrsync_logfile_name) { + if (!am_server || am_daemon || confine_rootlen <= 1 + || *rrsync_logfile_name != '/' || logfile_name || logfile_format) { + snprintf(err_buf, sizeof err_buf, "invalid restricted server log configuration\n"); + return 0; + } + logfile_name = rrsync_logfile_name; + } + if (logfile_name && !am_daemon) { if (!logfile_format) { logfile_format = "%i %n%L"; diff --git a/support/rrsync b/support/rrsync index 7afa1fcb3..bc134923a 100755 --- a/support/rrsync +++ b/support/rrsync @@ -525,6 +525,11 @@ def main(): die("sending to read-only server is not allowed") if args.wo and am_sender: die("reading from write-only server is not allowed") + if args.log is not None: + if not args.log: + die("empty -log FILE") + if args.dir == '/': + die("-log cannot be used when DIR is /") if args.wo or not am_sender: long_opts['sender'] = -1 @@ -532,7 +537,7 @@ def main(): for opt in long_opts: if opt.startswith(('remove', 'delete')): long_opts[opt] = -1 - if args.ro: + if args.ro or args.log is not None: long_opts['log-file'] = -1 global short_disabled @@ -567,6 +572,7 @@ def main(): log_fh = safe_open_logfile() + log_path = os.path.join(os.getcwd(), args.log) if args.log is not None else None try: os.chdir(args.dir) except OSError as e: @@ -679,6 +685,9 @@ def main(): if args.no_overwrite: rsync_opts.append('--ignore-existing') + if log_path is not None: + rsync_opts.append('--rrsync-log-file=' + log_path) + if not rsync_args: if dropped_missing_args: die('nothing to transfer: all source args are missing') @@ -1049,6 +1058,7 @@ if __name__ == '__main__': arg_parser.add_argument('-no-del', action='store_true', help="Disable rsync's --delete* and --remove* options.") arg_parser.add_argument('-no-lock', action='store_true', help="Avoid the single-run (per-user) lock check.") arg_parser.add_argument('-no-overwrite', action='store_true', help="Prevent overwriting existing files by enforcing --ignore-existing") + arg_parser.add_argument('-log', metavar='FILE', help="Write server-side transfer records to FILE.") arg_parser.add_argument('-help', '-h', action='help', help="Output this help message and exit.") arg_parser.add_argument('dir', metavar='DIR', help="The restricted directory to use.") args = arg_parser.parse_args() diff --git a/support/rrsync.1.md b/support/rrsync.1.md index 1eefb1cc6..b32621a49 100644 --- a/support/rrsync.1.md +++ b/support/rrsync.1.md @@ -5,7 +5,7 @@ rrsync - a script to setup restricted rsync users via ssh logins ## SYNOPSIS ``` -rrsync [-ro|-wo] [-munge] [-absolute] [-no-del] [-no-lock] [-no-overwrite] DIR +rrsync [-ro|-wo] [-munge] [-absolute] [-no-del] [-no-lock] [-no-overwrite] [-log FILE] DIR ``` The single non-option argument specifies the restricted _DIR_ to use. It can be @@ -91,6 +91,22 @@ The remainder of this manpage is dedicated to using the rrsync script. Avoid the single-run (per-user) lock check. Useful with [`-munge`](#opt). +0. `-log FILE` + + Record server-side transfers and deletions in FILE. A relative FILE is + resolved from rrsync's initial working directory. The log must be a regular + file outside DIR; the path cannot pass through DIR even when it later + leaves by `..` or a symlink. An existing log is appended without changing + its permissions. A new log is created with mode 0600, subject to the + process umask. The client's `--log-file` is refused while `-log` is set. + + The transfer is refused if the log cannot be opened securely. A later log + write failure makes rsync exit with an error, but files transferred before + that failure are not rolled back. Keep hard-link and bind-mount aliases of + the log outside the client's reach; path traversal cannot identify every + such alias. This option is unavailable when DIR is `/` or the platform + lacks the required no-follow directory operations. + 0. `-no-overwrite` Enforce `--ignore-existing` on the server. Prevents overwriting existing @@ -103,8 +119,9 @@ The remainder of this manpage is dedicated to using the rrsync script. replacing whatever has appeared at that name since the check), and backup mode (`-b`, `--backup-dir`, whose published backup replaces whatever already occupies the backup name). Resumable uploads with an explicit - `--partial-dir`, `--delay-updates`, `--delay-symlinks`, and server-side - logging are therefore unavailable under this option. + `--partial-dir`, `--delay-updates` and `--delay-symlinks` are therefore + unavailable under this option. Administrator-controlled `-log` remains + available because its log stays outside the restricted dir. 0. `-help`, `-h` diff --git a/syscall.c b/syscall.c index 105be0568..1cdd05493 100644 --- a/syscall.c +++ b/syscall.c @@ -439,6 +439,16 @@ static int open_operator_leaf(int dfd, const char *name, int flags, mode_t mode) fd = openat(dfd, name, (flags & ~O_CREAT) | O_NOFOLLOW, mode); return fd; } + +/* rrsync starts the server in DIR, so its cwd pins DIR even if it is renamed. */ +static int is_restricted_directory(int fd, const STRUCT_STAT *restricted) +{ + STRUCT_STAT st; + + if (fstat(fd, &st) < 0) + return -1; + return st.st_dev == restricted->st_dev && st.st_ino == restricted->st_ino; +} #endif /* Open an operator-supplied path, refusing to traverse any symlink (parent or @@ -456,8 +466,10 @@ static int open_operator_leaf(int dfd, const char *name, int flags, mode_t mode) * unavailable. */ /* Core walk. When out_abs is non-NULL and the path resolves to a directory * (O_DIRECTORY), the resolved absolute path is copied there -- owner_walk_parent - * uses it to filter-check the (otherwise unchecked) leaf basename. */ -static int ona_open(const char *path, int flags, mode_t mode, char *out_abs, size_t out_cap) + * uses it to filter-check the (otherwise unchecked) leaf basename. A non-NULL + * restricted root excludes that directory from the walk for a required log. */ +static int ona_open(const char *path, int flags, mode_t mode, char *out_abs, size_t out_cap, + const STRUCT_STAT *restricted) { #if defined AT_FDCWD && defined O_NOFOLLOW && defined O_DIRECTORY const int dir_traverse_flags = directory_traverse_flags() | O_CLOEXEC; @@ -468,7 +480,7 @@ static int ona_open(const char *path, int flags, mode_t mode, char *out_abs, siz /* Opted out (local --insecure-links, or a daemon module with "insecure * links = yes"): restore the legacy symlink-following open. */ - if (symlink_optout_allowed()) + if (symlink_optout_allowed() && !restricted) return open(path, flags, mode); const uid_t trusted_uid = geteuid(); @@ -538,6 +550,10 @@ static int ona_open(const char *path, int flags, mode_t mode, char *out_abs, siz memmove(remaining, p, strlen(p) + 1); #endif is_anchored = 1; + } else if (restricted) { + /* A required log must start from an opened absolute root. */ + errno = EINVAL; + return -1; } int loops = 40; /* SYMLOOP_MAX-ish; breaks symlink cycles. Counts symlink @@ -547,6 +563,14 @@ static int ona_open(const char *path, int flags, mode_t mode, char *out_abs, siz int saved_errno = 0; while (*remaining) { + if (restricted) { + int enters_root = is_restricted_directory(dfd, restricted); + if (enters_root != 0) { + saved_errno = enters_root < 0 ? errno : EPERM; + goto out; + } + } + /* Peel one component off the front of `remaining`. */ char *slash = strchr(remaining, '/'); size_t comp_len = slash ? (size_t)(slash - remaining) : strlen(remaining); @@ -584,7 +608,7 @@ static int ona_open(const char *path, int flags, mode_t mode, char *out_abs, siz saved_errno = errno; goto out; } - if (!pin_transit && abspath_outside_confinement(abspath, 1)) { + if (!restricted && !pin_transit && abspath_outside_confinement(abspath, 1)) { saved_errno = ELOOP; goto out; } @@ -713,11 +737,15 @@ static int ona_open(const char *path, int flags, mode_t mode, char *out_abs, siz /* Non-symlink. */ if (is_last) { + if (restricted && !S_ISREG(comp_mode)) { + saved_errno = EINVAL; + goto out; + } if (abspath_step(abspath, sizeof abspath, comp, comp_len) < 0) { saved_errno = errno; goto out; } - if (!pin_transit && abspath_outside_confinement(abspath, 1)) { + if (!restricted && !pin_transit && abspath_outside_confinement(abspath, 1)) { saved_errno = ELOOP; goto out; } @@ -742,7 +770,7 @@ static int ona_open(const char *path, int flags, mode_t mode, char *out_abs, siz if (next >= 0) close(next); goto out; } - if (!pin_transit && abspath_outside_confinement(abspath, 0)) { + if (!restricted && !pin_transit && abspath_outside_confinement(abspath, 0)) { saved_errno = ELOOP; if (next >= 0) close(next); goto out; @@ -773,7 +801,7 @@ static int ona_open(const char *path, int flags, mode_t mode, char *out_abs, siz * an O_PATH fd is sufficient for traversal and fchdir but not operations * such as fchmod. */ if (flags & O_DIRECTORY) { - if (!pin_transit && abspath_outside_confinement(abspath, 1)) { + if (!restricted && !pin_transit && abspath_outside_confinement(abspath, 1)) { saved_errno = ELOOP; goto out; } @@ -794,13 +822,51 @@ static int ona_open(const char *path, int flags, mode_t mode, char *out_abs, siz #else /* Pre-AT_FDCWD / no O_NOFOLLOW systems: best-effort fallback. */ (void)out_abs; (void)out_cap; + if (restricted) { + errno = ENOTSUP; + return -1; + } return open(path, flags, mode); #endif } int open_no_attacker_symlinks(const char *path, int flags, mode_t mode) { - return ona_open(path, flags, mode, NULL, 0); + return ona_open(path, flags, mode, NULL, 0, NULL); +} + +int open_rrsync_logfile(const char *path) +{ +#if defined AT_FDCWD && defined O_NOFOLLOW && defined O_DIRECTORY + STRUCT_STAT restricted, log_stat; + char cwd[MAXPATHLEN]; + int fd; + + if (!path || *path != '/' || !confine_root || confine_rootlen <= 1 + || !getcwd(cwd, sizeof cwd) || strcmp(cwd, confine_root) != 0) { + errno = EINVAL; + return -1; + } + if (fstatat(AT_FDCWD, ".", &restricted, 0) < 0) + return -1; + fd = ona_open(path, O_WRONLY | O_APPEND | O_CREAT | O_NONBLOCK | O_NOCTTY | O_CLOEXEC, + 0600, NULL, 0, &restricted); + if (fd < 0) + return -1; + if (fstat(fd, &log_stat) == 0) { + if (S_ISREG(log_stat.st_mode)) + return fd; + errno = EINVAL; + } + int saved_errno = errno; + close(fd); + errno = saved_errno; + return -1; +#else + (void)path; + errno = ENOTSUP; + return -1; +#endif } /* Open a directory for traversal or as *at()/fchdir() authority. Unlike an @@ -808,7 +874,7 @@ int open_no_attacker_symlinks(const char *path, int flags, mode_t mode) * directory when the kernel provides a safe search-only descriptor. */ int open_no_attacker_symlinks_dirfd(const char *path) { - return ona_open(path, directory_traverse_flags(), 0, NULL, 0); + return ona_open(path, directory_traverse_flags(), 0, NULL, 0, NULL); } /* When set, the do_*_at() wrappers resolve their path as an OPERATOR-supplied @@ -839,7 +905,7 @@ static int owner_walk_parent_with_length(const char *path, const char **bname, *bname = slash ? slash + 1 : path; pabs[0] = '\0'; if (!slash) - dfd = ona_open(".", flags, 0, pabs, sizeof pabs); + dfd = ona_open(".", flags, 0, pabs, sizeof pabs, NULL); else { dlen = slash == path ? 1 : (size_t)(slash - path); /* "/x" -> parent "/" */ if (dlen >= sizeof dir) { @@ -848,7 +914,7 @@ static int owner_walk_parent_with_length(const char *path, const char **bname, } memcpy(dir, path, dlen); dir[dlen] = '\0'; - dfd = ona_open(dir, flags, 0, pabs, sizeof pabs); + dfd = ona_open(dir, flags, 0, pabs, sizeof pabs, NULL); } if (dfd < 0) return -1; @@ -1008,7 +1074,7 @@ static void retain_basis_root(const char *basis, const char *path, size_t path_l if (basis_parents[0].fd >= 0 && basis_parents[1].fd >= 0) return; resolved[0] = '\0'; - fd = ona_open(basis, directory_traverse_flags() | O_CLOEXEC, 0, resolved, sizeof resolved); + fd = ona_open(basis, directory_traverse_flags() | O_CLOEXEC, 0, resolved, sizeof resolved, NULL); if (fd < 0) return; if (*resolved && basis_fd_cacheable(fd)) diff --git a/testsuite/tests/rrsync/rrsync-transfer-log.py b/testsuite/tests/rrsync/rrsync-transfer-log.py new file mode 100644 index 000000000..1ded77ff4 --- /dev/null +++ b/testsuite/tests/rrsync/rrsync-transfer-log.py @@ -0,0 +1,134 @@ +#!/usr/bin/env python3 + +import os +import shlex +import stat +import subprocess +import sys + +from fixtures.rrsync import patched_rrsync, rrsync_shell, rsync_wrapper +from harness import TestContext, requires, run +from harness.results import test_fail +from harness.rsync import forced_protocol, rsync_argv + + +def check_record(path, tag, name): + lines = path.read_text().splitlines() + if not any(tag in line and line.endswith(' ' + name) for line in lines): + test_fail(f'{name}: missing {tag!r} record in {path.name}: {lines!r}') + + +@requires(transports={'pipe'}, mutates={'filesystem', 'process'}, tags={'rrsync'}) +def test(context: TestContext): + base = context.scratch + source, restricted = base / 'source', base / 'restricted' + (source / 'sub').mkdir(parents=True) + restricted.mkdir() + (source / 'sub' / 'file').write_bytes(b'payload\n') + log = base / 'transfer log' + log.write_text('previous record\n') + log.chmod(0o600) + + rsync = base / 'rsync-under-test' + rsync_wrapper(rsync) + wrapper = patched_rrsync(base, rsync_path=str(rsync)) + shell = base / 'remote-shell' + + def transfer(*argv, flags=('-wo', '-no-lock'), logfile=log, + root=restricted, pull=False, expect=None, preexec_fn=None): + options = (*flags, '-log', str(logfile)) if logfile is not None else flags + rrsync_shell(shell, wrapper, root, *options) + operands = ('dummy:', f'{base / "download"}/') if pull else (f'{source}/', 'dummy:') + result = subprocess.run( + rsync_argv('-rI', *argv, '-e', shlex.quote(str(shell)), *operands), + cwd=base, capture_output=True, text=True, timeout=20, + preexec_fn=preexec_fn) + if expect is None: + if result.returncode: + test_fail(f'transfer failed ({result.returncode}): {result.stderr}') + elif not result.returncode or expect not in result.stderr: + test_fail(f'expected {expect!r}, got {result.returncode}: {result.stderr}') + return result + + transfer('-q', flags=('-wo',)) + if (restricted / 'sub' / 'file').read_bytes() != b'payload\n': + test_fail('logged upload did not preserve file contents') + check_record(log, '>f', 'sub/file') + + file_list = base / 'list' + file_list.write_text('sub/file\n') + transfer(f'--files-from={file_list}', flags=('-ro',), pull=True, logfile=log.name) + if (base / 'download' / 'sub' / 'file').read_bytes() != b'payload\n': + test_fail('logged pull with a local file list did not select the file') + check_record(log, '