-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearch.py
More file actions
224 lines (191 loc) · 7.85 KB
/
search.py
File metadata and controls
224 lines (191 loc) · 7.85 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
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
"""
search.py - Real-time search & filter engine for NetSpy
Supported filter syntax (can be combined with spaces):
tcp / udp / icmp / arp / dns / http — protocol
ip:192.168.1.1 — match src or dst IP (partial ok)
src:10.0.0.1 — source IP
dst:8.8.8.8 — destination IP
port:443 — src or dst port
sport:1234 — source port
dport:80 — destination port
flag:SYN / flag:RST / flag:ACK — TCP flag
len:>1000 / len:<100 / len:=64 — packet length
info:google — search in info/payload text
192.168.1.1 — bare IP: match src or dst (partial)
443 — bare number: match any port
anything — match against any field (fuzzy)
"""
import re
class SearchFilter:
"""
Parses a search query string and tests packets against it.
All tokens must match (implicit AND).
"""
PROTOCOLS = {"tcp", "udp", "icmp", "arp", "dns", "http", "https",
"ssh", "ftp", "smtp", "rdp", "ntp", "dhcp", "smb",
"ipv6", "other"}
def __init__(self, query: str = ""):
self.raw = query.strip()
self.tokens = self._parse(self.raw)
self.active = bool(self.raw)
# Pre-compiled for highlight
self._highlight_terms = self._extract_highlight_terms()
def _parse(self, query: str):
"""Return list of (type, value) matcher tuples."""
tokens = []
parts = query.split()
for part in parts:
part_lower = part.lower()
# Protocol shorthand
if part_lower in self.PROTOCOLS:
tokens.append(("proto", part_lower))
continue
# Keyed filters
if ":" in part:
key, _, val = part.partition(":")
key = key.lower()
val = val.strip()
if key == "ip":
tokens.append(("ip_any", val))
elif key == "src":
tokens.append(("src_ip", val))
elif key == "dst":
tokens.append(("dst_ip", val))
elif key == "port":
tokens.append(("port_any", val))
elif key in ("sport", "sp"):
tokens.append(("src_port", val))
elif key in ("dport", "dp"):
tokens.append(("dst_port", val))
elif key == "flag":
tokens.append(("flag", val.upper()))
elif key == "len":
tokens.append(("len", val))
elif key == "info":
tokens.append(("info", val.lower()))
elif key == "proto":
tokens.append(("proto", val.lower()))
else:
# Unknown key → fuzzy
tokens.append(("fuzzy", part.lower()))
continue
# Bare number → port
if part.isdigit():
tokens.append(("port_any", part))
continue
# Bare IP-like
if re.match(r"^\d{1,3}(\.\d{1,3}){0,3}$", part):
tokens.append(("ip_any", part))
continue
# Fallback fuzzy
tokens.append(("fuzzy", part.lower()))
return tokens
def _extract_highlight_terms(self):
"""Pull out plain text terms for UI highlighting."""
terms = []
for ttype, val in self.tokens:
if ttype in ("fuzzy", "info", "ip_any", "src_ip", "dst_ip"):
terms.append(val.lower())
elif ttype in ("port_any", "src_port", "dst_port"):
terms.append(val)
return terms
def _match_len(self, pkt_len: int, expr: str) -> bool:
"""Match len:>1000 / len:<100 / len:=64 / len:1000"""
try:
if expr.startswith(">"):
return pkt_len > int(expr[1:])
elif expr.startswith("<"):
return pkt_len < int(expr[1:])
elif expr.startswith("="):
return pkt_len == int(expr[1:])
else:
return pkt_len == int(expr)
except ValueError:
return False
def matches(self, pkt: dict) -> bool:
"""Return True if packet matches ALL tokens."""
if not self.tokens:
return True
proto = pkt.get("proto", "").lower()
src_ip = pkt.get("src_ip", "")
dst_ip = pkt.get("dst_ip", "")
src_port = str(pkt.get("src_port", "") or "")
dst_port = str(pkt.get("dst_port", "") or "")
flags = [f.upper() for f in pkt.get("flags", [])]
info = pkt.get("info", "").lower()
pkt_len = pkt.get("length", 0)
# Build a single "all fields" string for fuzzy matching
all_fields = " ".join(filter(None, [
proto, src_ip, dst_ip, src_port, dst_port, info,
",".join(flags)
])).lower()
for ttype, val in self.tokens:
if ttype == "proto":
if val not in proto:
return False
elif ttype == "ip_any":
if val not in src_ip and val not in dst_ip:
return False
elif ttype == "src_ip":
if val not in src_ip:
return False
elif ttype == "dst_ip":
if val not in dst_ip:
return False
elif ttype == "port_any":
if val != src_port and val != dst_port:
return False
elif ttype == "src_port":
if val != src_port:
return False
elif ttype == "dst_port":
if val != dst_port:
return False
elif ttype == "flag":
if val not in flags:
return False
elif ttype == "len":
if not self._match_len(pkt_len, val):
return False
elif ttype == "info":
if val not in info:
return False
elif ttype == "fuzzy":
if val not in all_fields:
return False
return True
def filter_packets(self, packets: list) -> list:
"""Return filtered list of packets."""
if not self.active:
return packets
return [p for p in packets if self.matches(p)]
@property
def summary(self) -> str:
"""Human-readable summary of active filters."""
if not self.tokens:
return ""
parts = []
for ttype, val in self.tokens:
if ttype == "proto":
parts.append(f"proto={val.upper()}")
elif ttype == "ip_any":
parts.append(f"ip~{val}")
elif ttype == "src_ip":
parts.append(f"src~{val}")
elif ttype == "dst_ip":
parts.append(f"dst~{val}")
elif ttype == "port_any":
parts.append(f"port={val}")
elif ttype == "src_port":
parts.append(f"sport={val}")
elif ttype == "dst_port":
parts.append(f"dport={val}")
elif ttype == "flag":
parts.append(f"flag={val}")
elif ttype == "len":
parts.append(f"len{val}")
elif ttype == "info":
parts.append(f'info~"{val}"')
elif ttype == "fuzzy":
parts.append(f'"{val}"')
return " ".join(parts)