su: remove interactive su request prompt

With the ability to explicitly grant superuser access in the app,
reactive su prompting and waiting for user response via an interactive
dialog is no longer needed.

- Remove app_request and the associated FIFO / poll waiting logic.
- Change the default SuPolicy and RootSettings from Query to Deny.
- Make SuInfo immutable by removing the internal Mutex<AccessInfo>,
  flattening settings into SuInfo, and refreshing with an updated
  clone on cache hits.
- Remove SuAppContext and convert notification and logging logic into
  private MagiskD methods.

Assisted-by: Gemini 3.8 Flash
This commit is contained in:
topjohnwu
2026-10-05 01:38:20 -07:00
committed by John Wu
parent ccad207125
commit 9a101215f1
4 changed files with 91 additions and 218 deletions
+3 -3
View File
@@ -55,7 +55,7 @@ where
}
}
#[derive(Default)]
#[derive(Copy, Clone, Default)]
pub struct DbSettings {
pub root_access: RootAccess,
pub multiuser_mode: MultiuserMode,
@@ -66,7 +66,7 @@ pub struct DbSettings {
}
#[repr(i32)]
#[derive(Default, FromPrimitive)]
#[derive(Copy, Clone, Default, FromPrimitive)]
pub enum RootAccess {
Disabled,
AppsOnly,
@@ -76,7 +76,7 @@ pub enum RootAccess {
}
#[repr(i32)]
#[derive(Default, FromPrimitive)]
#[derive(Copy, Clone, Default, FromPrimitive)]
pub enum MultiuserMode {
#[default]
OwnerOnly,
+58 -143
View File
@@ -1,20 +1,11 @@
use super::SuInfo;
use super::db::RootSettings;
use crate::consts::{INTERNAL_DIR, MAGISK_FILE_CON};
use crate::daemon::to_user_id;
use crate::ffi::{SuPolicy, SuRequest, fork_dont_care, get_magisk_tmp};
use crate::socket::IpcRead;
use crate::daemon::{MagiskD, to_user_id};
use crate::ffi::{SuRequest, fork_dont_care};
use ExtraVal::{Bool, Int, IntList, Str};
use base::{
BytesExt, FileAttr, LibcReturn, LoggedResult, ResultExt, Utf8CStrBuf, cstr, error,
};
use nix::fcntl::OFlag;
use nix::poll::{PollFd, PollFlags, PollTimeout};
use base::{BytesExt, error};
use nix::sys::signal::SigSet;
use num_traits::AsPrimitive;
use std::fmt::Write;
use std::fs::File;
use std::os::fd::AsFd;
use std::os::unix::net::UCred;
use std::os::unix::process::CommandExt;
use std::process::{Command, exit};
@@ -101,47 +92,36 @@ impl Extra<'_> {
}
}
pub(super) struct SuAppContext<'a> {
pub(super) cred: UCred,
pub(super) request: &'a SuRequest,
pub(super) info: &'a SuInfo,
pub(super) settings: &'a mut RootSettings,
pub(super) sdk_int: i32,
}
impl MagiskD {
fn exec_cmd(&self, eval_uid: i32, mgr_pkg: &str, action: &'static str, extras: &[Extra]) {
let user = to_user_id(eval_uid).to_string();
impl SuAppContext<'_> {
fn exec_cmd(&self, action: &'static str, extras: &[Extra], use_provider: bool) {
let user = to_user_id(self.info.eval_uid);
let user = user.to_string();
let provider = format!("content://{mgr_pkg}.provider");
let mut cmd = app_process();
cmd.args([
"/system/bin",
"com.android.commands.content.Content",
"call",
"--uri",
&provider,
"--user",
&user,
"--method",
action,
]);
if self.sdk_int() >= 30 {
extras.iter().for_each(|e| e.add_bind(&mut cmd))
} else {
extras.iter().for_each(|e| e.add_bind_legacy(&mut cmd))
}
cmd.env("CLASSPATH", "/system/framework/content.jar");
if use_provider {
let provider = format!("content://{}.provider", self.info.mgr_pkg);
let mut cmd = app_process();
cmd.args([
"/system/bin",
"com.android.commands.content.Content",
"call",
"--uri",
&provider,
"--user",
&user,
"--method",
action,
]);
if self.sdk_int >= 30 {
extras.iter().for_each(|e| e.add_bind(&mut cmd))
} else {
extras.iter().for_each(|e| e.add_bind_legacy(&mut cmd))
}
cmd.env("CLASSPATH", "/system/framework/content.jar");
if let Ok(output) = cmd.output()
&& !output.stderr.contains(b"Error")
&& !output.stdout.contains(b"Error")
{
// The provider call succeed
return;
}
if let Ok(output) = cmd.output()
&& !output.stderr.contains(b"Error")
&& !output.stdout.contains(b"Error")
{
// The provider call succeed
return;
}
let mut cmd = app_process();
@@ -150,7 +130,7 @@ impl SuAppContext<'_> {
"com.android.commands.am.Am",
"start",
"-p",
&self.info.mgr_pkg,
mgr_pkg,
"--user",
&user,
"-a",
@@ -174,122 +154,58 @@ impl SuAppContext<'_> {
}
}
fn app_request(&mut self) {
let mut fifo = cstr::buf::new::<64>();
fifo.write_fmt(format_args!(
"{}/{}/su_request_{}",
get_magisk_tmp(),
INTERNAL_DIR,
self.cred.pid.unwrap_or(-1)
))
.ok();
let fd = || -> LoggedResult<File> {
let mut attr = FileAttr::new();
attr.st.st_mode = 0o600;
attr.st.st_uid = self.info.mgr_uid.as_();
attr.st.st_gid = self.info.mgr_uid.as_();
attr.con.push_str(MAGISK_FILE_CON);
fifo.mkfifo(0o600)?;
fifo.set_attr(&attr)?;
let extras = [
Extra {
key: "fifo",
value: Str(&fifo),
},
Extra {
key: "uid",
value: Int(self.info.eval_uid),
},
Extra {
key: "pid",
value: Int(self.cred.pid.unwrap_or(-1)),
},
];
self.exec_cmd("request", &extras, false);
// Open with O_RDWR to prevent FIFO open block
let fd = fifo.open(OFlag::O_RDWR | OFlag::O_CLOEXEC)?;
let mut pfd = [PollFd::new(fd.as_fd(), PollFlags::POLLIN)];
// Wait for data input for at most 70 seconds
nix::poll::poll(
&mut pfd,
PollTimeout::try_from(70 * 1000).unwrap_or(PollTimeout::NONE),
)
.check_os_err("poll", None, None)?;
Ok(fd)
}();
fifo.remove().log_ok();
if let Ok(mut fd) = fd {
self.settings.policy = SuPolicy {
repr: fd
.read_decodable::<i32>()
.log()
.map(i32::from_be)
.unwrap_or(SuPolicy::Deny.repr),
};
} else {
self.settings.policy = SuPolicy::Deny;
};
}
fn app_notify(&self) {
fn app_notify(&self, cred: &UCred, info: &SuInfo) {
let extras = [
Extra {
key: "from.uid",
value: Int(self.cred.uid.as_()),
value: Int(cred.uid.as_()),
},
Extra {
key: "pid",
value: Int(self.cred.pid.unwrap_or(-1).as_()),
value: Int(cred.pid.unwrap_or(-1).as_()),
},
Extra {
key: "policy",
value: Int(self.settings.policy.repr),
value: Int(info.settings.policy.repr),
},
];
self.exec_cmd("notify", &extras, true);
self.exec_cmd(info.eval_uid, &info.mgr_pkg, "notify", &extras);
}
fn app_log(&self) {
let command = if self.request.command.is_empty() {
&self.request.shell
fn app_log(&self, cred: &UCred, info: &SuInfo, request: &SuRequest) {
let command = if request.command.is_empty() {
&request.shell
} else {
&self.request.command
&request.command
};
let extras = [
Extra {
key: "from.uid",
value: Int(self.cred.uid.as_()),
value: Int(cred.uid.as_()),
},
Extra {
key: "to.uid",
value: Int(self.request.target_uid),
value: Int(request.target_uid),
},
Extra {
key: "pid",
value: Int(self.cred.pid.unwrap_or(-1).as_()),
value: Int(cred.pid.unwrap_or(-1).as_()),
},
Extra {
key: "policy",
value: Int(self.settings.policy.repr),
value: Int(info.settings.policy.repr),
},
Extra {
key: "target",
value: Int(self.request.target_pid),
value: Int(request.target_pid),
},
Extra {
key: "context",
value: Str(&self.request.context),
value: Str(&request.context),
},
Extra {
key: "gids",
value: IntList(&self.request.gids),
value: IntList(&request.gids),
},
Extra {
key: "command",
@@ -297,19 +213,18 @@ impl SuAppContext<'_> {
},
Extra {
key: "notify",
value: Bool(self.settings.notify),
value: Bool(info.settings.notify),
},
];
self.exec_cmd("log", &extras, true);
self.exec_cmd(info.eval_uid, &info.mgr_pkg, "log", &extras);
}
pub(super) fn connect_app(&mut self) {
// If policy is undetermined, show dialog for user consent
if self.settings.policy == SuPolicy::Query {
self.app_request();
pub(super) fn notify_app(&self, cred: &UCred, info: &SuInfo, request: &SuRequest) {
if info.mgr_pkg.is_empty() {
return;
}
if !self.settings.log && !self.settings.notify {
if !info.settings.log && !info.settings.notify {
return;
}
@@ -318,10 +233,10 @@ impl SuAppContext<'_> {
}
// Notify su usage to application
if self.settings.log {
self.app_log();
} else if self.settings.notify {
self.app_notify();
if info.settings.log {
self.app_log(cred, info, request);
} else if info.settings.notify {
self.app_notify(cred, info);
}
exit(0);
+27 -70
View File
@@ -1,4 +1,3 @@
use super::connect::SuAppContext;
use super::db::RootSettings;
use crate::daemon::{AID_ROOT, AID_SHELL, MagiskD, to_app_id, to_user_id};
use crate::db::{DbSettings, MultiuserMode, RootAccess};
@@ -12,7 +11,6 @@ use std::time::{Duration, Instant};
#[allow(unused_imports)]
use std::os::fd::AsRawFd;
use std::sync::nonpoison::Mutex;
const DEFAULT_SHELL: &str = "/system/bin/sh";
@@ -32,17 +30,13 @@ impl Default for SuRequest {
}
}
#[derive(Clone)]
pub struct SuInfo {
pub(super) uid: i32,
pub(super) eval_uid: i32,
pub(super) mgr_pkg: String,
pub(super) mgr_uid: i32,
pub(super) settings: RootSettings,
cfg: DbSettings,
access: Mutex<AccessInfo>,
}
struct AccessInfo {
settings: RootSettings,
timestamp: Instant,
}
@@ -51,18 +45,9 @@ impl Default for SuInfo {
SuInfo {
uid: -1,
eval_uid: -1,
cfg: Default::default(),
mgr_pkg: Default::default(),
mgr_uid: -1,
access: Default::default(),
}
}
}
impl Default for AccessInfo {
fn default() -> Self {
AccessInfo {
settings: Default::default(),
cfg: Default::default(),
timestamp: Instant::now(),
}
}
@@ -70,37 +55,28 @@ impl Default for AccessInfo {
impl SuInfo {
fn allow(uid: i32) -> SuInfo {
let access = RootSettings {
let settings = RootSettings {
policy: SuPolicy::Allow,
log: false,
notify: false,
};
SuInfo {
uid,
access: Mutex::new(AccessInfo::new(access)),
settings,
..Default::default()
}
}
fn deny(uid: i32) -> SuInfo {
let access = RootSettings {
let settings = RootSettings {
policy: SuPolicy::Deny,
log: false,
notify: false,
};
SuInfo {
uid,
access: Mutex::new(AccessInfo::new(access)),
..Default::default()
}
}
}
impl AccessInfo {
fn new(settings: RootSettings) -> AccessInfo {
AccessInfo {
settings,
timestamp: Instant::now(),
..Default::default()
}
}
@@ -108,8 +84,11 @@ impl AccessInfo {
self.timestamp.elapsed() < Duration::from_secs(3)
}
fn refresh(&mut self) {
self.timestamp = Instant::now();
fn refresh(&self) -> SuInfo {
SuInfo {
timestamp: Instant::now(),
..self.clone()
}
}
}
@@ -132,27 +111,14 @@ impl MagiskD {
};
let info = self.get_su_info(cred.uid as i32);
{
let mut access = info.access.lock();
// Talk to su manager
let mut app = SuAppContext {
cred,
request: &req,
info: &info,
settings: &mut access.settings,
sdk_int: self.sdk_int(),
};
app.connect_app();
// Talk to su manager
self.notify_app(&cred, &info, &req);
// Before unlocking, refresh the timestamp
access.refresh();
if access.settings.policy == SuPolicy::Restrict {
req.drop_cap = true;
}
if access.settings.policy == SuPolicy::Deny {
match info.settings.policy {
SuPolicy::Restrict => req.drop_cap = true,
SuPolicy::Allow => {}
_ => {
warn!("su: request rejected ({})", info.uid);
client.write_pod(&SuPolicy::Deny.repr).ok();
return;
@@ -204,8 +170,10 @@ impl MagiskD {
}
let cached = self.cached_su_info.load();
if cached.uid == uid && cached.access.lock().is_fresh() {
return cached;
if cached.uid == uid && cached.is_fresh() {
let info = Arc::new(cached.refresh());
self.cached_su_info.store(info.clone());
return info;
}
let info = self.build_su_info(uid);
@@ -230,16 +198,10 @@ impl MagiskD {
_ => uid,
};
let mut access = RootSettings::default();
self.get_root_settings(eval_uid, &mut access)?;
let mut settings = RootSettings::default();
self.get_root_settings(eval_uid, &mut settings)?;
// We need to talk to the manager, get the app info
let (mgr_uid, mgr_pkg) =
if access.policy == SuPolicy::Query || access.log || access.notify {
self.get_manager(to_user_id(eval_uid), true)
} else {
(-1, String::new())
};
let (mgr_uid, mgr_pkg) = self.get_manager(to_user_id(eval_uid), true);
// If it's the manager, allow it silently
if to_app_id(uid) == to_app_id(mgr_uid) {
@@ -263,19 +225,14 @@ impl MagiskD {
_ => {}
};
// If still not determined, check if manager exists
if access.policy == SuPolicy::Query && mgr_uid < 0 {
return Ok(Arc::new(SuInfo::deny(uid)));
}
// Finally, the SuInfo
Ok(Arc::new(SuInfo {
uid,
eval_uid,
mgr_pkg,
mgr_uid,
settings,
cfg,
access: Mutex::new(AccessInfo::new(access)),
timestamp: Instant::now(),
}))
}();
+3 -2
View File
@@ -8,10 +8,11 @@ use base::ResultExt;
impl Default for SuPolicy {
fn default() -> Self {
SuPolicy::Query
SuPolicy::Deny
}
}
#[derive(Copy, Clone)]
pub struct RootSettings {
pub policy: SuPolicy,
pub log: bool,
@@ -21,7 +22,7 @@ pub struct RootSettings {
impl Default for RootSettings {
fn default() -> Self {
RootSettings {
policy: SuPolicy::Query,
policy: SuPolicy::Deny,
log: true,
notify: true,
}