wpchecker 0.2.2__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.
wpchecker/fetch.py ADDED
@@ -0,0 +1,268 @@
1
+ """Guarded fetcher (SSRF policy mirrors phpscan's).
2
+
3
+ http/https only, ports 80/443 only, no URL credentials, no
4
+ non-standard IP encodings; the host must resolve — every answer —
5
+ to globally routable public addresses, and the connection is
6
+ pinned to a checked IP (with SNI + certificate verification
7
+ against the original hostname for HTTPS), so DNS rebinding
8
+ between the policy check and the connect gets nothing. Every
9
+ redirect hop is re-validated the same way. Bodies are capped;
10
+ a shared monotonic deadline bounds the whole scan.
11
+ """
12
+
13
+ import http.client
14
+ import ipaddress
15
+ import re
16
+ import socket
17
+ import ssl
18
+ import time
19
+ import urllib.parse
20
+
21
+ from . import __version__
22
+
23
+ _UA = (f"wpchecker/{__version__} "
24
+ f"(+https://phpatch.com/security)")
25
+ _TIMEOUT = 12
26
+ _MAX_BODY = 1024 * 1024
27
+ _MAX_REDIRECTS = 5
28
+ _DEADLINE = 40 # total seconds for one whole scan, all fetches
29
+
30
+ # Ranges that Python's is_global / is_private flags do not
31
+ # classify consistently across versions, checked explicitly:
32
+ # carrier-grade NAT (includes cloud metadata endpoints in that
33
+ # space), the IETF special-purpose /24, benchmarking space, the
34
+ # deprecated 6to4 relay anycast, and the IPv6 transition prefixes
35
+ # whose embedded IPv4 destination could be non-public (NAT64
36
+ # well-known prefix, Teredo).
37
+ _EXTRA_BLOCKED = [ipaddress.ip_network(n) for n in (
38
+ "100.64.0.0/10", "192.0.0.0/24", "198.18.0.0/15",
39
+ "192.88.99.0/24", "64:ff9b::/96", "2001::/32")]
40
+
41
+
42
+ class BlockedTarget(Exception):
43
+ """Target refused by the scanner's SSRF/abuse policy."""
44
+
45
+
46
+ def _blocked(ip):
47
+ """True unless the address is globally routable public space.
48
+
49
+ Primary test is is_global (negated): it covers loopback,
50
+ RFC1918, link-local (incl. cloud metadata 169.254.169.254),
51
+ CGNAT, reserved and unspecified space across Python
52
+ versions, which the individual is_private-style flags
53
+ do not."""
54
+ return (not ip.is_global or ip.is_multicast
55
+ or any(ip in n for n in _EXTRA_BLOCKED))
56
+
57
+
58
+ def _public_ips(host):
59
+ """Resolve a host and require EVERY answer to be a public
60
+ IP, so the scanner can never be pointed at internal
61
+ services."""
62
+ try:
63
+ infos = socket.getaddrinfo(host, None,
64
+ proto=socket.IPPROTO_TCP)
65
+ except socket.gaierror as e:
66
+ raise BlockedTarget(f"DNS lookup failed for {host}: {e}")
67
+ ips = []
68
+ for info in infos:
69
+ ip = ipaddress.ip_address(info[4][0])
70
+ # Unwrap transition forms: the real TCP destination of
71
+ # an IPv4-mapped (::ffff:a.b.c.d) or 6to4 (2002:xxxx::)
72
+ # address is the embedded IPv4, so THAT is what must be
73
+ # checked.
74
+ if isinstance(ip, ipaddress.IPv6Address):
75
+ if ip.ipv4_mapped is not None:
76
+ ip = ip.ipv4_mapped
77
+ elif ip.sixtofour is not None:
78
+ ip = ip.sixtofour
79
+ if _blocked(ip):
80
+ raise BlockedTarget(
81
+ f"{host} resolves to a non-public address; "
82
+ "the scanner only fetches public websites")
83
+ if str(ip) not in ips:
84
+ ips.append(str(ip))
85
+ if not ips:
86
+ raise BlockedTarget(f"DNS lookup returned nothing for {host}")
87
+ return ips
88
+
89
+
90
+ class _PinnedHTTPS(http.client.HTTPSConnection):
91
+ """HTTPS to a pinned IP, with SNI + certificate checks
92
+ against the original hostname."""
93
+
94
+ def __init__(self, ip, port, sni_host, timeout):
95
+ super().__init__(ip, port, timeout=timeout,
96
+ context=ssl.create_default_context())
97
+ self._sni_host = sni_host
98
+
99
+ def connect(self):
100
+ http.client.HTTPConnection.connect(self)
101
+ self.sock = self._context.wrap_socket(
102
+ self.sock, server_hostname=self._sni_host)
103
+
104
+
105
+ def _literal_refusal(host):
106
+ """Refuse non-standard IP encodings: decimal (2130706433),
107
+ hex (0x7f000001), octal parts (0177.0.0.1), short forms
108
+ (127.1). Resolver libraries disagree on these spellings, so
109
+ they never reach a resolver at all."""
110
+ if re.fullmatch(r"0[xX][0-9a-fA-F]+", host):
111
+ return "hex-encoded IP addresses are refused"
112
+ if re.fullmatch(r"[0-9.]+", host):
113
+ parts = host.split(".")
114
+ if len(parts) != 4 or any(
115
+ not p.isdigit() or int(p) > 255 or
116
+ (len(p) > 1 and p.startswith("0")) for p in parts):
117
+ return "non-standard IP address forms are refused"
118
+ return None
119
+
120
+
121
+ def _preflight(url):
122
+ """Validate one fetch target. Called for the initial URL and
123
+ for EVERY redirect hop. Returns (error, parts, port); error
124
+ is None when clean."""
125
+ parts = urllib.parse.urlsplit(url)
126
+ if parts.scheme not in ("http", "https"):
127
+ return "only http/https URLs are scanned", None, None
128
+ if parts.username or parts.password:
129
+ return "URLs with credentials are refused", None, None
130
+ host = parts.hostname
131
+ if not host:
132
+ return "URL has no host", None, None
133
+ refusal = _literal_refusal(host)
134
+ if refusal:
135
+ return refusal, None, None
136
+ try:
137
+ port = parts.port or (443 if parts.scheme == "https" else 80)
138
+ except ValueError:
139
+ port = -1
140
+ if port not in (80, 443):
141
+ return "only ports 80 and 443 are scanned", None, None
142
+ return None, parts, port
143
+
144
+
145
+ def _headers_dict(resp):
146
+ """Response headers as a dict, merging duplicates (notably
147
+ Set-Cookie / Link) instead of keeping only the last one."""
148
+ out = {}
149
+ for k, v in resp.getheaders():
150
+ lk = k.lower()
151
+ out[lk] = f"{out[lk]}, {v}" if lk in out else v
152
+ return out
153
+
154
+
155
+ def _read_capped(resp, end):
156
+ """Read up to _MAX_BODY bytes, bounded by the shared scan
157
+ deadline. The socket timeout is recomputed from the time
158
+ remaining before every chunk, so a slow-drip server cannot
159
+ hold the scanner open one byte at a time. The cap applies to
160
+ the raw bytes as received; nothing is decompressed."""
161
+ chunks, got = [], 0
162
+ while got <= _MAX_BODY:
163
+ remaining = end - time.monotonic()
164
+ if remaining <= 0:
165
+ break
166
+ sock = getattr(resp, "fp", None)
167
+ raw = getattr(sock, "raw", None) if sock is not None else None
168
+ target = raw if raw is not None else sock
169
+ if target is not None and hasattr(target, "settimeout"):
170
+ try:
171
+ target.settimeout(max(0.1, min(_TIMEOUT, remaining)))
172
+ except Exception:
173
+ pass
174
+ try:
175
+ chunk = resp.read(min(65536, _MAX_BODY + 1 - got))
176
+ except http.client.IncompleteRead as e:
177
+ # Server/proxy closed mid-body; the partial body is
178
+ # still a successful fetch.
179
+ if e.partial:
180
+ chunks.append(e.partial)
181
+ break
182
+ except (socket.timeout, TimeoutError, OSError):
183
+ break
184
+ if not chunk:
185
+ break
186
+ chunks.append(chunk)
187
+ got += len(chunk)
188
+ return b"".join(chunks)[:_MAX_BODY]
189
+
190
+
191
+ def fetch(url, deadline=None):
192
+ """One guarded GET. Returns {"ok", "status", "final_url",
193
+ "headers", "body", "error"}; body is text (utf-8, replacement
194
+ chars) — the scanner only ever reads markup and text files.
195
+ Follows up to _MAX_REDIRECTS redirects, re-validating and
196
+ re-pinning every hop. `deadline` (time.monotonic()) lets a
197
+ scan share one budget across all its fetches."""
198
+ end = deadline if deadline is not None else \
199
+ time.monotonic() + _DEADLINE
200
+ current = url
201
+ for _hop in range(_MAX_REDIRECTS + 1):
202
+ err, parts, port = _preflight(current)
203
+ if err:
204
+ return {"ok": False, "status": None, "final_url": current,
205
+ "headers": {}, "body": "", "error": err}
206
+ host = parts.hostname
207
+ try:
208
+ ips = _public_ips(host)
209
+ except BlockedTarget as e:
210
+ return {"ok": False, "status": None, "final_url": current,
211
+ "headers": {}, "body": "", "error": str(e)}
212
+ path = parts.path or "/"
213
+ if parts.query:
214
+ path += "?" + parts.query
215
+ host_hdr = host if parts.port is None else f"{host}:{port}"
216
+ last_err = None
217
+ for ip in ips:
218
+ remaining = end - time.monotonic()
219
+ if remaining <= 0:
220
+ return {"ok": False, "status": None,
221
+ "final_url": current, "headers": {},
222
+ "body": "", "error": "scan deadline exceeded"}
223
+ timeout = max(1.0, min(_TIMEOUT, remaining))
224
+ conn = None
225
+ try:
226
+ if parts.scheme == "https":
227
+ conn = _PinnedHTTPS(ip, port, host, timeout)
228
+ else:
229
+ conn = http.client.HTTPConnection(
230
+ ip, port, timeout=timeout)
231
+ conn.request("GET", path,
232
+ headers={"User-Agent": _UA,
233
+ "Host": host_hdr,
234
+ "Accept": "*/*",
235
+ "Connection": "close"})
236
+ resp = conn.getresponse()
237
+ headers = _headers_dict(resp)
238
+ if resp.status in (301, 302, 303, 307, 308) and \
239
+ headers.get("location"):
240
+ conn.close()
241
+ current = urllib.parse.urljoin(
242
+ current, headers["location"])
243
+ last_err = None
244
+ break # next redirect hop
245
+ raw = _read_capped(resp, end)
246
+ conn.close()
247
+ return {"ok": True, "status": resp.status,
248
+ "final_url": current, "headers": headers,
249
+ "body": raw.decode("utf-8", "replace"),
250
+ "error": None}
251
+ except Exception as e: # connection-level: try next IP
252
+ last_err = f"{type(e).__name__}: {e}"
253
+ try:
254
+ if conn is not None:
255
+ conn.close()
256
+ except Exception:
257
+ pass
258
+ if last_err is not None:
259
+ return {"ok": False, "status": None, "final_url": current,
260
+ "headers": {}, "body": "", "error": last_err}
261
+ return {"ok": False, "status": None, "final_url": current,
262
+ "headers": {}, "body": "",
263
+ "error": f"too many redirects (>{_MAX_REDIRECTS})"}
264
+
265
+
266
+ def new_deadline():
267
+ """A fresh shared deadline for one scan."""
268
+ return time.monotonic() + _DEADLINE