-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMalwareDetection.py
More file actions
353 lines (270 loc) · 11.4 KB
/
MalwareDetection.py
File metadata and controls
353 lines (270 loc) · 11.4 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/python3
import hyperloglog
import sys
import pyshark
#-------------------------------------------------------------------------------
def parsing_parameters():
l = len(sys.argv)
f_name_ = ''
num_IP = 0
time_ = 0
num_portsSRC = 0
num_portsDST = 0
verbose = False
#Script with no parameters
if(l == 1):
print('''Usage:
python3 MalwareDetection.py -p <filename> -sIP <num_IP> -sPS <num_portsSRC> -sPD <num_portsDST> -t <time>
-p
name of file.pcap to analyze
-sIP
different IPdst threshold [default : 30]
-sPS
different source ports threshold [default : 50]
-sPD
different destination ports threshold [default : 50]
-t
interval time of each measurement in seconds [default : 30s]
-v
Enable verbose mode
''')
exit()
for i in range(1,l):
if(sys.argv[i] == '-p' and i<l):
f_name_ = sys.argv[i+1] #name of file pcap
elif(sys.argv[i] == '-sIP' and i<l):
num_IP = sys.argv[i+1] #threshold for number of different IPdst
elif(sys.argv[i] == '-sPS' and i<l):
num_portsSRC = sys.argv[i+1] #threshold for number of different source ports
elif(sys.argv[i] == '-sPD' and i<l):
num_portsDST = sys.argv[i+1] #threshold for number of different destination ports
elif(sys.argv[i] == '-t' and i<l):
time_ = sys.argv[i+1] #interval time in seconds
elif(sys.argv[i] == '-v' and i<l):
verbose = True #flag for verbose mode
elif((sys.argv[i] == '--help' or sys.argv[i] == '-h') and i<=l):
print('''Usage:
python3 MalwareDetection.py -p <filename> -sIP <num_IP> -sPS <num_portsSRC> -sPD <num_portsDST> -t <time>
-p
name of file.pcap to analyze
-sIP
different IPdst threshold [default : 30]
-sPS
different source ports threshold [default : 50]
-sPD
different destination ports threshold [default : 50]
-t
interval time of each measurement in seconds [default : 30s]
-v
Enable verbose mode
''')
exit()
#Default value for threshold
if(num_IP == 0):
num_IP = 30
#Default value for threshold
if(num_portsSRC == 0):
num_portsSRC = 50
#Default value for threshold
if(num_portsDST == 0):
num_portsDST = 50
#Default value for interval time (in seconds)
if(time_ == 0):
time_ = 30
return f_name_, int(num_IP), int(num_portsSRC), int(num_portsDST), int(time_), verbose
#-------------------------------------------------------------------------------
def get_info(pkt):
#Packet info on layer IP
if(hasattr(pkt, 'ip')):
#Check if packet has IPsrc and IPdst addresses
if(hasattr(pkt.ip, 'dst') and hasattr(pkt.ip, 'src')):
IP_dst = pkt.ip.dst
IP_src = pkt.ip.src
pkt_time = pkt.frame_info.time_relative
else:
IP_dst = 0
IP_src = 0
pkt_time = 0
else:
#If packet has another protocol, assign default value to IPs
IP_dst = 0
IP_src = 0
pkt_time = 0
#Packet info on layer TCP/UDP
if(hasattr(pkt,'tcp')):
#Check if packet has TCP port_src and port_dst
if(hasattr(pkt.tcp, 'srcport') and hasattr(pkt.tcp, 'dstport')):
PORT_src = pkt.tcp.srcport
PORT_dst = pkt.tcp.dstport
else:
PORT_src = 0
PORT_dst = 0
elif(hasattr(pkt,'udp')):
#Check if packet has UDP port_src and port_dst
if(hasattr(pkt.udp, 'srcport') and hasattr(pkt.udp, 'dstport')):
PORT_src = pkt.udp.srcport
PORT_dst = pkt.udp.dstport
else:
PORT_src = 0
PORT_dst = 0
else:
#If packet has another protocol, assign default value to ports
PORT_dst = 0
PORT_src = 0
return IP_dst, IP_src, PORT_dst, PORT_src, float(pkt_time)
#-------------------------------------------------------------------------------
def formatString(s):
s = s.replace('\'', '')
s = s.replace('(', '')
s = s.replace(')', '')
s = s.strip()
return s
#-------------------------------------------------------------------------------
def print_report(diz,n,threshold,flag,verb):
for key in diz:
if(len(diz[key]) > threshold):
if(n == 1): #first type of attack
if(verb == True):
print(f'''
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| Type of attack: 1 IP -> N IP
| Problem: probable source host infection
| Description: {key} is contacting {len(diz[key])} different hosts
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
''')
flag = True
elif(n == 2): #second type of at tack
s_key = str(key)
sorgIP, sorgPORT, destIP = s_key.split(',')
sorgIP = formatString(sorgIP)
sorgPORT = formatString(sorgPORT)
destIP = formatString(destIP)
if(verb == True):
print(f'''
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| Type of attack: 1 IP, 1 PORT -> 1 IP, N PORTS
| Problem: probable port scanning on {destIP}
| Description: {sorgIP}::{sorgPORT} is contacting host {destIP} on {len(diz[key])} different ports
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
''')
flag = True
else: #third type of attack
s_key = str(key)
sorgIP, destIP, destPORT = s_key.split(',')
#formattazione stringhe
sorgIP = formatString(sorgIP)
destIP = formatString(destIP)
destPORT = formatString(destPORT)
if(verb == True):
print(f'''
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| Type of attack: 1 IP, N PORTS -> 1 IP, 1 PORT
| Problem: probable attempt to access a service on {destPORT} port
| Description: {sorgIP} is contacting {destIP} on {destPORT} port many times, through {len(diz[key])} different source ports
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
''')
flag = True
return flag
#-------------------------------------------------------------------------------
def analyze_pcap(diz1,diz2,diz3,list_,soglia1,soglia2,soglia3,flag,verb):
for elem in list_:
#Take the info about the current item of the list
ip_s = elem[0]
port_s = elem[1]
ip_d = elem[2]
port_d = elem[3]
#Fill the first dictionary
if(ip_s not in diz1):
diz1[ip_s] = hyperloglog.HyperLogLog(0.05)
else:
diz1.get(ip_s).add(ip_d)
#Fill the second dictionary
if((ip_s,port_s,ip_d) not in diz2):
diz2[(ip_s,port_s,ip_d)] = hyperloglog.HyperLogLog(0.05)
else:
diz2.get((ip_s,port_s,ip_d)).add(port_d)
#Fill the third dictionary
if((ip_s, ip_d, port_d) not in diz3):
diz3[ip_s, ip_d, port_d] = hyperloglog.HyperLogLog(0.05)
else:
diz3[(ip_s,ip_d,port_d)].add(port_s)
flag[0] = print_report(diz1,1,soglia1,flag[0],verb)
flag[1] = print_report(diz2,2,soglia2,flag[1],verb)
flag[2] = print_report(diz3,3,soglia3,flag[2],verb)
#Reset dictionaries and list
list_.clear()
diz1.clear()
diz2.clear()
diz3.clear()
return flag
#-------------------------------------------------------------------------------
#Take the parameters from command line
nomeFile, soglia_IP, soglia_PorteSRC, soglia_PorteDST, step, verb = parsing_parameters()
#Open file pcap
filename = pyshark.FileCapture(nomeFile, keep_packets=False)
#Dictionary for attack (1 IPsrc --> N IPdst)
#key-value :: IPsrc - N IPdst
diz_attack1 = {}
#Dictionary for attack (1 IPsrc, 1 PORTsrc --> 1 IPdst, n PORTSdst)
#key-value :: IPsrc, IPdst, port src - N ports dst
diz_attack2 = {}
#Dictionary for attack (1 IPsrc, n PORTsrc --> 1 IPdst, 1 PORTdst)
#key-value :: IPsrc, IPdst, portdst - N ports src
diz_attack3 = {}
#List that contains every different flow
flows_list = []
i = 0
start_time = float(0)
current_time = 0
#Data structures to check if a type of attack has occured.
flagVett = [False, False, False]
flagAttack = [False, False, False]
print(f'\nAnalyzing {nomeFile} ...')
print(f'This tool analyzes file using {step} seconds intervals\n')
while True:
#Analyze one packet
try:
packet = filename.next()
IP_dst, IP_src, PORT_dst, PORT_src, current_time = get_info(packet)
#Packet has no IP protocol
if(IP_dst == 0):
continue
#Packet has no TCP/UDP protocol
if(PORT_dst == 0):
continue
flow = [IP_src, PORT_src, IP_dst, PORT_dst]
flow2 = [IP_dst,PORT_dst,IP_src,PORT_src]
#Fill the flows list
if((flow not in flows_list) and (flow2 not in flows_list)):
flows_list.append(flow)
#Check if interval time has expired
if(abs(start_time-current_time) >= step):
flagVett = analyze_pcap(diz_attack1, diz_attack2, diz_attack3, flows_list, soglia_IP, soglia_PorteDST, soglia_PorteSRC, flagVett, verb)
start_time = current_time
flagAttack[0] = flagAttack[0] or flagVett[0] #if there is an attack of type 1
flagAttack[1] = flagAttack[1] or flagVett[1] #if there is an attack of type 2
flagAttack[2] = flagAttack[2] or flagVett[2] #if there is an attack of type 3
i = i+1
#show progress
if(i%5000 == 0):
print('...Analyzing...')
except StopIteration:
flagVett = analyze_pcap(diz_attack1, diz_attack2, diz_attack3, flows_list, soglia_IP, soglia_PorteDST, soglia_PorteSRC, flagVett, verb)
start_time = current_time
flagAttack[0] = flagAttack[0] or flagVett[0] #if there is an attack of type 1
flagAttack[1] = flagAttack[1] or flagVett[1] #if there is an attack of type 2
flagAttack[2] = flagAttack[2] or flagVett[2] #if there is an attack of type 3
break
#Check if the tool has detected anomalies
if(flagAttack[0] == False and flagAttack[1] == False and flagAttack[2] == False):
print(f'This tool has detected no anomalies in file {nomeFile}\n')
#Report with verbose mode disabled
elif(verb == False):
if(flagAttack[0] == True):
print('Vulnerability detected: (1 IP --> N IP)')
if(flagAttack[1] == True):
print('Vulnerability detected: (1 IP, 1 PORT --> 1 IP, N PORTS)')
if(flagAttack[2] == True):
print('Vulnerability detected: (1 IP, N PORTS --> 1 IP, 1 PORT)')
print(f'\nAnalysis terminated\n Closing file {nomeFile}\n')
filename.close()