1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
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 args = std::env::args();
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);
}
}