use std::ffi::OsString;
use std::path::PathBuf;
use zeroize::Zeroize;
#[cfg_attr(
not(unix),
allow(
dead_code,
reason = "off-unix, macos's only in-crate caller is cfg(unix) posix.rs, so every item here is test-only"
)
)]
pub(crate) mod macos;
#[cfg_attr(
not(unix),
allow(
dead_code,
reason = "only the unix kill paths consult the front gate; it is tested everywhere"
)
)]
pub(crate) mod front;
#[cfg_attr(
not(unix),
allow(
dead_code,
reason = "pure, and a `Host` field everywhere; only the unix rewrite reads it"
)
)]
pub(crate) mod pkexec;
pub(crate) mod plan;
#[cfg(unix)]
#[path = "elevation/posix.rs"]
pub(crate) mod posix;
#[cfg_attr(
not(windows),
allow(dead_code, reason = "only the Windows ShellExecuteEx launch classifies its failures")
)]
pub(crate) mod runas_failure;
pub(crate) mod sanitize;
#[cfg_attr(
not(windows),
allow(
dead_code,
reason = "shell_file gates the ShellExecuteEx launch path (Windows-only); nothing calls it off-windows"
)
)]
pub(crate) mod shell_file;
#[cfg(unix)]
#[allow(
dead_code,
reason = "the shim is built bottom-up; the wire protocol lands before its users"
)]
pub(crate) mod shim;
#[cfg(windows)]
#[path = "elevation/windows.rs"]
pub(crate) mod windows;
#[cfg(unix)]
#[doc(hidden)]
pub use posix::controlling_terminal_present;
pub(crate) struct ArgvRefusals {
pub(crate) platform: &'static str,
pub(crate) op_prefix: &'static str,
pub(crate) commandline: &'static str,
pub(crate) setter: &'static str,
}
pub(crate) const SETTER_REFUSAL: &str = "name the elevated program as argv[0] (set .args([program, ...])): the \
elevated program is the one argv[0] names, so neither executable()'s search nor \
raw_executable()'s exact file can be honoured";
pub(crate) fn elevation_argv<'a>(
cmd: &'a crate::command::Command,
words: &ArgvRefusals,
) -> Result<&'a [OsString], crate::error::Error> {
use crate::command::{CommandInput, ExecutableSpec};
let refuse = |what: &str, detail: &str| crate::error::Error::Unsupported {
op: format!("{} {what}", words.op_prefix),
platform: words.platform,
detail: detail.into(),
source: None,
};
if let Some(spec) = cmd.executable_spec() {
let setter = match spec {
ExecutableSpec::Search(_) => "executable",
ExecutableSpec::Exact(_) => "raw_executable",
};
return Err(refuse(&format!("of a program set by {setter}()"), words.setter));
}
let no_program = || {
refuse(
"of an empty command",
"set a program via .args([...]) before .elevate()",
)
};
let argv = match cmd.input() {
CommandInput::Argv(argv) => argv,
CommandInput::Empty => return Err(no_program()),
CommandInput::CommandLine(_) => return Err(refuse("of a commandline() command", words.commandline)),
};
if argv.is_empty() {
return Err(no_program());
}
Ok(argv)
}
#[cfg_attr(
not(unix),
allow(
dead_code,
reason = "Launch is only constructed by the unix-only macos.rs and posix.rs backends; dead off-unix"
)
)]
#[derive(Debug)]
pub(crate) struct Launch {
pub(crate) program: OsString,
pub(crate) args: Vec<OsString>,
pub(crate) cwd: Option<PathBuf>,
}
pub use sanitize::EnvSanitizer;
pub fn is_elevated() -> bool {
#[cfg(unix)]
{
posix::is_elevated()
}
#[cfg(windows)]
{
windows::is_elevated()
}
#[cfg(not(any(unix, windows)))]
{
false
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Backend {
#[default]
Auto,
Sudo,
Doas,
Pkexec,
}
#[derive(Debug, Clone, Default)]
pub enum Auth {
#[default]
Interactive,
NonInteractive,
Askpass(PathBuf),
Stdin(Secret),
Gui,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ElevatedStdio {
Passthrough,
OwnConsole,
StdinConsumed,
OsascriptRelay,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ElevatedVia {
Wrapped(Backend),
WindowsUac,
MacosOsascript,
AlreadyElevated,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Privilege {
Unprivileged,
Elevated,
}
#[derive(Debug, Clone)]
pub struct ElevationReport {
pub via: ElevatedVia,
pub stripped_env: Vec<OsString>,
pub stdio: ElevatedStdio,
}
impl ElevationReport {
pub(crate) fn tracked(&self) -> front::TrackedKind {
use front::{Front, TrackedKind};
match self.via {
ElevatedVia::Wrapped(Backend::Sudo) => TrackedKind::Front(Front::Sudo),
ElevatedVia::Wrapped(Backend::Doas) => TrackedKind::Front(Front::Doas),
ElevatedVia::MacosOsascript => TrackedKind::Front(Front::Osascript),
ElevatedVia::Wrapped(Backend::Pkexec) | ElevatedVia::WindowsUac => TrackedKind::AnotherUser,
ElevatedVia::AlreadyElevated => TrackedKind::Own,
ElevatedVia::Wrapped(Backend::Auto) => {
debug_assert!(false, "a report never names Auto");
TrackedKind::Own
}
}
}
}
#[derive(Debug)]
pub(crate) struct ElevationRequest {
pub enabled: bool,
pub backend: Backend,
pub auth: Auth,
pub sanitizer: EnvSanitizer,
}
impl Default for ElevationRequest {
fn default() -> ElevationRequest {
ElevationRequest {
enabled: false,
backend: Backend::Auto,
auth: Auth::Interactive,
sanitizer: EnvSanitizer::default(),
}
}
}
#[cfg_attr(
not(windows),
allow(
dead_code,
reason = "consumed only by the Windows RunAsIs arms; the POSIX rewrite reports AlreadyElevated through PosixRewrite instead"
)
)]
pub(crate) fn already_elevated_report(stdio: ElevatedStdio) -> ElevationReport {
ElevationReport {
via: ElevatedVia::AlreadyElevated,
stripped_env: Vec::new(),
stdio,
}
}
#[cfg(unix)]
fn backend_unusable(backend_path: &std::path::Path) -> bool {
use std::os::unix::ffi::OsStrExt;
let Ok(cpath) = std::ffi::CString::new(backend_path.as_os_str().as_bytes()) else {
return true; };
unsafe { libc::faccessat(libc::AT_FDCWD, cpath.as_ptr(), libc::X_OK, libc::AT_EACCESS) != 0 }
}
#[allow(
dead_code,
reason = "remap_derived_spawn_error, its only caller, has no non-unix production call site"
)]
#[cfg(not(unix))]
fn backend_unusable(backend_path: &std::path::Path) -> bool {
!backend_path.exists()
}
#[cfg_attr(
not(unix),
allow(
dead_code,
reason = "consumed only by the unix sync spawn arm; the Windows arm delegates straight to windows::spawn_elevated"
)
)]
pub(crate) fn remap_derived_spawn_error(
err: crate::error::Error,
backend_path: &std::path::Path,
) -> crate::error::Error {
use crate::error::{ElevationErrorKind, Error};
match err {
Error::Io(e)
if matches!(
e.kind(),
std::io::ErrorKind::NotFound | std::io::ErrorKind::PermissionDenied
) && backend_unusable(backend_path) =>
{
Error::Elevation {
kind: ElevationErrorKind::BackendUnavailable,
detail: format!("elevation backend {} could not be executed", backend_path.display()),
source: Some(Error::io_cause(e)),
}
}
other => other,
}
}
#[derive(Clone)]
pub struct Secret(Vec<u8>);
impl Secret {
pub fn new(bytes: impl Into<Vec<u8>>) -> Secret {
Secret(bytes.into())
}
pub fn expose(&self) -> &[u8] {
&self.0
}
}
impl std::fmt::Debug for Secret {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("Secret(<redacted>)")
}
}
impl Drop for Secret {
fn drop(&mut self) {
self.0.zeroize();
}
}
#[cfg(test)]
#[path = "elevation_tests.rs"]
pub(crate) mod elevation_tests;