forked from secdev/scapy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
4035 lines (3485 loc) · 131 KB
/
utils.py
File metadata and controls
4035 lines (3485 loc) · 131 KB
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>
"""
General utility functions.
"""
from decimal import Decimal
from io import StringIO
from itertools import zip_longest
from uuid import UUID
import argparse
import array
import base64
import collections
import decimal
import difflib
import gzip
import inspect
import locale
import math
import os
import pickle
import random
import re
import shutil
import socket
import struct
import subprocess
import sys
import tempfile
import threading
import time
import traceback
import warnings
from scapy.config import conf
from scapy.consts import DARWIN, OPENBSD, WINDOWS
from scapy.data import MTU, DLT_EN10MB, DLT_RAW
from scapy.compat import (
orb,
plain_str,
chb,
hex_bytes,
bytes_encode,
)
from scapy.error import (
log_interactive,
log_runtime,
Scapy_Exception,
warning,
)
from scapy.pton_ntop import inet_pton
# Typing imports
from typing import (
cast,
Any,
AnyStr,
Callable,
Dict,
IO,
Iterator,
List,
Optional,
TYPE_CHECKING,
Tuple,
Type,
Union,
overload,
)
from scapy.compat import (
DecoratorCallable,
Literal,
)
if TYPE_CHECKING:
from scapy.packet import Packet
from scapy.plist import _PacketIterable, PacketList
from scapy.supersocket import SuperSocket
import prompt_toolkit
_ByteStream = Union[IO[bytes], gzip.GzipFile]
###########
# Tools #
###########
def issubtype(x, # type: Any
t, # type: Union[type, str]
):
# type: (...) -> bool
"""issubtype(C, B) -> bool
Return whether C is a class and if it is a subclass of class B.
When using a tuple as the second argument issubtype(X, (A, B, ...)),
is a shortcut for issubtype(X, A) or issubtype(X, B) or ... (etc.).
"""
if isinstance(t, str):
return t in (z.__name__ for z in x.__bases__)
if isinstance(x, type) and issubclass(x, t):
return True
return False
_Decimal = Union[Decimal, int]
class EDecimal(Decimal):
"""Extended Decimal
This implements arithmetic and comparison with float for
backward compatibility
"""
def __add__(self, other, context=None):
# type: (_Decimal, Any) -> EDecimal
return EDecimal(Decimal.__add__(self, Decimal(other)))
def __radd__(self, other):
# type: (_Decimal) -> EDecimal
return EDecimal(Decimal.__add__(self, Decimal(other)))
def __sub__(self, other):
# type: (_Decimal) -> EDecimal
return EDecimal(Decimal.__sub__(self, Decimal(other)))
def __rsub__(self, other):
# type: (_Decimal) -> EDecimal
return EDecimal(Decimal.__rsub__(self, Decimal(other)))
def __mul__(self, other):
# type: (_Decimal) -> EDecimal
return EDecimal(Decimal.__mul__(self, Decimal(other)))
def __rmul__(self, other):
# type: (_Decimal) -> EDecimal
return EDecimal(Decimal.__mul__(self, Decimal(other)))
def __truediv__(self, other):
# type: (_Decimal) -> EDecimal
return EDecimal(Decimal.__truediv__(self, Decimal(other)))
def __floordiv__(self, other):
# type: (_Decimal) -> EDecimal
return EDecimal(Decimal.__floordiv__(self, Decimal(other)))
def __divmod__(self, other):
# type: (_Decimal) -> Tuple[EDecimal, EDecimal]
r = Decimal.__divmod__(self, Decimal(other))
return EDecimal(r[0]), EDecimal(r[1])
def __mod__(self, other):
# type: (_Decimal) -> EDecimal
return EDecimal(Decimal.__mod__(self, Decimal(other)))
def __rmod__(self, other):
# type: (_Decimal) -> EDecimal
return EDecimal(Decimal.__rmod__(self, Decimal(other)))
def __pow__(self, other, modulo=None):
# type: (_Decimal, Optional[_Decimal]) -> EDecimal
return EDecimal(Decimal.__pow__(self, Decimal(other), modulo))
def __eq__(self, other):
# type: (Any) -> bool
if isinstance(other, Decimal):
return super(EDecimal, self).__eq__(other)
else:
return bool(float(self) == other)
def normalize(self, precision): # type: ignore
# type: (int) -> EDecimal
with decimal.localcontext() as ctx:
ctx.prec = precision
return EDecimal(super(EDecimal, self).normalize(ctx))
@overload
def get_temp_file(keep, autoext, fd):
# type: (bool, str, Literal[True]) -> IO[bytes]
pass
@overload
def get_temp_file(keep=False, autoext="", fd=False):
# type: (bool, str, Literal[False]) -> str
pass
def get_temp_file(keep=False, autoext="", fd=False):
# type: (bool, str, bool) -> Union[IO[bytes], str]
"""Creates a temporary file.
:param keep: If False, automatically delete the file when Scapy exits.
:param autoext: Suffix to add to the generated file name.
:param fd: If True, this returns a file-like object with the temporary
file opened. If False (default), this returns a file path.
"""
f = tempfile.NamedTemporaryFile(prefix="scapy", suffix=autoext,
delete=False)
if not keep:
conf.temp_files.append(f.name)
if fd:
return f
else:
# Close the file so something else can take it.
f.close()
return f.name
def get_temp_dir(keep=False):
# type: (bool) -> str
"""Creates a temporary file, and returns its name.
:param keep: If False (default), the directory will be recursively
deleted when Scapy exits.
:return: A full path to a temporary directory.
"""
dname = tempfile.mkdtemp(prefix="scapy")
if not keep:
conf.temp_files.append(dname)
return dname
def _create_fifo() -> Tuple[str, Any]:
"""Creates a temporary fifo.
You must then use open_fifo() on the server_fd once
the client is connected to use it.
:returns: (client_file, server_fd)
"""
if WINDOWS:
from scapy.arch.windows.structures import _get_win_fifo
return _get_win_fifo()
else:
f = get_temp_file()
os.unlink(f)
os.mkfifo(f)
return f, f
def _open_fifo(fd: Any, mode: str = "rb") -> IO[bytes]:
"""Open the server_fd (see create_fifo)
"""
if WINDOWS:
from scapy.arch.windows.structures import _win_fifo_open
return _win_fifo_open(fd)
else:
return open(fd, mode)
def sane(x, color=False):
# type: (AnyStr, bool) -> str
r = ""
for i in x:
j = orb(i)
if (j < 32) or (j >= 127):
if color:
r += conf.color_theme.not_printable(".")
else:
r += "."
else:
r += chr(j)
return r
@conf.commands.register
def restart():
# type: () -> None
"""Restarts scapy"""
if not conf.interactive or not os.path.isfile(sys.argv[0]):
raise OSError("Scapy was not started from console")
if WINDOWS:
res_code = 1
try:
res_code = subprocess.call([sys.executable] + sys.argv)
finally:
os._exit(res_code)
os.execv(sys.executable, [sys.executable] + sys.argv)
def lhex(x):
# type: (Any) -> str
from scapy.volatile import VolatileValue
if isinstance(x, VolatileValue):
return repr(x)
if isinstance(x, int):
return hex(x)
if isinstance(x, tuple):
return "(%s)" % ", ".join(lhex(v) for v in x)
if isinstance(x, list):
return "[%s]" % ", ".join(lhex(v) for v in x)
return str(x)
@conf.commands.register
def hexdump(p, dump=False):
# type: (Union[Packet, AnyStr], bool) -> Optional[str]
"""Build a tcpdump like hexadecimal view
:param p: a Packet
:param dump: define if the result must be printed or returned in a variable
:return: a String only when dump=True
"""
s = ""
x = bytes_encode(p)
x_len = len(x)
i = 0
while i < x_len:
s += "%04x " % i
for j in range(16):
if i + j < x_len:
s += "%02X " % orb(x[i + j])
else:
s += " "
s += " %s\n" % sane(x[i:i + 16], color=True)
i += 16
# remove trailing \n
s = s[:-1] if s.endswith("\n") else s
if dump:
return s
else:
print(s)
return None
@conf.commands.register
def linehexdump(p, onlyasc=0, onlyhex=0, dump=False):
# type: (Union[Packet, AnyStr], int, int, bool) -> Optional[str]
"""Build an equivalent view of hexdump() on a single line
Note that setting both onlyasc and onlyhex to 1 results in a empty output
:param p: a Packet
:param onlyasc: 1 to display only the ascii view
:param onlyhex: 1 to display only the hexadecimal view
:param dump: print the view if False
:return: a String only when dump=True
"""
s = ""
s = hexstr(p, onlyasc=onlyasc, onlyhex=onlyhex, color=not dump)
if dump:
return s
else:
print(s)
return None
@conf.commands.register
def chexdump(p, dump=False):
# type: (Union[Packet, AnyStr], bool) -> Optional[str]
"""Build a per byte hexadecimal representation
Example:
>>> chexdump(IP())
0x45, 0x00, 0x00, 0x14, 0x00, 0x01, 0x00, 0x00, 0x40, 0x00, 0x7c, 0xe7, 0x7f, 0x00, 0x00, 0x01, 0x7f, 0x00, 0x00, 0x01 # noqa: E501
:param p: a Packet
:param dump: print the view if False
:return: a String only if dump=True
"""
x = bytes_encode(p)
s = ", ".join("%#04x" % orb(x) for x in x)
if dump:
return s
else:
print(s)
return None
@conf.commands.register
def hexstr(p, onlyasc=0, onlyhex=0, color=False):
# type: (Union[Packet, AnyStr], int, int, bool) -> str
"""Build a fancy tcpdump like hex from bytes."""
x = bytes_encode(p)
s = []
if not onlyasc:
s.append(" ".join("%02X" % orb(b) for b in x))
if not onlyhex:
s.append(sane(x, color=color))
return " ".join(s)
def repr_hex(s):
# type: (bytes) -> str
""" Convert provided bitstring to a simple string of hex digits """
return "".join("%02x" % orb(x) for x in s)
@conf.commands.register
def hexdiff(
a: Union['Packet', AnyStr],
b: Union['Packet', AnyStr],
algo: Optional[str] = None,
autojunk: bool = False,
) -> None:
"""
Show differences between 2 binary strings, Packets...
Available algorithms:
- wagnerfischer: Use the Wagner and Fischer algorithm to compute the
Levenstein distance between the strings then backtrack.
- difflib: Use the difflib.SequenceMatcher implementation. This based on a
modified version of the Ratcliff and Obershelp algorithm.
This is much faster, but far less accurate.
https://docs.python.org/3.8/library/difflib.html#difflib.SequenceMatcher
:param a:
:param b: The binary strings, packets... to compare
:param algo: Force the algo to be 'wagnerfischer' or 'difflib'.
By default, this is chosen depending on the complexity, optimistically
preferring wagnerfischer unless really necessary.
:param autojunk: (difflib only) See difflib documentation.
"""
xb = bytes_encode(a)
yb = bytes_encode(b)
if algo is None:
# Choose the best algorithm
complexity = len(xb) * len(yb)
if complexity < 1e7:
# Comparing two (non-jumbos) Ethernet packets is ~2e6 which is manageable.
# Anything much larger than this shouldn't be attempted by default.
algo = "wagnerfischer"
if complexity > 1e6:
log_interactive.info(
"Complexity is a bit high. hexdiff will take a few seconds."
)
else:
algo = "difflib"
backtrackx = []
backtracky = []
if algo == "wagnerfischer":
xb = xb[::-1]
yb = yb[::-1]
# costs for the 3 operations
INSERT = 1
DELETE = 1
SUBST = 1
# Typically, d[i,j] will hold the distance between
# the first i characters of xb and the first j characters of yb.
# We change the Wagner Fischer to also store pointers to all
# the intermediate steps taken while calculating the Levenstein distance.
d = {(-1, -1): (0, (-1, -1))}
for j in range(len(yb)):
d[-1, j] = (j + 1) * INSERT, (-1, j - 1)
for i in range(len(xb)):
d[i, -1] = (i + 1) * INSERT + 1, (i - 1, -1)
# Compute the Levenstein distance between the two strings, but
# store all the steps to be able to backtrack at the end.
for j in range(len(yb)):
for i in range(len(xb)):
d[i, j] = min(
(d[i - 1, j - 1][0] + SUBST * (xb[i] != yb[j]), (i - 1, j - 1)),
(d[i - 1, j][0] + DELETE, (i - 1, j)),
(d[i, j - 1][0] + INSERT, (i, j - 1)),
)
# Iterate through the steps backwards to create the diff
i = len(xb) - 1
j = len(yb) - 1
while not (i == j == -1):
i2, j2 = d[i, j][1]
backtrackx.append(xb[i2 + 1:i + 1])
backtracky.append(yb[j2 + 1:j + 1])
i, j = i2, j2
elif algo == "difflib":
sm = difflib.SequenceMatcher(a=xb, b=yb, autojunk=autojunk)
xarr = [xb[i:i + 1] for i in range(len(xb))]
yarr = [yb[i:i + 1] for i in range(len(yb))]
# Iterate through opcodes to build the backtrack
for opcode in sm.get_opcodes():
typ, x0, x1, y0, y1 = opcode
if typ == 'delete':
backtrackx += xarr[x0:x1]
backtracky += [b''] * (x1 - x0)
elif typ == 'insert':
backtrackx += [b''] * (y1 - y0)
backtracky += yarr[y0:y1]
elif typ in ['equal', 'replace']:
backtrackx += xarr[x0:x1]
backtracky += yarr[y0:y1]
# Some lines may have been considered as junk. Check the sizes
if autojunk:
lbx = len(backtrackx)
lby = len(backtracky)
backtrackx += [b''] * (max(lbx, lby) - lbx)
backtracky += [b''] * (max(lbx, lby) - lby)
else:
raise ValueError("Unknown algorithm '%s'" % algo)
# Print the diff
x = y = i = 0
colorize: Dict[int, Callable[[str], str]] = {
0: lambda x: x,
-1: conf.color_theme.left,
1: conf.color_theme.right
}
dox = 1
doy = 0
btx_len = len(backtrackx)
while i < btx_len:
linex = backtrackx[i:i + 16]
liney = backtracky[i:i + 16]
xx = sum(len(k) for k in linex)
yy = sum(len(k) for k in liney)
if dox and not xx:
dox = 0
doy = 1
if dox and linex == liney:
doy = 1
if dox:
xd = y
j = 0
while not linex[j]:
j += 1
xd -= 1
print(colorize[doy - dox]("%04x" % xd), end=' ')
x += xx
line = linex
else:
print(" ", end=' ')
if doy:
yd = y
j = 0
while not liney[j]:
j += 1
yd -= 1
print(colorize[doy - dox]("%04x" % yd), end=' ')
y += yy
line = liney
else:
print(" ", end=' ')
print(" ", end=' ')
cl = ""
for j in range(16):
if i + j < min(len(backtrackx), len(backtracky)):
if line[j]:
col = colorize[(linex[j] != liney[j]) * (doy - dox)]
print(col("%02X" % orb(line[j])), end=' ')
if linex[j] == liney[j]:
cl += sane(line[j], color=True)
else:
cl += col(sane(line[j]))
else:
print(" ", end=' ')
cl += " "
else:
print(" ", end=' ')
if j == 7:
print("", end=' ')
print(" ", cl)
if doy or not yy:
doy = 0
dox = 1
i += 16
else:
if yy:
dox = 0
doy = 1
else:
i += 16
if struct.pack("H", 1) == b"\x00\x01": # big endian
checksum_endian_transform = lambda chk: chk # type: Callable[[int], int]
else:
checksum_endian_transform = lambda chk: ((chk >> 8) & 0xff) | chk << 8
def checksum(pkt):
# type: (bytes) -> int
if len(pkt) % 2 == 1:
pkt += b"\0"
s = sum(array.array("H", pkt))
s = (s >> 16) + (s & 0xffff)
s += s >> 16
s = ~s
return checksum_endian_transform(s) & 0xffff
def _fletcher16(charbuf):
# type: (bytes) -> Tuple[int, int]
# This is based on the GPLed C implementation in Zebra <http://www.zebra.org/> # noqa: E501
c0 = c1 = 0
for char in charbuf:
c0 += char
c1 += c0
c0 %= 255
c1 %= 255
return (c0, c1)
@conf.commands.register
def fletcher16_checksum(binbuf):
# type: (bytes) -> int
"""Calculates Fletcher-16 checksum of the given buffer.
Note:
If the buffer contains the two checkbytes derived from the Fletcher-16 checksum # noqa: E501
the result of this function has to be 0. Otherwise the buffer has been corrupted. # noqa: E501
"""
(c0, c1) = _fletcher16(binbuf)
return (c1 << 8) | c0
@conf.commands.register
def fletcher16_checkbytes(binbuf, offset):
# type: (bytes, int) -> bytes
"""Calculates the Fletcher-16 checkbytes returned as 2 byte binary-string.
Including the bytes into the buffer (at the position marked by offset) the # noqa: E501
global Fletcher-16 checksum of the buffer will be 0. Thus it is easy to verify # noqa: E501
the integrity of the buffer on the receiver side.
For details on the algorithm, see RFC 2328 chapter 12.1.7 and RFC 905 Annex B. # noqa: E501
"""
# This is based on the GPLed C implementation in Zebra <http://www.zebra.org/> # noqa: E501
if len(binbuf) < offset:
raise Exception("Packet too short for checkbytes %d" % len(binbuf))
binbuf = binbuf[:offset] + b"\x00\x00" + binbuf[offset + 2:]
(c0, c1) = _fletcher16(binbuf)
x = ((len(binbuf) - offset - 1) * c0 - c1) % 255
if (x <= 0):
x += 255
y = 510 - c0 - x
if (y > 255):
y -= 255
return chb(x) + chb(y)
def mac2str(mac):
# type: (str) -> bytes
return b"".join(chb(int(x, 16)) for x in plain_str(mac).split(':'))
def valid_mac(mac):
# type: (str) -> bool
try:
return len(mac2str(mac)) == 6
except ValueError:
pass
return False
def str2mac(s):
# type: (bytes) -> str
if isinstance(s, str):
return ("%02x:" * len(s))[:-1] % tuple(map(ord, s))
return ("%02x:" * len(s))[:-1] % tuple(s)
def randstring(length):
# type: (int) -> bytes
"""
Returns a random string of length (length >= 0)
"""
return b"".join(struct.pack('B', random.randint(0, 255))
for _ in range(length))
def zerofree_randstring(length):
# type: (int) -> bytes
"""
Returns a random string of length (length >= 0) without zero in it.
"""
return b"".join(struct.pack('B', random.randint(1, 255))
for _ in range(length))
def stror(s1, s2):
# type: (bytes, bytes) -> bytes
"""
Returns the binary OR of the 2 provided strings s1 and s2. s1 and s2
must be of same length.
"""
return b"".join(map(lambda x, y: struct.pack("!B", x | y), s1, s2))
def strxor(s1, s2):
# type: (bytes, bytes) -> bytes
"""
Returns the binary XOR of the 2 provided strings s1 and s2. s1 and s2
must be of same length.
"""
return b"".join(map(lambda x, y: struct.pack("!B", x ^ y), s1, s2))
def strand(s1, s2):
# type: (bytes, bytes) -> bytes
"""
Returns the binary AND of the 2 provided strings s1 and s2. s1 and s2
must be of same length.
"""
return b"".join(map(lambda x, y: struct.pack("!B", x & y), s1, s2))
def strrot(s1, count, right=True):
# type: (bytes, int, bool) -> bytes
"""
Rotate the binary by 'count' bytes
"""
off = count % len(s1)
if right:
return s1[-off:] + s1[:-off]
else:
return s1[off:] + s1[:off]
# Workaround bug 643005 : https://sourceforge.net/tracker/?func=detail&atid=105470&aid=643005&group_id=5470 # noqa: E501
try:
socket.inet_aton("255.255.255.255")
except socket.error:
def inet_aton(ip_string):
# type: (str) -> bytes
if ip_string == "255.255.255.255":
return b"\xff" * 4
else:
return socket.inet_aton(ip_string)
else:
inet_aton = socket.inet_aton # type: ignore
inet_ntoa = socket.inet_ntoa
def atol(x):
# type: (str) -> int
try:
ip = inet_aton(x)
except socket.error:
raise ValueError("Bad IP format: %s" % x)
return cast(int, struct.unpack("!I", ip)[0])
def valid_ip(addr):
# type: (str) -> bool
try:
addr = plain_str(addr)
except UnicodeDecodeError:
return False
try:
atol(addr)
except (OSError, ValueError, socket.error):
return False
return True
def valid_net(addr):
# type: (str) -> bool
try:
addr = plain_str(addr)
except UnicodeDecodeError:
return False
if '/' in addr:
ip, mask = addr.split('/', 1)
return valid_ip(ip) and mask.isdigit() and 0 <= int(mask) <= 32
return valid_ip(addr)
def valid_ip6(addr):
# type: (str) -> bool
try:
addr = plain_str(addr)
except UnicodeDecodeError:
return False
try:
inet_pton(socket.AF_INET6, addr)
except socket.error:
return False
return True
def valid_net6(addr):
# type: (str) -> bool
try:
addr = plain_str(addr)
except UnicodeDecodeError:
return False
if '/' in addr:
ip, mask = addr.split('/', 1)
return valid_ip6(ip) and mask.isdigit() and 0 <= int(mask) <= 128
return valid_ip6(addr)
def ltoa(x):
# type: (int) -> str
return inet_ntoa(struct.pack("!I", x & 0xffffffff))
def itom(x):
# type: (int) -> int
return (0xffffffff00000000 >> x) & 0xffffffff
def in4_cidr2mask(m):
# type: (int) -> bytes
"""
Return the mask (bitstring) associated with provided length
value. For instance if function is called on 20, return value is
b'\xff\xff\xf0\x00'.
"""
if m > 32 or m < 0:
raise Scapy_Exception("value provided to in4_cidr2mask outside [0, 32] domain (%d)" % m) # noqa: E501
return strxor(
b"\xff" * 4,
struct.pack(">I", 2**(32 - m) - 1)
)
def in4_isincluded(addr, prefix, mask):
# type: (str, str, int) -> bool
"""
Returns True when 'addr' belongs to prefix/mask. False otherwise.
"""
temp = inet_pton(socket.AF_INET, addr)
pref = in4_cidr2mask(mask)
zero = inet_pton(socket.AF_INET, prefix)
return zero == strand(temp, pref)
def in4_ismaddr(str):
# type: (str) -> bool
"""
Returns True if provided address in printable format belongs to
allocated Multicast address space (224.0.0.0/4).
"""
return in4_isincluded(str, "224.0.0.0", 4)
def in4_ismlladdr(str):
# type: (str) -> bool
"""
Returns True if address belongs to link-local multicast address
space (224.0.0.0/24)
"""
return in4_isincluded(str, "224.0.0.0", 24)
def in4_ismgladdr(str):
# type: (str) -> bool
"""
Returns True if address belongs to global multicast address
space (224.0.1.0-238.255.255.255).
"""
return (
in4_isincluded(str, "224.0.0.0", 4) and
not in4_isincluded(str, "224.0.0.0", 24) and
not in4_isincluded(str, "239.0.0.0", 8)
)
def in4_ismlsaddr(str):
# type: (str) -> bool
"""
Returns True if address belongs to limited scope multicast address
space (239.0.0.0/8).
"""
return in4_isincluded(str, "239.0.0.0", 8)
def in4_isaddrllallnodes(str):
# type: (str) -> bool
"""
Returns True if address is the link-local all-nodes multicast
address (224.0.0.1).
"""
return (inet_pton(socket.AF_INET, "224.0.0.1") ==
inet_pton(socket.AF_INET, str))
def in4_getnsmac(a):
# type: (bytes) -> str
"""
Return the multicast mac address associated with provided
IPv4 address. Passed address must be in network format.
"""
return "01:00:5e:%.2x:%.2x:%.2x" % (a[1] & 0x7f, a[2], a[3])
def decode_locale_str(x):
# type: (bytes) -> str
"""
Decode bytes into a string using the system locale.
Useful on Windows where it can be unusual (e.g. cp1252)
"""
return x.decode(encoding=locale.getlocale()[1] or "utf-8", errors="replace")
class ContextManagerSubprocess(object):
"""
Context manager that eases checking for unknown command, without
crashing.
Example:
>>> with ContextManagerSubprocess("tcpdump"):
>>> subprocess.Popen(["tcpdump", "--version"])
ERROR: Could not execute tcpdump, is it installed?
"""
def __init__(self, prog, suppress=True):
# type: (str, bool) -> None
self.prog = prog
self.suppress = suppress
def __enter__(self):
# type: () -> None
pass
def __exit__(self,
exc_type, # type: Optional[type]
exc_value, # type: Optional[Exception]
traceback, # type: Optional[Any]
):
# type: (...) -> Optional[bool]
if exc_value is None or exc_type is None:
return None
# Errored
if isinstance(exc_value, EnvironmentError):
msg = "Could not execute %s, is it installed?" % self.prog
else:
msg = "%s: execution failed (%s)" % (
self.prog,
exc_type.__class__.__name__
)
if not self.suppress:
raise exc_type(msg)
log_runtime.error(msg, exc_info=True)
return True # Suppress the exception
class ContextManagerCaptureOutput(object):
"""
Context manager that intercept the console's output.
Example:
>>> with ContextManagerCaptureOutput() as cmco:
... print("hey")
... assert cmco.get_output() == "hey"
"""
def __init__(self):
# type: () -> None
self.result_export_object = ""
def __enter__(self):
# type: () -> ContextManagerCaptureOutput
from unittest import mock
def write(s, decorator=self):
# type: (str, ContextManagerCaptureOutput) -> None
decorator.result_export_object += s
mock_stdout = mock.Mock()
mock_stdout.write = write
self.bck_stdout = sys.stdout
sys.stdout = mock_stdout
return self
def __exit__(self, *exc):
# type: (*Any) -> Literal[False]
sys.stdout = self.bck_stdout
return False
def get_output(self, eval_bytes=False):
# type: (bool) -> str
if self.result_export_object.startswith("b'") and eval_bytes:
return plain_str(eval(self.result_export_object))
return self.result_export_object