magen 0.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.
- magen/__init__.py +3 -0
- magen/cli.py +158 -0
- magen/leaks.py +232 -0
- magen/risk.py +157 -0
- magen/scan.py +205 -0
- magen/sources.py +321 -0
- magen-0.1.0.dist-info/METADATA +172 -0
- magen-0.1.0.dist-info/RECORD +13 -0
- magen-0.1.0.dist-info/WHEEL +5 -0
- magen-0.1.0.dist-info/entry_points.txt +2 -0
- magen-0.1.0.dist-info/licenses/LICENSE-APACHE +202 -0
- magen-0.1.0.dist-info/licenses/LICENSE-MIT +21 -0
- magen-0.1.0.dist-info/top_level.txt +1 -0
magen/__init__.py
ADDED
magen/cli.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"""magen: command line."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import sys
|
|
9
|
+
import unicodedata
|
|
10
|
+
|
|
11
|
+
from . import __version__, leaks, risk, scan
|
|
12
|
+
|
|
13
|
+
MAX_LINE = 2000
|
|
14
|
+
# Letters that render as nothing: a server named with them would be invisible.
|
|
15
|
+
BLANK = set("\u115f\u1160\u3164\uffa0\u2800\u180e\u17b4\u17b5\u034f")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def clean(text) -> str:
|
|
19
|
+
"""Nothing from a file reaches the terminal without this: secrets and emails masked, and every
|
|
20
|
+
control, format, invisible or line-breaking character (escape codes, bidi tricks, newlines that
|
|
21
|
+
could forge report lines, lone surrogates) replaced with '?'."""
|
|
22
|
+
text = leaks.redact(str(text), MAX_LINE)
|
|
23
|
+
text = text.encode("utf-8", "replace").decode("utf-8", "replace")
|
|
24
|
+
out = []
|
|
25
|
+
for ch in text:
|
|
26
|
+
cat = unicodedata.category(ch)
|
|
27
|
+
if ch == "️": # emoji variation selector: harmless, keeps our icons
|
|
28
|
+
out.append(ch)
|
|
29
|
+
elif cat in ("Cc", "Cf", "Zl", "Zp", "Cs", "Co", "Cn") or (cat == "Zs" and ch != " ") or ch in BLANK:
|
|
30
|
+
out.append("?")
|
|
31
|
+
else:
|
|
32
|
+
out.append(ch)
|
|
33
|
+
return "".join(out)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _short(path: str, home: str) -> str:
|
|
37
|
+
home = home.rstrip(os.sep)
|
|
38
|
+
if path == home:
|
|
39
|
+
return "~"
|
|
40
|
+
return "~" + path[len(home):] if path.startswith(home + os.sep) else path
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _scope(scope: str, home: str) -> str:
|
|
44
|
+
return "project:" + _short(scope[len("project:"):], home) if scope.startswith("project:") else scope
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _when(days, history) -> str:
|
|
48
|
+
if days is None:
|
|
49
|
+
return f"not used in the last {history} days"
|
|
50
|
+
if days == 0:
|
|
51
|
+
return "last used today"
|
|
52
|
+
if days == 1:
|
|
53
|
+
return "last used yesterday"
|
|
54
|
+
return f"last used {days} days ago"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def render(rep: scan.Report, home: str, verbose: bool = False) -> str:
|
|
58
|
+
I = risk.ICON
|
|
59
|
+
c = rep.counts
|
|
60
|
+
out = ["", "Magen scan", ""]
|
|
61
|
+
acc = rep.account or {}
|
|
62
|
+
who = ", ".join(x for x in (acc.get("email"), acc.get("organization")) if x)
|
|
63
|
+
out.append(f"Claude account: {who or 'not logged in to Claude Code'}")
|
|
64
|
+
out.append("(servers and rules belong to this computer user, claude.ai connectors to the Claude account)")
|
|
65
|
+
out.append(f"History: Claude Code keeps {rep.history_days} days of history (cleanupPeriodDays)")
|
|
66
|
+
out.append("")
|
|
67
|
+
|
|
68
|
+
out.append(f"MCP servers and connectors ({len(rep.servers)})")
|
|
69
|
+
if not rep.servers:
|
|
70
|
+
out.append(" none found")
|
|
71
|
+
for s in rep.servers:
|
|
72
|
+
where = s.scope if s.scope.startswith(("claude.ai", "other")) else \
|
|
73
|
+
f"{_scope(s.scope, home)}, {_short(s.source, home)}"
|
|
74
|
+
if s.never_used_connector:
|
|
75
|
+
out.append(f" [ask] {s.name} ({where}) connected at some point, not used in the last {rep.history_days} days")
|
|
76
|
+
out.append(f" do you still need it? If not, disconnect it: {scan.DISCONNECT_HINT}")
|
|
77
|
+
continue
|
|
78
|
+
when = _when(s.days_unused, rep.history_days)
|
|
79
|
+
flag = " (unused)" if s in rep.unused else ""
|
|
80
|
+
out.append(f" {I[s.level]} {s.name} ({where}) {when}{flag}")
|
|
81
|
+
out.append(f" {risk.PLAIN[s.level]}")
|
|
82
|
+
reds = sorted(t for t, (l, _) in s.tools.items() if l == risk.RED)
|
|
83
|
+
if reds:
|
|
84
|
+
out.append(f" risky tools: {', '.join(reds)}")
|
|
85
|
+
for loc in s.secrets:
|
|
86
|
+
out.append(f" secret in plain text in {loc}: move it to your keychain")
|
|
87
|
+
if verbose:
|
|
88
|
+
for t, (l, ts) in sorted(s.tools.items()):
|
|
89
|
+
out.append(f" {I[l]} {t} {ts[:10]}")
|
|
90
|
+
out.append("")
|
|
91
|
+
|
|
92
|
+
allow = [r for r in rep.rules if r.kind in ("setting", "allow")]
|
|
93
|
+
out.append(f"Allowed without asking ({len(allow)})")
|
|
94
|
+
if not allow:
|
|
95
|
+
out.append(" none")
|
|
96
|
+
for r in allow:
|
|
97
|
+
out.append(f" {I[r.level]} {r.rule} ({_short(r.source, home)})")
|
|
98
|
+
out.append(f" {r.why}")
|
|
99
|
+
others = [r for r in rep.rules if r.kind in ("ask", "deny")]
|
|
100
|
+
if others and verbose:
|
|
101
|
+
out.append("")
|
|
102
|
+
out.append("Ask / deny rules")
|
|
103
|
+
for r in others:
|
|
104
|
+
out.append(f" {r.kind}: {r.rule} ({_short(r.source, home)})")
|
|
105
|
+
out.append("")
|
|
106
|
+
|
|
107
|
+
out.append(f"Summary: red {c[risk.RED]}, yellow {c[risk.YELLOW]}, green {c[risk.GREEN]}, "
|
|
108
|
+
f"unclear {c[risk.UNKNOWN]} | secrets {rep.secret_count} | unused {len(rep.unused)} "
|
|
109
|
+
f"({rep.unused_days}+ days) | connected, not used {len(rep.never_used)}")
|
|
110
|
+
if c[risk.RED] or rep.secret_count:
|
|
111
|
+
out.append("Start with the secrets, then the red lines. Nothing was changed: Magen only looked.")
|
|
112
|
+
elif rep.unused or rep.never_used:
|
|
113
|
+
out.append("No red flags. Have a look at the unused ones. Nothing was changed: Magen only looked.")
|
|
114
|
+
else:
|
|
115
|
+
out.append("Looking good. Nothing was changed: Magen only looked.")
|
|
116
|
+
out.append("")
|
|
117
|
+
return "\n".join(clean(line) for line in out)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _quiet_broken_pipe():
|
|
121
|
+
"""`magen scan | head` closes the pipe early: stop quietly instead of printing a traceback."""
|
|
122
|
+
try:
|
|
123
|
+
fd = os.open(os.devnull, os.O_WRONLY)
|
|
124
|
+
os.dup2(fd, sys.stdout.fileno())
|
|
125
|
+
except (OSError, ValueError):
|
|
126
|
+
pass
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def main(argv=None) -> int:
|
|
130
|
+
p = argparse.ArgumentParser(prog="magen", description="A shield for your AI agent's permissions.")
|
|
131
|
+
p.add_argument("--version", action="version", version=f"magen {__version__}")
|
|
132
|
+
sub = p.add_subparsers(dest="cmd")
|
|
133
|
+
s = sub.add_parser("scan", help="show everything your agent is allowed to do")
|
|
134
|
+
s.add_argument("--json", action="store_true", help="machine-readable output")
|
|
135
|
+
s.add_argument("--days", type=int, default=30, help="call a server unused after N days (default 30)")
|
|
136
|
+
s.add_argument("--verbose", "-v", action="store_true", help="show every tool")
|
|
137
|
+
s.add_argument("--project", action="append", default=[], help="also scan this project folder")
|
|
138
|
+
s.add_argument("--home", default=os.path.expanduser("~"), help=argparse.SUPPRESS)
|
|
139
|
+
a = p.parse_args(argv)
|
|
140
|
+
|
|
141
|
+
if a.cmd != "scan":
|
|
142
|
+
p.print_help()
|
|
143
|
+
return 0
|
|
144
|
+
rep = scan.run(a.home, unused_days=a.days, extra_projects=[os.path.abspath(x) for x in a.project])
|
|
145
|
+
if a.json:
|
|
146
|
+
text = json.dumps(scan.to_dict(rep), indent=2, ensure_ascii=True) # ascii: no raw control codes
|
|
147
|
+
else:
|
|
148
|
+
text = render(rep, a.home, a.verbose)
|
|
149
|
+
try:
|
|
150
|
+
print(text)
|
|
151
|
+
sys.stdout.flush()
|
|
152
|
+
except BrokenPipeError:
|
|
153
|
+
_quiet_broken_pipe()
|
|
154
|
+
return 0
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
if __name__ == "__main__":
|
|
158
|
+
sys.exit(main())
|
magen/leaks.py
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
"""Find secrets written in plain text. Values are never returned or printed.
|
|
2
|
+
|
|
3
|
+
Every regex here starts with a lookbehind or a literal, so it runs in linear time even on
|
|
4
|
+
hostile megabyte-long strings (no ReDoS).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import math
|
|
10
|
+
import re
|
|
11
|
+
from urllib.parse import urlsplit # parsing only: urllib.parse has no network code
|
|
12
|
+
|
|
13
|
+
MASK = "•••"
|
|
14
|
+
MAX_SHOW = 500 # longest string Magen ever shows
|
|
15
|
+
MAX_SCAN = 4_096 # longest string Magen ever runs patterns on
|
|
16
|
+
|
|
17
|
+
# Words in a *name* that mean "the value is a secret".
|
|
18
|
+
SECRET_WORDS = {"key", "apikey", "token", "secret", "password", "passwd", "pass", "pwd", "pat",
|
|
19
|
+
"credential", "credentials", "privatekey", "bearer", "cookie", "authorization",
|
|
20
|
+
"dsn", "passphrase", "signature", "sig"}
|
|
21
|
+
# Words in a name that mean "this is about a secret, not the secret itself".
|
|
22
|
+
NOT_SECRET_WORDS = {"file", "path", "dir", "folder", "mode", "max", "min", "limit", "count", "size",
|
|
23
|
+
"type", "name", "url", "enabled", "enable", "disable", "disabled", "id", "env", "var",
|
|
24
|
+
"length", "ttl", "timeout", "header", "prefix", "format", "location", "store", "helper"}
|
|
25
|
+
|
|
26
|
+
B = r"(?<![A-Za-z0-9_-])" # "starts here", so each pattern is tried once per word, not once per letter
|
|
27
|
+
SECRET_SHAPE = re.compile(
|
|
28
|
+
B + r"(?:sk-ant-[A-Za-z0-9_-]{16,}|sk-[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}"
|
|
29
|
+
r"|xox[abprs]-[A-Za-z0-9-]{10,}|AKIA[0-9A-Z]{16}|AIza[0-9A-Za-z_-]{30,}|glpat-[A-Za-z0-9_-]{16,}"
|
|
30
|
+
r"|(?:sk|rk|pk)_(?:live|test)_[A-Za-z0-9]{10,}|npm_[A-Za-z0-9]{30,}|hf_[A-Za-z0-9]{30,}"
|
|
31
|
+
r"|eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]*"
|
|
32
|
+
r"|hooks\.slack\.com/(?:services|workflows|triggers)/[A-Za-z0-9/_-]{10,}"
|
|
33
|
+
r"|discord(?:app)?\.com/api/webhooks/\d+/[A-Za-z0-9_-]{10,}"
|
|
34
|
+
r"|outlook\.office\.com/webhook/[A-Za-z0-9@/_-]{10,})")
|
|
35
|
+
BEARER = re.compile(r"(?i)" + B + r"(bearer|basic|token)\s+([A-Za-z0-9._~+/=-]{8,})")
|
|
36
|
+
KV = re.compile(r"(?i)" + B + r"((?:api[_-]?key|apikey|access[_-]?token|token|secret|passw(?:or)?d|pwd|pass|key|auth)"
|
|
37
|
+
r"\s*[=:]\s*[\"']?)([^\s&'\")]{4,})")
|
|
38
|
+
DSN = re.compile(r"(?<![A-Za-z0-9+.-])[A-Za-z][A-Za-z0-9+.-]*://[^\s/:@]+:([^\s/@]+)@")
|
|
39
|
+
EMAIL = re.compile(r"(?<![A-Za-z0-9._%+-])([A-Za-z0-9._%+-])[A-Za-z0-9._%+-]*@([A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+)")
|
|
40
|
+
USERINFO = re.compile(r"(://)[^/@\s]+@")
|
|
41
|
+
REFERENCE = re.compile(r"\$\{[^}]*\}|\$[A-Za-z_][A-Za-z0-9_]*")
|
|
42
|
+
OTHER_REF = re.compile(r"^(op|keychain|vault|secret|env)://|^keychain:", re.I)
|
|
43
|
+
TOKENISH = re.compile(r"(?<![A-Za-z0-9+/=_.-])[A-Za-z0-9+/=_.-]{16,}")
|
|
44
|
+
|
|
45
|
+
# Extra shapes that only appear in shell commands (allow rules are saved word for word).
|
|
46
|
+
RULE_SECRET = re.compile(
|
|
47
|
+
r"(?<![A-Za-z])(?i:password|passwd|pwd|secret|token|api[_-]?key|access[_-]?key)[\w-]{0,40}\s*[=:]\s*[\"']?[^\s\"')*]{4,}"
|
|
48
|
+
r"|(?<![A-Za-z-])--(?i:token|password|passwd|secret|api-?key|access-?token)[= ]+[\"']?[^\s\"')*-][^\s\"')*]{3,}"
|
|
49
|
+
r"|(?<!\S)-u\s+[^\s:]*[A-Za-z][^\s:]*:[^\s)]+" # curl -u user:pass (not -u 1000:1000)
|
|
50
|
+
r"|(?<!\S)-p(?=\S*[a-z])(?=\S*[A-Z0-9])[^\s)]{3,}" # mysql -pPASS (not -print, -pthread)
|
|
51
|
+
r"|sshpass\s+-p\s*\S+"
|
|
52
|
+
r"|(?<!\S)--pass(?:word)?[= ]\S+"
|
|
53
|
+
r"|(?i:(?<![A-Za-z0-9_])[a-z0-9]{1,30}_(?:secret|token|password|passwd|key)[a-z0-9_]{0,30})\s+[\"']?[^\s\"')*-][^\s\"')*]{7,}")
|
|
54
|
+
ARG_SPLIT = re.compile(r"[\s='\":,;()]+")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _words(name: str) -> list[str]:
|
|
58
|
+
name = re.sub(r"([a-z])([A-Z])", r"\1_\2", name[:200])
|
|
59
|
+
return [w for w in re.split(r"[^A-Za-z]+", name.lower()) if w]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _entropy(s: str) -> float:
|
|
63
|
+
n = len(s)
|
|
64
|
+
return -sum(c / n * math.log2(c / n) for c in (s.count(ch) for ch in set(s)))
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _kinds(p: str) -> int:
|
|
68
|
+
return sum(bool(re.search(x, p)) for x in (r"[a-z]", r"[A-Z]", r"\d"))
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _change_rate(p: str) -> float:
|
|
72
|
+
"""How often the character kind (lower/upper/digit) switches: high for random keys,
|
|
73
|
+
low for names like listRepositoryIssuesV2 or MyCoolApp2025Frontend."""
|
|
74
|
+
cls = ["d" if c.isdigit() else "u" if c.isupper() else "l" for c in p if c.isalnum()]
|
|
75
|
+
return sum(a != b for a, b in zip(cls, cls[1:])) / max(1, len(cls) - 1)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _random_piece(p: str) -> bool:
|
|
79
|
+
if len(p) < 16 or not p.isalnum() or not p.isascii():
|
|
80
|
+
return False
|
|
81
|
+
if re.fullmatch(r"[0-9a-f]+|[0-9A-F]+", p): # hex token (not a 40-char git SHA)
|
|
82
|
+
return len(p) >= 24 and len(p) != 40 and len(re.findall(r"\d", p)) >= 4 and len(re.findall(r"[a-fA-F]", p)) >= 4
|
|
83
|
+
if re.fullmatch(r"[A-Z2-7]+", p): # base32 (TOTP seeds)
|
|
84
|
+
return len(re.findall(r"[2-7]", p)) >= 2 and _change_rate(p) >= 0.15
|
|
85
|
+
return _kinds(p) == 3 and _change_rate(p) >= 0.45 and _entropy(p) >= 3.0
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def random_looking(s: str) -> bool:
|
|
89
|
+
"""A key, not a name: some piece between - _ . / is long and random-looking."""
|
|
90
|
+
core = s.strip("=~")
|
|
91
|
+
if len(core) < 16 or not re.fullmatch(r"[A-Za-z0-9+/_.-]+", core):
|
|
92
|
+
return False
|
|
93
|
+
return any(_random_piece(p) for p in re.split(r"[-_./+]", core)) # paths are fine: their pieces are words
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _base64_with_slashes(t: str) -> bool:
|
|
97
|
+
"""AWS-style secrets: base64 with '/', several random-looking pieces (a path has word-like pieces)."""
|
|
98
|
+
if len(t) < 30 or not re.fullmatch(r"[A-Za-z0-9+/]+={0,2}", t) or t.startswith("/") or "/" not in t:
|
|
99
|
+
return False
|
|
100
|
+
if _kinds(t) != 3:
|
|
101
|
+
return False
|
|
102
|
+
return sum(1 for p in t.split("/") if len(p) >= 6 and _change_rate(p) >= 0.4) >= 2
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _leet_password(t: str) -> bool:
|
|
106
|
+
"""S3cretPassw0rd: digits inside words, mixed case."""
|
|
107
|
+
return (8 <= len(t) <= 64 and t.isalnum() and _kinds(t) == 3
|
|
108
|
+
and len(re.findall(r"(?<=[A-Za-z])\d{1,2}(?=[A-Za-z])", t)) >= 2)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _is_path_or_number(v: str) -> bool:
|
|
112
|
+
return bool(re.fullmatch(r"[-+]?\d+(\.\d+)?", v)) or v.startswith(("/", "~/", "./", "../")) \
|
|
113
|
+
or bool(re.match(r"^[A-Za-z]:\\", v))
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def looks_secret(name, value) -> bool:
|
|
117
|
+
if not isinstance(value, str):
|
|
118
|
+
return False
|
|
119
|
+
v = value.strip()[:MAX_SCAN]
|
|
120
|
+
if not v or OTHER_REF.match(v):
|
|
121
|
+
return False
|
|
122
|
+
had_ref = bool(REFERENCE.search(v))
|
|
123
|
+
v2 = REFERENCE.sub("", v).strip()
|
|
124
|
+
if not v2:
|
|
125
|
+
return False
|
|
126
|
+
if DSN.search(v2) or SECRET_SHAPE.search(v2) or BEARER.search(v2) or KV.search(v2):
|
|
127
|
+
return True
|
|
128
|
+
if had_ref or _is_path_or_number(v2) or v2.lower() in ("true", "false", "none", "null", "yes", "no"):
|
|
129
|
+
return False
|
|
130
|
+
words = set(_words(name)) if isinstance(name, str) else set()
|
|
131
|
+
if words & SECRET_WORDS and not words & NOT_SECRET_WORDS and len(v2) >= 6:
|
|
132
|
+
return True
|
|
133
|
+
return random_looking(v2)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def rule_has_secret(rule: str) -> bool:
|
|
137
|
+
"""Shell commands saved as allow rules often contain passwords in many shapes."""
|
|
138
|
+
if not isinstance(rule, str):
|
|
139
|
+
return False
|
|
140
|
+
r = REFERENCE.sub("", rule[:MAX_SCAN])
|
|
141
|
+
if RULE_SECRET.search(r) or DSN.search(r) or SECRET_SHAPE.search(r) or BEARER.search(r):
|
|
142
|
+
return True
|
|
143
|
+
for url in re.findall(r"(?<![A-Za-z0-9])https?://[^\s'\")]{1,2000}", r):
|
|
144
|
+
if url_secrets(url):
|
|
145
|
+
return True
|
|
146
|
+
for tok in ARG_SPLIT.split(r):
|
|
147
|
+
tok = tok.strip("\\")
|
|
148
|
+
if not tok or tok.startswith("-"):
|
|
149
|
+
continue
|
|
150
|
+
if "://" in tok or tok.startswith("http"):
|
|
151
|
+
if url_secrets(tok if "://" in tok else "https://" + tok):
|
|
152
|
+
return True
|
|
153
|
+
continue
|
|
154
|
+
if random_looking(tok) or _base64_with_slashes(tok) or _leet_password(tok):
|
|
155
|
+
return True
|
|
156
|
+
if "/" in tok and not tok.startswith(("/", "./", "~")) and any(_random_piece(p) for p in tok.split("/")):
|
|
157
|
+
return True
|
|
158
|
+
return False
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def url_secrets(url: str) -> list[str]:
|
|
162
|
+
found = []
|
|
163
|
+
try:
|
|
164
|
+
parts = urlsplit(url[:MAX_SCAN])
|
|
165
|
+
password, username = parts.password, parts.username
|
|
166
|
+
except ValueError:
|
|
167
|
+
return ["url (could not be read)"]
|
|
168
|
+
if password or (username and "@" in parts.netloc):
|
|
169
|
+
found.append("url (user:password in the address)")
|
|
170
|
+
if re.search(r"(?i)(?:^|&)[^=&]{0,60}(key|token|secret|sig|auth|password)[^=&]{0,60}=[^&]{8,}", parts.query):
|
|
171
|
+
found.append("url (key in the query string)")
|
|
172
|
+
if SECRET_SHAPE.search(parts.path) or any(SECRET_SHAPE.search(seg) or random_looking(seg) or _random_piece(seg)
|
|
173
|
+
for seg in parts.path.split("/")):
|
|
174
|
+
found.append("url (key in the path)")
|
|
175
|
+
return found
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def find_in_server(cfg) -> list[str]:
|
|
179
|
+
"""Where in one MCP server config a plain-text secret sits, e.g. ['env.GITHUB_TOKEN'].
|
|
180
|
+
Only the location is returned, never the value."""
|
|
181
|
+
if not isinstance(cfg, dict):
|
|
182
|
+
return []
|
|
183
|
+
found = []
|
|
184
|
+
for section in ("env", "headers"):
|
|
185
|
+
block = cfg.get(section)
|
|
186
|
+
if isinstance(block, dict):
|
|
187
|
+
for k, v in block.items():
|
|
188
|
+
if looks_secret(k, v):
|
|
189
|
+
found.append(f"{section}.{redact(str(k), 60)}")
|
|
190
|
+
cmd = cfg.get("command")
|
|
191
|
+
if isinstance(cmd, str):
|
|
192
|
+
toks = cmd.split()
|
|
193
|
+
if (any(looks_secret("", t) for t in toks)
|
|
194
|
+
or any(a.startswith("-") and "=" in a and looks_secret(*a.split("=", 1)) for a in toks)
|
|
195
|
+
or any(a.startswith("-") and looks_secret(a, b) for a, b in zip(toks, toks[1:]))
|
|
196
|
+
or any("=" in t and looks_secret(*t.split("=", 1)) for t in toks)):
|
|
197
|
+
found.append("command")
|
|
198
|
+
args = cfg.get("args")
|
|
199
|
+
if isinstance(args, list):
|
|
200
|
+
for i, a in enumerate(args):
|
|
201
|
+
if not isinstance(a, str):
|
|
202
|
+
continue
|
|
203
|
+
prev = args[i - 1] if i and isinstance(args[i - 1], str) else ""
|
|
204
|
+
if a.startswith("-") and "=" in a:
|
|
205
|
+
k, _, v = a.partition("=")
|
|
206
|
+
if looks_secret(k, v):
|
|
207
|
+
found.append(f"args[{i}]")
|
|
208
|
+
continue
|
|
209
|
+
if a.startswith("-"):
|
|
210
|
+
continue
|
|
211
|
+
if looks_secret("", a) or (prev.startswith("-") and looks_secret(prev, a)):
|
|
212
|
+
found.append(f"args[{i}]")
|
|
213
|
+
url = cfg.get("url")
|
|
214
|
+
if isinstance(url, str):
|
|
215
|
+
found += url_secrets(url)
|
|
216
|
+
return found
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def redact(text, limit: int = MAX_SHOW) -> str:
|
|
220
|
+
"""Hide anything that looks like a secret or an email in a string we are about to show."""
|
|
221
|
+
if not isinstance(text, str):
|
|
222
|
+
text = "" if text is None else str(text)
|
|
223
|
+
if len(text) > limit:
|
|
224
|
+
text = text[:limit] + "…"
|
|
225
|
+
text = SECRET_SHAPE.sub(MASK, text)
|
|
226
|
+
text = DSN.sub(lambda m: m.group(0).replace(":" + m.group(1) + "@", ":" + MASK + "@"), text)
|
|
227
|
+
text = BEARER.sub(lambda m: m.group(1) + " " + MASK, text)
|
|
228
|
+
text = KV.sub(lambda m: m.group(1) + MASK, text)
|
|
229
|
+
text = USERINFO.sub(r"\1" + MASK + "@", text)
|
|
230
|
+
text = EMAIL.sub(lambda m: m.group(1) + MASK + "@" + m.group(2), text) # screenshots get shared
|
|
231
|
+
text = TOKENISH.sub(lambda m: MASK if random_looking(m.group(0)) else m.group(0), text)
|
|
232
|
+
return text
|
magen/risk.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"""Risk levels: what a tool or permission rule can do, in plain words."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
|
|
7
|
+
RED, YELLOW, GREEN, UNKNOWN = "red", "yellow", "green", "unknown"
|
|
8
|
+
ORDER = {RED: 3, UNKNOWN: 2, YELLOW: 1, GREEN: 0}
|
|
9
|
+
ICON = {RED: "[red] ", YELLOW: "[yellow]", GREEN: "[green] ", UNKNOWN: "[?] "}
|
|
10
|
+
|
|
11
|
+
# Verbs found in tool names. Checked red first, then yellow, then green.
|
|
12
|
+
RED_WORDS = {"send", "reply", "forward", "post", "publish", "share", "delete", "trash", "remove", "rm",
|
|
13
|
+
"destroy", "drop", "purge", "wipe", "erase", "overwrite", "truncate", "pay", "purchase", "charge",
|
|
14
|
+
"transfer", "refund", "submit", "approve", "execute", "exec", "run", "shell", "eval",
|
|
15
|
+
"evaluate", "deploy", "push", "merge", "invite", "kill", "terminate", "stop", "shutdown",
|
|
16
|
+
"revoke", "grant", "transact", "withdraw", "sendmail", "tweet", "broadcast", "upload"}
|
|
17
|
+
RED_PREFIXES = ("send", "delete", "remove", "publish", "execute", "terminate", "destroy", "erase", "wipe",
|
|
18
|
+
"purge", "transfer", "forward", "overwrite", "kill", "revoke")
|
|
19
|
+
YELLOW_WORDS = {"create", "update", "edit", "write", "add", "set", "move", "rename", "label", "modify",
|
|
20
|
+
"insert", "patch", "put", "apply", "mark", "save", "draft", "comment", "archive", "assign",
|
|
21
|
+
"close", "open", "enable", "disable", "batch", "replace", "change", "install", "configure",
|
|
22
|
+
"restore", "copy", "sync", "import", "schedule", "start", "restart", "unlabel"}
|
|
23
|
+
GREEN_WORDS = {"get", "list", "read", "search", "fetch", "query", "find", "view", "describe", "show",
|
|
24
|
+
"lookup", "check", "count", "download", "export", "guide", "status", "inspect", "browse"}
|
|
25
|
+
|
|
26
|
+
PLAIN = {RED: "can act for you outside: send, delete, pay or run things",
|
|
27
|
+
YELLOW: "can change things: create, edit, move",
|
|
28
|
+
GREEN: "can only look: read, list, search",
|
|
29
|
+
UNKNOWN: "not sure: Magen can't tell yet what it can do"}
|
|
30
|
+
|
|
31
|
+
# Claude Code built-in tools in permission rules.
|
|
32
|
+
BUILTIN = {"Read": GREEN, "Glob": GREEN, "Grep": GREEN, "LS": GREEN, "TodoWrite": GREEN,
|
|
33
|
+
"WebSearch": GREEN, "Edit": YELLOW, "MultiEdit": YELLOW, "Write": YELLOW,
|
|
34
|
+
"NotebookEdit": YELLOW, "WebFetch": YELLOW, "Bash": RED}
|
|
35
|
+
|
|
36
|
+
RISKY = {"rm", "curl", "wget", "ssh", "scp", "sftp", "rsync", "sudo", "su", "doas", "chmod", "chown",
|
|
37
|
+
"dd", "mkfs", "nc", "ncat", "telnet", "ftp", "kill", "killall", "pkill", "osascript", "open",
|
|
38
|
+
"launchctl", "crontab", "security", "mv", "truncate", "shred", "sshpass", "mysql", "psql",
|
|
39
|
+
"defaults", "networksetup", "diskutil", "tee", "cp", "ln"}
|
|
40
|
+
# Programs that can run any other command: allowing them is like allowing everything.
|
|
41
|
+
ANY_COMMAND = {"bash", "sh", "zsh", "fish", "dash", "ksh", "pwsh", "powershell", "cmd", "python", "node",
|
|
42
|
+
"deno", "bun", "bunx", "perl", "ruby", "php", "lua", "eval", "exec", "xargs", "env", "find",
|
|
43
|
+
"npx", "uvx", "pipx", "nohup", "watch", "make", "awk", "gawk", "sed", "docker", "podman",
|
|
44
|
+
"kubectl", "ssh-agent", "source", ".", "osascript", "script", "expect", "parallel"}
|
|
45
|
+
# Programs that are safe for some subcommands and dangerous for others: allowed bare = dangerous.
|
|
46
|
+
SUBCOMMANDS = {"git": {"push", "config", "clean", "reset", "rm", "filter-branch", "update-ref", "credential",
|
|
47
|
+
"submodule", "remote", "send-email", "daemon", "gc", "checkout", "restore", "stash"},
|
|
48
|
+
"npm": {"publish", "run", "exec", "install", "i", "ci", "uninstall", "unpublish", "x", "start", "test"},
|
|
49
|
+
"pnpm": {"publish", "run", "exec", "dlx", "install", "add"}, "yarn": {"publish", "run", "dlx", "add"},
|
|
50
|
+
"pip": {"install", "uninstall", "download"}, "uv": {"run", "pip", "tool", "add"},
|
|
51
|
+
"poetry": {"run", "publish", "add"}, "cargo": {"run", "publish", "install"},
|
|
52
|
+
"gh": {"api", "pr", "repo", "release", "secret", "auth", "workflow", "run", "gist"},
|
|
53
|
+
"aws": set(), "gcloud": set(), "az": set(), "terraform": {"apply", "destroy"},
|
|
54
|
+
"brew": {"install", "uninstall"}, "go": {"run", "install", "generate"},
|
|
55
|
+
"docker": set(), "kubectl": set(), "heroku": set(), "vercel": set(), "fly": set()}
|
|
56
|
+
WRAPPERS = {"command", "builtin", "nice", "ionice", "timeout", "stdbuf", "caffeinate", "time", "nohup",
|
|
57
|
+
"arch", "chroot", "flock", "unbuffer", "chrt", "taskset", "setsid", "doas", "sudo", "su"}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _words(name: str) -> list[str]:
|
|
61
|
+
# split snake_case, kebab-case and camelCase into lowercase words
|
|
62
|
+
name = re.sub(r"([a-z])([A-Z])", r"\1_\2", name[:300])
|
|
63
|
+
return [w for w in re.split(r"[^A-Za-z]+", name.lower()) if w]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def tool_level(tool: str) -> str:
|
|
67
|
+
"""Risk of one tool, from the verbs in its name."""
|
|
68
|
+
words = _words(tool) if isinstance(tool, str) else []
|
|
69
|
+
if any(w in RED_WORDS or w.startswith(RED_PREFIXES) for w in words):
|
|
70
|
+
return RED
|
|
71
|
+
if any(w in YELLOW_WORDS for w in words):
|
|
72
|
+
return YELLOW
|
|
73
|
+
if any(w in GREEN_WORDS for w in words):
|
|
74
|
+
return GREEN
|
|
75
|
+
return UNKNOWN
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def worst(levels) -> str:
|
|
79
|
+
levels = list(levels)
|
|
80
|
+
return max(levels, key=ORDER.get) if levels else UNKNOWN
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _program(words: list[str]) -> tuple[str, list[str]]:
|
|
84
|
+
"""Skip VAR=value prefixes and wrappers like `timeout 5`; return (program, rest)."""
|
|
85
|
+
i = 0
|
|
86
|
+
while i < len(words):
|
|
87
|
+
w = words[i].lstrip("\\").strip("'\"")
|
|
88
|
+
if re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*=.*", w):
|
|
89
|
+
i += 1
|
|
90
|
+
continue
|
|
91
|
+
name = w.rsplit("/", 1)[-1]
|
|
92
|
+
if name in WRAPPERS:
|
|
93
|
+
i += 1
|
|
94
|
+
while i < len(words) and (words[i].startswith("-") or re.fullmatch(r"[\d.]+[smhd]?", words[i])):
|
|
95
|
+
i += 1
|
|
96
|
+
continue
|
|
97
|
+
prog = re.sub(r"[\d.]+$", "", name) or name # python3.12 -> python, pip3 -> pip
|
|
98
|
+
return prog, words[i + 1:]
|
|
99
|
+
return "", []
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _bash(arg: str) -> tuple[str, str]:
|
|
103
|
+
cmd = re.sub(r":\*$", "", arg).strip()
|
|
104
|
+
if cmd in ("", "*", ":*"):
|
|
105
|
+
return RED, "allows ANY shell command without asking"
|
|
106
|
+
if any(c in cmd for c in (";", "&&", "||", "|", "`", "$(", ">", "<", "\n")):
|
|
107
|
+
return RED, "chains several commands or redirects output, so it allows more than it looks"
|
|
108
|
+
words = cmd.split()
|
|
109
|
+
prog, rest = _program(words)
|
|
110
|
+
if not prog:
|
|
111
|
+
return RED, "allows ANY shell command without asking"
|
|
112
|
+
if "*" in prog or "?" in prog:
|
|
113
|
+
return RED, "a wildcard as the program matches almost any command"
|
|
114
|
+
if prog in ANY_COMMAND:
|
|
115
|
+
return RED, f"'{prog}' can run any other command, so this allows almost anything"
|
|
116
|
+
if prog in RISKY:
|
|
117
|
+
return RED, f"allows '{prog}' without asking"
|
|
118
|
+
# When in doubt: a risky program anywhere in the command (after wrappers we don't fully parse)
|
|
119
|
+
names = {re.sub(r"[\d.]+$", "", w.lstrip("\\").strip("'\"").rsplit("/", 1)[-1]) for w in words}
|
|
120
|
+
hidden = sorted((names & (RISKY | ANY_COMMAND)) - {prog})
|
|
121
|
+
if hidden and prog not in SUBCOMMANDS:
|
|
122
|
+
return RED, f"'{hidden[0]}' appears in the command, so it may run without asking"
|
|
123
|
+
if prog in SUBCOMMANDS:
|
|
124
|
+
if not rest or rest[0] == "*":
|
|
125
|
+
return RED, f"allows every '{prog}' command, including risky ones"
|
|
126
|
+
if rest[0].startswith("-"):
|
|
127
|
+
return RED, f"options before the '{prog}' command can change what runs"
|
|
128
|
+
risky = SUBCOMMANDS[prog]
|
|
129
|
+
if not risky or rest[0] in risky:
|
|
130
|
+
return RED, f"allows '{prog} {rest[0]}' without asking"
|
|
131
|
+
return YELLOW, f"allows '{prog} {rest[0]}' without asking"
|
|
132
|
+
return YELLOW, f"allows the shell command '{prog}' without asking"
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def rule_level(rule: str) -> tuple[str, str]:
|
|
136
|
+
"""Risk of a Claude Code permission rule like 'Bash(git status:*)' or 'mcp__github'.
|
|
137
|
+
Returns (level, plain-language reason)."""
|
|
138
|
+
if not isinstance(rule, str):
|
|
139
|
+
return UNKNOWN, "unusual rule format"
|
|
140
|
+
m = re.fullmatch(r"([A-Za-z_][\w*-]*)(?:\((.*)\))?", rule.strip(), re.DOTALL)
|
|
141
|
+
if not m:
|
|
142
|
+
return UNKNOWN, "unusual rule format"
|
|
143
|
+
tool, arg = m.group(1), (m.group(2) or "").strip()
|
|
144
|
+
if tool.startswith("mcp__"):
|
|
145
|
+
parts = tool.split("__")
|
|
146
|
+
if len(parts) <= 2 or parts[-1] in ("", "*") or "*" in parts[-1]:
|
|
147
|
+
return RED, "allows every tool of this server, now and in the future"
|
|
148
|
+
lvl = tool_level(parts[-1])
|
|
149
|
+
return lvl, PLAIN[lvl]
|
|
150
|
+
if tool == "Bash":
|
|
151
|
+
return _bash(arg)
|
|
152
|
+
if tool in BUILTIN:
|
|
153
|
+
lvl = BUILTIN[tool]
|
|
154
|
+
if tool == "WebFetch":
|
|
155
|
+
return lvl, "can reach the internet (a possible way out for your data)"
|
|
156
|
+
return lvl, PLAIN[lvl]
|
|
157
|
+
return UNKNOWN, PLAIN[UNKNOWN]
|