|
| 1 | +use super::Args; |
| 2 | +use anyhow::{bail, Context}; |
| 3 | +use forwarder::uri::Protocol; |
| 4 | +use std::process::Command; |
| 5 | + |
| 6 | +#[derive(Default, Clone)] |
| 7 | +pub struct IptablesGuard { |
| 8 | + filters: Vec<Filter>, |
| 9 | +} |
| 10 | + |
| 11 | +impl Drop for IptablesGuard { |
| 12 | + fn drop(&mut self) { |
| 13 | + for filter in self.filters.drain(..) { |
| 14 | + run_iptables_rst_filter(Action::Remove, filter) |
| 15 | + .with_context(|| "couldn't remove iptables filter") |
| 16 | + .unwrap(); |
| 17 | + } |
| 18 | + } |
| 19 | +} |
| 20 | + |
| 21 | +pub fn drop_rst(cli: &Args) -> anyhow::Result<IptablesGuard> { |
| 22 | + let mut guard = IptablesGuard::default(); |
| 23 | + if cli.remote_uri.protocol == Protocol::Pushack { |
| 24 | + let filter = Filter::DestPort(cli.remote_uri.addr.port()); |
| 25 | + run_iptables_rst_filter(Action::Add, filter) |
| 26 | + .with_context(|| "couldn't add rst filter for remote")?; |
| 27 | + guard.filters.push(filter); |
| 28 | + } |
| 29 | + if cli.listen_uri.protocol == Protocol::Pushack { |
| 30 | + let filter = Filter::SourcePort(cli.listen_uri.addr.port()); |
| 31 | + run_iptables_rst_filter(Action::Add, filter) |
| 32 | + .with_context(|| "couldn't add rst filter for listen")?; |
| 33 | + guard.filters.push(filter); |
| 34 | + } |
| 35 | + Ok(guard) |
| 36 | +} |
| 37 | + |
| 38 | +#[derive(Debug, PartialEq, Eq, Clone, Copy)] |
| 39 | +enum Filter { |
| 40 | + SourcePort(u16), |
| 41 | + DestPort(u16), |
| 42 | +} |
| 43 | + |
| 44 | +#[derive(PartialEq, Eq, Clone, Copy)] |
| 45 | +enum Action { |
| 46 | + Add, |
| 47 | + Remove, |
| 48 | +} |
| 49 | + |
| 50 | +fn run_iptables_rst_filter(action: Action, filter: Filter) -> anyhow::Result<()> { |
| 51 | + let (filter, value) = match filter { |
| 52 | + Filter::DestPort(port) => ("--dport", port.to_string()), |
| 53 | + Filter::SourcePort(port) => ("--sport", port.to_string()), |
| 54 | + }; |
| 55 | + run_command( |
| 56 | + "iptables", |
| 57 | + &[ |
| 58 | + "-t", |
| 59 | + "mangle", |
| 60 | + if action == Action::Add { "-I" } else { "-D" }, |
| 61 | + "POSTROUTING", |
| 62 | + "-p", |
| 63 | + "tcp", |
| 64 | + filter, |
| 65 | + &value, |
| 66 | + "--tcp-flags", |
| 67 | + "RST", |
| 68 | + "RST", |
| 69 | + "-j", |
| 70 | + "DROP", |
| 71 | + ], |
| 72 | + ) |
| 73 | + .with_context(|| "iptables command failed")?; |
| 74 | + Ok(()) |
| 75 | +} |
| 76 | + |
| 77 | +fn run_command(program: &str, args: &[&str]) -> anyhow::Result<String> { |
| 78 | + let output = Command::new(program) |
| 79 | + .args(args) |
| 80 | + .output() |
| 81 | + .with_context(|| format!("couldn't spawn '{program}' program"))?; |
| 82 | + let stdout = String::from_utf8(output.stdout)?; |
| 83 | + if !output.status.success() { |
| 84 | + let stderr = String::from_utf8(output.stderr)?; |
| 85 | + bail!("{stdout}\n{stderr}") |
| 86 | + } |
| 87 | + Ok(stdout) |
| 88 | +} |
0 commit comments