This repository has been archived by the owner on May 11, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fields.py
2570 lines (1993 loc) · 80.8 KB
/
fields.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
# -*- mode: python3; indent-tabs-mode: nil; tab-width: 4 -*-
# This file is part of Scapy
# See http://www.secdev.org/projects/scapy for more information
# Copyright (C) Philippe Biondi <phil@secdev.org>
# Copyright (C) Michael Farrell <micolous+git@gmail.com>
# This program is published under a GPLv2 license
"""
Fields: basic data structures that make up parts of packets.
"""
from __future__ import absolute_import
import calendar
import collections
import copy
import inspect
import socket
import struct
import time
from types import MethodType
from uuid import UUID
from scapy.config import conf
from scapy.dadict import DADict
from scapy.volatile import RandBin, RandByte, RandEnumKeys, RandInt, \
RandIP, RandIP6, RandLong, RandMAC, RandNum, RandShort, RandSInt, \
RandSByte, RandTermString, RandUUID, VolatileValue, RandSShort, \
RandSLong, RandFloat
from scapy.data import EPOCH
from scapy.error import log_runtime, Scapy_Exception
from scapy.compat import bytes_hex, chb, orb, plain_str, raw, bytes_encode
from scapy.pton_ntop import inet_ntop, inet_pton
from scapy.utils import inet_aton, inet_ntoa, lhex, mac2str, str2mac
from scapy.utils6 import in6_6to4ExtractAddr, in6_isaddr6to4, \
in6_isaddrTeredo, in6_ptop, Net6, teredoAddrExtractInfo
from scapy.base_classes import BasePacket, Gen, Net, Field_metaclass
from scapy.error import warning
import scapy.modules.six as six
from scapy.modules.six.moves import range
"""
Helper class to specify a protocol extendable for runtime modifications
"""
class ObservableDict(dict):
def __init__(self, *args, **kw):
self.observers = []
super(ObservableDict, self).__init__(*args, **kw)
def observe(self, observer):
self.observers.append(observer)
def __setitem__(self, key, value):
for o in self.observers:
o.notify_set(self, key, value)
super(ObservableDict, self).__setitem__(key, value)
def __delitem__(self, key):
for o in self.observers:
o.notify_del(self, key)
super(ObservableDict, self).__delitem__(key)
def update(self, anotherDict):
for k in anotherDict:
self[k] = anotherDict[k]
############
# Fields #
############
class Field(six.with_metaclass(Field_metaclass, object)):
"""For more information on how this work, please refer to
http://www.secdev.org/projects/scapy/files/scapydoc.pdf
chapter ``Adding a New Field''"""
__slots__ = ["name", "fmt", "default", "sz", "owners"]
islist = 0
ismutable = False
holds_packets = 0
def __init__(self, name, default, fmt="H"):
self.name = name
if fmt[0] in "@=<>!":
self.fmt = fmt
else:
self.fmt = "!" + fmt
self.default = self.any2i(None, default)
self.sz = struct.calcsize(self.fmt)
self.owners = []
def register_owner(self, cls):
self.owners.append(cls)
def i2len(self, pkt, x):
"""Convert internal value to a length usable by a FieldLenField"""
return self.sz
def i2count(self, pkt, x):
"""Convert internal value to a number of elements usable by a FieldLenField.
Always 1 except for list fields"""
return 1
def h2i(self, pkt, x):
"""Convert human value to internal value"""
return x
def i2h(self, pkt, x):
"""Convert internal value to human value"""
return x
def m2i(self, pkt, x):
"""Convert machine value to internal value"""
return x
def i2m(self, pkt, x):
"""Convert internal value to machine value"""
if x is None:
x = 0
elif isinstance(x, str):
return bytes_encode(x)
return x
def any2i(self, pkt, x):
"""Try to understand the most input values possible and make an internal value from them""" # noqa: E501
return self.h2i(pkt, x)
def i2repr(self, pkt, x):
"""Convert internal value to a nice representation"""
return repr(self.i2h(pkt, x))
def addfield(self, pkt, s, val):
"""Add an internal value to a string
Copy the network representation of field `val` (belonging to layer
`pkt`) to the raw string packet `s`, and return the new string packet.
"""
return s + struct.pack(self.fmt, self.i2m(pkt, val))
def getfield(self, pkt, s):
"""Extract an internal value from a string
Extract from the raw packet `s` the field value belonging to layer
`pkt`.
Returns a two-element list,
first the raw packet string after having removed the extracted field,
second the extracted field itself in internal representation.
"""
return s[self.sz:], self.m2i(pkt, struct.unpack(self.fmt, s[:self.sz])[0]) # noqa: E501
def do_copy(self, x):
if hasattr(x, "copy"):
return x.copy()
if isinstance(x, list):
x = x[:]
for i in range(len(x)):
if isinstance(x[i], BasePacket):
x[i] = x[i].copy()
return x
def __repr__(self):
return "<Field (%s).%s>" % (",".join(x.__name__ for x in self.owners), self.name) # noqa: E501
def copy(self):
return copy.deepcopy(self)
def randval(self):
"""Return a volatile object whose value is both random and suitable for this field""" # noqa: E501
fmtt = self.fmt[-1]
if fmtt in "BbHhIiQq":
return {"B": RandByte, "b": RandSByte,
"H": RandShort, "h": RandSShort,
"I": RandInt, "i": RandSInt,
"Q": RandLong, "q": RandSLong}[fmtt]()
elif fmtt == "s":
if self.fmt[0] in "0123456789":
value = int(self.fmt[:-1])
else:
value = int(self.fmt[1:-1])
return RandBin(value)
else:
warning("no random class for [%s] (fmt=%s).", self.name, self.fmt)
class Emph(object):
"""Empathize sub-layer for display"""
__slots__ = ["fld"]
def __init__(self, fld):
self.fld = fld
def __getattr__(self, attr):
return getattr(self.fld, attr)
def __hash__(self):
return hash(self.fld)
def __eq__(self, other):
return self.fld == other
class ActionField(object):
__slots__ = ["_fld", "_action_method", "_privdata"]
def __init__(self, fld, action_method, **kargs):
self._fld = fld
self._action_method = action_method
self._privdata = kargs
def any2i(self, pkt, val):
getattr(pkt, self._action_method)(val, self._fld, **self._privdata)
return getattr(self._fld, "any2i")(pkt, val)
def __getattr__(self, attr):
return getattr(self._fld, attr)
class ConditionalField(object):
__slots__ = ["fld", "cond"]
def __init__(self, fld, cond):
self.fld = fld
self.cond = cond
def _evalcond(self, pkt):
return self.cond(pkt)
def getfield(self, pkt, s):
if self._evalcond(pkt):
return self.fld.getfield(pkt, s)
else:
return s, None
def addfield(self, pkt, s, val):
if self._evalcond(pkt):
return self.fld.addfield(pkt, s, val)
else:
return s
def __getattr__(self, attr):
return getattr(self.fld, attr)
class MultipleTypeField(object):
"""MultipleTypeField are used for fields that can be implemented by
various Field subclasses, depending on conditions on the packet.
It is initialized with `flds` and `dflt`.
`dflt` is the default field type, to be used when none of the
conditions matched the current packet.
`flds` is a list of tuples (`fld`, `cond`), where `fld` if a field
type, and `cond` a "condition" to determine if `fld` is the field type
that should be used.
`cond` is either:
- a callable `cond_pkt` that accepts one argument (the packet) and
returns True if `fld` should be used, False otherwise.
- a tuple (`cond_pkt`, `cond_pkt_val`), where `cond_pkt` is the same
as in the previous case and `cond_pkt_val` is a callable that
accepts two arguments (the packet, and the value to be set) and
returns True if `fld` should be used, False otherwise.
See scapy.layers.l2.ARP (type "help(ARP)" in Scapy) for an example of
use.
"""
__slots__ = ["flds", "dflt", "name"]
def __init__(self, flds, dflt):
self.flds = flds
self.dflt = dflt
self.name = self.dflt.name
def _iterate_fields_cond(self, pkt, val, use_val):
"""Internal function used by _find_fld_pkt & _find_fld_pkt_val"""
# Iterate through the fields
for fld, cond in self.flds:
if isinstance(cond, tuple):
if use_val:
if cond[1](pkt, val):
return fld
continue
else:
cond = cond[0]
if cond(pkt):
return fld
return self.dflt
def _find_fld_pkt(self, pkt):
"""Given a Packet instance `pkt`, returns the Field subclass to be
used. If you know the value to be set (e.g., in .addfield()), use
._find_fld_pkt_val() instead.
"""
return self._iterate_fields_cond(pkt, None, False)
def _find_fld_pkt_val(self, pkt, val):
"""Given a Packet instance `pkt` and the value `val` to be set,
returns the Field subclass to be used, and the updated `val` if necessary.
"""
fld = self._iterate_fields_cond(pkt, val, True)
# Default ? (in this case, let's make sure it's up-do-date)
dflts_pkt = pkt.default_fields
if val == dflts_pkt[self.name] and self.name not in pkt.fields:
dflts_pkt[self.name] = fld.default
val = fld.default
return fld, val
def _find_fld(self):
"""Returns the Field subclass to be used, depending on the Packet
instance, or the default subclass.
DEV: since the Packet instance is not provided, we have to use a hack
to guess it. It should only be used if you cannot provide the current
Packet instance (for example, because of the current Scapy API).
If you have the current Packet instance, use ._find_fld_pkt_val() (if
the value to set is also known) of ._find_fld_pkt() instead.
"""
# Hack to preserve current Scapy API
# See https://stackoverflow.com/a/7272464/3223422
frame = inspect.currentframe().f_back.f_back
while frame is not None:
try:
pkt = frame.f_locals['self']
except KeyError:
pass
else:
if isinstance(pkt, tuple(self.dflt.owners)):
if not pkt.default_fields:
# Packet not initialized
return self.dflt
return self._find_fld_pkt(pkt)
frame = frame.f_back
return self.dflt
def getfield(self, pkt, s):
return self._find_fld_pkt(pkt).getfield(pkt, s)
def addfield(self, pkt, s, val):
fld, val = self._find_fld_pkt_val(pkt, val)
return fld.addfield(pkt, s, val)
def any2i(self, pkt, val):
fld, val = self._find_fld_pkt_val(pkt, val)
return fld.any2i(pkt, val)
def h2i(self, pkt, val):
fld, val = self._find_fld_pkt_val(pkt, val)
return fld.h2i(pkt, val)
def i2h(self, pkt, val):
fld, val = self._find_fld_pkt_val(pkt, val)
return fld.i2h(pkt, val)
def i2m(self, pkt, val):
fld, val = self._find_fld_pkt_val(pkt, val)
return fld.i2m(pkt, val)
def i2len(self, pkt, val):
fld, val = self._find_fld_pkt_val(pkt, val)
return fld.i2len(pkt, val)
def i2repr(self, pkt, val):
fld, val = self._find_fld_pkt_val(pkt, val)
return fld.i2repr(pkt, val)
def register_owner(self, cls):
for fld, _ in self.flds:
fld.owners.append(cls)
self.dflt.owners.append(cls)
def __getattr__(self, attr):
return getattr(self._find_fld(), attr)
class PadField(object):
"""Add bytes after the proxified field so that it ends at the specified
alignment from its beginning"""
__slots__ = ["_fld", "_align", "_padwith"]
def __init__(self, fld, align, padwith=None):
self._fld = fld
self._align = align
self._padwith = padwith or b""
def padlen(self, flen):
return -flen % self._align
def getfield(self, pkt, s):
remain, val = self._fld.getfield(pkt, s)
padlen = self.padlen(len(s) - len(remain))
return remain[padlen:], val
def addfield(self, pkt, s, val):
sval = self._fld.addfield(pkt, b"", val)
return s + sval + struct.pack("%is" % (self.padlen(len(sval))), self._padwith) # noqa: E501
def __getattr__(self, attr):
return getattr(self._fld, attr)
class ReversePadField(PadField):
"""Add bytes BEFORE the proxified field so that it starts at the specified
alignment from its beginning"""
def getfield(self, pkt, s):
# We need to get the length that has already been dissected
padlen = self.padlen(pkt._tmp_dissect_pos)
remain, val = self._fld.getfield(pkt, s[padlen:])
return remain, val
def addfield(self, pkt, s, val):
sval = self._fld.addfield(pkt, b"", val)
return s + struct.pack("%is" % (self.padlen(len(s))), self._padwith) + sval # noqa: E501
class FCSField(Field):
"""Special Field that gets its value from the end of the *packet*
(Note: not layer, but packet).
Mostly used for FCS
"""
def getfield(self, pkt, s):
previous_post_dissect = pkt.post_dissect
val = self.m2i(pkt, struct.unpack(self.fmt, s[-self.sz:])[0])
def _post_dissect(self, s):
# Reset packet to allow post_build
self.raw_packet_cache = None
self.post_dissect = previous_post_dissect
return previous_post_dissect(s)
pkt.post_dissect = MethodType(_post_dissect, pkt)
return s[:-self.sz], val
def addfield(self, pkt, s, val):
previous_post_build = pkt.post_build
value = struct.pack(self.fmt, self.i2m(pkt, val))
def _post_build(self, p, pay):
pay += value
self.post_build = previous_post_build
return previous_post_build(p, pay)
pkt.post_build = MethodType(_post_build, pkt)
return s
def i2repr(self, pkt, x):
return lhex(self.i2h(pkt, x))
class DestField(Field):
__slots__ = ["defaultdst"]
# Each subclass must have its own bindings attribute
# bindings = {}
def __init__(self, name, default):
self.defaultdst = default
def dst_from_pkt(self, pkt):
for addr, condition in self.bindings.get(pkt.payload.__class__, []):
try:
if all(pkt.payload.getfieldval(field) == value
for field, value in six.iteritems(condition)):
return addr
except AttributeError:
pass
return self.defaultdst
@classmethod
def bind_addr(cls, layer, addr, **condition):
cls.bindings.setdefault(layer, []).append((addr, condition))
class MACField(Field):
def __init__(self, name, default):
Field.__init__(self, name, default, "6s")
def i2m(self, pkt, x):
if x is None:
return b"\0\0\0\0\0\0"
return mac2str(x)
def m2i(self, pkt, x):
return str2mac(x)
def any2i(self, pkt, x):
if isinstance(x, bytes) and len(x) == 6:
x = self.m2i(pkt, x)
return x
def i2repr(self, pkt, x):
x = self.i2h(pkt, x)
if self in conf.resolve:
x = conf.manufdb._resolve_MAC(x)
return x
def randval(self):
return RandMAC()
class IPField(Field):
slots = []
def __init__(self, name, default):
Field.__init__(self, name, default, "4s")
def h2i(self, pkt, x):
if isinstance(x, bytes):
x = plain_str(x)
if isinstance(x, str):
try:
inet_aton(x)
except socket.error:
x = Net(x)
elif isinstance(x, list):
x = [self.h2i(pkt, n) for n in x]
return x
def resolve(self, x):
if self in conf.resolve:
try:
ret = socket.gethostbyaddr(x)[0]
except Exception:
pass
else:
if ret:
return ret
return x
def i2m(self, pkt, x):
if x is None:
return b'\x00\x00\x00\x00'
return inet_aton(plain_str(x))
def m2i(self, pkt, x):
return inet_ntoa(x)
def any2i(self, pkt, x):
return self.h2i(pkt, x)
def i2repr(self, pkt, x):
r = self.resolve(self.i2h(pkt, x))
return r if isinstance(r, str) else repr(r)
def randval(self):
return RandIP()
class SourceIPField(IPField):
__slots__ = ["dstname"]
def __init__(self, name, dstname):
IPField.__init__(self, name, None)
self.dstname = dstname
def __findaddr(self, pkt):
if conf.route is None:
# unused import, only to initialize conf.route
import scapy.route # noqa: F401
dst = ("0.0.0.0" if self.dstname is None
else getattr(pkt, self.dstname) or "0.0.0.0")
if isinstance(dst, (Gen, list)):
r = {conf.route.route(str(daddr)) for daddr in dst}
if len(r) > 1:
warning("More than one possible route for %r" % (dst,))
return min(r)[1]
return conf.route.route(dst)[1]
def i2m(self, pkt, x):
if x is None:
x = self.__findaddr(pkt)
return IPField.i2m(self, pkt, x)
def i2h(self, pkt, x):
if x is None:
x = self.__findaddr(pkt)
return IPField.i2h(self, pkt, x)
class IP6Field(Field):
def __init__(self, name, default):
Field.__init__(self, name, default, "16s")
def h2i(self, pkt, x):
if isinstance(x, bytes):
x = plain_str(x)
if isinstance(x, str):
try:
x = in6_ptop(x)
except socket.error:
x = Net6(x)
elif isinstance(x, list):
x = [self.h2i(pkt, n) for n in x]
return x
def i2m(self, pkt, x):
if x is None:
x = "::"
return inet_pton(socket.AF_INET6, plain_str(x))
def m2i(self, pkt, x):
return inet_ntop(socket.AF_INET6, x)
def any2i(self, pkt, x):
return self.h2i(pkt, x)
def i2repr(self, pkt, x):
if x is None:
return self.i2h(pkt, x)
elif not isinstance(x, Net6) and not isinstance(x, list):
if in6_isaddrTeredo(x): # print Teredo info
server, _, maddr, mport = teredoAddrExtractInfo(x)
return "%s [Teredo srv: %s cli: %s:%s]" % (self.i2h(pkt, x), server, maddr, mport) # noqa: E501
elif in6_isaddr6to4(x): # print encapsulated address
vaddr = in6_6to4ExtractAddr(x)
return "%s [6to4 GW: %s]" % (self.i2h(pkt, x), vaddr)
r = self.i2h(pkt, x) # No specific information to return
return r if isinstance(r, str) else repr(r)
def randval(self):
return RandIP6()
class SourceIP6Field(IP6Field):
__slots__ = ["dstname"]
def __init__(self, name, dstname):
IP6Field.__init__(self, name, None)
self.dstname = dstname
def i2m(self, pkt, x):
if x is None:
dst = ("::" if self.dstname is None else
getattr(pkt, self.dstname) or "::")
iff, x, nh = conf.route6.route(dst)
return IP6Field.i2m(self, pkt, x)
def i2h(self, pkt, x):
if x is None:
if conf.route6 is None:
# unused import, only to initialize conf.route6
import scapy.route6 # noqa: F401
dst = ("::" if self.dstname is None else getattr(pkt, self.dstname)) # noqa: E501
if isinstance(dst, (Gen, list)):
r = {conf.route6.route(str(daddr)) for daddr in dst}
if len(r) > 1:
warning("More than one possible route for %r" % (dst,))
x = min(r)[1]
else:
x = conf.route6.route(dst)[1]
return IP6Field.i2h(self, pkt, x)
class DestIP6Field(IP6Field, DestField):
bindings = {}
def __init__(self, name, default):
IP6Field.__init__(self, name, None)
DestField.__init__(self, name, default)
def i2m(self, pkt, x):
if x is None:
x = self.dst_from_pkt(pkt)
return IP6Field.i2m(self, pkt, x)
def i2h(self, pkt, x):
if x is None:
x = self.dst_from_pkt(pkt)
return IP6Field.i2h(self, pkt, x)
class ByteField(Field):
def __init__(self, name, default):
Field.__init__(self, name, default, "B")
class XByteField(ByteField):
def i2repr(self, pkt, x):
return lhex(self.i2h(pkt, x))
class OByteField(ByteField):
def i2repr(self, pkt, x):
return "%03o" % self.i2h(pkt, x)
class ThreeBytesField(ByteField):
def __init__(self, name, default):
Field.__init__(self, name, default, "!I")
def addfield(self, pkt, s, val):
return s + struct.pack(self.fmt, self.i2m(pkt, val))[1:4]
def getfield(self, pkt, s):
return s[3:], self.m2i(pkt, struct.unpack(self.fmt, b"\x00" + s[:3])[0]) # noqa: E501
class X3BytesField(ThreeBytesField, XByteField):
def i2repr(self, pkt, x):
return XByteField.i2repr(self, pkt, x)
class LEThreeBytesField(ByteField):
def __init__(self, name, default):
Field.__init__(self, name, default, "<I")
def addfield(self, pkt, s, val):
return s + struct.pack(self.fmt, self.i2m(pkt, val))[:3]
def getfield(self, pkt, s):
return s[3:], self.m2i(pkt, struct.unpack(self.fmt, s[:3] + b"\x00")[0]) # noqa: E501
class LEX3BytesField(LEThreeBytesField, XByteField):
def i2repr(self, pkt, x):
return XByteField.i2repr(self, pkt, x)
class SignedByteField(Field):
def __init__(self, name, default):
Field.__init__(self, name, default, "b")
class FieldValueRangeException(Scapy_Exception):
pass
class FieldAttributeException(Scapy_Exception):
pass
class YesNoByteField(ByteField):
"""
byte based flag field that shows representation of its number based on a given association # noqa: E501
in its default configuration the following representation is generated:
x == 0 : 'no'
x != 0 : 'yes'
in more sophisticated use-cases (e.g. yes/no/invalid) one can use the config attribute to configure # noqa: E501
key-value, key-range and key-value-set associations that will be used to generate the values representation. # noqa: E501
a range is given by a tuple (<first-val>, <last-value>) including the last value. a single-value tuple # noqa: E501
is treated as scalar.
a list defines a set of (probably non consecutive) values that should be associated to a given key. # noqa: E501
all values not associated with a key will be shown as number of type unsigned byte. # noqa: E501
config = {
'no' : 0,
'foo' : (1,22),
'yes' : 23,
'bar' : [24,25, 42, 48, 87, 253]
}
generates the following representations:
x == 0 : 'no'
x == 15: 'foo'
x == 23: 'yes'
x == 42: 'bar'
x == 43: 43
using the config attribute one could also revert the stock-yes-no-behavior:
config = {
'yes' : 0,
'no' : (1,255)
}
will generate the following value representation:
x == 0 : 'yes'
x != 0 : 'no'
"""
__slots__ = ['eval_fn']
def _build_config_representation(self, config):
assoc_table = dict()
for key in config:
value_spec = config[key]
value_spec_type = type(value_spec)
if value_spec_type is int:
if value_spec < 0 or value_spec > 255:
raise FieldValueRangeException('given field value {} invalid - ' # noqa: E501
'must be in range [0..255]'.format(value_spec)) # noqa: E501
assoc_table[value_spec] = key
elif value_spec_type is list:
for value in value_spec:
if value < 0 or value > 255:
raise FieldValueRangeException('given field value {} invalid - ' # noqa: E501
'must be in range [0..255]'.format(value)) # noqa: E501
assoc_table[value] = key
elif value_spec_type is tuple:
value_spec_len = len(value_spec)
if value_spec_len != 2:
raise FieldAttributeException('invalid length {} of given config item tuple {} - must be ' # noqa: E501
'(<start-range>, <end-range>).'.format(value_spec_len, value_spec)) # noqa: E501
value_range_start = value_spec[0]
if value_range_start < 0 or value_range_start > 255:
raise FieldValueRangeException('given field value {} invalid - ' # noqa: E501
'must be in range [0..255]'.format(value_range_start)) # noqa: E501
value_range_end = value_spec[1]
if value_range_end < 0 or value_range_end > 255:
raise FieldValueRangeException('given field value {} invalid - ' # noqa: E501
'must be in range [0..255]'.format(value_range_end)) # noqa: E501
for value in range(value_range_start, value_range_end + 1):
assoc_table[value] = key
self.eval_fn = lambda x: assoc_table[x] if x in assoc_table else x
def __init__(self, name, default, config=None, *args, **kargs):
if not config:
# this represents the common use case and therefore it is kept small # noqa: E501
self.eval_fn = lambda x: 'no' if x == 0 else 'yes'
else:
self._build_config_representation(config)
ByteField.__init__(self, name, default, *args, **kargs)
def i2repr(self, pkt, x):
return self.eval_fn(x)
class ShortField(Field):
def __init__(self, name, default):
Field.__init__(self, name, default, "H")
class SignedShortField(Field):
def __init__(self, name, default):
Field.__init__(self, name, default, "h")
class LEShortField(Field):
def __init__(self, name, default):
Field.__init__(self, name, default, "<H")
class XShortField(ShortField):
def i2repr(self, pkt, x):
return lhex(self.i2h(pkt, x))
class IntField(Field):
def __init__(self, name, default):
Field.__init__(self, name, default, "I")
class SignedIntField(Field):
def __init__(self, name, default):
Field.__init__(self, name, default, "i")
class LEIntField(Field):
def __init__(self, name, default):
Field.__init__(self, name, default, "<I")
class LESignedIntField(Field):
def __init__(self, name, default):
Field.__init__(self, name, default, "<i")
class XIntField(IntField):
def i2repr(self, pkt, x):
return lhex(self.i2h(pkt, x))
class XLEIntField(LEIntField, XIntField):
def i2repr(self, pkt, x):
return XIntField.i2repr(self, pkt, x)
class XLEShortField(LEShortField, XShortField):
def i2repr(self, pkt, x):
return XShortField.i2repr(self, pkt, x)
class LongField(Field):
def __init__(self, name, default):
Field.__init__(self, name, default, "Q")
class LELongField(LongField):
def __init__(self, name, default):
Field.__init__(self, name, default, "<Q")
class XLongField(LongField):
def i2repr(self, pkt, x):
return lhex(self.i2h(pkt, x))
class XLELongField(LELongField, XLongField):
def i2repr(self, pkt, x):
return XLongField.i2repr(self, pkt, x)
class IEEEFloatField(Field):
def __init__(self, name, default):
Field.__init__(self, name, default, "f")
class IEEEDoubleField(Field):
def __init__(self, name, default):
Field.__init__(self, name, default, "d")
class StrField(Field):
__slots__ = ["remain"]
def __init__(self, name, default, fmt="H", remain=0):
Field.__init__(self, name, default, fmt)
self.remain = remain
def i2len(self, pkt, x):
return len(x)
def any2i(self, pkt, x):
if isinstance(x, six.text_type):
x = bytes_encode(x)
return super(StrField, self).any2i(pkt, x)
def i2repr(self, pkt, x):
val = super(StrField, self).i2repr(pkt, x)
if val[:2] in ['b"', "b'"]:
return val[1:]
return val
def i2m(self, pkt, x):
if x is None:
return b""
if not isinstance(x, bytes):
return bytes_encode(x)
return x
def addfield(self, pkt, s, val):
return s + self.i2m(pkt, val)
def getfield(self, pkt, s):
if self.remain == 0:
return b"", self.m2i(pkt, s)
else:
return s[-self.remain:], self.m2i(pkt, s[:-self.remain])
def randval(self):
return RandBin(RandNum(0, 1200))
class PacketField(StrField):
__slots__ = ["cls"]
holds_packets = 1
def __init__(self, name, default, cls, remain=0):
StrField.__init__(self, name, default, remain=remain)
self.cls = cls
def i2m(self, pkt, i):
if i is None:
return b""
return raw(i)
def m2i(self, pkt, m):
return self.cls(m)
def getfield(self, pkt, s):
i = self.m2i(pkt, s)
remain = b""
if conf.padding_layer in i:
r = i[conf.padding_layer]
del(r.underlayer.payload)
remain = r.load
return remain, i
def randval(self):
from scapy.packet import fuzz
return fuzz(self.cls())