Skip to content

Commit a9de206

Browse files
authored
Merge pull request #236 from CoreTrace/feat/sarif-injection
feat(sarif): export the injection kind of command-injection results
2 parents 6e2baa9 + b078ff3 commit a9de206

3 files changed

Lines changed: 65 additions & 1 deletion

File tree

‎docs/usage.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ variable is not treated that way yet.
120120

121121
| Rule | Reached sink |
122122
|---|---|
123-
| `command-injection` | Shell or process execution (`os.system`, `subprocess` with a string, …), judged on what the input controls in the command. A string a shell runs, a string naming the program, the program itself, or an operand the program runs as a command (after the host for `ssh`, the program of `sudo`, `env`, `xargs`, `timeout`…, any argument of a batch file) is `high`. The script an interpreter runs (`bash run.sh`, `python tool.py`, its first operand when no option such as `-c` gives the code), or the module of `python -m`, is `high` and kept for review: execution is possible, and its exploitability depends on the file the input chooses. The arguments after a script or code are the script's own: options of unknown meaning, reported `medium` (a hotspot after an option of the script), refuted behind a constant prefix. Otherwise an element of an argument list run without a shell can only be read as an option: `medium`, or `high` when a documented option of the program runs a command it chooses (`git push --receive-pack=…`, `ssh -o ProxyCommand=…`). A value a documented option takes is judged by what the option does with it, whatever its prefix: run it (`sh -c`, `cmd /c`, `python -c`: `high`), keep it as data (`git commit -m`: refuted). After an option the rule does not know, the finding stays a hotspot to review. A constant prefix that keeps a standalone input from being an option (`f"v{version}"`), or an operand after `--` for a program that honours it, is refuted. Every case keeps the rule id `command-injection`, so suppressions and baselines match whatever the case. When the rule reads the command element by element and establishes what the input is there, the finding's `injection` metadata (in the JSON report) says so: `command` when the input runs or chooses what runs (a shell string, the program, an operand run as a command, the value of an option that runs it); `option` when it can only reach the program as an option or as the value of an option not established to run it, and the message is then titled `Option injection`. When that cannot be established (an option whose effect is to review, an unknown program or element before the input, a command that is not a list or tuple display, a sink such as `os.system` the rule does not read element by element), the metadata is absent and the title stays `Command injection`. |
123+
| `command-injection` | Shell or process execution (`os.system`, `subprocess` with a string, …), judged on what the input controls in the command. A string a shell runs, a string naming the program, the program itself, or an operand the program runs as a command (after the host for `ssh`, the program of `sudo`, `env`, `xargs`, `timeout`…, any argument of a batch file) is `high`. The script an interpreter runs (`bash run.sh`, `python tool.py`, its first operand when no option such as `-c` gives the code), or the module of `python -m`, is `high` and kept for review: execution is possible, and its exploitability depends on the file the input chooses. The arguments after a script or code are the script's own: options of unknown meaning, reported `medium` (a hotspot after an option of the script), refuted behind a constant prefix. Otherwise an element of an argument list run without a shell can only be read as an option: `medium`, or `high` when a documented option of the program runs a command it chooses (`git push --receive-pack=…`, `ssh -o ProxyCommand=…`). A value a documented option takes is judged by what the option does with it, whatever its prefix: run it (`sh -c`, `cmd /c`, `python -c`: `high`), keep it as data (`git commit -m`: refuted). After an option the rule does not know, the finding stays a hotspot to review. A constant prefix that keeps a standalone input from being an option (`f"v{version}"`), or an operand after `--` for a program that honours it, is refuted. Every case keeps the rule id `command-injection`, so suppressions and baselines match whatever the case. When the rule reads the command element by element and establishes what the input is there, the finding's `injection` metadata (in the JSON report, and as the only property of its SARIF result) says so: `command` when the input runs or chooses what runs (a shell string, the program, an operand run as a command, the value of an option that runs it); `option` when it can only reach the program as an option or as the value of an option not established to run it, and the message is then titled `Option injection`. When that cannot be established (an option whose effect is to review, an unknown program or element before the input, a command that is not a list or tuple display, a sink such as `os.system` the rule does not read element by element), the metadata is absent and the title stays `Command injection`. |
124124
| `code-injection` | The code `eval` or `exec` runs; the globals and locals passed with it are data. `dangerous-eval` reports every such call, this rule the ones attacker input reaches. |
125125
| `sql-injection` | A database statement (`cursor.execute`, SQLAlchemy `text`, Django `raw`, …). Parameters of a parameterised query are not statements. |
126126
| `nosql-injection` | A NoSQL query, such as a MongoDB filter, given attacker input that may hold a structure: a JSON body giving `{"$ne": null}` matches any value. The input that may hold a structure is JSON, the raw bodies a `json.loads` decodes, files, WebSocket messages and standard input. Text cannot hold an operator: form fields, query parameters, headers, cookies, URL parameters, the command line, the environment, and an entry-point parameter annotated with scalars (`str`, `int`, `Optional[str]`, `Annotated[str, Query()]`, `list[str]`, …), which FastAPI validates. A Django, REST framework, aiohttp or tornado view reads a request object: its text attributes (`GET`, `POST`, `headers`, `query_params`, `query`, `match_info`, `arguments`, …) and the URL parameters after it are text, its body, files and `data` are not. Limits: a helper function the request is passed to reads it as a whole; the keys of a dict are not followed, so a string concatenated into `$where` is not reported. The analyzer ships no NoSQL sink: model plugins declare them. |

‎src/coretrace_python/reporters/sarif.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,9 @@
1919
Severity.LOW: "note",
2020
Severity.INFO: "note",
2121
}
22+
# The kinds of injection a finding may carry, the only metadata a result exports: other
23+
# metadata, such as evidence, may quote what the analysed code holds.
24+
_INJECTIONS = frozenset({"option", "command"})
2225

2326

2427
def _artifact(report: Report, path: str) -> dict[str, str]:
@@ -53,6 +56,9 @@ def _result(
5356
"message": {"text": finding.message},
5457
"locations": [location],
5558
}
59+
injection = finding.metadata.get("injection")
60+
if injection in _INJECTIONS:
61+
result["properties"] = {"injection": injection}
5662
if suppressed:
5763
result["suppressions"] = [{"kind": "inSource"}]
5864
if baseline_state is not None:

‎tests/test_sarif_injection.py‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
"""Acceptance tests: the kind of a command injection in the SARIF log (#220).
2+
3+
A SARIF result carries the ``injection`` of its finding in its ``properties`` when the
4+
rule established it, ``option`` or ``command``, and no ``injection`` when it could not.
5+
No other metadata of a finding is exported there: some, such as evidence, may quote
6+
what the analysed code holds.
7+
"""
8+
9+
from __future__ import annotations
10+
11+
import json
12+
from pathlib import Path
13+
14+
import pytest
15+
16+
from coretrace_python.cli import main
17+
18+
CALLS = {
19+
"option.py": 'subprocess.run(["ls", sys.argv[1]])',
20+
"command.py": 'subprocess.run(["sh", "-c", sys.argv[1]])',
21+
"unknown.py": 'subprocess.run(["python", "-m", sys.argv[1]])',
22+
"shell.py": "os.system(sys.argv[1])",
23+
}
24+
25+
26+
@pytest.fixture
27+
def results(
28+
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
29+
) -> dict[str, dict[str, object]]:
30+
root = tmp_path / "proj"
31+
root.mkdir()
32+
for name, call in CALLS.items():
33+
(root / name).write_text(
34+
f"import os\nimport subprocess\nimport sys\n\n\ndef run():\n {call}\n",
35+
encoding="utf-8",
36+
)
37+
monkeypatch.chdir(tmp_path)
38+
main(["--check", "proj", "--format", "sarif"])
39+
log = json.loads(capsys.readouterr().out)
40+
return {
41+
r["locations"][0]["physicalLocation"]["artifactLocation"]["uri"]: r
42+
for r in log["runs"][0]["results"]
43+
if r["ruleId"] == "command-injection"
44+
}
45+
46+
47+
def test_a_result_carries_the_injection_its_rule_established(
48+
results: dict[str, dict[str, object]],
49+
) -> None:
50+
assert results["option.py"]["properties"] == {"injection": "option"}
51+
assert results["command.py"]["properties"] == {"injection": "command"}
52+
53+
54+
def test_a_result_whose_injection_is_not_established_has_none(
55+
results: dict[str, dict[str, object]],
56+
) -> None:
57+
assert "properties" not in results["unknown.py"]
58+
assert "properties" not in results["shell.py"]

0 commit comments

Comments
 (0)