Skip to content

Commit 7d19e3d

Browse files
committed
rrsync: fix forced transfer logging
1 parent 3cd6a4b commit 7d19e3d

5 files changed

Lines changed: 288 additions & 183 deletions

File tree

‎log.c‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -173,8 +173,7 @@ static void logfile_open(void)
173173
* attacker-writable dirs; a planted symlink could redirect root's log
174174
* into e.g. /root/.ssh/authorized_keys. Refuse symlinks not owned by
175175
* uid 0 or our euid. */
176-
int fd = open_no_attacker_symlinks(logfile_name,
177-
O_WRONLY | O_APPEND | O_CREAT, 0644);
176+
int fd = open_log_file(logfile_name, O_WRONLY | O_APPEND | O_CREAT, 0644);
178177
logfile_fp = fd >= 0 ? fdopen(fd, "a") : NULL;
179178
if (!logfile_fp && fd >= 0)
180179
close(fd);

‎support/rrsync‎

Lines changed: 39 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -490,13 +490,11 @@ def safe_open_logfile():
490490
return os.fdopen(fd, 'a')
491491

492492
def resolve_log_path(path, dir_st):
493-
"""Resolve the -log FILE one component at a time, as the kernel does.
494-
495-
Refuse it if any step enters DIR (by device and inode, so a bind mount of
496-
DIR counts too): from there the client decides where the path leads, even
497-
when the final path is outside DIR."""
493+
"""Resolve symlinks before .. and reject paths through DIR."""
498494
todo = [c for c in path.split('/') if c]
499-
done = '/'
495+
if path.endswith('/'):
496+
todo.append('.')
497+
done = '//' if path.startswith('//') and not path.startswith('///') else '/'
500498
hops = 0
501499
while todo:
502500
comp = todo.pop(0)
@@ -508,43 +506,40 @@ def resolve_log_path(path, dir_st):
508506
cand = os.path.join(done, comp)
509507
try:
510508
st = os.lstat(cand)
511-
except FileNotFoundError:
512-
return os.path.join(cand, *todo) # the open below creates or fails
509+
except FileNotFoundError as e:
510+
if not todo:
511+
return cand
512+
die("cannot resolve the -log FILE", cand + ':', e.strerror)
513513
except OSError as e:
514514
die("cannot resolve the -log FILE", cand + ':', e.strerror)
515515
if stat.S_ISLNK(st.st_mode):
516+
if st.st_uid not in (0, os.geteuid()):
517+
die("untrusted symlink in -log FILE:", cand)
516518
hops += 1
517519
if hops > 40:
518520
die("too many symlinks in the -log FILE path")
519-
target = os.readlink(cand)
521+
try:
522+
target = os.readlink(cand)
523+
except OSError as e:
524+
die("cannot resolve the -log FILE", cand + ':', e.strerror)
520525
if target.startswith('/'):
521-
done = '/'
522-
todo = [c for c in target.split('/') if c] + todo
526+
done = '//' if target.startswith('//') and not target.startswith('///') else '/'
527+
todo = [c for c in target.split('/') if c] + (['.'] if target.endswith('/') else []) + todo
523528
continue
524529
if os.path.samestat(st, dir_st):
525530
die("the -log FILE must be outside the restricted directory")
531+
if todo:
532+
try:
533+
os.stat(os.path.join(cand, '.'))
534+
except OSError as e:
535+
die("cannot resolve the -log FILE", cand + ':', e.strerror)
526536
done = cand
527537
return done
528538

529539
def main():
530540
if not os.path.isdir(args.dir):
531541
die("Restricted directory does not exist!")
532542

533-
if args.log:
534-
if args.dir == '/':
535-
die("-log cannot be used when DIR is /")
536-
args.log = resolve_log_path(args.log, os.stat(args.dir))
537-
# Opened here so a log that cannot be written stops the transfer, and
538-
# handed to rsync as the open file where rrsync pins paths.
539-
try:
540-
fd = os.open(args.log, os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_NOFOLLOW, 0o644)
541-
except OSError as e:
542-
die("cannot open the -log FILE", args.log + ':', e.strerror)
543-
make_inheritable(fd)
544-
pinned_fds.append(fd)
545-
if HAVE_PROC_SELF_FD:
546-
args.log = '/proc/self/fd/%d' % fd
547-
548543
# The format of the environment variables set by sshd:
549544
# SSH_ORIGINAL_COMMAND:
550545
# rsync --server -vlogDtpre.iLsfxCIvu --etc . ARG # push
@@ -725,6 +720,20 @@ def main():
725720
rsync_opts.append('--ignore-existing')
726721

727722
if args.log:
723+
if args.dir == '/':
724+
die("-log cannot be used when DIR is /")
725+
resolved_log = resolve_log_path(args.log, os.stat(args.dir))
726+
fd = None
727+
try:
728+
flags = os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_NONBLOCK | getattr(os, 'O_NOFOLLOW', 0)
729+
fd = os.open(resolved_log, flags, 0o644)
730+
if not stat.S_ISREG(os.fstat(fd).st_mode):
731+
die("-log FILE must be a regular file")
732+
except OSError as e:
733+
die("cannot open the -log FILE", args.log + ':', e.strerror)
734+
finally:
735+
if fd is not None:
736+
os.close(fd)
728737
rsync_opts.append('--log-file=' + args.log)
729738

730739
if not rsync_args:
@@ -1085,9 +1094,10 @@ if __name__ == '__main__':
10851094
args.dir = os.path.realpath(args.dir)
10861095
args.dir_slash = args.dir + '/'
10871096
args.dir_slash_len = len(args.dir_slash)
1088-
if args.log:
1089-
# rsync opens it after the chdir into DIR.
1090-
args.log = os.path.abspath(args.log)
1097+
if args.log is not None:
1098+
if not args.log:
1099+
die("empty -log FILE")
1100+
args.log = os.path.join(os.getcwd(), args.log)
10911101
if args.ro:
10921102
args.no_del = True
10931103
elif not args.no_lock:

‎support/rrsync.1.md‎

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -103,20 +103,29 @@ The remainder of this manpage is dedicated to using the rrsync script.
103103
replacing whatever has appeared at that name since the check), and backup
104104
mode (`-b`, `--backup-dir`, whose published backup replaces whatever
105105
already occupies the backup name). Resumable uploads with an explicit
106-
`--partial-dir`, `--delay-updates`, `--delay-symlinks`, and server-side
107-
logging are therefore unavailable under this option.
106+
`--partial-dir`, `--delay-updates`, `--delay-symlinks` and client-selected
107+
log files are therefore unavailable under this option. Administrator logging
108+
with [`-log FILE`](#opt) remains available.
108109
109110
0. `-log FILE`
110111
111-
Log every transfer to _FILE_ using rsync's [`--log-file`](rsync.1#opt),
112-
in its default "%i %n%L" format, so each file sent, received or deleted
113-
gets a line. _FILE_ can be relative to the user's home directory or an
114-
absolute path. The client's own `--log-file` option is refused while this
115-
is in force. _FILE_ is resolved one component at a time and refused if
116-
any step enters _DIR_, and `-log` cannot be used when _DIR_ is `/`.
117-
rrsync opens _FILE_ before running rsync and refuses the transfer if it
118-
cannot. After that, write errors are handled as for rsync's
119-
`--log-file`: they are not reported and do not stop the transfer.
112+
Write server-side transfer records to _FILE_ using rsync's
113+
[`--log-file`](rsync.1#opt). The default "%i %n%L" format records files sent,
114+
received or deleted, with timestamps and process IDs. The client's own
115+
`--log-file` is refused. This works with `-ro`, `-wo` and `-no-overwrite`.
116+
117+
_FILE_ must be a regular file outside _DIR_. It can be absolute or relative
118+
to the user's home directory. rrsync resolves symlinks before `..` and
119+
refuses paths that pass through _DIR_. `-log` is refused when _DIR_ is `/`.
120+
Symlinks must be owned by root or the user running rrsync. Keep the log and
121+
its parent directories out of untrusted users' reach, including
122+
through hard links or bind mounts; rrsync cannot detect every such alias.
123+
124+
rrsync checks that _FILE_ can be opened before starting the transfer.
125+
Rsync then opens the file itself. Logging is best-effort: a later open or
126+
write failure can leave a successful transfer with incomplete or missing
127+
records. Use rsync's exit status to determine whether a transfer succeeded.
128+
This option does not provide a tamper-resistant audit trail.
120129
121130
0. `-help`, `-h`
122131

‎syscall.c‎

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -421,7 +421,7 @@ static int ona_open_absolute_root(char *remaining, char *abspath, size_t abspath
421421
/* Core walk. When out_abs is non-NULL and the path resolves to a directory
422422
* (O_DIRECTORY), the resolved absolute path is copied there -- owner_walk_parent
423423
* uses it to filter-check the (otherwise unchecked) leaf basename. */
424-
static int ona_open(const char *path, int flags, mode_t mode, char *out_abs, size_t out_cap)
424+
static int ona_open(const char *path, int flags, mode_t mode, char *out_abs, size_t out_cap, int enforce_root)
425425
{
426426
#if defined AT_FDCWD && defined O_NOFOLLOW && defined O_DIRECTORY
427427
const int dir_traverse_flags = directory_traverse_flags() | O_CLOEXEC;
@@ -446,7 +446,7 @@ static int ona_open(const char *path, int flags, mode_t mode, char *out_abs, siz
446446
char abspath[MAXPATHLEN] = {0};
447447
if (am_daemon && module_dir && module_dir[0] == '/')
448448
strlcpy(abspath, module_dir, sizeof abspath); /* "/" for a path=/ module */
449-
else if (confine_root) {
449+
else if (enforce_root && confine_root) {
450450
/* Unlike a daemon's, this cwd is not pinned to the root -- the receiver
451451
* chdir's into the destination -- so it has to be read, not assumed.
452452
* It must be the PHYSICAL cwd: curr_dir is the lexical name change_dir()
@@ -472,7 +472,7 @@ static int ona_open(const char *path, int flags, mode_t mode, char *out_abs, siz
472472
* following the link restarts the walk at its absolute target, and every
473473
* component of THAT is checked, so a pin aimed outside is still refused. */
474474
const char *ptail = fd_pin_tail(path);
475-
int pin_transit = !am_daemon && confine_root && ptail != NULL;
475+
int pin_transit = enforce_root && !am_daemon && confine_root && ptail != NULL;
476476

477477
/* Path-walk state. `remaining` is the unconsumed tail; we splice
478478
* symlink targets back into it as we go. Sized 2x MAXPATHLEN so a
@@ -534,7 +534,7 @@ static int ona_open(const char *path, int flags, mode_t mode, char *out_abs, siz
534534
saved_errno = errno;
535535
goto out;
536536
}
537-
if (!pin_transit && abspath_outside_confinement(abspath, 1)) {
537+
if (enforce_root && !pin_transit && abspath_outside_confinement(abspath, 1)) {
538538
saved_errno = ELOOP;
539539
goto out;
540540
}
@@ -664,7 +664,7 @@ static int ona_open(const char *path, int flags, mode_t mode, char *out_abs, siz
664664
saved_errno = errno;
665665
goto out;
666666
}
667-
if (!pin_transit && abspath_outside_confinement(abspath, 1)) {
667+
if (enforce_root && !pin_transit && abspath_outside_confinement(abspath, 1)) {
668668
saved_errno = ELOOP;
669669
goto out;
670670
}
@@ -688,7 +688,7 @@ static int ona_open(const char *path, int flags, mode_t mode, char *out_abs, siz
688688
saved_errno = errno;
689689
goto out;
690690
}
691-
if (!pin_transit && abspath_outside_confinement(abspath, 0)) {
691+
if (enforce_root && !pin_transit && abspath_outside_confinement(abspath, 0)) {
692692
saved_errno = ELOOP;
693693
goto out;
694694
}
@@ -716,7 +716,7 @@ static int ona_open(const char *path, int flags, mode_t mode, char *out_abs, siz
716716
* an O_PATH fd is sufficient for traversal and fchdir but not operations
717717
* such as fchmod. */
718718
if (flags & O_DIRECTORY) {
719-
if (!pin_transit && abspath_outside_confinement(abspath, 1)) {
719+
if (enforce_root && !pin_transit && abspath_outside_confinement(abspath, 1)) {
720720
saved_errno = ELOOP;
721721
goto out;
722722
}
@@ -737,21 +737,28 @@ static int ona_open(const char *path, int flags, mode_t mode, char *out_abs, siz
737737
#else
738738
/* Pre-AT_FDCWD / no O_NOFOLLOW systems: best-effort fallback. */
739739
(void)out_abs; (void)out_cap;
740+
(void)enforce_root;
740741
return open(path, flags, mode);
741742
#endif
742743
}
743744

744745
int open_no_attacker_symlinks(const char *path, int flags, mode_t mode)
745746
{
746-
return ona_open(path, flags, mode, NULL, 0);
747+
return ona_open(path, flags, mode, NULL, 0, 1);
748+
}
749+
750+
/* A log's ownership check must not inherit file-list confinement. */
751+
int open_log_file(const char *path, int flags, mode_t mode)
752+
{
753+
return ona_open(path, flags, mode, NULL, 0, 0);
747754
}
748755

749756
/* Open a directory for traversal or as *at()/fchdir() authority. Unlike an
750757
* O_RDONLY directory endpoint, this accepts a searchable but unreadable
751758
* directory on Linux. */
752759
int open_no_attacker_symlinks_dirfd(const char *path)
753760
{
754-
return ona_open(path, directory_traverse_flags(), 0, NULL, 0);
761+
return ona_open(path, directory_traverse_flags(), 0, NULL, 0, 1);
755762
}
756763

757764
/* When set, the do_*_at() wrappers resolve their path as an OPERATOR-supplied
@@ -780,7 +787,7 @@ int owner_walk_parent(const char *path, const char **bname)
780787
*bname = slash ? slash + 1 : path;
781788
pabs[0] = '\0';
782789
if (!slash)
783-
dfd = ona_open(".", directory_traverse_flags(), 0, pabs, sizeof pabs);
790+
dfd = ona_open(".", directory_traverse_flags(), 0, pabs, sizeof pabs, 1);
784791
else {
785792
dlen = slash == path ? 1 : (size_t)(slash - path); /* "/x" -> parent "/" */
786793
if (dlen >= sizeof dir) {
@@ -789,7 +796,7 @@ int owner_walk_parent(const char *path, const char **bname)
789796
}
790797
memcpy(dir, path, dlen);
791798
dir[dlen] = '\0';
792-
dfd = ona_open(dir, directory_traverse_flags(), 0, pabs, sizeof pabs);
799+
dfd = ona_open(dir, directory_traverse_flags(), 0, pabs, sizeof pabs, 1);
793800
}
794801
if (dfd < 0)
795802
return -1;

0 commit comments

Comments
 (0)