use super::*;
use crate::TunConfig;
use std::sync::Arc;
pub(crate) const ADAPTER_NAME: &str = "FIPS";
const WINTUN_RING_CAPACITY: u32 = 0x200000;
pub struct TunDevice {
session: Arc<wintun::Session>,
_adapter: Arc<wintun::Adapter>,
name: String,
mtu: u16,
address: FipsAddress,
}
impl TunDevice {
pub async fn create(config: &TunConfig, address: FipsAddress) -> Result<Self, TunError> {
let name = config.name();
let mtu = config.mtu();
let wintun = unsafe { wintun::load() }.map_err(|e| {
TunError::Create(
format!(
"Failed to load wintun.dll: {}. Download from https://www.wintun.net/",
e
)
.into(),
)
})?;
let adapter = match wintun::Adapter::create(&wintun, ADAPTER_NAME, name, None) {
Ok(a) => a,
Err(e) => {
return Err(TunError::Create(
format!(
"Failed to create wintun adapter '{}': {}. Run as Administrator.",
name, e
)
.into(),
));
}
};
let session = adapter.start_session(WINTUN_RING_CAPACITY).map_err(|e| {
TunError::Create(format!("Failed to start wintun session: {}", e).into())
})?;
let session = Arc::new(session);
let ipv6_addr = address.to_ipv6();
configure_windows_interface(ADAPTER_NAME, ipv6_addr, mtu).await?;
Ok(Self {
session,
_adapter: adapter,
name: name.to_string(),
mtu,
address,
})
}
pub fn name(&self) -> &str {
&self.name
}
pub fn mtu(&self) -> u16 {
self.mtu
}
pub fn address(&self) -> &FipsAddress {
&self.address
}
pub fn read_packet(&mut self, buf: &mut [u8]) -> Result<usize, TunError> {
match self.session.receive_blocking() {
Ok(packet) => {
let bytes = packet.bytes();
let len = bytes.len().min(buf.len());
buf[..len].copy_from_slice(&bytes[..len]);
Ok(len)
}
Err(e) => Err(TunError::Configure(format!("read failed: {}", e))),
}
}
pub async fn shutdown(&self) -> Result<(), TunError> {
debug!(name = %self.name, "Shutting down TUN device");
let _ = tokio::process::Command::new("netsh")
.args([
"interface",
"ipv6",
"delete",
"route",
"fd00::/8",
&format!("interface={}", ADAPTER_NAME),
])
.output()
.await;
Ok(())
}
pub fn create_writer(
&self,
max_mss: u16,
path_mtu_lookup: PathMtuLookup,
) -> Result<(TunWriter, TunTx), TunError> {
let (tx, rx) = mpsc::channel();
Ok((
TunWriter {
session: self.session.clone(),
rx,
name: self.name.clone(),
max_mss,
path_mtu_lookup,
},
tx,
))
}
}
impl std::fmt::Debug for TunDevice {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TunDevice")
.field("name", &self.name)
.field("mtu", &self.mtu)
.field("address", &self.address)
.finish()
}
}
pub struct TunWriter {
session: Arc<wintun::Session>,
rx: mpsc::Receiver<Vec<u8>>,
name: String,
max_mss: u16,
path_mtu_lookup: PathMtuLookup,
}
impl TunWriter {
pub fn run(self) {
use super::per_flow_max_mss;
use crate::upper::tcp_mss::clamp_tcp_mss;
debug!(name = %self.name, max_mss = self.max_mss, "TUN writer starting");
for mut packet in self.rx {
let effective_max_mss = if packet.len() >= 24 {
per_flow_max_mss(&self.path_mtu_lookup, &packet[8..24], self.max_mss)
} else {
self.max_mss
};
if clamp_tcp_mss(&mut packet, effective_max_mss) {
trace!(
name = %self.name,
max_mss = effective_max_mss,
"Clamped TCP MSS in inbound SYN-ACK packet"
);
}
let pkt_len = match u16::try_from(packet.len()) {
Ok(len) => len,
Err(_) => {
warn!(name = %self.name, len = packet.len(), "Dropping oversized packet for TUN");
continue;
}
};
match self.session.allocate_send_packet(pkt_len) {
Ok(mut send_packet) => {
send_packet.bytes_mut().copy_from_slice(&packet);
self.session.send_packet(send_packet);
trace!(name = %self.name, len = packet.len(), "TUN packet written");
}
Err(e) => {
error!(name = %self.name, error = %e, "TUN write error (allocate)");
}
}
}
}
}
pub fn run_tun_reader(
mut device: TunDevice,
mtu: u16,
our_addr: FipsAddress,
tun_tx: TunTx,
outbound_tx: TunOutboundTx,
transport_mtu: u16,
path_mtu_lookup: PathMtuLookup,
) {
let (name, mut buf, max_mss) = super::tun_reader_setup(device.name(), mtu, transport_mtu);
loop {
match device.read_packet(&mut buf) {
Ok(n) if n > 0 => {
if !super::handle_tun_packet(
&mut buf[..n],
max_mss,
&name,
our_addr,
&tun_tx,
&outbound_tx,
&path_mtu_lookup,
) {
break;
}
}
Ok(_) => {}
Err(e) => {
let err_str = format!("{}", e);
if !err_str.contains("Bad address") {
error!(name = %name, error = %e, "TUN read error");
}
break;
}
}
}
}
pub async fn shutdown_tun_interface(name: &str) -> Result<(), TunError> {
debug!("Shutting down TUN interface {}", name);
let _ = tokio::process::Command::new("netsh")
.args([
"interface",
"ipv6",
"delete",
"route",
"fd00::/8",
&format!("interface={}", ADAPTER_NAME),
])
.output()
.await;
let _ = name; debug!("TUN interface {} stopped", name);
Ok(())
}
async fn configure_windows_interface(
adapter_name: &str,
addr: Ipv6Addr,
mtu: u16,
) -> Result<(), TunError> {
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
let output = tokio::process::Command::new("netsh")
.args([
"interface",
"ipv6",
"add",
"address",
adapter_name,
&format!("{}/128", addr),
])
.output()
.await
.map_err(|e| TunError::Configure(format!("netsh add address failed: {}", e)))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
if !stderr.contains("already") && !stdout.contains("already") {
warn!(
"netsh add address failed: stdout={} stderr={}",
stdout.trim(),
stderr.trim()
);
}
}
let output = tokio::process::Command::new("netsh")
.args([
"interface",
"ipv6",
"set",
"subinterface",
adapter_name,
&format!("mtu={}", mtu),
])
.output()
.await
.map_err(|e| TunError::Configure(format!("netsh set mtu failed: {}", e)))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
warn!(
"netsh set mtu failed: stdout={} stderr={}",
stdout.trim(),
stderr.trim()
);
}
let output = tokio::process::Command::new("netsh")
.args([
"interface",
"ipv6",
"add",
"route",
"fd00::/8",
adapter_name,
])
.output()
.await
.map_err(|e| TunError::Configure(format!("netsh add route failed: {}", e)))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
if !stderr.contains("already") && !stdout.contains("already") {
warn!(
"netsh add route failed: stdout={} stderr={}",
stdout.trim(),
stderr.trim()
);
}
}
Ok(())
}