Skip to content

disable auto startup for Windows tunnel service #88

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Apr 22, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
/target
.idea/
.vscode/
.direnv
.envrc
2 changes: 1 addition & 1 deletion examples/client.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::{net::SocketAddr, str::FromStr};

use defguard_wireguard_rs::{
host::Peer, key::Key, net::IpAddrMask, InterfaceConfiguration, Kernel, Userspace, WGApi,
host::Peer, key::Key, net::IpAddrMask, InterfaceConfiguration, Kernel, WGApi,
WireguardInterfaceApi,
};
use x25519_dalek::{EphemeralSecret, PublicKey};
Expand Down
2 changes: 1 addition & 1 deletion examples/server.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::str::FromStr;

use defguard_wireguard_rs::{
host::Peer, key::Key, net::IpAddrMask, InterfaceConfiguration, Kernel, Userspace, WGApi,
host::Peer, key::Key, net::IpAddrMask, InterfaceConfiguration, Kernel, WGApi,
WireguardInterfaceApi,
};
use x25519_dalek::{EphemeralSecret, PublicKey};
Expand Down
10 changes: 3 additions & 7 deletions examples/userspace.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
use std::{
io::{stdin, stdout, Read, Write},
net::SocketAddr,
str::FromStr,
};
#[cfg(target_os = "macos")]
use std::io::{stdin, stdout, Read, Write};

use defguard_wireguard_rs::{host::Peer, key::Key, net::IpAddrMask, InterfaceConfiguration};
#[cfg(target_os = "macos")]
use defguard_wireguard_rs::{Userspace, WGApi, WireguardInterfaceApi};
use x25519_dalek::{EphemeralSecret, PublicKey};

#[cfg(target_os = "macos")]
fn pause() {
let mut stdout = stdout();
stdout.write_all(b"Press Enter to continue...").unwrap();
Expand Down
82 changes: 82 additions & 0 deletions flake.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

39 changes: 39 additions & 0 deletions flake.nix
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
{
description = "Rust development flake";

inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
flake-utils.url = "github:numtide/flake-utils";
rust-overlay = {
url = "github:oxalica/rust-overlay";
inputs = {
nixpkgs.follows = "nixpkgs";
};
};
};

outputs = {
nixpkgs,
flake-utils,
rust-overlay,
...
}:
flake-utils.lib.eachDefaultSystem (system: let
overlays = [(import rust-overlay)];
pkgs = import nixpkgs {
inherit system overlays;
};
rustToolchain = pkgs.rust-bin.stable.latest.default.override {
extensions = ["rust-analyzer" "rust-src" "rustfmt" "clippy"];
};
# define shared build inputs
nativeBuildInputs = with pkgs; [rustToolchain pkg-config];
in {
devShells.default = pkgs.mkShell {
inherit nativeBuildInputs;

# Specify the rust-src path (many editors rely on this)
RUST_SRC_PATH = "${rustToolchain}/lib/rustlib/src/rust/library";
};
});
}
11 changes: 6 additions & 5 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,12 @@ pub enum WireguardInterfaceError {
KernelNotSupported,
#[error("DNS error: {0}")]
DnsError(String),
#[error("Service installation failed: `{message}`")]
ServiceInstallationFailed {
err: std::io::Error,
message: String,
},
#[cfg(target_os = "windows")]
#[error("Service installation failed: `{0}`")]
ServiceInstallationFailed(String),
#[cfg(target_os = "windows")]
#[error("Tunnel service removal failed: `{0}`")]
ServiceRemovalFailed(String),
#[error("Socket is closed: {0}")]
SocketClosed(String),
}
5 changes: 4 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,9 @@ mod wireguard_interface;
#[macro_use]
extern crate log;

use std::{fmt, process::Output};
use std::fmt;
#[cfg(not(target_os = "windows"))]
use std::process::Output;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -139,6 +141,7 @@ impl TryFrom<&InterfaceConfiguration> for Host {
}
}

#[cfg(not(target_os = "windows"))]
/// Utility function which checks external command output status.
fn check_command_output_status(output: Output) -> Result<(), WireguardInterfaceError> {
if !output.status.success() {
Expand Down
16 changes: 7 additions & 9 deletions src/netlink.rs
Original file line number Diff line number Diff line change
Expand Up @@ -467,6 +467,7 @@ fn get_interface_index(ifname: &str) -> NetlinkResult<Option<u32>> {
Ok(None)
}

#[cfg(test)]
/// Get default route for a given address family.
pub(crate) fn get_gateway(address_family: AddressFamily) -> NetlinkResult<Option<IpAddr>> {
let header = RouteHeader {
Expand All @@ -493,16 +494,13 @@ pub(crate) fn get_gateway(address_family: AddressFamily) -> NetlinkResult<Option
// Because messages can't be properly filtered, find the first `Gateway`.
if let RouteNetlinkMessage::NewRoute(RouteMessage { attributes, .. }) = message {
for nla in attributes {
match nla {
RouteAttribute::Gateway(address) => {
debug!("Found gateway {address:?}");
match address {
RouteAddress::Inet(ipv4) => return Ok(Some(IpAddr::V4(ipv4))),
RouteAddress::Inet6(ipv6) => return Ok(Some(IpAddr::V6(ipv6))),
_ => (),
}
if let RouteAttribute::Gateway(address) = nla {
debug!("Found gateway {address:?}");
match address {
RouteAddress::Inet(ipv4) => return Ok(Some(IpAddr::V4(ipv4))),
RouteAddress::Inet6(ipv6) => return Ok(Some(IpAddr::V6(ipv6))),
_ => (),
}
_ => (),
}
}
}
Expand Down
11 changes: 6 additions & 5 deletions src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,19 @@
use std::io::{BufRead, BufReader, Cursor, Error as IoError};
#[cfg(any(target_os = "freebsd", target_os = "macos", target_os = "netbsd"))]
use std::net::{Ipv4Addr, Ipv6Addr};
use std::net::{SocketAddr, ToSocketAddrs};
#[cfg(target_os = "linux")]
use std::{collections::HashSet, fs::OpenOptions};
#[cfg(any(target_os = "freebsd", target_os = "linux", target_os = "netbsd"))]
use std::{io::Write, process::Stdio};
use std::{
net::{IpAddr, SocketAddr, ToSocketAddrs},
process::Command,
};
#[cfg(not(target_os = "windows"))]
use std::{net::IpAddr, process::Command};

#[cfg(target_os = "freebsd")]
use crate::check_command_output_status;
#[cfg(not(target_os = "windows"))]
use crate::Peer;
use crate::WireguardInterfaceError;
#[cfg(any(target_os = "freebsd", target_os = "macos", target_os = "netbsd"))]
use crate::{
bsd::{add_gateway, add_linked_route, get_gateway},
Expand All @@ -21,7 +23,6 @@ use crate::{
};
#[cfg(target_os = "linux")]
use crate::{check_command_output_status, netlink, IpVersion};
use crate::{Peer, WireguardInterfaceError};

#[cfg(any(target_os = "freebsd", target_os = "linux", target_os = "netbsd"))]
pub(crate) fn configure_dns(
Expand Down
6 changes: 3 additions & 3 deletions src/wgapi_linux.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ impl WireguardInterfaceApi for WGApi<Kernel> {
// Assign IP addresses to the interface.
for address in &config.addresses {
debug!("Assigning address {address} to interface {}", self.ifname);
self.assign_address(&address)?;
self.assign_address(address)?;
debug!(
"Address {address} assigned to interface {} successfully",
self.ifname
Expand Down Expand Up @@ -102,9 +102,9 @@ impl WireguardInterfaceApi for WGApi<Kernel> {
/// If allowed IPs contain a default route, instead of adding a route for every peer, the following changes are made:
/// - A new default route is added
/// - The current default route is suppressed by modifying the main routing table rule with `suppress_prefixlen 0`, this makes
/// it so that the whole main routing table rules are still applied except for the default route rules (so the new default route is used instead)
/// it so that the whole main routing table rules are still applied except for the default route rules (so the new default route is used instead)
/// - A rule pushing all traffic through the WireGuard interface is added with the exception of traffic marked with 51820 (default) fwmark which
/// is used for the WireGuard traffic itself (so it doesn't get stuck in a loop)
/// is used for the WireGuard traffic itself (so it doesn't get stuck in a loop)
///
fn configure_peer_routing(&self, peers: &[Peer]) -> Result<(), WireguardInterfaceError> {
add_peer_routing(peers, &self.ifname)?;
Expand Down
50 changes: 38 additions & 12 deletions src/wgapi_windows.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::{
env,
fs::File,
io::{self, BufRead, BufReader, Cursor, Write},
io::{BufRead, BufReader, Cursor, Write},
net::{IpAddr, SocketAddr},
process::Command,
str::FromStr,
Expand Down Expand Up @@ -94,9 +94,8 @@ impl WireguardInterfaceApi for WGApi<Kernel> {
}

for peer in &config.peers {
wireguard_configuration.push_str(
format!("\n[Peer]\nPublicKey = {}", peer.public_key.to_string()).as_str(),
);
wireguard_configuration
.push_str(format!("\n[Peer]\nPublicKey = {}", peer.public_key).as_str());

if let Some(preshared_key) = &peer.preshared_key {
wireguard_configuration
Expand Down Expand Up @@ -175,7 +174,7 @@ impl WireguardInterfaceApi for WGApi<Kernel> {
break;
}

counter = counter + 1;
counter += 1;
}
debug!("Finished waiting for service to be removed, the service is considered to be removed, proceeding further");
}
Expand All @@ -187,8 +186,7 @@ impl WireguardInterfaceApi for WGApi<Kernel> {
.output()
.map_err(|err| {
error!("Failed to create interface. Error: {err}");
let message = err.to_string();
WireguardInterfaceError::ServiceInstallationFailed { err, message }
WireguardInterfaceError::ServiceInstallationFailed(err.to_string())
})?;

debug!("Done installing the new service. Service installation output: {service_installation_output:?}",);
Expand All @@ -198,10 +196,30 @@ impl WireguardInterfaceApi for WGApi<Kernel> {
"Failed to install WireGuard tunnel as a Windows service: {:?}",
service_installation_output.stdout
);
return Err(WireguardInterfaceError::ServiceInstallationFailed {
err: io::Error::new(io::ErrorKind::Other, "Cannot create service"),
message,
});
return Err(WireguardInterfaceError::ServiceInstallationFailed(message));
}

debug!(
"Disabling automatic restart for interface {} tunnel service",
self.ifname
);
let service_update_output = Command::new("sc")
.arg("config")
.arg(format!("WireGuardTunnel${}", self.ifname))
.arg("start=demand")
.output()
.map_err(|err| {
error!("Failed to configure tunnel service. Error: {err}");
WireguardInterfaceError::ServiceInstallationFailed(err.to_string())
})?;

debug!("Done disabling automatic restart for the new service. Service update output: {service_update_output:?}",);
if !service_update_output.status.success() {
let message = format!(
"Failed to configure WireGuard tunnel service: {:?}",
service_update_output.stdout
);
return Err(WireguardInterfaceError::ServiceInstallationFailed(message));
}

// TODO: set maximum transfer unit (MTU)
Expand All @@ -224,7 +242,7 @@ impl WireguardInterfaceApi for WGApi<Kernel> {
fn remove_interface(&self) -> Result<(), WireguardInterfaceError> {
debug!("Removing interface {}", self.ifname);

Command::new("wireguard")
let command_output = Command::new("wireguard")
.arg("/uninstalltunnelservice")
.arg(&self.ifname)
.output()
Expand All @@ -233,6 +251,14 @@ impl WireguardInterfaceApi for WGApi<Kernel> {
WireguardInterfaceError::CommandExecutionFailed(err)
})?;

if !command_output.status.success() {
let message = format!(
"Failed to remove WireGuard tunnel service: {:?}",
command_output.stdout
);
return Err(WireguardInterfaceError::ServiceRemovalFailed(message));
}

info!("Interface {} removed successfully", self.ifname);
Ok(())
}
Expand Down