vpn: out-of-range endpoint ports are rejected at import, not after TUN setup
- Commit
cf65c1bdeb51652f35e17b6f40f861f13e4f654c- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-01 09:09 UTC (5 days ago)
- Parents
d852a58
endpointPort passed any numeric suffix through, so an Endpoint of host:99999 (also 65536, 0, -1) imported successfully — then at connect time buildTun had already established the TUN (routes/DNS live) before resolveEndpoint's InetSocketAddress threw. The exception escaped the tunnel coroutine: the TUN fd was never closed, isRunning never cleared, and the UI kept showing a dead tunnel as connecting with stale routes up. The .mavpn manifest override reached the same path bypassing the .conf parser entirely. A shared endpointHasInvalidPort check now rejects such configs at import in both parsers (absent/non-numeric keeps the existing default-port behaviour), and resolveEndpoint returns null for an invalid port so already-stored bad configs take the clean closeQuietly + stopVpn path. Three regression tests failed pre-fix (parse accepted; raw IllegalArgumentException at connect). AGENTS.md documents the validation. Leak guard, per-app bypass, always-on restore and teardown were audited and cleared. Verified: :vpn:testDevUnitTest 141 tests pass; lint errors are pre-existing on untouched files.
Diff
vpn/AGENTS.md
diff --git a/vpn/AGENTS.md b/vpn/AGENTS.mdindex 055125351d..d775fa767a 100644--- a/vpn/AGENTS.md+++ b/vpn/AGENTS.md@@ -23,6 +23,7 @@ _Install: ./install vpn (dev by default)._ - Tunnel state lives in the service + Rust core — UI reflects, never drives; reconnect races come from driving twice - VPN permission + always-on/blocking modes are system-mediated; test grant/revoke, not just in-app toggles - WireGuard import (`WgConfigParser`, also used for `.mavpn` servers) is single-peer: configs with multiple `[Peer]` sections are rejected rather than merged into one tunnel+- An `Endpoint` (or `.mavpn` manifest endpoint override) with a numeric port outside 1-65535 is rejected at import; already-stored configs with such a port fail cleanly at tunnel start (established TUN closed, service stopped) instead of throwing out of the tunnel coroutine ## Key files ### Root — entry + navigation
vpn/src/main/java/com/vayunmathur/vpn/data/VpnConfig.kt
diff --git a/vpn/src/main/java/com/vayunmathur/vpn/data/VpnConfig.kt b/vpn/src/main/java/com/vayunmathur/vpn/data/VpnConfig.ktindex fc8a7bb0ce..c1fa19ff28 100644--- a/vpn/src/main/java/com/vayunmathur/vpn/data/VpnConfig.kt+++ b/vpn/src/main/java/com/vayunmathur/vpn/data/VpnConfig.kt@@ -103,6 +103,12 @@ object WgConfigParser { private fun buildImport(sections: Map<String, Map<String, String>>): WgQuickImport { val iface = sections["Interface"] ?: error("Missing [Interface]") val peer = sections["Peer"] ?: error("Missing [Peer]")+ val peerEndpoint = peer["endpoint"] ?: ""+ // A numeric port outside 1..65535 can never connect: storing it would+ // report a successful import for a tunnel that fails at start.+ if (endpointHasInvalidPort(peerEndpoint)) {+ error("Invalid Peer Endpoint port (must be $MIN_ENDPOINT_PORT-$MAX_ENDPOINT_PORT)")+ } return WgQuickImport( privateKey = iface["privatekey"] ?: error("Missing PrivateKey"), address = iface["address"] ?: "",@@ -111,7 +117,7 @@ object WgConfigParser { peerPublicKey = peer["publickey"] ?: error("Missing Peer PublicKey"), peerPresharedKey = peer["presharedkey"] ?: "", peerAllowedIps = peer["allowedips"] ?: "0.0.0.0/0, ::/0",- peerEndpoint = peer["endpoint"] ?: "",+ peerEndpoint = peerEndpoint, peerKeepalive = peer["persistentkeepalive"]?.toIntOrNull() ?: 25, ) }@@ -149,7 +155,22 @@ fun endpointHostOf(peerEndpoint: String): String { } fun VpnConfig.endpointPort(): Int = peerEndpoint.substringAfterLast(':').toIntOrNull() ?: DEFAULT_WG_PORT +/**+ * Whether [peerEndpoint] carries a numeric port outside the UDP port range.+ * An absent or non-numeric suffix is not invalid here: [endpointPort] falls+ * back to the default WireGuard port for those, as it always has. A numeric+ * suffix that parses but is out of range (0, -1, 65536, 99999, …) names a+ * port no socket can use, so callers must reject it instead of storing it or+ * handing it to `InetSocketAddress`, which throws for such ports.+ */+fun endpointHasInvalidPort(peerEndpoint: String): Boolean {+ val port = peerEndpoint.trim().substringAfterLast(':').toLongOrNull() ?: return false+ return port !in MIN_ENDPOINT_PORT..MAX_ENDPOINT_PORT+}+ private const val DEFAULT_WG_PORT = 51820+private const val MIN_ENDPOINT_PORT = 1+private const val MAX_ENDPOINT_PORT = 65535 /** Immutable value describing vpn stats. */ data class VpnStats(
vpn/src/main/java/com/vayunmathur/vpn/domain/MavpnBundle.kt
diff --git a/vpn/src/main/java/com/vayunmathur/vpn/domain/MavpnBundle.kt b/vpn/src/main/java/com/vayunmathur/vpn/domain/MavpnBundle.ktindex 153a3e0e8a..daef879aa5 100644--- a/vpn/src/main/java/com/vayunmathur/vpn/domain/MavpnBundle.kt+++ b/vpn/src/main/java/com/vayunmathur/vpn/domain/MavpnBundle.kt@@ -178,6 +178,12 @@ object MavpnParser { return MavpnManifest(format, provider, servers) } + /** Numeric endpoint ports must be real UDP ports; absent/non-numeric suffixes keep the default-port behaviour. */+ private fun endpointHasInvalidPort(endpoint: String): Boolean {+ val port = endpoint.trim().substringAfterLast(':').toLongOrNull() ?: return false+ return port !in 1..65535+ }+ private fun checkFormat(format: String) { val parts = format.split('/') if (parts.size != 2 || parts[0] != "mavpn") {@@ -199,6 +205,11 @@ object MavpnParser { throw MavpnFormatException("Invalid server file '$file' (expected servers/<name>.conf)") } val endpoint = obj["endpoint"]?.jsonPrimitive?.contentOrNull?.takeIf { it.isNotBlank() }+ // The manifest override bypasses the .conf parser, so it needs the same+ // port check: a numeric port outside 1..65535 can never connect.+ if (endpoint != null && endpointHasInvalidPort(endpoint)) {+ throw MavpnFormatException("Invalid server endpoint port (must be 1-65535)")+ } return MavpnServerEntry(id, country, city, file, endpoint) }
vpn/src/main/java/com/vayunmathur/vpn/service/VpnTunnelService.kt
diff --git a/vpn/src/main/java/com/vayunmathur/vpn/service/VpnTunnelService.kt b/vpn/src/main/java/com/vayunmathur/vpn/service/VpnTunnelService.ktindex 79f17d0e7a..5794421fbc 100644--- a/vpn/src/main/java/com/vayunmathur/vpn/service/VpnTunnelService.kt+++ b/vpn/src/main/java/com/vayunmathur/vpn/service/VpnTunnelService.kt@@ -18,6 +18,7 @@ import androidx.core.app.NotificationCompat import com.vayunmathur.vpn.R import com.vayunmathur.vpn.data.VpnConfig import com.vayunmathur.vpn.data.VpnDatabase+import com.vayunmathur.vpn.data.endpointHasInvalidPort import com.vayunmathur.vpn.data.endpointHost import com.vayunmathur.vpn.data.endpointPort import com.vayunmathur.vpn.data.toModel@@ -378,6 +379,14 @@ class VpnTunnelService : VpnService() { Log.error(TAG, "no endpoint") return null }+ // InetSocketAddress throws for ports outside 0..65535. That exception+ // escaped run() after buildTun() had established the TUN, leaking the+ // fd (and its routes/DNS) and leaving isRunning set, so an already-+ // stored bad endpoint must fail here as "no endpoint" instead.+ if (endpointHasInvalidPort(config.peerEndpoint)) {+ Log.error(TAG, "invalid endpoint port")+ return null+ } return InetSocketAddress(host, port) }
vpn/src/test/java/com/vayunmathur/vpn/data/WgConfigParserTest.kt
diff --git a/vpn/src/test/java/com/vayunmathur/vpn/data/WgConfigParserTest.kt b/vpn/src/test/java/com/vayunmathur/vpn/data/WgConfigParserTest.ktindex 99f0ca2fa6..a201ab4cbf 100644--- a/vpn/src/test/java/com/vayunmathur/vpn/data/WgConfigParserTest.kt+++ b/vpn/src/test/java/com/vayunmathur/vpn/data/WgConfigParserTest.kt@@ -120,6 +120,28 @@ class WgConfigParserTest { assertEquals(1234, VpnConfig(peerEndpoint = "10.0.0.1:1234").endpointPort()) } + @Test fun endpointWithOutOfRangePortIsRejected() {+ // A numeric endpoint port must be a real UDP port. Accepting 99999/0/-1+ // stores a config that can never connect: InetSocketAddress rejects the+ // port at tunnel start, long after import reported success.+ for (badPort in listOf("99999", "65536", "0", "-1")) {+ val conf = """+ [Interface]+ PrivateKey = priv=+ [Peer]+ PublicKey = peer=+ Endpoint = vpn.example.com:$badPort+ """.trimIndent()+ val result = WgConfigParser.parse(conf)+ assertTrue(result.isFailure, "endpoint port $badPort must be rejected, got ${result.getOrNull()}")+ }+ // The top of the valid range still parses.+ val ok = WgConfigParser.parse(+ "[Interface]\nPrivateKey = priv=\n[Peer]\nPublicKey = peer=\nEndpoint = vpn.example.com:65535\n",+ ).getOrThrow()+ assertEquals("vpn.example.com:65535", ok.peerEndpoint)+ }+ @Test fun entityModelRoundTripAndDefaults() { val cfg = VpnConfig(id = 5, name = "n", privateKey = "a", publicKey = "b", address = "c", dns = "d", mtu = 1400, peerPublicKey = "e", peerPresharedKey = "f", peerAllowedIPs = "g", peerEndpoint = "h:1", peerKeepalive = 9, lastUsed = 42) assertEquals(cfg, cfg.toEntity().toModel())
vpn/src/test/java/com/vayunmathur/vpn/domain/MavpnParserTest.kt
diff --git a/vpn/src/test/java/com/vayunmathur/vpn/domain/MavpnParserTest.kt b/vpn/src/test/java/com/vayunmathur/vpn/domain/MavpnParserTest.ktindex 9212d302a8..b6cf348a1e 100644--- a/vpn/src/test/java/com/vayunmathur/vpn/domain/MavpnParserTest.kt+++ b/vpn/src/test/java/com/vayunmathur/vpn/domain/MavpnParserTest.kt@@ -73,6 +73,17 @@ class MavpnParserTest { assertEquals("override.example:9999", server.effectiveEndpoint { it.peerEndpoint }) } + @Test fun rejectsManifestEndpointWithOutOfRangePort() {+ // The manifest endpoint override bypasses the .conf parser, so it needs+ // the same port validation: an override with port 99999 would otherwise+ // be stored and only fail (by throwing) at tunnel start.+ val text = manifest(+ servers = """[{"id":"de-1","country":"DE","city":"Frankfurt","file":"servers/de-1.conf",""" ++ """"endpoint":"override.example:99999"}]""",+ )+ assertTrue(parse(bundle(manifestText = text)).isFailure)+ }+ @Test fun rejectsUnknownFormatMajorAndBadFormat() { assertTrue(parse(bundle(manifestText = manifest(format = "mavpn/2"))).isFailure) assertTrue(parse(bundle(manifestText = manifest(format = "other/1"))).isFailure)
vpn/src/test/java/com/vayunmathur/vpn/service/VpnTunnelServiceTest.kt
diff --git a/vpn/src/test/java/com/vayunmathur/vpn/service/VpnTunnelServiceTest.kt b/vpn/src/test/java/com/vayunmathur/vpn/service/VpnTunnelServiceTest.ktindex 097ce3b5ec..c3187deaca 100644--- a/vpn/src/test/java/com/vayunmathur/vpn/service/VpnTunnelServiceTest.kt+++ b/vpn/src/test/java/com/vayunmathur/vpn/service/VpnTunnelServiceTest.kt@@ -97,6 +97,14 @@ class VpnTunnelServiceTest { assertEquals(51820, session(svc, VpnConfig(peerEndpoint = "127.0.0.1:51820")).resolveEndpoint()!!.port) assertNull(session(svc, VpnConfig(peerEndpoint = "")).resolveEndpoint()) assertEquals(51820, session(svc, VpnConfig(peerEndpoint = "example.invalid")).resolveEndpoint()!!.port)+ // An out-of-range numeric port (already-stored configs, .mavpn endpoint+ // overrides) must fail cleanly as "no endpoint" instead of throwing out+ // of InetSocketAddress: that exception escaped TunnelSession.run after+ // the TUN was established, leaking the fd/routes and leaving isRunning set.+ for (badPort in listOf("99999", "65536", "0", "-1")) {+ assertNull(session(svc, VpnConfig(peerEndpoint = "vpn.example.com:$badPort")).resolveEndpoint())+ }+ assertEquals(65535, session(svc, VpnConfig(peerEndpoint = "vpn.example.com:65535")).resolveEndpoint()!!.port) } @Test fun buildTunAndBuilderHelpersDoNotThrow() { runBlocking {