Verify Android proxy egress before reporting connected

This commit is contained in:
UCVL Software Automation
2026-11-15 22:08:40 +08:00
parent 35f2d3b4e7
commit 9c122a8913
12 changed files with 249 additions and 25 deletions
+2 -2
View File
@@ -13,8 +13,8 @@ android {
applicationId = "cn.toplc.zonghengjia"
minSdk = 24
targetSdk = 37
versionCode = 10007
versionName = "1.0.7"
versionCode = 10008
versionName = "1.0.8"
multiDexEnabled = true
val abiFilterList = (properties["ABI_FILTERS"] as? String)?.split(';')
@@ -0,0 +1,76 @@
package com.v2ray.ang.ucvl
import android.os.ParcelFileDescriptor
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.ServerSocket
import java.net.Socket
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
import kotlin.concurrent.thread
@RunWith(AndroidJUnit4::class)
class UcvlEgressProbeTest {
@Test fun rejectsWhenBothExplicitProxyChecksFail() {
exerciseProxy(acceptCloudflare = false)
}
@Test fun independentlyVerifiesSecondTlsTargetWhenFirstFails() {
exerciseProxy(acceptCloudflare = true)
}
private fun exerciseProxy(acceptCloudflare: Boolean) {
val automation = InstrumentationRegistry.getInstrumentation().uiAutomation
val device = ParcelFileDescriptor.AutoCloseInputStream(automation.executeShellCommand("getprop ro.kernel.qemu"))
assertEquals("1", device.bufferedReader().use { it.readText().trim() })
val received = LinkedBlockingQueue<String>()
ServerSocket(0, 4, InetAddress.getByName("127.0.0.1")).use { listener ->
listener.soTimeout = 15_000
val proxy = thread(isDaemon = true, name = "isolated-http-test-proxy") {
repeat(2) {
listener.accept().use { incoming ->
incoming.soTimeout = 10_000
val input = incoming.getInputStream().buffered()
val header = StringBuilder()
while (header.length < 4096 && !header.endsWith("\r\n\r\n")) {
val next = input.read()
if (next == -1) break
header.append(next.toChar())
}
val verb = header.lineSequence().firstOrNull().orEmpty()
received.put(verb)
val output = incoming.getOutputStream()
if (acceptCloudflare && verb == "CONNECT cp.cloudflare.com:443 HTTP/1.1") {
Socket().use { upstream ->
upstream.connect(InetSocketAddress("cp.cloudflare.com", 443), 5_000)
upstream.soTimeout = 10_000
output.write("HTTP/1.1 200 Connection established\r\n\r\n".toByteArray())
output.flush()
thread(isDaemon = true, name = "isolated-http-test-upload") {
runCatching { input.copyTo(upstream.getOutputStream()) }
}
runCatching { upstream.getInputStream().copyTo(output) }
}
} else {
output.write("HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".toByteArray())
output.flush()
}
}
}
}
val verified = runBlocking { UcvlEgressProbe.succeeds(listener.localPort) }
if (acceptCloudflare) assertTrue("Second proxy tunnel must return HTTPS 204", verified) else assertFalse(verified)
assertEquals("CONNECT www.gstatic.com:443 HTTP/1.1", received.poll(2, TimeUnit.SECONDS))
assertEquals("CONNECT cp.cloudflare.com:443 HTTP/1.1", received.poll(2, TimeUnit.SECONDS))
proxy.join(300)
}
}
}
@@ -68,14 +68,21 @@ class UpgradeSmokeTest {
}
}
assertTrue("Login did not render two frames", rendered.await(5, TimeUnit.SECONDS))
// SurfaceFlinger may still be displaying the launch surface after app
// frames are queued. Poll a bounded visual condition, retaining failure evidence.
val buttonCenter = IntArray(2)
inst.runOnMainSync {
val button = activity.findViewById<android.view.View>(R.id.loginButton)
button.getLocationOnScreen(buttonCenter)
// Sample the colored button away from its rounded corners and centered label.
buttonCenter[0] += button.width / 6
buttonCenter[1] += button.height / 2
}
// The scenery can contain a pale header and pale page at the same time.
// A filled blue action button distinguishes a rendered frame from the splash.
fun painted(bitmap: Bitmap): Boolean {
// Sample empty right-hand background, not the white title glyphs
// at the header centre (which caused a false blank-frame result).
val header = bitmap.getPixel(bitmap.width * 9 / 10, bitmap.height / 8)
val page = bitmap.getPixel(bitmap.width * 9 / 10, bitmap.height / 2)
return android.graphics.Color.red(page) - android.graphics.Color.red(header) > 80
val (x, y) = buttonCenter
if (x !in 0 until bitmap.width || y !in 0 until bitmap.height) return false
val pixel = bitmap.getPixel(x, y)
return android.graphics.Color.blue(pixel) - android.graphics.Color.red(pixel) > 80
}
var screenshot = inst.uiAutomation.takeScreenshot()
val deadline = android.os.SystemClock.elapsedRealtime() + 10_000
@@ -161,6 +161,8 @@ object AppConfig {
const val MSG_STATE_START = 3
const val MSG_STATE_START_SUCCESS = 31
const val MSG_STATE_START_FAILURE = 32
const val MSG_STATE_VERIFYING = 33
const val PREF_UCVL_MANAGED_PROFILE = "ucvl_managed_profile"
const val MSG_STATE_STOP = 4
const val MSG_STATE_STOP_SUCCESS = 41
const val MSG_STATE_RESTART = 5
@@ -49,6 +49,7 @@ object CoreServiceManager {
private var browserDialer: IDialerService? = null
private val coreLifecycleLock = Any()
private val coreGeneration = AtomicLong(0)
private val verifiedGeneration = AtomicLong(-1)
var serviceControl: SoftReference<ServiceControl>? = null
set(value) {
@@ -293,11 +294,31 @@ object CoreServiceManager {
}
requireSession(control, epoch)
check(control.reportIfSessionValid(epoch) {
val generation = coreGeneration.get()
if (service is CoreVpnService && guid == MmkvManager.decodeSettingsString(AppConfig.PREF_UCVL_MANAGED_PROFILE)) {
MessageUtil.sendMsg2UI(service, AppConfig.MSG_STATE_VERIFYING, "")
service.verifyEgress(epoch) { ready ->
if (ready) {
reportConnected(service, control, epoch, generation)
} else if (coreGeneration.get() == generation && control.reportIfSessionValid(epoch) {
MessageUtil.sendMsg2UI(service, AppConfig.MSG_STATE_START_FAILURE, "代理出口验证失败,请稍后重连。")
}) {
control.stopService()
}
}
} else {
check(reportConnected(service, control, epoch, generation)) { "VPN session was revoked before startup could be reported" }
}
}
private fun reportConnected(service: Service, control: ServiceControl, epoch: Long, generation: Long): Boolean {
if (serviceControl?.get() !== control || coreGeneration.get() != generation || !coreController.isRunning) return false
val reported = control.reportIfSessionValid(epoch) {
verifiedGeneration.set(generation)
MessageUtil.sendMsg2UI(service, AppConfig.MSG_STATE_START_SUCCESS, "")
}) { "VPN session was revoked before startup could be reported" }
if (isRunning()) NotificationManager.startSpeedNotification()
LogUtil.i(AppConfig.TAG, "StartCore-Manager: Core started successfully")
}
if (reported && isRunning()) NotificationManager.startSpeedNotification()
return reported
}
/**
@@ -518,7 +539,12 @@ object CoreServiceManager {
AppConfig.MSG_REGISTER_CLIENT -> {
val epoch = serviceControl.sessionEpoch()
if (!coreController.isRunning || !serviceControl.reportIfSessionValid(epoch) {
MessageUtil.sendMsg2UI(serviceControl.getService(), AppConfig.MSG_STATE_RUNNING, "")
val state = if (verifiedGeneration.get() == coreGeneration.get()) {
AppConfig.MSG_STATE_RUNNING
} else {
AppConfig.MSG_STATE_VERIFYING
}
MessageUtil.sendMsg2UI(serviceControl.getService(), state, "")
}) {
MessageUtil.sendMsg2UI(serviceControl.getService(), AppConfig.MSG_STATE_NOT_RUNNING, "")
}
@@ -33,6 +33,7 @@ import com.v2ray.ang.util.Utils
import java.lang.ref.SoftReference
import com.v2ray.ang.ucvl.UcvlApiClient
import com.v2ray.ang.ucvl.UcvlAuthorizationGuard
import com.v2ray.ang.ucvl.UcvlEgressProbe
import com.v2ray.ang.ucvl.UcvlSecureStore
import com.v2ray.ang.ucvl.UcvlVpnStartupLease
import kotlinx.coroutines.CoroutineScope
@@ -53,6 +54,7 @@ class CoreVpnService : VpnService(), ServiceControl {
private var tun2SocksService: Tun2SocksControl? = null
private val authorizationScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
private var authorizationJob: Job? = null
private var egressJob: Job? = null
/**destroy
* Unfortunately registerDefaultNetworkCallback is going to return our VPN interface: https://android.googlesource.com/platform/frameworks/base/+/dda156ab0c5d66ad82bdcf76cda07cbc0a9c8a2e
@@ -191,6 +193,15 @@ class CoreVpnService : VpnService(), ServiceControl {
stopAllService(true)
}
fun verifyEgress(epoch: Long, report: (Boolean) -> Unit) {
egressJob?.cancel()
egressJob = authorizationScope.launch {
// The managed runtime uses its fixed SOCKS port plus one for HTTP.
val ready = UcvlEgressProbe.succeeds(SettingsManager.getSocksPort() + 1)
if (isSessionValid(epoch)) report(ready)
}
}
override fun sessionEpoch(): Long = startupEpoch
override fun isSessionValid(epoch: Long): Boolean {
@@ -436,6 +447,8 @@ class CoreVpnService : VpnService(), ServiceControl {
}
private fun stopAllServiceOnMain(isForced: Boolean) {
egressJob?.cancel()
egressJob = null
authorizationJob?.cancel()
authorizationJob = null
// val configName = defaultDPreference.getPrefString(PREF_CURR_CONFIG_GUID, "")
@@ -54,6 +54,16 @@ object UcvlConfigBridge {
val rules = JsonArray()
rules.add(JsonParser.parseString("""{"type":"field","inboundTag":["socks-in","http-in"],"port":"53","outboundTag":"ucvl-dns-out"}"""))
rules.add(JsonParser.parseString("""{"type":"field","inboundTag":["ucvl-dns"],"outboundTag":"proxy"}"""))
// The app uses the loopback HTTP port for its HTTPS startup checks.
// Regular VPN traffic arrives over SOCKS and keeps the platform rules.
rules.add(JsonObject().apply {
addProperty("type", "field")
add("inboundTag", JsonArray().apply { add("http-in") })
add("domain", JsonArray().apply {
UcvlEgressProbe.targets.forEach { add("full:${it.host}") }
})
addProperty("outboundTag", "proxy")
})
originalRules.forEach { rules.add(it.deepCopy()) }
routing.add("rules", rules)
return result
@@ -0,0 +1,50 @@
package com.v2ray.ang.ucvl
import kotlinx.coroutines.suspendCancellableCoroutine
import okhttp3.Call
import okhttp3.Callback
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
import java.net.InetSocketAddress
import java.net.Proxy
import java.util.concurrent.TimeUnit
import kotlin.coroutines.resume
internal object UcvlEgressProbe {
val targets = listOf(
"https://www.gstatic.com/generate_204".toHttpUrl(),
"https://cp.cloudflare.com/generate_204".toHttpUrl(),
)
suspend fun succeeds(port: Int): Boolean {
val client = OkHttpClient.Builder()
.proxy(Proxy(Proxy.Type.HTTP, InetSocketAddress("127.0.0.1", port)))
.followRedirects(false)
.followSslRedirects(false)
.retryOnConnectionFailure(false)
.callTimeout(6, TimeUnit.SECONDS)
.build()
try {
return targets.any { target ->
val request = Request.Builder().url(target).build()
suspendCancellableCoroutine { continuation ->
val call = client.newCall(request)
continuation.invokeOnCancellation { call.cancel() }
call.enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) = continuation.resume(false)
override fun onResponse(call: Call, response: Response) {
response.use { continuation.resume(it.code == 204) }
}
})
}
}
} finally {
client.connectionPool.evictAll()
client.dispatcher.executorService.shutdown()
}
}
}
@@ -248,6 +248,9 @@ class UcvlMainActivity : AppCompatActivity() {
mainViewModel.isRunning.observe(this) { running ->
applyRunningState(running == true)
}
mainViewModel.isStarting.observe(this) {
applyRunningState(mainViewModel.isRunning.value == true)
}
mainViewModel.updateTestResultAction.observe(this) { result ->
if (!result.isNullOrBlank() && mainViewModel.isRunning.value == true) {
statusDetail.text = result
@@ -312,12 +315,12 @@ class UcvlMainActivity : AppCompatActivity() {
}
private fun toggleConnection() {
if (busy) return
if (mainViewModel.isRunning.value == true) {
if (mainViewModel.isRunning.value == true || mainViewModel.isStarting.value == true) {
CoreServiceManager.stopVService(this)
setConnectionState(false, "正在断开", "系统将自动恢复原网络")
return
}
if (busy) return
val currentProfile = profile ?: return
val route = currentProfile.routeModes.getOrNull(routeSpinner.selectedItemPosition)
if (currentProfile.nodes.isEmpty() || route == null) {
@@ -353,10 +356,10 @@ class UcvlMainActivity : AppCompatActivity() {
val raw = UcvlConfigBridge.buildRuntime(response.config, response.node.name, port, port + 1,
SettingsManager.getSocksUsername(), SettingsManager.getSocksPassword(),
response.gateway?.preferredAddress()).toString()
val ownedGuid = MmkvManager.decodeSettingsString(OWNED_PROFILE_KEY).orEmpty()
val ownedGuid = MmkvManager.decodeSettingsString(AppConfig.PREF_UCVL_MANAGED_PROFILE).orEmpty()
val selected = MmkvManager.encodeServerConfig(ownedGuid, CustomFmt.parse(raw))
MmkvManager.encodeServerRaw(selected, raw)
MmkvManager.encodeSettings(OWNED_PROFILE_KEY, selected)
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_MANAGED_PROFILE, selected)
MmkvManager.setSelectServer(selected)
}
MmkvManager.encodeSettings(LAST_NODE_KEY, response.node.slug)
@@ -468,13 +471,26 @@ class UcvlMainActivity : AppCompatActivity() {
val route = profile?.routeModes?.getOrNull(routeSpinner.selectedItemPosition)
currentNode.text = "$nodeName · 平台自动调度"
setConnectionState(true, "已安全连接", listOfNotNull(nodeName, route?.name).joinToString(" · "))
} else if (mainViewModel.isStarting.value == true) {
setConnectionState(false, "正在验证连接", "通过 VPN 检查 HTTPS 是否可用")
} else if (statusTitle.text != "连接失败" && statusTitle.text != "本地直连") {
currentNode.text = "连接后显示实际工作节点"
proxySpeed.text = "↑ 0 B/s ↓ 0 B/s"
setConnectionState(false, "未连接", "点击连接,由平台策略自动选择节点")
}
connectButton.text = if (running) "断开" else "连接"
routeSpinner.isEnabled = !running && !busy
updateConnectControls()
}
private fun updateConnectControls() {
val running = mainViewModel.isRunning.value == true
val verifying = mainViewModel.isStarting.value == true
connectButton.text = when {
running -> "断开"
verifying -> "取消"
else -> "连接"
}
connectButton.isEnabled = running || verifying || (!busy && profile?.nodes?.isNotEmpty() == true)
routeSpinner.isEnabled = !busy && !running && !verifying
}
private fun setConnectionState(connected: Boolean, title: String, detail: String) {
@@ -489,11 +505,10 @@ class UcvlMainActivity : AppCompatActivity() {
private fun setBusy(value: Boolean, message: String = "") {
busy = value
loginButton.isEnabled = !value
connectButton.isEnabled = !value && profile?.nodes?.isNotEmpty() == true
updateConnectControls()
refreshButton.isEnabled = !value
logoutButton.isEnabled = !value
exitButton.isEnabled = !value
routeSpinner.isEnabled = !value && mainViewModel.isRunning.value != true
if (value && dashboardPanel.visibility == View.VISIBLE && message.isNotBlank()) {
statusDetail.text = message
}
@@ -573,7 +588,6 @@ class UcvlMainActivity : AppCompatActivity() {
private const val SOURCE_URL = "https://pro.ucvl.cn/admin/ucvl-zonghengjia-android"
private const val LAST_NODE_KEY = "ucvl_last_node"
private const val LAST_NODE_NAME_KEY = "ucvl_last_node_name"
private const val OWNED_PROFILE_KEY = "ucvl_managed_profile"
private const val LAST_ROUTE_KEY = "ucvl_last_route"
}
}
@@ -44,6 +44,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
var keywordFilter = ""
val serversCache = mutableListOf<ServersCache>()
val isRunning by lazy { MutableLiveData<Boolean>() }
val isStarting by lazy { MutableLiveData(false) }
val updateListAction by lazy { MutableLiveData<Int>() }
val updateTestResultAction by lazy { MutableLiveData<String>() }
private val tcpingTestScope by lazy { CoroutineScope(Dispatchers.IO) }
@@ -457,15 +458,22 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
when (intent?.getIntExtra("key", 0)) {
AppConfig.MSG_STATE_RUNNING -> {
isRunning.value = true
isStarting.value = false
}
AppConfig.MSG_STATE_NOT_RUNNING -> {
isRunning.value = false
isStarting.value = false
}
AppConfig.MSG_STATE_VERIFYING -> {
isStarting.value = true
}
AppConfig.MSG_STATE_START_SUCCESS -> {
getApplication<AngApplication>().toastSuccess(R.string.toast_services_success)
isRunning.value = true
isStarting.value = false
}
AppConfig.MSG_STATE_START_FAILURE -> {
@@ -476,10 +484,12 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
getApplication<AngApplication>().toastError(R.string.toast_services_failure)
}
isRunning.value = false
isStarting.value = false
}
AppConfig.MSG_STATE_STOP_SUCCESS -> {
isRunning.value = false
isStarting.value = false
}
AppConfig.MSG_MEASURE_DELAY_SUCCESS -> {
@@ -26,7 +26,7 @@ class UcvlConfigBridgeTest {
assertEquals(before, source.toString())
assertEquals(source.getAsJsonArray("outbounds")[0], runtime.getAsJsonArray("outbounds")[0])
assertEquals(source.getAsJsonObject("routing").getAsJsonArray("rules")[0],
runtime.getAsJsonObject("routing").getAsJsonArray("rules")[2])
runtime.getAsJsonObject("routing").getAsJsonArray("rules")[3])
assertFalse(runtime.has("api"))
assertTrue(runtime.getAsJsonArray("inbounds").all { it.asJsonObject.get("listen").asString == "127.0.0.1" })
assertTrue(runtime.getAsJsonObject("policy").getAsJsonObject("system").get("statsOutboundUplink").asBoolean)
@@ -41,6 +41,20 @@ class UcvlConfigBridgeTest {
assertFalse(rules.any { it.asJsonObject.get("network")?.asString == "tcp,udp" })
}
@Test fun forcesOnlyLoopbackHttpConnectivityChecksThroughTheProxy() {
val source = fixture()
val rules = UcvlConfigBridge.buildRuntime(source, "VPN002", 10808, 10809)
.getAsJsonObject("routing").getAsJsonArray("rules")
val probe = rules.firstOrNull { rule ->
rule.asJsonObject.getAsJsonArray("inboundTag")?.map { it.asString } == listOf("http-in") &&
rule.asJsonObject.has("domain")
}?.asJsonObject ?: throw AssertionError("HTTPS startup checks can be routed directly")
assertEquals("proxy", probe.get("outboundTag").asString)
assertEquals(listOf("full:cp.cloudflare.com", "full:www.gstatic.com"),
probe.getAsJsonArray("domain").map { it.asString }.sorted())
assertTrue(rules.indexOf(probe) < rules.indexOf(source.getAsJsonObject("routing").getAsJsonArray("rules")[0]))
}
@Test fun usesUnifiedNpmGatewayWithoutChangingPortOrRealitySni() {
val runtime = UcvlConfigBridge.buildRuntime(
fixture(), "VPN002", 10808, 10809, gatewayAddress = "59.110.91.17")