diff --git a/controller/app/src/main/java/org/iiab/controller/PRootEngine.java b/controller/app/src/main/java/org/iiab/controller/PRootEngine.java index 370ca2f34..91c28d576 100644 --- a/controller/app/src/main/java/org/iiab/controller/PRootEngine.java +++ b/controller/app/src/main/java/org/iiab/controller/PRootEngine.java @@ -25,9 +25,21 @@ import org.iiab.controller.network.data.FileResolvConfWriter; import org.iiab.controller.network.data.PrefsDnsConfigRepository; import org.iiab.controller.network.domain.ApplyDnsUseCase; +import org.iiab.controller.proot.data.PrefsSeccompModeRepository; +import org.iiab.controller.proot.data.ProotEnvironment; +import org.iiab.controller.proot.domain.SeccompFailure; +import org.iiab.controller.proot.domain.SeccompMode; public class PRootEngine { private static final String TAG = "IIAB-PRootEngine"; + + /** + * ADFA-5362: how much of a launch's output to keep for {@link SeccompFailure}. An install + * streams megabytes, so this is a tail, not a buffer of everything — and a tail is the right + * end anyway, because the abort we look for is what ends the process. + */ + private static final int TAIL_LIMIT = 8192; + private volatile Process currentProcess; private volatile java.io.OutputStream processOutputStream; @@ -41,6 +53,9 @@ public interface OutputListener { public void executeInContainer(Context context, String rootfsDir, String command, OutputListener listener) { new Thread(() -> { + // ADFA-5362: how proot must run here is remembered per device, defaulting to the fast path. + PrefsSeccompModeRepository capability = new PrefsSeccompModeRepository(context); + SeccompMode mode = capability.load(); try { File nativeDir = new File(context.getApplicationInfo().nativeLibraryDir); File prootBinary = new File(nativeDir, "libproot.so"); @@ -177,26 +192,11 @@ public void executeInContainer(Context context, String rootfsDir, String command // ========================================================= // INJECT ENVIRONMENT VARIABLES // ========================================================= + // ADFA-5362: the environment is built in one place for every proot launch, so the + // app and the terminal cannot drift apart on the same phone. pb.environment().clear(); // Clean toxic Android vars - - // Tell PRoot where to find our Fake Termux Prefix - pb.environment().put("PREFIX", prefixDir.getCanonicalPath()); - - // Fallback environment variables for modern PRoot versions - if (loaderBinary.exists()) - pb.environment().put("PROOT_LOADER", loaderBinary.getAbsolutePath()); - File loader32 = new File(nativeDir, "libproot-loader32.so"); - if (loader32.exists()) - pb.environment().put("PROOT_LOADER_32", loader32.getAbsolutePath()); - - pb.environment().put("PROOT_TMP_DIR", prootTmpPath); - pb.environment().put("TMPDIR", "/tmp"); - pb.environment().put("HOME", "/root"); - pb.environment().put("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"); - pb.environment().put("TERM", "xterm-256color"); - pb.environment().put("LANG", "C.UTF-8"); - pb.environment().put("USER", "root"); - pb.environment().put("LOGNAME", "root"); + pb.environment().putAll(ProotEnvironment.build( + nativeDir, prefixDir.getCanonicalPath(), prootTmpPath, mode)); // ADFA-4458: wait on THIS call's process, not the shared field, so a // concurrent proot call can't make us return on the wrong process. @@ -207,15 +207,30 @@ public void executeInContainer(Context context, String rootfsDir, String command BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream())); String line; Handler mainHandler = new Handler(Looper.getMainLooper()); + StringBuilder tail = new StringBuilder(); while ((line = reader.readLine()) != null) { final String outLine = line; Log.i("IIAB-Ansible", "[Debian] " + outLine); // Funneled straight to Logcat! + appendTail(tail, outLine); mainHandler.post(() -> listener.onOutputLine(outLine)); } int exitCode = proc.waitFor(); + // ADFA-5362: proot has told us this kernel cannot run it with seccomp. Record it and + // report the failure as it happened — deliberately nothing relaunches here. The + // lifecycle owner already relaunches on its own tick whenever the environment is not + // alive (ServerLifecycleReconciler), and it will read the new mode when it does. + // Relaunching from inside the engine would be a second actuation path that does not + // consult `desired`, so a stop landing in that window would be overruled. + if (mode == SeccompMode.FILTER + && SeccompFailure.isSeccompAbort(exitCode, tail.toString())) { + Log.w(TAG, "ADFA-5362: proot cannot use seccomp on this kernel — remembering" + + " PROOT_NO_SECCOMP for this build; the next launch will use it"); + capability.remember(SeccompMode.DISABLED); + } + mainHandler.post(() -> listener.onProcessExit(exitCode)); } catch (Exception e) { @@ -225,8 +240,20 @@ public void executeInContainer(Context context, String rootfsDir, String command }).start(); } + /** Keep only the last {@link #TAIL_LIMIT} characters of the output. */ + private static void appendTail(StringBuilder tail, String line) { + tail.append(line).append('\n'); + if (tail.length() > TAIL_LIMIT) { + tail.delete(0, tail.length() - TAIL_LIMIT); + } + } + /** * Start an interactive bash session that stays live. + * + *

ADFA-5362: this consumes the remembered mode but does not learn one. A terminal is + * opened long after the environment has launched at least once, so the verdict is already known + * by the time anyone gets here; and a live session has no exit to read a verdict from. */ public void startInteractiveShell(Context context, String rootfsDir, OutputListener listener) { new Thread(() -> { @@ -307,22 +334,11 @@ public void startInteractiveShell(Context context, String rootfsDir, OutputListe ProcessBuilder pb = new ProcessBuilder(args); pb.redirectErrorStream(true); + // ADFA-5362: same single builder as executeInContainer. pb.environment().clear(); - pb.environment().put("PREFIX", prefixDir.getCanonicalPath()); - if (loaderBinary.exists()) - pb.environment().put("PROOT_LOADER", loaderBinary.getAbsolutePath()); - File loader32 = new File(nativeDir, "libproot-loader32.so"); - if (loader32.exists()) - pb.environment().put("PROOT_LOADER_32", loader32.getAbsolutePath()); - - pb.environment().put("PROOT_TMP_DIR", prootTmpPath); - pb.environment().put("TMPDIR", "/tmp"); - pb.environment().put("HOME", "/root"); - pb.environment().put("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"); - pb.environment().put("TERM", "xterm-256color"); - pb.environment().put("LANG", "C.UTF-8"); - pb.environment().put("USER", "root"); - pb.environment().put("LOGNAME", "root"); + pb.environment().putAll(ProotEnvironment.build( + nativeDir, prefixDir.getCanonicalPath(), prootTmpPath, + new PrefsSeccompModeRepository(context).load())); // ADFA-4458: wait on THIS call's process, not the shared field, so a // concurrent proot call can't make us return on the wrong process. diff --git a/controller/app/src/main/java/org/iiab/controller/TerminalController.java b/controller/app/src/main/java/org/iiab/controller/TerminalController.java index f6420d91a..11735ebda 100644 --- a/controller/app/src/main/java/org/iiab/controller/TerminalController.java +++ b/controller/app/src/main/java/org/iiab/controller/TerminalController.java @@ -678,7 +678,16 @@ public void addNewSession() { cliStr.append("BACKUPS_DIR=\"").append(backupsDir.getAbsolutePath()).append("\"\n"); cliStr.append("export PROOT_TMP_DIR=\"").append(tmpDir.getAbsolutePath()).append("\"\n"); cliStr.append("export PROOT_LOADER=\"").append(prootLoader.getAbsolutePath()).append("\"\n"); - cliStr.append("export PROOT_LOADER_32=\"").append(prootLoader32.getAbsolutePath()).append("\"\n\n"); + cliStr.append("export PROOT_LOADER_32=\"").append(prootLoader32.getAbsolutePath()).append("\"\n"); + // ADFA-5362: the CLI only consumes the verdict the app has already learned, so the + // terminal and the app launch proot the same way on the same phone. + if (new org.iiab.controller.proot.data.PrefsSeccompModeRepository(activity).load() + == org.iiab.controller.proot.domain.SeccompMode.DISABLED) { + cliStr.append("export ") + .append(org.iiab.controller.proot.data.ProotEnvironment.NO_SECCOMP) + .append("=1\n"); + } + cliStr.append("\n"); // Initialize Mount Flags cliStr.append("MOUNT_SDCARD=false\n"); diff --git a/controller/app/src/main/java/org/iiab/controller/proot/data/PrefsSeccompModeRepository.java b/controller/app/src/main/java/org/iiab/controller/proot/data/PrefsSeccompModeRepository.java new file mode 100644 index 000000000..85de7de2c --- /dev/null +++ b/controller/app/src/main/java/org/iiab/controller/proot/data/PrefsSeccompModeRepository.java @@ -0,0 +1,67 @@ +/* + * ============================================================================ + * Name : PrefsSeccompModeRepository.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : ADFA-5362. Remembers how proot must be launched on this device. + * ============================================================================ + */ +package org.iiab.controller.proot.data; + +import android.content.Context; +import android.content.SharedPreferences; +import android.os.Build; + +import org.iiab.controller.proot.domain.CapabilityKey; +import org.iiab.controller.proot.domain.SeccompMode; + +/** + * The one place that remembers whether this device's kernel can run proot with seccomp. + * + *

Lifecycle. Nothing is stored until a launch actually aborts, so the default is always + * {@link SeccompMode#FILTER} — the fast path — and a launch killed mid-flight leaves no verdict + * behind to be wrong about. What is stored is tied to a capability key: the OS build, the + * kernel and the app version. Any of the three changing means the answer may no longer hold (a + * kernel that gets fixed by an update, a different proot shipped in a new APK), so a key mismatch + * reads as "not known yet" and the next launch learns again. That is also why nothing ever needs to + * clear this: the key does it. + */ +public final class PrefsSeccompModeRepository { + + private static final String PREFS = "ProotCapabilityPrefs"; + private static final String K_KEY = "seccomp.key"; + private static final String K_DISABLED = "seccomp.disabled"; + + private final SharedPreferences prefs; + + public PrefsSeccompModeRepository(Context context) { + this.prefs = context.getSharedPreferences(PREFS, Context.MODE_MULTI_PROCESS); + } + + /** How proot must be launched here; {@link SeccompMode#FILTER} until proved otherwise. */ + public SeccompMode load() { + if (!CapabilityKey.holds(prefs.getString(K_KEY, null), capabilityKey())) { + return SeccompMode.FILTER; // never learned, or learned about a different OS/app + } + return prefs.getBoolean(K_DISABLED, false) ? SeccompMode.DISABLED : SeccompMode.FILTER; + } + + /** + * Record what this device needs. Written with {@code commit()}: the very next thing that happens + * is a relaunch, and on an ungraceful kill an unwritten verdict costs another aborted launch. + */ + public void remember(SeccompMode mode) { + prefs.edit() + .putString(K_KEY, capabilityKey()) + .putBoolean(K_DISABLED, mode == SeccompMode.DISABLED) + .commit(); + } + + /** This device's key, read off the platform; {@link CapabilityKey} owns what it means. */ + private static String capabilityKey() { + return CapabilityKey.of( + Build.FINGERPRINT, + System.getProperty("os.version"), + org.iiab.controller.BuildConfig.VERSION_CODE); + } +} diff --git a/controller/app/src/main/java/org/iiab/controller/proot/data/ProotEnvironment.java b/controller/app/src/main/java/org/iiab/controller/proot/data/ProotEnvironment.java new file mode 100644 index 000000000..351d38b58 --- /dev/null +++ b/controller/app/src/main/java/org/iiab/controller/proot/data/ProotEnvironment.java @@ -0,0 +1,91 @@ +/* + * ============================================================================ + * Name : ProotEnvironment.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : ADFA-5362. The single builder of the environment every proot + * launch runs with. + * ============================================================================ + */ +package org.iiab.controller.proot.data; + +import org.iiab.controller.proot.domain.SeccompMode; + +import java.io.File; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * One place that answers "what environment does a proot launch run with". + * + *

The same block was written out four times — twice in {@code PRootEngine} (the container + * command and the interactive shell) and once as {@code export} lines in the generated + * {@code iiab} CLI, which two of its own launches share. Four copies of one fact is how the + * terminal and the app end up disagreeing on the same phone, and it is why a per-device launch + * decision (ADFA-5362) had no single place to land. + * + *

Pure: files are only probed for existence, nothing is written and there is no {@code android.*}, + * so this is unit-tested on the JVM. + */ +public final class ProotEnvironment { + + /** The guest PATH; a login shell re-derives it, but proot's own exec needs it set. */ + public static final String GUEST_PATH = + "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"; + + /** proot reads this before its own {@code execvp}; any value disables seccomp filtering. */ + public static final String NO_SECCOMP = "PROOT_NO_SECCOMP"; + + private static final String LOADER = "libproot-loader.so"; + private static final String LOADER_32 = "libproot-loader32.so"; + + private ProotEnvironment() { + } + + /** + * The environment for a proot launch. + * + *

Callers apply it over a cleared environment ({@code pb.environment().clear()} then + * {@code putAll}): Android's own variables are toxic to the guest, so the launch starts from + * nothing and receives exactly this map. + * + *

The two loader variables are set only when the loader is actually on disk — the 32-bit + * loader ships on 64-bit ABIs only, and proot falls back to {@code PREFIX} when they are absent. + * + * @param nativeLibDir the app's native library directory (where the proot loaders live). + * @param prefixPath canonical path of the fake Termux prefix proot resolves its loader through. + * @param prootTmpPath canonical path of the host directory proot uses for its own temporaries. + * @param mode how proot must run here (ADFA-5362); only DISABLED adds a variable. + */ + public static Map build(File nativeLibDir, String prefixPath, + String prootTmpPath, SeccompMode mode) { + Map env = new LinkedHashMap<>(); + + env.put("PREFIX", prefixPath); + + // ADFA-5362: absent on a healthy kernel, so the fast path is byte-identical to what shipped. + if (mode == SeccompMode.DISABLED) { + env.put(NO_SECCOMP, "1"); + } + + File loader = new File(nativeLibDir, LOADER); + if (loader.exists()) { + env.put("PROOT_LOADER", loader.getAbsolutePath()); + } + File loader32 = new File(nativeLibDir, LOADER_32); + if (loader32.exists()) { + env.put("PROOT_LOADER_32", loader32.getAbsolutePath()); + } + + env.put("PROOT_TMP_DIR", prootTmpPath); + env.put("TMPDIR", "/tmp"); + env.put("HOME", "/root"); + env.put("PATH", GUEST_PATH); + env.put("TERM", "xterm-256color"); + env.put("LANG", "C.UTF-8"); + env.put("USER", "root"); + env.put("LOGNAME", "root"); + + return env; + } +} diff --git a/controller/app/src/main/java/org/iiab/controller/proot/domain/CapabilityKey.java b/controller/app/src/main/java/org/iiab/controller/proot/domain/CapabilityKey.java new file mode 100644 index 000000000..6a30eac70 --- /dev/null +++ b/controller/app/src/main/java/org/iiab/controller/proot/domain/CapabilityKey.java @@ -0,0 +1,58 @@ +/* + * ============================================================================ + * Name : CapabilityKey.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : ADFA-5362. When does a remembered proot verdict still apply? + * ============================================================================ + */ +package org.iiab.controller.proot.domain; + +/** + * The rule that keeps a remembered launch verdict from outliving what it was true about. + * + *

{@link SeccompMode#DISABLED} is learned from one kernel running one proot binary. Three things + * can make that answer wrong: the OS build changes (a vendor update can fix the kernel), the kernel + * string changes, or the app ships a different proot. So the verdict is stored against a key made of + * all three, and only counts while that key still describes the device. That is also why nothing + * ever has to clear the stored value — a key that no longer matches is already ignored. + * + *

Getting this wrong is quiet, not loud: a verdict that outlives its key leaves a healthy device + * permanently slower with no symptom to notice. Hence a pure rule with tests, rather than a string + * comparison buried in the data layer. + */ +public final class CapabilityKey { + + /** Stands in for a component the platform did not report, so the key stays well-formed. */ + private static final String UNKNOWN = "unknown"; + + private static final String SEPARATOR = "|"; + + private CapabilityKey() { + } + + /** + * Build the key a verdict is stored against. + * + * @param osBuild the OS build identity (Android's {@code Build.FINGERPRINT}). + * @param kernel the kernel version string ({@code os.version}). + * @param appVersion the app's version code — a new APK can carry a different proot. + */ + public static String of(String osBuild, String kernel, int appVersion) { + return orUnknown(osBuild) + SEPARATOR + orUnknown(kernel) + SEPARATOR + appVersion; + } + + /** + * Does a verdict stored under {@code storedKey} still describe this device? + * + *

False for anything that is not an exact match, including nothing stored at all: never + * having learned and having learned about something else both mean "do not use a verdict here". + */ + public static boolean holds(String storedKey, String currentKey) { + return storedKey != null && storedKey.equals(currentKey); + } + + private static String orUnknown(String component) { + return (component == null || component.isEmpty()) ? UNKNOWN : component; + } +} diff --git a/controller/app/src/main/java/org/iiab/controller/proot/domain/SeccompFailure.java b/controller/app/src/main/java/org/iiab/controller/proot/domain/SeccompFailure.java new file mode 100644 index 000000000..48574f3f1 --- /dev/null +++ b/controller/app/src/main/java/org/iiab/controller/proot/domain/SeccompFailure.java @@ -0,0 +1,53 @@ +/* + * ============================================================================ + * Name : SeccompFailure.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : ADFA-5362. Was this proot exit the kernel's broken seccomp? + * ============================================================================ + */ +package org.iiab.controller.proot.domain; + +/** + * Recognises the one failure that {@link SeccompMode#DISABLED} fixes. + * + *

Why a marker and not a timeout. proot names this failure itself, so there is a fact to + * read instead of a symptom to guess at. Keying on "died quickly" would instead flip the verdict on + * any fast failure — a broken rootfs, a bad command — and silently slow the device down for good. + * A marker cannot false-positive: if some other kernel fails in some other way, the logs will say + * so and this rule gets widened with evidence rather than on speculation. + * + *

Both markers are strings in the shipped proot binary. The assertion is the abort observed on + * an affected device (Android 9, kernel 3.18); the advice line is proot's own workaround message + * for the documented kernel bug, matched on enough of the sentence that it cannot collide with a + * guest log line that merely names the variable. + * + *

Pure: no {@code android.*}, unit-tested on the JVM. + */ +public final class SeccompFailure { + + /** proot's assertion when the kernel delivers its seccomp event in the state proot does not expect. */ + private static final String ASSERTION_MARKER = "IS_IN_SYSENTER"; + + /** proot's own advice for the documented kernel bug ("To workaround it, set the env. variable …"). */ + private static final String ADVICE_MARKER = "set the env. variable PROOT_NO_SECCOMP"; + + private SeccompFailure() { + } + + /** + * True when this exit is proot saying it cannot use seccomp on this kernel. + * + *

Both halves are required. A zero exit is proot working, whatever it printed on the way — + * matching output alone would misread a warning as a failure. + * + * @param exitCode the process exit code. + * @param output proot's combined output (a tail is enough — the abort ends the process). + */ + public static boolean isSeccompAbort(int exitCode, String output) { + if (exitCode == 0 || output == null) { + return false; + } + return output.contains(ASSERTION_MARKER) || output.contains(ADVICE_MARKER); + } +} diff --git a/controller/app/src/main/java/org/iiab/controller/proot/domain/SeccompMode.java b/controller/app/src/main/java/org/iiab/controller/proot/domain/SeccompMode.java new file mode 100644 index 000000000..a830ddb3f --- /dev/null +++ b/controller/app/src/main/java/org/iiab/controller/proot/domain/SeccompMode.java @@ -0,0 +1,33 @@ +/* + * ============================================================================ + * Name : SeccompMode.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : ADFA-5362. Which of the two ways this device can run proot. + * ============================================================================ + */ +package org.iiab.controller.proot.domain; + +/** + * How proot must be launched on this device. + * + *

Two rungs, not three. {@code PROOT_ASSUME_NEW_SECCOMP} — proot's other seccomp knob, which + * forces its guess about whether the kernel evaluates seccomp after the ptrace enter-stop — was + * measured on an affected device and aborts identically to the default, so it is not a rung. + */ +public enum SeccompMode { + + /** + * proot's seccomp acceleration: only the syscalls proot must translate are trapped. The default, + * and what every healthy kernel uses. Losing it costs real time — measured +18 % on a metadata + * walk and +75 % on a read-heavy pass — which is why this is not simply switched off everywhere. + */ + FILTER, + + /** + * {@code PROOT_NO_SECCOMP=1}: every syscall goes through ptrace. Slower, and the only way to run + * on a kernel whose seccomp/ptrace interaction is broken — there, proot with FILTER aborts in + * well under a second on {@code assertion "IS_IN_SYSENTER(tracee)" failed}. + */ + DISABLED +} diff --git a/controller/app/src/test/java/org/iiab/controller/proot/data/ProotEnvironmentTest.java b/controller/app/src/test/java/org/iiab/controller/proot/data/ProotEnvironmentTest.java new file mode 100644 index 000000000..15bbb748b --- /dev/null +++ b/controller/app/src/test/java/org/iiab/controller/proot/data/ProotEnvironmentTest.java @@ -0,0 +1,143 @@ +package org.iiab.controller.proot.data; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.HashMap; +import java.util.Map; + +import org.iiab.controller.proot.domain.SeccompMode; +import org.junit.Before; +import org.junit.Test; + +/** + * Unit tests for {@link ProotEnvironment} — ADFA-5362. + * + *

These pin the environment map value by value. The builder replaced four hand-written + * copies of the same block, and a proot launched with a variable missing (or renamed) fails on + * every device, healthy ones included — so the point of this test is to make any drift from the + * environment the app shipped with a test failure rather than a field report. + */ +public class ProotEnvironmentTest { + + private File nativeDir; + + @Before + public void setUp() throws IOException { + nativeDir = Files.createTempDirectory("nativeLibDir").toFile(); + nativeDir.deleteOnExit(); + } + + private void writeLoader(String name) throws IOException { + File f = new File(nativeDir, name); + assertTrue("could not create " + name, f.createNewFile()); + f.deleteOnExit(); + } + + /** The exact map the app launched proot with before the builder existed. */ + private Map expectedBase() { + Map expected = new HashMap<>(); + expected.put("PREFIX", "/data/app/files/usr"); + expected.put("PROOT_TMP_DIR", "/data/app/files/proot_tmp"); + expected.put("TMPDIR", "/tmp"); + expected.put("HOME", "/root"); + expected.put("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"); + expected.put("TERM", "xterm-256color"); + expected.put("LANG", "C.UTF-8"); + expected.put("USER", "root"); + expected.put("LOGNAME", "root"); + return expected; + } + + private Map build() { + return build(SeccompMode.FILTER); + } + + private Map build(SeccompMode mode) { + return ProotEnvironment.build( + nativeDir, "/data/app/files/usr", "/data/app/files/proot_tmp", mode); + } + + @Test + public void bothLoadersPresentYieldsTheFullShippedEnvironment() throws IOException { + writeLoader("libproot-loader.so"); + writeLoader("libproot-loader32.so"); + + Map expected = expectedBase(); + expected.put("PROOT_LOADER", new File(nativeDir, "libproot-loader.so").getAbsolutePath()); + expected.put("PROOT_LOADER_32", new File(nativeDir, "libproot-loader32.so").getAbsolutePath()); + + assertEquals(expected, build()); + } + + @Test + public void thirtyTwoBitLoaderIsOmittedWhenTheAbiDoesNotShipIt() throws IOException { + // armeabi-v7a carries no loader32; proot must not be told about one that is not there. + writeLoader("libproot-loader.so"); + + Map expected = expectedBase(); + expected.put("PROOT_LOADER", new File(nativeDir, "libproot-loader.so").getAbsolutePath()); + + assertEquals(expected, build()); + assertFalse(build().containsKey("PROOT_LOADER_32")); + } + + @Test + public void noLoadersFallsBackToPrefixOnly() { + // Neither loader on disk: proot resolves through PREFIX, so the keys stay absent + // rather than being set to a path that does not exist. + assertEquals(expectedBase(), build()); + } + + @Test + public void everyValueIsPinnedNotJustTheKeys() throws IOException { + writeLoader("libproot-loader.so"); + Map env = build(); + + // Guest-side identity and locale: a login shell inside the rootfs relies on these. + assertEquals("/root", env.get("HOME")); + assertEquals("root", env.get("USER")); + assertEquals("root", env.get("LOGNAME")); + assertEquals("C.UTF-8", env.get("LANG")); + assertEquals("xterm-256color", env.get("TERM")); + // TMPDIR is the guest path; PROOT_TMP_DIR is the host one. They are not interchangeable. + assertEquals("/tmp", env.get("TMPDIR")); + assertEquals("/data/app/files/proot_tmp", env.get("PROOT_TMP_DIR")); + assertEquals(ProotEnvironment.GUEST_PATH, env.get("PATH")); + } + + @Test + public void carriesNothingBeyondTheShippedVariables() throws IOException { + // The launch runs over a cleared environment, so anything extra here would be a new + // variable reaching the guest that never did before. + writeLoader("libproot-loader.so"); + writeLoader("libproot-loader32.so"); + assertEquals(11, build().size()); + } + + @Test + public void healthyKernelGetsNoSeccompVariableAtAll() throws IOException { + // FILTER must stay byte-identical to what shipped: absent, not set to "0". proot treats + // ANY value as "disable", so an empty or zero value would silently slow every device down. + writeLoader("libproot-loader.so"); + assertFalse(build(SeccompMode.FILTER).containsKey(ProotEnvironment.NO_SECCOMP)); + } + + @Test + public void affectedKernelGetsTheOnlyVariableThatChanges() throws IOException { + writeLoader("libproot-loader.so"); + Map disabled = build(SeccompMode.DISABLED); + + assertEquals("1", disabled.get(ProotEnvironment.NO_SECCOMP)); + + // Exactly one variable more than the fast path -- nothing else shifts with the mode. + Map expected = expectedBase(); + expected.put("PROOT_LOADER", new File(nativeDir, "libproot-loader.so").getAbsolutePath()); + expected.put(ProotEnvironment.NO_SECCOMP, "1"); + assertEquals(expected, disabled); + } +} diff --git a/controller/app/src/test/java/org/iiab/controller/proot/domain/CapabilityKeyTest.java b/controller/app/src/test/java/org/iiab/controller/proot/domain/CapabilityKeyTest.java new file mode 100644 index 000000000..ac81dfc8e --- /dev/null +++ b/controller/app/src/test/java/org/iiab/controller/proot/domain/CapabilityKeyTest.java @@ -0,0 +1,75 @@ +package org.iiab.controller.proot.domain; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +/** + * Unit tests for {@link CapabilityKey} — ADFA-5362. + * + *

This is the rule that stops a remembered verdict from outliving what it was true about. Its + * failure mode is silent — a healthy device left permanently slower, with nothing to notice — so + * the cases below are mostly about the key changing when it must. + */ +public class CapabilityKeyTest { + + /** The affected device this feature was built against. */ + private static final String OS = "Nokia/TA-1039_00WW/PLE:9/PKQ1.181105.001/00WW_6_19F:user/release-keys"; + private static final String KERNEL = "3.18.120-perf"; + private static final int APP = 600; + + private static String key() { + return CapabilityKey.of(OS, KERNEL, APP); + } + + @Test + public void theSameDeviceAndBuildKeepsTheSameKey() { + assertEquals(key(), CapabilityKey.of(OS, KERNEL, APP)); + assertTrue(CapabilityKey.holds(key(), key())); + } + + @Test + public void anOsUpdateRetiresTheVerdict() { + // A vendor update can fix the kernel; the old "cannot use seccomp" must not survive it. + String afterUpdate = CapabilityKey.of( + "Nokia/TA-1039_00WW/PLE:10/QKQ1.190910.002/00WW_7_01A:user/release-keys", KERNEL, APP); + assertNotEquals(key(), afterUpdate); + assertFalse(CapabilityKey.holds(key(), afterUpdate)); + } + + @Test + public void aKernelChangeRetiresTheVerdict() { + assertFalse(CapabilityKey.holds(key(), CapabilityKey.of(OS, "4.14.356", APP))); + } + + @Test + public void aNewAppVersionRetiresTheVerdict() { + // A new APK can carry a different proot, so the old answer no longer describes the pairing. + assertFalse(CapabilityKey.holds(key(), CapabilityKey.of(OS, KERNEL, APP + 1))); + } + + @Test + public void nothingStoredIsNotAMatch() { + assertFalse(CapabilityKey.holds(null, key())); + assertFalse(CapabilityKey.holds("", key())); + } + + @Test + public void missingPlatformValuesStillProduceADistinguishingKey() { + // os.version is nullable in principle. An absent component must not collapse two different + // devices onto one key -- that would apply one device's verdict to another OS build. + String noKernel = CapabilityKey.of(OS, null, APP); + String noKernelOtherOs = CapabilityKey.of("Other/device:9/BUILD:user/release-keys", null, APP); + assertNotEquals(noKernel, noKernelOtherOs); + assertFalse(CapabilityKey.holds(noKernel, noKernelOtherOs)); + } + + @Test + public void anUnknownComponentDoesNotMatchARealOne() { + // "learned before the kernel was readable" must not be reused once it is readable. + assertFalse(CapabilityKey.holds(CapabilityKey.of(OS, null, APP), key())); + } +} diff --git a/controller/app/src/test/java/org/iiab/controller/proot/domain/SeccompFailureTest.java b/controller/app/src/test/java/org/iiab/controller/proot/domain/SeccompFailureTest.java new file mode 100644 index 000000000..f66acde13 --- /dev/null +++ b/controller/app/src/test/java/org/iiab/controller/proot/domain/SeccompFailureTest.java @@ -0,0 +1,71 @@ +package org.iiab.controller.proot.domain; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +/** + * Unit tests for {@link SeccompFailure} — ADFA-5362. + * + *

The verdict this rule produces is cached and slows the device down for as long as it stands, + * so the tests that matter most are the ones proving it does not fire: an ordinary failed + * install must not be mistaken for a broken kernel. + */ +public class SeccompFailureTest { + + /** Verbatim from an affected device (Android 9, kernel 3.18.120). */ + private static final String REAL_ABORT = + "\n./tracee/event.c:684: int handle_tracee_event(Tracee *, int): " + + "assertion \"IS_IN_SYSENTER(tracee)\" failed\n" + + "proot warning: signal 6 received from process 31814\n"; + + /** proot's other documented seccomp diagnostic, from the strings in the shipped binary. */ + private static final String PROOT_ADVICE = + "It seems your kernel contains this bug: " + + "https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1202161\n" + + "To workaround it, set the env. variable PROOT_NO_SECCOMP to 1.\n"; + + @Test + public void recognisesTheAbortSeenOnAnAffectedDevice() { + assertTrue(SeccompFailure.isSeccompAbort(1, REAL_ABORT)); + } + + @Test + public void recognisesProotsOwnWorkaroundAdvice() { + assertTrue(SeccompFailure.isSeccompAbort(1, PROOT_ADVICE)); + } + + @Test + public void anExitCodeAloneIsNeverEnough() { + // The whole point of a marker: a failing install, a bad command, a missing rootfs all exit + // non-zero and fast. None of them may cost the device its seccomp acceleration for good. + assertFalse(SeccompFailure.isSeccompAbort(1, "")); + assertFalse(SeccompFailure.isSeccompAbort(127, "bash: pdsm: command not found\n")); + assertFalse(SeccompFailure.isSeccompAbort(2, "tar: /library: Cannot open: No such file\n")); + assertFalse(SeccompFailure.isSeccompAbort(137, "Killed\n")); + } + + @Test + public void aSuccessfulRunIsNeverAnAbortWhateverItPrinted() { + // proot warns about bindings it cannot sanitize and still works; exit 0 settles it. + assertFalse(SeccompFailure.isSeccompAbort(0, REAL_ABORT)); + assertFalse(SeccompFailure.isSeccompAbort(0, PROOT_ADVICE)); + } + + @Test + public void toleratesNoOutput() { + assertFalse(SeccompFailure.isSeccompAbort(1, null)); + } + + @Test + public void findsTheMarkerInATailOfANoisyInstall() { + // What the engine actually passes: the last few KB of a long run, marker at the end. + StringBuilder noisy = new StringBuilder(); + for (int i = 0; i < 200; i++) { + noisy.append("TASK [iiab : install something] ***\n"); + } + noisy.append(REAL_ABORT); + assertTrue(SeccompFailure.isSeccompAbort(1, noisy.toString())); + } +}