localhost-guard 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.
@@ -0,0 +1,150 @@
1
+ Metadata-Version: 2.4
2
+ Name: localhost-guard
3
+ Version: 0.1.0
4
+ Summary: Header checks that stop a random web page from driving your loopback HTTP service
5
+ Author: suimajian
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/suimajian/localhost-guard
8
+ Keywords: localhost,csrf,dns-rebinding,security,http
9
+ Requires-Python: >=3.9
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Dynamic: license-file
13
+
14
+ # localhost-guard
15
+
16
+ Your service listens on `127.0.0.1`, so it needs no login. Every page you visit
17
+ can still POST to it.
18
+
19
+ ```
20
+ POST http://127.0.0.1:8765/api/quit HTTP/1.1
21
+ Origin: https://evil.example
22
+ Content-Type: text/plain
23
+
24
+ ```
25
+
26
+ The browser sends it, your handler runs, the app exits. The port is not a secret
27
+ — a page can scan 8000–9000 in a second — and the request is indistinguishable
28
+ from the one your own UI issues. This is "drive-by localhost", and it works on
29
+ desktop shells, dev servers and anything else with a loopback HTTP API.
30
+
31
+ `localhost-guard` is the set of header checks that stops it, small enough to
32
+ paste into an existing `BaseHTTPRequestHandler`.
33
+
34
+ ## Install
35
+
36
+ Not on PyPI yet — `pip install localhost-guard` will 404 until 0.1.0 is
37
+ published. Install from the repository instead:
38
+
39
+ ```bash
40
+ pip install git+https://github.com/suimajian/localhost-guard
41
+ ```
42
+
43
+ The sdist and wheel are attached to the
44
+ [releases](https://github.com/suimajian/localhost-guard/releases); the publish
45
+ step is waiting for credentials, so nothing has been uploaded to the index.
46
+
47
+ ## Use
48
+
49
+ ```python
50
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
51
+ from localhost_guard import LoopbackOnly
52
+
53
+ class Handler(LoopbackOnly, BaseHTTPRequestHandler):
54
+ def do_GET(self):
55
+ if not self.guard():
56
+ return # response already written: 403 or 415
57
+ self.reply({"ok": True})
58
+
59
+ def do_POST(self):
60
+ if not self.guard():
61
+ return
62
+ ...
63
+ ```
64
+
65
+ Or call the pure function when you have your own framework:
66
+
67
+ ```python
68
+ from localhost_guard import check
69
+
70
+ decision = check("POST", request.headers)
71
+ if not decision.allowed:
72
+ return Response(decision.reason, status=decision.status)
73
+ ```
74
+
75
+ ## The four checks
76
+
77
+ | Header | Refuse when | Stops |
78
+ | --- | --- | --- |
79
+ | `Host` | not `127.0.0.1`, `localhost`, `[::1]`, or empty/missing on a write | DNS rebinding |
80
+ | `Sec-Fetch-Site` | `cross-site` (when present) | another page's request |
81
+ | `Origin` | not loopback, or `null` | cross-origin `fetch`/form posts |
82
+ | `Content-Type` | write without `application/json` | cross-origin form posts |
83
+
84
+ No single check is enough. `Sec-Fetch-*` is missing from older browsers, `Origin`
85
+ is omitted on same-origin GETs, and a cross-origin `fetch` with
86
+ `Content-Type: application/json` triggers a preflight your service never answers
87
+ — so it never arrives. That last one is why `require_json` is on by default for
88
+ writes: an HTML form cannot send that media type, so the drive-by request fails
89
+ before your handler sees it.
90
+
91
+ `trusted_origins` exists for the case where your own UI is served from a real
92
+ host during development:
93
+
94
+ ```python
95
+ class Handler(LoopbackOnly, BaseHTTPRequestHandler):
96
+ trusted_origins = ("https://demo.example",)
97
+ ```
98
+
99
+ ## What this does not cover
100
+
101
+ - **GET is always allowed.** A cross-site page can still trigger a GET to
102
+ `http://127.0.0.1:PORT/...`, because reads need no preflight and no CORS
103
+ approval. Never put a state change behind GET (`/delete?id=`, `/sync`,
104
+ `/switch-profile`) — that endpoint is unprotected no matter what this library
105
+ does. Either keep every mutation on POST/PUT/PATCH/DELETE, or call
106
+ `guard(write=True)` in that handler so the write rules apply to it anyway.
107
+ - **It is a function, not middleware.** Every handler has to call it; one handler
108
+ that forgets is one unguarded endpoint, silently. If you want it enforced
109
+ structurally, wrap your framework's dispatcher so a response cannot be produced
110
+ without a `Decision`.
111
+ - **`require_json=True` rejects file uploads.** `multipart/form-data` and
112
+ `fetch(..., body: new FormData())` get 415 by design; pass `require_json=False`
113
+ on upload routes and lean on `Sec-Fetch-Site` there.
114
+ - A local process running as another user on the same machine can send whatever
115
+ headers it likes. This is a browser-threat model, not an OS one.
116
+ - It does not replace authentication if the service is ever bound to a
117
+ non-loopback interface.
118
+ - **A write with no `Host` header is rejected, not trusted.** An empty or missing
119
+ `Host` is not loopback: it means something other than a browser reached you, so
120
+ the request gets 403. Reads without a `Host` are allowed, which keeps `curl
121
+ http://127.0.0.1:PORT/` working.
122
+
123
+ ## Scope and non-goals
124
+
125
+ - **Not a framework integration.** Flask/Django/FastAPI adapters are out of scope;
126
+ the package is one zero-dependency module you copy or import.
127
+ - **Not CSRF tokens.** There is no session, no token store, no cookie — the checks
128
+ are header-based (Host, `Sec-Fetch-Site`, Origin, and a JSON content type on
129
+ writes). If you need per-session tokens, add them; this is the cheap floor.
130
+ - **Not protection against local processes.** Anything running as another user on
131
+ the same box can forge headers. That is the browser threat model's edge.
132
+
133
+ ## Status
134
+
135
+ 0.1.0 — not on PyPI yet. A tag (`v*`) builds sdist + wheel and uploads them as a
136
+ workflow artifact; the publish step only runs when a `PYPI_API_TOKEN` repository
137
+ secret exists, so nothing is published by accident.
138
+
139
+ ## Tests
140
+
141
+ ```bash
142
+ python -m pytest -q
143
+ ```
144
+
145
+ Nineteen cases: the unit checks, plus a real `ThreadingHTTPServer` on an ephemeral
146
+ port to prove the mixin writes 403 for a cross-site POST and 415 for a form post.
147
+
148
+ ## Licence
149
+
150
+ MIT.
@@ -0,0 +1,6 @@
1
+ localhost_guard.py,sha256=MoqEz1ct3CIEYUQ9GYoTpvqjnL6WV_m8LDSHCtVPKFs,5854
2
+ localhost_guard-0.1.0.dist-info/licenses/LICENSE,sha256=3zJsa_ylIITLNIbTT7jWBjxzTN0n46bsm9IF17b2VCo,1066
3
+ localhost_guard-0.1.0.dist-info/METADATA,sha256=7rkfQv06niH0cm2n4LLRAbA7U35WQUoO6HoIixUEKMw,5702
4
+ localhost_guard-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
5
+ localhost_guard-0.1.0.dist-info/top_level.txt,sha256=omAxx6PlYcW6SjeMAD6wUw6lf8Q4QthRW8KAPBtmI4g,16
6
+ localhost_guard-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 suimajian
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ localhost_guard
localhost_guard.py ADDED
@@ -0,0 +1,145 @@
1
+ """Reject cross-origin requests to a service that listens on loopback.
2
+
3
+ A local HTTP API has no login, because it is only reachable from your machine.
4
+ That reasoning is wrong: any web page you visit can send requests to
5
+ ``http://127.0.0.1:<port>/`` — the browser will happily POST there, and the
6
+ service cannot tell the difference from a request its own UI made. Attackers
7
+ call it "drive-by localhost": the page probes a list of common ports and issues
8
+ ``POST /api/quit``, ``/api/shutdown``, ``/api/export`` and so on.
9
+
10
+ The port is not secret (the attacker can scan), so the defence has to be a
11
+ header check the browser will not let the page forge:
12
+
13
+ * ``Host`` — the service only answers to loopback names, which stops DNS
14
+ rebinding;
15
+ * ``Sec-Fetch-Site`` — ``cross-site`` is what another page's request looks like,
16
+ and pages cannot set it;
17
+ * ``Origin`` — for requests that carry it, refuse anything that is not loopback;
18
+ * ``Content-Type`` — a cross-origin HTML form can only send urlencoded,
19
+ multipart or text/plain. A service that demands ``application/json`` is not
20
+ reachable that way, because that media type requires a CORS preflight.
21
+
22
+ No single check is sufficient on its own, which is why all four are here: older
23
+ browsers omit ``Sec-Fetch-*``, and ``Origin`` is missing from same-origin GETs.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ from typing import Iterable, Mapping, Optional
29
+
30
+ __all__ = ["Decision", "check", "LoopbackOnly"]
31
+
32
+ LOOPBACK_HOSTS = frozenset({"127.0.0.1", "localhost", "[::1]", "::1"})
33
+ SAFE_SITES = frozenset({"same-origin", "same-site", "none"})
34
+ WRITE_METHODS = frozenset({"POST", "PUT", "PATCH", "DELETE"})
35
+ JSON_CONTENT_TYPE = "application/json"
36
+
37
+
38
+ class Decision:
39
+ """Outcome of a check: allowed, or refused with a reason for the log."""
40
+
41
+ __slots__ = ("allowed", "status", "reason")
42
+
43
+ def __init__(self, allowed: bool, status: int = 200, reason: str = "") -> None:
44
+ self.allowed = allowed
45
+ self.status = status
46
+ self.reason = reason
47
+
48
+ def __bool__(self) -> bool:
49
+ return self.allowed
50
+
51
+ def __repr__(self) -> str: # pragma: no cover - debugging aid
52
+ return f"Decision(allowed={self.allowed!r}, status={self.status!r}, reason={self.reason!r})"
53
+
54
+
55
+ _ALLOW = Decision(True)
56
+
57
+
58
+ def _host_port(host_header: str) -> str:
59
+ host = host_header.strip().lower()
60
+ if host.startswith("["): # [::1]:8080
61
+ end = host.find("]")
62
+ return host[: end + 1] if end != -1 else host
63
+ return host.split(":", 1)[0]
64
+
65
+
66
+ def check(method: str,
67
+ headers: Mapping[str, str],
68
+ *,
69
+ trusted_origins: Iterable[str] = (),
70
+ require_json: bool = True) -> Decision:
71
+ """Decide whether a request may touch the service.
72
+
73
+ ``headers`` is case-insensitive in practice; pass the request headers as a
74
+ plain mapping and the lookup below lower-cases both sides.
75
+ """
76
+ lowered = {k.lower(): v for k, v in headers.items()}
77
+ host = _host_port(lowered.get("host", ""))
78
+ if not host:
79
+ # No Host at all: HTTP/1.0, or something in the middle stripped it. A
80
+ # browser always sends one, so a write without it is not a browser we
81
+ # want to serve; a read is harmless and keeps old clients working.
82
+ if method.upper() in WRITE_METHODS:
83
+ return Decision(False, 403, "write without a Host header")
84
+ return _ALLOW
85
+ if host not in LOOPBACK_HOSTS:
86
+ return Decision(False, 403, f"host not loopback: {lowered.get('host')!r}")
87
+
88
+ site = lowered.get("sec-fetch-site", "")
89
+ if site and site not in SAFE_SITES:
90
+ return Decision(False, 403, f"cross-site request: sec-fetch-site={site!r}")
91
+
92
+ origin = lowered.get("origin", "")
93
+ if origin:
94
+ # A page loaded from file:// (or a sandboxed frame) sends "null"; treat it
95
+ # like any other stranger. Everything else only counts when it is loopback.
96
+ if origin == "null":
97
+ return Decision(False, 403, "opaque origin")
98
+ if origin.rstrip("/") not in {o.rstrip("/") for o in trusted_origins}:
99
+ origin_host = _host_port(origin.split("://", 1)[-1])
100
+ if origin_host not in LOOPBACK_HOSTS:
101
+ return Decision(False, 403, f"untrusted origin: {origin!r}")
102
+
103
+ if require_json and method.upper() in WRITE_METHODS:
104
+ ctype = lowered.get("content-type", "").split(";", 1)[0].strip().lower()
105
+ if ctype != JSON_CONTENT_TYPE:
106
+ return Decision(False, 415, f"write requires application/json, got {ctype!r}")
107
+
108
+ return _ALLOW
109
+
110
+
111
+ class LoopbackOnly:
112
+ """Mixin for :class:`http.server.BaseHTTPRequestHandler` subclasses.
113
+
114
+ Subclass it first, then call :meth:`guard` at the top of ``do_GET`` and
115
+ ``do_POST``::
116
+
117
+ class Handler(LoopbackOnly, BaseHTTPRequestHandler):
118
+ def do_POST(self):
119
+ if not self.guard():
120
+ return
121
+ ...
122
+
123
+ When the request is refused, ``guard`` has already written the response.
124
+ """
125
+
126
+ trusted_origins: tuple[str, ...] = ()
127
+ require_json: bool = True
128
+
129
+ def guard(self, *, write: Optional[bool] = None) -> bool:
130
+ method = getattr(self, "command", "GET")
131
+ if write is None:
132
+ write = method.upper() in WRITE_METHODS
133
+ decision = check(method, self.headers, trusted_origins=self.trusted_origins,
134
+ require_json=write and self.require_json)
135
+ if decision.allowed:
136
+ return True
137
+ self.send_response(decision.status)
138
+ self.send_header("Content-Type", "text/plain; charset=utf-8")
139
+ self.send_header("X-Guard-Reason", decision.reason)
140
+ self.end_headers()
141
+ try:
142
+ self.wfile.write(decision.reason.encode("utf-8", "replace"))
143
+ except Exception: # peer already gone
144
+ pass
145
+ return False