-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscan.py
More file actions
148 lines (127 loc) · 5.07 KB
/
scan.py
File metadata and controls
148 lines (127 loc) · 5.07 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
#!/usr/bin/env python3
"""
SkillGuard - Security scanner for OpenClaw skills
Scans skill directories for suspicious patterns that might indicate malicious code.
Usage: python scan.py /path/to/skill
"""
import sys
import os
import re
from pathlib import Path
from dataclasses import dataclass
from typing import List, Tuple
@dataclass
class Finding:
severity: str # HIGH, MEDIUM, LOW
file: str
line: int
pattern: str
context: str
# Patterns to detect
PATTERNS = {
"HIGH": [
(r'(api[_-]?key|secret|password|token|credential)["\s]*[:=]', "Hardcoded credential"),
(r'os\.environ\.get\(["\'][^"\']*(?:key|secret|token|password)', "Environment credential access"),
(r'requests\.(post|put)\s*\([^)]*(?<!api\.)|urllib|httpx.*post', "Outbound data exfiltration risk"),
(r'eval\s*\(|exec\s*\(', "Dynamic code execution"),
(r'subprocess.*shell\s*=\s*True', "Shell injection risk"),
(r'base64\.(b64encode|encode).*(?:key|secret|token|password)', "Encoded credential exfiltration"),
],
"MEDIUM": [
(r'open\s*\([^)]*["\']\/etc\/', "System file access"),
(r'os\.(system|popen|spawn)', "System command execution"),
(r'__import__\s*\(', "Dynamic import"),
(r'pickle\.load', "Pickle deserialization (code execution risk)"),
(r'chmod.*777|chmod.*\+x', "Overly permissive file permissions"),
],
"LOW": [
(r'# ?TODO|# ?FIXME|# ?HACK', "Code quality marker"),
(r'print\s*\(.*(?:key|secret|token)', "Potential credential logging"),
(r'\.env|dotenv', "Environment file usage"),
]
}
def scan_file(filepath: Path) -> List[Finding]:
"""Scan a single file for suspicious patterns."""
findings = []
try:
content = filepath.read_text(errors='ignore')
lines = content.split('\n')
for severity, patterns in PATTERNS.items():
for pattern, description in patterns:
for i, line in enumerate(lines, 1):
if re.search(pattern, line, re.IGNORECASE):
findings.append(Finding(
severity=severity,
file=str(filepath),
line=i,
pattern=description,
context=line.strip()[:100]
))
except Exception as e:
findings.append(Finding("ERROR", str(filepath), 0, "Read error", str(e)))
return findings
def scan_skill(skill_path: str) -> Tuple[List[Finding], int]:
"""Scan entire skill directory."""
path = Path(skill_path)
all_findings = []
# File extensions to scan
extensions = {'.py', '.sh', '.js', '.ts', '.md', '.json', '.yaml', '.yml'}
if path.is_file():
all_findings.extend(scan_file(path))
else:
for file in path.rglob('*'):
if file.is_file() and file.suffix in extensions:
all_findings.extend(scan_file(file))
# Calculate trust score (0-100)
high_count = sum(1 for f in all_findings if f.severity == "HIGH")
med_count = sum(1 for f in all_findings if f.severity == "MEDIUM")
low_count = sum(1 for f in all_findings if f.severity == "LOW")
score = 100 - (high_count * 25) - (med_count * 10) - (low_count * 2)
score = max(0, min(100, score))
return all_findings, score
def main():
if len(sys.argv) < 2:
print("Usage: python scan.py /path/to/skill")
print(" python scan.py /path/to/skill --json")
sys.exit(1)
skill_path = sys.argv[1]
json_output = "--json" in sys.argv
if not os.path.exists(skill_path):
print(f"Error: Path '{skill_path}' does not exist")
sys.exit(1)
findings, score = scan_skill(skill_path)
if json_output:
import json
output = {
"path": skill_path,
"trust_score": score,
"findings": [
{"severity": f.severity, "file": f.file, "line": f.line,
"pattern": f.pattern, "context": f.context}
for f in findings
]
}
print(json.dumps(output, indent=2))
else:
print(f"\n{'='*60}")
print(f"SkillGuard Security Scan: {skill_path}")
print(f"{'='*60}")
print(f"\nTrust Score: {score}/100", end="")
if score >= 80:
print(" ✅ LOW RISK")
elif score >= 50:
print(" ⚠️ MEDIUM RISK")
else:
print(" 🚨 HIGH RISK")
if findings:
print(f"\nFindings ({len(findings)}):")
for f in sorted(findings, key=lambda x: {"HIGH": 0, "MEDIUM": 1, "LOW": 2, "ERROR": 3}[x.severity]):
icon = {"HIGH": "🔴", "MEDIUM": "🟡", "LOW": "🟢", "ERROR": "❌"}[f.severity]
print(f"\n{icon} [{f.severity}] {f.pattern}")
print(f" File: {f.file}:{f.line}")
print(f" Context: {f.context}")
else:
print("\n✅ No suspicious patterns detected!")
print(f"\n{'='*60}\n")
if __name__ == "__main__":
main()