| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
import os |
| 10 |
import shutil |
| 11 |
import subprocess |
| 12 |
import sys |
| 13 |
from pathlib import Path |
| 14 |
|
| 15 |
from rsyncfns import TMPDIR, run_rsync, test_fail, test_skipped |
| 16 |
|
| 17 |
|
| 18 |
pr_path = Path('/proc/sys/fs/protected_regular') |
| 19 |
if not pr_path.is_file(): |
| 20 |
test_skipped("Can't find protected_regular setting (only available on Linux)") |
| 21 |
|
| 22 |
try: |
| 23 |
pr_lvl = pr_path.read_text().strip() |
| 24 |
except OSError: |
| 25 |
test_skipped("Can't check if fs.protected_regular is enabled") |
| 26 |
if pr_lvl == '0': |
| 27 |
test_skipped("fs.protected_regular is not enabled") |
| 28 |
|
| 29 |
workdir = TMPDIR / 'files' |
| 30 |
workdir.mkdir(parents=True, exist_ok=True) |
| 31 |
os.chmod(workdir, 0o1777) |
| 32 |
|
| 33 |
(workdir / 'src').write_text("Source\n") |
| 34 |
(workdir / 'dst').write_text("") |
| 35 |
|
| 36 |
|
| 37 |
def _chown_5001(path: Path) -> bool: |
| 38 |
"""Try to chown(2) `path` to uid 5001. Returns True on success.""" |
| 39 |
try: |
| 40 |
os.chown(path, 5001, -1) |
| 41 |
return True |
| 42 |
except PermissionError: |
| 43 |
return False |
| 44 |
|
| 45 |
|
| 46 |
if not _chown_5001(workdir / 'dst'): |
| 47 |
|
| 48 |
|
| 49 |
if not os.environ.get('RSYNC_UNSHARED'): |
| 50 |
unshare = shutil.which('unshare') |
| 51 |
if unshare is not None: |
| •52 |
try: |
| 53 |
probe = subprocess.run( |
| 54 |
[unshare, '--user', '--map-root-user', |
| 55 |
'--map-users', '5001:100000:1', 'true'], |
| 56 |
stdin=subprocess.DEVNULL, |
| 57 |
stdout=subprocess.DEVNULL, |
| 58 |
stderr=subprocess.DEVNULL, |
| 59 |
timeout=5, |
| 60 |
) |
| 61 |
except subprocess.TimeoutExpired: |
| 62 |
test_skipped("Can't chown (unshare probe timed out)") |
| 63 |
if probe.returncode == 0: |
| 64 |
print("Re-running under unshare with UID mapping...") |
| 65 |
env = os.environ.copy() |
| 66 |
env['RSYNC_UNSHARED'] = '1' |
| 67 |
os.execvpe( |
| 68 |
unshare, |
| 69 |
[unshare, '--user', '--map-root-user', |
| 70 |
'--map-users', '5001:100000:1', |
| 71 |
sys.executable, __file__], |
| 72 |
env, |
| 73 |
) |
| 74 |
test_skipped("Can't chown (need root or unshare with uidmap)") |
| 75 |
|
| 76 |
print(f"Contents of {workdir}:") |
| 77 |
subprocess.run(['ls', '-al', str(workdir)]) |
| 78 |
|
| 79 |
run_rsync('--inplace', str(workdir / 'src'), str(workdir / 'dst')) |
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
dst_content = (workdir / 'dst').read_text() |
| 84 |
if dst_content != "Source\n": |
| 85 |
test_fail(f"--inplace did not write the source content into the protected " |
| 86 |
f"dst: got {dst_content!r}") |