generated from ali/HarmonyTemplate
提交 Haven Android 仓库源码 v5.87.79
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
// Deliberately dependency-free. LogRedact is needed by leaf modules (serial, SMB,
|
||||
// Reticulum) that have no project dependencies at all, and making them pull in
|
||||
// :core:data — Room, DataStore, Hilt — to redact a hostname would be a poor
|
||||
// trade. Keep it that way: nothing in here should ever need a dependency.
|
||||
plugins {
|
||||
alias(libs.plugins.android.library)
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "sh.haven.core.redact"
|
||||
compileSdk = 37
|
||||
|
||||
defaultConfig {
|
||||
minSdk = 26
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
testImplementation(libs.junit)
|
||||
}
|
||||
|
||||
kotlin {
|
||||
compilerOptions {
|
||||
jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package sh.haven.core.redact
|
||||
|
||||
import java.security.MessageDigest
|
||||
import java.security.SecureRandom
|
||||
|
||||
/**
|
||||
* Short, stable stand-ins for values that must not reach logcat (#518).
|
||||
*
|
||||
* Haven logged hostnames, ports, usernames, profile labels and SSH key labels in
|
||||
* plain text. Since Android 4.1 another app cannot read our logcat, so the
|
||||
* exposure is not silent harvesting — it is **sharing**. `adb logcat` and
|
||||
* `adb bugreport` capture it, Haven shows logcat in Settings and over MCP, and
|
||||
* v5.87.3 actively asks users to paste crash reports into bug tickets. #518 was
|
||||
* filed by someone who had to hand-redact their own log to file it safely, which
|
||||
* is the whole argument in one sentence.
|
||||
*
|
||||
* Deleting the log lines was the alternative and is worse: knowing *which*
|
||||
* connection failed, and in what order, is most of what makes a support log
|
||||
* usable. A token preserves that and reveals nothing.
|
||||
*
|
||||
* ★ **Salted per process, on purpose.** Hostnames have very little entropy —
|
||||
* an unsalted hash of "192.168.1.10" or "github.com" falls to a wordlist in
|
||||
* seconds, so a bare digest would be redaction in appearance only. A random
|
||||
* per-process salt means tokens correlate within one log (which is what a
|
||||
* debugger needs) and are useless outside it. The cost is that the same host
|
||||
* reads differently across app restarts; that is the right trade.
|
||||
*
|
||||
* This is not anonymisation of a data set. It stops values being *transcribed*
|
||||
* into a log that gets shared. Someone who already knows the candidate hosts and
|
||||
* has the same running process could confirm a guess — offline, after the fact,
|
||||
* they cannot.
|
||||
*/
|
||||
object LogRedact {
|
||||
|
||||
private val salt: ByteArray = ByteArray(16).also { SecureRandom().nextBytes(it) }
|
||||
|
||||
/**
|
||||
* An 8-character token for [value], stable for this process.
|
||||
*
|
||||
* Null and blank map to fixed markers rather than a token, because "there was
|
||||
* no hostname" and "there was a hostname I am not showing you" are different
|
||||
* facts and a log that conflates them wastes the reader's time.
|
||||
*/
|
||||
fun of(value: String?): String {
|
||||
if (value == null) return "<null>"
|
||||
if (value.isBlank()) return "<blank>"
|
||||
val digest = MessageDigest.getInstance("SHA-256").apply {
|
||||
update(salt)
|
||||
update(value.toByteArray())
|
||||
}.digest()
|
||||
val hex = StringBuilder(TOKEN_CHARS)
|
||||
for (i in 0 until TOKEN_CHARS / 2) {
|
||||
hex.append(HEX[(digest[i].toInt() shr 4) and 0xF])
|
||||
hex.append(HEX[digest[i].toInt() and 0xF])
|
||||
}
|
||||
return "~$hex"
|
||||
}
|
||||
|
||||
/**
|
||||
* A host, and its port only when it is not the well-known one for the scheme.
|
||||
*
|
||||
* The port is included because it is weak on its own and genuinely useful
|
||||
* when diagnosing a connection — but it is attached to a redacted host, so it
|
||||
* does not identify a machine by itself.
|
||||
*/
|
||||
fun host(host: String?, port: Int? = null): String =
|
||||
if (port == null) of(host) else "${of(host)}:$port"
|
||||
|
||||
private const val TOKEN_CHARS = 8
|
||||
private val HEX = "0123456789abcdef".toCharArray()
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package sh.haven.core.redact
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* #518 — hostnames, ports, usernames and profile labels were written to logcat
|
||||
* in plain text, and a user filing a bug had to hand-redact their own log.
|
||||
*
|
||||
* The properties that matter are that the value does not survive into the token,
|
||||
* and that the token is still stable enough to follow a connection through a log.
|
||||
*/
|
||||
class LogRedactTest {
|
||||
|
||||
@Test
|
||||
fun `the original value never appears in the token`() {
|
||||
val secrets = listOf(
|
||||
"bastion.internal.example.com",
|
||||
"192.168.1.10",
|
||||
"root",
|
||||
"work — prod db (bob@example.com)",
|
||||
)
|
||||
for (secret in secrets) {
|
||||
val token = LogRedact.of(secret)
|
||||
assertFalse("token leaked the value: $token", token.contains(secret))
|
||||
// Also guard against a partial leak — a substring long enough to guess from.
|
||||
for (part in secret.split(".", " ", "@").filter { it.length >= 4 }) {
|
||||
assertFalse(
|
||||
"token leaked the fragment '$part': $token",
|
||||
token.contains(part, ignoreCase = true),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Two log lines about the same host must be tied together, or the log is useless. */
|
||||
@Test
|
||||
fun `the same value gives the same token within a process`() {
|
||||
assertEquals(LogRedact.of("host.example.com"), LogRedact.of("host.example.com"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `different values give different tokens`() {
|
||||
assertNotEquals(LogRedact.of("host-a.example.com"), LogRedact.of("host-b.example.com"))
|
||||
}
|
||||
|
||||
/**
|
||||
* "No hostname" and "a hostname I'm not showing you" are different facts;
|
||||
* collapsing them wastes the reader's time.
|
||||
*/
|
||||
@Test
|
||||
fun `null and blank are distinguishable and are not tokens`() {
|
||||
assertEquals("<null>", LogRedact.of(null))
|
||||
assertEquals("<blank>", LogRedact.of(""))
|
||||
assertEquals("<blank>", LogRedact.of(" "))
|
||||
assertNotEquals(LogRedact.of(null), LogRedact.of("null"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `tokens are short and visibly redacted`() {
|
||||
val token = LogRedact.of("something.example.com")
|
||||
assertTrue("should be marked as a token: $token", token.startsWith("~"))
|
||||
assertEquals("~ plus 8 hex chars", 9, token.length)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `host keeps the port but redacts the host`() {
|
||||
val withPort = LogRedact.host("db.example.com", 2222)
|
||||
assertFalse(withPort.contains("db.example.com"))
|
||||
assertTrue("the port is useful and not identifying on its own", withPort.endsWith(":2222"))
|
||||
assertEquals(LogRedact.of("db.example.com"), LogRedact.host("db.example.com"))
|
||||
}
|
||||
|
||||
/**
|
||||
* The salt is what makes this more than decoration: hostnames have so little
|
||||
* entropy that an unsalted digest of "192.168.1.10" falls to a wordlist. A
|
||||
* token must therefore NOT match the bare SHA-256 of its input.
|
||||
*/
|
||||
@Test
|
||||
fun `tokens are not a bare digest of the value`() {
|
||||
val value = "192.168.1.10"
|
||||
val bare = java.security.MessageDigest.getInstance("SHA-256")
|
||||
.digest(value.toByteArray())
|
||||
.joinToString("") { "%02x".format(it) }
|
||||
.take(8)
|
||||
assertNotEquals("unsalted digest would be trivially reversible", "~$bare", LogRedact.of(value))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
package sh.haven.core.redact
|
||||
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* #518 — a source scan asserting that hostnames, ports, usernames and
|
||||
* user-chosen labels do not reach `Log.*` unredacted.
|
||||
*
|
||||
* The fix for #518 was ~50 call sites across 15 modules. Fixing them once is
|
||||
* easy; keeping them fixed is not, because the natural way to write the next log
|
||||
* line is `Log.d(TAG, "connecting to $host")` and nothing would object. This is
|
||||
* the thing that objects.
|
||||
*
|
||||
* It reads the repository's Kotlin sources rather than inspecting behaviour,
|
||||
* which is unusual for a unit test and deliberate: the property being protected
|
||||
* is a property of the source, and there is no runtime moment at which "someone
|
||||
* wrote a leaky log statement" can be observed.
|
||||
*
|
||||
* Scope is honest about what it can catch. It matches the interpolation forms
|
||||
* that leaked in #518 — `$host`, `${profile.label}`, `${config.host}:${port}` —
|
||||
* and will not catch a value laundered through an intermediate variable with an
|
||||
* innocuous name. It is a ratchet against the common case, not a proof.
|
||||
*/
|
||||
class NoRawPiiInLogsTest {
|
||||
|
||||
/** Names that hold a hostname, address, port pair, username or user-chosen label. */
|
||||
private val sensitiveBare = listOf("host", "hostname", "ip", "newHost", "username")
|
||||
private val sensitiveProps = listOf("host", "hostname", "label", "username", "user")
|
||||
|
||||
/**
|
||||
* Values that are NOT user data despite matching the shape:
|
||||
* de.label / spec.label — a desktop environment ("XFCE") or a built-in
|
||||
* guest service, both from Haven's own catalogue.
|
||||
*/
|
||||
private val allowedReceivers = setOf("de", "spec")
|
||||
|
||||
private val logCall = Regex("""\bLog\.[dviwe]\(""")
|
||||
|
||||
private fun sourceRoots(): List<File> {
|
||||
// Walk up to the repository root, then take the module source trees.
|
||||
var dir = File(".").absoluteFile
|
||||
while (dir.parentFile != null && !File(dir, "settings.gradle.kts").exists()) {
|
||||
dir = dir.parentFile
|
||||
}
|
||||
// termlib is in this list because leaving it out is how #518 stayed open.
|
||||
// The original sweep covered app/core/feature, and the keystroke leak was
|
||||
// in termlib's ImeInputView — every character the user typed, reported
|
||||
// from a real logcat that reconstructed a shell session letter by letter.
|
||||
// A guard that does not cover the module holding the input path is not
|
||||
// guarding the input path.
|
||||
return listOf("app", "core", "feature", "termlib")
|
||||
.map { File(dir, it) }
|
||||
.filter { it.isDirectory }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `no raw hostname username or label reaches a log call`() {
|
||||
val offenders = mutableListOf<String>()
|
||||
|
||||
for (root in sourceRoots()) {
|
||||
root.walkTopDown()
|
||||
.filter { it.isFile && it.extension == "kt" }
|
||||
.filterNot { it.path.contains("/build/") }
|
||||
.filterNot { it.path.contains("/test/") || it.path.contains("/androidTest/") }
|
||||
// `src/debug` is a build-type source set: AGP compiles it into
|
||||
// debug builds only, so none of it reaches a release APK or a
|
||||
// user's logs. DebugReceiver exists precisely to dump state on a
|
||||
// developer's own device, and redacting it would defeat the
|
||||
// point. Excluded deliberately, not overlooked — this is the one
|
||||
// carve-out, and it is justified by the code never shipping.
|
||||
.filterNot { it.path.contains("/src/debug/") }
|
||||
.forEach { file ->
|
||||
file.readLines().forEachIndexed { index, line ->
|
||||
if (!logCall.containsMatchIn(line)) return@forEachIndexed
|
||||
if (line.contains("LogRedact.")) {
|
||||
// Partially redacted lines still need checking for a
|
||||
// second, unredacted value on the same line.
|
||||
}
|
||||
for (name in sensitiveBare) {
|
||||
// `$host` but not `$hostname`, and not `${LogRedact.of(host)}`.
|
||||
val bare = Regex("""\$$name\b(?!\w)""")
|
||||
if (bare.containsMatchIn(line.replace(Regex("""LogRedact\.\w+\([^)]*\)"""), ""))) {
|
||||
offenders += "${file.path}:${index + 1}: \$$name — ${line.trim()}"
|
||||
}
|
||||
}
|
||||
for (prop in sensitiveProps) {
|
||||
val propRe = Regex("""\$\{(\w+)\.$prop\}""")
|
||||
for (m in propRe.findAll(
|
||||
line.replace(Regex("""LogRedact\.\w+\([^)]*\)"""), ""),
|
||||
)) {
|
||||
val receiver = m.groupValues[1]
|
||||
if (receiver !in allowedReceivers) {
|
||||
offenders += "${file.path}:${index + 1}: \${$receiver.$prop} — ${line.trim()}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assertTrue(
|
||||
"Sensitive values reach Log.* unredacted (#518). Wrap them in " +
|
||||
"LogRedact.of(...) / LogRedact.host(host, port), or if the value is " +
|
||||
"genuinely not user data add its receiver to allowedReceivers with a " +
|
||||
"reason:\n" + offenders.joinToString("\n"),
|
||||
offenders.isEmpty(),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* What the user typed must not reach a log call either (#518, second round).
|
||||
*
|
||||
* The original sweep looked for hostnames, usernames and labels. It did not
|
||||
* occur to me that the input path logs the text itself, and a reporter
|
||||
* reconstructed a shell session from logcat character by character —
|
||||
* `commitText("e")`, `unicode=101` — noting that a sudo password typed into a
|
||||
* session would be captured the same way.
|
||||
*
|
||||
* `unicodeChar` and `KeyEvent.keyCode` each identify the key pressed, so on a
|
||||
* log line they are the payload, not metadata. Truncating text with `take(n)`
|
||||
* inside a log call is the other tell: it limits the size of the leak, not
|
||||
* the fact of it.
|
||||
*
|
||||
* Content may still be logged behind an explicit opt-in
|
||||
* (`Log.isLoggable(TAG, VERBOSE)`, set by a developer with `setprop`), which
|
||||
* is why `logContent` is allowed on these lines.
|
||||
*/
|
||||
@Test
|
||||
fun `no typed text or key identity reaches a log call`() {
|
||||
val offenders = mutableListOf<String>()
|
||||
|
||||
// `take(n)` cuts both ways. A small n is the redaction idiom — the first
|
||||
// 6 characters of a client id, 8 of a hash — deliberately showing enough
|
||||
// to correlate and not enough to identify. A large n is content being
|
||||
// truncated for the log, which limits the size of a leak rather than
|
||||
// preventing one. 16 is the line between the two here.
|
||||
val truncatedContent = Regex("""\.take\((\d+)\)""")
|
||||
val abbreviationLimit = 16
|
||||
|
||||
// Program diagnostics rather than anything the user typed: a subprocess's
|
||||
// own stderr/stdout, which is the entire reason those lines exist.
|
||||
val diagnosticStreams = listOf("stderr", "stdout", "probeOut", "output")
|
||||
|
||||
// Values whose prefix IS the intended log output: an identifier or a
|
||||
// digest, shortened to correlate without identifying. A TLS certificate
|
||||
// fingerprint is the server's, public, and printed on purpose. These are
|
||||
// the opposite of a leak and must not be nudged out by the length rule.
|
||||
val abbreviatedIdentifiers = listOf("sha256", "hash", "clientId", "fingerprint", "digest")
|
||||
|
||||
for (root in sourceRoots()) {
|
||||
root.walkTopDown()
|
||||
.filter { it.isFile && it.extension == "kt" }
|
||||
.filterNot { it.path.contains("/build/") }
|
||||
.filterNot { it.path.contains("/test/") || it.path.contains("/androidTest/") }
|
||||
.filterNot { it.path.contains("/src/debug/") }
|
||||
.forEach { file ->
|
||||
file.readLines().forEachIndexed { index, line ->
|
||||
if (!logCall.containsMatchIn(line)) return@forEachIndexed
|
||||
// Gated behind the developer opt-in, or routed through the
|
||||
// helper that honours it.
|
||||
if (line.contains("logContent") || line.contains("quoteForLog")) {
|
||||
return@forEachIndexed
|
||||
}
|
||||
for (needle in listOf("unicodeChar", ".keyCode")) {
|
||||
if (line.contains(needle)) {
|
||||
offenders += "${file.path}:${index + 1}: $needle — ${line.trim()}"
|
||||
}
|
||||
}
|
||||
if ((diagnosticStreams + abbreviatedIdentifiers).any { line.contains("$it.take(") }) {
|
||||
return@forEachIndexed
|
||||
}
|
||||
truncatedContent.findAll(line).forEach { m ->
|
||||
val n = m.groupValues[1].toIntOrNull() ?: 0
|
||||
if (n >= abbreviationLimit) {
|
||||
offenders += "${file.path}:${index + 1}: take($n) — ${line.trim()}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assertTrue(
|
||||
"Typed text or key identity reaches Log.* (#518). Gate it behind " +
|
||||
"Log.isLoggable(TAG, VERBOSE) or route it through a helper that " +
|
||||
"does, and log lengths/flags unconditionally instead:\n" +
|
||||
offenders.joinToString("\n"),
|
||||
offenders.isEmpty(),
|
||||
)
|
||||
}
|
||||
|
||||
/** The scan is worthless if it is looking at nothing — prove it found sources. */
|
||||
@Test
|
||||
fun `the scan actually reads the repository sources`() {
|
||||
val kotlinFiles = sourceRoots().sumOf { root ->
|
||||
root.walkTopDown().count {
|
||||
it.isFile && it.extension == "kt" && !it.path.contains("/build/")
|
||||
}
|
||||
}
|
||||
assertTrue(
|
||||
"found only $kotlinFiles Kotlin files — the scan is not looking where it thinks",
|
||||
kotlinFiles > 200,
|
||||
)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user