mod log;
mod script;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;
use self::log::LogReader;
use super::{Captured, Exit, OnLine, ProcessError, ProcessRunner, ProcessSpec, capture};
use crate::BoxFuture;
const POLL: Duration = Duration::from_millis(200);
const PROMPT_TIMEOUT: Duration = Duration::from_secs(300);
const MAY_MANAGE: [&str; 2] = ["S-1-16-12288", "S-1-5-32-578"];
#[derive(Debug, Clone, PartialEq, Eq)]
enum Session {
Unchecked,
Direct,
Broker {
dir: PathBuf,
token: String,
},
Failed(String),
}
pub(crate) struct Elevated {
inner: Arc<dyn ProcessRunner>,
root: PathBuf,
session: Mutex<Session>,
opening: tokio::sync::Mutex<()>,
next: AtomicU64,
forwarded: Vec<(String, String)>,
}
impl std::fmt::Debug for Elevated {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Elevated").field("root", &self.root).finish_non_exhaustive()
}
}
impl Elevated {
pub(crate) fn new(inner: Arc<dyn ProcessRunner>, root: PathBuf, forwarded: Vec<(String, String)>) -> Elevated {
Elevated {
inner,
root,
session: Mutex::new(Session::Unchecked),
opening: tokio::sync::Mutex::new(()),
next: AtomicU64::new(1),
forwarded,
}
}
fn session(&self) -> Session {
self.session.lock().unwrap_or_else(PoisonError::into_inner).clone()
}
fn set(&self, s: Session) {
*self.session.lock().unwrap_or_else(PoisonError::into_inner) = s;
}
async fn run_spec(&self, spec: &ProcessSpec, on_line: OnLine<'_>) -> Result<Exit, ProcessError> {
if self.session() == Session::Unchecked {
let _opening = self.opening.lock().await;
if self.session() == Session::Unchecked {
let s = self.open().await;
self.set(s);
}
}
match self.session() {
Session::Direct | Session::Unchecked => self.inner.run(spec, on_line).await,
Session::Failed(reason) => Err(ProcessError::Elevation { reason }),
Session::Broker { dir, token } => self.request(&dir, &token, spec, on_line).await,
}
}
async fn open(&self) -> Session {
if may_manage_hyperv(self.inner.as_ref()).await == Some(true) {
return Session::Direct;
}
self.start_broker().await.unwrap_or_else(Session::Failed)
}
async fn start_broker(&self) -> Result<Session, String> {
let token = token().map_err(|e| format!("no random session token: {e}"))?;
let dir = self.root.join(&token);
fresh_session_dir(&self.root, &dir).map_err(|e| format!("{}: {e}", self.root.display()))?;
let launcher = script::launcher(&script::broker(&dir, &token, std::process::id()));
let start = ProcessSpec::new("powershell", ["-NoProfile".to_owned(), "-NonInteractive".into(), "-Command".into(), launcher]);
match capture(self.inner.as_ref(), &start).await {
Ok(out) if out.success() => {}
Ok(out) => return Err(declined(&out)),
Err(e) => return Err(e.to_string()),
}
if wait_for(&dir.join("ready"), PROMPT_TIMEOUT).await {
Ok(Session::Broker { dir, token })
} else {
Err("the elevated session didn't start".into())
}
}
async fn request(&self, dir: &Path, token: &str, spec: &ProcessSpec, on_line: OnLine<'_>) -> Result<Exit, ProcessError> {
if let Some(why) = refusal(spec) {
return Err(ProcessError::Refused {
program: spec.program.clone(),
why,
});
}
let mut guard = Cancel {
dir,
armed: true,
session: &self.session,
};
let n = self.next.fetch_add(1, Ordering::SeqCst);
let io = |source| ProcessError::Io {
program: spec.program.clone(),
source,
};
crate::store::write_private(&dir.join(format!("env-{n}.json")), env_file(token, n, spec, &self.forwarded).as_bytes()).map_err(io)?;
crate::store::write_private(&dir.join(format!("req-{n}.json")), request_file(token, n, spec).as_bytes()).map_err(io)?;
let mut log_reader = LogReader::default();
let (log, exit) = (dir.join(format!("out-{n}.log")), dir.join(format!("exit-{n}")));
loop {
let done = read_if_there(&exit).map_err(io)?;
log_reader.read(&log, on_line).map_err(io)?;
if let Some(code) = done {
log_reader.finish(on_line);
guard.armed = false;
answered(dir, n).map_err(io)?;
return exit_code(&code).map(|c| Exit::new(Some(c))).map_err(io);
}
if let Some(reason) = ended(dir).map_err(io)? {
guard.armed = false;
self.set(Session::Failed(reason.clone()));
return Err(ProcessError::Elevation { reason });
}
tokio::time::sleep(POLL).await;
}
}
}
impl ProcessRunner for Elevated {
fn run<'a>(&'a self, spec: &'a ProcessSpec, on_line: OnLine<'a>) -> BoxFuture<'a, Result<Exit, ProcessError>> {
Box::pin(self.run_spec(spec, on_line))
}
}
impl Drop for Elevated {
fn drop(&mut self) {
if let Session::Broker { dir, .. } = self.session() {
signal(&dir, "done");
}
if let Err(e) = crate::store::remove_path(&self.root) {
tracing::warn!(error = %e, folder = %self.root.display(), "the elevated session's folder couldn't be removed");
}
}
}
struct Cancel<'a> {
dir: &'a Path,
armed: bool,
session: &'a Mutex<Session>,
}
impl Drop for Cancel<'_> {
fn drop(&mut self) {
if self.armed {
signal(self.dir, "cancel");
*self.session.lock().unwrap_or_else(PoisonError::into_inner) = Session::Failed("the elevated session was ended".into());
}
}
}
fn read_if_there(file: &Path) -> std::io::Result<Option<String>> {
crate::store::if_there(std::fs::read_to_string(file))
}
fn ended(dir: &Path) -> std::io::Result<Option<String>> {
if let Some(reason) = read_if_there(&dir.join("ended"))? {
return Ok(Some(format!("the elevated session ended: {}", reason.trim())));
}
Ok((!dir.try_exists()?).then(|| "the elevated session ended: its folder is gone".to_owned()))
}
fn signal(dir: &Path, what: &str) {
if let Err(e) = std::fs::write(dir.join(what), "") {
tracing::warn!(error = %e, signal = what, "the elevated session couldn't be told");
}
}
fn fresh_session_dir(root: &Path, dir: &Path) -> std::io::Result<()> {
crate::store::remove_path(root)?;
crate::store::private_dir(dir)
}
fn answered(dir: &Path, n: u64) -> std::io::Result<()> {
for file in [format!("out-{n}.log"), format!("exit-{n}"), format!("env-{n}.json")] {
crate::store::remove_path(&dir.join(file))?;
}
Ok(())
}
fn token() -> Result<String, getrandom::Error> {
let mut bytes = [0u8; 16];
getrandom::fill(&mut bytes)?;
Ok(bytes.iter().fold(String::with_capacity(32), |mut hex, b| {
hex.extend(char::from_digit(u32::from(b >> 4), 16));
hex.extend(char::from_digit(u32::from(b & 15), 16));
hex
}))
}
fn refusal(spec: &ProcessSpec) -> Option<String> {
if let Some(arg) = spec.args.iter().find(|a| !script::passes_intact(a)) {
return Some(format!("its argument `{}` wouldn't reach it intact through PowerShell", arg.escape_debug()));
}
spec.stdin
.as_ref()
.map(|stdin| format!("an elevated call can't be given a standard input ({})", stdin.display()))
}
fn exit_code(text: &str) -> std::io::Result<i32> {
text.trim().parse().map_err(|_| {
let why = format!("the elevated broker answered `{}`, not an exit code", text.trim().escape_debug());
std::io::Error::new(std::io::ErrorKind::InvalidData, why)
})
}
pub async fn may_manage_hyperv(processes: &dyn ProcessRunner) -> Option<bool> {
let whoami = ProcessSpec::new("whoami", ["/groups", "/fo", "csv", "/nh"]);
match capture(processes, &whoami).await {
Ok(out) if out.success() => Some(may_manage(&out.stdout.join("\n"))),
Ok(out) => {
tracing::warn!(stderr = %out.stderr.join("\n"), "`whoami /groups` failed: whether this account may manage Hyper-V is unknown");
None
}
Err(e) => {
tracing::warn!(error = %e, "`whoami /groups` didn't run: whether this account may manage Hyper-V is unknown");
None
}
}
}
fn may_manage(groups: &str) -> bool {
groups.lines().any(|l| MAY_MANAGE.iter().any(|sid| l.contains(&format!("\"{sid}\""))))
}
fn request_file(token: &str, n: u64, spec: &ProcessSpec) -> String {
serde_json::json!({
"session": token,
"seq": n,
"program": spec.program,
"args": spec.args,
"cwd": spec.cwd.as_ref().map_or_else(|| ".".into(), |c| c.display().to_string()),
})
.to_string()
}
fn env_file(token: &str, n: u64, spec: &ProcessSpec, forwarded: &[(String, String)]) -> String {
let mut env: Vec<(String, String)> = forwarded.to_vec();
for (k, v) in &spec.env {
env.retain(|(o, _)| !o.eq_ignore_ascii_case(k));
env.push((k.clone(), v.clone()));
}
serde_json::json!({
"session": token,
"seq": n,
"env": env.iter().map(|(k, v)| serde_json::json!({ "k": k, "v": v })).collect::<Vec<_>>(),
})
.to_string()
}
fn declined(out: &Captured) -> String {
let cancelled = |l: &String| l.contains("canceled by the user") || l.contains("cancelled by the user");
if out.stderr.iter().any(cancelled) {
"the Windows permission prompt was declined".into()
} else {
format!("the elevated session didn't start: {}", out.reason())
}
}
async fn wait_for(file: &Path, limit: Duration) -> bool {
let deadline = tokio::time::Instant::now() + limit;
while tokio::time::Instant::now() < deadline {
if file.exists() {
return true;
}
tokio::time::sleep(POLL).await;
}
file.exists()
}
#[cfg(test)]
mod tests;