use std::ffi::{OsStr, OsString};
use std::fs::File;
use std::os::fd::OwnedFd;
use std::os::unix::ffi::OsStrExt;
use std::path::{Path, PathBuf};
use zeroize::Zeroize;
use super::pkexec::PkexecVersion;
use super::plan::{launches_pkexec, BackendSet, Host, Os, Transition};
use super::shim::protocol::ShimArgs;
use super::{Auth, Backend, ElevatedStdio, ElevatedVia, ElevationReport, Launch, Privilege, Secret};
use crate::command::{Command, EnvOp};
use crate::error::{ElevationErrorKind, Error};
use crate::stdio::{Fd, Stdio};
fn valid_env_name(k: &OsStr) -> bool {
use std::os::unix::ffi::OsStrExt;
let b = k.as_bytes();
match b.first() {
Some(&c) if c == b'_' || c.is_ascii_alphabetic() => {}
_ => return false,
}
b.iter().all(|&c| c == b'_' || c.is_ascii_alphanumeric())
}
fn unsupported_env_name(k: &OsStr) -> Error {
Error::Unsupported {
op: "forwarding an env var with an unusual name across elevation".into(),
platform: "unix",
detail: format!("env var name {k:?} is not [A-Za-z_][A-Za-z0-9_]*; it cannot be forwarded losslessly"),
}
}
fn preserve_env_flag(env: &[(OsString, OsString)]) -> Result<OsString, Error> {
let mut flag = OsString::from("--preserve-env=");
for (i, (k, _)) in env.iter().enumerate() {
if !valid_env_name(k) {
return Err(unsupported_env_name(k));
}
if i > 0 {
flag.push(",");
}
flag.push(k);
}
Ok(flag)
}
pub(crate) fn build_argv(
backend: Backend,
backend_path: &OsStr,
auth: &Auth,
program: &OsStr,
args: &[OsString],
env: &[(OsString, OsString)],
) -> Result<Vec<OsString>, Error> {
let mut argv: Vec<OsString> = vec![backend_path.to_os_string()];
match backend {
Backend::Sudo => {
match auth {
Auth::NonInteractive => argv.push("-n".into()),
Auth::Stdin(_) => argv.push("-S".into()),
Auth::Askpass(_) => argv.push("-A".into()),
Auth::Interactive | Auth::Gui => {}
}
if !env.is_empty() {
argv.push(preserve_env_flag(env)?);
}
}
Backend::Doas => {
debug_assert!(
env.is_empty(),
"doas forwards no env; the rewrite rejects .env() for doas"
);
if matches!(auth, Auth::NonInteractive) {
argv.push("-n".into());
}
}
Backend::Pkexec => {
debug_assert!(
env.is_empty(),
"pkexec forwards no env; the rewrite rejects .env() for pkexec"
);
argv.push("--disable-internal-agent".into());
argv.push("--keep-cwd".into());
debug_assert!(
!program_starts_with_dash(program),
"pkexec has no `--`; the structural gate refuses a leading-dash program"
);
}
Backend::Auto => unreachable!("build_argv received unresolved Backend::Auto; the planner resolves Auto"),
}
if backend != Backend::Pkexec {
argv.push("--".into());
}
argv.push(program.to_os_string());
argv.extend(args.iter().cloned());
Ok(argv)
}
const POLKIT_SHORT_LINE: usize = 80;
const POLKIT_HEAD_CUT: usize = 38;
fn refuse_polkit_exe(shim_exe: &OsStr, argv: &[OsString]) -> Result<(), Error> {
let refuse = |why: &str| Error::Unsupported {
op: "pkexec with this shim executable".into(),
platform: "unix",
detail: format!("polkit cannot show {shim_exe:?}: {why}; choose a shim path that is plain ASCII"),
};
let Some(exe) = shim_exe.to_str() else {
return Err(refuse("it is not valid UTF-8"));
};
let line = argv.iter().map(|a| a.len()).sum::<usize>() + argv.len() - 1;
if line > POLKIT_SHORT_LINE && !exe.is_char_boundary(POLKIT_HEAD_CUT.min(exe.len())) {
return Err(refuse("its command line is cut inside one of its characters"));
}
Ok(())
}
#[allow(dead_code, reason = "no caller yet")]
pub(crate) fn build_shim_argv(
backend: Backend,
backend_path: &OsStr,
auth: &Auth,
shim_exe: &OsStr,
shim: &ShimArgs,
env: &[(OsString, OsString)],
) -> Result<Vec<OsString>, Error> {
debug_assert!(Path::new(shim_exe).is_absolute(), "shim_exe must be absolute");
let mut argv = shim.to_argv(shim_exe, false);
if backend == Backend::Pkexec {
if !argv[1..]
.iter()
.all(|a| a.as_bytes().iter().all(|b| (0x20..=0x7e).contains(b)))
{
argv = shim.to_argv(shim_exe, true);
}
refuse_polkit_exe(shim_exe, &argv)?;
}
build_argv(backend, backend_path, auth, &argv[0], &argv[1..], env)
}
fn program_starts_with_dash(program: &OsStr) -> bool {
use std::os::unix::ffi::OsStrExt;
program.as_bytes().first() == Some(&b'-')
}
pub(super) fn is_elevated() -> bool {
unsafe { libc::geteuid() == 0 }
}
#[doc(hidden)]
pub fn controlling_terminal_present() -> bool {
unsafe {
let fd = libc::open(c"/dev/tty".as_ptr(), libc::O_RDWR | libc::O_CLOEXEC | libc::O_NONBLOCK);
if fd < 0 {
return false;
}
libc::close(fd);
true
}
}
fn is_executable(path: &Path) -> bool {
use std::os::unix::ffi::OsStrExt;
let Ok(c) = std::ffi::CString::new(path.as_os_str().as_bytes()) else {
return false;
};
path.is_file() && unsafe { libc::faccessat(libc::AT_FDCWD, c.as_ptr(), libc::X_OK, libc::AT_EACCESS) == 0 }
}
pub(super) fn resolve_in_path_var(path_var: &OsStr, program: &str) -> Option<PathBuf> {
std::env::split_paths(path_var).find_map(|dir| {
if !dir.is_absolute() {
return None;
}
let cand = dir.join(program);
is_executable(&cand).then_some(cand)
})
}
#[cfg(target_os = "macos")]
fn kern_argmax() -> Option<usize> {
let mut mib = [libc::CTL_KERN, libc::KERN_ARGMAX];
let mut value: libc::c_int = 0;
let mut len = std::mem::size_of::<libc::c_int>();
let rc = unsafe {
libc::sysctl(
mib.as_mut_ptr(),
mib.len() as libc::c_uint,
&mut value as *mut libc::c_int as *mut libc::c_void,
&mut len,
std::ptr::null_mut(),
0,
)
};
if rc != 0 || value <= 0 {
log::debug!("could not read kern.argmax; the elevation length guard is disabled");
return None;
}
Some(value as usize)
}
pub(crate) fn probe_pkexec(
path: &Path,
pinned: &File,
run: impl FnOnce(std::process::Command) -> PkexecVersion,
) -> PkexecVersion {
use std::os::unix::process::CommandExt;
let mut probe = std::process::Command::new(pinned_exec_path(pinned));
probe.arg0(path).arg("--version");
run(probe)
}
fn pinned_exec_path(pinned: &File) -> PathBuf {
use std::os::fd::AsRawFd;
PathBuf::from(format!("/proc/self/fd/{}", pinned.as_raw_fd()))
}
fn pin(real: &Path) -> std::io::Result<File> {
use std::os::unix::fs::OpenOptionsExt;
#[cfg(target_os = "linux")]
let path_only = libc::O_PATH;
#[cfg(not(target_os = "linux"))]
let path_only = 0;
let file = std::fs::OpenOptions::new()
.read(true)
.custom_flags(path_only | libc::O_NOFOLLOW | libc::O_NONBLOCK)
.open(real)?;
if !file.metadata()?.is_file() {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"not a regular file",
));
}
Ok(File::from(crate::above_stdio::above_stdio(file.into())?))
}
pub(crate) fn run_version_probe(mut probe: std::process::Command) -> PkexecVersion {
probe
.env_clear()
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped());
#[allow(clippy::disallowed_methods, reason = "spawn_lock is held by `_guard` in this block")]
let spawned = {
let _guard = crate::child::spawn::spawn_lock();
probe.spawn()
};
match spawned.and_then(std::process::Child::wait_with_output) {
Err(e) => PkexecVersion::SpawnFailed(e.to_string()),
Ok(out) if !out.status.success() => PkexecVersion::Failed {
status: out.status.to_string(),
stdout: String::from_utf8_lossy(&out.stdout).into_owned(),
stderr: String::from_utf8_lossy(&out.stderr).into_owned(),
},
Ok(out) => super::pkexec::parse(&out.stdout),
}
}
pub(crate) fn pkexec_on(
path_var: &OsStr,
canonicalize: impl FnOnce(&Path) -> std::io::Result<PathBuf>,
) -> Option<Result<PathBuf, (PathBuf, std::io::Error)>> {
let found = resolve_in_path_var(path_var, "pkexec")?;
Some(canonicalize(&found).map_err(|e| (found, e)))
}
fn host_os() -> Os {
if cfg!(target_os = "macos") {
Os::MacOs
} else if cfg!(target_os = "linux") {
Os::Linux
} else {
Os::Unix
}
}
pub(super) fn detect(backend: Backend, auth: &Auth) -> Host {
detect_with(
std::env::var_os("PATH").as_deref(),
host_os(),
is_elevated(),
backend,
auth,
|p| std::fs::canonicalize(p),
run_version_probe,
)
}
pub(crate) fn detect_with(
path_var: Option<&OsStr>,
os: Os,
elevated: bool,
backend: Backend,
auth: &Auth,
canonicalize: impl FnOnce(&Path) -> std::io::Result<PathBuf>,
run: impl FnOnce(std::process::Command) -> PkexecVersion,
) -> Host {
let on_path = |program| path_var.and_then(|p| resolve_in_path_var(p, program));
let unresolved = |found: &Path, error: String| PkexecVersion::Unresolved {
path: found.display().to_string(),
error,
};
let (pkexec, pkexec_pin, pkexec_version) = if !launches_pkexec(os, backend, auth, elevated) {
(on_path("pkexec"), None, PkexecVersion::NotProbed)
} else {
match path_var.and_then(|p| pkexec_on(p, canonicalize)) {
None => (None, None, PkexecVersion::NotProbed),
Some(Err((found, e))) => (None, None, unresolved(&found, e.to_string())),
Some(Ok(real)) => match pin(&real) {
Ok(pinned) => {
let version = probe_pkexec(&real, &pinned, run);
(Some(real), Some(std::sync::Arc::new(pinned)), version)
}
Err(e) => {
let error = format!("opening {}: {e}", real.display());
(None, None, unresolved(&real, error))
}
},
}
};
Host {
elevated,
has_tty: controlling_terminal_present(),
available: BackendSet {
sudo: on_path("sudo"),
doas: on_path("doas"),
pkexec,
osascript: {
#[cfg(target_os = "macos")]
{
let p = Path::new("/usr/bin/osascript");
is_executable(p).then(|| p.to_path_buf())
}
#[cfg(not(target_os = "macos"))]
{
None
}
},
},
os,
arg_max: {
#[cfg(target_os = "macos")]
{
kern_argmax()
}
#[cfg(not(target_os = "macos"))]
{
None
}
},
pkexec_version,
pkexec_pin,
}
}
pub(crate) struct PendingPassword {
writer: std::io::PipeWriter,
secret: Secret,
}
fn password_line(secret: &[u8]) -> Vec<u8> {
let mut bytes = Vec::with_capacity(secret.len() + 1);
bytes.extend_from_slice(secret);
bytes.push(b'\n');
bytes
}
fn set_writer_nonblocking(writer: &std::io::PipeWriter) {
let flags = match rustix::fs::fcntl_getfl(writer) {
Ok(flags) => flags,
Err(e) => {
log::warn!("could not read the password channel's flags (F_GETFL): {e}; leaving it blocking");
return;
}
};
if let Err(e) = rustix::fs::fcntl_setfl(writer, flags | rustix::fs::OFlags::NONBLOCK) {
log::warn!("could not set the password channel non-blocking (F_SETFL): {e}; leaving it blocking");
}
}
fn wait_writable(fd: std::os::fd::RawFd) -> Result<bool, std::io::Error> {
loop {
let mut pfd = libc::pollfd {
fd,
events: libc::POLLOUT,
revents: 0,
};
let rc = unsafe { libc::poll(&mut pfd as *mut libc::pollfd, 1, -1) };
if rc < 0 {
let err = std::io::Error::last_os_error();
if err.kind() == std::io::ErrorKind::Interrupted {
continue; }
return Err(err);
}
if pfd.revents & (libc::POLLHUP | libc::POLLERR) != 0 {
return Ok(false);
}
if pfd.revents & libc::POLLOUT != 0 {
return Ok(true);
}
}
}
fn auth_failed(detail: String) -> Error {
Error::Elevation {
kind: ElevationErrorKind::AuthFailed,
detail,
}
}
fn write_password_bytes(writer: &mut std::io::PipeWriter, fd: std::os::fd::RawFd, bytes: &[u8]) -> Result<(), Error> {
use std::io::Write;
let mut written = 0usize;
while written < bytes.len() {
match writer.write(&bytes[written..]) {
Ok(0) => {
return if written == 0 {
log::debug!("elevation backend did not consume the password (fd0 accepted nothing)");
Ok(())
} else {
Err(auth_failed(
"elevation backend closed the password channel after a partial write".into(),
))
};
}
Ok(n) => written += n,
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
if written == 0 {
log::debug!("elevation backend did not consume the password (fd0 would block, no read): {e}");
return Ok(());
}
match wait_writable(fd) {
Ok(true) => continue,
Ok(false) => {
return Err(auth_failed(
"elevation backend closed fd0 after a partial password write".into(),
))
}
Err(pe) => {
return Err(auth_failed(format!(
"waiting to deliver the sudo -S password failed: {pe}"
)))
}
}
}
Err(e) if e.kind() == std::io::ErrorKind::BrokenPipe => {
if written == 0 {
log::debug!("elevation backend did not consume the password (fd0 closed / EPIPE): {e}");
return Ok(());
}
return Err(auth_failed(format!(
"elevation backend closed fd0 after a partial password write: {e}"
)));
}
Err(e) => return Err(auth_failed(format!("could not deliver the sudo -S password: {e}"))),
}
}
Ok(())
}
impl PendingPassword {
pub(crate) fn write_after_spawn(mut self) -> Result<(), Error> {
use std::os::fd::AsRawFd;
let mut bytes = password_line(self.secret.expose());
set_writer_nonblocking(&self.writer);
let fd = self.writer.as_raw_fd();
let result = write_password_bytes(&mut self.writer, fd, &bytes);
bytes.zeroize();
drop(self.writer); result
}
}
pub(crate) struct PosixRewrite {
pub derived: Option<Command>,
pub report: Option<ElevationReport>,
pub password_write: Option<PendingPassword>,
pub backend_path: Option<PathBuf>,
}
fn explicit_set_env(ops: &[EnvOp]) -> Vec<(OsString, OsString)> {
let mut map: std::collections::BTreeMap<OsString, OsString> = std::collections::BTreeMap::new();
for op in ops {
if let EnvOp::Set(k, v) = op {
map.insert(k.clone(), v.clone());
}
}
map.into_iter().collect()
}
fn checked_argv(cmd: &Command) -> Result<&[OsString], Error> {
super::elevation_argv(
cmd,
&super::ArgvRefusals {
platform: "unix",
op_prefix: "elevation",
commandline: "elevation requires an argv command (set .args([...])); a raw command line cannot be \
safely wrapped",
argv0: "the backend runs the loaded file with argv[0] = its path; a separate argv[0] cannot \
survive elevation",
},
)
}
fn anchored_program_and_args(cmd: &Command) -> Result<Launch, Error> {
let argv = checked_argv(cmd)?;
let program = match cmd.executable_spec() {
Some(crate::command::ExecutableSpec::Exact(p)) => {
crate::resolve::exact::anchor_posix(p.as_os_str(), cmd.cwd())?
.program
.into_os_string()
}
Some(crate::command::ExecutableSpec::Search(p)) => p.as_os_str().to_os_string(),
None => argv[0].clone(),
};
Ok(Launch {
program,
args: argv[1..].to_vec(),
cwd: cmd.cwd().map(Path::to_path_buf),
})
}
fn reject_structural_posix_config(cmd: &Command, backend: Backend, auth: &Auth) -> Result<(), Error> {
checked_argv(cmd)?;
if let Some(crate::command::ExecutableSpec::Exact(p)) = cmd.executable_spec() {
crate::resolve::exact::refuse_unnameable(p.as_os_str())?;
use std::os::unix::ffi::OsStrExt;
if backend == Backend::Pkexec && p.as_os_str().as_bytes().first() != Some(&b'/') {
return Err(Error::Unsupported {
op: "a relative raw_executable() under pkexec".into(),
platform: "unix",
detail: format!("pkexec requires an absolute program path; pass one instead of {p:?}"),
});
}
}
if backend == Backend::Pkexec {
let program = match cmd.executable_spec() {
Some(spec) => spec.path().as_os_str(),
None => checked_argv(cmd)?[0].as_os_str(),
};
if program_starts_with_dash(program) {
return Err(Error::Unsupported {
op: "elevating a leading-dash program under pkexec".into(),
platform: "unix",
detail: "pkexec cannot parse a `--` terminator, so a program starting with `-` would be taken \
as a pkexec option; use sudo/doas, or a path such as ./-x"
.into(),
});
}
}
if cmd.fds().keys().any(|f| f.raw() >= 3) {
return Err(Error::Unsupported {
op: "fd >= 3 on an elevated POSIX child".into(),
platform: "unix",
detail: "sudo/pkexec closefrom drops fds > 2; fd >= 3 needs the (deferred) broker".into(),
});
}
let ops = cmd.env_ops();
if ops.iter().any(|o| matches!(o, EnvOp::Remove(_) | EnvOp::Clear)) {
return Err(Error::Unsupported {
op: ".env_remove()/.env_clear() + elevate".into(),
platform: "unix",
detail: "the backend builds the elevated base environment; the crate can add but not subtract from it"
.into(),
});
}
if ops.iter().any(|o| matches!(o, EnvOp::Set(..))) && matches!(backend, Backend::Doas | Backend::Pkexec) {
return Err(Error::Unsupported {
op: format!(".env() + Backend::{backend:?}"),
platform: "unix",
detail: "doas and pkexec expose no environment-forwarding mechanism; .env()/.envs() cannot cross them"
.into(),
});
}
if matches!(auth, Auth::Stdin(_)) && cmd.fds().contains_key(&Fd::STDIN) {
return Err(Error::Unsupported {
op: "Auth::Stdin with a caller-configured stdin".into(),
platform: "unix",
detail: "Auth::Stdin consumes fd0 to feed sudo -S the password; do not also configure stdin".into(),
});
}
Ok(())
}
fn transfer_process_attrs(derived: &mut Command, cmd: &Command, cwd: Option<PathBuf>) {
if let Some(d) = cwd {
derived.current_dir(d);
}
derived.set_contain(cmd.contain_request());
derived.kill_on_drop(cmd.kill_on_drop_flag());
}
pub(crate) fn rewrite(cmd: &mut Command) -> Result<PosixRewrite, Error> {
reject_structural(cmd, host_os())?;
let request = cmd.elevation_request();
let host = Host::detect(request.backend, &request.auth);
rewrite_with_host(cmd, &host)
}
fn reject_structural(cmd: &Command, os: Os) -> Result<(), Error> {
let request = cmd.elevation_request();
if super::plan::is_macos_gui_auto(os, request.backend, &request.auth) {
super::macos::reject_structural_gui_config(cmd)
} else {
reject_structural_posix_config(cmd, request.backend, &request.auth)
}
}
pub(crate) fn rewrite_with_host(cmd: &mut Command, host: &Host) -> Result<PosixRewrite, Error> {
rewrite_with_host_and_cwd(cmd, host, std::env::current_dir)
}
pub(crate) fn rewrite_with_host_and_cwd(
cmd: &mut Command,
host: &Host,
process_cwd: impl FnOnce() -> std::io::Result<PathBuf>,
) -> Result<PosixRewrite, Error> {
let requested_backend = cmd.elevation_request().backend;
let requested_auth = cmd.elevation_request().auth.clone();
reject_structural(cmd, host.os)?;
match host.plan(Privilege::Elevated, requested_backend, requested_auth) {
Transition::Reject { error } => Err(error),
Transition::ElevateWindows { .. } => unreachable!("planner never yields ElevateWindows on a unix host"),
Transition::ElevateMacosGui { osascript, arg_max } => {
let launch = super::macos::program_and_args(cmd, process_cwd)?;
let (mut derived, report) = super::macos::build_rewrite(cmd, launch, &osascript, arg_max)?;
derived.set_elevation_front(super::front::front(Some(&report.via)));
Ok(PosixRewrite {
derived: Some(derived),
report: Some(report),
password_write: None,
backend_path: Some(osascript),
})
}
Transition::RunAsIs => {
let (kept, stripped) = cmd.elevation_request().sanitizer.apply(explicit_set_env(cmd.env_ops()));
let env_ops: Vec<EnvOp> = kept.iter().map(|(k, v)| EnvOp::Set(k.clone(), v.clone())).collect();
let mut derived = Command::new();
derived.set_input_argv(checked_argv(cmd)?.to_vec());
derived.set_executable_spec(cmd.executable_spec().cloned());
derived.set_env_ops(env_ops);
transfer_process_attrs(&mut derived, cmd, cmd.cwd().map(Path::to_path_buf));
for (slot, resolved) in std::mem::take(cmd.fds_mut()) {
derived.fds_mut().insert(slot, resolved);
}
Ok(PosixRewrite {
derived: Some(derived),
report: Some(ElevationReport {
via: ElevatedVia::AlreadyElevated,
stripped_env: stripped,
stdio: ElevatedStdio::Passthrough,
}),
password_write: None,
backend_path: None,
})
}
Transition::ElevatePosix { backend, path, auth } => {
let (kept, stripped) = cmd.elevation_request().sanitizer.apply(explicit_set_env(cmd.env_ops()));
if !kept.is_empty() && matches!(backend, Backend::Doas | Backend::Pkexec) {
return Err(Error::Unsupported {
op: format!(".env() + Backend::{backend:?} (resolved via Auto)"),
platform: "unix",
detail:
"doas and pkexec expose no environment-forwarding mechanism; .env()/.envs() cannot cross them"
.into(),
});
}
if backend == Backend::Pkexec {
debug_assert!(
host.pkexec_version != PkexecVersion::NotProbed,
"detect asks a pkexec request's pkexec its version"
);
if let Some(refusal) = host.pkexec_version.refusal() {
return Err(refusal);
}
}
let pinned = match (backend, &host.pkexec_pin) {
(Backend::Pkexec, Some(pin)) => Some(pin.clone()),
(Backend::Pkexec, None) => {
debug_assert!(false, "detect pins every pkexec it stores");
return Err(Error::Elevation {
kind: ElevationErrorKind::BackendUnavailable,
detail: "pkexec was not opened at detection".into(),
});
}
_ => None,
};
let Launch { program, args, cwd } = anchored_program_and_args(cmd)?;
let argv = build_argv(backend, path.as_os_str(), &auth, &program, &args, &kept)?;
let mut new_ops: Vec<EnvOp> = Vec::new();
debug_assert!(
kept.is_empty() || backend == Backend::Sudo,
"only sudo forwards env; {backend:?} with a non-empty env was rejected above"
);
for (k, v) in &kept {
new_ops.push(EnvOp::Set(k.clone(), v.clone()));
}
if let Auth::Askpass(p) = &auth {
new_ops.push(EnvOp::Set(OsString::from("SUDO_ASKPASS"), p.as_os_str().to_os_string()));
}
let mut derived = Command::new();
derived.set_input_argv(argv);
let mut backend_path = path;
if let Some(pin) = pinned {
backend_path = pinned_exec_path(&pin);
derived.set_executable_spec(Some(crate::command::ExecutableSpec::Exact(backend_path.clone())));
derived.hold(pin);
}
derived.set_env_ops(new_ops);
transfer_process_attrs(&mut derived, cmd, cwd);
derived.suppress_fd_marker();
let mut password_write = None;
if let Auth::Stdin(secret) = &auth {
let (reader, writer) = std::io::pipe().map_err(Error::Io)?;
let reader_file = File::from(OwnedFd::from(reader));
derived.stdin(Stdio::from_file(reader_file))?;
password_write = Some(PendingPassword {
writer,
secret: secret.clone(),
});
}
for (slot, resolved) in std::mem::take(cmd.fds_mut()) {
if password_write.is_some() && slot == Fd::STDIN {
continue;
}
derived.fds_mut().insert(slot, resolved);
}
let stdio = if matches!(auth, Auth::Stdin(_)) {
ElevatedStdio::StdinConsumed
} else {
ElevatedStdio::Passthrough
};
let via = ElevatedVia::Wrapped(backend);
derived.set_elevation_front(super::front::front(Some(&via)));
Ok(PosixRewrite {
derived: Some(derived),
report: Some(ElevationReport {
via,
stripped_env: stripped,
stdio,
}),
password_write,
backend_path: Some(backend_path),
})
}
}
}
#[cfg(test)]
#[path = "posix_tests.rs"]
mod posix_tests;