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