Modern Apps git

← Modern-Apps.git

vpn: an invalid preshared key now fails the tunnel instead of connecting without it

Commit
e3105840a9b87aace0508ffe3d8d39640734bfcc
Author
Vayun Mathur <[email protected]>
When
2026-12-01 01:51 UTC (5 days ago)
Parents
0372aaa
newTunnel decoded the PresharedKey with decode_key, whose
Option collapse turned a decode/length failure into the
same None as 'no PSK configured'. A config with
PresharedKey = not-a-key!!! (or valid base64 of the wrong
length) therefore built a live tunnel that handshaked with
a zero PSK while the peer expected the configured one: the
UI showed Connected and the traffic blackholed. Private and
peer keys already failed creation (-1/-2); the PSK was the
odd one out.

parse_psk now distinguishes absent (empty -> None) from
invalid (anything non-empty that does not decode to 32 bytes
-> error), and newTunnel returns -3, which the service
already treats as failure: the tunnel visibly fails to start
instead of silently connecting wrong. Regression tests on
both sides pin absent/valid/invalid/3-byte/16-byte cases; the
Kotlin test failed pre-fix with a positive handle. Config
parsing, endpoint handling, leak guard and Always-On restore
were audited and cleared. Verified: :vpn:testDevUnitTest 77
+ 62 native tests and the Rust unit test pass; lint errors
are pre-existing on untouched files.

Diff

vpn/src/main/java/com/vayunmathur/vpn/util/VpnNative.kt
diff --git a/vpn/src/main/java/com/vayunmathur/vpn/util/VpnNative.kt b/vpn/src/main/java/com/vayunmathur/vpn/util/VpnNative.ktindex 98fbfdef5a..1d8b82fde9 100644--- a/vpn/src/main/java/com/vayunmathur/vpn/util/VpnNative.kt+++ b/vpn/src/main/java/com/vayunmathur/vpn/util/VpnNative.kt@@ -33,7 +33,8 @@ object VpnNative {     /**      * Creates a new tunnel and returns a handle (positive) or negative error code.      * - privateKey, peerPublicKey: base64 standard-     * - presharedKey: base64 or empty+     * - presharedKey: base64 or empty; a non-empty value that does not decode+     *   to 32 bytes is an error, never silently treated as absent      * - persistentKeepalive: seconds (0 or <=0 means disabled)      */     @JvmStatic external fun newTunnel(
vpn/src/main/rust/src/lib.rs
diff --git a/vpn/src/main/rust/src/lib.rs b/vpn/src/main/rust/src/lib.rsindex f62923e7b0..99a94f23c7 100644--- a/vpn/src/main/rust/src/lib.rs+++ b/vpn/src/main/rust/src/lib.rs@@ -42,6 +42,14 @@ fn decode_key(s: &str) -> Option<[u8; 32]> {     let mut arr = [0u8; 32]; arr.copy_from_slice(&bytes); Some(arr) } fn b64e(k: &[u8]) -> String { use base64::Engine; base64::engine::general_purpose::STANDARD.encode(k) }+/// Parses the optional preshared key: empty means absent (`Ok(None)`), a+/// 32-byte key means present (`Ok(Some(..))`), and anything else is an error.+/// Collapsing the error case into `None` would silently build a tunnel+/// without the configured preshared key instead of failing tunnel creation.+fn parse_psk(s: &str) -> Result<Option<[u8; 32]>, ()> {+    if s.trim().is_empty() { return Ok(None); }+    decode_key(s).map(Some).ok_or(())+} /// Infallible OS RNG adapter for `CryptoRng`-bounded APIs (`random_from_rng`). /// Seeds a `StdRng` from `SysRng`; OS RNG failure is unrecoverable on Android, /// so this expect-matches the pre-existing `from_entropy().unwrap()` behavior.@@ -93,7 +101,7 @@ pub extern "system" fn Java_com_vayunmathur_vpn_util_VpnNative_newTunnel<'l>(         let psk_s = js_to_rs(env, &psk_j);         let Some(priv_b) = decode_key(&priv_s) else { return Ok(-1); };         let Some(peer_b) = decode_key(&peer_s) else { return Ok(-2); };-        let psk = if psk_s.trim().is_empty() { None } else { decode_key(&psk_s) };+        let psk = match parse_psk(&psk_s) { Ok(p) => p, Err(()) => return Ok(-3) };         let ka = if keepalive <= 0 { None } else { Some(keepalive as u16) };         let sec = x25519_dalek::StaticSecret::from(priv_b);         let pubk = x25519_dalek::PublicKey::from(peer_b);@@ -273,6 +281,18 @@ mod tests {         assert!(t0.elapsed() >= std::time::Duration::ZERO);     } +    #[test]+    fn parse_psk_distinguishes_absent_valid_and_invalid() {+        assert_eq!(crate::parse_psk(""), Ok(None));+        assert_eq!(crate::parse_psk("  "), Ok(None));+        let key = [3u8; 32];+        assert_eq!(crate::parse_psk(&crate::b64e(&key)), Ok(Some(key)));+        // Non-empty but not a 32-byte key: an error, never silently absent.+        assert_eq!(crate::parse_psk("not-a-key!!!"), Err(()));+        assert_eq!(crate::parse_psk("cHNr"), Err(())); // valid base64, 3 bytes+        assert_eq!(crate::parse_psk(&crate::b64e(&[0u8; 16])), Err(()));+    }+     #[test]     fn decode_key_unpadded_base64() {         let key = [1u8; 32];
vpn/src/test/java/com/vayunmathur/vpn/util/VpnNativeTest.kt
diff --git a/vpn/src/test/java/com/vayunmathur/vpn/util/VpnNativeTest.kt b/vpn/src/test/java/com/vayunmathur/vpn/util/VpnNativeTest.ktindex 303ec047bd..8656af1487 100644--- a/vpn/src/test/java/com/vayunmathur/vpn/util/VpnNativeTest.kt+++ b/vpn/src/test/java/com/vayunmathur/vpn/util/VpnNativeTest.kt@@ -46,4 +46,26 @@ class VpnNativeTest {         assertTrue(handle <= 0, "bad keys should fail, got handle=$handle")         if (handle > 0) VpnNative.freeTunnel(handle)     }++    @Test fun invalidPresharedKeyIsRejectedNotSilentlyDropped() {+        assertTrue(nativeAvailable(), "host vpn_wireguard lib unavailable: cargoBuildHost must produce libvpn_wireguard for JVM tests")+        val priv = VpnNative.generatePrivateKey()+        val pub = VpnNative.derivePublicKey(priv)+        // A non-empty PresharedKey that does not decode to 32 bytes must fail+        // tunnel creation, exactly like a bad private/peer key. Silently+        // treating it as "no preshared key" would build a tunnel whose+        // handshake uses a zero PSK instead of the configured one.+        for (badPsk in listOf("not-a-key!!!", "cHNr")) {+            val handle = VpnNative.newTunnel(priv, pub, badPsk, 25)+            assertTrue(handle <= 0, "invalid preshared key '$badPsk' should fail, got handle=$handle")+            if (handle > 0) VpnNative.freeTunnel(handle)+        }+        // A valid 32-byte preshared key (and the empty/absent case) still work.+        val validPsk = "cHNrMTIzNDU2Nzg5MGFiY2RlZmdoaWprbG1ub3BxcnM="+        for (psk in listOf(validPsk, "")) {+            val handle = VpnNative.newTunnel(priv, pub, psk, 25)+            assertTrue(handle > 0, "psk='$psk' should succeed, got handle=$handle")+            if (handle > 0) VpnNative.freeTunnel(handle)+        }+    } }