attackmap-analyzer-terraform 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-terraform might be problematic. Click here for more details.

@@ -0,0 +1,3 @@
1
+ from .analyzer import TerraformAnalyzer
2
+
3
+ __all__ = ["TerraformAnalyzer"]
@@ -0,0 +1,540 @@
1
+ """Terraform / HCL infrastructure-as-code analyzer for AttackMap.
2
+
3
+ This analyzer is shaped differently from language analyzers — Terraform doesn't
4
+ have routes in the application sense. Instead, the value is in:
5
+
6
+ - **Public ingress** — security groups / NACLs / Lambda function URLs / API
7
+ Gateway methods with no auth → `entrypoint_hints`
8
+ - **Asset inventory** — S3 buckets, RDS, DynamoDB, Cognito user pools, KMS keys
9
+ → `service_hints` and `database_hints`
10
+ - **Secrets** — `aws_secretsmanager_secret`, `aws_ssm_parameter` (SecureString),
11
+ `variable` blocks marked `sensitive = true` or with secret-shaped names
12
+ → `secret_hints`
13
+ - **IAM blast radius** — wildcards in policy actions (`Action: *`) → `auth_hints`
14
+ with low confidence (broad permissions)
15
+ - **Database engines** — `aws_db_instance.engine = "postgres"` → `database_hints`
16
+ with the engine as the kind
17
+
18
+ All emissions populate Signal v2 fields (line numbers, evidence snippets) so
19
+ downstream insights can cite `infra/main.tf:NN`.
20
+
21
+ HCL parsing uses brace-depth counting on top of regex. This is approximate but
22
+ sufficient for the resource-level introspection the analyzer needs. Variable
23
+ interpolation (`${var.foo}`) is not resolved — string literals and direct
24
+ attribute values are what we extract.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import re
30
+ from pathlib import Path
31
+
32
+ from .contracts import (
33
+ AnalyzerMetadata,
34
+ AuthHint,
35
+ DatabaseHint,
36
+ EntrypointHint,
37
+ ExternalCall,
38
+ FrameworkHint,
39
+ Route,
40
+ ScanResult,
41
+ SecretHint,
42
+ ServiceHint,
43
+ )
44
+
45
+ CODE_SUFFIXES = {".tf", ".tf.json", ".tfvars"}
46
+ SKIP_DIRS = {".terraform", ".git", "node_modules", "vendor"}
47
+ _SNIPPET_MAX_CHARS = 160
48
+
49
+ # ---------- Patterns ----------
50
+
51
+ # Top-level resource block header: resource "type" "name" {
52
+ RESOURCE_BLOCK_PATTERN = re.compile(
53
+ r'\bresource\s+"([a-z][a-z0-9_]+)"\s+"([a-zA-Z0-9_-]+)"\s*\{',
54
+ )
55
+ # Top-level variable block header: variable "name" {
56
+ VARIABLE_BLOCK_PATTERN = re.compile(
57
+ r'\bvariable\s+"([a-zA-Z0-9_-]+)"\s*\{',
58
+ )
59
+ # Top-level data source: data "type" "name" {
60
+ DATA_BLOCK_PATTERN = re.compile(
61
+ r'\bdata\s+"([a-z][a-z0-9_]+)"\s+"([a-zA-Z0-9_-]+)"\s*\{',
62
+ )
63
+ # Module block: module "name" {
64
+ MODULE_BLOCK_PATTERN = re.compile(
65
+ r'\bmodule\s+"([a-zA-Z0-9_-]+)"\s*\{',
66
+ )
67
+ # Provider declaration: provider "aws" { ... }
68
+ PROVIDER_BLOCK_PATTERN = re.compile(
69
+ r'\bprovider\s+"([a-z][a-z0-9_]+)"\s*\{',
70
+ )
71
+
72
+ # Common attribute extraction inside block bodies
73
+ _ATTR_RE = re.compile(r'^\s*(\w+)\s*=\s*(.+?)\s*$', re.MULTILINE)
74
+
75
+
76
+ def _line_of(content: str, offset: int) -> int:
77
+ if offset <= 0:
78
+ return 1
79
+ return content.count("\n", 0, offset) + 1
80
+
81
+
82
+ def _line_snippet(content: str, offset: int, *, max_chars: int = _SNIPPET_MAX_CHARS) -> str:
83
+ line_start = content.rfind("\n", 0, offset) + 1
84
+ line_end = content.find("\n", offset)
85
+ if line_end == -1:
86
+ line_end = len(content)
87
+ line = content[line_start:line_end].strip()
88
+ if len(line) > max_chars:
89
+ line = line[: max_chars - 1] + "…"
90
+ return line
91
+
92
+
93
+ def _block_body(content: str, body_start: int) -> tuple[str, int]:
94
+ """Return the body of a block whose `{` is at body_start-1, plus the offset
95
+ of the closing `}`. Tracks brace depth and string literals so nested
96
+ `ingress { ... }` blocks are included."""
97
+ depth = 1
98
+ i = body_start
99
+ in_string = False
100
+ escape = False
101
+ while i < len(content) and depth > 0:
102
+ ch = content[i]
103
+ if in_string:
104
+ if escape:
105
+ escape = False
106
+ elif ch == "\\":
107
+ escape = True
108
+ elif ch == '"':
109
+ in_string = False
110
+ else:
111
+ if ch == '"':
112
+ in_string = True
113
+ elif ch == "{":
114
+ depth += 1
115
+ elif ch == "}":
116
+ depth -= 1
117
+ if depth == 0:
118
+ return content[body_start:i], i
119
+ i += 1
120
+ return content[body_start:i], i
121
+
122
+
123
+ def _extract_attr(body: str, name: str) -> str | None:
124
+ """Return the value of a top-level attribute `name = ...` in a block body
125
+ (does not descend into nested blocks). Strips matching quotes."""
126
+ pattern = re.compile(rf'^\s*{re.escape(name)}\s*=\s*"([^"]*)"\s*$', re.MULTILINE)
127
+ match = pattern.search(body)
128
+ if match:
129
+ return match.group(1)
130
+ # Try unquoted form (booleans, references, numbers, lists)
131
+ raw_pattern = re.compile(rf'^\s*{re.escape(name)}\s*=\s*([^\n]+?)\s*$', re.MULTILINE)
132
+ match = raw_pattern.search(body)
133
+ if match:
134
+ return match.group(1).strip()
135
+ return None
136
+
137
+
138
+ def _has_open_cidr(body: str) -> bool:
139
+ """True if the body references an open CIDR (`0.0.0.0/0` or `::/0`)
140
+ as a list element."""
141
+ return '"0.0.0.0/0"' in body or '"::/0"' in body
142
+
143
+
144
+ def _has_iam_wildcard_action(body: str) -> bool:
145
+ """Detect IAM policy bodies with wildcard `Action` or `Resource`."""
146
+ if '"Action": "*"' in body or '"Action":"*"' in body:
147
+ return True
148
+ if re.search(r'"Action"\s*:\s*\[\s*"\*"\s*\]', body):
149
+ return True
150
+ if re.search(r'Action\s*=\s*\[\s*"\*"\s*\]', body):
151
+ return True
152
+ if re.search(r'Action\s*=\s*"\*"', body):
153
+ return True
154
+ return False
155
+
156
+
157
+ # Provider/framework labels — used both as framework_hints and to gate cloud-specific extractors.
158
+ _PROVIDER_LABEL = {
159
+ "aws": "terraform-aws",
160
+ "azurerm": "terraform-azure",
161
+ "google": "terraform-gcp",
162
+ "kubernetes": "terraform-kubernetes",
163
+ }
164
+
165
+
166
+ # Database engine inference for aws_db_instance / aws_rds_cluster
167
+ _ENGINE_KIND_MAP = {
168
+ "postgres": "postgresql",
169
+ "postgresql": "postgresql",
170
+ "aurora-postgresql": "postgresql",
171
+ "mysql": "mysql",
172
+ "aurora-mysql": "mysql",
173
+ "mariadb": "mariadb",
174
+ "oracle-ee": "oracle",
175
+ "oracle-se": "oracle",
176
+ "oracle-se2": "oracle",
177
+ "sqlserver-ee": "sqlserver",
178
+ "sqlserver-se": "sqlserver",
179
+ "sqlserver-ex": "sqlserver",
180
+ "sqlserver-web": "sqlserver",
181
+ }
182
+
183
+
184
+ _SECRET_KEYWORDS = ("secret", "token", "key", "password", "pass", "pwd", "credential", "apikey")
185
+
186
+
187
+ def _looks_secret_shaped(name: str) -> bool:
188
+ lowered = name.lower()
189
+ return any(kw in lowered for kw in _SECRET_KEYWORDS)
190
+
191
+
192
+ class TerraformAnalyzer:
193
+ metadata = AnalyzerMetadata(
194
+ name="terraform",
195
+ display_name="Terraform / HCL Analyzer",
196
+ version="0.1.0",
197
+ description="Terraform infrastructure-as-code analyzer covering AWS, Azure, and GCP resources, IAM wildcards, open security groups, and secrets.",
198
+ scope="Terraform / OpenTofu projects (.tf files). Detects provider-level resources, public ingress, secret resources, and database engines.",
199
+ targets=["terraform", "iac", "hcl", "aws", "azure", "gcp"],
200
+ languages=["hcl"],
201
+ priority=20,
202
+ experimental=False,
203
+ enabled_by_default=True,
204
+ )
205
+
206
+ @property
207
+ def name(self) -> str:
208
+ return self.metadata.name
209
+
210
+ # ---------- Public entry points ----------
211
+
212
+ def detect(self, repo_path: str | Path) -> bool:
213
+ root = Path(repo_path).resolve()
214
+ if not root.exists() or not root.is_dir():
215
+ return False
216
+ for path in root.rglob("*"):
217
+ if any(part in SKIP_DIRS for part in path.parts):
218
+ continue
219
+ if not path.is_file():
220
+ continue
221
+ if path.suffix == ".tf" or path.name.endswith(".tf.json") or path.suffix == ".tfvars":
222
+ return True
223
+ return False
224
+
225
+ def analyze(self, repo_path: str | Path) -> ScanResult:
226
+ root = Path(repo_path).resolve()
227
+ result = ScanResult(root=str(root))
228
+ if not root.exists() or not root.is_dir():
229
+ return result
230
+
231
+ for file_path in root.rglob("*"):
232
+ if not file_path.is_file():
233
+ continue
234
+ if any(part in SKIP_DIRS for part in file_path.parts):
235
+ continue
236
+ if not (file_path.suffix == ".tf" or file_path.name.endswith(".tf.json") or file_path.suffix == ".tfvars"):
237
+ continue
238
+
239
+ result.files_scanned += 1
240
+ if "hcl" not in result.languages:
241
+ result.languages.append("hcl")
242
+
243
+ try:
244
+ content = file_path.read_text(encoding="utf-8")
245
+ except UnicodeDecodeError:
246
+ continue
247
+
248
+ relative = str(file_path.relative_to(root))
249
+ self._extract_providers(content, relative, result)
250
+ self._extract_resources(content, relative, result)
251
+ self._extract_variables(content, relative, result)
252
+ self._extract_modules(content, relative, result)
253
+ self._extract_data_sources(content, relative, result)
254
+
255
+ result.languages.sort()
256
+ return result
257
+
258
+ # ---------- Extractors ----------
259
+
260
+ def _extract_providers(self, content: str, relative: str, result: ScanResult) -> None:
261
+ for match in PROVIDER_BLOCK_PATTERN.finditer(content):
262
+ provider = match.group(1)
263
+ label = _PROVIDER_LABEL.get(provider, f"terraform-{provider}")
264
+ self._append_unique_framework(
265
+ result, label, relative,
266
+ _line_of(content, match.start()),
267
+ _line_snippet(content, match.start()),
268
+ )
269
+
270
+ def _extract_resources(self, content: str, relative: str, result: ScanResult) -> None:
271
+ for match in RESOURCE_BLOCK_PATTERN.finditer(content):
272
+ resource_type, resource_name = match.group(1), match.group(2)
273
+ body, _ = _block_body(content, match.end())
274
+ line = _line_of(content, match.start())
275
+ self._dispatch_resource(resource_type, resource_name, body, relative, line, content, match.start(), result)
276
+
277
+ def _extract_variables(self, content: str, relative: str, result: ScanResult) -> None:
278
+ for match in VARIABLE_BLOCK_PATTERN.finditer(content):
279
+ var_name = match.group(1)
280
+ body, _ = _block_body(content, match.end())
281
+ line = _line_of(content, match.start())
282
+ sensitive = (_extract_attr(body, "sensitive") or "").lower() == "true"
283
+ if sensitive or _looks_secret_shaped(var_name):
284
+ self._append_unique_secret(
285
+ result, var_name, relative, line,
286
+ _line_snippet(content, match.start()),
287
+ )
288
+
289
+ def _extract_modules(self, content: str, relative: str, result: ScanResult) -> None:
290
+ for match in MODULE_BLOCK_PATTERN.finditer(content):
291
+ module_name = match.group(1)
292
+ self._append_unique_service(result, f"module:{module_name}", relative)
293
+
294
+ def _extract_data_sources(self, content: str, relative: str, result: ScanResult) -> None:
295
+ # data "aws_secretsmanager_secret" "x" { ... } — surface secret references via data.
296
+ for match in DATA_BLOCK_PATTERN.finditer(content):
297
+ data_type, data_name = match.group(1), match.group(2)
298
+ line = _line_of(content, match.start())
299
+ if data_type in {"aws_secretsmanager_secret", "aws_secretsmanager_secret_version", "aws_ssm_parameter"}:
300
+ self._append_unique_secret(
301
+ result, f"data:{data_type}:{data_name}", relative, line,
302
+ _line_snippet(content, match.start()),
303
+ )
304
+
305
+ # ---------- Resource dispatchers ----------
306
+
307
+ def _dispatch_resource(
308
+ self,
309
+ resource_type: str,
310
+ resource_name: str,
311
+ body: str,
312
+ file: str,
313
+ line: int,
314
+ content: str,
315
+ offset: int,
316
+ result: ScanResult,
317
+ ) -> None:
318
+ ev = _line_snippet(content, offset)
319
+
320
+ # ---- AWS ----
321
+ if resource_type == "aws_security_group" and _has_open_cidr(body):
322
+ self._append_unique_entrypoint(
323
+ result, f"sg_open_ingress:{resource_name}", file, line, ev,
324
+ )
325
+ return
326
+ if resource_type in {"aws_security_group_rule", "aws_vpc_security_group_ingress_rule"} and _has_open_cidr(body):
327
+ direction = (_extract_attr(body, "type") or "").lower() or "ingress"
328
+ self._append_unique_entrypoint(
329
+ result, f"sg_rule_{direction}_open:{resource_name}", file, line, ev,
330
+ )
331
+ return
332
+ if resource_type == "aws_lambda_function":
333
+ self._append_unique_entrypoint(
334
+ result, f"lambda:{resource_name}", file, line, ev,
335
+ )
336
+ self._append_unique_service(result, f"function:{resource_name}", file)
337
+ return
338
+ if resource_type == "aws_lambda_function_url":
339
+ authorization_type = (_extract_attr(body, "authorization_type") or "").upper()
340
+ label = "lambda_url_open" if authorization_type == "NONE" else "lambda_url"
341
+ self._append_unique_entrypoint(
342
+ result, f"{label}:{resource_name}", file, line, ev,
343
+ )
344
+ return
345
+ if resource_type == "aws_api_gateway_method":
346
+ http_method = (_extract_attr(body, "http_method") or "ANY").upper()
347
+ authorization = (_extract_attr(body, "authorization") or "").upper()
348
+ if authorization == "NONE":
349
+ self._append_unique_entrypoint(
350
+ result, f"apigw_open_method:{http_method}:{resource_name}", file, line, ev,
351
+ )
352
+ else:
353
+ self._append_unique_entrypoint(
354
+ result, f"apigw_method:{http_method}:{resource_name}", file, line, ev,
355
+ )
356
+ return
357
+ if resource_type == "aws_apigatewayv2_route":
358
+ route_key = _extract_attr(body, "route_key") or ""
359
+ authorization_type = (_extract_attr(body, "authorization_type") or "").upper()
360
+ if route_key:
361
+ # route_key is "GET /users" or "POST /things" — split into method + path.
362
+ parts = route_key.strip().split(maxsplit=1)
363
+ if len(parts) == 2:
364
+ method, path = parts[0].upper(), parts[1]
365
+ self._append_unique_route(result, path, method, file, line)
366
+ if authorization_type == "NONE":
367
+ self._append_unique_entrypoint(
368
+ result, f"apigwv2_open:{resource_name}", file, line, ev,
369
+ )
370
+ return
371
+ if resource_type in {"aws_lb", "aws_alb", "aws_cloudfront_distribution"}:
372
+ self._append_unique_entrypoint(
373
+ result, f"{resource_type}:{resource_name}", file, line, ev,
374
+ )
375
+ return
376
+ if resource_type == "aws_s3_bucket":
377
+ self._append_unique_service(result, f"s3_bucket:{resource_name}", file)
378
+ return
379
+ if resource_type == "aws_s3_bucket_acl":
380
+ acl = (_extract_attr(body, "acl") or "").lower()
381
+ if acl in {"public-read", "public-read-write"}:
382
+ self._append_unique_entrypoint(
383
+ result, f"s3_public_acl:{resource_name}", file, line, ev,
384
+ )
385
+ return
386
+ if resource_type == "aws_s3_bucket_public_access_block":
387
+ for attr in ("block_public_acls", "block_public_policy", "ignore_public_acls", "restrict_public_buckets"):
388
+ value = (_extract_attr(body, attr) or "true").lower()
389
+ if value == "false":
390
+ self._append_unique_entrypoint(
391
+ result, f"s3_public_block_disabled:{resource_name}", file, line, ev,
392
+ )
393
+ return
394
+ return
395
+ if resource_type == "aws_db_instance" or resource_type == "aws_rds_cluster":
396
+ engine = (_extract_attr(body, "engine") or "").lower()
397
+ kind = _ENGINE_KIND_MAP.get(engine, "sql")
398
+ self._append_unique_database(result, kind, file, line, ev)
399
+ self._append_unique_service(result, f"rds:{resource_name}", file)
400
+ publicly_accessible = (_extract_attr(body, "publicly_accessible") or "false").lower()
401
+ if publicly_accessible == "true":
402
+ self._append_unique_entrypoint(
403
+ result, f"rds_publicly_accessible:{resource_name}", file, line, ev,
404
+ )
405
+ return
406
+ if resource_type in {"aws_dynamodb_table", "aws_dynamodb_global_table"}:
407
+ self._append_unique_database(result, "dynamodb", file, line, ev)
408
+ self._append_unique_service(result, f"dynamodb:{resource_name}", file)
409
+ return
410
+ if resource_type in {"aws_elasticache_cluster", "aws_elasticache_replication_group"}:
411
+ self._append_unique_database(result, "redis", file, line, ev)
412
+ self._append_unique_service(result, f"elasticache:{resource_name}", file)
413
+ return
414
+ if resource_type in {"aws_documentdb_cluster", "aws_docdb_cluster"}:
415
+ self._append_unique_database(result, "mongodb", file, line, ev)
416
+ return
417
+ if resource_type == "aws_secretsmanager_secret":
418
+ self._append_unique_secret(result, f"secretsmanager:{resource_name}", file, line, ev)
419
+ return
420
+ if resource_type == "aws_ssm_parameter":
421
+ param_type = (_extract_attr(body, "type") or "").lower()
422
+ if param_type == "securestring":
423
+ self._append_unique_secret(result, f"ssm:{resource_name}", file, line, ev)
424
+ return
425
+ if resource_type == "aws_kms_key" or resource_type == "aws_kms_alias":
426
+ self._append_unique_service(result, f"kms:{resource_name}", file)
427
+ return
428
+ if resource_type == "aws_cognito_user_pool":
429
+ self._append_unique_auth(result, f"cognito_user_pool:{resource_name}", file, line, ev, 0.85)
430
+ return
431
+ if resource_type in {"aws_iam_policy", "aws_iam_role_policy", "aws_iam_user_policy"}:
432
+ if _has_iam_wildcard_action(body):
433
+ self._append_unique_auth(
434
+ result, f"iam_wildcard_action:{resource_name}", file, line, ev, 0.7,
435
+ )
436
+ return
437
+
438
+ # ---- Azure ----
439
+ if resource_type == "azurerm_storage_account":
440
+ self._append_unique_service(result, f"azure_storage:{resource_name}", file)
441
+ return
442
+ if resource_type == "azurerm_key_vault":
443
+ self._append_unique_service(result, f"key_vault:{resource_name}", file)
444
+ return
445
+ if resource_type == "azurerm_network_security_rule" and _has_open_cidr(body):
446
+ self._append_unique_entrypoint(
447
+ result, f"azure_nsg_open:{resource_name}", file, line, ev,
448
+ )
449
+ return
450
+ if resource_type in {"azurerm_postgresql_server", "azurerm_postgresql_flexible_server"}:
451
+ self._append_unique_database(result, "postgresql", file, line, ev)
452
+ return
453
+ if resource_type in {"azurerm_mysql_server", "azurerm_mysql_flexible_server"}:
454
+ self._append_unique_database(result, "mysql", file, line, ev)
455
+ return
456
+ if resource_type == "azurerm_cosmosdb_account":
457
+ self._append_unique_database(result, "cosmosdb", file, line, ev)
458
+ return
459
+
460
+ # ---- GCP ----
461
+ if resource_type == "google_storage_bucket":
462
+ self._append_unique_service(result, f"gcs_bucket:{resource_name}", file)
463
+ return
464
+ if resource_type == "google_compute_firewall" and _has_open_cidr(body):
465
+ self._append_unique_entrypoint(
466
+ result, f"gcp_firewall_open:{resource_name}", file, line, ev,
467
+ )
468
+ return
469
+ if resource_type == "google_sql_database_instance":
470
+ db_version = (_extract_attr(body, "database_version") or "").lower()
471
+ kind = "sql"
472
+ if "postgres" in db_version:
473
+ kind = "postgresql"
474
+ elif "mysql" in db_version:
475
+ kind = "mysql"
476
+ elif "sqlserver" in db_version:
477
+ kind = "sqlserver"
478
+ self._append_unique_database(result, kind, file, line, ev)
479
+ return
480
+
481
+ # ---------- Append helpers ----------
482
+
483
+ @staticmethod
484
+ def _append_unique_route(result: ScanResult, path: str, method: str, file: str, line: int | None) -> None:
485
+ key = (path, method, file)
486
+ if any((item.path, item.method, item.file) == key for item in result.routes):
487
+ return
488
+ result.routes.append(Route(path=path, method=method, file=file, line=line))
489
+
490
+ @staticmethod
491
+ def _append_unique_database(result: ScanResult, kind: str, file: str, line: int | None, evidence: str | None) -> None:
492
+ key = (kind, file)
493
+ if any((item.kind, item.file) == key for item in result.databases):
494
+ return
495
+ result.databases.append(DatabaseHint(kind=kind, file=file, line=line, evidence_text=evidence))
496
+
497
+ @staticmethod
498
+ def _append_unique_auth(result: ScanResult, hint: str, file: str, line: int | None, evidence: str | None, confidence: float) -> None:
499
+ key = (hint, file)
500
+ if any((item.hint, item.file) == key for item in result.auth_hints):
501
+ return
502
+ result.auth_hints.append(AuthHint(hint=hint, file=file, line=line, evidence_text=evidence, confidence=confidence))
503
+
504
+ @staticmethod
505
+ def _append_unique_secret(result: ScanResult, name: str, file: str, line: int | None, evidence: str | None) -> None:
506
+ key = (name, file)
507
+ if any((item.name, item.file) == key for item in result.secret_hints):
508
+ return
509
+ result.secret_hints.append(SecretHint(name=name, file=file, line=line, evidence_text=evidence, confidence=0.85))
510
+
511
+ @staticmethod
512
+ def _append_unique_external(result: ScanResult, target: str, file: str, line: int | None, evidence: str | None) -> None:
513
+ key = (target, file)
514
+ if any((item.target, item.file) == key for item in result.external_calls):
515
+ return
516
+ result.external_calls.append(ExternalCall(target=target, file=file, line=line, evidence_text=evidence))
517
+
518
+ @staticmethod
519
+ def _append_unique_framework(result: ScanResult, hint: str, file: str, line: int | None, evidence: str | None) -> None:
520
+ key = (hint, file)
521
+ if any((item.hint, item.file) == key for item in result.framework_hints):
522
+ return
523
+ result.framework_hints.append(FrameworkHint(hint=hint, file=file, line=line, evidence_text=evidence))
524
+
525
+ @staticmethod
526
+ def _append_unique_entrypoint(result: ScanResult, hint: str, file: str, line: int | None, evidence: str | None) -> None:
527
+ key = (hint, file)
528
+ if any((item.hint, item.file) == key for item in result.entrypoint_hints):
529
+ return
530
+ result.entrypoint_hints.append(EntrypointHint(hint=hint, file=file, line=line, evidence_text=evidence))
531
+
532
+ @staticmethod
533
+ def _append_unique_service(result: ScanResult, hint: str, file: str) -> None:
534
+ key = (hint, file)
535
+ if any((item.hint, item.file) == key for item in result.service_hints):
536
+ return
537
+ result.service_hints.append(ServiceHint(hint=hint, file=file))
538
+
539
+
540
+ __all__ = ["TerraformAnalyzer"]
@@ -0,0 +1,30 @@
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
+ AttackMapAnalyzerProtocol = AnalyzerProtocol
17
+
18
+ __all__ = [
19
+ "AnalyzerMetadata",
20
+ "AttackMapAnalyzerProtocol",
21
+ "Route",
22
+ "ExternalCall",
23
+ "DatabaseHint",
24
+ "AuthHint",
25
+ "EntrypointHint",
26
+ "FrameworkHint",
27
+ "ServiceHint",
28
+ "SecretHint",
29
+ "ScanResult",
30
+ ]
@@ -0,0 +1,94 @@
1
+ Metadata-Version: 2.4
2
+ Name: attackmap-analyzer-terraform
3
+ Version: 0.1.0
4
+ Summary: Terraform / HCL infrastructure-as-code analyzer plugin for AttackMap (AWS, Azure, GCP resources; IAM wildcards; open security groups; secret resources).
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-terraform
10
+ Project-URL: Repository, https://github.com/mlaify/attackmap-analyzer-terraform
11
+ Project-URL: Issues, https://github.com/mlaify/attackmap-analyzer-terraform/issues
12
+ Project-URL: Changelog, https://github.com/mlaify/attackmap-analyzer-terraform/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-terraform
42
+
43
+ Terraform / HCL infrastructure-as-code analyzer for [AttackMap](https://github.com/mlaify/AttackMap).
44
+
45
+ This analyzer is shaped differently from language analyzers — Terraform doesn't have routes in the application sense. Instead, it extracts:
46
+
47
+ - **Public ingress** — security groups and firewall rules with `0.0.0.0/0`, Lambda Function URLs with no auth, API Gateway methods with `authorization = "NONE"`, S3 buckets with public ACLs or disabled public-access blocks → `entrypoint_hints`
48
+ - **Asset inventory** — S3 buckets, Azure storage accounts, GCS buckets, KMS keys, Cognito user pools → `service_hints`
49
+ - **Databases** — `aws_db_instance` and `aws_rds_cluster` (engine-aware: postgres / mysql / oracle / sqlserver / mariadb), `aws_dynamodb_table`, `aws_elasticache_*`, `aws_documentdb_*`, Azure PostgreSQL/MySQL/CosmosDB, GCP Cloud SQL → `database_hints`
50
+ - **Secrets** — `aws_secretsmanager_secret`, `aws_ssm_parameter` (SecureString), `azurerm_key_vault`, plus `variable` blocks marked `sensitive = true` or with secret-shaped names (`*secret*`, `*token*`, `*password*`, `*key*`) → `secret_hints`
51
+ - **IAM blast radius** — `aws_iam_*_policy` resources with wildcard `Action = "*"` or `Resource = "*"` → `auth_hints` with confidence 0.7
52
+ - **Cognito** — `aws_cognito_user_pool` → `auth_hints`
53
+ - **Modules** — `module "x" { source = ... }` → `service_hints` keyed `module:x`
54
+ - **API Gateway v2 routes** — `aws_apigatewayv2_route` with `route_key = "POST /charges"` → actual `Route` entries
55
+
56
+ All emissions populate AttackMap's Signal v2 fields (line numbers + evidence snippets) so downstream insights can cite `infra/main.tf:NN`.
57
+
58
+ ## Install
59
+
60
+ ```bash
61
+ pip install git+https://github.com/mlaify/attackmap-analyzer-terraform.git
62
+ ```
63
+
64
+ The analyzer is auto-discovered by AttackMap via the `attackmap.analyzers` entry-point group.
65
+
66
+ ## Usage with AttackMap
67
+
68
+ ```bash
69
+ # Auto-discovered when installed:
70
+ attackmap analyze /path/to/terraform/repo
71
+
72
+ # Or invoke explicitly:
73
+ attackmap analyze /path/to/terraform/repo --module terraform
74
+ ```
75
+
76
+ ## Detection
77
+
78
+ `detect()` returns true when any `.tf`, `.tf.json`, or `.tfvars` file is present in the tree, ignoring `.terraform/`, `.git/`, `node_modules/`, and `vendor/`.
79
+
80
+ ## HCL block parsing
81
+
82
+ The analyzer parses HCL block bodies via brace-depth counting (with string-literal awareness so `"{" inside strings"` doesn't throw off the counter). Nested blocks like multiple `ingress { }` blocks inside a security group are handled correctly. **Variable interpolation** (`${var.foo}`, `aws_iam_role.app.id`) is **not resolved** — string literals and direct attribute values are what get extracted.
83
+
84
+ ## Coverage notes
85
+
86
+ - **AWS** is the most thoroughly covered provider. Azure and GCP have basic coverage (NSG/firewall open ingress, Storage Account / GCS bucket as service hints, PostgreSQL/MySQL/CosmosDB/CloudSQL as databases) — extend per resource type as needed.
87
+ - **IAM wildcard detection** matches both JSON-shaped (`"Action": "*"`) and HCL-shaped (`Action = "*"`) policy bodies. It does not currently look across separate `aws_iam_policy_document` data sources — that's roadmap.
88
+ - **API Gateway v1** routing is partial — only individual `aws_api_gateway_method` resources emit entrypoint hints. Path joining across `aws_api_gateway_resource` chains is not yet implemented (use API Gateway v2 / `aws_apigatewayv2_route` for full path+method extraction).
89
+ - **Lambda Function URLs** with `authorization_type = "NONE"` are flagged as open entrypoints. IAM-authorized URLs are emitted with the regular `lambda_url:` prefix.
90
+ - **Database `publicly_accessible = true`** on `aws_db_instance` produces a separate `rds_publicly_accessible:` entrypoint hint in addition to the standard database hint.
91
+
92
+ ## License
93
+
94
+ MIT
@@ -0,0 +1,9 @@
1
+ attackmap_analyzer_terraform/__init__.py,sha256=FL2a-KC-1kQAUIpLx-oY5ZcZqHuR6AWjZXOfylE4sKw,73
2
+ attackmap_analyzer_terraform/analyzer.py,sha256=vz9ufP_9A4guBwgNKXJVx5Crggao8af6EvFFSIEK0ak,23081
3
+ attackmap_analyzer_terraform/contracts.py,sha256=dsveFe7szz7xceev0PIfyc5jQlNiES0whsdxwu9D7YI,578
4
+ attackmap_analyzer_terraform-0.1.0.dist-info/licenses/LICENSE,sha256=vtPQVGUyxq359j0JmD3_eJaXyHmaHyjzaMOtaLwJc88,1097
5
+ attackmap_analyzer_terraform-0.1.0.dist-info/METADATA,sha256=Q1vMc09zEd_Aedg_4yKxXYfpDr48MPBnhLhcGuRrHKg,5736
6
+ attackmap_analyzer_terraform-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
7
+ attackmap_analyzer_terraform-0.1.0.dist-info/entry_points.txt,sha256=Z6ugFFGqxUo7luRMtwwx-2LteLuwZhya_Pi_VdVPITY,81
8
+ attackmap_analyzer_terraform-0.1.0.dist-info/top_level.txt,sha256=oG5SmotBIY4bE-wXhpT8DQyYWKOwInrdgZkM7y0Rb9M,29
9
+ attackmap_analyzer_terraform-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [attackmap.analyzers]
2
+ terraform = attackmap_analyzer_terraform:TerraformAnalyzer
@@ -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_terraform