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