Skip to content

Commit 8c607a5

Browse files
therealalephclaude
andauthored
Add Android app with full TUN bridge + two proxy fixes the desktop also wants (#29)
The app is a Kotlin/Compose front-end that reuses the mhrv-rs crate via JNI. It speaks VpnService to get a TUN fd, hands that to tun2proxy, and funnels every app's traffic through the in-process SOCKS5 listener — no per-app proxy setup on the device. Two fixes in `src/proxy_server.rs` apply to desktop builds too: * SNI peek via `LazyConfigAcceptor`. When a browser uses DoH (Chrome's default), tun2proxy hands us a raw IP in the SOCKS5 CONNECT. Minting a MITM cert for the IP produced `ERR_CERT_COMMON_NAME_INVALID` on Cloudflare-fronted sites. We now read the ClientHello's SNI first and use that both as the cert subject and as the upstream host for the Apps Script relay (fetching `https://<IP>/...` with an IP in the Host header gets rejected by CF anyway). * Short-circuit CORS preflight at the MITM boundary. `UrlFetchApp.fetch()` rejects `OPTIONS` with a Swedish "Ett attribut med ogiltigt värde har angetts: method" error, which silently broke every fetch()/XHR preflight and was the root cause of "JS doesn't load" on Discord, Yahoo, and similar. Since we already terminate the TLS the browser talks to, answering the preflight with a permissive 204 is safe — the real request still goes through the relay. Android-side capabilities (feature-parity with `mhrv-rs-ui` where it fits on a phone): * multi-deployment ID editor * SNI rotation pool + per-SNI "Test" + "Test all" (JNI into scan_sni) * live logs panel (JNI ring buffer drained on a 500 ms poll) * Advanced section: verify_ssl, parallel_relay, log_level, upstream_socks5 * CA install flow that matches modern Android's reality: saves `Downloads/mhrv-ca.crt` via MediaStore, deep-links Security settings, then verifies post-hoc by fingerprint lookup in AndroidCAStore (the KeyChain intent dead-ends with a Close-only dialog on Android 11+) * Start/Stop debounced to dodge an emulator EGL renderer crash on rapid taps Theme matches the desktop palette exactly — always-dark, accent `#4678B4`, card fill `#1C1E22`, 4dp button / 6dp card radii. No dynamic color, no light scheme: the desktop is always dark and we follow. Build wiring: * `Cargo.toml`: `cdylib` crate-type added; `jni` + `tun2proxy` scoped to `cfg(target_os = "android")` so desktop builds pay nothing. * `src/data_dir.rs`: `set_data_dir()` override so the Android app's private filesDir replaces the `directories` crate's desktop default. * `src/android_jni.rs`: JNI entry points for start/stop/exportCa plus a ring buffer draining to `Native.drainLogs()` and `testSni()` that wraps `scan_sni::probe_one`. * Gradle task chain runs `cargo ndk` before each assemble; post-step normalizes tun2proxy's hash-suffixed cdylib to a stable filename so `System.loadLibrary("tun2proxy")` works. Verified end-to-end on an API 34 emulator: ipleak, yahoo, discord, cloudflare.com all render; TLS is MITM-ed under our user-installed CA; service survives rapid Stop/Start cycles. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent f287921 commit 8c607a5

32 files changed

Lines changed: 4290 additions & 23 deletions

‎Cargo.lock‎

Lines changed: 1237 additions & 12 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Cargo.toml‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,10 @@ license = "MIT"
88
[lib]
99
name = "mhrv_rs"
1010
path = "src/lib.rs"
11+
# `cdylib` lets the Android app dlopen libmhrv_rs.so via System.loadLibrary.
12+
# `rlib` keeps the desktop binaries linking normally — same .rlib is used
13+
# for `mhrv-rs` and `mhrv-rs-ui` builds on macOS/Linux/Windows.
14+
crate-type = ["rlib", "cdylib"]
1115

1216
[[bin]]
1317
name = "mhrv-rs"
@@ -62,6 +66,19 @@ eframe = { version = "0.28", default-features = false, features = [
6266
[target.'cfg(unix)'.dependencies]
6367
libc = "0.2"
6468

69+
# Android-only deps: jni gives us the extern "system" wrappers used in
70+
# src/android_jni.rs; zero cost on any other platform because the whole
71+
# module is `#[cfg(target_os = "android")]`.
72+
#
73+
# tun2proxy is the TUN <-> SOCKS5 bridge — it reads raw IP packets from the
74+
# fd VpnService hands us, runs a userspace TCP/IP stack (smoltcp under the
75+
# hood), and funnels every TCP/UDP flow through our local SOCKS5. Without
76+
# this, VpnService establishes a TUN device nothing reads from and all
77+
# traffic black-holes (symptom: Chrome shows DNS_PROBE_STARTED).
78+
[target.'cfg(target_os = "android")'.dependencies]
79+
jni = { version = "0.21", default-features = false }
80+
tun2proxy = { version = "0.7", default-features = false }
81+
6582
[dev-dependencies]
6683
# Used in mitm tests to sanity-check the cert extensions we emit.
6784
x509-parser = "0.16"

‎android/.gitignore‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
.gradle/
2+
build/
3+
app/build/
4+
app/src/main/jniLibs/
5+
local.properties
6+
.idea/
7+
*.iml
8+
.DS_Store

‎android/app/build.gradle.kts‎

Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
1+
import org.gradle.api.tasks.Exec
2+
3+
plugins {
4+
id("com.android.application")
5+
id("org.jetbrains.kotlin.android")
6+
id("org.jetbrains.kotlin.plugin.compose")
7+
}
8+
9+
android {
10+
namespace = "com.therealaleph.mhrv"
11+
compileSdk = 34
12+
13+
defaultConfig {
14+
applicationId = "com.therealaleph.mhrv"
15+
minSdk = 24 // Android 7.0 — covers 99%+ of live devices.
16+
targetSdk = 34
17+
versionCode = 1
18+
versionName = "0.1.0"
19+
20+
// Only arm64 for now — we can add armeabi-v7a in a second pass
21+
// if field reports need it. Android emulators on Apple Silicon
22+
// only run arm64 natively, so keeping things aarch64-only makes
23+
// the dev loop fast.
24+
ndk {
25+
abiFilters += listOf("arm64-v8a")
26+
}
27+
}
28+
29+
buildTypes {
30+
release {
31+
isMinifyEnabled = false
32+
proguardFiles(
33+
getDefaultProguardFile("proguard-android-optimize.txt"),
34+
"proguard-rules.pro",
35+
)
36+
}
37+
}
38+
39+
compileOptions {
40+
sourceCompatibility = JavaVersion.VERSION_17
41+
targetCompatibility = JavaVersion.VERSION_17
42+
}
43+
44+
kotlinOptions {
45+
jvmTarget = "17"
46+
}
47+
48+
buildFeatures {
49+
compose = true
50+
buildConfig = true
51+
}
52+
53+
// libmhrv_rs.so is produced by `cargo ndk` in the repo root and dropped
54+
// under app/src/main/jniLibs/<abi>/. The cargoBuild task below runs
55+
// that before each assembleDebug / assembleRelease.
56+
sourceSets["main"].jniLibs.srcDirs("src/main/jniLibs")
57+
58+
packaging {
59+
resources.excludes += setOf(
60+
"META-INF/AL2.0",
61+
"META-INF/LGPL2.1",
62+
)
63+
}
64+
}
65+
66+
dependencies {
67+
val composeBom = platform("androidx.compose:compose-bom:2024.06.00")
68+
implementation(composeBom)
69+
androidTestImplementation(composeBom)
70+
71+
implementation("androidx.core:core-ktx:1.13.1")
72+
implementation("androidx.activity:activity-compose:1.9.0")
73+
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.8.2")
74+
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.8.2")
75+
76+
// Compose UI.
77+
implementation("androidx.compose.ui:ui")
78+
implementation("androidx.compose.ui:ui-graphics")
79+
implementation("androidx.compose.ui:ui-tooling-preview")
80+
implementation("androidx.compose.material3:material3")
81+
implementation("androidx.compose.material:material-icons-extended")
82+
83+
debugImplementation("androidx.compose.ui:ui-tooling")
84+
debugImplementation("androidx.compose.ui:ui-test-manifest")
85+
}
86+
87+
// --------------------------------------------------------------------------
88+
// Cross-compile the Rust crate to arm64 Android and drop the .so into the
89+
// place Android's packager looks. We hand the work off to `cargo ndk` which
90+
// wraps the right CC / AR / linker env vars for us.
91+
//
92+
// This ties to the `assemble*` task so every debug/release build triggers
93+
// a `cargo ndk` — no manual step. In CI we'd cache the target/ dir to
94+
// avoid full rebuilds.
95+
// --------------------------------------------------------------------------
96+
val rustCrateDir = rootProject.projectDir.parentFile
97+
val jniLibsDir = file("src/main/jniLibs")
98+
99+
// After cargo-ndk dumps artifacts into jniLibs/arm64-v8a/, the tun2proxy
100+
// cdylib lands as `libtun2proxy-<hash>.so` (rustc's deps/ naming convention,
101+
// because tun2proxy is a transitive dep not a root crate). Android's
102+
// System.loadLibrary expects a stable name, and the hash changes between
103+
// builds, so we normalize it to `libtun2proxy.so` here. Also deletes any
104+
// stale hash-suffixed copies from previous builds.
105+
fun normalizeTun2proxySo() {
106+
val abiDir = file("src/main/jniLibs/arm64-v8a")
107+
if (!abiDir.isDirectory) return
108+
val hashed = abiDir.listFiles { f -> f.name.matches(Regex("libtun2proxy-[0-9a-f]+\\.so")) }
109+
?: emptyArray()
110+
// Keep only the newest (release build) and rename it.
111+
val newest = hashed.maxByOrNull { it.lastModified() }
112+
if (newest != null) {
113+
val target = abiDir.resolve("libtun2proxy.so")
114+
if (target.exists()) target.delete()
115+
newest.copyTo(target, overwrite = true)
116+
}
117+
hashed.forEach { it.delete() }
118+
}
119+
120+
tasks.register<Exec>("cargoBuildDebug") {
121+
group = "build"
122+
// Intentionally ALWAYS uses --release. The Rust debug build is 80+MB
123+
// of unoptimized object code vs 3MB with release; the 20x APK bloat is
124+
// never worth it just for a Rust stack trace you wouldn't see in
125+
// logcat anyway. If you need Rust debug symbols, temporarily drop
126+
// `--release` below and accept the APK size.
127+
description = "Cross-compile mhrv_rs for arm64-v8a (release — same as cargoBuildRelease)"
128+
workingDir = rustCrateDir
129+
commandLine(
130+
"cargo", "ndk",
131+
"-t", "arm64-v8a",
132+
"-o", jniLibsDir.absolutePath,
133+
"build", "--release",
134+
)
135+
doLast { normalizeTun2proxySo() }
136+
}
137+
138+
tasks.register<Exec>("cargoBuildRelease") {
139+
group = "build"
140+
description = "Cross-compile mhrv_rs for arm64-v8a (release)"
141+
workingDir = rustCrateDir
142+
commandLine(
143+
"cargo", "ndk",
144+
"-t", "arm64-v8a",
145+
"-o", jniLibsDir.absolutePath,
146+
"build", "--release",
147+
)
148+
doLast { normalizeTun2proxySo() }
149+
}
150+
151+
// Hook the right cargo task in front of each Android build variant.
152+
tasks.configureEach {
153+
when (name) {
154+
"mergeDebugJniLibFolders" -> dependsOn("cargoBuildDebug")
155+
"mergeReleaseJniLibFolders" -> dependsOn("cargoBuildRelease")
156+
}
157+
}

‎android/app/proguard-rules.pro‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# Keep our JNI entry points so R8 doesn't strip them in release builds.
2+
# These methods are declared `external` in Kotlin — the JNI linker looks
3+
# them up by exact name at load time.
4+
-keep class com.therealaleph.mhrv.Native { *; }
5+
-keep class com.therealaleph.mhrv.MhrvVpnService { *; }
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
3+
xmlns:tools="http://schemas.android.com/tools">
4+
5+
<uses-permission android:name="android.permission.INTERNET" />
6+
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
7+
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
8+
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
9+
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
10+
11+
<application
12+
android:allowBackup="false"
13+
android:dataExtractionRules="@xml/data_extraction_rules"
14+
android:fullBackupContent="false"
15+
android:icon="@mipmap/ic_launcher"
16+
android:label="@string/app_name"
17+
android:networkSecurityConfig="@xml/network_security_config"
18+
android:supportsRtl="true"
19+
android:theme="@style/Theme.Mhrv"
20+
tools:targetApi="34">
21+
22+
<activity
23+
android:name=".MainActivity"
24+
android:exported="true"
25+
android:launchMode="singleTask"
26+
android:theme="@style/Theme.Mhrv">
27+
<intent-filter>
28+
<action android:name="android.intent.action.MAIN" />
29+
<category android:name="android.intent.category.LAUNCHER" />
30+
</intent-filter>
31+
</activity>
32+
33+
<!--
34+
VpnService: Android captures all traffic at the IP layer and feeds
35+
it to us via a TUN file descriptor. The android.net.VpnService action
36+
is what lets the system show us in the "VPN" section of settings
37+
and route through us.
38+
-->
39+
<service
40+
android:name=".MhrvVpnService"
41+
android:exported="false"
42+
android:permission="android.permission.BIND_VPN_SERVICE"
43+
android:foregroundServiceType="specialUse">
44+
<intent-filter>
45+
<action android:name="android.net.VpnService" />
46+
</intent-filter>
47+
<property
48+
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
49+
android:value="vpn_relay" />
50+
</service>
51+
52+
</application>
53+
54+
</manifest>
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package com.github.shadowsocks.bg
2+
3+
/**
4+
* JNI bridge to the tun2proxy crate's Android entry points.
5+
*
6+
* The tun2proxy Rust crate (already pulled in as an Android-only dep of
7+
* libmhrv_rs) defines its C entry points under this exact package path:
8+
* Java_com_github_shadowsocks_bg_Tun2proxy_run
9+
* Java_com_github_shadowsocks_bg_Tun2proxy_stop
10+
*
11+
* That's why this file lives at `com.github.shadowsocks.bg` — we did NOT
12+
* pick this package. Renaming it would break the JNI name mangling and
13+
* the native functions would fail to resolve at runtime.
14+
*
15+
* The crate is reusing Shadowsocks-Android's original JNI convention.
16+
*
17+
* NOTE: the tun2proxy JNI symbols live in libtun2proxy.so (not libmhrv_rs.so).
18+
* tun2proxy is pulled in as a Rust dep of mhrv-rs, but because nothing in
19+
* mhrv-rs calls these symbols directly, Rust's rlib-level dead-code
20+
* elimination drops them from libmhrv_rs.so. The cdylib variant of tun2proxy
21+
* (which rustc builds alongside the rlib) retains them, so we ship that .so
22+
* separately and load it explicitly here.
23+
*/
24+
object Tun2proxy {
25+
26+
init {
27+
System.loadLibrary("tun2proxy")
28+
}
29+
30+
/**
31+
* Start the TUN <-> proxy bridge.
32+
*
33+
* @param proxyUrl e.g. "socks5://127.0.0.1:1081"
34+
* @param tunFd raw fd from VpnService.Builder#establish().detachFd()
35+
* @param closeFdOnDrop whether tun2proxy should close the fd on shutdown.
36+
* We detach and hand over ownership, so this is true.
37+
* @param tunMtu MTU to match the VpnService setMtu() call.
38+
* @param verbosity 0=off, 1=error, 2=warn, 3=info, 4=debug, 5=trace.
39+
* Logs land in logcat under tag "tun2proxy".
40+
* @param dnsStrategy 0=Virtual (fake-IP DNS, tun2proxy resolves via proxy),
41+
* 1=OverTcp (UDP DNS tunneled as TCP via proxy),
42+
* 2=Direct (DNS goes straight through VpnService.protect).
43+
* Virtual is the right default here: app asks DNS for
44+
* example.com, gets a fake 198.18.x.y, tries to connect,
45+
* tun2proxy intercepts, knows the real hostname, opens
46+
* SOCKS5 to our proxy with "example.com:443" as target.
47+
* Our proxy does its own resolution via the Apps Script
48+
* relay, so this gives us end-to-end name resolution
49+
* without leaking plaintext DNS to the ISP.
50+
*
51+
* Returns 0 on normal shutdown, non-zero on error. BLOCKS until the TUN
52+
* is torn down or `stop()` is called — call this from a background thread.
53+
*/
54+
@JvmStatic
55+
external fun run(
56+
proxyUrl: String,
57+
tunFd: Int,
58+
closeFdOnDrop: Boolean,
59+
tunMtu: Char,
60+
verbosity: Int,
61+
dnsStrategy: Int,
62+
): Int
63+
64+
/** Signals the running `run()` to shut down. Idempotent. */
65+
@JvmStatic
66+
external fun stop(): Int
67+
}

0 commit comments

Comments
 (0)