Skip to content

Commit 303827c

Browse files
committed
feat: taint the keys of a **mapping as the keyword names of the call
Add the keys heap field and key taint for dict literals, dict(...), comprehensions and subscript assignment; report the keys of a ** argument as the (None, "**") way of an advisory flow; record Arguments.keyword_unpacked and fold a ** literal with constant keys that nothing else uses into the keywords (cache format 12); decide the new keyword_name advisory condition from them. Closes #193.
1 parent 2edac65 commit 303827c

9 files changed

Lines changed: 152 additions & 15 deletions

File tree

‎src/coretrace_python/abstract/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from coretrace_python.abstract.heap import (
99
ATTRIBUTES,
1010
ELEMENTS,
11+
KEYS,
1112
MUTATORS,
1213
AbstractObject,
1314
AliasSet,
@@ -24,6 +25,7 @@
2425
__all__ = [
2526
"ATTRIBUTES",
2627
"ELEMENTS",
28+
"KEYS",
2729
"MUTATORS",
2830
"AbstractObject",
2931
"AbstractValue",

‎src/coretrace_python/abstract/heap.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@
66
Each value points to an ``AliasSet`` of objects, computed by a flow-insensitive
77
points-to fixpoint over the SSA form; each object has two ``HeapLocation`` fields,
88
``elements`` for its items and ``attributes`` for its attributes, field-insensitive
9-
within each. Taint and dependence analyses key their states by these locations, so a
9+
within each, and a third, ``keys``, for the keys of a mapping, which only the taint
10+
engine fills. Taint and dependence analyses key their states by these locations, so a
1011
store, a mutating method call or a load on any alias reads and writes the same place.
1112
"""
1213

@@ -47,6 +48,8 @@
4748

4849
ELEMENTS = "elements"
4950
ATTRIBUTES = "attributes"
51+
# The keys of a mapping, stored by the taint engine; the points-to solver never fills it.
52+
KEYS = "keys"
5053

5154
# Method names that store their arguments into the receiver's elements.
5255
MUTATORS = frozenset(

‎src/coretrace_python/cache.py‎

Lines changed: 6 additions & 4 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 SourceId, SourceSpan
4444

45-
CACHE_FORMAT = 11
45+
CACHE_FORMAT = 12
4646

4747

4848
@dataclass(frozen=True)
@@ -368,18 +368,20 @@ def _encode_arguments(arguments: Arguments) -> dict[str, Any]:
368368
"positional": list(arguments.positional),
369369
"keywords": [[name, value] for name, value in arguments.keywords],
370370
"unpacked": arguments.unpacked,
371+
"keyword_unpacked": arguments.keyword_unpacked,
371372
}
372373

373374

374375
def _decode_arguments(data: Mapping[str, Any]) -> Arguments:
375376
def denoted(value: Any) -> str | None:
376377
return None if value is None else _string(value)
377378

378-
unpacked = data["unpacked"]
379-
if not isinstance(unpacked, bool):
380-
raise TypeError(f"expected a boolean, got {unpacked!r}")
379+
unpacked, keyword_unpacked = data["unpacked"], data["keyword_unpacked"]
380+
if not isinstance(unpacked, bool) or not isinstance(keyword_unpacked, bool):
381+
raise TypeError(f"expected booleans, got {unpacked!r} and {keyword_unpacked!r}")
381382
return Arguments(
382383
tuple(denoted(value) for value in data["positional"]),
383384
tuple((_string(name), denoted(value)) for name, value in data["keywords"]),
384385
unpacked,
386+
keyword_unpacked,
385387
)

‎src/coretrace_python/dependency/advisories.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -263,4 +263,8 @@ def _condition(entry: Mapping[str, Any]) -> Condition:
263263
(condition.argument is None and condition.position is None) or condition.values or condition.default
264264
):
265265
raise ValueError("a host condition names the URL argument, by keyword or position, and nothing else")
266+
if condition.kind == "keyword_name" and (
267+
condition.argument is not None or condition.position is not None or condition.values or condition.default
268+
):
269+
raise ValueError("a keyword_name condition carries its text and nothing else")
266270
return condition

‎src/coretrace_python/dependency/correlation.py‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
from coretrace_python.findings.refutation import Status, Verdict, Verdicts
2424
from coretrace_python.interprocedural import Arguments, CallSite, ExternalSymbol
2525
from coretrace_python.semantic.symbols import SymbolId
26-
from coretrace_python.taint import Sink, TaintFlow, TaintKind
26+
from coretrace_python.taint import KEYWORD_NAMES, Sink, TaintFlow, TaintKind
2727
from coretrace_python.taint.urls import UrlProof, redirects_disabled
2828

2929
Affected = Mapping[SymbolId, tuple[Advisory, ...]]
@@ -72,13 +72,25 @@ def check_conditions(
7272
a ``host`` condition, what ``url`` proves of the value the attacker's input is passed
7373
in (``passed_as``). A host the URL's constant text fixes rules the call out when the
7474
call disables redirects; otherwise a redirect may still lead to a host the attacker
75-
controls, and the condition stays pending with that uncertainty."""
75+
controls, and the condition stays pending with that uncertainty. A ``keyword_name``
76+
condition is met when the attacker's input is passed as the keys of a ``**`` mapping,
77+
pending when the call expands a mapping whose keys are not established, and
78+
contradicted by a call writing every keyword name."""
7679

7780
if entry is None:
7881
return ConditionCheck()
7982
met: list[Condition] = []
8083
pending: list[Condition] = []
8184
for condition in entry.conditions:
85+
if condition.kind == "keyword_name":
86+
if any(keyword == KEYWORD_NAMES for _, keyword in passed_as):
87+
met.append(condition)
88+
elif arguments is None or arguments.keyword_unpacked:
89+
pending.append(condition)
90+
else:
91+
names = ", ".join(sorted({name for name, _ in arguments.keywords}))
92+
return ConditionCheck(tuple(met), tuple(pending), condition, names or None)
93+
continue
8294
if condition.kind == "host":
8395
origin = url.origin if url is not None and _passed_in(condition, passed_as) else None
8496
if origin is None:
@@ -119,7 +131,8 @@ def ruled_out(module: str, site: CallSite, check: ConditionCheck) -> str:
119131
python.yaml.load(Loader=python.yaml.SafeLoader)``."""
120132

121133
assert check.contradicted is not None and isinstance(site.target, ExternalSymbol)
122-
argument = check.contradicted.argument or f"#{check.contradicted.position}"
134+
contradicted = check.contradicted
135+
argument = contradicted.argument or ("keywords" if contradicted.kind == "keyword_name" else f"#{contradicted.position}")
123136
passed = f"{argument} absent" if check.passed is None else f"{argument}={check.passed}"
124137
return f"{module}:{site.location.start_line} {site.target.symbol}({passed})"
125138

‎src/coretrace_python/dependency/graph.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,10 @@ class Condition:
154154
``default`` says an absent argument means a vulnerable value. A ``host`` condition
155155
says the attacker must choose the host of the URL passed as ``argument`` (or at
156156
``position``); the engine decides it from what the URL's constant text proves. A
157-
``semantic`` condition cannot be checked and is reported as pending review."""
157+
``keyword_name`` condition says the attacker must choose a keyword name of the call,
158+
as an ORM alias expanded from a mapping; the engine decides it from the keys of what
159+
the call expands with ``**``. A ``semantic`` condition cannot be checked and is
160+
reported as pending review."""
158161

159162
kind: str
160163
text: str

‎src/coretrace_python/interprocedural/callgraph.py‎

Lines changed: 61 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
from coretrace_python.analysis import Analysis, AnalysisContext, AnyAnalysis
1919
from coretrace_python.cfg import CFGError
2020
from coretrace_python.hir import nodes
21+
from coretrace_python.ir.defuse import DefUse, def_use
2122
from coretrace_python.ir.lowering import (
2223
MODULE_BODY,
2324
LoweringError,
@@ -26,6 +27,7 @@
2627
)
2728
from coretrace_python.ir.model import (
2829
Await,
30+
BuildDict,
2931
Call,
3032
Constant,
3133
FunctionIR,
@@ -68,11 +70,15 @@ class Arguments:
6870
(``python.yaml.FullLoader``), a constant as Python writes it (``True``, ``'/static'``),
6971
or None for anything else (a parameter, an expression). ``unpacked`` says the call
7072
unpacks ``*args`` or ``**kwargs``, so an argument it does not give explicitly may
71-
still be given; after ``*args`` no position is known, and ``positional`` is empty."""
73+
still be given; after ``*args`` no position is known, and ``positional`` is empty.
74+
``keyword_unpacked`` says the call expands a ``**mapping`` whose keys it does not
75+
write, so a keyword name may be anything; a literal with constant keys is written out
76+
as its keywords, and ``unpacked`` stays true for it only when ``*args`` is also given."""
7277

7378
positional: tuple[str | None, ...] = ()
7479
keywords: tuple[tuple[str, str | None], ...] = ()
7580
unpacked: bool = False
81+
keyword_unpacked: bool = False
7682

7783
def given(self, keyword: str | None, position: int | None = None) -> tuple[bool, str | None] | None:
7884
"""Whether the call gives an argument, by ``keyword`` or at ``position``, and what it
@@ -245,8 +251,45 @@ def derive_symbols(
245251
# passed as an argument is not recorded, so call sites stay small in the cache.
246252
MAX_CONSTANT_LENGTH = 64
247253

254+
_DICT = SymbolId("python.builtins.dict")
255+
256+
257+
def _keyword_entries(
258+
value: Value, symbols: Mapping[Value, SymbolId], defs: Mapping[Value, Instruction], uses: DefUse
259+
) -> tuple[tuple[str, Value], ...] | None:
260+
"""The keywords a ``**value`` gives when every name is established: the string keys
261+
of a dict literal, the keywords of ``dict(...)``, through what they unpack in turn;
262+
None when a key is computed, the mapping is built elsewhere, or anything but the
263+
call uses it, since a store or a mutating call may add a key the literal does not
264+
write."""
265+
266+
if len(uses.uses(value)) != 1:
267+
return None
268+
made = defs.get(value)
269+
entries: list[tuple[str, Value]] = []
270+
if isinstance(made, BuildDict):
271+
for key, item in made.items:
272+
constant = defs.get(key)
273+
if not isinstance(constant, Constant) or not isinstance(constant.value, str):
274+
return None
275+
entries.append((constant.value, item))
276+
nested = made.unpacked
277+
elif isinstance(made, Call) and symbols.get(made.callee) == _DICT and not made.arguments and not made.starred:
278+
nested = tuple(v for name, v in made.keywords if name is None)
279+
entries.extend((name, v) for name, v in made.keywords if name is not None)
280+
else:
281+
return None
282+
for inner in nested:
283+
found = _keyword_entries(inner, symbols, defs, uses)
284+
if found is None:
285+
return None
286+
entries.extend(found)
287+
return tuple(entries)
288+
248289

249-
def _arguments(call: Call, symbols: Mapping[Value, SymbolId], defs: Mapping[Value, Instruction]) -> Arguments:
290+
def _arguments(
291+
call: Call, symbols: Mapping[Value, SymbolId], defs: Mapping[Value, Instruction], uses: DefUse
292+
) -> Arguments:
250293
def denoted(value: Value) -> str | None:
251294
symbol = symbols.get(value)
252295
if symbol is not None:
@@ -257,10 +300,22 @@ def denoted(value: Value) -> str | None:
257300
written = repr(made.value)
258301
return written if len(written) <= MAX_CONSTANT_LENGTH else None
259302

303+
keywords: list[tuple[str, str | None]] = []
304+
keyword_unpacked = False
305+
for name, value in call.keywords:
306+
if name is not None:
307+
keywords.append((name, denoted(value)))
308+
continue
309+
entries = _keyword_entries(value, symbols, defs, uses)
310+
if entries is None:
311+
keyword_unpacked = True
312+
else:
313+
keywords.extend((key, denoted(item)) for key, item in entries)
260314
return Arguments(
261315
() if call.starred else tuple(denoted(value) for value in call.arguments),
262-
tuple((name, denoted(value)) for name, value in call.keywords if name is not None),
263-
bool(call.starred) or any(name is None for name, _ in call.keywords),
316+
tuple(keywords),
317+
bool(call.starred) or keyword_unpacked,
318+
keyword_unpacked,
264319
)
265320

266321

@@ -480,6 +535,7 @@ def compute(cls, ctx: AnalysisContext) -> CallGraph:
480535
table=table,
481536
)
482537
defs = {i.result: i for block in ssa.blocks for i in block.instructions if i.result is not None}
538+
uses = def_use(ssa)
483539
found: list[CallSite] = []
484540
for block in ssa.blocks:
485541
for instruction in block.instructions:
@@ -489,7 +545,7 @@ def compute(cls, ctx: AnalysisContext) -> CallGraph:
489545
name,
490546
instruction.location,
491547
targets.get(instruction.callee, UnknownTarget()),
492-
_arguments(instruction, symbols[name], defs),
548+
_arguments(instruction, symbols[name], defs, uses),
493549
)
494550
)
495551
sites[name] = tuple(found)

‎src/coretrace_python/taint/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from coretrace_python.semantic.symbols import Members
44
from coretrace_python.taint.engine import (
5+
KEYWORD_NAMES,
56
EntryPointAnalysis,
67
Taint,
78
TaintAnalysis,
@@ -46,6 +47,7 @@
4647

4748
__all__ = [
4849
"FILTER_FUNCTIONS",
50+
"KEYWORD_NAMES",
4951
"TEXT_KINDS",
5052
"AuthorizationGuard",
5153
"BasePattern",

‎src/coretrace_python/taint/engine.py‎

Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
from coretrace_python.abstract import (
1919
ATTRIBUTES,
2020
ELEMENTS,
21+
KEYS,
2122
HeapAnalysis,
2223
HeapFacts,
2324
HeapLocation,
@@ -130,12 +131,18 @@ class TaintFlow:
130131
# What the arguments of the sink call denote, to decide the conditions on them.
131132
sink_arguments: Arguments | None = None
132133
# How the tainted value is passed to the sink call: at a position, by a keyword, or
133-
# (None, None) unpacked with ``*`` or ``**``; ``f(x, key=x)`` passes it twice.
134+
# (None, None) unpacked with ``*`` or ``**``; ``f(x, key=x)`` passes it twice. The
135+
# keyword ``KEYWORD_NAMES`` says the value's keys are the keyword names of the call.
134136
passed_as: frozenset[tuple[int | None, str | None]] = frozenset()
135137

136138

137139
Key = Value | HeapLocation
138140

141+
# The ``keyword`` of a ``passed_as`` way whose value's keys become the keyword names of
142+
# the call: ``f(**m)`` passes the keys of ``m`` as ``(None, KEYWORD_NAMES)``.
143+
KEYWORD_NAMES = "**"
144+
_DICT = SymbolId("python.builtins.dict")
145+
139146

140147
class TaintFacts:
141148
def __init__(self, taints: Mapping[Key, Taint], flows: tuple[TaintFlow, ...]) -> None:
@@ -217,6 +224,14 @@ def loaded(self, instruction: GetAttr | GetItem | GetIter, state: Mapping[Key, T
217224
taint = taint.join(state.get(location, Taint.none()))
218225
return taint
219226

227+
def keyed(self, value: Value, state: Mapping[Key, Taint]) -> Taint:
228+
"""The taint of the keys of the mappings ``value`` points to."""
229+
230+
taint = Taint.none()
231+
for location in self.heap.locations(value, KEYS):
232+
taint = taint.join(state.get(location, Taint.none()))
233+
return taint
234+
220235
def initial(self) -> State:
221236
state: dict[Key, Taint] = {
222237
self.function.parameters[index]: Taint(source.kinds, frozenset({source}))
@@ -246,6 +261,17 @@ def evaluate(
246261
self.store(state, instruction.object, ATTRIBUTES, state.get(instruction.value, Taint.none()))
247262
elif isinstance(instruction, SetItem):
248263
self.store(state, instruction.object, ELEMENTS, state.get(instruction.value, Taint.none()))
264+
key = state.get(instruction.key, Taint.none())
265+
if key:
266+
self.store(state, instruction.object, KEYS, key)
267+
elif isinstance(instruction, BuildDict):
268+
keys = Taint.none()
269+
for item_key, _ in instruction.items:
270+
keys = keys.join(state.get(item_key, Taint.none()))
271+
for unpacked in instruction.unpacked: # ``{**d}`` copies d's keys
272+
keys = keys.join(self.keyed(unpacked, state))
273+
if keys:
274+
self.store(state, instruction.result, KEYS, keys)
249275
if instruction.result is None:
250276
continue
251277
if isinstance(instruction, Phi):
@@ -352,6 +378,10 @@ def call(self, call: Call, state: dict[Key, Taint], flows: list[TaintFlow]) -> T
352378
project, through, arguments, keywords, everything, call, flows, state, (), bound
353379
)
354380
return self.declared_clean(target.symbol, result)
381+
if target.symbol == _DICT:
382+
keys = self.constructed_keys(call, state)
383+
if keys:
384+
self.store(state, call.result, KEYS, keys)
355385
symbol = target.symbol
356386
if not self.modelled(symbol):
357387
# ``get_conn().execute`` derived ``app.database.get_conn.execute``; what
@@ -376,6 +406,23 @@ def call(self, call: Call, state: dict[Key, Taint], flows: list[TaintFlow]) -> T
376406
return self.external(returned, everything, call, state, flows)
377407
return everything.join(state.get(call.callee, Taint.none()))
378408

409+
def constructed_keys(self, call: Call, state: Mapping[Key, Taint]) -> Taint:
410+
"""What the keys of ``dict(...)`` carry: the keys of the mapping it copies
411+
(``dict(m)``, ``dict(**m)``) and the first element of each pair of a sequence
412+
literal (``dict([(k, v)])``); a keyword is a constant key, and an iterable built
413+
elsewhere (``zip(...)``, a parameter) gives keys the engine cannot establish."""
414+
415+
taint = Taint.none()
416+
for value in (*call.arguments[:1], *(v for name, v in call.keywords if name is None)):
417+
taint = taint.join(self.keyed(value, state))
418+
made = self.defs.get(value)
419+
if isinstance(made, BuildList | BuildTuple | BuildSet) and not made.unpacked:
420+
for element in made.elements:
421+
pair = self.defs.get(element)
422+
if isinstance(pair, BuildTuple | BuildList) and pair.elements:
423+
taint = taint.join(state.get(pair.elements[0], Taint.none()))
424+
return taint
425+
379426
def nonlocal_result(self, instruction: NonlocalResult, state: dict[Key, Taint]) -> Taint:
380427
"""The taint a nested callee left in its nonlocal ``name``, in the caller's terms."""
381428

@@ -455,6 +502,11 @@ def external(
455502
self.report(
456503
flows, sink, self.rendered(argument, state), argument, call, None, None, None, given, keyword=name
457504
)
505+
if name is None:
506+
# The keys of a ``**mapping`` are keyword names of the call: only an
507+
# advisory asks who chooses a name, no other sink reads one.
508+
keys = self.keyed(argument, state).without(~TaintKind.ADVISORY)
509+
self.report(flows, sink, keys, argument, call, None, None, None, given, keyword=KEYWORD_NAMES)
458510
self.template_filters(symbol, call, given, state, flows)
459511
cleared = self.clearing.clears(symbol, given)
460512
if cleared:

0 commit comments

Comments
 (0)