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