zond-engine 0.10.0

A lightweight, fast, and highly concurrent networking backend for packet crafting, protocol fingerprinting, and host discovery.
Documentation
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
// Copyright (c) 2026 Erik Lening (hollowpointer) and Contributors
//
// This file is part of Zond Engine, licensed under the GNU Affero General
// Public License, version 3 or later. See the LICENSE file for details, or
// <https://www.gnu.org/licenses/agpl-3.0.html>.
//
// SPDX-License-Identifier: AGPL-3.0-or-later

use crate::core::models::localhost::{FirewallStatus, IpServiceGroup, Service};
use anyhow;
use pnet::datalink::NetworkInterface;
use std::collections::{HashMap, HashSet};
use std::net::IpAddr;
#[cfg(any(target_os = "linux", target_os = "windows"))]
use std::process::Command;

/// Intermediate representation of a socket entry.
#[derive(Debug)]
struct SocketInfo {
    ip: IpAddr,
    port: u16,
    protocol: String, // "tcp" or "udp"
    process_name: String,
}

pub fn get_local_services() -> anyhow::Result<Vec<IpServiceGroup>> {
    let entries = retrieve_sockets()?;
    Ok(aggregate_services(entries))
}

#[cfg(not(target_os = "windows"))]
fn retrieve_sockets() -> anyhow::Result<Vec<SocketInfo>> {
    let raw_data = retrieve_raw_socket_data()?;
    Ok(parse_socket_data(&raw_data))
}

#[cfg(target_os = "windows")]
fn retrieve_sockets() -> anyhow::Result<Vec<SocketInfo>> {
    windows_impl::retrieve_native_sockets()
}

#[cfg(not(target_os = "windows"))]
fn retrieve_raw_socket_data() -> anyhow::Result<String> {
    use std::process::Command;
    let output = Command::new("ss").arg("-lntuH").arg("-p").output()?;

    if output.status.success() {
        Ok(String::from_utf8_lossy(&output.stdout).to_string())
    } else {
        Ok(String::new())
    }
}

#[cfg(not(target_os = "windows"))]
fn parse_socket_data(stdout: &str) -> Vec<SocketInfo> {
    stdout.lines().filter_map(parse_socket_line).collect()
}

#[cfg(not(target_os = "windows"))]
fn parse_socket_line(line: &str) -> Option<SocketInfo> {
    let parts: Vec<&str> = line.split_whitespace().collect();
    if parts.len() < 5 {
        return None;
    }

    let netid = parts[0];
    let state = parts[1];

    // Filter relevant sockets: TCP sets to LISTEN, UDP is usually UNCONN (but listed due to -l)
    if netid == "tcp" && state != "LISTEN" {
        return None;
    }
    if netid != "tcp" && netid != "udp" {
        return None;
    }

    let local_addr_port = parts[4];
    let (ip, port) = parse_address_port(local_addr_port)?;

    // Process info is usually in the last column
    let process_name = if let Some(users_field) = parts.last() {
        parse_process_name(users_field).unwrap_or_else(|| "Unknown".to_string())
    } else {
        "Unknown".to_string()
    };

    Some(SocketInfo {
        ip,
        port,
        protocol: netid.to_string(),
        process_name,
    })
}

#[cfg(not(target_os = "windows"))]
fn parse_address_port(addr_port: &str) -> Option<(IpAddr, u16)> {
    use std::net::Ipv4Addr;
    use std::str::FromStr;
    let idx = addr_port.rfind(':')?;
    let ip_str = &addr_port[..idx];
    let port_str = &addr_port[idx + 1..];

    let clean_ip_str = ip_str
        .trim_start_matches('[')
        .trim_end_matches(']')
        .trim_start_matches('*'); // ss sometimes uses * for 0.0.0.0

    let ip = if clean_ip_str.is_empty() || clean_ip_str == "*" {
        IpAddr::V4(Ipv4Addr::UNSPECIFIED)
    } else if let Ok(addr) = IpAddr::from_str(clean_ip_str) {
        addr
    } else {
        // Handle interface suffix (e.g., fe80::1%eth0)
        let pct_idx = clean_ip_str.find('%')?;
        IpAddr::from_str(&clean_ip_str[..pct_idx]).ok()?
    };

    let port = port_str.parse::<u16>().ok()?;
    if port == 0 {
        return None;
    }

    Some((ip, port))
}

#[cfg(not(target_os = "windows"))]
fn parse_process_name(users_field: &str) -> Option<String> {
    if !users_field.starts_with("users:((") {
        return None;
    }

    // Format: users:(("name",...))
    let start_quote = users_field.find('"')?;
    let remainder = &users_field[start_quote + 1..];
    let end_quote = remainder.find('"')?;

    Some(remainder[..end_quote].to_string())
}

fn aggregate_services(entries: Vec<SocketInfo>) -> Vec<IpServiceGroup> {
    struct ServiceBuilder {
        tcp_ports: HashMap<String, HashSet<u16>>,
        udp_ports: HashMap<String, HashSet<u16>>,
    }

    let mut ip_groups: HashMap<IpAddr, ServiceBuilder> = HashMap::new();

    for entry in entries {
        let builder = ip_groups.entry(entry.ip).or_insert(ServiceBuilder {
            tcp_ports: HashMap::new(),
            udp_ports: HashMap::new(),
        });

        let target_map = if entry.protocol == "tcp" {
            &mut builder.tcp_ports
        } else {
            &mut builder.udp_ports
        };

        target_map
            .entry(entry.process_name)
            .or_default()
            .insert(entry.port);
    }

    let mut result = Vec::new();
    for (ip, builder) in ip_groups {
        let mut tcp_services = convert_to_services(ip, builder.tcp_ports);
        let mut udp_services = convert_to_services(ip, builder.udp_ports);

        tcp_services.sort_by(|a, b| a.name.cmp(&b.name));
        udp_services.sort_by(|a, b| a.name.cmp(&b.name));

        result.push(IpServiceGroup::new(ip, tcp_services, udp_services));
    }

    result.sort_by_key(|g| g.ip_addr);
    result
}

fn convert_to_services(ip: IpAddr, port_map: HashMap<String, HashSet<u16>>) -> Vec<Service> {
    port_map
        .into_iter()
        .map(|(name, ports)| Service::new(name, ip, ports))
        .collect()
}

pub fn get_firewall_status() -> anyhow::Result<FirewallStatus> {
    #[cfg(target_os = "linux")]
    {
        let ufw_active = Command::new("ufw").arg("status").output().is_ok();
        let firewalld_active = Command::new("firewall-cmd").arg("--state").output().is_ok();

        if ufw_active || firewalld_active {
            Ok(FirewallStatus::Active)
        } else {
            Ok(FirewallStatus::NotDetected)
        }
    }
    #[cfg(target_os = "windows")]
    {
        let output = Command::new("netsh")
            .args(["advfirewall", "show", "allprofiles", "state"])
            .output()?;

        if output.status.success() {
            let stdout = String::from_utf8_lossy(&output.stdout);
            if stdout.to_lowercase().contains("on") {
                return Ok(FirewallStatus::Active);
            }
        }
        Ok(FirewallStatus::NotDetected)
    }
    #[cfg(not(any(target_os = "linux", target_os = "windows")))]
    {
        Ok(FirewallStatus::NotDetected)
    }
}

#[cfg(target_os = "windows")]
mod windows_impl {
    use super::*;
    use std::net::Ipv4Addr;
    use windows_sys::Win32::Foundation::{CloseHandle, FALSE, MAX_PATH, NO_ERROR};
    use windows_sys::Win32::NetworkManagement::IpHelper::{
        GetExtendedTcpTable, GetExtendedUdpTable, MIB_TCP_STATE_LISTEN,
        TCP_TABLE_OWNER_PID_LISTENER, UDP_TABLE_OWNER_PID,
    };
    use windows_sys::Win32::Networking::WinSock::AF_INET;
    use windows_sys::Win32::System::Threading::{
        OpenProcess, PROCESS_NAME_WIN32, PROCESS_QUERY_LIMITED_INFORMATION,
        QueryFullProcessImageNameW,
    };

    #[repr(C)]
    #[allow(non_snake_case)]
    struct MIB_TCPROW_OWNER_PID {
        dwState: u32,
        dwLocalAddr: u32,
        dwLocalPort: u32,
        dwRemoteAddr: u32,
        dwRemotePort: u32,
        dwOwningPid: u32,
    }

    #[repr(C)]
    #[allow(non_snake_case)]
    struct MIB_TCPTABLE_OWNER_PID_INTERNAL {
        dwNumEntries: u32,
        table: [MIB_TCPROW_OWNER_PID; 1],
    }

    #[repr(C)]
    #[allow(non_snake_case)]
    struct MIB_UDPROW_OWNER_PID {
        dwLocalAddr: u32,
        dwLocalPort: u32,
        dwOwningPid: u32,
    }

    #[repr(C)]
    #[allow(non_snake_case)]
    struct MIB_UDPTABLE_OWNER_PID_INTERNAL {
        dwNumEntries: u32,
        table: [MIB_UDPROW_OWNER_PID; 1],
    }

    /// Resolves a process ID to the file name of its executable, or `"Unknown"`
    /// when the process cannot be opened. Protected and already-exited processes
    /// routinely deny access, so failure here is expected rather than fatal.
    fn image_name(pid: u32) -> String {
        const UNKNOWN: &str = "Unknown";

        // SAFETY: `OpenProcess` validates the pid itself and reports failure by
        // returning null, which is checked before the handle is used.
        let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid) };
        if handle.is_null() {
            return UNKNOWN.to_string();
        }

        let mut buf = [0u16; MAX_PATH as usize];
        let mut len = buf.len() as u32;
        // SAFETY: `handle` is live and `len` states `buf`'s true capacity; the call
        // writes at most `len` code units and updates `len` to the count written.
        let ok = unsafe {
            QueryFullProcessImageNameW(handle, PROCESS_NAME_WIN32, buf.as_mut_ptr(), &mut len)
        } != 0;
        // SAFETY: `handle` came from `OpenProcess` above and is not used again.
        unsafe { CloseHandle(handle) };

        if !ok {
            return UNKNOWN.to_string();
        }

        let path = String::from_utf16_lossy(&buf[..len as usize]);
        path.rsplit('\\')
            .next()
            .filter(|name| !name.is_empty())
            .unwrap_or(UNKNOWN)
            .to_string()
    }

    pub fn retrieve_native_sockets() -> anyhow::Result<Vec<SocketInfo>> {
        let mut entries = Vec::new();
        // A process listening on many ports appears once per socket, so the name
        // is resolved at most once per distinct owner.
        let mut names: HashMap<u32, String> = HashMap::new();

        // 1. TCP IPv4
        let tcp_table = get_tcp_ipv4_table()?;
        for i in 0..tcp_table.dwNumEntries as usize {
            let row = unsafe { &*tcp_table.table.as_ptr().add(i) };
            if row.dwState == MIB_TCP_STATE_LISTEN as u32 {
                let pid = row.dwOwningPid;
                let process_name = names.entry(pid).or_insert_with(|| image_name(pid)).clone();

                entries.push(SocketInfo {
                    ip: IpAddr::V4(Ipv4Addr::from(u32::from_be(row.dwLocalAddr))),
                    port: u16::from_be(row.dwLocalPort as u16),
                    protocol: "tcp".to_string(),
                    process_name,
                });
            }
        }

        // 2. UDP IPv4
        let udp_table = get_udp_ipv4_table()?;
        for i in 0..udp_table.dwNumEntries as usize {
            let row = unsafe { &*udp_table.table.as_ptr().add(i) };
            let pid = row.dwOwningPid;
            let process_name = names.entry(pid).or_insert_with(|| image_name(pid)).clone();

            entries.push(SocketInfo {
                ip: IpAddr::V4(Ipv4Addr::from(u32::from_be(row.dwLocalAddr))),
                port: u16::from_be(row.dwLocalPort as u16),
                protocol: "udp".to_string(),
                process_name,
            });
        }

        Ok(entries)
    }

    fn get_tcp_ipv4_table() -> anyhow::Result<Box<MIB_TCPTABLE_OWNER_PID_INTERNAL>> {
        let mut size = 0;
        unsafe {
            GetExtendedTcpTable(
                std::ptr::null_mut(),
                &mut size,
                1,
                AF_INET as u32,
                TCP_TABLE_OWNER_PID_LISTENER,
                0,
            );
        }

        let mut buffer = vec![0u8; size as usize];
        let ret = unsafe {
            GetExtendedTcpTable(
                buffer.as_mut_ptr() as *mut _,
                &mut size,
                1,
                AF_INET as u32,
                TCP_TABLE_OWNER_PID_LISTENER,
                0,
            )
        };

        if ret == NO_ERROR {
            let ptr =
                Box::into_raw(buffer.into_boxed_slice()) as *mut MIB_TCPTABLE_OWNER_PID_INTERNAL;
            Ok(unsafe { Box::from_raw(ptr) })
        } else {
            anyhow::bail!("Failed to get TCP table: {}", ret)
        }
    }

    fn get_udp_ipv4_table() -> anyhow::Result<Box<MIB_UDPTABLE_OWNER_PID_INTERNAL>> {
        let mut size = 0;
        unsafe {
            GetExtendedUdpTable(
                std::ptr::null_mut(),
                &mut size,
                1,
                AF_INET as u32,
                UDP_TABLE_OWNER_PID,
                0,
            );
        }

        let mut buffer = vec![0u8; size as usize];
        let ret = unsafe {
            GetExtendedUdpTable(
                buffer.as_mut_ptr() as *mut _,
                &mut size,
                1,
                AF_INET as u32,
                UDP_TABLE_OWNER_PID,
                0,
            )
        };

        if ret == NO_ERROR {
            let ptr =
                Box::into_raw(buffer.into_boxed_slice()) as *mut MIB_UDPTABLE_OWNER_PID_INTERNAL;
            Ok(unsafe { Box::from_raw(ptr) })
        } else {
            anyhow::bail!("Failed to get UDP table: {}", ret)
        }
    }
}

pub fn get_network_interfaces() -> anyhow::Result<Vec<NetworkInterface>> {
    crate::system::interface::get_prioritized_interfaces(10)
}