Debian Codegraph @

testsuite/partial-protected-regular-retry-linux_test.py

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 #!/usr/bin/env python3
2 """PoC: EACCES recovery must retain partial-dir ownership policy (Linux).
3
4 Linux twin of partial-protected-regular-retry-policy_test.py, which runs only
5 under dyld interposing. It covers the recovery arm that test cannot reach:
6 the fs.protected_regular compatibility retry, i.e. the "#ifdef linux" arm of
7 recv_files(), which is not compiled on Darwin. Between them the two tests
8 cover both arms (Darwin's first EACCES goes straight to the generic
9 read-only-file chmod-and-reopen recovery, there being no Linux arm there).
10
11 The one-inplace partial leaf is first opened through the operator ownership
12 walk. The hook models an EACCES from that O_CREAT open and swaps the partial
13 directory for a symlink in the exact recovery window. A retry that drops to
14 the ordinary resolver follows the new parent with no ownership check and
15 writes the remote payload into a different file; one that keeps the walk
16 refuses the foreign-owned symlink.
17 """
18
19 import os
20 import platform
21 import subprocess
22
23 from rsyncfns import (
24 SCRATCHDIR, forced_protocol, rmtree, rsync_argv, test_fail, test_skipped,
25 )
26
27
28 if platform.system() != 'Linux':
29 test_skipped('LD_PRELOAD partial EACCES recovery hook is Linux-only')
30
31 # one_inplace staging needs inplace_partial, which is negotiated through the
32 # protocol-30 CF_INPLACE_PARTIAL_DIR capability flag. Below that the receiver
33 # uses the ordinary tmpfile path and the recovery under test never runs.
34 _proto = forced_protocol()
35 if _proto is not None and _proto < 30:
36 test_skipped(f'one-inplace partial staging needs protocol >= 30 (forced {_proto})')
37
38 hook_code = r'''
39 #define _GNU_SOURCE
40 #include <sys/stat.h>
41 #include <sys/syscall.h>
42 #include <sys/types.h>
43 #include <dlfcn.h>
44 #include <errno.h>
45 #include <fcntl.h>
46 #include <limits.h>
47 #include <stdarg.h>
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <unistd.h>
52
53 static int swapped;
54
55 static int (*real_open)(const char *, int, ...);
56 static int (*real_openat)(int, const char *, int, ...);
57 static int (*real_fstatat)(int, const char *, struct stat *, int);
58 static int (*real_fxstatat)(int, int, const char *, struct stat *, int);
59
60 /* Resolve on demand rather than trusting our constructor to have run. A
61 * preloaded open() interposes for the whole process the moment the loader maps
62 * us, including calls made from OTHER libraries' constructors -- and the order
63 * constructors run between unrelated shared objects is unspecified. On
64 * AlmaLinux 8, OPENSSL_init_library() calls open() from its constructor before
65 * ours runs, so a plain "resolved in the constructor" pointer is still NULL and
66 * the process dies with SIGSEGV inside the loader. */
67 /* If dlsym() itself reaches an interposed function, the nested wrapper must
68 * not recurse back into resolution -- it takes the raw path instead. */
69 static __thread int hook_resolving;
70
71 static void hook_resolve(void)
72 {
73 if (hook_resolving)
74 return;
75 hook_resolving = 1;
76 if (!real_open) real_open = dlsym(RTLD_NEXT, "open");
77 if (!real_openat) real_openat = dlsym(RTLD_NEXT, "openat");
78 if (!real_fstatat) real_fstatat = dlsym(RTLD_NEXT, "fstatat");
79 if (!real_fxstatat) real_fxstatat = dlsym(RTLD_NEXT, "__fxstatat");
80 hook_resolving = 0;
81 }
82
83 /* Last-resort passthrough if even dlsym() is unusable this early. openat(2)
84 * rather than open(2): open is not a syscall on every architecture. */
85 static int raw_openat(int dfd, const char *path, int flags, mode_t mode)
86 {
87 return (int)syscall(SYS_openat, dfd, path, flags, mode);
88 }
89
90 static void mark(const char *path)
91 {
92 int fd;
93 hook_resolve();
94 if (!path)
95 return;
96 fd = real_open ? real_open(path, O_WRONLY | O_CREAT | O_EXCL, 0600)
97 : raw_openat(AT_FDCWD, path, O_WRONLY | O_CREAT | O_EXCL, 0600);
98 if (fd >= 0)
99 close(fd);
100 }
101
102 /* Darwin's F_GETPATH equivalent. */
103 static int fd_path_is(int fd, const char *wanted)
104 {
105 char procpath[64], path[PATH_MAX];
106 ssize_t n;
107
108 if (!wanted || fd < 0)
109 return 0;
110 snprintf(procpath, sizeof procpath, "/proc/self/fd/%d", fd);
111 n = readlink(procpath, path, sizeof path - 1);
112 if (n < 0)
113 return 0;
114 path[n] = '\0';
115 return strcmp(path, wanted) == 0;
116 }
117
118 static void restore_partial(void)
119 {
120 const char *partial = getenv("RSYNC_PARTIAL_RETRY_DIR");
121 const char *held = getenv("RSYNC_PARTIAL_RETRY_HELD");
122 if (swapped && partial && held) {
123 unlink(partial);
124 if (rename(held, partial) == 0)
125 swapped = 0;
126 }
127 }
128
129 /* Swap the partial dir for a symlink and report EACCES, exactly as
130 * fs.protected_regular would on the O_CREAT open of an existing leaf. */
131 static int swap_and_deny(void)
132 {
133 const char *partial = getenv("RSYNC_PARTIAL_RETRY_DIR");
134 const char *held = getenv("RSYNC_PARTIAL_RETRY_HELD");
135 if (partial && held && rename(partial, held) == 0
136 && symlink("secret", partial) == 0) {
137 swapped = 1;
138 mark(getenv("RSYNC_PARTIAL_RETRY_EACCES_MARKER"));
139 errno = EACCES;
140 return -1;
141 }
142 restore_partial();
143 return 0; /* caller falls through to the real call */
144 }
145
146 #ifdef O_TMPFILE
147 /* O_TMPFILE is (__O_TMPFILE | O_DIRECTORY) on Linux, so a plain & test would
148 * also match an ordinary O_DIRECTORY open. */
149 # define HOOK_TAKES_MODE(f) (((f) & O_CREAT) || (((f) & O_TMPFILE) == O_TMPFILE))
150 #else
151 # define HOOK_TAKES_MODE(f) ((f) & O_CREAT)
152 #endif
153
154 static int is_victim_write(const char *path, int flags)
155 {
156 return path && strcmp(path, "victim") == 0
157 && (flags & O_ACCMODE) == O_WRONLY;
158 }
159
160 int openat(int dfd, const char *path, int flags, ...)
161 {
162 const char *partial, *secret;
163 mode_t mode = 0;
164 int fd, saved_errno;
165
166 hook_resolve();
167 partial = getenv("RSYNC_PARTIAL_RETRY_DIR");
168 secret = getenv("RSYNC_PARTIAL_RETRY_SECRET");
169
170 if (HOOK_TAKES_MODE(flags)) {
171 va_list ap;
172 va_start(ap, flags);
173 mode = (mode_t)va_arg(ap, int);
174 va_end(ap);
175 }
176
177 if (!swapped && is_victim_write(path, flags) && (flags & O_CREAT)
178 && fd_path_is(dfd, partial)) {
179 if (swap_and_deny() < 0)
180 return -1;
181 }
182
183 fd = real_openat ? real_openat(dfd, path, flags, mode)
184 : raw_openat(dfd, path, flags, mode);
185 saved_errno = errno;
186
187 /* An unconfined retry resolves the swapped parent and lands in the secret
188 * dir. Pin the evidence, then restore the name so later finalization
189 * cannot disguise which file was written. */
190 if (swapped && fd >= 0 && is_victim_write(path, flags)
191 && !(flags & O_CREAT) && fd_path_is(dfd, secret)) {
192 mark(getenv("RSYNC_PARTIAL_RETRY_OPEN_MARKER"));
193 restore_partial();
194 }
195 errno = saved_errno;
196 return fd;
197 }
198
199 int open(const char *path, int flags, ...)
200 {
201 mode_t mode = 0;
202 int fd, saved_errno;
203
204 hook_resolve();
205
206 if (HOOK_TAKES_MODE(flags)) {
207 va_list ap;
208 va_start(ap, flags);
209 mode = (mode_t)va_arg(ap, int);
210 va_end(ap);
211 }
212
213 if (!swapped && path && strstr(path, "pdir/victim")
214 && (flags & O_ACCMODE) == O_WRONLY && (flags & O_CREAT)) {
215 if (swap_and_deny() < 0)
216 return -1;
217 }
218
219 fd = real_open ? real_open(path, flags, mode)
220 : raw_openat(AT_FDCWD, path, flags, mode);
221 saved_errno = errno;
222
223 /* The pre-fix recovery uses plain open() on the full pathname, which walks
224 * the swapped symlink with no ownership check. */
225 if (swapped && fd >= 0 && path && strstr(path, "pdir/victim")
226 && (flags & O_ACCMODE) == O_WRONLY && !(flags & O_CREAT)) {
227 mark(getenv("RSYNC_PARTIAL_RETRY_OPEN_MARKER"));
228 restore_partial();
229 }
230 errno = saved_errno;
231 return fd;
232 }
233
234 /* ona_open() decides via fstatat(..., AT_SYMLINK_NOFOLLOW) and refuses a
235 * component owned by neither root nor the euid. Model the attacker as a
236 * different uid so a retry that kept the ownership walk refuses the swap. */
237 static void model_foreign_owner(int rc, const char *path, struct stat *st)
238 {
239 if (rc == 0 && swapped && path && strcmp(path, "pdir") == 0
240 && S_ISLNK(st->st_mode)) {
241 st->st_uid = geteuid() + 1;
242 mark(getenv("RSYNC_PARTIAL_RETRY_FOREIGN_MARKER"));
243 }
244 }
245
246 int fstatat(int dfd, const char *path, struct stat *st, int flags)
247 {
248 int rc, saved_errno;
249
250 hook_resolve();
251 if (!real_fstatat) {
252 errno = ENOSYS;
253 return -1;
254 }
255 rc = real_fstatat(dfd, path, st, flags);
256 saved_errno = errno;
257 model_foreign_owner(rc, path, st);
258 errno = saved_errno;
259 return rc;
260 }
261
262 /* glibc < 2.33 routes fstatat() through __fxstatat(). */
263 int __fxstatat(int ver, int dfd, const char *path, struct stat *st, int flags)
264 {
265 int rc, saved_errno;
266
267 hook_resolve();
268 if (!real_fxstatat) {
269 errno = ENOSYS;
270 return -1;
271 }
272 rc = real_fxstatat(ver, dfd, path, st, flags);
273 saved_errno = errno;
274 model_foreign_owner(rc, path, st);
275 errno = saved_errno;
276 return rc;
277 }
278
279 __attribute__((constructor)) static void hook_loaded(void)
280 {
281 hook_resolve();
282 mark(getenv("RSYNC_PARTIAL_RETRY_LOAD_MARKER"));
283 }
284
285 __attribute__((destructor)) static void hook_unload(void)
286 {
287 restore_partial();
288 }
289 '''
290
291
292 def run():
293 base = SCRATCHDIR / 'partial-protected-regular-retry-linux'
294 rmtree(base)
295 src = base / 'src'
296 mod = base / 'mod'
297 partial = mod / 'pdir'
298 held = mod / '.pdir-held'
299 secret = mod / 'secret'
300 markers = {
301 'load': base / 'hook-loaded',
302 'eacces': base / 'operator-open-eacces',
303 'retry': base / 'unconfined-retry-open',
304 'foreign': base / 'owner-check-would-refuse',
305 }
306 for directory in (src, partial, secret):
307 directory.mkdir(parents=True)
308
309 old_partial = b'OLD-PARTIAL-BASIS-' * 4096
310 new_source = b'NEW-REMOTE-PAYLOAD' * 4096
311 secret_data = b'OTHER-USER-SECRET!' * 4096
312 if not (len(old_partial) == len(new_source) == len(secret_data)):
313 raise AssertionError('PoC payloads must be equal length')
314 (partial / 'victim').write_bytes(old_partial)
315 (secret / 'victim').write_bytes(secret_data)
316 (src / 'victim').write_bytes(new_source)
317
318 hook_src = base / 'hook.c'
319 hook_lib = base / 'hook.so'
320 hook_src.write_text(hook_code)
321 build = subprocess.run(
322 ['cc', '-shared', '-fPIC', '-o', str(hook_lib), str(hook_src), '-ldl'],
323 stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
324 if build.returncode != 0:
325 test_skipped(f'cannot build LD_PRELOAD partial retry hook: {build.stdout!r}')
326
327 run_env = os.environ.copy()
328 run_env.update({
329 'LD_PRELOAD': str(hook_lib),
330 'RSYNC_PARTIAL_RETRY_DIR': str(partial),
331 'RSYNC_PARTIAL_RETRY_HELD': str(held),
332 'RSYNC_PARTIAL_RETRY_SECRET': str(secret),
333 'RSYNC_PARTIAL_RETRY_LOAD_MARKER': str(markers['load']),
334 'RSYNC_PARTIAL_RETRY_EACCES_MARKER': str(markers['eacces']),
335 'RSYNC_PARTIAL_RETRY_OPEN_MARKER': str(markers['retry']),
336 'RSYNC_PARTIAL_RETRY_FOREIGN_MARKER': str(markers['foreign']),
337 })
338
339 result = subprocess.run(
340 rsync_argv('-rtI', '--partial', '--partial-dir=pdir',
341 '--no-inc-recursive', f'{src}/', f'{mod}/'),
342 stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, env=run_env)
343
344 if held.exists():
345 if partial.is_symlink():
346 partial.unlink()
347 held.rename(partial)
348
349 ctx = f'rc={result.returncode}, output={result.stdout!r}'
350 # A negative returncode is death by signal. That is never a reason to skip:
351 # the hook killing the process under test is a bug in the hook, and reporting
352 # it as "not loaded" is exactly how a SIGSEGV on AlmaLinux 8 hid for weeks --
353 # the marker is written by the hook, so a crash before that looks identical
354 # to the hook never having loaded.
355 if result.returncode is not None and result.returncode < 0:
356 test_fail(f'rsync died by signal {-result.returncode} under the '
357 f'LD_PRELOAD hook ({ctx})')
358 if not markers['load'].exists():
359 test_skipped(f'LD_PRELOAD hook was not loaded ({ctx})')
360 if not markers['eacces'].exists():
361 test_fail('positive control failed: receiver did not open the existing '
362 f'partial file with O_CREAT ({ctx})')
363
364 # The escape check must come before the ownership-walk control below: on a
365 # vulnerable build no walk runs at all, and that has to be reported as the
366 # escape it is rather than as an inconclusive control failure.
367 observed = (secret / 'victim').read_bytes()
368 if observed == new_source:
369 test_fail('EACCES recovery dropped partial-dir ownership policy and '
370 f'overwrote a different file through the raced symlink ({ctx})')
371 if observed != secret_data:
372 test_fail(f'outside-policy target has unexpected contents ({ctx})')
373 if markers['retry'].exists():
374 test_fail('an unconfined retry opened the victim through the raced '
375 f'partial-dir symlink ({ctx})')
376
377 # Anti-vacuity: nothing was overwritten -- prove that is the ownership walk
378 # refusing the swap, not the scenario failing to arm.
379 if not markers['foreign'].exists():
380 test_fail('inconclusive: the recovery never inspected the raced '
381 f'partial-dir symlink, so no ownership check ran ({ctx})')
382
383
384 run()
385 print('protected_regular compatibility retry retained partial-dir ownership policy')