use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};
use super::{ElevatedStdio, ElevatedVia, ElevationReport, Launch};
use crate::command::Command;
use crate::error::Error;
use crate::stdio::{Fd, ResolvedStdio};
fn unsupported(op: &str, detail: String) -> Error {
Error::Unsupported {
op: op.into(),
platform: "macos",
detail,
}
}
fn os_bytes(s: &OsStr) -> Result<&[u8], Error> {
#[cfg(unix)]
{
use std::os::unix::ffi::OsStrExt;
Ok(s.as_bytes())
}
#[cfg(not(unix))]
{
if let Some(valid) = s.to_str() {
return Ok(valid.as_bytes());
}
use std::os::windows::ffi::OsStrExt;
let pos = char::decode_utf16(s.encode_wide())
.take_while(|c| c.is_ok())
.map(|c| c.expect("take_while kept only Ok").len_utf8())
.sum();
Err(Error::Quote(crate::error::QuoteError::new(
pos,
crate::error::QuoteErrorKind::NonUtf8,
)))
}
}
fn is_posix_absolute(s: &OsStr) -> Result<bool, Error> {
Ok(os_bytes(s)?.first() == Some(&b'/'))
}
pub(crate) fn build_shell_command(program: &OsStr, args: &[OsString], cwd: Option<&Path>) -> Result<Vec<u8>, Error> {
debug_assert!(
cwd.is_some() || matches!(is_posix_absolute(program), Ok(true)),
"a relative program needs the directory it is read against"
);
debug_assert!(
cwd.is_none_or(|d| matches!(is_posix_absolute(d.as_os_str()), Ok(true))),
"the structural gate must reject a non-absolute cwd before composition"
);
let mut words: Vec<&[u8]> = Vec::with_capacity(args.len() + 2);
words.push(b"exec".as_slice());
words.push(os_bytes(program)?);
let arg_bytes: Vec<&[u8]> = args.iter().map(|a| os_bytes(a)).collect::<Result<_, _>>()?;
words.extend(arg_bytes.iter().copied());
let mut out = Vec::new();
if let Some(dir) = cwd {
out.extend_from_slice(b"cd -P -- ");
out.extend_from_slice(&crate::quote::posix::quote(os_bytes(dir.as_os_str())?));
out.extend_from_slice(b" && ");
}
out.extend_from_slice(&crate::quote::posix::join(&words));
Ok(out)
}
pub(crate) fn wrap_do_shell_script(shell_command: &[u8], arg_max: Option<usize>) -> Result<String, Error> {
let body = crate::quote::applescript::escape_literal(shell_command).map_err(Error::Quote)?;
let script = format!("do shell script \"{body}\" with administrator privileges without altering line endings");
if let Some(max) = arg_max {
if script.len() > max {
return Err(Error::Elevation {
kind: crate::error::ElevationErrorKind::CommandTooLong,
detail: format!(
"the composed AppleScript is {} bytes; this system's kern.argmax is {max}. \
Shorten the command, or write the arguments to a file the elevated program reads",
script.len()
),
});
}
}
Ok(script)
}
#[cfg(unix)]
#[allow(dead_code, reason = "no caller yet")]
pub(crate) fn build_shim_script(
shim_exe: &OsStr,
shim: &super::shim::protocol::ShimArgs,
cwd: Option<&Path>,
arg_max: Option<usize>,
) -> Result<String, Error> {
debug_assert!(
matches!(is_posix_absolute(shim_exe), Ok(true)),
"shim_exe must be POSIX-absolute"
);
let argv = shim.to_argv(shim_exe, true);
let shell_command = build_shell_command(&argv[0], &argv[1..], cwd)?;
wrap_do_shell_script(&shell_command, arg_max)
}
fn checked_argv(cmd: &Command) -> Result<&[OsString], Error> {
super::elevation_argv(
cmd,
&super::ArgvRefusals {
platform: "macos",
op_prefix: "macOS graphical elevation",
commandline: "the command must be an argv (set .args([...])); a raw command line cannot be \
re-quoted for /bin/sh without guessing its word boundaries",
argv0: "`do shell script` execs the program, which sets argv[0] to its own path; a separate \
argv[0] cannot survive elevation",
},
)
}
pub(crate) fn program_and_args(
cmd: &Command,
process_cwd: impl FnOnce() -> std::io::Result<PathBuf>,
) -> Result<Launch, Error> {
let argv = checked_argv(cmd)?;
let as_given = || cmd.cwd().map(Path::to_path_buf);
let (program, cwd) = match cmd.executable_spec() {
Some(crate::command::ExecutableSpec::Exact(p)) => {
let entered = crate::resolve::exact::enter_posix(
p.as_os_str(),
cmd.cwd(),
crate::command::explain_cwd_read(process_cwd),
)?;
(entered.program, entered.dir)
}
Some(crate::command::ExecutableSpec::Search(p)) => (p.clone(), as_given()),
None => (PathBuf::from(&argv[0]), as_given()),
};
Ok(Launch {
program: program.into_os_string(),
args: argv[1..].to_vec(),
cwd,
})
}
pub(crate) fn reject_structural_gui_config(cmd: &Command) -> Result<(), Error> {
if let Some(dir) = cmd.cwd() {
if !is_posix_absolute(dir.as_os_str())? {
return Err(unsupported(
"macOS graphical elevation with a relative current_dir()",
format!(
"{dir:?} would resolve against this process's directory for osascript but \
against whatever the authorization trampoline hands the elevated shell for \
the command itself; pass an absolute path"
),
));
}
}
let argv = checked_argv(cmd)?;
let program = match cmd.executable_spec() {
Some(crate::command::ExecutableSpec::Exact(p)) => {
crate::resolve::exact::refuse_unnameable(p.as_os_str())?;
None
}
_ => Some(cmd.executable_path().map_or(argv[0].as_os_str(), |p| p.as_os_str())),
};
if let Some(program) = program {
if !is_posix_absolute(program)? {
return Err(unsupported(
"macOS graphical elevation of a non-absolute program",
format!(
"{program:?} would be resolved by the elevated shell's own PATH, not the caller's, \
so the binary that runs as root is not the one you selected; pass an absolute path"
),
));
}
}
for (&slot, resolved) in cmd.fds() {
if slot.raw() >= 3 {
return Err(unsupported(
"fd >= 3 on a macOS graphically-elevated child",
"the authorization trampoline passes no descriptors, so fd >= 3 cannot reach the \
elevated program"
.into(),
));
}
if slot == Fd::STDIN && !matches!(resolved, ResolvedStdio::Inherit | ResolvedStdio::Null) {
return Err(unsupported(
"a pipe or file on stdin for a macOS graphically-elevated child",
"the elevated program's stdin comes from Authorization Services; osascript never \
reads fd0, so anything written there would be silently discarded. Use null() or \
inherit()"
.into(),
));
}
}
if !cmd.env_ops().is_empty() {
return Err(unsupported(
"env forwarding to a macOS graphically-elevated child",
"the authorization trampoline builds the root environment; the only way to pass a \
variable would be an assignment in the command text, which is visible to anyone \
inspecting the running processes"
.into(),
));
}
if cmd.contain_request().mode.is_some() {
return Err(unsupported(
".contain() + macOS graphical elevation",
"the elevated program runs under the authorization trampoline, parented to launchd \
and outside this process's tree; containment cannot span it"
.into(),
));
}
Ok(())
}
pub(crate) fn build_rewrite(
cmd: &mut Command,
launch: Launch,
osascript: &Path,
arg_max: Option<usize>,
) -> Result<(Command, ElevationReport), Error> {
debug_assert!(
cmd.env_ops().is_empty(),
"reject_structural_gui_config must reject env ops before build_rewrite"
);
debug_assert!(
cmd.contain_request().mode.is_none(),
"reject_structural_gui_config must reject containment before build_rewrite"
);
debug_assert!(
cmd.fds().keys().all(|s| s.raw() < 3),
"reject_structural_gui_config must reject fd >= 3 before build_rewrite"
);
let Launch { program, args, cwd } = launch;
let shell_command = build_shell_command(&program, &args, cwd.as_deref())?;
let script = wrap_do_shell_script(&shell_command, arg_max)?;
let mut derived = Command::new();
derived.set_input_argv(vec![
osascript.as_os_str().to_os_string(),
OsString::from("-e"),
OsString::from(script),
]);
if let Some(d) = cwd {
derived.current_dir(d);
}
derived.kill_on_drop(cmd.kill_on_drop_flag());
if cmd.kill_on_drop_flag() {
log::warn!(
"kill_on_drop is set on a macOS graphically-elevated child ({program:?}), which cannot be \
killed: dropping it early leaves the root program and its osascript front-end running, \
with the program's exit status unobservable. Call .kill_on_drop(false) and wait() if that \
matters."
);
}
for (slot, resolved) in std::mem::take(cmd.fds_mut()) {
derived.fds_mut().insert(slot, resolved);
}
let report = ElevationReport {
via: ElevatedVia::MacosOsascript,
stripped_env: Vec::new(),
stdio: ElevatedStdio::OsascriptRelay,
};
Ok((derived, report))
}
#[cfg(test)]
#[path = "macos_tests.rs"]
mod macos_tests;