-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathParse80211.py
1104 lines (1034 loc) · 40.3 KB
/
Parse80211.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
__author__ = "TheX1le, Crypt0s, radiotap parsing orginally by Scott Raynel in the radiotap.py project"
import collections
import struct
from flufl.enum import IntEnum
import pdb
def nullstrip(dstring):
"""
Returns string stopped at the first null character.
"""
try:
dstring = dstring[:dstring.index('\x00')]
except ValueError: # No nulls were found, which is okay.
pass
return dstring
class RadioTapHeader(IntEnum) :
VERSION = 0
LENGTH = 1
PRESENCE = 2
EXTENDED_PRESENCE = 3
class RadioTapDefinedFields(IntEnum) :
TSFT = 0
FLAGS = 1
RATE = 2
CHANNEL = 3
FHSS = 4
ANTENNA_SIGNAL = 5
ANTENNA_NOISE = 6
LOCK_QUALITY = 7
TX_ATTENUATION = 8
DB_TX_ATTENUATION = 9
DBM_TX_POWER = 10
ANTENNA = 11
DB_ANTENNA_SIGNAL = 12
DB_ANTENNA_NOISE = 13
RX_FLAGS = 14
#TX_FLAGS = 15
#RTS_RETRIES = 16
#DATA_RETRIES = 17
#X_CHANNEL = 18
MCS = 19
A_MPDU = 20
VHT = 21
class RadioTapReservedFields(IntEnum) :
RADIOTAP_NAMESPACE = 29
VENDOR_NAMESPACE = 30
EXTENDED = 31 # Extended presence bitmaps
class RadioTapFieldChannel(IntEnum) :
FREQUENCY = 0
FLAGS = 1
class RadioTapFieldFhss(IntEnum) :
HOP_SET = 0
HOP_PATTERN = 1
class RadioTapFieldMcs(IntEnum) :
KNOWN = 0
FLAGS = 1
MCS = 2
class RadioTapFieldAmpdu(IntEnum) :
REFERENCE_NUMBER = 0
FLAGS = 1
DELIMITER_CRC = 2
RESERVED = 3
class RadioTapFieldVht(IntEnum) :
KNOWN = 0
FLAGS = 1
BANDWIDTH = 2
MCS_NSS_0 = 3
MCS_NSS_1 = 4
MCS_NSS_2 = 5
MCS_NSS_3 = 6
CODING = 7
GROUP_ID = 8
PARTIAL_AID = 9
RadioTapFieldProperties = collections.namedtuple('RadioTapFieldProperties', ['field', 'alignment', 'format', 'members'])
class RadioTapDecoder():
LITTLE_ENDIAN = '<'
HEADER_FORMAT = LITTLE_ENDIAN + 'BxHI'
BITMAP_EXT_FORMAT = LITTLE_ENDIAN + 'I'
def __init__(self) :
self._offset = 0
self._header = None
self._defined_fields = { }
self._defined_fields_properties = {
RadioTapDefinedFields.TSFT: RadioTapFieldProperties(
RadioTapDefinedFields.TSFT,
8,
self.LITTLE_ENDIAN + 'Q',
None),
RadioTapDefinedFields.FLAGS: RadioTapFieldProperties(
RadioTapDefinedFields.FLAGS,
1,
self.LITTLE_ENDIAN + 'B',
None),
RadioTapDefinedFields.RATE: RadioTapFieldProperties(
RadioTapDefinedFields.RATE,
1,
self.LITTLE_ENDIAN + 'B',
None),
RadioTapDefinedFields.CHANNEL: RadioTapFieldProperties(
RadioTapDefinedFields.CHANNEL,
2,
self.LITTLE_ENDIAN + 'HH',
RadioTapFieldChannel),
RadioTapDefinedFields.FHSS: RadioTapFieldProperties(
RadioTapDefinedFields.FHSS,
1,
self.LITTLE_ENDIAN + 'BB',
RadioTapFieldFhss),
RadioTapDefinedFields.ANTENNA_SIGNAL: RadioTapFieldProperties(
RadioTapDefinedFields.ANTENNA_SIGNAL,
1,
self.LITTLE_ENDIAN + 'b',
None),
RadioTapDefinedFields.ANTENNA_NOISE: RadioTapFieldProperties(
RadioTapDefinedFields.ANTENNA_NOISE,
1,
self.LITTLE_ENDIAN + 'b',
None),
RadioTapDefinedFields.LOCK_QUALITY: RadioTapFieldProperties(
RadioTapDefinedFields.LOCK_QUALITY,
2,
self.LITTLE_ENDIAN + 'H',
None),
RadioTapDefinedFields.TX_ATTENUATION: RadioTapFieldProperties(
RadioTapDefinedFields.TX_ATTENUATION,
2,
self.LITTLE_ENDIAN + 'H',
None),
RadioTapDefinedFields.DB_TX_ATTENUATION: RadioTapFieldProperties(
RadioTapDefinedFields.DB_TX_ATTENUATION,
2,
self.LITTLE_ENDIAN + 'H',
None),
RadioTapDefinedFields.DBM_TX_POWER: RadioTapFieldProperties(
RadioTapDefinedFields.DBM_TX_POWER,
1,
self.LITTLE_ENDIAN + 'b',
None),
RadioTapDefinedFields.ANTENNA: RadioTapFieldProperties(
RadioTapDefinedFields.ANTENNA,
1,
self.LITTLE_ENDIAN + 'B',
None),
RadioTapDefinedFields.DB_ANTENNA_SIGNAL: RadioTapFieldProperties(
RadioTapDefinedFields.DB_ANTENNA_SIGNAL,
1,
self.LITTLE_ENDIAN + 'B',
None),
RadioTapDefinedFields.DB_ANTENNA_NOISE: RadioTapFieldProperties(
RadioTapDefinedFields.DB_ANTENNA_NOISE,
1,
self.LITTLE_ENDIAN + 'B',
None),
RadioTapDefinedFields.RX_FLAGS: RadioTapFieldProperties(
RadioTapDefinedFields.RX_FLAGS,
2,
self.LITTLE_ENDIAN + 'H',
None),
RadioTapDefinedFields.MCS: RadioTapFieldProperties(
RadioTapDefinedFields.MCS,
1,
self.LITTLE_ENDIAN + 'BBB',
RadioTapFieldMcs),
RadioTapDefinedFields.A_MPDU: RadioTapFieldProperties(
RadioTapDefinedFields.A_MPDU,
4,
self.LITTLE_ENDIAN + 'IHBB',
RadioTapFieldAmpdu),
RadioTapDefinedFields.VHT: RadioTapFieldProperties(
RadioTapDefinedFields.VHT,
2,
self.LITTLE_ENDIAN + 'HBBBBBBBBH',
RadioTapFieldVht)
}
@property
def header(self) :
return self._header
@property
def defined_fields(self) :
return self._defined_fields
def decode(self, buffer) :
self._header = self._decode_header(buffer)
presence_standard_mask = 0
for field in RadioTapDefinedFields :
presence_standard_mask = presence_standard_mask | (1 << field.value)
for field in RadioTapReservedFields :
presence_standard_mask = presence_standard_mask | (1 << field.value)
if self._header[RadioTapHeader.PRESENCE] & (0xFFFFFFFF & (~ presence_standard_mask)) :
raise ValueError('Unsupported fields in standard presence bitmap.')
self._decode_defined_fields(buffer)
def _decode_defined_fields(self, buffer) :
defined_fields = [ field for field in RadioTapDefinedFields ]
defined_fields.sort(key=lambda x: x.value)
for field in defined_fields :
value = self._decode_field(self._defined_fields_properties[field], buffer)
if value is not None :
self._defined_fields[field] = value
def _decode_header(self, buffer) :
self._offset = struct.calcsize(self.HEADER_FORMAT)
version, length, bitmap = struct.unpack(self.HEADER_FORMAT, buffer[:self._offset])
bitmap_ext = None
bitmap_ext_mask = (1 << RadioTapReservedFields.EXTENDED.value)
if bitmap & bitmap_ext_mask :
# Extended presence bit set, decode until we do not see one
bitmap_ext = [ ]
bitmap_ext_value = bitmap
bitmap_ext_size = struct.calcsize(self.BITMAP_EXT_FORMAT)
while bitmap_ext_value & bitmap_ext_mask :
(bitmap_ext_value, ) = struct.unpack(self.BITMAP_EXT_FORMAT, buffer[self._offset:][:bitmap_ext_size])
bitmap_ext.append(bitmap_ext_value)
self._offset += bitmap_ext_size
return { RadioTapHeader.VERSION: version,
RadioTapHeader.LENGTH: length,
RadioTapHeader.PRESENCE: bitmap,
RadioTapHeader.EXTENDED_PRESENCE: bitmap_ext }
def _align_field(self, alignment) :
if alignment == 1 :
return
delta = self._offset % alignment
if delta == 0 :
return
self._offset += (alignment - delta)
def _decode_field(self, properties, buffer) :
if not self._header[RadioTapHeader.PRESENCE] & (1 << properties.field.value) :
return None
self._align_field(properties.alignment)
field_size = struct.calcsize(properties.format)
values = struct.unpack(properties.format, buffer[self._offset:][:field_size])
return_value = None
if properties.members is None :
return_value = values[0]
else :
return_value = { }
field_members = [ member for member in properties.members ]
field_members.sort(key=lambda x: x.value)
for member in field_members :
return_value[member] = values[member.value]
self._offset += field_size
return return_value
class IeTag80211:
"""
Parsing 802.11 frame information elements
"""
def __init__(self):
"""
build parser for IE tags
"""
self.tagdata = {"unparsed":[], "htPresent": False} # dict to return parsed tags
self.parser = {
"\x00": self.ssid, # ssid IE tag parser
"\x01": self.rates, # data rates tag parser
"\x03": self.channel, # channel tag parser
"\x30": self.rsn, # rsn tag parser
"\x32": self.exrates, # extended rates tag parser
"\xDD": self.vendor221, # 221 vendor tag parser
"\x3D": self.htinfo, # HT information tag checker
"\x07": self.country, # Country Code Parser
"\x85": self.ccxOne, # Cisco CCX v1 Parser
}
def ccxOne(self, **kwargs):
"""
Parse ap hostname and number of clients
from cisco CCX v1 IE tag
"""
rbytes = kwargs["rbytes"]
self.tagdata["APhostname"] = nullstrip(str(rbytes[12:28]))
self.tagdata["ClientNum"] = ord(rbytes[28])
def country(self, **kwargs):
"""
Return Country Code from beacon packet
"""
rbytes = kwargs["rbytes"]
self.tagdata["country"] = str(rbytes[2:4])
def htinfo(self, **kwargs):
"""
Check for existance of HT tag to denote support
For 802.11N Mark its existance true for mgt frame
save the reported HT primary channel
"""
rbytes = kwargs["rbytes"]
self.tagdata["htPresent"] = True
# reported primary channel
self.tagdata["htPriCH"] = ord(rbytes[2])
def vendor221(self, **kwargs):
"""
Parse the wpa IE tag 221 aka \xDD
returns wpa info in nested dict
gtkcs is group temportal cipher suite
akm is auth key managment, ie either wpa, psk ....
ptkcs is pairwise temportal cipher suite
"""
rbytes = kwargs.get("rbytes")
p2p_type = kwargs.get("p2p_type", None)
wpa = {}
ptkcs = []
akm = []
# need to extend this
cipherS = {
1 : "WEP-40/64",
2 : "TKIP",
3 : "RESERVED",
4 : "CCMP",
5 : "WEP-104/128"
}
authKey = {
0 : "None",
1 : "802.1x or PMK",
2 : "PSK",
}
try:
# remove IE tag, len and Microsoft OUI
packetLen = ord(rbytes[1])
vendor_OUI = rbytes[2:5]
vendor_OUI_type = ord(rbytes[5])
vendor_OUI_stype = ord(rbytes[6])
if vendor_OUI == "\x00\x50\xf2":
# Microsoft
if vendor_OUI_type == 1:
# WPA Element Parsing
version = struct.unpack('h', rbytes[6:8])[0]
wpa["gtkcsOUI"] = rbytes[8:11]
# GTK Bytes Parsing
gtkcsTypeI = ord(rbytes[11])
if gtkcsTypeI in cipherS.keys():
gtkcsType = cipherS[gtkcsTypeI]
else:
gtkcsType = gtkcsTypeI
wpa["gtkcsType"] = gtkcsType
# PTK Bytes Parsing
# len of ptk types supported
ptkcsTypeL = struct.unpack('h', rbytes[12:14])[0]
counter = ptkcsTypeL
cbyte = 14 #current byte
while counter != 0:
ptkcsTypeOUI = rbytes[cbyte:cbyte+3]
ptkcsTypeI = ord(rbytes[cbyte+3])
if ptkcsTypeI in cipherS.keys():
ptkcsType = cipherS[ptkcsTypeI]
else:
ptkcsType = ptkcsTypeI
cbyte += 4 # end up on next byte to parse
ptkcs.append({"ptkcsOUI":ptkcsTypeOUI,
"ptkcsType":ptkcsType})
counter -= 1
akmTypeL = struct.unpack('h', rbytes[cbyte:cbyte+2])[0]
counter = akmTypeL
# skip past the akm len
cbyte = cbyte + 2
while counter != 0:
akmTypeOUI = rbytes[cbyte:cbyte+3]
akmTypeI = ord(rbytes[cbyte+3])
if akmTypeI in authKey.keys():
akmType = authKey[akmTypeI]
else:
akmType = akmTypeI
cbyte += 4 # end up on next byte to parse
akm.append({"akmOUI":akmTypeOUI,
"akmType":akmType})
counter -= 1
wpa["ptkcs"] = ptkcs
wpa["akm"] = akm
self.tagdata["wpa"] = wpa
if vendor_OUI_type == 4:
wpsState = "Unknown"
# WPA Element Parsing
# Verson data element type
det = struct.unpack('h', rbytes[6:8])[0]
# data element length
delen = struct.unpack('h', rbytes[8:10])[0]
# wps version
version = ord(rbytes[10])
# WPS data element type
wdet = struct.unpack('h', rbytes[11:13])[0]
# WPS data element length
wdelen = struct.unpack('h', rbytes[13:15])[0]
# wps state
if ord(rbytes[15]) is 2:
# wps is configured
wpsState = "configured"
self.tagdata["wps"] = {"state": wpsState}
if vendor_OUI == "\x00\x0b\x86":
# aruba
if vendor_OUI_type == 1:
if vendor_OUI_stype == 3:
# aruba does ap hostname this way
self.tagdata["APhostname"] = rbytes[7:]
if vendor_OUI == "\x50\x6f\x9a":
# WifiAll <- wifi direct
p2p_type = kwargs.pop("p2p_type", None)
if p2p_type is not None:
# action packet p2p parser
if p2p_type in [0, 1]:
# go request parser
p2p_go_status = rbytes[6:11]
p2p_device_capability = rbytes[11:16]
p2p_go_owner_intent = ord(rbytes[16])
p2p_go_owner_len = ord(rbytes[17])
cnt = 17 + p2p_go_owner_len
p2p_go_owner_intent_go_num = ord(rbytes[17:cnt]) >> 1
p2p_go_owner_intent_go_tie_breaker = ord(
rbytes[17:cnt]) & 1
# skipping acutal parse of this for now
p2p_config_timeout = rbytes[cnt: cnt+5]
# skip listen channel for now, its not as useful
cnt += 5
p2p_go_listen_channel = rbytes[cnt: cnt+9]
# intended bssid parsing
cnt += 11
p2p_go_intented_p2p_addr = rbytes[cnt: cnt+7]
# TODO Finish Channel parsing as we still dont know how it signals which one it picked
if p2p_type is 0:
self.tagdata["wifi_direct"] = {
"channel_num_go_request": None,
"p2p_bssid_go_request": p2p_go_intented_p2p_addr,
"p2p_type": p2p_type}
elif p2p_type is 1:
self.tagdata["wifi_direct"] = {
"channel_num_go_response": None,
"p2p_bssid_go_response": p2p_go_intented_p2p_addr,
"p2p_type": p2p_type}
elif p2p_type ==3:
p2p_go_status = rbytes[6:11]
p2p_device_capability = rbytes[11:16]
p2p_operating_channel = rbytes[16:24]
p2p_channel_list = rbytes[24:56]
# parse the essid of new direct network
len = ord(rbytes[57])
p2p_ssid = rbytes[58: 58+len()]
self.tagdata["wifi_direct"] = {
"direct_ssid": p2p_ssid,
"p2p_type": p2p_type}
# generic parser for p2p data in probe request
# will most likely fail on probe response
elif vendor_OUI_type == 9:
# p2p_capability
p2p_attribute_type = ord(rbytes[6])
p2p_attribute_len = struct.unpack('h', rbytes[7:9])[0]
p2p_device_capability_bitmap = rbytes[9]
p2p_group_capability_bitmap = rbytes[10]
p2p_listen_channel = ord(rbytes[11])
p2p_listen_channel_len = ord(rbytes[12])
p2p_left_over = rbytes[13:]
p2p_channel_number = ord(p2p_left_over[-1])
p2p_operating_class = ord(p2p_left_over[-2])
p2p_country_string = p2p_left_over[:-2]
self.tagdata["wifi_direct"] = {
"channel_num": p2p_channel_number,
"listen_num": p2p_listen_channel}
except IndexError:
# mangled packets
return -1
def parseIE(self, **kwargs):
"""
takes string of raw bytes splits them into tags
passes those tags to the correct parser
retruns parsed tags as a dict, key is tag number
rbytes = string of bytes to parse
"""
rbytes = kwargs.pop("rbytes")
self.tagdata = {"unparsed":[]} # dict to return parsed tags
offsets = {}
while len(rbytes) > 0:
try:
fbyte = rbytes[0]
# add two to account for size byte and tag num byte
blen = ord(rbytes[1]) + 2 # byte len of ie tag
if fbyte in self.parser.keys():
prebytes = rbytes[0:blen]
if blen == len(prebytes):
# use kwargs to pass though args to sub parsers
ie_args = kwargs.copy()
ie_args["rbytes"] = prebytes
self.parser[fbyte](**ie_args)
else:
# mangled packets
return -1
else:
# we have no parser for the ie tag
self.tagdata["unparsed"].append(rbytes[0:blen])
rbytes = rbytes[blen:]
except IndexError:
# mangled packets
return -1
def exrates(self, **kwargs):
"""
parses extended supported rates
exrates IE tag number is 0x32
retruns exrates in a list
"""
rbytes = kwargs.get("rbytes")
exrates = []
for exrate in tuple(rbytes[2:]):
exrates.append((ord(exrate) & 127) * 0.5)
self.tagdata["exrates"] = exrates
def channel(self, **kwargs):
"""
parses channel
channel IE tag number is 0x03
returns channel as int
last byte is channel
"""
rbytes = kwargs["rbytes"]
self.tagdata["channel"] = ord(rbytes[2])
def ssid(self, **kwargs):
"""
parses ssid IE tag
ssid IE tag number is 0x00
returns the ssid as a string
"""
# how do we handle hidden ssids?
rbytes = kwargs.get("rbytes")
essid = unicode(rbytes[2:], errors='replace')
# check for a hidden ssid
if essid == '\x00' * len(essid):
self.tagdata["hidden"] = True
self.tagdata["ssid"] = ""
else:
self.tagdata["hidden"] = False
self.tagdata["ssid"] = essid
def rates(self, **kwargs):
"""
parses rates from ie tag
rates IE tag number is 0x01
returns rates as in a list
"""
rbytes = kwargs.get("rbytes")
rates = []
for rate in tuple(rbytes[2:]):
rates.append((ord(rate) & 127) * 0.5)
self.tagdata["rates"] = rates
def rsn(self, **kwargs):
"""
parses robust security network ie tag
rsn ie tag number is 0x30
returns rsn info in nested dict
gtkcs is group temportal cipher suite
akm is auth key managment, ie either wpa, psk ....
ptkcs is pairwise temportal cipher suite
"""
rbytes = kwargs.get("rbytes")
rsn = {}
ptkcs = []
akm = []
# need to extend this
cipherS = {
1 : "WEP-40/64",
2 : "TKIP",
3 : "RESERVED",
4 : "CCMP",
5 : "WEP-104/128"
}
authKey = {
0 : "None",
1 : "802.1x or PMK",
2 : "PSK",
}
try:
version = struct.unpack('h', rbytes[2:4])[0]
rsn["gtkcsOUI"] = rbytes[4:7]
# GTK Bytes Parsing
gtkcsTypeI = ord(rbytes[7])
if gtkcsTypeI in cipherS.keys():
gtkcsType = cipherS[gtkcsTypeI]
else:
gtkcsType = gtkcsTypeI
rsn["gtkcsType"] = gtkcsType
# PTK Bytes Parsing
# len of ptk types supported
ptkcsTypeL = struct.unpack('h', rbytes[8:10])[0]
counter = ptkcsTypeL
cbyte = 10 #current byte
while counter != 0:
ptkcsTypeOUI = rbytes[cbyte:cbyte+3]
ptkcsTypeI = ord(rbytes[cbyte+3])
if ptkcsTypeI in cipherS.keys():
ptkcsType = cipherS[ptkcsTypeI]
else:
ptkcsType = ptkcsTypeI
cbyte += 4 # end up on next byte to parse
ptkcs.append({"ptkcsOUI":ptkcsTypeOUI,
"ptkcsType":ptkcsType})
counter -= 1
akmTypeL = struct.unpack('h', rbytes[cbyte:cbyte+2])[0]
cbyte += 2
counter = akmTypeL
#this might break need testing
while counter != 0:
akmTypeOUI = rbytes[cbyte:cbyte+3]
akmTypeI = ord(rbytes[cbyte+3])
if akmTypeI in authKey.keys():
akmType = authKey[akmTypeI]
else:
akmType = akmTypeI
cbyte += 4 # end up on next byte to parse
akm.append({"akmOUI":akmTypeOUI,
"akmType":akmType})
counter -= 1
# 8 bits are switches for various features
capabil = rbytes[cbyte:cbyte+2]
cbyte += 3 # end up on PMKID list
rsn["pmkidcount"] = rbytes[cbyte:cbyte +2]
rsn["pmkidlist"] = rbytes[cbyte+3:]
rsn["ptkcs"] = ptkcs
rsn["akm"] = akm
rsn["capabil"] = capabil
self.tagdata["rsn"] = rsn
except Exception:
# mangled packets
return -1
class Parse80211:
"""
Class file for parsing
several common 802.11 frames
"""
def __init__(self, rth, headsize):
"""
start the parser
rth = Boolean if there is Radio tap header
headersize = actual header size
"""
self.rt = 0
self.rth = rth
self.headsize = headsize
# this gets set to True if were seeing mangled packets
self.mangled = False
# number of mangled packets seen
self.mangledcount = 0
# create ie tag parser
self.IE = IeTag80211()
self.parser = {0:{ # managment frames
0: self.placedef, # assoication request
1: self.placedef, # assoication response
2: self.placedef, # reassoication request
3: self.placedef, # reaassoication response
4: self.probeReq, # probe request
5: self.probeResp, # probe response
8: self.beacon, # beacon
9: self.placedef, # ATIM
10: self.deauthDisass, # disassoication
11: self.placedef, # authentication
12: self.deauthDisass, # deauthentication
13: self.action # action frame
}, 1: {}, # control frames
2: { # data frames
0: self.fdata, # data
1: self.fdata, # data + CF-ack
2: self.fdata, # data + CF-poll
3: self.fdata, # data + CF-ack+CF-poll
5: self.fdata, # CF-ack
6: self.fdata, # CF-poll
7: self.fdata, # CF-ack+CF-poll
8: self.fdata, # QoS Data
9: self.fdata, # QoS Data + CF-ack
10: self.fdata, # QoS Data + CF-poll
11: self.fdata, # QoS Data + CF-ack+CF-poll
12: self.fdata, # QoS Null
14: self.fdata, # QoS + CF-poll (no data)
15: self.fdata, # QoS + CF-ack (no data)
}}
self.packetBcast = {
"oldbcast": '\x00\x00\x00\x00\x00\x00', # old broadcast address
"l2": '\xff\xff\xff\xff\xff\xff', # layer 2 mac broadcast
"ipv6m": '\x33\x33\x00\x00\x00\x16', # ipv6 multicast
"stp": '\x01\x80\xc2\x00\x00\x00', # Spanning Tree multicast 802.1D
"cdp": '\x01\x00\x0c\xcc\xcc\xcc', # CDP/VTP mutlicast address
"cstp": '\x01\x00\x0C\xCC\xCC\xCD', # Cisco shared STP Address
"stpp": '\x01\x80\xc2\x00\x00\x08', # Spanning Tree multicast 802.1AD
"oam": '\x01\x80\xC2\x00\x00\x02', # oam protocol 802.3ah
"ipv4m": '\x01\x00\x5e\x7F\x00\xCD', # ipv4 multicast
"ota" : '\x01\x0b\x85\x00\x00\x00', # Over the air provisioning multicast
"v6Neigh" : '\x33\x33\xff\x00\x00\x00' # ipv6 neighborhood discovery
}
self.freqLookup = {
2412: 1, 2417: 2, 2422: 3,
2427: 4, 2432: 5, 2437: 6,
2442: 7, 2447: 8, 2452: 9,
2457: 10, 2462: 11, 2467: 12,
2472: 13, 2484: 14, 5170: 34,
5180: 36, 5190: 38, 5200: 40,
5210: 42, 5220: 44, 5230: 46,
5240: 48, 5260: 52, 5280: 56,
5300: 58, 5320: 60, 5500: 100,
5520: 104, 5540: 108, 5560: 112,
5580: 116, 5600: 120, 5620: 124,
5640: 128, 5660: 132, 5680: 136,
5700: 140, 5745: 149, 5765: 153,
5785: 157, 5805: 161, 5825: 165
}
def action(self, data):
"""
Action frame
"""
cat_code = ord(data[0])
if cat_code == 4:
# public action
public_action = ord(data[1])
if public_action == 9:
# vendor specific
oui = data[2:4]
if oui == "\x50\x6f\x9a":
subtype = data[4]
if subtype == 9:
p2p_action_subtype = data[5]
p2p_action_dialog_token = data[6]
"""
action subtype 0 is go request
action subtype 1 is go response
action subtype 2 is go conformation
action subtype 3 is go
"""
action_args = {"rbytes": data[7:],
"p2p_type": p2p_action_subtype}
self.IE.parseIE(**action_args)
# if checks failed out, return none
return None
def isBcast(self, mac):
"""
returns boolen if mac is a broadcast/multicast mac
"""
for bcastType in ['ipv6m', 'ipv4m', 'v6Neigh']:
if mac[:3] == self.packetBcast[bcastType][:3]:
return True
if mac in self.packetBcast.values():
return True
else:
return False
def placedef(self, data):
pass
#print data[self.rt].encode('hex')
#print "No parser for subtype\n"
def parseRtap(self, rtap):
"""
Pass rtap data off to the radio tap decoder
"""
decoder = RadioTapDecoder()
decoder.decode(rtap)
return decoder.defined_fields
def parseFrame(self, frame, ARP=False):
"""
Determine the type of frame and
choose the right parser
"""
# set the wep bit for the packet
self.wepbit = False
if frame is not None:
data = frame[1]
if data is None:
return None
if self.rth:
self.rt = struct.unpack('h', data[2:4])[0]
# check to see if packet really has a radio tap header
# lorcon injected packets wont
if self.rt != self.headsize:
self.rt = 0
else:
self.rt = 0
else:
return None
# parse radio tap if not 0
try:
self.rtapData = self.parseRtap(data[:self.rt])
except Exception:
# bad rtap header, pass for now
self.rtapData = -1
pass
# determine frame subtype
ptype = ord(data[self.rt])
# wipe out all bits we dont need
ftype = (ptype >> 2) & 3
stype = ptype >> 4
# protected data bit aka the WEP bit
flags = ord(data[self.rt + 1])
if (flags & 64):
self.wepbit = True
if ftype in self.parser.keys():
if stype in self.parser[ftype].keys():
# will return -1 if packet is mangled
# none if we cant parse it
parsedFrame = self.parser[ftype][stype](data[self.rt:])
# packet is mangled some how return the error
if parsedFrame in [None, -1]:
return parsedFrame
else:
parsedFrame["type"] = ftype
parsedFrame["stype"] = stype
parsedFrame["wepbit"] = self.wepbit
# strip the headers
parsedFrame['rtap'] = self.rt
# get the rssi and tsamp from rtap data
if self.rtapData == -1:
# truncated rtap, make rssi None
parsedFrame['rssi'] = None
else:
parsedFrame['rssi'] = self.rtapData[5]
try:
parsedFrame['rssi_ts'] = self.rtapData[0]
except KeyError:
# no time stamp found
parsedFrame['rssi_ts'] = None
parsedFrame["raw"] = data
if ARP is True:
if stype == '\x08':
# data packet, check for arp
pass
return parsedFrame
else:
# we dont have a parser for the packet
return None
else:
# we dont have a parser for the packet
return None
def fdata(self, data):
"""
parse the src,dst,bssid from a data frame
"""
# do a bit bitwise & to check which of the last 2 bits are set
try:
dsbits = ord(data[1]) & 3
# from ds to station via ap
if dsbits == 1:
bssid = data[4:10] # bssid addr 6 bytes
src = data[10:16] # src addr 6 bytes
dst = data[16:22] # destination addr 6 bytes
# from station to ds va ap
elif dsbits == 2:
dst = data[4:10] # destination addr 6 bytes
bssid = data[10:16] # bssid addr 6 bytes
src = data[16:22] # source addr 6 bytes
# wds frame
elif dsbits == 3:
# we dont do anything with these yet
return None
else:
# mangled ds bits
self.mangled = True
self.mangledcount += 1
return -1
except IndexError:
self.mangled = True
self.mangledcount += 1
return -1
return {"src":src, "dst":dst, "bssid":bssid, "ds":dsbits, "wepbit":self.wepbit}
def probeResp(self, data):
"""
Parse out probe response
return a dict of with keys of
src, dst, bssid, probe request
"""
try:
dsbits = ord(data[1]) & 3
dst = data[4:10] # destination addr 6 bytes
src = data[10:16] # source addr 6 bytes
bssid = data[16:22] # bssid addr 6 bytes
# parse the IE tags
# possible bug, no fixed 12 byte paramaters before ie tags?
# these seem to have it...
ie_args = {"rbytes": data[36:]}
self.IE.parseIE(**ie_args)
if "ssid" not in self.IE.tagdata.keys():
self.mangled = True
self.mangledcount += 1
return -1
else:
essid = self.IE.tagdata["ssid"]
if "channel" not in self.IE.tagdata.keys():
self.mangled = True
self.mangledcount += 1
return -1
else:
channel = self.IE.tagdata["channel"]
except IndexError:
self.mangled = True
self.mangledcount += 1
return -1
return {"bssid":bssid, "essid":essid, "src":src,
"dst":dst, "channel":channel, "extended":self.IE.tagdata, "ds":dsbits}
def probeReq(self, data):
"""
Parse out probe requests
return a dict of with keys of
src, dst, bssid, probe request
"""
try:
channel = 0
dsbits = ord(data[1]) & 3
dst = data[4:10] # destination addr 6 bytes
src = data[10:16] # source addr 6 bytes
bssid = data[16:22] # bssid addr 6 bytes
# parse the IE tags
# possible bug, no fixed 12 byte paramaters before ie tags?
ie_args = {"rbytes": data[24:]}
self.IE.parseIE(**ie_args)
if "ssid" not in self.IE.tagdata.keys():
self.mangled = True
self.mangledcount += 1
return -1
else:
essid = self.IE.tagdata["ssid"]
# BUG HERE No channel in 5ghz probe
# REMOVE THISs
if "channel" not in self.IE.tagdata.keys():
self.mangled = True
self.mangledcount += 1
return -1
else:
channel = self.IE.tagdata["channel"]
except IndexError:
self.mangled = True
self.mangledcount += 1
return -1
return {"bssid":bssid, "essid":essid, "src":src,
"dst":dst, "channel":channel, "extended":self.IE.tagdata, "ds":dsbits}
def deauthDisass(self, data):
"""
Parse out a deauthentication or disassoication packet
"""
try:
dsbits = ord(data[1]) & 3
dst = data[4:10] # destination addr 6 bytes
src = data[10:16] # source addr 6 bytes
bssid = data[16:22] # bssid addr 6 bytes
reasonCode = struct.unpack('h', data[-2:])[0]
except IndexError:
self.mangled = True
self.mangledcount += 1
return -1
return {"bssid":bssid, "src":src, "reasonCode":reasonCode,
"dst":dst, "ds":dsbits}
def beacon(self, data):
"""
Parse out beacon packets
return a dict with the keys of
src, dst, bssid, essid, channel ....