From 2feb35aa5ecee615c642bcd2e6dbb9e29c8291c1 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 3 Dec 2026 12:41:05 -0500 Subject: [PATCH] Attest the paired worker start time before its final GO --- app/build.gradle | 2 + app/src/main/cpp/waylandcomp/src/compositor.c | 58 ++++++++++--------- .../cpp/waylandcomp/src/frame_worker_peer.h | 42 ++++++++++++++ .../cpp/waylandcomp/src/waylandcomp_jni.c | 8 +-- .../runtime/FrameAcquireWorkerProbe.kt | 41 ++++++++++++- .../launcher/runtime/GuestWorkers.kt | 35 +++++++++-- .../launcher/wayland/WaylandCompositor.java | 2 +- .../runtime/FrameAcquireWorkerProbeTest.kt | 19 ++++++ tools/tests/frame_worker_peer_live_test.c | 11 ++-- tools/tests/frame_worker_peer_test.c | 20 +++++++ tools/tests/test_frame_acquire_peer_gate.py | 23 +++++--- 11 files changed, 209 insertions(+), 52 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index 254007b1cf..97aa390832 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -144,6 +144,8 @@ android { buildConfigField "String", "PR_TITLE", "\"${escapeJava(prTitle)}\"" buildConfigField "String", "BUILD_BRANCH", "\"${escapeJava(buildBranch)}\"" buildConfigField "boolean", "CI_BUILD", "${ciBuild}" + buildConfigField "boolean", "FRAME_ACQUIRE_WORKER_PROBE", + (project.findProperty('droiddeckFrameAcquireProbe') == 'true').toString() buildConfigField "String", "RELEASE_SIGNER", "\"${releaseSigner}\"" buildConfigField "long", "COMMIT_TIME", "${commitTime}L * 1000L" buildConfigField "String", "UPDATE_CATALOG_BRANCH", "\"${(System.getenv("DROIDDECK_UPDATE_CATALOG_BRANCH") ?: "main").with { it ==~ /[A-Za-z0-9._-]+/ ? it : "main" }}\"" diff --git a/app/src/main/cpp/waylandcomp/src/compositor.c b/app/src/main/cpp/waylandcomp/src/compositor.c index 1c9992f735..b1765b2730 100644 --- a/app/src/main/cpp/waylandcomp/src/compositor.c +++ b/app/src/main/cpp/waylandcomp/src/compositor.c @@ -1735,28 +1735,15 @@ static struct dd_worker_grant frame_worker_grant; static int frame_worker_pidfd = -1; static bool frame_worker_map_reported; -static uint64_t frame_worker_starttime(pid_t pid) { +static enum dd_worker_stat_result frame_worker_starttime(pid_t pid, uint64_t *out) { char proc[64], line[4096]; snprintf(proc, sizeof(proc), "/proc/%d/stat", pid); FILE *f = fopen(proc, "re"); - if (!f) return 0; - bool read = fgets(line, sizeof(line), f) != NULL; + if (!f) return dd_worker_open_failure(errno); + // Proc writes one bounded line; truncation is a read failure, not invisibility. + bool read = fgets(line, sizeof(line), f) != NULL && strchr(line, '\n') != NULL; fclose(f); - if (!read) return 0; - char *p = strrchr(line, ')'); - if (!p || p[1] != ' ') return 0; - p += 2; - // "state" is field 3, the kernel starttime is field 22. - for (int field = 3; field < 22; ++field) { - p = strchr(p, ' '); - if (!p) return 0; - while (*p == ' ') ++p; - } - char *end; - errno = 0; - if (*p < '0' || *p > '9') return 0; - uint64_t start = strtoull(p, &end, 10); - return !errno && end != p && *end == ' ' ? start : 0; + return read ? dd_worker_parse_start(line, out) : DD_WORKER_STAT_READ; } void droiddeck_frame_worker_revoke(int owner, int pid) { @@ -1771,9 +1758,9 @@ void droiddeck_frame_worker_revoke(int owner, int pid) { } int droiddeck_frame_worker_grant(int owner, pid_t pid, uint64_t expires, const char *path, - uint64_t expected_dev, uint64_t expected_ino) { + uint64_t expected_dev, uint64_t expected_ino, uint64_t receipt) { struct stat st; - if (owner <= 0 || pid <= 1 || !path || + if (owner <= 0 || pid <= 1 || !receipt || !path || strlen(path) >= sizeof(frame_worker_file) || lstat(path, &st) < 0 || !S_ISREG(st.st_mode) || (uint64_t)st.st_dev != expected_dev || (uint64_t)st.st_ino != expected_ino || st.st_uid != getuid()) { @@ -1785,9 +1772,23 @@ int droiddeck_frame_worker_grant(int owner, pid_t pid, uint64_t expires, const c droiddeck_log("probe", "worker_admission=NATIVE_PIDFD"); return 0; // No fallback to a recyclable PID. } - uint64_t start = frame_worker_starttime(pid); - if (!start) { - droiddeck_log("probe", "worker_admission=NATIVE_STARTTIME"); + struct pollfd alive = {.fd = pidfd, .events = POLLIN}; + uint64_t raw_start = 0; + enum dd_worker_stat_result stat = frame_worker_starttime(pid, &raw_start); + switch (stat) { + case DD_WORKER_STAT_OK: + if (raw_start != receipt) droiddeck_log("probe", "worker_admission=NATIVE_STAT_MISMATCH"); + break; + case DD_WORKER_STAT_DENIED: droiddeck_log("probe", "worker_admission=NATIVE_STAT_OPEN_DENIED"); break; + case DD_WORKER_STAT_HIDDEN: droiddeck_log("probe", "worker_admission=NATIVE_STAT_OPEN_HIDDEN"); break; + case DD_WORKER_STAT_OPEN: droiddeck_log("probe", "worker_admission=NATIVE_STAT_OPEN_OTHER"); break; + case DD_WORKER_STAT_READ: droiddeck_log("probe", "worker_admission=NATIVE_STAT_READ"); break; + case DD_WORKER_STAT_PARSE: droiddeck_log("probe", "worker_admission=NATIVE_STAT_PARSE"); break; + case DD_WORKER_STAT_ZERO: droiddeck_log("probe", "worker_admission=NATIVE_STAT_ZERO"); break; + } + if (!dd_worker_receipt_allows_reserve(stat, raw_start, receipt)) { close(pidfd); return 0; } + if (poll(&alive, 1, 0) != 0) { + droiddeck_log("probe", "worker_admission=NATIVE_PIDFD_NOT_LIVE"); close(pidfd); return 0; } @@ -1795,7 +1796,7 @@ int droiddeck_frame_worker_grant(int owner, pid_t pid, uint64_t expires, const c if (frame_worker_pidfd < 0) { strcpy(frame_worker_file, path); frame_worker_grant = (struct dd_worker_grant){ - .owner = owner, .uid = getuid(), .pid = pid, .start_ticks = start, .expires = expires, + .owner = owner, .uid = getuid(), .pid = pid, .start_ticks = receipt, .expires = expires, .dev_major = major(st.st_dev), .dev_minor = minor(st.st_dev), .ino = st.st_ino, .canonical_file = frame_worker_file, .app_launch_verified = true, .final_go = true, }; @@ -1816,7 +1817,9 @@ int droiddeck_frame_worker_grant(int owner, pid_t pid, uint64_t expires, const c static bool frame_worker_verified_exec_locked(const struct dd_worker_grant *g, uint64_t now) { char proc[64], line[PATH_MAX + 128]; const char *failure = "worker_admission=MAP_STARTTIME"; - if (frame_worker_starttime(g->pid) != g->start_ticks) goto reject; + uint64_t raw_start = 0; + if (frame_worker_starttime(g->pid, &raw_start) != DD_WORKER_STAT_OK || raw_start != g->start_ticks) + goto reject; snprintf(proc, sizeof(proc), "/proc/%u/maps", g->pid); FILE *f = fopen(proc, "re"); failure = "worker_admission=MAP_OPEN"; @@ -1827,7 +1830,7 @@ static bool frame_worker_verified_exec_locked(const struct dd_worker_grant *g, u size_t n = strlen(line); if (!n || line[n - 1] != '\n' || n > budget) break; budget -= n; - if (dd_worker_grant_matches(g, g->owner, g->uid, g->pid, g->start_ticks, now, line)) { + if (dd_worker_grant_matches(g, g->owner, g->uid, g->pid, raw_start, now, line)) { matched = true; break; } @@ -1855,7 +1858,8 @@ static int frame_acquire_peer_allowed(const struct wl_client *client, bool verif struct pollfd alive = {.fd = frame_worker_pidfd, .events = POLLIN}; bool allowed = frame_worker_pidfd >= 0 && uid == getuid() && pid > 1 && g->pid == (uint32_t)pid && g->uid == uid && now < g->expires && - poll(&alive, 1, 0) == 0 && (!verify_exec || frame_worker_verified_exec_locked(g, now)); + poll(&alive, 1, 0) == 0 && (!verify_exec || + (frame_worker_verified_exec_locked(g, now) && poll(&alive, 1, 0) == 0)); pthread_mutex_unlock(&frame_worker_lock); return allowed; } diff --git a/app/src/main/cpp/waylandcomp/src/frame_worker_peer.h b/app/src/main/cpp/waylandcomp/src/frame_worker_peer.h index 9834513bf3..989e59b336 100644 --- a/app/src/main/cpp/waylandcomp/src/frame_worker_peer.h +++ b/app/src/main/cpp/waylandcomp/src/frame_worker_peer.h @@ -3,6 +3,8 @@ #include #include #include +#include +#include #include #include @@ -15,6 +17,46 @@ struct dd_worker_grant { bool app_launch_verified, final_go; }; +enum dd_worker_stat_result { + DD_WORKER_STAT_OK, DD_WORKER_STAT_DENIED, DD_WORKER_STAT_HIDDEN, DD_WORKER_STAT_OPEN, + DD_WORKER_STAT_READ, DD_WORKER_STAT_PARSE, DD_WORKER_STAT_ZERO, +}; + +static inline enum dd_worker_stat_result dd_worker_parse_start(const char *line, uint64_t *out) { + const char *p = strrchr(line, ')'); + if (!p || p[1] != ' ' || !p[2] || p[3] != ' ') return DD_WORKER_STAT_PARSE; + p += 2; + // State is field 3. The starttime (22) is always followed by vsize (23). + for (int field = 3; field < 22; ++field) { + p = strchr(p, ' '); + if (!p) return DD_WORKER_STAT_PARSE; + while (*p == ' ') ++p; + } + char *end; + if (*p < '0' || *p > '9') return DD_WORKER_STAT_PARSE; + errno = 0; + uint64_t value = strtoull(p, &end, 10); + if (errno || end == p || *end != ' ') return DD_WORKER_STAT_PARSE; + if (!value) return DD_WORKER_STAT_ZERO; + *out = value; + return DD_WORKER_STAT_OK; +} + +static inline enum dd_worker_stat_result dd_worker_open_failure(int error) { + if (error == EACCES || error == EPERM) return DD_WORKER_STAT_DENIED; + if (error == ENOENT || error == ESRCH) return DD_WORKER_STAT_HIDDEN; + return DD_WORKER_STAT_OPEN; +} + +static inline bool dd_worker_receipt_allows_reserve(enum dd_worker_stat_result stat, + uint64_t raw, uint64_t receipt) { + if (!receipt) return false; + if (stat == DD_WORKER_STAT_OK) return raw == receipt; + // Only a visibility denial can defer the broker-side stat check, not any + // bad read, malformed record, mismatched timestamp, or other open error. + return stat == DD_WORKER_STAT_DENIED || stat == DD_WORKER_STAT_HIDDEN; +} + static inline bool dd_worker_map_matches(const struct dd_worker_grant *g, const char *line) { unsigned major, minor; uint64_t lo, hi, off, ino; diff --git a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c index 05b19365f4..5f0aa455eb 100644 --- a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c +++ b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c @@ -876,7 +876,7 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeStreamFrames(JNIEnv #ifdef DROIDDECK_FRAME_ACQUIRE_PROBE extern int droiddeck_frame_worker_grant(int owner, pid_t pid, uint64_t expires, const char *path, - uint64_t dev, uint64_t ino); + uint64_t dev, uint64_t ino, uint64_t receipt); extern void droiddeck_frame_worker_revoke(int owner, int pid); #endif @@ -891,12 +891,12 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_frameWorkerProbeEnabled(JN JNIEXPORT jboolean JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_frameWorkerProbeGrant(JNIEnv *env, jclass c, - jint owner, jint pid, jlong expires, jstring path, jlong dev, jlong ino) { + jint owner, jint pid, jlong expires, jstring path, jlong dev, jlong ino, jlong start_ticks) { #ifdef DROIDDECK_FRAME_ACQUIRE_PROBE - if (!path || expires <= 0 || ino <= 0) return JNI_FALSE; + if (!path || expires <= 0 || ino <= 0 || start_ticks <= 0) return JNI_FALSE; const char *name = (*env)->GetStringUTFChars(env, path, NULL); if (!name) return JNI_FALSE; - int granted = droiddeck_frame_worker_grant(owner, pid, (uint64_t)expires, name, (uint64_t)dev, (uint64_t)ino); + int granted = droiddeck_frame_worker_grant(owner, pid, (uint64_t)expires, name, (uint64_t)dev, (uint64_t)ino, (uint64_t)start_ticks); (*env)->ReleaseStringUTFChars(env, path, name); return granted ? JNI_TRUE : JNI_FALSE; #else diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/FrameAcquireWorkerProbe.kt b/app/src/main/java/com/droiddeck/launcher/runtime/FrameAcquireWorkerProbe.kt index 83122a7239..c7405618b5 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/FrameAcquireWorkerProbe.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/FrameAcquireWorkerProbe.kt @@ -17,6 +17,8 @@ internal object FrameAcquireWorkerProbe { private const val TEST_INTENT = "DD_THOR_WORKER_ACQUIRE_TEST=1" private const val SHA = "09a56e234ac7605cae25ea0b69d02e2b04bc815bbb1a32bd5a61b64c11e88fdf" private const val SIZE = 4272072L + internal const val RECEIPT_TAG = 0x44445046 + internal const val RECEIPT_BYTES = Int.SIZE_BYTES + Long.SIZE_BYTES private const val TTL_MS = 600_000L internal data class Ticket(val owner: Int, val root: File, val configuredRoot: File, val binary: File, val expires: Long) @@ -29,7 +31,7 @@ internal object FrameAcquireWorkerProbe { private enum class Reason { ENABLED, ARM_FILE, MATCH_ACK, MATCH_OWNER, MATCH_EXPIRED, MATCH_PATH, MATCH_ROOT, MATCH_ARGV, MATCH_FILE, MATCH_DIGEST, QUALIFIED, PUBLISH_TICKET, PUBLISH_RESTAT, - PUBLISH_NATIVE, RESERVED + PUBLISH_NATIVE, PUBLISH_RECEIPT, RESERVED } private val reported = mutableSetOf() @Synchronized private fun breadcrumb(stage: Stage, reason: Reason) { @@ -142,19 +144,52 @@ internal object FrameAcquireWorkerProbe { return qualified } + internal fun validReceipt(pid: Int, workerPid: Int, ticks: Long, bytes: Int): Long = + if (pid > 1 && pid == workerPid && ticks > 0 && bytes == RECEIPT_BYTES) ticks else 0L + + internal fun parseSelfStat(stat: String, pid: Int): Long { + if (pid <= 1 || !stat.startsWith("$pid (")) return 0L + val comm = stat.lastIndexOf(')') + if (comm < 3 || stat.getOrNull(comm + 1) != ' ') return 0L + val fields = stat.substring(comm + 2).split(' ').filter { it.isNotEmpty() } + if (fields.firstOrNull()?.length != 1 || fields.size < 21) return 0L + val value = fields[19] // field 22 from field 3 (the single-character task state). + return value.takeIf { it.isNotEmpty() && it.all { ch -> ch in '0'..'9' } } + ?.toLongOrNull()?.takeIf { it > 0 } ?: 0L + } + + internal fun selfStartTicks(pid: Int): Long = runCatching { + File("/proc/self/stat").inputStream().use { input -> + val bytes = ByteArray(4096) + var used = 0 + while (used < bytes.size) { + val n = input.read(bytes, used, bytes.size - used) + if (n < 0) break + if (n == 0) return@runCatching 0L + used += n + } + if (used == bytes.size || used == 0 || bytes[used-1] != '\n'.code.toByte()) 0L + else parseSelfStat(String(bytes, 0, used, Charsets.US_ASCII), pid) + } + }.getOrDefault(0L) + /** Runs just before the final GO byte. Failure never changes ordinary launch. */ - @Synchronized fun publish(q: Qualified, pid: Int) { + @Synchronized fun publish(q: Qualified, pid: Int, startTicks: Long) { val t = q.ticket if (intent !== t || pid <= 1 || SystemClock.elapsedRealtime() >= t.expires) { if (intent === t) breadcrumb(Stage.PUBLISH, Reason.PUBLISH_TICKET) return } intent = null // At most one candidate per explicitly armed session. + if (startTicks <= 0L) { + breadcrumb(Stage.PUBLISH, Reason.PUBLISH_RECEIPT) + return + } val status = runCatching { val st = Os.lstat(t.binary.path) require(st.st_size == SIZE && st.st_dev == q.dev && st.st_ino == q.ino && st.st_mtime == q.mtime && st.st_ctime == q.ctime) - if (WaylandCompositor.frameWorkerProbeGrant(t.owner, pid, t.expires, t.binary.path, st.st_dev, st.st_ino)) { + if (WaylandCompositor.frameWorkerProbeGrant(t.owner, pid, t.expires, t.binary.path, st.st_dev, st.st_ino, startTicks)) { nativeOwner = t.owner nativePid = pid Reason.RESERVED diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt b/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt index 229f7357ab..b0bbe88af3 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt @@ -20,6 +20,7 @@ import android.system.Os import android.system.OsConstants import android.system.StructPollfd import android.util.Log +import com.droiddeck.launcher.BuildConfig import org.json.JSONObject import java.io.DataInputStream import java.io.File @@ -45,7 +46,16 @@ open class GuestWorker : Service() { val fillBinderFd = data.readInt() != 0 val go = data.readFileDescriptor() val nice = data.readInt() - reply?.writeInt(Process.myPid()) + val pid = Process.myPid() + reply?.writeInt(pid) + // Optional fixed-size receipt, on the exact local, non-exported worker's Binder. + // Nothing in the guest socket request populates these fields. + if (BuildConfig.FRAME_ACQUIRE_WORKER_PROBE && reply != null && + Binder.getCallingUid() == Process.myUid() && + data.dataAvail() == Int.SIZE_BYTES && data.readInt() == FrameAcquireWorkerProbe.RECEIPT_TAG) { + reply.writeInt(pid) + reply.writeLong(FrameAcquireWorkerProbe.selfStartTicks(pid)) + } Handler(Looper.getMainLooper()).post { // The app writes a byte once it has the reply and has taken the launch on: an exec // before then would end this process with the reply undelivered, and with none (the @@ -436,7 +446,8 @@ object GuestWorkers { private fun start(context: Context, argv: List, env: List, fds: List, targets: IntArray, guest: Boolean, onExit: (Int) -> Unit, commit: (Int) -> Boolean = { true }, confirmed: () -> Boolean = { true }, owner: Int = session, - nice: Int = Process.getThreadPriority(Process.myTid())): Int { + nice: Int = Process.getThreadPriority(Process.myTid()), + testWorker: FrameAcquireWorkerProbe.Qualified? = null): Int { val app = context.applicationContext if (guest && owner <= stopped) { Log.w(TAG, (if (owner == 0) "a request naming no session" else "session $owner is stopping") + @@ -472,13 +483,21 @@ object GuestWorkers { data.writeInt(if (guest) 0 else 1) data.writeFileDescriptor(go[0].fileDescriptor) data.writeInt(nice) - slot.service!!.transact(GuestWorker.RUN, data, reply, 0) + val service = checkNotNull(slot.service) + if (testWorker != null) data.writeInt(FrameAcquireWorkerProbe.RECEIPT_TAG) + check(service.transact(GuestWorker.RUN, data, reply, 0)) // The worker has its own copy: with ours closed (and the request's, which holds one too), // a worker that gave up leaves no reader data.recycle() data = null go[0].close() val pid = reply.readInt() + val startTicks = if (testWorker != null) { + val size = reply.dataAvail() + if (size == FrameAcquireWorkerProbe.RECEIPT_BYTES) + FrameAcquireWorkerProbe.validReceipt(pid, reply.readInt(), reply.readLong(), size) + else 0L + } else 0L // Once a session's teardown has begun (stopGuests), none of its programs may start: it // would not find them. val stopping = { guest && owner <= stopped } @@ -507,7 +526,12 @@ object GuestWorkers { // launching slot), or never. val answered = Os.poll(arrayOf(answer), ANSWER_TIMEOUT_MS) > 0 && Os.read(go[1].fileDescriptor, ByteArray(1), 0, 1) == 1 val accepted = answered && synchronized(authorizing) { - !stopping() && confirmed() && Os.write(go[1].fileDescriptor, byteArrayOf(1), 0, 1) == 1 + if (stopping() || !confirmed()) false + else { + if (testWorker != null) FrameAcquireWorkerProbe.publish(testWorker, pid, + if (slot.service === service) startTicks else 0L) + Os.write(go[1].fileDescriptor, byteArrayOf(1), 0, 1) == 1 + } } val endedRunning = synchronized(slots) { slot.launching = false @@ -914,7 +938,6 @@ object GuestWorkers { out.flush() confirmedToHook = true }.isSuccess - if (confirmed && testWorker != null) FrameAcquireWorkerProbe.publish(testWorker, worker) confirmed }, commit = { started -> worker = started @@ -934,7 +957,7 @@ object GuestWorkers { } ended && line.toString() == "go" }.getOrDefault(false) - }) + }, testWorker = testWorker) if (pid <= 0 && testWorker != null && worker > 1) FrameAcquireWorkerProbe.revoke(owner, worker) handedOver = true programFds.filter { it !== table }.forEach { runCatching { it.close() } } diff --git a/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java b/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java index 0d444909af..e3447de901 100644 --- a/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java +++ b/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java @@ -10,7 +10,7 @@ public final class WaylandCompositor { private WaylandCompositor() {} public static native boolean frameWorkerProbeEnabled(); - public static native boolean frameWorkerProbeGrant(int owner, int pid, long expires, String path, long dev, long ino); + public static native boolean frameWorkerProbeGrant(int owner, int pid, long expires, String path, long dev, long ino, long startTicks); public static native void frameWorkerProbeRevoke(int owner, int pid); private static volatile Runnable firstFrameListener; diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/FrameAcquireWorkerProbeTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/FrameAcquireWorkerProbeTest.kt index 6f9b11a96f..206472d8c7 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/FrameAcquireWorkerProbeTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/FrameAcquireWorkerProbeTest.kt @@ -56,4 +56,23 @@ class FrameAcquireWorkerProbeTest { } } } + @Test fun selfStatAndFixedBinderReceiptRejectWrongWorkerAndExtraBytes() { + val probe = FrameAcquireWorkerProbe + val fields = (1..18).joinToString(" ") + fun stat(pid: Int, ticks: String) = "$pid (guest )worker) S $fields $ticks 123\n" + assertTrue(probe.parseSelfStat(stat(400, "125"), 400) == 125L) + for (bad in listOf(stat(401, "125"), stat(400, "0"), stat(400, "-1"), + stat(400, "1x"), stat(400, "9223372036854775808"), "400 (guest)")) { + assertTrue(probe.parseSelfStat(bad, 400) == 0L) + } + val size = probe.RECEIPT_BYTES + assertTrue(probe.validReceipt(400, 400, 125L, size) == 125L) + assertTrue(probe.validReceipt(400, 401, 125L, size) == 0L) + assertTrue(probe.validReceipt(1, 1, 125L, size) == 0L) + assertTrue(probe.validReceipt(400, 400, 0L, size) == 0L) + assertTrue(probe.validReceipt(400, 400, -1L, size) == 0L) + assertTrue(probe.validReceipt(400, 400, 125L, size - 4) == 0L) + assertTrue(probe.validReceipt(400, 400, 125L, size + 4) == 0L) + } + } diff --git a/tools/tests/frame_worker_peer_live_test.c b/tools/tests/frame_worker_peer_live_test.c index dcd0ce43ec..87e6ee300e 100644 --- a/tools/tests/frame_worker_peer_live_test.c +++ b/tools/tests/frame_worker_peer_live_test.c @@ -13,9 +13,9 @@ static uint64_t start_ticks(pid_t id) { char proc[64], line[4096]; snprintf(proc,sizeof(proc),"/proc/%d/stat",id); FILE *f=fopen(proc,"r");assert(f);assert(fgets(line,sizeof(line),f));fclose(f); - char *p=strrchr(line,')');assert(p&&p[1]==' ');p+=2; - for(int field=3;field<22;field++){p=strchr(p,' ');assert(p);while(*p==' ')p++;} - return strtoull(p,0,10); + uint64_t ticks=0; + assert(dd_worker_parse_start(line,&ticks)==DD_WORKER_STAT_OK); + return ticks; } static bool check_maps(const struct dd_worker_grant *g,pid_t id,uint64_t ticks) { char proc[64],line[4096];snprintf(proc,sizeof(proc),"/proc/%d/maps",id); @@ -39,7 +39,10 @@ int main(void){ struct pollfd pfd_poll={.fd=pfd,.events=POLLIN};assert(poll(&pfd_poll,1,0)==0); uint64_t start=start_ticks(id);assert(start); struct dd_worker_grant g={.owner=4,.uid=getuid(),.pid=id,.dev_major=major(st.st_dev),.dev_minor=minor(st.st_dev),.ino=st.st_ino,.start_ticks=start,.expires=10,.canonical_file=p,.app_launch_verified=true,.final_go=true}; - assert(check_maps(&g,id,start));assert(!check_maps(&g,id,start+1)); + assert(dd_worker_receipt_allows_reserve(DD_WORKER_STAT_DENIED,0,start+1)); + assert(!check_maps(&g,id,start+1)); // A forged self receipt fails against live post-exec ticks. + assert(dd_worker_receipt_allows_reserve(DD_WORKER_STAT_OK,start,start)); + assert(check_maps(&g,id,start)); g.final_go=false;assert(!check_maps(&g,id,start));g.final_go=true; assert(write(b[1],"n",1)==1);assert(read(a[0],&c,1)==1);assert(!check_maps(&g,id,start)); assert(write(b[1],"n",1)==1);assert(poll(&pfd_poll,1,2000)==1); diff --git a/tools/tests/frame_worker_peer_test.c b/tools/tests/frame_worker_peer_test.c index cfdfe16047..a8401aae0d 100644 --- a/tools/tests/frame_worker_peer_test.c +++ b/tools/tests/frame_worker_peer_test.c @@ -4,6 +4,26 @@ static const char file[]="/app/private/linuxfs/opt/droiddeck-agent/bin/gamescope"; static const char good[]="1000-2000 r-xp 00001000 fe:15 5502 /app/private/linuxfs/opt/droiddeck-agent/bin/gamescope\n"; int main(void) { + uint64_t ticks = 0; + assert(dd_worker_parse_start("650 (with ) parens) S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 251191 123\n", &ticks) == DD_WORKER_STAT_OK); + assert(ticks == 251191); + assert(dd_worker_parse_start("650 (x) S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 0 123\n", &ticks) == DD_WORKER_STAT_ZERO); + assert(dd_worker_parse_start("650 (x) S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 18446744073709551616 123\n", &ticks) == DD_WORKER_STAT_PARSE); + assert(dd_worker_parse_start("650 (x) S 1 2 3", &ticks) == DD_WORKER_STAT_PARSE); + assert(dd_worker_open_failure(EACCES) == DD_WORKER_STAT_DENIED); + assert(dd_worker_open_failure(EPERM) == DD_WORKER_STAT_DENIED); + assert(dd_worker_open_failure(ENOENT) == DD_WORKER_STAT_HIDDEN); + assert(dd_worker_open_failure(ESRCH) == DD_WORKER_STAT_HIDDEN); + assert(dd_worker_open_failure(EMFILE) == DD_WORKER_STAT_OPEN); + assert(dd_worker_receipt_allows_reserve(DD_WORKER_STAT_OK, 251191, 251191)); + assert(!dd_worker_receipt_allows_reserve(DD_WORKER_STAT_OK, 251192, 251191)); + assert(dd_worker_receipt_allows_reserve(DD_WORKER_STAT_DENIED, 0, 251191)); + assert(dd_worker_receipt_allows_reserve(DD_WORKER_STAT_HIDDEN, 0, 251191)); + assert(!dd_worker_receipt_allows_reserve(DD_WORKER_STAT_DENIED, 0, 0)); + assert(!dd_worker_receipt_allows_reserve(DD_WORKER_STAT_OPEN, 0, 251191)); + assert(!dd_worker_receipt_allows_reserve(DD_WORKER_STAT_READ, 0, 251191)); + assert(!dd_worker_receipt_allows_reserve(DD_WORKER_STAT_PARSE, 0, 251191)); + assert(!dd_worker_receipt_allows_reserve(DD_WORKER_STAT_ZERO, 0, 251191)); struct dd_worker_grant g={.owner=3,.uid=10197,.pid=650,.dev_major=254,.dev_minor=21, .start_ticks=251191,.ino=5502,.expires=1000,.canonical_file=file,.app_launch_verified=true,.final_go=true}; assert(dd_worker_grant_matches(&g,3,10197,650,251191,999,good)); diff --git a/tools/tests/test_frame_acquire_peer_gate.py b/tools/tests/test_frame_acquire_peer_gate.py index 2dd0388ee7..70d41bedd0 100644 --- a/tools/tests/test_frame_acquire_peer_gate.py +++ b/tools/tests/test_frame_acquire_peer_gate.py @@ -31,11 +31,18 @@ class FrameAcquirePeerGateTest(unittest.TestCase): def test_publish_before_worker_go_and_require_map_at_bind(self): workers=(JAVA/'runtime/GuestWorkers.kt').read_text() - match=workers.index('val testWorker = FrameAcquireWorkerProbe.match') - confirmation=workers.index('}, confirmed = {',match) - publish=workers.index('FrameAcquireWorkerProbe.publish',confirmation) - self.assertLess(publish,workers.index('}, commit = { started ->',confirmation)) - self.assertIn('confirmed() && Os.write(go[1]',workers) + broker=workers.split("private fun start(",1)[1].split("private fun takeWarm",1)[0] + check=broker.index("if (stopping() || !confirmed())") + publish=broker.index("FrameAcquireWorkerProbe.publish",check) + self.assertLess(publish,broker.index("Os.write(go[1]",check)) + self.assertIn("if (slot.service === service) startTicks else 0L",broker) + self.assertIn("val size = reply.dataAvail()",broker) + self.assertIn("if (size == FrameAcquireWorkerProbe.RECEIPT_BYTES)",broker) + service=workers.split("override fun onTransact",1)[1].split("Handler(",1)[0] + self.assertIn("BuildConfig.FRAME_ACQUIRE_WORKER_PROBE",service) + self.assertIn("Binder.getCallingUid() == Process.myUid()",service) + self.assertIn("data.dataAvail() == Int.SIZE_BYTES",service) + self.assertIn("reply.writeLong(FrameAcquireWorkerProbe.selfStartTicks(pid))",service) self.assertIn('if (pid <= 0 && testWorker != null && worker > 1) FrameAcquireWorkerProbe.revoke',workers) comp=(SRC/'compositor.c').read_text() bind=comp.split('static void bind_frame_acquire',1)[1].split('#endif',1)[0] @@ -57,10 +64,12 @@ class FrameAcquirePeerGateTest(unittest.TestCase): self.assertIn('"worker_admission=" + reason.name',kt) for name in ('ARM_FILE','MATCH_ACK','MATCH_OWNER','MATCH_EXPIRED','MATCH_PATH','MATCH_ROOT', 'MATCH_ARGV','MATCH_FILE','MATCH_DIGEST','QUALIFIED','PUBLISH_TICKET', - 'PUBLISH_RESTAT','PUBLISH_NATIVE','RESERVED'): + 'PUBLISH_RESTAT','PUBLISH_NATIVE','PUBLISH_RECEIPT','RESERVED'): self.assertIn('Reason.'+name,kt) self.assertIn(' return JNI_FALSE;\n#endif',jni.split('frameWorkerProbeEnabled(',1)[1]) self.assertIn('if (!frame_worker_map_reported)',comp) - for name in ('NATIVE_FILE','NATIVE_PIDFD','NATIVE_STARTTIME','NATIVE_ALREADY_RESERVED', + for name in ('NATIVE_FILE','NATIVE_PIDFD','NATIVE_STAT_OPEN_DENIED','NATIVE_STAT_OPEN_HIDDEN', + 'NATIVE_STAT_OPEN_OTHER','NATIVE_STAT_READ','NATIVE_STAT_PARSE','NATIVE_STAT_ZERO', + 'NATIVE_STAT_MISMATCH','NATIVE_PIDFD_NOT_LIVE','NATIVE_ALREADY_RESERVED', 'MAP_STARTTIME','MAP_OPEN','MAP_IDENTITY'): self.assertIn('"worker_admission='+name+'"',comp)