| 1 | #!/usr/bin/env python3 |
| 2 | # Regression test: the generated --write-batch replay script writes filter rules |
| 3 | # into a `<<'#E#'` here-doc, one rule per line. A filter pattern that contains |
| 4 | # an embedded newline followed by a line equal to the here-doc terminator "#E#" |
| 5 | # could close the here-doc early and turn the remaining pattern bytes into shell |
| 6 | # commands in the replay .sh. Command-line --filter/--exclude/--include keep an |
| 7 | # embedded newline (no word-splitting), and such a pattern can also come from a |
| 8 | # NUL-separated --exclude-from in an untrusted tree. The batch writer must refuse |
| 9 | # a newline-bearing pattern (fail-closed) so no injectable script is produced. |
| 10 | |
| 11 | import os |
| 12 | import subprocess |
| 13 | |
| 14 | from rsyncfns import SCRATCHDIR, rmtree, run_rsync, test_fail |
| 15 | |
| 16 | base = SCRATCHDIR / 'wb-filter-inj' |
| 17 | rmtree(base) |
| 18 | src = base / 'src' |
| 19 | src.mkdir(parents=True) |
| 20 | (src / 'keep').write_text("hello\n") |
| 21 | |
| 22 | # Relative sentinel path so a fired injection lands here, where we run the .sh. |
| 23 | os.chdir(base) |
| 24 | sentinel = base / 'PWNED_FILTER' |
| 25 | if sentinel.exists(): |
| 26 | sentinel.unlink() |
| 27 | |
| 28 | # A single filter rule whose pattern embeds: <newline> #E# <newline> touch ... |
| 29 | # Pre-fix this renders as |
| 30 | # - keep |
| 31 | # #E# |
| 32 | # touch PWNED_FILTER |
| 33 | # inside the here-doc, so the "#E#" line closes it early and the touch runs as a |
| 34 | # shell command when the replay script is executed. |
| 35 | evil = "- keep\n#E#\ntouch PWNED_FILTER" |
| 36 | |
| 37 | # check=False: the fixed binary refuses (exits non-zero) and the transfer itself |
| 38 | # may not complete; we judge solely by whether the injection can fire. |
| 39 | run_rsync('-a', '--write-batch=B', f'--filter={evil}', 'src/', 'dest/', check=False) |
| 40 | |
| 41 | batch_sh = base / 'B.sh' |
| 42 | if batch_sh.exists(): |
| 43 | # The replay script must not, when run, execute the injected command. |
| 44 | subprocess.run(['sh', 'B.sh'], |
| 45 | stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, |
| 46 | cwd=str(base), env=os.environ.copy()) |
| 47 | |
| 48 | if sentinel.exists(): |
| 49 | script = batch_sh.read_text() if batch_sh.exists() else '<no script>' |
| 50 | test_fail("a newline in a filter rule forged the here-doc terminator and " |
| 51 | f"injected a shell command into the replay script:\n{script}") |
| 52 | |
| 53 | print("write-batch-filter-injection: a newline-bearing filter rule cannot " |
| 54 | "inject into the replay script") |