use std::error::Error;
use std::process::Command;
#[macro_use]
extern crate log;
#[derive(Debug, PartialEq)]
pub enum RunningAs {
Root,
User,
Suid,
}
use RunningAs::*;
#[cfg(unix)]
pub fn check() -> RunningAs {
let uid = unsafe { libc::getuid() };
let euid = unsafe { libc::geteuid() };
match (uid, euid) {
(0, 0) => Root,
(_, 0) => Suid,
(_, _) => User,
}
}
#[cfg(unix)]
#[inline]
pub fn escalate_if_needed() -> Result<RunningAs, Box<dyn Error>> {
with_env(&[])
}
#[cfg(unix)]
pub fn with_env(prefixes: &[&str]) -> Result<RunningAs, Box<dyn Error>> {
let current = check();
trace!("Running as {:?}", current);
match current {
Root => {
trace!("already running as Root");
return Ok(current);
}
Suid => {
trace!("setuid(0)");
unsafe {
libc::setuid(0);
}
return Ok(current);
}
User => {
debug!("Escalating privileges");
}
}
let mut args: Vec<_> = std::env::args().collect();
if let Some(absolute_path) = std::env::current_exe()
.ok()
.and_then(|p| p.to_str().map(|p| p.to_string()))
{
args[0] = absolute_path;
}
let mut command: Command = Command::new("/usr/bin/sudo");
if let Ok(trace) = std::env::var("RUST_BACKTRACE") {
let value = match &*trace.to_lowercase() {
"" => None,
"1" | "true" => Some("1"),
"full" => Some("full"),
invalid => {
warn!(
"RUST_BACKTRACE has invalid value {:?} -> defaulting to \"full\"",
invalid
);
Some("full")
}
};
if let Some(value) = value {
trace!("relaying RUST_BACKTRACE={}", value);
command.arg(format!("RUST_BACKTRACE={}", value));
}
}
if prefixes.is_empty() == false {
for (name, value) in std::env::vars().filter(|(name, _)| name != "RUST_BACKTRACE") {
if prefixes.iter().any(|prefix| name.starts_with(prefix)) {
trace!("propagating {}={}", name, value);
command.arg(format!("{}={}", name, value));
}
}
}
let mut child = command.args(args).spawn().expect("failed to execute child");
let ecode = child.wait().expect("failed to wait on child");
if ecode.success() == false {
std::process::exit(ecode.code().unwrap_or(1));
} else {
std::process::exit(0);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let c = check();
assert!(true, "{:?}", c);
}
}