feat: per-app awg and custom via
This commit is contained in:
43 files changed
+2674
-197
No files matched your search
@@ -377,6 +377,18 @@ def _remove_interface_key(config: str, key: str) -> str:
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def dns_servers(config: str) -> list[str]:
|
||||
"""The addresses in [Interface] DNS, in order; search domains left out."""
|
||||
servers: list[str] = []
|
||||
for value in section_values(config, "interface", "dns"):
|
||||
for item in value.split(","):
|
||||
try:
|
||||
servers.append(str(ipaddress.ip_address(item.strip())))
|
||||
except ValueError:
|
||||
pass
|
||||
return servers
|
||||
|
||||
|
||||
def as_outbound(config: str, fwmark: int) -> str:
|
||||
"""Keep the host's routes and resolver: the proxy binds to the interface instead.
|
||||
|
||||
@@ -823,6 +835,11 @@ def main() -> int:
|
||||
metavar="MARK",
|
||||
help="render for an outbound-only interface: no routes or DNS, packets marked MARK",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--dns-out",
|
||||
metavar="FILE",
|
||||
help="also write the profile's DNS server addresses to FILE, one a line",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--wireproxy",
|
||||
metavar="ADDRESS",
|
||||
@@ -894,6 +911,9 @@ def main() -> int:
|
||||
if not isinstance(manifest, dict):
|
||||
raise ConfigError("manifest must be a JSON object")
|
||||
config = prepare(manifest)
|
||||
if args.dns_out is not None:
|
||||
# Before the outbound rendering drops them: per-app routing sends the app's DNS here.
|
||||
write_private(args.dns_out, "".join(f"{server}\n" for server in dns_servers(config)))
|
||||
if args.wireproxy is not None:
|
||||
config = as_wireproxy(config, args.wireproxy, args.outbound_fwmark)
|
||||
elif args.outbound_fwmark is not None:
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
#!/usr/bin/env python3
|
||||
"""DNS for apps run `--via` an AmneziaWG interface: queries over UDP and TCP on loopback, sent
|
||||
on to the profile's resolvers from sockets carrying a mark that policy routing takes into the
|
||||
interface. The app's lookups cannot reach the tunnel themselves: one asked of a stub resolver
|
||||
on 127.0.0.53 has a loopback source, which the kernel never routes out of a real interface.
|
||||
|
||||
With no route in the interface's table the mark meets an unreachable rule, so a lookup fails
|
||||
rather than leaving any other way.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import os
|
||||
import socket
|
||||
import struct
|
||||
import sys
|
||||
|
||||
TIMEOUT = 4.0
|
||||
MAX_MESSAGE = 65535
|
||||
|
||||
|
||||
def upstream_socket(server: str, kind: int, mark: int) -> socket.socket:
|
||||
family = socket.AF_INET6 if ":" in server else socket.AF_INET
|
||||
sock = socket.socket(family, kind)
|
||||
try:
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_MARK, mark)
|
||||
sock.setblocking(False)
|
||||
except OSError:
|
||||
sock.close()
|
||||
raise
|
||||
return sock
|
||||
|
||||
|
||||
async def ask_udp(query: bytes, servers: list[str], mark: int) -> bytes | None:
|
||||
"""The first answer any server gives, in order; None when none does."""
|
||||
loop = asyncio.get_running_loop()
|
||||
for server in servers:
|
||||
try:
|
||||
sock = upstream_socket(server, socket.SOCK_DGRAM, mark)
|
||||
except OSError:
|
||||
continue
|
||||
try:
|
||||
await loop.sock_connect(sock, (server, 53))
|
||||
await loop.sock_sendall(sock, query)
|
||||
return await asyncio.wait_for(loop.sock_recv(sock, MAX_MESSAGE), TIMEOUT)
|
||||
except (OSError, asyncio.TimeoutError):
|
||||
continue
|
||||
finally:
|
||||
sock.close()
|
||||
return None
|
||||
|
||||
|
||||
class UdpListener(asyncio.DatagramProtocol):
|
||||
def __init__(self, servers: list[str], mark: int):
|
||||
self.servers = servers
|
||||
self.mark = mark
|
||||
self.transport = None
|
||||
|
||||
def connection_made(self, transport):
|
||||
self.transport = transport
|
||||
|
||||
def datagram_received(self, data, addr):
|
||||
asyncio.ensure_future(self.answer(data, addr))
|
||||
|
||||
async def answer(self, query, addr):
|
||||
reply = await ask_udp(query, self.servers, self.mark)
|
||||
if reply is not None and self.transport is not None:
|
||||
self.transport.sendto(reply, addr)
|
||||
|
||||
|
||||
async def read_message(reader: asyncio.StreamReader) -> bytes | None:
|
||||
try:
|
||||
(length,) = struct.unpack("!H", await reader.readexactly(2))
|
||||
return await reader.readexactly(length)
|
||||
except (asyncio.IncompleteReadError, ConnectionError):
|
||||
return None
|
||||
|
||||
|
||||
async def ask_tcp(query: bytes, servers: list[str], mark: int) -> bytes | None:
|
||||
loop = asyncio.get_running_loop()
|
||||
for server in servers:
|
||||
try:
|
||||
sock = upstream_socket(server, socket.SOCK_STREAM, mark)
|
||||
except OSError:
|
||||
continue
|
||||
try:
|
||||
await asyncio.wait_for(loop.sock_connect(sock, (server, 53)), TIMEOUT)
|
||||
reader, writer = await asyncio.open_connection(sock=sock)
|
||||
except (OSError, asyncio.TimeoutError):
|
||||
sock.close()
|
||||
continue
|
||||
try:
|
||||
writer.write(struct.pack("!H", len(query)) + query)
|
||||
await writer.drain()
|
||||
reply = await asyncio.wait_for(read_message(reader), TIMEOUT)
|
||||
if reply is not None:
|
||||
return reply
|
||||
except (OSError, asyncio.TimeoutError):
|
||||
pass
|
||||
finally:
|
||||
writer.close()
|
||||
return None
|
||||
|
||||
|
||||
def tcp_handler(servers: list[str], mark: int):
|
||||
async def handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
|
||||
try:
|
||||
while (query := await asyncio.wait_for(read_message(reader), 30)) is not None:
|
||||
reply = await ask_tcp(query, servers, mark)
|
||||
if reply is None:
|
||||
break
|
||||
writer.write(struct.pack("!H", len(reply)) + reply)
|
||||
await writer.drain()
|
||||
except (OSError, asyncio.TimeoutError):
|
||||
pass
|
||||
finally:
|
||||
writer.close()
|
||||
|
||||
return handle
|
||||
|
||||
|
||||
def notify_ready():
|
||||
"""sd_notify(READY=1), for Type=notify: the start is done once the listeners are up."""
|
||||
path = os.environ.get("NOTIFY_SOCKET")
|
||||
if not path:
|
||||
return
|
||||
if path.startswith("@"):
|
||||
path = "\0" + path[1:]
|
||||
with socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) as sock:
|
||||
sock.connect(path)
|
||||
sock.sendall(b"READY=1")
|
||||
|
||||
|
||||
async def serve(port: int, mark: int, servers: list[str]):
|
||||
loop = asyncio.get_running_loop()
|
||||
for host in ("127.0.0.1", "::1"):
|
||||
try:
|
||||
await loop.create_datagram_endpoint(lambda: UdpListener(servers, mark), local_addr=(host, port))
|
||||
await asyncio.start_server(tcp_handler(servers, mark), host, port)
|
||||
except OSError as exc:
|
||||
# IPv6 may be off.
|
||||
if host == "127.0.0.1":
|
||||
raise
|
||||
print(f"per-app-dns: not on [{host}]:{port}: {exc}", file=sys.stderr)
|
||||
notify_ready()
|
||||
await asyncio.Event().wait()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--port", type=int, required=True)
|
||||
parser.add_argument("--mark", type=int, required=True)
|
||||
parser.add_argument("servers", nargs="*", help="resolver addresses, asked in order")
|
||||
args = parser.parse_args()
|
||||
asyncio.run(serve(args.port, args.mark, args.servers))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -499,6 +499,35 @@ class AmneziaWgConfigTests(unittest.TestCase):
|
||||
# The peer is untouched.
|
||||
self.assertIn("Endpoint = vpn.example.com:51820", rendered)
|
||||
|
||||
def test_dns_servers_skip_search_domains(self):
|
||||
config = BASE_CONFIG.replace("$PRIMARY_DNS,$SECONDARY_DNS", "1.1.1.1, corp.example,2606:4700::1111")
|
||||
self.assertEqual(amneziawg_config.dns_servers(config), ["1.1.1.1", "2606:4700::1111"])
|
||||
self.assertEqual(amneziawg_config.dns_servers("[Interface]\nAddress = 10.0.0.2/32\n"), [])
|
||||
|
||||
def test_dns_out_written_before_outbound_render_drops_dns(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
source = Path(directory) / "de.conf"
|
||||
source.write_text(BASE_CONFIG.replace("$PRIMARY_DNS,$SECONDARY_DNS", "1.1.1.1,8.8.8.8"))
|
||||
output = Path(directory) / "out.conf"
|
||||
dns = Path(directory) / "dns"
|
||||
subprocess.run(
|
||||
[
|
||||
sys.executable,
|
||||
amneziawg_config.__file__,
|
||||
"--config",
|
||||
str(source),
|
||||
"--output",
|
||||
str(output),
|
||||
"--outbound-fwmark",
|
||||
"2",
|
||||
"--dns-out",
|
||||
str(dns),
|
||||
],
|
||||
check=True,
|
||||
)
|
||||
self.assertEqual(dns.read_text(), "1.1.1.1\n8.8.8.8\n")
|
||||
self.assertEqual(amneziawg_config.section_values(output.read_text(), "interface", "dns"), [])
|
||||
|
||||
def test_resolve_endpoints(self):
|
||||
# Under the kill switch awg-quick gets addresses; a name that does not resolve is left.
|
||||
config = "[Peer]\nEndpoint = vpn.example:51820\n[Peer]\nEndpoint = 192.0.2.1:1\nendpoint = [2001:db8::1]:2\n[Peer]\nEndpoint = gone.invalid:3\n"
|
||||
|
||||
Reference in new issue
Block a user