aegismcp-security 3.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
aegismcp/__init__.py ADDED
@@ -0,0 +1,40 @@
1
+ """AegisMCP - Security scanner for MCP configurations and AI agent tools."""
2
+
3
+ from .ast_scanner import ASTFinding, scan_python_directory, scan_python_file
4
+ from .cli import main
5
+ from .config import Config
6
+ from .discovery import discover_mcp_files, get_config_paths
7
+ from .lockfile import (
8
+ Lockfile,
9
+ create_lock_from_config,
10
+ update_lockfile_with_tools,
11
+ verify_lockfile,
12
+ verify_tools,
13
+ )
14
+ from .rules.registry import Rule, registry
15
+ from .rules_core import Finding
16
+ from .sarif import export_sarif
17
+ from .scanner import scan_directory, scan_file
18
+
19
+ __version__ = "3.1.0"
20
+ __all__ = [
21
+ "ASTFinding",
22
+ "Config",
23
+ "Finding",
24
+ "Lockfile",
25
+ "Rule",
26
+ "create_lock_from_config",
27
+ "create_lockfile_from_config",
28
+ "discover_mcp_files",
29
+ "export_sarif",
30
+ "get_config_paths",
31
+ "main",
32
+ "registry",
33
+ "scan_directory",
34
+ "scan_file",
35
+ "scan_python_directory",
36
+ "scan_python_file",
37
+ "update_lockfile_with_tools",
38
+ "verify_lockfile",
39
+ "verify_tools",
40
+ ]
aegismcp/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Entry point for python -m aegismcp."""
2
+ from aegismcp.cli import main
3
+
4
+ if __name__ == "__main__":
5
+ main()
@@ -0,0 +1,416 @@
1
+ """AST-based scanning for Python MCP server source code."""
2
+ from __future__ import annotations
3
+
4
+ import ast
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+
8
+
9
+ @dataclass
10
+ class ASTFinding:
11
+ """A security finding from AST analysis."""
12
+ rule_id: str
13
+ severity: str
14
+ confidence: str # HIGH, MEDIUM, LOW
15
+ title: str
16
+ message: str
17
+ file_path: Path
18
+ line: int
19
+ column: int
20
+ remediation: str
21
+
22
+ @property
23
+ def location(self) -> str:
24
+ """Format location for reporting."""
25
+ return f"{self.file_path}:{self.line}:{self.column}"
26
+
27
+
28
+ class PythonASTVisitor(ast.NodeVisitor):
29
+ """AST visitor that detects security issues in Python MCP servers."""
30
+
31
+ def __init__(self, file_path: Path):
32
+ self.file_path = file_path
33
+ self.findings: list[ASTFinding] = []
34
+ # Taint tracking state: scope-aware variable -> taint source
35
+ self._taint_scope: list[dict[str, str]] = [{}]
36
+ # Current function parameters (taint sources)
37
+ self._current_params: set[str] = set()
38
+
39
+ def _push_scope(self) -> None:
40
+ self._taint_scope.append({})
41
+
42
+ def _pop_scope(self) -> None:
43
+ if len(self._taint_scope) > 1:
44
+ self._taint_scope.pop()
45
+
46
+ def _current_taint(self) -> dict[str, str]:
47
+ return self._taint_scope[-1]
48
+
49
+ def _is_tainted(self, node: ast.AST) -> bool:
50
+ """Check if an AST node is tainted (user-controlled)."""
51
+ if isinstance(node, ast.Name):
52
+ # Check if variable is in any scope
53
+ for scope in reversed(self._taint_scope):
54
+ if node.id in scope:
55
+ return True
56
+ # Function params are taint sources
57
+ return node.id in self._current_params
58
+ if isinstance(node, ast.JoinedStr): # f-string
59
+ return any(self._is_tainted(v) for v in node.values)
60
+ if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add): # concat
61
+ return self._is_tainted(node.left) or self._is_tainted(node.right)
62
+ if isinstance(node, ast.Subscript): # indexing
63
+ return self._is_tainted(node.value) or self._is_tainted(node.slice)
64
+ if isinstance(node, ast.Call):
65
+ # Function call result - conservative: tainted if any arg tainted
66
+ return any(self._is_tainted(a) for a in node.args) or any(
67
+ self._is_tainted(kw.value) for kw in node.keywords
68
+ )
69
+ if isinstance(node, ast.Attribute):
70
+ return self._is_tainted(node.value)
71
+ return False
72
+
73
+ def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
74
+ self._push_scope()
75
+ # Function parameters are taint sources
76
+ old_params = self._current_params
77
+ self._current_params = set()
78
+ for arg in node.args.args:
79
+ self._current_params.add(arg.arg)
80
+ # Defaults are not tainted
81
+ self.generic_visit(node)
82
+ self._current_params = old_params
83
+ self._pop_scope()
84
+
85
+ def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:
86
+ self.visit_FunctionDef(node) # type: ignore
87
+
88
+ def visit_Assign(self, node: ast.Assign) -> None:
89
+ # Propagate taint through assignments
90
+ tainted = self._is_tainted(node.value)
91
+ for target in node.targets:
92
+ if isinstance(target, ast.Name):
93
+ if tainted:
94
+ self._current_taint()[target.id] = "tainted"
95
+ else:
96
+ # Remove taint if reassigned to safe value
97
+ self._current_taint().pop(target.id, None)
98
+ self.generic_visit(node)
99
+
100
+ def visit_AugAssign(self, node: ast.AugAssign) -> None:
101
+ if isinstance(node.target, ast.Name) and (
102
+ self._is_tainted(node.value) or node.target.id in self._current_taint()
103
+ ):
104
+ self._current_taint()[node.target.id] = "tainted"
105
+ self.generic_visit(node)
106
+
107
+ def _add_finding(self, rule_id: str, severity: str, confidence: str, title: str, message: str,
108
+ node: ast.AST, remediation: str) -> None:
109
+ """Add a finding with location info."""
110
+ self.findings.append(ASTFinding(
111
+ rule_id=rule_id,
112
+ severity=severity,
113
+ confidence=confidence,
114
+ title=title,
115
+ message=message,
116
+ file_path=self.file_path,
117
+ line=getattr(node, 'lineno', 0),
118
+ column=getattr(node, 'col_offset', 0),
119
+ remediation=remediation,
120
+ ))
121
+
122
+ def visit_Call(self, node: ast.Call) -> None:
123
+ """Single visit_Call that runs all security checks."""
124
+ # Command Injection (AMCP101, AMCP102)
125
+ self._check_command_injection(node)
126
+
127
+ # SSRF (AMCP103)
128
+ self._check_ssrf(node)
129
+
130
+ # Path Traversal (AMCP104)
131
+ self._check_path_traversal(node)
132
+
133
+ # Insecure Deserialization (AMCP105)
134
+ self._check_insecure_deserialization(node)
135
+
136
+ self.generic_visit(node)
137
+
138
+ # === Command Injection (AMCP101, AMCP102) ===
139
+ def _check_command_injection(self, node: ast.Call) -> None:
140
+ # subprocess.run, Popen, call, check_call, check_output
141
+ if isinstance(node.func, ast.Attribute):
142
+ if node.func.attr in ("run", "Popen", "call", "check_call", "check_output"):
143
+ if isinstance(node.func.value, ast.Name) and node.func.value.id == "subprocess":
144
+ self._check_subprocess_call(node)
145
+ # os.system, os.popen
146
+ elif node.func.attr in ("system", "popen") and isinstance(node.func.value, ast.Name) and node.func.value.id == "os":
147
+ self._add_finding(
148
+ "AMCP101", "CRITICAL", "HIGH",
149
+ "Direct shell execution via os.system/popen",
150
+ f"Use of os.{node.func.attr}() detected - allows arbitrary command execution",
151
+ node,
152
+ "Use subprocess.run() with shell=False and validate/sanitize all inputs"
153
+ )
154
+
155
+ # eval, exec
156
+ elif isinstance(node.func, ast.Name) and node.func.id in ("eval", "exec"):
157
+ self._add_finding(
158
+ "AMCP102", "CRITICAL", "HIGH",
159
+ f"Use of {node.func.id}()",
160
+ f"Dynamic code execution via {node.func.id}() - severe security risk",
161
+ node,
162
+ f"Avoid {node.func.id}(). Use ast.literal_eval() for safe evaluation or redesign."
163
+ )
164
+
165
+ def _check_subprocess_call(self, node: ast.Call) -> None:
166
+ """Analyze subprocess call for injection risks."""
167
+ # Check if shell=True
168
+ shell_true = False
169
+ for kw in node.keywords:
170
+ if kw.arg == "shell" and isinstance(kw.value, ast.Constant) and kw.value.value is True:
171
+ shell_true = True
172
+ break
173
+
174
+ # Check if command is built from variables (not just literals)
175
+ args = node.args
176
+ if args:
177
+ first_arg = args[0]
178
+ if not self._is_safe_command(first_arg):
179
+ severity = "CRITICAL" if shell_true else "HIGH"
180
+ # Confidence based on taint analysis
181
+ if self._is_tainted(first_arg):
182
+ confidence = "HIGH"
183
+ elif isinstance(first_arg, ast.Constant):
184
+ confidence = "LOW"
185
+ else:
186
+ confidence = "MEDIUM"
187
+ if shell_true:
188
+ confidence = "HIGH"
189
+ self._add_finding(
190
+ "AMCP101", severity, confidence,
191
+ "Command injection via subprocess" + (" (shell=True)" if shell_true else ""),
192
+ "subprocess call with dynamic command arguments detected",
193
+ node,
194
+ "Use shell=False, pass args as list, validate/sanitize all inputs"
195
+ )
196
+
197
+ def _is_safe_command(self, node: ast.AST) -> bool:
198
+ """Check if a command argument is a safe literal list."""
199
+ # If it's a list/tuple of arguments, check if first element (the command) is a constant
200
+ if isinstance(node, (ast.List, ast.Tuple)):
201
+ if node.elts:
202
+ first = node.elts[0]
203
+ return isinstance(first, ast.Constant) and isinstance(first.value, str)
204
+ return False
205
+ # If it's a string constant (shell command), not safe for shell=False
206
+ if isinstance(node, ast.Constant) and isinstance(node.value, str):
207
+ return False
208
+ return False
209
+
210
+ # === SSRF (AMCP103) ===
211
+ def _check_ssrf(self, node: ast.Call) -> None:
212
+ """Detect potential SSRF in HTTP calls."""
213
+ http_methods = {"get", "post", "put", "patch", "delete", "head", "options", "request"}
214
+ http_libs = {"requests", "httpx", "urllib", "urllib3", "aiohttp", "http.client"}
215
+
216
+ func = node.func
217
+ method_name = None
218
+ lib_name = None
219
+
220
+ if isinstance(func, ast.Attribute):
221
+ method_name = func.attr
222
+ if isinstance(func.value, ast.Name):
223
+ lib_name = func.value.id
224
+ elif isinstance(func.value, ast.Attribute) and isinstance(func.value.value, ast.Name):
225
+ # e.g., requests.get, httpx.Client.get
226
+ lib_name = func.value.value.id
227
+
228
+ if method_name in http_methods and lib_name in http_libs:
229
+ # Check if URL argument is dynamic
230
+ url_arg = None
231
+ if node.args:
232
+ url_arg = node.args[0]
233
+ else:
234
+ for kw in node.keywords:
235
+ if kw.arg in ("url", "uri"):
236
+ url_arg = kw.value
237
+ break
238
+
239
+ if url_arg and not self._is_safe_url(url_arg):
240
+ confidence = "HIGH" if self._is_tainted(url_arg) else "MEDIUM"
241
+ self._add_finding(
242
+ "AMCP103", "HIGH", confidence,
243
+ "Potential SSRF (Server-Side Request Forgery)",
244
+ f"HTTP request with dynamic URL detected ({lib_name}.{method_name})",
245
+ node,
246
+ "Validate URLs against allowlist, block private/internal IPs (10.x, 172.16-31.x, 192.168.x, 127.x, 169.254.x)"
247
+ )
248
+
249
+ def _is_safe_url(self, node: ast.AST) -> bool:
250
+ """Check if URL is a safe literal."""
251
+ if isinstance(node, ast.Constant) and isinstance(node.value, str):
252
+ url = node.value
253
+ # Check for obviously safe patterns (but this is heuristic)
254
+ return url.startswith(("https://api.", "https://www."))
255
+ return False
256
+
257
+ # === Path Traversal (AMCP104) ===
258
+ def _check_path_traversal(self, node: ast.Call) -> None:
259
+ """Detect path traversal vulnerabilities."""
260
+ # Functions that accept paths - only flag if path is clearly user-controlled/dynamic
261
+ path_funcs = {
262
+ "open", "read", "write_text", "write_bytes", "unlink", "rmdir", "mkdir",
263
+ "remove", "rename", "replace", "symlink", "readlink", "lstat", "stat",
264
+ "chmod", "chown", "access", "exists", "is_file", "is_dir"
265
+ }
266
+
267
+ func_name = None
268
+ if isinstance(node.func, ast.Name):
269
+ func_name = node.func.id
270
+ elif isinstance(node.func, ast.Attribute):
271
+ func_name = node.func.attr
272
+
273
+ if func_name not in path_funcs:
274
+ return
275
+
276
+ # Check if there's a path argument
277
+ path_arg = None
278
+ if node.args:
279
+ path_arg = node.args[0]
280
+ else:
281
+ for kw in node.keywords:
282
+ if kw.arg in ("path", "file", "filename", "name"):
283
+ path_arg = kw.value
284
+ break
285
+
286
+ if path_arg and self._is_user_controlled_path(path_arg):
287
+ confidence = "HIGH" if self._is_tainted(path_arg) else "MEDIUM"
288
+ self._add_finding(
289
+ "AMCP104", "HIGH", confidence,
290
+ "Potential Path Traversal",
291
+ f"File operation with user-controlled path: {func_name}()",
292
+ node,
293
+ "Validate/resolve paths with Path.resolve(), restrict to allowed directories, avoid user input in paths"
294
+ )
295
+
296
+ def _is_user_controlled_path(self, node: ast.AST) -> bool:
297
+ """
298
+ Heuristic: does this path expression contain user-controlled/dynamic input?
299
+ Returns True if the path is likely from user input (function param, f-string,
300
+ concat, variable, function call), False if it's a safe literal or known-safe pattern.
301
+ """
302
+ # Safe: string literal without traversal sequences
303
+ if isinstance(node, ast.Constant) and isinstance(node.value, str):
304
+ val = node.value
305
+ # Known-safe patterns: temp paths, relative paths without ..
306
+ if ".." in val or val.startswith("/"):
307
+ # Absolute paths or explicit traversal - suspicious
308
+ # But allow known temp fixtures
309
+ return not ("tmp" in val.lower() or "temp" in val.lower())
310
+ return False
311
+
312
+ # Safe: Path(...).resolve() or Path.cwd() / "literal"
313
+ if isinstance(node, ast.Call):
314
+ # Path.resolve() calls
315
+ if isinstance(node.func, ast.Attribute) and node.func.attr == "resolve":
316
+ return False
317
+ # Path() constructor with safe args
318
+ if isinstance(node.func, ast.Name) and node.func.id == "Path":
319
+ return all(not self._is_user_controlled_path(arg) for arg in node.args)
320
+ # pathlib.Path operations
321
+ if isinstance(node.func, ast.Attribute) and node.func.attr in ("joinpath", "__truediv__"):
322
+ return any(self._is_user_controlled_path(arg) for arg in node.args)
323
+ return True # Other function calls are dynamic
324
+
325
+ # Unsafe: f-strings, string concatenation, variables
326
+ if isinstance(node, ast.JoinedStr): # f-string
327
+ return True
328
+ if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add): # string concat
329
+ return True
330
+ if isinstance(node, ast.Name): # variable
331
+ # Use taint tracking: if tainted, user-controlled
332
+ if self._is_tainted(node):
333
+ return True
334
+ # Non-tainted variable (e.g., local constant) - still potentially user-controlled
335
+ return True
336
+ return isinstance(node, (ast.Subscript, ast.Attribute)) # indexing like args[0] or attribute access like obj.path
337
+
338
+ # === Insecure Deserialization (AMCP105) ===
339
+ def _check_insecure_deserialization(self, node: ast.Call) -> None:
340
+ """Detect pickle.loads, yaml.load (unsafe), etc."""
341
+ unsafe_funcs = {
342
+ "pickle": ["loads", "load"],
343
+ "yaml": ["load", "unsafe_load"],
344
+ "marshal": ["loads", "load"],
345
+ "shelve": ["open"],
346
+ "dill": ["loads", "load"],
347
+ }
348
+
349
+ func = node.func
350
+ if isinstance(func, ast.Attribute) and isinstance(func.value, ast.Name):
351
+ lib = func.value.id
352
+ method = func.attr
353
+ if lib in unsafe_funcs and method in unsafe_funcs[lib]:
354
+ # Check if it's yaml.load without Loader=SafeLoader
355
+ if lib == "yaml" and method == "load":
356
+ has_safe_loader = any(
357
+ kw.arg == "Loader" for kw in node.keywords
358
+ )
359
+ if has_safe_loader:
360
+ return
361
+ self._add_finding(
362
+ "AMCP105", "CRITICAL", "HIGH",
363
+ f"Insecure Deserialization ({lib}.{method})",
364
+ f"Use of {lib}.{method}() can lead to arbitrary code execution",
365
+ node,
366
+ "Use safe alternatives: yaml.safe_load(), json.loads(), or specify Loader=yaml.SafeLoader"
367
+ )
368
+
369
+
370
+ def scan_python_file(file_path: Path) -> list[ASTFinding]:
371
+ """Scan a single Python file for security issues."""
372
+ try:
373
+ with file_path.open("r", encoding="utf-8") as f:
374
+ source = f.read()
375
+ except OSError:
376
+ return []
377
+
378
+ try:
379
+ tree = ast.parse(source, filename=str(file_path))
380
+ except SyntaxError:
381
+ return []
382
+
383
+ visitor = PythonASTVisitor(file_path)
384
+ visitor.visit(tree)
385
+ return visitor.findings
386
+
387
+
388
+ def _is_test_file(file_path: Path) -> bool:
389
+ """Check if a file is a test file based on naming conventions."""
390
+ name = file_path.name
391
+ # Check for test_*.py or *_test.py patterns
392
+ if name.startswith("test_") and name.endswith(".py"):
393
+ return True
394
+ return name.endswith("_test.py")
395
+
396
+
397
+ def _is_in_test_dir(file_path: Path) -> bool:
398
+ """Check if a file is in a test directory."""
399
+ test_dirs = {"tests", "test", "testing", "__tests__", "__test__"}
400
+ return any(part in test_dirs for part in file_path.parts)
401
+
402
+
403
+ def scan_python_directory(root: Path, include_tests: bool = False) -> list[ASTFinding]:
404
+ """Recursively scan all Python files in a directory."""
405
+ findings = []
406
+ ignore_dirs = {".git", "__pycache__", ".venv", "venv", "env", "dist", "build", ".pytest_cache", ".mypy_cache", "node_modules"}
407
+
408
+ for py_file in root.rglob("*.py"):
409
+ if any(part in ignore_dirs for part in py_file.parts):
410
+ continue
411
+ # Skip test files/directories unless explicitly included
412
+ if not include_tests and (_is_test_file(py_file) or _is_in_test_dir(py_file)):
413
+ continue
414
+ findings.extend(scan_python_file(py_file))
415
+
416
+ return findings