Skip to content

Commit 41ce7cb

Browse files
Fix MLAllowlist shadowing (GHSA-cffv-grgg-g429) (#278)
* Split shorten_code() formatting from dedup tracking (GHSA-cffv-grgg-g429) AnalysisContext.shorten_code() mutated a shared reported_shortened_code set as a side effect of formatting, even though most callers only wanted the formatted string. It could then shadow findings from future analysis runs. For instance, UnsafeImportsML processed every import and would leave MLAllowlist with an already-reported state for all of them. Any import outside ML_ALLOWLIST would not be flagged by the second run. Split shorten_code() into a pure formatter and an explicit mark_reported() helper. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * Make MLAllowlist opt-in Analysis.__init_subclass__ put every subclass into Analysis.ALL, and fickling/__init__.py transitively imported fickling.ml via hook.py, wich registered MLAllowlist. The shorten_code() shadowing bug (GHSA-cffv-grgg-g429) made it dead code until the previous commit, and now it conflicts with other default analysis passes. This commit makes MLAllowlist opt-in; use `check_safety(analyze=...)` if you need it. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent 91a40fc commit 41ce7cb

4 files changed

Lines changed: 74 additions & 25 deletions

File tree

‎fickling/analysis.py‎

Lines changed: 28 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -78,19 +78,25 @@ def analyze(self, analysis: Analysis) -> list[AnalysisResult]:
7878
def results(self) -> AnalysisResults:
7979
return AnalysisResults(pickled=self.pickled, results=self.previous_results)
8080

81-
def shorten_code(self, ast_node) -> tuple[str, bool]:
81+
def shorten_code(self, ast_node) -> str:
82+
"""Return a short, human-readable form of an AST node for use in
83+
analysis messages. Pure formatter — does not touch dedup state.
84+
"""
8285
code = unparse(ast_node).strip()
8386
if len(code) > 32:
8487
cutoff = code.find("(")
85-
if code[cutoff] == "(":
86-
shortened_code = f"{code[: code.find('(')].strip()}(...)"
87-
else:
88-
shortened_code = code
89-
else:
90-
shortened_code = code
91-
was_already_reported = shortened_code in self.reported_shortened_code
92-
self.reported_shortened_code.add(shortened_code)
93-
return shortened_code, was_already_reported
88+
if cutoff >= 0:
89+
return f"{code[:cutoff].strip()}(...)"
90+
return code
91+
92+
def mark_reported(self, shortened: str) -> bool:
93+
"""Mark a shortened code fragment as reported. Returns True if
94+
this was the first mark, False if a prior call already marked it.
95+
"""
96+
if shortened in self.reported_shortened_code:
97+
return False
98+
self.reported_shortened_code.add(shortened)
99+
return True
94100

95101

96102
class Analyzer(metaclass=AnalyzerMeta):
@@ -164,8 +170,10 @@ def __str__(self):
164170
class Analysis(ABC):
165171
ALL: list[Analysis] = []
166172

167-
def __init_subclass__(cls, **kwargs):
168-
Analysis.ALL.append(cls())
173+
def __init_subclass__(cls, *, register: bool = True, **kwargs):
174+
super().__init_subclass__(**kwargs)
175+
if register:
176+
Analysis.ALL.append(cls())
169177

170178
@abstractmethod
171179
def analyze(self, context: AnalysisContext) -> Iterator[AnalysisResult]:
@@ -255,8 +263,8 @@ def analyze(self, context: AnalysisContext) -> Iterator[AnalysisResult]:
255263
class NonStandardImports(Analysis):
256264
def analyze(self, context: AnalysisContext) -> Iterator[AnalysisResult]:
257265
for node in context.pickled.non_standard_imports():
258-
shortened, already_reported = context.shorten_code(node)
259-
if not already_reported:
266+
shortened = context.shorten_code(node)
267+
if context.mark_reported(shortened):
260268
yield AnalysisResult(
261269
Severity.LIKELY_UNSAFE,
262270
f"`{shortened}` imports a Python module that is not a part of "
@@ -324,7 +332,7 @@ class UnsafeImportsML(Analysis):
324332

325333
def analyze(self, context: AnalysisContext) -> Iterator[AnalysisResult]:
326334
for node in context.pickled.properties.imports:
327-
shortened, _ = context.shorten_code(node)
335+
shortened = context.shorten_code(node)
328336
all_modules = [
329337
node.module.rsplit(".", i)[0] for i in range(0, node.module.count(".") + 1)
330338
]
@@ -377,7 +385,7 @@ class BadCalls(Analysis):
377385

378386
def analyze(self, context: AnalysisContext) -> Iterator[AnalysisResult]:
379387
for node in context.pickled.properties.calls:
380-
shortened, _already_reported = context.shorten_code(node)
388+
shortened = context.shorten_code(node)
381389
if any(shortened.startswith(f"{c}(") for c in self.BAD_CALLS):
382390
yield AnalysisResult(
383391
Severity.OVERTLY_MALICIOUS,
@@ -397,7 +405,7 @@ def analyze(self, context: AnalysisContext) -> Iterator[AnalysisResult]:
397405
# if the call is to a constructor of an object imported from the Python
398406
# standard library, it's probably okay
399407
continue
400-
shortened, already_reported = context.shorten_code(node)
408+
shortened = context.shorten_code(node)
401409
if (
402410
shortened.startswith("eval(")
403411
or shortened.startswith("exec(")
@@ -413,7 +421,7 @@ def analyze(self, context: AnalysisContext) -> Iterator[AnalysisResult]:
413421
"OvertlyBadEval",
414422
trigger=shortened,
415423
)
416-
elif not already_reported:
424+
elif context.mark_reported(shortened):
417425
yield AnalysisResult(
418426
Severity.LIKELY_UNSAFE,
419427
f"Call to `{shortened}` can execute arbitrary code and is inherently unsafe",
@@ -429,7 +437,7 @@ def analyze(self, context: AnalysisContext) -> Iterator[AnalysisResult]:
429437
n.name in SAFE_BUILTINS for n in node.names
430438
):
431439
continue
432-
shortened, _ = context.shorten_code(node)
440+
shortened = context.shorten_code(node)
433441
yield AnalysisResult(
434442
Severity.LIKELY_OVERTLY_MALICIOUS,
435443
f"`{shortened}` is suspicious and indicative of an overtly malicious pickle file",
@@ -447,7 +455,7 @@ def analyze(self, context: AnalysisContext) -> Iterator[AnalysisResult]:
447455
# Malformed pickle or resource exhaustion - dedicated analyses will report this
448456
return
449457
for varname, asmt in unused.items():
450-
shortened, _ = context.shorten_code(asmt.value)
458+
shortened = context.shorten_code(asmt.value)
451459
yield AnalysisResult(
452460
Severity.SUSPICIOUS,
453461
f"Variable `{varname}` is assigned value `{shortened}` but unused afterward; "

‎fickling/ml.py‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -288,16 +288,14 @@
288288
}
289289

290290

291-
class MLAllowlist(Analysis):
291+
class MLAllowlist(Analysis, register=False):
292292
def __init__(self):
293293
super().__init__()
294294
self.allowlist = ML_ALLOWLIST
295295

296296
def analyze(self, context: AnalysisContext) -> Iterator[AnalysisResult]:
297297
for node in context.pickled.properties.imports:
298-
shortened, already_reported = context.shorten_code(node)
299-
if already_reported:
300-
continue
298+
shortened = context.shorten_code(node)
301299

302300
if isinstance(node, ast.ImportFrom):
303301
# from module import x

‎test/test_analysis.py‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
from unittest import TestCase
2+
3+
import fickling.fickle as op
4+
from fickling.analysis import Severity, check_safety
5+
from fickling.fickle import Pickled
6+
7+
8+
class TestAnalysis(TestCase):
9+
def test_benign_pickle(self):
10+
pickled = Pickled(
11+
[
12+
op.Proto.create(4),
13+
op.ShortBinUnicode("collections"),
14+
op.ShortBinUnicode("deque"),
15+
op.StackGlobal(),
16+
op.Stop(),
17+
]
18+
)
19+
self.assertEqual(check_safety(pickled).severity, Severity.LIKELY_SAFE)

‎test/test_bypasses.py‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,9 @@
22
from unittest import TestCase
33

44
import fickling.fickle as op
5-
from fickling.analysis import Severity, UnsafeImportsML, check_safety
5+
from fickling.analysis import Analyzer, Severity, UnsafeImportsML, check_safety
66
from fickling.fickle import Pickled
7+
from fickling.ml import MLAllowlist
78

89

910
class TestBypasses(TestCase):
@@ -683,6 +684,29 @@ def test_missing_osx_support(self):
683684
"from _osx_support import _find_build_tool",
684685
)
685686

687+
# https://github.com/trailofbits/fickling/security/advisories/GHSA-cffv-grgg-g429
688+
def test_ml_allowlist_not_shadowed_by_unsafe_imports_ml(self):
689+
"""MLAllowlist must flag imports outside ML_ALLOWLIST even when another
690+
analysis (UnsafeImportsML) has already iterated the same import.
691+
"""
692+
pickled = Pickled(
693+
[
694+
op.Proto.create(4),
695+
op.ShortBinUnicode("ast"),
696+
op.ShortBinUnicode("parse"),
697+
op.StackGlobal(),
698+
op.Stop(),
699+
]
700+
)
701+
analyzer = Analyzer([UnsafeImportsML(), MLAllowlist()])
702+
res = check_safety(pickled, analyzer=analyzer)
703+
self.assertGreater(res.severity, Severity.LIKELY_SAFE)
704+
detailed = res.detailed_results().get("AnalysisResult", {})
705+
self.assertIsNotNone(
706+
detailed.get("MLAllowlist"),
707+
"MLAllowlist did not produce a finding for `from ast import parse`",
708+
)
709+
686710

687711
class TestUnsafeModuleCoverage(TestCase):
688712
"""Verify every entry in UNSAFE_MODULES and UNSAFE_IMPORTS triggers detection."""

0 commit comments

Comments
 (0)