Skip to content

Commit 1fe578d

Browse files
committed
fix(summaries): keep a nonlocal's value where a nested function may leave it unwritten
NonlocalWrite.kept says the function may return without writing the name, and no record means it never does; NonlocalResult carries the variable's value before the call, which the caller keeps there, joined with what may be written. A write that cannot run, a write on some paths only, or none at all no longer erases the caller's taint. PyIR schema 2, cache format 16. Part of #258.
1 parent b2fe078 commit 1fe578d

8 files changed

Lines changed: 198 additions & 25 deletions

File tree

‎docs/usage.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -917,7 +917,10 @@ such as `metaclass=`, `with` targets of any assignable form and `match` with eve
917917
pattern kind. `finally` is modelled on the normal path only. A
918918
`nonlocal` write made by a nested function flows back to the enclosing variable when the
919919
enclosing function calls that nested function directly by name; a nested function passed
920-
around and called elsewhere keeps its writes to itself. Methods of module-level classes are
920+
around and called elsewhere keeps its writes to itself. Where the nested function may
921+
return without writing the name (no write on some path, a write constant propagation
922+
proves cannot run, or an exception before it), the variable keeps the value it had
923+
before the call, joined with what may be written; only a write on every path replaces it. Methods of module-level classes are
921924
analysed like functions.
922925

923926
## Looking at the intermediate representation

‎src/coretrace_python/cache.py‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@
4242
from coretrace_python.semantic.symbols import SymbolId
4343
from coretrace_python.source import FileLocation, Location, SourceId, SourceSpan
4444

45-
CACHE_FORMAT = 15
45+
CACHE_FORMAT = 16
4646

4747

4848
@dataclass(frozen=True)
@@ -300,7 +300,12 @@ def _encode_summary(summary: FunctionSummary) -> dict[str, Any]:
300300
],
301301
"side_effects": sorted(summary.side_effects),
302302
"nonlocal_writes": [
303-
{"name": w.name, "dependencies": sorted(w.dependencies), "externals": sorted(str(s) for s in w.externals)}
303+
{
304+
"name": w.name,
305+
"dependencies": sorted(w.dependencies),
306+
"externals": sorted(str(s) for s in w.externals),
307+
"kept": w.kept,
308+
}
304309
for w in summary.nonlocal_writes
305310
],
306311
"static": summary.static,
@@ -328,7 +333,10 @@ def _decode_summary(data: Mapping[str, Any]) -> FunctionSummary:
328333
frozenset(_string(name) for name in data["side_effects"]),
329334
tuple(
330335
NonlocalWrite(
331-
_string(w["name"]), _indices(w["dependencies"]), frozenset(SymbolId(_string(s)) for s in w["externals"])
336+
_string(w["name"]),
337+
_indices(w["dependencies"]),
338+
frozenset(SymbolId(_string(s)) for s in w["externals"]),
339+
bool(w["kept"]),
332340
)
333341
for w in data["nonlocal_writes"]
334342
),

‎src/coretrace_python/interprocedural/summaries.py‎

Lines changed: 47 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -332,11 +332,15 @@ class Mutation:
332332
@dataclass(frozen=True)
333333
class NonlocalWrite:
334334
"""What the function stores into its ``nonlocal`` ``name``: data of its parameters
335-
and results of external symbols, written back to the caller's variable."""
335+
and results of external symbols, written back to the caller's variable. ``kept``
336+
says it may also return without writing it, on a path with no reachable write, so
337+
the caller's variable may keep the value it had. A function with no record for a
338+
``nonlocal`` never writes it (#258)."""
336339

337340
name: str
338341
dependencies: Dependencies
339342
externals: frozenset[SymbolId]
343+
kept: bool = False
340344

341345

342346
@dataclass(frozen=True)
@@ -602,14 +606,17 @@ def call(self, call: Call, state: dict[Key, Dep]) -> Dep:
602606
return everything | state.get(call.callee, EMPTY)
603607

604608
def nonlocal_result(self, instruction: NonlocalResult, state: dict[Key, Dep]) -> Dep:
605-
"""What the nested callee left in its nonlocal ``name``, in the caller's terms."""
609+
"""What the nested callee left in its nonlocal ``name``, in the caller's terms:
610+
what it may write, and the value before the call wherever it may leave the name
611+
unwritten, or when what it does is not known."""
606612

613+
previous = self.deep(instruction.previous, state)
607614
call = self.defs.get(instruction.call)
608615
if not isinstance(call, Call):
609-
return EMPTY
616+
return previous
610617
target = self.graph.target_at(self.name, call.location)
611618
if not isinstance(target, KnownFunction) or target.name not in self.table:
612-
return EMPTY
619+
return previous
613620
callee = self.table[target.name]
614621
arguments = tuple(self.deep(a, state) for a in call.arguments)
615622
made = self.defs.get(call.callee)
@@ -620,10 +627,9 @@ def nonlocal_result(self, instruction: NonlocalResult, state: dict[Key, Dep]) ->
620627
keywords = EMPTY
621628
for value in (*call.starred, *(v for _, v in call.keywords)):
622629
keywords |= self.deep(value, state)
623-
deps = EMPTY
624-
for write in callee.nonlocal_writes:
625-
if write.name != instruction.name:
626-
continue
630+
written = [write for write in callee.nonlocal_writes if write.name == instruction.name]
631+
deps = previous if not written or any(write.kept for write in written) else EMPTY
632+
for write in written:
627633
for index in write.dependencies:
628634
deps |= arguments[index] if index < len(arguments) else keywords
629635
deps |= Dep(externals=write.externals)
@@ -686,6 +692,38 @@ def mapped(indices: Dependencies, cleared: Cleared = ()) -> Dep:
686692
def uses(self) -> DefUse:
687693
return def_use(self.function)
688694

695+
def may_return_unwritten(self, name: str) -> bool:
696+
"""Whether a path from the entry to a return writes no ``nonlocal`` ``name``,
697+
through the blocks that can run. An exception edge leaves a block before its
698+
write, so its handler is reached unwritten."""
699+
700+
writes = {
701+
block.id
702+
for block in self.function.blocks
703+
if any(isinstance(i, SetNonlocal) and i.name == name for i in block.instructions)
704+
}
705+
pending = [self.function.entry]
706+
seen: set[BlockId] = set()
707+
while pending:
708+
block_id = pending.pop()
709+
if block_id in seen or not self.reachable(block_id):
710+
continue
711+
seen.add(block_id)
712+
block = self.blocks[block_id]
713+
pending.extend(block.exception_targets)
714+
if block_id in writes:
715+
continue
716+
terminator = block.terminator
717+
if isinstance(terminator, Return):
718+
return True
719+
if isinstance(terminator, Branch):
720+
pending.extend((terminator.then_block, terminator.else_block))
721+
elif isinstance(terminator, Jump):
722+
pending.append(terminator.target)
723+
elif isinstance(terminator, ForNext):
724+
pending.extend((terminator.body, terminator.exit))
725+
return False
726+
689727
def runs(self, call: Call) -> bool:
690728
"""Whether ``call`` can run: its block is reachable by constant propagation."""
691729

@@ -793,9 +831,8 @@ def summarize(
793831
mutations=tuple(mutations),
794832
side_effects=frozenset(problem.mutated_globals),
795833
nonlocal_writes=tuple(
796-
NonlocalWrite(name, deps.parameters, deps.externals)
834+
NonlocalWrite(name, deps.parameters, deps.externals, problem.may_return_unwritten(name))
797835
for name, deps in sorted(problem.nonlocal_stores.items())
798-
if deps.parameters or deps.externals
799836
),
800837
static=static,
801838
return_cleared=problem.returns.cleared,

‎src/coretrace_python/ir/lowering.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -251,7 +251,8 @@ def write_back_nonlocals(self, node: nodes.Call, call: Value) -> None:
251251
return
252252
bindings = self.scopes.scope_for(nested).bindings
253253
for name in sorted(n for n, b in bindings.items() if b.kind is BindingKind.NONLOCAL):
254-
written = self.emit(NonlocalResult(self.new_value(), node.span, call, name))
254+
previous = self.expression(nodes.Name(name, node.span))
255+
written = self.emit(NonlocalResult(self.new_value(), node.span, call, name, previous))
255256
self.store(nodes.Name(name, node.span), written)
256257

257258
# ------------------------------------------------------------------ statements

‎src/coretrace_python/ir/model.py‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from coretrace_python.source import SourceSpan
1010

1111
# Bumped whenever the instruction set or its meaning changes; part of the cache key.
12-
PYIR_SCHEMA_VERSION = 1
12+
PYIR_SCHEMA_VERSION = 2
1313

1414

1515
@dataclass(frozen=True)
@@ -245,12 +245,15 @@ class Yield(Operands):
245245
@dataclass(frozen=True)
246246
class NonlocalResult(Operands):
247247
"""The value a nested function left in its ``nonlocal`` ``name`` when ``call``
248-
returned; the caller stores it back into its own variable."""
248+
returned; the caller stores it back into its own variable. ``previous`` is the value
249+
that variable held before the call, which it keeps wherever the function may leave
250+
the name unwritten (``NonlocalWrite.kept``)."""
249251

250252
result: Value
251253
location: SourceSpan
252254
call: Value
253255
name: str
256+
previous: Value
254257

255258

256259
@dataclass(frozen=True)

‎src/coretrace_python/ir/printer.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,10 @@ def _instruction(instruction: Instruction) -> str:
129129
suffix = "" if instruction.value is None else f" {_value(instruction.value)}"
130130
return f"{_value(instruction.result)} = yield{suffix}"
131131
if isinstance(instruction, NonlocalResult):
132-
return f"{_value(instruction.result)} = nonlocal_result {_value(instruction.call)}, {instruction.name!r}"
132+
return (
133+
f"{_value(instruction.result)} = nonlocal_result {_value(instruction.call)}, {instruction.name!r}"
134+
f" else {_value(instruction.previous)}"
135+
)
133136
if isinstance(instruction, SetAttr):
134137
return f"set_attr {_value(instruction.object)}, {instruction.attribute!r}, {_value(instruction.value)}"
135138
if isinstance(instruction, SetItem):

‎src/coretrace_python/taint/engine.py‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -464,14 +464,17 @@ def constructed_keys(self, call: Call, state: Mapping[Key, Taint]) -> Taint:
464464
return taint
465465

466466
def nonlocal_result(self, instruction: NonlocalResult, state: dict[Key, Taint]) -> Taint:
467-
"""The taint a nested callee left in its nonlocal ``name``, in the caller's terms."""
467+
"""The taint a nested callee left in its nonlocal ``name``, in the caller's terms:
468+
what it may write, and the value before the call wherever it may leave the name
469+
unwritten (``NonlocalWrite.kept``), or when what it does is not known."""
468470

471+
previous = self.deep(instruction.previous, state)
469472
call = self.defs.get(instruction.call)
470473
if not isinstance(call, Call):
471-
return Taint.none()
474+
return previous
472475
target = self.graph.target_at(self.name, call.location)
473476
if not isinstance(target, KnownFunction):
474-
return Taint.none()
477+
return previous
475478
summary = self.summaries.summary(target.name)
476479
arguments = (
477480
*(self.deep(r, state) for r in (() if summary.static else self.receiver(call, target.name))),
@@ -481,10 +484,9 @@ def nonlocal_result(self, instruction: NonlocalResult, state: dict[Key, Taint])
481484
keywords = Taint.none()
482485
for value in (*call.starred, *(v for _, v in call.keywords)):
483486
keywords = keywords.join(self.deep(value, state))
484-
result = Taint.none()
485-
for write in summary.nonlocal_writes:
486-
if write.name != instruction.name:
487-
continue
487+
written = [write for write in summary.nonlocal_writes if write.name == instruction.name]
488+
result = previous if not written or any(write.kept for write in written) else Taint.none()
489+
for write in written:
488490
for index in sorted(write.dependencies):
489491
result = result.join(arguments[index] if index < len(arguments) else keywords)
490492
for symbol in sorted(write.externals, key=str):

‎tests/test_nonlocal_kept_value.py‎

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
"""Review of #258 (PR #259): a nested function that may leave a ``nonlocal`` unwritten
2+
leaves the caller's variable as it was before the call.
3+
4+
The summary of a nested function says, for each ``nonlocal`` it writes, what it writes
5+
and whether it may also return without writing it (``NonlocalWrite.kept``); no record
6+
means it never writes it. The caller then keeps the value its variable held before the
7+
call wherever the name may be left unwritten, joined with what the function may write:
8+
a write under ``if False:``, on some paths only, after an exception, or no write at
9+
all. Only a write on every path that returns replaces the value.
10+
"""
11+
12+
from __future__ import annotations
13+
14+
from pathlib import Path
15+
16+
import pytest
17+
18+
from coretrace_python import engine
19+
from coretrace_python.cache import ProjectCache
20+
from coretrace_python.source import SourceManager
21+
22+
23+
def injections(body: str) -> list[tuple[int, str]]:
24+
text = "import os\n\n\n" + body
25+
findings = engine.check(SourceManager().add_source("app.py", text), [engine.BUNDLED_PLUGINS])
26+
return [(f.span.start_line, f.metadata["verdict"]) for f in findings if f.rule_id == "command-injection"]
27+
28+
29+
def nested(write: str, before_call: str = "") -> str:
30+
"""``run`` reads input into ``cmd``, defines ``keep`` writing it as ``write`` says,
31+
calls it and runs ``cmd``; the call to ``os.system`` is the last line."""
32+
33+
lines = ["def run(flag):", " cmd = input()", " def keep():", " nonlocal cmd"]
34+
lines += [f" {line}" for line in write.splitlines()]
35+
lines += [f" {line}" for line in before_call.splitlines()]
36+
lines += [" keep()", " os.system(cmd)"]
37+
return "\n".join(lines) + "\n"
38+
39+
40+
def last_line(body: str) -> int:
41+
return ("import os\n\n\n" + body).count("\n")
42+
43+
44+
@pytest.mark.parametrize(
45+
"write",
46+
[
47+
# The review's cases: the only write cannot run.
48+
"if False:\n cmd = cmd",
49+
"while False:\n cmd = cmd",
50+
"if False:\n cmd = 'ls'",
51+
# No write at all.
52+
"print(cmd)",
53+
# A write on some paths only.
54+
"if flag:\n cmd = 'ls'",
55+
# A write an exception may skip.
56+
"try:\n print(len(cmd))\n cmd = 'ls'\nexcept ValueError:\n pass",
57+
],
58+
)
59+
def test_a_value_the_nested_function_may_leave_unwritten_keeps_its_taint(write: str) -> None:
60+
body = nested(write)
61+
62+
assert injections(body) == [(last_line(body), "vulnerability")]
63+
64+
65+
@pytest.mark.parametrize(
66+
"write",
67+
[
68+
"cmd = 'ls'",
69+
"if flag:\n cmd = 'ls'\nelse:\n cmd = 'pwd'",
70+
"cmd = 'ls'\nif flag:\n cmd = 'pwd'",
71+
],
72+
)
73+
def test_a_safe_value_written_on_every_path_replaces_it(write: str) -> None:
74+
assert injections(nested(write)) == []
75+
76+
77+
def test_what_the_nested_function_writes_still_reaches_the_caller() -> None:
78+
body = (
79+
"def run():\n cmd = 'ls'\n def keep():\n nonlocal cmd\n cmd = input()\n"
80+
" keep()\n os.system(cmd)\n"
81+
)
82+
83+
assert injections(body) == [(last_line(body), "vulnerability")]
84+
85+
86+
def test_the_value_kept_is_the_one_before_the_call_not_at_the_definition() -> None:
87+
# Safe when ``keep`` is defined, input when it is called.
88+
body = (
89+
"def run():\n cmd = 'ls'\n def keep():\n nonlocal cmd\n if False:\n cmd = cmd\n"
90+
" cmd = input()\n keep()\n os.system(cmd)\n"
91+
)
92+
93+
assert injections(body) == [(last_line(body), "vulnerability")]
94+
95+
96+
def test_the_kept_value_reaches_the_caller_of_the_enclosing_function() -> None:
97+
body = (
98+
"def run(value):\n cmd = value\n def keep():\n nonlocal cmd\n if False:\n cmd = 'ls'\n"
99+
" keep()\n return cmd\n\n\ndef caller():\n os.system(run(input()))\n"
100+
)
101+
102+
assert injections(body) == [(last_line(body), "vulnerability")]
103+
104+
105+
def test_the_kept_flag_survives_the_cache(tmp_path: Path) -> None:
106+
root = tmp_path / "project"
107+
(root / "app").mkdir(parents=True)
108+
(root / "app" / "__init__.py").write_text("", encoding="utf-8")
109+
(root / "app" / "main.py").write_text("import os\n\n\n" + nested("if flag:\n cmd = 'ls'"), encoding="utf-8")
110+
cache = ProjectCache(tmp_path / "cache")
111+
112+
analysis = engine.analyze_project(root, [engine.BUNDLED_PLUGINS], cache=cache)
113+
entry = cache.load(analysis.keys["app.main"])
114+
115+
assert entry is not None
116+
assert [(w.name, w.kept) for w in entry.summaries["run.keep"].nonlocal_writes] == [("cmd", True)]

0 commit comments

Comments
 (0)