From bf119f68676eed0c34444f9de62aecbbd937c29d Mon Sep 17 00:00:00 2001 From: CH <340279802+connabyss@users.noreply.github.com> Date: Fri, 4 Dec 2026 08:22:57 +0000 Subject: [PATCH 1/6] ci: Atheris fuzzer for the worker's command filter, Scorecard re-runs on every merge tests/fuzz_atheris.py throws random commands at bite.command_ok and checks it never crashes and never lets through a redirect, a secret file name or a dangerous word outside quotes. New fuzz workflow: 10 min weekly, 1 min on PRs touching bite.py, hash-pinned. 232,316 local runs, no find. Scorecard now also runs on push to main, so a fix clears its alert right away. Assisted-by: Claude Code Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0175Q8iDuZWMcMmH9Uh7ywJN --- .github/requirements/atheris.txt | 6 +++ .github/workflows/fuzz.yml | 54 +++++++++++++++++++++++++ .github/workflows/scorecard.yml | 12 +++++- tests/fuzz_atheris.py | 69 ++++++++++++++++++++++++++++++++ 4 files changed, 139 insertions(+), 2 deletions(-) create mode 100644 .github/requirements/atheris.txt create mode 100644 .github/workflows/fuzz.yml create mode 100644 tests/fuzz_atheris.py diff --git a/.github/requirements/atheris.txt b/.github/requirements/atheris.txt new file mode 100644 index 0000000..9d5622a --- /dev/null +++ b/.github/requirements/atheris.txt @@ -0,0 +1,6 @@ +# Atheris (coverage-guided fuzzing) for tests/fuzz_atheris.py (the worker command filter) in .github/workflows/fuzz.yml. +# Hash-pinned (Scorecard Pinned-Dependencies). Linux x86-64 wheels only; the fuzz job runs on ubuntu-latest. +atheris==3.1.0 \ + --hash=sha256:ec5e11f21a4c197fe91f7aea2b2de88e623c73a21fc07b105ac6329a1588457b \ + --hash=sha256:f8a9f51ce8369026e8eb7b7174835e8c4c85a1a6db5d9add36c15100779d2a39 \ + --hash=sha256:315a0b5c819852b1ffe1ca72efc389c7724881f2c33e4aacb8c6bcec49bd5011 diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml new file mode 100644 index 0000000..9c3a46b --- /dev/null +++ b/.github/workflows/fuzz.yml @@ -0,0 +1,54 @@ +name: fuzz + +# Atheris (tests/fuzz_atheris.py), a coverage-guided fuzzer, throws random commands at the paid step's command +# filter (bite.command_ok) and keeps the ones that reach new code. A crash, or a command it lets through that has a +# redirect, a secret file name or a dangerous word outside quotes, is a find. 10 minutes weekly, 1 minute on pull +# requests that touch the filter. A weekly find opens one issue (label "fuzz"), and no new issue while one is open. +on: + schedule: + - cron: "29 6 * * 3" # Wednesdays 06:29 UTC + pull_request: + paths: ["bite.py", "tests/fuzz_atheris.py", ".github/requirements/atheris.txt", ".github/workflows/fuzz.yml"] + workflow_dispatch: + +permissions: {} + +concurrency: + group: fuzz-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + hunt: + runs-on: ubuntu-latest + timeout-minutes: 20 + permissions: + contents: read + issues: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: "3.12" + - name: coverage-guided (Atheris) + shell: bash + run: | + python -m pip install --require-hashes --no-deps -r .github/requirements/atheris.txt + secs=${{ github.event_name == 'pull_request' && 60 || 600 }} + set -o pipefail + python tests/fuzz_atheris.py -max_total_time="$secs" -timeout=30 -print_final_stats=1 2>&1 | tail -80 | tee atheris.log + - name: open one issue for the find + if: failure() && github.event_name != 'pull_request' + env: + GH_TOKEN: ${{ github.token }} + REPO: ${{ github.repository }} + RUN: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + [ -s atheris.log ] || exit 0 + gh label create fuzz --repo "$REPO" --color d93f0b --description "Found by the weekly fuzz run" 2>/dev/null || true + if [ "$(gh issue list --repo "$REPO" --label fuzz --state open --json number --jq length)" != "0" ]; then + echo "a fuzz issue is already open: not opening another"; exit 0; fi + { echo "The weekly fuzz run found something in the worker's command filter. Run: $RUN"; echo; echo '```'; tail -60 atheris.log; echo '```'; echo; + echo "Rerun locally: \`pip install atheris\`, then \`python tests/fuzz_atheris.py \`"; } > body.md + gh issue create --repo "$REPO" --label fuzz --title "fuzz: weekly run found a problem in the command filter" --body-file body.md diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml index 36e6c28..4150e88 100644 --- a/.github/workflows/scorecard.yml +++ b/.github/workflows/scorecard.yml @@ -2,9 +2,13 @@ name: scorecard # OpenSSF Scorecard grades this repo's safety habits (pinned actions, code review, branch protection, CodeQL and # more) from 0 to 10. Pros often look at it before they trust a stranger's tool. Runs every Saturday, so the Sunday -# findability report (connabyss/connabyss) shows a fresh score. Results go to the Security tab and to -# scorecard.dev, which feeds the README badge. It only reads the repo: no code from anyone else runs here. +# findability report (connabyss/connabyss) shows a fresh score. It also re-checks itself: every merge into main and +# every branch protection change runs it again, so a fix closes its alert minutes after it lands, not next Saturday. +# Results go to the Security tab and to scorecard.dev, which feeds the README badge. It only reads the repo: no +# code from anyone else runs here. on: + push: + branches: [main] schedule: - cron: "23 9 * * 6" # Saturdays 09:23 UTC branch_protection_rule: @@ -12,6 +16,10 @@ on: permissions: {} +concurrency: # a burst of merges runs it once, on the newest main + group: scorecard-${{ github.ref }} + cancel-in-progress: true + jobs: analysis: runs-on: ubuntu-latest diff --git a/tests/fuzz_atheris.py b/tests/fuzz_atheris.py new file mode 100644 index 0000000..41a38a0 --- /dev/null +++ b/tests/fuzz_atheris.py @@ -0,0 +1,69 @@ +"""Coverage-guided fuzzer for the worker's command filter (Atheris, Google's libFuzzer for Python). + +The paid step's worker may only run commands that bite.command_ok() lets through, so that filter is Bite's +main security line (SECURITY.md). This feeds it random commands, half raw text and half built from real shell +pieces (rm, curl, quotes, pipes, ../, key.txt ...), keeps the inputs that reach new code, and checks: + + - command_ok, split_commands, unquoted, uses_program and is_secret never raise on any text + - a command it lets through never has a redirect, heredoc or command substitution, never names a secret + file, and has no dangerous word outside quotes + +Any break prints the input. Not run by pytest (the file name doesn't start with test_). + + pip install atheris + python tests/fuzz_atheris.py -max_total_time=120 (any libFuzzer flag works; a find exits non-zero) +""" +import pathlib +import sys +import tempfile + +import atheris + +KIT = pathlib.Path(__file__).resolve().parent.parent +sys.path.insert(0, str(KIT)) + +with atheris.instrument_imports(): + import bite + +PIECES = ["ls", "cat", "grep -rn x .", "python -m pytest", "git log", "git push", "git -c x=y log", "rm -rf /", + "curl http://x", "find . -delete", "echo", "key.txt", ".env", ".ENV.local", "../", "/etc/passwd", "~", + "$HOME", "${X}", "$(id)", "`id`", ">", ">>", "<", "`", "$(")), f"let through a redirect or substitution: {cmd!r}" + assert not any(s in low for s in CFG.secrets), f"let through a secret file name: {cmd!r}" + assert not bite.DANGER.search(bite.unquoted(cmd)), f"let through a dangerous word: {cmd!r}" + + +def main(): + atheris.Setup(sys.argv, one_input) + atheris.Fuzz() + + +if __name__ == "__main__": + main() From 60ca173c2a2408fb81d473b002c201366cf01da3 Mon Sep 17 00:00:00 2001 From: CH <340279802+connabyss@users.noreply.github.com> Date: Fri, 4 Dec 2026 08:32:48 +0000 Subject: [PATCH 2/6] ci: fuzz finds stay private, Scorecard runs queue instead of cancelling A way past the command filter is a security hole, so the fuzz run only fails (emailing the maintainer) instead of opening a public issue. A newer Scorecard run now waits for a running one, so both uploads always finish. libFuzzer output files are git-ignored. (CodeRabbit review) Assisted-by: Claude Code Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0175Q8iDuZWMcMmH9Uh7ywJN --- .github/workflows/fuzz.yml | 18 ++---------------- .github/workflows/scorecard.yml | 4 ++-- .gitignore | 7 +++++++ 3 files changed, 11 insertions(+), 18 deletions(-) diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml index 9c3a46b..1c48a1d 100644 --- a/.github/workflows/fuzz.yml +++ b/.github/workflows/fuzz.yml @@ -3,7 +3,8 @@ name: fuzz # Atheris (tests/fuzz_atheris.py), a coverage-guided fuzzer, throws random commands at the paid step's command # filter (bite.command_ok) and keeps the ones that reach new code. A crash, or a command it lets through that has a # redirect, a secret file name or a dangerous word outside quotes, is a find. 10 minutes weekly, 1 minute on pull -# requests that touch the filter. A weekly find opens one issue (label "fuzz"), and no new issue while one is open. +# requests that touch the filter. A find fails the run, which emails the maintainer. It opens no public issue on +# purpose: a way past the filter is a security hole, and SECURITY.md asks for those to stay private until fixed. on: schedule: - cron: "29 6 * * 3" # Wednesdays 06:29 UTC @@ -23,7 +24,6 @@ jobs: timeout-minutes: 20 permissions: contents: read - issues: write steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -38,17 +38,3 @@ jobs: secs=${{ github.event_name == 'pull_request' && 60 || 600 }} set -o pipefail python tests/fuzz_atheris.py -max_total_time="$secs" -timeout=30 -print_final_stats=1 2>&1 | tail -80 | tee atheris.log - - name: open one issue for the find - if: failure() && github.event_name != 'pull_request' - env: - GH_TOKEN: ${{ github.token }} - REPO: ${{ github.repository }} - RUN: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} - run: | - [ -s atheris.log ] || exit 0 - gh label create fuzz --repo "$REPO" --color d93f0b --description "Found by the weekly fuzz run" 2>/dev/null || true - if [ "$(gh issue list --repo "$REPO" --label fuzz --state open --json number --jq length)" != "0" ]; then - echo "a fuzz issue is already open: not opening another"; exit 0; fi - { echo "The weekly fuzz run found something in the worker's command filter. Run: $RUN"; echo; echo '```'; tail -60 atheris.log; echo '```'; echo; - echo "Rerun locally: \`pip install atheris\`, then \`python tests/fuzz_atheris.py \`"; } > body.md - gh issue create --repo "$REPO" --label fuzz --title "fuzz: weekly run found a problem in the command filter" --body-file body.md diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml index 4150e88..4d8b5cd 100644 --- a/.github/workflows/scorecard.yml +++ b/.github/workflows/scorecard.yml @@ -16,9 +16,9 @@ on: permissions: {} -concurrency: # a burst of merges runs it once, on the newest main +concurrency: # a burst of merges queues up to one more run on the newest main; a running one finishes (both uploads) group: scorecard-${{ github.ref }} - cancel-in-progress: true + cancel-in-progress: false jobs: analysis: diff --git a/.gitignore b/.gitignore index 07b5e12..602ef7a 100644 --- a/.gitignore +++ b/.gitignore @@ -9,3 +9,10 @@ bot/night_clerk.json bot/*.pem bot/night_clerk_state.json bot/night_clerk.log + +# libFuzzer output from tests/fuzz_atheris.py +crash-* +slow-unit-* +timeout-* +oom-* +leak-* From b664d9171fef7dbfc3e511f7d4f9e8064ec9e8c4 Mon Sep 17 00:00:00 2001 From: CH <340279802+connabyss@users.noreply.github.com> Date: Fri, 4 Dec 2026 08:47:02 +0000 Subject: [PATCH 3/6] fix(bite): close two command-filter gaps, fuzz with an oracle of its own - unquoted() now keeps a quoted piece glued to the word before it, and option words without their quotes: find . -de"lete", find . -"delete" and sort "-o" x got past DANGER (found by CodeRabbit on this PR). - path_ok() refuses a name too long for the OS to look up instead of raising out of the filter (found by the new fuzzer in 60 s). - The fuzzer now checks accepted commands word by word as the shell reads them (shlex), not by rerunning the filter's own checks; it caught the -de"lete" gap on the old filter. Its messages carry no command, and CI prints only the seed and totals, so a find never lands in a public log. - tests/test_command_filter_quotes.py fails on the old filter (checked). Assisted-by: Claude Code Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0175Q8iDuZWMcMmH9Uh7ywJN --- .github/workflows/fuzz.yml | 11 ++++++-- bite.py | 12 ++++++--- tests/fuzz_atheris.py | 41 +++++++++++++++++++++++------ tests/test_command_filter_quotes.py | 36 +++++++++++++++++++++++++ 4 files changed, 87 insertions(+), 13 deletions(-) create mode 100644 tests/test_command_filter_quotes.py diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml index 1c48a1d..d33eeb1 100644 --- a/.github/workflows/fuzz.yml +++ b/.github/workflows/fuzz.yml @@ -36,5 +36,12 @@ jobs: run: | python -m pip install --require-hashes --no-deps -r .github/requirements/atheris.txt secs=${{ github.event_name == 'pull_request' && 60 || 600 }} - set -o pipefail - python tests/fuzz_atheris.py -max_total_time="$secs" -timeout=30 -print_final_stats=1 2>&1 | tail -80 | tee atheris.log + # The raw output stays on the runner: a find's traceback or input would spell out a way past the filter + # in a public log. Only the seed and the totals are printed; rerun locally to see the find. + status=0 + python tests/fuzz_atheris.py -max_total_time="$secs" -timeout=30 -print_final_stats=1 > atheris.log 2>&1 || status=$? + grep -E '^INFO: Seed:|^stat::number_of_executed_units' atheris.log || true + if [ "$status" != 0 ]; then + echo "::error::The fuzzer found a problem in the command filter. Details are kept off this public log: rerun tests/fuzz_atheris.py locally." + fi + exit "$status" diff --git a/bite.py b/bite.py index 77203f1..1ed8657 100644 --- a/bite.py +++ b/bite.py @@ -228,10 +228,13 @@ def split_commands(s: str) -> list: def unquoted(cmd: str) -> str: """The command with the inside of each quoted word blanked, except words that are options - ("--output=x" stays visible, so quoting a flag hides nothing).""" + ("--output=x" stays visible, so quoting a flag hides nothing). Those keep their text without the + quotes, the way the shell reads them, and so does a quoted piece glued to the word before it: + find . -de"lete" and sort "-o" x are -delete and -o to the shell, so they are to DANGER too.""" def keep(m): inner = m.group(0)[1:-1] - return m.group(0) if inner.lstrip().startswith("-") or "/proc" in inner else '""' + glued = m.start() > 0 and not m.string[m.start() - 1].isspace() + return inner if glued or inner.lstrip().startswith("-") or "/proc" in inner else '""' return re.sub(r"'[^']*'|\"[^\"]*\"", keep, cmd) @@ -284,7 +287,10 @@ def path_ok(tok: str, here: Path, cfg: Config) -> bool: if globbed: return False # /pro[c]/... or /e*/passwd: a pattern aimed outside the project first = Path(target.anchor) / target.parts[1] if len(target.parts) > 1 else Path(target.anchor) - return not first.exists() # "/api/" is a search word; "/etc/x" and "C:\Users" are places + try: + return not first.exists() # "/api/" is a search word; "/etc/x" and "C:\Users" are places + except OSError: + return False # a name too long (or too odd) for the OS to look up: refuse, don't crash the hook return False if not re.search(r"[/\\]", base) and base not in ("..", "."): return True # a plain name in the current folder (or a search word) diff --git a/tests/fuzz_atheris.py b/tests/fuzz_atheris.py index 41a38a0..e6d26eb 100644 --- a/tests/fuzz_atheris.py +++ b/tests/fuzz_atheris.py @@ -5,15 +5,19 @@ pieces (rm, curl, quotes, pipes, ../, key.txt ...), keeps the inputs that reach new code, and checks: - command_ok, split_commands, unquoted, uses_program and is_secret never raise on any text - - a command it lets through never has a redirect, heredoc or command substitution, never names a secret - file, and has no dangerous word outside quotes + - a command it lets through, read word by word the way the shell reads it (shlex, quotes removed), never + has a redirect, never names a secret file, and never passes find a deleting or running option, sort an + output file or any program --output (an oracle of its own, not the filter's checks run twice: it is how + find . -de"lete" was caught) -Any break prints the input. Not run by pytest (the file name doesn't start with test_). +A break raises with no command in the message, so CI logs don't spell out a way past the filter +(SECURITY.md). Not run by pytest (the file name doesn't start with test_). pip install atheris python tests/fuzz_atheris.py -max_total_time=120 (any libFuzzer flag works; a find exits non-zero) """ import pathlib +import shlex import sys import tempfile @@ -53,11 +57,32 @@ def one_input(data): bite.unquoted(cmd) bite.uses_program(cmd) bite.is_secret(cmd, CFG) - if bite.command_ok(cmd, CFG): - low = cmd.lower() - assert not any(t in cmd for t in ("<<", ">", "`", "$(")), f"let through a redirect or substitution: {cmd!r}" - assert not any(s in low for s in CFG.secrets), f"let through a secret file name: {cmd!r}" - assert not bite.DANGER.search(bite.unquoted(cmd)), f"let through a dangerous word: {cmd!r}" + if bite.command_ok(cmd, CFG) and not shell_safe(cmd): + raise AssertionError("the filter let through a command the shell would read as unsafe") + + +FIND_BAD = {"-delete", "-exec", "-execdir", "-ok", "-okdir", "-fprint", "-fprint0", "-fprintf", "-fls"} + + +def shell_safe(cmd): + """Read each segment the way the shell does and check the words themselves.""" + if any(t in cmd for t in ("<<", ">", "`", "$(")): + return False + for seg in bite.split_commands(cmd): + try: + words = shlex.split(seg, posix=True) + except ValueError: + continue # the filter refuses what shlex can't read; nothing to check + low = [w.lower() for w in words] + if any(any(w == s or w.startswith(s + ".") or w.endswith("/" + s) for s in CFG.secrets) for w in low): + return False + if "find" in low and FIND_BAD & set(low): + return False + if "sort" in low and any(w.startswith("-") and not w.startswith("--") and "o" in w[1:] for w in words): + return False + if any(w.startswith("--output") for w in low): + return False + return True def main(): diff --git a/tests/test_command_filter_quotes.py b/tests/test_command_filter_quotes.py new file mode 100644 index 0000000..4bfab9c --- /dev/null +++ b/tests/test_command_filter_quotes.py @@ -0,0 +1,36 @@ +"""The worker's command filter reads quotes the way the shell does. No network.""" + +import sys +from pathlib import Path + +KIT = Path(__file__).parent.parent +sys.path.insert(0, str(KIT)) + +import bite # noqa: E402 + + +def cfg(tmp_path): + ini = tmp_path / "f.ini" + ini.write_text(f"[bite]\nproject_folder = {tmp_path}\n", encoding="utf-8") + return bite.Config(ini) + + +def test_a_quote_inside_an_option_hides_nothing(tmp_path): + # Found by CodeRabbit on PR 321: the shell reads -de"lete" as -delete, and "-o" as -o. + c = cfg(tmp_path) + for cmd in ['find . -de"lete"', 'find . -"delete"', "find . -de''lete", 'sort "-o" x y', "sort -'o' x y", + 'find . "-de"lete']: + assert not bite.command_ok(cmd, c), cmd + + +def test_quoted_search_words_still_pass(tmp_path): + c = cfg(tmp_path) + for cmd in ['grep -rn "rm" .', "grep -n 'curl' notes.txt", 'echo "format"', "find . -name '*.py'"]: + assert bite.command_ok(cmd, c), cmd + + +def test_a_path_too_long_to_look_up_is_refused_not_a_crash(tmp_path): + # Found by tests/fuzz_atheris.py: Path.exists() raised "File name too long" out of the filter. + ok = bite.command_ok("cat /" + "x" * 5000, cfg(tmp_path)) # must not raise + if not bite.WINDOWS: # Windows may answer "no such file" instead, which makes it a harmless search word + assert ok is False From f01311692cd0944cd9169f48ead501a3680dc3d9 Mon Sep 17 00:00:00 2001 From: CH <340279802+connabyss@users.noreply.github.com> Date: Fri, 4 Dec 2026 13:05:05 +0000 Subject: [PATCH 4/6] fix(bite): a quoted ; no longer ends the find/sort option scan; oracle judges the program - unquoted(): a ; & | or line break kept from a glued quote (x";") becomes _, so find . -name x";" -o -delete is refused (CodeRabbit on PR 321). - The fuzzer's oracle moves to tests/fuzz_oracle.py (testable without atheris) and checks find/sort options only when find or sort is the program run. - The overlong-path test no longer depends on Python 3.14's exists(); a separate test makes exists() raise OSError and checks the refusal. Assisted-by: Claude Code Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0175Q8iDuZWMcMmH9Uh7ywJN --- .github/workflows/fuzz.yml | 2 +- bite.py | 8 ++++-- tests/fuzz_atheris.py | 33 ++++------------------ tests/fuzz_oracle.py | 44 +++++++++++++++++++++++++++++ tests/test_command_filter_quotes.py | 39 ++++++++++++++++++++++--- 5 files changed, 91 insertions(+), 35 deletions(-) create mode 100644 tests/fuzz_oracle.py diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml index d33eeb1..a23aecd 100644 --- a/.github/workflows/fuzz.yml +++ b/.github/workflows/fuzz.yml @@ -9,7 +9,7 @@ on: schedule: - cron: "29 6 * * 3" # Wednesdays 06:29 UTC pull_request: - paths: ["bite.py", "tests/fuzz_atheris.py", ".github/requirements/atheris.txt", ".github/workflows/fuzz.yml"] + paths: ["bite.py", "tests/fuzz_atheris.py", "tests/fuzz_oracle.py", ".github/requirements/atheris.txt", ".github/workflows/fuzz.yml"] workflow_dispatch: permissions: {} diff --git a/bite.py b/bite.py index 1ed8657..e2f8fcf 100644 --- a/bite.py +++ b/bite.py @@ -230,11 +230,15 @@ def unquoted(cmd: str) -> str: """The command with the inside of each quoted word blanked, except words that are options ("--output=x" stays visible, so quoting a flag hides nothing). Those keep their text without the quotes, the way the shell reads them, and so does a quoted piece glued to the word before it: - find . -de"lete" and sort "-o" x are -delete and -o to the shell, so they are to DANGER too.""" + find . -de"lete" and sort "-o" x are -delete and -o to the shell, so they are to DANGER too. A ; & | or + line break kept that way is plain text to the shell, so it becomes _ here: find . -name x";" -o -delete + is one find to the shell, and DANGER must not stop reading its options at that ;.""" def keep(m): inner = m.group(0)[1:-1] glued = m.start() > 0 and not m.string[m.start() - 1].isspace() - return inner if glued or inner.lstrip().startswith("-") or "/proc" in inner else '""' + if glued or inner.lstrip().startswith("-") or "/proc" in inner: + return re.sub(r"[;&|\r\n]", "_", inner) + return '""' return re.sub(r"'[^']*'|\"[^\"]*\"", keep, cmd) diff --git a/tests/fuzz_atheris.py b/tests/fuzz_atheris.py index e6d26eb..79adc8a 100644 --- a/tests/fuzz_atheris.py +++ b/tests/fuzz_atheris.py @@ -7,8 +7,8 @@ - command_ok, split_commands, unquoted, uses_program and is_secret never raise on any text - a command it lets through, read word by word the way the shell reads it (shlex, quotes removed), never has a redirect, never names a secret file, and never passes find a deleting or running option, sort an - output file or any program --output (an oracle of its own, not the filter's checks run twice: it is how - find . -de"lete" was caught) + output file or any program --output (tests/fuzz_oracle.py: an oracle of its own, not the filter's + checks run twice; it flags find . -de"lete" against the old filter) A break raises with no command in the message, so CI logs don't spell out a way past the filter (SECURITY.md). Not run by pytest (the file name doesn't start with test_). @@ -17,7 +17,6 @@ python tests/fuzz_atheris.py -max_total_time=120 (any libFuzzer flag works; a find exits non-zero) """ import pathlib -import shlex import sys import tempfile @@ -25,9 +24,11 @@ KIT = pathlib.Path(__file__).resolve().parent.parent sys.path.insert(0, str(KIT)) +sys.path.insert(0, str(KIT / "tests")) with atheris.instrument_imports(): import bite + from fuzz_oracle import shell_safe PIECES = ["ls", "cat", "grep -rn x .", "python -m pytest", "git log", "git push", "git -c x=y log", "rm -rf /", "curl http://x", "find . -delete", "echo", "key.txt", ".env", ".ENV.local", "../", "/etc/passwd", "~", @@ -57,34 +58,10 @@ def one_input(data): bite.unquoted(cmd) bite.uses_program(cmd) bite.is_secret(cmd, CFG) - if bite.command_ok(cmd, CFG) and not shell_safe(cmd): + if bite.command_ok(cmd, CFG) and not shell_safe(cmd, CFG.secrets): raise AssertionError("the filter let through a command the shell would read as unsafe") -FIND_BAD = {"-delete", "-exec", "-execdir", "-ok", "-okdir", "-fprint", "-fprint0", "-fprintf", "-fls"} - - -def shell_safe(cmd): - """Read each segment the way the shell does and check the words themselves.""" - if any(t in cmd for t in ("<<", ">", "`", "$(")): - return False - for seg in bite.split_commands(cmd): - try: - words = shlex.split(seg, posix=True) - except ValueError: - continue # the filter refuses what shlex can't read; nothing to check - low = [w.lower() for w in words] - if any(any(w == s or w.startswith(s + ".") or w.endswith("/" + s) for s in CFG.secrets) for w in low): - return False - if "find" in low and FIND_BAD & set(low): - return False - if "sort" in low and any(w.startswith("-") and not w.startswith("--") and "o" in w[1:] for w in words): - return False - if any(w.startswith("--output") for w in low): - return False - return True - - def main(): atheris.Setup(sys.argv, one_input) atheris.Fuzz() diff --git a/tests/fuzz_oracle.py b/tests/fuzz_oracle.py new file mode 100644 index 0000000..8b59353 --- /dev/null +++ b/tests/fuzz_oracle.py @@ -0,0 +1,44 @@ +"""The fuzzer's own check of a command (tests/fuzz_atheris.py), kept apart so pytest can test it without atheris. + +It reads each segment word by word the way the shell does (shlex, quotes removed) instead of running the +filter's checks twice, so a quote trick that fools the filter doesn't fool it. +""" +import re +import shlex + +import bite + +FIND_BAD = {"-delete", "-exec", "-execdir", "-ok", "-okdir", "-fprint", "-fprint0", "-fprintf", "-fls"} +LAUNCHERS = {"do", "then", "else", "timeout", "xargs", "env", "nice", "nohup", "command", "exec", "sudo"} + + +def program(words): + """The word the shell runs: skip loop and launcher words (timeout 5s, xargs ...) and take the basename.""" + i = 0 + while i < len(words) and (words[i].lower() in LAUNCHERS or re.match(r"^\d+[smh]?$", words[i])): + i += 1 + return words[i].replace("\\", "/").rsplit("/", 1)[-1].lower() if i < len(words) else "" + + +def shell_safe(cmd, secrets): + """False if the shell would read cmd as a redirect, a secret file, find deleting or running something, + sort writing a file, or any --output.""" + if any(t in cmd for t in ("<<", ">", "`", "$(")): + return False + for seg in bite.split_commands(cmd): + try: + words = shlex.split(seg, posix=True) + except ValueError: + continue # the filter refuses what shlex can't read; nothing to check + low = [w.lower() for w in words] + if any(any(w == s or w.startswith(s + ".") or w.endswith("/" + s) for s in secrets) for w in low): + return False + prog = program(words) + if prog in ("find", "find.exe") and FIND_BAD & set(low): + return False + if prog in ("sort", "sort.exe") and any(w.startswith("-") and not w.startswith("--") and "o" in w[1:] + for w in words): + return False + if any(w.startswith("--output") for w in low): + return False + return True diff --git a/tests/test_command_filter_quotes.py b/tests/test_command_filter_quotes.py index 4bfab9c..eb45bc2 100644 --- a/tests/test_command_filter_quotes.py +++ b/tests/test_command_filter_quotes.py @@ -23,14 +23,45 @@ def test_a_quote_inside_an_option_hides_nothing(tmp_path): assert not bite.command_ok(cmd, c), cmd +def test_a_quoted_separator_does_not_end_the_option_scan(tmp_path): + # Found by CodeRabbit on PR 321: x";" is one word to the shell, so the find below still deletes. + c = cfg(tmp_path) + for cmd in ['find . -name x";" -o -delete', "find . -name x';' -o -delete", 'find . -name x"|" -o -delete', + 'find . -name x"&" -exec ls', 'sort x";" -o out y']: + assert not bite.command_ok(cmd, c), cmd + assert bite.command_ok('grep -n x";"y notes.txt', c) + + def test_quoted_search_words_still_pass(tmp_path): c = cfg(tmp_path) for cmd in ['grep -rn "rm" .', "grep -n 'curl' notes.txt", 'echo "format"', "find . -name '*.py'"]: assert bite.command_ok(cmd, c), cmd -def test_a_path_too_long_to_look_up_is_refused_not_a_crash(tmp_path): +def test_a_path_too_long_to_look_up_is_not_a_crash(tmp_path): # Found by tests/fuzz_atheris.py: Path.exists() raised "File name too long" out of the filter. - ok = bite.command_ok("cat /" + "x" * 5000, cfg(tmp_path)) # must not raise - if not bite.WINDOWS: # Windows may answer "no such file" instead, which makes it a harmless search word - assert ok is False + bite.command_ok("cat /" + "x" * 5000, cfg(tmp_path)) # must not raise (3.14's exists() answers False instead) + + +def test_a_path_the_os_cannot_look_up_is_refused(tmp_path, monkeypatch): + def cannot_look_up(self, *args, **kwargs): + raise OSError(36, "File name too long") + + c = cfg(tmp_path) + monkeypatch.setattr(bite.Path, "exists", cannot_look_up) + assert bite.command_ok("cat /" + "x" * 5000, c) is False + + +def test_the_fuzzer_oracle_judges_the_program_not_any_word(): + """The fuzzer's oracle must check find's and sort's options only when find or sort is the program run: + a grep that searches for the words find and -delete is a safe search, not a filter bypass.""" + sys.path.insert(0, str(KIT / "tests")) + from fuzz_oracle import shell_safe + + secrets = ["key.txt", ".env"] + for cmd in ('grep -e "find" -e "-delete" notes.txt', "grep -n sort -e -o notes.txt", "echo find -exec", + 'echo "sort" -o', 'echo "find" -delete'): + assert shell_safe(cmd, secrets), cmd + for cmd in ('find . -de"lete"', "timeout 5s find . -delete", "/usr/bin/find . -exec ls ;", "sort -o x y", + 'xargs find . "-delete"', "cat key.txt"): + assert not shell_safe(cmd, secrets), cmd From 66cee3a07f2358ca00560b9ac8ca617b1081ea3d Mon Sep 17 00:00:00 2001 From: CH <340279802+connabyss@users.noreply.github.com> Date: Fri, 4 Dec 2026 13:15:00 +0000 Subject: [PATCH 5/6] fix(bite): a quoted program name ("find" . -delete) is still the program to the filter unquoted() blanked every quoted word that wasn't an option, including the program itself, so DANGER never saw find in "find" . -delete or sort in 'sort' -o out (older than this PR; CodeRabbit on PR 321). A quoted word where the shell runs a program (first word, after ; | & ( or a line break, or after do/xargs/timeout ...) now keeps its text. Quoted search words like grep "rm" . still pass. The fuzzer's pieces gain "find" and x";" so it tries both tricks. Assisted-by: Claude Code Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0175Q8iDuZWMcMmH9Uh7ywJN --- bite.py | 14 ++++++++++++-- tests/fuzz_atheris.py | 2 +- tests/test_command_filter_quotes.py | 10 ++++++++++ 3 files changed, 23 insertions(+), 3 deletions(-) diff --git a/bite.py b/bite.py index e2f8fcf..af4a145 100644 --- a/bite.py +++ b/bite.py @@ -226,17 +226,27 @@ def split_commands(s: str) -> list: ENV_PEEK = re.compile(r"environ|\{[^}\s]*(,|\.\.)[^}\s]*\}", re.I) # /proc/self/environ, {k,x}ey.txt +def runs_here(before: str) -> bool: + """True if the next word of a command whose text so far is `before` is a program the shell runs: the + first word, a word after ; | & ( or a line break, or after a word that runs the next one (do, xargs ...).""" + before = before.rstrip() + return (not before or before[-1] in ";|&(\n" + or re.search(r"(^|[\s;|&(])(do|then|else|xargs|env|nice|nohup|command|exec|sudo|timeout(\s+\S+)?)$", + before) is not None) + + def unquoted(cmd: str) -> str: """The command with the inside of each quoted word blanked, except words that are options ("--output=x" stays visible, so quoting a flag hides nothing). Those keep their text without the quotes, the way the shell reads them, and so does a quoted piece glued to the word before it: find . -de"lete" and sort "-o" x are -delete and -o to the shell, so they are to DANGER too. A ; & | or line break kept that way is plain text to the shell, so it becomes _ here: find . -name x";" -o -delete - is one find to the shell, and DANGER must not stop reading its options at that ;.""" + is one find to the shell, and DANGER must not stop reading its options at that ;. A quoted word where the + shell runs a program ("find" . -delete) keeps its text too: it is the program, not a search word.""" def keep(m): inner = m.group(0)[1:-1] glued = m.start() > 0 and not m.string[m.start() - 1].isspace() - if glued or inner.lstrip().startswith("-") or "/proc" in inner: + if glued or inner.lstrip().startswith("-") or "/proc" in inner or runs_here(m.string[:m.start()]): return re.sub(r"[;&|\r\n]", "_", inner) return '""' return re.sub(r"'[^']*'|\"[^\"]*\"", keep, cmd) diff --git a/tests/fuzz_atheris.py b/tests/fuzz_atheris.py index 79adc8a..a4b4365 100644 --- a/tests/fuzz_atheris.py +++ b/tests/fuzz_atheris.py @@ -31,7 +31,7 @@ from fuzz_oracle import shell_safe PIECES = ["ls", "cat", "grep -rn x .", "python -m pytest", "git log", "git push", "git -c x=y log", "rm -rf /", - "curl http://x", "find . -delete", "echo", "key.txt", ".env", ".ENV.local", "../", "/etc/passwd", "~", + "curl http://x", "find . -delete", "\"find\"", "x\";\"", "echo", "key.txt", ".env", ".ENV.local", "../", "/etc/passwd", "~", "$HOME", "${X}", "$(id)", "`id`", ">", ">>", "< Date: Fri, 4 Dec 2026 13:18:16 +0000 Subject: [PATCH 6/6] fix(bite): a quoted program after a line break is still the program; fuzz log drops the seed - runs_here() trimmed the line break before checking for it, so ls"find" . -delete slipped through (CodeRabbit on PR 321). It now trims only spaces and tabs; the regression test covers \n and \r\n. - fuzz.yml no longer prints the libFuzzer seed: it could replay a find from the public log. Only the run count and a generic error are shown. Assisted-by: Claude Code Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0175Q8iDuZWMcMmH9Uh7ywJN --- .github/workflows/fuzz.yml | 5 +++-- bite.py | 2 +- tests/test_command_filter_quotes.py | 3 ++- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml index a23aecd..5a546ec 100644 --- a/.github/workflows/fuzz.yml +++ b/.github/workflows/fuzz.yml @@ -37,10 +37,11 @@ jobs: python -m pip install --require-hashes --no-deps -r .github/requirements/atheris.txt secs=${{ github.event_name == 'pull_request' && 60 || 600 }} # The raw output stays on the runner: a find's traceback or input would spell out a way past the filter - # in a public log. Only the seed and the totals are printed; rerun locally to see the find. + # in a public log. Only the run count is printed (not even the seed, which could replay a find); a + # maintainer reruns the fuzzer locally and reports a confirmed find as a private advisory (SECURITY.md). status=0 python tests/fuzz_atheris.py -max_total_time="$secs" -timeout=30 -print_final_stats=1 > atheris.log 2>&1 || status=$? - grep -E '^INFO: Seed:|^stat::number_of_executed_units' atheris.log || true + grep -E '^stat::number_of_executed_units' atheris.log || true if [ "$status" != 0 ]; then echo "::error::The fuzzer found a problem in the command filter. Details are kept off this public log: rerun tests/fuzz_atheris.py locally." fi diff --git a/bite.py b/bite.py index af4a145..5e8e862 100644 --- a/bite.py +++ b/bite.py @@ -229,7 +229,7 @@ def split_commands(s: str) -> list: def runs_here(before: str) -> bool: """True if the next word of a command whose text so far is `before` is a program the shell runs: the first word, a word after ; | & ( or a line break, or after a word that runs the next one (do, xargs ...).""" - before = before.rstrip() + before = before.rstrip(" \t") # spaces only: a line break before the word makes it a program too return (not before or before[-1] in ";|&(\n" or re.search(r"(^|[\s;|&(])(do|then|else|xargs|env|nice|nohup|command|exec|sudo|timeout(\s+\S+)?)$", before) is not None) diff --git a/tests/test_command_filter_quotes.py b/tests/test_command_filter_quotes.py index cc2c744..db0d4ec 100644 --- a/tests/test_command_filter_quotes.py +++ b/tests/test_command_filter_quotes.py @@ -36,7 +36,8 @@ def test_a_quoted_program_name_is_still_the_program(tmp_path): # Found by CodeRabbit on PR 321 (older than it): "find" was blanked to "", so DANGER never saw find. c = cfg(tmp_path) for cmd in ['"find" . -delete', "'sort' -o out x", 'ls; "find" . -delete', 'ls | "find" . -exec ls', - 'timeout 5s "find" . -delete', 'for f in *; do "find" $f -delete; done']: + 'timeout 5s "find" . -delete', 'for f in *; do "find" $f -delete; done', 'ls\n"find" . -delete', + "ls\r\n'sort' -o out x"]: assert not bite.command_ok(cmd, c), cmd for cmd in ['grep "find" -e x notes.txt', 'echo 5 "rm"', '"ls"', 'git log --grep "rm"']: assert bite.command_ok(cmd, c), cmd