-
-
Notifications
You must be signed in to change notification settings - Fork 83
/
testcases.py
1712 lines (1435 loc) · 53.1 KB
/
testcases.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
import abc
import filecmp
import logging
import os
import random
import re
import shutil
import string
import subprocess
import sys
import tempfile
from datetime import timedelta
from enum import Enum, IntEnum
from trace import (
QUIC_V2,
Direction,
PacketType,
TraceAnalyzer,
get_direction,
get_packet_type,
)
from typing import List
from Crypto.Cipher import AES
from result import TestResult
KB = 1 << 10
MB = 1 << 20
QUIC_DRAFT = 34 # draft-34
QUIC_VERSION = hex(0x1)
class Perspective(Enum):
SERVER = "server"
CLIENT = "client"
class ECN(IntEnum):
NONE = 0
ECT1 = 1
ECT0 = 2
CE = 3
def random_string(length: int):
"""Generate a random string of fixed length"""
letters = string.ascii_lowercase
return "".join(random.choice(letters) for i in range(length))
def generate_cert_chain(directory: str, length: int = 1):
cmd = "./certs.sh " + directory + " " + str(length)
r = subprocess.run(
cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
)
logging.debug("%s", r.stdout.decode("utf-8"))
if r.returncode != 0:
logging.info("Unable to create certificates")
sys.exit(1)
class TestCase(abc.ABC):
_files = []
_www_dir = None
_client_keylog_file = None
_server_keylog_file = None
_download_dir = None
_sim_log_dir = None
_cert_dir = None
_cached_server_trace = None
_cached_client_trace = None
def __init__(
self,
sim_log_dir: tempfile.TemporaryDirectory,
client_keylog_file: str,
server_keylog_file: str,
):
self._server_keylog_file = server_keylog_file
self._client_keylog_file = client_keylog_file
self._files = []
self._sim_log_dir = sim_log_dir
@abc.abstractmethod
def name(self):
pass
@abc.abstractmethod
def desc(self):
pass
def __str__(self):
return self.name()
def testname(self, p: Perspective):
"""The name of testcase presented to the endpoint Docker images"""
return self.name()
@staticmethod
def scenario() -> str:
"""Scenario for the ns3 simulator"""
return "simple-p2p --delay=15ms --bandwidth=10Mbps --queue=25"
@staticmethod
def timeout() -> int:
"""timeout in s"""
return 60
@staticmethod
def urlprefix() -> str:
"""URL prefix"""
return "https://server4:443/"
@staticmethod
def additional_envs() -> List[str]:
return [""]
@staticmethod
def additional_containers() -> List[str]:
return [""]
def www_dir(self):
if not self._www_dir:
self._www_dir = tempfile.TemporaryDirectory(dir="/tmp", prefix="www_")
return self._www_dir.name + "/"
def download_dir(self):
if not self._download_dir:
self._download_dir = tempfile.TemporaryDirectory(
dir="/tmp", prefix="download_"
)
return self._download_dir.name + "/"
def certs_dir(self):
if not self._cert_dir:
self._cert_dir = tempfile.TemporaryDirectory(dir="/tmp", prefix="certs_")
generate_cert_chain(self._cert_dir.name)
return self._cert_dir.name + "/"
def _is_valid_keylog(self, filename) -> bool:
if not os.path.isfile(filename) or os.path.getsize(filename) == 0:
return False
with open(filename, "r") as file:
if not re.search(
r"^SERVER_HANDSHAKE_TRAFFIC_SECRET", file.read(), re.MULTILINE
):
logging.info("Key log file %s is using incorrect format.", filename)
return False
return True
def _keylog_file(self) -> str:
if self._is_valid_keylog(self._client_keylog_file):
logging.debug("Using the client's key log file.")
return self._client_keylog_file
elif self._is_valid_keylog(self._server_keylog_file):
logging.debug("Using the server's key log file.")
return self._server_keylog_file
logging.debug("No key log file found.")
def _inject_keylog_if_possible(self, trace: str):
"""
Inject the keylog file into the pcap file if it is available and valid.
"""
keylog = self._keylog_file()
if keylog is None:
return
with tempfile.NamedTemporaryFile() as tmp:
r = subprocess.run(
f"editcap --inject-secrets tls,{keylog} {trace} {tmp.name}",
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
logging.debug("%s", r.stdout.decode("utf-8"))
if r.returncode != 0:
return
shutil.copy(tmp.name, trace)
def _client_trace(self):
if self._cached_client_trace is None:
trace = self._sim_log_dir.name + "/trace_node_left.pcap"
self._inject_keylog_if_possible(trace)
self._cached_client_trace = TraceAnalyzer(trace, self._keylog_file())
return self._cached_client_trace
def _server_trace(self):
if self._cached_server_trace is None:
trace = self._sim_log_dir.name + "/trace_node_right.pcap"
self._inject_keylog_if_possible(trace)
self._cached_server_trace = TraceAnalyzer(trace, self._keylog_file())
return self._cached_server_trace
# see https://www.stefanocappellini.it/generate-pseudorandom-bytes-with-python/ for benchmarks
def _generate_random_file(self, size: int, filename_len=10) -> str:
filename = random_string(filename_len)
enc = AES.new(os.urandom(32), AES.MODE_OFB, b"a" * 16)
f = open(self.www_dir() + filename, "wb")
f.write(enc.encrypt(b" " * size))
f.close()
logging.debug("Generated random file: %s of size: %d", filename, size)
return filename
def _retry_sent(self) -> bool:
return len(self._client_trace().get_retry()) > 0
def _check_version_and_files(self) -> bool:
versions = [hex(int(v, 0)) for v in self._get_versions()]
if len(versions) != 1:
logging.info("Expected exactly one version. Got %s", versions)
return False
if QUIC_VERSION not in versions:
logging.info("Wrong version. Expected %s, got %s", QUIC_VERSION, versions)
return False
return self._check_files()
def _check_files(self) -> bool:
if len(self._files) == 0:
raise Exception("No test files generated.")
files = [
n
for n in os.listdir(self.download_dir())
if os.path.isfile(os.path.join(self.download_dir(), n))
]
too_many = [f for f in files if f not in self._files]
if len(too_many) != 0:
logging.info("Found unexpected downloaded files: %s", too_many)
too_few = [f for f in self._files if f not in files]
if len(too_few) != 0:
logging.info("Missing files: %s", too_few)
if len(too_many) != 0 or len(too_few) != 0:
return False
for f in self._files:
fp = self.download_dir() + f
if not os.path.isfile(fp):
logging.info("File %s does not exist.", fp)
return False
try:
size = os.path.getsize(self.www_dir() + f)
downloaded_size = os.path.getsize(fp)
if size != downloaded_size:
logging.info(
"File size of %s doesn't match. Original: %d bytes, downloaded: %d bytes.",
fp,
size,
downloaded_size,
)
return False
if not filecmp.cmp(self.www_dir() + f, fp, shallow=False):
logging.info("File contents of %s do not match.", fp)
return False
except Exception as exception:
logging.info(
"Could not compare files %s and %s: %s",
self.www_dir() + f,
fp,
exception,
)
return False
logging.debug("Check of downloaded files succeeded.")
return True
def _count_handshakes(self) -> int:
"""Count the number of QUIC handshakes"""
tr = self._server_trace()
# Determine the number of handshakes by looking at Initial packets.
# This is easier, since the SCID of Initial packets doesn't changes.
return len(set([p.scid for p in tr.get_initial(Direction.FROM_SERVER)]))
def _get_versions(self) -> set:
"""Get the QUIC versions"""
tr = self._server_trace()
return set([p.version for p in tr.get_initial(Direction.FROM_SERVER)])
def _payload_size(self, packets: List) -> int:
"""Get the sum of the payload sizes of all packets"""
size = 0
for p in packets:
if hasattr(p, "long_packet_type") or hasattr(p, "long_packet_type_v2"):
if hasattr(p, "payload"): # when keys are available
size += len(p.payload.split(":"))
else:
size += len(p.remaining_payload.split(":"))
else:
if hasattr(p, "protected_payload"):
size += len(p.protected_payload.split(":"))
return size
def cleanup(self):
if self._www_dir:
self._www_dir.cleanup()
self._www_dir = None
if self._download_dir:
self._download_dir.cleanup()
self._download_dir = None
@abc.abstractmethod
def get_paths(self):
pass
@abc.abstractmethod
def check(self) -> TestResult:
self._client_trace()
self._server_trace()
pass
class Measurement(TestCase):
@abc.abstractmethod
def result(self) -> float:
pass
@staticmethod
@abc.abstractmethod
def unit() -> str:
pass
@staticmethod
@abc.abstractmethod
def repetitions() -> int:
pass
class TestCaseVersionNegotiation(TestCase):
@staticmethod
def name():
return "versionnegotiation"
@staticmethod
def abbreviation():
return "V"
@staticmethod
def desc():
return "A version negotiation packet is elicited and acted on."
def get_paths(self):
return [""]
def check(self) -> TestResult:
super().check()
tr = self._client_trace()
initials = tr.get_initial(Direction.FROM_CLIENT)
dcid = ""
for p in initials:
dcid = p.dcid
break
if dcid == "":
logging.info("Didn't find an Initial / a DCID.")
return TestResult.FAILED
vnps = tr.get_vnp()
for p in vnps:
if p.scid == dcid:
return TestResult.SUCCEEDED
logging.info("Didn't find a Version Negotiation Packet with matching SCID.")
return TestResult.FAILED
class TestCaseHandshake(TestCase):
@staticmethod
def name():
return "handshake"
@staticmethod
def abbreviation():
return "H"
@staticmethod
def desc():
return "Handshake completes successfully."
def get_paths(self):
self._files = [self._generate_random_file(1 * KB)]
return self._files
def check(self) -> TestResult:
super().check()
if not self._check_version_and_files():
return TestResult.FAILED
if self._retry_sent():
logging.info("Didn't expect a Retry to be sent.")
return TestResult.FAILED
num_handshakes = self._count_handshakes()
if num_handshakes != 1:
logging.info("Expected exactly 1 handshake. Got: %d", num_handshakes)
return TestResult.FAILED
return TestResult.SUCCEEDED
class TestCaseLongRTT(TestCaseHandshake):
@staticmethod
def abbreviation():
return "LR"
@staticmethod
def name():
return "longrtt"
@staticmethod
def testname(p: Perspective):
return "handshake"
@staticmethod
def desc():
return "Handshake completes when RTT is long."
@staticmethod
def scenario() -> str:
"""Scenario for the ns3 simulator"""
return "simple-p2p --delay=750ms --bandwidth=10Mbps --queue=25"
def check(self) -> TestResult:
super().check()
num_handshakes = self._count_handshakes()
if num_handshakes != 1:
logging.info("Expected exactly 1 handshake. Got: %d", num_handshakes)
return TestResult.FAILED
if not self._check_version_and_files():
return TestResult.FAILED
num_ch = 0
for p in self._client_trace().get_initial(Direction.FROM_CLIENT):
if hasattr(p, "tls_handshake_type"):
if p.tls_handshake_type == "1":
num_ch += 1
# Retransmitted ClientHello does not have
# tls_handshake_type attribute. See
# https://gitlab.com/wireshark/wireshark/-/issues/18696
# for details.
elif hasattr(p, "retransmission") or hasattr(p, "overlap"):
num_ch += 1
if num_ch < 2:
logging.info("Expected at least 2 ClientHellos. Got: %d", num_ch)
return TestResult.FAILED
return TestResult.SUCCEEDED
class TestCaseTransfer(TestCase):
@staticmethod
def name():
return "transfer"
@staticmethod
def abbreviation():
return "DC"
@staticmethod
def desc():
return "Stream data is being sent and received correctly. Connection close completes with a zero error code."
def get_paths(self):
self._files = [
self._generate_random_file(2 * MB),
self._generate_random_file(3 * MB),
self._generate_random_file(5 * MB),
]
return self._files
def check(self) -> TestResult:
super().check()
num_handshakes = self._count_handshakes()
if num_handshakes != 1:
logging.info("Expected exactly 1 handshake. Got: %d", num_handshakes)
return TestResult.FAILED
if not self._check_version_and_files():
return TestResult.FAILED
return TestResult.SUCCEEDED
class TestCaseChaCha20(TestCase):
@staticmethod
def name():
return "chacha20"
@staticmethod
def testname(p: Perspective):
return "chacha20"
@staticmethod
def abbreviation():
return "C20"
@staticmethod
def desc():
return "Handshake completes using ChaCha20."
def get_paths(self):
self._files = [self._generate_random_file(3 * MB)]
return self._files
def check(self) -> TestResult:
super().check()
num_handshakes = self._count_handshakes()
if num_handshakes != 1:
logging.info("Expected exactly 1 handshake. Got: %d", num_handshakes)
return TestResult.FAILED
ciphersuites = []
for p in self._client_trace().get_initial(Direction.FROM_CLIENT):
if hasattr(p, "tls_handshake_ciphersuite"):
ciphersuites.append(p.tls_handshake_ciphersuite)
if len(set(ciphersuites)) != 1 or (
ciphersuites[0] != "4867" and ciphersuites[0] != "0x1303"
):
logging.info(
"Expected only ChaCha20 cipher suite to be offered. Got: %s",
set(ciphersuites),
)
return TestResult.FAILED
if not self._check_version_and_files():
return TestResult.FAILED
return TestResult.SUCCEEDED
class TestCaseMultiplexing(TestCase):
@staticmethod
def name():
return "multiplexing"
@staticmethod
def testname(p: Perspective):
return "transfer"
@staticmethod
def abbreviation():
return "M"
@staticmethod
def desc():
return "Thousands of files are transferred over a single connection, and server increased stream limits to accomodate client requests."
def get_paths(self):
for _ in range(1, 2000):
self._files.append(self._generate_random_file(32))
return self._files
def check(self) -> TestResult:
super().check()
if not self._keylog_file():
logging.info("Can't check test result. SSLKEYLOG required.")
return TestResult.UNSUPPORTED
num_handshakes = self._count_handshakes()
if num_handshakes != 1:
logging.info("Expected exactly 1 handshake. Got: %d", num_handshakes)
return TestResult.FAILED
if not self._check_version_and_files():
return TestResult.FAILED
# Check that the server set a bidirectional stream limit <= 1000
checked_stream_limit = False
for p in self._client_trace().get_handshake(Direction.FROM_SERVER):
if hasattr(p, "tls.quic.parameter.initial_max_streams_bidi"):
checked_stream_limit = True
stream_limit = int(
getattr(p, "tls.quic.parameter.initial_max_streams_bidi")
)
logging.debug("Server set bidirectional stream limit: %d", stream_limit)
if stream_limit > 1000:
logging.info("Server set a stream limit > 1000.")
return TestResult.FAILED
if not checked_stream_limit:
logging.info("Couldn't check stream limit.")
return TestResult.FAILED
return TestResult.SUCCEEDED
class TestCaseRetry(TestCase):
@staticmethod
def name():
return "retry"
@staticmethod
def abbreviation():
return "S"
@staticmethod
def desc():
return "Server sends a Retry, and a subsequent connection using the Retry token completes successfully."
def get_paths(self):
self._files = [
self._generate_random_file(10 * KB),
]
return self._files
def _check_trace(self) -> bool:
# check that (at least) one Retry packet was actually sent
tr = self._client_trace()
tokens = []
retries = tr.get_retry(Direction.FROM_SERVER)
for p in retries:
if not hasattr(p, "retry_token"):
logging.info("Retry packet doesn't have a retry_token")
logging.info(p)
return False
tokens += [p.retry_token.replace(":", "")]
if len(tokens) == 0:
logging.info("Didn't find any Retry packets.")
return False
# check that an Initial packet uses a token sent in the Retry packet(s)
highest_pn_before_retry = -1
for p in tr.get_initial(Direction.FROM_CLIENT):
pn = int(p.packet_number)
if p.token_length == "0":
highest_pn_before_retry = max(highest_pn_before_retry, pn)
continue
if pn <= highest_pn_before_retry:
logging.debug(
"Client reset the packet number. Check failed for PN %d", pn
)
return False
token = p.token.replace(":", "")
if token in tokens:
logging.debug("Check of Retry succeeded. Token used: %s", token)
return True
logging.info("Didn't find any Initial packet using a Retry token.")
return False
def check(self) -> TestResult:
super().check()
num_handshakes = self._count_handshakes()
if num_handshakes != 1:
logging.info("Expected exactly 1 handshake. Got: %d", num_handshakes)
return TestResult.FAILED
if not self._check_version_and_files():
return TestResult.FAILED
if not self._check_trace():
return TestResult.FAILED
return TestResult.SUCCEEDED
class TestCaseResumption(TestCase):
@staticmethod
def name():
return "resumption"
@staticmethod
def abbreviation():
return "R"
@staticmethod
def desc():
return "Connection is established using TLS Session Resumption."
def get_paths(self):
self._files = [
self._generate_random_file(5 * KB),
self._generate_random_file(10 * KB),
]
return self._files
def check(self) -> TestResult:
super().check()
if not self._keylog_file():
logging.info("Can't check test result. SSLKEYLOG required.")
return TestResult.UNSUPPORTED
num_handshakes = self._count_handshakes()
if num_handshakes != 2:
logging.info("Expected exactly 2 handshake. Got: %d", num_handshakes)
return TestResult.FAILED
handshake_packets = self._client_trace().get_handshake(Direction.FROM_SERVER)
cids = [p.scid for p in handshake_packets]
first_handshake_has_cert = False
for p in handshake_packets:
if p.scid == cids[0]:
if hasattr(p, "tls_handshake_certificates_length"):
first_handshake_has_cert = True
elif p.scid == cids[len(cids) - 1]: # second handshake
if hasattr(p, "tls_handshake_certificates_length"):
logging.info(
"Server sent a Certificate message in the second handshake."
)
return TestResult.FAILED
else:
logging.info(
"Found handshake packet that neither belongs to the first nor the second handshake."
)
return TestResult.FAILED
if not first_handshake_has_cert:
logging.info(
"Didn't find a Certificate message in the first handshake. That's weird."
)
return TestResult.FAILED
if not self._check_version_and_files():
return TestResult.FAILED
return TestResult.SUCCEEDED
class TestCaseZeroRTT(TestCase):
NUM_FILES = 40
FILESIZE = 32 # in bytes
FILENAMELEN = 250
@staticmethod
def name():
return "zerortt"
@staticmethod
def abbreviation():
return "Z"
@staticmethod
def desc():
return "0-RTT data is being sent and acted on."
def get_paths(self):
for _ in range(self.NUM_FILES):
self._files.append(
self._generate_random_file(self.FILESIZE, self.FILENAMELEN)
)
return self._files
def check(self) -> TestResult:
super().check()
num_handshakes = self._count_handshakes()
if num_handshakes != 2:
logging.info("Expected exactly 2 handshakes. Got: %d", num_handshakes)
return TestResult.FAILED
if not self._check_version_and_files():
return TestResult.FAILED
tr = self._client_trace()
zeroRTTSize = self._payload_size(tr.get_0rtt())
oneRTTSize = self._payload_size(tr.get_1rtt(Direction.FROM_CLIENT))
logging.debug("0-RTT size: %d", zeroRTTSize)
logging.debug("1-RTT size: %d", oneRTTSize)
if zeroRTTSize == 0:
logging.info("Client didn't send any 0-RTT data.")
return TestResult.FAILED
if oneRTTSize > 0.5 * self.FILENAMELEN * self.NUM_FILES:
logging.info("Client sent too much data in 1-RTT packets.")
return TestResult.FAILED
return TestResult.SUCCEEDED
class TestCaseHTTP3(TestCase):
@staticmethod
def name():
return "http3"
@staticmethod
def abbreviation():
return "3"
@staticmethod
def desc():
return "An H3 transaction succeeded."
def get_paths(self):
self._files = [
self._generate_random_file(5 * KB),
self._generate_random_file(10 * KB),
self._generate_random_file(500 * KB),
]
return self._files
def check(self) -> TestResult:
super().check()
num_handshakes = self._count_handshakes()
if num_handshakes != 1:
logging.info("Expected exactly 1 handshake. Got: %d", num_handshakes)
return TestResult.FAILED
if not self._check_version_and_files():
return TestResult.FAILED
return TestResult.SUCCEEDED
class TestCaseAmplificationLimit(TestCase):
@staticmethod
def name():
return "amplificationlimit"
@staticmethod
def testname(p: Perspective):
return "transfer"
@staticmethod
def abbreviation():
return "A"
@staticmethod
def desc():
return "The server obeys the 3x amplification limit."
def certs_dir(self):
if not self._cert_dir:
self._cert_dir = tempfile.TemporaryDirectory(dir="/tmp", prefix="certs_")
generate_cert_chain(self._cert_dir.name, 9)
return self._cert_dir.name + "/"
@staticmethod
def scenario() -> str:
"""Scenario for the ns3 simulator"""
# Let the ClientHello pass, but drop a bunch of retransmissions afterwards.
return "droplist --delay=15ms --bandwidth=10Mbps --queue=25 --drops_to_server=2,3,4,5,6,7"
def get_paths(self):
self._files = [self._generate_random_file(5 * KB)]
return self._files
def check(self) -> TestResult:
super().check()
if not self._keylog_file():
logging.info("Can't check test result. SSLKEYLOG required.")
return TestResult.UNSUPPORTED
num_handshakes = self._count_handshakes()
if num_handshakes != 1:
logging.info("Expected exactly 1 handshake. Got: %d", num_handshakes)
return TestResult.FAILED
if not self._check_version_and_files():
return TestResult.FAILED
# Check the highest offset of CRYPTO frames sent by the server.
# This way we can make sure that it actually used the provided cert chain.
max_handshake_offset = 0
for p in self._server_trace().get_handshake(Direction.FROM_SERVER):
if hasattr(p, "crypto_offset"):
max_handshake_offset = max(
max_handshake_offset, int(p.crypto_offset) + int(p.crypto_length)
)
if max_handshake_offset < 7500:
logging.info(
"Server sent too little Handshake CRYPTO data (%d bytes). Not using the provided cert chain?",
max_handshake_offset,
)
return TestResult.FAILED
logging.debug(
"Server sent %d bytes in Handshake CRYPTO frames.", max_handshake_offset
)
# Check that the server didn't send more than 3-4x what the client sent.
allowed = 0
allowed_with_tolerance = 0
client_sent, server_sent = 0, 0 # only for debug messages
res = TestResult.FAILED
log_output = []
for p in self._server_trace().get_raw_packets():
direction = get_direction(p)
packet_type = get_packet_type(p)
if packet_type == PacketType.VERSIONNEGOTIATION:
logging.info("Didn't expect a Version Negotiation packet.")
return TestResult.FAILED
packet_size = int(p.udp.length) - 8 # subtract the UDP header length
if packet_type == PacketType.INVALID:
logging.debug("Couldn't determine packet type.")
return TestResult.FAILED
if direction == Direction.FROM_CLIENT:
if packet_type is PacketType.HANDSHAKE:
res = TestResult.SUCCEEDED
break
if packet_type is PacketType.INITIAL:
client_sent += packet_size
allowed += 3 * packet_size
allowed_with_tolerance += 4 * packet_size
log_output.append(
"Received a {} byte Initial packet from the client. Amplification limit: {}".format(
packet_size, 3 * client_sent
)
)
elif direction == Direction.FROM_SERVER:
server_sent += packet_size
log_output.append(
"Received a {} byte Handshake packet from the server. Total: {}".format(
packet_size, server_sent
)
)
if packet_size >= allowed_with_tolerance:
log_output.append("Server violated the amplification limit.")
break
if packet_size > allowed:
log_output.append(
"Server violated the amplification limit, but stayed within 3-4x amplification. Letting it slide."
)
allowed_with_tolerance -= packet_size
allowed -= packet_size
else:
logging.debug("Couldn't determine sender of packet.")
return TestResult.FAILED
log_level = logging.DEBUG
if res == TestResult.FAILED:
log_level = logging.INFO
for msg in log_output:
logging.log(log_level, msg)
return res
class TestCaseBlackhole(TestCase):
@staticmethod
def name():
return "blackhole"
@staticmethod
def testname(p: Perspective):
return "transfer"
@staticmethod
def abbreviation():
return "B"
@staticmethod
def desc():
return "Transfer succeeds despite underlying network blacking out for a few seconds."
@staticmethod
def scenario() -> str:
"""Scenario for the ns3 simulator"""
return "blackhole --delay=15ms --bandwidth=10Mbps --queue=25 --on=5s --off=2s"
def get_paths(self):
self._files = [self._generate_random_file(10 * MB)]
return self._files
def check(self) -> TestResult:
super().check()
num_handshakes = self._count_handshakes()
if num_handshakes != 1:
logging.info("Expected exactly 1 handshake. Got: %d", num_handshakes)
return TestResult.FAILED
if not self._check_version_and_files():
return TestResult.FAILED
return TestResult.SUCCEEDED
class TestCaseKeyUpdate(TestCaseHandshake):
@staticmethod
def name():
return "keyupdate"
@staticmethod
def testname(p: Perspective):
if p is Perspective.CLIENT:
return "keyupdate"
return "transfer"
@staticmethod
def abbreviation():
return "U"
@staticmethod
def desc():
return "One of the two endpoints updates keys and the peer responds correctly."
def get_paths(self):
self._files = [self._generate_random_file(3 * MB)]
return self._files
def check(self) -> TestResult:
super().check()
if not self._keylog_file():
logging.info("Can't check test result. SSLKEYLOG required.")
return TestResult.UNSUPPORTED
num_handshakes = self._count_handshakes()
if num_handshakes != 1:
logging.info("Expected exactly 1 handshake. Got: %d", num_handshakes)
return TestResult.FAILED
if not self._check_version_and_files():
return TestResult.FAILED
client = {0: 0, 1: 0}
server = {0: 0, 1: 0}
try:
def _get_key_phase(pkt) -> int:
kp: str = pkt.key_phase.raw_value
# when key_phase bit is set in a QUIC packet, certain versions
# of wireshark (4.0.11, for example) have been seen to return the string value
# "1" and certain other versions of wireshark return the string value "True".
# here we deal with such values and return the integer value 1 for either of those.
return 1 if kp in ["1", "True"] else 0
for p in self._client_trace().get_1rtt(Direction.FROM_CLIENT):
key_phase = _get_key_phase(p)
client[key_phase] += 1
for p in self._server_trace().get_1rtt(Direction.FROM_SERVER):
key_phase = _get_key_phase(p)
server[key_phase] += 1
except Exception:
logging.info(
"Failed to read key phase bits. Potentially incorrect SSLKEYLOG?"
)
return TestResult.FAILED
succeeded = client[1] * server[1] > 0
log_level = logging.INFO
if succeeded:
log_level = logging.DEBUG
logging.log(
log_level,
"Client sent %d key phase 0 and %d key phase 1 packets.",
client[0],
client[1],
)
logging.log(
log_level,
"Server sent %d key phase 0 and %d key phase 1 packets.",
server[0],
server[1],