Generate the nftables ruleset for VM TAP networking.
(tap_device: &str, subnet: &str, gateway_port: u16)
| 16 | |
| 17 | /// Generate the nftables ruleset for VM TAP networking. |
| 18 | pub fn generate_tap_ruleset(tap_device: &str, subnet: &str, gateway_port: u16) -> String { |
| 19 | let table_name = teardown_table_name(tap_device); |
| 20 | let mut ruleset = String::with_capacity(512); |
| 21 | |
| 22 | writeln!(ruleset, "table ip {table_name} {{").unwrap(); |
| 23 | writeln!(ruleset, " chain postrouting {{").unwrap(); |
| 24 | writeln!( |
| 25 | ruleset, |
| 26 | " type nat hook postrouting priority 100; policy accept;" |
| 27 | ) |
| 28 | .unwrap(); |
| 29 | writeln!(ruleset, " ip saddr {subnet} masquerade").unwrap(); |
| 30 | writeln!(ruleset, " }}").unwrap(); |
| 31 | writeln!(ruleset, " chain forward {{").unwrap(); |
| 32 | writeln!( |
| 33 | ruleset, |
| 34 | " type filter hook forward priority 0; policy accept;" |
| 35 | ) |
| 36 | .unwrap(); |
| 37 | writeln!(ruleset, " iifname \"{tap_device}\" accept").unwrap(); |
| 38 | writeln!( |
| 39 | ruleset, |
| 40 | " oifname \"{tap_device}\" ct state related,established accept" |
| 41 | ) |
| 42 | .unwrap(); |
| 43 | writeln!(ruleset, " oifname \"{tap_device}\" drop").unwrap(); |
| 44 | writeln!(ruleset, " }}").unwrap(); |
| 45 | writeln!(ruleset, " chain input {{").unwrap(); |
| 46 | writeln!( |
| 47 | ruleset, |
| 48 | " type filter hook input priority 0; policy accept;" |
| 49 | ) |
| 50 | .unwrap(); |
| 51 | writeln!( |
| 52 | ruleset, |
| 53 | " iifname \"{tap_device}\" tcp dport {gateway_port} accept" |
| 54 | ) |
| 55 | .unwrap(); |
| 56 | writeln!(ruleset, " iifname \"{tap_device}\" drop").unwrap(); |
| 57 | writeln!(ruleset, " }}").unwrap(); |
| 58 | writeln!(ruleset, "}}").unwrap(); |
| 59 | |
| 60 | ruleset |
| 61 | } |
| 62 | |
| 63 | #[cfg(test)] |
| 64 | mod tests { |