attackmap-analyzer-go 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.
Potentially problematic release.
This version of attackmap-analyzer-go might be problematic. Click here for more details.
- attackmap_analyzer_go/__init__.py +3 -0
- attackmap_analyzer_go/analyzer.py +475 -0
- attackmap_analyzer_go/contracts.py +31 -0
- attackmap_analyzer_go-0.1.0.dist-info/METADATA +91 -0
- attackmap_analyzer_go-0.1.0.dist-info/RECORD +9 -0
- attackmap_analyzer_go-0.1.0.dist-info/WHEEL +5 -0
- attackmap_analyzer_go-0.1.0.dist-info/entry_points.txt +2 -0
- attackmap_analyzer_go-0.1.0.dist-info/licenses/LICENSE +21 -0
- attackmap_analyzer_go-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,475 @@
|
|
|
1
|
+
"""Go ecosystem analyzer for AttackMap.
|
|
2
|
+
|
|
3
|
+
Coverage (v0.1):
|
|
4
|
+
- Web frameworks: net/http (stdlib), chi, gin, echo, fiber, gorilla/mux
|
|
5
|
+
- Databases: database/sql, gorm, sqlx, pgx, mongo-go-driver, go-redis, bbolt
|
|
6
|
+
- Auth packages: golang-jwt/jwt, golang.org/x/oauth2, gorilla/sessions, casbin,
|
|
7
|
+
golang.org/x/crypto/bcrypt and friends, x/crypto/scrypt, x/crypto/argon2
|
|
8
|
+
- HTTP clients (external calls): net/http (http.Get/Post), go-resty
|
|
9
|
+
- Secrets: os.Getenv, godotenv (joho/godotenv), viper.GetString
|
|
10
|
+
- Entrypoints: http.ListenAndServe, gin.Run, echo.Start, fiber.Listen
|
|
11
|
+
- Service hints: module name from go.mod
|
|
12
|
+
|
|
13
|
+
Emits Signal v2 fields (line numbers + evidence snippets + confidence) so
|
|
14
|
+
downstream insights can cite `path/to/file.go:NN`.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import re
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
|
|
22
|
+
from .contracts import (
|
|
23
|
+
AnalyzerMetadata,
|
|
24
|
+
AuthHint,
|
|
25
|
+
DatabaseHint,
|
|
26
|
+
EntrypointHint,
|
|
27
|
+
ExternalCall,
|
|
28
|
+
FrameworkHint,
|
|
29
|
+
Route,
|
|
30
|
+
ScanResult,
|
|
31
|
+
SecretHint,
|
|
32
|
+
ServiceHint,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
CODE_SUFFIXES = {".go"}
|
|
36
|
+
SKIP_DIRS = {"vendor", ".git", "node_modules", "dist", "build"}
|
|
37
|
+
SKIP_SUFFIXES = {"_test.go"} # Go test files — keep as low-quality input
|
|
38
|
+
_SNIPPET_MAX_CHARS = 160
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
# ---------- Patterns ----------
|
|
42
|
+
|
|
43
|
+
# Gin: r.GET("/path", h), r.POST("/path", h), r.Group("/api")
|
|
44
|
+
# Method must be uppercase verb (Gin convention).
|
|
45
|
+
GIN_ROUTE_PATTERN = re.compile(
|
|
46
|
+
r'\b(\w+)\.(GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS)\(\s*"([^"]+)"',
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
# Chi: r.Get("/path", h), r.Post("/path", h)
|
|
50
|
+
# Title-case method (Chi convention). Same shape as Echo.
|
|
51
|
+
CHI_ECHO_ROUTE_PATTERN = re.compile(
|
|
52
|
+
r'\b(\w+)\.(Get|Post|Put|Delete|Patch|Head|Options)\(\s*"([^"]+)"',
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
# Fiber: app.Get("/path", h)
|
|
56
|
+
# Same shape as chi/echo title-case but framework is detected by app.* + fiber import.
|
|
57
|
+
|
|
58
|
+
# Gorilla/mux: r.HandleFunc("/path", h).Methods("GET", "POST")
|
|
59
|
+
GORILLA_HANDLEFUNC_PATTERN = re.compile(
|
|
60
|
+
r'\.HandleFunc\(\s*"([^"]+)"\s*,\s*\w+(?:\.\w+)*\s*\)(?P<chain>(?:\s*\.\s*\w+\([^)]*\))*)',
|
|
61
|
+
)
|
|
62
|
+
GORILLA_METHODS_PATTERN = re.compile(
|
|
63
|
+
r'\.Methods\(\s*((?:"[A-Z]+"(?:\s*,\s*)?)+)\s*\)',
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
# net/http stdlib: http.HandleFunc("/path", h) or mux.HandleFunc("/path", h)
|
|
67
|
+
NET_HTTP_HANDLEFUNC_PATTERN = re.compile(
|
|
68
|
+
r'\b(?:http|\w+)\.HandleFunc\(\s*"([^"]+)"\s*,',
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
# External HTTP calls
|
|
72
|
+
OUTBOUND_PATTERNS: list[re.Pattern[str]] = [
|
|
73
|
+
re.compile(r'\bhttp\.(?:Get|Post|Head)\(\s*"(https?://[^"]+)"'),
|
|
74
|
+
re.compile(r'\bhttp\.NewRequest\(\s*"[A-Z]+"\s*,\s*"(https?://[^"]+)"'),
|
|
75
|
+
re.compile(r'\bresty\.New\(\)\.\w+\(\)\.\w+\(\s*"(https?://[^"]+)"'),
|
|
76
|
+
re.compile(r'\bgrequests\.\w+\(\s*"(https?://[^"]+)"'),
|
|
77
|
+
re.compile(r'\bclient\.\w+\(\s*ctx\s*,\s*"(https?://[^"]+)"', re.IGNORECASE),
|
|
78
|
+
]
|
|
79
|
+
|
|
80
|
+
# Database libs
|
|
81
|
+
DB_PATTERNS: list[tuple[re.Pattern[str], str]] = [
|
|
82
|
+
(re.compile(r'\bsql\.Open\(\s*"postgres"'), "postgresql"),
|
|
83
|
+
(re.compile(r'\bsql\.Open\(\s*"pgx"'), "postgresql"),
|
|
84
|
+
(re.compile(r'\bsql\.Open\(\s*"mysql"'), "mysql"),
|
|
85
|
+
(re.compile(r'\bsql\.Open\(\s*"sqlite3?"'), "sqlite"),
|
|
86
|
+
(re.compile(r'\bsql\.Open\('), "sql"),
|
|
87
|
+
(re.compile(r'\bgorm\.Open\(\s*postgres\.'), "postgresql"),
|
|
88
|
+
(re.compile(r'\bgorm\.Open\(\s*mysql\.'), "mysql"),
|
|
89
|
+
(re.compile(r'\bgorm\.Open\(\s*sqlite\.'), "sqlite"),
|
|
90
|
+
(re.compile(r'\bgorm\.Open\('), "sql"),
|
|
91
|
+
(re.compile(r'\bsqlx\.(?:Connect|Open|MustConnect)\('), "sql"),
|
|
92
|
+
(re.compile(r'\bpgx\.(?:Connect|ConnectConfig)\(|\bpgxpool\.(?:New|Connect)\('), "postgresql"),
|
|
93
|
+
(re.compile(r'\bmongo\.Connect\('), "mongodb"),
|
|
94
|
+
(re.compile(r'\bredis\.NewClient\(|\bgo-redis\b'), "redis"),
|
|
95
|
+
(re.compile(r'\bbolt\.Open\(|\bbbolt\.Open\('), "bolt"),
|
|
96
|
+
(re.compile(r'\bs3\.New\w*\(|\baws-sdk-go(?:-v2)?/service/s3\b'), "object_storage"),
|
|
97
|
+
(re.compile(r'\bdynamodb\.New\w*\('), "dynamodb"),
|
|
98
|
+
]
|
|
99
|
+
|
|
100
|
+
# Auth-related signals
|
|
101
|
+
AUTH_PATTERNS: list[tuple[re.Pattern[str], str, float]] = [
|
|
102
|
+
(re.compile(r'\bgolang-jwt/jwt\b|\bjwt-go\b|\bjwt\.(?:Parse|NewWithClaims|MapClaims)\b'), "jwt", 0.85),
|
|
103
|
+
(re.compile(r'\bx/crypto/bcrypt\b|\bbcrypt\.GenerateFromPassword\b'), "bcrypt", 0.9),
|
|
104
|
+
(re.compile(r'\bx/crypto/argon2\b|\bargon2\.IDKey\b'), "argon2", 0.9),
|
|
105
|
+
(re.compile(r'\bx/crypto/scrypt\b'), "scrypt", 0.9),
|
|
106
|
+
(re.compile(r'\bx/oauth2\b|\boauth2\.Config\b'), "oauth", 0.85),
|
|
107
|
+
(re.compile(r'\bgorilla/sessions\b|\bsessions\.NewCookieStore\('), "gorilla_sessions", 0.85),
|
|
108
|
+
(re.compile(r'\bcasbin\.NewEnforcer\(|\bcasbin/v\d+\b'), "casbin_authz", 0.9),
|
|
109
|
+
(re.compile(r'\bgo-chi/jwtauth\b|\bjwtauth\.New\('), "chi_jwtauth", 0.85),
|
|
110
|
+
(re.compile(r'\bechojwt\b|\becho-jwt\b'), "echo_jwt", 0.85),
|
|
111
|
+
(re.compile(r'\bAuthorization\b'), "authorization_header", 0.6),
|
|
112
|
+
(re.compile(r'\bBearer\b'), "bearer_token", 0.6),
|
|
113
|
+
(re.compile(r'\bapi[_-]?key\b', re.IGNORECASE), "api_key", 0.6),
|
|
114
|
+
]
|
|
115
|
+
|
|
116
|
+
# Web framework presence
|
|
117
|
+
FRAMEWORK_PATTERNS: list[tuple[re.Pattern[str], str]] = [
|
|
118
|
+
(re.compile(r'\bgithub\.com/gin-gonic/gin\b|\bgin\.(?:Default|New|Engine)\('), "gin"),
|
|
119
|
+
(re.compile(r'\bgithub\.com/go-chi/chi\b|\bchi\.(?:NewRouter|NewMux)\('), "chi"),
|
|
120
|
+
(re.compile(r'\bgithub\.com/labstack/echo\b|\becho\.New\('), "echo"),
|
|
121
|
+
(re.compile(r'\bgithub\.com/gofiber/fiber\b|\bfiber\.New\('), "fiber"),
|
|
122
|
+
(re.compile(r'\bgithub\.com/gorilla/mux\b|\bmux\.NewRouter\('), "gorilla-mux"),
|
|
123
|
+
(re.compile(r'\bgithub\.com/gorilla/sessions\b'), "gorilla-sessions"),
|
|
124
|
+
(re.compile(r'\bnet/http\b|\bhttp\.HandleFunc\b'), "net-http"),
|
|
125
|
+
(re.compile(r'\bgrpc\.NewServer\(|\bgoogle\.golang\.org/grpc\b'), "grpc"),
|
|
126
|
+
]
|
|
127
|
+
|
|
128
|
+
# Entrypoint markers
|
|
129
|
+
ENTRYPOINT_PATTERNS: list[tuple[re.Pattern[str], str]] = [
|
|
130
|
+
(re.compile(r'\bhttp\.ListenAndServe(?:TLS)?\('), "net_http_listen"),
|
|
131
|
+
(re.compile(r'\b\w+\.ListenAndServe\(\)'), "server_listen"),
|
|
132
|
+
(re.compile(r'\b\w+\.Run\(\s*"[^"]*"\s*\)'), "gin_run"),
|
|
133
|
+
(re.compile(r'\b\w+\.Start\(\s*"[^"]*"\s*\)'), "echo_start"),
|
|
134
|
+
(re.compile(r'\b\w+\.Listen\(\s*"[^"]*"\s*\)'), "fiber_listen"),
|
|
135
|
+
(re.compile(r'\bgrpc\.NewServer\('), "grpc_server"),
|
|
136
|
+
]
|
|
137
|
+
|
|
138
|
+
# Secrets — Go env access patterns
|
|
139
|
+
SECRET_PATTERNS: list[re.Pattern[str]] = [
|
|
140
|
+
re.compile(
|
|
141
|
+
r'\bos\.Getenv\(\s*"([A-Z0-9_]*(SECRET|TOKEN|KEY|PASSWORD|PASS|PWD)[A-Z0-9_]*)"',
|
|
142
|
+
),
|
|
143
|
+
re.compile(
|
|
144
|
+
r'\bos\.LookupEnv\(\s*"([A-Z0-9_]*(SECRET|TOKEN|KEY|PASSWORD|PASS|PWD)[A-Z0-9_]*)"',
|
|
145
|
+
),
|
|
146
|
+
re.compile(
|
|
147
|
+
r'\bgodotenv\.\w+\(.*?"([A-Z0-9_]*(SECRET|TOKEN|KEY|PASSWORD|PASS|PWD)[A-Z0-9_]*)"',
|
|
148
|
+
re.DOTALL,
|
|
149
|
+
),
|
|
150
|
+
re.compile(
|
|
151
|
+
r'\bviper\.(?:GetString|Get)\(\s*"([A-Za-z0-9_.]*(?:secret|token|key|password|pass|pwd)[A-Za-z0-9_.]*)"',
|
|
152
|
+
re.IGNORECASE,
|
|
153
|
+
),
|
|
154
|
+
]
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _line_of(content: str, offset: int) -> int:
|
|
158
|
+
if offset <= 0:
|
|
159
|
+
return 1
|
|
160
|
+
return content.count("\n", 0, offset) + 1
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _line_snippet(content: str, offset: int, *, max_chars: int = _SNIPPET_MAX_CHARS) -> str:
|
|
164
|
+
line_start = content.rfind("\n", 0, offset) + 1
|
|
165
|
+
line_end = content.find("\n", offset)
|
|
166
|
+
if line_end == -1:
|
|
167
|
+
line_end = len(content)
|
|
168
|
+
line = content[line_start:line_end].strip()
|
|
169
|
+
if len(line) > max_chars:
|
|
170
|
+
line = line[: max_chars - 1] + "…"
|
|
171
|
+
return line
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _module_name_from_gomod(gomod_path: Path) -> str | None:
|
|
175
|
+
if not gomod_path.exists():
|
|
176
|
+
return None
|
|
177
|
+
try:
|
|
178
|
+
text = gomod_path.read_text(encoding="utf-8")
|
|
179
|
+
except UnicodeDecodeError:
|
|
180
|
+
return None
|
|
181
|
+
match = re.search(r"^\s*module\s+([^\s]+)\s*$", text, re.MULTILINE)
|
|
182
|
+
if match:
|
|
183
|
+
return match.group(1).strip()
|
|
184
|
+
return None
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
# Frameworks whose route extractor uses chi/echo title-case shape; we only call
|
|
188
|
+
# the relevant extractor when the file looks like it's using that framework, to
|
|
189
|
+
# avoid double-counting (chi.Get, echo.Get, fiber.Get all match the same regex).
|
|
190
|
+
def _file_is_chi(content: str) -> bool:
|
|
191
|
+
return "go-chi/chi" in content or "chi.NewRouter" in content or "chi.NewMux" in content
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _file_is_echo(content: str) -> bool:
|
|
195
|
+
return "labstack/echo" in content or "echo.New(" in content
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _file_is_fiber(content: str) -> bool:
|
|
199
|
+
return "gofiber/fiber" in content or "fiber.New(" in content
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _file_is_gin(content: str) -> bool:
|
|
203
|
+
return "gin-gonic/gin" in content or "gin.Default(" in content or "gin.New(" in content or "gin.Engine" in content
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _file_is_gorilla_mux(content: str) -> bool:
|
|
207
|
+
return "gorilla/mux" in content or "mux.NewRouter(" in content
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _file_is_net_http(content: str) -> bool:
|
|
211
|
+
return "net/http" in content or "http.HandleFunc" in content
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
class GoAnalyzer:
|
|
215
|
+
metadata = AnalyzerMetadata(
|
|
216
|
+
name="go",
|
|
217
|
+
display_name="Go Analyzer",
|
|
218
|
+
version="0.1.0",
|
|
219
|
+
description="Go ecosystem analyzer covering net/http, chi, gin, echo, fiber, gorilla/mux, and common DB/auth packages.",
|
|
220
|
+
scope="Go modules and workspaces. go.mod-bearing repos are auto-detected; pure .go trees also work.",
|
|
221
|
+
targets=["go", "golang", "gin", "chi", "echo", "fiber"],
|
|
222
|
+
languages=["go"],
|
|
223
|
+
priority=20,
|
|
224
|
+
experimental=False,
|
|
225
|
+
enabled_by_default=True,
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
@property
|
|
229
|
+
def name(self) -> str:
|
|
230
|
+
return self.metadata.name
|
|
231
|
+
|
|
232
|
+
# ---------- Public entry points ----------
|
|
233
|
+
|
|
234
|
+
def detect(self, repo_path: str | Path) -> bool:
|
|
235
|
+
root = Path(repo_path).resolve()
|
|
236
|
+
if not root.exists() or not root.is_dir():
|
|
237
|
+
return False
|
|
238
|
+
if (root / "go.mod").exists() or (root / "go.sum").exists():
|
|
239
|
+
return True
|
|
240
|
+
for path in root.rglob("go.mod"):
|
|
241
|
+
if any(part in SKIP_DIRS for part in path.parts):
|
|
242
|
+
continue
|
|
243
|
+
return True
|
|
244
|
+
for path in root.rglob("*.go"):
|
|
245
|
+
if any(part in SKIP_DIRS for part in path.parts):
|
|
246
|
+
continue
|
|
247
|
+
return True
|
|
248
|
+
return False
|
|
249
|
+
|
|
250
|
+
def analyze(self, repo_path: str | Path) -> ScanResult:
|
|
251
|
+
root = Path(repo_path).resolve()
|
|
252
|
+
result = ScanResult(root=str(root))
|
|
253
|
+
if not root.exists() or not root.is_dir():
|
|
254
|
+
return result
|
|
255
|
+
|
|
256
|
+
module_name = _module_name_from_gomod(root / "go.mod")
|
|
257
|
+
if module_name:
|
|
258
|
+
self._append_unique_service(result, f"module:{module_name}", "go.mod")
|
|
259
|
+
|
|
260
|
+
for file_path in root.rglob("*.go"):
|
|
261
|
+
if not file_path.is_file():
|
|
262
|
+
continue
|
|
263
|
+
if any(part in SKIP_DIRS for part in file_path.parts):
|
|
264
|
+
continue
|
|
265
|
+
|
|
266
|
+
result.files_scanned += 1
|
|
267
|
+
if "go" not in result.languages:
|
|
268
|
+
result.languages.append("go")
|
|
269
|
+
|
|
270
|
+
try:
|
|
271
|
+
content = file_path.read_text(encoding="utf-8")
|
|
272
|
+
except UnicodeDecodeError:
|
|
273
|
+
continue
|
|
274
|
+
|
|
275
|
+
relative = str(file_path.relative_to(root))
|
|
276
|
+
self._extract_routes(content, relative, result)
|
|
277
|
+
self._extract_databases(content, relative, result)
|
|
278
|
+
self._extract_auth(content, relative, result)
|
|
279
|
+
self._extract_secrets(content, relative, result)
|
|
280
|
+
self._extract_external_calls(content, relative, result)
|
|
281
|
+
self._extract_frameworks(content, relative, result)
|
|
282
|
+
self._extract_entrypoints(content, relative, result)
|
|
283
|
+
self._infer_service_role(content, relative, result)
|
|
284
|
+
|
|
285
|
+
result.languages.sort()
|
|
286
|
+
return result
|
|
287
|
+
|
|
288
|
+
# ---------- Extractors ----------
|
|
289
|
+
|
|
290
|
+
def _extract_routes(self, content: str, relative: str, result: ScanResult) -> None:
|
|
291
|
+
is_gin = _file_is_gin(content)
|
|
292
|
+
is_chi = _file_is_chi(content)
|
|
293
|
+
is_echo = _file_is_echo(content)
|
|
294
|
+
is_fiber = _file_is_fiber(content)
|
|
295
|
+
is_gorilla = _file_is_gorilla_mux(content)
|
|
296
|
+
is_net_http = _file_is_net_http(content)
|
|
297
|
+
|
|
298
|
+
# Gin / echo: uppercase verb method (r.GET, e.POST, ...). Echo's runtime API
|
|
299
|
+
# is the same uppercase shape as gin's despite different surface labels.
|
|
300
|
+
if is_gin or is_echo:
|
|
301
|
+
for match in GIN_ROUTE_PATTERN.finditer(content):
|
|
302
|
+
method, path = match.group(2).upper(), match.group(3)
|
|
303
|
+
self._append_unique_route(result, path, method, relative, _line_of(content, match.start()))
|
|
304
|
+
|
|
305
|
+
# Chi / fiber: title-case verb method (r.Get, app.Post, ...). Only run when
|
|
306
|
+
# we know which framework is in this file; otherwise we'd mis-attribute
|
|
307
|
+
# generic `.Get(...)` calls on non-router types.
|
|
308
|
+
if is_chi or is_fiber:
|
|
309
|
+
for match in CHI_ECHO_ROUTE_PATTERN.finditer(content):
|
|
310
|
+
method, path = match.group(2).upper(), match.group(3)
|
|
311
|
+
self._append_unique_route(result, path, method, relative, _line_of(content, match.start()))
|
|
312
|
+
|
|
313
|
+
# Gorilla/mux: HandleFunc + chained .Methods("GET", "POST")
|
|
314
|
+
if is_gorilla:
|
|
315
|
+
for match in GORILLA_HANDLEFUNC_PATTERN.finditer(content):
|
|
316
|
+
path = match.group(1)
|
|
317
|
+
line = _line_of(content, match.start())
|
|
318
|
+
chain = match.group("chain") or ""
|
|
319
|
+
methods_match = GORILLA_METHODS_PATTERN.search(chain)
|
|
320
|
+
if methods_match:
|
|
321
|
+
methods = re.findall(r'"([A-Z]+)"', methods_match.group(1))
|
|
322
|
+
if methods:
|
|
323
|
+
for method in methods:
|
|
324
|
+
self._append_unique_route(result, path, method, relative, line)
|
|
325
|
+
continue
|
|
326
|
+
self._append_unique_route(result, path, "ANY", relative, line)
|
|
327
|
+
|
|
328
|
+
# net/http stdlib: http.HandleFunc / mux.HandleFunc — always emit, but only
|
|
329
|
+
# when the file isn't already covered by gorilla/mux (which uses HandleFunc too
|
|
330
|
+
# but wraps it with .Methods()).
|
|
331
|
+
if is_net_http and not is_gorilla:
|
|
332
|
+
for match in NET_HTTP_HANDLEFUNC_PATTERN.finditer(content):
|
|
333
|
+
path = match.group(1)
|
|
334
|
+
self._append_unique_route(result, path, "ANY", relative, _line_of(content, match.start()))
|
|
335
|
+
|
|
336
|
+
def _extract_databases(self, content: str, relative: str, result: ScanResult) -> None:
|
|
337
|
+
for pattern, kind in DB_PATTERNS:
|
|
338
|
+
match = pattern.search(content)
|
|
339
|
+
if match is None:
|
|
340
|
+
continue
|
|
341
|
+
self._append_unique_database(
|
|
342
|
+
result, kind, relative,
|
|
343
|
+
_line_of(content, match.start()),
|
|
344
|
+
_line_snippet(content, match.start()),
|
|
345
|
+
)
|
|
346
|
+
|
|
347
|
+
def _extract_auth(self, content: str, relative: str, result: ScanResult) -> None:
|
|
348
|
+
for pattern, hint, confidence in AUTH_PATTERNS:
|
|
349
|
+
match = pattern.search(content)
|
|
350
|
+
if match is None:
|
|
351
|
+
continue
|
|
352
|
+
self._append_unique_auth(
|
|
353
|
+
result, hint, relative,
|
|
354
|
+
_line_of(content, match.start()),
|
|
355
|
+
_line_snippet(content, match.start()),
|
|
356
|
+
confidence,
|
|
357
|
+
)
|
|
358
|
+
|
|
359
|
+
def _extract_secrets(self, content: str, relative: str, result: ScanResult) -> None:
|
|
360
|
+
for pattern in SECRET_PATTERNS:
|
|
361
|
+
for match in pattern.finditer(content):
|
|
362
|
+
groups = match.groups()
|
|
363
|
+
name = groups[0] if groups and groups[0] else "unknown"
|
|
364
|
+
self._append_unique_secret(
|
|
365
|
+
result, name, relative,
|
|
366
|
+
_line_of(content, match.start()),
|
|
367
|
+
_line_snippet(content, match.start()),
|
|
368
|
+
)
|
|
369
|
+
|
|
370
|
+
def _extract_external_calls(self, content: str, relative: str, result: ScanResult) -> None:
|
|
371
|
+
for pattern in OUTBOUND_PATTERNS:
|
|
372
|
+
for match in pattern.finditer(content):
|
|
373
|
+
target = match.group(1)
|
|
374
|
+
if not (target.startswith("http://") or target.startswith("https://")):
|
|
375
|
+
continue
|
|
376
|
+
self._append_unique_external(
|
|
377
|
+
result, target, relative,
|
|
378
|
+
_line_of(content, match.start()),
|
|
379
|
+
_line_snippet(content, match.start()),
|
|
380
|
+
)
|
|
381
|
+
|
|
382
|
+
def _extract_frameworks(self, content: str, relative: str, result: ScanResult) -> None:
|
|
383
|
+
for pattern, name in FRAMEWORK_PATTERNS:
|
|
384
|
+
match = pattern.search(content)
|
|
385
|
+
if match is None:
|
|
386
|
+
continue
|
|
387
|
+
self._append_unique_framework(
|
|
388
|
+
result, name, relative,
|
|
389
|
+
_line_of(content, match.start()),
|
|
390
|
+
_line_snippet(content, match.start()),
|
|
391
|
+
)
|
|
392
|
+
|
|
393
|
+
def _extract_entrypoints(self, content: str, relative: str, result: ScanResult) -> None:
|
|
394
|
+
for pattern, hint in ENTRYPOINT_PATTERNS:
|
|
395
|
+
match = pattern.search(content)
|
|
396
|
+
if match is None:
|
|
397
|
+
continue
|
|
398
|
+
self._append_unique_entrypoint(
|
|
399
|
+
result, hint, relative,
|
|
400
|
+
_line_of(content, match.start()),
|
|
401
|
+
_line_snippet(content, match.start()),
|
|
402
|
+
)
|
|
403
|
+
|
|
404
|
+
def _infer_service_role(self, content: str, relative: str, result: ScanResult) -> None:
|
|
405
|
+
haystack = (relative + " " + content[:500]).lower()
|
|
406
|
+
role: str | None = None
|
|
407
|
+
if any(token in haystack for token in ("worker", "consumer", "queue", "background", "cronjob")):
|
|
408
|
+
role = "worker"
|
|
409
|
+
elif any(token in haystack for token in ("api", "server", "handler", "router", "controller")):
|
|
410
|
+
role = "api"
|
|
411
|
+
elif any(token in haystack for token in ("client", "sdk")):
|
|
412
|
+
role = "client"
|
|
413
|
+
if role:
|
|
414
|
+
self._append_unique_service(result, f"service_role:{role}", relative)
|
|
415
|
+
|
|
416
|
+
# ---------- Append helpers (dedup-aware) ----------
|
|
417
|
+
|
|
418
|
+
@staticmethod
|
|
419
|
+
def _append_unique_route(result: ScanResult, path: str, method: str, file: str, line: int | None) -> None:
|
|
420
|
+
key = (path, method, file)
|
|
421
|
+
if any((item.path, item.method, item.file) == key for item in result.routes):
|
|
422
|
+
return
|
|
423
|
+
result.routes.append(Route(path=path, method=method, file=file, line=line))
|
|
424
|
+
|
|
425
|
+
@staticmethod
|
|
426
|
+
def _append_unique_database(result: ScanResult, kind: str, file: str, line: int | None, evidence: str | None) -> None:
|
|
427
|
+
key = (kind, file)
|
|
428
|
+
if any((item.kind, item.file) == key for item in result.databases):
|
|
429
|
+
return
|
|
430
|
+
result.databases.append(DatabaseHint(kind=kind, file=file, line=line, evidence_text=evidence))
|
|
431
|
+
|
|
432
|
+
@staticmethod
|
|
433
|
+
def _append_unique_auth(result: ScanResult, hint: str, file: str, line: int | None, evidence: str | None, confidence: float) -> None:
|
|
434
|
+
key = (hint, file)
|
|
435
|
+
if any((item.hint, item.file) == key for item in result.auth_hints):
|
|
436
|
+
return
|
|
437
|
+
result.auth_hints.append(AuthHint(hint=hint, file=file, line=line, evidence_text=evidence, confidence=confidence))
|
|
438
|
+
|
|
439
|
+
@staticmethod
|
|
440
|
+
def _append_unique_secret(result: ScanResult, name: str, file: str, line: int | None, evidence: str | None) -> None:
|
|
441
|
+
key = (name, file)
|
|
442
|
+
if any((item.name, item.file) == key for item in result.secret_hints):
|
|
443
|
+
return
|
|
444
|
+
result.secret_hints.append(SecretHint(name=name, file=file, line=line, evidence_text=evidence, confidence=0.85))
|
|
445
|
+
|
|
446
|
+
@staticmethod
|
|
447
|
+
def _append_unique_external(result: ScanResult, target: str, file: str, line: int | None, evidence: str | None) -> None:
|
|
448
|
+
key = (target, file)
|
|
449
|
+
if any((item.target, item.file) == key for item in result.external_calls):
|
|
450
|
+
return
|
|
451
|
+
result.external_calls.append(ExternalCall(target=target, file=file, line=line, evidence_text=evidence))
|
|
452
|
+
|
|
453
|
+
@staticmethod
|
|
454
|
+
def _append_unique_framework(result: ScanResult, hint: str, file: str, line: int | None, evidence: str | None) -> None:
|
|
455
|
+
key = (hint, file)
|
|
456
|
+
if any((item.hint, item.file) == key for item in result.framework_hints):
|
|
457
|
+
return
|
|
458
|
+
result.framework_hints.append(FrameworkHint(hint=hint, file=file, line=line, evidence_text=evidence))
|
|
459
|
+
|
|
460
|
+
@staticmethod
|
|
461
|
+
def _append_unique_entrypoint(result: ScanResult, hint: str, file: str, line: int | None, evidence: str | None) -> None:
|
|
462
|
+
key = (hint, file)
|
|
463
|
+
if any((item.hint, item.file) == key for item in result.entrypoint_hints):
|
|
464
|
+
return
|
|
465
|
+
result.entrypoint_hints.append(EntrypointHint(hint=hint, file=file, line=line, evidence_text=evidence))
|
|
466
|
+
|
|
467
|
+
@staticmethod
|
|
468
|
+
def _append_unique_service(result: ScanResult, hint: str, file: str) -> None:
|
|
469
|
+
key = (hint, file)
|
|
470
|
+
if any((item.hint, item.file) == key for item in result.service_hints):
|
|
471
|
+
return
|
|
472
|
+
result.service_hints.append(ServiceHint(hint=hint, file=file))
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
__all__ = ["GoAnalyzer"]
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from attackmap.sdk.contracts import AnalyzerMetadata, AnalyzerProtocol
|
|
4
|
+
from attackmap.sdk.models import (
|
|
5
|
+
AuthHint,
|
|
6
|
+
DatabaseHint,
|
|
7
|
+
EntrypointHint,
|
|
8
|
+
ExternalCall,
|
|
9
|
+
FrameworkHint,
|
|
10
|
+
Route,
|
|
11
|
+
ScanResult,
|
|
12
|
+
SecretHint,
|
|
13
|
+
ServiceHint,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
# Compatibility alias used by existing analyzer implementations.
|
|
17
|
+
AttackMapAnalyzerProtocol = AnalyzerProtocol
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"AnalyzerMetadata",
|
|
21
|
+
"AttackMapAnalyzerProtocol",
|
|
22
|
+
"Route",
|
|
23
|
+
"ExternalCall",
|
|
24
|
+
"DatabaseHint",
|
|
25
|
+
"AuthHint",
|
|
26
|
+
"EntrypointHint",
|
|
27
|
+
"FrameworkHint",
|
|
28
|
+
"ServiceHint",
|
|
29
|
+
"SecretHint",
|
|
30
|
+
"ScanResult",
|
|
31
|
+
]
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: attackmap-analyzer-go
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Go ecosystem analyzer plugin for AttackMap (net/http, chi, gin, echo, fiber, gorilla/mux; database/sql, gorm, sqlx, pgx; golang-jwt; resty).
|
|
5
|
+
Author: AttackMap Contributors
|
|
6
|
+
Author-email: Matthew Davis <matthewd@matthewd.xyz>
|
|
7
|
+
Maintainer-email: Matthew Davis <matthewd@matthewd.xyz>
|
|
8
|
+
License: MIT
|
|
9
|
+
Project-URL: Homepage, https://github.com/mlaify/attackmap-analyzer-go
|
|
10
|
+
Project-URL: Repository, https://github.com/mlaify/attackmap-analyzer-go
|
|
11
|
+
Project-URL: Issues, https://github.com/mlaify/attackmap-analyzer-go/issues
|
|
12
|
+
Project-URL: Changelog, https://github.com/mlaify/attackmap-analyzer-go/blob/main/CHANGELOG.md
|
|
13
|
+
Project-URL: AttackMap core, https://github.com/mlaify/AttackMap
|
|
14
|
+
Keywords: security,static-analysis,appsec,defensive-security,attackmap,attackmap-plugin
|
|
15
|
+
Classifier: Development Status :: 4 - Beta
|
|
16
|
+
Classifier: Intended Audience :: Developers
|
|
17
|
+
Classifier: Intended Audience :: Information Technology
|
|
18
|
+
Classifier: Intended Audience :: System Administrators
|
|
19
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
20
|
+
Classifier: Operating System :: OS Independent
|
|
21
|
+
Classifier: Programming Language :: Python :: 3
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
25
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
26
|
+
Classifier: Topic :: Security
|
|
27
|
+
Classifier: Topic :: Software Development :: Quality Assurance
|
|
28
|
+
Classifier: Typing :: Typed
|
|
29
|
+
Requires-Python: >=3.11
|
|
30
|
+
Description-Content-Type: text/markdown
|
|
31
|
+
License-File: LICENSE
|
|
32
|
+
Requires-Dist: pydantic>=2.7.0
|
|
33
|
+
Provides-Extra: core
|
|
34
|
+
Requires-Dist: attackmap>=0.1.0; extra == "core"
|
|
35
|
+
Provides-Extra: dev
|
|
36
|
+
Requires-Dist: pytest>=8.0.0; extra == "dev"
|
|
37
|
+
Requires-Dist: build>=1.2.0; extra == "dev"
|
|
38
|
+
Requires-Dist: attackmap>=0.1.0; extra == "dev"
|
|
39
|
+
Dynamic: license-file
|
|
40
|
+
|
|
41
|
+
# attackmap-analyzer-go
|
|
42
|
+
|
|
43
|
+
Go ecosystem analyzer for [AttackMap](https://github.com/mlaify/AttackMap).
|
|
44
|
+
|
|
45
|
+
This analyzer extracts structured signals from Go modules and workspaces:
|
|
46
|
+
|
|
47
|
+
- **Web frameworks** — net/http (stdlib), chi, gin, echo, fiber, gorilla/mux (route + entrypoint extraction)
|
|
48
|
+
- **Databases** — `database/sql` (Postgres / MySQL / SQLite drivers), gorm (with driver-aware kind inference), sqlx, pgx, mongo-go-driver, go-redis, bbolt, AWS SDK (S3, DynamoDB)
|
|
49
|
+
- **Auth packages** — golang-jwt, golang.org/x/oauth2, gorilla/sessions, casbin, x/crypto/bcrypt / scrypt / argon2, go-chi/jwtauth, echo-jwt
|
|
50
|
+
- **HTTP clients (external calls)** — net/http (`http.Get` / `http.Post` / `http.NewRequest`), go-resty, grequests
|
|
51
|
+
- **Secrets** — `os.Getenv`, `os.LookupEnv`, `godotenv`, `viper.GetString`
|
|
52
|
+
- **Service hints** — module name extracted from `go.mod`
|
|
53
|
+
|
|
54
|
+
All emissions populate AttackMap's Signal v2 fields (line numbers, evidence snippets, confidence scores) so downstream insights can cite `path/to/file.go:NN`.
|
|
55
|
+
|
|
56
|
+
## Install
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
pip install git+https://github.com/mlaify/attackmap-analyzer-go.git
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
The analyzer is auto-discovered by AttackMap via the `attackmap.analyzers` entry-point group.
|
|
63
|
+
|
|
64
|
+
## Usage with AttackMap
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
# Auto-discovered when installed:
|
|
68
|
+
attackmap analyze /path/to/go/repo
|
|
69
|
+
|
|
70
|
+
# Or invoke explicitly:
|
|
71
|
+
attackmap analyze /path/to/go/repo --module go
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## Detection
|
|
75
|
+
|
|
76
|
+
`detect()` returns true when any of the following are present, ignoring `vendor/`, `.git/`, `node_modules/`, `dist/`, and `build/`:
|
|
77
|
+
|
|
78
|
+
- A `go.mod` or `go.sum` at the repository root, or anywhere in the tree
|
|
79
|
+
- One or more `.go` files in the tree
|
|
80
|
+
|
|
81
|
+
## Coverage notes
|
|
82
|
+
|
|
83
|
+
- **Framework-aware route extraction**: chi/echo/fiber all use the same title-case verb pattern (`r.Get(...)`, `r.Post(...)`). To avoid mis-attributing generic `.Get(...)` calls (e.g., on a map type) as routes, the analyzer only fires those extractors when the file *also* contains a recognizable framework marker (`go-chi/chi` import, `chi.NewRouter(`, `labstack/echo`, `echo.New(`, etc.).
|
|
84
|
+
- **gorilla/mux + net/http**: when both are detected in the same file, only the gorilla extractor runs. The stdlib `HandleFunc` extractor would otherwise double-count the same routes.
|
|
85
|
+
- **Method extraction**: gin uses uppercase methods (`r.GET`); chi/echo/fiber use title-case (`r.Get`); gorilla/mux chains `.Methods("GET", "POST")` after `HandleFunc`. All three shapes are supported. `http.HandleFunc` has no method information, so those routes are emitted with method `ANY`.
|
|
86
|
+
- **chi `Route()` / `Mount()` prefix nesting**: routes inside `r.Route("/api", func(r chi.Router) { ... })` are extracted but the outer `/api` prefix is not currently joined to the inner paths. Roadmap.
|
|
87
|
+
- **gRPC**: framework presence and `grpc.NewServer` entrypoint are detected. Per-service / per-method route extraction would require parsing `.proto` files — not yet supported.
|
|
88
|
+
|
|
89
|
+
## License
|
|
90
|
+
|
|
91
|
+
MIT
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
attackmap_analyzer_go/__init__.py,sha256=LpDQ2JdYEzHKhZTujOkIn2euGGEgcd4PBSwB-UeZseQ,59
|
|
2
|
+
attackmap_analyzer_go/analyzer.py,sha256=UDOcSLVNuvODCpxWl4yj66h_pnc1qpRnNLAcmqitPOQ,20307
|
|
3
|
+
attackmap_analyzer_go/contracts.py,sha256=6Kd8AZYMCQiR0JJpiAptlHYyuzr7ngWEwwXK-uUrWPM,643
|
|
4
|
+
attackmap_analyzer_go-0.1.0.dist-info/licenses/LICENSE,sha256=vtPQVGUyxq359j0JmD3_eJaXyHmaHyjzaMOtaLwJc88,1097
|
|
5
|
+
attackmap_analyzer_go-0.1.0.dist-info/METADATA,sha256=bjab-ffwDrhJ3hZpde-7dBsY52VZmbolch42Mp6IMck,4815
|
|
6
|
+
attackmap_analyzer_go-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
7
|
+
attackmap_analyzer_go-0.1.0.dist-info/entry_points.txt,sha256=9Ni8MAsEGnXwfETdrep8zCDuv_HBGYB0UjmCnDx3Ryc,60
|
|
8
|
+
attackmap_analyzer_go-0.1.0.dist-info/top_level.txt,sha256=AVdIjr1D2H2GnVkLeRhVuIakVCIkUbbRmm9n-uGfhCs,22
|
|
9
|
+
attackmap_analyzer_go-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Matthew Davis and AttackMap Contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
attackmap_analyzer_go
|