netlane 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.
- netlane/__init__.py +3 -0
- netlane/__main__.py +3 -0
- netlane/adb.py +67 -0
- netlane/cli.py +182 -0
- netlane/config.py +394 -0
- netlane/modes/__init__.py +0 -0
- netlane/modes/adb_reverse.py +229 -0
- netlane/modes/interface.py +34 -0
- netlane/modes/wireguard_ssh_reverse.py +335 -0
- netlane/remote.py +85 -0
- netlane/rulesets/__init__.py +0 -0
- netlane/rulesets/iptables.py +181 -0
- netlane/rulesets/nftables.py +194 -0
- netlane/scripts/ubuntu/install.sh +73 -0
- netlane/utils.py +157 -0
- netlane-0.1.0.dist-info/METADATA +248 -0
- netlane-0.1.0.dist-info/RECORD +19 -0
- netlane-0.1.0.dist-info/WHEEL +4 -0
- netlane-0.1.0.dist-info/entry_points.txt +3 -0
netlane/__init__.py
ADDED
netlane/__main__.py
ADDED
netlane/adb.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import shlex
|
|
3
|
+
import subprocess
|
|
4
|
+
import tempfile
|
|
5
|
+
from collections.abc import Iterable
|
|
6
|
+
|
|
7
|
+
from netlane.utils import run_cmd
|
|
8
|
+
|
|
9
|
+
logger = logging.getLogger(__name__)
|
|
10
|
+
|
|
11
|
+
DEVICE_TMP_DIR = "/data/local/tmp"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def run(
|
|
15
|
+
serial: str | None, args: Iterable[str], check: bool = True
|
|
16
|
+
) -> subprocess.CompletedProcess:
|
|
17
|
+
"""Runs `adb <args>` against the device with `serial`, or the only connected one."""
|
|
18
|
+
return run_cmd([*_adb(serial), *args], check=check)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def shell(
|
|
22
|
+
serial: str | None, cmd: str, check: bool = True
|
|
23
|
+
) -> subprocess.CompletedProcess:
|
|
24
|
+
"""Runs `cmd` in an unprivileged shell on the device."""
|
|
25
|
+
return run(serial, ["shell", "-n", cmd], check=check)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def run_script(
|
|
29
|
+
serial: str | None, elevation: str, content: str, check: bool = True
|
|
30
|
+
) -> subprocess.CompletedProcess:
|
|
31
|
+
"""Runs `content` from a device temp file as stdin of the root shell `elevation`. An empty `elevation` requires adbd to run as root."""
|
|
32
|
+
tmp = _upload_temp(serial, content)
|
|
33
|
+
root_shell = shlex.quote(elevation) if elevation else "sh"
|
|
34
|
+
return shell(
|
|
35
|
+
serial,
|
|
36
|
+
f"{_remove_on_exit(tmp)}; {root_shell} < {shlex.quote(tmp)}",
|
|
37
|
+
check=check,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def start(serial: str | None, args: Iterable[str]) -> subprocess.Popen:
|
|
42
|
+
"""Starts `adb <args>` in the background."""
|
|
43
|
+
cmd = [*_adb(serial), *args]
|
|
44
|
+
logger.debug(f"Starting: {' '.join(cmd)}")
|
|
45
|
+
return subprocess.Popen(cmd, stdin=subprocess.DEVNULL)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _adb(serial: str | None) -> list:
|
|
49
|
+
return ["adb", "-s", serial] if serial else ["adb"]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _upload_temp(serial: str | None, content: str) -> str:
|
|
53
|
+
"""Copies `content` to a new device temp file and returns its path."""
|
|
54
|
+
cmd = f"mktemp -p {DEVICE_TMP_DIR}"
|
|
55
|
+
tmp = shell(serial, cmd).stdout.decode("utf-8").strip()
|
|
56
|
+
with tempfile.NamedTemporaryFile(
|
|
57
|
+
mode="w", delete=True, delete_on_close=False
|
|
58
|
+
) as local:
|
|
59
|
+
local.write(content)
|
|
60
|
+
# Ensure data is written to disk before adb reads it
|
|
61
|
+
local.flush()
|
|
62
|
+
run(serial, ["push", local.name, tmp])
|
|
63
|
+
return tmp
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _remove_on_exit(path: str) -> str:
|
|
67
|
+
return f"trap {shlex.quote(f'rm -f {shlex.quote(path)}')} EXIT"
|
netlane/cli.py
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import io
|
|
3
|
+
import logging
|
|
4
|
+
import os
|
|
5
|
+
import sys
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from netlane.config import Config, ConfigValidationError, load_config
|
|
9
|
+
from netlane.modes import adb_reverse, wireguard_ssh_reverse
|
|
10
|
+
from netlane.modes.interface import Mode, StepError
|
|
11
|
+
from netlane.utils import COLOR_CHOICES, config_dir, setup_logging
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
MODES: dict[str, Mode] = {
|
|
16
|
+
"wireguard_ssh_reverse": wireguard_ssh_reverse,
|
|
17
|
+
"adb_reverse": adb_reverse,
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def mode_steps(mode: Mode) -> str:
|
|
22
|
+
"""The steps to run in order. down is left out as it only cleans up."""
|
|
23
|
+
return " → ".join(step for step in mode.STEPS if step != "down")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def modes_overview() -> str:
|
|
27
|
+
name_width = max(len(name) for name in MODES)
|
|
28
|
+
summary_width = max(len(mode.SUMMARY) for mode in MODES.values())
|
|
29
|
+
lines = ["modes:"]
|
|
30
|
+
for name, mode in MODES.items():
|
|
31
|
+
lines.append(
|
|
32
|
+
f" {name:<{name_width}} {mode.SUMMARY:<{summary_width}} {mode_steps(mode)}"
|
|
33
|
+
)
|
|
34
|
+
return "\n".join(lines)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
38
|
+
parser = argparse.ArgumentParser(
|
|
39
|
+
description="Mobile WG Interception Setup",
|
|
40
|
+
epilog=modes_overview(),
|
|
41
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
42
|
+
)
|
|
43
|
+
parser.add_argument(
|
|
44
|
+
"-v",
|
|
45
|
+
"--verbose",
|
|
46
|
+
action="store_true",
|
|
47
|
+
help="Show debug output like executed commands",
|
|
48
|
+
)
|
|
49
|
+
parser.add_argument(
|
|
50
|
+
"--config",
|
|
51
|
+
default=config_dir() / "config.toml",
|
|
52
|
+
type=Path,
|
|
53
|
+
help="Path to the TOML config file (default: %(default)s)",
|
|
54
|
+
)
|
|
55
|
+
parser.add_argument(
|
|
56
|
+
"--color",
|
|
57
|
+
choices=COLOR_CHOICES,
|
|
58
|
+
default="auto",
|
|
59
|
+
help="Color the output (default: %(default)s)",
|
|
60
|
+
)
|
|
61
|
+
parser.add_argument(
|
|
62
|
+
"--log",
|
|
63
|
+
type=Path,
|
|
64
|
+
metavar="PATH",
|
|
65
|
+
help="Also write a JSON Lines log including debug output to PATH",
|
|
66
|
+
)
|
|
67
|
+
subparsers = parser.add_subparsers(dest="command", required=True)
|
|
68
|
+
|
|
69
|
+
setup_parser = subparsers.add_parser(
|
|
70
|
+
"setup",
|
|
71
|
+
help="One-time setup of a dedicated remote server",
|
|
72
|
+
description="One-time setup of the profile's remote server. Assumes the server is used for nothing else.",
|
|
73
|
+
)
|
|
74
|
+
setup_parser.add_argument("profile", help="Name of the profile")
|
|
75
|
+
setup_parser.add_argument(
|
|
76
|
+
"--distro",
|
|
77
|
+
required=True,
|
|
78
|
+
choices=list(wireguard_ssh_reverse.DISTRO_SCRIPTS.keys()),
|
|
79
|
+
help="Linux distribution to install on",
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
pair_parser = subparsers.add_parser(
|
|
83
|
+
"pair",
|
|
84
|
+
help="Create keys and show the client config as a QR code",
|
|
85
|
+
description="Create keys and show the client config as a QR code. Requires setup first.",
|
|
86
|
+
)
|
|
87
|
+
pair_parser.add_argument("profile", help="Name of the profile")
|
|
88
|
+
pair_parser.add_argument(
|
|
89
|
+
"--save",
|
|
90
|
+
type=Path,
|
|
91
|
+
metavar="PATH",
|
|
92
|
+
help="Also save the client config to PATH",
|
|
93
|
+
)
|
|
94
|
+
pair_parser.add_argument(
|
|
95
|
+
"--force",
|
|
96
|
+
action="store_true",
|
|
97
|
+
help="Replace existing keys",
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
up_parser = subparsers.add_parser(
|
|
101
|
+
"up",
|
|
102
|
+
help="Apply the profile and start its tunnels until Ctrl-C",
|
|
103
|
+
description="Apply the profile and start its tunnels until Ctrl-C. Requires setup and pair first if the profile's mode has them.",
|
|
104
|
+
)
|
|
105
|
+
up_parser.add_argument("profile", help="Name of the profile")
|
|
106
|
+
|
|
107
|
+
down_parser = subparsers.add_parser("down", help="Clean up after an interrupted up")
|
|
108
|
+
down_parser.add_argument("profile", help="Name of the profile")
|
|
109
|
+
|
|
110
|
+
subparsers.add_parser("list", help="List profiles with their mode and steps")
|
|
111
|
+
|
|
112
|
+
return parser
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def list_profiles(config: Config) -> None:
|
|
116
|
+
if not config.profiles:
|
|
117
|
+
return
|
|
118
|
+
name_width = max(len(name) for name in config.profiles)
|
|
119
|
+
mode_width = max(len(profile.mode) for profile in config.profiles.values())
|
|
120
|
+
for name, profile in config.profiles.items():
|
|
121
|
+
steps = mode_steps(MODES[profile.mode])
|
|
122
|
+
print(f"{name:<{name_width}} {profile.mode:<{mode_width}} {steps}")
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def run_step(args: argparse.Namespace, config: Config) -> None:
|
|
126
|
+
name = args.profile
|
|
127
|
+
profile = config.profiles.get(name)
|
|
128
|
+
if profile is None:
|
|
129
|
+
raise StepError(f"Profile '{name}' not found in {args.config}")
|
|
130
|
+
|
|
131
|
+
step = args.command
|
|
132
|
+
mode = MODES[profile.mode]
|
|
133
|
+
if step not in mode.STEPS:
|
|
134
|
+
raise StepError(f"Profile '{name}' ({profile.mode}) has no {step} step.")
|
|
135
|
+
|
|
136
|
+
if step == "setup":
|
|
137
|
+
mode.setup(name, profile, args.distro)
|
|
138
|
+
elif step == "pair":
|
|
139
|
+
mode.pair(name, profile, args.save, args.force)
|
|
140
|
+
elif step == "up":
|
|
141
|
+
mode.up(name, profile)
|
|
142
|
+
elif step == "down":
|
|
143
|
+
mode.down(name, profile)
|
|
144
|
+
|
|
145
|
+
later_steps = mode.STEPS[mode.STEPS.index(step) + 1 :]
|
|
146
|
+
if later_steps and later_steps[0] != "down":
|
|
147
|
+
logger.info(f"Next: {later_steps[0]} {name}")
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def main():
|
|
151
|
+
# Piped output otherwise uses the locale's encoding, e.g. cp1252 on Windows.
|
|
152
|
+
for stream in (sys.stdout, sys.stderr):
|
|
153
|
+
if isinstance(stream, io.TextIOWrapper):
|
|
154
|
+
stream.reconfigure(encoding="utf-8")
|
|
155
|
+
if sys.platform == "win32":
|
|
156
|
+
os.system("") # Enables escape codes in the console as a side effect.
|
|
157
|
+
|
|
158
|
+
args = build_parser().parse_args()
|
|
159
|
+
context = {"step": args.command}
|
|
160
|
+
if "profile" in args:
|
|
161
|
+
context["profile"] = args.profile
|
|
162
|
+
setup_logging(args.verbose, args.color, args.log, context)
|
|
163
|
+
logger.debug(f"Arguments: {vars(args)}")
|
|
164
|
+
|
|
165
|
+
try:
|
|
166
|
+
config = load_config(args.config)
|
|
167
|
+
except ConfigValidationError as e:
|
|
168
|
+
logger.error(f"Failed to load config: {e}")
|
|
169
|
+
sys.exit(1)
|
|
170
|
+
|
|
171
|
+
try:
|
|
172
|
+
if args.command == "list":
|
|
173
|
+
list_profiles(config)
|
|
174
|
+
else:
|
|
175
|
+
run_step(args, config)
|
|
176
|
+
except StepError as e:
|
|
177
|
+
logger.error(str(e))
|
|
178
|
+
sys.exit(1)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
if __name__ == "__main__":
|
|
182
|
+
main()
|
netlane/config.py
ADDED
|
@@ -0,0 +1,394 @@
|
|
|
1
|
+
import ipaddress
|
|
2
|
+
import logging
|
|
3
|
+
import re
|
|
4
|
+
import tomllib
|
|
5
|
+
from contextlib import suppress
|
|
6
|
+
from dataclasses import dataclass, field, fields
|
|
7
|
+
from enum import Enum
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import TYPE_CHECKING, Any
|
|
10
|
+
|
|
11
|
+
if TYPE_CHECKING:
|
|
12
|
+
from _typeshed import DataclassInstance
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger(__name__)
|
|
15
|
+
|
|
16
|
+
IPNetwork = ipaddress.IPv4Network | ipaddress.IPv6Network
|
|
17
|
+
|
|
18
|
+
MIN_PORT, MAX_PORT = 1, 65535
|
|
19
|
+
MIN_UID, MAX_UID = 0, 2**32 - 2
|
|
20
|
+
|
|
21
|
+
# Other protocols are passed to iptables and nft as is, with a warning.
|
|
22
|
+
TESTED_PROTOCOLS = ("tcp", "udp")
|
|
23
|
+
ELEVATIONS = ("", "sudo", "doas", "su")
|
|
24
|
+
HOOKS = ("pre_up", "post_up", "pre_down", "post_down")
|
|
25
|
+
MATCH_FIELDS = ("saddr", "daddr", "protocol", "sport", "dport", "skuid", "app")
|
|
26
|
+
|
|
27
|
+
RULE_NAME = re.compile(r"[A-Za-z0-9 _.,:()/+-]{1,128}")
|
|
28
|
+
PROTOCOL_NAME = re.compile(r"[a-z][a-z0-9-]{0,31}")
|
|
29
|
+
MIN_PROTOCOL, MAX_PROTOCOL = 1, 255
|
|
30
|
+
SSH_USER = re.compile(r"[a-z_][a-z0-9_-]{0,31}")
|
|
31
|
+
HOSTNAME_LABEL = re.compile(r"(?!-)[A-Za-z0-9-]{1,63}(?<!-)")
|
|
32
|
+
MAX_HOSTNAME_LENGTH = 253
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class ConfigValidationError(Exception):
|
|
36
|
+
"""Exception raised for configuration validation errors."""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _parse_network(value: str | IPNetwork) -> IPNetwork:
|
|
40
|
+
if isinstance(value, (ipaddress.IPv4Network, ipaddress.IPv6Network)):
|
|
41
|
+
return value
|
|
42
|
+
try:
|
|
43
|
+
return ipaddress.ip_network(value, strict=False)
|
|
44
|
+
except ValueError as e:
|
|
45
|
+
raise ValueError(f"{value!r} is not a valid IP address or network: {e}") from e
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _validate_range(value: int, low: int, high: int, label: str) -> int:
|
|
49
|
+
if (
|
|
50
|
+
isinstance(value, bool)
|
|
51
|
+
or not isinstance(value, int)
|
|
52
|
+
or not (low <= value <= high)
|
|
53
|
+
):
|
|
54
|
+
raise ValueError(f"{value!r} is not a valid {label} ({low}-{high})")
|
|
55
|
+
return value
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _validate_pattern(value: str, pattern: re.Pattern, label: str) -> str:
|
|
59
|
+
if not isinstance(value, str) or not pattern.fullmatch(value):
|
|
60
|
+
raise ValueError(f"{value!r} is not a valid {label}")
|
|
61
|
+
return value
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _validate_choice(value: str, choices: tuple[str, ...], label: str) -> str:
|
|
65
|
+
if value not in choices:
|
|
66
|
+
raise ValueError(
|
|
67
|
+
f"{value!r} is not a valid {label} ({', '.join(map(repr, choices))})"
|
|
68
|
+
)
|
|
69
|
+
return value
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _validate_protocol(value: str) -> str:
|
|
73
|
+
"""Accepts a protocol name or number. Excludes 0 and all, which iptables reads as every protocol."""
|
|
74
|
+
if isinstance(value, str) and value.isascii() and value.isdigit():
|
|
75
|
+
_validate_range(int(value), MIN_PROTOCOL, MAX_PROTOCOL, "protocol number")
|
|
76
|
+
elif value == "all":
|
|
77
|
+
raise ValueError("'all' is not a valid protocol. Omit protocol to match all")
|
|
78
|
+
else:
|
|
79
|
+
_validate_pattern(value, PROTOCOL_NAME, "protocol")
|
|
80
|
+
if value not in TESTED_PROTOCOLS:
|
|
81
|
+
logger.warning(
|
|
82
|
+
f"Protocol {value!r} is uncharted territory and passed to iptables/nft as is. "
|
|
83
|
+
"Manually verifying the ruleset is recommended."
|
|
84
|
+
)
|
|
85
|
+
return value
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _validate_host(value: str) -> str:
|
|
89
|
+
"""Accepts an RFC 1123 hostname or an IP address without a zone index."""
|
|
90
|
+
if isinstance(value, str) and "%" not in value:
|
|
91
|
+
if len(value) <= MAX_HOSTNAME_LENGTH and all(
|
|
92
|
+
HOSTNAME_LABEL.fullmatch(label) for label in value.split(".")
|
|
93
|
+
):
|
|
94
|
+
return value
|
|
95
|
+
with suppress(ValueError):
|
|
96
|
+
ipaddress.ip_address(value)
|
|
97
|
+
return value
|
|
98
|
+
raise ValueError(f"{value!r} is not a valid hostname or IP address")
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _validate_tunnels(value: dict[str, int]) -> dict[str, int]:
|
|
102
|
+
if not isinstance(value, dict):
|
|
103
|
+
raise TypeError("tunnels must be a table of names to ports")
|
|
104
|
+
for port in value.values():
|
|
105
|
+
_validate_range(port, MIN_PORT, MAX_PORT, "port")
|
|
106
|
+
if len(set(value.values())) != len(value):
|
|
107
|
+
raise ValueError("tunnels must use distinct ports")
|
|
108
|
+
return value
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _validate_hooks(value: dict[str, str]) -> dict[str, str]:
|
|
112
|
+
if not isinstance(value, dict):
|
|
113
|
+
raise TypeError("hooks must be a table of hook names to commands")
|
|
114
|
+
for name, cmd in value.items():
|
|
115
|
+
_validate_choice(name, HOOKS, "hook")
|
|
116
|
+
if not isinstance(cmd, str):
|
|
117
|
+
raise TypeError(f"hook {name} must be a string")
|
|
118
|
+
return value
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class Action(Enum):
|
|
122
|
+
REJECT = "reject"
|
|
123
|
+
DROP = "drop"
|
|
124
|
+
PASSTHROUGH = "passthrough"
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
@dataclass(frozen=True)
|
|
128
|
+
class Tunnel:
|
|
129
|
+
name: str
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
Target = Action | Tunnel
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _parse_target(value: str | Target) -> Target:
|
|
136
|
+
"""Parses `action:<action>` or `tunnel:<name>`."""
|
|
137
|
+
if isinstance(value, (Action, Tunnel)):
|
|
138
|
+
return value
|
|
139
|
+
kind, _, name = str(value).partition(":")
|
|
140
|
+
if kind == "action" and name in {a.value for a in Action}:
|
|
141
|
+
return Action(name)
|
|
142
|
+
if kind == "tunnel" and name:
|
|
143
|
+
return Tunnel(name)
|
|
144
|
+
actions = ", ".join(f"action:{a.value}" for a in Action)
|
|
145
|
+
raise ValueError(f"{value!r} is not a valid target ({actions} or tunnel:<name>)")
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
@dataclass
|
|
149
|
+
class Rule:
|
|
150
|
+
name: str
|
|
151
|
+
target: Target
|
|
152
|
+
saddr: list[IPNetwork] | None = None
|
|
153
|
+
daddr: list[IPNetwork] | None = None
|
|
154
|
+
protocol: list[str] | None = None
|
|
155
|
+
sport: list[int] | None = None
|
|
156
|
+
dport: list[int] | None = None
|
|
157
|
+
skuid: list[int] | None = None
|
|
158
|
+
app: list[str] | None = None
|
|
159
|
+
|
|
160
|
+
def __post_init__(self):
|
|
161
|
+
_validate_pattern(self.name, RULE_NAME, "rule name")
|
|
162
|
+
self.target = _parse_target(self.target)
|
|
163
|
+
for name in MATCH_FIELDS:
|
|
164
|
+
value = getattr(self, name)
|
|
165
|
+
if value is not None and not isinstance(value, list):
|
|
166
|
+
raise ValueError(f"{name} must be a list, e.g. [{value!r}]")
|
|
167
|
+
if value == []:
|
|
168
|
+
raise ValueError(f"{name} must not be empty. Omit it to match all")
|
|
169
|
+
if self.saddr is not None:
|
|
170
|
+
self.saddr = [_parse_network(a) for a in self.saddr]
|
|
171
|
+
if self.daddr is not None:
|
|
172
|
+
self.daddr = [_parse_network(a) for a in self.daddr]
|
|
173
|
+
if (
|
|
174
|
+
self.saddr is not None
|
|
175
|
+
and self.daddr is not None
|
|
176
|
+
and _versions(self.saddr) != _versions(self.daddr)
|
|
177
|
+
):
|
|
178
|
+
raise ValueError(
|
|
179
|
+
"saddr/daddr family mismatch: both must cover the same address families"
|
|
180
|
+
)
|
|
181
|
+
if self.protocol is not None:
|
|
182
|
+
self.protocol = [_validate_protocol(p) for p in self.protocol]
|
|
183
|
+
if self.sport is not None:
|
|
184
|
+
self.sport = [
|
|
185
|
+
_validate_range(p, MIN_PORT, MAX_PORT, "port") for p in self.sport
|
|
186
|
+
]
|
|
187
|
+
if self.dport is not None:
|
|
188
|
+
self.dport = [
|
|
189
|
+
_validate_range(p, MIN_PORT, MAX_PORT, "port") for p in self.dport
|
|
190
|
+
]
|
|
191
|
+
if self.skuid is not None:
|
|
192
|
+
self.skuid = [
|
|
193
|
+
_validate_range(u, MIN_UID, MAX_UID, "uid") for u in self.skuid
|
|
194
|
+
]
|
|
195
|
+
|
|
196
|
+
@property
|
|
197
|
+
def families(self) -> list[int]:
|
|
198
|
+
"""The IP versions the rule matches: those of its addresses, both without addresses."""
|
|
199
|
+
addrs = self.saddr or self.daddr
|
|
200
|
+
return _versions(addrs) if addrs else [4, 6]
|
|
201
|
+
|
|
202
|
+
@property
|
|
203
|
+
def matches_all(self) -> bool:
|
|
204
|
+
return all(getattr(self, name) is None for name in MATCH_FIELDS)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _versions(networks: list[IPNetwork]) -> list[int]:
|
|
208
|
+
return sorted({n.version for n in networks})
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
@dataclass
|
|
212
|
+
class WireguardSSHReverseOpts:
|
|
213
|
+
ssh_host: str
|
|
214
|
+
ssh_user: str
|
|
215
|
+
elevation: str
|
|
216
|
+
tunnels: dict[str, int]
|
|
217
|
+
|
|
218
|
+
def __post_init__(self):
|
|
219
|
+
_validate_host(self.ssh_host)
|
|
220
|
+
_validate_pattern(self.ssh_user, SSH_USER, "SSH user")
|
|
221
|
+
_validate_choice(self.elevation, ELEVATIONS, "elevation")
|
|
222
|
+
_validate_tunnels(self.tunnels)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
@dataclass
|
|
226
|
+
class AdbReverseOpts:
|
|
227
|
+
elevation: str
|
|
228
|
+
tunnels: dict[str, int]
|
|
229
|
+
serial: str | None = None
|
|
230
|
+
|
|
231
|
+
def __post_init__(self):
|
|
232
|
+
_validate_choice(self.elevation, ELEVATIONS, "elevation")
|
|
233
|
+
_validate_tunnels(self.tunnels)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
@dataclass
|
|
237
|
+
class Profile[O: WireguardSSHReverseOpts | AdbReverseOpts]:
|
|
238
|
+
mode: str
|
|
239
|
+
mode_opts: O
|
|
240
|
+
rules: list[Rule] = field(default_factory=list)
|
|
241
|
+
hooks: dict[str, str] = field(default_factory=dict)
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
@dataclass
|
|
245
|
+
class Config:
|
|
246
|
+
profiles: dict[str, Profile[Any]] = field(default_factory=dict)
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _from_dict[T: DataclassInstance](cls: type[T], data: Any, context: str) -> T:
|
|
250
|
+
"""Instantiates a dataclass from a dict, strictly rejecting unknown keys."""
|
|
251
|
+
if not isinstance(data, dict):
|
|
252
|
+
raise ConfigValidationError(f"{context} must be a dictionary/table")
|
|
253
|
+
|
|
254
|
+
allowed_keys = {f.name for f in fields(cls)}
|
|
255
|
+
unknown_keys = set(data.keys()) - allowed_keys
|
|
256
|
+
if unknown_keys:
|
|
257
|
+
raise ConfigValidationError(
|
|
258
|
+
f"Unknown field(s) found in {context}: {unknown_keys}"
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
try:
|
|
262
|
+
return cls(**data)
|
|
263
|
+
except (TypeError, ValueError) as e:
|
|
264
|
+
raise ConfigValidationError(f"Invalid data in {context}: {e}") from e
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def parse_config_string(toml_content: str) -> Config:
|
|
268
|
+
"""Parses a TOML configuration string and returns a Config object strictly."""
|
|
269
|
+
try:
|
|
270
|
+
data = tomllib.loads(toml_content)
|
|
271
|
+
except tomllib.TOMLDecodeError as e:
|
|
272
|
+
raise ConfigValidationError(f"Invalid TOML: {e}") from e
|
|
273
|
+
|
|
274
|
+
# Validate root
|
|
275
|
+
unknown_keys = set(data.keys()) - {"profiles"}
|
|
276
|
+
if unknown_keys:
|
|
277
|
+
raise ConfigValidationError(
|
|
278
|
+
f"Unknown field(s) found in root config: {unknown_keys}"
|
|
279
|
+
)
|
|
280
|
+
|
|
281
|
+
if "profiles" not in data:
|
|
282
|
+
raise ConfigValidationError("Missing required 'profiles' section")
|
|
283
|
+
|
|
284
|
+
profiles_data = data["profiles"]
|
|
285
|
+
if not isinstance(profiles_data, dict):
|
|
286
|
+
raise ConfigValidationError("'profiles' must be a table")
|
|
287
|
+
|
|
288
|
+
parsed_profiles = {}
|
|
289
|
+
for profile_id, profile_dict in profiles_data.items():
|
|
290
|
+
if not isinstance(profile_dict, dict):
|
|
291
|
+
raise ConfigValidationError(f"Profile '{profile_id}' must be a table")
|
|
292
|
+
|
|
293
|
+
# Ensure no unknown keys at the profile level
|
|
294
|
+
allowed_profile_keys = {f.name for f in fields(Profile)}
|
|
295
|
+
unknown_keys = set(profile_dict.keys()) - allowed_profile_keys
|
|
296
|
+
if unknown_keys:
|
|
297
|
+
raise ConfigValidationError(
|
|
298
|
+
f"Unknown field(s) found in profile '{profile_id}': {unknown_keys}"
|
|
299
|
+
)
|
|
300
|
+
|
|
301
|
+
mode = profile_dict.get("mode")
|
|
302
|
+
if not mode:
|
|
303
|
+
raise ConfigValidationError(f"Profile '{profile_id}' missing 'mode'")
|
|
304
|
+
|
|
305
|
+
# Parse mode specific opts
|
|
306
|
+
mode_opts_data = profile_dict.get("mode_opts", {})
|
|
307
|
+
if mode == "wireguard_ssh_reverse":
|
|
308
|
+
mode_opts = _from_dict(
|
|
309
|
+
WireguardSSHReverseOpts,
|
|
310
|
+
mode_opts_data,
|
|
311
|
+
f"profile '{profile_id}' mode_opts",
|
|
312
|
+
)
|
|
313
|
+
elif mode == "adb_reverse":
|
|
314
|
+
mode_opts = _from_dict(
|
|
315
|
+
AdbReverseOpts, mode_opts_data, f"profile '{profile_id}' mode_opts"
|
|
316
|
+
)
|
|
317
|
+
else:
|
|
318
|
+
raise ConfigValidationError(
|
|
319
|
+
f"Unknown mode '{mode}' in profile '{profile_id}'"
|
|
320
|
+
)
|
|
321
|
+
|
|
322
|
+
# Parse rules
|
|
323
|
+
rules_list = profile_dict.get("rules", [])
|
|
324
|
+
if not isinstance(rules_list, list):
|
|
325
|
+
raise ConfigValidationError(
|
|
326
|
+
f"Profile '{profile_id}' 'rules' must be a list"
|
|
327
|
+
)
|
|
328
|
+
|
|
329
|
+
parsed_rules = []
|
|
330
|
+
for i, rule_dict in enumerate(rules_list):
|
|
331
|
+
rule = _from_dict(
|
|
332
|
+
Rule, rule_dict, f"rule at index {i} of profile '{profile_id}'"
|
|
333
|
+
)
|
|
334
|
+
if rule in parsed_rules:
|
|
335
|
+
raise ConfigValidationError(
|
|
336
|
+
f"Duplicate rule '{rule.name}' in profile '{profile_id}'"
|
|
337
|
+
)
|
|
338
|
+
if isinstance(rule.target, Tunnel):
|
|
339
|
+
if rule.target.name not in mode_opts.tunnels:
|
|
340
|
+
raise ConfigValidationError(
|
|
341
|
+
f"Target tunnel '{rule.target.name}' in rule '{rule.name}' is not defined in mode_opts.tunnels"
|
|
342
|
+
)
|
|
343
|
+
if rule.protocol != ["tcp"]:
|
|
344
|
+
raise ConfigValidationError(
|
|
345
|
+
f"Tunnel rule '{rule.name}' must match protocol tcp only"
|
|
346
|
+
)
|
|
347
|
+
if parsed_rules and parsed_rules[-1].matches_all:
|
|
348
|
+
raise ConfigValidationError(
|
|
349
|
+
f"Rule '{rule.name}' never matches, as '{parsed_rules[-1].name}' before it matches all traffic"
|
|
350
|
+
)
|
|
351
|
+
if (rule.app or rule.skuid) and mode == "wireguard_ssh_reverse":
|
|
352
|
+
raise ConfigValidationError(
|
|
353
|
+
f"Rule '{rule.name}': app and skuid matching are not supported in wireguard_ssh_reverse mode. "
|
|
354
|
+
"Select the apps in the WireGuard app's tunnel settings instead."
|
|
355
|
+
)
|
|
356
|
+
if (
|
|
357
|
+
(rule.sport or rule.dport)
|
|
358
|
+
and not rule.protocol
|
|
359
|
+
and mode == "adb_reverse"
|
|
360
|
+
):
|
|
361
|
+
raise ConfigValidationError(
|
|
362
|
+
f"Rule '{rule.name}': sport and dport require a protocol in adb_reverse mode, "
|
|
363
|
+
"as iptables matches ports only with a protocol (-p)"
|
|
364
|
+
)
|
|
365
|
+
parsed_rules.append(rule)
|
|
366
|
+
|
|
367
|
+
hooks = profile_dict.get("hooks", {})
|
|
368
|
+
try:
|
|
369
|
+
_validate_hooks(hooks)
|
|
370
|
+
except (TypeError, ValueError) as e:
|
|
371
|
+
raise ConfigValidationError(
|
|
372
|
+
f"Invalid hooks in profile '{profile_id}': {e}"
|
|
373
|
+
) from e
|
|
374
|
+
|
|
375
|
+
# Instantiate profile
|
|
376
|
+
parsed_profiles[profile_id] = Profile(
|
|
377
|
+
mode=mode,
|
|
378
|
+
rules=parsed_rules,
|
|
379
|
+
mode_opts=mode_opts,
|
|
380
|
+
hooks=hooks,
|
|
381
|
+
)
|
|
382
|
+
|
|
383
|
+
return Config(profiles=parsed_profiles)
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def load_config(file_path: Path) -> Config:
|
|
387
|
+
"""Reads a configuration file and parses it into a Config object."""
|
|
388
|
+
try:
|
|
389
|
+
with open(file_path, "r", encoding="utf-8") as f:
|
|
390
|
+
content = f.read()
|
|
391
|
+
except (OSError, UnicodeDecodeError) as e:
|
|
392
|
+
raise ConfigValidationError(f"Failed to read file {file_path}: {e}") from e
|
|
393
|
+
logger.debug(f"Config {file_path}:\n{content}")
|
|
394
|
+
return parse_config_string(content)
|
|
File without changes
|