#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Privilege {
Raw,
Connect,
}
impl Privilege {
#[must_use]
pub fn current() -> Self {
if can_send_raw() {
Self::Raw
} else {
Self::Connect
}
}
#[must_use]
pub fn is_raw(self) -> bool {
matches!(self, Self::Raw)
}
pub fn from_raw(raw: bool) -> Self {
if raw { Self::Raw } else { Self::Connect }
}
}
#[must_use]
pub fn can_send_raw() -> bool {
imp::can_send_raw()
}
#[must_use]
pub fn is_elevated() -> bool {
imp::is_elevated()
}
#[cfg(unix)]
mod imp {
pub fn is_elevated() -> bool {
unsafe { libc::geteuid() == 0 }
}
pub fn can_send_raw() -> bool {
let fd = unsafe { libc::socket(libc::AF_INET, libc::SOCK_RAW, libc::IPPROTO_TCP) };
if fd < 0 {
return false;
}
unsafe { libc::close(fd) };
true
}
}
#[cfg(windows)]
mod imp {
use windows_sys::Win32::Foundation::{CloseHandle, HANDLE};
use windows_sys::Win32::Security::{
GetTokenInformation, TOKEN_ELEVATION, TOKEN_QUERY, TokenElevation,
};
use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
pub fn is_elevated() -> bool {
let mut token: HANDLE = std::ptr::null_mut();
if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 {
return false;
}
let mut elevation = TOKEN_ELEVATION { TokenIsElevated: 0 };
let mut returned = 0u32;
let ok = unsafe {
GetTokenInformation(
token,
TokenElevation,
(&raw mut elevation).cast(),
size_of::<TOKEN_ELEVATION>() as u32,
&mut returned,
)
} != 0;
unsafe { CloseHandle(token) };
ok && elevation.TokenIsElevated != 0
}
pub fn can_send_raw() -> bool {
is_elevated()
}
}
#[cfg(not(any(unix, windows)))]
mod imp {
pub fn is_elevated() -> bool {
false
}
pub fn can_send_raw() -> bool {
false
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn being_root_answers_both_questions_the_same_way() {
if is_elevated() {
assert!(can_send_raw(), "root is granted a raw socket");
assert_eq!(Privilege::current(), Privilege::Raw);
} else {
assert_eq!(
Privilege::current(),
Privilege::from_raw(can_send_raw()),
"the distinction is made in one place"
);
}
}
#[test]
fn asking_repeatedly_gives_one_answer() {
let first = can_send_raw();
for _ in 0..64 {
assert_eq!(can_send_raw(), first);
}
}
}