mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-18 22:16:18 -05:00
feat: build and publish Windows NSH packages with verified updates
This commit is contained in:
113 files changed
+7264
-801
No files matched your search
@@ -10,6 +10,7 @@ pub enum AnchorSource {
|
||||
UnixMac,
|
||||
UnixRandom,
|
||||
MacosIokit,
|
||||
WindowsSmbios,
|
||||
}
|
||||
|
||||
impl From<AnchorSource> for u8 {
|
||||
@@ -18,6 +19,7 @@ impl From<AnchorSource> for u8 {
|
||||
AnchorSource::UnixMac => 1,
|
||||
AnchorSource::UnixRandom => 2,
|
||||
AnchorSource::MacosIokit => 3,
|
||||
AnchorSource::WindowsSmbios => 4,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -41,6 +43,7 @@ impl TryFrom<u8> for AnchorSource {
|
||||
1 => Ok(Self::UnixMac),
|
||||
2 => Ok(Self::UnixRandom),
|
||||
3 => Ok(Self::MacosIokit),
|
||||
4 => Ok(Self::WindowsSmbios),
|
||||
value => Err(InvalidAnchorSource(value)),
|
||||
}
|
||||
}
|
||||
@@ -65,6 +68,7 @@ impl DeviceAnchor {
|
||||
AnchorSource::UnixMac => b"gp-device-anchor:v1:unix-mac:".as_slice(),
|
||||
AnchorSource::UnixRandom => b"gp-device-anchor:v1:unix-random:".as_slice(),
|
||||
AnchorSource::MacosIokit => b"gp-device-anchor:v1:macos-platform-uuid:".as_slice(),
|
||||
AnchorSource::WindowsSmbios => b"gp-device-anchor:v1:windows-smbios-uuid:".as_slice(),
|
||||
};
|
||||
let mut input = domain.to_vec();
|
||||
input.extend_from_slice(seed.as_ref());
|
||||
@@ -81,7 +85,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn preserves_existing_hardware_ids_for_all_sources() {
|
||||
let cases: [(AnchorSource, &[u8], &str); 3] = [
|
||||
let cases: [(AnchorSource, &[u8], &str); 4] = [
|
||||
(
|
||||
AnchorSource::UnixMac,
|
||||
&[0, 17, 34, 51, 68, 85],
|
||||
@@ -97,6 +101,11 @@ mod tests {
|
||||
b"12345678-1234-5678-9abc-def012345678",
|
||||
"K1KMtAwiOiXKQvQuRmTDKPA6-ZPF5QKUWZzmvRzeP34",
|
||||
),
|
||||
(
|
||||
AnchorSource::WindowsSmbios,
|
||||
b"12345678-1234-5678-9abc-def012345678",
|
||||
"C843jG-lDX91Tab02VelrMJl_OmOji_pCtNWilwzW5s",
|
||||
),
|
||||
];
|
||||
for (source, seed, expected) in cases {
|
||||
let anchor = DeviceAnchor::derive(source, seed);
|
||||
@@ -124,12 +133,17 @@ mod tests {
|
||||
assert_eq!(serde_json::to_string(&AnchorSource::UnixMac).unwrap(), "1");
|
||||
assert_eq!(serde_json::to_string(&AnchorSource::UnixRandom).unwrap(), "2");
|
||||
assert_eq!(serde_json::to_string(&AnchorSource::MacosIokit).unwrap(), "3");
|
||||
assert_eq!(serde_json::to_string(&AnchorSource::WindowsSmbios).unwrap(), "4");
|
||||
assert_eq!(
|
||||
serde_json::from_str::<AnchorSource>("4").unwrap(),
|
||||
AnchorSource::WindowsSmbios
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::from_str::<AnchorSource>("1").unwrap(),
|
||||
AnchorSource::UnixMac
|
||||
);
|
||||
assert!(serde_json::from_str::<AnchorSource>("0").is_err());
|
||||
assert!(serde_json::from_str::<AnchorSource>("4").is_err());
|
||||
assert!(serde_json::from_str::<AnchorSource>("5").is_err());
|
||||
assert!(serde_json::from_str::<AnchorSource>(r#""unix_mac""#).is_err());
|
||||
}
|
||||
}
|
||||
@@ -31,3 +31,6 @@ pub mod clap;
|
||||
|
||||
#[cfg(feature = "desktop")]
|
||||
pub mod script_tun;
|
||||
|
||||
#[cfg(all(feature = "desktop", windows))]
|
||||
pub mod windows;
|
||||
@@ -236,7 +236,7 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
}
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
{
|
||||
if self.browser.is_none() {
|
||||
if self.hidpi {
|
||||
auth_cmd.arg("--hidpi");
|
||||
}
|
||||
@@ -409,6 +409,42 @@ mod tests {
|
||||
assert!(args.iter().any(|arg| arg == "--ignore-tls-errors"));
|
||||
}
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
#[test]
|
||||
fn external_browser_receives_no_embedded_window_arguments() {
|
||||
let args = child_args(
|
||||
SamlAuthLauncher::new("vpn.example.com")
|
||||
.browser(Some("edge"))
|
||||
.clean(true)
|
||||
.hidpi(true)
|
||||
.window_title("GP Connect Login")
|
||||
.window_theme(AuthWindowTheme::Dark),
|
||||
);
|
||||
assert!(args.windows(2).any(|pair| pair == ["--browser", "edge"]));
|
||||
for option in ["--clean", "--hidpi", "--window-title", "--window-theme"] {
|
||||
assert!(!args.iter().any(|arg| arg == option), "unexpected {option} in {args:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
#[test]
|
||||
fn embedded_window_receives_auth_preferences() {
|
||||
let args = child_args(
|
||||
SamlAuthLauncher::new("vpn.example.com")
|
||||
.clean(true)
|
||||
.window_title("GP Connect Login")
|
||||
.window_theme(AuthWindowTheme::Dark),
|
||||
);
|
||||
assert!(args.iter().any(|arg| arg == "--clean"));
|
||||
assert!(
|
||||
args
|
||||
.windows(2)
|
||||
.any(|pair| pair == ["--window-title", "GP Connect Login"])
|
||||
);
|
||||
assert!(args.windows(2).any(|pair| pair == ["--window-theme", "dark"]));
|
||||
assert!(!args.iter().any(|arg| arg == "--browser"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn os_profile_sets_os_from_profile() {
|
||||
let profile = OsProfileBuilder::new(ClientOs::Linux)
|
||||
|
||||
@@ -1,20 +1,41 @@
|
||||
#[cfg(unix)]
|
||||
mod command_runner;
|
||||
#[cfg(windows)]
|
||||
#[path = "windows/command_runner.rs"]
|
||||
mod command_runner;
|
||||
#[cfg(unix)]
|
||||
mod command_traits;
|
||||
#[cfg(windows)]
|
||||
#[path = "windows/command_traits.rs"]
|
||||
mod command_traits;
|
||||
#[cfg(unix)]
|
||||
mod desktop_child;
|
||||
#[cfg(unix)]
|
||||
mod desktop_session_env;
|
||||
#[cfg(unix)]
|
||||
pub(crate) mod gui_helper_launcher;
|
||||
|
||||
pub use command_traits::CommandExt;
|
||||
|
||||
pub mod auth_launcher;
|
||||
#[cfg(unix)]
|
||||
pub mod desktop_launcher;
|
||||
#[cfg(unix)]
|
||||
pub mod gui_launcher;
|
||||
#[cfg(any(target_os = "linux", test))]
|
||||
pub mod gui_switch;
|
||||
#[cfg(any(target_os = "linux", test))]
|
||||
mod nsh_runtime;
|
||||
#[cfg(unix)]
|
||||
pub mod users;
|
||||
|
||||
#[cfg(unix)]
|
||||
pub mod collection;
|
||||
#[cfg(windows)]
|
||||
#[path = "windows/collection.rs"]
|
||||
pub mod collection;
|
||||
|
||||
pub mod rendering_recovery;
|
||||
#[cfg(windows)]
|
||||
#[path = "windows/user_process.rs"]
|
||||
pub mod user_process;
|
||||
@@ -49,11 +49,17 @@ impl RecoveryState {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
pub(crate) fn is_crash_exit(status: ExitStatus) -> bool {
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
!status.success() && !matches!(status.signal(), Some(1 | 2 | 9 | 15))
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn is_crash_exit(status: ExitStatus) -> bool {
|
||||
status.code().is_some_and(|code| (code as u32) >= 0xC0000000)
|
||||
}
|
||||
|
||||
pub fn eligible(command: &Command) -> bool {
|
||||
eligible_with_inheritance(command, true)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
//! Resolve system collectors from Windows' system directory, never the working directory.
|
||||
use super::command_runner::run_controlled;
|
||||
use crate::collection::CollectionControl;
|
||||
use std::{
|
||||
io,
|
||||
path::{Path, PathBuf},
|
||||
process::{Command, Output},
|
||||
};
|
||||
|
||||
pub struct CollectorCommands<'a> {
|
||||
control: &'a dyn CollectionControl,
|
||||
}
|
||||
impl<'a> CollectorCommands<'a> {
|
||||
pub fn new(control: &'a dyn CollectionControl) -> Self {
|
||||
Self { control }
|
||||
}
|
||||
pub fn resolve(&self, name: &str) -> Option<PathBuf> {
|
||||
let system = std::env::var_os("SystemRoot")?;
|
||||
let path = PathBuf::from(system).join("System32").join(name).with_extension("exe");
|
||||
path.is_file().then_some(path)
|
||||
}
|
||||
pub fn run(&self, name: &str, args: &[&str]) -> io::Result<Option<Output>> {
|
||||
self.control.check()?;
|
||||
match self.resolve(name) {
|
||||
Some(path) => self.run_path(&path, args),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
pub fn run_executable(&self, path: &Path, args: &[&str]) -> io::Result<Option<Output>> {
|
||||
self.run_path(path, args)
|
||||
}
|
||||
pub fn run_path(&self, path: &Path, args: &[&str]) -> io::Result<Option<Output>> {
|
||||
self.control.check()?;
|
||||
let mut command = Command::new(path);
|
||||
command.args(args);
|
||||
match run_controlled(command, self.control, 256 * 1024) {
|
||||
Ok(output) => Ok(Some(output)),
|
||||
Err(error) if matches!(error.kind(), io::ErrorKind::NotFound | io::ErrorKind::PermissionDenied) => Ok(None),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
//! Controlled Windows child execution. Pipe polling keeps cancellation responsive.
|
||||
use crate::collection::CollectionControl;
|
||||
use std::{
|
||||
io::{self, Read, Write},
|
||||
os::windows::io::AsRawHandle,
|
||||
process::{Child, Command, Output, Stdio},
|
||||
thread,
|
||||
time::Duration,
|
||||
};
|
||||
use windows_sys::Win32::System::Pipes::PeekNamedPipe;
|
||||
|
||||
pub(crate) enum ChildInput<'a> {
|
||||
Null,
|
||||
Terminal,
|
||||
// Preserve the borrowed input type shared by callers without a Windows launcher.
|
||||
#[allow(dead_code)]
|
||||
Frame(&'a [u8]),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ObservedOutput {
|
||||
pub output: Output,
|
||||
}
|
||||
|
||||
pub(crate) fn run_controlled(command: Command, control: &dyn CollectionControl, limit: usize) -> io::Result<Output> {
|
||||
run_observed(
|
||||
command,
|
||||
control,
|
||||
Some(limit),
|
||||
&mut |_| {},
|
||||
&mut io::sink(),
|
||||
ChildInput::Null,
|
||||
)
|
||||
.map(|observed| observed.output)
|
||||
}
|
||||
|
||||
pub(crate) fn run_observed(
|
||||
mut command: Command,
|
||||
control: &dyn CollectionControl,
|
||||
output_limit: Option<usize>,
|
||||
observer: &mut dyn FnMut(&[u8]),
|
||||
stderr_sink: &mut dyn Write,
|
||||
stdin: ChildInput<'_>,
|
||||
) -> io::Result<ObservedOutput> {
|
||||
control.check()?;
|
||||
// Windows desktop processes must not open a console for each helper.
|
||||
use std::os::windows::process::CommandExt;
|
||||
if !matches!(stdin, ChildInput::Terminal) {
|
||||
command.creation_flags(0x08000000); // CREATE_NO_WINDOW
|
||||
}
|
||||
command.stdout(if output_limit.is_some() {
|
||||
Stdio::piped()
|
||||
} else {
|
||||
Stdio::inherit()
|
||||
});
|
||||
command.stderr(Stdio::piped());
|
||||
command.stdin(match stdin {
|
||||
ChildInput::Terminal => Stdio::inherit(),
|
||||
ChildInput::Null => Stdio::null(),
|
||||
ChildInput::Frame(_) => Stdio::piped(),
|
||||
});
|
||||
let mut child = ControlledChild(command.spawn()?);
|
||||
let input = if let ChildInput::Frame(frame) = stdin {
|
||||
let mut pipe = child.0.stdin.take().expect("piped stdin");
|
||||
let frame = frame.to_vec();
|
||||
Some(thread::spawn(move || pipe.write_all(&frame)))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut stdout = child.0.stdout.take();
|
||||
let mut stderr = child.0.stderr.take().expect("piped stderr");
|
||||
let mut output = Vec::new();
|
||||
let mut buffer = [0u8; 8192];
|
||||
loop {
|
||||
control.check()?;
|
||||
if let Some(pipe) = &mut stdout {
|
||||
let length = read_available(pipe, &mut buffer)?;
|
||||
if length > output_limit.unwrap().saturating_sub(output.len()) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"Command output exceeds its limit",
|
||||
));
|
||||
}
|
||||
output.extend_from_slice(&buffer[..length]);
|
||||
}
|
||||
let length = read_available(&mut stderr, &mut buffer)?;
|
||||
observer(&buffer[..length]);
|
||||
stderr_sink.write_all(&buffer[..length])?;
|
||||
if let Some(status) = child.0.try_wait()? {
|
||||
// Drain the remaining buffered output after the process exits.
|
||||
if let Some(pipe) = &mut stdout {
|
||||
loop {
|
||||
let length = read_available(pipe, &mut buffer)?;
|
||||
if length == 0 {
|
||||
break;
|
||||
}
|
||||
if length > output_limit.unwrap().saturating_sub(output.len()) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"Command output exceeds its limit",
|
||||
));
|
||||
}
|
||||
output.extend_from_slice(&buffer[..length]);
|
||||
}
|
||||
}
|
||||
loop {
|
||||
let length = read_available(&mut stderr, &mut buffer)?;
|
||||
if length == 0 {
|
||||
break;
|
||||
}
|
||||
observer(&buffer[..length]);
|
||||
stderr_sink.write_all(&buffer[..length])?;
|
||||
}
|
||||
if let Some(result) = input.and_then(|worker| worker.join().ok()) {
|
||||
result?;
|
||||
}
|
||||
return Ok(ObservedOutput {
|
||||
output: Output {
|
||||
status,
|
||||
stdout: output,
|
||||
stderr: Vec::new(),
|
||||
},
|
||||
});
|
||||
}
|
||||
thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
}
|
||||
|
||||
fn read_available(pipe: &mut (impl Read + AsRawHandle), buffer: &mut [u8]) -> io::Result<usize> {
|
||||
let mut available = 0;
|
||||
let success = unsafe {
|
||||
PeekNamedPipe(
|
||||
pipe.as_raw_handle(),
|
||||
std::ptr::null_mut(),
|
||||
0,
|
||||
std::ptr::null_mut(),
|
||||
&mut available,
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
if success == 0 {
|
||||
let error = io::Error::last_os_error();
|
||||
if error.raw_os_error() == Some(109) {
|
||||
return Ok(0);
|
||||
} // ERROR_BROKEN_PIPE
|
||||
return Err(error);
|
||||
}
|
||||
let length = buffer.len().min(available as usize);
|
||||
if length == 0 {
|
||||
return Ok(0);
|
||||
}
|
||||
pipe.read(&mut buffer[..length])
|
||||
}
|
||||
|
||||
struct ControlledChild(Child);
|
||||
impl Drop for ControlledChild {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.0.kill();
|
||||
let _ = self.0.wait();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn captures_output_and_rejects_excess_output() {
|
||||
let mut command = Command::new("cmd.exe");
|
||||
command.args(["/D", "/C", "echo hello"]);
|
||||
let result = run_controlled(command, &|| Ok(()), 1024).unwrap();
|
||||
assert!(result.status.success());
|
||||
assert_eq!(String::from_utf8(result.stdout).unwrap().trim(), "hello");
|
||||
let mut command = Command::new("cmd.exe");
|
||||
command.args(["/D", "/C", "echo too much"]);
|
||||
assert_eq!(
|
||||
run_controlled(command, &|| Ok(()), 2).unwrap_err().kind(),
|
||||
io::ErrorKind::InvalidData
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn cancels_a_running_helper() {
|
||||
let start = std::time::Instant::now();
|
||||
let mut command = Command::new("powershell.exe");
|
||||
command.args(["-NoProfile", "-Command", "Start-Sleep -Seconds 30"]);
|
||||
let control = || {
|
||||
if start.elapsed() > Duration::from_millis(150) {
|
||||
Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
assert_eq!(
|
||||
run_controlled(command, &control, 1024).unwrap_err().kind(),
|
||||
io::ErrorKind::Interrupted
|
||||
);
|
||||
assert!(start.elapsed() < Duration::from_secs(3));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
use tokio::process::Command;
|
||||
|
||||
/// Windows authentication runs in the interactive user's GUI process.
|
||||
pub trait CommandExt {
|
||||
fn into_non_root(self) -> anyhow::Result<Command>;
|
||||
}
|
||||
|
||||
impl CommandExt for Command {
|
||||
fn into_non_root(self) -> anyhow::Result<Command> {
|
||||
Ok(self)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
//! Launch a native worker with the admitted user's primary token and environment.
|
||||
use std::{
|
||||
ffi::{OsStr, c_void},
|
||||
io,
|
||||
os::windows::{
|
||||
ffi::OsStrExt,
|
||||
io::{AsRawHandle, BorrowedHandle, FromRawHandle, OwnedHandle},
|
||||
},
|
||||
path::Path,
|
||||
ptr,
|
||||
};
|
||||
use windows_sys::Win32::{
|
||||
Foundation::{WAIT_OBJECT_0, WAIT_TIMEOUT},
|
||||
Globalization::{CSTR_EQUAL, CompareStringOrdinal},
|
||||
Security::{ImpersonateLoggedOnUser, RevertToSelf},
|
||||
System::{
|
||||
Environment::{CreateEnvironmentBlock, DestroyEnvironmentBlock},
|
||||
JobObjects::*,
|
||||
Threading::*,
|
||||
},
|
||||
};
|
||||
|
||||
pub struct UserProcess {
|
||||
process: OwnedHandle,
|
||||
job: Option<OwnedHandle>,
|
||||
pid: u32,
|
||||
}
|
||||
struct Environment(*mut c_void);
|
||||
impl Drop for Environment {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
DestroyEnvironmentBlock(self.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
fn invalid(message: &str) -> io::Error {
|
||||
io::Error::new(io::ErrorKind::InvalidInput, message)
|
||||
}
|
||||
fn wide(value: &OsStr) -> io::Result<Vec<u16>> {
|
||||
let value: Vec<_> = value.encode_wide().collect();
|
||||
if value.contains(&0) {
|
||||
return Err(invalid("Windows process strings cannot contain NUL"));
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
fn quote(argument: &[u16], output: &mut Vec<u16>) {
|
||||
output.push(b'"' as u16);
|
||||
let mut backslashes = 0;
|
||||
for &character in argument {
|
||||
if character == b'\\' as u16 {
|
||||
backslashes += 1;
|
||||
continue;
|
||||
}
|
||||
let count = if character == b'"' as u16 {
|
||||
backslashes * 2 + 1
|
||||
} else {
|
||||
backslashes
|
||||
};
|
||||
output.extend(std::iter::repeat_n(b'\\' as u16, count));
|
||||
output.push(character);
|
||||
backslashes = 0;
|
||||
}
|
||||
output.extend(std::iter::repeat_n(b'\\' as u16, backslashes * 2));
|
||||
output.push(b'"' as u16);
|
||||
}
|
||||
fn command_line(program: &[u16], arguments: &[String]) -> io::Result<Vec<u16>> {
|
||||
let mut output = Vec::new();
|
||||
quote(program, &mut output);
|
||||
for argument in arguments {
|
||||
output.push(b' ' as u16);
|
||||
quote(&wide(OsStr::new(argument))?, &mut output);
|
||||
}
|
||||
output.push(0);
|
||||
if output.len() > 32767 {
|
||||
return Err(invalid("Windows worker command line is too long"));
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
fn key(entry: &[u16]) -> &[u16] {
|
||||
let end = entry
|
||||
.iter()
|
||||
.enumerate()
|
||||
.find(|(index, value)| *index != 0 && **value == b'=' as u16)
|
||||
.map(|(index, _)| index)
|
||||
.unwrap_or(entry.len());
|
||||
&entry[..end]
|
||||
}
|
||||
fn compare(left: &[u16], right: &[u16]) -> std::cmp::Ordering {
|
||||
// Environment names follow Windows' ordinal, case-insensitive ordering.
|
||||
unsafe { CompareStringOrdinal(left.as_ptr(), left.len() as i32, right.as_ptr(), right.len() as i32, 1) }
|
||||
.cmp(&CSTR_EQUAL)
|
||||
}
|
||||
fn user_environment(token: BorrowedHandle<'_>, variables: &[(&str, &str)]) -> io::Result<Vec<u16>> {
|
||||
let mut pointer = ptr::null_mut();
|
||||
if unsafe { CreateEnvironmentBlock(&mut pointer, token.as_raw_handle(), 0) } == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let environment = Environment(pointer);
|
||||
let mut entries = Vec::new();
|
||||
unsafe {
|
||||
let mut current = environment.0.cast::<u16>();
|
||||
while *current != 0 {
|
||||
let mut length = 0;
|
||||
while *current.add(length) != 0 {
|
||||
length += 1;
|
||||
}
|
||||
entries.push(std::slice::from_raw_parts(current, length).to_vec());
|
||||
current = current.add(length + 1);
|
||||
}
|
||||
}
|
||||
for (name, value) in variables {
|
||||
if name.is_empty() || name.contains('=') {
|
||||
return Err(invalid("Invalid worker environment name"));
|
||||
}
|
||||
let name = wide(OsStr::new(name))?;
|
||||
let value = wide(OsStr::new(value))?;
|
||||
entries.retain(|entry| compare(key(entry), &name) != std::cmp::Ordering::Equal);
|
||||
let mut entry = name;
|
||||
entry.push(b'=' as u16);
|
||||
entry.extend(value);
|
||||
entries.push(entry);
|
||||
}
|
||||
entries.sort_by(|left, right| compare(key(left), key(right)));
|
||||
let mut block = Vec::new();
|
||||
for entry in entries {
|
||||
block.extend(entry);
|
||||
block.push(0);
|
||||
}
|
||||
if block.is_empty() {
|
||||
block.push(0);
|
||||
}
|
||||
block.push(0);
|
||||
Ok(block)
|
||||
}
|
||||
impl UserProcess {
|
||||
/// No service handles or service environment are inherited. The user token
|
||||
/// determines the Windows session, including an existing interactive desktop.
|
||||
pub fn launch(
|
||||
token: BorrowedHandle<'_>,
|
||||
program: &Path,
|
||||
arguments: &[String],
|
||||
variables: &[(&str, &str)],
|
||||
) -> io::Result<Self> {
|
||||
if !program.is_absolute() {
|
||||
return Err(invalid("Windows worker executable must be absolute"));
|
||||
}
|
||||
let mut executable = wide(program.as_os_str())?;
|
||||
let mut command = command_line(&executable, arguments)?;
|
||||
executable.push(0);
|
||||
let mut environment = user_environment(token, variables)?;
|
||||
let directory = program.parent().ok_or_else(|| invalid("Worker directory is missing"))?;
|
||||
let mut directory = wide(directory.as_os_str())?;
|
||||
directory.push(0);
|
||||
let job = unsafe { CreateJobObjectW(ptr::null(), ptr::null()) };
|
||||
if job.is_null() {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let job = unsafe { OwnedHandle::from_raw_handle(job) };
|
||||
let limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION {
|
||||
BasicLimitInformation: JOBOBJECT_BASIC_LIMIT_INFORMATION {
|
||||
LimitFlags: JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
if unsafe {
|
||||
SetInformationJobObject(
|
||||
job.as_raw_handle(),
|
||||
JobObjectExtendedLimitInformation,
|
||||
(&limits as *const JOBOBJECT_EXTENDED_LIMIT_INFORMATION).cast(),
|
||||
std::mem::size_of_val(&limits) as u32,
|
||||
)
|
||||
} == 0
|
||||
{
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let mut desktop: Vec<u16> = "winsta0\\default".encode_utf16().chain(Some(0)).collect();
|
||||
let startup = STARTUPINFOW {
|
||||
cb: std::mem::size_of::<STARTUPINFOW>() as u32,
|
||||
lpDesktop: desktop.as_mut_ptr(),
|
||||
..Default::default()
|
||||
};
|
||||
let mut information = PROCESS_INFORMATION::default();
|
||||
// Read/execute the requested image as its user, as Unix exec-after-setuid
|
||||
// does. The service's filesystem access must not authorize a private image.
|
||||
if unsafe { ImpersonateLoggedOnUser(token.as_raw_handle()) } == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
struct Revert;
|
||||
impl Drop for Revert {
|
||||
fn drop(&mut self) {
|
||||
if unsafe { RevertToSelf() } == 0 {
|
||||
std::process::abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
let revert = Revert;
|
||||
let created = unsafe {
|
||||
CreateProcessAsUserW(
|
||||
token.as_raw_handle(),
|
||||
executable.as_ptr(),
|
||||
command.as_mut_ptr(),
|
||||
ptr::null(),
|
||||
ptr::null(),
|
||||
0,
|
||||
CREATE_UNICODE_ENVIRONMENT | CREATE_SUSPENDED | CREATE_NO_WINDOW,
|
||||
environment.as_mut_ptr().cast(),
|
||||
directory.as_ptr(),
|
||||
&startup,
|
||||
&mut information,
|
||||
)
|
||||
};
|
||||
let error = (created == 0).then(io::Error::last_os_error);
|
||||
drop(revert);
|
||||
if let Some(error) = error {
|
||||
return Err(error);
|
||||
}
|
||||
let process = unsafe { OwnedHandle::from_raw_handle(information.hProcess) };
|
||||
let thread = unsafe { OwnedHandle::from_raw_handle(information.hThread) };
|
||||
if unsafe { AssignProcessToJobObject(job.as_raw_handle(), process.as_raw_handle()) } == 0 {
|
||||
let error = io::Error::last_os_error();
|
||||
// The suspended child is not owned by the job on this failure path.
|
||||
unsafe {
|
||||
TerminateProcess(process.as_raw_handle(), 1);
|
||||
WaitForSingleObject(process.as_raw_handle(), 5000);
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
let child = Self {
|
||||
process,
|
||||
job: Some(job),
|
||||
pid: information.dwProcessId,
|
||||
};
|
||||
if unsafe { ResumeThread(thread.as_raw_handle()) } == u32::MAX {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Ok(child)
|
||||
}
|
||||
pub fn id(&self) -> u32 {
|
||||
self.pid
|
||||
}
|
||||
pub fn has_exited(&self) -> io::Result<bool> {
|
||||
match unsafe { WaitForSingleObject(self.process.as_raw_handle(), 0) } {
|
||||
WAIT_OBJECT_0 => Ok(true),
|
||||
WAIT_TIMEOUT => Ok(false),
|
||||
_ => Err(io::Error::last_os_error()),
|
||||
}
|
||||
}
|
||||
pub fn stop(&mut self) -> io::Result<()> {
|
||||
if self.job.take().is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
match unsafe { WaitForSingleObject(self.process.as_raw_handle(), 5000) } {
|
||||
WAIT_OBJECT_0 => Ok(()),
|
||||
WAIT_TIMEOUT => Err(io::Error::new(
|
||||
io::ErrorKind::TimedOut,
|
||||
"Windows worker did not terminate",
|
||||
)),
|
||||
_ => Err(io::Error::last_os_error()),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Drop for UserProcess {
|
||||
fn drop(&mut self) {
|
||||
if let Err(error) = self.stop() {
|
||||
log::warn!("Could not stop Windows worker: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use windows_sys::Win32::{Foundation::LocalFree, UI::Shell::CommandLineToArgvW};
|
||||
#[test]
|
||||
fn command_line_round_trips_through_windows_parser() {
|
||||
let program: Vec<u16> = r"C:\Program Files\GP Connect\gpgui-nsh.exe".encode_utf16().collect();
|
||||
let arguments = [
|
||||
"proxy-worker",
|
||||
"",
|
||||
"space value",
|
||||
"quoted\"value",
|
||||
"two\\\\\"quotes",
|
||||
"trailing\\",
|
||||
"雪",
|
||||
"&|<>",
|
||||
]
|
||||
.map(String::from);
|
||||
let command = command_line(&program, &arguments).unwrap();
|
||||
let mut count = 0;
|
||||
unsafe {
|
||||
let parsed = CommandLineToArgvW(command.as_ptr(), &mut count);
|
||||
assert!(!parsed.is_null());
|
||||
let result = std::slice::from_raw_parts(parsed, count as usize)
|
||||
.iter()
|
||||
.map(|&value| {
|
||||
let mut length = 0;
|
||||
while *value.add(length) != 0 {
|
||||
length += 1;
|
||||
}
|
||||
String::from_utf16_lossy(std::slice::from_raw_parts(value, length))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
LocalFree(parsed.cast());
|
||||
assert_eq!(result[0], String::from_utf16_lossy(&program));
|
||||
assert_eq!(result[1..], arguments);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,8 @@ pub use message::{ClientMessage, ServerMessage, ServiceRejection, ServiceResult}
|
||||
pub use noise::{NoiseInitiator, NoiseResponder, NoiseTransport};
|
||||
|
||||
pub const MAX_CREDENTIAL_FRAME: usize = 512;
|
||||
/// First request read before a Windows service captures its pipe client's token.
|
||||
pub const WINDOWS_ADMISSION_REQUEST: [u8; 4] = *b"GPC1";
|
||||
pub const MAX_PRELUDE: usize = 256;
|
||||
pub const MAX_PRODUCT_VERSION: usize = 64;
|
||||
pub const HIP_PROTOCOL_VERSION: u16 = 1;
|
||||
|
||||
@@ -29,6 +29,11 @@ use linux as platform;
|
||||
#[cfg(target_os = "macos")]
|
||||
use macos as platform;
|
||||
|
||||
#[cfg(windows)]
|
||||
mod windows;
|
||||
#[cfg(windows)]
|
||||
use windows as platform;
|
||||
|
||||
mod binding;
|
||||
use super::detection;
|
||||
pub mod native;
|
||||
@@ -475,6 +480,7 @@ fn snapshot(interfaces: &[Interface], control: &dyn CollectionControl) -> anyhow
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn command(name: &str, args: &[&str], control: &dyn CollectionControl) -> anyhow::Result<String> {
|
||||
let output = CollectorCommands::new(control)
|
||||
.run(name, args)?
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
//! Windows network identity from IP Helper and adapter DNS configuration.
|
||||
use super::*;
|
||||
use std::os::windows::io::AsRawSocket;
|
||||
use windows_sys::Win32::{
|
||||
NetworkManagement::IpHelper::{
|
||||
DNS_INTERFACE_SETTINGS, DNS_INTERFACE_SETTINGS_VERSION1, FreeInterfaceDnsSettings, FreeMibTable,
|
||||
GetInterfaceDnsSettings, GetIpForwardTable2,
|
||||
},
|
||||
Networking::WinSock::{
|
||||
AF_INET, AF_INET6, AF_UNSPEC, IP_UNICAST_IF, IPPROTO_IP, IPPROTO_IPV6, IPV6_UNICAST_IF, SOCKADDR_INET,
|
||||
SOCKET_ERROR, WSAGetLastError, setsockopt,
|
||||
},
|
||||
};
|
||||
|
||||
pub(super) fn scope_resolver_socket(
|
||||
socket: &tokio::net::UdpSocket,
|
||||
interface: &Interface,
|
||||
endpoint: SocketAddr,
|
||||
) -> anyhow::Result<()> {
|
||||
ensure!(interface.index != 0, "Resolver interface index is missing");
|
||||
// IP_UNICAST_IF uses network byte order; IPV6_UNICAST_IF uses host byte order.
|
||||
let (level, option, index) = if endpoint.is_ipv4() {
|
||||
(IPPROTO_IP, IP_UNICAST_IF, interface.index.to_be())
|
||||
} else {
|
||||
(IPPROTO_IPV6, IPV6_UNICAST_IF, interface.index)
|
||||
};
|
||||
let result = unsafe {
|
||||
setsockopt(
|
||||
socket.as_raw_socket() as usize,
|
||||
level,
|
||||
option,
|
||||
(&index as *const u32).cast(),
|
||||
std::mem::size_of::<u32>() as i32,
|
||||
)
|
||||
};
|
||||
if result == SOCKET_ERROR {
|
||||
return Err(io::Error::from_raw_os_error(unsafe { WSAGetLastError() }).into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn routes(control: &dyn CollectionControl) -> anyhow::Result<Vec<RouteContext>> {
|
||||
control.check()?;
|
||||
let mut table = std::ptr::null_mut();
|
||||
let status = unsafe { GetIpForwardTable2(AF_UNSPEC, &mut table) };
|
||||
if status != 0 {
|
||||
return Err(io::Error::from_raw_os_error(status as i32).into());
|
||||
}
|
||||
let interfaces = netdev::get_interfaces();
|
||||
let result = unsafe {
|
||||
let rows = std::slice::from_raw_parts((*table).Table.as_ptr(), (*table).NumEntries as usize);
|
||||
rows
|
||||
.iter()
|
||||
.filter_map(|row| {
|
||||
let destination = address(&row.DestinationPrefix.Prefix)?;
|
||||
let gateway = address(&row.NextHop)?;
|
||||
let interface = interfaces
|
||||
.iter()
|
||||
.find(|interface| interface.index == row.InterfaceIndex)?;
|
||||
Some(RouteContext {
|
||||
destination: format!("{destination}/{}", row.DestinationPrefix.PrefixLength),
|
||||
gateway: gateway.to_string(),
|
||||
interface: interface.name.clone(),
|
||||
table: "main".into(),
|
||||
metric: row.Metric.to_string(),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
unsafe {
|
||||
FreeMibTable(table.cast());
|
||||
}
|
||||
control.check()?;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
unsafe fn address(address: &SOCKADDR_INET) -> Option<IpAddr> {
|
||||
unsafe {
|
||||
match address.si_family {
|
||||
AF_INET => Some(std::net::Ipv4Addr::from(address.Ipv4.sin_addr.S_un.S_addr.to_ne_bytes()).into()),
|
||||
AF_INET6 => Some(std::net::Ipv6Addr::from(address.Ipv6.sin6_addr.u.Byte).into()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn resolvers(control: &dyn CollectionControl) -> anyhow::Result<Vec<ResolverContext>> {
|
||||
control.check()?;
|
||||
let mut resolvers = netdev::get_interfaces()
|
||||
.into_iter()
|
||||
.filter(|interface| !interface.dns_servers.is_empty())
|
||||
.map(|interface| {
|
||||
Ok(ResolverContext {
|
||||
interface: Some(interface.name.clone()),
|
||||
servers: interface.dns_servers.iter().map(ToString::to_string).collect(),
|
||||
domains: resolver_domains(&interface.name)?,
|
||||
})
|
||||
})
|
||||
.collect::<anyhow::Result<Vec<_>>>()?;
|
||||
resolvers.sort();
|
||||
control.check()?;
|
||||
Ok(resolvers)
|
||||
}
|
||||
|
||||
fn resolver_domains(interface: &str) -> anyhow::Result<Vec<String>> {
|
||||
let id = uuid::Uuid::parse_str(interface.trim_matches(['{', '}']))?;
|
||||
let (data1, data2, data3, data4) = id.as_fields();
|
||||
let guid = windows_sys::core::GUID {
|
||||
data1,
|
||||
data2,
|
||||
data3,
|
||||
data4: *data4,
|
||||
};
|
||||
let mut settings = DNS_INTERFACE_SETTINGS {
|
||||
Version: DNS_INTERFACE_SETTINGS_VERSION1,
|
||||
..Default::default()
|
||||
};
|
||||
let status = unsafe { GetInterfaceDnsSettings(guid, &mut settings) };
|
||||
if status != 0 {
|
||||
return Err(io::Error::from_raw_os_error(status as i32).into());
|
||||
}
|
||||
let mut domains = Vec::new();
|
||||
for pointer in [settings.Domain, settings.SearchList] {
|
||||
if pointer.is_null() {
|
||||
continue;
|
||||
}
|
||||
let text = unsafe {
|
||||
let mut length = 0;
|
||||
while *pointer.add(length) != 0 {
|
||||
length += 1;
|
||||
}
|
||||
String::from_utf16_lossy(std::slice::from_raw_parts(pointer, length))
|
||||
};
|
||||
for domain in text
|
||||
.split(|ch: char| ch == ',' || ch.is_whitespace())
|
||||
.filter(|domain| !domain.is_empty())
|
||||
{
|
||||
let domain = domain.to_ascii_lowercase();
|
||||
if !domains.contains(&domain) {
|
||||
domains.push(domain);
|
||||
}
|
||||
}
|
||||
}
|
||||
unsafe {
|
||||
FreeInterfaceDnsSettings(&mut settings);
|
||||
}
|
||||
Ok(domains)
|
||||
}
|
||||
@@ -45,7 +45,7 @@ fn bind_interface(builder: reqwest::ClientBuilder, binding: &GatewayBinding) ->
|
||||
Ok(builder.interface(binding.interface()))
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[cfg(any(target_os = "freebsd", target_os = "openbsd", windows))]
|
||||
fn bind_interface(builder: reqwest::ClientBuilder, binding: &GatewayBinding) -> anyhow::Result<reqwest::ClientBuilder> {
|
||||
if let std::net::SocketAddr::V6(source) = binding.source() {
|
||||
anyhow::ensure!(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use common::constants::GP_SERVICE_LOCK_FILE;
|
||||
use common::paths::service_lock_file;
|
||||
use thiserror::Error;
|
||||
use tokio::fs;
|
||||
|
||||
@@ -109,7 +109,7 @@ impl LockInfo {
|
||||
}
|
||||
|
||||
pub async fn gpservice_lock_info() -> Result<LockInfo, LockFileError> {
|
||||
gpservice_lock_info_at(GP_SERVICE_LOCK_FILE).await
|
||||
gpservice_lock_info_at(service_lock_file()).await
|
||||
}
|
||||
|
||||
pub async fn gpservice_lock_info_at(path: impl AsRef<Path>) -> Result<LockInfo, LockFileError> {
|
||||
|
||||
@@ -13,6 +13,9 @@ pub async fn shutdown_signal() {
|
||||
.await;
|
||||
};
|
||||
|
||||
#[cfg(not(unix))]
|
||||
let terminate = std::future::pending::<()>();
|
||||
|
||||
tokio::select! {
|
||||
_ = ctrl_c => {},
|
||||
_ = terminate => {},
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
//! Windows user identity and private local IPC.
|
||||
use std::os::windows::io::{AsHandle, AsRawHandle, BorrowedHandle, FromRawHandle, OwnedHandle};
|
||||
use std::{io, ptr};
|
||||
mod pipes;
|
||||
pub use pipes::{PacketPipe, connect_service_admission, connect_service_worker, create_service_admission_pipe};
|
||||
use tokio::net::windows::named_pipe::NamedPipeServer;
|
||||
use windows_sys::Win32::{
|
||||
Foundation::{CloseHandle, LocalFree},
|
||||
Security::{Authorization::ConvertSidToStringSidW, GetTokenInformation, TOKEN_QUERY, TOKEN_USER, TokenUser},
|
||||
System::Threading::{GetCurrentProcess, OpenProcess, OpenProcessToken, PROCESS_QUERY_LIMITED_INFORMATION},
|
||||
};
|
||||
|
||||
pub fn current_user_sid() -> io::Result<String> {
|
||||
unsafe {
|
||||
let mut token = ptr::null_mut();
|
||||
if OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let result = token_user_sid(token);
|
||||
CloseHandle(token);
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
/// An authenticated pipe client's primary token, retained for its user-session worker.
|
||||
/// Windows user identity is a SID and token; it is never represented as a Unix UID.
|
||||
pub struct PipeClientIdentity {
|
||||
sid: String,
|
||||
token: OwnedHandle,
|
||||
}
|
||||
|
||||
impl PipeClientIdentity {
|
||||
pub fn sid(&self) -> &str {
|
||||
&self.sid
|
||||
}
|
||||
|
||||
pub fn primary_token(&self) -> BorrowedHandle<'_> {
|
||||
self.token.as_handle()
|
||||
}
|
||||
|
||||
/// Call after reading the client's admission request. Impersonation stays on
|
||||
/// this thread and ends before returning; no asynchronous work can run in it.
|
||||
pub fn from_pipe(pipe: &NamedPipeServer) -> io::Result<Self> {
|
||||
use windows_sys::Win32::{
|
||||
Security::{
|
||||
DuplicateTokenEx, RevertToSelf, SecurityImpersonation, TOKEN_ASSIGN_PRIMARY, TOKEN_DUPLICATE, TokenPrimary,
|
||||
},
|
||||
System::{
|
||||
Pipes::ImpersonateNamedPipeClient,
|
||||
Threading::{GetCurrentThread, OpenThreadToken},
|
||||
},
|
||||
};
|
||||
struct Revert;
|
||||
impl Drop for Revert {
|
||||
fn drop(&mut self) {
|
||||
// Continuing a service thread as its client would corrupt its privilege
|
||||
// boundary. Windows documents terminating if RevertToSelf fails.
|
||||
if unsafe { RevertToSelf() } == 0 {
|
||||
std::process::abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
unsafe {
|
||||
if ImpersonateNamedPipeClient(pipe.as_raw_handle()) == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let _revert = Revert;
|
||||
let mut token = ptr::null_mut();
|
||||
if OpenThreadToken(GetCurrentThread(), TOKEN_QUERY | TOKEN_DUPLICATE, 1, &mut token) == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let token = OwnedHandle::from_raw_handle(token);
|
||||
let sid = token_user_sid(token.as_raw_handle())?;
|
||||
let mut primary = ptr::null_mut();
|
||||
if DuplicateTokenEx(
|
||||
token.as_raw_handle(),
|
||||
TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_ASSIGN_PRIMARY,
|
||||
ptr::null(),
|
||||
SecurityImpersonation,
|
||||
TokenPrimary,
|
||||
&mut primary,
|
||||
) == 0
|
||||
{
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Ok(Self {
|
||||
sid,
|
||||
token: OwnedHandle::from_raw_handle(primary),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve a local IPC peer from its OS process token.
|
||||
pub fn process_user_sid(pid: u32) -> io::Result<String> {
|
||||
unsafe {
|
||||
let process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
|
||||
if process.is_null() {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let mut token = ptr::null_mut();
|
||||
if OpenProcessToken(process, TOKEN_QUERY, &mut token) == 0 {
|
||||
let error = io::Error::last_os_error();
|
||||
CloseHandle(process);
|
||||
return Err(error);
|
||||
}
|
||||
CloseHandle(process);
|
||||
let result = token_user_sid(token);
|
||||
CloseHandle(token);
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn token_user_sid(token: windows_sys::Win32::Foundation::HANDLE) -> io::Result<String> {
|
||||
unsafe {
|
||||
let mut length = 0;
|
||||
GetTokenInformation(token, TokenUser, ptr::null_mut(), 0, &mut length);
|
||||
// TOKEN_USER contains pointers; retain pointer alignment in its backing allocation.
|
||||
let mut buffer = vec![0usize; (length as usize).div_ceil(std::mem::size_of::<usize>())];
|
||||
if GetTokenInformation(token, TokenUser, buffer.as_mut_ptr().cast(), length, &mut length) == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let user = &*buffer.as_ptr().cast::<TOKEN_USER>();
|
||||
let mut text = ptr::null_mut();
|
||||
if ConvertSidToStringSidW(user.User.Sid, &mut text) == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let mut length = 0;
|
||||
while *text.add(length) != 0 {
|
||||
length += 1;
|
||||
}
|
||||
let sid = String::from_utf16_lossy(std::slice::from_raw_parts(text, length));
|
||||
LocalFree(text.cast());
|
||||
Ok(sid)
|
||||
}
|
||||
}
|
||||
|
||||
/// Only the owning user and SYSTEM can access authentication callbacks.
|
||||
pub fn create_user_pipe(name: &str, first_instance: bool) -> io::Result<NamedPipeServer> {
|
||||
pipes::user_pipe(¤t_user_sid()?, name, first_instance)
|
||||
}
|
||||
|
||||
/// Query a registered service without requiring access to its SYSTEM process token.
|
||||
pub fn service_process_id(name: &str) -> io::Result<u32> {
|
||||
use windows_sys::Win32::System::Services::*;
|
||||
let name: Vec<u16> = name.encode_utf16().chain(Some(0)).collect();
|
||||
unsafe {
|
||||
let manager = OpenSCManagerW(ptr::null(), ptr::null(), SC_MANAGER_CONNECT);
|
||||
if manager.is_null() {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let service = OpenServiceW(manager, name.as_ptr(), SERVICE_QUERY_STATUS);
|
||||
if service.is_null() {
|
||||
let error = io::Error::last_os_error();
|
||||
CloseServiceHandle(manager);
|
||||
return Err(error);
|
||||
}
|
||||
let mut status = SERVICE_STATUS_PROCESS::default();
|
||||
let mut length = 0;
|
||||
let success = QueryServiceStatusEx(
|
||||
service,
|
||||
SC_STATUS_PROCESS_INFO,
|
||||
(&mut status as *mut SERVICE_STATUS_PROCESS).cast(),
|
||||
std::mem::size_of_val(&status) as u32,
|
||||
&mut length,
|
||||
);
|
||||
let result = if success == 0 {
|
||||
Err(io::Error::last_os_error())
|
||||
} else {
|
||||
Ok(status.dwProcessId)
|
||||
};
|
||||
CloseServiceHandle(service);
|
||||
CloseServiceHandle(manager);
|
||||
result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
//! Local service admission and worker pipes with explicit user access.
|
||||
use super::PipeClientIdentity;
|
||||
use std::{
|
||||
fs::OpenOptions,
|
||||
io,
|
||||
os::windows::{
|
||||
fs::OpenOptionsExt,
|
||||
io::{AsRawHandle, FromRawHandle, IntoRawHandle, OwnedHandle},
|
||||
},
|
||||
ptr,
|
||||
time::Duration,
|
||||
};
|
||||
use tokio::net::windows::named_pipe::{NamedPipeClient, NamedPipeServer, ServerOptions};
|
||||
use windows_sys::Win32::{
|
||||
Foundation::{ERROR_IO_PENDING, ERROR_PIPE_CONNECTED, INVALID_HANDLE_VALUE, LocalFree, WAIT_OBJECT_0, WAIT_TIMEOUT},
|
||||
Security::{Authorization::ConvertStringSecurityDescriptorToSecurityDescriptorW, SECURITY_ATTRIBUTES},
|
||||
Storage::FileSystem::*,
|
||||
System::{
|
||||
IO::{CancelIoEx, GetOverlappedResult, OVERLAPPED},
|
||||
Pipes::*,
|
||||
Threading::{CreateEventW, WaitForSingleObject},
|
||||
},
|
||||
};
|
||||
|
||||
// Generic write also grants FILE_CREATE_PIPE_INSTANCE. Clients receive only
|
||||
// data/metadata access; creating another instance remains SYSTEM-only.
|
||||
const CLIENT_ACCESS: u32 = FILE_GENERIC_READ | FILE_WRITE_DATA | FILE_WRITE_EA | FILE_WRITE_ATTRIBUTES;
|
||||
fn wide(value: &str) -> Vec<u16> {
|
||||
value.encode_utf16().chain(Some(0)).collect()
|
||||
}
|
||||
fn with_security<T>(sddl: &str, operation: impl FnOnce(&SECURITY_ATTRIBUTES) -> io::Result<T>) -> io::Result<T> {
|
||||
struct Descriptor(*mut std::ffi::c_void);
|
||||
impl Drop for Descriptor {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
LocalFree(self.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut pointer = ptr::null_mut();
|
||||
if unsafe {
|
||||
ConvertStringSecurityDescriptorToSecurityDescriptorW(wide(sddl).as_ptr(), 1, &mut pointer, ptr::null_mut())
|
||||
} == 0
|
||||
{
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let descriptor = Descriptor(pointer);
|
||||
operation(&SECURITY_ATTRIBUTES {
|
||||
nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
|
||||
lpSecurityDescriptor: descriptor.0,
|
||||
bInheritHandle: 0,
|
||||
})
|
||||
}
|
||||
fn server(sddl: &str, name: &str, first: bool) -> io::Result<NamedPipeServer> {
|
||||
with_security(sddl, |attributes| unsafe {
|
||||
ServerOptions::new()
|
||||
.first_pipe_instance(first)
|
||||
.reject_remote_clients(true)
|
||||
.create_with_security_attributes_raw(name, (attributes as *const SECURITY_ATTRIBUTES).cast_mut().cast())
|
||||
})
|
||||
}
|
||||
pub(super) fn user_pipe(sid: &str, name: &str, first: bool) -> io::Result<NamedPipeServer> {
|
||||
server(&format!("D:P(A;;GA;;;SY)(A;;GA;;;{sid})"), name, first)
|
||||
}
|
||||
pub fn create_service_admission_pipe(first: bool) -> io::Result<NamedPipeServer> {
|
||||
server(
|
||||
&format!("D:P(A;;GA;;;SY)(A;;0x{CLIENT_ACCESS:x};;;AU)"),
|
||||
common::paths::SERVICE_PIPE,
|
||||
first,
|
||||
)
|
||||
}
|
||||
fn client(name: &str, message: bool, impersonation: bool) -> io::Result<NamedPipeClient> {
|
||||
let file = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.access_mode(CLIENT_ACCESS)
|
||||
.custom_flags(FILE_FLAG_OVERLAPPED)
|
||||
.security_qos_flags(if impersonation {
|
||||
SECURITY_IMPERSONATION
|
||||
} else {
|
||||
SECURITY_IDENTIFICATION
|
||||
})
|
||||
.open(name)?;
|
||||
let pipe = unsafe { NamedPipeClient::from_raw_handle(file.into_raw_handle()) }?;
|
||||
let mut pid = 0;
|
||||
if unsafe { GetNamedPipeServerProcessId(pipe.as_raw_handle(), &mut pid) } == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
if pid == 0 || pid != super::service_process_id(common::paths::SERVICE_NAME)? {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::PermissionDenied,
|
||||
"Pipe does not belong to the registered VPN service",
|
||||
));
|
||||
}
|
||||
if message {
|
||||
let mode = PIPE_READMODE_MESSAGE;
|
||||
if unsafe { SetNamedPipeHandleState(pipe.as_raw_handle(), &mode, ptr::null(), ptr::null()) } == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
}
|
||||
Ok(pipe)
|
||||
}
|
||||
/// Verify the service before the first request permits it to impersonate this user.
|
||||
pub fn connect_service_admission() -> io::Result<NamedPipeClient> {
|
||||
client(common::paths::SERVICE_PIPE, false, true)
|
||||
}
|
||||
pub fn connect_service_worker(name: &str, message: bool) -> io::Result<NamedPipeClient> {
|
||||
client(name, message, false)
|
||||
}
|
||||
|
||||
impl PipeClientIdentity {
|
||||
pub fn create_control_pipe(&self, name: &str) -> io::Result<NamedPipeServer> {
|
||||
server(
|
||||
&format!("D:P(A;;GA;;;SY)(A;;0x{CLIENT_ACCESS:x};;;{})", self.sid()),
|
||||
name,
|
||||
true,
|
||||
)
|
||||
}
|
||||
pub fn create_packet_pipe(&self, name: &str) -> io::Result<PacketPipe> {
|
||||
let name = wide(name);
|
||||
with_security(
|
||||
&format!("D:P(A;;GA;;;SY)(A;;0x{CLIENT_ACCESS:x};;;{})", self.sid()),
|
||||
|attributes| {
|
||||
let handle = unsafe {
|
||||
CreateNamedPipeW(
|
||||
name.as_ptr(),
|
||||
PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE,
|
||||
PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_REJECT_REMOTE_CLIENTS,
|
||||
1,
|
||||
256 * 1024,
|
||||
256 * 1024,
|
||||
0,
|
||||
attributes,
|
||||
)
|
||||
};
|
||||
if handle == INVALID_HANDLE_VALUE {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Ok(PacketPipe(unsafe { OwnedHandle::from_raw_handle(handle) }))
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
/// Raw Win32 overlapped I/O, deliberately never registered with Tokio/Mio IOCP.
|
||||
pub struct PacketPipe(OwnedHandle);
|
||||
impl PacketPipe {
|
||||
pub fn connect(&mut self, expected_pid: u32, timeout: Duration) -> io::Result<()> {
|
||||
let event = unsafe { CreateEventW(ptr::null(), 1, 0, ptr::null()) };
|
||||
if event.is_null() {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let event = unsafe { OwnedHandle::from_raw_handle(event) };
|
||||
let mut overlap = OVERLAPPED {
|
||||
hEvent: event.as_raw_handle(),
|
||||
..Default::default()
|
||||
};
|
||||
if unsafe { ConnectNamedPipe(self.0.as_raw_handle(), &mut overlap) } == 0 {
|
||||
let error = io::Error::last_os_error();
|
||||
match error.raw_os_error().map(|code| code as u32) {
|
||||
Some(ERROR_PIPE_CONNECTED) => {}
|
||||
Some(ERROR_IO_PENDING) => {
|
||||
let status = unsafe {
|
||||
WaitForSingleObject(
|
||||
event.as_raw_handle(),
|
||||
timeout.as_millis().min(u32::MAX as u128 - 1) as u32,
|
||||
)
|
||||
};
|
||||
let mut bytes = 0;
|
||||
if status != WAIT_OBJECT_0 {
|
||||
// Complete cancellation before OVERLAPPED/event storage is released.
|
||||
unsafe {
|
||||
CancelIoEx(self.0.as_raw_handle(), &overlap);
|
||||
GetOverlappedResult(self.0.as_raw_handle(), &overlap, &mut bytes, 1);
|
||||
}
|
||||
if status == WAIT_TIMEOUT {
|
||||
return Err(io::Error::new(io::ErrorKind::TimedOut, "Packet worker did not connect"));
|
||||
}
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
if unsafe { GetOverlappedResult(self.0.as_raw_handle(), &overlap, &mut bytes, 0) } == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
}
|
||||
_ => return Err(error),
|
||||
}
|
||||
}
|
||||
let mut pid = 0;
|
||||
if unsafe { GetNamedPipeClientProcessId(self.0.as_raw_handle(), &mut pid) } == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
if pid != expected_pid {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::PermissionDenied,
|
||||
"Unexpected packet pipe client",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn into_handle(self) -> OwnedHandle {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user