-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1389 lines (1156 loc) · 54.9 KB
/
Copy pathapp.py
File metadata and controls
1389 lines (1156 loc) · 54.9 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
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
# ///////////////////////////////////////////
# ///////// For Dev Only ///////////////
# ///////// By err0rgod ///////////////
# ///////////////////////////////////////////
#Do not modify this file, it is for the developer only. and it may harm the working of the app.
from datetime import datetime
import numpy as np
import plost
import requests
import streamlit as st
import os
import random
from streamlit_folium import folium_static
from folium.plugins import MarkerCluster
import folium
from scapy.all import rdpcap
import collections
import tempfile
import sys
import pandas as pd
from scapy.utils import corrupt_bytes
from streamlit_echarts import st_echarts
import geoip2.database
import pydeck as pdk
import folium
from streamlit_option_menu import option_menu
# from scapy.layers.inet import IP,TCP,UDP,
from utils.pcap_decode import PcapDecode
import time
import plotly.express as px
# from streamlit_pandas_profiling import st_profile_report
# from folium.plugins import HeatMap
PD = PcapDecode() # Parser
PCAPS = None # Packets
if 'uploaded_file' not in st.session_state:
st.session_state.uploaded_file = None
if 'pcap_data' not in st.session_state:
st.session_state.pcap_data = None
def get_all_pcap(PCAPS, PD):
pcaps = collections.OrderedDict()
for count, i in enumerate(PCAPS, 1):
pcaps[count] = PD.ether_decode(i)
return pcaps
def get_filter_pcap(PCAPS, PD, key, value):
pcaps = collections.OrderedDict()
count = 1
for p in PCAPS:
pcap = PD.ether_decode(p)
if key == 'Procotol':
if value == pcap.get('Procotol').upper():
pcaps[count] = pcap
count += 1
else:
pass
elif key == 'Source':
if value == pcap.get('Source').upper():
pcaps[count] = pcap
count += 1
elif key == 'Destination':
if value == pcap.get('Destination').upper():
pcaps[count] = pcap
count += 1
else:
pass
return pcaps
def process_json_data(json_data):
# Convert JSON data to a pandas DataFrame
df = pd.DataFrame.from_dict(json_data, orient='index')
return df
# To Calculate Live Time
def calculate_live_time(pcap_data):
timestamps = [float(packet.time) for packet in pcap_data] # Convert to float
start_time = min(timestamps)
end_time = max(timestamps)
live_time_duration = end_time - start_time
live_time_duration_str = str(pd.Timedelta(seconds=live_time_duration))
return start_time, end_time, live_time_duration, live_time_duration_str
# protocol length statistics
def pcap_len_statistic(PCAPS):
pcap_len_dict = {'0-300': 0, '301-600': 0, '601-900': 0, '901-1200': 0, '1201-1500': 0, '1500-more': 0}
if PCAPS is None:
return pcap_len_dict
for pcap in PCAPS:
pcap_len = len(corrupt_bytes(pcap))
if 0 < pcap_len < 300:
pcap_len_dict['0-300'] += 1
elif 301 <= pcap_len < 600:
pcap_len_dict['301-600'] += 1
elif 601 <= pcap_len < 900:
pcap_len_dict['601-900'] += 1
elif 901 <= pcap_len < 1200:
pcap_len_dict['901-1200'] += 1
elif 1201 <= pcap_len <= 1500:
pcap_len_dict['1201-1500'] += 1
elif pcap_len > 1500:
pcap_len_dict['1500-more'] += 1
else:
pass
return pcap_len_dict
# protocol freq statistics
def common_proto_statistic(PCAPS):
common_proto_dict = collections.OrderedDict()
common_proto_dict['IP'] = 0
common_proto_dict['IPv6'] = 0
common_proto_dict['TCP'] = 0
common_proto_dict['UDP'] = 0
common_proto_dict['ARP'] = 0
common_proto_dict['ICMP'] = 0
common_proto_dict['DNS'] = 0
common_proto_dict['HTTP'] = 0
common_proto_dict['HTTPS'] = 0
common_proto_dict['Others'] = 0
if PCAPS is None:
return common_proto_dict
for pcap in PCAPS:
if pcap.haslayer("IP"):
common_proto_dict['IP'] += 1
elif pcap.haslayer("IPv6"):
common_proto_dict['IPv6'] += 1
if pcap.haslayer("TCP"):
common_proto_dict['TCP'] += 1
elif pcap.haslayer("UDP"):
common_proto_dict['UDP'] += 1
if pcap.haslayer("ARP"):
common_proto_dict['ARP'] += 1
elif pcap.haslayer("ICMP"):
common_proto_dict['ICMP'] += 1
elif pcap.haslayer("DNS"):
common_proto_dict['DNS'] += 1
elif pcap.haslayer("TCP"):
tcp = pcap.getlayer("TCP")
dport = tcp.dport
sport = tcp.sport
if dport == 80 or sport == 80:
common_proto_dict['HTTP'] += 1
elif dport == 443 or sport == 443:
common_proto_dict['HTTPS'] += 1
else:
common_proto_dict['Others'] += 1
elif pcap.haslayer("UDP"):
udp = pcap.getlayer("UDP")
dport = udp.dport
sport = udp.sport
if dport == 5353 or sport == 5353:
common_proto_dict['DNS'] += 1
else:
common_proto_dict['Others'] += 1
elif pcap.haslayer("ICMPv6ND_NS"):
common_proto_dict['ICMP'] += 1
else:
common_proto_dict['Others'] += 1
return common_proto_dict
# maximum protocol statistics
def most_proto_statistic(PCAPS, PD):
protos_list = list()
for pcap in PCAPS:
data = PD.ether_decode(pcap)
protos_list.append(data['Procotol'])
most_count_dict = collections.OrderedDict(collections.Counter(protos_list).most_common(10))
return most_count_dict
# http/https Protocol Statistics
def http_statistic(PCAPS):
http_dict = dict()
for pcap in PCAPS:
if pcap.haslayer("TCP"):
tcp = pcap.getlayer("TCP")
dport = tcp.dport
sport = tcp.sport
ip = None
if dport == 80 or dport == 443:
ip = pcap.getlayer("IP").dst
elif sport == 80 or sport == 443:
ip = pcap.getlayer("IP").src
if ip:
if ip in http_dict:
http_dict[ip] += 1
else:
http_dict[ip] = 1
return http_dict
def https_stats_main(PCAPS):
http_dict = http_statistic(PCAPS)
http_dict = sorted(http_dict.items(),
key=lambda d: d[1], reverse=False)
http_key_list = list()
http_value_list = list()
for key, value in http_dict:
http_key_list.append(key)
http_value_list.append(value)
return http_key_list, http_value_list
# DNS Protocol Statistics
def dns_statistic(PCAPS):
dns_dict = dict()
for pcap in PCAPS:
if pcap.haslayer("DNSQR"):
qname = pcap.getlayer("DNSQR").qname
if qname in dns_dict:
dns_dict[qname] += 1
else:
dns_dict[qname] = 1
return dns_dict
def dns_stats_main(PCAPS):
dns_dict = dns_statistic(PCAPS)
dns_dict = sorted(dns_dict.items(), key=lambda d: d[1], reverse=False)
dns_key_list = list()
dns_value_list = list()
for key, value in dns_dict:
dns_key_list.append(key.decode('utf-8'))
dns_value_list.append(value)
return dns_key_list, dns_value_list
def time_flow(PCAPS):
time_flow_dict = collections.OrderedDict()
start = PCAPS[0].time
time_flow_dict[time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(PCAPS[0].time)))] = len(
corrupt_bytes(PCAPS[0]))
for pcap in PCAPS:
timediff = pcap.time - start
time_flow_dict[float('%.3f' % timediff)] = len(corrupt_bytes(pcap))
return time_flow_dict
def get_host_ip(PCAPS):
ip_list = list()
for pcap in PCAPS:
if pcap.haslayer("IP"):
ip_list.append(pcap.getlayer("IP").src)
ip_list.append(pcap.getlayer("IP").dst)
host_ip = collections.Counter(ip_list).most_common(1)[0][0]
return host_ip
def data_flow(PCAPS, host_ip):
data_flow_dict = {'IN': 0, 'OUT': 0}
for pcap in PCAPS:
if pcap.haslayer("IP"):
if pcap.getlayer("IP").src == host_ip:
data_flow_dict['OUT'] += 1
elif pcap.getlayer("IP").dst == host_ip:
data_flow_dict['IN'] += 1
else:
pass
return data_flow_dict
def data_in_out_ip(PCAPS, host_ip):
in_ip_packet_dict = dict()
in_ip_len_dict = dict()
out_ip_packet_dict = dict()
out_ip_len_dict = dict()
for pcap in PCAPS:
if pcap.haslayer("IP"):
dst = pcap.getlayer("IP").dst
src = pcap.getlayer("IP").src
pcap_len = len(corrupt_bytes(pcap))
if dst == host_ip:
if src in in_ip_packet_dict:
in_ip_packet_dict[src] += 1
in_ip_len_dict[src] += pcap_len
else:
in_ip_packet_dict[src] = 1
in_ip_len_dict[src] = pcap_len
elif src == host_ip:
if dst in out_ip_packet_dict:
out_ip_packet_dict[dst] += 1
out_ip_len_dict[dst] += pcap_len
else:
out_ip_packet_dict[dst] = 1
out_ip_len_dict[dst] = pcap_len
else:
pass
in_packet_dict = in_ip_packet_dict
in_len_dict = in_ip_len_dict
out_packet_dict = out_ip_packet_dict
out_len_dict = out_ip_len_dict
in_packet_dict = sorted(in_packet_dict.items(), key=lambda d: d[1], reverse=False)
in_len_dict = sorted(in_len_dict.items(), key=lambda d: d[1], reverse=False)
out_packet_dict = sorted(out_packet_dict.items(), key=lambda d: d[1], reverse=False)
out_len_dict = sorted(out_len_dict.items(), key=lambda d: d[1], reverse=False)
in_keyp_list = list()
in_packet_list = list()
for key, value in in_packet_dict:
in_keyp_list.append(key)
in_packet_list.append(value)
in_keyl_list = list()
in_len_list = list()
for key, value in in_len_dict:
in_keyl_list.append(key)
in_len_list.append(value)
out_keyp_list = list()
out_packet_list = list()
for key, value in out_packet_dict:
out_keyp_list.append(key)
out_packet_list.append(value)
out_keyl_list = list()
out_len_list = list()
for key, value in out_len_dict:
out_keyl_list.append(key)
out_len_list.append(value)
in_ip_dict = {'in_keyp': in_keyp_list, 'in_packet': in_packet_list, 'in_keyl': in_keyl_list, 'in_len': in_len_list,
'out_keyp': out_keyp_list, 'out_packet': out_packet_list, 'out_keyl': out_keyl_list,
'out_len': out_len_list}
return in_ip_dict
def proto_flow(PCAPS):
proto_flow_dict = collections.OrderedDict()
proto_flow_dict['IP'] = 0
proto_flow_dict['IPv6'] = 0
proto_flow_dict['TCP'] = 0
proto_flow_dict['UDP'] = 0
proto_flow_dict['ARP'] = 0
proto_flow_dict['ICMP'] = 0
proto_flow_dict['DNS'] = 0
proto_flow_dict['HTTP'] = 0
proto_flow_dict['HTTPS'] = 0
proto_flow_dict['Others'] = 0
for pcap in PCAPS:
pcap_len = len(corrupt_bytes(pcap))
if pcap.haslayer("IP"):
proto_flow_dict['IP'] += pcap_len
elif pcap.haslayer("IPv6"):
proto_flow_dict['IPv6'] += pcap_len
if pcap.haslayer("TCP"):
proto_flow_dict['TCP'] += pcap_len
elif pcap.haslayer("UDP"):
proto_flow_dict['UDP'] += pcap_len
if pcap.haslayer("ARP"):
proto_flow_dict['ARP'] += pcap_len
elif pcap.haslayer("ICMP"):
proto_flow_dict['ICMP'] += pcap_len
elif pcap.haslayer("DNS"):
proto_flow_dict['DNS'] += pcap_len
elif pcap.haslayer("TCP"):
tcp = pcap.getlayer("TCP")
dport = tcp.dport
sport = tcp.sport
if dport == 80 or sport == 80:
proto_flow_dict['HTTP'] += pcap_len
elif dport == 443 or sport == 443:
proto_flow_dict['HTTPS'] += pcap_len
else:
proto_flow_dict['Others'] += pcap_len
elif pcap.haslayer("UDP"):
udp = pcap.getlayer("UDP")
dport = udp.dport
sport = udp.sport
if dport == 5353 or sport == 5353:
proto_flow_dict['DNS'] += pcap_len
else:
proto_flow_dict['Others'] += pcap_len
elif pcap.haslayer("ICMPv6ND_NS"):
proto_flow_dict['ICMP'] += pcap_len
else:
proto_flow_dict['Others'] += pcap_len
return proto_flow_dict
def most_flow_statistic(PCAPS, PD):
most_flow_dict = collections.defaultdict(int)
for pcap in PCAPS:
data = PD.ether_decode(pcap)
most_flow_dict[data['Procotol']] += len(corrupt_bytes(pcap))
return most_flow_dict
def getmyip():
try:
headers = {'User-Agent': 'Baiduspider+(+http://www.baidu.com/search/spider.htm'}
ip = requests.get('http://icanhazip.com', headers=headers).text
return ip.strip()
except:
return None
def get_geo(ip):
reader = geoip2.database.Reader('utils/GeoIP/GeoLite2-City.mmdb')
try:
response = reader.city(ip)
# city_name = response.country.names['zh-CN']+response.city.names['zh-CN']
city_name = response.country.names['en'] + response.city.names['en']
longitude = response.location.longitude
latitude = response.location.latitude
return [city_name, longitude, latitude]
except:
return None
def get_ipmap(PCAPS, host_ip):
geo_dict = dict()
ip_value_dict = dict()
ip_value_list = list()
for pcap in PCAPS:
if pcap.haslayer("IP"):
src = pcap.getlayer("IP").src
dst = pcap.getlayer("IP").dst
pcap_len = len(corrupt_bytes(pcap))
if src == host_ip:
oip = dst
else:
oip = src
if oip in ip_value_dict:
ip_value_dict[oip] += pcap_len
else:
ip_value_dict[oip] = pcap_len
for ip, value in ip_value_dict.items():
geo_list = get_geo(ip)
if geo_list:
geo_dict[geo_list[0]] = [geo_list[1], geo_list[2]]
Mvalue = str(float('%.2f' % (value / 1024.0))) + ':' + ip
ip_value_list.append({geo_list[0]: Mvalue})
else:
pass
return [geo_dict, ip_value_list]
# def ipmap(PCAPS):
# myip = getmyip()
# host_ip = get_host_ip(PCAPS)
# ipdata = get_ipmap(PCAPS, host_ip)
# geo_dict = ipdata[0]
# ip_value_list = ipdata[1]
# myip_geo = get_geo(myip)
# ip_value_list = [(list(d.keys())[0], list(d.values())[0])
# for d in ip_value_list]
# # print('ip_value_list', ip_value_list)
# # print('geo_dict', geo_dict)
# # return render_template('./dataanalyzer/ipmap.html', geo_data=geo_dict, ip_value=ip_value_list, mygeo=myip_geo)
# return geo_dict, ip_value_list, myip_geo
def ipmap(PCAPS):
# Assuming these functions are defined elsewhere in your code
myip = getmyip()
host_ip = get_host_ip(PCAPS)
ipdata = get_ipmap(PCAPS, host_ip)
geo_dict = ipdata[0]
ip_value_list = ipdata[1]
myip_geo = get_geo(myip)
ip_value_list = [(list(d.keys())[0], list(d.values())[0]) for d in ip_value_list]
# Create DataFrames from the dictionaries and lists
geo_df = pd.DataFrame(list(geo_dict.items()), columns=['Location', 'Coordinates'])
ip_df = pd.DataFrame(ip_value_list, columns=['Location', 'IP'])
# Check if myip_geo is not None before creating the DataFrame
# if myip_geo is not None:
# myip_geo_df = pd.DataFrame(myip_geo, columns=['MyLocation', 'MyCoordinates'])
#
# # Merge the DataFrames based on the 'Location' column
# merged_df = geo_df.merge(ip_df, on='Location', how='left').merge(myip_geo_df, left_on='Location',
# right_on='MyLocation', how='left')
# else:
# # If myip_geo is None, merge only geo_df and ip_df
merged_df = geo_df.merge(ip_df, on='Location', how='left')
# Split the 'IP' column into 'Numeric_Value' and 'IP_Address'
merged_df[['Data_Traffic', 'IP_Address']] = merged_df['IP'].str.split(':', expand=True)
# Drop the original 'IP' column
merged_df = merged_df.drop('IP', axis=1)
# print("merged_df>>", merged_df)
# Display the merged DataFrame
with st.expander("Geo Data Associated with PCAPs "):
st.write(merged_df)
return merged_df
def page_file_upload():
if "uploaded_file" not in st.session_state or st.session_state.uploaded_file is None:
# File upload with better description
st.markdown("### Upload PCAP File")
st.markdown("Please upload a PCAP (Packet Capture) file for analysis. Supported formats: `.pcap`, `.cap`")
st.info("If you run this app locally, there is no hard 200MB limit from Streamlit. The only limits are your machine RAM and CPU. (Streamlit Cloud may enforce 200MB per file.)")
uploaded_file = st.file_uploader(
"Choose a PCAP file",
type=["pcap", "cap"],
help="Select a PCAP file from any folder on your computer"
)
# Store the uploaded file in session state
st.session_state.uploaded_file = uploaded_file
if uploaded_file is not None:
st.success(f" File uploaded successfully: **{uploaded_file.name}**")
st.info(f" File size: {uploaded_file.size:,} bytes")
# Validate file type
if uploaded_file.name.endswith(('.pcap', '.cap')):
st.success(" Valid PCAP file format detected")
else:
st.warning("️ File extension not recognized as PCAP format")
else:
# Display existing file info
st.info(" **Current uploaded file:**")
st.write(f"**File Name:** {st.session_state.uploaded_file.name}")
st.write(f"**File Size:** {st.session_state.uploaded_file.size:,} bytes")
st.write(f"**File Type:** {st.session_state.uploaded_file.type}")
# Option to delete existing file and upload a new one
col1, col2 = st.columns(2)
with col1:
if st.button("️ Delete Current File"):
st.session_state.uploaded_file = None
st.session_state.pcap_data = None
st.success("File deleted successfully. Please upload a new file.")
st.rerun()
with col2:
if st.button(" Upload New File"):
st.session_state.uploaded_file = None
st.session_state.pcap_data = None
st.success("Ready to upload new file.")
st.rerun()
def page_display_info():
# Display uploaded file information
if st.session_state.get("uploaded_file") is not None:
st.markdown("### File Information")
# Create a nice display of file details
col1, col2, col3 = st.columns(3)
with col1:
st.metric("File Name", st.session_state.uploaded_file.name)
with col2:
st.metric("File Size", f"{st.session_state.uploaded_file.size:,} bytes")
with col3:
st.metric("File Type", st.session_state.uploaded_file.type)
# Show file details in an expander
with st.expander(" Detailed File Information"):
file_details = {
"File Name": st.session_state.uploaded_file.name,
"File Type": st.session_state.uploaded_file.type,
"File Size (bytes)": st.session_state.uploaded_file.size,
"File Size (KB)": round(st.session_state.uploaded_file.size / 1024, 2),
"File Size (MB)": round(st.session_state.uploaded_file.size / (1024 * 1024), 2)
}
st.json(file_details)
def Intro():
# Introduction
st.markdown(
"""
## About Me
I'm **Nirbhay Katiyar**, a passionate programmer and cybersecurity enthusiast. Focused on interconnecting hardware and software with secure coding practices. I love exploring the depths of technology and sharing my knowledge with the community.
This is midstalker analyzer , a sub part of midstalker project focues on analyzing the captured pcap files in very interactive way, one can't imagine. more is awaited to be added on this framework if you face any issues or wanted to give a feedback you can connect with me on any of my Socials.
[**GitHub**](https://github.com/err0rgod) — where my experiments turn into weapons-grade tools.
### Tagline
*“Every packet hides a story. I give you the tools to decode it.”*
### Connect with Me
"""
)
# Add social media links using Streamlit components (outside of markdown)
col1, col2, col3, col4 = st.columns(4)
with col1:
st.markdown(
f'<a href="https://www.linkedin.com/in/nirbhay-katiyar-904b86358/" target="_blank">'
f'<img src="https://img.shields.io/badge/LinkedIn-0077B5?style=for-the-badge&logo=linkedin&logoColor=white" alt="LinkedIn">'
f'</a>',
unsafe_allow_html=True
)
with col2:
st.markdown(
f'<a href="https://www.instagram.com/err0rgod" target="_blank">'
f'<img src="https://img.shields.io/badge/Instagram-E4405F?style=for-the-badge&logo=instagram&logoColor=white" alt="Instagram">'
f'</a>',
unsafe_allow_html=True
)
with col3:
st.markdown(
f'<a href="https://github.com/err0rgod" target="_blank">'
f'<img src="https://img.shields.io/badge/GitHub-100000?style=for-the-badge&logo=github&logoColor=white" alt="GitHub">'
f'</a>',
unsafe_allow_html=True
)
with col4:
st.markdown(
f'<a href="https://err0rgod.medium.com/" target="_blank">'
f'<img src="https://img.shields.io/badge/Medium-12100E?style=for-the-badge&logo=medium&logoColor=white" alt="Medium">'
f'</a>',
unsafe_allow_html=True
)
# Continue with the rest of the content
st.markdown(
"""
## What is MidStalker?
MidStalker is a Networking Framework for Offensive & Deffensive approach (Red/Blue team) It helps the User from getting the network packets from the network of the all hosts and after that also
able to perform more actions like DNS spoof , Vulnerebilty scanning if any bug exist it will inform you and more. But what are you seeing here on this website is the part of the Framework
it helps up analyzing the captured pcap files in very interactive way, one can't imagine. more is awaited to be added on this framework if you face any issues or wanted to give a feedback you
can connect with me on any of my Socials.
## What is a PCAP file?
A PCAP file (Packet Capture) is a binary file that stores network traffic data. It records the details of
each packet, such as source and destination addresses, protocol, and payload. PCAP files are widely used by
network administrators, security professionals, and researchers to analyze network behavior.
## Importance in Cybersecurity
PCAP files play a vital role in cybersecurity for several reasons:
- **Network Traffic Analysis:** Analyzing PCAP files helps detect anomalies, identify patterns, and
understand network behavior.
- **Incident Response:** In the event of a security incident, PCAP files can be instrumental in
reconstructing the sequence of events and identifying the root cause.
- **Forensic Investigations:** PCAP files provide a detailed record of network activity, aiding in
forensic investigations to determine the source and impact of security incidents.
Explore the capabilities of PCAP analysis tools to enhance your understanding of network traffic and
strengthen cybersecurity practices.
"""
)
def RawDataView():
# Check if a file has been uploaded
if "uploaded_file" not in st.session_state or st.session_state.uploaded_file is None:
st.warning("️ **No file uploaded!** Please go to the 'Upload File' section and upload a PCAP file first.")
st.info(" After uploading a file, you can view and filter the raw packet data here.")
return
uploaded_file = st.session_state.uploaded_file
if uploaded_file is not None:
# Check if the uploaded file is a PCAP file
if uploaded_file.type == "application/octet-stream" or uploaded_file.name.endswith(('.pcap', '.cap')):
try:
# Process the uploaded PCAP file - use BytesIO to handle in-memory file
import io
from scapy.utils import PcapReader
# Reset file pointer to beginning
uploaded_file.seek(0)
# Read the uploaded file content
file_content = uploaded_file.read()
# Create BytesIO object for Scapy
file_buffer = io.BytesIO(file_content)
# Use PcapReader to read from memory buffer
pcap_data = rdpcap(file_buffer)
st.session_state.pcap_data = pcap_data
# Example: Get all PCAPs
all_data = get_all_pcap(pcap_data, PD)
dataframe_data = process_json_data(all_data)
start_time, end_time, live_time_duration, live_time_duration_str = calculate_live_time(pcap_data)
# Show success message with packet count
st.success(f" **File processed successfully!** Found {len(pcap_data)} packets in the PCAP file.")
st.info(f" **Analysis Summary:**")
st.info(f" • Total packets: {len(pcap_data):,}")
st.info(f" • Time duration: {live_time_duration_str}")
st.info(f" • File size: {uploaded_file.size:,} bytes")
except Exception as e:
st.error(f" **Error processing PCAP file:** {str(e)}")
st.error("Please make sure you uploaded a valid PCAP file.")
return
# Add live time information to the data frame
# dataframe_data['Start Time'] = start_time
# dataframe_data['End Time'] = end_time
dataframe_data['Live Time Duration'] = live_time_duration_str
all_columns = list(dataframe_data.columns)
st.sidebar.header("P1ease Filter Here:")
# st.sidebar.divider()
# Filter reset button
if st.sidebar.button(" Reset All Filters"):
# Clear session state for filters
if 'filter_protocols' in st.session_state:
del st.session_state.filter_protocols
if 'filter_length' in st.session_state:
del st.session_state.filter_length
if 'filter_source' in st.session_state:
del st.session_state.filter_source
if 'filter_destination' in st.session_state:
del st.session_state.filter_destination
st.success(" All filters have been reset!")
st.rerun()
# Multiselect for filtering by protocol
selected_protocols = st.sidebar.multiselect(
"Select Protocol:",
options=dataframe_data["Procotol"].unique(),
default=None,
key="filter_protocols"
)
# st.sidebar.divider()
# Sidebar slider for filtering by length
filter_value_len = st.sidebar.slider(
"Filter by Packet Length",
min_value=min(dataframe_data["len"]),
max_value=max(dataframe_data["len"]),
value=(min(dataframe_data["len"]), max(dataframe_data["len"])),
key="filter_length"
)
# st.sidebar.divider()
# Sidebar text input for filtering by Source
filter_source = st.sidebar.text_input("Filter by Source IP:", "", key="filter_source")
# st.sidebar.divider()
# Sidebar text input for filtering by Destination
filter_destination = st.sidebar.text_input("Filter by Destination IP:", "", key="filter_destination")
# st.sidebar.divider()
# Apply filters based on user selection
if (
selected_protocols is None or not selected_protocols) and not filter_value_len and not filter_source and not filter_destination:
st.write("All PCAPs:")
Data_to_display_df = dataframe_data.copy()
st.dataframe(Data_to_display_df, use_container_width=True)
else:
# Apply filters based on user input
# Filter by protocol
if selected_protocols is not None and selected_protocols:
Data_to_display_df = dataframe_data[dataframe_data["Procotol"].isin(selected_protocols)]
else:
Data_to_display_df = dataframe_data
# Filter by length
Data_to_display_df = Data_to_display_df[
(Data_to_display_df["len"] >= filter_value_len[0]) & (
Data_to_display_df["len"] <= filter_value_len[1])
]
# Filter by Source
if filter_source:
Data_to_display_df = Data_to_display_df[
Data_to_display_df["Source"].str.contains(filter_source, case=False, na=False)]
# Filter by Destination
if filter_destination:
Data_to_display_df = Data_to_display_df[
Data_to_display_df["Destination"].str.contains(filter_destination, case=False, na=False)]
# Display the filtered dataframe
st.write("Filtered PCAPs:")
column_check = st.checkbox("Do you want to filter the data by column wise also ???")
if column_check:
# Multiselect for filtering by columns
selected_columns = st.multiselect(
"Select Columns to Display:",
options=all_columns, default=all_columns
)
Data_to_display_df = Data_to_display_df[selected_columns]
# selected_columns = [col for col in Data_to_display_df.columns if st.checkbox(col, value=True )]
st.checkbox("Use container width", value=True, key="use_container_width")
# Safely get the checkbox value with a default
use_container_width = st.session_state.get("use_container_width", True)
st.dataframe(Data_to_display_df, use_container_width=use_container_width)
st.subheader("Statistics of Selected Data")
# Time Analysis
Data_to_display_df['time'] = pd.to_datetime(Data_to_display_df['time'])
st.subheader("Time Range:")
st.write("Earliest timestamp:", Data_to_display_df['time'].min())
st.write("Latest timestamp:", Data_to_display_df['time'].max())
st.write("Duration:", Data_to_display_df['time'].max() - Data_to_display_df['time'].min())
####################################
col1, col2 = st.columns(2)
# Column 1: Packet Length Statistics
with col1:
st.subheader("Packet Length Statistics:")
st.table(Data_to_display_df['len'].describe())
# Source Counts
source_counts = Data_to_display_df['Source'].value_counts()
st.subheader("Source Counts:")
st.table(source_counts)
# Column 2: Protocol Distribution and Destination Counts
with col2:
# Protocol Distribution
protocol_counts = Data_to_display_df['Procotol'].value_counts(normalize=True)
st.subheader("Protocol Distribution:")
st.table(protocol_counts)
# Destination Counts
destination_counts = Data_to_display_df['Destination'].value_counts()
st.subheader("Destination Counts:")
st.table(destination_counts)
#####################################
else:
st.warning("Please upload a valid PCAP file.")
def DataPacketLengthStatistics(data):
# st.write("Data Packet Length Statistics")
data1 = {'pcap_len': list(data.keys()), 'count': list(data.values())}
df1 = pd.DataFrame(data1)
options = {
"title": {"text": "Data Packet Length Statistics", "subtext": "", "left": "center"},
"tooltip": {"trigger": "item"},
"legend": {"orient": "vertical", "left": "left", },
"series": [
{
"name": "Packets",
"type": "pie",
"radius": "50%",
"data": [
{"value": count, "name": pcap_len}
for pcap_len, count in zip(df1['pcap_len'], df1['count'])
],
"emphasis": {
"itemStyle": {
"shadowBlur": 10,
"shadowOffsetX": 0,
"shadowColor": "rgba(0, 0, 0, 0.5)",
}
},
}
],
"backgroundColor": "rgba(0, 0, 0, 0)", # Transparent background
}
# st.write("Data Packet Length Statistics")
st_echarts(options=options, height="600px", renderer='svg')
def CommonProtocolStatistics(data):
st.write("Common Protocol Statistics")
data2 = {'protocol_type': list(data.keys()),
'number_of_packets': list(data.values())}
df2 = pd.DataFrame(data2)
# plost.bar_chart(data=df2, bar='protocol_type', value='number_of_packets')
options = {
"xAxis": {
"type": "category",
"data": df2.protocol_type.tolist(),
},
"yAxis": {"type": "value"},
"series": [{"data": df2.number_of_packets.tolist(), "type": "bar"}],
}
st_echarts(options=options, height="500px")
def CommonProtocolStatistics_ploty(data):
# st.write('Common Protocol Statistics')
data2 = {'protocol_type': list(data.keys()),
'number_of_packets': list(data.values())}
df2 = pd.DataFrame(data2)
fig = px.bar(df2, x='protocol_type', y='number_of_packets',color="protocol_type",title="Common Protocol Statistics")
fig.update_layout(title_x=0.5)
st.plotly_chart(fig)
def MostFrequentProtocolStatistics(data):
# st.write("Data Packet Length Statistics")
data3 = {'protocol_type': list(data.keys()), 'freq': list(data.values())}
df3 = pd.DataFrame(data3)
options = {
"title": {"text": "Most Frequent Protocol Statistics", "subtext": "", "left": "center"},
"tooltip": {"trigger": "item"},
"legend": {"orient": "vertical", "left": "left", },
"series": [
{
"name": "Packets",
"type": "pie",
"radius": "50%",
"data": [
{"value": count, "name": pcap_len}
for pcap_len, count in zip(df3['protocol_type'], df3['freq'])
],
"emphasis": {
"itemStyle": {
"shadowBlur": 10,
"shadowOffsetX": 0,
"shadowColor": "rgba(0, 0, 0, 0.5)",
}
},
}
],
"backgroundColor": "rgba(0, 0, 0, 0)", # Transparent background
}
# st.write("Data Packet Length Statistics")
st_echarts(options=options, height="600px", renderer='svg')
def HTTP_HTTPSAccessStatistics(key,value):
# st.write("HTTP/HTTPS Access Statistics")
data4 = {'HTTP/HTTPS key': list(key),
'HTTP/HTTPS value': list(value)}
df4 = pd.DataFrame(data4)
fig = px.bar(df4, x='HTTP/HTTPS key', y='HTTP/HTTPS value',color="HTTP/HTTPS key",title="HTTP/HTTPS Access Statistics")
fig.update_layout(title_x=0.5)
st.plotly_chart(fig)
def DNSAccessStatistics(key, value):
# st.write("DNS Access Statistics")
data5 = {'dns_key': list(key),
'dns_value': list(value)}
df5 = pd.DataFrame(data5)
fig = px.bar(df5, x='dns_key', y='dns_value', color="dns_key",title="DNS Access Statistics")
fig.update_layout(title_x=0.5)
st.plotly_chart(fig)
def TimeFlowChart(data):
data6 = {'Relative_Time': list(data.keys()), 'Packet_Bytes': list(data.values())}
df6 = pd.DataFrame(data6)
fig = px.line(df6, x='Relative_Time', y="Packet_Bytes",title="Time Flow Chart")
fig.update_layout(title_x=0.5)
st.plotly_chart(fig)
def DataInOutStatistics(data):
# st.write("Data In/Out Statistics")
data7 = {'In/Out': list(data.keys()), 'freq': list(data.values())}
df7 = pd.DataFrame(data7)
options = {
"title": {"text": "Data In/Out Statistics", "subtext": "", "left": "center"},
"tooltip": {"trigger": "item"},
"legend": {"orient": "vertical", "left": "left", },
"series": [