aboutsummaryrefslogtreecommitdiff
path: root/src/fw.rs
blob: 955425ada30c9f22945fb10af6bdb13b786c2f48 (plain) (blame)
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
use iptables;
use regex::Regex;
use std::collections::HashSet;
use std::io;
use crate::messages;

#[derive(Debug)]
pub struct FirewallError(String);

impl From<iptables::error::IPTError> for FirewallError {
    fn from(error: iptables::error::IPTError) -> Self {
        FirewallError(error.to_string())
    }
}

pub fn setup(ipt: &iptables::IPTables) -> Result<(), FirewallError> {
    
    ipt.new_chain("filter", "DIPLONAT")?;
    ipt.insert("filter", "INPUT", "-j DIPLONAT", 1)?;

    Ok(())
}

pub fn open_ports(ipt: &iptables::IPTables, ports: messages::PublicExposedPorts) -> Result<(), FirewallError> {

    for p in ports.tcp_ports {
        ipt.append("filter", "DIPLONAT", &format!("-p tcp --dport {} -j ACCEPT", p))?;
    }

    for p in ports.udp_ports {
        ipt.append("filter", "DIPLONAT", &format!("-p udp --dport {} -j ACCEPT", p))?;
    }

    Ok(())
}

pub fn get_opened_ports(ipt: &iptables::IPTables) -> Result<messages::PublicExposedPorts, FirewallError> {
    let mut ports = messages::PublicExposedPorts {
        tcp_ports: HashSet::new(),
        udp_ports: HashSet::new()
    };

    let list = ipt.list("filter", "DIPLONAT")?;
    let re = Regex::new(r"\-A.*? \-p (\w+).*\-\-dport (\d+).*?\-j ACCEPT").unwrap();
    for i in list {
        let caps = re.captures(&i);
        match caps {
            Some(c) => {
                let raw_proto = c.get(1).unwrap();
                let raw_port = c.get(2).unwrap();

                let proto = String::from(raw_proto.as_str());
                let number = String::from(raw_port.as_str()).parse::<u16>().unwrap();

                if proto == "tcp" {
                    ports.tcp_ports.insert(number);
                } else {
                    ports.udp_ports.insert(number);
                }

            },
            _ => {}
        }
    }

    Ok(ports)
}

pub fn cleanup(ipt: &iptables::IPTables) -> Result<(), FirewallError> {
    ipt.flush_chain("filter", "DIPLONAT")?;
    ipt.delete("filter", "INPUT", "-j DIPLONAT")?;
    ipt.delete_chain("filter", "DIPLONAT")?;
    Ok(())
}

/*
fn main() {
    let ipt = iptables::new(false).unwrap();
    setup(&ipt);

    let mut test: HashSet<Port> = HashSet::new();
    test.insert(Port { proto: String::from("tcp"), number: 443 });
    let a = get_opened_ports(&ipt);
    let l = test.difference(&a).collect::<Vec<&Port>>();
    println!("{:?}", l);
}
*/