summaryrefslogtreecommitdiff
path: root/src/sniffing/headers.rs
blob: 1db0da6171c4828239df283a7806fc5473f0236a (plain)
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
use std::fmt;
use tun::Error;

// Here we will recieve bytes and try to get their destanation & apply Rules for them.
use crate::config::Config;

#[derive(Debug, PartialEq)]
pub enum Protocol {
    TCP,
    UDP,
    Unsupported(u8),
}
type SourceV4Ip = Ipv4;
type SourceV6Ip = Ipv6;
#[derive(PartialEq, Debug)]
pub enum IpVersion {
    V4,
    V6,
}
type Ipv4 = [u8; 4];
type Ipv6 = [u16; 8];
type Port = u16;
#[derive(Debug, PartialEq)]
pub enum PacketInfo {
    // <https://www.geeksforgeeks.org/computer-networks/what-is-ipv4/>
    V4 {
        src_ip: Ipv4,
        src_port: Port,
        dst_ip: Ipv4,
        dst_port: Port,
        protocol: Protocol,
        dns: bool,
    },
    // <https://www.geeksforgeeks.org/computer-networks/internet-protocol-version-6-ipv6-header/>
    V6 {
        src_ip: Ipv6,
        src_port: Port,
        dst_ip: Ipv6,
        dst_port: Port,
        protocol: Protocol,
        dns: bool,
    },
}

impl fmt::Display for PacketInfo {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.version() == &IpVersion::V4 {
            let src_ip = self.src_ipv4_ip().unwrap();
            let dst_ip = self.dst_ipv4_ip().unwrap();
            write!(
                f,
                "{}.{}.{}.{}:{} -> {}.{}.{}.{}:{} {:?} is dns? {:?}",
                src_ip[0],
                src_ip[1],
                src_ip[2],
                src_ip[3],
                self.src_port(),
                dst_ip[0],
                dst_ip[1],
                dst_ip[2],
                dst_ip[3],
                self.dst_port(),
                self.protocol(),
                self.dns()
            )
        } else {
            let src_ip = self.src_ipv6_ip().unwrap();
            let dst_ip = self.dst_ipv6_ip().unwrap();
            // y:y:y:y:y:y:y:y = 8 hexademical; y = segment, pair of 2 u8 big endian
            write!(
                f,
                "{:x}:{:x}:{:x}:{:x}:{:x}:{:x}:{:x}:{:x} port:{} -> {:x}:{:x}:{:x}:{:x}:{:x}:{:x}:{:x}:{:x} port:{} {:?} is dns? {:?}",
                src_ip[0],
                src_ip[1],
                src_ip[2],
                src_ip[3],
                src_ip[4],
                src_ip[5],
                src_ip[6],
                src_ip[7],
                self.src_port(),
                dst_ip[0],
                dst_ip[1],
                dst_ip[2],
                dst_ip[3],
                dst_ip[4],
                dst_ip[5],
                dst_ip[6],
                dst_ip[7],
                self.dst_port(),
                self.protocol(),
                self.dns()
            )
        }
    }
}

impl PacketInfo {
    pub fn dns(&self) -> &bool {
        match self {
            PacketInfo::V4 { dns, .. } => dns,
            PacketInfo::V6 { dns, .. } => dns,
        }
    }
    pub fn src_ipv6_ip(&self) -> Option<&SourceV6Ip> {
        match self {
            PacketInfo::V6 { src_ip, .. } => Some(src_ip),
            _ => None,
        }
    }
    pub fn dst_ipv6_ip(&self) -> Option<&SourceV6Ip> {
        match self {
            PacketInfo::V6 { dst_ip, .. } => Some(dst_ip),
            _ => None,
        }
    }
    pub fn src_ipv4_ip(&self) -> Option<&SourceV4Ip> {
        match self {
            PacketInfo::V4 { src_ip, .. } => Some(src_ip),
            _ => None,
        }
    }
    pub fn dst_ipv4_ip(&self) -> Option<&SourceV4Ip> {
        match self {
            PacketInfo::V4 { dst_ip, .. } => Some(dst_ip),
            _ => None,
        }
    }
    pub fn src_port(&self) -> &Port {
        match self {
            PacketInfo::V4 { src_port, .. } => src_port,
            PacketInfo::V6 { src_port, .. } => src_port,
        }
    }
    pub fn dst_port(&self) -> &Port {
        match self {
            PacketInfo::V4 { dst_port, .. } => dst_port,
            PacketInfo::V6 { dst_port, .. } => dst_port,
        }
    }
    pub fn version(&self) -> &IpVersion {
        match self {
            PacketInfo::V4 { .. } => &IpVersion::V4,
            PacketInfo::V6 { .. } => &IpVersion::V6,
        }
    }
    pub fn protocol(&self) -> &Protocol {
        match self {
            PacketInfo::V4 { protocol, .. } => protocol,
            PacketInfo::V6 { protocol, .. } => protocol,
        }
    }
}

// TODO: move these to some appropriate file for code readability.
type GenericError = Box<dyn std::error::Error + Send + Sync + 'static>;
type SniffedPacket = Result<PacketInfo, Box<dyn std::error::Error + Send + Sync + 'static>>;
type Packet = [u8];

pub fn sniff_raw_packets(packet: &Packet) -> SniffedPacket {
    let ver = packet[0] >> 4;
    match ver {
        4 => {
            // Internet Header Length (IHL).
            let ihl = (packet[0] & 0x0F) as usize * 4;
            let dst_port = Port::from_be_bytes([packet[ihl + 2], packet[ihl + 3]]);
            let dns;
            if dst_port == 53 {
                dns = true;
            } else {
                dns = false;
            };
            let v4 = PacketInfo::V4 {
                src_ip: <Ipv4>::try_from(&packet[12..16])?,
                src_port: Port::from_be_bytes([packet[ihl], packet[ihl + 1]]),
                dst_ip: <Ipv4>::try_from(&packet[16..20])?,
                dst_port,
                protocol: match packet[9] {
                    6 => Protocol::TCP,
                    17 => Protocol::UDP,
                    p => Protocol::Unsupported(p),
                },
                dns,
            };
            if !matches!(v4.protocol(), Protocol::Unsupported(_)) {
                println!("{v4}");
            } else {
                // TODO: make --debug option which will include this diagnostic, for general use this
                // should be off
                // println!("oppsie unsupported protocol: {:?}", v4.protocol());
            }
            Ok(v4)
        }
        6 => {
            // y:y:y:y:y:y:y:y hexademical; y = segment, pair of 2 u8 in big endian
            let src_ip = std::array::from_fn(|i| {
                u16::from_be_bytes([packet[8 + i * 2], packet[8 + i * 2 + 1]])
            });
            let dst_ip = std::array::from_fn(|i| {
                u16::from_be_bytes([packet[24 + i * 2], packet[24 + i * 2 + 1]])
            });

            let dst_port = Port::from_be_bytes([packet[42], packet[43]]);
            let dns;
            if dst_port == 53 {
                dns = true;
            } else {
                dns = false;
            };
            let v6 = PacketInfo::V6 {
                src_ip,
                src_port: Port::from_be_bytes([packet[40], packet[41]]),
                dst_ip,
                dst_port,
                protocol: match packet[6] {
                    6 => Protocol::TCP,
                    17 => Protocol::UDP,
                    p => Protocol::Unsupported(p),
                },
                dns,
            };
            if !matches!(v6.protocol(), Protocol::Unsupported(_)) {
                println!("{v6}");
            } else {
                // TODO: make --debug option which will include this diagnostic, for general use this
                // should be off
                // println!("oppsie unsupported protocol: {:?}", v6.protocol());
            }
            Ok(v6)
        }
        ver => Err(format!("unsuppiorted ver: {ver}").into()),
    }
}

pub fn apply_rules(config: Config, pinfo: PacketInfo) {
    todo!()
}