-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpacket_capture.py
More file actions
353 lines (307 loc) · 13.3 KB
/
packet_capture.py
File metadata and controls
353 lines (307 loc) · 13.3 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
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
#!/usr/bin/env python3
"""
DeepNet Packet Capture Engine
Handles packet sniffing and analysis
"""
import threading
import time
import queue
from datetime import datetime
from typing import Callable, Optional, List, Dict, Any
import json
try:
from scapy.all import sniff, get_if_list, conf # get_if_list imported here
from scapy.layers.inet import IP, TCP, UDP, ICMP
from scapy.layers.inet6 import IPv6
from scapy.layers.l2 import Ether, ARP
from scapy.layers.dns import DNS
except ImportError:
print("Error: Scapy not found. Install with: pip install scapy")
exit(1)
from utils import format_bytes, get_protocol_name, extract_payload
class PacketCapture:
"""Main packet capture class"""
def __init__(self, interface: Optional[str] = None,
filter_str: Optional[str] = None,
callback: Optional[Callable] = None):
self.interface = interface or self._get_default_interface()
self.filter_str = filter_str
self.callback = callback
self.running = False
self.packets = []
self.packet_queue = queue.Queue()
self.packet_count = 0
self.capture_thread = None
self.start_time = None
self.statistics = {
'total_packets': 0,
'protocols': {},
'data_transferred': 0,
'unique_ips': set(),
'packet_sizes': [],
'most_active_src': {}, # Added for analysis
'most_active_dst': {}, # Added for analysis
'avg_packet_size': 0.0,
'capture_duration': '0s'
}
def _get_default_interface(self) -> str:
"""Get the default network interface"""
try:
interfaces = get_if_list()
# Filter out loopback and inactive interfaces
active_interfaces = [iface for iface in interfaces
if not iface.startswith('lo') and
iface not in ['any', 'bluetooth-monitor']]
if active_interfaces:
return active_interfaces[0]
else:
return interfaces[0] if interfaces else 'any'
except Exception:
return 'any'
def get_available_interfaces(self) -> List[str]:
"""Get list of available network interfaces"""
try:
return get_if_list()
except Exception:
return ['any']
def start_capture(self, interface: str, filter_str: str, count: int = 0) -> None:
"""Start packet capture in a separate thread"""
if self.running:
return
self.interface = interface # Use provided interface
self.filter_str = filter_str # Use provided filter
self.running = True
self.start_time = datetime.now()
self.packet_count = 0
self.packets.clear()
# Reset statistics
self.statistics = {
'total_packets': 0,
'protocols': {},
'data_transferred': 0,
'unique_ips': set(),
'packet_sizes': [],
'most_active_src': {},
'most_active_dst': {},
'avg_packet_size': 0.0,
'capture_duration': '0s'
}
self.capture_thread = threading.Thread(
target=self._capture_packets,
args=(count,),
daemon=True
)
self.capture_thread.start()
def stop_capture(self) -> None:
"""Stop packet capture"""
self.running = False
if self.capture_thread:
self.capture_thread.join(timeout=2)
def _capture_packets(self, count: int) -> None:
"""Internal method to capture packets"""
try:
sniff(
iface=self.interface,
filter=self.filter_str,
count=count if count > 0 else 0,
prn=self._process_packet,
stop_filter=lambda x: not self.running,
store=0 # Do not store packets in Scapy's internal list to save memory
)
except Exception as e:
if self.callback:
self.callback({
'type': 'error',
'message': f"Capture error: {str(e)}"
})
def _process_packet(self, packet) -> None:
"""Process each captured packet"""
if not self.running:
return
try:
packet_info = self._analyze_packet(packet)
self.packet_queue.put(packet_info)
except Exception as e:
if self.callback:
self.callback({
'type': 'error',
'message': f"Packet processing error: {str(e)}"
})
def process_queue(self):
"""Process packets from queue"""
while not self.packet_queue.empty():
packet_info = self.packet_queue.get()
# Update statistics
self._update_statistics(packet_info)
# Store packet
self.packets.append(packet_info)
self.packet_count += 1
# Call callback if provided, include statistics for GUI updates
if self.callback:
self.callback({
'type': 'packet',
'packet': packet_info,
'statistics': self.get_statistics()
})
def _analyze_packet(self, packet) -> Dict[str, Any]:
"""Analyze a single packet and extract information"""
packet_info = {
'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3],
'size': len(packet),
'protocol': 'Unknown',
'src_ip': 'N/A',
'dst_ip': 'N/A',
'src_port': 'N/A',
'dst_port': 'N/A',
'payload': '',
'flags': '',
'summary': str(packet.summary()),
'hex': bytes(packet).hex() # Add hex dump
}
# Ethernet layer
if packet.haslayer(Ether):
packet_info['src_mac'] = packet[Ether].src
packet_info['dst_mac'] = packet[Ether].dst
# IP layer
if packet.haslayer(IP):
ip_layer = packet[IP]
packet_info['src_ip'] = ip_layer.src
packet_info['dst_ip'] = ip_layer.dst
packet_info['protocol'] = get_protocol_name(ip_layer.proto)
packet_info['ttl'] = ip_layer.ttl
packet_info['length'] = ip_layer.len
# IPv6 layer
elif packet.haslayer(IPv6):
ipv6_layer = packet[IPv6]
packet_info['src_ip'] = ipv6_layer.src
packet_info['dst_ip'] = ipv6_layer.dst
packet_info['protocol'] = 'IPv6'
# TCP layer
if packet.haslayer(TCP):
tcp_layer = packet[TCP]
packet_info['src_port'] = tcp_layer.sport
packet_info['dst_port'] = tcp_layer.dport
packet_info['protocol'] = 'TCP'
packet_info['flags'] = self._get_tcp_flags(tcp_layer)
packet_info['seq'] = tcp_layer.seq
packet_info['ack'] = tcp_layer.ack
packet_info['window'] = tcp_layer.window
# UDP layer
elif packet.haslayer(UDP):
udp_layer = packet[UDP]
packet_info['src_port'] = udp_layer.sport
packet_info['dst_port'] = udp_layer.dport
packet_info['protocol'] = 'UDP'
packet_info['length'] = udp_layer.len
# ICMP layer
elif packet.haslayer(ICMP):
packet_info['protocol'] = 'ICMP'
packet_info['type'] = packet[ICMP].type
packet_info['code'] = packet[ICMP].code
# ARP layer
elif packet.haslayer(ARP):
arp_layer = packet[ARP]
packet_info['protocol'] = 'ARP'
packet_info['src_ip'] = arp_layer.psrc
packet_info['dst_ip'] = arp_layer.pdst
packet_info['hwsrc'] = arp_layer.hwsrc
packet_info['hwdst'] = arp_layer.hwdst
# DNS layer (often within UDP/TCP)
if packet.haslayer(DNS):
dns_layer = packet[DNS]
packet_info['dns_query'] = dns_layer.qd.qname.decode() if dns_layer.qd else 'N/A'
packet_info['protocol'] = 'DNS' # Override if DNS is present
# Extract payload
packet_info['payload'] = extract_payload(packet)
return packet_info
def _get_tcp_flags(self, tcp_layer) -> str:
"""Decode TCP flags"""
flags = {
'F': 'FIN', 'S': 'SYN', 'R': 'RST', 'P': 'PSH',
'A': 'ACK', 'U': 'URG', 'E': 'ECE', 'C': 'CWR'
}
return ','.join([flags[f] for f in str(tcp_layer.flags)])
def _update_statistics(self, packet_info: Dict[str, Any]) -> None:
"""Update capture statistics"""
self.statistics['total_packets'] += 1
self.statistics['data_transferred'] += packet_info['size']
self.statistics['packet_sizes'].append(packet_info['size'])
# Protocol distribution
proto = packet_info['protocol']
self.statistics['protocols'][proto] = self.statistics['protocols'].get(proto, 0) + 1
# Unique IPs and Most Active IPs
src_ip = packet_info['src_ip']
dst_ip = packet_info['dst_ip']
if src_ip != 'N/A':
self.statistics['unique_ips'].add(src_ip)
self.statistics['most_active_src'][src_ip] = self.statistics['most_active_src'].get(src_ip, 0) + 1
if dst_ip != 'N/A':
self.statistics['unique_ips'].add(dst_ip)
self.statistics['most_active_dst'][dst_ip] = self.statistics['most_active_dst'].get(dst_ip, 0) + 1
# Calculate average packet size
if self.statistics['total_packets'] > 0:
self.statistics['avg_packet_size'] = sum(self.statistics['packet_sizes']) / self.statistics['total_packets']
# Calculate capture duration
if self.start_time:
duration = datetime.now() - self.start_time
self.statistics['capture_duration'] = str(duration).split('.')[0] # Remove microseconds
def get_statistics(self) -> Dict[str, Any]:
"""Get current capture statistics"""
# Ensure unique_ips is a count, not the set itself, for reporting
stats_copy = self.statistics.copy()
stats_copy['unique_ips'] = len(self.statistics['unique_ips'])
# Sort active IPs for display
stats_copy['most_active_src'] = dict(sorted(self.statistics['most_active_src'].items(),
key=lambda item: item[1], reverse=True))
stats_copy['most_active_dst'] = dict(sorted(self.statistics['most_active_dst'].items(),
key=lambda item: item[1], reverse=True))
return stats_copy
def get_packets(self) -> List[Dict[str, Any]]:
"""Get all captured packets"""
return list(self.packets) # Return a copy to prevent external modification
def clear_packets(self) -> None:
"""Clear all captured packets and reset statistics"""
self.stop_capture() # Ensure capture is stopped before clearing
self.packets.clear()
self.packet_queue = queue.Queue() # Clear the queue as well
self.packet_count = 0
self.start_time = None
self.statistics = {
'total_packets': 0,
'protocols': {},
'data_transferred': 0,
'unique_ips': set(),
'packet_sizes': [],
'most_active_src': {},
'most_active_dst': {},
'avg_packet_size': 0.0,
'capture_duration': '0s'
}
def save_to_pcap(self, filename: str) -> None:
"""Save captured packets to PCAP file"""
# This functionality requires storing raw Scapy packets, which is
# currently disabled with store=0 for memory efficiency.
# To enable PCAP saving, 'store=1' or similar handling would be needed
# in the sniff function, along with converting stored dicts back to Scapy packets.
# This is a placeholder for future implementation.
raise NotImplementedError("Saving to PCAP is not currently supported in this version due to memory optimization.")
def save_to_file(self, filename: str, format_type: str = 'json') -> None:
"""Save captured packets to file"""
try:
if format_type.lower() == 'json':
with open(filename, 'w') as f:
json.dump(self.packets, f, indent=2)
elif format_type.lower() == 'txt':
with open(filename, 'w') as f:
for packet in self.packets:
f.write(f"Timestamp: {packet['timestamp']}\n")
f.write(f"Protocol: {packet['protocol']}\n")
f.write(f"Source: {packet['src_ip']}:{packet['src_port']}\n")
f.write(f"Destination: {packet['dst_ip']}:{packet['dst_port']}\n")
f.write(f"Size: {packet['size']} bytes\n")
f.write(f"Payload: {packet['payload'][:100]}...\n")
f.write("-" * 50 + "\n")
else:
raise ValueError("Unsupported format type. Choose 'json' or 'txt'.")
except Exception as e:
raise Exception(f"Error saving file: {str(e)}")