Skip to content
3 changes: 3 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 9 additions & 3 deletions log.c
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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;
Expand All @@ -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();
Expand Down
11 changes: 11 additions & 0 deletions options.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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 */
Expand Down Expand Up @@ -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";
Expand Down
12 changes: 11 additions & 1 deletion support/rrsync
Original file line number Diff line number Diff line change
Expand Up @@ -525,14 +525,19 @@ 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
if args.no_del:
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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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')
Expand Down Expand Up @@ -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()
Expand Down
23 changes: 20 additions & 3 deletions support/rrsync.1.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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`

Expand Down
90 changes: 78 additions & 12 deletions syscall.c
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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;
Expand All @@ -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();
Expand Down Expand Up @@ -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
Expand All @@ -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);
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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;
}
Expand All @@ -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;
Expand Down Expand Up @@ -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;
}
Expand All @@ -794,21 +822,59 @@ 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
* O_RDONLY directory endpoint, this accepts a searchable but unreadable
* 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
Expand Down Expand Up @@ -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) {
Expand All @@ -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;
Expand Down Expand Up @@ -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))
Expand Down
Loading