xref: /openbsd-src/regress/lib/libssl/tlsfuzzer/tlsfuzzer.py (revision de8cc8edbc71bd3e3bc7fbffa27ba0e564c37d8b)
1#   $OpenBSD: tlsfuzzer.py,v 1.22 2021/01/27 20:16:58 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    # https://github.com/openssl/openssl/issues/8369
247    Test("test-tls13-obsolete-curves.py"),
248
249    # 3 failing rsa_pss_pss tests
250    Test("test-tls13-rsa-signatures.py"),
251
252    # AssertionError: Unexpected message from peer: ChangeCipherSpec()
253    # Most failing tests expect the CCS right before finished.
254    # What's up with that?
255    Test("test-tls13-version-negotiation.py"),
256])
257
258tls13_slow_failing_tests = TestGroup("slow, failing TLSv1.3 tests", [
259    # Other test failures bugs in keyshare/tlsext negotiation?
260    Test("test-tls13-unrecognised-groups.py"),    # unexpected closure
261
262    # 5 failures:
263    #   'app data split, conversation with KeyUpdate msg'
264    #   'fragmented keyupdate msg'
265    #   'multiple KeyUpdate messages'
266    #   'post-handshake KeyUpdate msg with update_not_request'
267    #   'post-handshake KeyUpdate msg with update_request'
268    Test("test-tls13-keyupdate.py"),
269
270    Test("test-tls13-symetric-ciphers.py"),       # unexpected message from peer
271
272    # 6 tests fail: 'rsa_pkcs1_{md5,sha{1,224,256,384,512}} signature'
273    # We send server hello, but the test expects handshake_failure
274    Test("test-tls13-pkcs-signature.py"),
275    # 8 tests fail: 'tls13 signature rsa_pss_{pss,rsae}_sha{256,384,512}
276    Test("test-tls13-rsapss-signatures.py"),
277])
278
279tls13_unsupported_tests = TestGroup("TLSv1.3 tests for unsupported features", [
280    # Tests for features we don't support
281    Test("test-tls13-0rtt-garbage.py"),
282    Test("test-tls13-ffdhe-groups.py"),
283    Test("test-tls13-ffdhe-sanity.py"),
284    Test("test-tls13-psk_dhe_ke.py"),
285    Test("test-tls13-psk_ke.py"),
286
287    # need server to react to HTTP GET for /keyupdate
288    Test("test-tls13-keyupdate-from-server.py"),
289
290    # Weird test: tests servers that don't support 1.3
291    Test("test-tls13-non-support.py"),
292
293    # broken test script
294    # UnboundLocalError: local variable 'cert' referenced before assignment
295    Test("test-tls13-post-handshake-auth.py"),
296
297    # ExpectNewSessionTicket
298    Test("test-tls13-session-resumption.py"),
299
300    # Server must be configured to support only rsa_pss_rsae_sha512
301    Test("test-tls13-signature-algorithms.py"),
302])
303
304tls12_exclude_legacy_protocols = [
305    # all these have BIO_read timeouts against TLSv1.3
306    "-e", "Protocol (3, 0)",
307    "-e", "Protocol (3, 0) in SSLv2 compatible ClientHello",
308    # the following only fail with TLSv1.3
309    "-e", "Protocol (3, 1) in SSLv2 compatible ClientHello",
310    "-e", "Protocol (3, 2) in SSLv2 compatible ClientHello",
311    "-e", "Protocol (3, 3) in SSLv2 compatible ClientHello",
312    "-e", "Protocol (3, 1) with x448 group",
313    "-e", "Protocol (3, 2) with x448 group",
314    "-e", "Protocol (3, 3) with x448 group",
315]
316
317tls12_tests = TestGroup("TLSv1.2 tests", [
318    # Tests that pass as they are.
319    Test("test-TLSv1_2-rejected-without-TLSv1_2.py"),
320    Test("test-aes-gcm-nonces.py"),
321    Test("test-chacha20.py"),
322    Test("test-conversation.py"),
323    Test("test-cve-2016-2107.py"),
324    Test("test-dhe-rsa-key-exchange.py"),
325    Test("test-dhe-rsa-key-exchange-with-bad-messages.py"),
326    Test("test-early-application-data.py"),
327    Test("test-empty-extensions.py"),
328    Test("test-fuzzed-MAC.py"),
329    Test("test-fuzzed-ciphertext.py"),
330    Test("test-fuzzed-finished.py"),
331    Test("test-fuzzed-padding.py"),
332    Test("test-hello-request-by-client.py"),
333    Test("test-invalid-cipher-suites.py"),
334    Test("test-invalid-content-type.py"),
335    Test("test-invalid-session-id.py"),
336    Test("test-invalid-version.py"),
337    Test("test-lucky13.py"),
338    Test("test-message-skipping.py"),
339    Test("test-no-heartbeat.py"),
340    Test("test-sessionID-resumption.py"),
341    Test("test-sslv2-connection.py"),
342    Test("test-truncating-of-finished.py"),
343    Test("test-truncating-of-kRSA-client-key-exchange.py"),
344    Test("test-unsupported-curve-fallback.py"),
345    Test("test-version-numbers.py"),
346    Test("test-zero-length-data.py"),
347
348    # Tests that need tweaking for unsupported features and ciphers.
349    Test(
350        "test-atypical-padding.py", [
351            "-e", "sanity - encrypt then MAC",
352            "-e", "2^14 bytes of AppData with 256 bytes of padding (SHA1 + Encrypt then MAC)",
353        ]
354    ),
355    Test(
356        "test-dhe-rsa-key-exchange-signatures.py", [
357            "-e", "TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA sha224 signature",
358            "-e", "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 sha224 signature",
359            "-e", "TLS_DHE_RSA_WITH_AES_128_CBC_SHA sha224 signature",
360            "-e", "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 sha224 signature",
361            "-e", "TLS_DHE_RSA_WITH_AES_256_CBC_SHA sha224 signature",
362        ]
363    ),
364    Test("test-dhe-key-share-random.py", tls12_exclude_legacy_protocols),
365    Test("test-export-ciphers-rejected.py", ["--min-ver", "TLSv1.0"]),
366    Test(
367        "test-downgrade-protection.py",
368        tls12_args = ["--server-max-protocol", "TLSv1.2"],
369        tls13_args = ["--server-max-protocol", "TLSv1.3"],
370    ),
371    Test("test-fallback-scsv.py", tls13_args = ["--tls-1.3"] ),
372    Test("test-serverhello-random.py", args = tls12_exclude_legacy_protocols),
373])
374
375tls12_slow_tests = TestGroup("slow TLSv1.2 tests", [
376    Test("test-cve-2016-7054.py"),
377    Test("test-dhe-no-shared-secret-padding.py", tls12_exclude_legacy_protocols),
378    Test("test-ecdhe-padded-shared-secret.py", tls12_exclude_legacy_protocols),
379    Test("test-ecdhe-rsa-key-share-random.py", tls12_exclude_legacy_protocols),
380    # This test has some failures once in a while.
381    Test("test-fuzzed-plaintext.py"),
382])
383
384tls12_failing_tests = TestGroup("failing TLSv1.2 tests", [
385    # no shared cipher
386    Test("test-aesccm.py"),
387    # need server to set up alpn
388    Test("test-alpn-negotiation.py"),
389    # many tests fail due to unexpected server_name extension
390    Test("test-bleichenbacher-workaround.py"),
391
392    # need client key and cert plus extra server setup
393    Test("test-certificate-malformed.py"),
394    Test("test-certificate-request.py"),
395    Test("test-certificate-verify-malformed-sig.py"),
396    Test("test-certificate-verify-malformed.py"),
397    Test("test-certificate-verify.py"),
398    Test("test-ecdsa-in-certificate-verify.py"),
399    Test("test-renegotiation-disabled-client-cert.py"),
400    Test("test-rsa-pss-sigs-on-certificate-verify.py"),
401    Test("test-rsa-sigs-on-certificate-verify.py"),
402
403    # test doesn't expect session ticket
404    Test("test-client-compatibility.py"),
405    # abrupt closure
406    Test("test-client-hello-max-size.py"),
407    # unknown signature algorithms
408    Test("test-clienthello-md5.py"),
409    # abrupt closure
410    Test("test-cve-2016-6309.py"),
411
412    # Tests expect an illegal_parameter alert
413    Test("test-ecdhe-rsa-key-exchange-with-bad-messages.py"),
414
415    # We send a handshake_failure while the test expects to succeed
416    Test("test-ecdhe-rsa-key-exchange.py"),
417
418    # unsupported?
419    Test("test-extended-master-secret-extension-with-client-cert.py"),
420
421    # no shared cipher
422    Test("test-ecdsa-sig-flexibility.py"),
423
424    # unsupported
425    Test("test-encrypt-then-mac-renegotiation.py"),
426    Test("test-encrypt-then-mac.py"),
427    Test("test-extended-master-secret-extension.py"),
428    Test("test-ffdhe-expected-params.py"),
429    Test("test-ffdhe-negotiation.py"),
430    # unsupported. Expects the server to send the heartbeat extension
431    Test("test-heartbeat.py"),
432
433    # 29 succeed, 263 fail:
434    #   'n extensions', 'n extensions last empty' n in 4086, 4096, 8192, 16383
435    #   'fuzz ext length to n' n in [0..255] with the exception of 41...
436    Test("test-extensions.py"),
437
438    # Tests expect SH but we send unexpected_message or handshake_failure
439    #   'Application data inside Client Hello'
440    #   'Application data inside Client Key Exchange'
441    #   'Application data inside Finished'
442    Test("test-interleaved-application-data-and-fragmented-handshakes-in-renegotiation.py"),
443    # Tests expect SH but we send handshake_failure
444    #   'Application data before Change Cipher Spec'
445    #   'Application data before Client Key Exchange'
446    #   'Application data before Finished'
447    Test("test-interleaved-application-data-in-renegotiation.py"),
448
449    # broken test script
450    # TypeError: '<' not supported between instances of 'int' and 'NoneType'
451    Test("test-invalid-client-hello-w-record-overflow.py"),
452
453    # Lots of failures. abrupt closure
454    Test("test-invalid-client-hello.py"),
455
456    # Test expects illegal_parameter, we send decode_error in ssl_srvr.c:1016
457    # Need to check that this is correct.
458    Test("test-invalid-compression-methods.py"),
459
460    # abrupt closure
461    # 'encrypted premaster set to all zero (n)' n in 256 384 512
462    Test("test-invalid-rsa-key-exchange-messages.py"),
463
464    # test expects illegal_parameter, we send unrecognized_name (which seems
465    # correct according to rfc 6066?)
466    Test("test-invalid-server-name-extension-resumption.py"),
467    # let through some server names without sending an alert
468    # again illegal_parameter vs unrecognized_name
469    Test("test-invalid-server-name-extension.py"),
470
471    Test("test-large-hello.py"),
472
473    # 14 pass
474    # 7 fail
475    # 'n extensions', n in 4095, 4096, 4097, 8191, 8192, 8193, 16383,
476    Test("test-large-number-of-extensions.py"),
477
478    # 4 failures:
479    #   'insecure (legacy) renegotiation with GET after 2nd handshake'
480    #   'insecure (legacy) renegotiation with incomplete GET'
481    #   'secure renegotiation with GET after 2nd handshake'
482    #   'secure renegotiation with incomplete GET'
483    Test("test-legacy-renegotiation.py"),
484
485    # 1 failure (timeout): we don't send the unexpected_message alert
486    # 'duplicate change cipher spec after Finished'
487    Test("test-message-duplication.py"),
488
489    # server should send status_request
490    Test("test-ocsp-stapling.py"),
491
492    # unexpected closure
493    Test("test-openssl-3712.py"),
494
495    # 3 failures:
496    # 'big, needs fragmentation: max fragment - 16336B extension'
497    # 'big, needs fragmentation: max fragment - 32768B extension'
498    # 'maximum size: max fragment - 65531B extension'
499    Test("test-record-layer-fragmentation.py"),
500
501    # wants --reply-AD-size
502    Test("test-record-size-limit.py"),
503
504    # failed: 3 (expect an alert, we send AD)
505    # 'try insecure (legacy) renegotiation with incomplete GET'
506    # 'try secure renegotiation with GET after 2nd CH'
507    # 'try secure renegotiation with incomplete GET'
508    Test("test-renegotiation-disabled.py"),
509
510    # 'resumption of safe session with NULL cipher'
511    # 'resumption with cipher from old CH but not selected by server'
512    Test("test-resumption-with-wrong-ciphers.py"),
513
514    # 5 failures:
515    #   'empty sigalgs'
516    #   'only undefined sigalgs'
517    #   'rsa_pss_pss_sha256 only'
518    #   'rsa_pss_pss_sha384 only'
519    #   'rsa_pss_pss_sha512 only'
520    Test("test-sig-algs.py"),
521
522    # 13 failures:
523    #   'duplicated n non-rsa schemes' for n in 202 2342 8119 23741 32744
524    #   'empty list of signature methods'
525    #   'tolerance n RSA or ECDSA methods' for n in 215 2355 8132 23754
526    #   'tolerance 32758 methods with sig_alg_cert'
527    #   'tolerance max 32744 number of methods with sig_alg_cert'
528    #   'tolerance max (32760) number of methods'
529    Test("test-signature-algorithms.py"),
530
531    # times out
532    Test("test-ssl-death-alert.py"),
533
534    # 17 pass, 13 fail. padding and truncation
535    Test("test-truncating-of-client-hello.py"),
536
537    # x448 tests need disabling plus x25519 corner cases need sorting out
538    Test("test-x25519.py"),
539])
540
541tls12_unsupported_tests = TestGroup("TLSv1.2 for unsupported features", [
542    # protocol_version
543    Test("test-SSLv3-padding.py"),
544    # we don't do RSA key exchanges
545    Test("test-bleichenbacher-timing.py"),
546])
547
548# These tests take a ton of time to fail against an 1.3 server,
549# so don't run them against 1.3 pending further investigation.
550legacy_tests = TestGroup("Legacy protocol tests", [
551    Test("test-sslv2-force-cipher-3des.py"),
552    Test("test-sslv2-force-cipher-non3des.py"),
553    Test("test-sslv2-force-cipher.py"),
554    Test("test-sslv2-force-export-cipher.py"),
555    Test("test-sslv2hello-protocol.py"),
556])
557
558all_groups = [
559    tls13_tests,
560    tls13_slow_tests,
561    tls13_extra_cert_tests,
562    tls13_failing_tests,
563    tls13_slow_failing_tests,
564    tls13_unsupported_tests,
565    tls12_tests,
566    tls12_slow_tests,
567    tls12_failing_tests,
568    tls12_unsupported_tests,
569    legacy_tests,
570]
571
572failing_groups = [
573    tls13_failing_tests,
574    tls13_slow_failing_tests,
575    tls12_failing_tests,
576]
577
578class TestRunner:
579    """ Runs the given tests troups against a server and displays stats. """
580
581    def __init__(
582        self, timing=False, verbose=False, port=4433, use_tls1_3=True,
583        dry_run=False, tests=[], scriptdir=tlsfuzzer_scriptdir,
584    ):
585        self.tests = []
586
587        self.dryrun = dry_run
588        self.use_tls1_3 = use_tls1_3
589        self.port = str(port)
590        self.scriptdir = scriptdir
591
592        self.stats = []
593        self.failed = []
594        self.missing = []
595
596        self.timing = timing
597        self.verbose = verbose
598
599    def add(self, title="tests", tests=[]):
600        # tests.sort(key=lambda test: test.name)
601        self.tests.append(TestGroup(title, tests))
602
603    def add_group(self, group):
604        self.tests.append(group)
605
606    def run_script(self, test):
607        script = test.name
608        args = ["-p"] + [self.port] + test.args(self.use_tls1_3)
609
610        if self.dryrun:
611            if not self.verbose:
612                args = []
613            print(script , end=' ' if args else '')
614            print(' '.join([f"\"{arg}\"" for arg in args]))
615            return
616
617        if self.verbose:
618            print(script)
619        else:
620            print(f"{script[:68]:<72}", end=" ", flush=True)
621        start = timer()
622        scriptpath = os.path.join(self.scriptdir, script)
623        if not os.path.exists(scriptpath):
624            self.missing.append(script)
625            print("MISSING")
626            return
627        test = subprocess.run(
628            ["python3", scriptpath] + args,
629            capture_output=not self.verbose,
630            text=True,
631        )
632        end = timer()
633        self.stats.append((script, end - start))
634        if test.returncode == 0:
635            print("OK")
636            return
637        print("FAILED")
638        self.failed.append(script)
639
640        if self.verbose:
641            return
642
643        print('\n'.join(test.stdout.split("Test end\n", 1)[1:]), end="")
644
645    def run(self):
646        for group in self:
647            print(f"Running {group.title} ...")
648            for test in group:
649                self.run_script(test)
650        return not self.failed
651
652    def __iter__(self):
653        return iter(self.tests)
654
655    def __del__(self):
656        if self.timing and self.stats:
657            total = 0.0
658            for (script, time) in self.stats:
659                print(f"{round(time, 2):6.2f} {script}")
660                total += time
661            print(f"{round(total, 2):6.2f} total")
662
663        if self.failed:
664            print("Failed tests:")
665            print('\n'.join(self.failed))
666
667        if self.missing:
668            print("Missing tests (outdated package?):")
669            print('\n'.join(self.missing))
670
671class TlsServer:
672    """ Spawns an s_server listening on localhost:port if necessary. """
673
674    def __init__(self, port=4433):
675        self.spawn = True
676        # Check whether a server is already listening on localhost:port
677        self.spawn = subprocess.run(
678            ["nc", "-c", "-z", "-T", "noverify", "localhost", str(port)],
679            stderr=subprocess.DEVNULL,
680        ).returncode != 0
681
682        if self.spawn:
683            self.server = subprocess.Popen(
684                [
685                    "openssl",
686                    "s_server",
687                    "-accept",
688                    str(port),
689                    "-groups",
690                    "X25519:P-256:P-521:P-384",
691                    "-key",
692                    "localhost.key",
693                    "-cert",
694                    "localhost.crt",
695                    "-www",
696                ],
697                stdout=subprocess.DEVNULL,
698                stderr=subprocess.PIPE,
699                text=True,
700            )
701
702        # Check whether the server talks TLSv1.3
703        self.has_tls1_3 = True or subprocess.run(
704            [
705                "nc",
706                "-c",
707                "-z",
708                "-T",
709                "noverify",
710                "-T",
711                "protocols=TLSv1.3",
712                "localhost",
713                str(port),
714            ],
715            stderr=subprocess.DEVNULL,
716        ).returncode == 0
717
718        self.check()
719
720    def check(self):
721        if self.spawn and self.server.poll() is not None:
722            print(self.server.stderr.read())
723            raise RuntimeError(
724                f"openssl s_server died. Return code: {self.server.returncode}."
725            )
726        if self.spawn:
727            self.server.stderr.detach()
728
729    def __del__(self):
730        if self.spawn:
731            self.server.terminate()
732
733# Extract the arguments we pass to script
734def defaultargs(script, has_tls1_3):
735    return next(
736        (test for group in all_groups for test in group if test.name == script),
737        Test()
738    ).args(has_tls1_3)
739
740def list_or_missing(missing=True):
741    tests = [test.name for group in all_groups for test in group]
742
743    if missing:
744        scripts = {
745            f for f in os.listdir(tlsfuzzer_scriptdir) if f != "__pycache__"
746        }
747        missing = scripts - set(tests)
748        if missing:
749            print('\n'.join(sorted(missing)))
750        exit(0)
751
752    tests.sort()
753    print('\n'.join(tests))
754    exit(0)
755
756def usage():
757    print("Usage: python3 tlsfuzzer.py [-lmnstv] [-p port] [script [test...]]")
758    print(" --help      help")
759    print(" -f          run failing tests")
760    print(" -l          list tests")
761    print(" -m          list new tests after package update")
762    print(" -n          do not run tests, but list the ones that would be run")
763    print(" -p port     connect to this port - defaults to 4433")
764    print(" -s          run slow tests")
765    print(" -t          show timing stats at end")
766    print(" -v          verbose output")
767    exit(0)
768
769def main():
770    failing = False
771    list = False
772    missing = False
773    dryrun = False
774    port = 4433
775    slow = False
776    timing = False
777    verbose = False
778
779    argv = sys.argv[1:]
780    opts, args = getopt.getopt(argv, "flmnp:stv", ["help"])
781    for opt, arg in opts:
782        if opt == '--help':
783            usage()
784        elif opt == '-f':
785            failing = True
786        elif opt == '-l':
787            list = True
788        elif opt == '-m':
789            missing = True
790        elif opt == '-n':
791            dryrun = True
792        elif opt == '-p':
793            port = int(arg)
794        elif opt == '-s':
795            slow = True
796        elif opt == '-t':
797            timing = True
798        elif opt == '-v':
799            verbose = True
800        else:
801            raise ValueError(f"Unknown option: {opt}")
802
803    if not os.path.exists(tlsfuzzer_scriptdir):
804        print("package py3-tlsfuzzer is required for this regress")
805        exit(1)
806
807    if list and failing:
808        failing = [test.name for group in failing_groups for test in group]
809        failing.sort()
810        print('\n'.join(failing))
811        exit(0)
812
813    if list or missing:
814        list_or_missing(missing)
815
816    tls_server = TlsServer(port)
817
818    tests = TestRunner(timing, verbose, port, tls_server.has_tls1_3, dryrun)
819
820    if args:
821        (dir, script) = os.path.split(args[0])
822        if dir and not dir == '.':
823            tests.scriptdir = dir
824
825        testargs = defaultargs(script, tls_server.has_tls1_3)
826
827        tests.verbose = True
828        tests.add("test from command line", [Test(script, testargs + args[1:])])
829
830        exit(not tests.run())
831
832    if failing:
833        if tls_server.has_tls1_3:
834            tests.add_group(tls13_failing_tests)
835            if slow:
836                tests.add_group(tls13_slow_failing_tests)
837        tests.add_group(tls12_failing_tests)
838
839    if tls_server.has_tls1_3:
840        tests.add_group(tls13_tests)
841        if slow:
842            tests.add_group(tls13_slow_tests)
843    else:
844        tests.add_group(legacy_tests)
845
846    tests.add_group(tls12_tests)
847    if slow:
848        tests.add_group(tls12_slow_tests)
849
850    success = tests.run()
851    del tests
852
853    if not success:
854        print("FAILED")
855        exit(1)
856
857if __name__ == "__main__":
858    main()
859