Copyright year updates
[openssl.git] / test / quicapitest.c
1 /*
2  * Copyright 2022-2024 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <stdio.h>
11 #include <string.h>
12
13 #include <openssl/opensslconf.h>
14 #include <openssl/quic.h>
15 #include <openssl/rand.h>
16
17 #include "helpers/ssltestlib.h"
18 #include "helpers/quictestlib.h"
19 #include "testutil.h"
20 #include "testutil/output.h"
21 #include "../ssl/ssl_local.h"
22 #include "internal/quic_error.h"
23
24 static OSSL_LIB_CTX *libctx = NULL;
25 static OSSL_PROVIDER *defctxnull = NULL;
26 static char *certsdir = NULL;
27 static char *cert = NULL;
28 static char *ccert = NULL;
29 static char *cauthca = NULL;
30 static char *privkey = NULL;
31 static char *cprivkey = NULL;
32 static char *datadir = NULL;
33
34 static int is_fips = 0;
35
36 /* The ssltrace test assumes some options are switched on/off */
37 #if !defined(OPENSSL_NO_SSL_TRACE) \
38     && defined(OPENSSL_NO_BROTLI) && defined(OPENSSL_NO_ZSTD) \
39     && !defined(OPENSSL_NO_ECX) && !defined(OPENSSL_NO_DH)
40 # define DO_SSL_TRACE_TEST
41 #endif
42
43 /*
44  * Test that we read what we've written.
45  * Test 0: Non-blocking
46  * Test 1: Blocking
47  * Test 2: Blocking, introduce socket error, test error handling.
48  */
49 static int test_quic_write_read(int idx)
50 {
51     SSL_CTX *cctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method());
52     SSL_CTX *sctx = NULL;
53     SSL *clientquic = NULL;
54     QUIC_TSERVER *qtserv = NULL;
55     int j, k, ret = 0;
56     unsigned char buf[20], scratch[64];
57     static char *msg = "A test message";
58     size_t msglen = strlen(msg);
59     size_t numbytes = 0;
60     int ssock = 0, csock = 0;
61     uint64_t sid = UINT64_MAX;
62     SSL_SESSION *sess = NULL;
63
64     if (idx >= 1 && !qtest_supports_blocking())
65         return TEST_skip("Blocking tests not supported in this build");
66
67     for (k = 0; k < 2; k++) {
68         if (!TEST_ptr(cctx)
69                 || !TEST_true(qtest_create_quic_objects(libctx, cctx, sctx,
70                                                         cert, privkey,
71                                                         idx >= 1
72                                                             ? QTEST_FLAG_BLOCK
73                                                             : 0,
74                                                         &qtserv, &clientquic,
75                                                         NULL, NULL))
76                 || !TEST_true(SSL_set_tlsext_host_name(clientquic, "localhost")))
77             goto end;
78
79         if (sess != NULL && !TEST_true(SSL_set_session(clientquic, sess)))
80             goto end;
81
82         if (!TEST_true(qtest_create_quic_connection(qtserv, clientquic)))
83             goto end;
84
85         if (idx >= 1) {
86             if (!TEST_true(BIO_get_fd(ossl_quic_tserver_get0_rbio(qtserv),
87                                       &ssock)))
88                 goto end;
89             if (!TEST_int_gt(csock = SSL_get_rfd(clientquic), 0))
90                 goto end;
91         }
92
93         sid = 0; /* client-initiated bidirectional stream */
94
95         for (j = 0; j < 2; j++) {
96             /* Check that sending and receiving app data is ok */
97             if (!TEST_true(SSL_write_ex(clientquic, msg, msglen, &numbytes))
98                 || !TEST_size_t_eq(numbytes, msglen))
99                 goto end;
100             if (idx >= 1) {
101                 do {
102                     if (!TEST_true(wait_until_sock_readable(ssock)))
103                         goto end;
104
105                     ossl_quic_tserver_tick(qtserv);
106
107                     if (!TEST_true(ossl_quic_tserver_read(qtserv, sid, buf,
108                                                           sizeof(buf),
109                                                           &numbytes)))
110                         goto end;
111                 } while (numbytes == 0);
112
113                 if (!TEST_mem_eq(buf, numbytes, msg, msglen))
114                     goto end;
115             }
116
117             if (idx >= 2 && j > 0)
118                 /* Introduce permanent socket error */
119                 BIO_closesocket(csock);
120
121             ossl_quic_tserver_tick(qtserv);
122             if (!TEST_true(ossl_quic_tserver_write(qtserv, sid,
123                                                    (unsigned char *)msg,
124                                                    msglen, &numbytes)))
125                 goto end;
126             ossl_quic_tserver_tick(qtserv);
127             SSL_handle_events(clientquic);
128
129             if (idx >= 2 && j > 0) {
130                 if (!TEST_false(SSL_read_ex(clientquic, buf, 1, &numbytes))
131                         || !TEST_int_eq(SSL_get_error(clientquic, 0),
132                                         SSL_ERROR_SYSCALL)
133                         || !TEST_false(SSL_write_ex(clientquic, msg, msglen,
134                                                     &numbytes))
135                         || !TEST_int_eq(SSL_get_error(clientquic, 0),
136                                         SSL_ERROR_SYSCALL))
137                     goto end;
138                 break;
139             }
140
141             /*
142             * In blocking mode the SSL_read_ex call will block until the socket
143             * is readable and has our data. In non-blocking mode we're doing
144             * everything in memory, so it should be immediately available
145             */
146             if (!TEST_true(SSL_read_ex(clientquic, buf, 1, &numbytes))
147                     || !TEST_size_t_eq(numbytes, 1)
148                     || !TEST_true(SSL_has_pending(clientquic))
149                     || !TEST_int_eq(SSL_pending(clientquic), msglen - 1)
150                     || !TEST_true(SSL_read_ex(clientquic, buf + 1,
151                                               sizeof(buf) - 1, &numbytes))
152                     || !TEST_mem_eq(buf, numbytes + 1, msg, msglen))
153                 goto end;
154         }
155
156         /* Test that exporters work. */
157         if (!TEST_true(SSL_export_keying_material(clientquic, scratch,
158                         sizeof(scratch), "test", 4, (unsigned char *)"ctx", 3,
159                         1)))
160             goto end;
161
162         if (sess == NULL) {
163             /* We didn't supply a session so we're not expecting resumption */
164             if (!TEST_false(SSL_session_reused(clientquic)))
165                 goto end;
166             /* We should have a session ticket by now */
167             sess = SSL_get1_session(clientquic);
168             if (!TEST_ptr(sess))
169                 goto end;
170         } else {
171             /* We supplied a session so we should have resumed */
172             if (!TEST_true(SSL_session_reused(clientquic)))
173                 goto end;
174         }
175
176         if (!TEST_true(qtest_shutdown(qtserv, clientquic)))
177             goto end;
178
179         if (sctx == NULL) {
180             sctx = ossl_quic_tserver_get0_ssl_ctx(qtserv);
181             if (!TEST_true(SSL_CTX_up_ref(sctx))) {
182                 sctx = NULL;
183                 goto end;
184             }
185         }
186         ossl_quic_tserver_free(qtserv);
187         qtserv = NULL;
188         SSL_free(clientquic);
189         clientquic = NULL;
190
191         if (idx >= 2)
192             break;
193     }
194
195     ret = 1;
196
197  end:
198     SSL_SESSION_free(sess);
199     ossl_quic_tserver_free(qtserv);
200     SSL_free(clientquic);
201     SSL_CTX_free(cctx);
202     SSL_CTX_free(sctx);
203
204     return ret;
205 }
206
207 /*
208  * Test that sending FIN with no data to a client blocking in SSL_read_ex() will
209  * wake up the client.
210  */
211 static int test_fin_only_blocking(void)
212 {
213     SSL_CTX *cctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method());
214     SSL_CTX *sctx = NULL;
215     SSL *clientquic = NULL;
216     QUIC_TSERVER *qtserv = NULL;
217     const char *msg = "Hello World";
218     uint64_t sid;
219     size_t numbytes;
220     unsigned char buf[32];
221     int ret = 0;
222     OSSL_TIME timer, timediff;
223
224     if (!qtest_supports_blocking())
225         return TEST_skip("Blocking tests not supported in this build");
226
227     if (!TEST_ptr(cctx)
228             || !TEST_true(qtest_create_quic_objects(libctx, cctx, sctx,
229                                                     cert, privkey,
230                                                     QTEST_FLAG_BLOCK,
231                                                     &qtserv, &clientquic,
232                                                     NULL, NULL))
233             || !TEST_true(SSL_set_tlsext_host_name(clientquic, "localhost")))
234         goto end;
235
236     if (!TEST_true(qtest_create_quic_connection(qtserv, clientquic)))
237         goto end;
238
239     if (!TEST_true(ossl_quic_tserver_stream_new(qtserv, 0, &sid))
240             || !TEST_true(ossl_quic_tserver_write(qtserv, sid,
241                                                   (unsigned char *)msg,
242                                                   strlen(msg), &numbytes))
243             || !TEST_size_t_eq(strlen(msg), numbytes))
244         goto end;
245
246     ossl_quic_tserver_tick(qtserv);
247
248     if (!TEST_true(SSL_read_ex(clientquic, buf, sizeof(buf), &numbytes))
249             || !TEST_mem_eq(msg, strlen(msg), buf, numbytes))
250
251
252         goto end;
253
254     if (!TEST_true(ossl_quic_tserver_conclude(qtserv, sid)))
255         goto end;
256
257     timer = ossl_time_now();
258     if (!TEST_false(SSL_read_ex(clientquic, buf, sizeof(buf), &numbytes)))
259         goto end;
260     timediff = ossl_time_subtract(ossl_time_now(), timer);
261
262     if (!TEST_int_eq(SSL_get_error(clientquic, 0), SSL_ERROR_ZERO_RETURN)
263                /*
264                 * We expect the SSL_read_ex to not have blocked so this should
265                 * be very fast. 20ms should be plenty.
266                 */
267             || !TEST_uint64_t_le(ossl_time2ms(timediff), 20))
268         goto end;
269
270     if (!TEST_true(qtest_shutdown(qtserv, clientquic)))
271         goto end;
272
273     ret = 1;
274
275  end:
276     ossl_quic_tserver_free(qtserv);
277     SSL_free(clientquic);
278     SSL_CTX_free(cctx);
279     SSL_CTX_free(sctx);
280
281     return ret;
282 }
283
284 /* Test that a vanilla QUIC SSL object has the expected ciphersuites available */
285 static int test_ciphersuites(void)
286 {
287     SSL_CTX *ctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method());
288     SSL *ssl;
289     int testresult = 0;
290     const STACK_OF(SSL_CIPHER) *ciphers = NULL;
291     const SSL_CIPHER *cipher;
292     /* We expect this exact list of ciphersuites by default */
293     int cipherids[] = {
294         TLS1_3_CK_AES_256_GCM_SHA384,
295 #if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
296         TLS1_3_CK_CHACHA20_POLY1305_SHA256,
297 #endif
298         TLS1_3_CK_AES_128_GCM_SHA256
299     };
300     size_t i, j;
301
302     if (!TEST_ptr(ctx))
303         return 0;
304
305     ssl = SSL_new(ctx);
306     if (!TEST_ptr(ssl))
307         goto err;
308
309     ciphers = SSL_get_ciphers(ssl);
310
311     for (i = 0, j = 0; i < OSSL_NELEM(cipherids); i++) {
312         if (cipherids[i] == TLS1_3_CK_CHACHA20_POLY1305_SHA256 && is_fips)
313             continue;
314         cipher = sk_SSL_CIPHER_value(ciphers, j++);
315         if (!TEST_ptr(cipher))
316             goto err;
317         if (!TEST_uint_eq(SSL_CIPHER_get_id(cipher), cipherids[i]))
318             goto err;
319     }
320
321     /* We should have checked all the ciphers in the stack */
322     if (!TEST_int_eq(sk_SSL_CIPHER_num(ciphers), j))
323         goto err;
324
325     testresult = 1;
326  err:
327     SSL_free(ssl);
328     SSL_CTX_free(ctx);
329
330     return testresult;
331 }
332
333 static int test_cipher_find(void)
334 {
335     SSL_CTX *cctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method());
336     SSL *clientquic = NULL;
337     struct {
338         const unsigned char *cipherbytes;
339         int ok;
340     } testciphers[]  = {
341         { TLS13_AES_128_GCM_SHA256_BYTES, 1 },
342         { TLS13_AES_256_GCM_SHA384_BYTES, 1 },
343         { TLS13_CHACHA20_POLY1305_SHA256_BYTES, 1 },
344         { TLS13_AES_128_CCM_SHA256_BYTES, 0 },
345         { TLS13_AES_128_CCM_8_SHA256_BYTES, 0 }
346     };
347     size_t i;
348     int testresult = 0;
349
350     if (!TEST_ptr(cctx))
351         goto err;
352
353     clientquic = SSL_new(cctx);
354     if (!TEST_ptr(clientquic))
355         goto err;
356
357     for (i = 0; i < OSSL_NELEM(testciphers); i++)
358         if (testciphers[i].ok) {
359             if (!TEST_ptr(SSL_CIPHER_find(clientquic,
360                                           testciphers[i].cipherbytes)))
361                 goto err;
362         } else {
363             if (!TEST_ptr_null(SSL_CIPHER_find(clientquic,
364                                                testciphers[i].cipherbytes)))
365                 goto err;
366         }
367
368     testresult = 1;
369  err:
370     SSL_free(clientquic);
371     SSL_CTX_free(cctx);
372
373     return testresult;
374 }
375
376 /*
377  * Test that SSL_version, SSL_get_version, SSL_is_quic, SSL_is_tls and
378  * SSL_is_dtls return the expected results for a QUIC connection. Compare with
379  * test_version() in sslapitest.c which does the same thing for TLS/DTLS
380  * connections.
381  */
382 static int test_version(void)
383 {
384     SSL_CTX *cctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method());
385     SSL *clientquic = NULL;
386     QUIC_TSERVER *qtserv = NULL;
387     int testresult = 0;
388
389     if (!TEST_ptr(cctx)
390             || !TEST_true(qtest_create_quic_objects(libctx, cctx, NULL, cert,
391                                                     privkey, 0, &qtserv,
392                                                     &clientquic, NULL, NULL))
393             || !TEST_true(qtest_create_quic_connection(qtserv, clientquic)))
394         goto err;
395
396     if (!TEST_int_eq(SSL_version(clientquic), OSSL_QUIC1_VERSION)
397             || !TEST_str_eq(SSL_get_version(clientquic), "QUICv1"))
398         goto err;
399
400     if (!TEST_true(SSL_is_quic(clientquic))
401             || !TEST_false(SSL_is_tls(clientquic))
402             || !TEST_false(SSL_is_dtls(clientquic)))
403         goto err;
404
405
406     testresult = 1;
407  err:
408     ossl_quic_tserver_free(qtserv);
409     SSL_free(clientquic);
410     SSL_CTX_free(cctx);
411
412     return testresult;
413 }
414
415 #if defined(DO_SSL_TRACE_TEST)
416 static void strip_line_ends(char *str)
417 {
418     size_t i;
419
420     for (i = strlen(str);
421          i > 0 && (str[i - 1] == '\n' || str[i - 1] == '\r');
422          i--);
423
424     str[i] = '\0';
425 }
426
427 static int compare_with_file(BIO *membio)
428 {
429     BIO *file = NULL, *newfile = NULL;
430     char buf1[512], buf2[512];
431     char *reffile;
432     int ret = 0;
433     size_t i;
434
435 #ifdef OPENSSL_NO_ZLIB
436     reffile = test_mk_file_path(datadir, "ssltraceref.txt");
437 #else
438     reffile = test_mk_file_path(datadir, "ssltraceref-zlib.txt");
439 #endif
440     if (!TEST_ptr(reffile))
441         goto err;
442
443     file = BIO_new_file(reffile, "rb");
444     if (!TEST_ptr(file))
445         goto err;
446
447     newfile = BIO_new_file("ssltraceref-new.txt", "wb");
448     if (!TEST_ptr(newfile))
449         goto err;
450
451     while (BIO_gets(membio, buf2, sizeof(buf2)) > 0)
452         if (BIO_puts(newfile, buf2) <= 0) {
453             TEST_error("Failed writing new file data");
454             goto err;
455         }
456
457     if (!TEST_int_ge(BIO_seek(membio, 0), 0))
458         goto err;
459
460     while (BIO_gets(file, buf1, sizeof(buf1)) > 0) {
461         if (BIO_gets(membio, buf2, sizeof(buf2)) <= 0) {
462             TEST_error("Failed reading mem data");
463             goto err;
464         }
465         strip_line_ends(buf1);
466         strip_line_ends(buf2);
467         if (strlen(buf1) != strlen(buf2)) {
468             TEST_error("Actual and ref line data length mismatch");
469             TEST_info("%s", buf1);
470             TEST_info("%s", buf2);
471            goto err;
472         }
473         for (i = 0; i < strlen(buf1); i++) {
474             /* '?' is a wild card character in the reference text */
475             if (buf1[i] == '?')
476                 buf2[i] = '?';
477         }
478         if (!TEST_str_eq(buf1, buf2))
479             goto err;
480     }
481     if (!TEST_true(BIO_eof(file))
482             || !TEST_true(BIO_eof(membio)))
483         goto err;
484
485     ret = 1;
486  err:
487     OPENSSL_free(reffile);
488     BIO_free(file);
489     BIO_free(newfile);
490     return ret;
491 }
492
493 /*
494  * Tests that the SSL_trace() msg_callback works as expected with a QUIC
495  * connection. This also provides testing of the msg_callback at the same time.
496  */
497 static int test_ssl_trace(void)
498 {
499     SSL_CTX *cctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method());
500     SSL *clientquic = NULL;
501     QUIC_TSERVER *qtserv = NULL;
502     int testresult = 0;
503     BIO *bio = BIO_new(BIO_s_mem());
504
505     /*
506      * Ensure we only configure ciphersuites that are available with both the
507      * default and fips providers to get the same output in both cases
508      */
509     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_128_GCM_SHA256")))
510         goto err;
511
512     if (!TEST_ptr(cctx)
513             || !TEST_ptr(bio)
514             || !TEST_true(qtest_create_quic_objects(libctx, cctx, NULL, cert,
515                                                     privkey,
516                                                     QTEST_FLAG_FAKE_TIME,
517                                                     &qtserv,
518                                                     &clientquic, NULL, NULL)))
519         goto err;
520
521     SSL_set_msg_callback(clientquic, SSL_trace);
522     SSL_set_msg_callback_arg(clientquic, bio);
523
524     if (!TEST_true(qtest_create_quic_connection(qtserv, clientquic)))
525         goto err;
526
527     if (!TEST_true(compare_with_file(bio)))
528         goto err;
529
530     testresult = 1;
531  err:
532     ossl_quic_tserver_free(qtserv);
533     SSL_free(clientquic);
534     SSL_CTX_free(cctx);
535     BIO_free(bio);
536
537     return testresult;
538 }
539 #endif
540
541 static int ensure_valid_ciphers(const STACK_OF(SSL_CIPHER) *ciphers)
542 {
543     size_t i;
544
545     /* Ensure ciphersuite list is suitably subsetted. */
546     for (i = 0; i < (size_t)sk_SSL_CIPHER_num(ciphers); ++i) {
547         const SSL_CIPHER *cipher = sk_SSL_CIPHER_value(ciphers, i);
548         switch (SSL_CIPHER_get_id(cipher)) {
549             case TLS1_3_CK_AES_128_GCM_SHA256:
550             case TLS1_3_CK_AES_256_GCM_SHA384:
551             case TLS1_3_CK_CHACHA20_POLY1305_SHA256:
552                 break;
553             default:
554                 TEST_error("forbidden cipher: %s", SSL_CIPHER_get_name(cipher));
555                 return 0;
556         }
557     }
558
559     return 1;
560 }
561
562 /*
563  * Test that handshake-layer APIs which shouldn't work don't work with QUIC.
564  */
565 static int test_quic_forbidden_apis_ctx(void)
566 {
567     int testresult = 0;
568     SSL_CTX *ctx = NULL;
569
570     if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method())))
571         goto err;
572
573 #ifndef OPENSSL_NO_SRTP
574     /* This function returns 0 on success and 1 on error, and should fail. */
575     if (!TEST_true(SSL_CTX_set_tlsext_use_srtp(ctx, "SRTP_AEAD_AES_128_GCM")))
576         goto err;
577 #endif
578
579     /*
580      * List of ciphersuites we do and don't allow in QUIC.
581      */
582 #define QUIC_CIPHERSUITES \
583     "TLS_AES_128_GCM_SHA256:"           \
584     "TLS_AES_256_GCM_SHA384:"           \
585     "TLS_CHACHA20_POLY1305_SHA256"
586
587 #define NON_QUIC_CIPHERSUITES           \
588     "TLS_AES_128_CCM_SHA256:"           \
589     "TLS_AES_256_CCM_SHA384:"           \
590     "TLS_AES_128_CCM_8_SHA256"
591
592     /* Set TLSv1.3 ciphersuite list for the SSL_CTX. */
593     if (!TEST_true(SSL_CTX_set_ciphersuites(ctx,
594                                             QUIC_CIPHERSUITES ":"
595                                             NON_QUIC_CIPHERSUITES)))
596         goto err;
597
598     /*
599      * Forbidden ciphersuites should show up in SSL_CTX accessors, they are only
600      * filtered in SSL_get1_supported_ciphers, so we don't check for
601      * non-inclusion here.
602      */
603
604     testresult = 1;
605 err:
606     SSL_CTX_free(ctx);
607     return testresult;
608 }
609
610 static int test_quic_forbidden_apis(void)
611 {
612     int testresult = 0;
613     SSL_CTX *ctx = NULL;
614     SSL *ssl = NULL;
615     STACK_OF(SSL_CIPHER) *ciphers = NULL;
616
617     if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method())))
618         goto err;
619
620     if (!TEST_ptr(ssl = SSL_new(ctx)))
621         goto err;
622
623 #ifndef OPENSSL_NO_SRTP
624     /* This function returns 0 on success and 1 on error, and should fail. */
625     if (!TEST_true(SSL_set_tlsext_use_srtp(ssl, "SRTP_AEAD_AES_128_GCM")))
626         goto err;
627 #endif
628
629     /* Set TLSv1.3 ciphersuite list for the SSL_CTX. */
630     if (!TEST_true(SSL_set_ciphersuites(ssl,
631                                         QUIC_CIPHERSUITES ":"
632                                         NON_QUIC_CIPHERSUITES)))
633         goto err;
634
635     /* Non-QUIC ciphersuites must not appear in supported ciphers list. */
636     if (!TEST_ptr(ciphers = SSL_get1_supported_ciphers(ssl))
637         || !TEST_true(ensure_valid_ciphers(ciphers)))
638         goto err;
639
640     testresult = 1;
641 err:
642     sk_SSL_CIPHER_free(ciphers);
643     SSL_free(ssl);
644     SSL_CTX_free(ctx);
645     return testresult;
646 }
647
648 static int test_quic_forbidden_options(void)
649 {
650     int testresult = 0;
651     SSL_CTX *ctx = NULL;
652     SSL *ssl = NULL;
653     char buf[16];
654     size_t len;
655
656     if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method())))
657         goto err;
658
659     /* QUIC options restrictions do not affect SSL_CTX */
660     SSL_CTX_set_options(ctx, UINT64_MAX);
661
662     if (!TEST_uint64_t_eq(SSL_CTX_get_options(ctx), UINT64_MAX))
663         goto err;
664
665     /* Set options on CTX which should not be inherited (tested below). */
666     SSL_CTX_set_read_ahead(ctx, 1);
667     SSL_CTX_set_max_early_data(ctx, 1);
668     SSL_CTX_set_recv_max_early_data(ctx, 1);
669     SSL_CTX_set_quiet_shutdown(ctx, 1);
670
671     if (!TEST_ptr(ssl = SSL_new(ctx)))
672         goto err;
673
674     /* Only permitted options get transferred to SSL object */
675     if (!TEST_uint64_t_eq(SSL_get_options(ssl), OSSL_QUIC_PERMITTED_OPTIONS))
676         goto err;
677
678     /* Try again using SSL_set_options */
679     SSL_set_options(ssl, UINT64_MAX);
680
681     if (!TEST_uint64_t_eq(SSL_get_options(ssl), OSSL_QUIC_PERMITTED_OPTIONS))
682         goto err;
683
684     /* Clear everything */
685     SSL_clear_options(ssl, UINT64_MAX);
686
687     if (!TEST_uint64_t_eq(SSL_get_options(ssl), 0))
688         goto err;
689
690     /* Readahead */
691     if (!TEST_false(SSL_get_read_ahead(ssl)))
692         goto err;
693
694     SSL_set_read_ahead(ssl, 1);
695     if (!TEST_false(SSL_get_read_ahead(ssl)))
696         goto err;
697
698     /* Block padding */
699     if (!TEST_true(SSL_set_block_padding(ssl, 0))
700         || !TEST_true(SSL_set_block_padding(ssl, 1))
701         || !TEST_false(SSL_set_block_padding(ssl, 2)))
702         goto err;
703
704     /* Max fragment length */
705     if (!TEST_true(SSL_set_tlsext_max_fragment_length(ssl, TLSEXT_max_fragment_length_DISABLED))
706         || !TEST_false(SSL_set_tlsext_max_fragment_length(ssl, TLSEXT_max_fragment_length_512)))
707         goto err;
708
709     /* Max early data */
710     if (!TEST_false(SSL_set_recv_max_early_data(ssl, 1))
711         || !TEST_false(SSL_set_max_early_data(ssl, 1)))
712         goto err;
713
714     /* Read/Write */
715     if (!TEST_false(SSL_read_early_data(ssl, buf, sizeof(buf), &len))
716         || !TEST_false(SSL_write_early_data(ssl, buf, sizeof(buf), &len)))
717         goto err;
718
719     /* Buffer Management */
720     if (!TEST_true(SSL_alloc_buffers(ssl))
721         || !TEST_false(SSL_free_buffers(ssl)))
722         goto err;
723
724     /* Pipelining */
725     if (!TEST_false(SSL_set_max_send_fragment(ssl, 2))
726         || !TEST_false(SSL_set_split_send_fragment(ssl, 2))
727         || !TEST_false(SSL_set_max_pipelines(ssl, 2)))
728         goto err;
729
730     /* HRR */
731     if  (!TEST_false(SSL_stateless(ssl)))
732         goto err;
733
734     /* Quiet Shutdown */
735     if (!TEST_false(SSL_get_quiet_shutdown(ssl)))
736         goto err;
737
738     /* No duplication */
739     if (!TEST_ptr_null(SSL_dup(ssl)))
740         goto err;
741
742     /* No clear */
743     if (!TEST_false(SSL_clear(ssl)))
744         goto err;
745
746     testresult = 1;
747 err:
748     SSL_free(ssl);
749     SSL_CTX_free(ctx);
750     return testresult;
751 }
752
753 static int test_quic_set_fd(int idx)
754 {
755     int testresult = 0;
756     SSL_CTX *ctx = NULL;
757     SSL *ssl = NULL;
758     int fd = -1, resfd = -1;
759     BIO *bio = NULL;
760
761     if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method())))
762         goto err;
763
764     if (!TEST_ptr(ssl = SSL_new(ctx)))
765         goto err;
766
767     if (!TEST_int_ge(fd = BIO_socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP, 0), 0))
768         goto err;
769
770     if (idx == 0) {
771         if (!TEST_true(SSL_set_fd(ssl, fd)))
772             goto err;
773         if (!TEST_ptr(bio = SSL_get_rbio(ssl)))
774             goto err;
775         if (!TEST_ptr_eq(bio, SSL_get_wbio(ssl)))
776             goto err;
777     } else if (idx == 1) {
778         if (!TEST_true(SSL_set_rfd(ssl, fd)))
779             goto err;
780         if (!TEST_ptr(bio = SSL_get_rbio(ssl)))
781             goto err;
782         if (!TEST_ptr_null(SSL_get_wbio(ssl)))
783             goto err;
784     } else {
785         if (!TEST_true(SSL_set_wfd(ssl, fd)))
786             goto err;
787         if (!TEST_ptr(bio = SSL_get_wbio(ssl)))
788             goto err;
789         if (!TEST_ptr_null(SSL_get_rbio(ssl)))
790             goto err;
791     }
792
793     if (!TEST_int_eq(BIO_method_type(bio), BIO_TYPE_DGRAM))
794         goto err;
795
796     if (!TEST_true(BIO_get_fd(bio, &resfd))
797         || !TEST_int_eq(resfd, fd))
798         goto err;
799
800     testresult = 1;
801 err:
802     SSL_free(ssl);
803     SSL_CTX_free(ctx);
804     if (fd >= 0)
805         BIO_closesocket(fd);
806     return testresult;
807 }
808
809 #define MAXLOOPS    1000
810
811 static int test_bio_ssl(void)
812 {
813     /*
814      * We just use OSSL_QUIC_client_method() rather than
815      * OSSL_QUIC_client_thread_method(). We will never leave the connection idle
816      * so we will always be implicitly handling time events anyway via other
817      * IO calls.
818      */
819     SSL_CTX *cctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method());
820     SSL *clientquic = NULL, *stream = NULL;
821     QUIC_TSERVER *qtserv = NULL;
822     int testresult = 0;
823     BIO *cbio = NULL, *strbio = NULL, *thisbio;
824     const char *msg = "Hello world";
825     int abortctr = 0, err, clienterr = 0, servererr = 0, retc = 0, rets = 0;
826     size_t written, readbytes, msglen;
827     int sid = 0, i;
828     unsigned char buf[80];
829
830     if (!TEST_ptr(cctx))
831         goto err;
832
833     cbio = BIO_new_ssl(cctx, 1);
834     if (!TEST_ptr(cbio))
835         goto err;
836
837     /*
838      * We must configure the ALPN/peer address etc so we get the SSL object in
839      * order to pass it to qtest_create_quic_objects for configuration.
840      */
841     if (!TEST_int_eq(BIO_get_ssl(cbio, &clientquic), 1))
842         goto err;
843
844     if (!TEST_true(qtest_create_quic_objects(libctx, NULL, NULL, cert, privkey,
845                                              0, &qtserv, &clientquic, NULL,
846                                              NULL)))
847         goto err;
848
849     msglen = strlen(msg);
850
851     do {
852         err = BIO_FLAGS_WRITE;
853         while (!clienterr && !retc && err == BIO_FLAGS_WRITE) {
854             retc = BIO_write_ex(cbio, msg, msglen, &written);
855             if (!retc) {
856                 if (BIO_should_retry(cbio))
857                     err = BIO_retry_type(cbio);
858                 else
859                     err = 0;
860             }
861         }
862
863         if (!clienterr && retc <= 0 && err != BIO_FLAGS_READ) {
864             TEST_info("BIO_write_ex() failed %d, %d", retc, err);
865             TEST_openssl_errors();
866             clienterr = 1;
867         }
868
869         if (!servererr && rets <= 0) {
870             ossl_quic_tserver_tick(qtserv);
871             servererr = ossl_quic_tserver_is_term_any(qtserv);
872             if (!servererr)
873                 rets = ossl_quic_tserver_is_handshake_confirmed(qtserv);
874         }
875
876         if (clienterr && servererr)
877             goto err;
878
879         if (++abortctr == MAXLOOPS) {
880             TEST_info("No progress made");
881             goto err;
882         }
883     } while ((!retc && !clienterr) || (rets <= 0 && !servererr));
884
885     /*
886      * 2 loops: The first using the default stream, and the second using a new
887      * client initiated bidi stream.
888      */
889     for (i = 0, thisbio = cbio; i < 2; i++) {
890         if (!TEST_true(ossl_quic_tserver_read(qtserv, sid, buf, sizeof(buf),
891                                               &readbytes))
892                 || !TEST_mem_eq(msg, msglen, buf, readbytes))
893             goto err;
894
895         if (!TEST_true(ossl_quic_tserver_write(qtserv, sid, (unsigned char *)msg,
896                                                msglen, &written)))
897             goto err;
898         ossl_quic_tserver_tick(qtserv);
899
900         if (!TEST_true(BIO_read_ex(thisbio, buf, sizeof(buf), &readbytes))
901                 || !TEST_mem_eq(msg, msglen, buf, readbytes))
902             goto err;
903
904         if (i == 1)
905             break;
906
907         if (!TEST_true(SSL_set_mode(clientquic, 0)))
908             goto err;
909
910         /*
911          * Now create a new stream and repeat. The bottom two bits of the stream
912          * id represents whether the stream is bidi and whether it is client
913          * initiated or not. For client initiated bidi they are both 0. So the
914          * first client initiated bidi stream is 0 and the next one is 4.
915          */
916         sid = 4;
917         stream = SSL_new_stream(clientquic, 0);
918         if (!TEST_ptr(stream))
919             goto err;
920
921         if (!TEST_true(SSL_set_mode(stream, 0)))
922             goto err;
923
924         thisbio = strbio = BIO_new(BIO_f_ssl());
925         if (!TEST_ptr(strbio))
926             goto err;
927
928         if (!TEST_int_eq(BIO_set_ssl(thisbio, stream, BIO_CLOSE), 1))
929             goto err;
930         stream = NULL;
931
932         if (!TEST_true(BIO_write_ex(thisbio, msg, msglen, &written)))
933             goto err;
934
935         ossl_quic_tserver_tick(qtserv);
936     }
937
938     testresult = 1;
939  err:
940     BIO_free_all(cbio);
941     BIO_free_all(strbio);
942     SSL_free(stream);
943     ossl_quic_tserver_free(qtserv);
944     SSL_CTX_free(cctx);
945
946     return testresult;
947 }
948
949 #define BACK_PRESSURE_NUM_LOOPS 10000
950 /*
951  * Test that sending data from the client to the server faster than the server
952  * can process it eventually results in back pressure on the client.
953  */
954 static int test_back_pressure(void)
955 {
956     SSL_CTX *cctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method());
957     SSL *clientquic = NULL;
958     QUIC_TSERVER *qtserv = NULL;
959     int testresult = 0;
960     unsigned char *msg = NULL;
961     const size_t msglen = 1024;
962     unsigned char buf[64];
963     size_t readbytes, written;
964     int i;
965
966     if (!TEST_ptr(cctx)
967             || !TEST_true(qtest_create_quic_objects(libctx, cctx, NULL, cert,
968                                                     privkey, 0, &qtserv,
969                                                     &clientquic, NULL, NULL))
970             || !TEST_true(qtest_create_quic_connection(qtserv, clientquic)))
971         goto err;
972
973     msg = OPENSSL_malloc(msglen);
974     if (!TEST_ptr(msg))
975         goto err;
976     if (!TEST_int_eq(RAND_bytes_ex(libctx, msg, msglen, 0), 1))
977         goto err;
978
979     /*
980      * Limit to 10000 loops. If we've not seen any back pressure after that
981      * we're going to run out of memory, so abort.
982      */
983     for (i = 0; i < BACK_PRESSURE_NUM_LOOPS; i++) {
984         /* Send data from the client */
985         if (!SSL_write_ex(clientquic, msg, msglen, &written)) {
986             /* Check if we are seeing back pressure */
987             if (SSL_get_error(clientquic, 0) == SSL_ERROR_WANT_WRITE)
988                 break;
989             TEST_error("Unexpected client failure");
990             goto err;
991         }
992
993         /* Receive data at the server */
994         ossl_quic_tserver_tick(qtserv);
995         if (!TEST_true(ossl_quic_tserver_read(qtserv, 0, buf, sizeof(buf),
996                                               &readbytes)))
997             goto err;
998     }
999
1000     if (i == BACK_PRESSURE_NUM_LOOPS) {
1001         TEST_error("No back pressure seen");
1002         goto err;
1003     }
1004
1005     testresult = 1;
1006  err:
1007     SSL_free(clientquic);
1008     ossl_quic_tserver_free(qtserv);
1009     SSL_CTX_free(cctx);
1010     OPENSSL_free(msg);
1011
1012     return testresult;
1013 }
1014
1015
1016 static int dgram_ctr = 0;
1017
1018 static void dgram_cb(int write_p, int version, int content_type,
1019                      const void *buf, size_t msglen, SSL *ssl, void *arg)
1020 {
1021     if (!write_p)
1022         return;
1023
1024     if (content_type != SSL3_RT_QUIC_DATAGRAM)
1025         return;
1026
1027     dgram_ctr++;
1028 }
1029
1030 /* Test that we send multiple datagrams in one go when appropriate */
1031 static int test_multiple_dgrams(void)
1032 {
1033     SSL_CTX *cctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method());
1034     SSL *clientquic = NULL;
1035     QUIC_TSERVER *qtserv = NULL;
1036     int testresult = 0;
1037     unsigned char *buf;
1038     const size_t buflen = 1400;
1039     size_t written;
1040
1041     buf = OPENSSL_zalloc(buflen);
1042
1043     if (!TEST_ptr(cctx)
1044             || !TEST_ptr(buf)
1045             || !TEST_true(qtest_create_quic_objects(libctx, cctx, NULL, cert,
1046                                                     privkey, 0, &qtserv,
1047                                                     &clientquic, NULL, NULL))
1048             || !TEST_true(qtest_create_quic_connection(qtserv, clientquic)))
1049         goto err;
1050
1051     dgram_ctr = 0;
1052     SSL_set_msg_callback(clientquic, dgram_cb);
1053     if (!TEST_true(SSL_write_ex(clientquic, buf, buflen, &written))
1054             || !TEST_size_t_eq(written, buflen)
1055                /* We wrote enough data for 2 datagrams */
1056             || !TEST_int_eq(dgram_ctr, 2))
1057         goto err;
1058
1059     testresult = 1;
1060  err:
1061     OPENSSL_free(buf);
1062     SSL_free(clientquic);
1063     ossl_quic_tserver_free(qtserv);
1064     SSL_CTX_free(cctx);
1065
1066     return testresult;
1067 }
1068
1069 static int non_io_retry_cert_verify_cb(X509_STORE_CTX *ctx, void *arg)
1070 {
1071     int idx = SSL_get_ex_data_X509_STORE_CTX_idx();
1072     SSL *ssl;
1073     const int *allow = (int *)arg;
1074
1075     /* this should not happen but check anyway */
1076     if (idx < 0
1077         || (ssl = X509_STORE_CTX_get_ex_data(ctx, idx)) == NULL)
1078         return 0;
1079
1080     /* If this is our first attempt then retry */
1081     if (*allow == 0)
1082         return SSL_set_retry_verify(ssl);
1083
1084     /* Otherwise do nothing - verification succeeds. Continue as normal */
1085     return 1;
1086 }
1087
1088 /* Test that we can handle a non-io related retry error
1089  * Test 0: Non-blocking
1090  * Test 1: Blocking
1091  */
1092 static int test_non_io_retry(int idx)
1093 {
1094     SSL_CTX *cctx;
1095     SSL *clientquic = NULL;
1096     QUIC_TSERVER *qtserv = NULL;
1097     int testresult = 0;
1098     int flags = 0, allow = 0;
1099
1100     if (idx >= 1 && !qtest_supports_blocking())
1101         return TEST_skip("Blocking tests not supported in this build");
1102
1103     cctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method());
1104     if (!TEST_ptr(cctx))
1105         goto err;
1106
1107     SSL_CTX_set_cert_verify_callback(cctx, non_io_retry_cert_verify_cb, &allow);
1108
1109     flags = (idx >= 1) ? QTEST_FLAG_BLOCK : 0;
1110     if (!TEST_true(qtest_create_quic_objects(libctx, cctx, NULL, cert, privkey,
1111                                              flags, &qtserv, &clientquic, NULL,
1112                                              NULL))
1113             || !TEST_true(qtest_create_quic_connection_ex(qtserv, clientquic,
1114                             SSL_ERROR_WANT_RETRY_VERIFY))
1115             || !TEST_int_eq(SSL_want(clientquic), SSL_RETRY_VERIFY))
1116         goto err;
1117
1118     allow = 1;
1119     if (!TEST_true(qtest_create_quic_connection(qtserv, clientquic)))
1120         goto err;
1121
1122     testresult = 1;
1123  err:
1124     SSL_free(clientquic);
1125     ossl_quic_tserver_free(qtserv);
1126     SSL_CTX_free(cctx);
1127
1128     return testresult;
1129 }
1130
1131 static int use_session_cb_cnt = 0;
1132 static int find_session_cb_cnt = 0;
1133 static const char *pskid = "Identity";
1134 static SSL_SESSION *serverpsk = NULL, *clientpsk = NULL;
1135
1136 static int use_session_cb(SSL *ssl, const EVP_MD *md, const unsigned char **id,
1137                           size_t *idlen, SSL_SESSION **sess)
1138 {
1139     use_session_cb_cnt++;
1140
1141     if (clientpsk == NULL)
1142         return 0;
1143
1144     SSL_SESSION_up_ref(clientpsk);
1145
1146     *sess = clientpsk;
1147     *id = (const unsigned char *)pskid;
1148     *idlen = strlen(pskid);
1149
1150     return 1;
1151 }
1152
1153 static int find_session_cb(SSL *ssl, const unsigned char *identity,
1154                            size_t identity_len, SSL_SESSION **sess)
1155 {
1156     find_session_cb_cnt++;
1157
1158     if (serverpsk == NULL)
1159         return 0;
1160
1161     /* Identity should match that set by the client */
1162     if (strlen(pskid) != identity_len
1163             || strncmp(pskid, (const char *)identity, identity_len) != 0)
1164         return 0;
1165
1166     SSL_SESSION_up_ref(serverpsk);
1167     *sess = serverpsk;
1168
1169     return 1;
1170 }
1171
1172 static int test_quic_psk(void)
1173 {
1174     SSL_CTX *cctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method());
1175     SSL *clientquic = NULL;
1176     QUIC_TSERVER *qtserv = NULL;
1177     int testresult = 0;
1178
1179     if (!TEST_ptr(cctx)
1180                /* No cert or private key for the server, i.e. PSK only */
1181             || !TEST_true(qtest_create_quic_objects(libctx, cctx, NULL, NULL,
1182                                                     NULL, 0, &qtserv,
1183                                                     &clientquic, NULL, NULL)))
1184         goto end;
1185
1186     SSL_set_psk_use_session_callback(clientquic, use_session_cb);
1187     ossl_quic_tserver_set_psk_find_session_cb(qtserv, find_session_cb);
1188     use_session_cb_cnt = 0;
1189     find_session_cb_cnt = 0;
1190
1191     clientpsk = serverpsk = create_a_psk(clientquic, SHA384_DIGEST_LENGTH);
1192     if (!TEST_ptr(clientpsk))
1193         goto end;
1194     /* We already had one ref. Add another one */
1195     SSL_SESSION_up_ref(clientpsk);
1196
1197     if (!TEST_true(qtest_create_quic_connection(qtserv, clientquic))
1198             || !TEST_int_eq(1, find_session_cb_cnt)
1199             || !TEST_int_eq(1, use_session_cb_cnt)
1200                /* Check that we actually used the PSK */
1201             || !TEST_true(SSL_session_reused(clientquic)))
1202         goto end;
1203
1204     testresult = 1;
1205
1206  end:
1207     SSL_free(clientquic);
1208     ossl_quic_tserver_free(qtserv);
1209     SSL_CTX_free(cctx);
1210     SSL_SESSION_free(clientpsk);
1211     SSL_SESSION_free(serverpsk);
1212     clientpsk = serverpsk = NULL;
1213
1214     return testresult;
1215 }
1216
1217 static int test_client_auth(int idx)
1218 {
1219     SSL_CTX *cctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method());
1220     SSL_CTX *sctx = SSL_CTX_new_ex(libctx, NULL, TLS_method());
1221     SSL *clientquic = NULL;
1222     QUIC_TSERVER *qtserv = NULL;
1223     int testresult = 0;
1224     unsigned char buf[20];
1225     static char *msg = "A test message";
1226     size_t msglen = strlen(msg);
1227     size_t numbytes = 0;
1228
1229     if (!TEST_ptr(cctx) || !TEST_ptr(sctx))
1230         goto err;
1231
1232     SSL_CTX_set_verify(sctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT
1233                              | SSL_VERIFY_CLIENT_ONCE, NULL);
1234
1235     if (!TEST_true(SSL_CTX_load_verify_file(sctx, cauthca)))
1236         goto err;
1237
1238     if (idx > 0
1239         && (!TEST_true(SSL_CTX_use_certificate_chain_file(cctx, ccert))
1240             || !TEST_true(SSL_CTX_use_PrivateKey_file(cctx, cprivkey,
1241                                                       SSL_FILETYPE_PEM))))
1242             goto err;
1243
1244     if (!TEST_true(qtest_create_quic_objects(libctx, cctx, sctx, cert,
1245                                              privkey, 0, &qtserv,
1246                                              &clientquic, NULL, NULL)))
1247         goto err;
1248
1249     if (idx > 1) {
1250         if (!TEST_true(ssl_ctx_add_large_cert_chain(libctx, cctx, ccert))
1251             || !TEST_true(ssl_ctx_add_large_cert_chain(libctx, sctx, cert)))
1252             goto err;
1253     }
1254
1255     if (idx == 0) {
1256         if (!TEST_false(qtest_create_quic_connection(qtserv, clientquic)))
1257             goto err;
1258
1259         /* negative test passed */
1260         testresult = 1;
1261         goto err;
1262     }
1263
1264     if (!TEST_true(qtest_create_quic_connection(qtserv, clientquic)))
1265         goto err;
1266
1267     /* Check that sending and receiving app data is ok */
1268     if (!TEST_true(SSL_write_ex(clientquic, msg, msglen, &numbytes))
1269         || !TEST_size_t_eq(numbytes, msglen))
1270         goto err;
1271
1272     ossl_quic_tserver_tick(qtserv);
1273     if (!TEST_true(ossl_quic_tserver_write(qtserv, 0,
1274                                            (unsigned char *)msg,
1275                                            msglen, &numbytes)))
1276         goto err;
1277
1278     ossl_quic_tserver_tick(qtserv);
1279     SSL_handle_events(clientquic);
1280
1281     if (!TEST_true(SSL_read_ex(clientquic, buf, sizeof(buf), &numbytes))
1282             || !TEST_size_t_eq(numbytes, msglen)
1283             || !TEST_mem_eq(buf, numbytes, msg, msglen))
1284         goto err;
1285
1286     if (!TEST_true(qtest_shutdown(qtserv, clientquic)))
1287         goto err;
1288
1289     testresult = 1;
1290
1291  err:
1292     SSL_free(clientquic);
1293     ossl_quic_tserver_free(qtserv);
1294     SSL_CTX_free(sctx);
1295     SSL_CTX_free(cctx);
1296
1297     return testresult;
1298 }
1299
1300 /*
1301  * Test that we correctly handle ALPN supplied by the application
1302  * Test 0: ALPN is provided
1303  * Test 1: No ALPN is provided
1304  */
1305 static int test_alpn(int idx)
1306 {
1307     SSL_CTX *cctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method());
1308     SSL *clientquic = NULL;
1309     QUIC_TSERVER *qtserv = NULL;
1310     int testresult = 0;
1311     int ret;
1312
1313     /*
1314      * Ensure we only configure ciphersuites that are available with both the
1315      * default and fips providers to get the same output in both cases
1316      */
1317     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_128_GCM_SHA256")))
1318         goto err;
1319
1320     if (!TEST_ptr(cctx)
1321             || !TEST_true(qtest_create_quic_objects(libctx, cctx, NULL, cert,
1322                                                     privkey,
1323                                                     QTEST_FLAG_FAKE_TIME,
1324                                                     &qtserv,
1325                                                     &clientquic, NULL, NULL)))
1326         goto err;
1327
1328     if (idx == 0) {
1329         /*
1330         * Clear the ALPN we set in qtest_create_quic_objects. We use TEST_false
1331         * because SSL_set_alpn_protos returns 0 for success.
1332         */
1333         if (!TEST_false(SSL_set_alpn_protos(clientquic, NULL, 0)))
1334             goto err;
1335     }
1336
1337     ret = SSL_connect(clientquic);
1338     if (!TEST_int_le(ret, 0))
1339         goto err;
1340     if (idx == 0) {
1341         /* We expect an immediate error due to lack of ALPN */
1342         if (!TEST_int_eq(SSL_get_error(clientquic, ret), SSL_ERROR_SSL))
1343             goto err;
1344     } else {
1345         /* ALPN was provided so we expect the connection to succeed */
1346         if (!TEST_int_eq(SSL_get_error(clientquic, ret), SSL_ERROR_WANT_READ)
1347                 || !TEST_true(qtest_create_quic_connection(qtserv, clientquic)))
1348             goto err;
1349     }
1350
1351     testresult = 1;
1352  err:
1353     ossl_quic_tserver_free(qtserv);
1354     SSL_free(clientquic);
1355     SSL_CTX_free(cctx);
1356
1357     return testresult;
1358 }
1359
1360 /*
1361  * Test SSL_get_shutdown() behavior.
1362  */
1363 static int test_get_shutdown(void)
1364 {
1365     SSL_CTX *cctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method());
1366     SSL *clientquic = NULL;
1367     QUIC_TSERVER *qtserv = NULL;
1368     int testresult = 0;
1369
1370     if (!TEST_ptr(cctx)
1371             || !TEST_true(qtest_create_quic_objects(libctx, cctx, NULL, cert,
1372                                                     privkey,
1373                                                     QTEST_FLAG_FAKE_TIME,
1374                                                     &qtserv, &clientquic,
1375                                                     NULL, NULL))
1376             || !TEST_true(qtest_create_quic_connection(qtserv, clientquic)))
1377         goto err;
1378
1379     if (!TEST_int_eq(SSL_get_shutdown(clientquic), 0))
1380         goto err;
1381
1382     if (!TEST_int_eq(SSL_shutdown(clientquic), 0))
1383         goto err;
1384
1385     if (!TEST_int_eq(SSL_get_shutdown(clientquic), SSL_SENT_SHUTDOWN))
1386         goto err;
1387
1388     do {
1389         ossl_quic_tserver_tick(qtserv);
1390         qtest_add_time(100);
1391     } while (SSL_shutdown(clientquic) == 0);
1392
1393     if (!TEST_int_eq(SSL_get_shutdown(clientquic),
1394                      SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN))
1395         goto err;
1396
1397     testresult = 1;
1398  err:
1399     ossl_quic_tserver_free(qtserv);
1400     SSL_free(clientquic);
1401     SSL_CTX_free(cctx);
1402
1403     return testresult;
1404 }
1405
1406 #define MAX_LOOPS   2000
1407
1408 /*
1409  * Keep retrying SSL_read_ex until it succeeds or we give up. Accept a stream
1410  * if we don't already have one
1411  */
1412 static int unreliable_client_read(SSL *clientquic, SSL **stream, void *buf,
1413                                   size_t buflen, size_t *readbytes,
1414                                   QUIC_TSERVER *qtserv)
1415 {
1416     int abortctr;
1417
1418     /* We just do this in a loop with a sleep for simplicity */
1419     for (abortctr = 0; abortctr < MAX_LOOPS; abortctr++) {
1420         if (*stream == NULL) {
1421             SSL_handle_events(clientquic);
1422             *stream = SSL_accept_stream(clientquic, 0);
1423         }
1424
1425         if (*stream != NULL) {
1426             if (SSL_read_ex(*stream, buf, buflen, readbytes))
1427                 return 1;
1428             if (!TEST_int_eq(SSL_get_error(*stream, 0), SSL_ERROR_WANT_READ))
1429                 return 0;
1430         }
1431         ossl_quic_tserver_tick(qtserv);
1432         qtest_add_time(1);
1433         qtest_wait_for_timeout(clientquic, qtserv);
1434     }
1435
1436     TEST_error("No progress made");
1437     return 0;
1438 }
1439
1440 /* Keep retrying ossl_quic_tserver_read until it succeeds or we give up */
1441 static int unreliable_server_read(QUIC_TSERVER *qtserv, uint64_t sid,
1442                                   void *buf, size_t buflen, size_t *readbytes,
1443                                   SSL *clientquic)
1444 {
1445     int abortctr;
1446
1447     /* We just do this in a loop with a sleep for simplicity */
1448     for (abortctr = 0; abortctr < MAX_LOOPS; abortctr++) {
1449         if (ossl_quic_tserver_read(qtserv, sid, buf, buflen, readbytes)
1450                 && *readbytes > 1)
1451             return 1;
1452         ossl_quic_tserver_tick(qtserv);
1453         SSL_handle_events(clientquic);
1454         qtest_add_time(1);
1455         qtest_wait_for_timeout(clientquic, qtserv);
1456     }
1457
1458     TEST_error("No progress made");
1459     return 0;
1460 }
1461
1462 /*
1463  * Create a connection and send data using an unreliable transport. We introduce
1464  * random noise to drop, delay and duplicate datagrams.
1465  * Test 0: Introduce random noise to datagrams
1466  * Test 1: As with test 0 but also split datagrams containing multiple packets
1467  *         into individual datagrams so that individual packets can be affected
1468  *         by noise - not just a whole datagram.
1469  */
1470 static int test_noisy_dgram(int idx)
1471 {
1472     SSL_CTX *cctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method());
1473     SSL *clientquic = NULL, *stream[2] = { NULL, NULL };
1474     QUIC_TSERVER *qtserv = NULL;
1475     int testresult = 0;
1476     uint64_t sid = 0;
1477     char *msg = "Hello world!";
1478     size_t msglen = strlen(msg), written, readbytes, i, j;
1479     unsigned char buf[80];
1480     int flags = QTEST_FLAG_NOISE | QTEST_FLAG_FAKE_TIME;
1481     QTEST_FAULT *fault = NULL;
1482
1483     if (idx == 1)
1484         flags |= QTEST_FLAG_PACKET_SPLIT;
1485
1486     if (!TEST_ptr(cctx)
1487             || !TEST_true(qtest_create_quic_objects(libctx, cctx, NULL, cert,
1488                                                     privkey, flags,
1489                                                     &qtserv,
1490                                                     &clientquic, &fault, NULL)))
1491         goto err;
1492
1493     if (!TEST_true(qtest_create_quic_connection(qtserv, clientquic)))
1494             goto err;
1495
1496     if (!TEST_true(SSL_set_incoming_stream_policy(clientquic,
1497                                                   SSL_INCOMING_STREAM_POLICY_ACCEPT,
1498                                                   0))
1499             || !TEST_true(SSL_set_default_stream_mode(clientquic,
1500                                                       SSL_DEFAULT_STREAM_MODE_NONE)))
1501         goto err;
1502
1503     for (j = 0; j < 2; j++) {
1504         if (!TEST_true(ossl_quic_tserver_stream_new(qtserv, 0, &sid)))
1505             goto err;
1506         ossl_quic_tserver_tick(qtserv);
1507         qtest_add_time(1);
1508
1509         /*
1510          * Send data from the server to the client. Some datagrams may get
1511          * lost, modified, dropped or re-ordered. We repeat 20 times to ensure
1512          * we are sending enough datagrams for problems to be noticed.
1513          */
1514         for (i = 0; i < 20; i++) {
1515             if (!TEST_true(ossl_quic_tserver_write(qtserv, sid,
1516                                                    (unsigned char *)msg, msglen,
1517                                                    &written))
1518                     || !TEST_size_t_eq(msglen, written))
1519                 goto err;
1520             ossl_quic_tserver_tick(qtserv);
1521             qtest_add_time(1);
1522
1523             /*
1524              * Since the underlying BIO is now noisy we may get failures that
1525              * need to be retried - so we use unreliable_client_read() to
1526              * handle that
1527              */
1528             if (!TEST_true(unreliable_client_read(clientquic, &stream[j], buf,
1529                                                   sizeof(buf), &readbytes,
1530                                                   qtserv))
1531                     || !TEST_mem_eq(msg, msglen, buf, readbytes))
1532                 goto err;
1533         }
1534
1535         /* Send data from the client to the server */
1536         for (i = 0; i < 20; i++) {
1537             if (!TEST_true(SSL_write_ex(stream[j], (unsigned char *)msg,
1538                                         msglen, &written))
1539                     || !TEST_size_t_eq(msglen, written))
1540                 goto err;
1541
1542             ossl_quic_tserver_tick(qtserv);
1543             qtest_add_time(1);
1544
1545             /*
1546              * Since the underlying BIO is now noisy we may get failures that
1547              * need to be retried - so we use unreliable_server_read() to
1548              * handle that
1549              */
1550             if (!TEST_true(unreliable_server_read(qtserv, sid, buf, sizeof(buf),
1551                                                   &readbytes, clientquic))
1552                     || !TEST_mem_eq(msg, msglen, buf, readbytes))
1553                 goto err;
1554         }
1555     }
1556
1557     testresult = 1;
1558  err:
1559     ossl_quic_tserver_free(qtserv);
1560     SSL_free(stream[0]);
1561     SSL_free(stream[1]);
1562     SSL_free(clientquic);
1563     SSL_CTX_free(cctx);
1564     qtest_fault_free(fault);
1565
1566     return testresult;
1567 }
1568
1569 /*
1570  * Create a connection and send some big data using a transport with limited bandwidth.
1571  */
1572
1573 #define TEST_TRANSFER_DATA_SIZE (2*1024*1024)    /* 2 MBytes */
1574 #define TEST_SINGLE_WRITE_SIZE (16*1024)        /* 16 kBytes */
1575 #define TEST_BW_LIMIT 1000                      /* 1000 Bytes/ms */
1576 static int test_bw_limit(void)
1577 {
1578     SSL_CTX *cctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method());
1579     SSL *clientquic = NULL;
1580     QUIC_TSERVER *qtserv = NULL;
1581     int testresult = 0;
1582     unsigned char *msg = NULL, *recvbuf = NULL;
1583     size_t sendlen = TEST_TRANSFER_DATA_SIZE;
1584     size_t recvlen = TEST_TRANSFER_DATA_SIZE;
1585     size_t written, readbytes;
1586     int flags = QTEST_FLAG_NOISE | QTEST_FLAG_FAKE_TIME;
1587     QTEST_FAULT *fault = NULL;
1588     uint64_t real_bw;
1589
1590     if (!TEST_ptr(cctx)
1591             || !TEST_true(qtest_create_quic_objects(libctx, cctx, NULL, cert,
1592                                                     privkey, flags,
1593                                                     &qtserv,
1594                                                     &clientquic, &fault, NULL)))
1595         goto err;
1596
1597     if (!TEST_ptr(msg = OPENSSL_zalloc(TEST_SINGLE_WRITE_SIZE))
1598         || !TEST_ptr(recvbuf = OPENSSL_zalloc(TEST_SINGLE_WRITE_SIZE)))
1599         goto err;
1600
1601     /* Set BW to 1000 Bytes/ms -> 1MByte/s both ways */
1602     if (!TEST_true(qtest_fault_set_bw_limit(fault, 1000, 1000, 0)))
1603         goto err;
1604
1605     if (!TEST_true(qtest_create_quic_connection(qtserv, clientquic)))
1606             goto err;
1607
1608     qtest_start_stopwatch();
1609
1610     while (recvlen > 0) {
1611         qtest_add_time(1);
1612
1613         if (sendlen > 0) {
1614             if (!SSL_write_ex(clientquic, msg,
1615                               sendlen > TEST_SINGLE_WRITE_SIZE ? TEST_SINGLE_WRITE_SIZE
1616                                                                : sendlen,
1617                               &written)) {
1618                 TEST_info("Retrying to send: %llu", (unsigned long long) sendlen);
1619                 if (!TEST_int_eq(SSL_get_error(clientquic, 0), SSL_ERROR_WANT_WRITE))
1620                     goto err;
1621             } else {
1622                 sendlen -= written;
1623                 TEST_info("Remaining to send: %llu", (unsigned long long) sendlen);
1624             }
1625         } else {
1626             SSL_handle_events(clientquic);
1627         }
1628
1629         if (ossl_quic_tserver_read(qtserv, 0, recvbuf,
1630                                    recvlen > TEST_SINGLE_WRITE_SIZE ? TEST_SINGLE_WRITE_SIZE
1631                                                                     : recvlen,
1632                                    &readbytes)
1633             && readbytes > 1) {
1634             recvlen -= readbytes;
1635             TEST_info("Remaining to recv: %llu", (unsigned long long) recvlen);
1636         } else {
1637             TEST_info("No progress on recv: %llu", (unsigned long long) recvlen);
1638         }
1639         ossl_quic_tserver_tick(qtserv);
1640     }
1641     real_bw = TEST_TRANSFER_DATA_SIZE / qtest_get_stopwatch_time();
1642
1643     TEST_info("BW limit: %d Bytes/ms Real bandwidth reached: %llu Bytes/ms",
1644               TEST_BW_LIMIT, (unsigned long long)real_bw);
1645
1646     if (!TEST_uint64_t_lt(real_bw, TEST_BW_LIMIT))
1647         goto err;
1648
1649     testresult = 1;
1650  err:
1651     OPENSSL_free(msg);
1652     OPENSSL_free(recvbuf);
1653     ossl_quic_tserver_free(qtserv);
1654     SSL_free(clientquic);
1655     SSL_CTX_free(cctx);
1656     qtest_fault_free(fault);
1657
1658     return testresult;
1659 }
1660
1661 enum {
1662     TPARAM_OP_DUP,
1663     TPARAM_OP_DROP,
1664     TPARAM_OP_INJECT,
1665     TPARAM_OP_INJECT_TWICE,
1666     TPARAM_OP_INJECT_RAW,
1667     TPARAM_OP_DROP_INJECT,
1668     TPARAM_OP_MUTATE
1669 };
1670
1671 #define TPARAM_CHECK_DUP(name, reason) \
1672     { QUIC_TPARAM_##name, TPARAM_OP_DUP, (reason) },
1673 #define TPARAM_CHECK_DROP(name, reason) \
1674     { QUIC_TPARAM_##name, TPARAM_OP_DROP, (reason) },
1675 #define TPARAM_CHECK_INJECT(name, buf, buf_len, reason) \
1676     { QUIC_TPARAM_##name, TPARAM_OP_INJECT, (reason), \
1677       (buf), (buf_len) },
1678 #define TPARAM_CHECK_INJECT_A(name, buf, reason) \
1679     TPARAM_CHECK_INJECT(name, buf, sizeof(buf), reason)
1680 #define TPARAM_CHECK_DROP_INJECT(name, buf, buf_len, reason) \
1681     { QUIC_TPARAM_##name, TPARAM_OP_DROP_INJECT, (reason), \
1682       (buf), (buf_len) },
1683 #define TPARAM_CHECK_DROP_INJECT_A(name, buf, reason) \
1684     TPARAM_CHECK_DROP_INJECT(name, buf, sizeof(buf), reason)
1685 #define TPARAM_CHECK_INJECT_TWICE(name, buf, buf_len, reason) \
1686     { QUIC_TPARAM_##name, TPARAM_OP_INJECT_TWICE, (reason), \
1687       (buf), (buf_len) },
1688 #define TPARAM_CHECK_INJECT_TWICE_A(name, buf, reason) \
1689     TPARAM_CHECK_INJECT_TWICE(name, buf, sizeof(buf), reason)
1690 #define TPARAM_CHECK_INJECT_RAW(buf, buf_len, reason) \
1691     { 0, TPARAM_OP_INJECT_RAW, (reason), \
1692       (buf), (buf_len) },
1693 #define TPARAM_CHECK_INJECT_RAW_A(buf, reason) \
1694     TPARAM_CHECK_INJECT_RAW(buf, sizeof(buf), reason)
1695 #define TPARAM_CHECK_MUTATE(name, reason) \
1696     { QUIC_TPARAM_##name, TPARAM_OP_MUTATE, (reason) },
1697 #define TPARAM_CHECK_INT(name, reason) \
1698     TPARAM_CHECK_DROP_INJECT(name, NULL, 0, reason) \
1699     TPARAM_CHECK_DROP_INJECT_A(name, bogus_int, reason) \
1700     TPARAM_CHECK_DROP_INJECT_A(name, int_with_trailer, reason)
1701
1702 struct tparam_test {
1703     uint64_t    id;
1704     int         op;
1705     const char  *expect_fail; /* substring to expect in reason */
1706     const void  *buf;
1707     size_t      buf_len;
1708 };
1709
1710 static const unsigned char retry_scid_1[8] = { 0 };
1711
1712 static const unsigned char disable_active_migration_1[] = {
1713     0x00
1714 };
1715
1716 static const unsigned char malformed_stateless_reset_token_1[] = {
1717     0x02, 0xff
1718 };
1719
1720 static const unsigned char malformed_stateless_reset_token_2[] = {
1721     0x01
1722 };
1723
1724 static const unsigned char malformed_stateless_reset_token_3[15] = { 0 };
1725
1726 static const unsigned char malformed_stateless_reset_token_4[17] = { 0 };
1727
1728 static const unsigned char malformed_preferred_addr_1[] = {
1729     0x0d, 0xff
1730 };
1731
1732 static const unsigned char malformed_preferred_addr_2[42] = {
1733     0x0d, 0x28, /* too short */
1734 };
1735
1736 static const unsigned char malformed_preferred_addr_3[64] = {
1737     0x0d, 0x3e, /* too long */
1738 };
1739
1740 static const unsigned char malformed_preferred_addr_4[] = {
1741     /* TPARAM too short for CID length indicated */
1742     0x0d, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1743     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1744     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1745     0x00, 0x00, 0x01, 0x55,
1746     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1747     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1748 };
1749
1750 static const unsigned char malformed_unknown_1[] = {
1751     0xff
1752 };
1753
1754 static const unsigned char malformed_unknown_2[] = {
1755     0x55, 0x55,
1756 };
1757
1758 static const unsigned char malformed_unknown_3[] = {
1759     0x55, 0x55, 0x01,
1760 };
1761
1762 static const unsigned char ack_delay_exp[] = {
1763     0x03
1764 };
1765
1766 static const unsigned char stateless_reset_token[16] = { 0x42 };
1767
1768 static const unsigned char preferred_addr[] = {
1769     0x44, 0x44, 0x44, 0x44,
1770     0x55, 0x55,
1771     0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
1772     0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
1773     0x77, 0x77,
1774     0x02, 0xAA, 0xBB,
1775     0x99, 0x99, 0x99, 0x99, 0x99, 0x99, 0x99, 0x99,
1776     0x99, 0x99, 0x99, 0x99, 0x99, 0x99, 0x99, 0x99,
1777 };
1778
1779 static const unsigned char long_cid[21] = { 0x42 };
1780
1781 static const unsigned char excess_ack_delay_exp[] = {
1782     0x15,
1783 };
1784
1785 static const unsigned char excess_max_ack_delay[] = {
1786     0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00,
1787 };
1788
1789 static const unsigned char excess_initial_max_streams[] = {
1790     0xD0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
1791 };
1792
1793 static const unsigned char undersize_udp_payload_size[] = {
1794     0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0xaf,
1795 };
1796
1797 static const unsigned char undersize_active_conn_id_limit[] = {
1798     0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
1799 };
1800
1801 static const unsigned char bogus_int[9] = { 0 };
1802
1803 static const unsigned char int_with_trailer[2] = { 0x01 };
1804
1805 #define QUIC_TPARAM_UNKNOWN_1   0xf1f1
1806
1807 static const struct tparam_test tparam_tests[] = {
1808     TPARAM_CHECK_DUP(ORIG_DCID,
1809                      "ORIG_DCID appears multiple times")
1810     TPARAM_CHECK_DUP(INITIAL_SCID,
1811                      "INITIAL_SCID appears multiple times")
1812     TPARAM_CHECK_DUP(INITIAL_MAX_DATA,
1813                      "INITIAL_MAX_DATA appears multiple times")
1814     TPARAM_CHECK_DUP(INITIAL_MAX_STREAM_DATA_BIDI_LOCAL,
1815                      "INITIAL_MAX_STREAM_DATA_BIDI_LOCAL appears multiple times")
1816     TPARAM_CHECK_DUP(INITIAL_MAX_STREAM_DATA_BIDI_REMOTE,
1817                      "INITIAL_MAX_STREAM_DATA_BIDI_REMOTE appears multiple times")
1818     TPARAM_CHECK_DUP(INITIAL_MAX_STREAM_DATA_UNI,
1819                      "INITIAL_MAX_STREAM_DATA_UNI appears multiple times")
1820     TPARAM_CHECK_DUP(INITIAL_MAX_STREAMS_BIDI,
1821                      "INITIAL_MAX_STREAMS_BIDI appears multiple times")
1822     TPARAM_CHECK_DUP(INITIAL_MAX_STREAMS_UNI,
1823                      "INITIAL_MAX_STREAMS_UNI appears multiple times")
1824     TPARAM_CHECK_DUP(MAX_IDLE_TIMEOUT,
1825                      "MAX_IDLE_TIMEOUT appears multiple times")
1826     TPARAM_CHECK_DUP(MAX_UDP_PAYLOAD_SIZE,
1827                      "MAX_UDP_PAYLOAD_SIZE appears multiple times")
1828     TPARAM_CHECK_DUP(ACTIVE_CONN_ID_LIMIT,
1829                      "ACTIVE_CONN_ID_LIMIT appears multiple times")
1830     TPARAM_CHECK_DUP(DISABLE_ACTIVE_MIGRATION,
1831                      "DISABLE_ACTIVE_MIGRATION appears multiple times")
1832
1833     TPARAM_CHECK_DROP(INITIAL_SCID,
1834                       "INITIAL_SCID was not sent but is required")
1835     TPARAM_CHECK_DROP(ORIG_DCID,
1836                       "ORIG_DCID was not sent but is required")
1837
1838     TPARAM_CHECK_INJECT_A(RETRY_SCID, retry_scid_1,
1839                           "RETRY_SCID sent when not performing a retry")
1840     TPARAM_CHECK_DROP_INJECT_A(DISABLE_ACTIVE_MIGRATION, disable_active_migration_1,
1841                                "DISABLE_ACTIVE_MIGRATION is malformed")
1842     TPARAM_CHECK_INJECT(UNKNOWN_1, NULL, 0,
1843                         NULL)
1844     TPARAM_CHECK_INJECT_RAW_A(malformed_stateless_reset_token_1,
1845                               "STATELESS_RESET_TOKEN is malformed")
1846     TPARAM_CHECK_INJECT_A(STATELESS_RESET_TOKEN,
1847                           malformed_stateless_reset_token_2,
1848                           "STATELESS_RESET_TOKEN is malformed")
1849     TPARAM_CHECK_INJECT_A(STATELESS_RESET_TOKEN,
1850                           malformed_stateless_reset_token_3,
1851                           "STATELESS_RESET_TOKEN is malformed")
1852     TPARAM_CHECK_INJECT_A(STATELESS_RESET_TOKEN,
1853                           malformed_stateless_reset_token_4,
1854                           "STATELESS_RESET_TOKEN is malformed")
1855     TPARAM_CHECK_INJECT(STATELESS_RESET_TOKEN,
1856                         NULL, 0,
1857                         "STATELESS_RESET_TOKEN is malformed")
1858     TPARAM_CHECK_INJECT_RAW_A(malformed_preferred_addr_1,
1859                               "PREFERRED_ADDR is malformed")
1860     TPARAM_CHECK_INJECT_RAW_A(malformed_preferred_addr_2,
1861                               "PREFERRED_ADDR is malformed")
1862     TPARAM_CHECK_INJECT_RAW_A(malformed_preferred_addr_3,
1863                               "PREFERRED_ADDR is malformed")
1864     TPARAM_CHECK_INJECT_RAW_A(malformed_preferred_addr_4,
1865                               "PREFERRED_ADDR is malformed")
1866     TPARAM_CHECK_INJECT_RAW_A(malformed_unknown_1,
1867                               "bad transport parameter")
1868     TPARAM_CHECK_INJECT_RAW_A(malformed_unknown_2,
1869                               "bad transport parameter")
1870     TPARAM_CHECK_INJECT_RAW_A(malformed_unknown_3,
1871                               "bad transport parameter")
1872
1873     TPARAM_CHECK_INJECT_A(ACK_DELAY_EXP, excess_ack_delay_exp,
1874                           "ACK_DELAY_EXP is malformed")
1875     TPARAM_CHECK_INJECT_A(MAX_ACK_DELAY, excess_max_ack_delay,
1876                           "MAX_ACK_DELAY is malformed")
1877     TPARAM_CHECK_DROP_INJECT_A(INITIAL_MAX_STREAMS_BIDI, excess_initial_max_streams,
1878                                "INITIAL_MAX_STREAMS_BIDI is malformed")
1879     TPARAM_CHECK_DROP_INJECT_A(INITIAL_MAX_STREAMS_UNI, excess_initial_max_streams,
1880                                "INITIAL_MAX_STREAMS_UNI is malformed")
1881
1882     TPARAM_CHECK_DROP_INJECT_A(MAX_UDP_PAYLOAD_SIZE, undersize_udp_payload_size,
1883                                "MAX_UDP_PAYLOAD_SIZE is malformed")
1884     TPARAM_CHECK_DROP_INJECT_A(ACTIVE_CONN_ID_LIMIT, undersize_active_conn_id_limit,
1885                                "ACTIVE_CONN_ID_LIMIT is malformed")
1886
1887     TPARAM_CHECK_INJECT_TWICE_A(ACK_DELAY_EXP, ack_delay_exp,
1888                                 "ACK_DELAY_EXP appears multiple times")
1889     TPARAM_CHECK_INJECT_TWICE_A(MAX_ACK_DELAY, ack_delay_exp,
1890                                 "MAX_ACK_DELAY appears multiple times")
1891     TPARAM_CHECK_INJECT_TWICE_A(STATELESS_RESET_TOKEN, stateless_reset_token,
1892                                 "STATELESS_RESET_TOKEN appears multiple times")
1893     TPARAM_CHECK_INJECT_TWICE_A(PREFERRED_ADDR, preferred_addr,
1894                                 "PREFERRED_ADDR appears multiple times")
1895
1896     TPARAM_CHECK_MUTATE(ORIG_DCID,
1897                         "ORIG_DCID does not match expected value")
1898     TPARAM_CHECK_MUTATE(INITIAL_SCID,
1899                         "INITIAL_SCID does not match expected value")
1900
1901     TPARAM_CHECK_DROP_INJECT_A(ORIG_DCID, long_cid,
1902                                "ORIG_DCID is malformed")
1903     TPARAM_CHECK_DROP_INJECT_A(INITIAL_SCID, long_cid,
1904                                "INITIAL_SCID is malformed")
1905
1906     TPARAM_CHECK_INT(INITIAL_MAX_DATA,
1907                      "INITIAL_MAX_DATA is malformed")
1908     TPARAM_CHECK_INT(INITIAL_MAX_STREAM_DATA_BIDI_LOCAL,
1909                      "INITIAL_MAX_STREAM_DATA_BIDI_LOCAL is malformed")
1910     TPARAM_CHECK_INT(INITIAL_MAX_STREAM_DATA_BIDI_REMOTE,
1911                      "INITIAL_MAX_STREAM_DATA_BIDI_REMOTE is malformed")
1912     TPARAM_CHECK_INT(INITIAL_MAX_STREAM_DATA_UNI,
1913                      "INITIAL_MAX_STREAM_DATA_UNI is malformed")
1914     TPARAM_CHECK_INT(ACK_DELAY_EXP,
1915                      "ACK_DELAY_EXP is malformed")
1916     TPARAM_CHECK_INT(MAX_ACK_DELAY,
1917                      "MAX_ACK_DELAY is malformed")
1918     TPARAM_CHECK_INT(INITIAL_MAX_STREAMS_BIDI,
1919                      "INITIAL_MAX_STREAMS_BIDI is malformed")
1920     TPARAM_CHECK_INT(INITIAL_MAX_STREAMS_UNI,
1921                      "INITIAL_MAX_STREAMS_UNI is malformed")
1922     TPARAM_CHECK_INT(MAX_IDLE_TIMEOUT,
1923                      "MAX_IDLE_TIMEOUT is malformed")
1924     TPARAM_CHECK_INT(MAX_UDP_PAYLOAD_SIZE,
1925                      "MAX_UDP_PAYLOAD_SIZE is malformed")
1926     TPARAM_CHECK_INT(ACTIVE_CONN_ID_LIMIT,
1927                      "ACTIVE_CONN_ID_LIMIT is malformed")
1928 };
1929
1930 struct tparam_ctx {
1931     const struct tparam_test *t;
1932 };
1933
1934 static int tparam_handle(struct tparam_ctx *ctx,
1935                          uint64_t id, unsigned char *data,
1936                          size_t data_len,
1937                          WPACKET *wpkt)
1938 {
1939     const struct tparam_test *t = ctx->t;
1940
1941     switch (t->op) {
1942     case TPARAM_OP_DUP:
1943         if (!TEST_ptr(ossl_quic_wire_encode_transport_param_bytes(wpkt, id,
1944                                                                   data, data_len)))
1945             return 0;
1946
1947         /*
1948          * If this is the matching ID, write it again, duplicating the TPARAM.
1949          */
1950         if (id == t->id
1951             && !TEST_ptr(ossl_quic_wire_encode_transport_param_bytes(wpkt, id,
1952                                                                      data, data_len)))
1953             return 0;
1954
1955         return 1;
1956
1957     case TPARAM_OP_DROP:
1958     case TPARAM_OP_DROP_INJECT:
1959         /* Pass through unless ID matches. */
1960         if (id != t->id
1961             && !TEST_ptr(ossl_quic_wire_encode_transport_param_bytes(wpkt, id,
1962                                                                      data, data_len)))
1963             return 0;
1964
1965         return 1;
1966
1967     case TPARAM_OP_INJECT:
1968     case TPARAM_OP_INJECT_TWICE:
1969     case TPARAM_OP_INJECT_RAW:
1970         /* Always pass through. */
1971         if (!TEST_ptr(ossl_quic_wire_encode_transport_param_bytes(wpkt, id,
1972                                                                   data, data_len)))
1973             return 0;
1974
1975         return 1;
1976
1977     case TPARAM_OP_MUTATE:
1978         if (id == t->id) {
1979             if (!TEST_size_t_gt(data_len, 0))
1980                 return 0;
1981
1982             data[0] ^= 1;
1983         }
1984
1985         if (!TEST_ptr(ossl_quic_wire_encode_transport_param_bytes(wpkt, id,
1986                                                                   data, data_len)))
1987             return 0;
1988
1989         if (id == t->id)
1990             data[0] ^= 1;
1991
1992         return 1;
1993
1994     default:
1995         return 0;
1996     }
1997 }
1998
1999 static int tparam_on_enc_ext(QTEST_FAULT *qtf, QTEST_ENCRYPTED_EXTENSIONS *ee,
2000                              size_t ee_len, void *arg)
2001 {
2002     int rc = 0;
2003     struct tparam_ctx *ctx = arg;
2004     PACKET pkt = {0};
2005     WPACKET wpkt;
2006     int have_wpkt = 0;
2007     BUF_MEM *old_bufm = NULL, *new_bufm = NULL;
2008     unsigned char *tp_p;
2009     size_t tp_len, written, old_len, eb_len;
2010     uint64_t id;
2011
2012     if (!TEST_ptr(old_bufm = BUF_MEM_new()))
2013         goto err;
2014
2015     /*
2016      * Delete transport parameters TLS extension and capture the contents of the
2017      * extension which was removed.
2018      */
2019     if (!TEST_true(qtest_fault_delete_extension(qtf, TLSEXT_TYPE_quic_transport_parameters,
2020                                                 ee->extensions, &ee->extensionslen,
2021                                                 old_bufm)))
2022         goto err;
2023
2024     if (!TEST_true(PACKET_buf_init(&pkt, (unsigned char *)old_bufm->data, old_bufm->length))
2025         || !TEST_ptr(new_bufm = BUF_MEM_new())
2026         || !TEST_true(WPACKET_init(&wpkt, new_bufm)))
2027         goto err;
2028
2029     have_wpkt = 1;
2030
2031     /*
2032      * Open transport parameters TLS extension:
2033      *
2034      *   u16  Extension ID (quic_transport_parameters)
2035      *   u16  Extension Data Length
2036      *   ...  Extension Data
2037      *
2038      */
2039     if (!TEST_true(WPACKET_put_bytes_u16(&wpkt,
2040                                          TLSEXT_TYPE_quic_transport_parameters))
2041         || !TEST_true(WPACKET_start_sub_packet_u16(&wpkt)))
2042         goto err;
2043
2044     for (; PACKET_remaining(&pkt) > 0; ) {
2045         tp_p = (unsigned char *)ossl_quic_wire_decode_transport_param_bytes(&pkt,
2046                                                                             &id,
2047                                                                             &tp_len);
2048         if (!TEST_ptr(tp_p)) {
2049             TEST_mem_eq(PACKET_data(&pkt), PACKET_remaining(&pkt), NULL, 0);
2050             goto err;
2051         }
2052
2053         if (!TEST_true(tparam_handle(ctx, id, tp_p, tp_len, &wpkt)))
2054             goto err;
2055     }
2056
2057     if (ctx->t->op == TPARAM_OP_INJECT || ctx->t->op == TPARAM_OP_DROP_INJECT
2058         || ctx->t->op == TPARAM_OP_INJECT_TWICE) {
2059         if (!TEST_ptr(ossl_quic_wire_encode_transport_param_bytes(&wpkt, ctx->t->id,
2060                                                                   ctx->t->buf,
2061                                                                   ctx->t->buf_len)))
2062             goto err;
2063
2064         if (ctx->t->op == TPARAM_OP_INJECT_TWICE
2065             && !TEST_ptr(ossl_quic_wire_encode_transport_param_bytes(&wpkt, ctx->t->id,
2066                                                                      ctx->t->buf,
2067                                                                      ctx->t->buf_len)))
2068             goto err;
2069     } else if (ctx->t->op == TPARAM_OP_INJECT_RAW) {
2070         if (!TEST_true(WPACKET_memcpy(&wpkt, ctx->t->buf, ctx->t->buf_len)))
2071             goto err;
2072     }
2073
2074     if (!TEST_true(WPACKET_close(&wpkt))) /* end extension data, set length */
2075         goto err;
2076
2077     if (!TEST_true(WPACKET_get_total_written(&wpkt, &written)))
2078         goto err;
2079
2080     WPACKET_finish(&wpkt);
2081     have_wpkt = 0;
2082
2083     /*
2084      * Append the constructed extension blob to the extension block.
2085      */
2086     old_len = ee->extensionslen;
2087
2088     if (!qtest_fault_resize_message(qtf, ee->extensionslen + written))
2089         goto err;
2090
2091     memcpy(ee->extensions + old_len, new_bufm->data, written);
2092
2093     /* Fixup the extension block header (u16 length of entire block). */
2094     eb_len = (((uint16_t)ee->extensions[0]) << 8) + (uint16_t)ee->extensions[1];
2095     eb_len += written;
2096     ee->extensions[0] = (unsigned char)((eb_len >> 8) & 0xFF);
2097     ee->extensions[1] = (unsigned char)( eb_len       & 0xFF);
2098
2099     rc = 1;
2100 err:
2101     if (have_wpkt)
2102         WPACKET_cleanup(&wpkt);
2103     BUF_MEM_free(old_bufm);
2104     BUF_MEM_free(new_bufm);
2105     return rc;
2106 }
2107
2108 static int test_tparam(int idx)
2109 {
2110     int testresult = 0;
2111     SSL_CTX *c_ctx = NULL;
2112     SSL *c_ssl = NULL;
2113     QUIC_TSERVER *s = NULL;
2114     QTEST_FAULT *qtf = NULL;
2115     struct tparam_ctx ctx = {0};
2116
2117     ctx.t = &tparam_tests[idx];
2118
2119     if (!TEST_ptr(c_ctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method())))
2120         goto err;
2121
2122     if (!TEST_true(qtest_create_quic_objects(libctx, c_ctx, NULL, cert,
2123                                              privkey, 0, &s,
2124                                              &c_ssl, &qtf, NULL)))
2125         goto err;
2126
2127     if (!TEST_true(qtest_fault_set_hand_enc_ext_listener(qtf, tparam_on_enc_ext,
2128                                                          &ctx)))
2129         goto err;
2130
2131     if (!TEST_true(qtest_create_quic_connection_ex(s, c_ssl,
2132                                                    ctx.t->expect_fail != NULL)))
2133         goto err;
2134
2135     if (ctx.t->expect_fail != NULL) {
2136         SSL_CONN_CLOSE_INFO info = {0};
2137
2138         if (!TEST_true(SSL_get_conn_close_info(c_ssl, &info, sizeof(info))))
2139             goto err;
2140
2141         if (!TEST_true((info.flags & SSL_CONN_CLOSE_FLAG_TRANSPORT) != 0)
2142             || !TEST_uint64_t_eq(info.error_code, OSSL_QUIC_ERR_TRANSPORT_PARAMETER_ERROR)
2143             || !TEST_ptr(strstr(info.reason, ctx.t->expect_fail))) {
2144             TEST_error("expected connection closure information mismatch"
2145                        " during TPARAM test: flags=%llu ec=%llu reason='%s'",
2146                        (unsigned long long)info.flags,
2147                        (unsigned long long)info.error_code,
2148                        info.reason);
2149             goto err;
2150         }
2151     }
2152
2153     testresult = 1;
2154 err:
2155     if (!testresult) {
2156         if (ctx.t->expect_fail != NULL)
2157             TEST_info("failed during test for id=%llu, op=%d, bl=%zu, "
2158                       "expected failure='%s'", (unsigned long long)ctx.t->id,
2159                       ctx.t->op, ctx.t->buf_len, ctx.t->expect_fail);
2160         else
2161             TEST_info("failed during test for id=%llu, op=%d, bl=%zu",
2162                       (unsigned long long)ctx.t->id, ctx.t->op, ctx.t->buf_len);
2163     }
2164
2165     ossl_quic_tserver_free(s);
2166     SSL_free(c_ssl);
2167     SSL_CTX_free(c_ctx);
2168     qtest_fault_free(qtf);
2169     return testresult;
2170 }
2171 /***********************************************************************************/
2172
2173 OPT_TEST_DECLARE_USAGE("provider config certsdir datadir\n")
2174
2175 int setup_tests(void)
2176 {
2177     char *modulename;
2178     char *configfile;
2179
2180     libctx = OSSL_LIB_CTX_new();
2181     if (!TEST_ptr(libctx))
2182         return 0;
2183
2184     defctxnull = OSSL_PROVIDER_load(NULL, "null");
2185
2186     /*
2187      * Verify that the default and fips providers in the default libctx are not
2188      * available
2189      */
2190     if (!TEST_false(OSSL_PROVIDER_available(NULL, "default"))
2191             || !TEST_false(OSSL_PROVIDER_available(NULL, "fips")))
2192         goto err;
2193
2194     if (!test_skip_common_options()) {
2195         TEST_error("Error parsing test options\n");
2196         goto err;
2197     }
2198
2199     if (!TEST_ptr(modulename = test_get_argument(0))
2200             || !TEST_ptr(configfile = test_get_argument(1))
2201             || !TEST_ptr(certsdir = test_get_argument(2))
2202             || !TEST_ptr(datadir = test_get_argument(3)))
2203         goto err;
2204
2205     if (!TEST_true(OSSL_LIB_CTX_load_config(libctx, configfile)))
2206         goto err;
2207
2208     /* Check we have the expected provider available */
2209     if (!TEST_true(OSSL_PROVIDER_available(libctx, modulename)))
2210         goto err;
2211
2212     /* Check the default provider is not available */
2213     if (strcmp(modulename, "default") != 0
2214             && !TEST_false(OSSL_PROVIDER_available(libctx, "default")))
2215         goto err;
2216
2217     if (strcmp(modulename, "fips") == 0)
2218         is_fips = 1;
2219
2220     cert = test_mk_file_path(certsdir, "servercert.pem");
2221     if (cert == NULL)
2222         goto err;
2223
2224     ccert = test_mk_file_path(certsdir, "ee-client-chain.pem");
2225     if (ccert == NULL)
2226         goto err;
2227
2228     cauthca = test_mk_file_path(certsdir, "root-cert.pem");
2229     if (cauthca == NULL)
2230         goto err;
2231
2232     privkey = test_mk_file_path(certsdir, "serverkey.pem");
2233     if (privkey == NULL)
2234         goto err;
2235
2236     cprivkey = test_mk_file_path(certsdir, "ee-key.pem");
2237     if (privkey == NULL)
2238         goto err;
2239
2240     ADD_ALL_TESTS(test_quic_write_read, 3);
2241     ADD_TEST(test_fin_only_blocking);
2242     ADD_TEST(test_ciphersuites);
2243     ADD_TEST(test_cipher_find);
2244     ADD_TEST(test_version);
2245 #if defined(DO_SSL_TRACE_TEST)
2246     ADD_TEST(test_ssl_trace);
2247 #endif
2248     ADD_TEST(test_quic_forbidden_apis_ctx);
2249     ADD_TEST(test_quic_forbidden_apis);
2250     ADD_TEST(test_quic_forbidden_options);
2251     ADD_ALL_TESTS(test_quic_set_fd, 3);
2252     ADD_TEST(test_bio_ssl);
2253     ADD_TEST(test_back_pressure);
2254     ADD_TEST(test_multiple_dgrams);
2255     ADD_ALL_TESTS(test_non_io_retry, 2);
2256     ADD_TEST(test_quic_psk);
2257     ADD_ALL_TESTS(test_client_auth, 3);
2258     ADD_ALL_TESTS(test_alpn, 2);
2259     ADD_ALL_TESTS(test_noisy_dgram, 2);
2260     ADD_TEST(test_bw_limit);
2261     ADD_TEST(test_get_shutdown);
2262     ADD_ALL_TESTS(test_tparam, OSSL_NELEM(tparam_tests));
2263
2264     return 1;
2265  err:
2266     cleanup_tests();
2267     return 0;
2268 }
2269
2270 void cleanup_tests(void)
2271 {
2272     bio_f_noisy_dgram_filter_free();
2273     bio_f_pkt_split_dgram_filter_free();
2274     OPENSSL_free(cert);
2275     OPENSSL_free(privkey);
2276     OPENSSL_free(ccert);
2277     OPENSSL_free(cauthca);
2278     OPENSSL_free(cprivkey);
2279     OSSL_PROVIDER_unload(defctxnull);
2280     OSSL_LIB_CTX_free(libctx);
2281 }