-
Notifications
You must be signed in to change notification settings - Fork 4
/
multicapconverter.py
executable file
·1804 lines (1736 loc) · 70.8 KB
/
multicapconverter.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "Abdelhafidh Belalia (s77rt)"
__credits__ = ['Jens Steube <[email protected]>', 'Philipp "philsmd" Schmidt <[email protected]>', 'ZerBea (https://github.com/ZerBea)', 'RealEnder (https://github.com/RealEnder)']
__license__ = "MIT"
__maintainer__ = "Abdelhafidh Belalia (s77rt)"
__email__ = "[email protected]"
__version__ = "0.1.6"
__github__ = "https://github.com/s77rt/multicapconverter/"
import os
import sys
import argparse
import struct
import errno
import re
import gzip
from collections import namedtuple
from operator import itemgetter
from itertools import groupby, islice
from enum import Enum
from multiprocessing import Process, Manager
### Endianness ###
if sys.byteorder == "big":
BIG_ENDIAN_HOST = True
xprint("WARNING! Endianness is not well tested on BIG_ENDIAN_HOST!")
else:
BIG_ENDIAN_HOST = False
###
### WBIT ###
def WBIT(n):
return (1 << (n))
###
### Constants ###
HCCAPX_VERSION = 4
HCCAPX_SIGNATURE = 0x58504348 # HCPX
HCWPAX_SIGNATURE = "WPA"
TCPDUMP_MAGIC = 0xa1b2c3d4
TCPDUMP_CIGAM = 0xd4c3b2a1
PCAPNG_MAGIC = 0x1A2B3C4D
PCAPNG_CIGAM = 0xD4C3B2A1
TCPDUMP_DECODE_LEN = 65535
DLT_NULL = 0 # BSD loopback encapsulation
DLT_EN10MB = 1 # Ethernet (10Mb)
DLT_EN3MB = 2 # Experimental Ethernet (3Mb)
DLT_AX25 = 3 # Amateur Radio AX.25
DLT_PRONET = 4 # Proteon ProNET Token Ring
DLT_CHAOS = 5 # Chaos
DLT_IEEE802 = 6 # IEEE 802 Networks
DLT_ARCNET = 7 # ARCNET, with BSD-style header
DLT_SLIP = 8 # Serial Line IP
DLT_PPP = 9 # Point-to-point Protocol
DLT_FDDI = 10 # FDDI
DLT_RAW = 12 # Raw headers (no link layer)
DLT_RAW2 = 14
DLT_RAW3 = 101
DLT_IEEE802_11 = 105 # IEEE 802.11 wireless
DLT_IEEE802_11_PRISM = 119
DLT_IEEE802_11_RADIO = 127
DLT_IEEE802_11_PPI_HDR = 192
IEEE80211_FCTL_FTYPE = 0x000c
IEEE80211_FCTL_STYPE = 0x00f0
IEEE80211_FCTL_TODS = 0x0100
IEEE80211_FCTL_FROMDS = 0x0200
IEEE80211_FTYPE_MGMT = 0x0000
IEEE80211_FTYPE_DATA = 0x0008
IEEE80211_STYPE_ASSOC_REQ = 0x0000
IEEE80211_STYPE_ASSOC_RESP = 0x0010
IEEE80211_STYPE_REASSOC_REQ = 0x0020
IEEE80211_STYPE_REASSOC_RESP = 0x0030
IEEE80211_STYPE_PROBE_REQ = 0x0040
IEEE80211_STYPE_PROBE_RESP = 0x0050
IEEE80211_STYPE_BEACON = 0x0080
IEEE80211_STYPE_QOS_DATA = 0x0080
IEEE80211_STYPE_ATIM = 0x0090
IEEE80211_STYPE_DISASSOC = 0x00A0
IEEE80211_STYPE_AUTH = 0x00B0
IEEE80211_STYPE_DEAUTH = 0x00C0
IEEE80211_STYPE_ACTION = 0x00D0
IEEE80211_LLC_DSAP = 0xAA
IEEE80211_LLC_SSAP = 0xAA
IEEE80211_LLC_CTRL = 0x03
IEEE80211_DOT1X_AUTHENTICATION = 0x8E88
MFIE_TYPE_SSID = 0
MFIE_TYPE_RATES = 1
MFIE_TYPE_FH_SET = 2
MFIE_TYPE_DS_SET = 3
MFIE_TYPE_CF_SET = 4
MFIE_TYPE_TIM = 5
MFIE_TYPE_IBSS_SET = 6
MFIE_TYPE_CHALLENGE = 16
MFIE_TYPE_ERP = 42
MFIE_TYPE_RSN = 48
MFIE_TYPE_RATES_EX = 50
MFIE_TYPE_GENERIC = 221
SIZE_OF_pcap_pkthdr_t = 16
SIZE_OF_pcap_file_header_t = 24
SIZE_OF_prism_header_t = 144
SIZE_OF_ieee80211_radiotap_header_t = 8
SIZE_OF_ppi_packet_header_t = 8
SIZE_OF_ieee80211_hdr_3addr_t = 24
SIZE_OF_ieee80211_qos_hdr_t = 26
SIZE_OF_beacon_t = 12
SIZE_OF_assocreq_t = 4
SIZE_OF_reassocreq_t = 10
SIZE_OF_ieee80211_llc_snap_header_t = 8
SIZE_OF_auth_packet_t = 99
SIZE_OF_EAPOL = 256
BROADCAST_MAC = b'\xff\xff\xff\xff\xff\xff'
MAX_ESSID_LEN = 32
EAPOL_TTL = 1
TEST_REPLAYCOUNT = 0
ZERO = (0,)
WPA_KEY_INFO_TYPE_MASK = (WBIT(0) | WBIT(1) | WBIT(2))
WPA_KEY_INFO_TYPE_HMAC_MD5_RC4 = WBIT(0)
WPA_KEY_INFO_TYPE_HMAC_SHA1_AES = WBIT(1)
WPA_KEY_INFO_KEY_TYPE = WBIT(3) # 1 = Pairwise, 0 = Group key
WPA_KEY_INFO_KEY_INDEX_MASK = (WBIT(4) | WBIT(5))
WPA_KEY_INFO_KEY_INDEX_SHIFT = 4
WPA_KEY_INFO_INSTALL = WBIT(6) # pairwise
WPA_KEY_INFO_TXRX = WBIT(6) # group
WPA_KEY_INFO_ACK = WBIT(7)
WPA_KEY_INFO_MIC = WBIT(8)
WPA_KEY_INFO_SECURE = WBIT(9)
WPA_KEY_INFO_ERROR = WBIT(10)
WPA_KEY_INFO_REQUEST = WBIT(11)
WPA_KEY_INFO_ENCR_KEY_DATA = WBIT(12) # IEEE 802.11i/RSN only
ESSID_SOURCE_USER = 1
ESSID_SOURCE_REASSOC = 2
ESSID_SOURCE_ASSOC = 3
ESSID_SOURCE_PROBE = 4
ESSID_SOURCE_DIRECTED_PROBE = 5
ESSID_SOURCE_BEACON = 6
EXC_PKT_NUM_1 = 1
EXC_PKT_NUM_2 = 2
EXC_PKT_NUM_3 = 3
EXC_PKT_NUM_4 = 4
MESSAGE_PAIR_M12E2 = 0
MESSAGE_PAIR_M14E4 = 1
MESSAGE_PAIR_M32E2 = 2
MESSAGE_PAIR_M32E3 = 3
MESSAGE_PAIR_M34E3 = 4
MESSAGE_PAIR_M34E4 = 5
MESSAGE_PAIR_APLESS = 0b00010000
MESSAGE_PAIR_LE = 0b00100000
MESSAGE_PAIR_BE = 0b01000000
MESSAGE_PAIR_NC = 0b10000000
Interface_Description_Block = 0x00000001
Packet_Block = 0x00000002
Simple_Packet_Block = 0x00000003
Name_Resolution_Block = 0x00000004
Interface_Statistics_Block = 0x00000005
Enhanced_Packet_Block = 0x00000006
IRIG_Timestamp_Block = 0x00000007
Arinc_429_in_AFDX_Encapsulation_Information_Block = 0x00000008
Section_Header_Block = 0x0A0D0D0A
Custom_Block = 0x0000000bad
Custom_Option_Codes = [2988, 2989, 19372, 19373]
if_tsresol_code = 9
opt_endofopt = 0
HCXDUMPTOOL_PEN = 0x2a, 0xce, 0x46, 0xa1
HCXDUMPTOOL_MAGIC_NUMBER = 0x2a, 0xce, 0x46, 0xa1, 0x79, 0xa0, 0x72, 0x33, 0x83, 0x37, 0x27, 0xab, 0x59, 0x33, 0xb3, 0x62, 0x45, 0x37, 0x11, 0x47, 0xa7, 0xcf, 0x32, 0x7f, 0x8d, 0x69, 0x80, 0xc0, 0x89, 0x5e, 0x5e, 0x98
HCXDUMPTOOL_OPTIONCODE_MACAP = 0xf29b
HCXDUMPTOOL_OPTIONCODE_RC = 0xf29c
HCXDUMPTOOL_OPTIONCODE_ANONCE = 0xf29d
HCXDUMPTOOL_OPTIONCODE_MACCLIENT = 0xf29e
HCXDUMPTOOL_OPTIONCODE_SNONCE = 0xf29f
HCXDUMPTOOL_OPTIONCODE_WEAKCANDIDATE = 0xf2a0
HCXDUMPTOOL_OPTIONCODE_NMEA = 0xf2a1
SUITE_OUI = 0x00, 0x0f, 0xac
CS_WEP40 = 1
CS_TKIP = 2
CS_WRAP = 3
CS_CCMP = 4
CS_WEP104 = 5
CS_BIP = 6
CS_NOT_ALLOWED = 7
AK_PMKSA = 1
AK_PSK = 2
AK_FT = 3
AK_FT_PSK = 4
AK_PMKSA256 = 5
AK_PSKSHA256 = 6
AK_TDLS = 7
AK_SAE_SHA256 = 8
AK_FT_SAE = 9
DB_ESSID_MAX = 50000
DB_EXCPKT_MAX = 100000
MAX_WORK_PER_PROCESS = 100
CHUNK_SIZE = 8192
# Log Levels
INFO = 10
WARNING = 20
ERROR = 30
CRITICAL = 40
DEBUG = 50
###
### Structures-Like ###
pcap_file_header_t = namedtuple( \
'pcap_file_header', '\
magic \
version_major \
version_minor \
thiszone \
sigfigs \
snaplen \
linktype \
')
pcap_pkthdr_t = namedtuple( \
'pcap_pkthdr', '\
tv_sec \
tv_usec \
caplen \
len \
')
ieee80211_hdr_3addr_t = namedtuple( \
'ieee80211_hdr_3addr', '\
frame_control \
duration_id \
addr1 \
addr2 \
addr3 \
seq_ctrl \
')
ieee80211_qos_hdr_t = namedtuple( \
'ieee80211_qos_hdr', '\
frame_control \
duration_id \
addr1 \
addr2 \
addr3 \
seq_ctrl \
qos_ctrl \
')
ieee80211_llc_snap_header_t = namedtuple( \
'ieee80211_llc_snap_header', '\
dsap \
ssap \
ctrl \
oui \
ethertype \
')
prism_item_t = namedtuple( \
'prism_item', '\
did \
status \
len \
data \
')
prism_header_t = namedtuple( \
'prism_header', '\
msgcode \
msglen \
devname \
hosttime \
mactime \
channel \
rssi \
sq \
signal \
noise \
rate \
istx \
frmlen \
')
ieee80211_radiotap_header_t = namedtuple( \
'ieee80211_radiotap_header', '\
it_version \
it_pad \
it_len \
it_present \
')
ppi_packet_header_t = namedtuple( \
'ppi_packet_header', '\
pph_version \
pph_flags \
pph_len \
pph_dlt \
')
beacon_t = namedtuple( \
'beaconinfo', '\
beacon_timestamp \
beacon_interval \
beacon_capabilities \
')
assocreq_t = namedtuple( \
'associationreqf', '\
client_capabilities \
client_listeninterval \
')
reassocreq_t = namedtuple( \
'reassociationreqf', '\
client_capabilities \
client_listeninterval \
addr \
')
auth_packet_t = namedtuple( \
'auth_packet', '\
version \
type \
length \
key_descriptor \
key_information \
key_length \
replay_counter \
wpa_key_nonce \
wpa_key_iv \
wpa_key_rsc \
wpa_key_id \
wpa_key_mic \
wpa_key_data_length \
')
hccapx_t = namedtuple( \
'hccapx', '\
signature \
version \
message_pair \
essid_len \
essid \
keyver \
keymic \
mac_ap \
nonce_ap \
mac_sta \
nonce_sta \
eapol_len \
eapol \
')
pcapng_general_block_structure = namedtuple( \
'pcapng_general_block', '\
block_type \
block_total_length \
block_body \
block_total_length_2 \
')
###
### LOGGER ###
class l_messages(dict):
def log(self, key, value=1):
"""
key => message
value => counter of message
"""
if key not in self:
dict.__setitem__(self, key, value)
else:
self[key] += value
class Logger(object):
def __init__(self):
super(Logger, self).__init__()
self.info = l_messages()
self.warning = l_messages()
self.error = l_messages()
self.critical = l_messages()
self.debug = l_messages()
def log(self, message, level):
if level >= DEBUG:
self.debug.log(message)
elif level >= CRITICAL:
self.critical.log(message)
elif level >= ERROR:
self.error.log(message)
elif level >= WARNING:
self.warning.log(message)
else:
self.info.log(message)
LOGGER = Logger()
###
### H-Functions ###
def byte_swap_16(n):
return (n & 0xff00) >> 8 \
| (n & 0x00ff) << 8
def byte_swap_32(n):
return (n & 0xff000000) >> 24 \
| (n & 0x00ff0000) >> 8 \
| (n & 0x0000ff00) << 8 \
| (n & 0x000000ff) << 24
def byte_swap_64(n):
return (n & 0xff00000000000000) >> 56 \
| (n & 0x00ff000000000000) >> 40 \
| (n & 0x0000ff0000000000) >> 24 \
| (n & 0x000000ff00000000) >> 8 \
| (n & 0x00000000ff000000) << 8 \
| (n & 0x0000000000ff0000) << 24 \
| (n & 0x000000000000ff00) << 40 \
| (n & 0x00000000000000ff) << 56
def to_signed_32(n):
n = n & 0xffffffff
return (n ^ 0x80000000) - 0x80000000
def pymemcpy(src, count):
dest = src[:count]
if isinstance(dest, bytes):
dest += b'\x00'*(count - len(dest))
elif isinstance(dest, (list,tuple)):
dest += (0,)*(count - len(dest))
if len(dest) != count:
LOGGER.log('pymemcpy failed', ERROR)
raise ValueError('pymemcpy failed')
return dest
#
def get_valid_bssid(bssid):
bssid = bssid.lower()
bssid = re.match("[0-9a-f]{2}([-:]?)[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$", bssid)
if bssid:
return bssid[0].replace(':', '').replace('-', '')
def get_valid_filename(s, r='_'):
s = str(s).strip().replace(' ', '_')
return re.sub(r'(?u)[^-\w.\@]', r, s)
def xprint(text="", end='\n', flush=True):
print(text, end=end, flush=flush)
###
### Database-Like ###
## Tables:
class essids(dict):
def __setitem__(self, key, value):
if key not in self:
dict.__setitem__(self, key, value)
elif value['essid_source'] > self[key]['essid_source']:
self[key]['essid_source'] = value['essid_source']
class excpkts(dict):
def __setitem__(self, key, value):
if key not in self:
dict.__setitem__(self, key, value)
else:
subkey = list(value.keys())[0]
if subkey not in self[key]:
self[key].__setitem__(subkey, list(value.values())[0])
else:
subsubkey = list(list(value.values())[0].keys())[0]
if subsubkey not in self[key][subkey]:
self[key][subkey].__setitem__(subsubkey, list(list(value.values())[0].values())[0])
else:
self[key][subkey][subsubkey].append(list(list(value.values())[0].values())[0][0])
class hccapxs(list):
def __init__(self):
list.__init__(self)
class hcwpaxs(dict):
def __setitem__(self, key, value):
if key not in self:
dict.__setitem__(self, key, value)
class hcpmkids(dict):
def __setitem__(self, key, value):
if key not in self:
dict.__setitem__(self, key, value)
class pmkids(dict):
def __setitem__(self, key, value):
if key not in self:
dict.__setitem__(self, key, value)
else:
self[key]['pmkid'] = value['pmkid']
class pcapng_info(dict):
def __setitem__(self, key, value):
if key not in self:
dict.__setitem__(self, key, [value])
else:
self[key].append(value)
## Database:
class Database(object):
def __init__(self):
super(Database, self).__init__()
self.essids = essids()
self.excpkts = excpkts()
self.hccapxs = hccapxs()
self.hcwpaxs = hcwpaxs()
self.hcpmkids = hcpmkids()
self.pmkids = pmkids()
self.pcapng_info = pcapng_info()
def essid_add(self, bssid, essid, essid_len, essid_source):
if len(self.essids) == DB_ESSID_MAX:
LOGGER.log('DB_ESSID_MAX Exceeded!', CRITICAL)
raise ValueError('DB_ESSID_MAX Exceeded!')
if essid_len == 0 or not essid:
return
key = pymemcpy(bssid, 6)
self.essids.__setitem__(key, {
'bssid': pymemcpy(bssid, 6),
'essid': essid,
'essid_len': essid_len,
'essid_source': essid_source
})
def excpkt_add(self, excpkt_num, tv_sec, tv_usec, replay_counter, mac_ap, mac_sta, nonce, eapol_len, eapol, keyver, keymic):
if len(self.excpkts) == DB_EXCPKT_MAX:
LOGGER.log('DB_EXCPKT_MAX Exceeded!', CRITICAL)
raise ValueError('DB_EXCPKT_MAX Exceeded!')
key = pymemcpy(mac_ap, 6)
subkey = pymemcpy(mac_sta, 6)
subsubkey = 'ap' if excpkt_num in [EXC_PKT_NUM_1, EXC_PKT_NUM_3] else 'sta'
check = self.excpkts.get(key, {}).get(subkey, {}).get(subsubkey, {})
for c in check:
if c['eapol'] == eapol or (c['nonce'] == nonce and c['keymic'] == keymic):
return
self.excpkts.__setitem__(key, {subkey: {subsubkey: [{
'excpkt_num': excpkt_num,
'tv_sec': tv_sec,
'tv_usec': tv_usec,
'replay_counter': replay_counter,
'mac_ap': pymemcpy(mac_ap, 6),
'mac_sta': pymemcpy(mac_sta, 6),
'nonce': pymemcpy(nonce, 32),
'eapol_len': eapol_len,
'eapol': eapol,
'keyver': keyver,
'keymic': keymic
}]}})
def hccapx_add(self, bssid, essid, raw_data):
self.hccapxs.append({ \
'bssid': bssid, \
'essid': essid, \
'raw_data': raw_data \
})
def hccapx_groupby(self, group_by):
if group_by is None or group_by == "none":
self.hccapxs = [{'key': 'none', 'raw_data': [v['raw_data'] for v in self.hccapxs]}]
elif group_by == "handshake":
self.hccapxs = [{'key': v['bssid']+"_"+str(k), 'raw_data': [v['raw_data']]} for k, v in enumerate(self.hccapxs)]
else:
self.hccapxs.sort(key=itemgetter(group_by))
self.hccapxs = groupby(self.hccapxs, key=itemgetter(group_by))
self.hccapxs = [{'key': k, 'raw_data': [x['raw_data'] for x in v]} for k, v in self.hccapxs]
def hcwpaxs_add(self, signature, ftype, pmkid_or_mic, mac_ap, mac_sta, essid, anonce=None, eapol=None, message_pair=None):
if ftype == "01":
key = pmkid_or_mic
self.hcwpaxs.__setitem__(key, { \
'signature': signature, \
'type': ftype, \
'pmkid_or_mic': pmkid_or_mic, \
'mac_ap': mac_ap, \
'mac_sta': mac_sta, \
'essid': bytes(essid).hex(), \
'anonce': '', \
'eapol': '', \
'message_pair': '' \
})
else:
key = hash((pmkid_or_mic, message_pair))
self.hcwpaxs.__setitem__(key, { \
'signature': signature, \
'type': ftype, \
'pmkid_or_mic': bytes(pmkid_or_mic).hex(), \
'mac_ap': bytes(mac_ap).hex(), \
'mac_sta': bytes(mac_sta).hex(), \
'essid': bytes(essid).hex(), \
'anonce': bytes(anonce).hex(), \
'eapol': bytes(eapol).hex(), \
'message_pair': '{:02x}'.format(message_pair) \
})
def hcpmkid_add(self, pmkid, mac_ap, mac_sta, essid):
key = pmkid
self.hcpmkids.__setitem__(key, { \
'pmkid': pmkid, \
'mac_ap': mac_ap, \
'mac_sta': mac_sta, \
'essid': bytes(essid).hex() \
})
def pmkid_add(self, mac_ap, mac_sta, pmkid, akm):
key = hash(mac_ap+mac_sta)
self.pmkids.__setitem__(key, {
'mac_ap': bytes(mac_ap).hex(),
'mac_sta': bytes(mac_sta).hex(),
'pmkid': pmkid,
'akm': akm
})
def pcapng_info_add(self, key, info):
self.pcapng_info.__setitem__(key, info)
DB = Database()
###
### STATUS ###
class Status(object):
def __init__(self):
super(Status, self).__init__()
self.total_filesize = 0
self.current_filepos = 0
self.current_packet = 0
def set_filesize(self, filesize):
self.total_filesize = filesize
def step_packet(self):
self.current_packet += 1
def set_filepos(self, filepos):
self.current_filepos = filepos
STATUS = Status()
###
### HX-Functions ###
def get_essid_from_tag(packet, header, length_skip):
if length_skip > header['caplen']:
return -1, None
length = header['caplen'] - length_skip
beacon = packet[length_skip:length_skip+length]
cur = 0
end = len(beacon)
while cur < end:
if (cur + 2) >= end:
break
tagtype = beacon[cur]
cur += 1
taglen = beacon[cur]
cur += 1
if (cur + taglen) >= end:
break
if tagtype == MFIE_TYPE_SSID:
if taglen < MAX_ESSID_LEN:
essid = {}
essid['essid'] = pymemcpy(beacon[cur:cur+taglen], MAX_ESSID_LEN)
essid['essid_len'] = taglen
return 0, essid
cur += taglen
return -1, None
def get_pmkid_from_packet(packet, source):
if source == "EAPOL-M1":
akm = None # Unknown AKM
if packet:
pos = 0
while True:
try:
tag_id = packet[pos]
tag_len = packet[pos+1]
tag_data = packet[pos+2:pos+2+tag_len]
if tag_id == 221:
if tag_data[0:3] == bytes(SUITE_OUI):
pmkid = tag_data[4:].hex()
if pmkid != '0'*32:
yield pmkid, akm
pos = pos+2+tag_len
except:
break
return
elif source == "EAPOL-M2":
pos = 0
elif source == IEEE80211_STYPE_ASSOC_REQ:
pos = 28
elif source == IEEE80211_STYPE_REASSOC_REQ:
pos = 34
else:
return
while True:
try:
tag_id = packet[pos]
tag_len = packet[pos+1]
tag_data = packet[pos+2:pos+2+tag_len]
if tag_id == 48:
#tag_version = tag_data[0:2]
#tag_group_cipher_suite = tag_data[2:6]
# Pairwise Cipher Suite
tag_pairwise_suite_count = struct.unpack('=H', tag_data[6:8])[0]
if BIG_ENDIAN_HOST:
tag_pairwise_suite_count = byte_swap_16(tag_pairwise_suite_count)
#tag_pairwise_suite = []
pos = 8
#for i in range(0, tag_pairwise_suite_count):
# pos += (4*i)+4
# tag_pairwise_suite.append(tag_data[pos-4:pos])
pos += 4*tag_pairwise_suite_count
# AKM Suite
tag_authentication_suite_count = struct.unpack('=H', tag_data[pos:pos+2])[0]
if BIG_ENDIAN_HOST:
tag_authentication_suite_count = byte_swap_16(tag_authentication_suite_count)
#tag_authentication_suite = []
pos = pos+2
skip = 0
for i in range(0, tag_authentication_suite_count):
pos += (4*i)+4
akm = tag_data[pos-4:pos]
if akm[0:3] != bytes(SUITE_OUI):
skip = 1
break
if skip == 1:
break
###############
#tag_capabilities = tag_data[pos:pos+2]
##############################
try:
pmkid_count = struct.unpack('=H', tag_data[pos+2:pos+4])[0]
if BIG_ENDIAN_HOST:
pmkid_count = byte_swap_16(pmkid_count)
pos = pos+4
for i in range(0, pmkid_count):
pos += (16*i)+16
pmkid = tag_data[pos-16:pos].hex()
if pmkid != '0'*32:
yield pmkid, akm[3]
except:
break
##############################
break
pos = pos+2+tag_len
except:
break
def handle_llc(ieee80211_llc_snap_header):
if ieee80211_llc_snap_header['dsap'] != IEEE80211_LLC_DSAP:
return -1
if ieee80211_llc_snap_header['ssap'] != IEEE80211_LLC_SSAP:
return -1
if ieee80211_llc_snap_header['ctrl'] != IEEE80211_LLC_CTRL:
return -1
if ieee80211_llc_snap_header['ethertype'] != IEEE80211_DOT1X_AUTHENTICATION:
return -1
return 0
def handle_auth(auth_packet, auth_packet_copy, rest_packet, pkt_offset, pkt_size):
ap_length = byte_swap_16(auth_packet['length'])
ap_key_information = byte_swap_16(auth_packet['key_information'])
ap_replay_counter = byte_swap_64(auth_packet['replay_counter'])
ap_wpa_key_data_length = byte_swap_16(auth_packet['wpa_key_data_length'])
if ap_length == 0:
return -1, None
if ap_key_information & WPA_KEY_INFO_ACK:
if ap_key_information & WPA_KEY_INFO_INSTALL:
excpkt_num = EXC_PKT_NUM_3
else:
excpkt_num = EXC_PKT_NUM_1
else:
if ap_key_information & WPA_KEY_INFO_SECURE:
excpkt_num = EXC_PKT_NUM_4
else:
excpkt_num = EXC_PKT_NUM_2
if auth_packet['wpa_key_nonce'] == ZERO*32:
return -1, None
excpkt = {}
excpkt['nonce'] = pymemcpy(auth_packet['wpa_key_nonce'], 32)
excpkt['replay_counter'] = ap_replay_counter
excpkt['excpkt_num'] = excpkt_num
excpkt['eapol_len'] = SIZE_OF_auth_packet_t + ap_wpa_key_data_length
if (pkt_offset + excpkt['eapol_len']) > pkt_size:
return -1, None
if (SIZE_OF_auth_packet_t + ap_wpa_key_data_length) > SIZE_OF_EAPOL:
return -1, None
auth_packet_copy_packed = struct.pack('=BBHBHHQ32B16B8B8B16BH', *auth_packet_copy)
excpkt['eapol'] = pymemcpy(auth_packet_copy_packed, SIZE_OF_auth_packet_t)
excpkt['eapol'] += pymemcpy(rest_packet[:ap_wpa_key_data_length], SIZE_OF_EAPOL-SIZE_OF_auth_packet_t)
excpkt['keymic'] = pymemcpy(auth_packet['wpa_key_mic'], 16)
excpkt['keyver'] = ap_key_information & WPA_KEY_INFO_TYPE_MASK
if (excpkt_num == EXC_PKT_NUM_3) or (excpkt_num == EXC_PKT_NUM_4):
excpkt['replay_counter'] -= 1
return 0, excpkt
###
### PCAPNG ONLY ###
def read_blocks(pcapng):
while True:
piece = pcapng.read(8)
if not piece:
break
block_total_length = struct.unpack('=II', piece)[1]
if BIG_ENDIAN_HOST:
block_total_length = byte_swap_32(block_total_length)
block_body_length = block_total_length - 12
body_unpacked = struct.unpack('=II{}BI'.format(block_body_length), piece+pcapng.read(block_body_length+4))
block_type = body_unpacked[0]
block_length = body_unpacked[1]
block_body = body_unpacked[2:2+block_body_length]
if BIG_ENDIAN_HOST:
block_type = byte_swap_32(block_type)
block_length = byte_swap_32(block_length)
block = (dict(pcapng_general_block_structure._asdict(pcapng_general_block_structure._make(( \
block_type, \
block_length, \
block_body, \
block_length \
)))))
yield block
def read_options(options_block, bitness):
while True:
option = {}
try:
option['code'] = struct.unpack("H",struct.pack('2B', *options_block[0:2]))[0]
option['length'] = struct.unpack("H",struct.pack('2B', *options_block[2:4]))[0]
except:
break
if BIG_ENDIAN_HOST:
option['code'] = byte_swap_16(option['code'])
option['length'] = byte_swap_16(option['length'])
if bitness:
option['code'] = byte_swap_16(option['code'])
option['length'] = byte_swap_16(option['length'])
if option['code'] == opt_endofopt:
break
option_length = option['length'] + (-(option['length'])%4)
option['value'] = options_block[4:4+option_length]
if option['code'] in Custom_Option_Codes:
pen = option['value'][0:4]
if pen == HCXDUMPTOOL_PEN:
magic = option['value'][4:36]
if magic == HCXDUMPTOOL_MAGIC_NUMBER:
for custom_option in read_options(option['value'][36:], bitness):
yield custom_option
options_block = options_block[4+option_length:]
else:
option['value'] = bytes(option['value'])
options_block = options_block[4+option_length:]
yield option
def read_custom_block(custom_block, bitness):
name, data, options = None, None, None
pen = custom_block[0:4]
if pen == HCXDUMPTOOL_PEN:
magic = custom_block[4:36]
if magic == HCXDUMPTOOL_MAGIC_NUMBER:
name = 'hcxdumptool'
data = None
options = []
for option in read_options(custom_block[36:], bitness):
if option['code'] == HCXDUMPTOOL_OPTIONCODE_RC:
option['value'] = byte_swap_64(int(option['value'].hex(), 16))
if BIG_ENDIAN_HOST:
option['value'] = byte_swap_64(option['value'])
if bitness:
option['value'] = byte_swap_64(option['value'])
options.append(option)
return name, data, options
###
######################### READ FILE #########################
def get_filesize(file):
old_file_pos = file.tell()
file.seek(0, os.SEEK_END)
filesize = file.tell()
file.seek(old_file_pos, os.SEEK_SET)
return filesize
def read_file(file):
if file.lower().endswith('.gz'):
return gzip.open(file, 'rb')
return open(file, 'rb')
def read_pcap_file_header(pcap):
try:
pcap_file_header = dict(pcap_file_header_t._asdict(pcap_file_header_t._make(struct.unpack('=IHHIIII', pcap.read(SIZE_OF_pcap_file_header_t)))))
except struct.error:
LOGGER.log('Could not read pcap header', WARNING)
raise ValueError('Could not read pcap header')
if BIG_ENDIAN_HOST:
pcap_file_header['magic'] = byte_swap_32(pcap_file_header['magic'])
pcap_file_header['version_major'] = byte_swap_16(pcap_file_header['version_major'])
pcap_file_header['version_minor'] = byte_swap_16(pcap_file_header['version_minor'])
pcap_file_header['thiszone'] = byte_swap_32(pcap_file_header['thiszone'])
pcap_file_header['sigfigs'] = byte_swap_32(pcap_file_header['sigfigs'])
pcap_file_header['snaplen'] = byte_swap_32(pcap_file_header['snaplen'])
pcap_file_header['linktype'] = byte_swap_32(pcap_file_header['linktype'])
if pcap_file_header['magic'] == TCPDUMP_MAGIC:
bitness = 0
elif pcap_file_header['magic'] == TCPDUMP_CIGAM:
bitness = 1
xprint("WARNING Endianness(big) is not well tested!")
else:
LOGGER.log('Invalid pcap header', WARNING)
raise ValueError('Invalid pcap header')
if (pcap_file_header['linktype'] != DLT_IEEE802_11) \
and (pcap_file_header['linktype'] != DLT_IEEE802_11_PRISM) \
and (pcap_file_header['linktype'] != DLT_IEEE802_11_RADIO) \
and (pcap_file_header['linktype'] != DLT_IEEE802_11_PPI_HDR):
LOGGER.log('Unsupported linktype detected', WARNING)
raise ValueError('Unsupported linktype detected')
return pcap_file_header, bitness
def read_pcapng_file_header(pcapng):
blocks = read_blocks(pcapng)
for block in blocks:
if block['block_type'] == Section_Header_Block:
try:
interface = next(blocks)
except:
break
pcapng_file_header = {}
pcapng_file_header['magic'] = block['block_body'][:4]
pcapng_file_header['version_major'] = block['block_body'][4:6]
pcapng_file_header['version_minor'] = block['block_body'][6:8]
pcapng_file_header['thiszone'] = 0
pcapng_file_header['sigfigs'] = 0
pcapng_file_header['snaplen'] = interface['block_body'][2:4]
pcapng_file_header['linktype'] = interface['block_body'][0]
if BIG_ENDIAN_HOST:
pcapng_file_header['magic'] = byte_swap_32(pcapng_file_header['magic'])
pcapng_file_header['version_major'] = byte_swap_16(pcapng_file_header['version_major'])
pcapng_file_header['version_minor'] = byte_swap_16(pcapng_file_header['version_minor'])
pcapng_file_header['thiszone'] = byte_swap_32(pcapng_file_header['thiszone'])
pcapng_file_header['sigfigs'] = byte_swap_32(pcapng_file_header['sigfigs'])
pcapng_file_header['snaplen'] = byte_swap_32(pcapng_file_header['snaplen'])
pcapng_file_header['linktype'] = byte_swap_32(pcapng_file_header['linktype'])
if struct.unpack("I", struct.pack("4B", *pcapng_file_header['magic']))[0] == PCAPNG_MAGIC:
bitness = 0
elif struct.unpack("I", struct.pack("4B", *pcapng_file_header['magic']))[0] == PCAPNG_CIGAM:
pcapng_file_header['magic'] = byte_swap_32(pcapng_file_header['magic'])
pcapng_file_header['version_major'] = byte_swap_16(pcapng_file_header['version_major'])
pcapng_file_header['version_minor'] = byte_swap_16(pcapng_file_header['version_minor'])
pcapng_file_header['thiszone'] = byte_swap_32(pcapng_file_header['thiszone'])
pcapng_file_header['sigfigs'] = byte_swap_32(pcapng_file_header['sigfigs'])
pcapng_file_header['snaplen'] = byte_swap_32(pcapng_file_header['snaplen'])
pcapng_file_header['linktype'] = byte_swap_32(pcapng_file_header['linktype'])
bitness = 1
xxprint("WARNING Endianness(big) is not well tested!")
else:
continue
pcapng_file_header['section_options'] = []
for option in read_options(block['block_body'][16:], bitness):
pcapng_file_header['section_options'].append(option)
if_tsresol = 6
pcapng_file_header['interface_options'] = []
for option in read_options(interface['block_body'][8:], bitness):
if option['code'] == if_tsresol_code:
if_tsresol = option['code']
## currently only supports if_tsresol = 6
if if_tsresol != 6:
xprint("Unsupported if_tsresol")
continue
pcapng_file_header['interface_options'].append(option)
if (pcapng_file_header['linktype'] != DLT_IEEE802_11) \
and (pcapng_file_header['linktype'] != DLT_IEEE802_11_PRISM) \
and (pcapng_file_header['linktype'] != DLT_IEEE802_11_RADIO) \
and (pcapng_file_header['linktype'] != DLT_IEEE802_11_PPI_HDR):
continue
yield pcapng_file_header, bitness, if_tsresol, blocks
######################### PROCESS PACKETS #########################
def process_packet(packet, header):
xprint("Reading file: {}/{} ({} packets)".format(STATUS.current_filepos, STATUS.total_filesize, STATUS.current_packet), end='\r')
if (header['caplen'] < SIZE_OF_ieee80211_hdr_3addr_t):
return
unpacked_packet = struct.unpack('=HH6B6B6BH', packet[:SIZE_OF_ieee80211_hdr_3addr_t])
ieee80211_hdr_3addr = dict(ieee80211_hdr_3addr_t._asdict(ieee80211_hdr_3addr_t._make(( \
unpacked_packet[0], \
unpacked_packet[1], \
(unpacked_packet[2], unpacked_packet[3], unpacked_packet[4], unpacked_packet[5], unpacked_packet[6], unpacked_packet[7]), \
(unpacked_packet[8], unpacked_packet[9], unpacked_packet[10], unpacked_packet[11], unpacked_packet[12], unpacked_packet[13]), \
(unpacked_packet[14], unpacked_packet[15], unpacked_packet[16], unpacked_packet[17], unpacked_packet[18], unpacked_packet[19]), \
unpacked_packet[20] \
))))
if BIG_ENDIAN_HOST:
ieee80211_hdr_3addr['frame_control'] = byte_swap_16(ieee80211_hdr_3addr['frame_control'])
ieee80211_hdr_3addr['duration_id'] = byte_swap_16(ieee80211_hdr_3addr['duration_id'])
ieee80211_hdr_3addr['seq_ctrl'] = byte_swap_16(ieee80211_hdr_3addr['seq_ctrl'])
frame_control = ieee80211_hdr_3addr['frame_control']
if frame_control & IEEE80211_FCTL_FTYPE == IEEE80211_FTYPE_MGMT:
if bytes(ieee80211_hdr_3addr['addr3']) == BROADCAST_MAC:
return
stype = frame_control & IEEE80211_FCTL_STYPE
if stype == IEEE80211_STYPE_BEACON:
length_skip = SIZE_OF_ieee80211_hdr_3addr_t + SIZE_OF_beacon_t
rc_beacon, essid = get_essid_from_tag(packet, header, length_skip)
if rc_beacon == -1:
return
DB.essid_add(bssid=ieee80211_hdr_3addr['addr3'], essid=essid['essid'], essid_len=essid['essid_len'], essid_source=ESSID_SOURCE_BEACON)
elif stype == IEEE80211_STYPE_PROBE_REQ:
length_skip = SIZE_OF_ieee80211_hdr_3addr_t
rc_beacon, essid = get_essid_from_tag(packet, header, length_skip)
if rc_beacon == -1:
return
DB.essid_add(bssid=ieee80211_hdr_3addr['addr3'], essid=essid['essid'], essid_len=essid['essid_len'], essid_source=ESSID_SOURCE_PROBE)
elif stype == IEEE80211_STYPE_PROBE_RESP:
length_skip = SIZE_OF_ieee80211_hdr_3addr_t + SIZE_OF_beacon_t
rc_beacon, essid = get_essid_from_tag(packet, header, length_skip)
if rc_beacon == -1:
return
DB.essid_add(bssid=ieee80211_hdr_3addr['addr3'], essid=essid['essid'], essid_len=essid['essid_len'], essid_source=ESSID_SOURCE_PROBE)
elif stype == IEEE80211_STYPE_ASSOC_REQ:
mac_ap = ieee80211_hdr_3addr['addr3']
if mac_ap == ieee80211_hdr_3addr['addr1']:
mac_sta = ieee80211_hdr_3addr['addr2']
else:
mac_sta = ieee80211_hdr_3addr['addr1']
for pmkid, akm in get_pmkid_from_packet(packet, stype):
DB.pmkid_add(mac_ap=mac_ap, mac_sta=mac_sta, pmkid=pmkid, akm=akm)
length_skip = SIZE_OF_ieee80211_hdr_3addr_t + SIZE_OF_assocreq_t