Restore the socket source address across Android mesh networks
Android VpnService routes can select the primary VPN address for traffic to a second subnet even when both aliases are installed. Keep a bounded binding at the local TUN boundary so the peer receives the source it owns in that network and the original Android socket receives the reply. Preserve native primary traffic, separate per-subnet capacity, handle fragmented IPv4 and quoted ICMP errors, and retain eligible bindings when VpnService replaces its descriptor. Support TCP, UDP and ICMP echo. An ambiguous tuple retains its original binding. Explicitly bound traffic for other IPv4 protocols passes using the proper network address. Mesh authentication, address admission and wire formats stay unchanged. Reproduced the wrong source on a disposable Android API 37 ARM64 emulator. After the fix, system ping and an unbound connected UDP socket both received replies across each real VPN subnet. Built both debug APKs and confirmed that only the instrumentation APK includes its helper. Eleven focused Rust checks cover reverse mapping, checksums, fragments, limits and reconfiguration.
This commit is contained in:
1 parent
2e83483f00
commit
972b98363d
11 files changed
+1224
-20
No files matched your search
+15
-1
@@ -20,11 +20,25 @@ Open **tsunagi**, tap **Start VPN**, accept Android’s VPN prompt, then join wi
|
||||
|
||||
The Rust agent owns one interface across the active networks. The Android service establishes the TUN and supplies its descriptor when addresses or exit routes change. Discovery and transport sockets use the selected physical network. TCP health checks bind to the VPN and the address of their own mesh network. The per-network transport selector offers `wg`, `awg`, `wg-quic` and `tcp-tls` in the same default order as the desktop. Each network retains its saved selection and priority. An advertised remote exit can carry the phone’s IPv4 internet traffic.
|
||||
|
||||
When Android chooses the first VPN address for a connection to another mesh, tsunagi translates TCP, UDP and ICMP echo traffic to that mesh’s address and returns replies to the original socket. Applications using other IPv4 protocols should bind to the address of their target mesh. If two sockets would use the same addresses, ports and protocol on the wire, the existing flow keeps its binding.
|
||||
|
||||
Applications using Android’s system resolver can connect to `<member>.<network>` and `<vip>.<network>`, for example `k8s.tsng:6443`. The VPN answers UDP and TCP DNS questions locally using the same signed roster and service records as the desktop. Unknown names in a joined mesh receive an authoritative negative answer. Other names go to Android’s resolver on the underlying Wi-Fi or cellular network, including while using a remote exit. Android 10 and later support arbitrary external DNS record types. On Android 8 and 9 the system lookup API supplies external A and AAAA records.
|
||||
|
||||
The tray and Android use the same egui network tiles, join form, device list, VIP editor and live traffic diagram from `crates/tsunagi-ui`. On Android, the Rust activity view opens each form in the current viewport. Kotlin handles the service, connectivity, rendering surface, input and clipboard.
|
||||
|
||||
Open **Exit node…** on a network tile to compare remote gateways by control RTT and data path. Tap a row and confirm to route IPv4 internet traffic through it. The selected exit has an ongoing notification, including when the peer is offline. **Disconnect exit node** restores the ordinary internet route and keeps mesh access and DNS active. Mesh-only mode has no persistent app notification. Android controls the system VPN indicator. Android 13 and later request notification permission for the exit notice. Starting with Android 14, an unlocked device allows an individual swipe to dismiss an ongoing VPN notification. [Android notification behavior](https://developer.android.com/about/versions/14/behavior-changes-all#non-dismissable-notifications)
|
||||
Open **Exit node…** on a network tile to compare remote gateways by measured data RTT and data path. Tap a row and confirm to route IPv4 internet traffic through it. The selected exit has an ongoing notification, including when the peer is offline. **Disconnect exit node** restores the ordinary internet route and keeps mesh access and DNS active. Mesh-only mode has no persistent app notification. Android controls the system VPN indicator. Android 13 and later request notification permission for the exit notice. Starting with Android 14, an unlocked device allows an individual swipe to dismiss an ongoing VPN notification. [Android notification behavior](https://developer.android.com/about/versions/14/behavior-changes-all#non-dismissable-notifications)
|
||||
|
||||
## Check two networks on an emulator
|
||||
|
||||
Use a disposable ARM64 emulator. The test establishes a temporary VPN, sends UDP and system pings through the production TUN adapter to a local echo peer in each subnet, and checks that the originating applications receive their replies. Set `ANDROID_SERIAL` to that emulator's serial and run from the `android` directory.
|
||||
|
||||
```sh
|
||||
./gradlew :app:assembleDebug :app:assembleDebugAndroidTest
|
||||
adb -s "$ANDROID_SERIAL" install -r app/build/outputs/apk/debug/app-debug.apk
|
||||
adb -s "$ANDROID_SERIAL" install -r app/build/outputs/apk/androidTest/debug/app-debug-androidTest.apk
|
||||
adb -s "$ANDROID_SERIAL" shell appops set cy.hexor.tsunagi ACTIVATE_VPN allow
|
||||
adb -s "$ANDROID_SERIAL" shell am instrument -w cy.hexor.tsunagi.test/androidx.test.runner.AndroidJUnitRunner
|
||||
```
|
||||
|
||||
## Configure GitHub release signing
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@ android {
|
||||
applicationId 'cy.hexor.tsunagi'
|
||||
minSdk 26
|
||||
targetSdk 35
|
||||
testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
|
||||
versionCode providers.gradleProperty('tsunagiVersionCode').getOrElse('1').toInteger()
|
||||
versionName providers.gradleProperty('tsunagiVersionName').getOrElse('1.0.1')
|
||||
ndk { abiFilters abi }
|
||||
@@ -33,7 +34,8 @@ def metadata = providers.exec {
|
||||
workingDir workspace
|
||||
commandLine 'cargo', 'metadata', '--locked', '--format-version', '1', '--filter-platform', 'aarch64-linux-android'
|
||||
}.standardOutput.asText.get()
|
||||
def verifier = new JsonSlurper().parseText(metadata).packages.find { it.name == 'rustls-platform-verifier-android' }
|
||||
def cargoMetadata = new JsonSlurper().parseText(metadata)
|
||||
def verifier = cargoMetadata.packages.find { it.name == 'rustls-platform-verifier-android' }
|
||||
repositories {
|
||||
maven {
|
||||
url new File(new File(verifier.manifest_path).parent, 'maven')
|
||||
@@ -43,7 +45,11 @@ repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
dependencies { implementation "rustls:rustls-platform-verifier:${verifier.version}" }
|
||||
dependencies {
|
||||
implementation "rustls:rustls-platform-verifier:${verifier.version}"
|
||||
androidTestImplementation 'androidx.test:runner:1.5.2'
|
||||
androidTestImplementation 'junit:junit:4.13.2'
|
||||
}
|
||||
|
||||
abstract class BuildRust extends Exec {
|
||||
@OutputDirectory abstract DirectoryProperty getJniLibs()
|
||||
@@ -63,4 +69,20 @@ androidComponents.onVariants(androidComponents.selector().all()) { variant ->
|
||||
if (mode == 'release') args '--release'
|
||||
}
|
||||
variant.sources.jniLibs.addGeneratedSourceDirectory(nativeBuild) { it.jniLibs }
|
||||
if (variant.androidTest != null) {
|
||||
def probe = tasks.register('cargoVpnSourceProbe', BuildRust) {
|
||||
workingDir workspace
|
||||
jniLibs.set(layout.buildDirectory.dir('generated/rust/vpnSourceTest'))
|
||||
inputs.files(nativeBuild.map { it.inputs.files }, fileTree("${workspace}/crates/tsunagi-android/examples"))
|
||||
commandLine 'cargo', 'ndk', '--target', abi, '--platform', '26',
|
||||
'build', '--locked', '--example', 'vpn_source_probe', '-p', 'tsunagi-android'
|
||||
doLast {
|
||||
project.copy {
|
||||
from "${cargoMetadata.target_directory}/aarch64-linux-android/debug/examples/libvpn_source_probe.so"
|
||||
into jniLibs.dir(abi)
|
||||
}
|
||||
}
|
||||
}
|
||||
variant.androidTest.sources.jniLibs.addGeneratedSourceDirectory(probe) { it.jniLibs }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package cy.hexor.tsunagi
|
||||
|
||||
import android.content.Context
|
||||
import android.content.ContextWrapper
|
||||
import android.net.ConnectivityManager
|
||||
import android.net.NetworkCapabilities
|
||||
import android.net.VpnService
|
||||
import android.os.ParcelFileDescriptor
|
||||
import android.os.SystemClock
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import org.junit.Test
|
||||
|
||||
class VpnSourceTest {
|
||||
private external fun checkSockets(fd: Int, networkCount: Int)
|
||||
|
||||
@Test fun udpAndPingReceiveFromBothNetworksAfterAddingTheSecond() {
|
||||
System.loadLibrary("vpn_source_probe")
|
||||
val context = InstrumentationRegistry.getInstrumentation().targetContext
|
||||
check(VpnService.prepare(context) == null) { "Grant VPN consent on the test emulator first" }
|
||||
val connectivity = context.getSystemService(ConnectivityManager::class.java)
|
||||
// Android requires the manifest-declared service class. Attach it under the
|
||||
// application UID without starting the agent and binding this process to the underlay.
|
||||
val vpn = MeshVpn()
|
||||
ContextWrapper::class.java.getDeclaredMethod("attachBaseContext", Context::class.java)
|
||||
.apply { isAccessible = true }.invoke(vpn, context)
|
||||
MeshVpn::class.java.getDeclaredField("upstream").apply { isAccessible = true }
|
||||
.set(vpn, connectivity.activeNetwork)
|
||||
val hosts = listOf("198.18.234.1/24", "198.19.234.1/24")
|
||||
val routes = listOf("198.18.234.0/24", "198.19.234.0/24")
|
||||
fun establish(count: Int): ParcelFileDescriptor {
|
||||
val fd = vpn.establishTun(hosts.take(count).joinToString(","),
|
||||
routes.take(count).joinToString(","), "", 1280, false)
|
||||
check(fd >= 0) { "VPN establishment failed" }
|
||||
return ParcelFileDescriptor.adoptFd(fd)
|
||||
}
|
||||
fun checkVpn(fd: ParcelFileDescriptor, count: Int) {
|
||||
val deadline = SystemClock.elapsedRealtime() + 5000
|
||||
while (true) {
|
||||
val active = connectivity.activeNetwork
|
||||
if (connectivity.getNetworkCapabilities(active)?.hasTransport(NetworkCapabilities.TRANSPORT_VPN) == true
|
||||
&& connectivity.getLinkProperties(active)?.linkAddresses?.size == count) break
|
||||
check(SystemClock.elapsedRealtime() < deadline) { "Timed out waiting for VPN routes" }
|
||||
SystemClock.sleep(25)
|
||||
}
|
||||
checkSockets(ParcelFileDescriptor.dup(fd.fileDescriptor).detachFd(), count)
|
||||
}
|
||||
establish(1).use { first ->
|
||||
checkVpn(first, 1)
|
||||
establish(2).use { both -> checkVpn(both, 2) }
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user