-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfilter_builder.c
More file actions
97 lines (81 loc) · 2.55 KB
/
filter_builder.c
File metadata and controls
97 lines (81 loc) · 2.55 KB
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
#include "filter_builder.h"
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <arpa/inet.h>
bool parse_mac_address(const char *mac_str, uint8_t *mac_out)
{
unsigned int bytes[6];
int n;
if (!mac_str || !mac_out) {
return false;
}
n = sscanf(mac_str, "%x:%x:%x:%x:%x:%x",
&bytes[0], &bytes[1], &bytes[2],
&bytes[3], &bytes[4], &bytes[5]);
if (n != 6) {
return false;
}
for (int i = 0; i < 6; i++) {
if (bytes[i] > 255) {
return false;
}
mac_out[i] = (uint8_t)bytes[i];
}
return true;
}
bool validate_ip_address(const char *ip_str)
{
struct in_addr addr;
if (!ip_str) {
return false;
}
return inet_pton(AF_INET, ip_str, &addr) == 1;
}
int build_and_apply_filter(pcap_t *handle, const char *mac_address,
const char *ip_address, char *errbuf)
{
char filter_expr[256];
struct bpf_program fp;
uint8_t mac[6];
if (mac_address) {
if (!parse_mac_address(mac_address, mac)) {
snprintf(errbuf, PCAP_ERRBUF_SIZE,
"Invalid MAC address format: %s", mac_address);
return -1;
}
/* Filter for traffic to or from this MAC */
snprintf(filter_expr, sizeof(filter_expr),
"ether src %02x:%02x:%02x:%02x:%02x:%02x or "
"ether dst %02x:%02x:%02x:%02x:%02x:%02x",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5],
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
} else if (ip_address) {
if (!validate_ip_address(ip_address)) {
snprintf(errbuf, PCAP_ERRBUF_SIZE,
"Invalid IP address format: %s", ip_address);
return -1;
}
/* Filter for traffic to or from this IP */
snprintf(filter_expr, sizeof(filter_expr), "host %s", ip_address);
} else {
snprintf(errbuf, PCAP_ERRBUF_SIZE,
"No MAC or IP address specified");
return -1;
}
/* Compile the filter */
if (pcap_compile(handle, &fp, filter_expr, 1, PCAP_NETMASK_UNKNOWN) == -1) {
snprintf(errbuf, PCAP_ERRBUF_SIZE,
"Filter compile failed: %s", pcap_geterr(handle));
return -1;
}
/* Apply the filter */
if (pcap_setfilter(handle, &fp) == -1) {
pcap_freecode(&fp);
snprintf(errbuf, PCAP_ERRBUF_SIZE,
"Filter apply failed: %s", pcap_geterr(handle));
return -1;
}
pcap_freecode(&fp);
return 0;
}