-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathImpactPacket.py
2144 lines (1695 loc) · 65.4 KB
/
ImpactPacket.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
# Impacket - Collection of Python classes for working with network protocols.
#
# SECUREAUTH LABS. Copyright (C) 2018 SecureAuth Corporation. All rights reserved.
#
# This software is provided under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# Description:
# Network packet codecs basic building blocks.
# Low-level packet codecs for various Internet protocols.
#
# Author:
# Javier Burroni (javier)
# Bruce Leidl (brl)
# Javier Kohen (jkohen)
#
from __future__ import division
from __future__ import print_function
import array
import struct
import socket
import string
import sys
from binascii import hexlify
from functools import reduce
# Alias function for compatibility with both Python <3.2 `tostring` and `fromstring` methods, and
# Python >=3.2 `tobytes` and `tostring`
if sys.version_info[0] >= 3 and sys.version_info[1] >= 2:
array_tobytes = lambda array_object: array_object.tobytes()
array_frombytes = lambda array_object, bytes: array_object.frombytes(bytes)
else:
array_tobytes = lambda array_object: array_object.tostring()
array_frombytes = lambda array_object, bytes: array_object.fromstring(bytes)
"""Classes to build network packets programmatically.
Each protocol layer is represented by an object, and these objects are
hierarchically structured to form a packet. This list is traversable
in both directions: from parent to child and vice versa.
All objects can be turned back into a raw buffer ready to be sent over
the wire (see method get_packet).
"""
class ImpactPacketException(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class PacketBuffer(object):
"""Implement the basic operations utilized to operate on a
packet's raw buffer. All the packet classes derive from this one.
The byte, word, long and ip_address getters and setters accept
negative indexes, having these the a similar effect as in a
regular Python sequence slice.
"""
def __init__(self, length = None):
"If 'length' is specified the buffer is created with an initial size"
if length:
self.__bytes = array.array('B', b'\0' * length)
else:
self.__bytes = array.array('B')
def set_bytes_from_string(self, data):
"Sets the value of the packet buffer from the string 'data'"
self.__bytes = array.array('B', data)
def get_buffer_as_string(self):
"Returns the packet buffer as a string object"
return array_tobytes(self.__bytes)
def get_bytes(self):
"Returns the packet buffer as an array"
return self.__bytes
def set_bytes(self, bytes):
"Set the packet buffer from an array"
# Make a copy to be safe
self.__bytes = array.array('B', bytes.tolist())
def set_byte(self, index, value):
"Set byte at 'index' to 'value'"
index = self.__validate_index(index, 1)
self.__bytes[index] = value
def get_byte(self, index):
"Return byte at 'index'"
index = self.__validate_index(index, 1)
return self.__bytes[index]
def set_word(self, index, value, order = '!'):
"Set 2-byte word at 'index' to 'value'. See struct module's documentation to understand the meaning of 'order'."
index = self.__validate_index(index, 2)
ary = array.array("B", struct.pack(order + 'H', value))
if -2 == index:
self.__bytes[index:] = ary
else:
self.__bytes[index:index+2] = ary
def get_word(self, index, order = '!'):
"Return 2-byte word at 'index'. See struct module's documentation to understand the meaning of 'order'."
index = self.__validate_index(index, 2)
if -2 == index:
bytes = self.__bytes[index:]
else:
bytes = self.__bytes[index:index+2]
(value,) = struct.unpack(order + 'H', array_tobytes(bytes))
return value
def set_long(self, index, value, order = '!'):
"Set 4-byte 'value' at 'index'. See struct module's documentation to understand the meaning of 'order'."
index = self.__validate_index(index, 4)
ary = array.array("B", struct.pack(order + 'L', value))
if -4 == index:
self.__bytes[index:] = ary
else:
self.__bytes[index:index+4] = ary
def get_long(self, index, order = '!'):
"Return 4-byte value at 'index'. See struct module's documentation to understand the meaning of 'order'."
index = self.__validate_index(index, 4)
if -4 == index:
bytes = self.__bytes[index:]
else:
bytes = self.__bytes[index:index+4]
(value,) = struct.unpack(order + 'L', array_tobytes(bytes))
return value
def set_long_long(self, index, value, order = '!'):
"Set 8-byte 'value' at 'index'. See struct module's documentation to understand the meaning of 'order'."
index = self.__validate_index(index, 8)
ary = array.array("B", struct.pack(order + 'Q', value))
if -8 == index:
self.__bytes[index:] = ary
else:
self.__bytes[index:index+8] = ary
def get_long_long(self, index, order = '!'):
"Return 8-byte value at 'index'. See struct module's documentation to understand the meaning of 'order'."
index = self.__validate_index(index, 8)
if -8 == index:
bytes = self.__bytes[index:]
else:
bytes = self.__bytes[index:index+8]
(value,) = struct.unpack(order + 'Q', array_tobytes(bytes))
return value
def get_ip_address(self, index):
"Return 4-byte value at 'index' as an IP string"
index = self.__validate_index(index, 4)
if -4 == index:
bytes = self.__bytes[index:]
else:
bytes = self.__bytes[index:index+4]
return socket.inet_ntoa(array_tobytes(bytes))
def set_ip_address(self, index, ip_string):
"Set 4-byte value at 'index' from 'ip_string'"
index = self.__validate_index(index, 4)
raw = socket.inet_aton(ip_string)
(b1,b2,b3,b4) = struct.unpack("BBBB", raw)
self.set_byte(index, b1)
self.set_byte(index + 1, b2)
self.set_byte(index + 2, b3)
self.set_byte(index + 3, b4)
def set_checksum_from_data(self, index, data):
"Set 16-bit checksum at 'index' by calculating checksum of 'data'"
self.set_word(index, self.compute_checksum(data))
def compute_checksum(self, anArray):
"Return the one's complement of the one's complement sum of all the 16-bit words in 'anArray'"
nleft = len(anArray)
sum = 0
pos = 0
while nleft > 1:
sum = anArray[pos] * 256 + (anArray[pos + 1] + sum)
pos = pos + 2
nleft = nleft - 2
if nleft == 1:
sum = sum + anArray[pos] * 256
return self.normalize_checksum(sum)
def normalize_checksum(self, aValue):
sum = aValue
sum = (sum >> 16) + (sum & 0xFFFF)
sum += (sum >> 16)
sum = (~sum & 0xFFFF)
return sum
def __validate_index(self, index, size):
"""This method performs two tasks: to allocate enough space to
fit the elements at positions index through index+size, and to
adjust negative indexes to their absolute equivalent.
"""
orig_index = index
curlen = len(self.__bytes)
if index < 0:
index = curlen + index
diff = index + size - curlen
if diff > 0:
array_frombytes(self.__bytes, b'\0' * diff)
if orig_index < 0:
orig_index -= diff
return orig_index
class ProtocolLayer():
"Protocol Layer Manager for insertion and removal of protocol layers."
__child = None
__parent = None
def contains(self, aHeader):
"Set 'aHeader' as the child of this protocol layer"
self.__child = aHeader
aHeader.set_parent(self)
def set_parent(self, my_parent):
"Set the header 'my_parent' as the parent of this protocol layer"
self.__parent = my_parent
def child(self):
"Return the child of this protocol layer"
return self.__child
def parent(self):
"Return the parent of this protocol layer"
return self.__parent
def unlink_child(self):
"Break the hierarchy parent/child child/parent"
if self.__child:
self.__child.set_parent(None)
self.__child = None
class ProtocolPacket(ProtocolLayer):
__HEADER_SIZE = 0
__BODY_SIZE = 0
__TAIL_SIZE = 0
__header = None
__body = None
__tail = None
def __init__(self, header_size, tail_size):
self.__HEADER_SIZE = header_size
self.__TAIL_SIZE = tail_size
self.__header=PacketBuffer(self.__HEADER_SIZE)
self.__body=PacketBuffer()
self.__tail=PacketBuffer(self.__TAIL_SIZE)
def __update_body_from_child(self):
# Update child raw packet in my body
if self.child():
body=self.child().get_packet()
self.__BODY_SIZE=len(body)
self.__body.set_bytes_from_string(body)
def __get_header(self):
return self.__header
header = property(__get_header)
def __get_body(self):
self.__update_body_from_child()
return self.__body
body = property(__get_body)
def __get_tail(self):
return self.__tail
tail = property(__get_tail)
def get_header_size(self):
"Return frame header size"
return self.__HEADER_SIZE
def get_tail_size(self):
"Return frame tail size"
return self.__TAIL_SIZE
def get_body_size(self):
"Return frame body size"
self.__update_body_from_child()
return self.__BODY_SIZE
def get_size(self):
"Return frame total size"
return self.get_header_size()+self.get_body_size()+self.get_tail_size()
def load_header(self, aBuffer):
self.__HEADER_SIZE=len(aBuffer)
self.__header.set_bytes_from_string(aBuffer)
def load_body(self, aBuffer):
"Load the packet body from string. "\
"WARNING: Using this function will break the hierarchy of preceding protocol layer"
self.unlink_child()
self.__BODY_SIZE=len(aBuffer)
self.__body.set_bytes_from_string(aBuffer)
def load_tail(self, aBuffer):
self.__TAIL_SIZE=len(aBuffer)
self.__tail.set_bytes_from_string(aBuffer)
def __extract_header(self, aBuffer):
self.load_header(aBuffer[:self.__HEADER_SIZE])
def __extract_body(self, aBuffer):
if self.__TAIL_SIZE<=0:
end=None
else:
end=-self.__TAIL_SIZE
self.__BODY_SIZE=len(aBuffer[self.__HEADER_SIZE:end])
self.__body.set_bytes_from_string(aBuffer[self.__HEADER_SIZE:end])
def __extract_tail(self, aBuffer):
if self.__TAIL_SIZE<=0:
# leave the array empty
return
else:
start=-self.__TAIL_SIZE
self.__tail.set_bytes_from_string(aBuffer[start:])
def load_packet(self, aBuffer):
"Load the whole packet from a string" \
"WARNING: Using this function will break the hierarchy of preceding protocol layer"
self.unlink_child()
self.__extract_header(aBuffer)
self.__extract_body(aBuffer)
self.__extract_tail(aBuffer)
def get_header_as_string(self):
return self.__header.get_buffer_as_string()
def get_body_as_string(self):
self.__update_body_from_child()
return self.__body.get_buffer_as_string()
body_string = property(get_body_as_string)
def get_tail_as_string(self):
return self.__tail.get_buffer_as_string()
tail_string = property(get_tail_as_string)
def get_packet(self):
self.__update_body_from_child()
ret = b''
header = self.get_header_as_string()
if header:
ret += header
body = self.get_body_as_string()
if body:
ret += body
tail = self.get_tail_as_string()
if tail:
ret += tail
return ret
class Header(PacketBuffer,ProtocolLayer):
"This is the base class from which all protocol definitions extend."
packet_printable = [c for c in string.printable if c not in string.whitespace] + [' ']
ethertype = None
protocol = None
def __init__(self, length = None):
PacketBuffer.__init__(self, length)
self.auto_checksum = 1
def get_data_as_string(self):
"Returns all data from children of this header as string"
if self.child():
return self.child().get_packet()
else:
return None
def get_packet(self):
"""Returns the raw representation of this packet and its
children as a string. The output from this method is a packet
ready to be transmitted over the wire.
"""
self.calculate_checksum()
data = self.get_data_as_string()
if data:
return self.get_buffer_as_string() + data
else:
return self.get_buffer_as_string()
def get_size(self):
"Return the size of this header and all of it's children"
tmp_value = self.get_header_size()
if self.child():
tmp_value = tmp_value + self.child().get_size()
return tmp_value
def calculate_checksum(self):
"Calculate and set the checksum for this header"
pass
def get_pseudo_header(self):
"Pseudo headers can be used to limit over what content will the checksums be calculated."
# default implementation returns empty array
return array.array('B')
def load_header(self, aBuffer):
"Properly set the state of this instance to reflect that of the raw packet passed as argument."
self.set_bytes_from_string(aBuffer)
hdr_len = self.get_header_size()
if(len(aBuffer) < hdr_len): #we must do something like this
diff = hdr_len - len(aBuffer)
for i in range(0, diff):
aBuffer += '\x00'
self.set_bytes_from_string(aBuffer[:hdr_len])
def get_header_size(self):
"Return the size of this header, that is, not counting neither the size of the children nor of the parents."
raise RuntimeError("Method %s.get_header_size must be overridden." % self.__class__)
def list_as_hex(self, aList):
if len(aList):
ltmp = []
line = []
count = 0
for byte in aList:
if not (count % 2):
if (count % 16):
ltmp.append(' ')
else:
ltmp.append(' '*4)
ltmp.append(''.join(line))
ltmp.append('\n')
line = []
if chr(byte) in Header.packet_printable:
line.append(chr(byte))
else:
line.append('.')
ltmp.append('%.2x' % byte)
count += 1
if (count%16):
left = 16 - (count%16)
ltmp.append(' ' * (4+(left // 2) + (left*2)))
ltmp.append(''.join(line))
ltmp.append('\n')
return ltmp
else:
return []
def __str__(self):
ltmp = self.list_as_hex(self.get_bytes().tolist())
if self.child():
ltmp.append(['\n', str(self.child())])
if len(ltmp)>0:
return ''.join(ltmp)
else:
return ''
class Data(Header):
"""This packet type can hold raw data. It's normally employed to
hold a packet's innermost layer's contents in those cases for
which the protocol details are unknown, and there's a copy of a
valid packet available.
For instance, if all that's known about a certain protocol is that
a UDP packet with its contents set to "HELLO" initiate a new
session, creating such packet is as simple as in the following code
fragment:
packet = UDP()
packet.contains('HELLO')
"""
def __init__(self, aBuffer = None):
Header.__init__(self)
if aBuffer:
self.set_data(aBuffer)
def set_data(self, data):
self.set_bytes_from_string(data)
def get_size(self):
return len(self.get_bytes())
class EthernetTag(PacketBuffer):
"""Represents a VLAN header specified in IEEE 802.1Q and 802.1ad.
Provides methods for convenient manipulation with header fields."""
def __init__(self, value=0x81000000):
PacketBuffer.__init__(self, 4)
self.set_long(0, value)
def get_tpid(self):
"""Returns Tag Protocol Identifier"""
return self.get_word(0)
def set_tpid(self, value):
"""Sets Tag Protocol Identifier"""
return self.set_word(0, value)
def get_pcp(self):
"""Returns Priority Code Point"""
return (self.get_byte(2) & 0xE0) >> 5
def set_pcp(self, value):
"""Sets Priority Code Point"""
orig_value = self.get_byte(2)
self.set_byte(2, (orig_value & 0x1F) | ((value & 0x07) << 5))
def get_dei(self):
"""Returns Drop Eligible Indicator"""
return (self.get_byte(2) & 0x10) >> 4
def set_dei(self, value):
"""Sets Drop Eligible Indicator"""
orig_value = self.get_byte(2)
self.set_byte(2, orig_value | 0x10 if value else orig_value & 0xEF)
def get_vid(self):
"""Returns VLAN Identifier"""
return self.get_word(2) & 0x0FFF
def set_vid(self, value):
"""Sets VLAN Identifier"""
orig_value = self.get_word(2)
self.set_word(2, (orig_value & 0xF000) | (value & 0x0FFF))
def __str__(self):
priorities = (
'Best Effort',
'Background',
'Excellent Effort',
'Critical Applications',
'Video, < 100 ms latency and jitter',
'Voice, < 10 ms latency and jitter',
'Internetwork Control',
'Network Control')
pcp = self.get_pcp()
return '\n'.join((
'802.1Q header: 0x{0:08X}'.format(self.get_long(0)),
'Priority Code Point: {0} ({1})'.format(pcp, priorities[pcp]),
'Drop Eligible Indicator: {0}'.format(self.get_dei()),
'VLAN Identifier: {0}'.format(self.get_vid())))
class Ethernet(Header):
def __init__(self, aBuffer = None):
Header.__init__(self, 14)
self.tag_cnt = 0
if(aBuffer):
self.load_header(aBuffer)
def set_ether_type(self, aValue):
"Set ethernet data type field to 'aValue'"
self.set_word(12 + 4*self.tag_cnt, aValue)
def get_ether_type(self):
"Return ethernet data type field"
return self.get_word(12 + 4*self.tag_cnt)
def get_tag(self, index):
"""Returns an EthernetTag initialized from index-th VLAN tag.
The tags are numbered from 0 to self.tag_cnt-1 as they appear in the frame.
It is possible to use negative indexes as well."""
index = self.__validate_tag_index(index)
return EthernetTag(self.get_long(12+4*index))
def set_tag(self, index, tag):
"""Sets the index-th VLAN tag to contents of an EthernetTag object.
The tags are numbered from 0 to self.tag_cnt-1 as they appear in the frame.
It is possible to use negative indexes as well."""
index = self.__validate_tag_index(index)
pos = 12 + 4*index
for i,val in enumerate(tag.get_bytes()):
self.set_byte(pos+i, val)
def push_tag(self, tag, index=0):
"""Inserts contents of an EthernetTag object before the index-th VLAN tag.
Index defaults to 0 (the top of the stack)."""
if index < 0:
index += self.tag_cnt
pos = 12 + 4*max(0, min(index, self.tag_cnt))
data = self.get_bytes()
data[pos:pos] = tag.get_bytes()
self.set_bytes(data)
self.tag_cnt += 1
def pop_tag(self, index=0):
"""Removes the index-th VLAN tag and returns it as an EthernetTag object.
Index defaults to 0 (the top of the stack)."""
index = self.__validate_tag_index(index)
pos = 12 + 4*index
tag = self.get_long(pos)
data = self.get_bytes()
del data[pos:pos+4]
self.set_bytes(data)
self.tag_cnt -= 1
return EthernetTag(tag)
def load_header(self, aBuffer):
self.tag_cnt = 0
while aBuffer[12+4*self.tag_cnt:14+4*self.tag_cnt] in (b'\x81\x00', b'\x88\xa8', b'\x91\x00'):
self.tag_cnt += 1
hdr_len = self.get_header_size()
diff = hdr_len - len(aBuffer)
if diff > 0:
aBuffer += b'\x00'*diff
self.set_bytes_from_string(aBuffer[:hdr_len])
def get_header_size(self):
"Return size of Ethernet header"
return 14 + 4*self.tag_cnt
def get_packet(self):
if self.child():
try:
self.set_ether_type(self.child().ethertype)
except:
" an Ethernet packet may have a Data() "
pass
return Header.get_packet(self)
def get_ether_dhost(self):
"Return 48 bit destination ethernet address as a 6 byte array"
return self.get_bytes()[0:6]
def set_ether_dhost(self, aValue):
"Set destination ethernet address from 6 byte array 'aValue'"
for i in range(0, 6):
self.set_byte(i, aValue[i])
def get_ether_shost(self):
"Return 48 bit source ethernet address as a 6 byte array"
return self.get_bytes()[6:12]
def set_ether_shost(self, aValue):
"Set source ethernet address from 6 byte array 'aValue'"
for i in range(0, 6):
self.set_byte(i + 6, aValue[i])
@staticmethod
def as_eth_addr(anArray):
tmp_list = [x > 15 and '%x'%x or '0%x'%x for x in anArray]
return '' + reduce(lambda x, y: x+':'+y, tmp_list)
def __str__(self):
tmp_str = 'Ether: ' + self.as_eth_addr(self.get_ether_shost()) + ' -> '
tmp_str += self.as_eth_addr(self.get_ether_dhost())
if self.child():
tmp_str += '\n' + str( self.child())
return tmp_str
def __validate_tag_index(self, index):
"""Adjusts negative indices to their absolute equivalents.
Raises IndexError when out of range <0, self.tag_cnt-1>."""
if index < 0:
index += self.tag_cnt
if index < 0 or index >= self.tag_cnt:
raise IndexError("Tag index out of range")
return index
# Linux "cooked" capture encapsulation.
# Used, for instance, for packets returned by the "any" interface.
class LinuxSLL(Header):
type_descriptions = [
"sent to us by somebody else",
"broadcast by somebody else",
"multicast by somebody else",
"sent to somebody else to somebody else",
"sent by us",
]
def __init__(self, aBuffer = None):
Header.__init__(self, 16)
if (aBuffer):
self.load_header(aBuffer)
def set_type(self, type):
"Sets the packet type field to type"
self.set_word(0, type)
def get_type(self):
"Returns the packet type field"
return self.get_word(0)
def set_arphdr(self, value):
"Sets the ARPHDR value for the link layer device type"
self.set_word(2, type)
def get_arphdr(self):
"Returns the ARPHDR value for the link layer device type"
return self.get_word(2)
def set_addr_len(self, len):
"Sets the length of the sender's address field to len"
self.set_word(4, len)
def get_addr_len(self):
"Returns the length of the sender's address field"
return self.get_word(4)
def set_addr(self, addr):
"Sets the sender's address field to addr. Addr must be at most 8-byte long."
if (len(addr) < 8):
addr += b'\0' * (8 - len(addr))
self.get_bytes()[6:14] = addr
def get_addr(self):
"Returns the sender's address field"
return array_tobytes(self.get_bytes()[6:14])
def set_ether_type(self, aValue):
"Set ethernet data type field to 'aValue'"
self.set_word(14, aValue)
def get_ether_type(self):
"Return ethernet data type field"
return self.get_word(14)
def get_header_size(self):
"Return size of packet header"
return 16
def get_packet(self):
if self.child():
self.set_ether_type(self.child().ethertype)
return Header.get_packet(self)
def get_type_desc(self):
type = self.get_type()
if type < len(LinuxSLL.type_descriptions):
return LinuxSLL.type_descriptions[type]
else:
return "Unknown"
def __str__(self):
ss = []
alen = self.get_addr_len()
addr = hexlify(self.get_addr()[0:alen])
ss.append("Linux SLL: addr=%s type=`%s'" % (addr, self.get_type_desc()))
if self.child():
ss.append(str(self.child()))
return '\n'.join(ss)
class IP(Header):
ethertype = 0x800
def __init__(self, aBuffer = None):
Header.__init__(self, 20)
self.set_ip_v(4)
self.set_ip_hl(5)
self.set_ip_ttl(255)
self.__option_list = []
if(aBuffer):
# When decoding, checksum shouldn't be modified
self.auto_checksum = 0
self.load_header(aBuffer)
if sys.platform.count('bsd'):
self.is_BSD = True
else:
self.is_BSD = False
def get_packet(self):
# set protocol
if self.get_ip_p() == 0 and self.child():
self.set_ip_p(self.child().protocol)
# set total length
if self.get_ip_len() == 0:
self.set_ip_len(self.get_size())
child_data = self.get_data_as_string()
if self.auto_checksum:
self.reset_ip_sum()
my_bytes = self.get_bytes()
for op in self.__option_list:
my_bytes.extend(op.get_bytes())
# Pad to a multiple of 4 bytes
num_pad = (4 - (len(my_bytes) % 4)) % 4
if num_pad:
array_frombytes(my_bytes, b"\0" * num_pad)
# only change ip_hl value if options are present
if len(self.__option_list):
self.set_ip_hl(len(my_bytes) // 4)
# set the checksum if the user hasn't modified it
if self.auto_checksum:
self.set_ip_sum(self.compute_checksum(my_bytes))
if child_data is None:
return array_tobytes(my_bytes)
else:
return array_tobytes(my_bytes) + child_data
# def calculate_checksum(self, buffer = None):
# tmp_value = self.get_ip_sum()
# if self.auto_checksum and (not tmp_value):
# if buffer:
# tmp_bytes = buffer
# else:
# tmp_bytes = self.bytes[0:self.get_header_size()]
#
# self.set_ip_sum(self.compute_checksum(tmp_bytes))
def get_pseudo_header(self):
pseudo_buf = array.array("B")
pseudo_buf.extend(self.get_bytes()[12:20])
pseudo_buf.fromlist([0])
pseudo_buf.extend(self.get_bytes()[9:10])
tmp_size = self.child().get_size()
size_str = struct.pack("!H", tmp_size)
array_frombytes(pseudo_buf, size_str)
return pseudo_buf
def add_option(self, option):
self.__option_list.append(option)
sum = 0
for op in self.__option_list:
sum += op.get_len()
if sum > 40:
raise ImpactPacketException("Options overflowed in IP packet with length: %d" % sum)
def get_ip_v(self):
n = self.get_byte(0)
return (n >> 4)
def set_ip_v(self, value):
n = self.get_byte(0)
version = value & 0xF
n = n & 0xF
n = n | (version << 4)
self.set_byte(0, n)
def get_ip_hl(self):
n = self.get_byte(0)
return (n & 0xF)
def set_ip_hl(self, value):
n = self.get_byte(0)
len = value & 0xF
n = n & 0xF0
n = (n | len)
self.set_byte(0, n)
def get_ip_tos(self):
return self.get_byte(1)
def set_ip_tos(self,value):
self.set_byte(1, value)
def get_ip_len(self):
if self.is_BSD:
return self.get_word(2, order = '=')
else:
return self.get_word(2)
def set_ip_len(self, value):
if self.is_BSD:
self.set_word(2, value, order = '=')
else:
self.set_word(2, value)
def get_ip_id(self):
return self.get_word(4)
def set_ip_id(self, value):
return self.set_word(4, value)
def get_ip_off(self):
if self.is_BSD:
return self.get_word(6, order = '=')
else:
return self.get_word(6)
def set_ip_off(self, aValue):
if self.is_BSD:
self.set_word(6, aValue, order = '=')
else:
self.set_word(6, aValue)
def get_ip_offmask(self):
return self.get_ip_off() & 0x1FFF
def set_ip_offmask(self, aValue):
tmp_value = self.get_ip_off() & 0xD000
tmp_value |= aValue
self.set_ip_off(tmp_value)
def get_ip_rf(self):
return self.get_ip_off() & 0x8000
def set_ip_rf(self, aValue):
tmp_value = self.get_ip_off()
if aValue:
tmp_value |= 0x8000
else:
my_not = 0xFFFF ^ 0x8000
tmp_value &= my_not
self.set_ip_off(tmp_value)
def get_ip_df(self):
return self.get_ip_off() & 0x4000
def set_ip_df(self, aValue):
tmp_value = self.get_ip_off()
if aValue:
tmp_value |= 0x4000
else:
my_not = 0xFFFF ^ 0x4000
tmp_value &= my_not
self.set_ip_off(tmp_value)
def get_ip_mf(self):
return self.get_ip_off() & 0x2000
def set_ip_mf(self, aValue):
tmp_value = self.get_ip_off()
if aValue:
tmp_value |= 0x2000
else:
my_not = 0xFFFF ^ 0x2000
tmp_value &= my_not
self.set_ip_off(tmp_value)
def fragment_by_list(self, aList):
if self.child():
proto = self.child().protocol
else:
proto = 0
child_data = self.get_data_as_string()
if not child_data:
return [self]
ip_header_bytes = self.get_bytes()
current_offset = 0
fragment_list = []
for frag_size in aList:
ip = IP()
ip.set_bytes(ip_header_bytes) # copy of original header
ip.set_ip_p(proto)
if frag_size % 8: # round this fragment size up to next multiple of 8
frag_size += 8 - (frag_size % 8)
ip.set_ip_offmask(current_offset // 8)
current_offset += frag_size
data = Data(child_data[:frag_size])
child_data = child_data[frag_size:]
ip.set_ip_len(20 + data.get_size())
ip.contains(data)
if child_data: