partition_sim/commands/
ip.rs

1use std::net::IpAddr;
2
3use super::Commands;
4
5/// All Iptables commands require root privileges
6/// so we'll run them with `sudo` assuming that the user
7/// has sudo access. We'll fail otherwise.
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub enum IpTablesCommands {
10    /// Flush all rules across all the peers so that all nodes
11    /// can communicate with each other.
12    Restore,
13    /// Remove all inbound rules in the target node for a given source IP.
14    RestoreFrom { source_ip: IpAddr },
15    /// Add a rule to drop all inbound traffic into the target node originating from a given source IP.
16    DropFrom { source_ip: IpAddr },
17    /// List all inbound rules in the target node.
18    Get,
19}
20
21impl From<IpTablesCommands> for Commands {
22    fn from(command: IpTablesCommands) -> Self {
23        Self::IpTables(command)
24    }
25}
26
27impl super::Command for IpTablesCommands {
28    fn build<'session>(&self, session: &'session openssh::Session) -> openssh::Command<'session> {
29        match self {
30            Self::Restore => {
31                let mut command = session.raw_command("sudo");
32                command.arg("/usr/sbin/iptables");
33                command.arg("-F");
34                command
35            }
36            Self::RestoreFrom { source_ip } => {
37                let mut command = session.raw_command("sudo");
38                command.arg("/usr/sbin/iptables");
39                command.arg("-D");
40                command.arg("INPUT");
41                command.arg("-s");
42                command.arg(source_ip.to_string());
43                command.arg("-j");
44                command.arg("DROP");
45                command
46            }
47            Self::DropFrom { source_ip } => {
48                let mut command = session.raw_command("sudo");
49                command.arg("/usr/sbin/iptables");
50                command.arg("-A");
51                command.arg("INPUT");
52                command.arg("-s");
53                command.arg(source_ip.to_string());
54                command.arg("-j");
55                command.arg("DROP");
56                command
57            }
58            Self::Get => {
59                let mut command = session.raw_command("sudo");
60                command.arg("/usr/sbin/iptables");
61                command.arg("-L");
62                command.arg("INPUT");
63                command.arg("-n");
64                command
65            }
66        }
67    }
68}