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
31 changes: 26 additions & 5 deletions controller/app/src/main/java/org/iiab/controller/TarExtractor.java
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,28 @@ public void startExtraction(Context context, String archivePath, String destDir,
// bail out (without extracting anything) if any member is absolute
// or climbs out of destDir via "..". An imported/restored backup is
// untrusted, so this runs for every extraction.
// K2GO-372: identity before the listing pass. The listing below is irreducible —
// the traversal guard has to see every member name — but it costs a full pass over
// the archive, and a wrong-ABI or non-rootfs file used to be rejected only after
// paying for it. The manifest that answers identity is packed first, so reading it
// here refuses the same files in about a second, and leaves the long pass for
// archives that are actually going to be extracted.
// K2GO-372: DeepOpService runs this same check on the picked stream before it copies,
// purely to avoid paying for a copy it will throw away. This one is not a duplicate of
// it: this is the fail-closed gate every caller shares (import, install, restore), it
// judges the artifact actually about to be extracted, and both delegate to the one rule
// in RootfsIdentity. Deleting either does not make the other cover it.
if (validateRootfs) {
org.iiab.controller.deploy.data.RootfsArchiveValidator.Result early =
org.iiab.controller.deploy.data.RootfsArchiveValidator.identityRejection(
org.iiab.controller.deploy.data.RootfsManifest.read(archivePath));
String why = org.iiab.controller.deploy.data.RootfsArchiveValidator
.rejectionMessage(context, early);
if (why != null) {
throw new Exception(why);
}
}

List<String> entries = listEntries(tarBinary, archivePath, isGzip, listener);
for (String entry : entries) {
if (ArchiveEntry.escapesRoot(entry)) {
Expand All @@ -132,11 +154,10 @@ public void startExtraction(Context context, String archivePath, String destDir,
org.iiab.controller.deploy.data.RootfsArchiveValidator.Result vr =
org.iiab.controller.deploy.data.RootfsArchiveValidator
.validateWithEntries(context, archivePath, isGzip, tarBinary, entries);
if (vr == org.iiab.controller.deploy.data.RootfsArchiveValidator.Result.NOT_A_ROOTFS) {
throw new Exception(context.getString(R.string.install_error_not_rootfs));
}
if (vr == org.iiab.controller.deploy.data.RootfsArchiveValidator.Result.WRONG_ARCH) {
throw new Exception(context.getString(R.string.install_error_wrong_arch));
String why = org.iiab.controller.deploy.data.RootfsArchiveValidator
.rejectionMessage(context, vr);
if (why != null) {
throw new Exception(why);
}
}

Expand Down

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,12 @@
import org.iiab.controller.deploy.domain.ElfClass;
import org.iiab.controller.deploy.domain.RootfsArchive;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.zip.GZIPInputStream;

/**
Expand Down Expand Up @@ -53,22 +50,49 @@ private RootfsArchiveValidator() {
// Static utility; not instantiable.
}

/** Validate from a file path (lists the archive itself; use for the import gate). */
public static Result validate(Context context, String archivePath) {
try {
String tarBinary = resolveTar(context);
boolean isGzip = archivePath.toLowerCase(Locale.US).endsWith(".gz");
List<String> entries = listEntries(tarBinary, archivePath, isGzip);
if (entries.isEmpty()) {
return Result.UNREADABLE;
}
return validateWithEntries(context, archivePath, isGzip, tarBinary, entries, true);
} catch (Exception e) {
Log.e(TAG, "Validation error", e);
return Result.UNREADABLE;
/**
* K2GO-372: the manifest's rejection, if any — a thin adapter over the pure rule in
* {@link org.iiab.controller.deploy.domain.RootfsIdentity}, which is where the decision lives
* and where it is tested. This half supplies the two things the rule cannot know on its own:
* the running app's ABI, and how a domain verdict maps onto {@link Result}.
*
* <p>Worth calling before the listing pass: the manifest is packed first, so this reads a few
* KB, while the listing reads the whole archive.
*
* @return the rejecting {@link Result}, or {@code null} when the manifest does not reject.
*/
public static Result identityRejection(RootfsManifest.Identity id) {
org.iiab.controller.deploy.domain.RootfsIdentity.Verdict v =
org.iiab.controller.deploy.domain.RootfsIdentity.check(
id != null && id.present,
id == null ? null : id.kind,
id == null ? null : id.arch,
RootfsManifest.appAbiId());
switch (v) {
case NOT_A_ROOTFS: return Result.NOT_A_ROOTFS;
case WRONG_ARCH: return Result.WRONG_ARCH;
default: return null;
}
}

/**
* K2GO-372: the reason to show for a rejecting {@link Result}, or {@code null} when it does not
* reject. Both extractor gates and the restore's pre-copy check spell the same verdicts, and they
* used to each carry their own if-chain of strings.
*
* <p>Note it rejects {@link Result#CORRUPT} too, which the extractor's two inline chains did not:
* failing closed on a failed integrity check is the right direction, and it is inert on today's
* callers (the extractor validates with {@code checkIntegrity=false}, where CORRUPT cannot arise).
* {@link Result#UNREADABLE} is deliberately NOT a rejection here — see the callers; that gap
* predates this method.
*/
public static String rejectionMessage(Context ctx, Result r) {
if (r == Result.NOT_A_ROOTFS) return ctx.getString(org.iiab.controller.R.string.install_error_not_rootfs);
if (r == Result.WRONG_ARCH) return ctx.getString(org.iiab.controller.R.string.install_error_wrong_arch);
if (r == Result.CORRUPT) return ctx.getString(org.iiab.controller.R.string.install_error_corrupt);
return null;
}

/**
* Validate when the caller already has the entry listing (e.g. {@code TarExtractor}
* lists once for the D11 traversal guard — reuse it here, no second listing).
Expand All @@ -93,14 +117,11 @@ public static Result validateWithEntries(Context context, String archivePath,
// (installed-rootfs/iiab/.iiab-rootfs.json, packed first). See
// docs/ROOTFS_MANIFEST.md. When present it decides kind + arch.
RootfsManifest.Identity id = RootfsManifest.read(archivePath);
Result rejection = identityRejection(id);
if (rejection != null) {
return rejection;
}
if (id.present) {
if (!"iiab-rootfs".equals(id.kind)) {
return Result.NOT_A_ROOTFS;
}
if (id.arch != null && !id.arch.isEmpty()
&& !id.arch.equals(RootfsManifest.appAbiId())) {
return Result.WRONG_ARCH;
}
// Identity is authoritative for kind+arch. Now decide integrity.
if ("device-backup".equals(id.origin)) {
// App-made backup: no checksum by design (we don't turn the
Expand Down Expand Up @@ -148,38 +169,6 @@ public static Result validateWithEntries(Context context, String archivePath,
}
}

private static String resolveTar(Context context) {
File staticTar = new File(context.getApplicationInfo().nativeLibraryDir, "libtar.so");
return staticTar.exists() ? staticTar.getAbsolutePath() : "/system/bin/tar";
}

private static List<String> listEntries(String tarBinary, String archivePath, boolean isGzip) throws Exception {
List<String> names = new ArrayList<>();
List<String> cmd = new ArrayList<>();
cmd.add(tarBinary);
if (isGzip) {
cmd.add("-t");
cmd.add("-f");
cmd.add("-");
} else {
cmd.add("-tf");
cmd.add(archivePath);
}
Process p = new ProcessBuilder(cmd).start();
Thread feeder = isGzip ? startGzipFeeder(archivePath, p.getOutputStream()) : null;
try (BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
String line;
while ((line = r.readLine()) != null) {
names.add(line);
}
}
p.waitFor();
if (feeder != null) {
feeder.join();
}
return names;
}

private static byte[] readMemberHeader(String tarBinary, String archivePath, boolean isGzip,
String member, int n) throws Exception {
List<String> cmd = new ArrayList<>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,21 @@ public static String appAbiId() {
/** Read the identity manifest from {@code archivePath}, or {@link Identity#absent()}. */
public static Identity read(String archivePath) {
boolean isGzip = archivePath.toLowerCase(Locale.US).endsWith(".gz");
try (InputStream raw = new FileInputStream(archivePath);
InputStream in = isGzip ? new GZIPInputStream(raw) : new BufferedInputStream(raw)) {
try (InputStream raw = new FileInputStream(archivePath)) {
return read(raw, isGzip);
} catch (Exception e) {
Log.w(TAG, "Could not read identity manifest: " + e.getMessage());
return Identity.absent();
}
}

/**
* K2GO-372: the same read from an already-open stream, so a file can be judged before it is copied
* anywhere. Only the first few KB are consumed — the manifest is the first member — but the stream
* is closed here either way, since a caller that has its verdict has no use for the rest.
*/
public static Identity read(InputStream raw, boolean isGzip) {
try (InputStream in = isGzip ? new GZIPInputStream(raw) : new BufferedInputStream(raw)) {

byte[] header = new byte[512];
for (int i = 0; i < MAX_HEADERS; i++) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,16 +49,33 @@ public static long etaSeconds(long done, long total, long ratePerSec) {
}

/**
* ADFA-5118: map a single pass's percent onto the unified two-pass bar. Verify owns
* [0,50), extract owns [50,100). {@code passPercent} is that pass's own 0..100; it is
* clamped, halved, and offset by 50 for the second pass. The result is capped at 99 so
* only true completion (set by the caller) reaches 100. This keeps the bar monotone
* across the handoff: verify ends near 49, extract starts at 50.
* ADFA-5118: map a single pass's percent onto the unified two-pass bar — the shape the rootfs
* install runs. Verify owns [0,50), extract owns [50,100). The result is capped at 99 so only
* true completion (set by the caller) reaches 100, which keeps the bar monotone across the
* handoff: verify ends near 49, extract starts at 50.
*/
public static int unifiedPercent(int passPercent, boolean secondPass) {
return unifiedPercent(passPercent, secondPass ? 1 : 0, 2);
}

/**
* K2GO-372: the same rule for a run of any number of passes, because a restore has three — it
* stages the picked file before it verifies and extracts it. Each pass owns an equal slice of the
* bar, so no pass can fill the bar and send it back to zero, which is the whole point of a unified
* percent. Slices are equal, not time-weighted: the passes' durations depend on the device and the
* archive, and a bar that lies about which slice is long is worse than one that moves unevenly.
*
* @param passPercent this pass's own 0-100 progress.
* @param passIndex which pass is running, from 0.
* @param passCount how many passes the whole run has.
*/
public static int unifiedPercent(int passPercent, int passIndex, int passCount) {
if (passCount < 1) passCount = 1;
if (passIndex < 0) passIndex = 0;
if (passIndex > passCount - 1) passIndex = passCount - 1;
if (passPercent < 0) passPercent = 0;
if (passPercent > 100) passPercent = 100;
int v = (secondPass ? 50 : 0) + passPercent / 2;
int v = (passIndex * 100 + passPercent) / passCount;
return v > 99 ? 99 : v;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/*
* ============================================================================
* Name : RootfsIdentity.java
* Author : AppDevForAll
* Copyright : Copyright (c) 2026 AppDevForAll
* Description : K2GO-372. Is this archive a rootfs, and is it ours to unpack?
* ============================================================================
*/
package org.iiab.controller.deploy.domain;

/**
* The identity half of the archive verdict: what the manifest alone can settle.
*
* <p>Separate from the rest of validation because it is answerable from a few KB — the manifest is
* packed first — while the structural checks need the whole archive listed. Splitting it lets a
* caller reject the wrong file before paying for a full decompression pass, which on a phone is
* the difference between a one-second refusal and a five-minute one.
*
* <p>Pure: the ABI to compare against is passed in rather than read from {@code android.os}, so the
* rule is unit-tested on the JVM instead of only on a device.
*/
public final class RootfsIdentity {

/** What the manifest says about whether this archive may be unpacked here. */
public enum Verdict {
/** Nothing to reject: identity checks out, or there is no manifest to ask. */
OK,
/** The manifest says this is not a rootfs at all. */
NOT_A_ROOTFS,
/** A rootfs, but built for a different ABI than this app runs. */
WRONG_ARCH
}

/** The kind every rootfs manifest declares; anything else is a different sort of archive. */
private static final String KIND_ROOTFS = "iiab-rootfs";

private RootfsIdentity() {
}

/**
* Decide whether the manifest rejects this archive.
*
* <p>An absent manifest is {@link Verdict#OK} rather than a rejection: older archives predate
* it, and refusing them here would turn a missing hint into a hard failure. The structural
* fallback decides those.
*
* <p>An empty or absent {@code arch} is likewise not a rejection — the manifest simply does not
* claim one, so there is nothing to contradict.
*
* @param present whether the archive carried a manifest at all.
* @param kind the manifest's declared kind.
* @param arch the manifest's declared ABI.
* @param appAbi the ABI this app runs as; the archive must match it to be unpackable.
*/
public static Verdict check(boolean present, String kind, String arch, String appAbi) {
if (!present) {
return Verdict.OK;
}
if (!KIND_ROOTFS.equals(kind)) {
return Verdict.NOT_A_ROOTFS;
}
if (arch != null && !arch.isEmpty() && appAbi != null && !arch.equals(appAbi)) {
return Verdict.WRONG_ARCH;
}
return Verdict.OK;
}
}
Loading
Loading