-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathregression.uts
More file actions
4908 lines (3868 loc) · 177 KB
/
regression.uts
File metadata and controls
4908 lines (3868 loc) · 177 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
% Regression tests for Scapy
# More information at http://www.secdev.org/projects/UTscapy/
############
############
+ Information on Scapy
= Setup
def expect_exception(e, c):
try:
c()
return False
except e:
return True
= Get conf
~ conf command
* Dump the current configuration
conf
IP().src
conf.loopback_name
= Test module version detection
~ conf
class FakeModule(object):
__version__ = "v1.12"
class FakeModule2(object):
__version__ = "5.143.3.12"
class FakeModule3(object):
__version__ = "v2.4.2.dev42"
from scapy.config import _version_checker
assert _version_checker(FakeModule, (1,11,5))
assert not _version_checker(FakeModule, (1,13))
assert _version_checker(FakeModule2, (5, 1))
assert not _version_checker(FakeModule2, (5, 143, 4))
assert _version_checker(FakeModule3, (2, 4, 2))
= Check Scapy version
from unittest import mock
import scapy
from scapy import _parse_tag, _version_from_git_describe
from scapy.config import _version_checker
b = Bunch(returncode=0, communicate=lambda *args, **kargs: (b"v2.4.5rc1-261-g44b98e14", None))
with mock.patch('scapy.subprocess.Popen', return_value=b):
with mock.patch('scapy.os.path.isdir', return_value=True):
class GitModuleScapy(object):
__version__ = _version_from_git_describe()
# GH3847
with mock.patch('scapy.subprocess.Popen', return_value=b):
with mock.patch('scapy.os.path.isdir', return_value=False):
try:
_version_from_git_describe()
assert False
except ValueError:
pass
assert GitModuleScapy.__version__ == '2.4.5rc1.dev261'
assert _version_checker(GitModuleScapy, (2, 4, 5))
= List layers
~ conf command
ls()
= List layers - advanced
~ conf command
with ContextManagerCaptureOutput() as cmco:
ls("IP", case_sensitive=True)
result_ls = cmco.get_output().split("\n")
assert all("IP" in x for x in result_ls if x.strip())
assert len(result_ls) >= 3
= List packet fields - ls
~ command
with ContextManagerCaptureOutput() as cmco:
ls(ARP(hwsrc="aa:aa:aa:aa:aa:aa", psrc="1.1.1.1"))
result_ls = cmco.get_output().split("\n")
result_ls
assert result_ls[5] == "hwsrc : MultipleTypeField (SourceMACField, StrFixedLenField) = 'aa:aa:aa:aa:aa:aa' ('None')"
assert result_ls[6] == "psrc : MultipleTypeField (SourceIPField, SourceIP6Field, StrFixedLenField) = '1.1.1.1' ('None')"
= List commands
~ conf command
lsc()
= List contribs
~ command
def test_list_contrib():
with ContextManagerCaptureOutput() as cmco:
list_contrib()
result_list_contrib = cmco.get_output()
assert "http2 : HTTP/2 (RFC 7540, RFC 7541) status=loads" in result_list_contrib
assert len(result_list_contrib.split('\n')) > 40
test_list_contrib()
= Test packet show() on LatexTheme
% with LatexTheme
class SmallPacket(Packet):
fields_desc = [ByteField("a", 0)]
conf_color_theme = conf.color_theme
conf.color_theme = LatexTheme()
pkt = SmallPacket()
with ContextManagerCaptureOutput() as cmco:
pkt.show()
result = cmco.get_output().strip()
assert result == '\\#\\#\\#[ \\textcolor{red}{\\bf SmallPacket} ]\\#\\#\\#\n \\textcolor{blue}{a} = \\textcolor{purple}{0}'
conf.color_theme = conf_color_theme
= Test rfc()
~ command
dat = rfc(IP, ret=True).split("\n")
assert dat[0].replace(" ", "").strip() == "0123"
assert "0123456789" in dat[1].replace(" ", "")
for l in dat:
# only upper case and +-
assert re.match(r"[A-Z+-]*", l)
# Add a space before each + to avoid conflicts with UTscapy !
# They will be stripped below
result = """
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|VERSION| IHL | TOS | LEN |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| ID |FLAGS| FRAG |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| TTL | PROTO | CHKSUM |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| SRC |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| DST |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| OPTIONS |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Fig. IP
""".strip()
result = [x.strip() for x in result.split("\n")]
output = [x.strip() for x in rfc(IP, ret=True).strip().split("\n")]
assert result == output
result = """
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| CODE | ID | LEN |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| TYPE |L|M|S|RES|VERSI| MESSAGE LEN |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| | DATA |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Fig. EAP_TTLS
""".strip()
result = [x.strip() for x in result.split("\n")]
output = [x.strip() for x in rfc(EAP_TTLS, ret=True).strip().split("\n")]
assert result == output
result = """
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|VERSION| TC | FL |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| PLEN | NH | HLIM |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| SRC |
+ +
| |
+ +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| DST |
+ +
| |
+ +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Fig. IPv6
""".strip()
result = [x.strip() for x in result.split("\n")]
output = [x.strip() for x in rfc(IPv6, ret=True).strip().split("\n")]
assert result == output
class TestPad(Packet):
fields_desc = [ShortField("f0", 0),
ShortField("f1", 0),
PadField(ByteField("f2", 1), 8),
PadField(ShortField("f3", 0), 4)]
result = """
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| F0 | F1 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| F2 | padding |
+-+-+-+-+-+-+-+-+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| F3 | padding |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Fig. TestPad
""".strip()
result = [x.strip() for x in result.split("\n")]
output = [x.strip() for x in rfc(TestPad, ret=True).strip().split("\n")]
assert result == output
= Check that all contrib modules are well-configured
~ command
list_contrib(_debug=True)
= Configuration
~ conf
conf.debug_dissector = True
= Configuration conf.use_* LINUX
~ linux
try:
conf.use_bpf = True
assert False
except:
True
assert not conf.use_bpf
= Configuration conf.use_* WINDOWS
~ windows
try:
conf.use_bpf = True
assert False
except:
True
assert not conf.use_bpf
= Configuration conf.use_pcap
~ linux libpcap
if not conf.use_pcap:
assert not conf.iface.provider.libpcap
conf.use_pcap = True
assert conf.iface.provider.libpcap
for iface in conf.ifaces.values():
assert iface.provider.libpcap or iface.is_valid() == False
conf.use_pcap = False
assert not conf.iface.provider.libpcap
= Test layer filtering
~ filter
pkt = NetflowHeader()/NetflowHeaderV5()/NetflowRecordV5()
conf.layers.filter([NetflowHeader, NetflowHeaderV5])
assert NetflowRecordV5 not in NetflowHeader(bytes(pkt))
# Conf.ifaces.reload() should still work (arch/* is exempt)
conf.ifaces.reload()
conf.layers.unfilter()
assert NetflowRecordV5 in NetflowHeader(bytes(pkt))
###########
###########
= UTscapy route check
* Check that UTscapy has correctly replaced the routes. Many tests won't work otherwise
p = IP().src
p
assert p == "127.0.0.1"
############
############
+ Scapy functions tests
= Interface related functions
from unittest import mock
conf.iface
get_if_addr(conf.iface)
get_if_hwaddr(conf.iface)
bytes_hex(get_if_raw_addr(conf.iface))
def get_dummy_interface():
"""Returns a dummy network interface"""
conf.ifaces._add_fake_iface("dummy0")
return "dummy0"
get_if_raw_addr(get_dummy_interface())
get_if_list()
get_working_if()
get_if_raw_addr6(conf.iface)
= More Interfaces related functions
# Test name resolution
old = conf.iface
conf.iface = conf.iface.name
assert conf.iface == old
assert isinstance(conf.iface, NetworkInterface)
assert conf.iface.is_valid()
from unittest import mock
@mock.patch("scapy.interfaces.conf.route.routes", [])
@mock.patch("scapy.interfaces.conf.ifaces.values")
def _test_get_working_if(rou):
rou.side_effect = lambda: []
assert get_working_if() is None
assert conf.iface + "a" # left +
assert "hey! are you, ready to go ? %s" % conf.iface # format
assert "cuz you know the way to go" + conf.iface # right +
_test_get_working_if()
= Test conf.ifaces
conf.iface
conf.ifaces
assert conf.iface in conf.ifaces.values()
assert conf.ifaces.dev_from_index(conf.iface.index) == conf.iface
assert conf.ifaces.dev_from_networkname(conf.iface.network_name) == conf.iface
conf.ifaces.data = {'a': NetworkInterface(InterfaceProvider(), {"name": 'a', "network_name": 'a', "description": 'a', "ips": ["127.0.0.1", "::1", "::2", "127.0.0.2"], "mac": 'aa:aa:aa:aa:aa:aa'})}
with ContextManagerCaptureOutput() as cmco:
conf.ifaces.show()
output = cmco.get_output()
data = """
Source Index Name MAC IPv4 IPv6
Unknown 0 a aa:aa:aa:aa:aa:aa 127.0.0.1 ::1
127.0.0.2 ::2
""".strip()
output = [x.strip() for x in output.strip().split("\n")]
data = [x.strip() for x in data.strip().split("\n")]
assert output == data
conf.ifaces.reload()
= Test extcap detection in conf.ifaces
~ linux extcap
import os
from scapy.libs.extcap import load_extcap
_bkp_extcap = conf.prog.extcap_folders
_bkp_providers = conf.ifaces.providers.copy()
conf.ifaces.providers.clear()
# Create some sort of extcap parody program
extcapfld = get_temp_dir()
extcapprog = os.path.join(extcapfld, "runner.sh")
data = """#!/usr/bin/env python3
import struct
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--extcap-interfaces', action='store_true')
parser.add_argument('--capture', action='store_true')
parser.add_argument('--extcap-config', action='store_true')
parser.add_argument('--scan-follow-rsp', action='store_true')
parser.add_argument('--scan-follow-aux', action='store_true')
parser.add_argument('--extcap-interface', type=str)
parser.add_argument('--fifo', type=str)
args = parser.parse_args()
if args.extcap_interfaces:
# List interfaces
print(bytes.fromhex("0a657874636170207b76657273696f6e3d342e312e317d7b646973706c61793d6e524620536e696666657220666f7220426c7565746f6f7468204c457d7b68656c703d68747470733a2f2f7777772e6e6f7264696373656d692e636f6d2f536f6674776172652d616e642d546f6f6c732f446576656c6f706d656e742d546f6f6c732f6e52462d536e69666665722d666f722d426c7565746f6f74682d4c457d0a696e74657266616365207b76616c75653d2f6465762f747479555342352d4e6f6e657d7b646973706c61793d6e524620536e696666657220666f7220426c7565746f6f7468204c457d0a636f6e74726f6c207b6e756d6265723d307d7b747970653d73656c6563746f727d7b646973706c61793d4465766963657d7b746f6f6c7469703d446576696365206c6973747d0a636f6e74726f6c207b6e756d6265723d317d7b747970653d73656c6563746f727d7b646973706c61793d4b65797d7b746f6f6c7469703d7d0a636f6e74726f6c207b6e756d6265723d327d7b747970653d737472696e677d7b646973706c61793d56616c75657d7b746f6f6c7469703d3620646967697420706173736b6579206f72203136206f7220333220627974657320656e6372797074696f6e206b657920696e2068657861646563696d616c207374617274696e67207769746820273078272c2062696720656e6469616e20666f726d61742e49662074686520656e7465726564206b65792069732073686f72746572207468616e203136206f722033322062797465732c2069742077696c6c206265207a65726f2d70616464656420696e2066726f6e74277d7b76616c69646174696f6e3d5c625e28285b302d395d7b367d297c2830785b302d39612d66412d465d7b312c36347d297c285b302d39412d46612d665d7b327d5b3a2d5d297b357d285b302d39412d46612d665d7b327d2920287075626c69637c72616e646f6d2929245c627d0a636f6e74726f6c207b6e756d6265723d337d7b747970653d737472696e677d7b646973706c61793d41647620486f707d7b64656661756c743d33372c33382c33397d7b746f6f6c7469703d4164766572746973696e67206368616e6e656c20686f702073657175656e63652e204368616e676520746865206f7264657220696e2077686963682074686520736e6966666572207377697463686573206164766572746973696e67206368616e6e656c732e2056616c6964206368616e6e656c73206172652033372c20333820616e642033392073657061726174656420627920636f6d6d612e7d7b76616c69646174696f6e3d5e5c732a282833377c33387c3339295c732a2c5c732a297b302c327d2833377c33387c3339297b317d5c732a247d7b72657175697265643d747275657d0a636f6e74726f6c207b6e756d6265723d377d7b747970653d627574746f6e7d7b646973706c61793d436c6561727d7b746f6f6c746f703d436c656172206f722072656d6f7665206465766963652066726f6d20446576696365206c6973747d0a636f6e74726f6c207b6e756d6265723d347d7b747970653d627574746f6e7d7b726f6c653d68656c707d7b646973706c61793d48656c707d7b746f6f6c7469703d416363657373207573657220677569646520286c61756e636865732062726f77736572297d0a636f6e74726f6c207b6e756d6265723d357d7b747970653d627574746f6e7d7b726f6c653d726573746f72657d7b646973706c61793d44656661756c74737d7b746f6f6c7469703d52657365747320746865207573657220696e7465726661636520616e6420636c6561727320746865206c6f672066696c657d0a636f6e74726f6c207b6e756d6265723d367d7b747970653d627574746f6e7d7b726f6c653d6c6f676765727d7b646973706c61793d4c6f677d7b746f6f6c7469703d4c6f672070657220696e746572666163657d0a76616c7565207b636f6e74726f6c3d307d7b76616c75653d207d7b646973706c61793d416c6c206164766572746973696e6720646576696365737d7b64656661756c743d747275657d0a76616c7565207b636f6e74726f6c3d307d7b76616c75653d5b30302c30302c30302c30302c30302c30302c305d7d7b646973706c61793d466f6c6c6f772049524b7d0a76616c7565207b636f6e74726f6c3d317d7b76616c75653d307d7b646973706c61793d4c656761637920506173736b65797d7b64656661756c743d747275657d0a76616c7565207b636f6e74726f6c3d317d7b76616c75653d317d7b646973706c61793d4c6567616379204f4f4220646174617d0a76616c7565207b636f6e74726f6c3d317d7b76616c75653d327d7b646973706c61793d4c6567616379204c544b7d0a76616c7565207b636f6e74726f6c3d317d7b76616c75653d337d7b646973706c61793d5343204c544b7d0a76616c7565207b636f6e74726f6c3d317d7b76616c75653d347d7b646973706c61793d53432050726976617465204b65797d0a76616c7565207b636f6e74726f6c3d317d7b76616c75653d357d7b646973706c61793d49524b7d0a76616c7565207b636f6e74726f6c3d317d7b76616c75653d367d7b646973706c61793d416464204c4520616464726573737d0a76616c7565207b636f6e74726f6c3d317d7b76616c75653d377d7b646973706c61793d466f6c6c6f77204c4520616464726573737d").decode())
elif args.extcap_interface and args.extcap_config:
# List config
print(bytes.fromhex("617267207b6e756d6265723d307d7b63616c6c3d2d2d6f6e6c792d6164766572746973696e677d7b646973706c61793d4f6e6c79206164766572746973696e67207061636b6574737d7b746f6f6c7469703d54686520736e69666665722077696c6c206f6e6c792063617074757265206164766572746973696e67207061636b6574732066726f6d207468652073656c6563746564206465766963657d7b747970653d626f6f6c666c61677d7b736176653d747275657d0a617267207b6e756d6265723d317d7b63616c6c3d2d2d6f6e6c792d6c65676163792d6164766572746973696e677d7b646973706c61793d4f6e6c79206c6567616379206164766572746973696e67207061636b6574737d7b746f6f6c7469703d54686520736e69666665722077696c6c206f6e6c792063617074757265206c6567616379206164766572746973696e67207061636b6574732066726f6d207468652073656c6563746564206465766963657d7b747970653d626f6f6c666c61677d7b736176653d747275657d0a617267207b6e756d6265723d327d7b63616c6c3d2d2d7363616e2d666f6c6c6f772d7273707d7b646973706c61793d46696e64207363616e20726573706f6e736520646174617d7b746f6f6c7469703d54686520736e69666665722077696c6c20666f6c6c6f77207363616e20726571756573747320616e64207363616e20726573706f6e73657320696e207363616e206d6f64657d7b747970653d626f6f6c666c61677d7b64656661756c743d747275657d7b736176653d747275657d0a617267207b6e756d6265723d337d7b63616c6c3d2d2d7363616e2d666f6c6c6f772d6175787d7b646973706c61793d46696e6420617578696c6961727920706f696e74657220646174617d7b746f6f6c7469703d54686520736e69666665722077696c6c20666f6c6c6f772061757820706f696e7465727320696e207363616e206d6f64657d7b747970653d626f6f6c666c61677d7b64656661756c743d747275657d7b736176653d747275657d0a617267207b6e756d6265723d337d7b63616c6c3d2d2d636f6465647d7b646973706c61793d5363616e20616e6420666f6c6c6f772064657669636573206f6e204c4520436f646564205048597d7b746f6f6c7469703d5363616e20666f72206465766963657320616e6420666f6c6c6f772061647665727469736572206f6e204c4520436f646564205048597d7b747970653d626f6f6c666c61677d7b64656661756c743d66616c73657d7b736176653d747275657d").decode())
elif args.capture and args.extcap_interface and args.fifo:
# Capture
pkts = [
bytes.fromhex("ffffffffffff00000000000008004500001c0001000040117cce7f0000017f0000010035003500080172")
]
with open(args.fifo, "wb", 0) as fd:
# header
fd.write(
struct.pack(
"IHHIIII",
0xa1b2c3d4,
2, 4, 0, 0, 65535, 1
)
)
for pkt in pkts:
fd.write(struct.pack("IIII", 0, 0, len(pkt), len(pkt)))
fd.write(bytes(pkt))
else:
raise ValueError("Bad arguments")
""".strip()
with open(extcapprog, "w") as fd:
fd.write(data)
print(data)
os.chmod(extcapprog, 0o777)
# Inject and load provider
conf.prog.extcap_folders = [extcapfld]
load_extcap()
print(conf.ifaces.providers)
conf.ifaces.reload()
# Now do the tests
iface = conf.ifaces.dev_from_networkname('/dev/ttyUSB5-None')
assert iface.name == "nRF Sniffer for Bluetooth LE"
sock = iface.l2listen()(iface=iface)
pkts = sock.sniff(timeout=2)
sock.close()
assert UDP in pkts[0]
config = iface.get_extcap_config()
assert config["arg"] == [
('0', '--only-advertising', 'Only advertising packets', '', ''),
('1', '--only-legacy-advertising', 'Only legacy advertising packets', '', ''),
('2', '--scan-follow-rsp', 'Find scan response data', 'true', ''),
('3', '--scan-follow-aux', 'Find auxiliary pointer data', 'true', ''),
('3', '--coded', 'Scan and follow devices on LE Coded PHY', 'false', '')
]
# Restore
conf.prog.extcap_folders = _bkp_extcap
conf.ifaces.providers = _bkp_providers
conf.ifaces.reload()
= Test read_routes6() - default output
routes6 = read_routes6()
if WINDOWS:
from scapy.arch.windows import _route_add_loopback
_route_add_loopback(routes6, True)
routes6
# Expected results:
# - one route if there is only the loopback interface
# - one route if IPv6 is supported but disabled on network interfaces
# - three routes if there is a network interface
# - on OpenBSD, only two routes on lo0 are expected
if routes6:
iflist = get_if_list()
if WINDOWS:
from scapy.arch.windows import _route_add_loopback
_route_add_loopback(ipv6=True, iflist=iflist)
if OPENBSD:
len(routes6) >= 2
elif iflist == [conf.loopback_name]:
len(routes6) == 1
elif len(iflist) >= 2:
len(routes6) >= 1
else:
False
else:
# IPv6 seems disabled. Force a route to ::1
conf.route6.routes.append(("::1", 128, "::", conf.loopback_name, ["::1"], 1))
conf.route6.ipv6_ifaces = set([conf.loopback_name])
True
= Build HBHOptUnknown for IPv6ExtHdrHopByHop with disabled autopad
~ ipv6 hbh opt
* Build the HBHOptUnknown of IPv6ExtHdrHopByHop with autopad=0
v6Opt = HBHOptUnknown(otype=3, optlen=7, optdata="Beijing")
pkt = Ether()/IPv6()/IPv6ExtHdrHopByHop(autopad=0, options=[v6Opt, ])
pkt.build()
= Build HBHOptUnknown for IPv6ExtHdrDestOpt with disabled autopad
~ ipv6 hbh opt
* Build the HBHOptUnknown of IPv6ExtHdrDestOpt with autopad=0
v6Opt = HBHOptUnknown(otype=3, optlen=6, optdata="Haikou")
pkt = Ether()/IPv6()/IPv6ExtHdrDestOpt(autopad=0, options=[v6Opt, ])
pkt.build()
= Test read_routes6() - check mandatory routes
import re
ll_route = re.compile(r"fe80:\d{0,2}:")
# match fe80::, fe80:5:, etc. (if scoped)
conf.route6
if len(routes6) > 2 and not WINDOWS:
# Identify routes to fe80::/64
assert sum(1 for r in routes6 if r[0] == "::1" and r[4] == ["::1"]) >= 1
if len(iflist) >= 2:
assert sum(1 for r in routes6 if ll_route.match(r[0]) and r[1] == 64) >= 1
try:
# Identify a route to a node IPv6 link-local address
assert sum(1 for r in routes6 if in6_islladdr(r[0]) and r[1] == 128) >= 1
except:
# IPv6 is not available, but we still check the loopback
assert conf.route6.route("::/0") == (conf.loopback_name, "::", "::")
assert sum(1 for r in routes6 if r[1] == 128 and r[4] == ["::1"]) >= 1
else:
True
= Test ifchange()
conf.route6.ifchange(conf.loopback_name, "::1/128")
if WINDOWS:
conf.netcache.in6_neighbor["::1"] = "ff:ff:ff:ff:ff:ff" # Restore fake cache
True
= Packet.route()
assert (Ether() / ARP()).route()[0] is not None
assert (Ether() / ARP()).payload.route()[0] is not None
assert (ARP(ptype=0, pdst="hello. this isn't a valid IP")).route()[0] is None
= utils/in4_is*
assert in4_ismaddr("224.0.0.1")
assert not in4_ismaddr("192.168.0.1")
assert in4_ismaddr("239.0.0.255")
assert in4_ismlladdr("224.0.0.1")
assert in4_ismlladdr("224.0.0.255")
assert not in4_ismlladdr("224.0.1.255")
assert in4_ismgladdr("235.0.0.1")
assert not in4_ismgladdr("224.0.0.1")
assert not in4_ismgladdr("239.0.0.1")
assert in4_ismlsaddr("239.0.0.1")
assert not in4_ismlsaddr("224.0.0.1")
assert in4_isaddrllallnodes("224.0.0.1")
assert not in4_isaddrllallnodes("224.0.0.3")
assert in4_getnsmac(b'\xe0\x00\x00\x01') == '01:00:5e:00:00:01'
assert getmacbyip("224.0.0.1") == '01:00:5e:00:00:01'
= plain_str test
data = b"\xffsweet\xef celestia\xab"
assert plain_str(data) == "\\xffsweet\\xef celestia\\xab"
############
############
+ compat.py
= test bytes_hex/hex_bytes
monty_data = b"Stop! Who approaches the Bridge of Death must answer me these questions three, 'ere the other side he see."
hex_data = bytes_hex(monty_data)
assert hex_data == b'53746f70212057686f20617070726f61636865732074686520427269646765206f66204465617468206d75737420616e73776572206d65207468657365207175657374696f6e732074687265652c202765726520746865206f746865722073696465206865207365652e'
assert hex_bytes(hex_data) == monty_data
= orb/chb
assert orb(b"\x01"[0]) == 1
assert chb(1) == b"\x01"
############
############
+ Main.py tests
= Pickle and unpickle a packet
import pickle
a = IP(dst="192.168.0.1")/UDP()
b = pickle.dumps(a)
c = pickle.loads(b)
assert c[IP].dst == "192.168.0.1"
assert raw(c) == raw(a)
= Usage test
from scapy.main import _usage
try:
_usage()
assert False
except SystemExit:
assert True
= Emulate interact()
~ interact
import sys
from unittest import mock
from scapy.main import interact
from scapy.main import DEFAULT_PRESTART_FILE, DEFAULT_PRESTART, _read_config_file
_read_config_file(DEFAULT_PRESTART_FILE, _locals=globals(), default=DEFAULT_PRESTART)
# By now .config/scapy/startup.py should have been created
with open(DEFAULT_PRESTART_FILE, "r") as fd:
OLD_DEFAULT_PRESTART = fd.read()
with open(DEFAULT_PRESTART_FILE, "w+") as fd:
fd.write("conf.interactive_shell = 'ipython'")
# Detect IPython
try:
import IPython
except:
code_interact_import = "scapy.main.code.interact"
else:
code_interact_import = "IPython.embed"
@mock.patch(code_interact_import)
def interact_emulator(code_int, extra_args=[]):
try:
code_int.side_effect = lambda *args, **kwargs: lambda *args, **kwargs: None
interact(argv=["-s scapy1"] + extra_args, mybanner="What a test")
finally:
sys.ps1 = ">>> "
interact_emulator() # Default
try:
interact_emulator(extra_args=["-?"]) # Failing
assert False
except:
pass
interact_emulator(extra_args=["-d"]) # Extended
= Emulate interact() and test startup.py with ptpython
~ interact
import sys
from unittest import mock
from scapy.main import DEFAULT_PRESTART_FILE, DEFAULT_PRESTART, _read_config_file
_read_config_file(DEFAULT_PRESTART_FILE, _locals=globals(), default=DEFAULT_PRESTART)
# By now .config/scapy/startup.py should have been created
with open(DEFAULT_PRESTART_FILE, "w+") as fd:
fd.write("conf.interactive_shell = 'ptpython'")
called = []
def checker(*args, **kwargs):
locals = kwargs.pop("locals")
assert locals["IP"]
history_filename = kwargs.pop("history_filename")
assert history_filename == conf.histfile
called.append(True)
ptpython_mocked_module = Bunch(
repl=Bunch(
embed=checker
)
)
modules_patched = {
"ptpython": ptpython_mocked_module,
"ptpython.repl": ptpython_mocked_module.repl,
"ptpython.repl.embed": ptpython_mocked_module.repl.embed,
}
with mock.patch.dict("sys.modules", modules_patched):
try:
interact()
finally:
sys.ps1 = ">>> "
# Restore
with open(DEFAULT_PRESTART_FILE, "w") as fd:
print(OLD_DEFAULT_PRESTART)
r = fd.write(OLD_DEFAULT_PRESTART)
assert called
= Test explore() with GUI mode
~ command
from unittest import mock
def test_explore_gui(is_layer, layer):
prompt_toolkit_mocked_module = Bunch(
shortcuts=Bunch(
dialogs=Bunch(
radiolist_dialog=(lambda *args, **kargs: layer),
button_dialog=(lambda *args, **kargs: "layers" if is_layer else "contribs")
)
),
formatted_text=Bunch(HTML=lambda x: x),
__version__="2.0.0"
)
# a mock.patch isn't enough to mock a module. Let's roll sys.modules
modules_patched = {
"prompt_toolkit": prompt_toolkit_mocked_module,
"prompt_toolkit.shortcuts": prompt_toolkit_mocked_module.shortcuts,
"prompt_toolkit.shortcuts.dialogs": prompt_toolkit_mocked_module.shortcuts.dialogs,
"prompt_toolkit.formatted_text": prompt_toolkit_mocked_module.formatted_text,
}
with mock.patch.dict("sys.modules", modules_patched):
with ContextManagerCaptureOutput() as cmco:
explore()
result_explore = cmco.get_output()
return result_explore
conf.interactive = True
explore_dns = test_explore_gui(True, "scapy.layers.dns")
assert "DNS" in explore_dns
assert "DNS Question Record" in explore_dns
assert "DNSRRNSEC3" in explore_dns
assert "DNS TSIG Resource Record" in explore_dns
explore_avs = test_explore_gui(False, "avs")
assert "AVSWLANHeader" in explore_avs
assert "AVS WLAN Monitor Header" in explore_avs
= Test explore() with non-GUI mode
~ command
def test_explore_non_gui(layer):
with ContextManagerCaptureOutput() as cmco:
explore(layer)
result_explore = cmco.get_output()
return result_explore
explore_dns = test_explore_non_gui("scapy.layers.dns")
assert "DNS" in explore_dns
assert "DNS Question Record" in explore_dns
assert "DNSRRNSEC3" in explore_dns
assert "DNS TSIG Resource Record" in explore_dns
explore_avs = test_explore_non_gui("avs")
assert "AVSWLANHeader" in explore_avs
assert "AVS WLAN Monitor Header" in explore_avs
assert test_explore_non_gui("scapy.layers.dns") == test_explore_non_gui("dns")
assert test_explore_non_gui("scapy.contrib.avs") == test_explore_non_gui("avs")
try:
explore("unknown_module")
assert False # The previous should have raised an exception
except Scapy_Exception:
pass
= Test load_contrib overwrite
load_contrib("gtp")
assert GTPHeader.__module__ == "scapy.contrib.gtp"
load_contrib("gtp_v2")
assert GTPHeader.__module__ == "scapy.contrib.gtp_v2"
load_contrib("gtp")
assert GTPHeader.__module__ == "scapy.contrib.gtp"
= Test load_contrib failure
try:
load_contrib("doesnotexist")
assert False
except:
pass
= Test sane function
sane("A\x00\xFFB") == "A..B"
= Test lhex function
assert lhex(42) == "0x2a"
assert lhex((28,7)) == "(0x1c, 0x7)"
assert lhex([28,7]) == "[0x1c, 0x7]"
= Test restart function
from unittest import mock
conf.interactive = True
try:
from scapy.utils import restart
import os
@mock.patch("os.execv")
@mock.patch("subprocess.call")
@mock.patch("os._exit")
def _test(e, m, m2):
def check(x, y=[]):
z = [x] + y if not isinstance(x, list) else x + y
assert os.path.isfile(z[0])
assert os.path.isfile(z[1])
return 0
m2.side_effect = check
m.side_effect = check
e.side_effect = lambda x: None
restart()
_test()
finally:
conf.interactive = False
= Test linehexdump function
conf_color_theme = conf.color_theme
conf.color_theme = BlackAndWhite()
assert linehexdump(Ether(src="00:01:02:03:04:05"), dump=True) == 'FF FF FF FF FF FF 00 01 02 03 04 05 90 00 ..............'
conf.color_theme = conf_color_theme
= Test chexdump function
chexdump(Ether(src="00:01:02:02:04:05"), dump=True) == "0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x01, 0x02, 0x02, 0x04, 0x05, 0x90, 0x00"
= Test repr_hex function
repr_hex("scapy") == "7363617079"
= Test hexstr function
hexstr(b"A\x00\xFFB") == "41 00 FF 42 A..B"
= Test fletcher16 functions
assert fletcher16_checksum(b"\x28\x07") == 22319
assert fletcher16_checkbytes(b"\x28\x07", 1) == b"\xaf("
= Test hexdiff function
~ not_pypy
def test_hexdiff(a, b, algo=None, autojunk=False):
conf_color_theme = conf.color_theme
conf.color_theme = BlackAndWhite()
with ContextManagerCaptureOutput() as cmco:
hexdiff(a, b, algo=algo, autojunk=autojunk)
result_hexdiff = cmco.get_output()
conf.interactive = True
conf.color_theme = conf_color_theme
return result_hexdiff
# Basic string test
result_hexdiff = test_hexdiff("abcde", "abCde")
expected = "0000 61 62 63 64 65 abcde\n"
expected += " 0000 61 62 43 64 65 abCde\n"
assert result_hexdiff == expected
# More advanced string test
result_hexdiff = test_hexdiff("add_common_", "_common_removed")
expected = "0000 61 64 64 5F 63 6F 6D 6D 6F 6E 5F add_common_ \n"
expected += " -003 5F 63 6F 6D 6D 6F 6E 5F 72 65 6D 6F 76 _common_remov\n"
expected += " 000d 65 64 ed\n"
assert result_hexdiff == expected
# Compare packets
result_hexdiff = test_hexdiff(IP(dst="127.0.0.1", src="127.0.0.1"), IP(dst="127.0.0.2", src="127.0.0.1"))
expected = "0000 45 00 00 14 00 01 00 00 40 00 7C E7 7F 00 00 01 E.......@.|.....\n"
expected += " 0000 45 00 00 14 00 01 00 00 40 00 7C E6 7F 00 00 01 E.......@.|.....\n"
expected += "0010 7F 00 00 01 ....\n"
expected += " 0010 7F 00 00 02 ....\n"
assert result_hexdiff == expected
# Compare using difflib
a = "A" * 1000 + "findme" + "B" * 1000
b = "A" * 1000 + "B" * 1000
ret1 = test_hexdiff(a, b, algo="difflib")
ret2 = test_hexdiff(a, b, algo="difflib", autojunk=True)
expected_ret1 = """
03d0 03d0 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA
03e0 41 41 41 41 41 41 41 41 66 69 6E 64 6D 65 42 42 AAAAAAAAfindmeBB
03e0 41 41 41 41 41 41 41 41 42 42 AAAAAAAA BB
03ea 03ea 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB
"""
expected_ret2 = """
03d0 03d0 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 AAAAAAAAAAAAAAAA
03e0 41 41 41 41 41 41 41 41 66 69 6E 64 6D 65 42 42 AAAAAAAAfindmeBB
03e0 41 41 41 41 41 41 41 41 42 42 42 42 42 42 42 42 AAAAAAAABBBBBBBB
03f0 03f0 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 BBBBBBBBBBBBBBBB
"""
assert ret1 != ret2
assert expected_ret1 in ret1
assert expected_ret2 in ret2
# Test corner cases that should not crash
hexdiff(b"abc", IP() / TCP())
hexdiff(IP() / TCP(), b"abc")
= Test mysummary functions - Ether
p = Ether(dst="ff:ff:ff:ff:ff:ff", src="ff:ff:ff:ff:ff:ff", type=0x9000)
p
assert p.mysummary() in ['ff:ff:ff:ff:ff:ff > ff:ff:ff:ff:ff:ff (%s)' % loop
for loop in ['0x9000', 'LOOP']]
= Test zerofree_randstring function
random.seed(0x2807)
zerofree_randstring(4) in [b"\xd2\x12\xe4\x5b", b'\xd3\x8b\x13\x12']
= Test strand function
assert strand(b"AC", b"BC") == b'@C'
= Test tex_escape function
tex_escape("$#_") == "\\$\\#\\_"
= Test colgen function
f = colgen(range(3))
assert len([next(f) for i in range(2)]) == 2
= Test incremental_label function
f = incremental_label()
assert [next(f) for i in range(2)] == ["tag00000", "tag00001"]
= Test corrupt_* functions
import random
random.seed(0x2807)
assert corrupt_bytes("ABCDE") in [b"ABCDW", b"ABCDX"]
assert sane(corrupt_bytes("ABCDE", n=3)) in ["A.8D4", ".2.DE"]
assert corrupt_bits("ABCDE") in [b"EBCDE", b"ABCDG"]
assert sane(corrupt_bits("ABCDE", n=3)) in ["AF.EE", "QB.TE"]
= Test whois function
~ netaccess
if not WINDOWS:
result = whois("193.0.6.139")
assert b"inetnum" in result and b"Amsterdam" in result
= Test manuf DB methods
~ manufdb
assert conf.manufdb._resolve_MAC("00:00:0F:01:02:03") == "Next:01:02:03"
assert conf.manufdb._get_short_manuf("00:00:0F:01:02:03") == "Next"
assert in6_addrtovendor("fe80::0200:0fff:fe01:0203").lower().startswith("next")
assert conf.manufdb.lookup("00:00:0F:01:02:03") == ('Next', 'Next, Inc.')
assert "00:00:0F" in conf.manufdb.reverse_lookup("Next")
= Test multiple wireshark's manuf formats
~ manufdb
new_format = """
# comment
00:00:00 JokyIsland Joky Insland Corp SA
00:01:12 SecdevCorp Secdev Corporation SA LLC
EE:05:01 Scapy Scapy CO LTD & CIE
FF:00:11 NoName
"""
old_format = """
# comment
00:00:00 JokyIsland # Joky Insland Corp SA
00:01:12 SecdevCorp # Secdev Corporation SA LLC
EE:05:01 Scapy # Scapy CO LTD & CIE
FF:00:11 NoName
"""
manuf1 = get_temp_file()
manuf2 = get_temp_file()
with open(manuf1, "w") as w:
w.write(old_format)
with open(manuf2, "w") as w:
w.write(new_format)
a = load_manuf(manuf1)
b = load_manuf(manuf2)
assert a.lookup("00:00:00") == ('JokyIsland', 'Joky Insland Corp SA')
assert a.lookup("FF:00:11:00:00:00") == ('NoName', 'NoName')
assert a.reverse_lookup("Scapy") == {'EE:05:01': ('Scapy', 'Scapy CO LTD & CIE')}
assert a.reverse_lookup("Secdevcorp") == {'00:01:12': ('SecdevCorp', 'Secdev Corporation SA LLC')}