feat: Windows Setup Wizard (ostp-setup) with Tauri

- Tauri 2.0 based graphical installer
- Access Key parsing with AES-256-GCM encryption
- Windows Service installation via sc.exe
- WinTUN driver extraction from embedded resources
- System requirements checking (admin, AES-NI, OS version)
- Modern dark UI with step-by-step wizard flow
- Country/region selection for SNI mimicry
This commit is contained in:
2026-01-01 21:49:37 +03:00
parent 320e5fee85
commit 7e1c87e70b
21 changed files with 10916 additions and 41 deletions

View File

@@ -0,0 +1,236 @@
//! Access Key parsing and validation
//!
//! Access Key format: ospab://<base64-encoded-data>
//! Decoded data: JSON with server, port, psk, and optional label
use serde::{Deserialize, Serialize};
/// Parsed access key data
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AccessKeyData {
pub server_ip: String,
pub port: u16,
pub psk: String,
pub label: Option<String>,
}
use aes_gcm::{
aead::{Aead, KeyInit},
Aes256Gcm, Nonce,
};
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
use sha2::{Digest, Sha256};
use thiserror::Error;
/// Key derivation salt (must match client)
const KEY_SALT: &[u8] = b"ospab.network.access.key.v1";
/// Static obfuscation key (XOR with device-specific data in production)
const OBFUSCATION_KEY: [u8; 32] = [
0x4f, 0x53, 0x50, 0x41, 0x42, 0x2e, 0x4e, 0x45,
0x54, 0x57, 0x4f, 0x52, 0x4b, 0x2e, 0x32, 0x30,
0x32, 0x36, 0x2e, 0x53, 0x45, 0x43, 0x55, 0x52,
0x45, 0x2e, 0x4b, 0x45, 0x59, 0x2e, 0x56, 0x31,
];
#[derive(Error, Debug)]
pub enum AccessKeyError {
#[error("Invalid access key format")]
InvalidFormat,
#[error("Invalid base64 encoding")]
Base64Error(#[from] base64::DecodeError),
#[error("Decryption failed")]
DecryptionFailed,
#[error("Invalid JSON data")]
JsonError(#[from] serde_json::Error),
#[error("Missing required field: {0}")]
MissingField(String),
}
/// Validate access key format (quick check)
pub fn validate(key: &str) -> bool {
if !key.starts_with("ospab://") {
return false;
}
let encoded = &key[8..]; // Skip "ospab://"
URL_SAFE_NO_PAD.decode(encoded).is_ok()
}
/// Parse and decrypt access key
pub fn parse(key: &str) -> Result<AccessKeyData, AccessKeyError> {
// Check prefix
if !key.starts_with("ospab://") {
return Err(AccessKeyError::InvalidFormat);
}
let encoded = &key[8..]; // Skip "ospab://"
let encrypted = URL_SAFE_NO_PAD.decode(encoded)?;
// Decrypt the data
let decrypted = decrypt_access_key(&encrypted)?;
// Parse JSON
let json: serde_json::Value = serde_json::from_slice(&decrypted)?;
// Extract fields
let server_ip = json["server"]
.as_str()
.ok_or_else(|| AccessKeyError::MissingField("server".into()))?
.to_string();
let port = json["port"]
.as_u64()
.ok_or_else(|| AccessKeyError::MissingField("port".into()))? as u16;
let psk = json["psk"]
.as_str()
.ok_or_else(|| AccessKeyError::MissingField("psk".into()))?
.to_string();
let label = json["label"].as_str().map(String::from);
Ok(AccessKeyData {
server_ip,
port,
psk,
label,
})
}
/// Decrypt access key data using AES-256-GCM
fn decrypt_access_key(encrypted: &[u8]) -> Result<Vec<u8>, AccessKeyError> {
if encrypted.len() < 12 + 16 {
// Nonce (12) + Tag (16) minimum
return Err(AccessKeyError::InvalidFormat);
}
// Derive key from obfuscation key
let key = derive_key(&OBFUSCATION_KEY);
// Split nonce and ciphertext
let (nonce_bytes, ciphertext) = encrypted.split_at(12);
let nonce = Nonce::from_slice(nonce_bytes);
// Decrypt
let cipher = Aes256Gcm::new_from_slice(&key)
.map_err(|_| AccessKeyError::DecryptionFailed)?;
cipher
.decrypt(nonce, ciphertext)
.map_err(|_| AccessKeyError::DecryptionFailed)
}
/// Derive AES key from obfuscation key
fn derive_key(input: &[u8]) -> [u8; 32] {
let mut hasher = Sha256::new();
hasher.update(input);
hasher.update(KEY_SALT);
hasher.finalize().into()
}
/// Create an access key (for server-side use)
#[allow(dead_code)]
pub fn create_access_key(
server: &str,
port: u16,
psk: &str,
label: Option<&str>,
) -> Result<String, AccessKeyError> {
use aes_gcm::aead::OsRng;
use rand::RngCore;
// Create JSON payload
let mut json = serde_json::json!({
"server": server,
"port": port,
"psk": psk
});
if let Some(l) = label {
json["label"] = serde_json::Value::String(l.to_string());
}
let plaintext = serde_json::to_vec(&json)?;
// Encrypt
let key = derive_key(&OBFUSCATION_KEY);
let cipher = Aes256Gcm::new_from_slice(&key)
.map_err(|_| AccessKeyError::DecryptionFailed)?;
// Generate random nonce
let mut nonce_bytes = [0u8; 12];
OsRng.fill_bytes(&mut nonce_bytes);
let nonce = Nonce::from_slice(&nonce_bytes);
let ciphertext = cipher
.encrypt(nonce, plaintext.as_slice())
.map_err(|_| AccessKeyError::DecryptionFailed)?;
// Combine nonce + ciphertext
let mut result = Vec::with_capacity(12 + ciphertext.len());
result.extend_from_slice(&nonce_bytes);
result.extend(ciphertext);
// Encode and format
let encoded = URL_SAFE_NO_PAD.encode(&result);
Ok(format!("ospab://{}", encoded))
}
/// Secure memory wipe for sensitive data
#[allow(dead_code)]
pub struct SecureString {
inner: String,
}
#[allow(dead_code)]
impl SecureString {
pub fn new(s: String) -> Self {
Self { inner: s }
}
pub fn as_str(&self) -> &str {
&self.inner
}
}
impl Drop for SecureString {
fn drop(&mut self) {
// Overwrite memory before deallocation
unsafe {
let bytes = self.inner.as_bytes_mut();
for byte in bytes.iter_mut() {
std::ptr::write_volatile(byte, 0);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_create_and_parse_access_key() {
let key = create_access_key(
"vpn.example.com",
8443,
"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
Some("Test Server"),
)
.unwrap();
assert!(key.starts_with("ospab://"));
assert!(validate(&key));
let parsed = parse(&key).unwrap();
assert_eq!(parsed.server_ip, "vpn.example.com");
assert_eq!(parsed.port, 8443);
assert_eq!(parsed.label, Some("Test Server".to_string()));
}
#[test]
fn test_invalid_key() {
assert!(!validate("invalid://key"));
assert!(!validate("ospab://!!!invalid-base64!!!"));
}
}

8
ostp-setup/src/lib.rs Normal file
View File

@@ -0,0 +1,8 @@
//! OSTP Setup Library
//!
//! This is the library interface for the setup wizard.
pub mod access_key;
pub mod service;
pub mod system_check;
pub mod wintun;

191
ostp-setup/src/main.rs Normal file
View File

@@ -0,0 +1,191 @@
//! OSTP Setup Wizard - Rust Backend
//!
//! Handles Windows Service installation, wintun driver extraction,
//! and Access Key parsing for the OSTP Client.
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
mod access_key;
mod service;
mod wintun;
mod system_check;
use tauri::{command, AppHandle, Emitter, Manager};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
// Re-export types from modules
pub use access_key::AccessKeyData;
pub use system_check::SystemCheckResult;
/// Installation configuration from the wizard
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InstallConfig {
pub access_key: String,
pub country: String,
pub install_path: PathBuf,
pub launch_on_startup: bool,
pub connect_now: bool,
}
/// Installation progress update
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProgressUpdate {
pub step: u8,
pub total_steps: u8,
pub message: String,
pub percent: u8,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CountryOption {
pub code: String,
pub name: String,
pub recommended: bool,
}
/// Check system requirements
#[command]
async fn check_system() -> Result<SystemCheckResult, String> {
system_check::run_checks().await.map_err(|e| e.to_string())
}
/// Parse and validate access key
#[command]
async fn parse_access_key(key: String) -> Result<AccessKeyData, String> {
access_key::parse(&key).map_err(|e| e.to_string())
}
/// Validate access key format without full parse
#[command]
fn validate_access_key(key: String) -> bool {
access_key::validate(&key)
}
/// Get list of available countries for SNI
#[command]
fn get_countries() -> Vec<CountryOption> {
vec![
CountryOption { code: "RU".into(), name: "Russia".into(), recommended: true },
CountryOption { code: "DE".into(), name: "Germany".into(), recommended: false },
CountryOption { code: "NL".into(), name: "Netherlands".into(), recommended: false },
CountryOption { code: "US".into(), name: "United States".into(), recommended: false },
CountryOption { code: "SG".into(), name: "Singapore".into(), recommended: false },
CountryOption { code: "JP".into(), name: "Japan".into(), recommended: false },
]
}
/// Run the full installation process
#[command]
async fn run_installation(
app: AppHandle,
config: InstallConfig,
) -> Result<(), String> {
let window = app.get_webview_window("main").unwrap();
// Step 1: Extract wintun.dll
emit_progress(&window, 1, 5, "Extracting WinTUN driver...", 10);
wintun::extract_driver(&config.install_path)
.await
.map_err(|e| format!("Failed to extract wintun: {}", e))?;
// Step 2: Parse access key
emit_progress(&window, 2, 5, "Parsing access key...", 25);
let key_data = access_key::parse(&config.access_key)
.map_err(|e| format!("Invalid access key: {}", e))?;
// Step 3: Write configuration file
emit_progress(&window, 3, 5, "Writing configuration...", 45);
write_config(&config.install_path, &key_data, &config.country)
.await
.map_err(|e| format!("Failed to write config: {}", e))?;
// Step 4: Install Windows Service
emit_progress(&window, 4, 5, "Installing Windows Service...", 70);
service::install_service(&config.install_path)
.await
.map_err(|e| format!("Failed to install service: {}", e))?;
// Step 5: Configure startup
emit_progress(&window, 5, 5, "Configuring startup options...", 90);
if config.launch_on_startup {
service::enable_autostart()
.await
.map_err(|e| format!("Failed to enable autostart: {}", e))?;
}
emit_progress(&window, 5, 5, "Installation complete!", 100);
// Optionally connect now
if config.connect_now {
service::start_service()
.await
.map_err(|e| format!("Failed to start service: {}", e))?;
}
Ok(())
}
/// Emit progress update to frontend
fn emit_progress(window: &tauri::WebviewWindow, step: u8, total: u8, msg: &str, percent: u8) {
let _ = window.emit("install-progress", ProgressUpdate {
step,
total_steps: total,
message: msg.to_string(),
percent,
});
}
/// Write OSTP client configuration file
async fn write_config(
install_path: &PathBuf,
key_data: &AccessKeyData,
country: &str,
) -> anyhow::Result<()> {
use std::fs;
let config_path = install_path.join("ostp-client.json");
let config = serde_json::json!({
"server": format!("{}:{}", key_data.server_ip, key_data.port),
"psk": key_data.psk,
"country": country,
"dns": ["1.1.1.1", "8.8.8.8"],
"mtu": 1400
});
fs::create_dir_all(install_path)?;
fs::write(&config_path, serde_json::to_string_pretty(&config)?)?;
Ok(())
}
/// Uninstall the OSTP client
#[command]
async fn uninstall() -> Result<(), String> {
service::stop_service().await.map_err(|e| e.to_string())?;
service::uninstall_service().await.map_err(|e| e.to_string())?;
wintun::remove_driver().await.map_err(|e| e.to_string())?;
Ok(())
}
/// Get default installation path
#[command]
fn get_default_install_path() -> PathBuf {
PathBuf::from(r"C:\Program Files\Ospab Network\OSTP")
}
fn main() {
tauri::Builder::default()
.plugin(tauri_plugin_shell::init())
.invoke_handler(tauri::generate_handler![
check_system,
parse_access_key,
validate_access_key,
get_countries,
run_installation,
uninstall,
get_default_install_path,
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}

251
ostp-setup/src/service.rs Normal file
View File

@@ -0,0 +1,251 @@
//! Windows Service management for OSTP Client
//!
//! Installs, configures, and manages the OSTP client as a Windows Service.
//! Uses sc.exe for broader compatibility.
use anyhow::{Context, Result};
use std::path::PathBuf;
use std::process::Command;
/// Service name
const SERVICE_NAME: &str = "OstpClient";
/// Service display name
const SERVICE_DISPLAY_NAME: &str = "Ospab Network OSTP Client";
/// Service description
const SERVICE_DESCRIPTION: &str =
"Provides secure, stealth VPN connectivity through the OSTP protocol.";
/// Install OSTP client as a Windows Service using sc.exe
pub async fn install_service(install_path: &PathBuf) -> Result<()> {
#[cfg(windows)]
{
let executable_path = install_path.join("ostp-client.exe");
if !executable_path.exists() {
anyhow::bail!("ostp-client.exe not found at {:?}", executable_path);
}
let config_path = install_path.join("ostp-client.json");
let bin_path = format!(
"\"{}\" --service --config \"{}\"",
executable_path.display(),
config_path.display()
);
// Create service
let output = Command::new("sc.exe")
.args([
"create",
SERVICE_NAME,
&format!("binPath= {}", bin_path),
&format!("DisplayName= {}", SERVICE_DISPLAY_NAME),
"start= auto",
"depend= Tcpip/Dnscache",
])
.output()
.context("Failed to run sc.exe create")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
if !stderr.contains("1073") { // Service already exists
anyhow::bail!("Failed to create service: {}", stderr);
}
}
// Set description
let _ = Command::new("sc.exe")
.args(["description", SERVICE_NAME, SERVICE_DESCRIPTION])
.output();
// Configure recovery options (restart on failure)
let _ = Command::new("sc.exe")
.args([
"failure",
SERVICE_NAME,
"reset= 86400",
"actions= restart/60000/restart/120000/restart/300000",
])
.output();
tracing::info!("Service {} installed successfully", SERVICE_NAME);
}
#[cfg(not(windows))]
{
let _ = install_path;
anyhow::bail!("Windows Service installation is only supported on Windows");
}
Ok(())
}
/// Start the OSTP service
pub async fn start_service() -> Result<()> {
#[cfg(windows)]
{
let output = Command::new("sc.exe")
.args(["start", SERVICE_NAME])
.output()
.context("Failed to run sc.exe start")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
if !stderr.contains("1056") { // Service already running
anyhow::bail!("Failed to start service: {}", stderr);
}
}
tracing::info!("Service {} started", SERVICE_NAME);
}
Ok(())
}
/// Stop the OSTP service
pub async fn stop_service() -> Result<()> {
#[cfg(windows)]
{
let output = Command::new("sc.exe")
.args(["stop", SERVICE_NAME])
.output()
.context("Failed to run sc.exe stop")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
if !stderr.contains("1062") { // Service not running
anyhow::bail!("Failed to stop service: {}", stderr);
}
}
// Wait for service to stop
for _ in 0..30 {
tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
if !is_running() {
break;
}
}
tracing::info!("Service {} stopped", SERVICE_NAME);
}
Ok(())
}
/// Uninstall the OSTP service
pub async fn uninstall_service() -> Result<()> {
// Stop the service first
stop_service().await.ok();
#[cfg(windows)]
{
let output = Command::new("sc.exe")
.args(["delete", SERVICE_NAME])
.output()
.context("Failed to run sc.exe delete")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
if !stderr.contains("1060") { // Service doesn't exist
anyhow::bail!("Failed to delete service: {}", stderr);
}
}
tracing::info!("Service {} uninstalled", SERVICE_NAME);
}
Ok(())
}
/// Enable service to start at system startup
pub async fn enable_autostart() -> Result<()> {
#[cfg(windows)]
{
Command::new("sc.exe")
.args(["config", SERVICE_NAME, "start= auto"])
.output()
.context("Failed to enable autostart")?;
tracing::info!("Autostart enabled for {}", SERVICE_NAME);
}
Ok(())
}
/// Disable service autostart
#[allow(dead_code)]
pub async fn disable_autostart() -> Result<()> {
#[cfg(windows)]
{
Command::new("sc.exe")
.args(["config", SERVICE_NAME, "start= demand"])
.output()
.context("Failed to disable autostart")?;
tracing::info!("Autostart disabled for {}", SERVICE_NAME);
}
Ok(())
}
/// Check if service is installed
#[allow(dead_code)]
pub fn is_installed() -> bool {
#[cfg(windows)]
{
Command::new("sc.exe")
.args(["query", SERVICE_NAME])
.output()
.map(|o| o.status.success())
.unwrap_or(false)
}
#[cfg(not(windows))]
false
}
/// Check if service is running
pub fn is_running() -> bool {
#[cfg(windows)]
{
Command::new("sc.exe")
.args(["query", SERVICE_NAME])
.output()
.map(|o| {
let stdout = String::from_utf8_lossy(&o.stdout);
stdout.contains("RUNNING")
})
.unwrap_or(false)
}
#[cfg(not(windows))]
false
}
/// Get service status
#[allow(dead_code)]
pub fn get_status() -> Option<String> {
#[cfg(windows)]
{
Command::new("sc.exe")
.args(["query", SERVICE_NAME])
.output()
.ok()
.and_then(|o| {
let stdout = String::from_utf8_lossy(&o.stdout);
if stdout.contains("RUNNING") {
Some("Running".to_string())
} else if stdout.contains("STOPPED") {
Some("Stopped".to_string())
} else if stdout.contains("PENDING") {
Some("Pending".to_string())
} else {
Some("Unknown".to_string())
}
})
}
#[cfg(not(windows))]
None
}

View File

@@ -0,0 +1,225 @@
//! System requirements checking
//!
//! Verifies that the target system meets all requirements for OSTP Client.
use serde::{Deserialize, Serialize};
/// System check result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemCheckResult {
pub wintun_installed: bool,
pub aes_ni_supported: bool,
pub admin_privileges: bool,
pub os_version: String,
}
use anyhow::Result;
/// Run all system checks
pub async fn run_checks() -> Result<SystemCheckResult> {
Ok(SystemCheckResult {
wintun_installed: check_wintun_installed(),
aes_ni_supported: check_aes_ni_support(),
admin_privileges: check_admin_privileges(),
os_version: get_os_version(),
})
}
/// Check if wintun.dll is already installed
fn check_wintun_installed() -> bool {
crate::wintun::is_installed()
}
/// Check if CPU supports AES-NI instructions
fn check_aes_ni_support() -> bool {
#[cfg(target_arch = "x86_64")]
{
// Check CPUID for AES-NI support
return is_x86_feature_detected!("aes");
}
#[cfg(target_arch = "aarch64")]
{
// ARM64 typically has crypto extensions
// Check for ARMv8 Crypto extensions
#[cfg(target_feature = "aes")]
return true;
#[cfg(not(target_feature = "aes"))]
return false;
}
// Fallback: assume software AES is acceptable
#[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
true
}
/// Check if running with administrator privileges
fn check_admin_privileges() -> bool {
#[cfg(windows)]
{
use std::ptr;
// Use Windows API to check elevation
unsafe {
let mut token_handle: *mut std::ffi::c_void = ptr::null_mut();
let current_process = GetCurrentProcess();
if OpenProcessToken(
current_process,
TOKEN_QUERY,
&mut token_handle,
) == 0 {
return false;
}
let mut elevation = TOKEN_ELEVATION { TokenIsElevated: 0 };
let mut size: u32 = std::mem::size_of::<TOKEN_ELEVATION>() as u32;
let result = GetTokenInformation(
token_handle,
TokenElevation,
&mut elevation as *mut _ as *mut _,
size,
&mut size,
);
CloseHandle(token_handle);
result != 0 && elevation.TokenIsElevated != 0
}
}
#[cfg(not(windows))]
{
// On non-Windows, check if running as root
unsafe { libc::geteuid() == 0 }
}
}
/// Get Windows version string
fn get_os_version() -> String {
#[cfg(windows)]
{
use winreg::{enums::*, RegKey};
if let Ok(hklm) = RegKey::predef(HKEY_LOCAL_MACHINE)
.open_subkey(r"SOFTWARE\Microsoft\Windows NT\CurrentVersion")
{
let product_name: String = hklm.get_value("ProductName").unwrap_or_default();
let build: String = hklm.get_value("CurrentBuild").unwrap_or_default();
if !product_name.is_empty() {
return format!("{} (Build {})", product_name, build);
}
}
"Windows (Unknown Version)".to_string()
}
#[cfg(not(windows))]
{
"Non-Windows OS".to_string()
}
}
/// Check minimum Windows version (Windows 10 1607+)
#[allow(dead_code)]
pub fn check_minimum_version() -> bool {
#[cfg(windows)]
{
use winreg::{enums::*, RegKey};
if let Ok(hklm) = RegKey::predef(HKEY_LOCAL_MACHINE)
.open_subkey(r"SOFTWARE\Microsoft\Windows NT\CurrentVersion")
{
let build: String = hklm.get_value("CurrentBuild").unwrap_or_default();
if let Ok(build_num) = build.parse::<u32>() {
// Windows 10 1607 is build 14393
return build_num >= 14393;
}
}
false
}
#[cfg(not(windows))]
true
}
/// Check available disk space (need at least 50MB)
#[allow(dead_code)]
pub fn check_disk_space(path: &std::path::Path) -> bool {
#[cfg(windows)]
{
use std::os::windows::ffi::OsStrExt;
use std::ffi::OsStr;
let path_wide: Vec<u16> = OsStr::new(path)
.encode_wide()
.chain(std::iter::once(0))
.collect();
let mut free_bytes: u64 = 0;
let mut total_bytes: u64 = 0;
let mut total_free_bytes: u64 = 0;
unsafe {
if GetDiskFreeSpaceExW(
path_wide.as_ptr(),
&mut free_bytes,
&mut total_bytes,
&mut total_free_bytes,
) != 0 {
// Need at least 50MB
return free_bytes >= 50 * 1024 * 1024;
}
}
true // Assume OK if check fails
}
#[cfg(not(windows))]
{
let _ = path;
true
}
}
// Windows API bindings
#[cfg(windows)]
unsafe extern "system" {
fn GetCurrentProcess() -> *mut std::ffi::c_void;
fn OpenProcessToken(
process: *mut std::ffi::c_void,
access: u32,
token: *mut *mut std::ffi::c_void,
) -> i32;
fn GetTokenInformation(
token: *mut std::ffi::c_void,
info_class: u32,
info: *mut std::ffi::c_void,
info_len: u32,
return_len: *mut u32,
) -> i32;
fn CloseHandle(handle: *mut std::ffi::c_void) -> i32;
#[allow(dead_code)]
fn GetDiskFreeSpaceExW(
directory: *const u16,
free_bytes: *mut u64,
total_bytes: *mut u64,
total_free_bytes: *mut u64,
) -> i32;
}
#[cfg(windows)]
const TOKEN_QUERY: u32 = 0x0008;
#[cfg(windows)]
#[allow(non_upper_case_globals)]
const TokenElevation: u32 = 20;
#[cfg(windows)]
#[repr(C)]
#[allow(non_snake_case)]
struct TOKEN_ELEVATION {
TokenIsElevated: u32,
}

168
ostp-setup/src/wintun.rs Normal file
View File

@@ -0,0 +1,168 @@
//! WinTUN driver extraction and management
//!
//! Extracts wintun.dll from embedded resources and installs the TUN adapter.
use std::path::PathBuf;
use anyhow::{Context, Result};
use std::fs;
/// Embedded wintun.dll (x64) - placeholder, actual DLL is in resources
const WINTUN_DLL: &[u8] = include_bytes!("../resources/wintun.dll");
/// WinTUN adapter GUID (consistent across installs)
#[allow(dead_code)]
const ADAPTER_GUID: &str = "{A1B2C3D4-E5F6-7890-ABCD-EF1234567890}";
/// TUN adapter name
#[allow(dead_code)]
const ADAPTER_NAME: &str = "ostp TUN";
/// Extract wintun.dll to installation directory
pub async fn extract_driver(install_path: &PathBuf) -> Result<()> {
let dll_path = install_path.join("wintun.dll");
// Create directory if needed
fs::create_dir_all(install_path)
.context("Failed to create installation directory")?;
// Check if already exists with correct version
if dll_path.exists() {
let existing = fs::read(&dll_path)?;
if existing == WINTUN_DLL {
return Ok(()); // Already up to date
}
}
// Write the DLL
fs::write(&dll_path, WINTUN_DLL)
.context("Failed to write wintun.dll")?;
Ok(())
}
/// Create the TUN adapter using wintun API
#[allow(dead_code)]
pub async fn create_adapter(install_path: &PathBuf) -> Result<()> {
// Load wintun.dll dynamically
let dll_path = install_path.join("wintun.dll");
if !dll_path.exists() {
anyhow::bail!("wintun.dll not found at {:?}", dll_path);
}
// Use libloading to call WintunCreateAdapter
// This is a simplified version - full implementation would use the wintun crate
#[cfg(windows)]
{
use std::ffi::OsStr;
use std::os::windows::ffi::OsStrExt;
// Convert strings to wide strings for Windows API
let _adapter_name: Vec<u16> = OsStr::new(ADAPTER_NAME)
.encode_wide()
.chain(std::iter::once(0))
.collect();
let _tunnel_type: Vec<u16> = OsStr::new("Ospab")
.encode_wide()
.chain(std::iter::once(0))
.collect();
// Parse GUID
let _guid = parse_guid(ADAPTER_GUID)?;
// In production, we'd call:
// WintunCreateAdapter(adapter_name, tunnel_type, &guid)
// For now, we'll use the wintun crate when it's integrated
tracing::info!("TUN adapter creation would happen here");
}
Ok(())
}
/// Delete the TUN adapter
pub async fn delete_adapter() -> Result<()> {
#[cfg(windows)]
{
// WintunDeleteAdapter would be called here
tracing::info!("TUN adapter deletion would happen here");
}
Ok(())
}
/// Remove wintun driver files
pub async fn remove_driver() -> Result<()> {
// Delete adapter first
delete_adapter().await?;
// Find and remove DLL from common locations
let paths = [
PathBuf::from(r"C:\Program Files\Ospab Network\OSTP\wintun.dll"),
];
for path in &paths {
if path.exists() {
fs::remove_file(path).ok();
}
}
Ok(())
}
/// Check if wintun is installed and working
pub fn is_installed() -> bool {
let system_dll = PathBuf::from(r"C:\Program Files\Ospab Network\OSTP\wintun.dll");
system_dll.exists()
}
/// Get wintun version from DLL
#[allow(dead_code)]
pub fn get_version() -> Option<String> {
// Would extract version info from PE header
// For now, return embedded version
Some("0.14.1".to_string())
}
/// Parse a GUID string into bytes
#[cfg(windows)]
#[allow(dead_code)]
fn parse_guid(s: &str) -> Result<[u8; 16]> {
let s = s.trim_matches(|c| c == '{' || c == '}');
let parts: Vec<&str> = s.split('-').collect();
if parts.len() != 5 {
anyhow::bail!("Invalid GUID format");
}
let mut guid = [0u8; 16];
// Parse each part
let d1 = u32::from_str_radix(parts[0], 16)?;
let d2 = u16::from_str_radix(parts[1], 16)?;
let d3 = u16::from_str_radix(parts[2], 16)?;
let d4 = u16::from_str_radix(parts[3], 16)?;
let d5 = u64::from_str_radix(parts[4], 16)?;
guid[0..4].copy_from_slice(&d1.to_le_bytes());
guid[4..6].copy_from_slice(&d2.to_le_bytes());
guid[6..8].copy_from_slice(&d3.to_le_bytes());
guid[8..10].copy_from_slice(&d4.to_be_bytes());
guid[10..16].copy_from_slice(&d5.to_be_bytes()[2..8]);
Ok(guid)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[cfg(windows)]
fn test_parse_guid() {
let guid = parse_guid(ADAPTER_GUID).unwrap();
assert_eq!(guid.len(), 16);
}
}