osint-lead-identificationPortfolio

py333 lines14.3 KB
Raw
1"""Security layer of the local review dashboard: loopback-only, DNS-rebinding and CSRF defenses, strict CSP.
2
3 python3 -m leads.local_server --static docs/demo-site --port 8765
4
5* **Bound to 127.0.0.1, always.** There is no flag to bind anywhere else. The
6 corpus names private individuals; a bind address is not the place to be
7 casual.
8* **No network on read.** The pages load no CDN, no font service, no
9 analytics. A restrictive Content-Security-Policy is served with every
10 response so a future edit that adds a third-party script fails visibly in the
11 browser instead of quietly phoning out.
12* **Writes are POST-only, same-origin, and token-checked.** A page on another
13 origin can reach 127.0.0.1, and a hostname that resolves to it can be used to
14 smuggle a request past a naive server. So every request's Host header is
15 checked against the loopback names, every write additionally needs a matching
16 Origin and the server-bound CSRF token, and CORS is never granted, including
17 the preflight, which is refused outright.
18"""
19from __future__ import annotations
20
21import argparse
22import hmac
23import json
24import re
25import secrets
26import sys
27import threading
28from datetime import datetime, timezone
29from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
30from pathlib import Path
31from urllib.parse import unquote, urlsplit
32
33#: Serving only these names, from one directory, is what makes path traversal a
34#: non-question rather than a regex to get right twice.
35STATIC_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")
36CONTENT_TYPES = {
37 ".html": "text/html; charset=utf-8",
38 ".css": "text/css; charset=utf-8",
39 ".js": "text/javascript; charset=utf-8",
40 ".json": "application/json; charset=utf-8",
41 ".svg": "image/svg+xml",
42}
43
44#: The loopback names a browser may legitimately put in a Host header for this
45#: server. Anything else, including a public hostname that happens to resolve
46#: to 127.0.0.1 (which is how DNS rebinding reaches a local service), is refused
47#: before any handler runs.
48LOOPBACK_NAMES = {"127.0.0.1", "localhost", "::1"}
49
50MAX_BODY_BYTES = 64 * 1024
51DEFAULT_PORT = 8765
52
53#: One page, one stylesheet, one script. `connect-src 'self'` is the line that
54#: makes "no telemetry" checkable rather than promised.
55CSP = ("default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; "
56 "connect-src 'self'; font-src 'self'; form-action 'none'; frame-ancestors 'none'; "
57 "base-uri 'none'")
58
59
60class HttpError(Exception):
61 """A refusal with a status code and a message the operator can act on."""
62
63 def __init__(self, status: int, message: str, detail: str = ""):
64 super().__init__(message)
65 self.status = status
66 self.message = message
67 self.detail = detail
68
69
70def split_host(header: str) -> tuple[str, str]:
71 """('127.0.0.1', '8765') from a Host header, IPv6 brackets included."""
72 value = (header or "").strip()
73 if value.startswith("["):
74 close = value.find("]")
75 if close < 0:
76 return "", ""
77 name, rest = value[1:close], value[close + 1:]
78 if rest and not rest.startswith(":"):
79 return "", ""
80 return name.lower(), rest[1:]
81 name, _, port = value.partition(":")
82 return name.lower(), port
83
84
85def host_allowed(header: str, port: int) -> bool:
86 name, host_port = split_host(header)
87 if name not in LOOPBACK_NAMES:
88 return False
89 return host_port in ("", str(port))
90
91
92def origin_allowed(origin: str, port: int) -> bool:
93 """A write must come from this very page, so the Origin must be ours.
94
95 An absent Origin is refused rather than trusted: browsers send it on every
96 POST, so its absence means the request did not come from the dashboard.
97 """
98 if not origin:
99 return False
100 parsed = urlsplit(origin.strip())
101 if parsed.scheme != "http":
102 return False
103 if (parsed.hostname or "").lower() not in LOOPBACK_NAMES:
104 return False
105 return parsed.port in (None, port)
106
107
108class Workspace:
109 """Server-side state: the static directory, the notes, the CSRF token."""
110
111 def __init__(self, static_dir: Path):
112 self.static_dir = Path(static_dir).resolve()
113 #: Bound to this process, never persisted. Restarting the server
114 #: invalidates every token a stale tab is holding, which is the correct
115 #: outcome.
116 self.csrf_token = secrets.token_urlsafe(32)
117 self.notes: list[dict] = []
118 self._lock = threading.Lock()
119
120 def add_note(self, subject_id: str, body) -> dict:
121 if not isinstance(body, str) or not body.strip():
122 raise HttpError(422, "refused", "A note needs a non-empty text body.")
123 record = {"subject_id": subject_id, "body": body.strip(),
124 "created_at": datetime.now(timezone.utc).isoformat(timespec="seconds")}
125 with self._lock:
126 self.notes.append(record)
127 return record
128
129
130class DashboardHandler(BaseHTTPRequestHandler):
131 """Routing, and the checks that run before any route does."""
132
133 server_version = "leads-dashboard"
134 sys_version = ""
135 protocol_version = "HTTP/1.1"
136
137 @property
138 def app(self) -> Workspace:
139 return self.server.app # type: ignore[attr-defined]
140
141 # ---- plumbing -----------------------------------------------------
142 def log_message(self, fmt: str, *args) -> None:
143 # Local, minimal, and to stderr: a request log, not telemetry.
144 sys.stderr.write("dashboard %s - %s\n" % (self.address_string(), fmt % args))
145
146 def _send(self, status: int, body: bytes, content_type: str) -> None:
147 self.send_response(status)
148 self.send_header("Content-Type", content_type)
149 self.send_header("Content-Length", str(len(body)))
150 self.send_header("Content-Security-Policy", CSP)
151 self.send_header("X-Content-Type-Options", "nosniff")
152 self.send_header("X-Frame-Options", "DENY")
153 self.send_header("Referrer-Policy", "no-referrer")
154 self.send_header("Cross-Origin-Resource-Policy", "same-origin")
155 self.send_header("Cache-Control", "no-store")
156 self.end_headers()
157 if self.command != "HEAD":
158 self.wfile.write(body)
159
160 def _json(self, payload: dict, status: int = 200) -> None:
161 self._send(status, json.dumps(payload).encode("utf-8"), "application/json; charset=utf-8")
162
163 def _fail(self, error: HttpError) -> None:
164 self._json({"error": error.message, "detail": error.detail}, status=error.status)
165
166 # ---- guards -------------------------------------------------------
167 def _check_host(self) -> None:
168 """Refuse any Host but loopback, which is what stops DNS rebinding.
169
170 Binding to 127.0.0.1 keeps *packets* local; it does not stop a page at
171 evil.example from pointing a hostname at 127.0.0.1 and having the
172 browser send same-origin-looking requests here. The Host header is the
173 part of that attack that cannot be forged into looking local.
174 """
175 if not host_allowed(self.headers.get("Host", ""), self.server.server_address[1]):
176 raise HttpError(403, "host not allowed",
177 "This server answers only to 127.0.0.1 and localhost. Open it at "
178 "the URL the command printed.")
179
180 def _check_fetch_metadata(self) -> None:
181 site = (self.headers.get("Sec-Fetch-Site") or "").strip().lower()
182 if site and site not in ("same-origin", "none"):
183 raise HttpError(403, "cross-site request refused",
184 f"Sec-Fetch-Site was {site!r}; this server answers its own page only.")
185
186 def _check_write_guards(self) -> None:
187 port = self.server.server_address[1]
188 if not origin_allowed(self.headers.get("Origin", ""), port):
189 raise HttpError(403, "cross-origin write refused",
190 "A write must carry an Origin header from this dashboard.")
191 token = (self.headers.get("X-CSRF-Token") or "").strip()
192 if not token or not hmac.compare_digest(token, self.app.csrf_token):
193 raise HttpError(403, "missing or stale CSRF token",
194 "Reload the dashboard: the token is bound to this server process.")
195 ctype = (self.headers.get("Content-Type") or "").split(";")[0].strip().lower()
196 if ctype != "application/json":
197 raise HttpError(415, "unsupported content type",
198 "Writes are JSON. A form content type is refused on purpose: it is "
199 "the one a cross-site form could send without a preflight.")
200
201 def _read_body(self) -> dict:
202 raw = self.headers.get("Content-Length")
203 if raw is None:
204 raise HttpError(411, "length required", "A write must declare its Content-Length.")
205 try:
206 length = int(raw)
207 except ValueError:
208 raise HttpError(400, "bad Content-Length", "Content-Length must be an integer.")
209 if length < 0:
210 raise HttpError(400, "bad Content-Length", "Content-Length must not be negative.")
211 if length > MAX_BODY_BYTES:
212 raise HttpError(413, "request body too large",
213 f"The limit is {MAX_BODY_BYTES} bytes; this workspace stores notes, "
214 "not uploads.")
215 body = self.rfile.read(length) if length else b""
216 if not body:
217 raise HttpError(400, "empty request body", "Expected a JSON object.")
218 try:
219 payload = json.loads(body.decode("utf-8"))
220 except (UnicodeDecodeError, ValueError) as exc:
221 raise HttpError(400, "body is not valid JSON", str(exc))
222 if not isinstance(payload, dict):
223 raise HttpError(400, "body must be a JSON object",
224 f"got {type(payload).__name__}")
225 return payload
226
227 # ---- routes -------------------------------------------------------
228 def do_OPTIONS(self) -> None:
229 """Refuse the preflight, which is how a cross-origin JSON POST dies early."""
230 self._send(403, b"", "text/plain; charset=utf-8")
231
232 def do_HEAD(self) -> None:
233 self.do_GET()
234
235 def do_GET(self) -> None:
236 try:
237 self._check_host()
238 self._check_fetch_metadata()
239 path = unquote(urlsplit(self.path).path)
240 if path in ("/", "/index.html"):
241 return self._static("index.html")
242 if path.startswith("/static/"):
243 return self._static(path[len("/static/"):])
244 if path == "/api/session":
245 return self._json({"csrf_token": self.app.csrf_token})
246 if path == "/api/notes":
247 raise HttpError(405, "writes are POST only",
248 "A GET must never change stored state.")
249 raise HttpError(404, "no such path", path)
250 except HttpError as exc:
251 self._fail(exc)
252 except Exception as exc: # pragma: no cover - last resort
253 self.log_message("unhandled %s: %s", type(exc).__name__, exc)
254 self._fail(HttpError(500, "internal error", type(exc).__name__))
255
256 def do_POST(self) -> None:
257 try:
258 self._check_host()
259 self._check_fetch_metadata()
260 self._check_write_guards()
261 path = unquote(urlsplit(self.path).path)
262 if path != "/api/notes":
263 raise HttpError(404, "no such path", path)
264 payload = self._read_body()
265 subject_id = payload.get("subject_id", "")
266 if not isinstance(subject_id, str) or not subject_id.strip():
267 raise HttpError(400, "subject_id must be a non-empty string")
268 record = self.app.add_note(subject_id.strip(), payload.get("body"))
269 return self._json({"ok": True, "record": record}, status=201)
270 except HttpError as exc:
271 self._fail(exc)
272 except Exception as exc: # pragma: no cover - last resort
273 self.log_message("unhandled %s: %s", type(exc).__name__, exc)
274 self._fail(HttpError(500, "internal error", type(exc).__name__))
275
276 # ---- static -------------------------------------------------------
277 def _static(self, name: str) -> None:
278 """Serve one asset by name, never by a path from the browser."""
279 if not STATIC_NAME_RE.match(name):
280 raise HttpError(404, "no such asset", "Assets are served by name from one directory.")
281 root = self.app.static_dir
282 path = (root / name).resolve()
283 try:
284 path.relative_to(root)
285 except ValueError:
286 raise HttpError(404, "no such asset", name)
287 if not path.is_file():
288 raise HttpError(404, "no such asset", name)
289 content_type = CONTENT_TYPES.get(path.suffix)
290 if content_type is None:
291 raise HttpError(404, "no such asset", f"{path.suffix} is not served")
292 self._send(200, path.read_bytes(), content_type)
293
294
295class DashboardServer(ThreadingHTTPServer):
296 daemon_threads = True
297 allow_reuse_address = True
298
299 def __init__(self, address, app: Workspace):
300 self.app = app
301 super().__init__(address, DashboardHandler)
302
303
304def serve(static_dir: Path, port: int = DEFAULT_PORT, echo=print) -> int:
305 """Run until interrupted. The bind address is not configurable, by design."""
306 app = Workspace(static_dir)
307 server = DashboardServer(("127.0.0.1", port), app)
308 echo(f"dashboard http://127.0.0.1:{server.server_address[1]}/")
309 echo(" bound to 127.0.0.1 only; no outbound requests. Ctrl-C to stop.")
310 try:
311 server.serve_forever()
312 except KeyboardInterrupt:
313 echo("\nstopped.")
314 finally:
315 server.server_close()
316 return 0
317
318
319def main(argv: list[str] | None = None) -> int:
320 parser = argparse.ArgumentParser(prog="python3 -m leads.local_server",
321 description="Local review dashboard, loopback only.")
322 parser.add_argument("--static", type=Path, required=True,
323 help="directory holding index.html and its assets")
324 parser.add_argument("--port", type=int, default=DEFAULT_PORT,
325 help=f"loopback port (default {DEFAULT_PORT}; 0 picks a free one)")
326 args = parser.parse_args(argv)
327 if args.port < 0 or args.port > 65535:
328 parser.error("--port must be between 0 and 65535")
329 return serve(args.static, args.port)
330
331
332if __name__ == "__main__":
333 sys.exit(main())