forked from cisco-ai-defense/skill-scanner
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstatic.py
More file actions
2743 lines (2405 loc) · 121 KB
/
Copy pathstatic.py
File metadata and controls
2743 lines (2405 loc) · 121 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2026 Cisco Systems, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
"""
Static pattern analyzer for detecting security vulnerabilities.
"""
import ast
import configparser
import hashlib
import logging
import re
from pathlib import Path
from typing import Any
from ...config.yara_modes import YaraModeConfig
from ...core.models import Finding, Severity, Skill, ThreatCategory
from ...core.rules.patterns import RuleLoader, SecurityRule
from ...core.rules.yara_scanner import YaraScanner
from ...core.scan_policy import ScanPolicy
from ...threats.threats import ThreatMapping
from .base import BaseAnalyzer
try:
import tomllib
except ModuleNotFoundError: # Python < 3.11
tomllib = None
logger = logging.getLogger(__name__)
# Pre-compiled regex patterns for file operation checks
_READ_PATTERNS = [
re.compile(r"open\([^)]+['\"]r['\"]"),
re.compile(r"\.read\("),
re.compile(r"\.readline\("),
re.compile(r"\.readlines\("),
re.compile(r"Path\([^)]+\)\.read_text"),
re.compile(r"Path\([^)]+\)\.read_bytes"),
re.compile(r"with\s+open\([^)]+['\"]r"),
]
_WRITE_PATTERNS = [
re.compile(r"open\([^)]+['\"]w['\"]"),
re.compile(r"\.write\("),
re.compile(r"\.writelines\("),
re.compile(r"pathlib\.Path\([^)]+\)\.write"),
re.compile(r"with\s+open\([^)]+['\"]w"),
]
_GREP_PATTERNS = [
re.compile(r"re\.search\("),
re.compile(r"re\.findall\("),
re.compile(r"re\.match\("),
re.compile(r"re\.finditer\("),
re.compile(r"re\.sub\("),
re.compile(r"grep"),
]
_GLOB_PATTERNS = [
re.compile(r"glob\.glob\("),
re.compile(r"glob\.iglob\("),
re.compile(r"Path\([^)]*\)\.glob\("),
re.compile(r"\.glob\("),
re.compile(r"\.rglob\("),
re.compile(r"fnmatch\."),
]
_EXCEPTION_PATTERNS = [
re.compile(r"except\s+(EOFError|StopIteration|KeyboardInterrupt|Exception|BaseException)"),
re.compile(r"except\s*:"),
re.compile(r"break\s*$", re.MULTILINE),
re.compile(r"return\s*$", re.MULTILINE),
re.compile(r"sys\.exit\s*\("),
re.compile(r"raise\s+StopIteration"),
]
_SKILL_NAME_PATTERN = re.compile(r"[a-z0-9-]+")
_MARKDOWN_LINK_PATTERN = re.compile(r"\[([^\]]+)\]\(([^\)]+)\)")
_PYTHON_IMPORT_PATTERN = re.compile(r"^from\s+\.([A-Za-z0-9_.]*)\s+import", re.MULTILINE)
_BASH_SOURCE_PATTERN = re.compile(r"(?:source|\.)\s+([A-Za-z0-9_\-./]+\.(?:sh|bash))")
_RM_TARGET_PATTERN = re.compile(r"rm\s+-r[^;]*?\s+([^\s;]+)")
_DEFAULT_SAFE_CLEANUP_DIRS = {
"dist",
"build",
"tmp",
"temp",
".tmp",
".temp",
"bundle.html",
"bundle.js",
"bundle.css",
"node_modules",
".next",
".nuxt",
".cache",
}
_DEFAULT_PLACEHOLDER_MARKERS = {
"your-",
"your_",
"your ",
"example",
"sample",
"dummy",
"placeholder",
"replace",
"changeme",
"change_me",
"<your",
"<insert",
}
def _is_path_traversal(ref_path: str) -> bool:
"""Check if a reference path contains traversal sequences or is absolute."""
return ".." in ref_path or ref_path.startswith("/")
def _is_within_directory(path: Path, directory: Path) -> bool:
"""Check if a resolved path stays within the given directory."""
try:
resolved_path = path.resolve()
resolved_directory = directory.resolve()
return resolved_path.is_relative_to(resolved_directory)
except (ValueError, OSError):
return False
def _redact_secret(text: str) -> str:
"""Redact a matched secret, preserving a short prefix for identification.
Returns a version like ``AKIA****`` or ``sk_live_****`` so the type of
secret is still recognisable in the report without exposing the full value.
"""
if not text:
return text
_KNOWN_PREFIXES = {
"AKIA": 4,
"AGPA": 4,
"AIDA": 4,
"AROA": 4,
"AIPA": 4,
"ANPA": 4,
"ANVA": 4,
"ASIA": 4,
"AIza": 4,
}
for prefix, length in _KNOWN_PREFIXES.items():
if text.startswith(prefix):
return text[:length] + "****"
_TOKEN_PREFIXES = ("sk_live_", "pk_live_", "sk_test_", "pk_test_", "ghp_", "gho_", "ghu_", "ghs_", "ghr_")
for prefix in _TOKEN_PREFIXES:
if text.startswith(prefix):
return prefix + "****"
if text.startswith("eyJ"):
return "eyJ****"
_PK_MARKER_BEGIN = "-----BEGIN"
_PK_MARKER_TYPE = "PRIVATE KEY"
if _PK_MARKER_BEGIN in text and _PK_MARKER_TYPE in text:
return f"{_PK_MARKER_BEGIN} {_PK_MARKER_TYPE}----- [REDACTED]"
if len(text) <= 8:
return text[:2] + "****"
return text[:4] + "****"
class StaticAnalyzer(BaseAnalyzer):
"""Static pattern-based security analyzer."""
def __init__(
self,
rules_file: Path | None = None,
use_yara: bool = True,
yara_mode: YaraModeConfig | str | None = None,
custom_yara_rules_path: str | Path | None = None,
disabled_rules: set[str] | None = None,
policy: ScanPolicy | None = None,
extra_rules_dirs: list[Path] | None = None,
):
"""
Initialize static analyzer.
Args:
rules_file: Optional custom YAML rules file
use_yara: Whether to use YARA scanning (default: True)
yara_mode: YARA detection mode - can be:
- YaraModeConfig instance
- Mode name string: "strict", "balanced", "permissive"
- None for default (balanced)
custom_yara_rules_path: Path to directory containing custom YARA rules
(.yara files). If provided, uses these instead of built-in rules.
disabled_rules: Set of rule names to disable. Rules can be YARA rule
names (e.g., "YARA_script_injection") or static rule IDs
(e.g., "COMMAND_INJECTION_EVAL").
policy: Scan policy for org-specific allowlists and rule scoping.
If None, loads built-in defaults.
extra_rules_dirs: Additional signature rule directories from
community/external packs to load alongside the core rules.
"""
super().__init__("static_analyzer", policy=policy)
# Unreferenced scripts are computed during _check_file_inventory()
# and exposed to the scanner for LLM enrichment context (not as
# standalone findings).
self._unreferenced_scripts: list[str] = []
self.rule_loader = RuleLoader(rules_file, extra_rules_dirs=extra_rules_dirs)
self.rule_loader.load_rules()
# Configure YARA mode.
# When no explicit yara_mode is supplied, derive it from the policy's
# ``preset_base`` so that ``--policy strict`` (or a custom policy
# generated from the strict preset) automatically gets strict YARA
# post-filtering. ``preset_base`` is a stable field that survives
# policy-name customisation (e.g. "acme-corp"), unlike
# ``policy_name`` which is a user-facing display name.
if yara_mode is None:
preset = getattr(self.policy, "preset_base", "balanced")
_PRESET_TO_YARA = {"strict": "strict", "permissive": "permissive"}
mode_name = _PRESET_TO_YARA.get(preset, "balanced")
self.yara_mode = YaraModeConfig.from_mode_name(mode_name)
elif isinstance(yara_mode, str):
self.yara_mode = YaraModeConfig.from_mode_name(yara_mode)
else:
self.yara_mode = yara_mode
# Store disabled rules (merge CLI + mode + policy)
self.disabled_rules = set(disabled_rules or set())
self.disabled_rules.update(self.yara_mode.disabled_rules)
self.disabled_rules.update(self.policy.disabled_rules)
# Store custom YARA rules path
self.custom_yara_rules_path = Path(custom_yara_rules_path) if custom_yara_rules_path else None
self.use_yara = use_yara
self.yara_scanner = None
if use_yara:
try:
max_scan_bytes = self.policy.file_limits.max_yara_scan_file_size_bytes
# Use custom rules path if provided
if self.custom_yara_rules_path:
self.yara_scanner = YaraScanner(
rules_dir=self.custom_yara_rules_path,
max_scan_file_size=max_scan_bytes,
)
logger.info("Using custom YARA rules from: %s", self.custom_yara_rules_path)
else:
self.yara_scanner = YaraScanner(max_scan_file_size=max_scan_bytes)
except Exception as e:
logger.warning("Could not load YARA scanner: %s", e)
self.yara_scanner = None
def _is_rule_enabled(self, rule_name: str) -> bool:
"""
Check if a rule is enabled.
A rule is enabled if:
1. It's enabled in the current YARA mode
2. It's not in the explicitly disabled rules set
3. It's not in the policy's disabled_rules set
Args:
rule_name: Name of the rule to check (e.g., "YARA_script_injection")
Returns:
True if the rule is enabled, False otherwise
"""
# Check mode-based enable/disable first
if not self.yara_mode.is_rule_enabled(rule_name):
return False
# Check if explicitly disabled via policy or constructor
if rule_name in self.disabled_rules:
return False
base_name = rule_name.replace("YARA_", "") if rule_name.startswith("YARA_") else rule_name
if base_name in self.disabled_rules:
return False
return True
def analyze(self, skill: Skill) -> list[Finding]:
"""
Analyze skill using static pattern matching.
Performs multi-pass scanning:
1. Manifest validation
2. Instruction body scanning (SKILL.md)
3. Script/code scanning
4. Consistency checks
5. Dependency pinning checks
6. Reference file scanning
Args:
skill: Skill to analyze
Returns:
List of security findings
"""
findings = []
self._unreferenced_scripts = [] # reset per-scan enrichment state
findings.extend(self._check_manifest(skill))
findings.extend(self._scan_instruction_body(skill))
findings.extend(self._scan_scripts(skill))
findings.extend(self._check_consistency(skill))
findings.extend(self._check_dependency_pinning(skill))
findings.extend(self._scan_referenced_files(skill))
findings.extend(self._check_binary_files(skill))
findings.extend(self._check_hidden_files(skill))
findings.extend(self._check_ascii_smuggling(skill))
findings.extend(self._check_file_inventory(skill))
findings.extend(self._check_pdf_documents(skill))
findings.extend(self._check_office_documents(skill))
findings.extend(self._check_homoglyph_attacks(skill))
if self.yara_scanner:
findings.extend(self._yara_scan(skill))
findings.extend(self._scan_asset_files(skill))
# Filter out disabled rules (both explicitly disabled and via enabled=false knob)
findings = [f for f in findings if self._is_rule_enabled(f.rule_id)]
# Filter out well-known test/placeholder credentials
findings = [f for f in findings if not self._is_known_test_credential(f)]
# Collapse duplicate findings emitted by overlapping scan phases
# (e.g., script scan + recursive reference scan on the same file/line).
if self.policy.rule_scoping.dedupe_duplicate_findings:
findings = self._dedupe_findings(findings)
return findings
def get_unreferenced_scripts(self) -> list[str]:
"""Return unreferenced script paths computed during the last ``analyze()`` call.
These are scripts present in the skill package that are not mentioned
in SKILL.md. They are stored as enrichment context for the LLM
analyzer rather than emitted as standalone findings.
"""
return list(self._unreferenced_scripts)
def _is_known_test_credential(self, finding: Finding) -> bool:
"""Check if a finding matches a well-known test/placeholder credential (from policy)."""
if finding.category != ThreatCategory.HARDCODED_SECRETS:
return False
snippet = finding.snippet or ""
for cred in self.policy.credentials.known_test_values:
if cred in snippet:
return True
return False
def _is_doc_file(self, rel_path: str) -> bool:
"""Check if a file is in a documentation directory or is an educational file.
Uses ``doc_path_indicators`` and ``doc_filename_patterns`` from the
active scan policy to determine if a given relative path belongs to a
documentation or example area (e.g. ``docs/``, ``examples/``).
"""
path_obj = Path(rel_path)
parts = path_obj.parts
doc_indicators = self.policy.rule_scoping.doc_path_indicators
if any(p.lower() in doc_indicators for p in parts):
return True
doc_re = self.policy._compiled_doc_filename_re
if doc_re and doc_re.search(path_obj.stem):
return True
return False
def _check_manifest(self, skill: Skill) -> list[Finding]:
"""Validate skill manifest for security issues."""
findings = []
manifest = skill.manifest
max_name_length = self.policy.file_limits.max_name_length
if len(manifest.name) > max_name_length or not _SKILL_NAME_PATTERN.fullmatch(manifest.name or ""):
findings.append(
Finding(
id=self._generate_finding_id("MANIFEST_INVALID_NAME", "manifest"),
rule_id="MANIFEST_INVALID_NAME",
category=ThreatCategory.POLICY_VIOLATION,
severity=Severity.INFO,
title="Skill name does not follow agent skills naming rules",
description=(
f"Skill name '{manifest.name}' is invalid. Agent skills require lowercase letters, numbers, "
f"and hyphens only, with a maximum length of {max_name_length} characters."
),
file_path="SKILL.md",
remediation="Rename the skill to match `[a-z0-9-]{1,64}` (e.g., 'pdf-processing')",
analyzer="static",
)
)
max_desc_length = self.policy.file_limits.max_description_length
if len(manifest.description or "") > max_desc_length:
findings.append(
Finding(
id=self._generate_finding_id("MANIFEST_DESCRIPTION_TOO_LONG", "manifest"),
rule_id="MANIFEST_DESCRIPTION_TOO_LONG",
category=ThreatCategory.POLICY_VIOLATION,
severity=Severity.LOW,
title="Skill description exceeds agent skills length limit",
description=(
f"Skill description is {len(manifest.description)} characters; Agent skills limit the "
f"`description` field to {max_desc_length} characters."
),
file_path="SKILL.md",
remediation=f"Shorten the description to {max_desc_length} characters or fewer while keeping it specific",
analyzer="static",
)
)
min_desc_length = self.policy.file_limits.min_description_length
if len(manifest.description or "") < min_desc_length:
findings.append(
Finding(
id=self._generate_finding_id("SOCIAL_ENG_VAGUE_DESCRIPTION", "manifest"),
rule_id="SOCIAL_ENG_VAGUE_DESCRIPTION",
category=ThreatCategory.SOCIAL_ENGINEERING,
severity=Severity.LOW,
title="Vague skill description",
description=f"Skill description is too short ({len(manifest.description)} chars). Provide detailed explanation.",
file_path="SKILL.md",
remediation="Provide a clear, detailed description of what the skill does and when to use it",
analyzer="static",
)
)
description_lower = manifest.description.lower()
name_lower = manifest.name.lower()
is_anthropic_mentioned = "anthropic" in name_lower or "anthropic" in description_lower
if is_anthropic_mentioned:
legitimate_patterns = ["apply", "brand", "guidelines", "colors", "typography", "style"]
is_legitimate = any(pattern in description_lower for pattern in legitimate_patterns)
if not is_legitimate:
findings.append(
Finding(
id=self._generate_finding_id("SOCIAL_ENG_ANTHROPIC_IMPERSONATION", "manifest"),
rule_id="SOCIAL_ENG_ANTHROPIC_IMPERSONATION",
category=ThreatCategory.SOCIAL_ENGINEERING,
severity=Severity.MEDIUM,
title="Potential Anthropic brand impersonation",
description="Skill name or description contains 'Anthropic', suggesting official affiliation",
file_path="SKILL.md",
remediation="Do not impersonate official skills or use unauthorized branding",
analyzer="static",
)
)
if "claude official" in manifest.name.lower() or "claude official" in manifest.description.lower():
findings.append(
Finding(
id=self._generate_finding_id("SOCIAL_ENG_CLAUDE_OFFICIAL", "manifest"),
rule_id="SOCIAL_ENG_ANTHROPIC_IMPERSONATION",
category=ThreatCategory.SOCIAL_ENGINEERING,
severity=Severity.HIGH,
title="Claims to be official skill",
description="Skill claims to be an 'official' skill",
file_path="SKILL.md",
remediation="Remove 'official' claims unless properly authorized",
analyzer="static",
)
)
if not manifest.license:
findings.append(
Finding(
id=self._generate_finding_id("MANIFEST_MISSING_LICENSE", "manifest"),
rule_id="MANIFEST_MISSING_LICENSE",
category=ThreatCategory.POLICY_VIOLATION,
severity=Severity.INFO,
title="Skill does not specify a license",
description="Skill manifest does not include a 'license' field. Specifying a license helps users understand usage terms.",
file_path="SKILL.md",
remediation="Add 'license' field to SKILL.md frontmatter (e.g., MIT, Apache-2.0)",
analyzer="static",
)
)
return findings
def _scan_instruction_body(self, skill: Skill) -> list[Finding]:
"""Scan SKILL.md instruction body for prompt injection patterns."""
findings = []
markdown_rules = self.rule_loader.get_rules_for_file_type("markdown")
for rule in markdown_rules:
matches = rule.scan_content(skill.instruction_body, "SKILL.md")
for match in matches:
findings.append(self._create_finding_from_match(rule, match))
return findings
def _scan_scripts(self, skill: Skill) -> list[Finding]:
"""Scan all script files (Python, Bash) for vulnerabilities."""
findings = []
skip_in_docs = set(self.policy.rule_scoping.skip_in_docs)
for skill_file in skill.files:
if skill_file.file_type not in ("python", "bash", "javascript", "typescript"):
continue
rules = self.rule_loader.get_rules_for_file_type(skill_file.file_type)
content = skill_file.read_content()
if not content:
continue
is_doc = self._is_doc_file(skill_file.relative_path)
for rule in rules:
# Skip rules scoped out of documentation files
if is_doc and rule.id in skip_in_docs:
continue
matches = rule.scan_content(content, skill_file.relative_path)
for match in matches:
if rule.id == "RESOURCE_ABUSE_INFINITE_LOOP" and skill_file.file_type == "python":
if self._is_loop_with_exception_handler(content, match["line_number"]):
continue
findings.append(self._create_finding_from_match(rule, match))
return findings
def _is_loop_with_exception_handler(self, content: str, loop_line_num: int) -> bool:
"""Check if a while True loop has an exception handler in surrounding context."""
context_size = self.policy.analysis_thresholds.exception_handler_context_lines
lines = content.split("\n")
context_lines = lines[loop_line_num - 1 : min(loop_line_num + context_size, len(lines))]
context_text = "\n".join(context_lines)
for pattern in _EXCEPTION_PATTERNS:
if pattern.search(context_text):
return True
return False
def _check_consistency(self, skill: Skill) -> list[Finding]:
"""Check for inconsistencies between manifest and actual behavior."""
findings = []
uses_network = self._skill_uses_network(skill)
declared_network = self._manifest_declares_network(skill)
skillmd = str(skill.skill_md_path)
if uses_network and not declared_network:
findings.append(
Finding(
id=self._generate_finding_id("TOOL_MISMATCH_NETWORK", skill.name),
rule_id="TOOL_ABUSE_UNDECLARED_NETWORK",
category=ThreatCategory.UNAUTHORIZED_TOOL_USE,
severity=Severity.MEDIUM,
title="Undeclared network usage",
description="Skill code uses network libraries but doesn't declare network requirement",
file_path=skillmd,
remediation="Declare network usage in compatibility field or remove network calls",
analyzer="static",
)
)
findings.extend(self._check_allowed_tools_violations(skill))
if self._check_description_mismatch(skill):
findings.append(
Finding(
id=self._generate_finding_id("DESC_BEHAVIOR_MISMATCH", skill.name),
rule_id="SOCIAL_ENG_MISLEADING_DESC",
category=ThreatCategory.SOCIAL_ENGINEERING,
severity=Severity.MEDIUM,
title="Potential description-behavior mismatch",
description="Skill performs actions not reflected in its description",
file_path="SKILL.md",
remediation="Ensure description accurately reflects all skill capabilities",
analyzer="static",
)
)
return findings
# Lockfiles whose presence means dependency versions are already resolved/frozen.
_LOCKFILE_NAMES = {"uv.lock", "poetry.lock", "pipfile.lock", "requirements.lock"}
# name[extras] followed by an optional version specifier.
_REQUIREMENT_RE = re.compile(r"^([A-Za-z0-9][A-Za-z0-9._-]*)\s*(?:\[[^\]]*\])?\s*(.*)$")
_SPECIFIER_RE = re.compile(r"^(===|==|~=|!=|<=|>=|<|>)\s*(.+)$")
@staticmethod
def _classify_requirement(raw: str) -> tuple[str, str] | None:
"""Classify a single requirement line.
Returns ``(package_name, status)`` where ``status`` is one of
``"pinned"`` (has an exact ``==`` version), ``"wildcard"`` (``==1.*``
style range pin), or ``"unpinned"`` (bare name or open range such as
``>=``). Returns ``None`` for lines that are not package requirements
(blank, comments, pip options like ``-r``/``--hash``, or direct
URL/VCS references which are already pinned to a specific artifact).
"""
line = raw.split("#", 1)[0].strip()
if not line or line.startswith("-"):
return None
# Drop PEP 508 environment markers (e.g. "; python_version < '3.11'").
line = line.split(";", 1)[0].strip()
# Direct URL / VCS / local-file references are pinned to an artifact.
if "://" in line or line.startswith("git+") or " @ " in line:
return None
match = StaticAnalyzer._REQUIREMENT_RE.match(line)
if not match:
return None
name = match.group(1)
spec = match.group(2).strip()
if not spec:
return (name, "unpinned")
has_exact = False
has_wildcard_pin = False
for part in (p.strip() for p in spec.split(",") if p.strip()):
op_match = StaticAnalyzer._SPECIFIER_RE.match(part)
if not op_match:
continue
operator, version = op_match.group(1), op_match.group(2).strip()
if operator in ("==", "==="):
if "*" in version:
has_wildcard_pin = True
else:
has_exact = True
if has_exact:
return (name, "pinned")
if has_wildcard_pin:
return (name, "wildcard")
return (name, "unpinned")
@staticmethod
def _first_line_containing(content: str, needle: str) -> int | None:
"""Best-effort 1-based line number of the first line containing ``needle``."""
if not needle:
return None
for index, line in enumerate(content.splitlines(), start=1):
if needle in line:
return index
return None
@staticmethod
def _safe_toml(content: str) -> dict | None:
"""Parse TOML, returning None when unavailable (py<3.11) or malformed."""
if tomllib is None:
return None
try:
return tomllib.loads(content)
except Exception: # noqa: BLE001 - malformed manifest, treat as no data
return None
def _entries_from_pyproject(self, path: str, content: str) -> list[tuple[str, int | None, str]]:
"""PEP 621 ``[project]`` dependencies and optional-dependencies."""
data = self._safe_toml(content)
project = data.get("project") if isinstance(data, dict) else None
if not isinstance(project, dict):
return []
specs: list[str] = []
deps = project.get("dependencies")
if isinstance(deps, list):
specs.extend(str(dep) for dep in deps)
optional = project.get("optional-dependencies")
if isinstance(optional, dict):
for group in optional.values():
if isinstance(group, list):
specs.extend(str(dep) for dep in group)
return [(path, self._first_line_containing(content, spec), spec) for spec in specs]
def _entries_from_setup_cfg(self, path: str, content: str) -> list[tuple[str, int | None, str]]:
"""``[options] install_requires`` and ``[options.extras_require]``."""
parser = configparser.ConfigParser()
try:
parser.read_string(content)
except configparser.Error:
return []
blocks: list[str] = []
if parser.has_option("options", "install_requires"):
blocks.append(parser.get("options", "install_requires"))
if parser.has_section("options.extras_require"):
blocks.extend(value for _, value in parser.items("options.extras_require"))
entries: list[tuple[str, int | None, str]] = []
for block in blocks:
for piece in block.replace(",", "\n").splitlines():
spec = piece.strip()
if spec:
entries.append((path, self._first_line_containing(content, spec), spec))
return entries
def _entries_from_setup_py(self, path: str, content: str) -> list[tuple[str, int | None, str]]:
"""String literals inside ``install_requires=[...]`` in setup.py."""
try:
tree = ast.parse(content)
except SyntaxError:
return []
entries: list[tuple[str, int | None, str]] = []
for node in ast.walk(tree):
if not (isinstance(node, ast.keyword) and node.arg == "install_requires"):
continue
for literal in ast.walk(node.value):
if isinstance(literal, ast.Constant) and isinstance(literal.value, str):
line_number = getattr(literal, "lineno", None)
entries.append((path, line_number, literal.value))
return entries
@staticmethod
def _pipfile_requirement(name: str, spec: Any) -> str | None:
"""Convert a Pipfile entry into a requirement string, or None to skip."""
if isinstance(spec, str):
version = spec.strip()
return name if version in ("", "*") else f"{name}{version}"
if isinstance(spec, dict):
# git/path/url references are pinned to a specific artifact.
if any(key in spec for key in ("git", "path", "file", "url")):
return None
version = str(spec.get("version", "")).strip()
return name if version in ("", "*") else f"{name}{version}"
return None
def _entries_from_pipfile(self, path: str, content: str) -> list[tuple[str, int | None, str]]:
"""``[packages]`` and ``[dev-packages]`` sections of a Pipfile (TOML)."""
data = self._safe_toml(content)
if not isinstance(data, dict):
return []
entries: list[tuple[str, int | None, str]] = []
for section in ("packages", "dev-packages"):
packages = data.get(section)
if not isinstance(packages, dict):
continue
for name, spec in packages.items():
requirement = self._pipfile_requirement(name, spec)
if requirement is not None:
entries.append((path, self._first_line_containing(content, name), requirement))
return entries
def _collect_requirement_entries(self, skill: Skill) -> list[tuple[str, int | None, str]]:
"""Gather ``(source_path, line_number, requirement_string)`` from every
dependency-declaring file in the skill plus manifest metadata."""
entries: list[tuple[str, int | None, str]] = []
for skill_file in skill.files:
file_name = Path(skill_file.relative_path).name.lower()
path = skill_file.relative_path
if file_name.startswith("requirements") and file_name.endswith(".txt"):
for line_number, raw in enumerate(skill_file.read_content().splitlines(), start=1):
entries.append((path, line_number, raw))
elif file_name == "pyproject.toml":
entries.extend(self._entries_from_pyproject(path, skill_file.read_content()))
elif file_name == "setup.cfg":
entries.extend(self._entries_from_setup_cfg(path, skill_file.read_content()))
elif file_name == "setup.py":
entries.extend(self._entries_from_setup_py(path, skill_file.read_content()))
elif file_name == "pipfile":
entries.extend(self._entries_from_pipfile(path, skill_file.read_content()))
metadata = skill.manifest.metadata
if isinstance(metadata, dict):
declared = metadata.get("dependencies")
if isinstance(declared, list):
for declared_dep in declared:
entries.append((str(skill.skill_md_path), None, str(declared_dep)))
return entries
def _check_dependency_pinning(self, skill: Skill) -> list[Finding]:
"""Flag dependencies declared without an exact pinned version.
Skill packages are end-user applications, so unpinned dependencies
(``requests>=2`` or a bare ``requests``) let a later, potentially
compromised release be pulled in at install time -- a supply-chain
risk. This differs from library pinning policy: libraries
intentionally use ranges, so if a lockfile is present the versions are
already frozen and we do not flag.
Sources checked: ``requirements*.txt``, ``pyproject.toml``
(``[project]`` dependencies and optional-dependencies), ``setup.cfg``,
``setup.py`` (``install_requires``), ``Pipfile``, and a
``dependencies`` list under manifest ``metadata``.
"""
findings: list[Finding] = []
# A lockfile freezes the resolved versions, so ranges are intentional.
if any(Path(f.relative_path).name.lower() in self._LOCKFILE_NAMES for f in skill.files):
return findings
for source_label, line_number, raw in self._collect_requirement_entries(skill):
classified = self._classify_requirement(raw)
if classified is None:
continue
package_name, status = classified
if status == "pinned":
continue
severity = Severity.LOW if status == "wildcard" else Severity.MEDIUM
if status == "wildcard":
detail = f"'{package_name}' is pinned to a wildcard version range"
else:
detail = f"'{package_name}' has no pinned (==) version"
findings.append(
Finding(
id=self._generate_finding_id(
"SUPPLY_CHAIN_UNPINNED_DEPENDENCY", f"{source_label}:{line_number}:{package_name}"
),
rule_id="SUPPLY_CHAIN_UNPINNED_DEPENDENCY",
category=ThreatCategory.SUPPLY_CHAIN_ATTACK,
severity=severity,
title="Unpinned dependency",
description=(
f"Dependency {detail}. Unpinned dependencies in a skill package allow a later, "
f"potentially malicious release to be installed automatically (supply-chain risk)."
),
file_path=source_label,
line_number=line_number,
snippet=raw.strip() or None,
remediation="Pin the dependency to an exact version (e.g. 'package==1.2.3').",
analyzer="static",
)
)
return findings
def _scan_referenced_files(self, skill: Skill) -> list[Finding]:
"""Scan files referenced in instruction body with recursive scanning."""
max_depth = self.policy.file_limits.max_reference_depth
findings = []
findings.extend(self._scan_references_recursive(skill, skill.referenced_files, max_depth=max_depth))
return findings
def _scan_references_recursive(
self,
skill: Skill,
references: list[str],
max_depth: int = 5,
current_depth: int = 0,
visited: set[str] | None = None,
) -> list[Finding]:
"""
Recursively scan referenced files up to a maximum depth.
This detects lazy-loaded content that might contain malicious patterns
hidden in nested references.
Args:
skill: The skill being analyzed
references: List of file paths to scan
max_depth: Maximum recursion depth
current_depth: Current depth in recursion
visited: Set of already-visited files to prevent cycles
Returns:
List of findings from all referenced files
"""
findings = []
if visited is None:
visited = set()
if current_depth > max_depth:
if references:
findings.append(
Finding(
id=self._generate_finding_id("LAZY_LOAD_DEEP", str(current_depth)),
rule_id="LAZY_LOAD_DEEP_NESTING",
category=ThreatCategory.OBFUSCATION,
severity=Severity.MEDIUM,
title="Deeply nested file references detected",
description=(
f"Skill has file references nested more than {max_depth} levels deep. "
f"This could be an attempt to hide malicious content in files that are "
f"only loaded under specific conditions."
),
file_path="SKILL.md",
remediation="Flatten the reference structure or ensure all nested files are safe",
analyzer="static",
)
)
return findings
for ref_file_path in references:
if _is_path_traversal(ref_file_path):
findings.append(
Finding(
id=self._generate_finding_id("PATH_TRAVERSAL", ref_file_path),
rule_id="PATH_TRAVERSAL_ATTEMPT",
category=ThreatCategory.DATA_EXFILTRATION,
severity=Severity.CRITICAL,
title="Path traversal attempt in file reference",
description=(
f"Reference '{ref_file_path}' attempts to escape the skill directory. "
f"This is a path traversal attack that could read sensitive files "
f"from the host system."
),
file_path="SKILL.md",
remediation="Remove path traversal sequences from file references",
analyzer="static",
)
)
continue
full_path = skill.directory / ref_file_path
if not full_path.exists():
alt_paths = [
skill.directory / "references" / ref_file_path,
skill.directory / "assets" / ref_file_path,
skill.directory / "templates" / ref_file_path,
skill.directory / "scripts" / ref_file_path,
]
for alt in alt_paths:
if alt.exists():
full_path = alt
break
if not full_path.exists():
continue
if not _is_within_directory(full_path, skill.directory):
findings.append(
Finding(
id=self._generate_finding_id("PATH_TRAVERSAL_RESOLVED", ref_file_path),
rule_id="PATH_TRAVERSAL_ATTEMPT",
category=ThreatCategory.DATA_EXFILTRATION,
severity=Severity.CRITICAL,
title="File reference resolves outside skill directory",
description=(
f"Reference '{ref_file_path}' resolves to a path outside the skill "
f"directory. This could be a path traversal attack."
),
file_path="SKILL.md",
remediation="Ensure all file references point to files within the skill directory",
analyzer="static",
)
)
continue
dedupe_reference_aliases = self.policy.rule_scoping.dedupe_reference_aliases
# De-duplicate aliases to the same physical file (e.g.
# "cover_art_generator.py" and "scripts/cover_art_generator.py").
if dedupe_reference_aliases:
try:
visited_key = str(full_path.resolve())
except OSError:
visited_key = str(full_path)
else:
visited_key = ref_file_path
if visited_key in visited:
continue
visited.add(visited_key)
# Prefer the canonical skill-relative path for reporting.
display_path = ref_file_path
if dedupe_reference_aliases:
try:
resolved_full = full_path.resolve()
for sf in skill.files:
try:
if sf.path.resolve() == resolved_full:
display_path = sf.relative_path
break
except OSError:
continue
except OSError:
pass
try:
with open(full_path, encoding="utf-8") as f:
content = f.read()
suffix = full_path.suffix.lower()
if suffix in (".md", ".markdown"):
rules = self.rule_loader.get_rules_for_file_type("markdown")
elif suffix == ".py":
rules = self.rule_loader.get_rules_for_file_type("python")
elif suffix in (".sh", ".bash"):
rules = self.rule_loader.get_rules_for_file_type("bash")
elif suffix in (".js", ".mjs", ".cjs"):
rules = self.rule_loader.get_rules_for_file_type("javascript")
elif suffix in (".ts", ".tsx"):
rules = self.rule_loader.get_rules_for_file_type("typescript")
else:
rules = []
skip_in_docs = set(self.policy.rule_scoping.skip_in_docs)
is_doc = self._is_doc_file(display_path)
for rule in rules:
# Skip rules scoped out of documentation files