zero_ports_check.py 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063
  1. #!/usr/bin/env python3
  2. """External zero-open-ports check for the stage 1 connectors (issue #91).
  3. Run by hand, from a machine that is NOT in the VPC, after any firewall or
  4. droplet change. It attempts one TCP connect to every port (1 to 65535) of every
  5. connector's public address and passes only if every attempt timed out: no
  6. answer at all, as seen from this network.
  7. There is no way to give it an address. It takes no host, address, target or
  8. file argument and reads no environment variable except DIGITALOCEAN_TOKEN (the
  9. credential). Targets come only from the DigitalOcean API, read-only, and only
  10. after discovery is complete: a droplet is a target only if it carries the
  11. baseline tag AND is a member of the project `clouds-against-humanity`, and the
  12. operator states how many such droplets must exist (--expect-connectors N). The
  13. API is a trust anchor: a lying API defeats this rail, and a person who edits
  14. this script defeats it too. The rails make the intended use the only easy one.
  15. Usage (the token comes from Doppler, in its own read-only config):
  16. doppler run -- python3 -I scripts/zero_ports_check.py --expect-connectors 2 [--region tor1] [--resource-key KEY] [--out PATH]
  17. Exit codes: 0 only if every expected address and every port was attempted
  18. exactly once and every attempt timed out; 1 if any port answered (a connection,
  19. or a refusal, which means something answered); 2 for everything else
  20. (discovery problems, a local error, unreachable, an inventory change,
  21. interruption, a report that could not be written).
  22. Output is a fixed set of strings and counts: connector labels (connector-1),
  23. never an address; the token never appears anywhere. TCP only, one vantage point,
  24. one moment in time. See docs/stages/01-access.md.
  25. Standard library only; spawns no subprocess.
  26. """
  27. from __future__ import annotations
  28. import argparse
  29. import concurrent.futures
  30. import errno
  31. import http.client
  32. import ipaddress
  33. import itertools
  34. import json
  35. import os
  36. import re
  37. import resource
  38. import socket
  39. import ssl
  40. import sys
  41. import threading
  42. import time
  43. import urllib.error
  44. import urllib.parse
  45. import urllib.request
  46. from collections.abc import Callable
  47. from dataclasses import dataclass, field
  48. from pathlib import Path
  49. API_ORIGIN = "https://api.digitalocean.com"
  50. PROJECT_NAME = "clouds-against-humanity"
  51. TOKEN_ENV = "DIGITALOCEAN_TOKEN"
  52. TAG_PREFIX = "cah-baseline-"
  53. CONTROL_TARGET = ("api.digitalocean.com", 443)
  54. MAX_BODY = 4 * 1024 * 1024
  55. MAX_PAGES = 20
  56. PER_PAGE = 200
  57. API_TIMEOUT = 15.0
  58. MAX_PORT = 65535
  59. ALL_PORTS = range(1, MAX_PORT + 1)
  60. NOFILE_MARGIN = 64
  61. OPEN = "open"
  62. REFUSED = "refused"
  63. TIMEOUT = "timeout"
  64. UNREACHABLE = "unreachable"
  65. LOCAL = "local_error"
  66. ERROR = "error"
  67. OPEN_CLEANUP = "open_cleanup_problem"
  68. REFUSED_CLEANUP = "refused_cleanup_problem"
  69. _CLEANUP_TAGGED = {OPEN: OPEN_CLEANUP, REFUSED: REFUSED_CLEANUP}
  70. _CLEANUP_BASE = {OPEN_CLEANUP: OPEN, REFUSED_CLEANUP: REFUSED}
  71. OUTCOMES = frozenset({OPEN, REFUSED, TIMEOUT, UNREACHABLE, LOCAL, ERROR, OPEN_CLEANUP, REFUSED_CLEANUP})
  72. _SAFE_ID = re.compile(r"[A-Za-z0-9-]{1,64}")
  73. _DROPLET_URN = re.compile(r"do:droplet:([0-9]{1,18})")
  74. _REGION = re.compile(r"[a-z0-9]{2,16}")
  75. # The same format stacks/00-foundation allows for resource_key.
  76. _RESOURCE_KEY = re.compile(r"[a-z][a-z0-9-]{1,23}")
  77. _TOKEN = re.compile(r"[\x21-\x7e]{8,256}")
  78. # Anything unexpected that is still a program or system fault, not a test assertion.
  79. _INTERNAL_ERRORS = (
  80. OSError,
  81. LookupError,
  82. ArithmeticError,
  83. ValueError,
  84. TypeError,
  85. AttributeError,
  86. RuntimeError,
  87. http.client.HTTPException,
  88. )
  89. class CheckError(Exception):
  90. """Every expected failure. The message is a fixed string: no URL, body or value."""
  91. class InventoryChanged(CheckError):
  92. pass
  93. class Interrupted(CheckError):
  94. pass
  95. # ----------------------------------------------------------------- transport
  96. class _Secret:
  97. __slots__ = ("_v",)
  98. def __init__(self, value: str) -> None:
  99. self._v = value
  100. def reveal(self) -> str:
  101. return self._v
  102. def __repr__(self) -> str:
  103. return "<redacted>"
  104. __str__ = __repr__
  105. class _RefuseRedirect(urllib.request.HTTPRedirectHandler):
  106. def redirect_request(self, *args, **kwargs): # urllib signature
  107. return None
  108. def _origin(url: str) -> tuple[str, str]:
  109. parts = urllib.parse.urlsplit(url)
  110. return parts.scheme, parts.netloc
  111. def build_opener() -> urllib.request.OpenerDirector:
  112. """No proxy from the environment, verified TLS, every redirect refused."""
  113. # debuglevel=0 is explicit: left unset, a handler copies http.client's class attribute, and an
  114. # importing process that set it to 1 would make urllib print the Authorization header.
  115. return urllib.request.build_opener(
  116. urllib.request.ProxyHandler({}),
  117. _RefuseRedirect(),
  118. urllib.request.HTTPHandler(debuglevel=0),
  119. urllib.request.HTTPSHandler(debuglevel=0, context=ssl.create_default_context()),
  120. )
  121. class ApiTransport:
  122. """Read-only GETs against one fixed origin. URLs are built here, never taken from a response."""
  123. def __init__(self, token: str, base_url: str = API_ORIGIN, max_body: int = MAX_BODY) -> None:
  124. if not isinstance(token, str) or not _TOKEN.fullmatch(token):
  125. raise CheckError("the API token is missing or malformed")
  126. if base_url != API_ORIGIN:
  127. # Test seam only (never reachable from the command line): loopback http.
  128. parts = urllib.parse.urlsplit(base_url)
  129. if parts.scheme != "http" or parts.hostname != "127.0.0.1":
  130. raise CheckError("refusing a non-default API origin")
  131. self._token = _Secret(token)
  132. self._base = base_url
  133. self._max_body = max_body
  134. self._opener = build_opener()
  135. def __repr__(self) -> str:
  136. return "ApiTransport(<redacted>)"
  137. def get(self, path: str, params: dict[str, str | int]) -> dict:
  138. url = self._base + path
  139. if params:
  140. url += "?" + urllib.parse.urlencode(sorted(params.items()))
  141. req = urllib.request.Request(url, method="GET") # fixed origin, checked above
  142. req.add_unredirected_header("Authorization", "Bearer " + self._token.reveal())
  143. req.add_unredirected_header("Accept", "application/json")
  144. # A sanitized error is raised only AFTER the except block has ended, so it carries
  145. # no __context__ or __cause__ that could still hold the request, the header or the body.
  146. failure = None
  147. raw = b""
  148. try:
  149. with self._opener.open(req, timeout=API_TIMEOUT) as resp:
  150. if _origin(resp.geturl()) != _origin(self._base):
  151. failure = "the API answered from an unexpected origin"
  152. elif resp.status != 200:
  153. failure = "the API answered with an unexpected status"
  154. else:
  155. raw = resp.read(self._max_body + 1)
  156. except urllib.error.HTTPError as exc:
  157. code = exc.code
  158. try:
  159. exc.close()
  160. except _INTERNAL_ERRORS:
  161. pass # cleanup trouble must not replace the sanitized error raised below
  162. if 300 <= code < 400:
  163. failure = "the API tried to redirect; redirects are refused"
  164. elif code in (401, 403):
  165. failure = "the API refused the token or its scopes"
  166. else:
  167. failure = "the API answered with an error status"
  168. except (urllib.error.URLError, OSError, http.client.HTTPException, ValueError):
  169. failure = "the API could not be reached or the connection failed"
  170. if failure is not None:
  171. raise CheckError(failure)
  172. if len(raw) > self._max_body:
  173. raise CheckError("the API response was larger than the limit")
  174. return _parse_json(raw)
  175. def _no_duplicates(pairs: list[tuple[str, object]]) -> dict:
  176. out: dict = {}
  177. for key, value in pairs:
  178. if key in out:
  179. raise ValueError("duplicate key")
  180. out[key] = value
  181. return out
  182. def _reject_constant(_name: str) -> None:
  183. raise ValueError("non-finite number")
  184. def _parse_json(raw: bytes) -> dict:
  185. data = None
  186. failed = False
  187. try:
  188. data = json.loads(
  189. raw.decode("utf-8"),
  190. object_pairs_hook=_no_duplicates,
  191. parse_constant=_reject_constant,
  192. )
  193. except (ValueError, RecursionError): # UnicodeDecodeError is a ValueError
  194. failed = True
  195. if failed:
  196. raise CheckError("the API response was not valid JSON")
  197. if not isinstance(data, dict):
  198. raise CheckError("the API response had an unexpected shape")
  199. return data
  200. # ----------------------------------------------------------------- discovery
  201. @dataclass(frozen=True)
  202. class Unit:
  203. """One address to scan. The address is never printed; the label is."""
  204. label: str
  205. address: str = field(repr=False)
  206. droplet_id: int = field(repr=False)
  207. @dataclass(frozen=True)
  208. class Inventory:
  209. units: tuple[Unit, ...]
  210. @property
  211. def labels(self) -> tuple[str, ...]:
  212. return tuple(u.label for u in self.units)
  213. def default_address_ok(addr: ipaddress.IPv4Address) -> bool:
  214. # is_global is True for multicast (224.0.0.0/4), so the other classes are excluded by name too.
  215. return addr.is_global and not (
  216. addr.is_multicast
  217. or addr.is_private
  218. or addr.is_loopback
  219. or addr.is_link_local
  220. or addr.is_reserved
  221. or addr.is_unspecified
  222. )
  223. def parse_public_ipv4(value: object, address_ok: Callable[[ipaddress.IPv4Address], bool]) -> str:
  224. """JSON string, canonical dotted quad, parsed from a str only, and public."""
  225. if not isinstance(value, str):
  226. raise CheckError("an address was not a JSON string")
  227. addr = None
  228. try:
  229. addr = ipaddress.IPv4Address(value)
  230. except ValueError:
  231. pass
  232. if addr is None:
  233. raise CheckError("an address was not a dotted-quad IPv4 address")
  234. if str(addr) != value:
  235. raise CheckError("an address was not in canonical form")
  236. if not address_ok(addr):
  237. raise CheckError("an address was not a public address")
  238. return value
  239. def _is_int(value: object) -> bool:
  240. return isinstance(value, int) and not isinstance(value, bool)
  241. def _fetch_all(transport, path: str, params: dict, key: str, ident: str) -> list[dict]:
  242. """Follow pages with locally built requests; never follow a returned URL."""
  243. items: list[dict] = []
  244. seen: set = set()
  245. total = None
  246. for page in range(1, MAX_PAGES + 1):
  247. data = transport.get(path, {**params, "page": page, "per_page": PER_PAGE})
  248. batch = data.get(key)
  249. if not isinstance(batch, list) or not all(isinstance(i, dict) for i in batch):
  250. raise CheckError("an API listing had an unexpected shape")
  251. meta = data.get("meta")
  252. if not isinstance(meta, dict) or not _is_int(meta.get("total")) or meta["total"] < 0:
  253. raise CheckError("an API listing had no usable total")
  254. if total is not None and meta["total"] != total:
  255. raise CheckError("an API listing total changed between pages")
  256. total = meta["total"]
  257. for item in batch:
  258. ident_value = item.get(ident)
  259. if not isinstance(ident_value, (str, int)) or isinstance(ident_value, bool):
  260. raise CheckError("an API listing item had no usable identifier")
  261. if ident_value in seen:
  262. raise CheckError("an API listing repeated an item")
  263. seen.add(ident_value)
  264. items.extend(batch)
  265. links = data.get("links")
  266. pages = links.get("pages") if isinstance(links, dict) else None
  267. more = bool(pages.get("next")) if isinstance(pages, dict) else False
  268. if not more:
  269. break
  270. if not batch:
  271. raise CheckError("an API listing promised more pages after an empty page")
  272. else:
  273. raise CheckError("an API listing exceeded the page limit")
  274. if len(items) != total:
  275. raise CheckError("an API listing total contradicts its pages")
  276. return items
  277. def discover(
  278. transport,
  279. expected: int,
  280. region: str = "tor1",
  281. address_ok: Callable[[ipaddress.IPv4Address], bool] = default_address_ok,
  282. resource_key: str = "",
  283. ) -> Inventory:
  284. """All API reads, strict parsing and the intersection. Raises CheckError; opens no socket."""
  285. if not _is_int(expected) or expected < 1:
  286. raise CheckError("--expect-connectors must be at least 1")
  287. if not isinstance(region, str) or not _REGION.fullmatch(region):
  288. raise CheckError("the region is malformed")
  289. if not isinstance(resource_key, str) or (
  290. resource_key != "" and not _RESOURCE_KEY.fullmatch(resource_key)
  291. ):
  292. raise CheckError("the resource key is malformed")
  293. # The stack names the tag from resource_key when set, else from the region.
  294. tag = TAG_PREFIX + (resource_key or region)
  295. projects = _fetch_all(transport, "/v2/projects", {}, "projects", "id")
  296. named = [p for p in projects if p.get("name") == PROJECT_NAME]
  297. if len(named) != 1:
  298. raise CheckError("the project was not found exactly once")
  299. project_id = named[0]["id"]
  300. if not isinstance(project_id, str) or not _SAFE_ID.fullmatch(project_id):
  301. raise CheckError("the project identifier was malformed")
  302. resources = _fetch_all(
  303. transport, f"/v2/projects/{project_id}/resources", {}, "resources", "urn"
  304. )
  305. project_droplets: set[int] = set()
  306. for res in resources:
  307. urn = res["urn"]
  308. if not isinstance(urn, str):
  309. raise CheckError("a project resource identifier was malformed")
  310. match = _DROPLET_URN.fullmatch(urn)
  311. if match:
  312. project_droplets.add(int(match.group(1)))
  313. tagged = _fetch_all(transport, "/v2/droplets", {"tag_name": tag}, "droplets", "id")
  314. by_id: dict[int, dict] = {}
  315. for droplet in tagged:
  316. if not _is_int(droplet["id"]):
  317. raise CheckError("a droplet identifier was not an integer")
  318. _require_baseline_tag(droplet, tag)
  319. by_id[droplet["id"]] = droplet
  320. if project_droplets - set(by_id):
  321. raise CheckError("a droplet in the project does not carry the baseline tag")
  322. targets = sorted(set(by_id) & project_droplets)
  323. if len(targets) != expected:
  324. raise CheckError("the number of tagged project droplets is not the expected number")
  325. reserved_by_droplet = _reserved_for(transport, set(targets), address_ok)
  326. units: list[Unit] = []
  327. for index, droplet_id in enumerate(targets, start=1):
  328. label = f"connector-{index}"
  329. addresses = _droplet_public_v4(by_id[droplet_id], address_ok)
  330. if not addresses:
  331. raise CheckError("a droplet has no public IPv4 address")
  332. units.append(Unit(label, addresses[0], droplet_id))
  333. extra = sorted((set(addresses) | set(reserved_by_droplet.get(droplet_id, ()))) - {addresses[0]})
  334. for number, address in enumerate(extra, start=1):
  335. units.append(Unit(f"{label}-extra-{number}", address, droplet_id))
  336. if len({u.address for u in units}) != len(units):
  337. raise CheckError("two scan units share an address")
  338. return Inventory(tuple(units))
  339. def _require_baseline_tag(droplet: dict, tag: str) -> None:
  340. """The tag filter is a request parameter, not proof: check the droplet itself."""
  341. tags = droplet.get("tags")
  342. if (
  343. not isinstance(tags, list)
  344. or not all(isinstance(t, str) for t in tags)
  345. or len(set(tags)) != len(tags)
  346. or tag not in tags
  347. ):
  348. raise CheckError("a droplet does not carry the exact baseline tag")
  349. def _droplet_public_v4(droplet: dict, address_ok) -> list[str]:
  350. networks = droplet.get("networks")
  351. if not isinstance(networks, dict):
  352. raise CheckError("a droplet had no network information")
  353. v4 = networks.get("v4", [])
  354. v6 = networks.get("v6", [])
  355. if not isinstance(v4, list) or not isinstance(v6, list):
  356. raise CheckError("a droplet had malformed network information")
  357. for entry in v6:
  358. if not isinstance(entry, dict) or entry.get("type") not in ("public", "private"):
  359. raise CheckError("a droplet had a malformed IPv6 entry")
  360. if entry["type"] == "public":
  361. raise CheckError("a droplet has a public IPv6 address")
  362. out: list[str] = []
  363. for entry in v4:
  364. if not isinstance(entry, dict) or entry.get("type") not in ("public", "private"):
  365. raise CheckError("a droplet had a malformed IPv4 entry")
  366. if entry["type"] == "public":
  367. out.append(parse_public_ipv4(entry.get("ip_address"), address_ok))
  368. return sorted(set(out))
  369. def _reserved_for(transport, droplet_ids: set[int], address_ok) -> dict[int, list[str]]:
  370. found: dict[int, list[str]] = {}
  371. v4 = _fetch_all(transport, "/v2/reserved_ips", {}, "reserved_ips", "ip")
  372. for item in v4:
  373. owner = _reserved_owner(item)
  374. if owner in droplet_ids:
  375. found.setdefault(owner, []).append(parse_public_ipv4(item.get("ip"), address_ok))
  376. v6 = _fetch_all(transport, "/v2/reserved_ipv6", {}, "reserved_ipv6s", "ip")
  377. for item in v6:
  378. if _reserved_owner(item) in droplet_ids:
  379. raise CheckError("a droplet has a reserved IPv6 address")
  380. return found
  381. def _reserved_owner(item: dict) -> int | None:
  382. droplet = item.get("droplet")
  383. if droplet is None:
  384. return None
  385. if not isinstance(droplet, dict) or not _is_int(droplet.get("id")):
  386. raise CheckError("a reserved address had a malformed assignment")
  387. return droplet["id"]
  388. # ------------------------------------------------------------------- scanning
  389. @dataclass(frozen=True)
  390. class Budget:
  391. concurrency: int = 512
  392. timeout: float = 2.0
  393. rate: float = 1500.0
  394. batch: int = 4096
  395. def classify_errno(code: int | None) -> str:
  396. if code in (errno.ECONNREFUSED, errno.ECONNRESET, errno.ECONNABORTED):
  397. return REFUSED
  398. if code == errno.ETIMEDOUT:
  399. return TIMEOUT
  400. if code in (errno.ENETUNREACH, errno.EHOSTUNREACH, errno.ENETDOWN, errno.EHOSTDOWN):
  401. return UNREACHABLE
  402. if code in (
  403. errno.EMFILE,
  404. errno.ENFILE,
  405. errno.EADDRNOTAVAIL,
  406. errno.ENOBUFS,
  407. errno.ENOMEM,
  408. errno.EAGAIN,
  409. ):
  410. return LOCAL
  411. return ERROR
  412. def _attempt(sock, address: str, port: int) -> str:
  413. """The connect call itself: the only place where a TimeoutError means "no answer"."""
  414. try:
  415. sock.connect((address, port))
  416. except TimeoutError:
  417. return TIMEOUT
  418. except OSError as exc:
  419. return classify_errno(exc.errno)
  420. return OPEN
  421. def tcp_connect(address: str, port: int, timeout: float, *, socket_factory=socket.socket) -> str:
  422. """One attempt. The timeout starts here, when the attempt begins. The socket is always closed.
  423. Socket creation, setup and close failures of any type are LOCAL errors (exit 2), never a
  424. timeout: only a TimeoutError raised by connect() itself counts as silence.
  425. """
  426. sock = None
  427. outcome = LOCAL
  428. try:
  429. sock = socket_factory(socket.AF_INET, socket.SOCK_STREAM)
  430. sock.settimeout(timeout)
  431. ready = True
  432. except _INTERNAL_ERRORS:
  433. ready = False
  434. if ready:
  435. outcome = _attempt(sock, address, port)
  436. if sock is not None:
  437. try:
  438. sock.close()
  439. except _INTERNAL_ERRORS:
  440. # An observed answer stays an answer, with the cleanup problem recorded beside it.
  441. # After silence (or any other result) a failed close means we cannot tell.
  442. outcome = _CLEANUP_TAGGED.get(outcome, LOCAL)
  443. return outcome
  444. class Accounting:
  445. def __init__(self, labels: tuple[str, ...]) -> None:
  446. self.labels = labels
  447. self._lock = threading.Lock()
  448. n = len(labels)
  449. self.counts = [dict.fromkeys(OUTCOMES, 0) for _ in range(n)]
  450. self.open_ports: list[list[int]] = [[] for _ in range(n)]
  451. self.refused_ports: list[list[int]] = [[] for _ in range(n)]
  452. self._seen = [bytearray(MAX_PORT + 1) for _ in range(n)]
  453. self.unique = [0] * n
  454. self.cleanup_problems = [0] * n
  455. self.duplicates = 0
  456. self.invalid = 0
  457. def record(self, unit: int, port: int, outcome: str) -> None:
  458. with self._lock:
  459. if not (0 <= unit < len(self.labels)) or not (1 <= port <= MAX_PORT):
  460. self.invalid += 1
  461. return
  462. if outcome not in OUTCOMES:
  463. outcome = ERROR
  464. if self._seen[unit][port]:
  465. self.duplicates += 1
  466. return
  467. self._seen[unit][port] = 1
  468. self.unique[unit] += 1
  469. if outcome in _CLEANUP_BASE:
  470. self.cleanup_problems[unit] += 1
  471. outcome = _CLEANUP_BASE[outcome]
  472. self.counts[unit][outcome] += 1
  473. if outcome == OPEN:
  474. self.open_ports[unit].append(port)
  475. elif outcome == REFUSED:
  476. self.refused_ports[unit].append(port)
  477. class _RateLimiter:
  478. """Spaces connect starts at least 1/rate apart. Called by each worker right before connect().
  479. A grant loop: eligibility is re-checked under the lock after every sleep and the next
  480. allowed time comes from the ACTUAL grant time, so a worker that slept past its slot earns
  481. no credit for the others. The lock is never held while sleeping.
  482. """
  483. def __init__(self, rate: float, clock, sleep) -> None:
  484. self._gap = 1.0 / rate
  485. self._clock = clock
  486. self._sleep = sleep
  487. self._next = None
  488. self._lock = threading.Lock()
  489. def wait(self) -> None:
  490. while True:
  491. with self._lock:
  492. now = self._clock()
  493. if self._next is None or now >= self._next:
  494. self._next = now + self._gap
  495. return
  496. delay = self._next - now
  497. self._sleep(delay)
  498. def check_nofile(concurrency: int, getrlimit=resource.getrlimit) -> None:
  499. soft, _hard = getrlimit(resource.RLIMIT_NOFILE)
  500. if soft != resource.RLIM_INFINITY and soft < concurrency + NOFILE_MARGIN:
  501. raise CheckError("the open-file limit is too low for the concurrency; cannot tell")
  502. def scan(
  503. inventory: Inventory,
  504. connect: Callable[[str, int, float], str],
  505. budget: Budget,
  506. *,
  507. reread: Callable[[], Inventory],
  508. clock: Callable[[], float] = time.monotonic,
  509. sleep: Callable[[float], None] = time.sleep,
  510. executor_factory=concurrent.futures.ThreadPoolExecutor,
  511. ports=None,
  512. ) -> Accounting:
  513. """Attempt every (unit, port) once. Re-read the inventory after each batch; a change raises."""
  514. acc = Accounting(inventory.labels)
  515. limiter = _RateLimiter(budget.rate, clock, sleep)
  516. gate = threading.BoundedSemaphore(budget.concurrency)
  517. units = inventory.units
  518. attempts = itertools.product(ALL_PORTS if ports is None else ports, range(len(units)))
  519. def run(ui: int, port: int) -> str:
  520. # An exception here lands in the future; done() counts it as ERROR, never a timeout.
  521. limiter.wait() # the cap applies to connect starts, however the pool schedules workers
  522. outcome = connect(units[ui].address, port, budget.timeout)
  523. return outcome if outcome in OUTCOMES else ERROR
  524. def done(fut, ui: int, port: int) -> None:
  525. if fut.cancelled() or fut.exception() is not None:
  526. outcome = ERROR
  527. else:
  528. outcome = fut.result()
  529. acc.record(ui, port, outcome)
  530. gate.release()
  531. executor = executor_factory(max_workers=budget.concurrency)
  532. try:
  533. while True:
  534. chunk = list(itertools.islice(attempts, budget.batch))
  535. if not chunk:
  536. break
  537. futures = []
  538. for port, ui in chunk:
  539. gate.acquire()
  540. fut = None
  541. try:
  542. fut = executor.submit(run, ui, port)
  543. except RuntimeError: # the interpreter could not start a worker thread
  544. fut = None
  545. if fut is None:
  546. acc.record(ui, port, LOCAL)
  547. gate.release()
  548. continue
  549. fut.add_done_callback(lambda f, u=ui, p=port: done(f, u, p))
  550. futures.append(fut)
  551. concurrent.futures.wait(futures)
  552. # A done callback runs after its future is marked done: take every permit
  553. # back so all results are recorded before the batch is judged.
  554. for _ in range(budget.concurrency):
  555. gate.acquire()
  556. for _ in range(budget.concurrency):
  557. gate.release()
  558. if reread() != inventory:
  559. raise InventoryChanged("the droplet inventory changed during the scan; results discarded")
  560. except KeyboardInterrupt:
  561. raise Interrupted("interrupted; results discarded") from None
  562. finally:
  563. executor.shutdown(wait=True, cancel_futures=True)
  564. return acc
  565. @dataclass(frozen=True)
  566. class Verdict:
  567. code: int
  568. reasons: tuple[str, ...]
  569. def verdict(acc: Accounting, expected_units: int, expected_ports: int = MAX_PORT) -> Verdict:
  570. """Pure: the table and the exit codes of the design."""
  571. answered = any(acc.open_ports) or any(acc.refused_ports)
  572. reasons: list[str] = []
  573. if any(acc.cleanup_problems):
  574. reasons.append("closing a socket failed after an answer (cleanup problems)")
  575. if answered:
  576. if any(acc.open_ports):
  577. reasons.append("a port accepted a connection")
  578. if any(acc.refused_ports):
  579. reasons.append("an answer was received on a port (a refusal)")
  580. problems: list[str] = []
  581. if len(acc.labels) != expected_units:
  582. problems.append("the number of scanned addresses is not the expected number")
  583. for ui in range(len(acc.labels)):
  584. c = acc.counts[ui]
  585. if c[LOCAL]:
  586. problems.append("a local resource error occurred; it is not a timeout")
  587. if c[UNREACHABLE]:
  588. problems.append("the network or host was unreachable")
  589. if c[ERROR]:
  590. problems.append("an attempt failed for another reason")
  591. if acc.unique[ui] != expected_ports:
  592. problems.append("not every port was attempted exactly once")
  593. if acc.duplicates or acc.invalid:
  594. problems.append("a port was recorded twice or out of range")
  595. # Exact accounting: expected_units * expected_ports attempts, each timing out.
  596. timeouts = sum(c[TIMEOUT] for c in acc.counts)
  597. all_timed_out = (
  598. not answered
  599. and not problems
  600. and timeouts == expected_units * expected_ports
  601. and len(acc.labels) == expected_units
  602. )
  603. if answered:
  604. return Verdict(1, tuple(dict.fromkeys(reasons + problems)))
  605. if all_timed_out:
  606. return Verdict(0, ())
  607. if not problems:
  608. problems.append("the attempt count does not add up")
  609. return Verdict(2, tuple(dict.fromkeys(problems)))
  610. # --------------------------------------------------------------------- output
  611. def render(
  612. acc: Accounting,
  613. result: Verdict,
  614. budget: Budget,
  615. control_ms: int,
  616. expected: int,
  617. ) -> list[str]:
  618. lines = [
  619. "zero-ports-check: TCP only; observed from this network only; a point in time",
  620. f"connectors expected: {expected}",
  621. (
  622. f"timeout {budget.timeout:g} s, concurrency {budget.concurrency}, "
  623. f"control round trip {control_ms} ms"
  624. ),
  625. ]
  626. for ui, label in enumerate(acc.labels):
  627. c = acc.counts[ui]
  628. errors = c[LOCAL] + c[UNREACHABLE] + c[ERROR]
  629. lines.append(
  630. f"{label}: attempted {acc.unique[ui]}, timeouts {c[TIMEOUT]}, "
  631. f"answers {c[OPEN] + c[REFUSED]}, errors {errors}"
  632. )
  633. if acc.cleanup_problems[ui]:
  634. lines.append(f"{label}: cleanup problems: {acc.cleanup_problems[ui]}")
  635. if acc.open_ports[ui]:
  636. lines.append(f"{label}: open ports: " + ", ".join(map(str, sorted(acc.open_ports[ui]))))
  637. if acc.refused_ports[ui]:
  638. lines.append(
  639. f"{label}: ports that answered with a refusal: "
  640. + ", ".join(map(str, sorted(acc.refused_ports[ui])))
  641. )
  642. if result.code == 0:
  643. lines.append("verdict: PASS: no answer was received on any port (TCP, this network only)")
  644. elif result.code == 1:
  645. lines.append("verdict: FAIL: an answer was received")
  646. lines.extend(f" {r}" for r in result.reasons)
  647. else:
  648. lines.append("verdict: CANNOT TELL")
  649. lines.extend(f" {r}" for r in result.reasons)
  650. return lines
  651. def _repo_root() -> Path:
  652. return Path(__file__).resolve().parent.parent
  653. @dataclass
  654. class ReportTarget:
  655. """A validated, already-open parent directory and a file name inside it."""
  656. dir_fd: int
  657. name: str
  658. _DIR_FLAGS = os.O_RDONLY | os.O_DIRECTORY | getattr(os, "O_CLOEXEC", 0)
  659. def _inside_repo(dir_fd: int) -> bool:
  660. """Walk the physical ancestry of an open directory; True if the repository is on the way.
  661. Uses descriptors only (no path is re-resolved), so a path swapped after validation cannot
  662. change the answer. Any doubt (an unreadable ancestor, absurd depth) counts as inside.
  663. Limits: a descriptor pins a directory object, not its place in the tree, so callers re-ask
  664. this just before and just after writing; and a bind mount of a repository subdirectory
  665. elsewhere has a different ancestry and is not seen.
  666. """
  667. root = os.stat(_repo_root())
  668. root_id = (root.st_dev, root.st_ino)
  669. cur = os.dup(dir_fd) # owned: always closed in finally
  670. up = -1 # owned only while it is open and not yet promoted to cur
  671. try:
  672. for _ in range(4096):
  673. st = os.fstat(cur)
  674. if (st.st_dev, st.st_ino) == root_id:
  675. return True
  676. up = os.open("..", _DIR_FLAGS, dir_fd=cur)
  677. up_st = os.fstat(up)
  678. if (up_st.st_dev, up_st.st_ino) == (st.st_dev, st.st_ino):
  679. return False # reached the filesystem root
  680. old, cur, up = cur, up, -1 # ownership moves before anything else can fail
  681. os.close(old)
  682. return True
  683. except OSError:
  684. return True
  685. finally:
  686. if up >= 0:
  687. os.close(up)
  688. os.close(cur)
  689. def close_report_target(target: ReportTarget) -> None:
  690. if target.dir_fd >= 0:
  691. try:
  692. os.close(target.dir_fd)
  693. except OSError:
  694. pass
  695. target.dir_fd = -1
  696. def _open_plain_directory(path: str) -> int:
  697. """Open a directory by walking every component with O_NOFOLLOW: a symlink anywhere on the way
  698. (not only the last component) is refused. Returns -1 on any failure."""
  699. cur = -1
  700. try:
  701. cur = os.open("/" if path.startswith("/") else ".", _DIR_FLAGS)
  702. for part in path.split("/"):
  703. if part in ("", "."):
  704. continue
  705. nxt = os.open(part, _DIR_FLAGS | os.O_NOFOLLOW, dir_fd=cur)
  706. os.close(cur)
  707. cur = nxt
  708. result, cur = cur, -1
  709. return result
  710. except OSError:
  711. return -1
  712. finally:
  713. if cur >= 0:
  714. os.close(cur)
  715. def check_out_path(raw: str) -> ReportTarget:
  716. """Validate before any network use and keep the parent open: outside the repository, a plain
  717. (non-symlink) directory, and no existing file. The caller must close_report_target()."""
  718. expanded = os.path.expanduser(raw)
  719. name = os.path.basename(expanded)
  720. if name in ("", ".", ".."):
  721. raise CheckError("the report path has no file name")
  722. parent = os.path.dirname(expanded) or "."
  723. dir_fd = _open_plain_directory(parent)
  724. if dir_fd < 0:
  725. raise CheckError("the report directory does not exist or is not a plain directory")
  726. exists = True
  727. kept = False
  728. try:
  729. if _inside_repo(dir_fd):
  730. raise CheckError("the report path is inside the repository; refused")
  731. try:
  732. os.stat(name, dir_fd=dir_fd, follow_symlinks=False)
  733. except FileNotFoundError:
  734. exists = False
  735. except OSError:
  736. exists = True # cannot tell: treat as present and refuse
  737. if exists:
  738. raise CheckError("the report path already exists; not overwriting")
  739. kept = True
  740. finally:
  741. if not kept:
  742. os.close(dir_fd)
  743. return ReportTarget(dir_fd, name)
  744. def write_report(target: ReportTarget, lines: list[str]) -> None:
  745. """Create the file through the pinned directory. The directory is checked against the
  746. repository just before creating and again after writing; if it moved in, the file is removed."""
  747. flags = (
  748. os.O_WRONLY
  749. | os.O_CREAT
  750. | os.O_EXCL
  751. | getattr(os, "O_NOFOLLOW", 0)
  752. | getattr(os, "O_CLOEXEC", 0)
  753. )
  754. if _inside_repo(target.dir_fd):
  755. raise CheckError("the report directory is inside the repository; refused")
  756. failed = False
  757. try:
  758. fd = os.open(target.name, flags, 0o600, dir_fd=target.dir_fd)
  759. try:
  760. os.fchmod(fd, 0o600)
  761. with os.fdopen(fd, "w", encoding="utf-8") as fh:
  762. fd = -1
  763. fh.write("\n".join(lines) + "\n")
  764. finally:
  765. if fd >= 0:
  766. os.close(fd)
  767. except (OSError, ValueError):
  768. failed = True
  769. if failed:
  770. raise CheckError("the report could not be written")
  771. if _inside_repo(target.dir_fd):
  772. try:
  773. os.unlink(target.name, dir_fd=target.dir_fd)
  774. except OSError:
  775. pass # the fixed message below is raised either way
  776. raise CheckError("the report directory moved inside the repository; the report was removed")
  777. # ----------------------------------------------------------------------- main
  778. @dataclass
  779. class Hooks:
  780. """Test seams. None of these is reachable from the command line."""
  781. base_url: str = API_ORIGIN
  782. address_ok: Callable = default_address_ok
  783. connect: Callable[[str, int, float], str] = tcp_connect
  784. control_connect: Callable[[str, int, float], None] | None = None
  785. control_target: tuple[str, int] = CONTROL_TARGET
  786. budget: Budget = field(default_factory=Budget)
  787. ports: range | list | None = None # None is production: every port, 1 to 65535
  788. clock: Callable[[], float] = time.monotonic
  789. sleep: Callable[[float], None] = time.sleep
  790. executor_factory: Callable = concurrent.futures.ThreadPoolExecutor
  791. transport_factory: Callable[[str], object] | None = None
  792. getrlimit: Callable = resource.getrlimit
  793. def effective_ports(self):
  794. return ALL_PORTS if self.ports is None else self.ports
  795. def _default_control(host: str, port: int, timeout: float) -> None:
  796. with socket.create_connection((host, port), timeout):
  797. pass
  798. def positive_control(hooks: Hooks) -> int:
  799. fn = hooks.control_connect or _default_control
  800. start = hooks.clock()
  801. failed = False
  802. try:
  803. fn(hooks.control_target[0], hooks.control_target[1], hooks.budget.timeout)
  804. except OSError: # any control failure means the local path cannot be trusted
  805. failed = True
  806. if failed:
  807. raise CheckError("the positive control failed; this network path cannot be trusted")
  808. return max(0, round((hooks.clock() - start) * 1000))
  809. def build_parser() -> argparse.ArgumentParser:
  810. parser = argparse.ArgumentParser(
  811. prog="zero_ports_check.py",
  812. description="External zero-open-ports check for the connectors. Targets come only "
  813. "from the DigitalOcean API (token in DIGITALOCEAN_TOKEN); no address can be given.",
  814. )
  815. parser.add_argument(
  816. "--expect-connectors",
  817. type=int,
  818. required=True,
  819. metavar="N",
  820. help="how many tagged project droplets must exist (N >= 1)",
  821. )
  822. parser.add_argument("--region", default="tor1", help="region of the baseline tag (default tor1)")
  823. parser.add_argument(
  824. "--resource-key",
  825. default="",
  826. metavar="KEY",
  827. help="the stack's resource_key, if it sets one (baseline tag cah-baseline-KEY); "
  828. "default: the tag is built from --region",
  829. )
  830. parser.add_argument(
  831. "--out",
  832. default=None,
  833. metavar="PATH",
  834. help="write the report here (mode 0600, never overwrites, outside the repository)",
  835. )
  836. return parser
  837. def main(argv=None, *, env=None, hooks: Hooks | None = None, stdout=None) -> int:
  838. out = stdout if stdout is not None else sys.stdout
  839. hooks = hooks or Hooks()
  840. env = os.environ if env is None else env
  841. try:
  842. args = build_parser().parse_args(argv)
  843. return _run(args, env, hooks, out)
  844. except InventoryChanged as exc:
  845. print(f"zero-ports-check: {exc}", file=out)
  846. return 2
  847. except Interrupted as exc:
  848. print(f"zero-ports-check: {exc}", file=out)
  849. return 2
  850. except CheckError as exc:
  851. print(f"zero-ports-check: {exc}", file=out)
  852. return 2
  853. except KeyboardInterrupt:
  854. print("zero-ports-check: interrupted; results discarded", file=out)
  855. return 2
  856. except _INTERNAL_ERRORS: # never print a traceback: it could carry request data
  857. print("zero-ports-check: an internal error occurred; cannot tell", file=out)
  858. return 2
  859. def _run(args, env, hooks: Hooks, out) -> int:
  860. if args.expect_connectors < 1:
  861. raise CheckError("--expect-connectors must be at least 1")
  862. target = check_out_path(args.out) if args.out else None
  863. try:
  864. return _run_checked(args, env, hooks, out, target)
  865. finally:
  866. if target is not None:
  867. close_report_target(target)
  868. def _run_checked(args, env, hooks: Hooks, out, out_target) -> int:
  869. expected = args.expect_connectors
  870. token = env.get(TOKEN_ENV, "")
  871. check_nofile(hooks.budget.concurrency, hooks.getrlimit)
  872. if hooks.transport_factory is not None:
  873. transport = hooks.transport_factory(token)
  874. else:
  875. transport = ApiTransport(token, hooks.base_url)
  876. def fresh() -> Inventory:
  877. return discover(transport, expected, args.region, hooks.address_ok, args.resource_key)
  878. inventory = fresh()
  879. control_ms = positive_control(hooks)
  880. acc = scan(
  881. inventory,
  882. hooks.connect,
  883. hooks.budget,
  884. reread=fresh,
  885. clock=hooks.clock,
  886. sleep=hooks.sleep,
  887. executor_factory=hooks.executor_factory,
  888. ports=hooks.effective_ports(),
  889. )
  890. # Completeness is judged against the constant, not against whatever range was generated.
  891. expected_ports = MAX_PORT if hooks.ports is None else len(hooks.ports)
  892. result = verdict(acc, len(inventory.units), expected_ports)
  893. lines = render(acc, result, hooks.budget, control_ms, expected)
  894. code = result.code
  895. if out_target is not None:
  896. try:
  897. write_report(out_target, lines)
  898. except CheckError:
  899. if code == 0:
  900. # A pass nobody can read back is not reported as a pass.
  901. result = Verdict(2, ("the report could not be written",))
  902. code = 2
  903. lines = render(acc, result, hooks.budget, control_ms, expected)
  904. else:
  905. # An answer stays exit 1: it is the stronger signal.
  906. lines.append("the report could not be written")
  907. for line in lines:
  908. print(line, file=out)
  909. return code
  910. if __name__ == "__main__":
  911. sys.exit(main())