Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@
- **TLS Fragmentation (Record & Packet)**
- **uTLS Fingerprint Emulation**
- **Upstream Proxy Chaining**
- **Custom Edge Override**
- **Custom Edge Override/Scanner**
- **Custom SNI**
- **Multiplexing & Concurrency Controls**
- **Custom Tunnel MTU**
- **Automatic Connection Recovery**
Expand Down
4 changes: 2 additions & 2 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ android {
applicationId = "com.vauth.foxyvpn"
minSdk = 26
targetSdk = 35
versionCode = 50
versionName = "2.0.4"
versionCode = 51
versionName = "2.0.5"
}

splits {
Expand Down
3 changes: 3 additions & 0 deletions app/src/main/java/com/vauth/foxyvpn/FoxyVpnApp.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import android.app.NotificationManager
import android.content.res.Configuration
import com.vauth.foxyvpn.data.ControlPlaneHttp
import com.vauth.foxyvpn.data.CrashReporter
import com.vauth.foxyvpn.data.EdgeScanner
import com.vauth.foxyvpn.data.FoxyRemoteConfig
import com.vauth.foxyvpn.data.FxaAuthRepository
import com.vauth.foxyvpn.data.GuardianClient
Expand Down Expand Up @@ -68,6 +69,8 @@ class FoxyVpnApp : Application(), AppContainer {
)
} else null
}
EdgeScanner.upstreamProxyProvider = ControlPlaneHttp.upstreamProxyProvider
EdgeScanner.bootstrapDnsConfigProvider = ControlPlaneHttp.bootstrapDnsConfigProvider
ControlPlaneHttp.relayerConfigProvider = {
RelayerConfig(
provider = settingsStore.relayerProvider,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ object ControlPlaneHttp {
@Volatile private var cachedDnsOverHttps: DnsOverHttps? = null
private val dohLock = Any()

private fun getOrCreateDoh(dohUrl: String): DnsOverHttps? {
internal fun getOrCreateDoh(dohUrl: String): DnsOverHttps? {
if (cachedDohUrl == dohUrl) {
val cached = cachedDnsOverHttps
if (cached != null) return cached
Expand Down
137 changes: 137 additions & 0 deletions app/src/main/java/com/vauth/foxyvpn/data/EdgeScanner.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
package com.vauth.foxyvpn.data

import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.Proxy
import java.net.Socket
import java.util.concurrent.atomic.AtomicInteger
import javax.net.ssl.HttpsURLConnection
import javax.net.ssl.SNIHostName
import javax.net.ssl.SSLContext
import javax.net.ssl.SSLSocket
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withPermit
import kotlinx.coroutines.withContext
import okhttp3.Dns

object EdgeScanner {
const val MASQUE_HOST = "p.m1.fastly-masque.net"
const val MASQUE_PORT = 2499
const val RANGE_BASE = "23.235.42"
const val HOST_COUNT = 254

private const val CONNECT_TIMEOUT_MS = 1500
private const val TLS_TIMEOUT_MS = 3000
private const val MAX_CONCURRENT = 20

@Volatile var upstreamProxyProvider: (() -> UpstreamProxyConfig?)? = null

@Volatile var bootstrapDnsConfigProvider: (() -> Pair<SettingsStore.DnsProvider, String>)? = null

@Volatile var networkProvider: (() -> android.net.Network?)? = null

@Volatile var socketProtector: ((Socket) -> Boolean)? = null

data class EdgeScanResult(val address: String, val ms: Int)

private data class ProbeOutcome(val address: String, val tlsMs: Int, val httpMs: Int?)

suspend fun scanBestEdge(onProgress: suspend (tested: Int, total: Int) -> Unit): EdgeScanResult? =
withContext(Dispatchers.IO) {
val proxy = proxyForScan() ?: return@withContext null
val hosts = (1..HOST_COUNT).map { "$RANGE_BASE.$it" }
val tested = AtomicInteger(0)
val semaphore = Semaphore(MAX_CONCURRENT)
val sslContext = SSLContext.getInstance("TLS").apply { init(null, null, null) }
val outcomes = hosts.map { host ->
async {
val result = semaphore.withPermit { probeEdge(host, sslContext, proxy) }
onProgress(tested.incrementAndGet(), hosts.size)
result
}
}.awaitAll().filterNotNull()
val httpBest = outcomes.mapNotNull { outcome ->
outcome.httpMs?.let { EdgeScanResult(outcome.address, it) }
}.minByOrNull { it.ms }
if (httpBest != null) return@withContext httpBest
outcomes.minByOrNull { it.tlsMs }?.let { EdgeScanResult(it.address, it.tlsMs) }
}

private fun proxyForScan(): Proxy? {
val config = upstreamProxyProvider?.invoke() ?: return Proxy.NO_PROXY
if (config.host.isBlank() || config.port !in 1..65535) return Proxy.NO_PROXY
val proxyType = if (config.type == SettingsStore.UpstreamProxyType.HTTP) Proxy.Type.HTTP else Proxy.Type.SOCKS
val address = resolveProxyHost(config.host) ?: return null
return Proxy(proxyType, InetSocketAddress(address, config.port))
}

private fun resolveProxyHost(host: String): InetAddress? {
if (SettingsStore.isValidIpAddress(host)) {
return runCatching { InetAddress.getByName(host) }.getOrNull()
}
val config = bootstrapDnsConfigProvider?.invoke()
val provider = config?.first ?: SettingsStore.DnsProvider.DIRECT_SYSTEM
val dohUrl = config?.second.orEmpty()
if (provider != SettingsStore.DnsProvider.DIRECT_SYSTEM && dohUrl.isNotBlank()) {
val doh = ControlPlaneHttp.getOrCreateDoh(dohUrl)
if (doh != null) {
return runCatching { doh.lookup(host).firstOrNull() }.getOrNull()
}
}
val network = runCatching { networkProvider?.invoke() }.getOrNull()
val fromNetwork = if (network != null) {
runCatching { network.getAllByName(host).toList() }.getOrNull()
} else {
null
}
if (!fromNetwork.isNullOrEmpty()) return fromNetwork.first()
return runCatching { Dns.SYSTEM.lookup(host).firstOrNull() }.getOrNull()
}

private fun probeEdge(host: String, sslContext: SSLContext, proxy: Proxy): ProbeOutcome? {
val start = System.nanoTime()
val plain = Socket(proxy)
try {
val protector = socketProtector
if (protector != null && !protector(plain)) return null
plain.connect(InetSocketAddress(host, MASQUE_PORT), CONNECT_TIMEOUT_MS)
val sslSocket = sslContext.socketFactory.createSocket(plain, host, MASQUE_PORT, true) as SSLSocket
sslSocket.soTimeout = TLS_TIMEOUT_MS
return sslSocket.use {
val params = it.sslParameters
params.serverNames = listOf(SNIHostName(MASQUE_HOST))
it.sslParameters = params
it.startHandshake()
if (!HttpsURLConnection.getDefaultHostnameVerifier().verify(MASQUE_HOST, it.session)) return@use null
val tlsMs = ((System.nanoTime() - start) / 1_000_000L).coerceAtLeast(1L).toInt()
val httpMs = try {
val request = "GET / HTTP/1.1\r\nHost: $MASQUE_HOST\r\nConnection: close\r\n\r\n"
it.outputStream.write(request.toByteArray(Charsets.US_ASCII))
it.outputStream.flush()
val buffer = ByteArray(5)
var read = 0
while (read < 5) {
val n = it.inputStream.read(buffer, read, 5 - read)
if (n == -1) return@use ProbeOutcome(host, tlsMs, null)
read += n
}
if (!String(buffer, Charsets.US_ASCII).startsWith("HTTP/")) return@use ProbeOutcome(host, tlsMs, null)
((System.nanoTime() - start) / 1_000_000L).coerceAtLeast(1L).toInt()
} catch (_: Exception) {
null
}
ProbeOutcome(host, tlsMs, httpMs)
}
} catch (_: Exception) {
return null
} finally {
try {
plain.close()
} catch (_: Exception) {
}
}
}
}
14 changes: 13 additions & 1 deletion app/src/main/java/com/vauth/foxyvpn/data/SettingsStore.kt
Original file line number Diff line number Diff line change
Expand Up @@ -382,14 +382,25 @@ class SettingsStore(context: Context) {
var customEdgeAddress: String
get() = prefs.getString(KEY_CUSTOM_EDGE_ADDRESS, "") ?: ""
set(value) {
val normalized = value.trim().lowercase()
val normalized = value.trim().lowercase().removeSuffix(".")
if (normalized.isNotEmpty() && !isValidEdgeHost(normalized)) return
prefs.edit().putString(KEY_CUSTOM_EDGE_ADDRESS, normalized).apply()
}

val effectiveCustomEdgeAddress: String?
get() = customEdgeAddress.takeIf { isValidEdgeHost(it) }

var customSni: String
get() = prefs.getString(KEY_CUSTOM_SNI, "") ?: ""
set(value) {
val normalized = value.trim().lowercase().removeSuffix(".")
if (normalized.isNotEmpty() && !isValidHostname(normalized)) return
prefs.edit().putString(KEY_CUSTOM_SNI, normalized).apply()
}

val effectiveCustomSni: String?
get() = customSni.takeIf { isValidHostname(it) }

val localProxyAuthEnabled: Boolean
get() = prefs.getBoolean("local_proxy_auth_enabled", false)

Expand Down Expand Up @@ -702,6 +713,7 @@ class SettingsStore(context: Context) {
const val DEFAULT_MAX_CONCURRENT_STREAMS = 32
private const val KEY_PROXY_ONLY_MODE = "proxy_only_mode"
private const val KEY_CUSTOM_EDGE_ADDRESS = "custom_edge_address"
private const val KEY_CUSTOM_SNI = "custom_sni"
private const val KEY_UPSTREAM_PROXY_ENABLED = "upstream_proxy_enabled"
private const val KEY_UPSTREAM_PROXY_TYPE = "upstream_proxy_type"
private const val KEY_UPSTREAM_PROXY_HOST = "upstream_proxy_host"
Expand Down
2 changes: 2 additions & 0 deletions app/src/main/java/com/vauth/foxyvpn/data/TunnelSettings.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ data class TunnelSettings(
val dnsProvider: SettingsStore.DnsProvider,
val bootstrapDnsProvider: SettingsStore.DnsProvider,
val effectiveCustomEdgeAddress: String?,
val effectiveCustomSni: String?,
val effectiveDohUrl: String,
val effectiveBootstrapDohUrl: String,
val excludedApps: Set<String>,
Expand Down Expand Up @@ -46,6 +47,7 @@ fun SettingsStore.tunnelSnapshot(): TunnelSettings =
dnsProvider = dnsProvider,
bootstrapDnsProvider = bootstrapDnsProvider,
effectiveCustomEdgeAddress = effectiveCustomEdgeAddress,
effectiveCustomSni = effectiveCustomSni,
effectiveDohUrl = effectiveDohUrl,
effectiveBootstrapDohUrl = effectiveBootstrapDohUrl,
excludedApps = excludedApps.toSet(),
Expand Down
20 changes: 20 additions & 0 deletions app/src/main/java/com/vauth/foxyvpn/ui/screens/SettingsScreen.kt
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ import com.vauth.foxyvpn.ui.ProxyEditor
import com.vauth.foxyvpn.ui.ProxySettingsViewModel
import com.vauth.foxyvpn.ui.settings.ConcurrencyPickerDialog
import com.vauth.foxyvpn.ui.settings.CustomEdgeAddressDialog
import com.vauth.foxyvpn.ui.settings.CustomSniDialog
import com.vauth.foxyvpn.ui.settings.DnsProviderPickerDialog
import com.vauth.foxyvpn.ui.settings.HttpVersionPickerDialog
import com.vauth.foxyvpn.ui.settings.IpModePickerDialog
Expand Down Expand Up @@ -84,6 +85,7 @@ private enum class SettingsDialog {
DNS_PROVIDER,
BOOTSTRAP_DNS_PROVIDER,
EDGE_ADDRESS,
CUSTOM_SNI,
SPLIT_TUNNEL,
HTTP_VERSION,
IP_MODE,
Expand Down Expand Up @@ -114,6 +116,7 @@ fun SettingsScreen(
var customBootstrapDohUrl by remember { mutableStateOf(settingsStore.customBootstrapDohUrl) }
var proxyOnlyMode by remember { mutableStateOf(settingsStore.proxyOnlyMode) }
var customEdgeAddress by remember { mutableStateOf(settingsStore.customEdgeAddress) }
var customSni by remember { mutableStateOf(settingsStore.customSni) }
var excludedApps by remember { mutableStateOf(settingsStore.excludedApps) }
var includedApps by remember { mutableStateOf(settingsStore.includedApps) }
var bypassLocalNetwork by remember { mutableStateOf(settingsStore.bypassLocalNetwork) }
Expand Down Expand Up @@ -269,6 +272,15 @@ fun SettingsScreen(
activeDialog = SettingsDialog.NONE
},
)
SettingsDialog.CUSTOM_SNI -> CustomSniDialog(
current = customSni,
onDismiss = { activeDialog = SettingsDialog.NONE },
onConfirm = {
customSni = it
settingsStore.customSni = it
activeDialog = SettingsDialog.NONE
},
)
SettingsDialog.SPLIT_TUNNEL -> SplitTunnelDialog(
currentMode = splitTunnelMode,
currentExcluded = excludedApps,
Expand Down Expand Up @@ -559,6 +571,14 @@ fun SettingsScreen(
},
modifier = Modifier.clickable { activeDialog = SettingsDialog.EDGE_ADDRESS },
)
ListItem(
headlineContent = { Text(stringResource(R.string.settings_custom_sni)) },
supportingContent = { Text(customSni.ifBlank { stringResource(R.string.not_set) }) },
trailingContent = {
Icon(Icons.AutoMirrored.Filled.KeyboardArrowRight, contentDescription = null)
},
modifier = Modifier.clickable { activeDialog = SettingsDialog.CUSTOM_SNI },
)
ListItem(
headlineContent = { Text(stringResource(R.string.settings_transport_protocol)) },
supportingContent = { Text(httpVersion.label) },
Expand Down
Loading
Loading