Compare commits
9 Commits
v0.1.0-bet
...
v0.1.0-bet
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
56201f6b72 | ||
|
|
b160652737 | ||
|
|
7df5aa4317 | ||
|
|
99a2993ace | ||
|
|
fb7ad7ec40 | ||
|
|
87bb99c10b | ||
|
|
ba8e2b0aa1 | ||
|
|
e63d41c153 | ||
| 57249605fb |
15
README.md
15
README.md
@@ -35,7 +35,7 @@ Most VPNs treat TCP as a fallback. Konduit is designed for TCP from the ground u
|
||||
- **QR code provisioning** — scan once, connect instantly
|
||||
- **Cross-platform** — Linux, Windows, Android (macOS and iOS coming soon)
|
||||
- **Modern cryptography** — X25519 key exchange, ChaCha20-Poly1305 data channel
|
||||
- **Stealth mode** — port 443 deployment with decoy proxy for hostile network environments
|
||||
- **SOCKS5 chaining** — egress-dial (`use_proxy`) to reach the server through your own proxy, or a post-tunnel listener (`listen_socks`) for per-app routing — see [SOCKS Modes](docs/socks-modes.md)
|
||||
- **Memory safe** — written entirely in Rust
|
||||
|
||||
## Download
|
||||
@@ -80,7 +80,7 @@ Extract the zip and run `konduit.exe` (CLI) or `Konduit.exe` (GUI). `wintun.dll`
|
||||
|
||||
### Android
|
||||
|
||||
Download from [Google Play](https://play.google.com/store/apps/details?id=eu.kaparulin.konduit) or sideload the `.aab` using [bundletool](https://github.com/google/bundletool).
|
||||
Download from [Google Play](https://play.google.com/store/apps/details?id=eu.k_ops.konduit) or sideload the `.aab` using [bundletool](https://github.com/google/bundletool).
|
||||
|
||||
### macOS · iOS
|
||||
|
||||
@@ -95,7 +95,8 @@ Coming soon.
|
||||
**CLI & server**
|
||||
- [Client Quickstart](docs/client-quickstart.md) — download, configure, connect, run as a systemd service
|
||||
- [Server Quickstart](docs/server-quickstart.md) — install, provision, NAT setup for iptables and firewalld
|
||||
- [Stealth Mode Setup](docs/stealth-setup.md) — HAProxy TCP passthrough + camouflage configuration
|
||||
- [SOCKS5 Modes](docs/socks-modes.md) — reach the server through a proxy, or expose a local SOCKS5 listener
|
||||
- [Connection Tuning](docs/connection-tuning.md) — opt-in connection pooling for unstable links
|
||||
- [systemd units](docs/systemd/) — service files for konduit-server, konduit (client), and konduit-admin-ui
|
||||
|
||||
## Architecture
|
||||
@@ -124,7 +125,7 @@ Konduit engine (Rust)
|
||||
|
||||
The [`konduit-platform`](./konduit-platform) crate is published here for transparency and security audit. It contains the cryptographic primitives, connection statistics, and platform networking layer (TUN device, DNS, routes) — everything an auditor needs to verify what runs on your machine. It is licensed under the [PolyForm Noncommercial License 1.0.0](LICENSE) — free to read, study, and use for noncommercial purposes.
|
||||
|
||||
The VPN server, management UI, and stealth-mode protocol are proprietary. Keeping stealth mechanisms private makes automated DPI fingerprinting significantly harder. Source review under NDA is available for enterprise partners.
|
||||
The VPN server and management UI are proprietary. Source review under NDA is available for enterprise partners.
|
||||
|
||||
## Security
|
||||
|
||||
@@ -132,13 +133,9 @@ The VPN server, management UI, and stealth-mode protocol are proprietary. Keepin
|
||||
|
||||
**Key storage:** Private keys are stored in the OS secure enclave on every platform (iOS Keychain, macOS Keychain, Android Keystore). They are never written to disk in plaintext.
|
||||
|
||||
**Stealth mode:** On port 443, failed or unrecognized handshakes are proxied transparently to a configurable decoy service. From the outside, the server is indistinguishable from a standard HTTPS endpoint.
|
||||
|
||||
## Support
|
||||
|
||||
**Bug reports:** Use the in-app reporting feature or open an issue in this repository.
|
||||
|
||||
**Security vulnerabilities:** Do not open a public issue. Contact the maintainer directly at the address shown in the application's About screen.
|
||||
Bug reports, security vulnerabilities, and any other inquiries: use the contact form at [www.k-ops.eu](https://www.k-ops.eu).
|
||||
|
||||
**Contributing:** Core development is handled internally. We do not currently accept external pull requests.
|
||||
|
||||
|
||||
@@ -18,8 +18,6 @@ sudo cp client.toml /opt/konduit/client.toml
|
||||
sudo chmod 600 /opt/konduit/client.toml
|
||||
```
|
||||
|
||||
If your server runs in stealth mode, the config already points to port 443. No additional client-side configuration is needed.
|
||||
|
||||
## 3. Connect
|
||||
|
||||
```bash
|
||||
|
||||
20
docs/connection-tuning.md
Normal file
20
docs/connection-tuning.md
Normal file
@@ -0,0 +1,20 @@
|
||||
# Connection Tuning
|
||||
|
||||
Konduit is a TCP-native VPN. On stable networks, a single TCP connection works fine. On unstable links (spotty Wi-Fi, mobile data, satellite), you can opt into a small pool of pre-warmed connections so a failing connection can be replaced without a full reconnect cascade.
|
||||
|
||||
## Config
|
||||
|
||||
```toml
|
||||
[connection]
|
||||
pool_enabled = false # default off; opt in for unstable links
|
||||
pool_size = 3 # pre-warmed idle connections when enabled
|
||||
carry_duration = 1.0 # seconds an active connection carries traffic before handoff
|
||||
```
|
||||
|
||||
- `pool_enabled` — when `true`, the client keeps `pool_size` extra pre-authenticated connections warm, so an in-use connection can fail over instantly instead of paying a fresh TCP-plus-handshake cost.
|
||||
- `pool_size` — number of pre-warmed idle connections to keep, in addition to the active one. Only used when `pool_enabled = true`.
|
||||
- `carry_duration` — how long (in seconds) an active connection carries traffic before handoff to a pre-warmed one. Only used when `pool_enabled = true`.
|
||||
|
||||
This is a resilience feature, not a stealth feature — it exists purely to make konduit more tolerant of flaky links, and has no effect on how konduit's traffic looks to a network observer.
|
||||
|
||||
Server-side, sticky DL-target routing keeps your active connection selected until it actually fails (detected via a write timeout), rather than rotating on a fixed timer. This needs no client-side configuration.
|
||||
62
docs/diagrams/stealth-architecture.svg
Normal file
62
docs/diagrams/stealth-architecture.svg
Normal file
@@ -0,0 +1,62 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 620 415" width="620" height="415">
|
||||
<defs>
|
||||
<marker id="stealth-ah" markerWidth="8" markerHeight="8" refX="8" refY="3" orient="auto">
|
||||
<path d="M0,0 L0,6 L8,3 z" fill="#546e7a"/>
|
||||
</marker>
|
||||
<marker id="stealth-ahb" markerWidth="8" markerHeight="8" refX="8" refY="3" orient="auto">
|
||||
<path d="M0,0 L0,6 L8,3 z" fill="#1565c0"/>
|
||||
</marker>
|
||||
</defs>
|
||||
|
||||
<!-- Background -->
|
||||
<rect width="620" height="415" rx="10" fill="#fafafa" stroke="#dee2e6" stroke-width="1"/>
|
||||
|
||||
<!-- Title -->
|
||||
<text x="310" y="27" text-anchor="middle" font-family="monospace" font-size="14" font-weight="bold" fill="#263238">Stealth Mode: Real TLS Bypass via HAProxy</text>
|
||||
|
||||
<!-- ── Client ── -->
|
||||
<rect x="185" y="42" width="250" height="62" rx="8" fill="#e0f7fa" stroke="#00838f" stroke-width="2"/>
|
||||
<text x="310" y="68" text-anchor="middle" font-family="monospace" font-size="13" font-weight="bold" fill="#00695c">Client</text>
|
||||
<text x="310" y="87" text-anchor="middle" font-family="monospace" font-size="11" fill="#00695c">stealth = true (or tls = true)</text>
|
||||
|
||||
<!-- Arrow: Client → HAProxy -->
|
||||
<line x1="310" y1="104" x2="310" y2="150" stroke="#546e7a" stroke-width="2" marker-end="url(#stealth-ah)"/>
|
||||
<!-- Arrow label (right side) -->
|
||||
<rect x="318" y="109" width="148" height="34" rx="3" fill="#eceff1"/>
|
||||
<text x="392" y="122" text-anchor="middle" font-family="monospace" font-size="10" fill="#37474f">TLS 1.3 · port 443</text>
|
||||
<text x="392" y="136" text-anchor="middle" font-family="monospace" font-size="10" fill="#37474f">real cert (certbot)</text>
|
||||
<!-- DPI callout (left side of arrow) -->
|
||||
<text x="302" y="120" text-anchor="end" font-family="monospace" font-size="10" font-weight="bold" fill="#e65100">DPI/TSPU:</text>
|
||||
<text x="302" y="134" text-anchor="end" font-family="monospace" font-size="10" fill="#e65100">sees valid HTTPS ✓</text>
|
||||
|
||||
<!-- ── HAProxy ── -->
|
||||
<rect x="108" y="150" width="404" height="78" rx="8" fill="#e8f5e9" stroke="#2e7d32" stroke-width="2"/>
|
||||
<text x="310" y="176" text-anchor="middle" font-family="monospace" font-size="13" font-weight="bold" fill="#1b5e20">HAProxy :443</text>
|
||||
<text x="310" y="194" text-anchor="middle" font-family="monospace" font-size="11" fill="#1b5e20">TLS termination · inspect first byte of payload</text>
|
||||
<text x="310" y="213" text-anchor="middle" font-family="monospace" font-size="10" fill="#388e3c">HTTP method bytes → web backend · binary → konduit</text>
|
||||
|
||||
<!-- Arrow: HAProxy → Web (down-left) -->
|
||||
<line x1="208" y1="228" x2="168" y2="275" stroke="#78909c" stroke-width="1.5" marker-end="url(#stealth-ah)"/>
|
||||
<text x="163" y="258" text-anchor="end" font-family="monospace" font-size="10" fill="#546e7a">HTTP</text>
|
||||
|
||||
<!-- Arrow: HAProxy → Konduit (down-right) -->
|
||||
<line x1="412" y1="228" x2="452" y2="275" stroke="#1565c0" stroke-width="2" marker-end="url(#stealth-ahb)"/>
|
||||
<text x="456" y="258" font-family="monospace" font-size="10" fill="#1565c0">binary</text>
|
||||
|
||||
<!-- ── Web backend ── -->
|
||||
<rect x="78" y="275" width="184" height="58" rx="8" fill="#f5f5f5" stroke="#9e9e9e" stroke-width="1.5"/>
|
||||
<text x="170" y="301" text-anchor="middle" font-family="monospace" font-size="12" font-weight="bold" fill="#424242">Web backend</text>
|
||||
<text x="170" y="319" text-anchor="middle" font-family="monospace" font-size="10" fill="#616161">:8080 (nginx / any HTTP)</text>
|
||||
|
||||
<!-- ── Konduit ── -->
|
||||
<rect x="358" y="275" width="184" height="58" rx="8" fill="#e3f2fd" stroke="#1565c0" stroke-width="2"/>
|
||||
<text x="450" y="301" text-anchor="middle" font-family="monospace" font-size="12" font-weight="bold" fill="#0d47a1">Konduit</text>
|
||||
<text x="450" y="319" text-anchor="middle" font-family="monospace" font-size="10" fill="#1565c0">:8443 plain TCP (stealth off)</text>
|
||||
|
||||
<!-- Arrow: Konduit → VPN -->
|
||||
<line x1="450" y1="333" x2="450" y2="357" stroke="#1565c0" stroke-width="2" marker-end="url(#stealth-ahb)"/>
|
||||
|
||||
<!-- ── VPN Tunnel ── -->
|
||||
<rect x="358" y="357" width="184" height="40" rx="8" fill="#1565c0"/>
|
||||
<text x="450" y="382" text-anchor="middle" font-family="monospace" font-size="12" font-weight="bold" fill="#ffffff">VPN Tunnel</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 4.2 KiB |
@@ -51,7 +51,6 @@ Server-side connection logs are retained for a limited period for operational pu
|
||||
|
||||
- All traffic between client and server is encrypted using **X25519** key exchange and **ChaCha20-Poly1305** AEAD.
|
||||
- The pre-shared key (PSK) is stored in the local config file with permissions restricted to the current user.
|
||||
- Stealth mode wraps the tunnel in a protocol that is indistinguishable from HTTPS, preventing deep-packet inspection from identifying Konduit traffic.
|
||||
|
||||
## Children
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@ echo "your secret mantra phrase here" | ./konduit-ctl bootstrap -l vpn.example.c
|
||||
echo "your secret mantra phrase here" | ./konduit-ctl bootstrap -l vpn.example.com:8443 --public-port 443 -p -
|
||||
```
|
||||
|
||||
`--public-port` sets the port written into client configs, so they connect to 443 even though konduit listens on 8443. See [stealth-setup.md](stealth-setup.md) for the full HAProxy configuration.
|
||||
`--public-port` sets the port written into client configs, so they connect to 443 even though konduit listens on 8443 — useful when running behind any TCP-passthrough reverse proxy (e.g. HAProxy, nginx `stream` module).
|
||||
|
||||
## 3. Add a Client
|
||||
|
||||
@@ -102,8 +102,8 @@ sudo apt install iptables-persistent && sudo netfilter-persistent save
|
||||
## 7. Verify
|
||||
|
||||
```bash
|
||||
# Should return your website (camouflage) not an error
|
||||
curl -sk https://your-server/
|
||||
# Connect a client and confirm the tunnel comes up
|
||||
./konduit --config client.toml
|
||||
|
||||
# Check konduit logs
|
||||
journalctl -u konduit-server -f
|
||||
|
||||
50
docs/socks-modes.md
Normal file
50
docs/socks-modes.md
Normal file
@@ -0,0 +1,50 @@
|
||||
# SOCKS5 Modes
|
||||
|
||||
Konduit is a VPN for reaching your own resources over the public internet — it is not a censorship-circumvention tool, and it doesn't try to disguise its traffic. If you need to get through a network that's actively blocking or fingerprinting VPN traffic, that's a job for a dedicated, purpose-built tool — an SSH SOCKS proxy (`ssh -D`), Xray, sing-box, or similar — not something konduit reimplements.
|
||||
|
||||
What konduit does provide is standard SOCKS5 support on both sides of the connection, so you can chain it with whichever of those tools you already trust.
|
||||
|
||||
## Egress-dial: reaching the server through a proxy (`use_proxy`)
|
||||
|
||||
If you already have a SOCKS5 proxy that gets you out of a restrictive network (for example `ssh -D 1080 jumphost`), point konduit at it instead of dialing the server directly:
|
||||
|
||||
```toml
|
||||
[client]
|
||||
server_endpoint = "vpn.example.com:443"
|
||||
use_proxy = "socks5://127.0.0.1:1080"
|
||||
```
|
||||
|
||||
Or via the CLI:
|
||||
|
||||
```bash
|
||||
./konduit connect --config client.toml --use-proxy socks5://127.0.0.1:1080
|
||||
```
|
||||
|
||||
Konduit dials the SOCKS5 proxy, asks it to `CONNECT` to your server, and then runs its normal protocol over that connection — the proxy is otherwise transparent to it. If the proxy is unreachable, or requires authentication konduit doesn't support, the connection attempt fails immediately; there is no silent fallback to a direct connection.
|
||||
|
||||
## Listener: exposing a SOCKS5 proxy after the tunnel is up (`listen_socks`)
|
||||
|
||||
Once connected, konduit can also expose a local SOCKS5 listener so other tools (browsers, curl, Xray outbounds) can route traffic through the tunnel without needing their own TUN-level integration:
|
||||
|
||||
```toml
|
||||
[client]
|
||||
listen_socks = "127.0.0.1:1080"
|
||||
```
|
||||
|
||||
Or via the CLI:
|
||||
|
||||
```bash
|
||||
./konduit connect --config client.toml --listen-socks 127.0.0.1:1080
|
||||
```
|
||||
|
||||
Connections accepted by the listener are plain outbound TCP connections, routed through the tunnel by the kernel's routing table — the same routes any other tunnelled traffic uses. The SOCKS code itself has no VPN-specific logic.
|
||||
|
||||
Notes:
|
||||
|
||||
- SOCKS5 only, `CONNECT` command only — no `BIND`, no `UDP ASSOCIATE`.
|
||||
- No authentication — bind it to localhost (the default) unless you understand the exposure of doing otherwise.
|
||||
- If no address is given, konduit falls back to `127.0.0.1:1080`. Override the fallback itself with the `KONDUIT_SOCKS_LISTEN_ADDR` environment variable.
|
||||
|
||||
## Using both together
|
||||
|
||||
`use_proxy` and `listen_socks` are independent and can be combined — for example, dial out through an SSH SOCKS proxy to reach your server, and also expose a local SOCKS5 listener once connected for other apps to use.
|
||||
@@ -1,105 +0,0 @@
|
||||
# Stealth Mode: HAProxy + Konduit
|
||||
|
||||
Konduit's stealth mode makes the VPN server indistinguishable from a normal HTTPS site. It implements a fake TLS handshake — embedding the client's ephemeral key inside the TLS `SessionID` field. For this to work, **konduit must see the raw TCP stream from the client**. Any proxy that terminates TLS before konduit breaks stealth mode.
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
Client
|
||||
│ raw TCP (looks like TLS to observers)
|
||||
▼
|
||||
HAProxy :443 ── TCP passthrough ──► konduit-server :8443
|
||||
│
|
||||
valid handshake │ handshake fails (real browser)
|
||||
│ ▼
|
||||
│ HAProxy :4443 (SSL termination)
|
||||
│ │
|
||||
│ ▼
|
||||
│ real HTTPS backend
|
||||
VPN tunnel
|
||||
```
|
||||
|
||||
## HAProxy Configuration
|
||||
|
||||
```haproxy
|
||||
# VPN ingress — raw TCP passthrough, no SSL termination
|
||||
frontend vpn-ingress
|
||||
bind *:443
|
||||
mode tcp
|
||||
option tcplog
|
||||
default_backend konduit-vpn
|
||||
|
||||
backend konduit-vpn
|
||||
mode tcp
|
||||
server konduit 127.0.0.1:8443
|
||||
|
||||
# Camouflage backend — receives failed handshakes from konduit via PROXY protocol
|
||||
# SSL is terminated here, not on the ingress
|
||||
frontend camouflage
|
||||
bind *:4443 ssl crt /etc/haproxy/ssl/your-domain.pem accept-proxy
|
||||
mode http
|
||||
http-request set-header X-Real-IP %[src]
|
||||
http-request set-header X-Forwarded-Proto https
|
||||
default_backend web
|
||||
|
||||
backend web
|
||||
mode http
|
||||
server web1 127.0.0.1:80 check
|
||||
```
|
||||
|
||||
## Konduit server.toml
|
||||
|
||||
```toml
|
||||
[server]
|
||||
listen_addr = "0.0.0.0"
|
||||
listen_port = 8443
|
||||
public_addr = "your-domain.com"
|
||||
public_port = 443 # port clients connect to (HAProxy front)
|
||||
|
||||
[stealth]
|
||||
enabled = true
|
||||
camouflage = "127.0.0.1:4443" # where to proxy non-konduit connections
|
||||
```
|
||||
|
||||
Bootstrap with `--public-port` so generated client configs reference port 443:
|
||||
|
||||
```bash
|
||||
echo "your mantra" | ./konduit-ctl bootstrap -l your-domain.com:8443 --public-port 443 -p -
|
||||
```
|
||||
|
||||
## How It Works
|
||||
|
||||
**Konduit client (stealth handshake):**
|
||||
1. Client sends fake TLS ClientHello with identity proof embedded
|
||||
2. HAProxy passes raw TCP to konduit on port 8443
|
||||
3. Konduit verifies identity, completes handshake, establishes VPN tunnel
|
||||
4. Traffic looks like TLS Application Data to any observer
|
||||
|
||||
**Real browser or censor probe:**
|
||||
1. Browser sends a real TLS ClientHello
|
||||
2. HAProxy passes it raw to konduit
|
||||
3. Konduit cannot verify identity — proxies the connection to `127.0.0.1:4443` with a PROXY protocol header preserving the real client IP
|
||||
4. HAProxy at 4443 terminates TLS and serves your website
|
||||
5. Observer sees a normal HTTPS site
|
||||
|
||||
## Common Mistakes
|
||||
|
||||
```
|
||||
# WRONG — TLS terminated by HAProxy before konduit, fake handshake never works
|
||||
Client → HAProxy SSL termination → konduit
|
||||
|
||||
# CORRECT — raw TCP passed through, konduit handles the fake TLS
|
||||
Client → HAProxy TCP passthrough → konduit → HAProxy SSL termination (on failure)
|
||||
```
|
||||
|
||||
The camouflage frontend uses `accept-proxy` — do not use it as the VPN ingress.
|
||||
|
||||
## Verify
|
||||
|
||||
```bash
|
||||
# Browser should see your real website, not an error
|
||||
curl -sk https://your-domain.com/
|
||||
|
||||
# Check konduit logs for stealth handshakes
|
||||
journalctl -u konduit-server -f | grep -E "Stealth|Authenticated|camouflage"
|
||||
```
|
||||
@@ -100,15 +100,17 @@ pub async fn restore(
|
||||
|
||||
info!("Restoring DNS settings...");
|
||||
|
||||
let result = match if_index {
|
||||
Some(idx) => revert_link_dbus(idx).await,
|
||||
None => revert_resolvectl(interface).await,
|
||||
};
|
||||
|
||||
if let Err(e) = result {
|
||||
warn!("D-Bus DNS revert failed ({}), trying resolvectl", e);
|
||||
revert_resolvectl(interface).await.ok();
|
||||
// Always attempt both paths: D-Bus RevertLink clears per-link config in
|
||||
// systemd-resolved's in-memory state; resolvectl revert is a belt-and-suspenders
|
||||
// pass that ensures the +DefaultRoute domain is removed even if D-Bus races
|
||||
// with interface teardown.
|
||||
if let Some(idx) = if_index {
|
||||
if let Err(e) = revert_link_dbus(idx).await {
|
||||
warn!("D-Bus RevertLink({}) failed: {}", idx, e);
|
||||
}
|
||||
}
|
||||
// Always run resolvectl revert as a second pass.
|
||||
revert_resolvectl(interface).await.ok();
|
||||
|
||||
state.configured = false;
|
||||
Ok(())
|
||||
@@ -172,6 +174,14 @@ async fn revert_link_dbus(if_index: u32) -> Result<()> {
|
||||
.await
|
||||
.context("Failed to create resolve1 proxy")?;
|
||||
|
||||
// Clear DNS servers and routing domains explicitly before the full revert.
|
||||
// RevertLink alone can race with interface teardown in systemd-resolved;
|
||||
// zeroing each setting first ensures they are gone even if RevertLink races.
|
||||
let _ = proxy.set_link_dns(if_index as i32, vec![]).await;
|
||||
let _ = proxy
|
||||
.set_link_domains(if_index as i32, vec![])
|
||||
.await;
|
||||
|
||||
proxy
|
||||
.revert_link(if_index as i32)
|
||||
.await
|
||||
|
||||
@@ -5,6 +5,12 @@ use rtnetlink::{new_connection, Handle, IpVersion};
|
||||
use std::net::{IpAddr, Ipv4Addr};
|
||||
use tracing::{info, warn};
|
||||
|
||||
// Added with priority lower than typical policy-routing stacks (e.g., xray uses 9001).
|
||||
// Ensures konduit's main-table routes (tun0 default, server host-route) win in
|
||||
// full-tunnel mode without modifying any third-party routing table.
|
||||
const VPN_RULE_PRIORITY: u32 = 8000;
|
||||
|
||||
|
||||
const VPN_ROUTE_METRIC: u32 = 50;
|
||||
|
||||
/// Manages routing table for VPN connection using netlink.
|
||||
@@ -21,6 +27,8 @@ pub struct RouteManager {
|
||||
wifi_gateway: Option<Ipv4Addr>,
|
||||
// Saved for re-adding the VPN default route after reconnect.
|
||||
vpn_gateway: Option<Ipv4Addr>,
|
||||
// True when we installed an ip rule to override policy-routing stacks.
|
||||
added_policy_rule: bool,
|
||||
}
|
||||
|
||||
impl RouteManager {
|
||||
@@ -39,6 +47,7 @@ impl RouteManager {
|
||||
server_ip: None,
|
||||
wifi_gateway: None,
|
||||
vpn_gateway: None,
|
||||
added_policy_rule: false,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -58,22 +67,40 @@ impl RouteManager {
|
||||
}
|
||||
|
||||
async fn get_default_gateway(&self) -> Result<Ipv4Addr> {
|
||||
use netlink_packet_route::route::RouteAddress;
|
||||
|
||||
let mut routes = self.handle.route().get(IpVersion::V4).execute();
|
||||
// Collect all default-route gateways with their metrics.
|
||||
// VPN default routes have low metric (50); physical/DHCP routes have high metric (600+).
|
||||
// We want the physical gateway, so take the one with the highest metric.
|
||||
let mut candidates: Vec<(u32, Ipv4Addr)> = Vec::new();
|
||||
|
||||
while let Some(route) = routes.try_next().await? {
|
||||
if route.header.destination_prefix_length == 0 {
|
||||
if route.header.destination_prefix_length != 0 {
|
||||
continue;
|
||||
}
|
||||
let mut metric = 0u32;
|
||||
let mut gateway: Option<Ipv4Addr> = None;
|
||||
for nla in route.attributes.iter() {
|
||||
if let netlink_packet_route::route::RouteAttribute::Gateway(addr) = nla {
|
||||
use netlink_packet_route::route::RouteAddress;
|
||||
if let RouteAddress::Inet(ipv4_addr) = addr {
|
||||
return Ok(*ipv4_addr);
|
||||
}
|
||||
match nla {
|
||||
netlink_packet_route::route::RouteAttribute::Gateway(
|
||||
RouteAddress::Inet(ip),
|
||||
) => gateway = Some(*ip),
|
||||
netlink_packet_route::route::RouteAttribute::Priority(m) => metric = *m,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let Some(gw) = gateway {
|
||||
candidates.push((metric, gw));
|
||||
}
|
||||
}
|
||||
|
||||
anyhow::bail!("No default gateway found")
|
||||
// Highest metric = physical/DHCP interface (not VPN).
|
||||
candidates
|
||||
.into_iter()
|
||||
.max_by_key(|(m, _)| *m)
|
||||
.map(|(_, gw)| gw)
|
||||
.ok_or_else(|| anyhow::anyhow!("No default gateway found"))
|
||||
}
|
||||
|
||||
/// Install routes for the VPN connection.
|
||||
@@ -178,6 +205,8 @@ impl RouteManager {
|
||||
.map_err(|e| anyhow::anyhow!("Failed to add VPN default route: {:?}", e))?;
|
||||
|
||||
self.added_routes.push((Ipv4Addr::new(0, 0, 0, 0), 0));
|
||||
|
||||
self.install_policy_rule().await;
|
||||
} else {
|
||||
info!(
|
||||
"Split-tunnel mode: adding {} routes via VPN...",
|
||||
@@ -239,6 +268,52 @@ impl RouteManager {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Add a high-priority ip rule so konduit's main-table routes override any
|
||||
/// policy-routing stack (e.g., xray, sing-box) that intercepts traffic via a
|
||||
/// separate routing table at priority ~9000.
|
||||
///
|
||||
/// Uses the same netlink handle as every other route change here, rather
|
||||
/// than shelling out to `ip rule add` -- a child process spawned via
|
||||
/// std::process::Command does NOT inherit capabilities granted to this
|
||||
/// process via `setcap`/file capabilities (they'd need to be raised into
|
||||
/// the ambient set first, which nothing here does), so the subprocess
|
||||
/// silently failed with EPERM ("RTNETLINK answers: Operation not
|
||||
/// permitted") every time, regardless of environment. That meant this
|
||||
/// rule never actually got installed, so a competing policy-routing
|
||||
/// stack (e.g. Xray) could keep overriding the VPN's own routes.
|
||||
async fn install_policy_rule(&mut self) {
|
||||
match self
|
||||
.handle
|
||||
.rule()
|
||||
.add()
|
||||
.v4()
|
||||
.priority(VPN_RULE_PRIORITY)
|
||||
// RuleAddRequest::new() defaults the rule's action to Unspec, not
|
||||
// ToTable. A "from all" rule (matches every packet) with an
|
||||
// Unspec action is not a valid "jump to main table" rule and the
|
||||
// kernel does not fall through past it — it broke route lookups
|
||||
// for ALL traffic, not just VPN traffic, until reboot.
|
||||
.action(netlink_packet_route::rule::RuleAction::ToTable)
|
||||
.execute()
|
||||
.await
|
||||
{
|
||||
Ok(()) => {
|
||||
self.added_policy_rule = true;
|
||||
info!("Added ip rule priority {} → main table", VPN_RULE_PRIORITY);
|
||||
}
|
||||
Err(e) => {
|
||||
let err_msg = format!("{:?}", e);
|
||||
if err_msg.contains("File exists") || err_msg.contains("EEXIST") || err_msg.contains("code: Some(-17)")
|
||||
{
|
||||
self.added_policy_rule = true;
|
||||
warn!("ip rule priority {} already exists, continuing...", VPN_RULE_PRIORITY);
|
||||
} else {
|
||||
warn!("Failed to add ip rule priority {}: {:?}", VPN_RULE_PRIORITY, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Setup DNS configuration
|
||||
pub async fn setup_dns(&mut self, dns_servers: &[IpAddr], assigned_ip: IpAddr) -> Result<()> {
|
||||
if dns_servers.is_empty() {
|
||||
@@ -312,11 +387,13 @@ impl RouteManager {
|
||||
let mut to_delete = None;
|
||||
while let Some(route) = routes.try_next().await? {
|
||||
if route.header.destination_prefix_length == 0 {
|
||||
// Identify our default route by its output interface (tun0), not metric,
|
||||
// since the kernel may not round-trip the Priority attribute reliably.
|
||||
let is_ours = route.attributes.iter().any(|nla| {
|
||||
matches!(
|
||||
nla,
|
||||
netlink_packet_route::route::RouteAttribute::Priority(p)
|
||||
if *p == VPN_ROUTE_METRIC
|
||||
netlink_packet_route::route::RouteAttribute::Oif(idx)
|
||||
if Some(*idx) == self.tun_index
|
||||
)
|
||||
});
|
||||
if is_ours {
|
||||
@@ -380,6 +457,33 @@ impl RouteManager {
|
||||
self.added_routes.len()
|
||||
);
|
||||
|
||||
// Remove the policy rule first so traffic stops using the VPN immediately.
|
||||
// Same netlink-handle approach as the add side above -- `handle.rule().del()`
|
||||
// needs the exact existing RuleMessage, so look it up by priority first.
|
||||
if self.added_policy_rule {
|
||||
let mut rules = self.handle.rule().get(IpVersion::V4).execute();
|
||||
let mut to_delete = None;
|
||||
while let Some(rule) = rules.try_next().await? {
|
||||
let matches_priority = rule
|
||||
.attributes
|
||||
.iter()
|
||||
.any(|attr| matches!(attr, netlink_packet_route::rule::RuleAttribute::Priority(p) if *p == VPN_RULE_PRIORITY));
|
||||
if matches_priority {
|
||||
to_delete = Some(rule);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
match to_delete {
|
||||
Some(rule) => match self.handle.rule().del(rule).execute().await {
|
||||
Ok(()) => info!("Removed ip rule priority {}", VPN_RULE_PRIORITY),
|
||||
Err(e) => warn!("Failed to delete ip rule priority {}: {:?}", VPN_RULE_PRIORITY, e),
|
||||
},
|
||||
None => warn!("ip rule priority {} not found, nothing to remove", VPN_RULE_PRIORITY),
|
||||
}
|
||||
self.added_policy_rule = false;
|
||||
}
|
||||
|
||||
if self.added_routes.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -406,16 +510,23 @@ impl RouteManager {
|
||||
|
||||
if let Some(ip) = dest_ip {
|
||||
if self.added_routes.contains(&(ip, prefix_len)) {
|
||||
// For the default route (0.0.0.0/0), match by output interface
|
||||
// (tun0), not just destination prefix — otherwise we also delete
|
||||
// the WiFi default route (same prefix, different OIF/metric).
|
||||
if prefix_len == 0 {
|
||||
let is_ours = route.attributes.iter().any(|nla| {
|
||||
matches!(
|
||||
nla,
|
||||
netlink_packet_route::route::RouteAttribute::Priority(p)
|
||||
if *p == VPN_ROUTE_METRIC
|
||||
netlink_packet_route::route::RouteAttribute::Oif(idx)
|
||||
if Some(*idx) == self.tun_index
|
||||
)
|
||||
});
|
||||
if is_ours {
|
||||
routes_to_delete.push(route);
|
||||
}
|
||||
} else {
|
||||
routes_to_delete.push(route);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -442,3 +553,69 @@ impl Drop for RouteManager {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use netlink_packet_route::rule::RuleAction;
|
||||
|
||||
const REEXEC_ENV_VAR: &str = "KORIDOR_ROUTE_TEST_IN_NETNS";
|
||||
|
||||
// `unshare(CLONE_NEWUSER)` fails with EINVAL if the calling process is
|
||||
// multithreaded (which `cargo test`'s harness always is). So instead of
|
||||
// calling the syscall in-process, re-exec this same test binary under
|
||||
// the external `unshare --user --net --map-root-user` command, which
|
||||
// starts a fresh, single-threaded process already inside an isolated
|
||||
// user+net namespace -- no real root needed, and the host's actual
|
||||
// routing rules are never touched.
|
||||
fn run_in_isolated_netns(test_name: &str) {
|
||||
let exe = std::env::current_exe().expect("current_exe");
|
||||
let status = std::process::Command::new("unshare")
|
||||
.args(["--user", "--net", "--map-root-user", "--"])
|
||||
.arg(&exe)
|
||||
.args(["--exact", test_name, "--nocapture", "--test-threads=1"])
|
||||
.env(REEXEC_ENV_VAR, "1")
|
||||
.status()
|
||||
.expect("failed to spawn unshare (is util-linux's `unshare` installed?)");
|
||||
assert!(status.success(), "test failed inside isolated netns (see output above)");
|
||||
}
|
||||
|
||||
// Regression test for the bug where connecting broke ALL host networking
|
||||
// (not just VPN traffic) until a reboot: the policy rule installed to
|
||||
// make konduit's routes win over other policy-routing stacks was built
|
||||
// via `RuleAddRequest::new()`, which defaults `header.action` to
|
||||
// `RuleAction::Unspec` — a "from all" rule (matches every packet) with
|
||||
// no action is not a valid "jump to main table" rule, and the kernel
|
||||
// does not fall through to the next rule for it, breaking route lookups
|
||||
// system-wide. The fix must set the action explicitly to `ToTable`.
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn policy_rule_uses_to_table_action() {
|
||||
if std::env::var(REEXEC_ENV_VAR).is_err() {
|
||||
run_in_isolated_netns("routes::linux::tests::policy_rule_uses_to_table_action");
|
||||
return;
|
||||
}
|
||||
|
||||
let mut mgr = RouteManager::new("lo".to_string())
|
||||
.await
|
||||
.expect("failed to create RouteManager in isolated netns");
|
||||
|
||||
mgr.install_policy_rule().await;
|
||||
|
||||
let mut rules = mgr.handle.rule().get(IpVersion::V4).execute();
|
||||
let mut found = false;
|
||||
while let Some(rule) = rules.try_next().await.unwrap() {
|
||||
let is_ours = rule.attributes.iter().any(|attr| {
|
||||
matches!(attr, netlink_packet_route::rule::RuleAttribute::Priority(p) if *p == VPN_RULE_PRIORITY)
|
||||
});
|
||||
if is_ours {
|
||||
assert_eq!(
|
||||
rule.header.action,
|
||||
RuleAction::ToTable,
|
||||
"policy rule must use the ToTable action, or the kernel treats it as a black hole for every packet it matches (i.e. everything)"
|
||||
);
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
assert!(found, "installed policy rule not found via rule().get()");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -247,35 +247,6 @@ mod tests {
|
||||
assert_eq!(stats.download_bytes, 2048);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_speed_calculation() {
|
||||
let tracker = StatsTracker::new("utilbox.eu:8443".to_string(), "test".to_string());
|
||||
|
||||
// Record some traffic
|
||||
tracker.record_upload(1024);
|
||||
tracker.record_download(2048);
|
||||
|
||||
// Update to calculate speed
|
||||
tracker.update();
|
||||
|
||||
let stats = tracker.get_stats(false);
|
||||
assert_eq!(stats.upload_speed, 1024);
|
||||
assert_eq!(stats.download_speed, 2048);
|
||||
|
||||
// Record more traffic
|
||||
tracker.record_upload(512);
|
||||
tracker.record_download(1024);
|
||||
|
||||
// Update again
|
||||
tracker.update();
|
||||
|
||||
let stats = tracker.get_stats(false);
|
||||
assert_eq!(stats.upload_bytes, 1536);
|
||||
assert_eq!(stats.download_bytes, 3072);
|
||||
assert_eq!(stats.upload_speed, 512);
|
||||
assert_eq!(stats.download_speed, 1024);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ring_buffer() {
|
||||
let mut buffer = RingBuffer::new();
|
||||
|
||||
@@ -200,6 +200,35 @@ impl TunDevice {
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
|
||||
// Server→TUN first: deliver incoming VPN traffic immediately.
|
||||
//
|
||||
// Deliberately NOT write_all(): a TUN character device requires each
|
||||
// write() syscall to contain exactly one complete packet. write_all()
|
||||
// retries a short write by sending the *remaining* bytes in a follow-up
|
||||
// write() call -- correct for stream sockets, but for a TUN device that
|
||||
// turns one packet into two malformed ones (a truncated first packet,
|
||||
// plus a bogus "packet" made of leftover bytes with no valid IP header).
|
||||
// A single write() either succeeds atomically or it doesn't; there is no
|
||||
// safe way to "continue" a partial packet write, so treat anything short
|
||||
// of a full write as a dropped packet, not a retry target.
|
||||
Some(packet) = from_tcp_rx.recv() => {
|
||||
match writer.write(&packet).await {
|
||||
Ok(n) if n == packet.len() => {}
|
||||
Ok(n) => {
|
||||
error!(
|
||||
"TUN short write: wrote {} of {} bytes -- packet dropped (TUN writes must be atomic per-packet)",
|
||||
n, packet.len()
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
error!("TUN write error: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TUN→TCP: forward outgoing packets from the kernel.
|
||||
packet = tun_pkt_rx.recv() => {
|
||||
match packet {
|
||||
Some(pkt) => {
|
||||
@@ -213,11 +242,6 @@ impl TunDevice {
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(packet) = from_tcp_rx.recv() => {
|
||||
if let Err(e) = writer.write_all(&packet).await {
|
||||
error!("TUN write error: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user