Skip to content

Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.

feat: implement VpnService as a local kill-switch firewall in Tier 3 and expand Tier 4 capabilities

Durganshu Mishra5b7d78c198d8
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index dbfe455..55480ad 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -103,6 +103,17 @@
</intent-filter>
</service>
+ <!-- Tier 3: VpnService — local kill-switch firewall (blocks all traffic; user consents once). -->
+ <service
+ android:name=".service.GotchaVpnService"
+ android:exported="false"
+ android:label="@string/app_name"
+ android:permission="android.permission.BIND_VPN_SERVICE">
+ <intent-filter>
+ <action android:name="android.net.VpnService" />
+ </intent-filter>
+ </service>
+
<!-- Tier 3: Device Admin — lock screen, password policy, disable camera. -->
<receiver
android:name=".service.GotchaDeviceAdminReceiver"
diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.kt
index d106727..1edc071 100644
--- a/app/src/main/java/com/gotcha/MainActivity.kt
+++ b/app/src/main/java/com/gotcha/MainActivity.kt
@@ -3,6 +3,7 @@ package com.gotcha
import android.app.admin.DevicePolicyManager
import android.content.Intent
import android.net.Uri
+import android.net.VpnService
import android.os.Build
import android.os.Bundle
import android.provider.Settings as AndroidSettings
@@ -101,6 +102,14 @@ class MainActivity : ComponentActivity() {
"password policy, and disable the camera when you ask it to."
)
)
+ ToolResult.VPN_CONSENT -> VpnService.prepare(this@MainActivity)?.let {
+ // Non-null means consent is still needed; launch the system dialog.
+ startActivity(it)
+ } ?: Toast.makeText(
+ this@MainActivity,
+ "VPN already authorized — ask the assistant again.",
+ Toast.LENGTH_SHORT
+ ).show()
else -> permissionLauncher.launch(permission)
}
}
diff --git a/app/src/main/java/com/gotcha/service/GotchaVpnService.kt b/app/src/main/java/com/gotcha/service/GotchaVpnService.kt
new file mode 100644
index 0000000..0800466
--- /dev/null
+++ b/app/src/main/java/com/gotcha/service/GotchaVpnService.kt
@@ -0,0 +1,117 @@
+package com.gotcha.service
+
+import android.content.Intent
+import android.net.VpnService
+import android.os.ParcelFileDescriptor
+import java.io.FileInputStream
+
+/**
+ * Tier 3 — VpnService.
+ *
+ * A **local kill-switch firewall**: it establishes a tun interface that routes *all*
+ * device traffic into this app and then discards every packet, so nothing reaches the
+ * network. There is no remote server and no packet inspection — traffic is simply
+ * black-holed while the tunnel is up, which is the classic no-server VpnService use
+ * (an on-device "block all internet" switch).
+ *
+ * Unlike the other Tier 3 components, the enable step is gated by the system VPN consent
+ * dialog rather than a Settings toggle: [android.net.VpnService.prepare] returns a consent
+ * Intent the UI must launch once. After the user consents, [VpnTool] starts this service.
+ *
+ * The service exposes a static [isRunning] flag so the stateless [com.gotcha.tools.VpnTool]
+ * can report status without holding a binding.
+ */
+class GotchaVpnService : VpnService() {
+
+ private var vpnInterface: ParcelFileDescriptor? = null
+ private var worker: Thread? = null
+
+ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
+ return when (intent?.action) {
+ ACTION_STOP -> {
+ teardown()
+ stopSelf()
+ START_NOT_STICKY
+ }
+ else -> {
+ establish()
+ START_STICKY
+ }
+ }
+ }
+
+ /** Bring up the tun interface routing everything into this app (then drop it). */
+ private fun establish() {
+ if (vpnInterface != null) return
+ val builder = Builder()
+ .setSession("Gotcha Firewall")
+ .addAddress("10.0.0.2", 32)
+ .addRoute("0.0.0.0", 0)
+ // Also swallow IPv6 where the device supports it, so v6 traffic can't leak past
+ // the block. Guarded because some devices reject an IPv6 config outright.
+ try {
+ builder.addAddress("fd00::2", 128).addRoute("::", 0)
+ } catch (_: Exception) {
+ // IPv6 not available; IPv4 block still applies.
+ }
+
+ vpnInterface = try {
+ builder.establish()
+ } catch (_: Exception) {
+ null
+ }
+ isRunning = vpnInterface != null
+
+ // Drain and discard packets so the tun buffer doesn't back up. Reading blocks
+ // until a packet arrives; we never write anything back, so nothing is forwarded.
+ vpnInterface?.let { pfd ->
+ worker = Thread {
+ val input = FileInputStream(pfd.fileDescriptor)
+ val buffer = ByteArray(MAX_PACKET)
+ try {
+ while (!Thread.interrupted()) {
+ if (input.read(buffer) < 0) break
+ }
+ } catch (_: Exception) {
+ // Interface closed on teardown; exit the loop.
+ }
+ }.apply { isDaemon = true; start() }
+ }
+ }
+
+ private fun teardown() {
+ worker?.interrupt()
+ worker = null
+ try {
+ vpnInterface?.close()
+ } catch (_: Exception) {
+ // Already closed.
+ }
+ vpnInterface = null
+ isRunning = false
+ }
+
+ /** The user revoked the VPN from system settings / another VPN took over. */
+ override fun onRevoke() {
+ teardown()
+ stopSelf()
+ super.onRevoke()
+ }
+
+ override fun onDestroy() {
+ teardown()
+ super.onDestroy()
+ }
+
+ companion object {
+ const val ACTION_START = "com.gotcha.vpn.START"
+ const val ACTION_STOP = "com.gotcha.vpn.STOP"
+
+ private const val MAX_PACKET = 32_767
+
+ /** True while the blocking tunnel is established; false otherwise. */
+ @Volatile
+ var isRunning: Boolean = false
+ private set
+ }
+}
diff --git a/app/src/main/java/com/gotcha/tools/RootTool.kt b/app/src/main/java/com/gotcha/tools/RootTool.kt
new file mode 100644
index 0000000..fe02972
--- /dev/null
+++ b/app/src/main/java/com/gotcha/tools/RootTool.kt
@@ -0,0 +1,137 @@
+package com.gotcha.tools
+
+import java.util.concurrent.TimeUnit
+
+/**
+ * Tier 4 — privileged execution via a root shell (`su`).
+ *
+ * Everything here runs `su -c <command>`, so it only works on a rooted device (Magisk et al.).
+ * When no `su` binary is present, [ProcessBuilder] throws and the tool returns a plain error
+ * explaining the device is not rooted — there is no Settings screen to hand the user to, so
+ * (unlike the Tier 2/3 special-access tools) it does **not** emit a permission marker.
+ *
+ * A root shell subsumes the remaining Tier 4 wishes that a normal app can't reach:
+ * `WRITE_SECURE_SETTINGS` (`settings put secure …`, exposed as [writeSecureSetting]), silent
+ * install (`pm install`), reading other apps' data, etc. — all via [runRootCommand].
+ *
+ * These commands are marked sensitive (they pass through the confirmation dialog). A small
+ * deny-list still blocks the few irreversible, device-bricking operations, mirroring the
+ * project's stance of never exposing outright device destruction (cf. Device-Admin wipe).
+ */
+class RootTool(
+ private val timeoutSeconds: Long = 20,
+ private val maxOutputBytes: Int = 32 * 1024
+) {
+
+ /** Irreversible, device-destroying operations we refuse even with root. */
+ private val denyPatterns = listOf(
+ Regex("""\bmkfs\b"""), // reformat a filesystem
+ Regex("""\bdd\b[^\n]*\bof=/dev/"""), // raw write to a block device
+ Regex("""\brm\s+-[a-z]*r[a-z]*f?\s+/(\s|$)"""), // rm -rf / (wipe the root tree)
+ Regex("""\bfastboot\b"""),
+ Regex("""\brecovery\b[^\n]*--wipe""")
+ )
+
+ /** Probe whether a working root shell is available. Read-only. */
+ fun checkRoot(): ToolResult {
+ val result = exec("id")
+ return when {
+ result == null ->
+ ToolResult.ok("Root is NOT available — this device has no `su` binary (it isn't rooted).")
+ result.exit == 0 && result.output.contains("uid=0") ->
+ ToolResult.ok("Root IS available — `su` granted a root shell (${result.output.trim().take(120)}).")
+ else ->
+ ToolResult.ok(
+ "Root appears unavailable — `su` did not return a root uid " +
+ "(exit ${result.exit}: ${result.output.trim().take(120)})."
+ )
+ }
+ }
+
+ /** Run an arbitrary command as root and return stdout/stderr/exit code. */
+ fun runRootCommand(command: String): ToolResult {
+ val trimmed = command.trim()
+ if (trimmed.isEmpty()) return ToolResult.error("Empty command.")
+ denyPatterns.firstOrNull { it.containsMatchIn(trimmed) }?.let {
+ return ToolResult.error(
+ "Command blocked by safety policy (irreversible/device-destroying): $trimmed"
+ )
+ }
+ val result = exec(trimmed) ?: return notRooted()
+ val message = buildString {
+ append("exit code: ${result.exit}")
+ if (result.output.isNotEmpty()) append("\noutput:\n${result.output}") else append("\n(no output)")
+ }
+ return ToolResult(success = result.exit == 0, message = message)
+ }
+
+ /**
+ * Write a secure/system/global setting via `settings put` — the `WRITE_SECURE_SETTINGS`
+ * capability an ordinary app can't hold. Needs root.
+ */
+ fun writeSecureSetting(namespace: String, key: String, value: String): ToolResult {
+ val ns = namespace.trim().lowercase()
+ if (ns !in setOf("system", "secure", "global")) {
+ return ToolResult.error("namespace must be one of: system, secure, global (got '$namespace').")
+ }
+ if (key.isBlank()) return ToolResult.error("Provide the setting key to write.")
+ // Guard against argument injection through the key/value.
+ if (unsafeArg(key) || unsafeArg(value)) {
+ return ToolResult.error("The key/value contain shell metacharacters that aren't allowed here.")
+ }
+ val result = exec("settings put $ns $key $value") ?: return notRooted()
+ return if (result.exit == 0) {
+ ToolResult.ok("Set $ns setting '$key' to '$value'.")
+ } else {
+ ToolResult.error("Failed to set $ns/$key (exit ${result.exit}): ${result.output.trim()}")
+ }
+ }
+
+ private fun unsafeArg(s: String): Boolean =
+ s.any { it in "\n\r;&|`$()<>\"'\\ " }
+
+ private fun notRooted() = ToolResult.error(
+ "This action needs root, but no `su` binary is available — the device isn't rooted, so I can't do it."
+ )
+
+ private data class ExecResult(val exit: Int, val output: String)
+
+ /** Execute [command] via `su -c`; returns null when the device has no `su` binary. */
+ private fun exec(command: String): ExecResult? {
+ return try {
+ val process = ProcessBuilder("su", "-c", command)
+ .redirectErrorStream(true)
+ .start()
+
+ val reader = process.inputStream.bufferedReader()
+ val builder = StringBuilder()
+ val pump = Thread {
+ val buf = CharArray(4096)
+ try {
+ while (true) {
+ val n = reader.read(buf, 0, buf.size)
+ if (n < 0) break
+ if (builder.length < maxOutputBytes) {
+ builder.append(buf, 0, minOf(n, maxOutputBytes - builder.length))
+ if (builder.length >= maxOutputBytes) builder.append("\n…(output capped)")
+ }
+ }
+ } catch (_: Exception) {
+ // Stream closed on process death/timeout.
+ }
+ }.apply { start() }
+
+ val finished = process.waitFor(timeoutSeconds, TimeUnit.SECONDS)
+ if (!finished) {
+ process.destroyForcibly()
+ pump.join(2000)
+ return ExecResult(-1, builder.toString().ifEmpty { "(timed out after ${timeoutSeconds}s)" })
+ }
+ pump.join(2000)
+ ExecResult(process.exitValue(), builder.toString())
+ } catch (_: Exception) {
+ // No `su` on PATH → IOException. Treat as "not rooted".
+ null
+ }
+ }
+}
diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
index b4d64a9..19e1b46 100644
--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
@@ -739,6 +739,85 @@ object ToolDefinitions {
}
)
+ // ---- Tier 3 addition: VpnService (local traffic firewall) ----
+
+ val setFirewall = tool(
+ "set_firewall",
+ "Enable or disable a local VPN that blocks ALL device network traffic — an on-device " +
+ "internet kill-switch. Nothing is inspected or sent anywhere; while it is on, every " +
+ "packet is dropped so no app can reach the network. Enabling needs a one-time system " +
+ "VPN consent the first time.",
+ schema {
+ putJsonObject("properties") {
+ putJsonObject("enabled") {
+ put("type", "boolean")
+ put("description", "true to block all network traffic, false to restore connectivity.")
+ }
+ }
+ putJsonArray("required") { add("enabled") }
+ }
+ )
+
+ val getFirewallStatus = tool(
+ "get_firewall_status",
+ "Report whether the local traffic-blocking VPN firewall is currently on or off.",
+ schema { putJsonObject("properties") {} }
+ )
+
+ // ---- Tier 4 additions (privileged / rooted execution) ----
+
+ val checkRoot = tool(
+ "check_root",
+ "Check whether this device is rooted (a working `su` shell is available). Use this before " +
+ "attempting run_root_command or write_secure_settings so you can tell the user if root is missing.",
+ schema { putJsonObject("properties") {} }
+ )
+
+ val runRootCommand = tool(
+ "run_root_command",
+ "Run a shell command as ROOT via `su` and return its output. Only works on a rooted device; " +
+ "on a normal phone this fails with a clear 'not rooted' message. This is the Tier 4 escape " +
+ "hatch for privileged operations an ordinary app can't do — e.g. silent `pm install`, reading " +
+ "other apps' data, `settings put secure …`. A few irreversible device-wiping commands are blocked.",
+ schema {
+ putJsonObject("properties") {
+ putJsonObject("command") {
+ put("type", "string")
+ put("description", "Shell command line to run as root, e.g. 'pm list packages -s'.")
+ }
+ }
+ putJsonArray("required") { add("command") }
+ }
+ )
+
+ val writeSecureSettings = tool(
+ "write_secure_settings",
+ "Write an Android setting in the system/secure/global namespace (the WRITE_SECURE_SETTINGS " +
+ "capability, e.g. Settings.Secure). Uses root under the hood, so it needs a rooted device. " +
+ "Example: namespace='secure', key='location_mode', value='3'.",
+ schema {
+ putJsonObject("properties") {
+ putJsonObject("namespace") {
+ put("type", "string")
+ put("description", "One of: system, secure, global.")
+ }
+ putJsonObject("key") {
+ put("type", "string")
+ put("description", "Setting key, e.g. 'location_mode'.")
+ }
+ putJsonObject("value") {
+ put("type", "string")
+ put("description", "Value to write.")
+ }
+ }
+ putJsonArray("required") {
+ add("namespace")
+ add("key")
+ add("value")
+ }
+ }
+ )
+
val all: List<ToolDefinition> = listOf(
dialNumber, getStorageInfo, getBatteryInfo, listFiles, readFile, writeFile,
clearAppCache, openApp, toggleDarkMode, setBrightness, toggleWifi,
@@ -753,6 +832,10 @@ object ToolDefinitions {
readScreen, tap, swipe, inputText, globalAction,
readNotifications, dismissNotifications, mediaControl,
showOverlay, hideOverlay,
- lockScreen, disableCamera, setPasswordPolicy
+ lockScreen, disableCamera, setPasswordPolicy,
+ // Tier 3 addition: VpnService firewall
+ setFirewall, getFirewallStatus,
+ // Tier 4 additions: privileged / rooted execution
+ checkRoot, runRootCommand, writeSecureSettings
)
}
diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
index 6930f1a..ef3084b 100644
--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
@@ -36,6 +36,9 @@ class ToolExecutor(context: Context) {
private val notificationTool = NotificationTool(appContext)
private val overlayTool = OverlayTool(appContext)
private val deviceAdminTool = DeviceAdminTool(appContext)
+ private val vpnTool = VpnTool(appContext)
+ // Tier 4 tools
+ private val rootTool = RootTool()
private val actionLog = ActionLog(appContext)
suspend fun execute(name: String, args: JsonObject): ToolResult {
@@ -153,6 +156,18 @@ class ToolExecutor(context: Context) {
"set_password_policy" -> deviceAdminTool.setPasswordPolicy(
args.requireInt("min_length") ?: return missing("min_length")
)
+ "set_firewall" -> vpnTool.setFirewall(
+ args["enabled"]?.jsonPrimitive?.booleanOrNull ?: return missing("enabled")
+ )
+ "get_firewall_status" -> vpnTool.getFirewallStatus()
+ // ---- Tier 4 ----
+ "check_root" -> rootTool.checkRoot()
+ "run_root_command" -> rootTool.runRootCommand(args.requireString("command") ?: return missing("command"))
+ "write_secure_settings" -> rootTool.writeSecureSetting(
+ namespace = args.requireString("namespace") ?: return missing("namespace"),
+ key = args.requireString("key") ?: return missing("key"),
+ value = args.requireString("value") ?: return missing("value")
+ )
else -> ToolResult.error("Tool '$name' has no executor.")
}
}
diff --git a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt b/app/src/main/java/com/gotcha/tools/ToolRegistry.kt
index 10c07c8..470f3c1 100644
--- a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolRegistry.kt
@@ -27,7 +27,11 @@ object ToolRegistry {
"read_screen", "tap", "swipe", "input_text", "global_action",
"read_notifications", "dismiss_notifications", "media_control",
"show_overlay", "hide_overlay",
- "lock_screen", "disable_camera", "set_password_policy"
+ "lock_screen", "disable_camera", "set_password_policy",
+ // Tier 3: VpnService — enabling cuts all device connectivity.
+ "set_firewall",
+ // Tier 4: privileged root execution.
+ "run_root_command", "write_secure_settings"
)
fun allDefinitions(): List<ToolDefinition> = definitions.values.toList()
diff --git a/app/src/main/java/com/gotcha/tools/ToolResult.kt b/app/src/main/java/com/gotcha/tools/ToolResult.kt
index 59d61f6..388e806 100644
--- a/app/src/main/java/com/gotcha/tools/ToolResult.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolResult.kt
@@ -39,6 +39,9 @@ data class ToolResult(
/** Marker for activating the Device Admin component. */
const val DEVICE_ADMIN = "special:device_admin"
+ /** Marker for the one-time system VPN consent dialog (VpnService). */
+ const val VPN_CONSENT = "special:vpn_consent"
+
fun ok(message: String) = ToolResult(true, message)
fun error(message: String) = ToolResult(false, message)
fun permissionNeeded(permission: String, message: String) =
diff --git a/app/src/main/java/com/gotcha/tools/VpnTool.kt b/app/src/main/java/com/gotcha/tools/VpnTool.kt
new file mode 100644
index 0000000..4f412eb
--- /dev/null
+++ b/app/src/main/java/com/gotcha/tools/VpnTool.kt
@@ -0,0 +1,54 @@
+package com.gotcha.tools
+
+import android.content.Context
+import android.content.Intent
+import android.net.VpnService
+import com.gotcha.service.GotchaVpnService
+
+/**
+ * Tier 3 — controls the [GotchaVpnService] local kill-switch firewall.
+ *
+ * Enabling needs the one-time system VPN consent: [VpnService.prepare] returns a consent
+ * Intent when the user has not authorized a VPN for this app. In that case the tool returns
+ * the [ToolResult.VPN_CONSENT] marker so `MainActivity` can launch the consent dialog, matching
+ * the "grant, then ask again" flow used by the other special-access tools. Once consent is on
+ * record, `prepare` returns null and the tool starts/stops the service.
+ */
+class VpnTool(private val context: Context) {
+
+ /** Turn the traffic-blocking VPN on ([enabled] = true) or off (false). */
+ fun setFirewall(enabled: Boolean): ToolResult {
+ if (!enabled) {
+ if (!GotchaVpnService.isRunning) return ToolResult.ok("The network firewall is already off.")
+ context.startService(stopIntent())
+ return ToolResult.ok("Network firewall disabled — traffic can flow normally again.")
+ }
+
+ // Enabling: check we hold VPN consent first.
+ val consent = VpnService.prepare(context)
+ if (consent != null) {
+ return ToolResult.permissionNeeded(
+ ToolResult.VPN_CONSENT,
+ "Blocking network traffic needs your one-time VPN permission. I have opened the " +
+ "system consent dialog — please allow it for Gotcha and ask again."
+ )
+ }
+ context.startService(startIntent())
+ return ToolResult.ok(
+ "Network firewall enabled — a local VPN is now blocking ALL device network traffic " +
+ "(nothing is inspected or sent anywhere). Ask me to disable it to restore connectivity."
+ )
+ }
+
+ /** Report whether the blocking VPN is currently up. */
+ fun getFirewallStatus(): ToolResult = ToolResult.ok(
+ if (GotchaVpnService.isRunning) "The network firewall is ON — all traffic is blocked."
+ else "The network firewall is OFF — traffic flows normally."
+ )
+
+ private fun startIntent() =
+ Intent(context, GotchaVpnService::class.java).setAction(GotchaVpnService.ACTION_START)
+
+ private fun stopIntent() =
+ Intent(context, GotchaVpnService::class.java).setAction(GotchaVpnService.ACTION_STOP)
+}