auditwright 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.
auditwright/netscan.py ADDED
@@ -0,0 +1,532 @@
1
+ """Authorised network exposure scan.
2
+
3
+ Finds live hosts and open TCP ports on networks you own, identifies services
4
+ from their banners, and checks the classic ways networks get breached without a
5
+ single exploit: databases, caches, container and cluster APIs that answer
6
+ without authentication; cleartext protocols; old SSH; exposed remote-desktop and
7
+ file-sharing ports; web consoles; weak TLS.
8
+
9
+ Only read-only protocol handshakes are used (PING, version and status queries,
10
+ an anonymous FTP login attempt, an MQTT connect without credentials). Nothing is
11
+ written, no passwords are guessed and no exploits are sent. By default only
12
+ private, loopback and link-local addresses may be scanned.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import ipaddress
18
+ import re
19
+ import socket
20
+ import ssl
21
+ import struct
22
+ import time
23
+ from collections.abc import Callable
24
+ from concurrent.futures import ThreadPoolExecutor
25
+ from datetime import UTC, datetime
26
+ from typing import Any
27
+
28
+ from .model import Finding, RuleMeta
29
+ from .rules.base import register
30
+
31
+ A01 = "A01:2021 Broken Access Control"
32
+ A02 = "A02:2021 Cryptographic Failures"
33
+ A05 = "A05:2021 Security Misconfiguration"
34
+ A06 = "A06:2021 Vulnerable and Outdated Components"
35
+ A07 = "A07:2021 Identification and Authentication Failures"
36
+
37
+
38
+ def _r(id_, title, sev, cwe, owasp, fix) -> RuleMeta:
39
+ return register(RuleMeta(id_, title, "network", sev, cwe, owasp, fix))
40
+
41
+
42
+ R = {
43
+ "telnet": _r("AW-NET-001", "Telnet service exposed", "high", "CWE-319", A02, "Disable Telnet and use SSH with key authentication."),
44
+ "ftp_anon": _r("AW-NET-002", "Anonymous FTP login allowed", "high", "CWE-306", A07, "Disable anonymous FTP; prefer SFTP."),
45
+ "ftp": _r("AW-NET-003", "Cleartext FTP service", "medium", "CWE-319", A02, "Replace FTP with SFTP or FTPS."),
46
+ "redis": _r("AW-NET-004", "Redis without authentication", "critical", "CWE-306", A07, "Enable requirepass/ACLs, bind to localhost or a private interface, and enable protected-mode."),
47
+ "mongo": _r("AW-NET-005", "MongoDB without authentication", "critical", "CWE-306", A07, "Enable authorization (security.authorization: enabled) and bind to private interfaces."),
48
+ "elastic": _r("AW-NET-006", "Elasticsearch/OpenSearch without authentication", "critical", "CWE-306", A07, "Enable the security plugin with TLS and users; never expose port 9200 broadly."),
49
+ "docker": _r("AW-NET-007", "Docker API exposed without TLS", "critical", "CWE-306", A07, "Never expose dockerd over TCP without mutual TLS; it grants root on the host."),
50
+ "kubelet": _r("AW-NET-008", "Kubelet or Kubernetes API answers anonymously", "critical", "CWE-306", A07, "Disable anonymous auth and require webhook authorization."),
51
+ "memcached": _r("AW-NET-009", "Memcached without authentication", "high", "CWE-306", A07, "Bind memcached to localhost, enable SASL, and disable UDP (amplification attacks)."),
52
+ "couch": _r("AW-NET-010", "CouchDB lists databases anonymously", "critical", "CWE-306", A07, "Require authentication and remove admin party mode."),
53
+ "mqtt": _r("AW-NET-011", "MQTT broker accepts anonymous clients", "high", "CWE-306", A07, "Disable anonymous access and require TLS with client credentials."),
54
+ "db_exposed": _r("AW-NET-012", "Database port reachable", "medium", "CWE-668", A05, "Restrict database ports to application hosts with a firewall."),
55
+ "remote_admin": _r("AW-NET-013", "Remote administration port reachable", "medium", "CWE-668", A05, "Put RDP, VNC and SMB behind a VPN; enable NLA and strong authentication."),
56
+ "ssh_old": _r("AW-NET-014", "Outdated or legacy SSH server", "medium", "CWE-1104", A06, "Update the SSH server and disable protocol 1 and legacy algorithms."),
57
+ "http_cleartext": _r("AW-NET-015", "Web service without TLS", "low", "CWE-319", A02, "Serve over HTTPS, or restrict the service to localhost."),
58
+ "tls_cert": _r("AW-NET-016", "Untrusted or expiring TLS certificate", "low", "CWE-295", A02, "Use certificates from a trusted (or internal, distributed) CA and renew before expiry."),
59
+ "console": _r("AW-NET-017", "Monitoring or admin console exposed", "medium", "CWE-200", A05, "Require authentication for dashboards (Prometheus, Kibana, Grafana, router admin) and restrict access."),
60
+ "listing": _r("AW-NET-018", "Web server lists directory contents", "medium", "CWE-548", A05, "Disable directory indexes."),
61
+ "rsync": _r("AW-NET-019", "rsync modules listed anonymously", "high", "CWE-306", A07, "Require authentication for rsync modules or close the port."),
62
+ "smb": _r("AW-NET-020", "SMB file sharing reachable", "medium", "CWE-668", A05, "Restrict SMB (445) to trusted hosts; disable SMBv1."),
63
+ } # fmt: skip
64
+
65
+ PORTS: dict[int, str] = {
66
+ 21: "ftp", 22: "ssh", 23: "telnet", 25: "smtp", 53: "dns", 80: "http", 110: "pop3", 111: "rpcbind", 135: "msrpc",
67
+ 139: "netbios", 143: "imap", 389: "ldap", 443: "https", 445: "smb", 465: "smtps", 587: "submission", 631: "ipp",
68
+ 873: "rsync", 993: "imaps", 995: "pop3s", 1433: "mssql", 1521: "oracle", 1883: "mqtt", 2049: "nfs", 2375: "docker",
69
+ 2376: "docker-tls", 3000: "http", 3306: "mysql", 3389: "rdp", 5000: "http", 5432: "postgresql", 5601: "kibana",
70
+ 5900: "vnc", 5984: "couchdb", 6379: "redis", 6443: "kubernetes", 8000: "http", 8080: "http", 8081: "http",
71
+ 8443: "https", 8888: "http", 9000: "http", 9090: "prometheus", 9200: "elasticsearch", 10250: "kubelet",
72
+ 11211: "memcached", 27017: "mongodb", 50000: "http",
73
+ } # fmt: skip
74
+ WEB_SERVICES = {"http", "https", "kibana", "prometheus", "kubernetes"}
75
+
76
+
77
+ _REACHABILITY = {"db_exposed", "remote_admin", "smb", "http_cleartext", "console"}
78
+
79
+
80
+ class ScopeError(ValueError):
81
+ pass
82
+
83
+
84
+ def expand_targets(spec: str, *, allow_public: bool = False, max_hosts: int = 1024) -> list[str]:
85
+ """Turn '192.168.1.0/24, 10.0.0.5, nas.local' into a list of IP addresses, enforcing scope."""
86
+ hosts: list[str] = []
87
+ for part in [p.strip() for p in spec.split(",") if p.strip()]:
88
+ try:
89
+ if "/" in part:
90
+ net = ipaddress.ip_network(part, strict=False)
91
+ if net.num_addresses > max_hosts + 2:
92
+ raise ScopeError(
93
+ f"{part} has {net.num_addresses} addresses; the limit is {max_hosts} (raise --max-hosts)"
94
+ )
95
+ addrs = [str(h) for h in (net.hosts() if net.num_addresses > 2 else net)]
96
+ else:
97
+ addrs = [str(ipaddress.ip_address(part))]
98
+ except ValueError as exc:
99
+ if isinstance(exc, ScopeError):
100
+ raise
101
+ try:
102
+ addrs = sorted({ai[4][0] for ai in socket.getaddrinfo(part, None, proto=socket.IPPROTO_TCP)})
103
+ except OSError as err:
104
+ raise ScopeError(f"cannot resolve {part}") from err
105
+ for a in addrs:
106
+ ip = ipaddress.ip_address(a)
107
+ if not allow_public and not (ip.is_private or ip.is_loopback or ip.is_link_local):
108
+ raise ScopeError(f"{a} is a public address; scanning it needs --allow-public and written permission")
109
+ hosts.append(a)
110
+ unique = list(dict.fromkeys(hosts))
111
+ if len(unique) > max_hosts:
112
+ raise ScopeError(f"{len(unique)} hosts exceed the limit of {max_hosts} (raise --max-hosts)")
113
+ return unique
114
+
115
+
116
+ def _connect(host: str, port: int, timeout: float) -> socket.socket | None:
117
+ try:
118
+ return socket.create_connection((host, port), timeout=timeout)
119
+ except OSError:
120
+ return None
121
+
122
+
123
+ def _exchange(host: str, port: int, payload: bytes | None, timeout: float, *, read: int = 4096) -> bytes:
124
+ s = _connect(host, port, timeout)
125
+ if s is None:
126
+ return b""
127
+ try:
128
+ s.settimeout(timeout)
129
+ if payload:
130
+ s.sendall(payload)
131
+ data = b""
132
+ deadline = time.monotonic() + timeout
133
+ while len(data) < read and time.monotonic() < deadline:
134
+ try:
135
+ chunk = s.recv(read - len(data))
136
+ except (TimeoutError, OSError):
137
+ break
138
+ if not chunk:
139
+ break
140
+ data += chunk
141
+ if payload is None and b"\n" in data:
142
+ break
143
+ return data
144
+ finally:
145
+ s.close()
146
+
147
+
148
+ def _http(host: str, port: int, path: str, timeout: float, *, tls: bool = False) -> tuple[int, dict[str, str], bytes]:
149
+ s = _connect(host, port, timeout)
150
+ if s is None:
151
+ return 0, {}, b""
152
+ try:
153
+ if tls:
154
+ ctx = ssl.create_default_context()
155
+ ctx.check_hostname = False
156
+ ctx.verify_mode = ssl.CERT_NONE
157
+ s = ctx.wrap_socket(s, server_hostname=host)
158
+ s.settimeout(timeout)
159
+ s.sendall(
160
+ f"GET {path} HTTP/1.1\r\nHost: {host}\r\nUser-Agent: auditwright-netscan\r\nAccept: */*\r\nConnection: close\r\n\r\n".encode()
161
+ )
162
+ data = b""
163
+ while len(data) < 262_144:
164
+ try:
165
+ chunk = s.recv(65536)
166
+ except (TimeoutError, OSError):
167
+ break
168
+ if not chunk:
169
+ break
170
+ data += chunk
171
+ except (OSError, ssl.SSLError):
172
+ return 0, {}, b""
173
+ finally:
174
+ s.close()
175
+ head, _, body = data.partition(b"\r\n\r\n")
176
+ lines = head.decode("latin-1").split("\r\n")
177
+ m = re.match(r"HTTP/\d(?:\.\d)?\s+(\d{3})", lines[0] if lines else "")
178
+ headers = {k.strip().lower(): v.strip() for k, _, v in (ln.partition(":") for ln in lines[1:]) if k}
179
+ return (int(m.group(1)) if m else 0), headers, body
180
+
181
+
182
+ def _bson_cmd() -> bytes:
183
+ """OP_MSG {listDatabases: 1, nameOnly: true, $db: "admin"}."""
184
+
185
+ def elem_int(name: str, v: int) -> bytes:
186
+ return b"\x10" + name.encode() + b"\x00" + struct.pack("<i", v)
187
+
188
+ def elem_bool(name: str, v: bool) -> bytes:
189
+ return b"\x08" + name.encode() + b"\x00" + (b"\x01" if v else b"\x00")
190
+
191
+ def elem_str(name: str, v: str) -> bytes:
192
+ raw = v.encode() + b"\x00"
193
+ return b"\x02" + name.encode() + b"\x00" + struct.pack("<i", len(raw)) + raw
194
+
195
+ body = elem_int("listDatabases", 1) + elem_bool("nameOnly", True) + elem_str("$db", "admin")
196
+ doc = struct.pack("<i", len(body) + 5) + body + b"\x00"
197
+ msg = struct.pack("<I", 0) + b"\x00" + doc
198
+ header = struct.pack("<iiii", 16 + len(msg), 1, 0, 2013)
199
+ return header + msg
200
+
201
+
202
+ def _mqtt_connect() -> bytes:
203
+ var = b"\x00\x04MQTT\x04\x02\x00\x3c"
204
+ payload = b"\x00\x0aauditwright"
205
+ rest = var + payload
206
+ return b"\x10" + bytes([len(rest)]) + rest
207
+
208
+
209
+ class NetScan:
210
+ def __init__(self, hosts: list[str], *, ports: dict[int, str] | None = None, timeout: float = 0.8, workers: int = 64,
211
+ progress: Callable[[str], None] | None = None) -> None: # fmt: skip
212
+ self.hosts = hosts
213
+ self.portmap = ports or PORTS
214
+ self.ports = sorted(self.portmap)
215
+ self.timeout = timeout
216
+ self.workers = max(1, min(workers, 256))
217
+ self.say = progress or (lambda _m: None)
218
+ self.findings: list[Finding] = []
219
+ self.services: dict[str, list[dict[str, Any]]] = {}
220
+
221
+ def add(self, key: str, host: str, port: int, msg: str, evidence: str = "", **kw) -> None:
222
+ if key in _REACHABILITY and ipaddress.ip_address(host).is_loopback:
223
+ # Reachable on loopback means "this machine only": informational, not an exposure.
224
+ kw["severity"] = "info"
225
+ msg += " (loopback only: reachable from this machine, not the network)"
226
+ self.findings.append(
227
+ Finding.from_rule(
228
+ R[key],
229
+ msg,
230
+ file=f"{host}:{port}",
231
+ snippet=evidence[:240],
232
+ confidence=kw.pop("confidence", "high"),
233
+ **kw,
234
+ )
235
+ )
236
+
237
+ def run(self) -> tuple[list[Finding], dict[str, Any]]:
238
+ started = time.monotonic()
239
+ pairs = [(h, p) for h in self.hosts for p in self.ports]
240
+ self.say(f"probing {len(self.hosts)} hosts x {len(self.ports)} ports")
241
+ with ThreadPoolExecutor(max_workers=self.workers) as pool:
242
+ results = list(pool.map(lambda hp: (hp, self._is_open(*hp)), pairs))
243
+ open_ports = [hp for hp, ok in results if ok]
244
+ self.say(f"{len(open_ports)} open ports; identifying services")
245
+ with ThreadPoolExecutor(max_workers=min(self.workers, 32)) as pool:
246
+ for (host, _port), svc in zip(open_ports, pool.map(lambda hp: self._inspect(*hp), open_ports), strict=True):
247
+ self.services.setdefault(host, []).append(svc)
248
+ hosts = [
249
+ {"host": h, "services": sorted(v, key=lambda s: s["port"])}
250
+ for h, v in sorted(self.services.items(), key=lambda kv: ipaddress.ip_address(kv[0]))
251
+ ]
252
+ facts = {
253
+ "scanned_hosts": len(self.hosts),
254
+ "live_hosts": len(hosts),
255
+ "open_ports": len(open_ports),
256
+ "ports_checked": len(self.ports),
257
+ "duration_s": round(time.monotonic() - started, 1),
258
+ "hosts": hosts,
259
+ }
260
+ return self.findings, facts
261
+
262
+ def _is_open(self, host: str, port: int) -> bool:
263
+ s = _connect(host, port, self.timeout)
264
+ if s is None:
265
+ return False
266
+ s.close()
267
+ return True
268
+
269
+ def _inspect(self, host: str, port: int) -> dict[str, Any]: # noqa: C901 - one probe per service
270
+ name = self.portmap.get(port, "unknown")
271
+ svc: dict[str, Any] = {"port": port, "service": name, "banner": ""}
272
+ t = max(self.timeout, 1.5)
273
+ try:
274
+ if name in WEB_SERVICES:
275
+ self._web(host, port, svc, t)
276
+ elif name == "ftp":
277
+ banner = _exchange(host, port, None, t).decode("latin-1", "replace").strip()
278
+ svc["banner"] = banner[:120]
279
+ reply = _exchange(
280
+ host, port, b"USER anonymous\r\nPASS auditwright@example.com\r\nQUIT\r\n", t + 1
281
+ ).decode("latin-1", "replace")
282
+ if re.search(r"(?m)^230", reply):
283
+ self.add("ftp_anon", host, port, "The FTP server accepts anonymous logins.", banner)
284
+ else:
285
+ self.add(
286
+ "ftp", host, port, "FTP sends credentials and data in cleartext.", banner, confidence="medium"
287
+ )
288
+ elif name == "ssh":
289
+ banner = _exchange(host, port, None, t).decode("latin-1", "replace").strip()
290
+ svc["banner"] = banner[:120]
291
+ m = re.search(r"OpenSSH_(\d+)\.(\d+)", banner)
292
+ if banner.startswith("SSH-1.") or (m and (int(m.group(1)), int(m.group(2))) < (8, 0)):
293
+ self.add("ssh_old", host, port, f"The SSH server is outdated: {banner[:60]}.", banner)
294
+ elif name == "telnet":
295
+ svc["banner"] = _exchange(host, port, None, t).decode("latin-1", "replace").strip()[:120]
296
+ self.add(
297
+ "telnet",
298
+ host,
299
+ port,
300
+ "Telnet transmits logins in cleartext and is a top target of IoT botnets.",
301
+ svc["banner"],
302
+ )
303
+ elif name == "redis":
304
+ reply = _exchange(host, port, b"PING\r\n", t).decode("latin-1", "replace")
305
+ svc["banner"] = reply.strip()[:80]
306
+ if reply.startswith("+PONG"):
307
+ info = _exchange(host, port, b"INFO server\r\n", t).decode("latin-1", "replace")
308
+ ver = re.search(r"redis_version:([\d.]+)", info)
309
+ svc["banner"] = f"Redis {ver.group(1)}" if ver else "Redis"
310
+ self.add(
311
+ "redis",
312
+ host,
313
+ port,
314
+ "Redis answers commands without a password. Attackers write SSH keys or cron jobs through it to take over the host.",
315
+ svc["banner"],
316
+ )
317
+ elif name == "mongodb":
318
+ reply = _exchange(host, port, _bson_cmd(), t, read=65536)
319
+ svc["banner"] = "MongoDB" if reply else ""
320
+ if b"databases" in reply and b"Unauthorized" not in reply and b"requires authentication" not in reply:
321
+ names = re.findall(rb"\x02name\x00.{4}([^\x00]{1,40})\x00", reply)[:8]
322
+ shown = ", ".join(n.decode("latin-1") for n in names)
323
+ self.add(
324
+ "mongo",
325
+ host,
326
+ port,
327
+ f"MongoDB lists databases without authentication ({shown or 'databases visible'}).",
328
+ "listDatabases succeeded",
329
+ )
330
+ elif name == "elasticsearch":
331
+ code, _, body = _http(host, port, "/", t)
332
+ if code == 200 and b"cluster_name" in body:
333
+ svc["banner"] = "Elasticsearch"
334
+ code2, _, body2 = _http(host, port, "/_cat/indices?h=index", t)
335
+ if code2 == 200:
336
+ n = len([x for x in body2.decode("latin-1").splitlines() if x.strip()])
337
+ self.add(
338
+ "elastic",
339
+ host,
340
+ port,
341
+ f"The search cluster answers anonymously ({n} indices readable).",
342
+ "GET /_cat/indices -> 200",
343
+ )
344
+ elif name in ("docker", "docker-tls"):
345
+ code, _, body = _http(host, port, "/version", t, tls=name == "docker-tls")
346
+ if code == 200 and b"ApiVersion" in body:
347
+ svc["banner"] = "Docker Engine API"
348
+ self.add(
349
+ "docker",
350
+ host,
351
+ port,
352
+ "The Docker API answers without client authentication: anyone reaching it gets root on the host.",
353
+ "GET /version -> 200",
354
+ )
355
+ elif name == "kubelet":
356
+ code, _, body = _http(host, port, "/pods", t, tls=True)
357
+ svc["banner"] = "kubelet"
358
+ if code == 200 and b"items" in body:
359
+ self.add(
360
+ "kubelet",
361
+ host,
362
+ port,
363
+ "The kubelet lists pods anonymously; anonymous exec is often possible too.",
364
+ "GET /pods -> 200",
365
+ )
366
+ elif name == "memcached":
367
+ reply = _exchange(host, port, b"stats\r\n", t).decode("latin-1", "replace")
368
+ if "STAT pid" in reply:
369
+ svc["banner"] = "memcached"
370
+ self.add(
371
+ "memcached",
372
+ host,
373
+ port,
374
+ "Memcached answers without authentication; cached data (often sessions) can be read and altered.",
375
+ "stats -> STAT pid",
376
+ )
377
+ elif name == "couchdb":
378
+ code, _, body = _http(host, port, "/_all_dbs", t)
379
+ svc["banner"] = "CouchDB"
380
+ if code == 200 and body.strip().startswith(b"["):
381
+ self.add(
382
+ "couch", host, port, "CouchDB lists all databases to anonymous users.", "GET /_all_dbs -> 200"
383
+ )
384
+ elif name == "mqtt":
385
+ reply = _exchange(host, port, _mqtt_connect(), t, read=4)
386
+ svc["banner"] = "MQTT"
387
+ if reply[:1] == b"\x20" and len(reply) >= 4 and reply[3] == 0:
388
+ self.add(
389
+ "mqtt",
390
+ host,
391
+ port,
392
+ "The MQTT broker accepts clients without credentials; attackers can read and publish device messages.",
393
+ "CONNACK 0",
394
+ )
395
+ elif name == "rsync":
396
+ reply = _exchange(host, port, b"@RSYNCD: 31.0\n\n", t + 1, read=8192).decode("latin-1", "replace")
397
+ svc["banner"] = reply.splitlines()[0][:80] if reply else "rsync"
398
+ modules = [
399
+ ln.split()[0] for ln in reply.splitlines()[1:] if ln.strip() and not ln.startswith("@RSYNCD")
400
+ ]
401
+ if modules:
402
+ self.add(
403
+ "rsync",
404
+ host,
405
+ port,
406
+ f"rsync lists modules without authentication: {', '.join(modules[:6])}.",
407
+ "module list",
408
+ )
409
+ elif name in ("mssql", "oracle", "mysql", "postgresql"):
410
+ banner = _exchange(host, port, None, t).decode("latin-1", "replace")
411
+ svc["banner"] = re.sub(r"[^\x20-\x7e]", " ", banner)[:80].strip()
412
+ self.add(
413
+ "db_exposed",
414
+ host,
415
+ port,
416
+ f"{name} accepts network connections from this scanner's network.",
417
+ svc["banner"],
418
+ confidence="medium",
419
+ )
420
+ elif name in ("rdp", "vnc", "msrpc", "netbios"):
421
+ if name == "vnc":
422
+ svc["banner"] = _exchange(host, port, None, t).decode("latin-1", "replace").strip()[:40]
423
+ self.add(
424
+ "remote_admin",
425
+ host,
426
+ port,
427
+ f"{name.upper()} is reachable; it is a common ransomware entry point.",
428
+ svc["banner"],
429
+ confidence="medium",
430
+ )
431
+ elif name == "smb":
432
+ self.add("smb", host, port, "SMB file sharing is reachable from this network.", "", confidence="medium")
433
+ else:
434
+ svc["banner"] = _exchange(host, port, None, min(t, 1.0)).decode("latin-1", "replace").strip()[:120]
435
+ except (OSError, ValueError, struct.error) as exc: # a misbehaving service must not stop the scan
436
+ svc["error"] = type(exc).__name__
437
+ return svc
438
+
439
+ def _web(self, host: str, port: int, svc: dict[str, Any], t: float) -> None:
440
+ tls = self.portmap.get(port) in ("https", "kubernetes")
441
+ code, headers, body = _http(host, port, "/", t, tls=tls)
442
+ if not code and not tls:
443
+ code, headers, body = _http(host, port, "/", t, tls=True)
444
+ tls = bool(code)
445
+ title = re.search(rb"(?is)<title[^>]*>(.{0,120}?)</title>", body)
446
+ svc["service"] = "https" if tls else "http"
447
+ svc["banner"] = " | ".join(
448
+ x for x in (headers.get("server", ""), title.group(1).decode("latin-1").strip() if title else "") if x
449
+ )[:120]
450
+ svc["status"] = code
451
+ if tls:
452
+ self._tls(host, port)
453
+ elif code:
454
+ self.add(
455
+ "http_cleartext", host, port, "A web service is served without TLS.", svc["banner"], confidence="medium"
456
+ )
457
+ text = body[:200_000].decode("latin-1", "replace")
458
+ if re.search(r"(?:<title>|<h1>)Index of /|Directory listing for /", text):
459
+ self.add("listing", host, port, "The web root lists files.", "Index of /")
460
+ if code == 200 and re.search(
461
+ r"(?i)prometheus|kibana|grafana|jenkins|portainer|phpmyadmin|adminer|rabbitmq|traefik|router|routeros|openwrt|pfsense",
462
+ text[:20000] + svc["banner"],
463
+ ):
464
+ self.add(
465
+ "console",
466
+ host,
467
+ port,
468
+ f"An admin or monitoring console is reachable: {svc['banner'] or 'web console'}.",
469
+ svc["banner"],
470
+ confidence="medium",
471
+ )
472
+
473
+ def _tls(self, host: str, port: int) -> None:
474
+ try:
475
+ raw = socket.create_connection((host, port), timeout=3)
476
+ except OSError:
477
+ return
478
+ try:
479
+ ctx = ssl.create_default_context()
480
+ ctx.check_hostname = False
481
+ try:
482
+ with ctx.wrap_socket(raw, server_hostname=host) as s:
483
+ cert = s.getpeercert() or {}
484
+ if cert.get("notAfter"):
485
+ days = (
486
+ datetime.fromtimestamp(ssl.cert_time_to_seconds(cert["notAfter"]), UTC) - datetime.now(UTC)
487
+ ).days
488
+ if days < 21:
489
+ self.add("tls_cert", host, port, f"The certificate expires in {days} days.", "")
490
+ except ssl.SSLCertVerificationError as exc:
491
+ self.add(
492
+ "tls_cert",
493
+ host,
494
+ port,
495
+ f"The certificate is not trusted: {exc.verify_message or exc}.",
496
+ "",
497
+ confidence="medium",
498
+ )
499
+ except (OSError, ssl.SSLError):
500
+ pass
501
+ finally:
502
+ raw.close()
503
+
504
+
505
+ def parse_ports(spec: str) -> dict[int, str]:
506
+ """'22,80,6380=redis' -> {22: 'ssh', 80: 'http', 6380: 'redis'}; 'top' or '' -> the default set."""
507
+ if not spec or spec == "top":
508
+ return dict(PORTS)
509
+ out: dict[int, str] = {}
510
+ for part in spec.split(","):
511
+ part = part.strip()
512
+ if not part:
513
+ continue
514
+ num, _, svc = part.partition("=")
515
+ if "-" in num:
516
+ lo, hi = (int(x) for x in num.split("-", 1))
517
+ if not (0 < lo <= hi < 65536) or hi - lo > 5000:
518
+ raise ScopeError(f"bad port range {num}")
519
+ for n in range(lo, hi + 1):
520
+ out[n] = PORTS.get(n, "unknown")
521
+ continue
522
+ n = int(num)
523
+ if not 0 < n < 65536:
524
+ raise ScopeError(f"bad port {num}")
525
+ out[n] = svc or PORTS.get(n, "unknown")
526
+ return out
527
+
528
+
529
+ def run(targets: str, *, allow_public: bool = False, max_hosts: int = 1024, ports: dict[int, str] | None = None,
530
+ timeout: float = 0.8, workers: int = 64, progress: Callable[[str], None] | None = None) -> tuple[list[Finding], dict[str, Any]]: # fmt: skip
531
+ hosts = expand_targets(targets, allow_public=allow_public, max_hosts=max_hosts)
532
+ return NetScan(hosts, ports=ports, timeout=timeout, workers=workers, progress=progress).run()