Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .github/requirements/atheris.txt
Original file line number Diff line number Diff line change
@@ -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
48 changes: 48 additions & 0 deletions .github/workflows/fuzz.yml
Original file line number Diff line number Diff line change
@@ -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"
12 changes: 10 additions & 2 deletions .github/workflows/scorecard.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,24 @@ 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:
workflow_dispatch:

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
Expand Down
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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-*
26 changes: 23 additions & 3 deletions bite.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 '""'
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
return re.sub(r"'[^']*'|\"[^\"]*\"", keep, cmd)


Expand Down Expand Up @@ -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)
Expand Down
71 changes: 71 additions & 0 deletions tests/fuzz_atheris.py
Original file line number Diff line number Diff line change
@@ -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`", ">", ">>", "<<EOF", "|", "||", "&&", ";", "\n", "'", '"', "\\", " ",
"--output=x", "-O", "for f in *; do cat $f; done", "if true; then ls; fi", "sort -o x", "/proc/self",
"/dev/tcp/1/2", "timeout 5s", "cd ..", "cd sub", "C:\\Windows", "%USERPROFILE%", "format", "\t"]


def make_config():
project = pathlib.Path(tempfile.mkdtemp(prefix="bite_fuzz_"))
(project / "sub").mkdir()
ini = project / "fuzz.ini"
ini.write_text(f"[bite]\nproject_folder = {project}\nallowed_programs = python, pytest\n", encoding="utf-8")
return bite.Config(ini)


CFG = make_config()


def one_input(data):
fdp = atheris.FuzzedDataProvider(data)
if fdp.ConsumeBool():
cmd = fdp.ConsumeUnicodeNoSurrogates(300)
else:
cmd = " ".join(PIECES[fdp.ConsumeIntInRange(0, len(PIECES) - 1)] for _ in range(fdp.ConsumeIntInRange(1, 12)))
bite.split_commands(cmd)
bite.unquoted(cmd)
bite.uses_program(cmd)
bite.is_secret(cmd, CFG)
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")


def main():
atheris.Setup(sys.argv, one_input)
atheris.Fuzz()


if __name__ == "__main__":
main()
44 changes: 44 additions & 0 deletions tests/fuzz_oracle.py
Original file line number Diff line number Diff line change
@@ -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
78 changes: 78 additions & 0 deletions tests/test_command_filter_quotes.py
Original file line number Diff line number Diff line change
@@ -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