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..5a546ec --- /dev/null +++ b/.github/workflows/fuzz.yml @@ -0,0 +1,48 @@ +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 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 + pull_request: + paths: ["bite.py", "tests/fuzz_atheris.py", "tests/fuzz_oracle.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 + 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 }} + # 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 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 '^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/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml index 36e6c28..4d8b5cd 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 queues up to one more run on the newest main; a running one finishes (both uploads) + group: scorecard-${{ github.ref }} + cancel-in-progress: false + jobs: analysis: runs-on: ubuntu-latest 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-* diff --git a/bite.py b/bite.py index 77203f1..5e8e862 100644 --- a/bite.py +++ b/bite.py @@ -226,12 +226,29 @@ 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(" \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) + + 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. 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 ;. 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] - 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() + 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) @@ -284,7 +301,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 new file mode 100644 index 0000000..a4b4365 --- /dev/null +++ b/tests/fuzz_atheris.py @@ -0,0 +1,71 @@ +"""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, 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 (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_). + + 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)) +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", "\"find\"", "x\";\"", "echo", "key.txt", ".env", ".ENV.local", "../", "/etc/passwd", "~", + "$HOME", "${X}", "$(id)", "`id`", ">", ">>", "<", "`", "$(")): + 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 new file mode 100644 index 0000000..db0d4ec --- /dev/null +++ b/tests/test_command_filter_quotes.py @@ -0,0 +1,78 @@ +"""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_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_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', '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 + + +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_not_a_crash(tmp_path): + # Found by tests/fuzz_atheris.py: Path.exists() raised "File name too long" out of the filter. + 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