-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathmain.py
1754 lines (1520 loc) · 67.9 KB
/
main.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
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#regex for ipv4 and ipv6 in the same time
regex = "((^\s*((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\s*$)|(^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$))"
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QIcon, QFont, QCursor, QPixmap, QColor, QKeySequence, QPalette
from PyQt5.QtCore import pyqtSlot, QThread, Qt, pyqtSignal, QPoint
from PyQt5.QtWidgets import QHBoxLayout, QFrame, QAbstractItemView, QSplitter, \
QStyleFactory, QMenu, QShortcut,\
QMainWindow, QApplication, QWidget, QAction, QTableWidget,\
QTableWidgetItem, QVBoxLayout, \
QTabWidget, QProgressBar, QFileDialog, QCompleter, QStyledItemDelegate,QProxyStyle,QStyle
from threading import Thread
import sys
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
import os
from multiprocessing import Manager, Process, Queue
from ctypes import *
from time import sleep, time
from datetime import datetime
import re
"""Import from other files in this directory"""
from var import VAR
from packet_r import Packet_r, igmptypes, arpoptypes
from httpconverter import HttpConverter, HttpHeader
#redirect all output to files in order to keep the console clean
#filename = open(r"outputfile.txt",'w')
#sys.stdout = filename
"""Used to make long string wrap to newline"""
import textwrap
"""The library to convert ANSI escape code to html css"""
from ansi2html import Ansi2HTMLConverter
from contextlib import contextmanager
"""Optional usage of pyshark to give brief info"""
try:
import pyshark
flag_pyshark = True
except ImportError:
flag_pyshark = False
@contextmanager
def redirect_stderr(new_target):
"""Suppress all warnings to keep console clean.
"""
import sys
old_target, sys.stderr = sys.stderr, new_target
try:
yield new_target
finally:
sys.stderr = old_target
with open(os.devnull, 'w') as errf:
"""Suppress all annoying warnings when loading scapy
Scapy will show a lot of annoying warnings when loading.
This function is going to suppress all of them.
"""
with redirect_stderr(errf):
from scapy.all import *
import scapy.contrib.igmp
#Use pcap to capture in Windows
conf.use_pcap = True
#psutil is used to detect network speed
import psutil
"""The following functions are used to handle tcp reassembly"""
"""The following function is used to give wireshark-type string"""
def packet_align(s):
"""Convert hex string to Wireshark-type raw hex string.
Args:
s: hex string of a packet
Returns:
string:Wireshark-type raw hex string
"""
s = [s[i:i + 32] for i in range(0, len(s), 32)]
for n in range(len(s)):
s[n] = [s[n][i:i + 2] for i in range(0, len(s[n]), 2)]
s[n].append("\n")
s[n].insert(0, format(n * 16, "04x"))
s[n] = " ".join(s[n])
return s
"""The following functions is used to parse filter when dict is given"""
def InputToFilter(flag_dict):
"""Return the filter string of input.
Return the filter string of input when the dict is given.
Args:
flag_dict: manager.dict, pass args between processes.
Returns:
f:string of the filter satisfying BPF filter rules
"""
f = ""
if (flag_dict['close'] == False):
for key in flag_dict.keys():
if (flag_dict[key] != ''):
if (key == 'pro'):
f += " and " + flag_dict['pro']
elif (key == 'src' or key == 'dst'):
f += " and " + key + " " + flag_dict[key]
elif (key == 'sport'):
f += " and src port " + flag_dict['sport']
elif (key == 'dport'):
f += " and dst port " + flag_dict['dport']
f = f[5:].lower()
return f
"""The following function is an additional process to sniff continously"""
def InfiniteProcess(flag_dict, pkt_lst):
"""The infinite process of sniffing.
The dedicated process to sniff, which is to get the iface and filter and then starting sniffing.
Args:
flag_dict: manager.dict pass args between processes.
pkt_lst: manager.queue pass pkts between processes.
"""
while (flag_dict['close'] == False):
sleep(0.1)
if (flag_dict['start'] == True and flag_dict['error'] == False):
f = InputToFilter(flag_dict)
while not pkt_lst.empty():
"""Clear all remaining before each start.
"""
pkt_lst.get()
try:
if (f == ""):
a = sniff(
iface=flag_dict['iface'],
store=0,
pkt_lst=pkt_lst,
flag_dict=flag_dict,
stopperTimeout=0.2,
)
else:
a = sniff(
iface=flag_dict['iface'],
store=0,
filter=f,
pkt_lst=pkt_lst,
flag_dict=flag_dict,
stopperTimeout=0.2,
)
except NameError:
flag_dict['error'] = True
"""The following classes are customized class derived from QtWidgets"""
class SearchButton(QtWidgets.QPushButton):
"""
A button class specifically for search button derived from QPushButton
"""
def enterEvent(self, event):
"""Refine mouse enter event of the search button.
If mouse enters, then it shows feedback to the user.
"""
self.setStyleSheet("border: 1px solid grey;background-color: white;")
def leaveEvent(self, event):
"""Refine mouse leave event of the search button.
If mouse leaves, then it remains white background like search bar.
"""
self.setStyleSheet("border: none;background-color: white;")
class NewButton(QtWidgets.QPushButton):
"""
A new button class derived from QPushButton
"""
def enterEvent(self, event):
"""Refine mouse enter event of the button.
If mouse enters, then it shows feedback to the user.
"""
self.setStyleSheet("background-color:rgb(225, 225, 225);color:blue")
def leaveEvent(self, event):
"""Refine mouse enter event of the button.
If mouse enters, then it remains background as background.
"""
self.setStyleSheet(
"background-color: transparent;border-style: outset;border-width: 0px;color:blue")
class Table(QtWidgets.QTableWidget):
"""A new table class derived from QTableWidget.
Modify contextMenuEvent to save selected packet(s)
"""
def leaveEvent(self, event):
if (share.last_row != ''):
last_row = share.last_row
if (share.flag_search):
try:
last_row = share.dict_search[last_row]
except:
return
color_list = share.list_packet[last_row].getColor()
for i in range(6):
try:
self.item(share.last_row, i).setBackground(QtGui.QColor(
color_list[0][0], color_list[0][1], color_list[0][2]))
except AttributeError:
pass
share.last_row = ''
def contextMenuEvent(self, event):
"""Refine contextMenu Event of the QtableWidget.
If right click occurs, pop up a menu for user to save.
"""
self.menu = QtWidgets.QMenu(self)
if (len(self.selectedItems()) > 6):
saveAction = QtWidgets.QAction(
'Save selected %d packets' % (len(self.selectedItems()) / 6), self)
copyAction = QtWidgets.QAction(
'Copy selected %d packets' % (len(self.selectedItems()) / 6), self)
else:
saveAction = QtWidgets.QAction('Save selected packet', self)
copyAction = QtWidgets.QAction('Copy selected packet', self)
saveAction.triggered.connect(self.SaveReadablePackets)
copyAction.triggered.connect(self.CopyReadablePackets)
self.menu.addAction(saveAction)
self.menu.addAction(copyAction)
self.menu.setFont(QFont('Consolas', 10, QFont.Light))
self.menu.popup(QtGui.QCursor.pos())
def SaveReadablePackets(self):
"""Save Readable Packets to location.
Save readable information of packet(s) to location.
"""
a = []
for i in self.selectedItems():
a.append(i.row())
filename = QFileDialog.getSaveFileName(filter="Text files (*.txt)")[0]
s = ""
if (filename != ""):
f = open(filename, "w")
l = set(a)
list(l).sort()
for i in l:
if (share.flag_search == True):
i = share.dict_search[i]
s += self.GetReadablePackets(i)
f.write(s)
f.close()
# open the file as soon as the progress of saving is finished
t = Thread(target=self.OpenFile, args=(filename,))
t.start()
def CopyReadablePackets(self):
"""Copy Readable Packets to Clipboard.
Copy readable information of packet(s) to Clipboard.
"""
cb = QtWidgets.QApplication.clipboard()
cb.clear(mode=cb.Clipboard)
a = []
for i in self.selectedItems():
a.append(i.row())
s = ""
l = set(a)
list(l).sort()
for i in l:
if (share.flag_search == True):
i = share.dict_search[i]
s += self.GetReadablePackets(i)
cb.setText(s, mode=cb.Clipboard)
def GetReadablePackets(self, i):
"""Using index to give readable packets
Return readable packets' string.
Args:
i: index of the packet in list_packet
"""
return ('No.' + str(share.list_packet[i].num) + '\nCapture Time:' + share.list_packet[i].time +
'\tSave Time:' + datetime.now().strftime("%H:%M:%S") +
'\n' + share.list_packet[i].show(dump=True) + '\n')
def OpenFile(self, filename):
"""Open file in a new thread to prevent GUI from freezing.
Args:
filename: a string of file location.
"""
os.system(filename)
class Style(QProxyStyle):
"""A new style class derived from QProxyStyle.
Make the tablewidget no dotted line without sacrificing the control by keyboard
"""
def drawPrimitive(self, element, option, painter, widget):
if element == QStyle.PE_FrameFocusRect:
return
super().drawPrimitive(element, option, painter, widget)
class ColorDelegate(QtWidgets.QStyledItemDelegate):
"""A new colordelegate class derived from QStyledItemDelegate.
Modify every item's selection color in table widget.
"""
def paint(self, painter, option, index):
"""Overwrite original method of selection color
Overwrite original method of selection color,
ensuring every row's color shows independently,
even in multiple selection
Args:
painter: default parameter
option: default parameter
index: default parameter
"""
color = index.data(Qt.UserRole)
if (color == QColor((18 - 30) % 256, (39 - 30) % 256, (46 - 30) % 256)):
option.palette.setColor(QPalette.Highlight, QColor(50, 39, 46))
option.palette.setColor(
QPalette.HighlightedText, QColor(247, 135, 135))
else:
option.palette.setColor(QPalette.Highlight, color)
option.palette.setColor(
QPalette.HighlightedText, QColor(18, 39, 46))
QStyledItemDelegate.paint(self, painter, option, index)
"""The following classes are customized class derived from QThread"""
class ProcessingThread(QThread):
"""A class derived from QThread of processing raw packets.
The major parsing packets happens here, which is to get each packet from
Queue in sniffing process and parse it one by one.
"""
AddPacket = pyqtSignal(list)
Scroll = pyqtSignal(str)
def __init__(self, parent=None):
QThread.__init__(self, parent=parent)
self.isRunning = True
def run(self):
"""Run the thread of processing.
The dedicated thread to process raw packet, which is to process
each raw packet and make it display in the QTableWidget.
"""
num = 0
global pkt_lst
while self.isRunning:
if (share.flag_search == False):
try:
p = pkt_lst.get()
except:
continue
list_byte.append(p[0])
packet = Ether(p[0])
packet.time = p[1]
packet.num = num
packet = Packet_r(packet)
# possible preprocess for TCP reassembly
if packet.haslayer(TCP):
seq = packet.packet[TCP].seq
src = packet.src
dst = packet.dst
sport = packet.packet[TCP].sport
dport = packet.packet[TCP].dport
try:
seqlen = len(packet.packet[Raw])
except:
seqlen = 0
share.tcp_seq.append(
(packet.num, seq, seqlen, src, dst, sport, dport))
try:
fetch_dict = share.dict_expect_tcp_seq[(
packet.src, packet.dst, packet.packet[TCP].sport, packet.packet[TCP].dport)]
seq_expect = fetch_dict[0]
last_syn = fetch_dict[1]
if (seq != seq_expect and last_syn == False):
packet.tcp_order = False
except KeyError:
pass
binary_flags = bin(int(packet.packet[TCP].flags.split(' ')[0]))[
2:].rjust(7, '0')
syn = binary_flags[-2]
if (syn == '1'):
syn = True
else:
syn = False
share.dict_expect_tcp_seq[(
packet.src, packet.dst, packet.packet[TCP].sport, packet.packet[TCP].dport)] = (seq + seqlen, syn)
# possible preprocess for IP reassembly
if packet.haslayer(IP):
if packet.packet[IP].flags != 2:
if (packet.packet[IP].src, packet.packet[IP].dst,
packet.packet[IP].id) in share.ip_seq.keys():
share.ip_seq[(packet.packet[IP].src, packet.packet[IP].dst,
packet.packet[IP].id)].append(
(packet.num, packet.packet[IP].flags,
packet.packet[IP].frag))
else:
share.ip_seq[(packet.packet[IP].src, packet.packet[IP].dst,
packet.packet[IP].id)] = [(packet.num, packet.packet[IP].flags,
packet.packet[IP].frag)]
share.list_packet.append(packet)
if (share.flag_search == False):
l = packet.packet_to_info()
l.append(packet.getColor())
l.append(num)
self.AddPacket.emit(l)
share.list_tmp.append(packet.packet_to_info())
num += 1
if ((share.flag_select == False and share.flag_search == False)
or (share.flag_select == True and share.flag_cancel == True
and share.flag_search == False)):
# make the scroll bar update
self.Scroll.emit("True")
else:
sleep(0.2)
def stop(self):
self.isRunning = False
self.quit()
self.wait()
class NetworkspeedThread(QThread):
"""A class derived from QThread of caculating network speed.
"""
SetNetworkSpeed = pyqtSignal(list)
def __init__(self, parent=None):
QThread.__init__(self, parent=parent)
self.isRunning = True
def run(self):
"""The dedicated thread to caculate networkspeed
"""
s_up = 0.00
s_down = 0.00
while (share.mac == ''):
sleep(0.5)
t0 = time.time()
macname = share.dict_mac2name[share.mac]
upload = psutil.net_io_counters(pernic=True)[macname][0]
download = psutil.net_io_counters(pernic=True)[macname][1]
up_down = (upload, download)
while self.isRunning:
last_up_down = up_down
upload = psutil.net_io_counters(pernic=True)[macname][0]
download = psutil.net_io_counters(pernic=True)[macname][1]
t1 = time.time()
up_down = (upload, download)
try:
s_up, s_down = [(now - last) / (t1 - t0)
for now, last in zip(up_down, last_up_down)]
t0 = time.time()
except:
pass
time.sleep(0.5)
self.SetNetworkSpeed.emit([int(s_up), int(s_down)])
def stop(self):
self.isRunning = False
self.quit()
self.wait()
"""The following classe is the main GUI class"""
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
self.MainWindow = MainWindow
self.MainWindow.setObjectName("self.MainWindow")
self.MainWindow.resize(850, 800)
self.centralwidget = QtWidgets.QWidget(self.MainWindow)
self.MainWindow.setCentralWidget(self.centralwidget)
# using grid layout to put widgets
# vlayout is used to expand items automatically
self.vlayout = QtWidgets.QVBoxLayout(self.centralwidget)
self.gridLayout = QtWidgets.QGridLayout()
self.gridLayout.setContentsMargins(0, 0, 0, 0)
'''1st line'''
# NIC label
self.label_NIC = QtWidgets.QLabel(self.centralwidget)
self.label_NIC.setText("NIC")
self.label_NIC.setFont(QFont('Consolas', 11, QFont.Bold))
# NIC comboBox
self.comboBox = QtWidgets.QComboBox(self.centralwidget)
self.comboBox.setFont(QFont('Consolas', 10, QFont.Light))
# add interface name into comboBox
for i in share.interfaces:
self.comboBox.addItem(i)
self.comboBox.currentTextChanged.connect(self.EvtIface)
# checkbox for max mod
self.checkBox = QtWidgets.QCheckBox(self.centralwidget)
self.checkBox.setFont(QFont('Consolas', 10, QFont.Light))
self.checkBox.setText("OC")
self.checkBox.setChecked(True)
self.checkBox.clicked.connect(self.EvtOcMode)
self.checkBox.setToolTip(
"OC MODE:\nUsing a dedicated process to sniff continuously,\nwhich may enhance CPU usage.")
'''1st line layout'''
self.gridLayout.addWidget(self.label_NIC, 0, 0, 1, 1)
self.gridLayout.addWidget(self.comboBox, 0, 1, 1, 7)
self.gridLayout.addWidget(self.checkBox, 0, 8, 1, 1)
'''2nd line'''
# protocol label
self.label_pro = QtWidgets.QLabel(self.centralwidget)
self.label_pro.setFont(QFont('Consolas', 11, QFont.Bold))
self.label_pro.setText("PRO")
# source address label
self.label_src = QtWidgets.QLabel(self.centralwidget)
self.label_src.setFont(QFont('Consolas', 11, QFont.Bold))
self.label_src.setText("SRC")
# source port label
self.label_sport = QtWidgets.QLabel(self.centralwidget)
self.label_sport.setFont(QFont('Consolas', 11, QFont.Bold))
self.label_sport.setText("SPORT")
# destination address label
self.label_dst = QtWidgets.QLabel(self.centralwidget)
self.label_dst.setFont(QFont('Consolas', 11, QFont.Bold))
self.label_dst.setText("DST")
# destination port label
self.label_dport = QtWidgets.QLabel(self.centralwidget)
self.label_dport.setFont(QFont('Consolas', 11, QFont.Bold))
self.label_dport.setText("DPORT")
# protocol LineEdit
self.pro = QtWidgets.QLineEdit(self.centralwidget)
self.pro.setFont(QFont('Consolas', 10, QFont.Light))
#auto complete with some options
completer = QtWidgets.QCompleter(
["ip", "ip6", "tcp", "udp", "arp", "icmp", "icmp6", "igmp"])
completer.popup().setFont(QFont('Consolas', 10, QFont.Light))
self.pro.setCompleter(completer)
self.pro.textChanged.connect(self.EvtTextPro)
# src LineEdit
self.src = QtWidgets.QLineEdit(self.centralwidget)
self.src.setFont(QFont('Consolas', 10, QFont.Light))
self.src.textChanged.connect(self.EvtTextSrc)
v = QtGui.QRegExpValidator(QtCore.QRegExp(regex))
self.src.setValidator(v)
# sport LineEdit
self.sport = QtWidgets.QLineEdit(self.centralwidget)
self.sport.setFont(QFont('Consolas', 10, QFont.Light))
self.sport.textChanged.connect(self.EvtTextSport)
self.sport.setValidator(QtGui.QIntValidator(0, 65535))
# dst LineEdit
self.dst = QtWidgets.QLineEdit(self.centralwidget)
self.dst.setFont(QFont('Consolas', 10, QFont.Light))
self.dst.textChanged.connect(self.EvtTextDst)
self.dst.setValidator(v)
# dport LineEdit
self.dport = QtWidgets.QLineEdit(self.centralwidget)
self.dport.setFont(QFont('Consolas', 10, QFont.Light))
self.dport.textChanged.connect(self.EvtTextDport)
self.dport.setValidator(QtGui.QIntValidator(0, 65535))
'''2nd line layout'''
self.gridLayout.addWidget(self.label_pro, 1, 0, 1, 1)
self.gridLayout.addWidget(self.pro, 1, 1, 1, 1)
self.gridLayout.addWidget(self.label_src, 1, 2, 1, 1)
self.gridLayout.addWidget(self.src, 1, 3, 1, 1)
self.gridLayout.addWidget(self.label_sport, 1, 4, 1, 1)
self.gridLayout.addWidget(self.sport, 1, 5, 1, 1)
self.gridLayout.addWidget(self.label_dst, 1, 6, 1, 1)
self.gridLayout.addWidget(self.dst, 1, 7, 1, 1)
self.gridLayout.addWidget(self.label_dport, 1, 8, 1, 1)
self.gridLayout.addWidget(self.dport, 1, 9, 1, 1)
'''3rd line'''
# searchbar LineEdit
self.searchbar = QtWidgets.QLineEdit(self.centralwidget)
self.searchbar.setPlaceholderText("Search")
self.searchbar.setFont(QFont('Consolas', 10, QFont.Light))
self.searchbar.setFrame(False)
self.searchbar.setFixedHeight(30)
self.searchbar.setClearButtonEnabled(True)
# searchbutton with icon
self.searchbutton = SearchButton(self.centralwidget)
self.searchbutton.setIcon(QIcon(os.path.dirname(
os.path.realpath(__file__)) + "\\icons\\searchicon.png"))
self.searchbutton.setStyleSheet("border: none;background-color: white;")
self.searchbutton.setFixedSize(30, 30)
self.searchbutton.clicked.connect(self.EvtSearch)
# start/stop button
self.button = QtWidgets.QPushButton(self.centralwidget)
self.button.setText("START")
self.button.setFont(QFont('Consolas', 10, QFont.Light))
self.button.clicked.connect(self.EvtStart)
self.button.setFont(QFont('Consolas', 11, QFont.Light))
self.button.setFixedHeight(30)
#combine searchbutton and search icon into a HBoxLayout
hbox = QtWidgets.QHBoxLayout()
hbox.setContentsMargins(0, 0, 0, 0)
hbox.addWidget(self.searchbar)
hbox.addWidget(self.searchbutton)
hbox.setSpacing(0)
self.searchbar.returnPressed.connect(self.EvtSearch)
'''3nd line layout'''
self.gridLayout.addLayout(hbox, 2, 0, 1, 10)
self.gridLayout.addWidget(self.button, 0, 9, 1, 1)
"""table """
self.tableWidget = Table(self.centralwidget)
self.tableWidget.verticalHeader().setDefaultSectionSize(25)
self.tableWidget.horizontalHeader().setFont(QFont('Consolas', 11, QFont.Light))
self.tableWidget.setSizeAdjustPolicy(
QtWidgets.QAbstractScrollArea.AdjustToContents)
#No border when focus
self.tableWidget.setStyle(Style())
self.tableWidget.setStyleSheet(" QTableWidget {outline: 0;}" )
self.tableWidget.setMinimumHeight(50)
self.tableWidget.setColumnCount(6)
self.tableWidget.verticalHeader().setVisible(False)
self.tableWidget.horizontalHeader().setDefaultAlignment(Qt.AlignLeft)
self.tableWidget.setHorizontalHeaderLabels(
['No.', 'Time', 'Source address', 'Destination address', 'Length', 'Protocol'])
self.tableWidget.setColumnWidth(0, 60)
self.tableWidget.setColumnWidth(1, 100)
self.tableWidget.setColumnWidth(2, 240)
self.tableWidget.setColumnWidth(3, 240)
self.tableWidget.setColumnWidth(4, 75)
self.tableWidget.setColumnWidth(5, 90)
self.tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)
# set every column resizes automatically to fill remaining spaces
self.tableWidget.horizontalHeader().setStretchLastSection(True)
self.tableWidget.setShowGrid(False)
self.tableWidget.setFont(QFont('Consolas', 10, QFont.Light))
self.tableWidget.itemSelectionChanged.connect(self.EvtSelect)
self.tableWidget.itemDoubleClicked.connect(self.EvtCancelFreeze)
self.tableWidget.cellEntered.connect(self.EvtMouseOnRow)
#colordelegate for every row
self.tableWidget.setItemDelegate(ColorDelegate())
#select a row when clicking
self.tableWidget.setSelectionBehavior(QTableWidget.SelectRows)
self.tableWidget.setMouseTracking(True)
#self.tableWidget.setStyleSheet("QTableWidget::item:selected{ background-color: rgba(255, 0, 0, 10%)}")
# QThread to receive signal of adding and scrolling
self.th = ProcessingThread()
self.th.AddPacket.connect(self.AddPacketToTable)
self.th.Scroll.connect(self.ScrollToEnd)
self.th.start()
"""tab1"""
self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)
self.tabWidget.setMinimumHeight(50)
self.tabWidget.setFont(QFont('Consolas', 10, QFont.Light))
"""tab2"""
self.tabWidget_2 = QtWidgets.QTabWidget(self.centralwidget)
self.tabWidget_2.setMinimumHeight(50)
self.tabWidget_2.setFont(QFont('Consolas', 10, QFont.Light))
"""split window"""
splitter = QSplitter(Qt.Vertical)
splitter.addWidget(self.tableWidget)
splitter.addWidget(self.tabWidget)
splitter.addWidget(self.tabWidget_2)
splitter.setSizes([232, 225, 225])
self.gridLayout.addWidget(splitter, 3, 0, 5, 10)
self.gridLayout.setRowMinimumHeight(3, 690)
self.vlayout.addLayout(self.gridLayout)
"""button: continue to reassemble"""
self.continue_reassemble_button = NewButton(self.tabWidget_2)
self.continue_reassemble_button.setGeometry(
QtCore.QRect(500, -4, 300, 30))
self.continue_reassemble_button.setText("Continue to reassemble")
self.continue_reassemble_button.setFont(
QFont('Consolas', 11, QFont.Light))
self.continue_reassemble_button.clicked.connect(
self.EvtContinueReassemble)
self.continue_reassemble_button.setStyleSheet(
"background-color: rgb(240, 240, 240);border-style: outset;border-width: 0px;color:blue")
self.continue_reassemble_button.hide()
"""status bar"""
self.statusbar = QtWidgets.QStatusBar(self.MainWindow)
self.statusbar.setFixedHeight(30)
self.statusbar.setObjectName("statusbar")
self.MainWindow.setStatusBar(self.statusbar)
#speedlabel
self.speedlabel = QtWidgets.QLabel()
self.speedlabel.setText("")
self.speedlabel.setFont(QFont('Consolas', 10, QFont.Light))
#save reassemble button
self.save_reassemble_button = NewButton()
self.save_reassemble_button.setText("Save reassembly Result")
self.save_reassemble_button.setStyleSheet(
"background-color: rgb(240, 240, 240);border-style: outset;border-width: 0px;color:blue")
self.save_reassemble_button.setFont(QFont('Consolas', 10, QFont.Light))
self.save_reassemble_button.clicked.connect(self.EvtSaveReassemble)
self.save_reassemble_button.hide()
self.statusbar.addPermanentWidget(self.save_reassemble_button)
self.statusbar.addPermanentWidget(self.speedlabel)
#progressbar
self.pbar = QProgressBar()
self.pbar.setValue(0)
self.pbar.setFixedWidth(150)
self.statusbar.addWidget(self.pbar)
self.pbar.hide()
self.th2 = NetworkspeedThread()
self.th2.SetNetworkSpeed.connect(self.SetSpeedOnStatusBar)
self.th2.start()
#whether have http content
self.http_content = ""
"""shortcuts"""
# color mode default on
self.colorModeStatus = True
self.colorshortcut = QShortcut(
QKeySequence("Ctrl+F"), self.centralwidget)
self.colorshortcut.activated.connect(self.ColorMode)
#copy packets
self.copypacket = QShortcut(
QKeySequence("Ctrl+C"), self.centralwidget)
self.copypacket.activated.connect(self.tableWidget.CopyReadablePackets)
#save packets
self.savepacket = QShortcut(
QKeySequence("Ctrl+S"), self.centralwidget)
self.savepacket.activated.connect(self.tableWidget.SaveReadablePackets)
#quick start/resume
self.quickstart = QShortcut(
QKeySequence("Alt+Q"), self.centralwidget)
self.quickstart.activated.connect(self.EvtStart)
self.title = 'Sniffer V2.0'
self.MainWindow.setWindowIcon(QIcon(os.path.dirname(
os.path.realpath(__file__)) + "\\icons\\icon.png"))
self.MainWindow.setWindowTitle(self.title)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def EvtIface(self):
"""Event when combobox changes.
The event for selecting the Network Interface in Combobox,
which is to save it for filter(default:all)
"""
global flag_dict
flag_dict['iface'] = self.comboBox.currentText()
share.mac = share.mac_dict[flag_dict['iface']]
flag_dict['mac'] = share.mac_dict[flag_dict['iface']]
def EvtTextPro(self):
"""Event when protocol LineEdit changes.
The event for entering the protocol,
which is to save it for filter(default:all)
"""
global flag_dict
flag_dict['pro'] = self.pro.text()
def EvtTextSrc(self):
"""Event when src LineEdit changes.
The event for entering the src,
which is to save it for filter(default:all)
"""
global flag_dict
flag_dict['src'] = self.src.text()
def EvtTextSport(self):
"""Event when sport LineEdit changes.
The event for entering the sport,
which is to save it for filter(default:all)
"""
global flag_dict
flag_dict['sport'] = self.sport.text()
def EvtTextDst(self):
"""Event when dst LineEdit changes.
The event for entering the dst,
which is to save it for filter(default:all)
"""
global flag_dict
flag_dict['dst'] = self.dst.text()
def EvtTextDport(self):
"""Event when dport LineEdit changes.
The event for entering the dport,
which is to save it for filter(default:all)
"""
global flag_dict
flag_dict['dport'] = self.dport.text()
def EvtOcMode(self):
"""Set OC mode settings.
The event for selecting the mode of mulitiprocessing
for the higher-end performance, which is to save it for filter(default:on).
"""
global flag_dict
flag_dict['max'] = self.checkBox.isChecked()
def EvtStart(self):
"""Event when Start button changes.
The event for clicking the Start/Stop button, which is to start/stop the progress.
At the same time, set window's title accordingly
"""
global flag_dict
flag_dict['start'] = not flag_dict['start']
if (flag_dict['start']):
sleep(0.3)
if (flag_dict['error'] == True):
#filter error
flag_dict['start'] = False
flag_dict['error'] = False
buttonReply = QtWidgets.QMessageBox.critical(
self.centralwidget, 'Filter Error', "Your Input is not valid.\nPlease try another one.",
QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.Ok)
return
filterstr = InputToFilter(flag_dict) if (
InputToFilter(flag_dict) != "") else "ALL"
self.button.setText('Stop')
title = self.title + " - " + \
flag_dict["iface"] + " - " + \
filterstr
if (flag_dict["max"]):
title += " - OC: ON"
else:
title += " - OC: OFF"
self.MainWindow.setWindowTitle(title)
else:
self.button.setText('Start')
self.MainWindow.setWindowTitle(self.title)
t = Thread(target=self.TsharkInfo)
t.start()
def TsharkInfo(self):
"""If pyshark is installed, displaying info on mouse event.
"""
if (flag_pyshark):
capture = pyshark.InMemCapture(only_summaries=True)
l = []
for i in share.list_packet:
l.append(bytes(i.packet))
capture.feed_packets(l)
share.list_TsharkInfo = []
for i in capture:
share.list_TsharkInfo.append(i.info)
def EvtMouseOnRow(self, row, column):
"""Mouse entering event for the packet
Show color change effect and Pyshark Info(if install pyshark).
Args:
row: row index of the packet with cursor
column: column index of the packet with cursor
"""
if (self.colorModeStatus == False):
share.last_row = ''
else:
if (share.last_row != ''):
last_row = share.last_row
if (share.flag_search):
try:
last_row = share.dict_search[share.last_row]
except KeyError:
return
color_list = share.list_packet[last_row].getColor()
for i in range(6):
self.tableWidget.item(share.last_row, i).setBackground(QtGui.QColor(
color_list[0][0], color_list[0][1], color_list[0][2]))
share.last_row = row
if (share.flag_search):
row = share.dict_search[row]
color_list = share.list_packet[row].getColor()
for i in range(6):
self.tableWidget.item(share.last_row, i).setBackground(QtGui.QColor(
(color_list[0][0] - 10) % 256, (color_list[0][1] - 10) % 256, (color_list[0][2] - 10) % 256))
if (flag_dict['start'] == False):
pos = QCursor().pos()
if (flag_pyshark):
"""If having pyshark, turn on this feature.
Mouse Entering event for every packet when stopped.
"""
try:
tooltipstr = share.list_TsharkInfo[row]
tooltipstr = tooltipstr.replace('\\xe2\\x86\\x92', '→')
QtWidgets.QToolTip.showText(
pos, textwrap.fill(tooltipstr, 20))
except:
QtWidgets.QToolTip.showText(pos, "Processing")
QtWidgets.QToolTip.setFont(
QFont('Consolas', 10, QFont.Light))
def EvtSelect(self):
"""Event when select a row(packet).
The event for selecting a row(packet), which is to show detailed and
reassembly information about the chosen packet.
"""
QtCore.QCoreApplication.processEvents()
try:
self.continue_reassemble_button.hide()
self.save_reassemble_button.hide()
self.pbar.hide()
except:
pass
for i in self.tableWidget.selectedItems():
val = i.row()
if (share.flag_search == True):
try:
val = share.dict_search[val]
except UnboundLocalError:
return
share.flag_select = True
share.flag_cancel = False
try:
self.val = val