fips-core 0.3.79

Reusable FIPS mesh, endpoint, transport, and protocol library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
use super::*;
use crate::TunConfig;
use std::sync::Arc;

/// The Windows adapter name visible in network settings and used in netsh commands.
pub(crate) const ADAPTER_NAME: &str = "FIPS";

/// Wintun ring buffer capacity in bytes. Must be a power of 2 between
/// 0x20000 (128 KiB) and 0x4000000 (64 MiB). 2 MiB balances memory
/// usage against burst tolerance.
const WINTUN_RING_CAPACITY: u32 = 0x200000; // 2 MiB

/// FIPS TUN device wrapper (Windows/wintun).
///
/// Uses the wintun driver for userspace packet I/O on Windows. The wintun
/// DLL must be present in the executable's directory or system PATH.
/// Adapter creation requires Administrator privileges.
///
/// Unlike the Linux TUN which uses a file descriptor, wintun uses a
/// session-based API with ring buffers for packet exchange.
pub struct TunDevice {
    session: Arc<wintun::Session>,
    _adapter: Arc<wintun::Adapter>,
    name: String,
    mtu: u16,
    address: FipsAddress,
}

impl TunDevice {
    /// Create a wintun TUN adapter and configure it with an IPv6 address.
    ///
    /// Loads the wintun DLL, creates (or reopens) a named adapter, starts
    /// a session with a 2 MiB ring buffer, and configures the interface
    /// via netsh. Requires Administrator privileges.
    pub async fn create(config: &TunConfig, address: FipsAddress) -> Result<Self, TunError> {
        let name = config.name();
        let mtu = config.mtu();

        // Load the wintun DLL
        let wintun = unsafe { wintun::load() }.map_err(|e| {
            TunError::Create(
                format!(
                    "Failed to load wintun.dll: {}. Download from https://www.wintun.net/",
                    e
                )
                .into(),
            )
        })?;

        // Create or reopen the adapter.
        // First arg: adapter name visible in Windows network settings.
        // Second arg: tunnel type (internal identifier for wintun).
        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(),
                ));
            }
        };

        // Start a session with the configured ring buffer capacity
        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);

        // Configure the IPv6 address and route via netsh.
        // Use the adapter name (ADAPTER_NAME) not the tunnel type name.
        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,
        })
    }

    /// Get the device name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get the configured MTU.
    pub fn mtu(&self) -> u16 {
        self.mtu
    }

    /// Get the FIPS address assigned to this device.
    pub fn address(&self) -> &FipsAddress {
        &self.address
    }

    /// Read a packet from the TUN device.
    ///
    /// Blocks until a packet is available from the wintun session.
    /// Returns the number of bytes copied into `buf`.
    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))),
        }
    }

    /// Shutdown the TUN device by removing the fd00::/8 route.
    ///
    /// The wintun adapter and session are cleaned up when dropped.
    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(())
    }

    /// Create a TunWriter for this device.
    ///
    /// Clones the wintun session `Arc` so the writer can allocate and send
    /// packets independently. Returns the writer and a channel sender for
    /// submitting packets to be written.
    ///
    /// `max_mss` is the global TCP MSS ceiling. `path_mtu_lookup` is a
    /// read-only handle to per-destination path MTU learned via
    /// discovery.
    pub fn create_writer(
        &self,
        max_mss: u16,
        path_mtu_lookup: PathMtuLookup,
    ) -> Result<(TunWriter, TunTx), TunError> {
        let (tx, rx) = write_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()
    }
}

/// Writer thread for TUN device (Windows).
///
/// Services a queue of outbound packets and writes them to the wintun
/// session. Uses `allocate_send_packet()` / `send_packet()` instead of
/// file I/O.
///
/// Also performs TCP MSS clamping on inbound SYN-ACK packets.
pub struct TunWriter {
    session: Arc<wintun::Session>,
    rx: TunRx,
    name: String,
    max_mss: u16,
    path_mtu_lookup: PathMtuLookup,
}

impl TunWriter {
    /// Run the writer loop.
    ///
    /// Blocks forever, reading packets from the channel and writing them
    /// to the wintun session. Returns when the channel is closed.
    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");

        while let Some(mut packet) = self.rx.recv() {
            // Per-destination clamp (peer source IPv6 = bytes 8..24)
            let effective_max_mss = if packet.len() >= 24 {
                per_flow_max_mss(
                    &self.path_mtu_lookup,
                    &packet.as_slice()[8..24],
                    self.max_mss,
                )
            } else {
                self.max_mss
            };
            // Clamp TCP MSS on inbound SYN-ACK packets
            if clamp_tcp_mss(packet.as_mut_slice(), 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.as_slice());
                    self.session.send_packet(send_packet);
                    crate::perf_profile::record_tun_write_packet(packet.len());
                    trace!(name = %self.name, len = packet.len(), "TUN packet written");
                }
                Err(e) => {
                    error!(name = %self.name, error = %e, "TUN write error (allocate)");
                }
            }
        }
    }
}

/// TUN packet reader loop (Windows).
///
/// Reads IPv6 packets from the wintun session. Packets destined for FIPS
/// addresses (fd::/8) are forwarded to the Node via the outbound channel
/// for session encapsulation and routing. Non-FIPS packets receive ICMPv6
/// Destination Unreachable responses.
///
/// Also performs TCP MSS clamping on SYN packets to prevent oversized segments.
///
/// This is designed to run in a dedicated thread since wintun reads are blocking.
/// The loop exits when the session is closed or an unrecoverable error occurs.
pub(crate) fn run_tun_reader(runtime: super::TunReaderRuntime) {
    let super::TunReaderRuntime {
        mut device,
        mtu,
        our_addr,
        tun_tx,
        outbound_tx,
        transport_mtu,
        path_mtu_lookup,
    } = runtime;
    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 => {
                crate::perf_profile::record_tun_read_packet(n);
                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;
            }
        }
    }
}

/// Shutdown and delete a TUN interface by name (Windows).
///
/// Removes the fd00::/8 route via netsh. The wintun adapter itself
/// is cleaned up when the `Adapter` handle is dropped.
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; // name is the tunnel type, not the adapter name
    debug!("TUN interface {} stopped", name);
    Ok(())
}

/// Configure the Windows network interface with IPv6 address, MTU, and route.
///
/// Uses `netsh` commands to configure the wintun adapter. A brief delay
/// is inserted before configuration to allow Windows to fully register
/// the adapter in its network stack.
///
/// `adapter_name` must be the Windows adapter name (e.g. "FIPS"), not the
/// wintun tunnel type name.
async fn configure_windows_interface(
    adapter_name: &str,
    addr: Ipv6Addr,
    mtu: u16,
) -> Result<(), TunError> {
    // Brief delay to let Windows fully register the adapter
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;

    // Set IPv6 address
    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()
            );
        }
    }

    // Set MTU
    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()
        );
    }

    // Add route for fd00::/8 (FIPS address space) via this adapter
    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(())
}