/
packet.py
2532 lines (2277 loc) · 89 KB
/
packet.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
# SPDX-License-Identifier: GPL-2.0-only
# This file is part of Scapy
# See https://scapy.net/ for more information
# Copyright (C) Philippe Biondi <phil@secdev.org>
"""
Packet class
Provides:
- the default Packet classes
- binding mechanisms
- fuzz() method
- exploration methods: explore() / ls()
"""
from __future__ import absolute_import
from __future__ import print_function
from collections import defaultdict
import re
import time
import itertools
import copy
import types
import warnings
from scapy.fields import (
AnyField,
BitField,
ConditionalField,
Emph,
EnumField,
Field,
FlagsField,
MultiEnumField,
MultipleTypeField,
PacketListField,
RawVal,
StrField,
)
from scapy.config import conf, _version_checker
from scapy.compat import raw, orb, bytes_encode
from scapy.base_classes import BasePacket, Gen, SetGen, Packet_metaclass, \
_CanvasDumpExtended
from scapy.interfaces import _GlobInterfaceType
from scapy.volatile import RandField, VolatileValue
from scapy.utils import import_hexcap, tex_escape, colgen, issubtype, \
pretty_list, EDecimal
from scapy.error import Scapy_Exception, log_runtime, warning
from scapy.libs.test_pyx import PYX
import scapy.libs.six as six
# Typing imports
from scapy.compat import (
Any,
Callable,
Dict,
Iterator,
List,
NoReturn,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
Sequence,
cast,
)
try:
import pyx
except ImportError:
pass
_T = TypeVar("_T", Dict[str, Any], Optional[Dict[str, Any]])
# six.with_metaclass typing is glitchy
class Packet(six.with_metaclass(Packet_metaclass, # type: ignore
BasePacket, _CanvasDumpExtended)):
__slots__ = [
"time", "sent_time", "name",
"default_fields", "fields", "fieldtype",
"overload_fields", "overloaded_fields",
"packetfields",
"original", "explicit", "raw_packet_cache",
"raw_packet_cache_fields", "_pkt", "post_transforms",
# then payload, underlayer and parent
"payload", "underlayer", "parent",
"name",
# used for sr()
"_answered",
# used when sniffing
"direction", "sniffed_on",
# handle snaplen Vs real length
"wirelen",
"comment"
]
name = None
fields_desc = [] # type: Sequence[AnyField]
deprecated_fields = {} # type: Dict[str, Tuple[str, str]]
overload_fields = {} # type: Dict[Type[Packet], Dict[str, Any]]
payload_guess = [] # type: List[Tuple[Dict[str, Any], Type[Packet]]]
show_indent = 1
show_summary = True
match_subclass = False
class_dont_cache = {} # type: Dict[Type[Packet], bool]
class_packetfields = {} # type: Dict[Type[Packet], Any]
class_default_fields = {} # type: Dict[Type[Packet], Dict[str, Any]]
class_default_fields_ref = {} # type: Dict[Type[Packet], List[str]]
class_fieldtype = {} # type: Dict[Type[Packet], Dict[str, AnyField]] # noqa: E501
@classmethod
def from_hexcap(cls):
# type: (Type[Packet]) -> Packet
return cls(import_hexcap())
@classmethod
def upper_bonds(self):
# type: () -> None
for fval, upper in self.payload_guess:
print("%-20s %s" % (upper.__name__, ", ".join("%-12s" % ("%s=%r" % i) for i in six.iteritems(fval)))) # noqa: E501
@classmethod
def lower_bonds(self):
# type: () -> None
for lower, fval in six.iteritems(self._overload_fields):
print("%-20s %s" % (lower.__name__, ", ".join("%-12s" % ("%s=%r" % i) for i in six.iteritems(fval)))) # noqa: E501
def __init__(self,
_pkt=b"", # type: Union[bytes, bytearray]
post_transform=None, # type: Any
_internal=0, # type: int
_underlayer=None, # type: Optional[Packet]
_parent=None, # type: Optional[Packet]
**fields # type: Any
):
# type: (...) -> None
self.time = time.time() # type: Union[EDecimal, float]
self.sent_time = None # type: Union[EDecimal, float, None]
self.name = (self.__class__.__name__
if self._name is None else
self._name)
self.default_fields = {} # type: Dict[str, Any]
self.overload_fields = self._overload_fields
self.overloaded_fields = {} # type: Dict[str, Any]
self.fields = {} # type: Dict[str, Any]
self.fieldtype = {} # type: Dict[str, AnyField]
self.packetfields = [] # type: List[AnyField]
self.payload = NoPayload()
self.init_fields()
self.underlayer = _underlayer
self.parent = _parent
if isinstance(_pkt, bytearray):
_pkt = bytes(_pkt)
self.original = _pkt
self.explicit = 0
self.raw_packet_cache = None # type: Optional[bytes]
self.raw_packet_cache_fields = None # type: Optional[Dict[str, Any]] # noqa: E501
self.wirelen = None # type: Optional[int]
self.direction = None # type: Optional[int]
self.sniffed_on = None # type: Optional[_GlobInterfaceType]
self.comment = None # type: Optional[bytes]
if _pkt:
self.dissect(_pkt)
if not _internal:
self.dissection_done(self)
# We use this strange initialization so that the fields
# are initialized in their declaration order.
# It is required to always support MultipleTypeField
for field in self.fields_desc:
fname = field.name
try:
value = fields.pop(fname)
except KeyError:
continue
self.fields[fname] = value if isinstance(value, RawVal) else \
self.get_field(fname).any2i(self, value)
# The remaining fields are unknown
for fname in fields:
if fname in self.deprecated_fields:
# Resolve deprecated fields
value = fields[fname]
fname = self._resolve_alias(fname)
self.fields[fname] = value if isinstance(value, RawVal) else \
self.get_field(fname).any2i(self, value)
continue
raise AttributeError(fname)
if isinstance(post_transform, list):
self.post_transforms = post_transform
elif post_transform is None:
self.post_transforms = []
else:
self.post_transforms = [post_transform]
_PickleType = Tuple[
Union[EDecimal, float],
Optional[Union[EDecimal, float, None]],
Optional[int],
Optional[_GlobInterfaceType],
Optional[int],
Optional[bytes],
]
def __reduce__(self):
# type: () -> Tuple[Type[Packet], Tuple[bytes], Packet._PickleType]
"""Used by pickling methods"""
return (self.__class__, (self.build(),), (
self.time,
self.sent_time,
self.direction,
self.sniffed_on,
self.wirelen,
self.comment
))
def __setstate__(self, state):
# type: (Packet._PickleType) -> Packet
"""Rebuild state using pickable methods"""
self.time = state[0]
self.sent_time = state[1]
self.direction = state[2]
self.sniffed_on = state[3]
self.wirelen = state[4]
self.comment = state[5]
return self
def __deepcopy__(self,
memo, # type: Any
):
# type: (...) -> Packet
"""Used by copy.deepcopy"""
return self.copy()
def init_fields(self):
# type: () -> None
"""
Initialize each fields of the fields_desc dict
"""
if self.class_dont_cache.get(self.__class__, False):
self.do_init_fields(self.fields_desc)
else:
self.do_init_cached_fields()
def do_init_fields(self,
flist, # type: Sequence[AnyField]
):
# type: (...) -> None
"""
Initialize each fields of the fields_desc dict
"""
default_fields = {}
for f in flist:
default_fields[f.name] = copy.deepcopy(f.default)
self.fieldtype[f.name] = f
if f.holds_packets:
self.packetfields.append(f)
# We set default_fields last to avoid race issues
self.default_fields = default_fields
def do_init_cached_fields(self):
# type: () -> None
"""
Initialize each fields of the fields_desc dict, or use the cached
fields information
"""
cls_name = self.__class__
# Build the fields information
if Packet.class_default_fields.get(cls_name, None) is None:
self.prepare_cached_fields(self.fields_desc)
# Use fields information from cache
default_fields = Packet.class_default_fields.get(cls_name, None)
if default_fields:
self.default_fields = default_fields
self.fieldtype = Packet.class_fieldtype[cls_name]
self.packetfields = Packet.class_packetfields[cls_name]
# Deepcopy default references
for fname in Packet.class_default_fields_ref[cls_name]:
value = self.default_fields[fname]
try:
self.fields[fname] = value.copy()
except AttributeError:
# Python 2.7 - list only
self.fields[fname] = value[:]
def prepare_cached_fields(self, flist):
# type: (Sequence[AnyField]) -> None
"""
Prepare the cached fields of the fields_desc dict
"""
cls_name = self.__class__
# Fields cache initialization
if not flist:
return
class_default_fields = dict()
class_default_fields_ref = list()
class_fieldtype = dict()
class_packetfields = list()
# Fields initialization
for f in flist:
if isinstance(f, MultipleTypeField):
# Abort
self.class_dont_cache[cls_name] = True
self.do_init_fields(self.fields_desc)
return
tmp_copy = copy.deepcopy(f.default)
class_default_fields[f.name] = tmp_copy
class_fieldtype[f.name] = f
if f.holds_packets:
class_packetfields.append(f)
# Remember references
if isinstance(f.default, (list, dict, set, RandField, Packet)):
class_default_fields_ref.append(f.name)
# Apply
Packet.class_default_fields_ref[cls_name] = class_default_fields_ref
Packet.class_fieldtype[cls_name] = class_fieldtype
Packet.class_packetfields[cls_name] = class_packetfields
# Last to avoid racing issues
Packet.class_default_fields[cls_name] = class_default_fields
def dissection_done(self, pkt):
# type: (Packet) -> None
"""DEV: will be called after a dissection is completed"""
self.post_dissection(pkt)
self.payload.dissection_done(pkt)
def post_dissection(self, pkt):
# type: (Packet) -> None
"""DEV: is called after the dissection of the whole packet"""
pass
def get_field(self, fld):
# type: (str) -> AnyField
"""DEV: returns the field instance from the name of the field"""
return self.fieldtype[fld]
def add_payload(self, payload):
# type: (Union[Packet, bytes]) -> None
if payload is None:
return
elif not isinstance(self.payload, NoPayload):
self.payload.add_payload(payload)
else:
if isinstance(payload, Packet):
self.payload = payload
payload.add_underlayer(self)
for t in self.aliastypes:
if t in payload.overload_fields:
self.overloaded_fields = payload.overload_fields[t]
break
elif isinstance(payload, (bytes, str, bytearray, memoryview)):
self.payload = conf.raw_layer(load=bytes_encode(payload))
else:
raise TypeError("payload must be 'Packet', 'bytes', 'str', 'bytearray', or 'memoryview', not [%s]" % repr(payload)) # noqa: E501
def remove_payload(self):
# type: () -> None
self.payload.remove_underlayer(self)
self.payload = NoPayload()
self.overloaded_fields = {}
def add_underlayer(self, underlayer):
# type: (Packet) -> None
self.underlayer = underlayer
def remove_underlayer(self, other):
# type: (Packet) -> None
self.underlayer = None
def add_parent(self, parent):
# type: (Packet) -> None
"""Set packet parent.
When packet is an element in PacketListField, parent field would
point to the list owner packet."""
self.parent = parent
def remove_parent(self, other):
# type: (Packet) -> None
"""Remove packet parent.
When packet is an element in PacketListField, parent field would
point to the list owner packet."""
self.parent = None
def copy(self):
# type: () -> Packet
"""Returns a deep copy of the instance."""
clone = self.__class__()
clone.fields = self.copy_fields_dict(self.fields)
clone.default_fields = self.copy_fields_dict(self.default_fields)
clone.overloaded_fields = self.overloaded_fields.copy()
clone.underlayer = self.underlayer
clone.parent = self.parent
clone.explicit = self.explicit
clone.raw_packet_cache = self.raw_packet_cache
clone.raw_packet_cache_fields = self.copy_fields_dict(
self.raw_packet_cache_fields
)
clone.wirelen = self.wirelen
clone.post_transforms = self.post_transforms[:]
clone.payload = self.payload.copy()
clone.payload.add_underlayer(clone)
clone.time = self.time
clone.comment = self.comment
return clone
def _resolve_alias(self, attr):
# type: (str) -> str
new_attr, version = self.deprecated_fields[attr]
warnings.warn(
"%s has been deprecated in favor of %s since %s !" % (
attr, new_attr, version
), DeprecationWarning
)
return new_attr
def getfieldval(self, attr):
# type: (str) -> Any
if self.deprecated_fields and attr in self.deprecated_fields:
attr = self._resolve_alias(attr)
if attr in self.fields:
return self.fields[attr]
if attr in self.overloaded_fields:
return self.overloaded_fields[attr]
if attr in self.default_fields:
return self.default_fields[attr]
return self.payload.getfieldval(attr)
def getfield_and_val(self, attr):
# type: (str) -> Tuple[AnyField, Any]
if self.deprecated_fields and attr in self.deprecated_fields:
attr = self._resolve_alias(attr)
if attr in self.fields:
return self.get_field(attr), self.fields[attr]
if attr in self.overloaded_fields:
return self.get_field(attr), self.overloaded_fields[attr]
if attr in self.default_fields:
return self.get_field(attr), self.default_fields[attr]
raise ValueError
def __getattr__(self, attr):
# type: (str) -> Any
try:
fld, v = self.getfield_and_val(attr)
except ValueError:
return self.payload.__getattr__(attr)
if fld is not None:
return v if isinstance(v, RawVal) else fld.i2h(self, v)
return v
def setfieldval(self, attr, val):
# type: (str, Any) -> None
if self.deprecated_fields and attr in self.deprecated_fields:
attr = self._resolve_alias(attr)
if attr in self.default_fields:
fld = self.get_field(attr)
if fld is None:
any2i = lambda x, y: y # type: Callable[..., Any]
else:
any2i = fld.any2i
self.fields[attr] = val if isinstance(val, RawVal) else \
any2i(self, val)
self.explicit = 0
self.raw_packet_cache = None
self.raw_packet_cache_fields = None
self.wirelen = None
elif attr == "payload":
self.remove_payload()
self.add_payload(val)
else:
self.payload.setfieldval(attr, val)
def __setattr__(self, attr, val):
# type: (str, Any) -> None
if attr in self.__all_slots__:
return object.__setattr__(self, attr, val)
try:
return self.setfieldval(attr, val)
except AttributeError:
pass
return object.__setattr__(self, attr, val)
def delfieldval(self, attr):
# type: (str) -> None
if attr in self.fields:
del self.fields[attr]
self.explicit = 0 # in case a default value must be explicit
self.raw_packet_cache = None
self.raw_packet_cache_fields = None
self.wirelen = None
elif attr in self.default_fields:
pass
elif attr == "payload":
self.remove_payload()
else:
self.payload.delfieldval(attr)
def __delattr__(self, attr):
# type: (str) -> None
if attr == "payload":
return self.remove_payload()
if attr in self.__all_slots__:
return object.__delattr__(self, attr)
try:
return self.delfieldval(attr)
except AttributeError:
pass
return object.__delattr__(self, attr)
def _superdir(self):
# type: () -> Set[str]
"""
Return a list of slots and methods, including those from subclasses.
"""
attrs = set()
cls = self.__class__
if hasattr(cls, '__all_slots__'):
attrs.update(cls.__all_slots__)
for bcls in cls.__mro__:
if hasattr(bcls, '__dict__'):
attrs.update(bcls.__dict__)
return attrs
def __dir__(self):
# type: () -> List[str]
"""
Add fields to tab completion list.
"""
return sorted(itertools.chain(self._superdir(), self.default_fields))
def __repr__(self):
# type: () -> str
s = ""
ct = conf.color_theme
for f in self.fields_desc:
if isinstance(f, ConditionalField) and not f._evalcond(self):
continue
if f.name in self.fields:
fval = self.fields[f.name]
if isinstance(fval, (list, dict, set)) and len(fval) == 0:
continue
val = f.i2repr(self, fval)
elif f.name in self.overloaded_fields:
fover = self.overloaded_fields[f.name]
if isinstance(fover, (list, dict, set)) and len(fover) == 0:
continue
val = f.i2repr(self, fover)
else:
continue
if isinstance(f, Emph) or f in conf.emph:
ncol = ct.emph_field_name
vcol = ct.emph_field_value
else:
ncol = ct.field_name
vcol = ct.field_value
s += " %s%s%s" % (ncol(f.name),
ct.punct("="),
vcol(val))
return "%s%s %s %s%s%s" % (ct.punct("<"),
ct.layer_name(self.__class__.__name__),
s,
ct.punct("|"),
repr(self.payload),
ct.punct(">"))
if six.PY2:
def __str__(self):
# type: () -> str
return self.build()
else:
def __str__(self):
# type: () -> str
return self.summary()
def __bytes__(self):
# type: () -> bytes
return self.build()
def __div__(self, other):
# type: (Any) -> Packet
if isinstance(other, Packet):
cloneA = self.copy()
cloneB = other.copy()
cloneA.add_payload(cloneB)
return cloneA
elif isinstance(other, (bytes, str, bytearray, memoryview)):
return self / conf.raw_layer(load=bytes_encode(other))
else:
return other.__rdiv__(self) # type: ignore
__truediv__ = __div__
def __rdiv__(self, other):
# type: (Any) -> Packet
if isinstance(other, (bytes, str, bytearray, memoryview)):
return conf.raw_layer(load=bytes_encode(other)) / self
else:
raise TypeError
__rtruediv__ = __rdiv__
def __mul__(self, other):
# type: (Any) -> List[Packet]
if isinstance(other, int):
return [self] * other
else:
raise TypeError
def __rmul__(self, other):
# type: (Any) -> List[Packet]
return self.__mul__(other)
def __nonzero__(self):
# type: () -> bool
return True
__bool__ = __nonzero__
def __len__(self):
# type: () -> int
return len(self.__bytes__())
def copy_field_value(self, fieldname, value):
# type: (str, Any) -> Any
return self.get_field(fieldname).do_copy(value)
def copy_fields_dict(self, fields):
# type: (_T) -> _T
if fields is None:
return None
return {fname: self.copy_field_value(fname, fval)
for fname, fval in six.iteritems(fields)}
def clear_cache(self):
# type: () -> None
"""Clear the raw packet cache for the field and all its subfields"""
self.raw_packet_cache = None
for fld, fval in six.iteritems(self.fields):
fld = self.get_field(fld)
if fld.holds_packets:
if isinstance(fval, Packet):
fval.clear_cache()
elif isinstance(fval, list):
for fsubval in fval:
fsubval.clear_cache()
self.payload.clear_cache()
def self_build(self):
# type: () -> bytes
"""
Create the default layer regarding fields_desc dict
:param field_pos_list:
"""
if self.raw_packet_cache is not None:
for fname, fval in six.iteritems(self.raw_packet_cache_fields):
if self.getfieldval(fname) != fval:
self.raw_packet_cache = None
self.raw_packet_cache_fields = None
self.wirelen = None
break
if self.raw_packet_cache is not None:
return self.raw_packet_cache
p = b""
for f in self.fields_desc:
val = self.getfieldval(f.name)
if isinstance(val, RawVal):
p += bytes(val)
else:
try:
p = f.addfield(self, p, val)
except Exception as ex:
try:
ex.args = (
"While dissecting field '%s': " % f.name +
ex.args[0],
) + ex.args[1:]
except (AttributeError, IndexError):
pass
raise ex
return p
def do_build_payload(self):
# type: () -> bytes
"""
Create the default version of the payload layer
:return: a string of payload layer
"""
return self.payload.do_build()
def do_build(self):
# type: () -> bytes
"""
Create the default version of the layer
:return: a string of the packet with the payload
"""
if not self.explicit:
self = next(iter(self))
pkt = self.self_build()
for t in self.post_transforms:
pkt = t(pkt)
pay = self.do_build_payload()
if self.raw_packet_cache is None:
return self.post_build(pkt, pay)
else:
return pkt + pay
def build_padding(self):
# type: () -> bytes
return self.payload.build_padding()
def build(self):
# type: () -> bytes
"""
Create the current layer
:return: string of the packet with the payload
"""
p = self.do_build()
p += self.build_padding()
p = self.build_done(p)
return p
def post_build(self, pkt, pay):
# type: (bytes, bytes) -> bytes
"""
DEV: called right after the current layer is build.
:param str pkt: the current packet (build by self_build function)
:param str pay: the packet payload (build by do_build_payload function)
:return: a string of the packet with the payload
"""
return pkt + pay
def build_done(self, p):
# type: (bytes) -> bytes
return self.payload.build_done(p)
def do_build_ps(self):
# type: () -> Tuple[bytes, List[Tuple[Packet, List[Tuple[Field[Any, Any], str, bytes]]]]] # noqa: E501
p = b""
pl = []
q = b""
for f in self.fields_desc:
if isinstance(f, ConditionalField) and not f._evalcond(self):
continue
p = f.addfield(self, p, self.getfieldval(f.name))
if isinstance(p, bytes):
r = p[len(q):]
q = p
else:
r = b""
pl.append((f, f.i2repr(self, self.getfieldval(f.name)), r))
pkt, lst = self.payload.build_ps(internal=1)
p += pkt
lst.append((self, pl))
return p, lst
def build_ps(self, internal=0):
# type: (int) -> Tuple[bytes, List[Tuple[Packet, List[Tuple[Any, Any, bytes]]]]] # noqa: E501
p, lst = self.do_build_ps()
# if not internal:
# pkt = self
# while pkt.haslayer(conf.padding_layer):
# pkt = pkt.getlayer(conf.padding_layer)
# lst.append( (pkt, [ ("loakjkjd", pkt.load, pkt.load) ] ) )
# p += pkt.load
# pkt = pkt.payload
return p, lst
def canvas_dump(self, layer_shift=0, rebuild=1):
# type: (int, int) -> pyx.canvas.canvas
if PYX == 0:
raise ImportError("PyX and its dependencies must be installed")
canvas = pyx.canvas.canvas()
if rebuild:
_, t = self.__class__(raw(self)).build_ps()
else:
_, t = self.build_ps()
YTXTI = len(t)
for _, l in t:
YTXTI += len(l)
YTXT = float(YTXTI)
YDUMP = YTXT
XSTART = 1
XDSTART = 10
y = 0.0
yd = 0.0
XMUL = 0.55
YMUL = 0.4
backcolor = colgen(0.6, 0.8, 1.0, trans=pyx.color.rgb)
forecolor = colgen(0.2, 0.5, 0.8, trans=pyx.color.rgb)
# backcolor=makecol(0.376, 0.729, 0.525, 1.0)
def hexstr(x):
# type: (bytes) -> str
return " ".join("%02x" % orb(c) for c in x)
def make_dump_txt(x, y, txt):
# type: (int, float, bytes) -> pyx.text.text
return pyx.text.text(
XDSTART + x * XMUL,
(YDUMP - y) * YMUL,
r"\tt{%s}" % hexstr(txt),
[pyx.text.size.Large]
)
def make_box(o):
# type: (pyx.bbox.bbox) -> pyx.bbox.bbox
return pyx.box.rect(
o.left(), o.bottom(), o.width(), o.height(),
relcenter=(0.5, 0.5)
)
def make_frame(lst):
# type: (List[Any]) -> pyx.path.path
if len(lst) == 1:
b = lst[0].bbox()
b.enlarge(pyx.unit.u_pt)
return b.path()
else:
fb = lst[0].bbox()
fb.enlarge(pyx.unit.u_pt)
lb = lst[-1].bbox()
lb.enlarge(pyx.unit.u_pt)
if len(lst) == 2 and fb.left() > lb.right():
return pyx.path.path(pyx.path.moveto(fb.right(), fb.top()),
pyx.path.lineto(fb.left(), fb.top()),
pyx.path.lineto(fb.left(), fb.bottom()), # noqa: E501
pyx.path.lineto(fb.right(), fb.bottom()), # noqa: E501
pyx.path.moveto(lb.left(), lb.top()),
pyx.path.lineto(lb.right(), lb.top()),
pyx.path.lineto(lb.right(), lb.bottom()), # noqa: E501
pyx.path.lineto(lb.left(), lb.bottom())) # noqa: E501
else:
# XXX
gb = lst[1].bbox()
if gb != lb:
gb.enlarge(pyx.unit.u_pt)
kb = lst[-2].bbox()
if kb != gb and kb != lb:
kb.enlarge(pyx.unit.u_pt)
return pyx.path.path(pyx.path.moveto(fb.left(), fb.top()),
pyx.path.lineto(fb.right(), fb.top()),
pyx.path.lineto(fb.right(), kb.bottom()), # noqa: E501
pyx.path.lineto(lb.right(), kb.bottom()), # noqa: E501
pyx.path.lineto(lb.right(), lb.bottom()), # noqa: E501
pyx.path.lineto(lb.left(), lb.bottom()), # noqa: E501
pyx.path.lineto(lb.left(), gb.top()),
pyx.path.lineto(fb.left(), gb.top()),
pyx.path.closepath(),)
def make_dump(s, # type: bytes
shift=0, # type: int
y=0., # type: float
col=None, # type: pyx.color.color
bkcol=None, # type: pyx.color.color
large=16 # type: int
):
# type: (...) -> Tuple[pyx.canvas.canvas, pyx.bbox.bbox, int, float] # noqa: E501
c = pyx.canvas.canvas()
tlist = []
while s:
dmp, s = s[:large - shift], s[large - shift:]
txt = make_dump_txt(shift, y, dmp)
tlist.append(txt)
shift += len(dmp)
if shift >= 16:
shift = 0
y += 1
if col is None:
col = pyx.color.rgb.red
if bkcol is None:
bkcol = pyx.color.rgb.white
c.stroke(make_frame(tlist), [col, pyx.deco.filled([bkcol]), pyx.style.linewidth.Thick]) # noqa: E501
for txt in tlist:
c.insert(txt)
return c, tlist[-1].bbox(), shift, y
last_shift, last_y = 0, 0.0
while t:
bkcol = next(backcolor)
proto, fields = t.pop()
y += 0.5
pt = pyx.text.text(
XSTART,
(YTXT - y) * YMUL,
r"\font\cmssfont=cmss10\cmssfont{%s}" % tex_escape(
str(proto.name)
),
[pyx.text.size.Large]
)
y += 1
ptbb = pt.bbox()
ptbb.enlarge(pyx.unit.u_pt * 2)
canvas.stroke(ptbb.path(), [pyx.color.rgb.black, pyx.deco.filled([bkcol])]) # noqa: E501
canvas.insert(pt)
for field, fval, fdump in fields:
col = next(forecolor)
ft = pyx.text.text(XSTART, (YTXT - y) * YMUL, r"\font\cmssfont=cmss10\cmssfont{%s}" % tex_escape(field.name)) # noqa: E501
if isinstance(field, BitField):
fsize = '%sb' % field.size
else:
fsize = '%sB' % len(fdump)
if (hasattr(field, 'field') and
'LE' in field.field.__class__.__name__[:3] or
'LE' in field.__class__.__name__[:3]):
fsize = r'$\scriptstyle\langle$' + fsize
st = pyx.text.text(XSTART + 3.4, (YTXT - y) * YMUL, r"\font\cmbxfont=cmssbx10 scaled 600\cmbxfont{%s}" % fsize, [pyx.text.halign.boxright]) # noqa: E501
if isinstance(fval, str):
if len(fval) > 18:
fval = fval[:18] + "[...]"
else:
fval = ""
vt = pyx.text.text(XSTART + 3.5, (YTXT - y) * YMUL, r"\font\cmssfont=cmss10\cmssfont{%s}" % tex_escape(fval)) # noqa: E501
y += 1.0
if fdump:
dt, target, last_shift, last_y = make_dump(fdump, last_shift, last_y, col, bkcol) # noqa: E501
dtb = target
vtb = vt.bbox()
bxvt = make_box(vtb)
bxdt = make_box(dtb)
dtb.enlarge(pyx.unit.u_pt)
try:
if yd < 0:
cnx = pyx.connector.curve(bxvt, bxdt, absangle1=0, absangle2=-90) # noqa: E501
else:
cnx = pyx.connector.curve(bxvt, bxdt, absangle1=0, absangle2=90) # noqa: E501
except Exception:
pass
else:
canvas.stroke(cnx, [pyx.style.linewidth.thin, pyx.deco.earrow.small, col]) # noqa: E501
canvas.insert(dt)
canvas.insert(ft)
canvas.insert(st)
canvas.insert(vt)
last_y += layer_shift
return canvas
def extract_padding(self, s):
# type: (bytes) -> Tuple[bytes, Optional[bytes]]
"""
DEV: to be overloaded to extract current layer's padding.
:param str s: the current layer
:return: a couple of strings (actual layer, padding)
"""
return s, None
def post_dissect(self, s):
# type: (bytes) -> bytes
"""DEV: is called right after the current layer has been dissected"""
return s
def pre_dissect(self, s):
# type: (bytes) -> bytes
"""DEV: is called right before the current layer is dissected"""
return s
def do_dissect(self, s):
# type: (bytes) -> bytes
_raw = s
self.raw_packet_cache_fields = {}
for f in self.fields_desc:
if not s:
break
s, fval = f.getfield(self, s)
# Skip unused ConditionalField
if isinstance(f, ConditionalField) and fval is None:
continue
# We need to track fields with mutable values to discard
# .raw_packet_cache when needed.
if f.islist or f.holds_packets or f.ismutable:
self.raw_packet_cache_fields[f.name] = f.do_copy(fval)
self.fields[f.name] = fval
self.raw_packet_cache = _raw[:-len(s)] if s else _raw
self.explicit = 1
return s
def do_dissect_payload(self, s):
# type: (bytes) -> None