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