Skip to content
Closed
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ The daemon part of MSD runs as the `system` user and with the `CAP_CHOWN` capabi

When setting up mass storage devices, the daemon never opens files on its own. The app opens files itself and then sends the open file descriptor the daemon over a Unix socket. This way, even if a malicious client happened to be able to connect to the daemon, it can't expose files over mass storage devices that it didn't already have access to.

The daemon relies on SELinux for access control. If it detects certain scenarios where SELinux is not configured correctly, it will reject connections from all clients to avoid opening a security hole.
The app runs in Android's stock `untrusted_app` domain. The daemon authenticates clients using their kernel-reported UID and installed APK signing certificate, with Package Manager queries handled by a root supervisor. The daemon retains its restricted `msd_daemon` domain and SELinux safety checks.

## Advanced features

Expand Down
25 changes: 24 additions & 1 deletion app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import org.eclipse.jgit.lib.ObjectId
import org.gradle.kotlin.dsl.support.uppercaseFirstChar
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
import org.json.JSONObject
import java.security.KeyStore
import java.security.MessageDigest

plugins {
alias(libs.plugins.android.application)
Expand Down Expand Up @@ -381,13 +383,33 @@ androidComponents.onVariants { variant ->
"user=_app",
"isPrivApp=true",
"name=${variant.applicationId.get()}",
"domain=msd_app",
"domain=untrusted_app",
"type=app_data_file",
"levelFrom=all",
).joinToString(" "))
}
}

val clientCertificate = tasks.register("clientCertificate${capitalized}") {
dependsOn("assemble${capitalized}")
val certificateFile = variantDir.map { it.file("client-cert.sha256") }
outputs.file(certificateFile)
// Always recheck the signing configuration rather than reusing a stale pin.
outputs.upToDateWhen { false }
doLast {
val signing = android.buildTypes.getByName(variant.name).signingConfig!!
val store = KeyStore.getInstance(signing.storeType ?: "JKS")
signing.storeFile!!.inputStream().use {
store.load(it, signing.storePassword!!.toCharArray())
}
val digest = MessageDigest.getInstance("SHA-256")
.digest(store.getCertificate(signing.keyAlias!!).encoded)
certificateFile.get().asFile.writeText(digest.joinToString("") {
"%02x".format(it.toInt() and 0xff)
} + "\n")
}
}

tasks.register<Zip>("zip${capitalized}") {
inputs.property("rootProject.name", rootProject.name)
inputs.property("variant.applicationId", variant.applicationId)
Expand All @@ -404,6 +426,7 @@ androidComponents.onVariants { variant ->
isReproducibleFileOrder = true

from(moduleProp.map { it.outputs })
from(clientCertificate.map { it.outputs })
from(configXml.map { it.outputs }) {
into("system/etc/sysconfig")
}
Expand Down
10 changes: 5 additions & 5 deletions app/module/service.sh
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ source "${0%/*}/boot_common.sh" /data/local/tmp/msd/service.log

header Starting daemon

# Full path because Magisk runs this script in busybox's standalone ash mode and
# we need Android's toybox version of runcon.
/system/bin/runcon u:r:msd_daemon:s0 \
"${mod_dir}"/msd-tool."$(getprop ro.product.cpu.abi)" \
daemon --log-target logcat --log-level debug &
# The root supervisor authenticates clients; its child runs in msd_daemon.
CLASSPATH="${cli_apk}" /system/bin/app_process / \
com.chiller3.msd.standalone.AuthenticatedDaemon \
"${mod_dir}/msd-tool.$(getprop ro.product.cpu.abi)" \
"${mod_dir}/client-cert.sha256" &

sleep 1

Expand Down
117 changes: 117 additions & 0 deletions app/src/main/java/com/chiller3/msd/standalone/AuthenticatedDaemon.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
/* SPDX-License-Identifier: GPL-3.0-only */
package com.chiller3.msd.standalone;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.os.Process;
import android.util.Log;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.MessageDigest;

/** Root supervisor. Only the private child pipes carry authentication queries. */
public final class AuthenticatedDaemon {
private static final String TAG = "MSDAuth";
private static final String PACKAGE = "com.chiller3.msd";
private static final int PER_USER_RANGE = 100000;
private final Method checkService;
private final Method asPackageManager;
private final Method packagesForUid;
private final Method packageInfo;
private final boolean longFlags;
private final String certificate;

AuthenticatedDaemon(String certificate) throws Exception {
if (!certificate.matches("[0-9a-f]{64}")) {
throw new IllegalArgumentException("Invalid SHA-256 certificate pin");
}
this.certificate = certificate;
checkService = Class.forName("android.os.ServiceManager")
.getMethod("checkService", String.class);
asPackageManager = Class.forName("android.content.pm.IPackageManager$Stub")
.getMethod("asInterface", android.os.IBinder.class);
Class<?> ipm = Class.forName("android.content.pm.IPackageManager");
packagesForUid = ipm.getMethod("getPackagesForUid", int.class);
Method info;
boolean wide;
try {
info = ipm.getMethod("getPackageInfo", String.class, long.class, int.class);
wide = true;
} catch (NoSuchMethodException e) {
info = ipm.getMethod("getPackageInfo", String.class, int.class, int.class);
wide = false;
}
packageInfo = info;
longFlags = wide;
}

boolean authorize(int uid) throws Exception {
// Reject system/isolated UIDs and shared-UID installations. Match the
// complete UID, not just its appId; query the actual Android user.
int appId = uid % PER_USER_RANGE;
if (uid < 0 || appId < 10000 || appId > 19999) return false;
// Look up the service at query time: late-start can precede Package
// Manager readiness, and a dead Binder must never become a cached allow.
Object binder = checkService.invoke(null, "package");
if (binder == null) return false;
Object packageManager = asPackageManager.invoke(null, binder);
String[] packages = (String[]) packagesForUid.invoke(packageManager, uid);
if (packages == null || packages.length != 1 || !PACKAGE.equals(packages[0])) return false;
Object flags;
if (longFlags) flags = Long.valueOf(PackageManager.GET_SIGNING_CERTIFICATES);
else flags = Integer.valueOf(PackageManager.GET_SIGNING_CERTIFICATES);
PackageInfo info = (PackageInfo) packageInfo.invoke(
packageManager, PACKAGE, flags, uid / PER_USER_RANGE);
if (info == null || !PACKAGE.equals(info.packageName) || info.applicationInfo == null
|| info.applicationInfo.uid != uid || info.sharedUserId != null
|| info.signingInfo == null || info.signingInfo.hasMultipleSigners()) return false;
Signature[] signers = info.signingInfo.getApkContentsSigners();
if (signers == null || signers.length != 1) return false;
byte[] digest = MessageDigest.getInstance("SHA-256").digest(signers[0].toByteArray());
StringBuilder hex = new StringBuilder(64);
for (byte b : digest) hex.append(String.format(java.util.Locale.ROOT, "%02x", b & 0xff));
return certificate.contentEquals(hex);
}

public static void main(String[] args) throws Exception {
if (Process.myUid() != 0) throw new SecurityException("Supervisor must start as root");
if (args.length != 2) throw new IllegalArgumentException("Expected daemon path and certificate file");
String pin = new String(Files.readAllBytes(Paths.get(args[1])), StandardCharsets.US_ASCII).trim();
AuthenticatedDaemon auth = new AuthenticatedDaemon(pin);
// A check-only invocation is useful for device-side negative tests; it
// exercises precisely the same verification used for daemon requests.
if (args[0].startsWith("check:")) {
boolean allowed = auth.authorize(Integer.parseInt(args[0].substring(6)));
System.out.println(allowed ? "ALLOW" : "DENY");
System.exit(allowed ? 0 : 1);
}
java.lang.Process child = new ProcessBuilder(
"/system/bin/runcon", "u:r:msd_daemon:s0", args[0], "daemon",
"--log-target", "logcat", "--log-level", "debug")
.redirectError(java.lang.ProcessBuilder.Redirect.INHERIT).start();
Runtime.getRuntime().addShutdownHook(new Thread(child::destroy));
try (DataInputStream requests = new DataInputStream(child.getInputStream());
DataOutputStream responses = new DataOutputStream(child.getOutputStream())) {
while (true) {
int uid;
try { uid = requests.readInt(); } catch (EOFException e) { break; }
boolean allowed = false;
try { allowed = auth.authorize(uid); }
catch (Exception e) { Log.e(TAG, "Package verification failed for UID " + uid, e); }
if (!allowed) Log.w(TAG, "Rejected UID " + uid);
responses.writeByte(allowed ? 1 : 0);
responses.flush();
}
} finally {
child.destroy();
}
throw new IllegalStateException("MSD daemon exited");
}
}
2 changes: 1 addition & 1 deletion msd-tool/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ anyhow = "1.0.86"
byteorder = "1.5.0"
cap-std = "4.0.0"
clap = { version = "4.5.8", features = ["derive"] }
rustix = { version = "1.1.3", features = ["fs", "net", "process", "thread"] }
rustix = { version = "1.1.3", features = ["event", "fs", "net", "process", "thread"] }
tracing = "0.1.40"
tracing-subscriber = "0.3.18"

Expand Down
184 changes: 184 additions & 0 deletions msd-tool/src/auth.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
// SPDX-License-Identifier: GPL-3.0-only

//! Authentication over private pipes inherited from the trusted app_process
//! supervisor. No identity or authorization response is read from the client.

use std::{
fs::File,
io::{Read, Write},
sync::Mutex,
};

use anyhow::{Context, Result, bail};
use rustix::{
event::{PollFd, PollFlags, Timespec, poll},
fs::Uid,
};

struct Channel {
input: File,
output: File,
failed: bool,
}

pub struct Authenticator(Mutex<Channel>);

impl Authenticator {
pub fn new() -> Result<Self> {
Ok(Self(Mutex::new(Channel {
input: rustix::io::dup(std::io::stdin())?.into(),
output: rustix::io::dup(std::io::stdout())?.into(),
failed: false,
})))
}

pub fn authorize(&self, uid: Uid) -> Result<()> {
// Retain root's administrative CLI access. Neither shell nor the system
// UID is implicitly authorized.
if uid == Uid::ROOT {
return Ok(());
}
let mut channel = self
.0
.lock()
.map_err(|_| anyhow::anyhow!("Authenticator poisoned"))?;
if channel.failed {
bail!("Authentication supervisor unavailable");
}
let result = channel.query(uid.as_raw());
// A timeout, EOF, or malformed response permanently poisons this channel:
// a late response must never authorize a different client's request.
if result.is_err() {
channel.failed = true;
}
if !result? {
bail!("Client UID {} is not the trusted MSD package", uid.as_raw());
}
Ok(())
}
}

impl Channel {
fn query(&mut self, uid: u32) -> Result<bool> {
self.output
.write_all(&uid.to_be_bytes())
.context("Sending authentication query")?;
self.output.flush()?;
let mut fds = [PollFd::new(&self.input, PollFlags::IN)];
if poll(
&mut fds,
Some(&Timespec {
tv_sec: 5,
tv_nsec: 0,
}),
)? == 0
{
bail!("Authentication supervisor timed out");
}
let mut response = [0];
self.input
.read_exact(&mut response)
.context("Reading authentication result")?;
match response[0] {
0 => Ok(false),
1 => Ok(true),
value => bail!("Invalid authentication response: {value}"),
}
}
}

#[cfg(test)]
mod tests {
use super::*;
use std::{
os::{fd::OwnedFd, unix::net::UnixStream},
thread,
};

fn channel() -> (Authenticator, UnixStream) {
let (daemon, supervisor) = UnixStream::pair().unwrap();
let input: OwnedFd = daemon.try_clone().unwrap().into();
let output: OwnedFd = daemon.into();
(
Authenticator(Mutex::new(Channel {
input: input.into(),
output: output.into(),
failed: false,
})),
supervisor,
)
}

#[test]
fn checks_full_uid_and_does_not_cache_authorization() {
let (auth, mut supervisor) = channel();
let worker = thread::spawn(move || {
for (uid, answer) in [(10469u32, 1u8), (110469, 0), (10469, 0)] {
let mut query = [0; 4];
supervisor.read_exact(&mut query).unwrap();
assert_eq!(u32::from_be_bytes(query), uid);
supervisor.write_all(&[answer]).unwrap();
}
});
assert!(auth.authorize(Uid::from_raw(10469)).is_ok());
assert!(auth.authorize(Uid::from_raw(110469)).is_err());
assert!(auth.authorize(Uid::from_raw(10469)).is_err());
worker.join().unwrap();
}

#[test]
fn malformed_response_permanently_fails_closed() {
let (auth, mut supervisor) = channel();
let worker = thread::spawn(move || {
let mut query = [0; 4];
supervisor.read_exact(&mut query).unwrap();
supervisor.write_all(&[2, 1]).unwrap();
});
assert!(auth.authorize(Uid::from_raw(10469)).is_err());
assert!(auth.authorize(Uid::from_raw(10469)).is_err());
worker.join().unwrap();
}

#[test]
fn supervisor_eof_fails_closed() {
let (auth, mut supervisor) = channel();
let worker = thread::spawn(move || {
let mut query = [0; 4];
supervisor.read_exact(&mut query).unwrap();
});
assert!(auth.authorize(Uid::from_raw(10469)).is_err());
assert!(auth.authorize(Uid::from_raw(10469)).is_err());
worker.join().unwrap();
}

#[test]
fn only_root_bypasses_the_supervisor() {
let (auth, mut supervisor) = channel();
assert!(auth.authorize(Uid::ROOT).is_ok());
let worker = thread::spawn(move || {
for uid in [1000u32, 2000] {
let mut query = [0; 4];
supervisor.read_exact(&mut query).unwrap();
assert_eq!(u32::from_be_bytes(query), uid);
supervisor.write_all(&[0]).unwrap();
}
});
assert!(auth.authorize(Uid::from_raw(1000)).is_err());
assert!(auth.authorize(Uid::from_raw(2000)).is_err());
worker.join().unwrap();
}

#[test]
fn late_response_after_timeout_cannot_authorize_another_request() {
let (auth, mut supervisor) = channel();
let worker = thread::spawn(move || {
let mut query = [0; 4];
supervisor.read_exact(&mut query).unwrap();
thread::sleep(std::time::Duration::from_millis(5200));
supervisor.write_all(&[1]).unwrap();
});
assert!(auth.authorize(Uid::from_raw(10469)).is_err());
worker.join().unwrap();
assert!(auth.authorize(Uid::from_raw(10470)).is_err());
}
}
Loading