1#[cfg(any(test, target_os = "macos"))]
9use std::fmt::Write as _;
10#[cfg(any(target_os = "linux", target_os = "macos"))]
11use std::process::Output;
12#[cfg(any(target_os = "linux", target_os = "macos"))]
13use std::process::{Command, Stdio};
14
15use thiserror::Error;
16
17pub const FIPS_MESH_IPV6_PREFIX: &str = "fd00::/8";
19
20const DEFAULT_LINUX_TABLE_NAME: &str = "fips_host";
21const DEFAULT_MACOS_ANCHOR_NAME: &str = "com.apple/fips/host";
22
23#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct HostFirewallConfig {
26 interface: String,
27 inbound_tcp_ports: Vec<u16>,
28 linux_table_name: String,
29 macos_anchor_name: String,
30}
31
32impl HostFirewallConfig {
33 #[must_use]
35 pub fn new(interface: impl Into<String>) -> Self {
36 Self {
37 interface: interface.into(),
38 inbound_tcp_ports: Vec::new(),
39 linux_table_name: DEFAULT_LINUX_TABLE_NAME.to_string(),
40 macos_anchor_name: DEFAULT_MACOS_ANCHOR_NAME.to_string(),
41 }
42 }
43
44 #[must_use]
46 pub fn with_inbound_tcp_ports(mut self, ports: impl IntoIterator<Item = u16>) -> Self {
47 self.inbound_tcp_ports = normalized_tcp_ports(ports);
48 self
49 }
50
51 #[must_use]
53 pub fn with_linux_table_name(mut self, table_name: impl Into<String>) -> Self {
54 self.linux_table_name = table_name.into();
55 self
56 }
57
58 #[must_use]
60 pub fn with_macos_anchor_name(mut self, anchor_name: impl Into<String>) -> Self {
61 self.macos_anchor_name = anchor_name.into();
62 self
63 }
64
65 #[must_use]
67 pub fn interface(&self) -> &str {
68 &self.interface
69 }
70
71 #[must_use]
73 pub fn inbound_tcp_ports(&self) -> &[u16] {
74 &self.inbound_tcp_ports
75 }
76
77 #[must_use]
79 pub fn linux_table_name(&self) -> &str {
80 &self.linux_table_name
81 }
82
83 #[must_use]
85 pub fn macos_anchor_name(&self) -> &str {
86 &self.macos_anchor_name
87 }
88
89 fn validate(&self) -> Result<(), HostFirewallError> {
90 validate_interface_name(&self.interface)?;
91 validate_nft_table_name(&self.linux_table_name)?;
92 validate_pf_anchor_name(&self.macos_anchor_name)?;
93 Ok(())
94 }
95}
96
97#[derive(Debug)]
102pub struct HostFirewallGuard {
103 #[cfg(any(target_os = "linux", target_os = "macos"))]
104 backend: HostFirewallBackend,
105}
106
107#[cfg(any(target_os = "linux", target_os = "macos"))]
108#[derive(Debug)]
109enum HostFirewallBackend {
110 #[cfg(target_os = "linux")]
111 Linux { table_name: String },
112 #[cfg(target_os = "macos")]
113 Macos {
114 anchor_name: String,
115 enable_token: Option<String>,
116 },
117}
118
119impl HostFirewallGuard {
120 #[must_use]
122 pub const fn platform_supported() -> bool {
123 cfg!(any(target_os = "linux", target_os = "macos"))
124 }
125
126 #[must_use]
129 pub fn platform_available() -> bool {
130 #[cfg(target_os = "linux")]
131 return command_exists("nft");
132 #[cfg(target_os = "macos")]
133 return command_exists("pfctl");
134 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
135 return false;
136 }
137
138 pub fn install(config: &HostFirewallConfig) -> Result<Self, HostFirewallError> {
144 config.validate()?;
145
146 #[cfg(target_os = "linux")]
147 {
148 install_linux_firewall(config)
149 }
150 #[cfg(target_os = "macos")]
151 {
152 install_macos_firewall(config)
153 }
154 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
155 {
156 let _ = config;
157 Err(HostFirewallError::UnsupportedPlatform)
158 }
159 }
160
161 pub fn cleanup_disabled_artifacts(config: &HostFirewallConfig) {
166 #[cfg(target_os = "linux")]
167 remove_nft_table(config.linux_table_name());
168 #[cfg(target_os = "macos")]
169 flush_pf_anchor(config.macos_anchor_name());
170 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
171 let _ = config;
172 }
173}
174
175impl Drop for HostFirewallGuard {
176 fn drop(&mut self) {
177 #[cfg(target_os = "linux")]
178 {
179 let HostFirewallBackend::Linux { table_name } = &self.backend;
180 remove_nft_table(table_name);
181 }
182 #[cfg(target_os = "macos")]
183 {
184 let HostFirewallBackend::Macos {
185 anchor_name,
186 enable_token,
187 } = &self.backend;
188 flush_pf_anchor(anchor_name);
189 if let Some(token) = enable_token {
190 release_pf_enable_token(token);
191 }
192 }
193 }
194}
195
196#[derive(Debug, Error)]
198pub enum HostFirewallError {
199 #[error("host firewall is not supported on this platform")]
201 UnsupportedPlatform,
202
203 #[error("required firewall command `{0}` was not found")]
205 MissingCommand(&'static str),
206
207 #[error("invalid {field}: {value}")]
209 InvalidName {
210 field: &'static str,
212 value: String,
214 },
215
216 #[error("failed to run `{command}`: {source}")]
218 CommandIo {
219 command: &'static str,
221 #[source]
223 source: std::io::Error,
224 },
225
226 #[error("`{command}` exited with {status}: {stderr}")]
228 CommandFailed {
229 command: &'static str,
231 status: std::process::ExitStatus,
233 stderr: String,
235 },
236}
237
238fn normalized_tcp_ports(ports: impl IntoIterator<Item = u16>) -> Vec<u16> {
239 let mut ports = ports.into_iter().collect::<Vec<_>>();
240 ports.sort_unstable();
241 ports.dedup();
242 ports
243}
244
245fn validate_interface_name(name: &str) -> Result<(), HostFirewallError> {
246 validate_name(
247 "interface",
248 name,
249 |ch| ch.is_ascii_alphanumeric() || matches!(ch, '_' | '-' | '.'),
250 false,
251 )
252}
253
254fn validate_nft_table_name(name: &str) -> Result<(), HostFirewallError> {
255 if name.is_empty()
256 || !name
257 .chars()
258 .next()
259 .is_some_and(|ch| ch.is_ascii_alphabetic() || ch == '_')
260 {
261 return Err(HostFirewallError::InvalidName {
262 field: "nft table name",
263 value: name.to_string(),
264 });
265 }
266 validate_name(
267 "nft table name",
268 name,
269 |ch| ch.is_ascii_alphanumeric() || ch == '_',
270 false,
271 )
272}
273
274fn validate_pf_anchor_name(name: &str) -> Result<(), HostFirewallError> {
275 validate_name(
276 "pf anchor name",
277 name,
278 |ch| ch.is_ascii_alphanumeric() || matches!(ch, '_' | '-' | '.' | '/'),
279 true,
280 )
281}
282
283fn validate_name(
284 field: &'static str,
285 value: &str,
286 valid_char: impl Fn(char) -> bool,
287 allow_slash: bool,
288) -> Result<(), HostFirewallError> {
289 let slash_ok = allow_slash && !value.starts_with('/') && !value.ends_with('/');
290 let slash_valid = !value.contains('/') || slash_ok;
291 if value.is_empty() || !slash_valid || !value.chars().all(valid_char) {
292 return Err(HostFirewallError::InvalidName {
293 field,
294 value: value.to_string(),
295 });
296 }
297 Ok(())
298}
299
300#[cfg(any(test, target_os = "linux"))]
301#[must_use]
302pub fn render_nft_host_firewall_rules(
303 table_name: &str,
304 iface: &str,
305 inbound_tcp_ports: &[u16],
306) -> String {
307 let ports = normalized_tcp_ports(inbound_tcp_ports.iter().copied());
308 let inbound_tcp_rule = match ports.as_slice() {
309 [] => String::new(),
310 [port] => format!(" tcp dport {port} accept\n"),
311 ports => {
312 let joined = ports
313 .iter()
314 .map(u16::to_string)
315 .collect::<Vec<_>>()
316 .join(", ");
317 format!(" tcp dport {{ {joined} }} accept\n")
318 }
319 };
320
321 format!(
322 "table inet {table_name} {{\n\
323 chain input {{\n\
324 type filter hook input priority 0; policy accept;\n\
325 iifname != \"{iface}\" return\n\
326 meta nfproto != ipv6 return\n\
327 ip6 saddr != {FIPS_MESH_IPV6_PREFIX} return\n\
328 ct state established,related accept\n\
329 {inbound_tcp_rule}\
330 counter drop\n\
331 }}\n\
332 chain output {{\n\
333 type filter hook output priority 0; policy accept;\n\
334 oifname != \"{iface}\" return\n\
335 meta nfproto != ipv6 return\n\
336 ip6 daddr != {FIPS_MESH_IPV6_PREFIX} return\n\
337 ct state established,related accept\n\
338 meta l4proto tcp accept\n\
339 counter drop\n\
340 }}\n\
341 }}\n"
342 )
343}
344
345#[cfg(any(test, target_os = "macos"))]
346#[must_use]
347pub fn render_macos_pf_host_firewall_rules(iface: &str, inbound_tcp_ports: &[u16]) -> String {
348 let ports = normalized_tcp_ports(inbound_tcp_ports.iter().copied());
349 let mut rules = String::from("# Managed by fips-core for FIPS host routing.\n");
350
351 match ports.as_slice() {
352 [] => {}
353 [port] => {
354 let _ = writeln!(
355 rules,
356 "pass in quick on {iface} inet6 proto tcp from {FIPS_MESH_IPV6_PREFIX} to any port {port} flags S/SA keep state"
357 );
358 }
359 ports => {
360 let joined = ports
361 .iter()
362 .map(u16::to_string)
363 .collect::<Vec<_>>()
364 .join(", ");
365 let _ = writeln!(
366 rules,
367 "pass in quick on {iface} inet6 proto tcp from {FIPS_MESH_IPV6_PREFIX} to any port {{ {joined} }} flags S/SA keep state"
368 );
369 }
370 }
371
372 let _ = write!(
373 rules,
374 "pass out quick on {iface} inet6 proto tcp from any to {FIPS_MESH_IPV6_PREFIX} flags S/SA keep state\n\
375 block drop in quick on {iface} inet6 from {FIPS_MESH_IPV6_PREFIX} to any\n\
376 block drop out quick on {iface} inet6 from any to {FIPS_MESH_IPV6_PREFIX}\n"
377 );
378 rules
379}
380
381#[cfg(target_os = "linux")]
382fn install_linux_firewall(
383 config: &HostFirewallConfig,
384) -> Result<HostFirewallGuard, HostFirewallError> {
385 if !command_exists("nft") {
386 return Err(HostFirewallError::MissingCommand("nft"));
387 }
388
389 let rules = render_nft_host_firewall_rules(
390 config.linux_table_name(),
391 config.interface(),
392 config.inbound_tcp_ports(),
393 );
394 remove_nft_table(config.linux_table_name());
395 let mut child = Command::new("nft")
396 .arg("-f")
397 .arg("-")
398 .stdin(Stdio::piped())
399 .stderr(Stdio::piped())
400 .spawn()
401 .map_err(|source| HostFirewallError::CommandIo {
402 command: "nft",
403 source,
404 })?;
405 {
406 let stdin = child
407 .stdin
408 .as_mut()
409 .ok_or_else(|| HostFirewallError::CommandIo {
410 command: "nft",
411 source: std::io::Error::new(
412 std::io::ErrorKind::BrokenPipe,
413 "nft stdin unavailable",
414 ),
415 })?;
416 use std::io::Write as _;
417 stdin
418 .write_all(rules.as_bytes())
419 .map_err(|source| HostFirewallError::CommandIo {
420 command: "nft",
421 source,
422 })?;
423 }
424 let output = child
425 .wait_with_output()
426 .map_err(|source| HostFirewallError::CommandIo {
427 command: "nft",
428 source,
429 })?;
430 ensure_success("nft", output)?;
431
432 Ok(HostFirewallGuard {
433 backend: HostFirewallBackend::Linux {
434 table_name: config.linux_table_name().to_string(),
435 },
436 })
437}
438
439#[cfg(target_os = "linux")]
440fn remove_nft_table(table_name: &str) {
441 if !command_exists("nft") {
442 return;
443 }
444 let _ = Command::new("nft")
445 .arg("delete")
446 .arg("table")
447 .arg("inet")
448 .arg(table_name)
449 .stdout(Stdio::null())
450 .stderr(Stdio::null())
451 .status();
452}
453
454#[cfg(target_os = "macos")]
455fn install_macos_firewall(
456 config: &HostFirewallConfig,
457) -> Result<HostFirewallGuard, HostFirewallError> {
458 if !command_exists("pfctl") {
459 return Err(HostFirewallError::MissingCommand("pfctl"));
460 }
461
462 let rules = render_macos_pf_host_firewall_rules(config.interface(), config.inbound_tcp_ports());
463 let _ = run_pfctl(&["-a", config.macos_anchor_name(), "-F", "rules"], None)?;
464 run_pfctl(&["-a", config.macos_anchor_name(), "-f", "-"], Some(&rules))?;
465 let enable_output = run_pfctl(&["-E"], None)?;
466 let enable_token = parse_pf_enable_token(&String::from_utf8_lossy(&enable_output.stdout));
467
468 Ok(HostFirewallGuard {
469 backend: HostFirewallBackend::Macos {
470 anchor_name: config.macos_anchor_name().to_string(),
471 enable_token,
472 },
473 })
474}
475
476#[cfg(target_os = "macos")]
477fn flush_pf_anchor(anchor_name: &str) {
478 if !command_exists("pfctl") {
479 return;
480 }
481 let _ = run_pfctl(&["-a", anchor_name, "-F", "rules"], None);
482}
483
484#[cfg(target_os = "macos")]
485fn release_pf_enable_token(token: &str) {
486 if !command_exists("pfctl") {
487 return;
488 }
489 let _ = run_pfctl(&["-X", token], None);
490}
491
492#[cfg(target_os = "macos")]
493fn run_pfctl(args: &[&str], stdin: Option<&str>) -> Result<Output, HostFirewallError> {
494 let mut command = Command::new("pfctl");
495 command.args(args).stderr(Stdio::piped());
496 if stdin.is_some() {
497 command.stdin(Stdio::piped());
498 }
499 let mut child = command
500 .spawn()
501 .map_err(|source| HostFirewallError::CommandIo {
502 command: "pfctl",
503 source,
504 })?;
505 if let Some(input) = stdin {
506 let child_stdin = child
507 .stdin
508 .as_mut()
509 .ok_or_else(|| HostFirewallError::CommandIo {
510 command: "pfctl",
511 source: std::io::Error::new(
512 std::io::ErrorKind::BrokenPipe,
513 "pfctl stdin unavailable",
514 ),
515 })?;
516 use std::io::Write as _;
517 child_stdin
518 .write_all(input.as_bytes())
519 .map_err(|source| HostFirewallError::CommandIo {
520 command: "pfctl",
521 source,
522 })?;
523 }
524 let output = child
525 .wait_with_output()
526 .map_err(|source| HostFirewallError::CommandIo {
527 command: "pfctl",
528 source,
529 })?;
530 ensure_success("pfctl", output)
531}
532
533#[cfg(target_os = "macos")]
534fn parse_pf_enable_token(output: &str) -> Option<String> {
535 output.lines().find_map(|line| {
536 let (label, value) = line.split_once(':')?;
537 if label.trim().eq_ignore_ascii_case("token") {
538 let token = value.trim();
539 if !token.is_empty() {
540 return Some(token.to_string());
541 }
542 }
543 None
544 })
545}
546
547#[cfg(any(target_os = "linux", target_os = "macos"))]
548fn ensure_success(command: &'static str, output: Output) -> Result<Output, HostFirewallError> {
549 if output.status.success() {
550 Ok(output)
551 } else {
552 Err(HostFirewallError::CommandFailed {
553 command,
554 status: output.status,
555 stderr: String::from_utf8_lossy(&output.stderr).trim().to_string(),
556 })
557 }
558}
559
560#[cfg(any(target_os = "linux", target_os = "macos"))]
561fn command_exists(command: &str) -> bool {
562 Command::new("sh")
563 .arg("-c")
564 .arg(format!("command -v {command} >/dev/null 2>&1"))
565 .status()
566 .is_ok_and(|status| status.success())
567}
568
569#[cfg(test)]
570mod tests {
571 use super::*;
572
573 #[test]
574 fn config_normalizes_inbound_tcp_ports() {
575 let config = HostFirewallConfig::new("fips0").with_inbound_tcp_ports([443, 22, 22]);
576
577 assert_eq!(config.inbound_tcp_ports(), &[22, 443]);
578 }
579
580 #[test]
581 fn rejects_unsafe_names() {
582 assert!(HostFirewallConfig::new("utun0").validate().is_ok());
583 assert!(HostFirewallConfig::new("utun0; reboot").validate().is_err());
584 assert!(
585 HostFirewallConfig::new("utun0")
586 .with_linux_table_name("1bad")
587 .validate()
588 .is_err()
589 );
590 assert!(
591 HostFirewallConfig::new("utun0")
592 .with_macos_anchor_name("/bad")
593 .validate()
594 .is_err()
595 );
596 }
597
598 #[test]
599 fn nft_rules_default_to_outbound_tcp_only() {
600 let rules = render_nft_host_firewall_rules("fips_host", "nvpn0", &[]);
601
602 assert!(rules.contains("table inet fips_host"));
603 assert!(rules.contains("iifname != \"nvpn0\" return"));
604 assert!(rules.contains("oifname != \"nvpn0\" return"));
605 assert!(rules.contains("ip6 saddr != fd00::/8 return"));
606 assert!(rules.contains("ip6 daddr != fd00::/8 return"));
607 assert!(rules.contains("meta l4proto tcp accept"));
608 assert!(!rules.contains("tcp dport"));
609 }
610
611 #[test]
612 fn nft_rules_allow_configured_inbound_tcp_ports() {
613 let rules = render_nft_host_firewall_rules("fips_host", "nvpn0", &[443, 22, 22]);
614
615 assert!(rules.contains("tcp dport { 22, 443 } accept"));
616 }
617
618 #[test]
619 fn macos_pf_rules_default_to_outbound_tcp_only() {
620 let rules = render_macos_pf_host_firewall_rules("utun8", &[]);
621
622 assert!(rules.contains("pass out quick on utun8 inet6 proto tcp"));
623 assert!(rules.contains("block drop in quick on utun8 inet6 from fd00::/8 to any"));
624 assert!(rules.contains("block drop out quick on utun8 inet6 from any to fd00::/8"));
625 assert!(!rules.contains("pass in quick"));
626 assert!(!rules.contains("proto udp"));
627 }
628
629 #[test]
630 fn macos_pf_rules_allow_configured_inbound_tcp_ports() {
631 let rules = render_macos_pf_host_firewall_rules("utun8", &[443, 22, 22]);
632
633 assert!(rules.contains(
634 "pass in quick on utun8 inet6 proto tcp from fd00::/8 to any port { 22, 443 }"
635 ));
636 }
637
638 #[cfg(target_os = "macos")]
639 #[test]
640 fn parses_pf_enable_token() {
641 assert_eq!(
642 parse_pf_enable_token("Token : 1234567890\n"),
643 Some("1234567890".to_string())
644 );
645 }
646}