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