test_ipv6_closed.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. """IPv6 stays closed: a static, offline scan of every .tf file in modules/ and stacks/.
  2. "Zero inbound" is only true if IPv6 is closed too. A DigitalOcean droplet made
  3. with `ipv6 = true` gets a public IPv6 address, and an inbound source of `::/0`
  4. would open it. Nothing else fails if a later change flips either, so this does.
  5. The scan reads resource blocks (not prose), so the word "ipv6" or a `::/0` in a
  6. comment or a description never trips it. It reuses the block-skipping helpers
  7. of scripts/hcl_variables.py and fails closed: a file that cannot be read, or a
  8. block that cannot be parsed, is a failure that names its path.
  9. Add a rule by adding one line to RULES (or FORBIDDEN_RESOURCES).
  10. Scope: the rules guard INBOUND sources. The DigitalOcean firewall's outbound
  11. rules list `::/0` as a destination on purpose (egress on ports 443, 80, 53,
  12. 123 only); that is not exposure and is not flagged.
  13. Limit: a `::/0` that reaches an inbound rule only through a `locals` value is
  14. not followed. The inbound attribute itself must be a literal, so a reference
  15. there fails as unprovable instead.
  16. """
  17. from __future__ import annotations
  18. import json
  19. import re
  20. import sys
  21. from collections.abc import Callable, Iterator
  22. from dataclasses import dataclass
  23. from pathlib import Path
  24. ROOT = Path(__file__).resolve().parent.parent
  25. sys.path.insert(0, str(ROOT / "scripts"))
  26. from hcl_variables import ( # sys.path is set up just above
  27. NAME_RE,
  28. OPEN,
  29. HclError,
  30. _read_balanced,
  31. _skip_heredoc,
  32. _skip_string,
  33. _skip_ws_comments,
  34. )
  35. IPV6_LITERAL = re.compile(r"^[0-9A-Fa-f:.]*:[0-9A-Fa-f:.]*:[0-9A-Fa-f:.]*(/[0-9]{1,3})?$")
  36. # ---------------------------------------------------------------- reading ----
  37. def strip_comments(expr: str) -> str:
  38. """The expression without #, // and /* */ comments; strings are kept whole."""
  39. out: list[str] = []
  40. i = 0
  41. while i < len(expr):
  42. if expr[i] == '"':
  43. end = _skip_string(expr, i, lenient=True)
  44. out.append(expr[i:end])
  45. i = end
  46. continue
  47. j = _skip_ws_comments(expr, i, newlines=False)
  48. if j != i and expr[i] in "#/":
  49. i = j
  50. continue
  51. out.append(expr[i])
  52. i += 1
  53. return "".join(out).strip()
  54. def _expression_end(text: str, i: int) -> int:
  55. while i < len(text) and text[i] != "\n":
  56. c = text[i]
  57. if c == '"':
  58. i = _skip_string(text, i, lenient=True)
  59. elif c in OPEN:
  60. i = _read_balanced(text, i, lenient=True)
  61. elif c == "#" or text.startswith("//", i) or text.startswith("/*", i):
  62. i = _skip_ws_comments(text, i, newlines=False)
  63. elif text.startswith("<<", i):
  64. i = _skip_heredoc(text, i)
  65. else:
  66. i += 1
  67. return i
  68. @dataclass
  69. class Block:
  70. kind: str
  71. labels: list[str]
  72. attrs: list[tuple[str, str]]
  73. blocks: list[Block]
  74. def parse_body(text: str, where: str) -> tuple[list[tuple[str, str]], list[Block]]:
  75. attrs: list[tuple[str, str]] = []
  76. blocks: list[Block] = []
  77. i = 0
  78. while True:
  79. i = _skip_ws_comments(text, i)
  80. if i >= len(text):
  81. return attrs, blocks
  82. m = NAME_RE.match(text, i)
  83. if not m:
  84. raise HclError(f"unexpected text {text[i : i + 30]!r} in {where}")
  85. name = m.group(0)
  86. i = _skip_ws_comments(text, m.end(), newlines=False)
  87. if text.startswith("=", i) and not text.startswith("==", i):
  88. start = _skip_ws_comments(text, i + 1, newlines=False)
  89. end = _expression_end(text, start)
  90. expr = strip_comments(text[start:end])
  91. if not expr:
  92. raise HclError(f"{name} has an empty value in {where}")
  93. attrs.append((name, expr))
  94. i = end
  95. continue
  96. labels: list[str] = []
  97. while text.startswith('"', i):
  98. end = _skip_string(text, i, lenient=True)
  99. labels.append(json.loads(text[i:end]))
  100. i = _skip_ws_comments(text, end, newlines=False)
  101. if not text.startswith("{", i):
  102. raise HclError(f"cannot read {name!r} in {where}")
  103. end = _read_balanced(text, i, lenient=True)
  104. inner_attrs, inner_blocks = parse_body(text[i + 1 : end - 1], f"{where}/{name}")
  105. blocks.append(Block(name, labels, inner_attrs, inner_blocks))
  106. i = end
  107. def parse_file(text: str, where: str) -> list[Block]:
  108. """Top-level blocks of one .tf file (a top-level attribute is an HclError)."""
  109. attrs, blocks = parse_body(text, where)
  110. if attrs:
  111. raise HclError(f"top-level attribute {attrs[0][0]} is not understood")
  112. return blocks
  113. def walk(block: Block, path: tuple[str, ...] = ()) -> Iterator[tuple[tuple[str, ...], str, str]]:
  114. """(enclosing block names, attribute, expression) at every depth.
  115. `dynamic "x"` counts as a block named x, and its `content` is transparent.
  116. """
  117. for name, expr in block.attrs:
  118. yield path, name, expr
  119. for sub in block.blocks:
  120. if sub.kind == "dynamic" and sub.labels:
  121. attrs = list(sub.attrs)
  122. blocks: list[Block] = []
  123. for inner in sub.blocks:
  124. if inner.kind == "content":
  125. attrs += inner.attrs
  126. blocks += inner.blocks
  127. else:
  128. blocks.append(inner)
  129. sub = Block(sub.labels[0], [], attrs, blocks)
  130. yield from walk(sub, path + (sub.kind,))
  131. def attr_in(block: Block, name: str) -> str | None:
  132. return next((e for n, e in block.attrs if n == name), None)
  133. # ------------------------------------------------------------------ rules ----
  134. def is_off(expr: str) -> bool:
  135. return expr in ("false", "0", "null", "[]")
  136. def is_false(expr: str) -> bool:
  137. return expr == "false"
  138. def is_null(expr: str) -> bool:
  139. return expr == "null"
  140. # References that are provably IPv4-only because the variable's own validation
  141. # rejects any ':' and 0.0.0.0/0. Empty today (the edge firewall has no variable
  142. # source; iperf3 stays closed until its own stack). Adding a name here is a
  143. # reviewed decision, and the variable's validation needs a test beside it.
  144. IPV4_ONLY_REFERENCES: frozenset[str] = frozenset()
  145. def literal_without_ipv6(expr: str) -> bool:
  146. """A literal list of strings, none of them an IPv6 range. A reference is unprovable,
  147. except the few in IPV4_ONLY_REFERENCES."""
  148. if expr in IPV4_ONLY_REFERENCES:
  149. return True
  150. strings = re.findall(r'"((?:[^"\\]|\\.)*)"', expr)
  151. rest = re.sub(r'"(?:[^"\\]|\\.)*"', "", expr)
  152. return not re.search(r"[A-Za-z_]", rest) and not any(IPV6_LITERAL.match(s) for s in strings)
  153. @dataclass(frozen=True)
  154. class Rule:
  155. name: str
  156. types: tuple[str, ...] # resource types the rule applies to
  157. attr: str # attribute that is checked
  158. ok: Callable[[str], bool] # accepts the (comment-free) expression text
  159. required: bool = False # absent counts as a failure
  160. within: str | None = None # only inside a nested block of this name
  161. when: Callable[[Block], bool] | None = None # only for resources where this holds
  162. def _is_ingress_type(block: Block) -> bool:
  163. return attr_in(block, "type") == '"ingress"'
  164. _MACHINES = ("aws_instance", "aws_launch_template", "aws_network_interface")
  165. # One line per rule: for this resource type, this attribute must satisfy ok.
  166. RULES: tuple[Rule, ...] = (
  167. # 1. a droplet must state ipv6 = false
  168. Rule("droplet-ipv6-false", ("digitalocean_droplet",), "ipv6", is_false, required=True),
  169. # 2. no IPv6 source on an inbound rule
  170. Rule("do-firewall-inbound-source", ("digitalocean_firewall",), "source_addresses", literal_without_ipv6, within="inbound_rule"),
  171. Rule("aws-sg-ingress-source", ("aws_security_group",), "ipv6_cidr_blocks", is_off, within="ingress"),
  172. Rule("aws-ingress-rule-source", ("aws_vpc_security_group_ingress_rule",), "cidr_ipv6", is_null),
  173. Rule("aws-sg-rule-ingress-source", ("aws_security_group_rule",), "ipv6_cidr_blocks", is_off, when=_is_ingress_type),
  174. # 3. no IPv6 plumbing in the VPC or a subnet
  175. Rule("vpc-generated-ipv6", ("aws_vpc",), "assign_generated_ipv6_cidr_block", is_off),
  176. Rule("vpc-ipv6-cidr", ("aws_vpc", "aws_subnet"), "ipv6_cidr_block", is_null),
  177. Rule("vpc-ipv6-netmask", ("aws_vpc", "aws_subnet"), "ipv6_netmask_length", is_off),
  178. Rule("subnet-generated-ipv6", ("aws_subnet",), "assign_ipv6_address_on_creation", is_off),
  179. Rule("subnet-ipv6-native", ("aws_subnet",), "ipv6_native", is_off),
  180. # 4. no IPv6 address on a machine
  181. Rule("machine-ipv6-count", _MACHINES, "ipv6_address_count", is_off),
  182. Rule("machine-ipv6-addresses", _MACHINES, "ipv6_addresses", is_off),
  183. )
  184. # Resource types that must not exist at all (IPv6 plumbing).
  185. FORBIDDEN_RESOURCES = frozenset(
  186. {
  187. "aws_vpc_ipv6_cidr_block_association",
  188. "aws_egress_only_internet_gateway",
  189. }
  190. )
  191. def check_block(block: Block, where: str) -> list[str]:
  192. if block.kind != "resource":
  193. return []
  194. if len(block.labels) != 2:
  195. return [f"{where}: resource block without type and name labels"]
  196. rtype, rname = block.labels
  197. out: list[str] = []
  198. if rtype in FORBIDDEN_RESOURCES:
  199. out.append(f"{where}: {rtype}.{rname}: IPv6 plumbing must not exist in this repository (forbidden-resource)")
  200. for rule in RULES:
  201. if rtype not in rule.types or (rule.when and not rule.when(block)):
  202. continue
  203. hits = [e for p, n, e in walk(block) if n == rule.attr and (rule.within is None or rule.within in p)]
  204. if not hits and rule.required:
  205. out.append(f"{where}: {rtype}.{rname}: {rule.attr} is not stated, it must be set explicitly (breaks {rule.name})")
  206. for expr in hits:
  207. if not rule.ok(expr):
  208. out.append(f"{where}: {rtype}.{rname}: {rule.attr} = {expr} (breaks {rule.name}; IPv6 must stay closed)")
  209. return out
  210. def scan_text(text: str, where: str) -> list[str]:
  211. try:
  212. blocks = parse_file(text, where)
  213. except HclError as exc:
  214. return [f"{where}: cannot parse (fail closed): {exc}"]
  215. problems: list[str] = []
  216. for block in blocks:
  217. problems.extend(check_block(block, where))
  218. return problems
  219. def tf_files(root: Path) -> list[Path]:
  220. found: list[Path] = []
  221. for top in ("modules", "stacks"):
  222. found.extend(p for p in sorted((root / top).rglob("*.tf")) if ".terraform" not in p.parts)
  223. return found
  224. def scan_tree(root: Path) -> list[str]:
  225. problems: list[str] = []
  226. for tf in tf_files(root):
  227. rel = tf.relative_to(root).as_posix()
  228. try:
  229. text = tf.read_text(encoding="utf-8")
  230. except (OSError, UnicodeDecodeError) as exc:
  231. problems.append(f"{rel}: cannot read (fail closed): {exc}")
  232. continue
  233. problems.extend(scan_text(text, rel))
  234. return problems
  235. def count_resources(root: Path, rtype: str) -> int:
  236. n = 0
  237. for tf in tf_files(root):
  238. for b in parse_file(tf.read_text(encoding="utf-8"), tf.name):
  239. n += b.kind == "resource" and b.labels[:1] == [rtype]
  240. return n
  241. # ------------------------------------------------------------- real tree ----
  242. def test_the_repository_keeps_ipv6_closed():
  243. assert tf_files(ROOT), "no .tf files under modules/ or stacks/: the scan would prove nothing"
  244. problems = scan_tree(ROOT)
  245. assert not problems, "IPv6 exposure:\n" + "\n".join(problems)
  246. def test_the_scan_sees_the_resources_it_guards():
  247. # Guard against a silent no-op: the real tree has these resources.
  248. for rtype in ("digitalocean_droplet", "digitalocean_firewall", "aws_vpc", "aws_instance", "aws_security_group"):
  249. assert count_resources(ROOT, rtype) >= 1, f"no {rtype} found: the scan lost its target"
  250. # -------------------------------------------------------------- fixtures ----
  251. BAD = {
  252. "droplet-ipv6-true": 'resource "digitalocean_droplet" "x" {\n ipv6 = true\n}\n',
  253. "droplet-ipv6-absent": 'resource "digitalocean_droplet" "x" {\n name = "a"\n}\n',
  254. "droplet-ipv6-reference": 'resource "digitalocean_droplet" "x" {\n ipv6 = var.v6\n}\n',
  255. "do-firewall-ipv6-any": 'resource "digitalocean_firewall" "x" {\n inbound_rule {\n protocol = "tcp"\n source_addresses = ["::/0"]\n }\n}\n',
  256. "do-firewall-ipv6-cidr-dynamic": 'resource "digitalocean_firewall" "x" {\n dynamic "inbound_rule" {\n for_each = []\n content {\n source_addresses = ["2001:db8::/32"]\n }\n }\n}\n',
  257. "do-firewall-other-reference-in-dynamic": 'resource "digitalocean_firewall" "x" {\n dynamic "inbound_rule" {\n for_each = []\n content {\n source_addresses = var.iperf3_allowed_sources_v6\n }\n }\n}\n',
  258. "do-firewall-source-reference": 'resource "digitalocean_firewall" "x" {\n inbound_rule {\n source_addresses = var.sources\n }\n}\n',
  259. "aws-sg-inline-ingress": 'resource "aws_security_group" "x" {\n ingress {\n ipv6_cidr_blocks = ["::/0"]\n }\n}\n',
  260. "aws-ingress-rule": 'resource "aws_vpc_security_group_ingress_rule" "x" {\n cidr_ipv6 = "::/0"\n}\n',
  261. "aws-sg-rule-ingress": 'resource "aws_security_group_rule" "x" {\n type = "ingress"\n ipv6_cidr_blocks = ["::/0"]\n}\n',
  262. "vpc-generated": 'resource "aws_vpc" "x" {\n assign_generated_ipv6_cidr_block = true\n}\n',
  263. "vpc-cidr": 'resource "aws_vpc" "x" {\n ipv6_cidr_block = "2001:db8::/56"\n}\n',
  264. "vpc-netmask": 'resource "aws_vpc" "x" {\n ipv6_netmask_length = 56\n}\n',
  265. "subnet-cidr": 'resource "aws_subnet" "x" {\n ipv6_cidr_block = "2001:db8::/64"\n}\n',
  266. "subnet-on-creation": 'resource "aws_subnet" "x" {\n assign_ipv6_address_on_creation = true\n}\n',
  267. "subnet-native": 'resource "aws_subnet" "x" {\n ipv6_native = true\n}\n',
  268. "association": 'resource "aws_vpc_ipv6_cidr_block_association" "x" {\n}\n',
  269. "egress-only-gateway": 'resource "aws_egress_only_internet_gateway" "x" {\n vpc_id = "v"\n}\n',
  270. "instance-count": 'resource "aws_instance" "x" {\n ipv6_address_count = 1\n}\n',
  271. "instance-addresses": 'resource "aws_instance" "x" {\n ipv6_addresses = ["2001:db8::1"]\n}\n',
  272. "template-nested-count": 'resource "aws_launch_template" "x" {\n network_interfaces {\n ipv6_address_count = 2\n }\n}\n',
  273. }
  274. GOOD = {
  275. "droplet": 'resource "digitalocean_droplet" "x" {\n ipv6 = false\n}\n',
  276. "firewall-tags-only": 'resource "digitalocean_firewall" "x" {\n inbound_rule {\n source_tags = ["a"]\n }\n outbound_rule {\n destination_addresses = ["0.0.0.0/0", "::/0"]\n }\n}\n',
  277. "aws-sg": 'resource "aws_security_group" "x" {\n description = "no ::/0 and no ipv6 here"\n ingress {\n ipv6_cidr_blocks = []\n }\n}\n',
  278. "aws-ingress-rule": 'resource "aws_vpc_security_group_ingress_rule" "x" {\n cidr_ipv4 = "10.0.0.0/8"\n}\n',
  279. "aws-sg-rule-egress": 'resource "aws_security_group_rule" "x" {\n type = "egress"\n ipv6_cidr_blocks = ["::/0"]\n}\n',
  280. "vpc": 'resource "aws_vpc" "x" {\n assign_generated_ipv6_cidr_block = false\n}\n',
  281. "subnet": 'resource "aws_subnet" "x" {\n ipv6_native = false\n ipv6_cidr_block = null\n}\n',
  282. "instance": 'resource "aws_instance" "x" {\n ipv6_address_count = 0\n}\n',
  283. "templated-strings": 'resource "digitalocean_droplet" "x" {\n name = "${var.layer}-a"\n ipv6 = false\n}\n',
  284. }
  285. PROSE_ONLY = (
  286. "# an ipv6 = true droplet and a ::/0 source would be bad\n"
  287. 'variable "v" {\n type = string\n default = "ipv6 ::/0"\n description = "never ::/0 or ipv6 = true"\n}\n'
  288. '/* block comment: ipv6 = true, source_addresses = ["::/0"] */\n'
  289. 'resource "digitalocean_droplet" "x" {\n'
  290. " # ipv6 = true is wrong\n"
  291. " ipv6 = false // ipv6 = true elsewhere\n"
  292. ' name = "about ::/0 and ipv6 = true"\n'
  293. "}\n"
  294. 'resource "digitalocean_firewall" "x" {\n'
  295. ' description = "source_addresses = [::/0]"\n'
  296. " inbound_rule {\n"
  297. ' # source_addresses = ["::/0"]\n'
  298. ' source_tags = ["t"]\n'
  299. " }\n"
  300. "}\n"
  301. )
  302. def _write(root: Path, top: str, name: str, text: str) -> None:
  303. d = root / top / name
  304. d.mkdir(parents=True)
  305. (d / "main.tf").write_text(text)
  306. def test_each_hostile_fixture_fails(tmp_path):
  307. for name, text in BAD.items():
  308. root = tmp_path / name
  309. _write(root, "modules", "m", text)
  310. problems = scan_tree(root)
  311. assert problems, f"{name}: a violating fixture passed the IPv6 check"
  312. assert all(p.startswith("modules/m/main.tf") for p in problems), problems
  313. def test_each_compliant_fixture_passes(tmp_path):
  314. for name, text in GOOD.items():
  315. root = tmp_path / name
  316. _write(root, "stacks", "s", text)
  317. assert scan_tree(root) == [], name
  318. def test_ipv6_only_in_comments_descriptions_and_defaults_passes(tmp_path):
  319. _write(tmp_path, "modules", "m", PROSE_ONLY)
  320. assert scan_tree(tmp_path) == []
  321. def test_every_rule_has_a_hostile_fixture():
  322. # A new rule cannot be added without a fixture that proves it bites.
  323. hit: set[str] = set()
  324. for text in BAD.values():
  325. for problem in scan_text(text, "f.tf"):
  326. hit.update(re.findall(r"breaks ([a-z0-9-]+)", problem))
  327. missing = {r.name for r in RULES} - hit
  328. assert not missing, f"rules without a failing fixture: {sorted(missing)}"
  329. forbidden = [p for t in BAD.values() for p in scan_text(t, "f.tf") if "forbidden-resource" in p]
  330. assert len(forbidden) >= len(FORBIDDEN_RESOURCES)
  331. def test_an_unreadable_or_unparsable_file_fails_closed(tmp_path):
  332. (tmp_path / "modules" / "m").mkdir(parents=True)
  333. bad = tmp_path / "modules" / "m" / "broken.tf"
  334. bad.write_text('resource "digitalocean_droplet" "x" {\n ipv6 = false\n')
  335. problems = scan_tree(tmp_path)
  336. assert problems and "modules/m/broken.tf" in problems[0] and "fail closed" in problems[0]
  337. bad.write_bytes(b"\xff\xfe resource")
  338. problems = scan_tree(tmp_path)
  339. assert problems and "modules/m/broken.tf" in problems[0] and "cannot read" in problems[0]