Debian Codegraph @

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

raw symbols ◀ ▶ SCIP
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 /* Build the hook itself WITHOUT large-file redirection, whatever the compiler
41 * defaults to. Debian's armhf/hppa/powerpc gcc predefines
42 * -D_FILE_OFFSET_BITS=64 -D_TIME_BITS=64 (check with "gcc -v -E -"), and under
43 * those macros glibc's __REDIRECT renames the DEFINITIONS below -- open()
44 * becomes open64(), fstatat() becomes __fstatat64_time64() -- which then
45 * collide with the explicit large-file wrappers further down ("symbol `open64'
46 * is already defined"). Undefining them here keeps each name declared exactly
47 * once, so the hook always exports both spellings and interposes whichever set
48 * the rsync under test was linked against. */
49 #undef _FILE_OFFSET_BITS
50 #undef _TIME_BITS
51 #include <sys/stat.h>
52 #include <sys/syscall.h>
53 #include <sys/types.h>
54 #include <dlfcn.h>
55 #include <errno.h>
56 #include <fcntl.h>
57 #include <limits.h>
58 #include <stdarg.h>
59 #include <stdio.h>
60 #include <stdlib.h>
61 #include <string.h>
62 #include <unistd.h>
63
64 static int swapped;
65
66 static int (*real_open)(const char *, int, ...);
67 static int (*real_openat)(int, const char *, int, ...);
68 static int (*real_fstatat)(int, const char *, struct stat *, int);
69 static int (*real_fxstatat)(int, int, const char *, struct stat *, int);
•70 static int (*real_fstatat64)(int, const char *, struct stat64 *, int);
71 static int (*real_fxstatat64)(int, int, const char *, struct stat64 *, int);
72 static int (*real_fstatat64_time64)(int, const char *, struct stat64 *, int);
73
74 /* Resolve on demand rather than trusting our constructor to have run. A
75 * preloaded open() interposes for the whole process the moment the loader maps
76 * us, including calls made from OTHER libraries' constructors -- and the order
77 * constructors run between unrelated shared objects is unspecified. On
78 * AlmaLinux 8, OPENSSL_init_library() calls open() from its constructor before
79 * ours runs, so a plain "resolved in the constructor" pointer is still NULL and
80 * the process dies with SIGSEGV inside the loader. */
81 /* If dlsym() itself reaches an interposed function, the nested wrapper must
82 * not recurse back into resolution -- it takes the raw path instead. */
83 static __thread int hook_resolving;
84
85 static void hook_resolve(void)
86 {
87 if (hook_resolving)
88 return;
89 hook_resolving = 1;
90 if (!real_open) real_open = dlsym(RTLD_NEXT, "open");
91 if (!real_openat) real_openat = dlsym(RTLD_NEXT, "openat");
92 if (!real_fstatat) real_fstatat = dlsym(RTLD_NEXT, "fstatat");
93 if (!real_fxstatat) real_fxstatat = dlsym(RTLD_NEXT, "__fxstatat");
•94 if (!real_fstatat64) real_fstatat64 = dlsym(RTLD_NEXT, "fstatat64");
95 if (!real_fxstatat64) real_fxstatat64 = dlsym(RTLD_NEXT, "__fxstatat64");
96 if (!real_fstatat64_time64)
97 real_fstatat64_time64 = dlsym(RTLD_NEXT, "__fstatat64_time64");
98 hook_resolving = 0;
99 }
100
101 /* Last-resort passthrough if even dlsym() is unusable this early. openat(2)
102 * rather than open(2): open is not a syscall on every architecture. */
103 static int raw_openat(int dfd, const char *path, int flags, mode_t mode)
104 {
105 return (int)syscall(SYS_openat, dfd, path, flags, mode);
106 }
107
108 static void mark(const char *path)
109 {
110 int fd;
111 hook_resolve();
112 if (!path)
113 return;
114 fd = real_open ? real_open(path, O_WRONLY | O_CREAT | O_EXCL, 0600)
115 : raw_openat(AT_FDCWD, path, O_WRONLY | O_CREAT | O_EXCL, 0600);
116 if (fd >= 0)
117 close(fd);
118 }
119
120 /* Darwin's F_GETPATH equivalent. */
121 static int fd_path_is(int fd, const char *wanted)
122 {
123 char procpath[64], path[PATH_MAX];
124 ssize_t n;
125
126 if (!wanted || fd < 0)
127 return 0;
128 snprintf(procpath, sizeof procpath, "/proc/self/fd/%d", fd);
129 n = readlink(procpath, path, sizeof path - 1);
130 if (n < 0)
131 return 0;
132 path[n] = '\0';
133 return strcmp(path, wanted) == 0;
134 }
135
136 static void restore_partial(void)
137 {
138 const char *partial = getenv("RSYNC_PARTIAL_RETRY_DIR");
139 const char *held = getenv("RSYNC_PARTIAL_RETRY_HELD");
140 if (swapped && partial && held) {
141 unlink(partial);
142 if (rename(held, partial) == 0)
143 swapped = 0;
144 }
145 }
146
147 /* Swap the partial dir for a symlink and report EACCES, exactly as
148 * fs.protected_regular would on the O_CREAT open of an existing leaf. */
149 static int swap_and_deny(void)
150 {
151 const char *partial = getenv("RSYNC_PARTIAL_RETRY_DIR");
152 const char *held = getenv("RSYNC_PARTIAL_RETRY_HELD");
153 if (partial && held && rename(partial, held) == 0
154 && symlink("secret", partial) == 0) {
155 swapped = 1;
156 mark(getenv("RSYNC_PARTIAL_RETRY_EACCES_MARKER"));
157 errno = EACCES;
158 return -1;
159 }
160 restore_partial();
161 return 0; /* caller falls through to the real call */
162 }
163
164 #ifdef O_TMPFILE
165 /* O_TMPFILE is (__O_TMPFILE | O_DIRECTORY) on Linux, so a plain & test would
166 * also match an ordinary O_DIRECTORY open. */
167 # define HOOK_TAKES_MODE(f) (((f) & O_CREAT) || (((f) & O_TMPFILE) == O_TMPFILE))
168 #else
169 # define HOOK_TAKES_MODE(f) ((f) & O_CREAT)
170 #endif
171
•172 #ifndef O_LARGEFILE
173 # define O_LARGEFILE 0
174 #endif
175
176 static int is_victim_write(const char *path, int flags)
177 {
178 return path && strcmp(path, "victim") == 0
179 && (flags & O_ACCMODE) == O_WRONLY;
180 }
181
182 int openat(int dfd, const char *path, int flags, ...)
183 {
184 const char *partial, *secret;
185 mode_t mode = 0;
186 int fd, saved_errno;
187
188 hook_resolve();
189 partial = getenv("RSYNC_PARTIAL_RETRY_DIR");
190 secret = getenv("RSYNC_PARTIAL_RETRY_SECRET");
191
192 if (HOOK_TAKES_MODE(flags)) {
193 va_list ap;
194 va_start(ap, flags);
195 mode = (mode_t)va_arg(ap, int);
196 va_end(ap);
197 }
198
199 if (!swapped && is_victim_write(path, flags) && (flags & O_CREAT)
200 && fd_path_is(dfd, partial)) {
201 if (swap_and_deny() < 0)
202 return -1;
203 }
204
205 fd = real_openat ? real_openat(dfd, path, flags, mode)
206 : raw_openat(dfd, path, flags, mode);
207 saved_errno = errno;
208
209 /* An unconfined retry resolves the swapped parent and lands in the secret
210 * dir. Pin the evidence, then restore the name so later finalization
211 * cannot disguise which file was written. */
212 if (swapped && fd >= 0 && is_victim_write(path, flags)
213 && !(flags & O_CREAT) && fd_path_is(dfd, secret)) {
214 mark(getenv("RSYNC_PARTIAL_RETRY_OPEN_MARKER"));
215 restore_partial();
216 }
217 errno = saved_errno;
218 return fd;
219 }
220
221 int open(const char *path, int flags, ...)
222 {
223 mode_t mode = 0;
224 int fd, saved_errno;
225
226 hook_resolve();
227
228 if (HOOK_TAKES_MODE(flags)) {
229 va_list ap;
230 va_start(ap, flags);
231 mode = (mode_t)va_arg(ap, int);
232 va_end(ap);
233 }
234
235 if (!swapped && path && strstr(path, "pdir/victim")
236 && (flags & O_ACCMODE) == O_WRONLY && (flags & O_CREAT)) {
237 if (swap_and_deny() < 0)
238 return -1;
239 }
240
241 fd = real_open ? real_open(path, flags, mode)
242 : raw_openat(AT_FDCWD, path, flags, mode);
243 saved_errno = errno;
244
245 /* The pre-fix recovery uses plain open() on the full pathname, which walks
246 * the swapped symlink with no ownership check. */
247 if (swapped && fd >= 0 && path && strstr(path, "pdir/victim")
248 && (flags & O_ACCMODE) == O_WRONLY && !(flags & O_CREAT)) {
249 mark(getenv("RSYNC_PARTIAL_RETRY_OPEN_MARKER"));
250 restore_partial();
251 }
252 errno = saved_errno;
253 return fd;
254 }
255
•256 /* --- large-file spellings -------------------------------------------------
257 * Which names the RECEIVER calls is settled by its own build: where off_t is
258 * not already 64 bits, configure's AC_SYS_LARGEFILE adds -D_FILE_OFFSET_BITS=64
259 * (i386, alpha, ...), and distro CPPFLAGS add it -- along with -D_TIME_BITS=64
260 * -- on the 64-bit time_t ports, so glibc redirects each open()/openat()/
261 * fstatat() call to open64()/openat64()/fstatat64()/__fstatat64_time64().
262 * "objdump -T rsync | grep UND" says which set a given build imports.
263 *
264 * Which names THIS HOOK exports is a different question with a different
265 * answer, settled by whatever the "cc" below it defaults to -- see the #undef
266 * at the top. Nothing keeps the two in step, so define every spelling and let
267 * the loader match them up. With only the unsuffixed ones the receiver's opens
268 * sail straight past the hook, no EACCES is ever injected, and the test reports
269 * "positive control failed" having exercised nothing at all.
270 *
271 * O_LARGEFILE is the only thing open64() adds over open(), so the wrappers
272 * below can hand the call to the unsuffixed interposer above. */
273 int open64(const char *path, int flags, ...)
274 {
275 mode_t mode = 0;
276
277 if (HOOK_TAKES_MODE(flags)) {
278 va_list ap;
279 va_start(ap, flags);
280 mode = (mode_t)va_arg(ap, int);
281 va_end(ap);
282 }
283 return open(path, flags | O_LARGEFILE, mode);
284 }
285
286 int openat64(int dfd, const char *path, int flags, ...)
287 {
288 mode_t mode = 0;
289
290 if (HOOK_TAKES_MODE(flags)) {
291 va_list ap;
292 va_start(ap, flags);
293 mode = (mode_t)va_arg(ap, int);
294 va_end(ap);
295 }
296 return openat(dfd, path, flags | O_LARGEFILE, mode);
297 }
298
299 /* ona_open() decides via fstatat(..., AT_SYMLINK_NOFOLLOW) and refuses a
300 * component owned by neither root nor the euid. Model the attacker as a
301 * different uid so a retry that kept the ownership walk refuses the swap. */
302 static void model_foreign_owner(int rc, const char *path, struct stat *st)
303 {
304 if (rc == 0 && swapped && path && strcmp(path, "pdir") == 0
305 && S_ISLNK(st->st_mode)) {
306 st->st_uid = geteuid() + 1;
307 mark(getenv("RSYNC_PARTIAL_RETRY_FOREIGN_MARKER"));
308 }
309 }
310
311 int fstatat(int dfd, const char *path, struct stat *st, int flags)
312 {
313 int rc, saved_errno;
314
315 hook_resolve();
316 if (!real_fstatat) {
317 errno = ENOSYS;
318 return -1;
319 }
320 rc = real_fstatat(dfd, path, st, flags);
321 saved_errno = errno;
322 model_foreign_owner(rc, path, st);
323 errno = saved_errno;
324 return rc;
325 }
326
327 /* glibc < 2.33 routes fstatat() through __fxstatat(). */
328 int __fxstatat(int ver, int dfd, const char *path, struct stat *st, int flags)
329 {
330 int rc, saved_errno;
331
332 hook_resolve();
333 if (!real_fxstatat) {
334 errno = ENOSYS;
335 return -1;
336 }
337 rc = real_fxstatat(ver, dfd, path, st, flags);
338 saved_errno = errno;
339 model_foreign_owner(rc, path, st);
340 errno = saved_errno;
341 return rc;
342 }
•343
344 /* The stat family's large-file spellings. st_mode and st_uid sit ahead of the
345 * timestamps in every glibc struct stat layout, so the time32/time64 variants
346 * of the buffer are interchangeable for the two fields touched here. */
347 static void model_foreign_owner64(int rc, const char *path, struct stat64 *st)
348 {
349 if (rc == 0 && swapped && path && strcmp(path, "pdir") == 0
350 && S_ISLNK(st->st_mode)) {
351 st->st_uid = geteuid() + 1;
352 mark(getenv("RSYNC_PARTIAL_RETRY_FOREIGN_MARKER"));
353 }
354 }
355
356 int fstatat64(int dfd, const char *path, struct stat64 *st, int flags)
357 {
358 int rc, saved_errno;
359
360 hook_resolve();
361 if (!real_fstatat64) {
362 errno = ENOSYS;
363 return -1;
364 }
365 rc = real_fstatat64(dfd, path, st, flags);
366 saved_errno = errno;
367 model_foreign_owner64(rc, path, st);
368 errno = saved_errno;
369 return rc;
370 }
371
372 int __fxstatat64(int ver, int dfd, const char *path, struct stat64 *st, int flags)
373 {
374 int rc, saved_errno;
375
376 hook_resolve();
377 if (!real_fxstatat64) {
378 errno = ENOSYS;
379 return -1;
380 }
381 rc = real_fxstatat64(ver, dfd, path, st, flags);
382 saved_errno = errno;
383 model_foreign_owner64(rc, path, st);
384 errno = saved_errno;
385 return rc;
386 }
387
388 /* A 32-bit port built with -D_TIME_BITS=64 (Debian's armhf/armel/hppa/powerpc,
389 * ...) reaches fstatat() under this third name. */
390 int __fstatat64_time64(int dfd, const char *path, struct stat64 *st, int flags)
391 {
392 int rc, saved_errno;
393
394 hook_resolve();
395 if (!real_fstatat64_time64) {
396 errno = ENOSYS;
397 return -1;
398 }
399 rc = real_fstatat64_time64(dfd, path, st, flags);
400 saved_errno = errno;
401 model_foreign_owner64(rc, path, st);
402 errno = saved_errno;
403 return rc;
404 }
405
406 __attribute__((constructor)) static void hook_loaded(void)
407 {
408 hook_resolve();
409 mark(getenv("RSYNC_PARTIAL_RETRY_LOAD_MARKER"));
410 }
411
412 __attribute__((destructor)) static void hook_unload(void)
413 {
414 restore_partial();
415 }
416 '''
417
418
419 def run():
420 base = SCRATCHDIR / 'partial-protected-regular-retry-linux'
421 rmtree(base)
422 src = base / 'src'
423 mod = base / 'mod'
424 partial = mod / 'pdir'
425 held = mod / '.pdir-held'
426 secret = mod / 'secret'
427 markers = {
428 'load': base / 'hook-loaded',
429 'eacces': base / 'operator-open-eacces',
430 'retry': base / 'unconfined-retry-open',
431 'foreign': base / 'owner-check-would-refuse',
432 }
433 for directory in (src, partial, secret):
434 directory.mkdir(parents=True)
435
436 old_partial = b'OLD-PARTIAL-BASIS-' * 4096
437 new_source = b'NEW-REMOTE-PAYLOAD' * 4096
438 secret_data = b'OTHER-USER-SECRET!' * 4096
439 if not (len(old_partial) == len(new_source) == len(secret_data)):
440 raise AssertionError('PoC payloads must be equal length')
441 (partial / 'victim').write_bytes(old_partial)
442 (secret / 'victim').write_bytes(secret_data)
443 (src / 'victim').write_bytes(new_source)
444
445 hook_src = base / 'hook.c'
446 hook_lib = base / 'hook.so'
447 hook_src.write_text(hook_code)
448 build = subprocess.run(
449 ['cc', '-shared', '-fPIC', '-o', str(hook_lib), str(hook_src), '-ldl'],
450 stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
451 if build.returncode != 0:
452 test_skipped(f'cannot build LD_PRELOAD partial retry hook: {build.stdout!r}')
453
454 run_env = os.environ.copy()
455 run_env.update({
456 'LD_PRELOAD': str(hook_lib),
457 'RSYNC_PARTIAL_RETRY_DIR': str(partial),
458 'RSYNC_PARTIAL_RETRY_HELD': str(held),
459 'RSYNC_PARTIAL_RETRY_SECRET': str(secret),
460 'RSYNC_PARTIAL_RETRY_LOAD_MARKER': str(markers['load']),
461 'RSYNC_PARTIAL_RETRY_EACCES_MARKER': str(markers['eacces']),
462 'RSYNC_PARTIAL_RETRY_OPEN_MARKER': str(markers['retry']),
463 'RSYNC_PARTIAL_RETRY_FOREIGN_MARKER': str(markers['foreign']),
464 })
465
466 result = subprocess.run(
467 rsync_argv('-rtI', '--partial', '--partial-dir=pdir',
468 '--no-inc-recursive', f'{src}/', f'{mod}/'),
469 stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, env=run_env)
470
471 if held.exists():
472 if partial.is_symlink():
473 partial.unlink()
474 held.rename(partial)
475
476 ctx = f'rc={result.returncode}, output={result.stdout!r}'
477 # A negative returncode is death by signal. That is never a reason to skip:
478 # the hook killing the process under test is a bug in the hook, and reporting
479 # it as "not loaded" is exactly how a SIGSEGV on AlmaLinux 8 hid for weeks --
480 # the marker is written by the hook, so a crash before that looks identical
481 # to the hook never having loaded.
482 if result.returncode is not None and result.returncode < 0:
483 test_fail(f'rsync died by signal {-result.returncode} under the '
484 f'LD_PRELOAD hook ({ctx})')
485 if not markers['load'].exists():
486 test_skipped(f'LD_PRELOAD hook was not loaded ({ctx})')
487 if not markers['eacces'].exists():
488 test_fail('positive control failed: receiver did not open the existing '
489 f'partial file with O_CREAT ({ctx})')
490
491 # The escape check must come before the ownership-walk control below: on a
492 # vulnerable build no walk runs at all, and that has to be reported as the
493 # escape it is rather than as an inconclusive control failure.
494 observed = (secret / 'victim').read_bytes()
495 if observed == new_source:
496 test_fail('EACCES recovery dropped partial-dir ownership policy and '
497 f'overwrote a different file through the raced symlink ({ctx})')
498 if observed != secret_data:
499 test_fail(f'outside-policy target has unexpected contents ({ctx})')
500 if markers['retry'].exists():
501 test_fail('an unconfined retry opened the victim through the raced '
502 f'partial-dir symlink ({ctx})')
503
504 # Anti-vacuity: nothing was overwritten -- prove that is the ownership walk
505 # refusing the swap, not the scenario failing to arm.
506 if not markers['foreign'].exists():
507 test_fail('inconclusive: the recovery never inspected the raced '
508 f'partial-dir symlink, so no ownership check ran ({ctx})')
509
510
511 run()
512 print('protected_regular compatibility retry retained partial-dir ownership policy')