diff --git a/README.md b/README.md index 919898c..820d63b 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 48e1b64..f7d14d4 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -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) @@ -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${capitalized}") { inputs.property("rootProject.name", rootProject.name) inputs.property("variant.applicationId", variant.applicationId) @@ -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") } diff --git a/app/module/service.sh b/app/module/service.sh index 49251be..16ed318 100644 --- a/app/module/service.sh +++ b/app/module/service.sh @@ -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 diff --git a/app/src/main/java/com/chiller3/msd/standalone/AuthenticatedDaemon.java b/app/src/main/java/com/chiller3/msd/standalone/AuthenticatedDaemon.java new file mode 100644 index 0000000..4b364db --- /dev/null +++ b/app/src/main/java/com/chiller3/msd/standalone/AuthenticatedDaemon.java @@ -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"); + } +} diff --git a/msd-tool/Cargo.toml b/msd-tool/Cargo.toml index aa5efea..47f47bb 100644 --- a/msd-tool/Cargo.toml +++ b/msd-tool/Cargo.toml @@ -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" diff --git a/msd-tool/src/auth.rs b/msd-tool/src/auth.rs new file mode 100644 index 0000000..cc0a809 --- /dev/null +++ b/msd-tool/src/auth.rs @@ -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); + +impl Authenticator { + pub fn new() -> Result { + 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 { + 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()); + } +} diff --git a/msd-tool/src/daemon.rs b/msd-tool/src/daemon.rs index ffea5a5..c42a600 100644 --- a/msd-tool/src/daemon.rs +++ b/msd-tool/src/daemon.rs @@ -6,8 +6,8 @@ //! currently active functions and setting the USB controller to emulate mass //! storage devices. //! -//! Access control is handled entirely by the SELinux policy. If SELinux is not -//! enforcing at the time of the connection, the connection will be terminated. +//! The trusted supervisor authenticates each peer UID against Android's package +//! manager and the pinned signing certificate. SELinux must also be enforcing. //! //! Protocol violations terminate the connection. Only valid, but failed, //! requests result in an [`ErrorResponse`]. @@ -41,6 +41,7 @@ use rustix::{ use tracing::{debug, error, info, info_span, warn}; use crate::{ + auth::Authenticator, message::{ self, ActiveMassStorageDevice, ErrorResponse, FromSocket, GetFunctionsResponse, GetMassStorageResponse, Request, Response, SetMassStorageRequest, SetMassStorageResponse, @@ -67,8 +68,7 @@ pub fn socket_addr() -> SocketAddr { } /// Check that SELinux is enabled, enforcing, and that the policy seems to be -/// correct. This acts as a sanity check since we rely on SELinux for access -/// control. +/// correct. Certificate authentication supplements these SELinux safeguards. fn check_selinux() -> Result<()> { let path = Path::new(SELINUX_ENFORCE); @@ -329,7 +329,7 @@ fn handle_request(request: &Request) -> Response { }) } -fn handle_client(mut stream: UnixStream) -> Result<()> { +fn handle_client(mut stream: UnixStream, uid: Uid, auth: &Authenticator) -> Result<()> { check_selinux()?; negotiate_protocol(&mut stream)?; @@ -340,6 +340,8 @@ fn handle_client(mut stream: UnixStream) -> Result<()> { Err(e) => return Err(e).context("Failed to receive request"), }; + // Revalidate existing connections too, including after package changes. + auth.authorize(uid)?; debug!("Request: {request:?}"); let response = handle_request(&request); @@ -421,17 +423,26 @@ fn drop_privileges() -> Result<()> { } pub fn subcommand_daemon(_cli: &DaemonCli) -> Result<()> { + let auth = Authenticator::new()?; drop_privileges()?; let listener = UnixListener::bind_addr(&socket_addr()).context("Failed to listen on domain socket")?; thread::scope(|scope| -> Result<()> { + let auth = &auth; for stream in listener.incoming() { let stream = stream.context("Failed to accept incoming connection")?; let ucred = rustix::net::sockopt::socket_peercred(&stream) .context("Failed to get socket peer credentials")?; + // Reject unauthenticated clients before parsing bytes or allocating + // a worker thread. The pipe query has a bounded timeout. + if let Err(e) = auth.authorize(ucred.uid) { + warn!(uid = ucred.uid.as_raw(), "Rejected connection: {e:#}"); + continue; + } + scope.spawn(move || { let _span = info_span!( "peer", @@ -448,7 +459,7 @@ pub fn subcommand_daemon(_cli: &DaemonCli) -> Result<()> { info!("Received connection"); - if let Err(e) = handle_client(stream) { + if let Err(e) = handle_client(stream, ucred.uid, auth) { error!("Thread failed: {e:?}"); } }); diff --git a/msd-tool/src/main.rs b/msd-tool/src/main.rs index 9027731..1ae6e78 100644 --- a/msd-tool/src/main.rs +++ b/msd-tool/src/main.rs @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: 2024 Andrew Gunnerson // SPDX-License-Identifier: GPL-3.0-only +mod auth; mod client; mod daemon; mod message; diff --git a/msd-tool/src/sepatch.rs b/msd-tool/src/sepatch.rs index 05e5aae..9da960e 100644 --- a/msd-tool/src/sepatch.rs +++ b/msd-tool/src/sepatch.rs @@ -2,7 +2,6 @@ // SPDX-License-Identifier: GPL-3.0-only use std::{ - collections::HashMap, fs::{self, OpenOptions}, io::Write, path::{Path, PathBuf}, @@ -75,9 +74,6 @@ pub fn subcommand_sepatch(cli: &SepatchCli) -> Result<()> { let mut pdb = read_policy(cli.source.as_path())?; let n_source_type = "untrusted_app"; - let n_source_uffd_type = "untrusted_app_userfaultfd"; - let n_target_type = "msd_app"; - let n_target_uffd_type = "msd_app_userfaultfd"; let n_daemon_type = "msd_daemon"; macro_rules! r { @@ -193,60 +189,9 @@ pub fn subcommand_sepatch(cli: &SepatchCli) -> Result<()> { let c_unix_stream_socket = c!("unix_stream_socket")?; let p_unix_stream_socket_connectto = p!(c_unix_stream_socket, "connectto")?; - // Make msd_app a copy of untrusted_app. - - let t_source = t!(n_source_type)?; - let t_target = pdb.create_type(n_target_type, false)?.0; - - let mut type_map = HashMap::new(); - type_map.insert(t_source, t_target); - - // https://android.googlesource.com/platform/system/sepolicy/+/06edcd8250a249192981c7fbeea196249394b9ad - match t!(n_source_uffd_type) { - Ok(t_source_uffd) => { - let (t_target_uffd, _) = pdb.create_type(n_target_uffd_type, false)?; - - type_map.insert(t_source_uffd, t_target_uffd); - } - Err(e) => { - eprintln!("{e}; assuming old version of Android"); - } - }; - - for (from, to) in &type_map { - pdb.copy_roles(*from, *to)?; - pdb.copy_attributes(*from, *to)?; - pdb.copy_constraints(*from, *to); - } - - pdb.copy_avtab_rules(&|source_type, target_type| { - let new_source_type = type_map.get(&source_type).copied(); - let new_target_type = type_map.get(&target_type).copied(); - - if new_source_type.is_none() && new_target_type.is_none() { - None - } else { - Some(( - new_source_type.unwrap_or(source_type), - new_target_type.unwrap_or(target_type), - )) - } - })?; - pdb.copy_filename_trans_rules(&|source_type, file_type, trans_type| { - let new_source_type = type_map.get(&source_type).copied(); - let new_file_type = type_map.get(&file_type).copied(); - let new_trans_type = type_map.get(&trans_type).copied(); - - if new_source_type.is_none() && new_file_type.is_none() && new_trans_type.is_none() { - None - } else { - Some(( - new_source_type.unwrap_or(source_type), - new_file_type.unwrap_or(file_type), - new_trans_type.unwrap_or(trans_type), - )) - } - }); + // Use a stock app domain so KernelSU SELinux Hide can validate it against + // its original policy. The daemon authenticates clients independently. + let t_target = t!(n_source_type)?; // Create a new type for running the daemon. @@ -255,6 +200,32 @@ pub fn subcommand_sepatch(cli: &SepatchCli) -> Result<()> { pdb.set_attribute(t_daemon, t_domain, true)?; pdb.set_attribute(t_daemon, t_mlstrustedsubject, true)?; + // The root app_process supervisor only exchanges UID decisions through + // inherited anonymous pipes. The daemon gets no Package Manager privileges. + let c_fifo = c!("fifo_file")?; + let p_sigchld = p!(c_process, "sigchld")?; + for name in ["ksu", "su", "magisk", "init"] { + if let Some(supervisor) = pdb.get_type_id(name) { + pdb.set_rule(t_daemon, supervisor, c_fd, p_fd_use, RuleAction::Allow); + pdb.set_rule( + t_daemon, + supervisor, + c_process, + p_sigchld, + RuleAction::Allow, + ); + for name in ["read", "write", "getattr"] { + pdb.set_rule( + t_daemon, + supervisor, + c_fifo, + p!(c_fifo, name)?, + RuleAction::Allow, + ); + } + } + } + // Setting the `domain` attribute isn't sufficient to grab many of the // "standard" rules. These are defined in the sepolicy source with a target // type of `self`, which means they were expanded at compile time. Since we @@ -451,7 +422,8 @@ pub fn subcommand_sepatch(cli: &SepatchCli) -> Result<()> { RuleAction::Deny, ); - // Allow the client to connect to daemon. + // Shared app-domain connectivity is gated by certificate + UID checks in + // the daemon, before the protocol handshake or any request is processed. pdb.set_rule( t_target, t_daemon, @@ -460,6 +432,8 @@ pub fn subcommand_sepatch(cli: &SepatchCli) -> Result<()> { RuleAction::Allow, ); + pdb.set_rule(t_daemon, t_target, c_fd, p_fd_use, RuleAction::Allow); + // Unprivileged execution of `msd-tool client` is denied by default to // reduce the attack surface. if cli.allow_adb {