awport 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.
- awport-0.1.0/PKG-INFO +61 -0
- awport-0.1.0/README.md +42 -0
- awport-0.1.0/awport/__init__.py +52 -0
- awport-0.1.0/awport/cli.py +484 -0
- awport-0.1.0/awport/crypto.py +353 -0
- awport-0.1.0/awport/firewall.py +265 -0
- awport-0.1.0/awport/forward.py +931 -0
- awport-0.1.0/awport/store.py +284 -0
- awport-0.1.0/awport.egg-info/PKG-INFO +61 -0
- awport-0.1.0/awport.egg-info/SOURCES.txt +15 -0
- awport-0.1.0/awport.egg-info/dependency_links.txt +1 -0
- awport-0.1.0/awport.egg-info/entry_points.txt +2 -0
- awport-0.1.0/awport.egg-info/requires.txt +14 -0
- awport-0.1.0/awport.egg-info/top_level.txt +1 -0
- awport-0.1.0/pyproject.toml +29 -0
- awport-0.1.0/setup.cfg +4 -0
- awport-0.1.0/tests/test_awport.py +315 -0
awport-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: awport
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Leased, firewall-gated, end-to-end encrypted TCP/UDP port forwarding for AitherMesh and AitherNet
|
|
5
|
+
License: Apache-2.0
|
|
6
|
+
Requires-Python: >=3.10
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
Requires-Dist: awdit
|
|
9
|
+
Requires-Dist: awnet
|
|
10
|
+
Requires-Dist: awseal
|
|
11
|
+
Requires-Dist: awwall
|
|
12
|
+
Requires-Dist: cryptography>=41
|
|
13
|
+
Provides-Extra: alerts
|
|
14
|
+
Requires-Dist: awlert; extra == "alerts"
|
|
15
|
+
Provides-Extra: tunnel
|
|
16
|
+
Requires-Dist: awtunnel; extra == "tunnel"
|
|
17
|
+
Provides-Extra: dev
|
|
18
|
+
Requires-Dist: pytest>=7; extra == "dev"
|
|
19
|
+
|
|
20
|
+
# awport
|
|
21
|
+
|
|
22
|
+
Leased, firewall-gated, end-to-end encrypted TCP/UDP port forwarding for **AitherMesh** (`10.77.0.0/16` / Headscale `100.64.0.0/10`) and **AitherNet**.
|
|
23
|
+
|
|
24
|
+
Instead of trusting a forgotten `ssh -L`, a stale netavark DNAT rule, or an unguarded open port, **`awport`** gives you an **Ed25519-signed (`awseal`), TTL-bounded, `awwall` + `AitherFirewall`-gated, live-verified forward** whose opens, closes, denials, and drifts are recorded in **`awdit`** and alerted via **`awlert`**.
|
|
25
|
+
|
|
26
|
+
## What it composes
|
|
27
|
+
|
|
28
|
+
- **`awwall`** — fail-closed outbound/egress allowlist before opening any forward.
|
|
29
|
+
- **`AitherFirewall`** (`:8213`) — stateful inbound gate (`POST /firewall/evaluate`, `POST /firewall/zone/lookup`) and active threat feedback (`POST /firewall/threat-report`) when peers fail crypto auth or tamper with frames.
|
|
30
|
+
- **`awseal`** + `cryptography` — Ed25519 signed leases + forward-secret **X25519 + Ed25519 + AES-256-GCM** encrypted stream relay (`awport/v1`) for untrusted AitherNet hops.
|
|
31
|
+
- **`awnet`** — 3-valued upstream reachability (`ok` / `unreachable` / `unknown`) + live listener & round-trip checks.
|
|
32
|
+
- **`awdit`** — tamper-evident, anchored hash-chain log of every lease & denial.
|
|
33
|
+
- **`awlert`** — signed fleet notifications (Discord ops / `awrelay` / encrypted webhooks) on opens, exposures, denials, and health drift.
|
|
34
|
+
- **`awtunnel`** — optional temporary public HTTPS exposure for `--scope public`.
|
|
35
|
+
|
|
36
|
+
## Quick start
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
awport --self-test
|
|
40
|
+
awport mesh-ip
|
|
41
|
+
|
|
42
|
+
# Local/Mesh TCP or UDP forward with hard TTL & firewall gating
|
|
43
|
+
awport forward 127.0.0.1:11434 10.77.0.12:11434 --ttl 2h
|
|
44
|
+
awport forward 127.0.0.1:25565 10.77.0.12:25565 --proto udp --ttl 4h
|
|
45
|
+
|
|
46
|
+
# Expose a local port onto the AitherMesh interface (auto-detects 10.77/100.64)
|
|
47
|
+
awport expose 47960 --scope mesh --ttl 1h
|
|
48
|
+
|
|
49
|
+
# End-to-end encrypted AitherNet relay (mutual Ed25519 + X25519 + AES-256-GCM)
|
|
50
|
+
awport relay-serve 0.0.0.0:9443 127.0.0.1:8080 --allow-peer <client_ed25519_pubkey_hex>
|
|
51
|
+
awport relay-connect 127.0.0.1:8080 relay.example:9443 --expect-peer <server_ed25519_pubkey_hex>
|
|
52
|
+
|
|
53
|
+
# Daemon & fleet inspection
|
|
54
|
+
awport daemon # persistent lease manager + TTL reaper + health watchdog
|
|
55
|
+
awport ls # list active leased forwards + byte/conn counters
|
|
56
|
+
awport verify # live listener + awnet upstream + round-trip check
|
|
57
|
+
awport audit-verify # verify awdit hash chain (0 ok / 1 tampered / 2 missing)
|
|
58
|
+
awport firewall-status # check awwall + AitherFirewall (:8213) status
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Apache-2.0.
|
awport-0.1.0/README.md
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# awport
|
|
2
|
+
|
|
3
|
+
Leased, firewall-gated, end-to-end encrypted TCP/UDP port forwarding for **AitherMesh** (`10.77.0.0/16` / Headscale `100.64.0.0/10`) and **AitherNet**.
|
|
4
|
+
|
|
5
|
+
Instead of trusting a forgotten `ssh -L`, a stale netavark DNAT rule, or an unguarded open port, **`awport`** gives you an **Ed25519-signed (`awseal`), TTL-bounded, `awwall` + `AitherFirewall`-gated, live-verified forward** whose opens, closes, denials, and drifts are recorded in **`awdit`** and alerted via **`awlert`**.
|
|
6
|
+
|
|
7
|
+
## What it composes
|
|
8
|
+
|
|
9
|
+
- **`awwall`** — fail-closed outbound/egress allowlist before opening any forward.
|
|
10
|
+
- **`AitherFirewall`** (`:8213`) — stateful inbound gate (`POST /firewall/evaluate`, `POST /firewall/zone/lookup`) and active threat feedback (`POST /firewall/threat-report`) when peers fail crypto auth or tamper with frames.
|
|
11
|
+
- **`awseal`** + `cryptography` — Ed25519 signed leases + forward-secret **X25519 + Ed25519 + AES-256-GCM** encrypted stream relay (`awport/v1`) for untrusted AitherNet hops.
|
|
12
|
+
- **`awnet`** — 3-valued upstream reachability (`ok` / `unreachable` / `unknown`) + live listener & round-trip checks.
|
|
13
|
+
- **`awdit`** — tamper-evident, anchored hash-chain log of every lease & denial.
|
|
14
|
+
- **`awlert`** — signed fleet notifications (Discord ops / `awrelay` / encrypted webhooks) on opens, exposures, denials, and health drift.
|
|
15
|
+
- **`awtunnel`** — optional temporary public HTTPS exposure for `--scope public`.
|
|
16
|
+
|
|
17
|
+
## Quick start
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
awport --self-test
|
|
21
|
+
awport mesh-ip
|
|
22
|
+
|
|
23
|
+
# Local/Mesh TCP or UDP forward with hard TTL & firewall gating
|
|
24
|
+
awport forward 127.0.0.1:11434 10.77.0.12:11434 --ttl 2h
|
|
25
|
+
awport forward 127.0.0.1:25565 10.77.0.12:25565 --proto udp --ttl 4h
|
|
26
|
+
|
|
27
|
+
# Expose a local port onto the AitherMesh interface (auto-detects 10.77/100.64)
|
|
28
|
+
awport expose 47960 --scope mesh --ttl 1h
|
|
29
|
+
|
|
30
|
+
# End-to-end encrypted AitherNet relay (mutual Ed25519 + X25519 + AES-256-GCM)
|
|
31
|
+
awport relay-serve 0.0.0.0:9443 127.0.0.1:8080 --allow-peer <client_ed25519_pubkey_hex>
|
|
32
|
+
awport relay-connect 127.0.0.1:8080 relay.example:9443 --expect-peer <server_ed25519_pubkey_hex>
|
|
33
|
+
|
|
34
|
+
# Daemon & fleet inspection
|
|
35
|
+
awport daemon # persistent lease manager + TTL reaper + health watchdog
|
|
36
|
+
awport ls # list active leased forwards + byte/conn counters
|
|
37
|
+
awport verify # live listener + awnet upstream + round-trip check
|
|
38
|
+
awport audit-verify # verify awdit hash chain (0 ok / 1 tampered / 2 missing)
|
|
39
|
+
awport firewall-status # check awwall + AitherFirewall (:8213) status
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Apache-2.0.
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""awport: leased, firewall-gated, encrypted TCP/UDP port forwarding for AitherMesh & AitherNet."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from awport.crypto import (
|
|
5
|
+
PROTOCOL_VERSION,
|
|
6
|
+
EncryptedStream,
|
|
7
|
+
client_handshake,
|
|
8
|
+
ensure_seal_key,
|
|
9
|
+
server_handshake,
|
|
10
|
+
sign_lease,
|
|
11
|
+
verify_lease,
|
|
12
|
+
)
|
|
13
|
+
from awport.firewall import FirewallGate, FirewallVerdict
|
|
14
|
+
from awport.forward import (
|
|
15
|
+
EncryptedRelayClient,
|
|
16
|
+
EncryptedRelayServer,
|
|
17
|
+
PortManager,
|
|
18
|
+
TcpForwarder,
|
|
19
|
+
UdpForwarder,
|
|
20
|
+
)
|
|
21
|
+
from awport.store import (
|
|
22
|
+
LeaseStore,
|
|
23
|
+
PortLease,
|
|
24
|
+
detect_mesh_ip,
|
|
25
|
+
parse_duration,
|
|
26
|
+
verify_forward,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
__version__ = "0.1.0"
|
|
30
|
+
|
|
31
|
+
__all__ = [
|
|
32
|
+
"__version__",
|
|
33
|
+
"PROTOCOL_VERSION",
|
|
34
|
+
"EncryptedStream",
|
|
35
|
+
"client_handshake",
|
|
36
|
+
"server_handshake",
|
|
37
|
+
"ensure_seal_key",
|
|
38
|
+
"sign_lease",
|
|
39
|
+
"verify_lease",
|
|
40
|
+
"FirewallGate",
|
|
41
|
+
"FirewallVerdict",
|
|
42
|
+
"PortLease",
|
|
43
|
+
"LeaseStore",
|
|
44
|
+
"detect_mesh_ip",
|
|
45
|
+
"parse_duration",
|
|
46
|
+
"verify_forward",
|
|
47
|
+
"TcpForwarder",
|
|
48
|
+
"UdpForwarder",
|
|
49
|
+
"EncryptedRelayServer",
|
|
50
|
+
"EncryptedRelayClient",
|
|
51
|
+
"PortManager",
|
|
52
|
+
]
|
|
@@ -0,0 +1,484 @@
|
|
|
1
|
+
"""awport CLI — leased, firewall-gated, encrypted TCP/UDP port forwarding for AitherMesh & AitherNet."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import signal
|
|
8
|
+
import socket
|
|
9
|
+
import sys
|
|
10
|
+
import tempfile
|
|
11
|
+
import threading
|
|
12
|
+
import time
|
|
13
|
+
import urllib.error
|
|
14
|
+
import urllib.request
|
|
15
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any, Dict, Optional, Tuple
|
|
18
|
+
|
|
19
|
+
import awwall
|
|
20
|
+
|
|
21
|
+
from awport.firewall import FirewallGate
|
|
22
|
+
from awport.forward import PortManager, create_control_server
|
|
23
|
+
from awport.store import LeaseStore, detect_mesh_ip, parse_duration
|
|
24
|
+
|
|
25
|
+
DEFAULT_CONTROL_URL = os.getenv("AWPORT_CONTROL_URL", "http://127.0.0.1:47965")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _parse_host_port(spec: str, default_host: str = "127.0.0.1") -> Tuple[str, int]:
|
|
29
|
+
s = str(spec).strip()
|
|
30
|
+
if ":" in s:
|
|
31
|
+
h, p = s.rsplit(":", 1)
|
|
32
|
+
return (h.strip() or default_host), int(p.strip())
|
|
33
|
+
return default_host, int(s)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _control_req(method: str, path: str, body: Optional[Dict[str, Any]] = None) -> Optional[Dict[str, Any]]:
|
|
37
|
+
url = DEFAULT_CONTROL_URL.rstrip("/") + path
|
|
38
|
+
data = json.dumps(body).encode("utf-8") if body is not None else None
|
|
39
|
+
headers = {"Content-Type": "application/json"} if data is not None else {}
|
|
40
|
+
req = urllib.request.Request(url, data=data, method=method, headers=headers)
|
|
41
|
+
try:
|
|
42
|
+
with urllib.request.urlopen(req, timeout=4) as r:
|
|
43
|
+
return json.loads(r.read().decode("utf-8") or "{}")
|
|
44
|
+
except urllib.error.HTTPError as exc:
|
|
45
|
+
err = exc.read().decode("utf-8", "replace")
|
|
46
|
+
print(err, file=sys.stderr)
|
|
47
|
+
raise SystemExit(1)
|
|
48
|
+
except Exception: # noqa: BLE001
|
|
49
|
+
return None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _self_test() -> int:
|
|
53
|
+
"""Prove every layer live in an isolated temp dir: awseal, awwall, AitherFirewall, TCP, UDP, encrypted relay, awdit."""
|
|
54
|
+
with tempfile.TemporaryDirectory(prefix="awport-selftest-") as td:
|
|
55
|
+
root = Path(td)
|
|
56
|
+
srv_key = root / "srv.pem"
|
|
57
|
+
cli_key = root / "cli.pem"
|
|
58
|
+
bad_key = root / "bad.pem"
|
|
59
|
+
|
|
60
|
+
# 1. Mock AitherFirewall server to prove live HTTP /firewall/evaluate + /firewall/threat-report
|
|
61
|
+
threats = []
|
|
62
|
+
|
|
63
|
+
class _MockFW(BaseHTTPRequestHandler):
|
|
64
|
+
def log_message(self, *a):
|
|
65
|
+
pass
|
|
66
|
+
|
|
67
|
+
def do_GET(self):
|
|
68
|
+
raw = json.dumps({"status": "healthy"}).encode()
|
|
69
|
+
self.send_response(200)
|
|
70
|
+
self.send_header("Content-Type", "application/json")
|
|
71
|
+
self.send_header("Content-Length", str(len(raw)))
|
|
72
|
+
self.end_headers()
|
|
73
|
+
self.wfile.write(raw)
|
|
74
|
+
|
|
75
|
+
def do_POST(self):
|
|
76
|
+
n = int(self.headers.get("Content-Length", "0"))
|
|
77
|
+
doc = json.loads(self.rfile.read(n).decode() or "{}")
|
|
78
|
+
if self.path == "/firewall/evaluate":
|
|
79
|
+
out = {"verdict": "allowed", "zone": "mesh", "rule_name": "selftest-allow"}
|
|
80
|
+
elif self.path == "/firewall/threat-report":
|
|
81
|
+
threats.append(doc)
|
|
82
|
+
out = {"received": True, "blocked": False}
|
|
83
|
+
else:
|
|
84
|
+
out = {}
|
|
85
|
+
raw = json.dumps(out).encode()
|
|
86
|
+
self.send_response(200)
|
|
87
|
+
self.send_header("Content-Type", "application/json")
|
|
88
|
+
self.send_header("Content-Length", str(len(raw)))
|
|
89
|
+
self.end_headers()
|
|
90
|
+
self.wfile.write(raw)
|
|
91
|
+
|
|
92
|
+
fw_srv = ThreadingHTTPServer(("127.0.0.1", 0), _MockFW)
|
|
93
|
+
fw_port = fw_srv.server_address[1]
|
|
94
|
+
threading.Thread(target=fw_srv.serve_forever, daemon=True).start()
|
|
95
|
+
|
|
96
|
+
# 2. Local TCP echo server + UDP echo server
|
|
97
|
+
tcp_echo = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
98
|
+
tcp_echo.bind(("127.0.0.1", 0))
|
|
99
|
+
tcp_echo.listen(8)
|
|
100
|
+
tcp_echo_port = tcp_echo.getsockname()[1]
|
|
101
|
+
|
|
102
|
+
def _tcp_echo_loop():
|
|
103
|
+
while True:
|
|
104
|
+
try:
|
|
105
|
+
c, _ = tcp_echo.accept()
|
|
106
|
+
except OSError:
|
|
107
|
+
break
|
|
108
|
+
data = c.recv(4096)
|
|
109
|
+
if data:
|
|
110
|
+
c.sendall(b"ECHO:" + data)
|
|
111
|
+
c.close()
|
|
112
|
+
|
|
113
|
+
threading.Thread(target=_tcp_echo_loop, daemon=True).start()
|
|
114
|
+
|
|
115
|
+
udp_echo = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
116
|
+
udp_echo.bind(("127.0.0.1", 0))
|
|
117
|
+
udp_echo_port = udp_echo.getsockname()[1]
|
|
118
|
+
|
|
119
|
+
def _udp_echo_loop():
|
|
120
|
+
while True:
|
|
121
|
+
try:
|
|
122
|
+
d, a = udp_echo.recvfrom(4096)
|
|
123
|
+
udp_echo.sendto(b"UDP:" + d, a)
|
|
124
|
+
except OSError:
|
|
125
|
+
break
|
|
126
|
+
|
|
127
|
+
threading.Thread(target=_udp_echo_loop, daemon=True).start()
|
|
128
|
+
|
|
129
|
+
try:
|
|
130
|
+
# 3. Verify awwall fail-closed egress gate
|
|
131
|
+
strict_gate = FirewallGate(
|
|
132
|
+
awwall_policy=awwall.Policy([]),
|
|
133
|
+
firewall_url=f"http://127.0.0.1:{fw_port}",
|
|
134
|
+
strict_egress=True,
|
|
135
|
+
strict_firewall=True,
|
|
136
|
+
)
|
|
137
|
+
assert strict_gate.check_egress("evil.example.com", 443).allowed is False
|
|
138
|
+
|
|
139
|
+
gate = FirewallGate(
|
|
140
|
+
awwall_policy=awwall.Policy([awwall.AllowRule("127.0.0.1", "exact", "selftest")]),
|
|
141
|
+
firewall_url=f"http://127.0.0.1:{fw_port}",
|
|
142
|
+
strict_egress=True,
|
|
143
|
+
strict_firewall=True,
|
|
144
|
+
)
|
|
145
|
+
srv_store = LeaseStore(root / "srv_store", key_path=srv_key, notify_awlert=False)
|
|
146
|
+
cli_store = LeaseStore(root / "cli_store", key_path=cli_key, notify_awlert=False)
|
|
147
|
+
srv_pub = srv_store.pubkey_hex()
|
|
148
|
+
cli_pub = cli_store.pubkey_hex()
|
|
149
|
+
|
|
150
|
+
mgr_srv = PortManager(srv_store, gate, reaper_interval_s=0.5)
|
|
151
|
+
mgr_cli = PortManager(cli_store, gate, reaper_interval_s=0.5)
|
|
152
|
+
|
|
153
|
+
# 4. TCP forward round-trip + awnet verify
|
|
154
|
+
f_tcp = mgr_srv.open_lease(
|
|
155
|
+
mode="forward", proto="tcp",
|
|
156
|
+
listen_host="127.0.0.1", listen_port=0,
|
|
157
|
+
target_host="127.0.0.1", target_port=tcp_echo_port,
|
|
158
|
+
)
|
|
159
|
+
tcp_port = int(f_tcp["listen"].split(":")[1])
|
|
160
|
+
with socket.create_connection(("127.0.0.1", tcp_port), timeout=2.0) as s:
|
|
161
|
+
s.sendall(b"ping-tcp")
|
|
162
|
+
assert s.recv(64) == b"ECHO:ping-tcp"
|
|
163
|
+
checks = mgr_srv.verify_all(f_tcp["lease_id"])
|
|
164
|
+
assert checks[0]["ok"] is True and checks[0]["lease_sig_ok"] is True
|
|
165
|
+
|
|
166
|
+
# 5. UDP forward round-trip
|
|
167
|
+
f_udp = mgr_srv.open_lease(
|
|
168
|
+
mode="forward", proto="udp",
|
|
169
|
+
listen_host="127.0.0.1", listen_port=0,
|
|
170
|
+
target_host="127.0.0.1", target_port=udp_echo_port,
|
|
171
|
+
)
|
|
172
|
+
udp_port = int(f_udp["listen"].split(":")[1])
|
|
173
|
+
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as us:
|
|
174
|
+
us.settimeout(2.0)
|
|
175
|
+
us.sendto(b"ping-udp", ("127.0.0.1", udp_port))
|
|
176
|
+
reply, _ = us.recvfrom(64)
|
|
177
|
+
assert reply == b"UDP:ping-udp"
|
|
178
|
+
|
|
179
|
+
# 6. Encrypted AitherNet relay (mutual Ed25519 + X25519 + AES-256-GCM)
|
|
180
|
+
f_rsrv = mgr_srv.open_lease(
|
|
181
|
+
mode="relay-serve", proto="tcp",
|
|
182
|
+
listen_host="127.0.0.1", listen_port=0,
|
|
183
|
+
target_host="127.0.0.1", target_port=tcp_echo_port,
|
|
184
|
+
scope="aithernet",
|
|
185
|
+
allowed_peers=[cli_pub],
|
|
186
|
+
)
|
|
187
|
+
rsrv_port = int(f_rsrv["listen"].split(":")[1])
|
|
188
|
+
f_rcli = mgr_cli.open_lease(
|
|
189
|
+
mode="relay-connect", proto="tcp",
|
|
190
|
+
listen_host="127.0.0.1", listen_port=0,
|
|
191
|
+
target_host="127.0.0.1", target_port=rsrv_port,
|
|
192
|
+
scope="aithernet",
|
|
193
|
+
expect_peer=srv_pub,
|
|
194
|
+
)
|
|
195
|
+
rcli_port = int(f_rcli["listen"].split(":")[1])
|
|
196
|
+
with socket.create_connection(("127.0.0.1", rcli_port), timeout=3.0) as s:
|
|
197
|
+
s.sendall(b"secret-aithernet")
|
|
198
|
+
assert s.recv(64) == b"ECHO:secret-aithernet"
|
|
199
|
+
|
|
200
|
+
# 7. Unauthorized peer triggers rejection + AitherFirewall threat-report!
|
|
201
|
+
bad_store = LeaseStore(root / "bad_store", key_path=bad_key, notify_awlert=False)
|
|
202
|
+
bad_store.pubkey_hex()
|
|
203
|
+
from awport.crypto import AuthError, client_handshake
|
|
204
|
+
|
|
205
|
+
rejected = False
|
|
206
|
+
with socket.create_connection(("127.0.0.1", rsrv_port), timeout=2.0) as bs:
|
|
207
|
+
try:
|
|
208
|
+
client_handshake(bs, key_path=bad_key, expect_peer=srv_pub)
|
|
209
|
+
except AuthError:
|
|
210
|
+
rejected = True
|
|
211
|
+
assert rejected is True
|
|
212
|
+
time.sleep(0.15)
|
|
213
|
+
assert len(threats) >= 1 and threats[-1]["event_type"] == "awport_crypto_auth_failure"
|
|
214
|
+
|
|
215
|
+
mgr_cli.shutdown()
|
|
216
|
+
mgr_srv.shutdown()
|
|
217
|
+
ver = srv_store.audit_verify()
|
|
218
|
+
assert ver["ok"] is True
|
|
219
|
+
|
|
220
|
+
print(json.dumps({
|
|
221
|
+
"self_test": "PASS",
|
|
222
|
+
"awseal": srv_pub[:16] + "...",
|
|
223
|
+
"awwall_fail_closed": "ok",
|
|
224
|
+
"aither_firewall_gate": "ok",
|
|
225
|
+
"aither_firewall_threat_report": len(threats),
|
|
226
|
+
"tcp_forward": "ok",
|
|
227
|
+
"udp_forward": "ok",
|
|
228
|
+
"encrypted_relay_x25519_aes256gcm": "ok",
|
|
229
|
+
"awnet_verify": "ok",
|
|
230
|
+
"awdit": f"ok ({ver['records']} records)",
|
|
231
|
+
}, indent=2))
|
|
232
|
+
return 0
|
|
233
|
+
finally:
|
|
234
|
+
tcp_echo.close()
|
|
235
|
+
udp_echo.close()
|
|
236
|
+
fw_srv.shutdown()
|
|
237
|
+
fw_srv.server_close()
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _build_runtime(args) -> Tuple[LeaseStore, FirewallGate]:
|
|
241
|
+
store = LeaseStore(
|
|
242
|
+
root=Path(args.dir) if getattr(args, "dir", "") else None,
|
|
243
|
+
notify_awlert=not getattr(args, "no_alerts", False),
|
|
244
|
+
)
|
|
245
|
+
gate = FirewallGate(
|
|
246
|
+
awwall_policy_path=Path(args.awwall_policy) if getattr(args, "awwall_policy", "") else None,
|
|
247
|
+
firewall_url=getattr(args, "firewall_url", None),
|
|
248
|
+
strict_egress=bool(getattr(args, "strict_egress", False)),
|
|
249
|
+
strict_firewall=bool(getattr(args, "strict_firewall", False)),
|
|
250
|
+
)
|
|
251
|
+
return store, gate
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _run_foreground(mgr: PortManager, info: Dict[str, Any]) -> int:
|
|
255
|
+
print(json.dumps(info, indent=2), flush=True)
|
|
256
|
+
stop = threading.Event()
|
|
257
|
+
signal.signal(signal.SIGINT, lambda *_: stop.set())
|
|
258
|
+
signal.signal(signal.SIGTERM, lambda *_: stop.set())
|
|
259
|
+
try:
|
|
260
|
+
while not stop.wait(0.5):
|
|
261
|
+
if not mgr.list_active():
|
|
262
|
+
break
|
|
263
|
+
finally:
|
|
264
|
+
mgr.shutdown()
|
|
265
|
+
return 0
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def main(argv=None) -> int:
|
|
269
|
+
ap = argparse.ArgumentParser(
|
|
270
|
+
prog="awport",
|
|
271
|
+
description="Leased, firewall-gated, encrypted TCP/UDP port forwarding for AitherMesh & AitherNet",
|
|
272
|
+
)
|
|
273
|
+
ap.add_argument("--self-test", action="store_true", help="Run full live crypto/firewall/TCP/UDP self-test")
|
|
274
|
+
ap.add_argument("--dir", default="", help="Override state/audit dir (default: /var/lib/aither/awport)")
|
|
275
|
+
ap.add_argument("--awwall-policy", default="", help="Path to awwall policy JSON")
|
|
276
|
+
ap.add_argument("--firewall-url", default=None, help="AitherFirewall URL (default: http://127.0.0.1:8213)")
|
|
277
|
+
ap.add_argument("--strict-egress", action="store_true", help="Require explicit awwall rule even for mesh/local")
|
|
278
|
+
ap.add_argument("--strict-firewall", action="store_true", help="Fail closed if AitherFirewall :8213 is unreachable")
|
|
279
|
+
ap.add_argument("--no-alerts", action="store_true", help="Disable awlert fleet notifications")
|
|
280
|
+
sub = ap.add_subparsers(dest="cmd")
|
|
281
|
+
|
|
282
|
+
p_fwd = sub.add_parser("forward", help="Forward local/mesh port to a target host:port")
|
|
283
|
+
p_fwd.add_argument("listen", help="Local listen [host:]port (e.g. 127.0.0.1:11434 or 11434)")
|
|
284
|
+
p_fwd.add_argument("target", help="Target host:port (e.g. 10.77.0.12:11434)")
|
|
285
|
+
p_fwd.add_argument("--proto", choices=("tcp", "udp"), default="tcp")
|
|
286
|
+
p_fwd.add_argument("--scope", choices=("local", "mesh", "aithernet"), default="local")
|
|
287
|
+
p_fwd.add_argument("--ttl", default="2h")
|
|
288
|
+
p_fwd.add_argument("--max-conns", type=int, default=256)
|
|
289
|
+
p_fwd.add_argument("--max-bytes", type=int, default=0)
|
|
290
|
+
p_fwd.add_argument("--foreground", action="store_true", help="Run directly instead of delegating to awport daemon")
|
|
291
|
+
|
|
292
|
+
p_exp = sub.add_parser("expose", help="Expose a local service port onto mesh (10.77/100.64) or public (awtunnel)")
|
|
293
|
+
p_exp.add_argument("target_port", type=int, help="Local service port to expose")
|
|
294
|
+
p_exp.add_argument("--scope", choices=("mesh", "local", "public"), default="mesh")
|
|
295
|
+
p_exp.add_argument("--listen-port", type=int, default=0, help="Listen port (default: same as target_port)")
|
|
296
|
+
p_exp.add_argument("--proto", choices=("tcp", "udp"), default="tcp")
|
|
297
|
+
p_exp.add_argument("--ttl", default="1h")
|
|
298
|
+
p_exp.add_argument("--foreground", action="store_true")
|
|
299
|
+
|
|
300
|
+
p_rsrv = sub.add_parser("relay-serve", help="Serve an encrypted awport/v1 (X25519+Ed25519+AES-256-GCM) relay")
|
|
301
|
+
p_rsrv.add_argument("listen", help="Relay listen [host:]port (e.g. 0.0.0.0:9443)")
|
|
302
|
+
p_rsrv.add_argument("target", help="Upstream target host:port (e.g. 127.0.0.1:8080)")
|
|
303
|
+
p_rsrv.add_argument("--allow-peer", default="", help="Comma-separated allowed client Ed25519 pubkey hexes")
|
|
304
|
+
p_rsrv.add_argument("--ttl", default="2h")
|
|
305
|
+
p_rsrv.add_argument("--foreground", action="store_true")
|
|
306
|
+
|
|
307
|
+
p_rcli = sub.add_parser("relay-connect", help="Connect locally to an encrypted awport/v1 relay server")
|
|
308
|
+
p_rcli.add_argument("listen", help="Local listen [host:]port (e.g. 127.0.0.1:8080)")
|
|
309
|
+
p_rcli.add_argument("relay", help="Remote relay host:port")
|
|
310
|
+
p_rcli.add_argument("--expect-peer", default="", help="Pinned server Ed25519 pubkey hex")
|
|
311
|
+
p_rcli.add_argument("--ttl", default="2h")
|
|
312
|
+
p_rcli.add_argument("--foreground", action="store_true")
|
|
313
|
+
|
|
314
|
+
p_d = sub.add_parser("daemon", help="Run persistent awport lease daemon + localhost control API")
|
|
315
|
+
p_d.add_argument("--host", default="127.0.0.1")
|
|
316
|
+
p_d.add_argument("--port", type=int, default=47965)
|
|
317
|
+
|
|
318
|
+
sub.add_parser("ls", help="List active port leases")
|
|
319
|
+
p_ver = sub.add_parser("verify", help="Verify listener, awnet upstream reachability, and Ed25519 lease sigs")
|
|
320
|
+
p_ver.add_argument("lease_id", nargs="?", default="")
|
|
321
|
+
|
|
322
|
+
p_cls = sub.add_parser("close", help="Close/revoke an active port lease")
|
|
323
|
+
p_cls.add_argument("lease_id")
|
|
324
|
+
|
|
325
|
+
sub.add_parser("audit-verify", help="Verify awdit hash chain (0 ok / 1 tampered / 2 missing)")
|
|
326
|
+
sub.add_parser("firewall-status", help="Show awwall + AitherFirewall (:8213) status")
|
|
327
|
+
sub.add_parser("firewall-rules", help="Emit iptables rules for active leases + awwall policy")
|
|
328
|
+
sub.add_parser("mesh-ip", help="Print detected AitherMesh/Headscale overlay IP and node pubkey")
|
|
329
|
+
|
|
330
|
+
args = ap.parse_args(argv)
|
|
331
|
+
if args.self_test:
|
|
332
|
+
return _self_test()
|
|
333
|
+
|
|
334
|
+
if args.cmd == "mesh-ip":
|
|
335
|
+
store, _ = _build_runtime(args)
|
|
336
|
+
print(json.dumps({"mesh_ip": detect_mesh_ip(), "awseal_pubkey": store.pubkey_hex()}, indent=2))
|
|
337
|
+
return 0
|
|
338
|
+
|
|
339
|
+
if args.cmd == "audit-verify":
|
|
340
|
+
store, _ = _build_runtime(args)
|
|
341
|
+
res = store.audit_verify()
|
|
342
|
+
print(json.dumps(res, indent=2))
|
|
343
|
+
return int(res["code"])
|
|
344
|
+
|
|
345
|
+
if args.cmd == "firewall-status":
|
|
346
|
+
_, gate = _build_runtime(args)
|
|
347
|
+
print(json.dumps(gate.status(), indent=2))
|
|
348
|
+
return 0
|
|
349
|
+
|
|
350
|
+
if args.cmd == "firewall-rules":
|
|
351
|
+
store, gate = _build_runtime(args)
|
|
352
|
+
leases = [l.to_dict() for l in store.list_leases()]
|
|
353
|
+
sys.stdout.write(gate.emit_iptables_for_leases(leases))
|
|
354
|
+
return 0
|
|
355
|
+
|
|
356
|
+
if args.cmd == "daemon":
|
|
357
|
+
store, gate = _build_runtime(args)
|
|
358
|
+
mgr = PortManager(store, gate)
|
|
359
|
+
srv = create_control_server(mgr, host=args.host, port=args.port)
|
|
360
|
+
print(
|
|
361
|
+
f"[awport] daemon listening on http://{args.host}:{args.port} "
|
|
362
|
+
f"(mesh_ip={detect_mesh_ip() or 'none'}, key={store.pubkey_hex()[:12]}...)",
|
|
363
|
+
flush=True,
|
|
364
|
+
)
|
|
365
|
+
stop_ev = threading.Event()
|
|
366
|
+
signal.signal(signal.SIGINT, lambda *_: stop_ev.set())
|
|
367
|
+
signal.signal(signal.SIGTERM, lambda *_: stop_ev.set())
|
|
368
|
+
t = threading.Thread(target=srv.serve_forever, daemon=True)
|
|
369
|
+
t.start()
|
|
370
|
+
try:
|
|
371
|
+
while not stop_ev.wait(0.5):
|
|
372
|
+
pass
|
|
373
|
+
finally:
|
|
374
|
+
srv.shutdown()
|
|
375
|
+
srv.server_close()
|
|
376
|
+
mgr.shutdown()
|
|
377
|
+
return 0
|
|
378
|
+
|
|
379
|
+
if args.cmd == "ls":
|
|
380
|
+
remote = _control_req("GET", "/leases")
|
|
381
|
+
if remote is not None:
|
|
382
|
+
print(json.dumps(remote, indent=2))
|
|
383
|
+
return 0
|
|
384
|
+
store, _ = _build_runtime(args)
|
|
385
|
+
print(json.dumps({"leases": [l.to_dict() for l in store.list_leases()], "daemon_online": False}, indent=2))
|
|
386
|
+
return 0
|
|
387
|
+
|
|
388
|
+
if args.cmd == "verify":
|
|
389
|
+
q = f"/verify?id={args.lease_id}" if args.lease_id else "/verify"
|
|
390
|
+
remote = _control_req("GET", q)
|
|
391
|
+
if remote is not None:
|
|
392
|
+
print(json.dumps(remote, indent=2))
|
|
393
|
+
ok = all(c.get("ok") and c.get("lease_sig_ok") for c in remote.get("checks", []))
|
|
394
|
+
return 0 if ok else 1
|
|
395
|
+
print(json.dumps({"error": "awport daemon is not running; start with `awport daemon` or `systemctl start aither-awport`"}), file=sys.stderr)
|
|
396
|
+
return 2
|
|
397
|
+
|
|
398
|
+
if args.cmd == "close":
|
|
399
|
+
remote = _control_req("POST", "/close", {"lease_id": args.lease_id})
|
|
400
|
+
if remote is not None:
|
|
401
|
+
print(json.dumps(remote, indent=2))
|
|
402
|
+
return 0 if remote.get("closed") else 1
|
|
403
|
+
store, _ = _build_runtime(args)
|
|
404
|
+
ok = store.remove_lease(args.lease_id)
|
|
405
|
+
print(json.dumps({"closed": ok}))
|
|
406
|
+
return 0 if ok else 1
|
|
407
|
+
|
|
408
|
+
if args.cmd in ("forward", "expose", "relay-serve", "relay-connect"):
|
|
409
|
+
if args.cmd == "forward":
|
|
410
|
+
lh, lp = _parse_host_port(args.listen, "127.0.0.1")
|
|
411
|
+
th, tp = _parse_host_port(args.target)
|
|
412
|
+
req_doc = {
|
|
413
|
+
"mode": "forward", "proto": args.proto, "scope": args.scope,
|
|
414
|
+
"listen_host": lh, "listen_port": lp, "target_host": th, "target_port": tp,
|
|
415
|
+
"ttl": args.ttl, "max_conns": args.max_conns, "max_bytes": args.max_bytes,
|
|
416
|
+
}
|
|
417
|
+
elif args.cmd == "expose":
|
|
418
|
+
if args.scope == "mesh":
|
|
419
|
+
mip = detect_mesh_ip()
|
|
420
|
+
if not mip:
|
|
421
|
+
print("error: no AitherMesh/Headscale IP detected (set AWPORT_MESH_IP)", file=sys.stderr)
|
|
422
|
+
return 2
|
|
423
|
+
lh = mip
|
|
424
|
+
else:
|
|
425
|
+
lh = "127.0.0.1"
|
|
426
|
+
lp = args.listen_port if args.listen_port > 0 else args.target_port
|
|
427
|
+
req_doc = {
|
|
428
|
+
"mode": "expose", "proto": args.proto, "scope": args.scope,
|
|
429
|
+
"listen_host": lh, "listen_port": lp, "target_host": "127.0.0.1", "target_port": args.target_port,
|
|
430
|
+
"ttl": args.ttl,
|
|
431
|
+
}
|
|
432
|
+
elif args.cmd == "relay-serve":
|
|
433
|
+
lh, lp = _parse_host_port(args.listen, "0.0.0.0")
|
|
434
|
+
th, tp = _parse_host_port(args.target)
|
|
435
|
+
peers = [p.strip() for p in args.allow_peer.split(",") if p.strip()]
|
|
436
|
+
req_doc = {
|
|
437
|
+
"mode": "relay-serve", "proto": "tcp", "scope": "aithernet",
|
|
438
|
+
"listen_host": lh, "listen_port": lp, "target_host": th, "target_port": tp,
|
|
439
|
+
"ttl": args.ttl, "allowed_peers": peers,
|
|
440
|
+
}
|
|
441
|
+
else:
|
|
442
|
+
lh, lp = _parse_host_port(args.listen, "127.0.0.1")
|
|
443
|
+
th, tp = _parse_host_port(args.relay)
|
|
444
|
+
req_doc = {
|
|
445
|
+
"mode": "relay-connect", "proto": "tcp", "scope": "aithernet",
|
|
446
|
+
"listen_host": lh, "listen_port": lp, "target_host": th, "target_port": tp,
|
|
447
|
+
"ttl": args.ttl, "expect_peer": args.expect_peer,
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
if not args.foreground:
|
|
451
|
+
remote = _control_req("POST", "/open", req_doc)
|
|
452
|
+
if remote is not None:
|
|
453
|
+
print(json.dumps(remote, indent=2))
|
|
454
|
+
return 0
|
|
455
|
+
|
|
456
|
+
store, gate = _build_runtime(args)
|
|
457
|
+
mgr = PortManager(store, gate)
|
|
458
|
+
try:
|
|
459
|
+
info = mgr.open_lease(
|
|
460
|
+
mode=req_doc["mode"],
|
|
461
|
+
proto=req_doc["proto"],
|
|
462
|
+
listen_host=req_doc["listen_host"],
|
|
463
|
+
listen_port=req_doc["listen_port"],
|
|
464
|
+
target_host=req_doc["target_host"],
|
|
465
|
+
target_port=req_doc["target_port"],
|
|
466
|
+
scope=req_doc["scope"],
|
|
467
|
+
ttl_s=parse_duration(req_doc["ttl"]),
|
|
468
|
+
max_conns=req_doc.get("max_conns", 256),
|
|
469
|
+
max_bytes=req_doc.get("max_bytes", 0),
|
|
470
|
+
allowed_peers=req_doc.get("allowed_peers"),
|
|
471
|
+
expect_peer=req_doc.get("expect_peer", ""),
|
|
472
|
+
)
|
|
473
|
+
except PermissionError as exc:
|
|
474
|
+
print(f"DENIED: {exc}", file=sys.stderr)
|
|
475
|
+
mgr.shutdown()
|
|
476
|
+
return 1
|
|
477
|
+
return _run_foreground(mgr, info)
|
|
478
|
+
|
|
479
|
+
ap.print_help()
|
|
480
|
+
return 0
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
if __name__ == "__main__":
|
|
484
|
+
raise SystemExit(main())
|