Improve VPN video routing, profile storage and authorization reuse

This commit is contained in:
shen
2026-10-13 00:34:16 -07:00
parent c94143dfae
commit f94dab0555
30 changed files with 1303 additions and 139 deletions
@@ -53,4 +53,7 @@ flutter {
}
// Offline QR decoding and an in-app camera capture Activity.
dependencies { implementation("com.journeyapps:zxing-android-embedded:4.3.0") }
dependencies {
implementation("com.journeyapps:zxing-android-embedded:4.3.0")
testImplementation("junit:junit:4.13.2")
}
@@ -0,0 +1,83 @@
package com.example.meshport_lab
import java.io.File
import java.nio.ByteBuffer
import java.nio.channels.FileChannel
import java.nio.charset.CodingErrorAction
import java.nio.file.Files
import java.nio.file.LinkOption.NOFOLLOW_LINKS
import java.nio.file.StandardCopyOption
import java.nio.file.StandardOpenOption
import java.nio.file.attribute.PosixFilePermissions
/** App-private local profiles. Legacy access is used once and never on save. */
class LocalProfileFiles(val root: File, private val namespace: String, private val legacyRead: () -> String?) {
init { require(namespace == "proxy" || namespace == "profile") }
private val name = if (namespace == "proxy") "proxy-profile.json" else "network-profile.toml"
private val file get() = File(root, name).toPath()
private val done get() = File(root, ".$name.migrated").toPath()
private val pending get() = File(root, ".$name.migration-pending").toPath()
private fun exists(path: java.nio.file.Path) = Files.exists(path, NOFOLLOW_LINKS)
private fun prepare() {
val path = root.toPath()
if (!exists(path)) Files.createDirectories(path, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------")))
check(Files.isDirectory(path, NOFOLLOW_LINKS) && !Files.isSymbolicLink(path)) { "Invalid configuration directory" }
Files.setPosixFilePermissions(path, PosixFilePermissions.fromString("rwx------"))
}
private fun verify(path: java.nio.file.Path) {
check(Files.isRegularFile(path, NOFOLLOW_LINKS) && !Files.isSymbolicLink(path)) { "Invalid configuration file" }
Files.setPosixFilePermissions(path, PosixFilePermissions.fromString("rw-------"))
}
private fun write(data: ByteArray, target: java.nio.file.Path) {
prepare()
if (exists(target)) verify(target)
val temp = Files.createTempFile(root.toPath(), ".profile-", ".tmp",
PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------")))
try {
FileChannel.open(temp, StandardOpenOption.WRITE).use { channel ->
val buffer = ByteBuffer.wrap(data)
while (buffer.hasRemaining()) channel.write(buffer)
channel.force(true)
}
Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING)
} finally { Files.deleteIfExists(temp) }
}
private fun finish() {
write(byteArrayOf(), done)
if (exists(pending)) { verify(pending); Files.delete(pending) }
}
fun save(text: String) {
val data = text.toByteArray(Charsets.UTF_8)
require(data.size <= 65536) { "Configuration exceeds storage limit" }
write(data, file)
finish()
}
fun load(): String? {
prepare()
if (exists(file)) {
verify(file)
check(Files.size(file) <= 65536) { "Configuration exceeds storage limit" }
return Charsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT).decode(ByteBuffer.wrap(Files.readAllBytes(file))).toString()
}
if (exists(done) || exists(pending)) return null
return try {
val text = legacyRead()
if (text == null) finish() else save(text)
text
} catch (_: Exception) { write(byteArrayOf(), pending); null }
}
fun migrationPending(): Boolean { prepare(); return exists(pending) }
fun migratePending() {
prepare()
if (!exists(pending)) return
if (exists(file)) { verify(file); finish(); return }
val text = legacyRead()
if (text == null) finish() else save(text)
}
fun delete() {
prepare()
if (exists(file)) { verify(file); Files.delete(file) }
finish() // Do not resurrect a deleted local profile from legacy storage.
}
}
@@ -76,6 +76,15 @@ class MainActivity : FlutterActivity() {
try {
val profiles = ProfileStore(this)
when (call.method) {
"profile_storage_status" -> {
val pending = profiles.migrationPending() || ProfileStore(this,"proxy").migrationPending()
main.post { result.success(mapOf("path" to profiles.directory, "migration_pending" to pending)) }
}
"migrate_profiles" -> {
ProfileStore(this,"proxy").migratePending()
profiles.migratePending()
main.post { result.success(null) }
}
"debug_os_echo" -> {
check(BuildConfig.DEBUG)
val host = "10.253.79.1"
@@ -1,40 +1,30 @@
package com.example.meshport_lab
import android.content.Context
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.util.Base64
import java.io.File
import java.security.KeyStore
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
class ProfileStore(context: Context, namespace: String = "profile") {
private val prefs = context.getSharedPreferences("meshport_$namespace", Context.MODE_PRIVATE)
private val alias = "MeshPort.Network.$namespace"
private fun key(): SecretKey {
val store = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
(store.getKey(alias, null) as? SecretKey)?.let { return it }
return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore").apply {
init(KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM).setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE).build())
}.generateKey()
}
fun save(config: String) {
require(config.toByteArray(Charsets.UTF_8).size <= 65536)
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.ENCRYPT_MODE, key())
val data = cipher.doFinal(config.toByteArray(Charsets.UTF_8))
check(prefs.edit().putString("data", Base64.encodeToString(data, Base64.NO_WRAP))
.putString("iv", Base64.encodeToString(cipher.iv, Base64.NO_WRAP)).commit())
}
fun load(): String? {
private val local = LocalProfileFiles(File(context.filesDir, "MeshPort"), namespace, ::loadLegacy)
val directory: String get() = local.root.absolutePath
private fun loadLegacy(): String? {
val data = prefs.getString("data", null) ?: return null
val iv = prefs.getString("iv", null) ?: error("Missing profile IV")
val iv = prefs.getString("iv", null) ?: error("Missing legacy profile IV")
val store = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
val key = store.getKey(alias, null) as? SecretKey ?: error("Legacy profile key unavailable")
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.DECRYPT_MODE, key(), GCMParameterSpec(128, Base64.decode(iv, Base64.NO_WRAP)))
cipher.init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(128, Base64.decode(iv, Base64.NO_WRAP)))
return cipher.doFinal(Base64.decode(data, Base64.NO_WRAP)).toString(Charsets.UTF_8)
}
fun delete() { check(prefs.edit().clear().commit()) }
fun save(config: String) = local.save(config)
fun load(): String? = local.load()
fun delete() = local.delete()
fun migrationPending(): Boolean = local.migrationPending()
fun migratePending() = local.migratePending()
}
@@ -0,0 +1,68 @@
package com.example.meshport_lab
import org.junit.Test
import org.junit.After
import org.junit.Assert.*
import java.nio.file.Files
import java.nio.file.attribute.PosixFilePermissions
class LocalProfileFilesTest {
private val root = Files.createTempDirectory("meshport-profile-tests").toFile()
@After fun cleanup() { Files.walk(root.toPath()).use { it.sorted(Comparator.reverseOrder()).forEach(Files::deleteIfExists) } }
@Test fun migrationAndReadsUseLocalFilesWithPrivatePermissions() {
var legacyReads = 0
val dir = root.resolve("MeshPort")
val store = LocalProfileFiles(dir, "proxy") { legacyReads++; "{\"nodes\":[]}" }
assertEquals("{\"nodes\":[]}", store.load())
store.save("{\"nodes\":[\"fixture\"]}")
assertEquals("{\"nodes\":[\"fixture\"]}", store.load())
assertEquals(1, legacyReads)
assertEquals(PosixFilePermissions.fromString("rwx------"), Files.getPosixFilePermissions(dir.toPath()))
assertEquals(PosixFilePermissions.fromString("rw-------"), Files.getPosixFilePermissions(dir.resolve("proxy-profile.json").toPath()))
val reopened = LocalProfileFiles(dir, "proxy") { error("Unexpected legacy access") }
assertEquals(store.load(), reopened.load())
store.delete()
assertNull(store.load())
assertEquals(1, legacyReads)
}
@Test fun failedMigrationIsNotRepeatedAndCanBeRetriedExplicitly() {
var reads = 0
var available = false
val store = LocalProfileFiles(root.resolve("MeshPort"), "profile") {
reads++; check(available); "network_name = \"fixture\""
}
assertNull(store.load())
assertNull(store.load())
assertEquals(1, reads)
assertTrue(store.migrationPending())
available = true
store.migratePending()
assertEquals("network_name = \"fixture\"", store.load())
assertFalse(store.migrationPending())
assertEquals(2, reads)
}
@Test fun rejectedWriteAndCorruptFileDoNotOverwriteValidOrLegacyData() {
var reads = 0
val dir = root.resolve("MeshPort")
val store = LocalProfileFiles(dir, "proxy") { reads++; null }
store.save("valid")
assertThrows(IllegalArgumentException::class.java) { store.save("x".repeat(65537)) }
assertEquals("valid", store.load())
Files.write(dir.resolve("proxy-profile.json").toPath(), byteArrayOf(-1))
assertThrows(java.nio.charset.CharacterCodingException::class.java) { store.load() }
assertEquals(0, reads)
}
@Test fun symlinksCannotReadOrOverwriteOutsideFiles() {
val dir = root.resolve("MeshPort")
val store = LocalProfileFiles(dir, "proxy") { null }
store.save("initial")
val outside = root.resolve("outside").apply { writeText("unchanged") }
val profile = dir.resolve("proxy-profile.json").toPath()
Files.delete(profile)
Files.createSymbolicLink(profile, outside.toPath())
assertThrows(IllegalStateException::class.java) { store.load() }
assertThrows(IllegalStateException::class.java) { store.save("replacement") }
assertEquals("unchanged", outside.readText())
}
}