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