-
Notifications
You must be signed in to change notification settings - Fork 0
/
live_analysis.py
207 lines (177 loc) · 7.82 KB
/
live_analysis.py
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
# import subprocess
# import json
# import time
# import joblib
# import random
# # Load the pre-trained machine learning model
# model = joblib.load('stk_model.pkl')
# # Global storage for packet frequency counts and total traffic
# packet_freqs = {}
# total_traffic = 0
# live_results = []
# def preprocess(packet_data):
# """ Prepare packet data for model prediction based on features similar to static analysis. """
# processed_features = [
# packet_data['len'],
# packet_data['src_packet_freq'],
# packet_data['dst_packet_freq'],
# packet_data['traffic_volume']
# ]
# print(f"Preprocessed features: {processed_features}") # Debugging statement
# return processed_features
# def process_packet(packet_json):
# """Process each packet captured by tshark, ignoring packets without necessary data."""
# try:
# packet_data = json.loads(packet_json)
# # Ensure all required fields are present
# if 'layers' in packet_data and all(k in packet_data['layers'] for k in ['ip_src', 'ip_dst', 'ip_len']):
# src_ip = packet_data['layers']['ip_src'][0]
# dst_ip = packet_data['layers']['ip_dst'][0]
# packet_len = int(packet_data['layers']['ip_len'][0])
# # Accumulate frequency and total traffic as done in static analysis
# global packet_freqs, total_traffic
# packet_freqs[src_ip] = packet_freqs.get(src_ip, 0) + 1
# packet_freqs[dst_ip] = packet_freqs.get(dst_ip, 0) + 1
# total_traffic += packet_len
# packet_info = {
# "len": packet_len,
# "src_packet_freq": packet_freqs[src_ip],
# "dst_packet_freq": packet_freqs[dst_ip],
# "traffic_volume": total_traffic
# }
# features = preprocess(packet_info)
# prediction = model.predict([features])
# live_results.append({
# "IP": {
# "src": src_ip,
# "dst": dst_ip,
# "len": packet_len,
# "prediction": prediction[0]
# },
# "time": time.time()
# })
# # Limit the size of live_results
# if len(live_results) > 100:
# live_results.pop(0)
# print(f"Processed packet: {packet_info}, Prediction: {prediction[0]}")
# else:
# print("Packet skipped due to incomplete data")
# except json.JSONDecodeError as e:
# print(f"JSON decoding error: {str(e)}")
# except Exception as e:
# print(f"Error processing packet: {str(e)}")
# def start_tshark(interface):
# """ Start the tshark process to capture packets using provided interface. """
# command = ['tshark', '-i', interface, '-T', 'ek', '-e', 'ip.src', '-e', 'ip.dst', '-e', 'ip.len', '-Y', 'ip', '-l']
# print(f"Starting tshark with command: {' '.join(command)}") # Debugging statement
# with subprocess.Popen(command, stdout=subprocess.PIPE, text=True) as proc:
# for line in proc.stdout:
# process_packet(line.strip())
# def get_live_results():
# """ Return a copy of the live results. """
# print(f"Returning live results: {live_results}") # Debugging statement
# #return live_results.copy()
# example_data = {
# 'len': random.randint(40, 1500),
# 'src_packet_freq': random.randint(1, 1000),
# 'dst_packet_freq': random.randint(1, 1000),
# 'traffic_volume': random.randint(1, 1000000)
# }
# return example_data
# if __name__ == "__main__":
# interface = "\\Device\\NPF_{3958AAE7-B2D7-4302-9F76-EA8AD698D618}"
# start_tshark(interface)
import subprocess
import json
import time
import joblib
import random
import threading
# Load the pre-trained machine learning model
model = joblib.load('stk_model.pkl')
# Global storage for packet frequency counts and total traffic
packet_freqs = {}
total_traffic = 0
live_results = []
def preprocess(packet_data):
""" Prepare packet data for model prediction based on features similar to static analysis. """
processed_features = [
packet_data['len'],
packet_data['src_packet_freq'],
packet_data['dst_packet_freq'],
packet_data['traffic_volume']
]
return processed_features
def process_packet(packet_json):
"""Process each packet captured by tshark, ignoring packets without necessary data."""
try:
packet_data = json.loads(packet_json)
if 'layers' in packet_data and all(k in packet_data['layers'] for k in ['ip_src', 'ip_dst', 'ip_len', 'ip_proto', 'tcp_port', 'udp_port']):
src_ip = packet_data['layers']['ip_src'][0]
dst_ip = packet_data['layers']['ip_dst'][0]
packet_len = int(packet_data['layers']['ip_len'][0])
protocol = packet_data['layers']['ip_proto'][0]
src_port = packet_data['layers'].get('tcp_port', [None])[0] or packet_data['layers'].get('udp_port', [None])[0]
global packet_freqs, total_traffic
packet_freqs[src_ip] = packet_freqs.get(src_ip, 0) + 1
packet_freqs[dst_ip] = packet_freqs.get(dst_ip, 0) + 1
total_traffic += packet_len
packet_info = {
"len": packet_len,
"src_packet_freq": packet_freqs[src_ip],
"dst_packet_freq": packet_freqs[dst_ip],
"traffic_volume": total_traffic,
"protocol": protocol,
"src_port": src_port,
}
features = preprocess(packet_info)
prediction = model.predict([features])
live_results.append({
"src_ip": src_ip,
"dst_ip": dst_ip,
"len": packet_len,
"protocol": protocol,
"src_port": src_port,
"src_packet_freq": packet_freqs[src_ip],
"dst_packet_freq": packet_freqs[dst_ip],
"traffic_volume": total_traffic,
"prediction": prediction[0],
"time": time.time()
})
if len(live_results) > 100:
live_results.pop(0)
else:
print("Packet skipped due to incomplete data")
except json.JSONDecodeError as e:
print(f"JSON decoding error: {str(e)}")
except Exception as e:
print(f"Error processing packet: {str(e)}")
def start_tshark(interface):
""" Start the tshark process to capture packets using provided interface. """
command = ['tshark', '-i', interface, '-T', 'ek', '-e', 'ip.src', '-e', 'ip.dst', '-e', 'ip.len', '-e', 'ip.proto', '-e', 'tcp.port', '-e', 'udp.port', '-Y', 'ip', '-l']
with subprocess.Popen(command, stdout=subprocess.PIPE, text=True) as proc:
for line in proc.stdout:
process_packet(line.strip())
def get_live_results():
""" Return a copy of the live results. """
if live_results:
return live_results[-1]
else:
example_data = {
'src_ip': f'192.168.{random.randint(1, 254)}.{random.randint(1, 254)}',
'dst_ip': f'192.168.{random.randint(1, 254)}.{random.randint(1, 254)}',
'len': random.randint(40, 1500),
'src_packet_freq': random.randint(1, 1000),
'dst_packet_freq': random.randint(1, 1000),
'traffic_volume': random.randint(1, 1000000),
'protocol': random.choice(['TCP', 'UDP', 'ICMP']),
'src_port': random.randint(1, 65535)
}
return example_data
def start_live_analysis(interface):
""" Start live analysis in a separate thread. """
analysis_thread = threading.Thread(target=start_tshark, args=(interface,))
analysis_thread.start()
if __name__ == "__main__":
interface = "\\Device\\NPF_{3958AAE7-B2D7-4302-9F76-EA8AD698D618}"
start_live_analysis(interface)