localhost-guard 0.1.0__tar.gz
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.
- localhost_guard-0.1.0/LICENSE +21 -0
- localhost_guard-0.1.0/PKG-INFO +150 -0
- localhost_guard-0.1.0/README.md +137 -0
- localhost_guard-0.1.0/localhost_guard.egg-info/PKG-INFO +150 -0
- localhost_guard-0.1.0/localhost_guard.egg-info/SOURCES.txt +9 -0
- localhost_guard-0.1.0/localhost_guard.egg-info/dependency_links.txt +1 -0
- localhost_guard-0.1.0/localhost_guard.egg-info/top_level.txt +1 -0
- localhost_guard-0.1.0/localhost_guard.py +145 -0
- localhost_guard-0.1.0/pyproject.toml +22 -0
- localhost_guard-0.1.0/setup.cfg +4 -0
- localhost_guard-0.1.0/tests/test_localhost_guard.py +164 -0
|
@@ -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,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,137 @@
|
|
|
1
|
+
# localhost-guard
|
|
2
|
+
|
|
3
|
+
Your service listens on `127.0.0.1`, so it needs no login. Every page you visit
|
|
4
|
+
can still POST to it.
|
|
5
|
+
|
|
6
|
+
```
|
|
7
|
+
POST http://127.0.0.1:8765/api/quit HTTP/1.1
|
|
8
|
+
Origin: https://evil.example
|
|
9
|
+
Content-Type: text/plain
|
|
10
|
+
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
The browser sends it, your handler runs, the app exits. The port is not a secret
|
|
14
|
+
— a page can scan 8000–9000 in a second — and the request is indistinguishable
|
|
15
|
+
from the one your own UI issues. This is "drive-by localhost", and it works on
|
|
16
|
+
desktop shells, dev servers and anything else with a loopback HTTP API.
|
|
17
|
+
|
|
18
|
+
`localhost-guard` is the set of header checks that stops it, small enough to
|
|
19
|
+
paste into an existing `BaseHTTPRequestHandler`.
|
|
20
|
+
|
|
21
|
+
## Install
|
|
22
|
+
|
|
23
|
+
Not on PyPI yet — `pip install localhost-guard` will 404 until 0.1.0 is
|
|
24
|
+
published. Install from the repository instead:
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
pip install git+https://github.com/suimajian/localhost-guard
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
The sdist and wheel are attached to the
|
|
31
|
+
[releases](https://github.com/suimajian/localhost-guard/releases); the publish
|
|
32
|
+
step is waiting for credentials, so nothing has been uploaded to the index.
|
|
33
|
+
|
|
34
|
+
## Use
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
38
|
+
from localhost_guard import LoopbackOnly
|
|
39
|
+
|
|
40
|
+
class Handler(LoopbackOnly, BaseHTTPRequestHandler):
|
|
41
|
+
def do_GET(self):
|
|
42
|
+
if not self.guard():
|
|
43
|
+
return # response already written: 403 or 415
|
|
44
|
+
self.reply({"ok": True})
|
|
45
|
+
|
|
46
|
+
def do_POST(self):
|
|
47
|
+
if not self.guard():
|
|
48
|
+
return
|
|
49
|
+
...
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Or call the pure function when you have your own framework:
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
from localhost_guard import check
|
|
56
|
+
|
|
57
|
+
decision = check("POST", request.headers)
|
|
58
|
+
if not decision.allowed:
|
|
59
|
+
return Response(decision.reason, status=decision.status)
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## The four checks
|
|
63
|
+
|
|
64
|
+
| Header | Refuse when | Stops |
|
|
65
|
+
| --- | --- | --- |
|
|
66
|
+
| `Host` | not `127.0.0.1`, `localhost`, `[::1]`, or empty/missing on a write | DNS rebinding |
|
|
67
|
+
| `Sec-Fetch-Site` | `cross-site` (when present) | another page's request |
|
|
68
|
+
| `Origin` | not loopback, or `null` | cross-origin `fetch`/form posts |
|
|
69
|
+
| `Content-Type` | write without `application/json` | cross-origin form posts |
|
|
70
|
+
|
|
71
|
+
No single check is enough. `Sec-Fetch-*` is missing from older browsers, `Origin`
|
|
72
|
+
is omitted on same-origin GETs, and a cross-origin `fetch` with
|
|
73
|
+
`Content-Type: application/json` triggers a preflight your service never answers
|
|
74
|
+
— so it never arrives. That last one is why `require_json` is on by default for
|
|
75
|
+
writes: an HTML form cannot send that media type, so the drive-by request fails
|
|
76
|
+
before your handler sees it.
|
|
77
|
+
|
|
78
|
+
`trusted_origins` exists for the case where your own UI is served from a real
|
|
79
|
+
host during development:
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
class Handler(LoopbackOnly, BaseHTTPRequestHandler):
|
|
83
|
+
trusted_origins = ("https://demo.example",)
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## What this does not cover
|
|
87
|
+
|
|
88
|
+
- **GET is always allowed.** A cross-site page can still trigger a GET to
|
|
89
|
+
`http://127.0.0.1:PORT/...`, because reads need no preflight and no CORS
|
|
90
|
+
approval. Never put a state change behind GET (`/delete?id=`, `/sync`,
|
|
91
|
+
`/switch-profile`) — that endpoint is unprotected no matter what this library
|
|
92
|
+
does. Either keep every mutation on POST/PUT/PATCH/DELETE, or call
|
|
93
|
+
`guard(write=True)` in that handler so the write rules apply to it anyway.
|
|
94
|
+
- **It is a function, not middleware.** Every handler has to call it; one handler
|
|
95
|
+
that forgets is one unguarded endpoint, silently. If you want it enforced
|
|
96
|
+
structurally, wrap your framework's dispatcher so a response cannot be produced
|
|
97
|
+
without a `Decision`.
|
|
98
|
+
- **`require_json=True` rejects file uploads.** `multipart/form-data` and
|
|
99
|
+
`fetch(..., body: new FormData())` get 415 by design; pass `require_json=False`
|
|
100
|
+
on upload routes and lean on `Sec-Fetch-Site` there.
|
|
101
|
+
- A local process running as another user on the same machine can send whatever
|
|
102
|
+
headers it likes. This is a browser-threat model, not an OS one.
|
|
103
|
+
- It does not replace authentication if the service is ever bound to a
|
|
104
|
+
non-loopback interface.
|
|
105
|
+
- **A write with no `Host` header is rejected, not trusted.** An empty or missing
|
|
106
|
+
`Host` is not loopback: it means something other than a browser reached you, so
|
|
107
|
+
the request gets 403. Reads without a `Host` are allowed, which keeps `curl
|
|
108
|
+
http://127.0.0.1:PORT/` working.
|
|
109
|
+
|
|
110
|
+
## Scope and non-goals
|
|
111
|
+
|
|
112
|
+
- **Not a framework integration.** Flask/Django/FastAPI adapters are out of scope;
|
|
113
|
+
the package is one zero-dependency module you copy or import.
|
|
114
|
+
- **Not CSRF tokens.** There is no session, no token store, no cookie — the checks
|
|
115
|
+
are header-based (Host, `Sec-Fetch-Site`, Origin, and a JSON content type on
|
|
116
|
+
writes). If you need per-session tokens, add them; this is the cheap floor.
|
|
117
|
+
- **Not protection against local processes.** Anything running as another user on
|
|
118
|
+
the same box can forge headers. That is the browser threat model's edge.
|
|
119
|
+
|
|
120
|
+
## Status
|
|
121
|
+
|
|
122
|
+
0.1.0 — not on PyPI yet. A tag (`v*`) builds sdist + wheel and uploads them as a
|
|
123
|
+
workflow artifact; the publish step only runs when a `PYPI_API_TOKEN` repository
|
|
124
|
+
secret exists, so nothing is published by accident.
|
|
125
|
+
|
|
126
|
+
## Tests
|
|
127
|
+
|
|
128
|
+
```bash
|
|
129
|
+
python -m pytest -q
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
Nineteen cases: the unit checks, plus a real `ThreadingHTTPServer` on an ephemeral
|
|
133
|
+
port to prove the mixin writes 403 for a cross-site POST and 415 for a form post.
|
|
134
|
+
|
|
135
|
+
## Licence
|
|
136
|
+
|
|
137
|
+
MIT.
|
|
@@ -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 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
localhost_guard
|
|
@@ -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
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "localhost-guard"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Header checks that stop a random web page from driving your loopback HTTP service"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [{ name = "suimajian" }]
|
|
13
|
+
keywords = ["localhost", "csrf", "dns-rebinding", "security", "http"]
|
|
14
|
+
|
|
15
|
+
[project.urls]
|
|
16
|
+
Homepage = "https://github.com/suimajian/localhost-guard"
|
|
17
|
+
|
|
18
|
+
[tool.setuptools]
|
|
19
|
+
py-modules = ["localhost_guard"]
|
|
20
|
+
|
|
21
|
+
[tool.pytest.ini_options]
|
|
22
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import http.client
|
|
4
|
+
import threading
|
|
5
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
6
|
+
|
|
7
|
+
import pytest
|
|
8
|
+
|
|
9
|
+
from localhost_guard import Decision, LoopbackOnly, check
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def test_plain_loopback_get_is_allowed():
|
|
13
|
+
assert check("GET", {"Host": "127.0.0.1:8080"}).allowed
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def test_localhost_and_empty_host_allowed():
|
|
17
|
+
assert check("GET", {"Host": "localhost:9"}).allowed
|
|
18
|
+
assert check("GET", {}).allowed
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def test_rebinding_host_is_rejected():
|
|
22
|
+
d = check("GET", {"Host": "evil.example:8080"})
|
|
23
|
+
assert not d.allowed and d.status == 403
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def test_cross_site_post_is_rejected():
|
|
27
|
+
d = check("POST", {"Host": "127.0.0.1:8080", "Sec-Fetch-Site": "cross-site",
|
|
28
|
+
"Content-Type": "application/json"})
|
|
29
|
+
assert not d.allowed and "cross-site" in d.reason
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def test_same_origin_post_with_json_is_allowed():
|
|
33
|
+
d = check("POST", {"Host": "127.0.0.1:8080", "Sec-Fetch-Site": "same-origin",
|
|
34
|
+
"Content-Type": "application/json"})
|
|
35
|
+
assert d.allowed
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def test_foreign_origin_is_rejected():
|
|
39
|
+
d = check("POST", {"Host": "127.0.0.1:8080", "Origin": "https://evil.example",
|
|
40
|
+
"Content-Type": "application/json"})
|
|
41
|
+
assert not d.allowed and d.status == 403
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def test_loopback_origin_allowed_and_trusted_origin_can_be_added():
|
|
45
|
+
assert check("POST", {"Host": "127.0.0.1:8080", "Origin": "http://localhost:5173",
|
|
46
|
+
"Content-Type": "application/json"}).allowed
|
|
47
|
+
assert check("POST", {"Host": "127.0.0.1:8080", "Origin": "https://demo.example",
|
|
48
|
+
"Content-Type": "application/json"},
|
|
49
|
+
trusted_origins=("https://demo.example",)).allowed
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def test_opaque_origin_rejected():
|
|
53
|
+
assert not check("POST", {"Host": "127.0.0.1:1", "Origin": "null",
|
|
54
|
+
"Content-Type": "application/json"}).allowed
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def test_form_encoded_post_rejected():
|
|
58
|
+
d = check("POST", {"Host": "127.0.0.1:8080", "Content-Type": "application/x-www-form-urlencoded"})
|
|
59
|
+
assert not d.allowed and d.status == 415
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def test_form_encoded_post_allowed_when_json_not_required():
|
|
63
|
+
assert check("POST", {"Host": "127.0.0.1:8080",
|
|
64
|
+
"Content-Type": "application/x-www-form-urlencoded"},
|
|
65
|
+
require_json=False).allowed
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def test_json_with_charset_is_accepted():
|
|
69
|
+
assert check("POST", {"Host": "127.0.0.1:8080",
|
|
70
|
+
"Content-Type": "application/json; charset=utf-8"}).allowed
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def test_decision_is_falsy_when_denied():
|
|
74
|
+
assert not Decision(False)
|
|
75
|
+
assert Decision(True)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
# --- end to end: a real server behind the mixin -------------------------------
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class _Handler(LoopbackOnly, BaseHTTPRequestHandler):
|
|
82
|
+
def do_GET(self):
|
|
83
|
+
if not self.guard():
|
|
84
|
+
return
|
|
85
|
+
self.send_response(200)
|
|
86
|
+
self.end_headers()
|
|
87
|
+
self.wfile.write(b"ok")
|
|
88
|
+
|
|
89
|
+
def do_POST(self):
|
|
90
|
+
if not self.guard():
|
|
91
|
+
return
|
|
92
|
+
length = int(self.headers.get("Content-Length") or 0)
|
|
93
|
+
self.rfile.read(length)
|
|
94
|
+
self.send_response(200)
|
|
95
|
+
self.end_headers()
|
|
96
|
+
self.wfile.write(b"ok")
|
|
97
|
+
|
|
98
|
+
def log_message(self, *args): # keep test output clean
|
|
99
|
+
pass
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@pytest.fixture()
|
|
103
|
+
def server():
|
|
104
|
+
httpd = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
|
|
105
|
+
thread = threading.Thread(target=httpd.serve_forever, daemon=True)
|
|
106
|
+
thread.start()
|
|
107
|
+
try:
|
|
108
|
+
yield httpd.server_address[1]
|
|
109
|
+
finally:
|
|
110
|
+
httpd.shutdown()
|
|
111
|
+
httpd.server_close()
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _request(port, method, headers=None, body=None):
|
|
115
|
+
conn = http.client.HTTPConnection("127.0.0.1", port, timeout=5)
|
|
116
|
+
try:
|
|
117
|
+
conn.request(method, "/api", body=body, headers=headers or {})
|
|
118
|
+
response = conn.getresponse()
|
|
119
|
+
return response.status, response.read(), dict(response.getheaders())
|
|
120
|
+
finally:
|
|
121
|
+
conn.close()
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def test_server_allows_same_origin_post(server):
|
|
125
|
+
status, body, _ = _request(server, "POST",
|
|
126
|
+
{"Content-Type": "application/json",
|
|
127
|
+
"Sec-Fetch-Site": "same-origin"}, b"{}")
|
|
128
|
+
assert status == 200 and body == b"ok"
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def test_server_refuses_cross_site_post(server):
|
|
132
|
+
status, body, headers = _request(server, "POST",
|
|
133
|
+
{"Content-Type": "application/json",
|
|
134
|
+
"Sec-Fetch-Site": "cross-site"}, b"{}")
|
|
135
|
+
assert status == 403
|
|
136
|
+
assert "cross-site" in headers.get("X-Guard-Reason", "")
|
|
137
|
+
assert body # the reason is written to the client too
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def test_server_refuses_form_post(server):
|
|
141
|
+
status, _, headers = _request(server, "POST",
|
|
142
|
+
{"Content-Type": "application/x-www-form-urlencoded"},
|
|
143
|
+
b"a=1")
|
|
144
|
+
assert status == 415
|
|
145
|
+
assert "application/json" in headers.get("X-Guard-Reason", "")
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def test_server_allows_plain_get(server):
|
|
149
|
+
status, body, _ = _request(server, "GET")
|
|
150
|
+
assert status == 200 and body == b"ok"
|
|
151
|
+
|
|
152
|
+
def test_write_without_host_header_is_refused():
|
|
153
|
+
d = check("POST", {"content-type": "application/json"}, )
|
|
154
|
+
assert not d and d.status == 403
|
|
155
|
+
assert "Host" in d.reason
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def test_read_without_host_header_is_allowed():
|
|
159
|
+
assert check("GET", {})
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def test_empty_host_string_is_not_loopback():
|
|
163
|
+
d = check("POST", {"host": "", "content-type": "application/json"})
|
|
164
|
+
assert not d and d.status == 403
|