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
36 changes: 36 additions & 0 deletions app/src/main/java/dev/r1ptt/sys/DeviceLock.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package dev.r1ptt.sys

import android.app.KeyguardManager
import android.app.admin.DeviceAdminInfo
import android.app.admin.DevicePolicyManager
import android.content.ComponentName
import android.content.Context

/**
* Locks Android at once, for lost mode. Device admin's lockNow() where Android supports device
* admin; otherwise Android's lockdown through root, the power menu's "Lockdown", which locks at
* once and requires the screen lock. Many R1 builds have no device-admin support at all. Either
* way it only means something with an Android screen lock.
*/
class DeviceLock(
ctx: Context,
private val rootAvailable: () -> Boolean = { Root.verified },
private val root: (String, Long) -> Int = Root::run,
) {
private val dpm = ctx.getSystemService(DevicePolicyManager::class.java)
private val keyguard = ctx.getSystemService(KeyguardManager::class.java)
private val admin = ComponentName(ctx, AdminReceiver::class.java)

private fun viaAdmin() = dpm.isAdminActive(admin) && dpm.hasGrantedPolicy(admin, DeviceAdminInfo.USES_POLICY_FORCE_LOCK)

/** A lock request would actually lock: an Android screen lock, plus device admin or root. */
fun available(): Boolean = keyguard.isDeviceSecure && (viaAdmin() || rootAvailable())

/** Locking goes through root, which can block: call [lockNow] off the main thread then. */
fun usesRoot(): Boolean = !viaAdmin()

/** Blocks on root, so call it off the main thread. */
fun lockNow(): Boolean =
if (viaAdmin()) runCatching { dpm.lockNow() }.isSuccess
else root("cmd lock_settings require-strong-auth STRONG_AUTH_REQUIRED_AFTER_USER_LOCKDOWN && input keyevent 223", 8_000) == 0
}
5 changes: 5 additions & 0 deletions app/src/main/java/dev/r1ptt/sys/Root.kt
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ object Root {
private const val TAG = "r1ptt"
private val pool = Executors.newCachedThreadPool()

/** A root command has succeeded in this process, so root is granted. */
@Volatile var verified = false
private set

/** Runs [cmd] under `su -c`; returns its exit code, or -1 on timeout or failure. */
fun run(cmd: String, timeoutMs: Long = 4000): Int = exec(cmd, timeoutMs, collect = false).first

Expand Down Expand Up @@ -60,6 +64,7 @@ object Root {
return -1 to null
}
drainer.join(500)
if (p.exitValue() == 0) verified = true
return p.exitValue() to out?.toString(Charsets.UTF_8.name())
} catch (e: Throwable) {
Log.w(TAG, "su failed: $cmd", e)
Expand Down
6 changes: 6 additions & 0 deletions app/src/main/java/dev/r1ptt/ui/DeviceActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,10 @@ open class DeviceActivity : Activity() {
val content = findViewById<View>(android.R.id.content) ?: return
val blocked = recoveryBlocksScreen()
noteGate(blocked)
// A lost R1 locks Android too. Its page, with the owner's return message, shows over the lock
// screen; robotOS's content stays hidden behind the cover. Changed only when it changes,
// because this runs on every layout pass.
if (showsOverLock != hub.quarantined) { showsOverLock = hub.quarantined; setShowWhenLocked(hub.quarantined) }
if (!blocked) { liftGate(content); return }
// This runs on every layout pass. Hiding content is idempotent; window flags and keyboard
// requests are not (each one relayouts and calls back here), so they run only when the
Expand Down Expand Up @@ -207,6 +211,8 @@ open class DeviceActivity : Activity() {
if (requestCode == OWNER_PIN && resultCode == RESULT_OK) recoveryApp?.workspace?.confirmedByOwner()
}

private var showsOverLock = false

private fun liftGate(content: View) {
val root = gate
if (root == null) {
Expand Down
21 changes: 16 additions & 5 deletions app/src/main/java/dev/r1ptt/workspace/HubManagement.kt
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ class HubManagement(private val app: App, private val hub: WorkspaceClient) {
private fun management() = permissions.allowed("remote_management")
private fun locationAllowed() = permissions.allowed("location_reporting") && app.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
app.checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION) == PackageManager.PERMISSION_GRANTED
private fun secureLock() = app.getSystemService(KeyguardManager::class.java).isDeviceSecure && policies.isAdminActive(admin) && policies.hasGrantedPolicy(admin, DeviceAdminInfo.USES_POLICY_FORCE_LOCK)
internal var deviceLock = dev.r1ptt.sys.DeviceLock(app)
private fun secureLock() = deviceLock.available()
fun capabilities(): JSONObject = JSONObject().apply {
put("ring", management()); put("stop_ring", management()); put("show_message", management())
put("lock", management() && permissions.allowed("secure_lock") && secureLock())
Expand Down Expand Up @@ -64,8 +65,16 @@ class HubManagement(private val app: App, private val hub: WorkspaceClient) {
if (state.optBoolean("secure_lock_applied")) hub.identity.update { it.put("secure_lock_applied", false) }
} else if (!state.optBoolean("secure_lock_applied")) {
// Persist evidence only after Android accepts the request. Never invent a credential.
if (runCatching { policies.lockNow() }.isSuccess)
hub.identity.update { it.put("secure_lock_applied", true) }
fun lock() = runCatching { deviceLock.lockNow() }.getOrDefault(false).also { locked ->
if (locked) {
hub.identity.update { it.put("secure_lock_applied", true) }
dev.r1ptt.data.EventLog.record("lost mode: Android locked")
}
}
// Device admin locks at once; root can block, so it locks off the main thread.
if (deviceLock.usesRoot()) kotlin.concurrent.thread(name = "lost-lock") {
if (lock()) main.post { dev.r1ptt.ui.DeviceActivity.refreshRecovery(app) }
} else lock()
}
dev.r1ptt.ui.DeviceActivity.refreshRecovery(app)
}
Expand Down Expand Up @@ -184,8 +193,10 @@ class HubManagement(private val app: App, private val hub: WorkspaceClient) {
hub.identity.update { it.put("return_message", text) }; app.notices.add(text)
finish("applied", "Return information saved for display")
}
"lock" -> withContext(Dispatchers.Main) {
check(secureLock()); policies.lockNow(); hub.identity.update { it.put("secure_lock_applied", true) }
"lock" -> {
check(secureLock()); check(deviceLock.lockNow()) { "Android did not lock" }
hub.identity.update { it.put("secure_lock_applied", true) }
dev.r1ptt.data.EventLog.record("remote lock: Android locked")
finish("applied", "Android secure lock requested")
}
"locate" -> {
Expand Down
5 changes: 3 additions & 2 deletions app/src/main/java/dev/r1ptt/workspace/HubSettingsActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,9 @@ class HubSettingsActivity : DeviceActivity() {
permission("secure_lock", "Allow secure remote lock", "With your permission, lost or revoked status automatically requests Android secure lock whenever an Android screen lock and active device admin are available. Enabling Android security later automatically strengthens recovery protection. Without them robotOS restricts its own screens and actions; other Android apps remain accessible.")
val security = hub.management.security()
body.addView(ui.note(if (security.optBoolean("secure_lock_available")) "Protection: robotOS restriction and Android secure lock."
else "Protection: robotOS restriction. Android secure lock requires the permission above, remote management, an Android screen lock (PIN, pattern or password) and device admin."))
body.addView(ui.button("Enable Android device admin") {
else "Protection: robotOS restriction. Android secure lock requires the permission above, remote management, an Android screen lock (PIN, pattern or password), and device admin or root."))
// Many R1 builds have no device admin; robotOS then locks through Android's lockdown with root.
if (packageManager.hasSystemFeature(android.content.pm.PackageManager.FEATURE_DEVICE_ADMIN)) body.addView(ui.button("Enable Android device admin") {
startActivity(Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN).putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
android.content.ComponentName(this, dev.r1ptt.sys.AdminReceiver::class.java)))
})
Expand Down
37 changes: 37 additions & 0 deletions app/src/test/java/dev/r1ptt/sys/DeviceLockTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package dev.r1ptt.sys

import android.app.KeyguardManager
import dev.r1ptt.App
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config

@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], application = App::class)
class DeviceLockTest {
private val app get() = RuntimeEnvironment.getApplication() as App

/** Many R1 builds have no device admin; root's lockdown locks at once and requires the screen lock. */
@Test fun withoutDeviceAdminRootLocksThroughLockdown() {
val commands = mutableListOf<String>()
val lock = DeviceLock(app, rootAvailable = { true }, root = { cmd, _ -> commands += cmd; 0 })
assertFalse(lock.available()) // No Android screen lock: locking would protect nothing.
shadowOf(app.getSystemService(KeyguardManager::class.java)).setIsDeviceSecure(true)
assertTrue(lock.available())
assertTrue(lock.usesRoot())
assertTrue(lock.lockNow())
assertTrue(commands.single().contains("require-strong-auth STRONG_AUTH_REQUIRED_AFTER_USER_LOCKDOWN"))
assertTrue(commands.single().contains("input keyevent 223"))
}

@Test fun withNeitherAdminNorRootThereIsNoRemoteLock() {
shadowOf(app.getSystemService(KeyguardManager::class.java)).setIsDeviceSecure(true)
val lock = DeviceLock(app, rootAvailable = { false }, root = { _, _ -> -1 })
assertFalse(lock.available())
assertFalse(lock.lockNow())
}
}
21 changes: 21 additions & 0 deletions app/src/test/java/dev/r1ptt/workspace/RecoveryProtectionTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,21 @@ class RecoveryProtectionTest {
app.workspace.management.refreshProtection()
assertFalse(app.workspace.management.security().getBoolean("secure_lock_applied"))
}
/** On an R1 whose Android has no device admin, lost mode locks Android through root's lockdown. */
@Test fun aLostR1LocksAndroidThroughRootWithoutDeviceAdmin() {
enrolled()
shadowOf(app.getSystemService(KeyguardManager::class.java)).setIsDeviceSecure(true)
val commands = CopyOnWriteArrayList<String>()
app.workspace.management.deviceLock = dev.r1ptt.sys.DeviceLock(app, rootAvailable = { true }, root = { cmd, _ -> commands += cmd; 0 })
app.workspace.identity.permission("secure_lock", true)
assertTrue(app.workspace.management.security().getBoolean("secure_lock_available"))
app.workspace.identity.update { it.put("lost", true) }
app.workspace.management.refreshProtection()
val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(3)
while (!app.workspace.identity.value.optBoolean("secure_lock_applied") && System.nanoTime() < until) Thread.sleep(5)
assertTrue(app.workspace.management.security().getBoolean("secure_lock_applied"))
assertEquals(1, commands.count { it.contains("STRONG_AUTH_REQUIRED_AFTER_USER_LOCKDOWN") })
}
@Test fun clearingWorkspaceDoesNotPermitReEnrollmentWhileLostOrWithoutFreshRecovery() {
enrolled()
app.workspace.identity.update { it.put("local_workspace_cleared", true) }
Expand Down Expand Up @@ -602,6 +617,12 @@ class RecoveryProtectionTest {
shadowOf(Looper.getMainLooper()).idleFor(java.time.Duration.ofMillis(DeviceActivity.COVER_MS + 50))
assertEquals(View.GONE, logo.visibility)
assertTrue(activity.window.decorView.find(TextView::class.java).single { it.text == "Please return this R1" }.isShown)
// Lost mode locks Android too; the finder still sees the return message over the lock screen.
assertTrue(shadowOf(activity).showWhenLocked)
app.workspace.identity.update { it.put("lost", false) }
dev.r1ptt.ui.DeviceActivity.refreshRecovery(app)
shadowOf(Looper.getMainLooper()).idle()
assertFalse(shadowOf(activity).showWhenLocked)
controller.pause().stop().destroy()
}

Expand Down
8 changes: 4 additions & 4 deletions docs/HUB.md
Original file line number Diff line number Diff line change
Expand Up @@ -200,17 +200,17 @@ and factory reset must advertise their actual availability. Unsupported operatio
Location requires a working provider, precise location permission and Android's “Allow all the
time” background permission, granted on the R1. Enable system location if provisioning disabled
it. A fix includes its timestamp and
accuracy; a missing fix is not the device's current position. Secure lock requires a PIN/password
and active device-admin support. Factory reset requires supported device-owner enrollment and
accuracy; a missing fix is not the device's current position. Secure lock requires an Android screen lock
and either device admin or root, which uses Android's lockdown. Factory reset requires supported device-owner enrollment and
separate local authorization. Provisioning preserves the existing lock screen and device-admin
state; it does not create a credential or grant admin access. Older provisioning disabled the
keyguard, so configure and verify a secure credential locally before relying on remote locking.

Protection adapts to the security features actually enabled on the R1. Without a secure Android
credential, robotOS restricts its own screens and action entry points; this does not lock Android
or prevent access through other apps, debugging or a modified operating system. With a secure
credential, active device admin and locally enabled management, lost mode can also request an
Android lock. A secure credential is the recommended setup ([INSTALL.md](INSTALL.md#lock-it-with-a-screen-lock)):
credential, device admin or root, and locally enabled management, lost mode also locks Android at
once and shows the lost-device page, with the owner's return message, over the lock screen. A secure credential is the recommended setup ([INSTALL.md](INSTALL.md#lock-it-with-a-screen-lock)):
an Android PIN, pattern or password encrypts the R1's data and limits guessing, which robotOS's own
screens cannot do. While Android is locked the button only wakes the lock screen. When the host
can't confirm a wake, the recovery screen can open robotOS with Android's own confirmation of the
Expand Down
12 changes: 8 additions & 4 deletions docs/INSTALL.md
Original file line number Diff line number Diff line change
Expand Up @@ -204,12 +204,16 @@ mode or other Android screens.
- **Power button instantly locks:** off. The R1's button is its power button, and robotOS's
tap-to-sleep counts as a press, so leaving this on locks the R1 on every tap.
3. Back in **Host & devices**, turn on **Allow remote management** and **Allow secure remote
lock**, then tap **Enable Android device admin** and choose **Activate**. Marking the R1 lost on
your host then locks Android too. robotOS uses device admin only to lock the screen; you can turn
it off in Android's **Settings → Security → Device admin apps**.
lock**. Marking the R1 lost on your host then locks Android too, at once, and the lost-device
page with your return message shows on top of the lock screen. Most R1 builds have no Android
device-admin support, so robotOS locks through Android's lockdown (the power menu's "Lockdown")
using root. If your build does support device admin, an **Enable Android device admin** button
appears; tap it and choose **Activate**. robotOS uses it only to lock the screen, and you can
turn it off in Android's **Settings → Security → Device admin apps**.

**Check it worked:** **Host & devices** shows "Protection: robotOS restriction and Android secure
lock". If it shows only "robotOS restriction", one of the three steps is missing.
lock". If it shows only "robotOS restriction", one of the three steps is missing, or robotOS
hasn't confirmed root yet (it does on its next start).

What changes:
- Android's lock screen shows robotOS's glowing mark on black, like the recovery cover, so swiping
Expand Down
23 changes: 23 additions & 0 deletions docs/releases/v0.6.9.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
Marking an R1 lost now locks Android even on R1s whose Android has no device-admin support, which
is most of them.

- **Lockdown through root.** Where device admin isn't available, robotOS locks with Android's own
lockdown, the power menu's "Lockdown": the R1 locks at once and needs its screen lock. Device
admin is still used where Android supports it. Either way, Android's screen lock must be set.
- **The return message stays visible.** A lost R1's page, with your return message and **Stop
ringing**, now shows on top of Android's lock screen, so whoever finds it can still read how to
return it. robotOS's own content stays hidden behind the cover.
- **No dead button.** On builds without device admin, **Host & devices** no longer offers "Enable
Android device admin". On those builds Android accepts the request and silently ignores it, so
the button did nothing.

App update only. The hub and Hermes tools are unchanged.

Automated tests cover the following:
- lockdown through root when device admin is missing;
- no remote lock without a screen lock, or without both device admin and root;
- lost mode locking through root;
- the lost page showing over the lock screen, and stopping once the R1 is restored.

On a physical R1 with a pattern lock, the lockdown command locked Android at once and required the
pattern.
Loading