xref: /openbsd-src/regress/lib/libssl/tlsfuzzer/tlsfuzzer.py (revision 44072c60256e69240df075cb1b556c9641bedec7)
1#   $OpenBSD: tlsfuzzer.py,v 1.9 2020/06/19 21:29:41 tb Exp $
2#
3# Copyright (c) 2020 Theo Buehler <tb@openbsd.org>
4#
5# Permission to use, copy, modify, and distribute this software for any
6# purpose with or without fee is hereby granted, provided that the above
7# copyright notice and this permission notice appear in all copies.
8#
9# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16
17import getopt
18import os
19import subprocess
20import sys
21from timeit import default_timer as timer
22
23tlsfuzzer_scriptdir = "/usr/local/share/tlsfuzzer/scripts/"
24
25class Test:
26    """
27    Represents a tlsfuzzer test script.
28        name:           the script's name
29        args:           arguments to feed to the script
30        tls12_args:     override args for a TLSv1.2 server
31        tls13_args:     override args for a TLSv1.3 server
32
33    XXX Add client cert support.
34    """
35    def __init__(self, name="", args=[], tls12_args=[], tls13_args=[]):
36        self.name = name
37        self.tls12_args = args
38        self.tls13_args = args
39        if tls12_args:
40            self.tls12_args = tls12_args
41        if tls13_args:
42            self.tls13_args = tls13_args
43
44    def args(self, has_tls1_3: True):
45        if has_tls1_3:
46            return self.tls13_args
47        else:
48            return self.tls12_args
49
50    def __repr__(self):
51        return "<Test: %s tls12_args: %s tls13_args: %s>" % (
52                self.name, self.tls12_args, tls13_args
53            )
54
55class TestGroup:
56    """ A group of Test objects to be run by TestRunner."""
57    def __init__(self, title="Tests", tests=[]):
58        self.title = title
59        self.tests = tests
60
61    def __iter__(self):
62        return iter(self.tests)
63
64# argument to pass to several tests
65tls13_unsupported_ciphers = [
66    "-e", "TLS 1.3 with ffdhe2048",
67    "-e", "TLS 1.3 with ffdhe3072",
68    "-e", "TLS 1.3 with secp521r1",   # XXX: why is this curve problematic?
69    "-e", "TLS 1.3 with x448",
70]
71
72tls13_tests = TestGroup("TLSv1.3 tests", [
73    Test("test-tls13-ccs.py"),
74    Test("test-tls13-conversation.py"),
75    Test("test-tls13-count-tickets.py"),
76    Test("test-tls13-empty-alert.py"),
77    Test("test-tls13-finished-plaintext.py"),
78    Test("test-tls13-hrr.py"),
79    Test("test-tls13-legacy-version.py"),
80    Test("test-tls13-nociphers.py"),
81    Test("test-tls13-record-padding.py"),
82    Test("test-tls13-shuffled-extentions.py"),
83
84    # The skipped tests fail due to a bug in BIO_gets() which masks the retry
85    # signalled from an SSL_read() failure. Testing with httpd(8) shows we're
86    # handling these corner cases correctly since tls13_record_layer.c -r1.47.
87    Test("test-tls13-zero-length-data.py", [
88        "-e", "zero-length app data",
89        "-e", "zero-length app data with large padding",
90        "-e", "zero-length app data with padding",
91    ]),
92])
93
94# Tests that take a lot of time (> ~30s on an x280)
95tls13_slow_tests = TestGroup("slow TLSv1.3 tests", [
96    # XXX: Investigate the occasional message
97    # "Got shared secret with 1 most significant bytes equal to zero."
98    Test("test-tls13-dhe-shared-secret-padding.py", tls13_unsupported_ciphers),
99
100    Test("test-tls13-invalid-ciphers.py"),
101    Test("test-tls13-serverhello-random.py", tls13_unsupported_ciphers),
102
103    # Mark two tests cases as xfail for now. The tests expect an arguably
104    # correct decode_error while we send a decrypt_error (like fizz/boring).
105    Test("test-tls13-record-layer-limits.py", [
106        "-x", "max size payload (2**14) of Finished msg, with 16348 bytes of left padding, cipher TLS_AES_128_GCM_SHA256",
107        "-x", "max size payload (2**14) of Finished msg, with 16348 bytes of left padding, cipher TLS_CHACHA20_POLY1305_SHA256",
108    ]),
109])
110
111tls13_extra_cert_tests = TestGroup("TLSv1.3 certificate tests", [
112    # need to set up client certs to run these
113    Test("test-tls13-certificate-request.py"),
114    Test("test-tls13-certificate-verify.py"),
115    Test("test-tls13-ecdsa-in-certificate-verify.py"),
116
117    # Test expects the server to have installed three certificates:
118    # with P-256, P-384 and P-521 curve. Also SHA1+ECDSA is verified
119    # to not work.
120    Test("test-tls13-ecdsa-support.py"),
121])
122
123tls13_failing_tests = TestGroup("failing TLSv1.3 tests", [
124    # Some tests fail because we fail later than the scripts expect us to.
125    # With X25519, we accept weak peer public keys and fail when we actually
126    # compute the keyshare.  Other tests seem to indicate that we could be
127    # stricter about what keyshares we accept.
128    Test("test-tls13-crfg-curves.py"),
129    Test("test-tls13-ecdhe-curves.py"),
130
131    # Expects a missing_extensions alert
132    # AssertionError: Unexpected message from peer: Handshake(server_hello)
133    Test("test-tls13-keyshare-omitted.py"),
134
135    # https://github.com/openssl/openssl/issues/8369
136    Test("test-tls13-obsolete-curves.py"),
137
138    # 3 failing rsa_pss_pss tests
139    Test("test-tls13-rsa-signatures.py"),
140
141    # AssertionError: Unexpected message from peer: ChangeCipherSpec()
142    # Most failing tests expect the CCS right before finished.
143    # What's up with that?
144    Test("test-tls13-version-negotiation.py"),
145])
146
147tls13_slow_failing_tests = TestGroup("slow, failing TLSv1.3 tests", [
148    # Other test failures bugs in keyshare/tlsext negotiation?
149    Test("test-tls13-unrecognised-groups.py"),    # unexpected closure
150
151    # 5 failures:
152    #   'app data split, conversation with KeyUpdate msg'
153    #   'fragmented keyupdate msg'
154    #   'multiple KeyUpdate messages'
155    #   'post-handshake KeyUpdate msg with update_not_request'
156    #   'post-handshake KeyUpdate msg with update_request'
157    Test("test-tls13-keyupdate.py"),
158
159    Test("test-tls13-symetric-ciphers.py"),       # unexpected message from peer
160
161    # 70 fail and 644 pass. For some reason the tests expect a decode_error
162    # but we send a decrypt_error after the CBS_mem_equal() fails in
163    # tls13_server_finished_recv() (which is correct).
164    Test("test-tls13-finished.py"),               # decrypt_error -> decode_error?
165
166    # The following two tests fail Test (skip empty extensions for the first one):
167    # 'empty unassigned extensions, ids in range from 2 to 4118'
168    # 'unassigned extensions with random payload, ids in range from 2 to 1046'
169    Test("test-tls13-large-number-of-extensions.py"), # 2 fail: empty/random payload
170
171    # 6 tests fail: 'rsa_pkcs1_{md5,sha{1,224,256,384,512}} signature'
172    # We send server hello, but the test expects handshake_failure
173    Test("test-tls13-pkcs-signature.py"),
174    # 8 tests fail: 'tls13 signature rsa_pss_{pss,rsae}_sha{256,384,512}
175    Test("test-tls13-rsapss-signatures.py"),
176
177    # ExpectNewSessionTicket
178    Test("test-tls13-session-resumption.py"),
179])
180
181tls13_unsupported_tests = TestGroup("TLSv1.3 tests for unsupported features", [
182    # Tests for features we don't support
183    Test("test-tls13-0rtt-garbage.py"),
184    Test("test-tls13-ffdhe-groups.py"),
185    Test("test-tls13-ffdhe-sanity.py"),
186    Test("test-tls13-psk_dhe_ke.py"),
187    Test("test-tls13-psk_ke.py"),
188
189    # need server to react to HTTP GET for /keyupdate
190    Test("test-tls13-keyupdate-from-server.py"),
191
192    # Weird test: tests servers that don't support 1.3
193    Test("test-tls13-non-support.py"),
194
195    # broken test script
196    # UnboundLocalError: local variable 'cert' referenced before assignment
197    Test("test-tls13-post-handshake-auth.py"),
198
199    # Server must be configured to support only rsa_pss_rsae_sha512
200    Test("test-tls13-signature-algorithms.py"),
201])
202
203tls12_exclude_legacy_protocols = [
204    # all these have BIO_read timeouts against TLSv1.3
205    "-e", "Protocol (3, 0)",
206    "-e", "Protocol (3, 0) in SSLv2 compatible ClientHello",
207    # the following only fail with TLSv1.3
208    "-e", "Protocol (3, 1) in SSLv2 compatible ClientHello",
209    "-e", "Protocol (3, 2) in SSLv2 compatible ClientHello",
210    "-e", "Protocol (3, 3) in SSLv2 compatible ClientHello",
211    "-e", "Protocol (3, 1) with secp521r1 group",   # XXX
212    "-e", "Protocol (3, 1) with x448 group",
213    "-e", "Protocol (3, 2) with secp521r1 group",   # XXX
214    "-e", "Protocol (3, 2) with x448 group",
215    "-e", "Protocol (3, 3) with secp521r1 group",   # XXX
216    "-e", "Protocol (3, 3) with x448 group",
217]
218
219tls12_tests = TestGroup("TLSv1.2 tests", [
220    # Tests that pass as they are.
221    Test("test-TLSv1_2-rejected-without-TLSv1_2.py"),
222    Test("test-aes-gcm-nonces.py"),
223    Test("test-chacha20.py"),
224    Test("test-conversation.py"),
225    Test("test-cve-2016-2107.py"),
226    Test("test-dhe-rsa-key-exchange.py"),
227    Test("test-dhe-rsa-key-exchange-with-bad-messages.py"),
228    Test("test-early-application-data.py"),
229    Test("test-empty-extensions.py"),
230    Test("test-fuzzed-MAC.py"),
231    Test("test-fuzzed-ciphertext.py"),
232    Test("test-fuzzed-finished.py"),
233    Test("test-fuzzed-padding.py"),
234    Test("test-hello-request-by-client.py"),
235    Test("test-invalid-cipher-suites.py"),
236    Test("test-invalid-content-type.py"),
237    Test("test-invalid-session-id.py"),
238    Test("test-invalid-version.py"),
239    Test("test-lucky13.py"),
240    Test("test-message-skipping.py"),
241    Test("test-no-heartbeat.py"),
242    Test("test-sessionID-resumption.py"),
243    Test("test-sslv2-connection.py"),
244    Test("test-truncating-of-finished.py"),
245    Test("test-truncating-of-kRSA-client-key-exchange.py"),
246    Test("test-unsupported-curve-fallback.py"),
247    Test("test-version-numbers.py"),
248    Test("test-zero-length-data.py"),
249
250    # Tests that need tweaking for unsupported features and ciphers.
251    Test(
252        "test-atypical-padding.py", [
253            "-e", "sanity - encrypt then MAC",
254            "-e", "2^14 bytes of AppData with 256 bytes of padding (SHA1 + Encrypt then MAC)",
255        ]
256    ),
257    Test(
258        "test-dhe-rsa-key-exchange-signatures.py", [
259            "-e", "TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA sha224 signature",
260            "-e", "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 sha224 signature",
261            "-e", "TLS_DHE_RSA_WITH_AES_128_CBC_SHA sha224 signature",
262            "-e", "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 sha224 signature",
263            "-e", "TLS_DHE_RSA_WITH_AES_256_CBC_SHA sha224 signature",
264        ]
265    ),
266    Test("test-dhe-key-share-random.py", tls12_exclude_legacy_protocols),
267    Test("test-export-ciphers-rejected.py", ["--min-ver", "TLSv1.0"]),
268    Test(
269        "test-downgrade-protection.py",
270        tls12_args = ["--server-max-protocol", "TLSv1.2"],
271        tls13_args = ["--server-max-protocol", "TLSv1.3"],
272    ),
273    Test("test-fallback-scsv.py", tls13_args = ["--tls-1.3"] ),
274    Test("test-serverhello-random.py", args = tls12_exclude_legacy_protocols),
275])
276
277tls12_slow_tests = TestGroup("slow TLSv1.2 tests", [
278    Test("test-cve-2016-7054.py"),
279    Test("test-dhe-no-shared-secret-padding.py", tls12_exclude_legacy_protocols),
280    Test("test-ecdhe-padded-shared-secret.py", tls12_exclude_legacy_protocols),
281    Test("test-ecdhe-rsa-key-share-random.py", tls12_exclude_legacy_protocols),
282    # This test has some failures once in a while.
283    Test("test-fuzzed-plaintext.py"),
284])
285
286tls12_failing_tests = TestGroup("failing TLSv1.2 tests", [
287    # no shared cipher
288    Test("test-aesccm.py"),
289    # need server to set up alpn
290    Test("test-alpn-negotiation.py"),
291    # many tests fail due to unexpected server_name extension
292    Test("test-bleichenbacher-workaround.py"),
293
294    # need client key and cert plus extra server setup
295    Test("test-certificate-malformed.py"),
296    Test("test-certificate-request.py"),
297    Test("test-certificate-verify-malformed-sig.py"),
298    Test("test-certificate-verify-malformed.py"),
299    Test("test-certificate-verify.py"),
300    Test("test-ecdsa-in-certificate-verify.py"),
301    Test("test-renegotiation-disabled-client-cert.py"),
302    Test("test-rsa-pss-sigs-on-certificate-verify.py"),
303    Test("test-rsa-sigs-on-certificate-verify.py"),
304
305    # test doesn't expect session ticket
306    Test("test-client-compatibility.py"),
307    # abrupt closure
308    Test("test-client-hello-max-size.py"),
309    # unknown signature algorithms
310    Test("test-clienthello-md5.py"),
311    # abrupt closure
312    Test("test-cve-2016-6309.py"),
313
314    # Tests expect an illegal_parameter alert
315    Test("test-ecdhe-rsa-key-exchange-with-bad-messages.py"),
316
317    # We send a handshake_failure while the test expects to succeed
318    Test("test-ecdhe-rsa-key-exchange.py"),
319
320    # unsupported?
321    Test("test-extended-master-secret-extension-with-client-cert.py"),
322
323    # no shared cipher
324    Test("test-ecdsa-sig-flexibility.py"),
325
326    # unsupported
327    Test("test-encrypt-then-mac-renegotiation.py"),
328    Test("test-encrypt-then-mac.py"),
329    Test("test-extended-master-secret-extension.py"),
330    Test("test-ffdhe-negotiation.py"),
331    # unsupported. Expects the server to send the heartbeat extension
332    Test("test-heartbeat.py"),
333
334    # 29 succeed, 263 fail:
335    #   'n extensions', 'n extensions last empty' n in 4086, 4096, 8192, 16383
336    #   'fuzz ext length to n' n in [0..255] with the exception of 41...
337    Test("test-extensions.py"),
338
339    # Tests expect SH but we send unexpected_message or handshake_failure
340    #   'Application data inside Client Hello'
341    #   'Application data inside Client Key Exchange'
342    #   'Application data inside Finished'
343    Test("test-interleaved-application-data-and-fragmented-handshakes-in-renegotiation.py"),
344    # Tests expect SH but we send handshake_failure
345    #   'Application data before Change Cipher Spec'
346    #   'Application data before Client Key Exchange'
347    #   'Application data before Finished'
348    Test("test-interleaved-application-data-in-renegotiation.py"),
349
350    # broken test script
351    # TypeError: '<' not supported between instances of 'int' and 'NoneType'
352    Test("test-invalid-client-hello-w-record-overflow.py"),
353
354    # Lots of failures. abrupt closure
355    Test("test-invalid-client-hello.py"),
356
357    # Test expects illegal_parameter, we send decode_error in ssl_srvr.c:1016
358    # Need to check that this is correct.
359    Test("test-invalid-compression-methods.py"),
360
361    # abrupt closure
362    # 'encrypted premaster set to all zero (n)' n in 256 384 512
363    Test("test-invalid-rsa-key-exchange-messages.py"),
364
365    # test expects illegal_parameter, we send unrecognized_name (which seems
366    # correct according to rfc 6066?)
367    Test("test-invalid-server-name-extension-resumption.py"),
368    # let through some server names without sending an alert
369    # again illegal_parameter vs unrecognized_name
370    Test("test-invalid-server-name-extension.py"),
371
372    Test("test-large-hello.py"),
373
374    # 14 pass
375    # 7 fail
376    # 'n extensions', n in 4095, 4096, 4097, 8191, 8192, 8193, 16383,
377    Test("test-large-number-of-extensions.py"),
378
379    # 4 failures:
380    #   'insecure (legacy) renegotiation with GET after 2nd handshake'
381    #   'insecure (legacy) renegotiation with incomplete GET'
382    #   'secure renegotiation with GET after 2nd handshake'
383    #   'secure renegotiation with incomplete GET'
384    Test("test-legacy-renegotiation.py"),
385
386    # 1 failure (timeout): we don't send the unexpected_message alert
387    # 'duplicate change cipher spec after Finished'
388    Test("test-message-duplication.py"),
389
390    # server should send status_request
391    Test("test-ocsp-stapling.py"),
392
393    # unexpected closure
394    Test("test-openssl-3712.py"),
395
396    # 3 failures:
397    # 'big, needs fragmentation: max fragment - 16336B extension'
398    # 'big, needs fragmentation: max fragment - 32768B extension'
399    # 'maximum size: max fragment - 65531B extension'
400    Test("test-record-layer-fragmentation.py"),
401
402    # wants --reply-AD-size
403    Test("test-record-size-limit.py"),
404
405    # failed: 3 (expect an alert, we send AD)
406    # 'try insecure (legacy) renegotiation with incomplete GET'
407    # 'try secure renegotiation with GET after 2nd CH'
408    # 'try secure renegotiation with incomplete GET'
409    Test("test-renegotiation-disabled.py"),
410
411    # 'resumption of safe session with NULL cipher'
412    # 'resumption with cipher from old CH but not selected by server'
413    Test("test-resumption-with-wrong-ciphers.py"),
414
415    # 5 failures:
416    #   'empty sigalgs'
417    #   'only undefined sigalgs'
418    #   'rsa_pss_pss_sha256 only'
419    #   'rsa_pss_pss_sha384 only'
420    #   'rsa_pss_pss_sha512 only'
421    Test("test-sig-algs.py"),
422
423    # 13 failures:
424    #   'duplicated n non-rsa schemes' for n in 202 2342 8119 23741 32744
425    #   'empty list of signature methods'
426    #   'tolerance n RSA or ECDSA methods' for n in 215 2355 8132 23754
427    #   'tolerance 32758 methods with sig_alg_cert'
428    #   'tolerance max 32744 number of methods with sig_alg_cert'
429    #   'tolerance max (32760) number of methods'
430    Test("test-signature-algorithms.py"),
431
432    # times out
433    Test("test-ssl-death-alert.py"),
434
435    # 17 pass, 13 fail. padding and truncation
436    Test("test-truncating-of-client-hello.py"),
437
438    # x448 tests need disabling plus x25519 corner cases need sorting out
439    Test("test-x25519.py"),
440])
441
442tls12_unsupported_tests = TestGroup("TLSv1.2 for unsupported features", [
443    # protocol_version
444    Test("test-SSLv3-padding.py"),
445    # we don't do RSA key exchanges
446    Test("test-bleichenbacher-timing.py"),
447])
448
449# These tests take a ton of time to fail against an 1.3 server,
450# so don't run them against 1.3 pending further investigation.
451legacy_tests = TestGroup("Legacy protocol tests", [
452    Test("test-sslv2-force-cipher-3des.py"),
453    Test("test-sslv2-force-cipher-non3des.py"),
454    Test("test-sslv2-force-cipher.py"),
455    Test("test-sslv2-force-export-cipher.py"),
456    Test("test-sslv2hello-protocol.py"),
457])
458
459all_groups = [
460    tls13_tests,
461    tls13_slow_tests,
462    tls13_extra_cert_tests,
463    tls13_failing_tests,
464    tls13_slow_failing_tests,
465    tls13_unsupported_tests,
466    tls12_tests,
467    tls12_slow_tests,
468    tls12_failing_tests,
469    tls12_unsupported_tests,
470    legacy_tests,
471]
472
473failing_groups = [
474    tls13_failing_tests,
475    tls13_slow_failing_tests,
476    tls12_failing_tests,
477]
478
479class TestRunner:
480    """ Runs the given tests troups against a server and displays stats. """
481
482    def __init__(
483        self, timing=False, verbose=False, port=4433, use_tls1_3=True,
484        dry_run=False, tests=[], scriptdir=tlsfuzzer_scriptdir,
485    ):
486        self.tests = []
487
488        self.dryrun = dry_run
489        self.use_tls1_3 = use_tls1_3
490        self.port = str(port)
491        self.scriptdir = scriptdir
492
493        self.stats = []
494        self.failed = []
495
496        self.timing = timing
497        self.verbose = verbose
498
499    def add(self, title="tests", tests=[]):
500        # tests.sort(key=lambda test: test.name)
501        self.tests.append(TestGroup(title, tests))
502
503    def add_group(self, group):
504        self.tests.append(group)
505
506    def run_script(self, test):
507        script = test.name
508        args = ["-p"] + [self.port] + test.args(self.use_tls1_3)
509
510        if self.dryrun:
511            if not self.verbose:
512                args = []
513            print(script , end=' ' if args else '')
514            print(' '.join([f"\"{arg}\"" for arg in args]))
515            return
516
517        if self.verbose:
518            print(script)
519        else:
520            print(f"{script[:68]:<72}", end=" ", flush=True)
521        start = timer()
522        test = subprocess.run(
523            ["python3", os.path.join(self.scriptdir, script)] + args,
524            capture_output=not self.verbose,
525            text=True,
526        )
527        end = timer()
528        self.stats.append((script, end - start))
529        if test.returncode == 0:
530            print("OK")
531            return
532        print("FAILED")
533        self.failed.append(script)
534
535        if self.verbose:
536            return
537
538        print('\n'.join(test.stdout.split("Test end\n", 1)[1:]), end="")
539
540    def run(self):
541        for group in self:
542            print(f"Running {group.title} ...")
543            for test in group:
544                self.run_script(test)
545        return not self.failed
546
547    def __iter__(self):
548        return iter(self.tests)
549
550    def __del__(self):
551        if self.timing and self.stats:
552            total = 0.0
553            for (script, time) in self.stats:
554                print(f"{round(time, 2):6.2f} {script}")
555                total += time
556            print(f"{round(total, 2):6.2f} total")
557
558        if self.failed:
559            print("Failed tests:")
560            print('\n'.join(self.failed))
561
562class TlsServer:
563    """ Spawns an s_server listening on localhost:port if necessary. """
564
565    def __init__(self, port=4433):
566        self.spawn = True
567        # Check whether a server is already listening on localhost:port
568        self.spawn = subprocess.run(
569            ["nc", "-c", "-z", "-T", "noverify", "localhost", str(port)],
570            stderr=subprocess.DEVNULL,
571        ).returncode != 0
572
573        if self.spawn:
574            self.server = subprocess.Popen(
575                [
576                    "openssl",
577                    "s_server",
578                    "-accept",
579                    str(port),
580                    "-key",
581                    "localhost.key",
582                    "-cert",
583                    "localhost.crt",
584                    "-www",
585                ],
586                stdout=subprocess.DEVNULL,
587                stderr=subprocess.PIPE,
588                text=True,
589            )
590
591        # Check whether the server talks TLSv1.3
592        self.has_tls1_3 = True or subprocess.run(
593            [
594                "nc",
595                "-c",
596                "-z",
597                "-T",
598                "noverify",
599                "-T",
600                "protocols=TLSv1.3",
601                "localhost",
602                str(port),
603            ],
604            stderr=subprocess.DEVNULL,
605        ).returncode == 0
606
607        self.check()
608
609    def check(self):
610        if self.spawn and self.server.poll() is not None:
611            print(self.server.stderr.read())
612            raise RuntimeError(
613                f"openssl s_server died. Return code: {self.server.returncode}."
614            )
615        if self.spawn:
616            self.server.stderr.detach()
617
618    def __del__(self):
619        if self.spawn:
620            self.server.terminate()
621
622# Extract the arguments we pass to script
623def defaultargs(script, has_tls1_3):
624    return next(
625        (test for group in all_groups for test in group if test.name == script),
626        Test()
627    ).args(has_tls1_3)
628
629def list_or_missing(missing=True):
630    tests = [test.name for group in all_groups for test in group]
631
632    if missing:
633        scripts = {
634            f for f in os.listdir(tlsfuzzer_scriptdir) if f != "__pycache__"
635        }
636        missing = scripts - set(tests)
637        if missing:
638            print('\n'.join(sorted(missing)))
639        exit(0)
640
641    tests.sort()
642    print('\n'.join(tests))
643    exit(0)
644
645def usage():
646    print("Usage: python3 tlsfuzzer.py [-lmnstv] [-p port] [script [test...]]")
647    print(" --help      help")
648    print(" -f          run failing tests")
649    print(" -l          list tests")
650    print(" -m          list new tests after package update")
651    print(" -n          do not run tests, but list the ones that would be run")
652    print(" -p port     connect to this port - defaults to 4433")
653    print(" -s          run slow tests")
654    print(" -t          show timing stats at end")
655    print(" -v          verbose output")
656    exit(0)
657
658def main():
659    failing = False
660    list = False
661    missing = False
662    dryrun = False
663    port = 4433
664    slow = False
665    timing = False
666    verbose = False
667
668    argv = sys.argv[1:]
669    opts, args = getopt.getopt(argv, "flmnp:stv", ["help"])
670    for opt, arg in opts:
671        if opt == '--help':
672            usage()
673        elif opt == '-f':
674            failing = True
675        elif opt == '-l':
676            list = True
677        elif opt == '-m':
678            missing = True
679        elif opt == '-n':
680            dryrun = True
681        elif opt == '-p':
682            port = int(arg)
683        elif opt == '-s':
684            slow = True
685        elif opt == '-t':
686            timing = True
687        elif opt == '-v':
688            verbose = True
689        else:
690            raise ValueError(f"Unknown option: {opt}")
691
692    if not os.path.exists(tlsfuzzer_scriptdir):
693        print("package py3-tlsfuzzer is required for this regress")
694        exit(1)
695
696    if list and failing:
697        failing = [test.name for group in failing_groups for test in group]
698        failing.sort()
699        print('\n'.join(failing))
700        exit(0)
701
702    if list or missing:
703        list_or_missing(missing)
704
705    tls_server = TlsServer(port)
706
707    tests = TestRunner(timing, verbose, port, tls_server.has_tls1_3, dryrun)
708
709    if args:
710        (dir, script) = os.path.split(args[0])
711        if dir and not dir == '.':
712            tests.scriptdir = dir
713
714        testargs = defaultargs(script, tls_server.has_tls1_3)
715
716        tests.verbose = True
717        tests.add("test from command line", [Test(script, testargs + args[1:])])
718
719        exit(not tests.run())
720
721    if failing:
722        if tls_server.has_tls1_3:
723            tests.add_group(tls13_failing_tests)
724            if slow:
725                tests.add_group(tls13_slow_failing_tests)
726        tests.add_group(tls12_failing_tests)
727
728    if tls_server.has_tls1_3:
729        tests.add_group(tls13_tests)
730        if slow:
731            tests.add_group(tls13_slow_tests)
732    else:
733        tests.add_group(legacy_tests)
734
735    tests.add_group(tls12_tests)
736    if slow:
737        tests.add_group(tls12_slow_tests)
738
739    success = tests.run()
740    del tests
741
742    if not success:
743        print("FAILED")
744        exit(1)
745
746if __name__ == "__main__":
747    main()
748