otynx 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.
- otynx/__init__.py +4 -0
- otynx/__main__.py +6 -0
- otynx/agent_config.py +194 -0
- otynx/cli.py +72 -0
- otynx/detectors.py +241 -0
- otynx/finding.py +55 -0
- otynx/home.py +290 -0
- otynx/masking.py +36 -0
- otynx/report.py +96 -0
- otynx/rules.py +222 -0
- otynx/scanner.py +75 -0
- otynx/scoring.py +70 -0
- otynx/walker.py +110 -0
- otynx-0.1.0.dist-info/METADATA +119 -0
- otynx-0.1.0.dist-info/RECORD +19 -0
- otynx-0.1.0.dist-info/WHEEL +5 -0
- otynx-0.1.0.dist-info/entry_points.txt +2 -0
- otynx-0.1.0.dist-info/licenses/LICENSE +21 -0
- otynx-0.1.0.dist-info/top_level.txt +1 -0
otynx/__init__.py
ADDED
otynx/__main__.py
ADDED
otynx/agent_config.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
"""Check AI-agent settings files for secrets and loose permissions.
|
|
2
|
+
|
|
3
|
+
- MCP configs (.mcp.json, .cursor/mcp.json, .vscode/mcp.json): secrets
|
|
4
|
+
written straight into "env" or "headers" instead of loaded from the
|
|
5
|
+
environment.
|
|
6
|
+
- Claude Code settings (.claude/settings.json, .claude/settings.local.json):
|
|
7
|
+
all Bash commands allowed with no deny rules for destructive commands.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import re
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from otynx.detectors import (
|
|
15
|
+
context_clues,
|
|
16
|
+
find_line_number,
|
|
17
|
+
find_secrets_in_line,
|
|
18
|
+
fingerprint,
|
|
19
|
+
is_placeholder,
|
|
20
|
+
)
|
|
21
|
+
from otynx.finding import Finding
|
|
22
|
+
from otynx.masking import mask
|
|
23
|
+
|
|
24
|
+
MCP_FILES = (".mcp.json", ".cursor/mcp.json", ".vscode/mcp.json")
|
|
25
|
+
CLAUDE_SETTINGS_FILES = (".claude/settings.json", ".claude/settings.local.json")
|
|
26
|
+
|
|
27
|
+
MCP_FIX = (
|
|
28
|
+
'Load it from an environment variable instead, e.g. "${GITHUB_TOKEN}", '
|
|
29
|
+
"and keep the real value outside the project."
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
# Names that suggest a value is a secret.
|
|
33
|
+
SECRET_NAME = re.compile(r"(?i)secret|token|passw|pwd|api[_-]?key|access[_-]?key|private[_-]?key|auth|credential")
|
|
34
|
+
|
|
35
|
+
# Allow rules that mean "the agent may run ANY shell command".
|
|
36
|
+
BROAD_BASH_RULES = {"Bash", "Bash(*)", "Bash(**)", "Bash(:*)"}
|
|
37
|
+
|
|
38
|
+
# Deny rules that block at least one destructive command.
|
|
39
|
+
DESTRUCTIVE = re.compile(r"(?i)(?<![a-z])(?:rm|drop|delete|truncate|mkfs|dd)(?![a-z])|--force|reset --hard")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def check_agent_configs(root: Path) -> list[Finding]:
|
|
43
|
+
"""Run every agent-config check on the project folder `root`."""
|
|
44
|
+
findings = []
|
|
45
|
+
for name in MCP_FILES:
|
|
46
|
+
path = root / name
|
|
47
|
+
if path.is_file():
|
|
48
|
+
findings += check_mcp_file(path, name)
|
|
49
|
+
for name in CLAUDE_SETTINGS_FILES:
|
|
50
|
+
path = root / name
|
|
51
|
+
if path.is_file():
|
|
52
|
+
findings += check_claude_settings(path, name)
|
|
53
|
+
return findings
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def load_json(path: Path) -> tuple[object, str]:
|
|
57
|
+
"""Return (parsed JSON or None, raw text). Broken JSON gives None."""
|
|
58
|
+
try:
|
|
59
|
+
text = path.read_text(encoding="utf-8", errors="replace")
|
|
60
|
+
except OSError:
|
|
61
|
+
return None, ""
|
|
62
|
+
try:
|
|
63
|
+
return json.loads(text), text
|
|
64
|
+
except ValueError:
|
|
65
|
+
return None, text
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def is_reference(value: str) -> bool:
|
|
69
|
+
"""True when a value points to the environment instead of holding a secret.
|
|
70
|
+
|
|
71
|
+
e.g. "${GITHUB_TOKEN}", "${env:GITHUB_TOKEN}", "$TOKEN", or "".
|
|
72
|
+
"""
|
|
73
|
+
value = value.strip()
|
|
74
|
+
return value == "" or value.startswith(("$", "{{", "%")) or value.lower().startswith("env:")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
# ---------- MCP configs ----------
|
|
78
|
+
|
|
79
|
+
def check_mcp_file(path: Path, display: str) -> list[Finding]:
|
|
80
|
+
"""Find secrets written directly into an MCP config."""
|
|
81
|
+
data, text = load_json(path)
|
|
82
|
+
if not isinstance(data, dict):
|
|
83
|
+
return []
|
|
84
|
+
|
|
85
|
+
# Claude Code and Cursor use "mcpServers"; VS Code uses "servers".
|
|
86
|
+
servers = data.get("mcpServers") or data.get("servers") or {}
|
|
87
|
+
if not isinstance(servers, dict):
|
|
88
|
+
return []
|
|
89
|
+
|
|
90
|
+
findings = []
|
|
91
|
+
for server_name, server in servers.items():
|
|
92
|
+
if not isinstance(server, dict):
|
|
93
|
+
continue
|
|
94
|
+
for section in ("env", "headers"):
|
|
95
|
+
values = server.get(section)
|
|
96
|
+
if not isinstance(values, dict):
|
|
97
|
+
continue
|
|
98
|
+
for key, value in values.items():
|
|
99
|
+
if isinstance(value, str) and not is_reference(value):
|
|
100
|
+
findings += _secrets_in_mcp_value(key, value, str(server_name), display, text)
|
|
101
|
+
return findings
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _secrets_in_mcp_value(key: str, value: str, server: str, display: str, text: str) -> list[Finding]:
|
|
105
|
+
line_number = find_line_number(text, value)
|
|
106
|
+
live, safe = context_clues(f"{key} {server} {display}")
|
|
107
|
+
common = dict(
|
|
108
|
+
file_path=display,
|
|
109
|
+
line_number=line_number,
|
|
110
|
+
fix=MCP_FIX,
|
|
111
|
+
looks_live=live,
|
|
112
|
+
looks_safe=safe,
|
|
113
|
+
in_project=True,
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
# 1. A value with a known shape (GitHub token, Stripe key, ...).
|
|
117
|
+
matches = find_secrets_in_line(value, skip_generic=True)
|
|
118
|
+
if matches:
|
|
119
|
+
return [
|
|
120
|
+
Finding(
|
|
121
|
+
rule_id=m.rule.id,
|
|
122
|
+
title=f"{m.rule.title} written inside MCP config",
|
|
123
|
+
masked_value=m.shown,
|
|
124
|
+
what_it_can_do=m.rule.what_it_can_do,
|
|
125
|
+
base_points=m.rule.base_points,
|
|
126
|
+
fingerprint=fingerprint(m.secret) if m.rule.has_secret_value else "",
|
|
127
|
+
**common,
|
|
128
|
+
)
|
|
129
|
+
for m in matches
|
|
130
|
+
]
|
|
131
|
+
|
|
132
|
+
# 2. Unknown shape, but the name says it's a secret.
|
|
133
|
+
if SECRET_NAME.search(key) and len(value) >= 8 and not is_placeholder(value):
|
|
134
|
+
return [
|
|
135
|
+
Finding(
|
|
136
|
+
rule_id="mcp-secret",
|
|
137
|
+
title=f"Secret written inside MCP config ({key})",
|
|
138
|
+
masked_value=mask(value),
|
|
139
|
+
what_it_can_do=f"Unknown: anything the '{server}' MCP server can do with it.",
|
|
140
|
+
base_points=10,
|
|
141
|
+
fingerprint=fingerprint(value),
|
|
142
|
+
**common,
|
|
143
|
+
)
|
|
144
|
+
]
|
|
145
|
+
return []
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
# ---------- Claude Code settings ----------
|
|
149
|
+
|
|
150
|
+
def check_claude_settings(path: Path, display: str) -> list[Finding]:
|
|
151
|
+
"""Flag very loose permissions in .claude/settings*.json."""
|
|
152
|
+
data, text = load_json(path)
|
|
153
|
+
if not isinstance(data, dict):
|
|
154
|
+
return []
|
|
155
|
+
|
|
156
|
+
permissions = data.get("permissions")
|
|
157
|
+
if not isinstance(permissions, dict):
|
|
158
|
+
permissions = {}
|
|
159
|
+
allow = [rule for rule in permissions.get("allow") or [] if isinstance(rule, str)]
|
|
160
|
+
deny = [rule for rule in permissions.get("deny") or [] if isinstance(rule, str)]
|
|
161
|
+
|
|
162
|
+
findings = []
|
|
163
|
+
|
|
164
|
+
broad = [rule for rule in allow if rule.replace(" ", "") in BROAD_BASH_RULES]
|
|
165
|
+
has_destructive_deny = any(rule.startswith("Bash") and DESTRUCTIVE.search(rule) for rule in deny)
|
|
166
|
+
if broad and not has_destructive_deny:
|
|
167
|
+
findings.append(
|
|
168
|
+
Finding(
|
|
169
|
+
rule_id="agent-loose-bash",
|
|
170
|
+
title="Bash commands allowed with no deny rules",
|
|
171
|
+
file_path=display,
|
|
172
|
+
line_number=find_line_number(text, f'"{broad[0]}"'),
|
|
173
|
+
masked_value=f'allow: "{broad[0]}"',
|
|
174
|
+
what_it_can_do="The agent can run rm -rf, DROP TABLE, etc. without asking.",
|
|
175
|
+
fix='Add deny rules for destructive commands, e.g. "Bash(rm:*)", "Bash(git push --force:*)".',
|
|
176
|
+
is_permission=True,
|
|
177
|
+
)
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
if permissions.get("defaultMode") == "bypassPermissions":
|
|
181
|
+
findings.append(
|
|
182
|
+
Finding(
|
|
183
|
+
rule_id="agent-bypass-permissions",
|
|
184
|
+
title="Permission prompts are turned off (bypassPermissions)",
|
|
185
|
+
file_path=display,
|
|
186
|
+
line_number=find_line_number(text, "bypassPermissions"),
|
|
187
|
+
masked_value='defaultMode: "bypassPermissions"',
|
|
188
|
+
what_it_can_do="The agent can run any command and edit any file without asking.",
|
|
189
|
+
fix="Remove bypassPermissions and allow only the commands you need.",
|
|
190
|
+
is_permission=True,
|
|
191
|
+
)
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
return findings
|
otynx/cli.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""The `otynx scan` command.
|
|
2
|
+
|
|
3
|
+
typer turns the scan() function below into a command: its parameters
|
|
4
|
+
become the command's options, and its docstring becomes the --help text.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Annotated
|
|
10
|
+
|
|
11
|
+
import typer
|
|
12
|
+
|
|
13
|
+
from otynx.report import print_report, safe, to_json
|
|
14
|
+
from otynx.scanner import run_scan
|
|
15
|
+
|
|
16
|
+
app = typer.Typer(
|
|
17
|
+
add_completion=False,
|
|
18
|
+
no_args_is_help=True,
|
|
19
|
+
help="Otynx: see which secrets your AI agent could reach.",
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@app.callback()
|
|
24
|
+
def main() -> None:
|
|
25
|
+
"""Sniff out the keys your AI agent could grab."""
|
|
26
|
+
# Having this callback makes `scan` a sub-command: `otynx scan .`
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@app.command()
|
|
30
|
+
def scan(
|
|
31
|
+
# Annotated[type, extra info] lets typer know how to treat each parameter.
|
|
32
|
+
folder: Annotated[
|
|
33
|
+
Path,
|
|
34
|
+
typer.Argument(help="The project folder to scan.", exists=True, file_okay=False, dir_okay=True),
|
|
35
|
+
] = Path("."),
|
|
36
|
+
home: Annotated[
|
|
37
|
+
bool,
|
|
38
|
+
typer.Option("--home", help="Also check credential files in your home folder (~/.aws, ~/.kube, ...)."),
|
|
39
|
+
] = False,
|
|
40
|
+
json_output: Annotated[
|
|
41
|
+
bool,
|
|
42
|
+
typer.Option("--json", help="Print the results as JSON instead of a coloured report."),
|
|
43
|
+
] = False,
|
|
44
|
+
list_files: Annotated[
|
|
45
|
+
bool,
|
|
46
|
+
typer.Option("--list-files", help="Also print every file that was scanned."),
|
|
47
|
+
] = False,
|
|
48
|
+
) -> None:
|
|
49
|
+
"""Scan FOLDER for secrets and risky AI-agent settings. Read-only and offline."""
|
|
50
|
+
_make_output_safe()
|
|
51
|
+
result = run_scan(folder, include_home=home)
|
|
52
|
+
|
|
53
|
+
if json_output:
|
|
54
|
+
typer.echo(to_json(result))
|
|
55
|
+
else:
|
|
56
|
+
if list_files:
|
|
57
|
+
for path in result.scanned_paths:
|
|
58
|
+
typer.echo(safe(path)) # file names can hold terminal control codes
|
|
59
|
+
typer.echo()
|
|
60
|
+
print_report(result)
|
|
61
|
+
|
|
62
|
+
# Exit code 1 = something CRITICAL was found (useful in CI and hooks).
|
|
63
|
+
raise typer.Exit(code=result.exit_code)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _make_output_safe() -> None:
|
|
67
|
+
"""Some Windows terminals can't show symbols like '→'. Show '?' instead of crashing."""
|
|
68
|
+
for stream in (sys.stdout, sys.stderr):
|
|
69
|
+
try:
|
|
70
|
+
stream.reconfigure(errors="replace")
|
|
71
|
+
except (AttributeError, ValueError):
|
|
72
|
+
pass
|
otynx/detectors.py
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
"""Look inside text for secrets, using the rules from rules.py.
|
|
2
|
+
|
|
3
|
+
This is step 2 of the assembly line:
|
|
4
|
+
walker.py -> detectors.py -> scoring.py -> report.py
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import bisect
|
|
8
|
+
import hashlib
|
|
9
|
+
import math
|
|
10
|
+
import re
|
|
11
|
+
from collections import Counter
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from otynx.finding import Finding
|
|
16
|
+
from otynx.masking import mask
|
|
17
|
+
from otynx.rules import PLACEHOLDER_VALUES, PLACEHOLDER_WORDS, RULES, Rule
|
|
18
|
+
|
|
19
|
+
# Words near a secret that hint it's real ("live") or harmless ("safe").
|
|
20
|
+
# (?<![a-z]) and (?![a-z]) stop "prod" matching inside "product".
|
|
21
|
+
LIVE_CLUES = re.compile(r"(?<![a-z])(?:prod|production|live)(?![a-z])", re.IGNORECASE)
|
|
22
|
+
SAFE_CLUES = re.compile(
|
|
23
|
+
r"(?<![a-z])(?:localhost|127\.0\.0\.1|test|tests|testing|dev|development|sandbox)(?![a-z])",
|
|
24
|
+
re.IGNORECASE,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
# Files like ".env.example" are templates, not real config.
|
|
28
|
+
EXAMPLE_ENDINGS = (".example", ".sample", ".template", ".dist")
|
|
29
|
+
|
|
30
|
+
# Documentation is full of sample values like SECRET_KEY = "192b9bdd...",
|
|
31
|
+
# so in docs we only report keys with a known shape (AWS, GitHub, ...).
|
|
32
|
+
DOC_ENDINGS = (".md", ".mdx", ".rst", ".adoc")
|
|
33
|
+
|
|
34
|
+
# ...except instruction files that AI agents read every session.
|
|
35
|
+
AGENT_INSTRUCTION_FILES = {"claude.md", "agents.md", "gemini.md", "copilot-instructions.md"}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass
|
|
39
|
+
class SecretMatch:
|
|
40
|
+
"""One secret found in one line (before it becomes a Finding)."""
|
|
41
|
+
rule: Rule
|
|
42
|
+
secret: str # the real value - stays in memory only, never shown
|
|
43
|
+
start: int # where it starts in the line
|
|
44
|
+
end: int # where it ends in the line
|
|
45
|
+
shown: str # the masked text that is safe to show
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
# ---------- small helpers ----------
|
|
49
|
+
|
|
50
|
+
def shannon_entropy(text: str) -> float:
|
|
51
|
+
"""How random a string looks, in bits per character.
|
|
52
|
+
|
|
53
|
+
"aaaaaaaa" -> 0.0 (not random at all). A real key like "q8Zr2Lm9..."
|
|
54
|
+
scores about 4. The formula adds up -p * log2(p) for every character,
|
|
55
|
+
where p is how often that character appears.
|
|
56
|
+
"""
|
|
57
|
+
if not text:
|
|
58
|
+
return 0.0
|
|
59
|
+
counts = Counter(text) # e.g. Counter("aab") -> {"a": 2, "b": 1}
|
|
60
|
+
total = len(text)
|
|
61
|
+
return -sum((n / total) * math.log2(n / total) for n in counts.values())
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def looks_random(value: str, min_entropy: float) -> bool:
|
|
65
|
+
"""Real secrets mix letters and digits and look random."""
|
|
66
|
+
has_digit = any(char.isdigit() for char in value)
|
|
67
|
+
has_letter = any(char.isalpha() for char in value)
|
|
68
|
+
return has_digit and has_letter and shannon_entropy(value) >= min_entropy
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def is_placeholder(value: str) -> bool:
|
|
72
|
+
"""True for fake values like 'your-key-here', 'xxxx' or '<API_KEY>'."""
|
|
73
|
+
lowered = value.lower()
|
|
74
|
+
if lowered in PLACEHOLDER_VALUES:
|
|
75
|
+
return True
|
|
76
|
+
# A template like "{DB_PASSWORD}" (Python f-strings, .format(), ...).
|
|
77
|
+
if lowered.startswith("{") and lowered.endswith("}"):
|
|
78
|
+
return True
|
|
79
|
+
return any(word in lowered for word in PLACEHOLDER_WORDS)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def fingerprint(secret: str) -> str:
|
|
83
|
+
"""A one-way hash of the secret, used only to spot the same secret twice.
|
|
84
|
+
|
|
85
|
+
You can't turn a hash back into the secret, so it's safe to keep.
|
|
86
|
+
"""
|
|
87
|
+
return hashlib.sha256(secret.encode("utf-8")).hexdigest()[:16]
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def context_clues(text: str) -> tuple[bool, bool]:
|
|
91
|
+
"""Return (looks_live, looks_safe) for some text near a secret."""
|
|
92
|
+
return bool(LIVE_CLUES.search(text)), bool(SAFE_CLUES.search(text))
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def find_line_number(text: str, needle: str) -> int | None:
|
|
96
|
+
"""The first line (counting from 1) that contains `needle`."""
|
|
97
|
+
for number, line in enumerate(text.splitlines(), start=1):
|
|
98
|
+
if needle in line:
|
|
99
|
+
return number
|
|
100
|
+
return None
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def is_example_file(path: Path) -> bool:
|
|
104
|
+
"""True for templates like '.env.example' or 'config.sample.json'."""
|
|
105
|
+
name = path.name.lower()
|
|
106
|
+
return name.endswith(EXAMPLE_ENDINGS) or ".example." in name or ".sample." in name
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def is_docs_file(path: Path) -> bool:
|
|
110
|
+
"""True for documentation like README.md, but not CLAUDE.md or AGENTS.md."""
|
|
111
|
+
name = path.name.lower()
|
|
112
|
+
return name.endswith(DOC_ENDINGS) and name not in AGENT_INSTRUCTION_FILES
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def is_auto_loaded(path: Path) -> bool:
|
|
116
|
+
"""Frameworks load '.env' (and '.env.local', ...) automatically on start."""
|
|
117
|
+
name = path.name.lower()
|
|
118
|
+
return (name == ".env" or name.startswith(".env.")) and not is_example_file(path)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
# ---------- finding secrets ----------
|
|
122
|
+
|
|
123
|
+
def _secret_part(rule: Rule, match: re.Match) -> tuple[str, int, int]:
|
|
124
|
+
"""Which part of the match is the secret: the named group, or all of it."""
|
|
125
|
+
if "secret" in rule.pattern.groupindex and match.group("secret") is not None:
|
|
126
|
+
return match.group("secret"), match.start("secret"), match.end("secret")
|
|
127
|
+
return match.group(0), match.start(), match.end()
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _shown(rule: Rule, match: re.Match, secret: str, start: int, end: int) -> str:
|
|
131
|
+
"""The text we're allowed to show for this match (always masked)."""
|
|
132
|
+
if rule.show == "match":
|
|
133
|
+
whole = match.group(0)
|
|
134
|
+
if not rule.has_secret_value:
|
|
135
|
+
return whole # e.g. a private-key header line
|
|
136
|
+
before = whole[: start - match.start()]
|
|
137
|
+
after = whole[end - match.start():]
|
|
138
|
+
return before + mask(secret) + after
|
|
139
|
+
return mask(secret)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def find_secrets(text: str, skip_generic: bool = False) -> list[SecretMatch]:
|
|
143
|
+
"""Run every rule over some text and return what they find, in order.
|
|
144
|
+
|
|
145
|
+
Each rule searches the WHOLE text in one go. (Checking line by line
|
|
146
|
+
was about 10x slower: millions of tiny searches instead of a few big ones.)
|
|
147
|
+
"""
|
|
148
|
+
found: list[SecretMatch] = []
|
|
149
|
+
taken: list[tuple[int, int]] = [] # parts of the text already claimed
|
|
150
|
+
lowered = text.lower() # for the quick keyword pre-check
|
|
151
|
+
|
|
152
|
+
for rule in RULES:
|
|
153
|
+
if skip_generic and rule.id == "generic-secret":
|
|
154
|
+
continue
|
|
155
|
+
# Quick pre-check: skip the slow regex if none of its words are here.
|
|
156
|
+
if rule.keywords and not any(word in lowered for word in rule.keywords):
|
|
157
|
+
continue
|
|
158
|
+
for match in rule.pattern.finditer(text):
|
|
159
|
+
secret, start, end = _secret_part(rule, match)
|
|
160
|
+
|
|
161
|
+
if rule.has_secret_value and is_placeholder(secret):
|
|
162
|
+
continue
|
|
163
|
+
if rule.min_entropy is not None and not looks_random(secret, rule.min_entropy):
|
|
164
|
+
continue
|
|
165
|
+
# A more specific rule (earlier in RULES) already found this spot.
|
|
166
|
+
if any(start < taken_end and taken_start < end for taken_start, taken_end in taken):
|
|
167
|
+
continue
|
|
168
|
+
|
|
169
|
+
taken.append((start, end))
|
|
170
|
+
found.append(SecretMatch(rule, secret, start, end, _shown(rule, match, secret, start, end)))
|
|
171
|
+
|
|
172
|
+
found.sort(key=lambda match: match.start)
|
|
173
|
+
return found
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def find_secrets_in_line(line: str, skip_generic: bool = False) -> list[SecretMatch]:
|
|
177
|
+
"""Same as find_secrets(), for a single line or value."""
|
|
178
|
+
return find_secrets(line, skip_generic=skip_generic)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def scan_text(
|
|
182
|
+
text: str,
|
|
183
|
+
display_path: str,
|
|
184
|
+
*,
|
|
185
|
+
in_project: bool = True,
|
|
186
|
+
auto_loaded: bool = False,
|
|
187
|
+
skip_generic: bool = False,
|
|
188
|
+
) -> list[Finding]:
|
|
189
|
+
"""Find secrets in some text and turn them into Findings."""
|
|
190
|
+
path_live, path_safe = context_clues(display_path)
|
|
191
|
+
|
|
192
|
+
# Where each line starts, so we can turn a position into a line number.
|
|
193
|
+
line_starts = [0] + [newline.end() for newline in re.finditer("\n", text)]
|
|
194
|
+
|
|
195
|
+
findings = []
|
|
196
|
+
for match in find_secrets(text, skip_generic=skip_generic):
|
|
197
|
+
# bisect finds which line the match is on (counting lines from 1).
|
|
198
|
+
number = bisect.bisect_right(line_starts, match.start)
|
|
199
|
+
line_start = line_starts[number - 1]
|
|
200
|
+
line_end = line_starts[number] - 1 if number < len(line_starts) else len(text)
|
|
201
|
+
|
|
202
|
+
# Look for clues on the same line, but NOT inside the secret itself.
|
|
203
|
+
nearby = text[line_start: match.start] + text[match.end: line_end]
|
|
204
|
+
live, safe = context_clues(nearby)
|
|
205
|
+
rule = match.rule
|
|
206
|
+
findings.append(
|
|
207
|
+
Finding(
|
|
208
|
+
rule_id=rule.id,
|
|
209
|
+
title=rule.title,
|
|
210
|
+
file_path=display_path,
|
|
211
|
+
line_number=number,
|
|
212
|
+
masked_value=match.shown,
|
|
213
|
+
what_it_can_do=rule.what_it_can_do,
|
|
214
|
+
fix=rule.fix,
|
|
215
|
+
base_points=rule.base_points,
|
|
216
|
+
looks_live=live or path_live,
|
|
217
|
+
looks_safe=safe or path_safe,
|
|
218
|
+
in_project=in_project,
|
|
219
|
+
auto_loaded=auto_loaded,
|
|
220
|
+
fingerprint=fingerprint(match.secret) if rule.has_secret_value else "",
|
|
221
|
+
)
|
|
222
|
+
)
|
|
223
|
+
return findings
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def scan_file(path: Path, root: Path) -> list[Finding]:
|
|
227
|
+
"""Read one project file and find the secrets in it."""
|
|
228
|
+
try:
|
|
229
|
+
# errors="replace" turns unreadable bytes into "?" instead of crashing.
|
|
230
|
+
text = path.read_text(encoding="utf-8", errors="replace")
|
|
231
|
+
except OSError:
|
|
232
|
+
return []
|
|
233
|
+
return scan_text(
|
|
234
|
+
text,
|
|
235
|
+
path.relative_to(root).as_posix(),
|
|
236
|
+
in_project=True,
|
|
237
|
+
auto_loaded=is_auto_loaded(path),
|
|
238
|
+
# Templates (.env.example) and docs (README.md): only report keys
|
|
239
|
+
# with a known shape, not "possible secrets".
|
|
240
|
+
skip_generic=is_example_file(path) or is_docs_file(path),
|
|
241
|
+
)
|
otynx/finding.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""The Finding: one thing Otynx found that an AI agent could misuse.
|
|
2
|
+
|
|
3
|
+
Every check in Otynx returns Findings. Everything else just builds,
|
|
4
|
+
scores or prints them.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
# @dataclass writes the boring parts of a class for us (like __init__),
|
|
11
|
+
# so we only list the fields and their types.
|
|
12
|
+
@dataclass
|
|
13
|
+
class Finding:
|
|
14
|
+
# --- What was found ---
|
|
15
|
+
rule_id: str # which rule found it, e.g. "aws-key"
|
|
16
|
+
title: str # short description, e.g. "AWS access key"
|
|
17
|
+
file_path: str # where, as shown to the user, e.g. ".env"
|
|
18
|
+
line_number: int | None # None when there's no single line (a key file)
|
|
19
|
+
masked_value: str # e.g. "AKIA****ABCD" - NEVER the full secret
|
|
20
|
+
what_it_can_do: str # the damage an agent could do with it
|
|
21
|
+
fix: str # how to fix it
|
|
22
|
+
|
|
23
|
+
# --- Clues used for scoring (see scoring.py) ---
|
|
24
|
+
base_points: int = 10
|
|
25
|
+
looks_live: bool = False # "prod", "production", "live" nearby
|
|
26
|
+
looks_safe: bool = False # "localhost", "test", "dev", "sandbox" nearby
|
|
27
|
+
in_project: bool = True # inside the project folder (not ~/...)
|
|
28
|
+
auto_loaded: bool = False # tools pick it up automatically (.env, default profile)
|
|
29
|
+
is_permission: bool = False # a loose agent setting, not a secret
|
|
30
|
+
fingerprint: str = "" # a one-way hash of the secret, to spot copies
|
|
31
|
+
|
|
32
|
+
# --- Filled in later by scoring.py ---
|
|
33
|
+
points: int = 0
|
|
34
|
+
level: str = ""
|
|
35
|
+
|
|
36
|
+
@property
|
|
37
|
+
def location(self) -> str:
|
|
38
|
+
"""'file:line', or just 'file' when there's no line number."""
|
|
39
|
+
if self.line_number is None:
|
|
40
|
+
return self.file_path
|
|
41
|
+
return f"{self.file_path}:{self.line_number}"
|
|
42
|
+
|
|
43
|
+
def to_dict(self) -> dict:
|
|
44
|
+
"""The fields we show in --json output (no fingerprint, no clues)."""
|
|
45
|
+
return {
|
|
46
|
+
"rule_id": self.rule_id,
|
|
47
|
+
"title": self.title,
|
|
48
|
+
"level": self.level,
|
|
49
|
+
"points": self.points,
|
|
50
|
+
"file_path": self.file_path,
|
|
51
|
+
"line_number": self.line_number,
|
|
52
|
+
"masked_value": self.masked_value,
|
|
53
|
+
"what_it_can_do": self.what_it_can_do,
|
|
54
|
+
"fix": self.fix,
|
|
55
|
+
}
|