1/* BEGIN_HEADER */
2#include <ssl_misc.h>
3#include <mbedtls/timing.h>
4#include <mbedtls/debug.h>
5#include <mbedtls/pk.h>
6#include <ssl_tls13_keys.h>
7#include <ssl_tls13_invasive.h>
8#include <test/ssl_helpers.h>
9
10#include <constant_time_internal.h>
11#include <test/constant_flow.h>
12
13#define SSL_MESSAGE_QUEUE_INIT      { NULL, 0, 0, 0 }
14
15/* Mnemonics for the early data test scenarios */
16#define TEST_EARLY_DATA_ACCEPTED 0
17#define TEST_EARLY_DATA_NO_INDICATION_SENT 1
18#define TEST_EARLY_DATA_SERVER_REJECTS 2
19#define TEST_EARLY_DATA_HRR 3
20#define TEST_EARLY_DATA_SAME_ALPN 4
21#define TEST_EARLY_DATA_DIFF_ALPN 5
22#define TEST_EARLY_DATA_NO_INITIAL_ALPN 6
23#define TEST_EARLY_DATA_NO_LATER_ALPN 7
24
25#if (!defined(MBEDTLS_SSL_PROTO_TLS1_2)) && \
26    defined(MBEDTLS_SSL_EARLY_DATA) && defined(MBEDTLS_SSL_CLI_C) && \
27    defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_DEBUG_C) && \
28    defined(MBEDTLS_TEST_AT_LEAST_ONE_TLS1_3_CIPHERSUITE) && \
29    defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED) && \
30    defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED) && \
31    defined(MBEDTLS_MD_CAN_SHA256) && \
32    defined(MBEDTLS_ECP_HAVE_SECP256R1) && defined(MBEDTLS_ECP_HAVE_SECP384R1) && \
33    defined(MBEDTLS_PK_CAN_ECDSA_VERIFY) && defined(MBEDTLS_SSL_SESSION_TICKETS)
34/*
35 * Test function to write early data for negative tests where
36 * mbedtls_ssl_write_early_data() cannot be used.
37 */
38static int write_early_data(mbedtls_ssl_context *ssl,
39                            unsigned char *buf, size_t len)
40{
41    int ret = mbedtls_ssl_get_max_out_record_payload(ssl);
42
43    TEST_ASSERT(ret > 0);
44    TEST_LE_U(len, (size_t) ret);
45
46    ret = mbedtls_ssl_flush_output(ssl);
47    TEST_EQUAL(ret, 0);
48    TEST_EQUAL(ssl->out_left, 0);
49
50    ssl->out_msglen = len;
51    ssl->out_msgtype = MBEDTLS_SSL_MSG_APPLICATION_DATA;
52    if (len > 0) {
53        memcpy(ssl->out_msg, buf, len);
54    }
55
56    ret = mbedtls_ssl_write_record(ssl, 1);
57    TEST_EQUAL(ret, 0);
58
59    ret = len;
60
61exit:
62    return ret;
63}
64#endif
65
66/* END_HEADER */
67
68/* BEGIN_DEPENDENCIES
69 * depends_on:MBEDTLS_SSL_TLS_C
70 * END_DEPENDENCIES
71 */
72
73/* BEGIN_CASE */
74void test_callback_buffer_sanity()
75{
76    enum { MSGLEN = 10 };
77    mbedtls_test_ssl_buffer buf;
78    mbedtls_test_ssl_buffer_init(&buf);
79    unsigned char input[MSGLEN];
80    unsigned char output[MSGLEN];
81
82    USE_PSA_INIT();
83    memset(input, 0, sizeof(input));
84
85    /* Make sure calling put and get on NULL buffer results in error. */
86    TEST_ASSERT(mbedtls_test_ssl_buffer_put(NULL, input, sizeof(input))
87                == -1);
88    TEST_ASSERT(mbedtls_test_ssl_buffer_get(NULL, output, sizeof(output))
89                == -1);
90    TEST_ASSERT(mbedtls_test_ssl_buffer_put(NULL, NULL, sizeof(input))
91                == -1);
92
93    TEST_ASSERT(mbedtls_test_ssl_buffer_put(NULL, NULL, 0) == -1);
94    TEST_ASSERT(mbedtls_test_ssl_buffer_get(NULL, NULL, 0) == -1);
95
96    /* Make sure calling put and get on a buffer that hasn't been set up results
97     * in error. */
98    TEST_ASSERT(mbedtls_test_ssl_buffer_put(&buf, input, sizeof(input))
99                == -1);
100    TEST_ASSERT(mbedtls_test_ssl_buffer_get(&buf, output, sizeof(output))
101                == -1);
102    TEST_ASSERT(mbedtls_test_ssl_buffer_put(&buf, NULL, sizeof(input))
103                == -1);
104
105    TEST_ASSERT(mbedtls_test_ssl_buffer_put(&buf, NULL, 0) == -1);
106    TEST_ASSERT(mbedtls_test_ssl_buffer_get(&buf, NULL, 0) == -1);
107
108    /* Make sure calling put and get on NULL input only results in
109     * error if the length is not zero, and that a NULL output is valid for data
110     * dropping.
111     */
112
113    TEST_ASSERT(mbedtls_test_ssl_buffer_setup(&buf, sizeof(input)) == 0);
114
115    TEST_ASSERT(mbedtls_test_ssl_buffer_put(&buf, NULL, sizeof(input))
116                == -1);
117    TEST_ASSERT(mbedtls_test_ssl_buffer_get(&buf, NULL, sizeof(output))
118                == 0);
119    TEST_ASSERT(mbedtls_test_ssl_buffer_put(&buf, NULL, 0) == 0);
120    TEST_ASSERT(mbedtls_test_ssl_buffer_get(&buf, NULL, 0) == 0);
121
122    /* Make sure calling put several times in the row is safe */
123
124    TEST_ASSERT(mbedtls_test_ssl_buffer_put(&buf, input, sizeof(input))
125                == sizeof(input));
126    TEST_ASSERT(mbedtls_test_ssl_buffer_get(&buf, output, 2) == 2);
127    TEST_ASSERT(mbedtls_test_ssl_buffer_put(&buf, input, 1) == 1);
128    TEST_ASSERT(mbedtls_test_ssl_buffer_put(&buf, input, 2) == 1);
129    TEST_ASSERT(mbedtls_test_ssl_buffer_put(&buf, input, 2) == 0);
130
131
132exit:
133    mbedtls_test_ssl_buffer_free(&buf);
134    USE_PSA_DONE();
135}
136/* END_CASE */
137
138/*
139 * Test if the implementation of `mbedtls_test_ssl_buffer` related functions is
140 * correct and works as expected.
141 *
142 * That is
143 *  - If we try to put in \p put1 bytes then we can put in \p put1_ret bytes.
144 *  - Afterwards if we try to get \p get1 bytes then we can get \get1_ret bytes.
145 *  - Next, if we try to put in \p put1 bytes then we can put in \p put1_ret
146 *    bytes.
147 *  - Afterwards if we try to get \p get1 bytes then we can get \get1_ret bytes.
148 *  - All of the bytes we got match the bytes we put in in a FIFO manner.
149 */
150
151/* BEGIN_CASE */
152void test_callback_buffer(int size, int put1, int put1_ret,
153                          int get1, int get1_ret, int put2, int put2_ret,
154                          int get2, int get2_ret)
155{
156    enum { ROUNDS = 2 };
157    size_t put[ROUNDS];
158    int put_ret[ROUNDS];
159    size_t get[ROUNDS];
160    int get_ret[ROUNDS];
161    mbedtls_test_ssl_buffer buf;
162    unsigned char *input = NULL;
163    size_t input_len;
164    unsigned char *output = NULL;
165    size_t output_len;
166    size_t i, j, written, read;
167
168    mbedtls_test_ssl_buffer_init(&buf);
169    USE_PSA_INIT();
170    TEST_ASSERT(mbedtls_test_ssl_buffer_setup(&buf, size) == 0);
171
172    /* Check the sanity of input parameters and initialise local variables. That
173     * is, ensure that the amount of data is not negative and that we are not
174     * expecting more to put or get than we actually asked for. */
175    TEST_ASSERT(put1 >= 0);
176    put[0] = put1;
177    put_ret[0] = put1_ret;
178    TEST_ASSERT(put1_ret <= put1);
179    TEST_ASSERT(put2 >= 0);
180    put[1] = put2;
181    put_ret[1] = put2_ret;
182    TEST_ASSERT(put2_ret <= put2);
183
184    TEST_ASSERT(get1 >= 0);
185    get[0] = get1;
186    get_ret[0] = get1_ret;
187    TEST_ASSERT(get1_ret <= get1);
188    TEST_ASSERT(get2 >= 0);
189    get[1] = get2;
190    get_ret[1] = get2_ret;
191    TEST_ASSERT(get2_ret <= get2);
192
193    input_len = 0;
194    /* Calculate actual input and output lengths */
195    for (j = 0; j < ROUNDS; j++) {
196        if (put_ret[j] > 0) {
197            input_len += put_ret[j];
198        }
199    }
200    /* In order to always have a valid pointer we always allocate at least 1
201     * byte. */
202    if (input_len == 0) {
203        input_len = 1;
204    }
205    TEST_CALLOC(input, input_len);
206
207    output_len = 0;
208    for (j = 0; j < ROUNDS; j++) {
209        if (get_ret[j] > 0) {
210            output_len += get_ret[j];
211        }
212    }
213    TEST_ASSERT(output_len <= input_len);
214    /* In order to always have a valid pointer we always allocate at least 1
215     * byte. */
216    if (output_len == 0) {
217        output_len = 1;
218    }
219    TEST_CALLOC(output, output_len);
220
221    /* Fill up the buffer with structured data so that unwanted changes
222     * can be detected */
223    for (i = 0; i < input_len; i++) {
224        input[i] = i & 0xFF;
225    }
226
227    written = read = 0;
228    for (j = 0; j < ROUNDS; j++) {
229        TEST_ASSERT(put_ret[j] == mbedtls_test_ssl_buffer_put(&buf,
230                                                              input + written, put[j]));
231        written += put_ret[j];
232        TEST_ASSERT(get_ret[j] == mbedtls_test_ssl_buffer_get(&buf,
233                                                              output + read, get[j]));
234        read += get_ret[j];
235        TEST_ASSERT(read <= written);
236        if (get_ret[j] > 0) {
237            TEST_ASSERT(memcmp(output + read - get_ret[j],
238                               input + read - get_ret[j], get_ret[j])
239                        == 0);
240        }
241    }
242
243exit:
244    mbedtls_free(input);
245    mbedtls_free(output);
246    mbedtls_test_ssl_buffer_free(&buf);
247    USE_PSA_DONE();
248}
249/* END_CASE */
250
251/*
252 * Test if the implementation of `mbedtls_test_mock_socket` related
253 * I/O functions is correct and works as expected on unconnected sockets.
254 */
255
256/* BEGIN_CASE */
257void ssl_mock_sanity()
258{
259    enum { MSGLEN = 105 };
260    unsigned char message[MSGLEN] = { 0 };
261    unsigned char received[MSGLEN] = { 0 };
262    mbedtls_test_mock_socket socket;
263
264    mbedtls_test_mock_socket_init(&socket);
265    USE_PSA_INIT();
266    TEST_ASSERT(mbedtls_test_mock_tcp_send_b(&socket, message, MSGLEN) < 0);
267    mbedtls_test_mock_socket_close(&socket);
268    mbedtls_test_mock_socket_init(&socket);
269    TEST_ASSERT(mbedtls_test_mock_tcp_recv_b(&socket, received, MSGLEN) < 0);
270    mbedtls_test_mock_socket_close(&socket);
271
272    mbedtls_test_mock_socket_init(&socket);
273    TEST_ASSERT(mbedtls_test_mock_tcp_send_nb(&socket, message, MSGLEN) < 0);
274    mbedtls_test_mock_socket_close(&socket);
275    mbedtls_test_mock_socket_init(&socket);
276    TEST_ASSERT(mbedtls_test_mock_tcp_recv_nb(&socket, received, MSGLEN) < 0);
277    mbedtls_test_mock_socket_close(&socket);
278
279exit:
280    mbedtls_test_mock_socket_close(&socket);
281    USE_PSA_DONE();
282}
283/* END_CASE */
284
285/*
286 * Test if the implementation of `mbedtls_test_mock_socket` related functions
287 * can send a single message from the client to the server.
288 */
289
290/* BEGIN_CASE */
291void ssl_mock_tcp(int blocking)
292{
293    enum { MSGLEN = 105 };
294    enum { BUFLEN = MSGLEN / 5 };
295    unsigned char message[MSGLEN];
296    unsigned char received[MSGLEN];
297    mbedtls_test_mock_socket client;
298    mbedtls_test_mock_socket server;
299    size_t written, read;
300    int send_ret, recv_ret;
301    mbedtls_ssl_send_t *send;
302    mbedtls_ssl_recv_t *recv;
303    unsigned i;
304
305    if (blocking == 0) {
306        send = mbedtls_test_mock_tcp_send_nb;
307        recv = mbedtls_test_mock_tcp_recv_nb;
308    } else {
309        send = mbedtls_test_mock_tcp_send_b;
310        recv = mbedtls_test_mock_tcp_recv_b;
311    }
312
313    mbedtls_test_mock_socket_init(&client);
314    mbedtls_test_mock_socket_init(&server);
315    USE_PSA_INIT();
316
317    /* Fill up the buffer with structured data so that unwanted changes
318     * can be detected */
319    for (i = 0; i < MSGLEN; i++) {
320        message[i] = i & 0xFF;
321    }
322
323    /* Make sure that sending a message takes a few  iterations. */
324    TEST_ASSERT(0 == mbedtls_test_mock_socket_connect(&client, &server,
325                                                      BUFLEN));
326
327    /* Send the message to the server */
328    send_ret = recv_ret = 1;
329    written = read = 0;
330    while (send_ret != 0 || recv_ret != 0) {
331        send_ret = send(&client, message + written, MSGLEN - written);
332
333        TEST_ASSERT(send_ret >= 0);
334        TEST_ASSERT(send_ret <= BUFLEN);
335        written += send_ret;
336
337        /* If the buffer is full we can test blocking and non-blocking send */
338        if (send_ret == BUFLEN) {
339            int blocking_ret = send(&client, message, 1);
340            if (blocking) {
341                TEST_ASSERT(blocking_ret == 0);
342            } else {
343                TEST_ASSERT(blocking_ret == MBEDTLS_ERR_SSL_WANT_WRITE);
344            }
345        }
346
347        recv_ret = recv(&server, received + read, MSGLEN - read);
348
349        /* The result depends on whether any data was sent */
350        if (send_ret > 0) {
351            TEST_ASSERT(recv_ret > 0);
352            TEST_ASSERT(recv_ret <= BUFLEN);
353            read += recv_ret;
354        } else if (blocking) {
355            TEST_ASSERT(recv_ret == 0);
356        } else {
357            TEST_ASSERT(recv_ret == MBEDTLS_ERR_SSL_WANT_READ);
358            recv_ret = 0;
359        }
360
361        /* If the buffer is empty we can test blocking and non-blocking read */
362        if (recv_ret == BUFLEN) {
363            int blocking_ret = recv(&server, received, 1);
364            if (blocking) {
365                TEST_ASSERT(blocking_ret == 0);
366            } else {
367                TEST_ASSERT(blocking_ret == MBEDTLS_ERR_SSL_WANT_READ);
368            }
369        }
370    }
371    TEST_ASSERT(memcmp(message, received, MSGLEN) == 0);
372
373exit:
374    mbedtls_test_mock_socket_close(&client);
375    mbedtls_test_mock_socket_close(&server);
376    USE_PSA_DONE();
377}
378/* END_CASE */
379
380/*
381 * Test if the implementation of `mbedtls_test_mock_socket` related functions
382 * can send messages in both direction at the same time (with the I/O calls
383 * interleaving).
384 */
385
386/* BEGIN_CASE */
387void ssl_mock_tcp_interleaving(int blocking)
388{
389    enum { ROUNDS = 2 };
390    enum { MSGLEN = 105 };
391    enum { BUFLEN = MSGLEN / 5 };
392    unsigned char message[ROUNDS][MSGLEN];
393    unsigned char received[ROUNDS][MSGLEN];
394    mbedtls_test_mock_socket client;
395    mbedtls_test_mock_socket server;
396    size_t written[ROUNDS];
397    size_t read[ROUNDS];
398    int send_ret[ROUNDS];
399    int recv_ret[ROUNDS];
400    unsigned i, j, progress;
401    mbedtls_ssl_send_t *send;
402    mbedtls_ssl_recv_t *recv;
403
404    if (blocking == 0) {
405        send = mbedtls_test_mock_tcp_send_nb;
406        recv = mbedtls_test_mock_tcp_recv_nb;
407    } else {
408        send = mbedtls_test_mock_tcp_send_b;
409        recv = mbedtls_test_mock_tcp_recv_b;
410    }
411
412    mbedtls_test_mock_socket_init(&client);
413    mbedtls_test_mock_socket_init(&server);
414    USE_PSA_INIT();
415
416    /* Fill up the buffers with structured data so that unwanted changes
417     * can be detected */
418    for (i = 0; i < ROUNDS; i++) {
419        for (j = 0; j < MSGLEN; j++) {
420            message[i][j] = (i * MSGLEN + j) & 0xFF;
421        }
422    }
423
424    /* Make sure that sending a message takes a few  iterations. */
425    TEST_ASSERT(0 == mbedtls_test_mock_socket_connect(&client, &server,
426                                                      BUFLEN));
427
428    /* Send the message from both sides, interleaving. */
429    progress = 1;
430    for (i = 0; i < ROUNDS; i++) {
431        written[i] = 0;
432        read[i] = 0;
433    }
434    /* This loop does not stop as long as there was a successful write or read
435     * of at least one byte on either side. */
436    while (progress != 0) {
437        mbedtls_test_mock_socket *socket;
438
439        for (i = 0; i < ROUNDS; i++) {
440            /* First sending is from the client */
441            socket = (i % 2 == 0) ? (&client) : (&server);
442
443            send_ret[i] = send(socket, message[i] + written[i],
444                               MSGLEN - written[i]);
445            TEST_ASSERT(send_ret[i] >= 0);
446            TEST_ASSERT(send_ret[i] <= BUFLEN);
447            written[i] += send_ret[i];
448
449            /* If the buffer is full we can test blocking and non-blocking
450             * send */
451            if (send_ret[i] == BUFLEN) {
452                int blocking_ret = send(socket, message[i], 1);
453                if (blocking) {
454                    TEST_ASSERT(blocking_ret == 0);
455                } else {
456                    TEST_ASSERT(blocking_ret == MBEDTLS_ERR_SSL_WANT_WRITE);
457                }
458            }
459        }
460
461        for (i = 0; i < ROUNDS; i++) {
462            /* First receiving is from the server */
463            socket = (i % 2 == 0) ? (&server) : (&client);
464
465            recv_ret[i] = recv(socket, received[i] + read[i],
466                               MSGLEN - read[i]);
467
468            /* The result depends on whether any data was sent */
469            if (send_ret[i] > 0) {
470                TEST_ASSERT(recv_ret[i] > 0);
471                TEST_ASSERT(recv_ret[i] <= BUFLEN);
472                read[i] += recv_ret[i];
473            } else if (blocking) {
474                TEST_ASSERT(recv_ret[i] == 0);
475            } else {
476                TEST_ASSERT(recv_ret[i] == MBEDTLS_ERR_SSL_WANT_READ);
477                recv_ret[i] = 0;
478            }
479
480            /* If the buffer is empty we can test blocking and non-blocking
481             * read */
482            if (recv_ret[i] == BUFLEN) {
483                int blocking_ret = recv(socket, received[i], 1);
484                if (blocking) {
485                    TEST_ASSERT(blocking_ret == 0);
486                } else {
487                    TEST_ASSERT(blocking_ret == MBEDTLS_ERR_SSL_WANT_READ);
488                }
489            }
490        }
491
492        progress = 0;
493        for (i = 0; i < ROUNDS; i++) {
494            progress += send_ret[i] + recv_ret[i];
495        }
496    }
497
498    for (i = 0; i < ROUNDS; i++) {
499        TEST_ASSERT(memcmp(message[i], received[i], MSGLEN) == 0);
500    }
501
502exit:
503    mbedtls_test_mock_socket_close(&client);
504    mbedtls_test_mock_socket_close(&server);
505    USE_PSA_DONE();
506}
507/* END_CASE */
508
509/* BEGIN_CASE */
510void ssl_message_queue_sanity()
511{
512    mbedtls_test_ssl_message_queue queue = SSL_MESSAGE_QUEUE_INIT;
513
514    USE_PSA_INIT();
515    /* Trying to push/pull to an empty queue */
516    TEST_ASSERT(mbedtls_test_ssl_message_queue_push_info(NULL, 1)
517                == MBEDTLS_TEST_ERROR_ARG_NULL);
518    TEST_ASSERT(mbedtls_test_ssl_message_queue_pop_info(NULL, 1)
519                == MBEDTLS_TEST_ERROR_ARG_NULL);
520
521    TEST_ASSERT(mbedtls_test_ssl_message_queue_setup(&queue, 3) == 0);
522    TEST_ASSERT(queue.capacity == 3);
523    TEST_ASSERT(queue.num == 0);
524
525exit:
526    mbedtls_test_ssl_message_queue_free(&queue);
527    USE_PSA_DONE();
528}
529/* END_CASE */
530
531/* BEGIN_CASE */
532void ssl_message_queue_basic()
533{
534    mbedtls_test_ssl_message_queue queue = SSL_MESSAGE_QUEUE_INIT;
535
536    USE_PSA_INIT();
537    TEST_ASSERT(mbedtls_test_ssl_message_queue_setup(&queue, 3) == 0);
538
539    /* Sanity test - 3 pushes and 3 pops with sufficient space */
540    TEST_ASSERT(mbedtls_test_ssl_message_queue_push_info(&queue, 1) == 1);
541    TEST_ASSERT(queue.capacity == 3);
542    TEST_ASSERT(queue.num == 1);
543    TEST_ASSERT(mbedtls_test_ssl_message_queue_push_info(&queue, 1) == 1);
544    TEST_ASSERT(queue.capacity == 3);
545    TEST_ASSERT(queue.num == 2);
546    TEST_ASSERT(mbedtls_test_ssl_message_queue_push_info(&queue, 2) == 2);
547    TEST_ASSERT(queue.capacity == 3);
548    TEST_ASSERT(queue.num == 3);
549
550    TEST_ASSERT(mbedtls_test_ssl_message_queue_pop_info(&queue, 1) == 1);
551    TEST_ASSERT(mbedtls_test_ssl_message_queue_pop_info(&queue, 1) == 1);
552    TEST_ASSERT(mbedtls_test_ssl_message_queue_pop_info(&queue, 2) == 2);
553
554exit:
555    mbedtls_test_ssl_message_queue_free(&queue);
556    USE_PSA_DONE();
557}
558/* END_CASE */
559
560/* BEGIN_CASE */
561void ssl_message_queue_overflow_underflow()
562{
563    mbedtls_test_ssl_message_queue queue = SSL_MESSAGE_QUEUE_INIT;
564
565    USE_PSA_INIT();
566    TEST_ASSERT(mbedtls_test_ssl_message_queue_setup(&queue, 3) == 0);
567
568    /* 4 pushes (last one with an error), 4 pops (last one with an error) */
569    TEST_ASSERT(mbedtls_test_ssl_message_queue_push_info(&queue, 1) == 1);
570    TEST_ASSERT(mbedtls_test_ssl_message_queue_push_info(&queue, 1) == 1);
571    TEST_ASSERT(mbedtls_test_ssl_message_queue_push_info(&queue, 2) == 2);
572    TEST_ASSERT(mbedtls_test_ssl_message_queue_push_info(&queue, 3)
573                == MBEDTLS_ERR_SSL_WANT_WRITE);
574
575    TEST_ASSERT(mbedtls_test_ssl_message_queue_pop_info(&queue, 1) == 1);
576    TEST_ASSERT(mbedtls_test_ssl_message_queue_pop_info(&queue, 1) == 1);
577    TEST_ASSERT(mbedtls_test_ssl_message_queue_pop_info(&queue, 2) == 2);
578
579    TEST_ASSERT(mbedtls_test_ssl_message_queue_pop_info(&queue, 1)
580                == MBEDTLS_ERR_SSL_WANT_READ);
581
582exit:
583    mbedtls_test_ssl_message_queue_free(&queue);
584    USE_PSA_DONE();
585}
586/* END_CASE */
587
588/* BEGIN_CASE */
589void ssl_message_queue_interleaved()
590{
591    mbedtls_test_ssl_message_queue queue = SSL_MESSAGE_QUEUE_INIT;
592
593    USE_PSA_INIT();
594    TEST_ASSERT(mbedtls_test_ssl_message_queue_setup(&queue, 3) == 0);
595
596    /* Interleaved test - [2 pushes, 1 pop] twice, and then two pops
597     * (to wrap around the buffer) */
598    TEST_ASSERT(mbedtls_test_ssl_message_queue_push_info(&queue, 1) == 1);
599    TEST_ASSERT(mbedtls_test_ssl_message_queue_push_info(&queue, 1) == 1);
600
601    TEST_ASSERT(mbedtls_test_ssl_message_queue_pop_info(&queue, 1) == 1);
602
603    TEST_ASSERT(mbedtls_test_ssl_message_queue_push_info(&queue, 2) == 2);
604    TEST_ASSERT(mbedtls_test_ssl_message_queue_push_info(&queue, 3) == 3);
605
606    TEST_ASSERT(mbedtls_test_ssl_message_queue_pop_info(&queue, 1) == 1);
607    TEST_ASSERT(mbedtls_test_ssl_message_queue_pop_info(&queue, 2) == 2);
608
609    TEST_ASSERT(mbedtls_test_ssl_message_queue_push_info(&queue, 5) == 5);
610    TEST_ASSERT(mbedtls_test_ssl_message_queue_push_info(&queue, 8) == 8);
611
612    TEST_ASSERT(mbedtls_test_ssl_message_queue_pop_info(&queue, 3) == 3);
613
614    TEST_ASSERT(mbedtls_test_ssl_message_queue_pop_info(&queue, 5) == 5);
615
616    TEST_ASSERT(mbedtls_test_ssl_message_queue_pop_info(&queue, 8) == 8);
617
618exit:
619    mbedtls_test_ssl_message_queue_free(&queue);
620    USE_PSA_DONE();
621}
622/* END_CASE */
623
624/* BEGIN_CASE */
625void ssl_message_queue_insufficient_buffer()
626{
627    mbedtls_test_ssl_message_queue queue = SSL_MESSAGE_QUEUE_INIT;
628    size_t message_len = 10;
629    size_t buffer_len = 5;
630
631    USE_PSA_INIT();
632    TEST_ASSERT(mbedtls_test_ssl_message_queue_setup(&queue, 1) == 0);
633
634    /* Popping without a sufficient buffer */
635    TEST_ASSERT(mbedtls_test_ssl_message_queue_push_info(&queue, message_len)
636                == (int) message_len);
637    TEST_ASSERT(mbedtls_test_ssl_message_queue_pop_info(&queue, buffer_len)
638                == (int) buffer_len);
639exit:
640    mbedtls_test_ssl_message_queue_free(&queue);
641    USE_PSA_DONE();
642}
643/* END_CASE */
644
645/* BEGIN_CASE */
646void ssl_message_mock_uninitialized()
647{
648    enum { MSGLEN = 10 };
649    unsigned char message[MSGLEN] = { 0 }, received[MSGLEN];
650    mbedtls_test_mock_socket client, server;
651    mbedtls_test_ssl_message_queue server_queue, client_queue;
652    mbedtls_test_message_socket_context server_context, client_context;
653    mbedtls_test_message_socket_init(&server_context);
654    mbedtls_test_message_socket_init(&client_context);
655
656    USE_PSA_INIT();
657    /* Send with a NULL context */
658    TEST_ASSERT(mbedtls_test_mock_tcp_send_msg(NULL, message, MSGLEN)
659                == MBEDTLS_TEST_ERROR_CONTEXT_ERROR);
660
661    TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(NULL, message, MSGLEN)
662                == MBEDTLS_TEST_ERROR_CONTEXT_ERROR);
663
664    TEST_ASSERT(mbedtls_test_message_socket_setup(&server_queue,
665                                                  &client_queue, 1,
666                                                  &server,
667                                                  &server_context) == 0);
668
669    TEST_ASSERT(mbedtls_test_message_socket_setup(&client_queue,
670                                                  &server_queue, 1,
671                                                  &client,
672                                                  &client_context) == 0);
673
674    TEST_ASSERT(mbedtls_test_mock_tcp_send_msg(&client_context, message,
675                                               MSGLEN)
676                == MBEDTLS_TEST_ERROR_SEND_FAILED);
677
678    TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&server_context, received,
679                                               MSGLEN)
680                == MBEDTLS_ERR_SSL_WANT_READ);
681
682    /* Push directly to a queue to later simulate a disconnected behavior */
683    TEST_ASSERT(mbedtls_test_ssl_message_queue_push_info(&server_queue,
684                                                         MSGLEN)
685                == MSGLEN);
686
687    /* Test if there's an error when trying to read from a disconnected
688     * socket */
689    TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&server_context, received,
690                                               MSGLEN)
691                == MBEDTLS_TEST_ERROR_RECV_FAILED);
692exit:
693    mbedtls_test_message_socket_close(&server_context);
694    mbedtls_test_message_socket_close(&client_context);
695    USE_PSA_DONE();
696}
697/* END_CASE */
698
699/* BEGIN_CASE */
700void ssl_message_mock_basic()
701{
702    enum { MSGLEN = 10 };
703    unsigned char message[MSGLEN], received[MSGLEN];
704    mbedtls_test_mock_socket client, server;
705    unsigned i;
706    mbedtls_test_ssl_message_queue server_queue, client_queue;
707    mbedtls_test_message_socket_context server_context, client_context;
708
709    mbedtls_test_message_socket_init(&server_context);
710    mbedtls_test_message_socket_init(&client_context);
711    USE_PSA_INIT();
712
713    TEST_ASSERT(mbedtls_test_message_socket_setup(&server_queue,
714                                                  &client_queue, 1,
715                                                  &server,
716                                                  &server_context) == 0);
717
718    TEST_ASSERT(mbedtls_test_message_socket_setup(&client_queue,
719                                                  &server_queue, 1,
720                                                  &client,
721                                                  &client_context) == 0);
722
723    /* Fill up the buffer with structured data so that unwanted changes
724     * can be detected */
725    for (i = 0; i < MSGLEN; i++) {
726        message[i] = i & 0xFF;
727    }
728    TEST_ASSERT(0 == mbedtls_test_mock_socket_connect(&client, &server,
729                                                      MSGLEN));
730
731    /* Send the message to the server */
732    TEST_ASSERT(mbedtls_test_mock_tcp_send_msg(&client_context, message,
733                                               MSGLEN) == MSGLEN);
734
735    /* Read from the server */
736    TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&server_context, received,
737                                               MSGLEN)
738                == MSGLEN);
739
740    TEST_ASSERT(memcmp(message, received, MSGLEN) == 0);
741    memset(received, 0, MSGLEN);
742
743    /* Send the message to the client */
744    TEST_ASSERT(mbedtls_test_mock_tcp_send_msg(&server_context, message,
745                                               MSGLEN)
746                == MSGLEN);
747
748    /* Read from the client */
749    TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&client_context, received,
750                                               MSGLEN)
751                == MSGLEN);
752    TEST_ASSERT(memcmp(message, received, MSGLEN) == 0);
753
754exit:
755    mbedtls_test_message_socket_close(&server_context);
756    mbedtls_test_message_socket_close(&client_context);
757    USE_PSA_DONE();
758}
759/* END_CASE */
760
761/* BEGIN_CASE */
762void ssl_message_mock_queue_overflow_underflow()
763{
764    enum { MSGLEN = 10 };
765    unsigned char message[MSGLEN], received[MSGLEN];
766    mbedtls_test_mock_socket client, server;
767    unsigned i;
768    mbedtls_test_ssl_message_queue server_queue, client_queue;
769    mbedtls_test_message_socket_context server_context, client_context;
770
771    mbedtls_test_message_socket_init(&server_context);
772    mbedtls_test_message_socket_init(&client_context);
773    USE_PSA_INIT();
774
775    TEST_ASSERT(mbedtls_test_message_socket_setup(&server_queue,
776                                                  &client_queue, 2,
777                                                  &server,
778                                                  &server_context) == 0);
779
780    TEST_ASSERT(mbedtls_test_message_socket_setup(&client_queue,
781                                                  &server_queue, 2,
782                                                  &client,
783                                                  &client_context) == 0);
784
785    /* Fill up the buffer with structured data so that unwanted changes
786     * can be detected */
787    for (i = 0; i < MSGLEN; i++) {
788        message[i] = i & 0xFF;
789    }
790    TEST_ASSERT(0 == mbedtls_test_mock_socket_connect(&client, &server,
791                                                      MSGLEN*2));
792
793    /* Send three message to the server, last one with an error */
794    TEST_ASSERT(mbedtls_test_mock_tcp_send_msg(&client_context, message,
795                                               MSGLEN - 1)
796                == MSGLEN - 1);
797
798    TEST_ASSERT(mbedtls_test_mock_tcp_send_msg(&client_context, message,
799                                               MSGLEN)
800                == MSGLEN);
801
802    TEST_ASSERT(mbedtls_test_mock_tcp_send_msg(&client_context, message,
803                                               MSGLEN)
804                == MBEDTLS_ERR_SSL_WANT_WRITE);
805
806    /* Read three messages from the server, last one with an error */
807    TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&server_context, received,
808                                               MSGLEN - 1)
809                == MSGLEN - 1);
810
811    TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&server_context, received,
812                                               MSGLEN)
813                == MSGLEN);
814
815    TEST_ASSERT(memcmp(message, received, MSGLEN) == 0);
816
817    TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&server_context, received,
818                                               MSGLEN)
819                == MBEDTLS_ERR_SSL_WANT_READ);
820
821exit:
822    mbedtls_test_message_socket_close(&server_context);
823    mbedtls_test_message_socket_close(&client_context);
824    USE_PSA_DONE();
825}
826/* END_CASE */
827
828/* BEGIN_CASE */
829void ssl_message_mock_socket_overflow()
830{
831    enum { MSGLEN = 10 };
832    unsigned char message[MSGLEN], received[MSGLEN];
833    mbedtls_test_mock_socket client, server;
834    unsigned i;
835    mbedtls_test_ssl_message_queue server_queue, client_queue;
836    mbedtls_test_message_socket_context server_context, client_context;
837
838    mbedtls_test_message_socket_init(&server_context);
839    mbedtls_test_message_socket_init(&client_context);
840    USE_PSA_INIT();
841
842    TEST_ASSERT(mbedtls_test_message_socket_setup(&server_queue,
843                                                  &client_queue, 2,
844                                                  &server,
845                                                  &server_context) == 0);
846
847    TEST_ASSERT(mbedtls_test_message_socket_setup(&client_queue,
848                                                  &server_queue, 2,
849                                                  &client,
850                                                  &client_context) == 0);
851
852    /* Fill up the buffer with structured data so that unwanted changes
853     * can be detected */
854    for (i = 0; i < MSGLEN; i++) {
855        message[i] = i & 0xFF;
856    }
857    TEST_ASSERT(0 == mbedtls_test_mock_socket_connect(&client, &server,
858                                                      MSGLEN));
859
860    /* Send two message to the server, second one with an error */
861    TEST_ASSERT(mbedtls_test_mock_tcp_send_msg(&client_context, message,
862                                               MSGLEN)
863                == MSGLEN);
864
865    TEST_ASSERT(mbedtls_test_mock_tcp_send_msg(&client_context, message,
866                                               MSGLEN)
867                == MBEDTLS_TEST_ERROR_SEND_FAILED);
868
869    /* Read the only message from the server */
870    TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&server_context, received,
871                                               MSGLEN)
872                == MSGLEN);
873
874    TEST_ASSERT(memcmp(message, received, MSGLEN) == 0);
875
876exit:
877    mbedtls_test_message_socket_close(&server_context);
878    mbedtls_test_message_socket_close(&client_context);
879    USE_PSA_DONE();
880}
881/* END_CASE */
882
883/* BEGIN_CASE */
884void ssl_message_mock_truncated()
885{
886    enum { MSGLEN = 10 };
887    unsigned char message[MSGLEN], received[MSGLEN];
888    mbedtls_test_mock_socket client, server;
889    unsigned i;
890    mbedtls_test_ssl_message_queue server_queue, client_queue;
891    mbedtls_test_message_socket_context server_context, client_context;
892
893    mbedtls_test_message_socket_init(&server_context);
894    mbedtls_test_message_socket_init(&client_context);
895    USE_PSA_INIT();
896
897    TEST_ASSERT(mbedtls_test_message_socket_setup(&server_queue,
898                                                  &client_queue, 2,
899                                                  &server,
900                                                  &server_context) == 0);
901
902    TEST_ASSERT(mbedtls_test_message_socket_setup(&client_queue,
903                                                  &server_queue, 2,
904                                                  &client,
905                                                  &client_context) == 0);
906
907    memset(received, 0, MSGLEN);
908    /* Fill up the buffer with structured data so that unwanted changes
909     * can be detected */
910    for (i = 0; i < MSGLEN; i++) {
911        message[i] = i & 0xFF;
912    }
913    TEST_ASSERT(0 == mbedtls_test_mock_socket_connect(&client, &server,
914                                                      2 * MSGLEN));
915
916    /* Send two messages to the server, the second one small enough to fit in the
917     * receiver's buffer. */
918    TEST_ASSERT(mbedtls_test_mock_tcp_send_msg(&client_context, message,
919                                               MSGLEN)
920                == MSGLEN);
921    TEST_ASSERT(mbedtls_test_mock_tcp_send_msg(&client_context, message,
922                                               MSGLEN / 2)
923                == MSGLEN / 2);
924    /* Read a truncated message from the server */
925    TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&server_context, received,
926                                               MSGLEN/2)
927                == MSGLEN/2);
928
929    /* Test that the first half of the message is valid, and second one isn't */
930    TEST_ASSERT(memcmp(message, received, MSGLEN/2) == 0);
931    TEST_ASSERT(memcmp(message + MSGLEN/2, received + MSGLEN/2, MSGLEN/2)
932                != 0);
933    memset(received, 0, MSGLEN);
934
935    /* Read a full message from the server */
936    TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&server_context, received,
937                                               MSGLEN/2)
938                == MSGLEN / 2);
939
940    /* Test that the first half of the message is valid */
941    TEST_ASSERT(memcmp(message, received, MSGLEN/2) == 0);
942
943exit:
944    mbedtls_test_message_socket_close(&server_context);
945    mbedtls_test_message_socket_close(&client_context);
946    USE_PSA_DONE();
947}
948/* END_CASE */
949
950/* BEGIN_CASE */
951void ssl_message_mock_socket_read_error()
952{
953    enum { MSGLEN = 10 };
954    unsigned char message[MSGLEN], received[MSGLEN];
955    mbedtls_test_mock_socket client, server;
956    unsigned i;
957    mbedtls_test_ssl_message_queue server_queue, client_queue;
958    mbedtls_test_message_socket_context server_context, client_context;
959
960    mbedtls_test_message_socket_init(&server_context);
961    mbedtls_test_message_socket_init(&client_context);
962    USE_PSA_INIT();
963
964    TEST_ASSERT(mbedtls_test_message_socket_setup(&server_queue,
965                                                  &client_queue, 1,
966                                                  &server,
967                                                  &server_context) == 0);
968
969    TEST_ASSERT(mbedtls_test_message_socket_setup(&client_queue,
970                                                  &server_queue, 1,
971                                                  &client,
972                                                  &client_context) == 0);
973
974    /* Fill up the buffer with structured data so that unwanted changes
975     * can be detected */
976    for (i = 0; i < MSGLEN; i++) {
977        message[i] = i & 0xFF;
978    }
979    TEST_ASSERT(0 == mbedtls_test_mock_socket_connect(&client, &server,
980                                                      MSGLEN));
981
982    TEST_ASSERT(mbedtls_test_mock_tcp_send_msg(&client_context, message,
983                                               MSGLEN)
984                == MSGLEN);
985
986    /* Force a read error by disconnecting the socket by hand */
987    server.status = 0;
988    TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&server_context, received,
989                                               MSGLEN)
990                == MBEDTLS_TEST_ERROR_RECV_FAILED);
991    /* Return to a valid state */
992    server.status = MBEDTLS_MOCK_SOCKET_CONNECTED;
993
994    memset(received, 0, sizeof(received));
995
996    /* Test that even though the server tried to read once disconnected, the
997     * continuity is preserved */
998    TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&server_context, received,
999                                               MSGLEN)
1000                == MSGLEN);
1001
1002    TEST_ASSERT(memcmp(message, received, MSGLEN) == 0);
1003
1004exit:
1005    mbedtls_test_message_socket_close(&server_context);
1006    mbedtls_test_message_socket_close(&client_context);
1007    USE_PSA_DONE();
1008}
1009/* END_CASE */
1010
1011/* BEGIN_CASE */
1012void ssl_message_mock_interleaved_one_way()
1013{
1014    enum { MSGLEN = 10 };
1015    unsigned char message[MSGLEN], received[MSGLEN];
1016    mbedtls_test_mock_socket client, server;
1017    unsigned i;
1018    mbedtls_test_ssl_message_queue server_queue, client_queue;
1019    mbedtls_test_message_socket_context server_context, client_context;
1020
1021    mbedtls_test_message_socket_init(&server_context);
1022    mbedtls_test_message_socket_init(&client_context);
1023    USE_PSA_INIT();
1024
1025    TEST_ASSERT(mbedtls_test_message_socket_setup(&server_queue,
1026                                                  &client_queue, 3,
1027                                                  &server,
1028                                                  &server_context) == 0);
1029
1030    TEST_ASSERT(mbedtls_test_message_socket_setup(&client_queue,
1031                                                  &server_queue, 3,
1032                                                  &client,
1033                                                  &client_context) == 0);
1034
1035    /* Fill up the buffer with structured data so that unwanted changes
1036     * can be detected */
1037    for (i = 0; i < MSGLEN; i++) {
1038        message[i] = i & 0xFF;
1039    }
1040    TEST_ASSERT(0 == mbedtls_test_mock_socket_connect(&client, &server,
1041                                                      MSGLEN*3));
1042
1043    /* Interleaved test - [2 sends, 1 read] twice, and then two reads
1044     * (to wrap around the buffer) */
1045    for (i = 0; i < 2; i++) {
1046        TEST_ASSERT(mbedtls_test_mock_tcp_send_msg(&client_context, message,
1047                                                   MSGLEN) == MSGLEN);
1048
1049        TEST_ASSERT(mbedtls_test_mock_tcp_send_msg(&client_context, message,
1050                                                   MSGLEN) == MSGLEN);
1051
1052        TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&server_context, received,
1053                                                   MSGLEN) == MSGLEN);
1054        TEST_ASSERT(memcmp(message, received, MSGLEN) == 0);
1055        memset(received, 0, sizeof(received));
1056    }
1057
1058    for (i = 0; i < 2; i++) {
1059        TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&server_context, received,
1060                                                   MSGLEN) == MSGLEN);
1061
1062        TEST_ASSERT(memcmp(message, received, MSGLEN) == 0);
1063    }
1064    TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&server_context, received,
1065                                               MSGLEN)
1066                == MBEDTLS_ERR_SSL_WANT_READ);
1067exit:
1068    mbedtls_test_message_socket_close(&server_context);
1069    mbedtls_test_message_socket_close(&client_context);
1070    USE_PSA_DONE();
1071}
1072/* END_CASE */
1073
1074/* BEGIN_CASE */
1075void ssl_message_mock_interleaved_two_ways()
1076{
1077    enum { MSGLEN = 10 };
1078    unsigned char message[MSGLEN], received[MSGLEN];
1079    mbedtls_test_mock_socket client, server;
1080    unsigned i;
1081    mbedtls_test_ssl_message_queue server_queue, client_queue;
1082    mbedtls_test_message_socket_context server_context, client_context;
1083
1084    mbedtls_test_message_socket_init(&server_context);
1085    mbedtls_test_message_socket_init(&client_context);
1086    USE_PSA_INIT();
1087
1088    TEST_ASSERT(mbedtls_test_message_socket_setup(&server_queue,
1089                                                  &client_queue, 3,
1090                                                  &server,
1091                                                  &server_context) == 0);
1092
1093    TEST_ASSERT(mbedtls_test_message_socket_setup(&client_queue,
1094                                                  &server_queue, 3,
1095                                                  &client,
1096                                                  &client_context) == 0);
1097
1098    /* Fill up the buffer with structured data so that unwanted changes
1099     * can be detected */
1100    for (i = 0; i < MSGLEN; i++) {
1101        message[i] = i & 0xFF;
1102    }
1103    TEST_ASSERT(0 == mbedtls_test_mock_socket_connect(&client, &server,
1104                                                      MSGLEN*3));
1105
1106    /* Interleaved test - [2 sends, 1 read] twice, both ways, and then two reads
1107     * (to wrap around the buffer) both ways. */
1108    for (i = 0; i < 2; i++) {
1109        TEST_ASSERT(mbedtls_test_mock_tcp_send_msg(&client_context, message,
1110                                                   MSGLEN) == MSGLEN);
1111
1112        TEST_ASSERT(mbedtls_test_mock_tcp_send_msg(&client_context, message,
1113                                                   MSGLEN) == MSGLEN);
1114
1115        TEST_ASSERT(mbedtls_test_mock_tcp_send_msg(&server_context, message,
1116                                                   MSGLEN) == MSGLEN);
1117
1118        TEST_ASSERT(mbedtls_test_mock_tcp_send_msg(&server_context, message,
1119                                                   MSGLEN) == MSGLEN);
1120
1121        TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&server_context, received,
1122                                                   MSGLEN) == MSGLEN);
1123
1124        TEST_ASSERT(memcmp(message, received, MSGLEN) == 0);
1125
1126        memset(received, 0, sizeof(received));
1127
1128        TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&client_context, received,
1129                                                   MSGLEN) == MSGLEN);
1130
1131        TEST_ASSERT(memcmp(message, received, MSGLEN) == 0);
1132
1133        memset(received, 0, sizeof(received));
1134    }
1135
1136    for (i = 0; i < 2; i++) {
1137        TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&server_context, received,
1138                                                   MSGLEN) == MSGLEN);
1139
1140        TEST_ASSERT(memcmp(message, received, MSGLEN) == 0);
1141        memset(received, 0, sizeof(received));
1142
1143        TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&client_context, received,
1144                                                   MSGLEN) == MSGLEN);
1145
1146        TEST_ASSERT(memcmp(message, received, MSGLEN) == 0);
1147        memset(received, 0, sizeof(received));
1148    }
1149
1150    TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&server_context, received,
1151                                               MSGLEN)
1152                == MBEDTLS_ERR_SSL_WANT_READ);
1153
1154    TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&client_context, received,
1155                                               MSGLEN)
1156                == MBEDTLS_ERR_SSL_WANT_READ);
1157exit:
1158    mbedtls_test_message_socket_close(&server_context);
1159    mbedtls_test_message_socket_close(&client_context);
1160    USE_PSA_DONE();
1161}
1162/* END_CASE */
1163
1164/* BEGIN_CASE depends_on:MBEDTLS_SSL_DTLS_ANTI_REPLAY */
1165void ssl_dtls_replay(data_t *prevs, data_t *new, int ret)
1166{
1167    uint32_t len = 0;
1168    mbedtls_ssl_context ssl;
1169    mbedtls_ssl_config conf;
1170
1171    mbedtls_ssl_init(&ssl);
1172    mbedtls_ssl_config_init(&conf);
1173    MD_OR_USE_PSA_INIT();
1174
1175    TEST_ASSERT(mbedtls_ssl_config_defaults(&conf,
1176                                            MBEDTLS_SSL_IS_CLIENT,
1177                                            MBEDTLS_SSL_TRANSPORT_DATAGRAM,
1178                                            MBEDTLS_SSL_PRESET_DEFAULT) == 0);
1179    mbedtls_ssl_conf_rng(&conf, mbedtls_test_random, NULL);
1180
1181    TEST_ASSERT(mbedtls_ssl_setup(&ssl, &conf) == 0);
1182
1183    /* Read previous record numbers */
1184    for (len = 0; len < prevs->len; len += 6) {
1185        memcpy(ssl.in_ctr + 2, prevs->x + len, 6);
1186        mbedtls_ssl_dtls_replay_update(&ssl);
1187    }
1188
1189    /* Check new number */
1190    memcpy(ssl.in_ctr + 2, new->x, 6);
1191    TEST_ASSERT(mbedtls_ssl_dtls_replay_check(&ssl) == ret);
1192
1193exit:
1194    mbedtls_ssl_free(&ssl);
1195    mbedtls_ssl_config_free(&conf);
1196    MD_OR_USE_PSA_DONE();
1197}
1198/* END_CASE */
1199
1200/* BEGIN_CASE depends_on:MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
1201void ssl_set_hostname_twice(char *input_hostname0, char *input_hostname1)
1202{
1203    const char *output_hostname;
1204    mbedtls_ssl_context ssl;
1205
1206    mbedtls_ssl_init(&ssl);
1207    USE_PSA_INIT();
1208
1209    TEST_ASSERT(mbedtls_ssl_set_hostname(&ssl, input_hostname0) == 0);
1210    output_hostname = mbedtls_ssl_get_hostname(&ssl);
1211    TEST_ASSERT(strcmp(input_hostname0, output_hostname) == 0);
1212
1213    TEST_ASSERT(mbedtls_ssl_set_hostname(&ssl, input_hostname1) == 0);
1214    output_hostname = mbedtls_ssl_get_hostname(&ssl);
1215    TEST_ASSERT(strcmp(input_hostname1, output_hostname) == 0);
1216
1217exit:
1218    mbedtls_ssl_free(&ssl);
1219    USE_PSA_DONE();
1220}
1221/* END_CASE */
1222
1223/* BEGIN_CASE */
1224void ssl_crypt_record(int cipher_type, int hash_id,
1225                      int etm, int tag_mode, int ver,
1226                      int cid0_len, int cid1_len)
1227{
1228    /*
1229     * Test several record encryptions and decryptions
1230     * with plenty of space before and after the data
1231     * within the record buffer.
1232     */
1233
1234    int ret;
1235    int num_records = 16;
1236    mbedtls_ssl_context ssl; /* ONLY for debugging */
1237
1238    mbedtls_ssl_transform t0, t1;
1239    unsigned char *buf = NULL;
1240    size_t const buflen = 512;
1241    mbedtls_record rec, rec_backup;
1242
1243    mbedtls_ssl_init(&ssl);
1244    mbedtls_ssl_transform_init(&t0);
1245    mbedtls_ssl_transform_init(&t1);
1246    MD_OR_USE_PSA_INIT();
1247
1248    ret = mbedtls_test_ssl_build_transforms(&t0, &t1, cipher_type, hash_id,
1249                                            etm, tag_mode, ver,
1250                                            (size_t) cid0_len,
1251                                            (size_t) cid1_len);
1252
1253    TEST_ASSERT(ret == 0);
1254
1255    TEST_CALLOC(buf, buflen);
1256
1257    while (num_records-- > 0) {
1258        mbedtls_ssl_transform *t_dec, *t_enc;
1259        /* Take turns in who's sending and who's receiving. */
1260        if (num_records % 3 == 0) {
1261            t_dec = &t0;
1262            t_enc = &t1;
1263        } else {
1264            t_dec = &t1;
1265            t_enc = &t0;
1266        }
1267
1268        /*
1269         * The record header affects the transformation in two ways:
1270         * 1) It determines the AEAD additional data
1271         * 2) The record counter sometimes determines the IV.
1272         *
1273         * Apart from that, the fields don't have influence.
1274         * In particular, it is currently not the responsibility
1275         * of ssl_encrypt/decrypt_buf to check if the transform
1276         * version matches the record version, or that the
1277         * type is sensible.
1278         */
1279
1280        memset(rec.ctr, num_records, sizeof(rec.ctr));
1281        rec.type    = 42;
1282        rec.ver[0]  = num_records;
1283        rec.ver[1]  = num_records;
1284#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
1285        rec.cid_len = 0;
1286#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1287
1288        rec.buf     = buf;
1289        rec.buf_len = buflen;
1290        rec.data_offset = 16;
1291        /* Make sure to vary the length to exercise different
1292         * paddings. */
1293        rec.data_len = 1 + num_records;
1294
1295        memset(rec.buf + rec.data_offset, 42, rec.data_len);
1296
1297        /* Make a copy for later comparison */
1298        rec_backup = rec;
1299
1300        /* Encrypt record */
1301        ret = mbedtls_ssl_encrypt_buf(&ssl, t_enc, &rec,
1302                                      mbedtls_test_rnd_std_rand, NULL);
1303        TEST_ASSERT(ret == 0 || ret == MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL);
1304        if (ret != 0) {
1305            continue;
1306        }
1307
1308#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
1309        if (rec.cid_len != 0) {
1310            /* DTLS 1.2 + CID hides the real content type and
1311             * uses a special CID content type in the protected
1312             * record. Double-check this. */
1313            TEST_ASSERT(rec.type == MBEDTLS_SSL_MSG_CID);
1314        }
1315#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1316
1317#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
1318        if (t_enc->tls_version == MBEDTLS_SSL_VERSION_TLS1_3) {
1319            /* TLS 1.3 hides the real content type and
1320             * always uses Application Data as the content type
1321             * for protected records. Double-check this. */
1322            TEST_ASSERT(rec.type == MBEDTLS_SSL_MSG_APPLICATION_DATA);
1323        }
1324#endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
1325
1326        /* Decrypt record with t_dec */
1327        ret = mbedtls_ssl_decrypt_buf(&ssl, t_dec, &rec);
1328        TEST_ASSERT(ret == 0);
1329
1330        /* Compare results */
1331        TEST_ASSERT(rec.type == rec_backup.type);
1332        TEST_ASSERT(memcmp(rec.ctr, rec_backup.ctr, 8) == 0);
1333        TEST_ASSERT(rec.ver[0] == rec_backup.ver[0]);
1334        TEST_ASSERT(rec.ver[1] == rec_backup.ver[1]);
1335        TEST_ASSERT(rec.data_len == rec_backup.data_len);
1336        TEST_ASSERT(rec.data_offset == rec_backup.data_offset);
1337        TEST_ASSERT(memcmp(rec.buf + rec.data_offset,
1338                           rec_backup.buf + rec_backup.data_offset,
1339                           rec.data_len) == 0);
1340    }
1341
1342exit:
1343
1344    /* Cleanup */
1345    mbedtls_ssl_free(&ssl);
1346    mbedtls_ssl_transform_free(&t0);
1347    mbedtls_ssl_transform_free(&t1);
1348
1349    mbedtls_free(buf);
1350    MD_OR_USE_PSA_DONE();
1351}
1352/* END_CASE */
1353
1354/* BEGIN_CASE */
1355void ssl_crypt_record_small(int cipher_type, int hash_id,
1356                            int etm, int tag_mode, int ver,
1357                            int cid0_len, int cid1_len)
1358{
1359    /*
1360     * Test pairs of encryption and decryption with an increasing
1361     * amount of space in the record buffer - in more detail:
1362     * 1) Try to encrypt with 0, 1, 2, ... bytes available
1363     *    in front of the plaintext, and expect the encryption
1364     *    to succeed starting from some offset. Always keep
1365     *    enough space in the end of the buffer.
1366     * 2) Try to encrypt with 0, 1, 2, ... bytes available
1367     *    at the end of the plaintext, and expect the encryption
1368     *    to succeed starting from some offset. Always keep
1369     *    enough space at the beginning of the buffer.
1370     * 3) Try to encrypt with 0, 1, 2, ... bytes available
1371     *    both at the front and end of the plaintext,
1372     *    and expect the encryption to succeed starting from
1373     *    some offset.
1374     *
1375     * If encryption succeeds, check that decryption succeeds
1376     * and yields the original record.
1377     */
1378
1379    mbedtls_ssl_context ssl; /* ONLY for debugging */
1380
1381    mbedtls_ssl_transform t0, t1;
1382    unsigned char *buf = NULL;
1383    size_t const buflen = 256;
1384    mbedtls_record rec, rec_backup;
1385
1386    int ret;
1387    int mode;              /* Mode 1, 2 or 3 as explained above     */
1388    size_t offset;         /* Available space at beginning/end/both */
1389    size_t threshold = 96; /* Maximum offset to test against        */
1390
1391    size_t default_pre_padding  = 64;  /* Pre-padding to use in mode 2  */
1392    size_t default_post_padding = 128; /* Post-padding to use in mode 1 */
1393
1394    int seen_success; /* Indicates if in the current mode we've
1395                       * already seen a successful test. */
1396
1397    mbedtls_ssl_init(&ssl);
1398    mbedtls_ssl_transform_init(&t0);
1399    mbedtls_ssl_transform_init(&t1);
1400    MD_OR_USE_PSA_INIT();
1401
1402    ret = mbedtls_test_ssl_build_transforms(&t0, &t1, cipher_type, hash_id,
1403                                            etm, tag_mode, ver,
1404                                            (size_t) cid0_len,
1405                                            (size_t) cid1_len);
1406
1407    TEST_ASSERT(ret == 0);
1408
1409    TEST_CALLOC(buf, buflen);
1410
1411    for (mode = 1; mode <= 3; mode++) {
1412        seen_success = 0;
1413        for (offset = 0; offset <= threshold; offset++) {
1414            mbedtls_ssl_transform *t_dec, *t_enc;
1415            t_dec = &t0;
1416            t_enc = &t1;
1417
1418            memset(rec.ctr, offset, sizeof(rec.ctr));
1419            rec.type    = 42;
1420            rec.ver[0]  = offset;
1421            rec.ver[1]  = offset;
1422            rec.buf     = buf;
1423            rec.buf_len = buflen;
1424#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
1425            rec.cid_len = 0;
1426#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1427
1428            switch (mode) {
1429                case 1: /* Space in the beginning */
1430                    rec.data_offset = offset;
1431                    rec.data_len = buflen - offset - default_post_padding;
1432                    break;
1433
1434                case 2: /* Space in the end */
1435                    rec.data_offset = default_pre_padding;
1436                    rec.data_len = buflen - default_pre_padding - offset;
1437                    break;
1438
1439                case 3: /* Space in the beginning and end */
1440                    rec.data_offset = offset;
1441                    rec.data_len = buflen - 2 * offset;
1442                    break;
1443
1444                default:
1445                    TEST_ASSERT(0);
1446                    break;
1447            }
1448
1449            memset(rec.buf + rec.data_offset, 42, rec.data_len);
1450
1451            /* Make a copy for later comparison */
1452            rec_backup = rec;
1453
1454            /* Encrypt record */
1455            ret = mbedtls_ssl_encrypt_buf(&ssl, t_enc, &rec,
1456                                          mbedtls_test_rnd_std_rand, NULL);
1457
1458            if (ret == MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL) {
1459                /* It's ok if the output buffer is too small. We do insist
1460                 * on at least one mode succeeding; this is tracked by
1461                 * seen_success. */
1462                continue;
1463            }
1464
1465            TEST_EQUAL(ret, 0);
1466            seen_success = 1;
1467
1468#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
1469            if (rec.cid_len != 0) {
1470                /* DTLS 1.2 + CID hides the real content type and
1471                 * uses a special CID content type in the protected
1472                 * record. Double-check this. */
1473                TEST_ASSERT(rec.type == MBEDTLS_SSL_MSG_CID);
1474            }
1475#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1476
1477#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
1478            if (t_enc->tls_version == MBEDTLS_SSL_VERSION_TLS1_3) {
1479                /* TLS 1.3 hides the real content type and
1480                 * always uses Application Data as the content type
1481                 * for protected records. Double-check this. */
1482                TEST_ASSERT(rec.type == MBEDTLS_SSL_MSG_APPLICATION_DATA);
1483            }
1484#endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
1485
1486            /* Decrypt record with t_dec */
1487            TEST_ASSERT(mbedtls_ssl_decrypt_buf(&ssl, t_dec, &rec) == 0);
1488
1489            /* Compare results */
1490            TEST_ASSERT(rec.type == rec_backup.type);
1491            TEST_ASSERT(memcmp(rec.ctr, rec_backup.ctr, 8) == 0);
1492            TEST_ASSERT(rec.ver[0] == rec_backup.ver[0]);
1493            TEST_ASSERT(rec.ver[1] == rec_backup.ver[1]);
1494            TEST_ASSERT(rec.data_len == rec_backup.data_len);
1495            TEST_ASSERT(rec.data_offset == rec_backup.data_offset);
1496            TEST_ASSERT(memcmp(rec.buf + rec.data_offset,
1497                               rec_backup.buf + rec_backup.data_offset,
1498                               rec.data_len) == 0);
1499        }
1500
1501        TEST_ASSERT(seen_success == 1);
1502    }
1503
1504exit:
1505
1506    /* Cleanup */
1507    mbedtls_ssl_free(&ssl);
1508    mbedtls_ssl_transform_free(&t0);
1509    mbedtls_ssl_transform_free(&t1);
1510
1511    mbedtls_free(buf);
1512    MD_OR_USE_PSA_DONE();
1513}
1514/* END_CASE */
1515
1516/* BEGIN_CASE depends_on:MBEDTLS_SSL_PROTO_TLS1_3 */
1517void ssl_tls13_hkdf_expand_label(int hash_alg,
1518                                 data_t *secret,
1519                                 int label_idx,
1520                                 data_t *ctx,
1521                                 int desired_length,
1522                                 data_t *expected)
1523{
1524    unsigned char dst[100];
1525
1526    unsigned char const *lbl = NULL;
1527    size_t lbl_len;
1528#define MBEDTLS_SSL_TLS1_3_LABEL(name, string)                       \
1529    if (label_idx == (int) tls13_label_ ## name)                      \
1530    {                                                                  \
1531        lbl = mbedtls_ssl_tls13_labels.name;                           \
1532        lbl_len = sizeof(mbedtls_ssl_tls13_labels.name);             \
1533    }
1534    MBEDTLS_SSL_TLS1_3_LABEL_LIST
1535#undef MBEDTLS_SSL_TLS1_3_LABEL
1536    TEST_ASSERT(lbl != NULL);
1537
1538    /* Check sanity of test parameters. */
1539    TEST_ASSERT((size_t) desired_length <= sizeof(dst));
1540    TEST_ASSERT((size_t) desired_length == expected->len);
1541
1542    PSA_INIT();
1543
1544    TEST_ASSERT(mbedtls_ssl_tls13_hkdf_expand_label(
1545                    (psa_algorithm_t) hash_alg,
1546                    secret->x, secret->len,
1547                    lbl, lbl_len,
1548                    ctx->x, ctx->len,
1549                    dst, desired_length) == 0);
1550
1551    TEST_MEMORY_COMPARE(dst, (size_t) desired_length,
1552                        expected->x, (size_t) expected->len);
1553
1554exit:
1555    PSA_DONE();
1556}
1557/* END_CASE */
1558
1559/* BEGIN_CASE depends_on:MBEDTLS_SSL_PROTO_TLS1_3 */
1560void ssl_tls13_traffic_key_generation(int hash_alg,
1561                                      data_t *server_secret,
1562                                      data_t *client_secret,
1563                                      int desired_iv_len,
1564                                      int desired_key_len,
1565                                      data_t *expected_server_write_key,
1566                                      data_t *expected_server_write_iv,
1567                                      data_t *expected_client_write_key,
1568                                      data_t *expected_client_write_iv)
1569{
1570    mbedtls_ssl_key_set keys;
1571
1572    /* Check sanity of test parameters. */
1573    TEST_ASSERT(client_secret->len == server_secret->len);
1574    TEST_ASSERT(
1575        expected_client_write_iv->len == expected_server_write_iv->len &&
1576        expected_client_write_iv->len == (size_t) desired_iv_len);
1577    TEST_ASSERT(
1578        expected_client_write_key->len == expected_server_write_key->len &&
1579        expected_client_write_key->len == (size_t) desired_key_len);
1580
1581    PSA_INIT();
1582
1583    TEST_ASSERT(mbedtls_ssl_tls13_make_traffic_keys(
1584                    (psa_algorithm_t) hash_alg,
1585                    client_secret->x,
1586                    server_secret->x,
1587                    client_secret->len /* == server_secret->len */,
1588                    desired_key_len, desired_iv_len,
1589                    &keys) == 0);
1590
1591    TEST_MEMORY_COMPARE(keys.client_write_key,
1592                        keys.key_len,
1593                        expected_client_write_key->x,
1594                        (size_t) desired_key_len);
1595    TEST_MEMORY_COMPARE(keys.server_write_key,
1596                        keys.key_len,
1597                        expected_server_write_key->x,
1598                        (size_t) desired_key_len);
1599    TEST_MEMORY_COMPARE(keys.client_write_iv,
1600                        keys.iv_len,
1601                        expected_client_write_iv->x,
1602                        (size_t) desired_iv_len);
1603    TEST_MEMORY_COMPARE(keys.server_write_iv,
1604                        keys.iv_len,
1605                        expected_server_write_iv->x,
1606                        (size_t) desired_iv_len);
1607
1608exit:
1609    PSA_DONE();
1610}
1611/* END_CASE */
1612
1613/* BEGIN_CASE depends_on:MBEDTLS_SSL_PROTO_TLS1_3 */
1614void ssl_tls13_derive_secret(int hash_alg,
1615                             data_t *secret,
1616                             int label_idx,
1617                             data_t *ctx,
1618                             int desired_length,
1619                             int already_hashed,
1620                             data_t *expected)
1621{
1622    unsigned char dst[100];
1623
1624    unsigned char const *lbl = NULL;
1625    size_t lbl_len;
1626#define MBEDTLS_SSL_TLS1_3_LABEL(name, string)                       \
1627    if (label_idx == (int) tls13_label_ ## name)                      \
1628    {                                                                  \
1629        lbl = mbedtls_ssl_tls13_labels.name;                           \
1630        lbl_len = sizeof(mbedtls_ssl_tls13_labels.name);             \
1631    }
1632    MBEDTLS_SSL_TLS1_3_LABEL_LIST
1633#undef MBEDTLS_SSL_TLS1_3_LABEL
1634    TEST_ASSERT(lbl != NULL);
1635
1636    /* Check sanity of test parameters. */
1637    TEST_ASSERT((size_t) desired_length <= sizeof(dst));
1638    TEST_ASSERT((size_t) desired_length == expected->len);
1639
1640    PSA_INIT();
1641
1642    TEST_ASSERT(mbedtls_ssl_tls13_derive_secret(
1643                    (psa_algorithm_t) hash_alg,
1644                    secret->x, secret->len,
1645                    lbl, lbl_len,
1646                    ctx->x, ctx->len,
1647                    already_hashed,
1648                    dst, desired_length) == 0);
1649
1650    TEST_MEMORY_COMPARE(dst, desired_length,
1651                        expected->x, desired_length);
1652
1653exit:
1654    PSA_DONE();
1655}
1656/* END_CASE */
1657
1658/* BEGIN_CASE depends_on:MBEDTLS_SSL_PROTO_TLS1_3 */
1659void ssl_tls13_derive_early_secrets(int hash_alg,
1660                                    data_t *secret,
1661                                    data_t *transcript,
1662                                    data_t *traffic_expected,
1663                                    data_t *exporter_expected)
1664{
1665    mbedtls_ssl_tls13_early_secrets secrets;
1666
1667    /* Double-check that we've passed sane parameters. */
1668    psa_algorithm_t alg = (psa_algorithm_t) hash_alg;
1669    size_t const hash_len = PSA_HASH_LENGTH(alg);
1670    TEST_ASSERT(PSA_ALG_IS_HASH(alg)             &&
1671                secret->len == hash_len            &&
1672                transcript->len == hash_len        &&
1673                traffic_expected->len == hash_len  &&
1674                exporter_expected->len == hash_len);
1675
1676    PSA_INIT();
1677
1678    TEST_ASSERT(mbedtls_ssl_tls13_derive_early_secrets(
1679                    alg, secret->x, transcript->x, transcript->len,
1680                    &secrets) == 0);
1681
1682    TEST_MEMORY_COMPARE(secrets.client_early_traffic_secret, hash_len,
1683                        traffic_expected->x, traffic_expected->len);
1684    TEST_MEMORY_COMPARE(secrets.early_exporter_master_secret, hash_len,
1685                        exporter_expected->x, exporter_expected->len);
1686
1687exit:
1688    PSA_DONE();
1689}
1690/* END_CASE */
1691
1692/* BEGIN_CASE depends_on:MBEDTLS_SSL_PROTO_TLS1_3 */
1693void ssl_tls13_derive_handshake_secrets(int hash_alg,
1694                                        data_t *secret,
1695                                        data_t *transcript,
1696                                        data_t *client_expected,
1697                                        data_t *server_expected)
1698{
1699    mbedtls_ssl_tls13_handshake_secrets secrets;
1700
1701    /* Double-check that we've passed sane parameters. */
1702    psa_algorithm_t alg = (psa_algorithm_t) hash_alg;
1703    size_t const hash_len = PSA_HASH_LENGTH(alg);
1704    TEST_ASSERT(PSA_ALG_IS_HASH(alg)            &&
1705                secret->len == hash_len           &&
1706                transcript->len == hash_len       &&
1707                client_expected->len == hash_len  &&
1708                server_expected->len == hash_len);
1709
1710    PSA_INIT();
1711
1712    TEST_ASSERT(mbedtls_ssl_tls13_derive_handshake_secrets(
1713                    alg, secret->x, transcript->x, transcript->len,
1714                    &secrets) == 0);
1715
1716    TEST_MEMORY_COMPARE(secrets.client_handshake_traffic_secret, hash_len,
1717                        client_expected->x, client_expected->len);
1718    TEST_MEMORY_COMPARE(secrets.server_handshake_traffic_secret, hash_len,
1719                        server_expected->x, server_expected->len);
1720
1721exit:
1722    PSA_DONE();
1723}
1724/* END_CASE */
1725
1726/* BEGIN_CASE depends_on:MBEDTLS_SSL_PROTO_TLS1_3 */
1727void ssl_tls13_derive_application_secrets(int hash_alg,
1728                                          data_t *secret,
1729                                          data_t *transcript,
1730                                          data_t *client_expected,
1731                                          data_t *server_expected,
1732                                          data_t *exporter_expected)
1733{
1734    mbedtls_ssl_tls13_application_secrets secrets;
1735
1736    /* Double-check that we've passed sane parameters. */
1737    psa_algorithm_t alg = (psa_algorithm_t) hash_alg;
1738    size_t const hash_len = PSA_HASH_LENGTH(alg);
1739    TEST_ASSERT(PSA_ALG_IS_HASH(alg)            &&
1740                secret->len == hash_len           &&
1741                transcript->len == hash_len       &&
1742                client_expected->len == hash_len  &&
1743                server_expected->len == hash_len  &&
1744                exporter_expected->len == hash_len);
1745
1746    PSA_INIT();
1747
1748    TEST_ASSERT(mbedtls_ssl_tls13_derive_application_secrets(
1749                    alg, secret->x, transcript->x, transcript->len,
1750                    &secrets) == 0);
1751
1752    TEST_MEMORY_COMPARE(secrets.client_application_traffic_secret_N, hash_len,
1753                        client_expected->x, client_expected->len);
1754    TEST_MEMORY_COMPARE(secrets.server_application_traffic_secret_N, hash_len,
1755                        server_expected->x, server_expected->len);
1756    TEST_MEMORY_COMPARE(secrets.exporter_master_secret, hash_len,
1757                        exporter_expected->x, exporter_expected->len);
1758
1759exit:
1760    PSA_DONE();
1761}
1762/* END_CASE */
1763
1764/* BEGIN_CASE depends_on:MBEDTLS_SSL_PROTO_TLS1_3 */
1765void ssl_tls13_derive_resumption_secrets(int hash_alg,
1766                                         data_t *secret,
1767                                         data_t *transcript,
1768                                         data_t *resumption_expected)
1769{
1770    mbedtls_ssl_tls13_application_secrets secrets;
1771
1772    /* Double-check that we've passed sane parameters. */
1773    psa_algorithm_t alg = (psa_algorithm_t) hash_alg;
1774    size_t const hash_len = PSA_HASH_LENGTH(alg);
1775    TEST_ASSERT(PSA_ALG_IS_HASH(alg)              &&
1776                secret->len == hash_len             &&
1777                transcript->len == hash_len         &&
1778                resumption_expected->len == hash_len);
1779
1780    PSA_INIT();
1781
1782    TEST_ASSERT(mbedtls_ssl_tls13_derive_resumption_master_secret(
1783                    alg, secret->x, transcript->x, transcript->len,
1784                    &secrets) == 0);
1785
1786    TEST_MEMORY_COMPARE(secrets.resumption_master_secret, hash_len,
1787                        resumption_expected->x, resumption_expected->len);
1788
1789exit:
1790    PSA_DONE();
1791}
1792/* END_CASE */
1793
1794/* BEGIN_CASE depends_on:MBEDTLS_SSL_PROTO_TLS1_3 */
1795void ssl_tls13_create_psk_binder(int hash_alg,
1796                                 data_t *psk,
1797                                 int psk_type,
1798                                 data_t *transcript,
1799                                 data_t *binder_expected)
1800{
1801    unsigned char binder[MBEDTLS_MD_MAX_SIZE];
1802
1803    /* Double-check that we've passed sane parameters. */
1804    psa_algorithm_t alg = (psa_algorithm_t) hash_alg;
1805    size_t const hash_len = PSA_HASH_LENGTH(alg);
1806    TEST_ASSERT(PSA_ALG_IS_HASH(alg)          &&
1807                transcript->len == hash_len     &&
1808                binder_expected->len == hash_len);
1809
1810    PSA_INIT();
1811
1812    TEST_ASSERT(mbedtls_ssl_tls13_create_psk_binder(
1813                    NULL,  /* SSL context for debugging only */
1814                    alg,
1815                    psk->x, psk->len,
1816                    psk_type,
1817                    transcript->x,
1818                    binder) == 0);
1819
1820    TEST_MEMORY_COMPARE(binder, hash_len,
1821                        binder_expected->x, binder_expected->len);
1822
1823exit:
1824    PSA_DONE();
1825}
1826/* END_CASE */
1827
1828/* BEGIN_CASE depends_on:MBEDTLS_SSL_PROTO_TLS1_3 */
1829void ssl_tls13_record_protection(int ciphersuite,
1830                                 int endpoint,
1831                                 int ctr,
1832                                 int padding_used,
1833                                 data_t *server_write_key,
1834                                 data_t *server_write_iv,
1835                                 data_t *client_write_key,
1836                                 data_t *client_write_iv,
1837                                 data_t *plaintext,
1838                                 data_t *ciphertext)
1839{
1840    mbedtls_ssl_key_set keys;
1841    mbedtls_ssl_transform transform_send;
1842    mbedtls_ssl_transform_init(&transform_send);
1843    mbedtls_ssl_transform transform_recv;
1844    mbedtls_ssl_transform_init(&transform_recv);
1845    mbedtls_record rec;
1846    unsigned char *buf = NULL;
1847    size_t buf_len;
1848    int other_endpoint;
1849
1850    TEST_ASSERT(endpoint == MBEDTLS_SSL_IS_CLIENT ||
1851                endpoint == MBEDTLS_SSL_IS_SERVER);
1852
1853    if (endpoint == MBEDTLS_SSL_IS_SERVER) {
1854        other_endpoint = MBEDTLS_SSL_IS_CLIENT;
1855    }
1856    if (endpoint == MBEDTLS_SSL_IS_CLIENT) {
1857        other_endpoint = MBEDTLS_SSL_IS_SERVER;
1858    }
1859
1860    TEST_ASSERT(server_write_key->len == client_write_key->len);
1861    TEST_ASSERT(server_write_iv->len  == client_write_iv->len);
1862
1863    memcpy(keys.client_write_key,
1864           client_write_key->x, client_write_key->len);
1865    memcpy(keys.client_write_iv,
1866           client_write_iv->x, client_write_iv->len);
1867    memcpy(keys.server_write_key,
1868           server_write_key->x, server_write_key->len);
1869    memcpy(keys.server_write_iv,
1870           server_write_iv->x, server_write_iv->len);
1871
1872    keys.key_len = server_write_key->len;
1873    keys.iv_len  = server_write_iv->len;
1874
1875    MD_OR_USE_PSA_INIT();
1876
1877    TEST_ASSERT(mbedtls_ssl_tls13_populate_transform(
1878                    &transform_send, endpoint,
1879                    ciphersuite, &keys, NULL) == 0);
1880    TEST_ASSERT(mbedtls_ssl_tls13_populate_transform(
1881                    &transform_recv, other_endpoint,
1882                    ciphersuite, &keys, NULL) == 0);
1883
1884    /* Make sure we have enough space in the buffer even if
1885     * we use more padding than the KAT. */
1886    buf_len = ciphertext->len + MBEDTLS_SSL_CID_TLS1_3_PADDING_GRANULARITY;
1887    TEST_CALLOC(buf, buf_len);
1888    rec.type   = MBEDTLS_SSL_MSG_APPLICATION_DATA;
1889
1890    /* TLS 1.3 uses the version identifier from TLS 1.2 on the wire. */
1891    mbedtls_ssl_write_version(rec.ver,
1892                              MBEDTLS_SSL_TRANSPORT_STREAM,
1893                              MBEDTLS_SSL_VERSION_TLS1_2);
1894
1895    /* Copy plaintext into record structure */
1896    rec.buf = buf;
1897    rec.buf_len = buf_len;
1898    rec.data_offset = 0;
1899    TEST_ASSERT(plaintext->len <= ciphertext->len);
1900    memcpy(rec.buf + rec.data_offset, plaintext->x, plaintext->len);
1901    rec.data_len = plaintext->len;
1902#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
1903    rec.cid_len = 0;
1904#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1905
1906    memset(&rec.ctr[0], 0, 8);
1907    rec.ctr[7] = ctr;
1908
1909    TEST_ASSERT(mbedtls_ssl_encrypt_buf(NULL, &transform_send, &rec,
1910                                        NULL, NULL) == 0);
1911
1912    if (padding_used == MBEDTLS_SSL_CID_TLS1_3_PADDING_GRANULARITY) {
1913        TEST_MEMORY_COMPARE(rec.buf + rec.data_offset, rec.data_len,
1914                            ciphertext->x, ciphertext->len);
1915    }
1916
1917    TEST_ASSERT(mbedtls_ssl_decrypt_buf(NULL, &transform_recv, &rec) == 0);
1918    TEST_MEMORY_COMPARE(rec.buf + rec.data_offset, rec.data_len,
1919                        plaintext->x, plaintext->len);
1920
1921exit:
1922    mbedtls_free(buf);
1923    mbedtls_ssl_transform_free(&transform_send);
1924    mbedtls_ssl_transform_free(&transform_recv);
1925    MD_OR_USE_PSA_DONE();
1926}
1927/* END_CASE */
1928
1929/* BEGIN_CASE depends_on:MBEDTLS_SSL_PROTO_TLS1_3 */
1930void ssl_tls13_key_evolution(int hash_alg,
1931                             data_t *secret,
1932                             data_t *input,
1933                             data_t *expected)
1934{
1935    unsigned char secret_new[MBEDTLS_MD_MAX_SIZE];
1936
1937    PSA_INIT();
1938
1939    TEST_ASSERT(mbedtls_ssl_tls13_evolve_secret(
1940                    (psa_algorithm_t) hash_alg,
1941                    secret->len ? secret->x : NULL,
1942                    input->len ? input->x : NULL, input->len,
1943                    secret_new) == 0);
1944
1945    TEST_MEMORY_COMPARE(secret_new, (size_t) expected->len,
1946                        expected->x, (size_t) expected->len);
1947
1948exit:
1949    PSA_DONE();
1950}
1951/* END_CASE */
1952
1953/* BEGIN_CASE depends_on:MBEDTLS_SSL_PROTO_TLS1_2 */
1954void ssl_tls_prf(int type, data_t *secret, data_t *random,
1955                 char *label, data_t *result_str, int exp_ret)
1956{
1957    unsigned char *output;
1958
1959    output = mbedtls_calloc(1, result_str->len);
1960    if (output == NULL) {
1961        goto exit;
1962    }
1963
1964    MD_OR_USE_PSA_INIT();
1965
1966    TEST_ASSERT(mbedtls_ssl_tls_prf(type, secret->x, secret->len,
1967                                    label, random->x, random->len,
1968                                    output, result_str->len) == exp_ret);
1969
1970    if (exp_ret == 0) {
1971        TEST_ASSERT(mbedtls_test_hexcmp(output, result_str->x,
1972                                        result_str->len, result_str->len) == 0);
1973    }
1974exit:
1975
1976    mbedtls_free(output);
1977    MD_OR_USE_PSA_DONE();
1978}
1979/* END_CASE */
1980
1981/* BEGIN_CASE */
1982void ssl_serialize_session_save_load(int ticket_len, char *crt_file,
1983                                     int endpoint_type, int tls_version)
1984{
1985    mbedtls_ssl_session original, restored;
1986    unsigned char *buf = NULL;
1987    size_t len;
1988
1989    /*
1990     * Test that a save-load pair is the identity
1991     */
1992    mbedtls_ssl_session_init(&original);
1993    mbedtls_ssl_session_init(&restored);
1994    USE_PSA_INIT();
1995
1996    /* Prepare a dummy session to work on */
1997    ((void) tls_version);
1998    ((void) ticket_len);
1999    ((void) crt_file);
2000#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
2001    if (tls_version == MBEDTLS_SSL_VERSION_TLS1_3) {
2002        TEST_ASSERT(mbedtls_test_ssl_tls13_populate_session(
2003                        &original, 0, endpoint_type) == 0);
2004    }
2005#endif
2006
2007#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
2008    if (tls_version == MBEDTLS_SSL_VERSION_TLS1_2) {
2009        TEST_ASSERT(mbedtls_test_ssl_tls12_populate_session(
2010                        &original, ticket_len, endpoint_type, crt_file) == 0);
2011    }
2012#endif
2013
2014    /* Serialize it */
2015    TEST_ASSERT(mbedtls_ssl_session_save(&original, NULL, 0, &len)
2016                == MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL);
2017    TEST_CALLOC(buf, len);
2018    TEST_ASSERT(mbedtls_ssl_session_save(&original, buf, len, &len)
2019                == 0);
2020
2021    /* Restore session from serialized data */
2022    TEST_ASSERT(mbedtls_ssl_session_load(&restored, buf, len) == 0);
2023
2024    /*
2025     * Make sure both session structures are identical
2026     */
2027#if defined(MBEDTLS_HAVE_TIME)
2028    if (tls_version == MBEDTLS_SSL_VERSION_TLS1_2) {
2029        TEST_ASSERT(original.start == restored.start);
2030    }
2031#if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_SRV_C)
2032    TEST_ASSERT(original.ticket_creation_time == restored.ticket_creation_time);
2033#endif
2034#endif /* MBEDTLS_HAVE_TIME */
2035
2036    TEST_ASSERT(original.tls_version == restored.tls_version);
2037    TEST_ASSERT(original.endpoint == restored.endpoint);
2038    TEST_ASSERT(original.ciphersuite == restored.ciphersuite);
2039#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
2040    if (tls_version == MBEDTLS_SSL_VERSION_TLS1_2) {
2041        TEST_ASSERT(original.id_len == restored.id_len);
2042        TEST_ASSERT(memcmp(original.id,
2043                           restored.id, sizeof(original.id)) == 0);
2044        TEST_ASSERT(memcmp(original.master,
2045                           restored.master, sizeof(original.master)) == 0);
2046
2047#if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
2048#if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
2049        TEST_ASSERT((original.peer_cert == NULL) ==
2050                    (restored.peer_cert == NULL));
2051        if (original.peer_cert != NULL) {
2052            TEST_ASSERT(original.peer_cert->raw.len ==
2053                        restored.peer_cert->raw.len);
2054            TEST_ASSERT(memcmp(original.peer_cert->raw.p,
2055                               restored.peer_cert->raw.p,
2056                               original.peer_cert->raw.len) == 0);
2057        }
2058#else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2059        TEST_ASSERT(original.peer_cert_digest_type ==
2060                    restored.peer_cert_digest_type);
2061        TEST_ASSERT(original.peer_cert_digest_len ==
2062                    restored.peer_cert_digest_len);
2063        TEST_ASSERT((original.peer_cert_digest == NULL) ==
2064                    (restored.peer_cert_digest == NULL));
2065        if (original.peer_cert_digest != NULL) {
2066            TEST_ASSERT(memcmp(original.peer_cert_digest,
2067                               restored.peer_cert_digest,
2068                               original.peer_cert_digest_len) == 0);
2069        }
2070#endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2071#endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
2072        TEST_ASSERT(original.verify_result == restored.verify_result);
2073
2074#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
2075        TEST_ASSERT(original.mfl_code == restored.mfl_code);
2076#endif
2077
2078#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
2079        TEST_ASSERT(original.encrypt_then_mac == restored.encrypt_then_mac);
2080#endif
2081#if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
2082        TEST_ASSERT(original.ticket_len == restored.ticket_len);
2083        if (original.ticket_len != 0) {
2084            TEST_ASSERT(original.ticket != NULL);
2085            TEST_ASSERT(restored.ticket != NULL);
2086            TEST_ASSERT(memcmp(original.ticket,
2087                               restored.ticket, original.ticket_len) == 0);
2088        }
2089        TEST_ASSERT(original.ticket_lifetime == restored.ticket_lifetime);
2090#endif
2091    }
2092#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
2093
2094#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
2095    if (tls_version == MBEDTLS_SSL_VERSION_TLS1_3) {
2096        TEST_ASSERT(original.ciphersuite == restored.ciphersuite);
2097        TEST_ASSERT(original.ticket_age_add == restored.ticket_age_add);
2098        TEST_ASSERT(original.ticket_flags == restored.ticket_flags);
2099        TEST_ASSERT(original.resumption_key_len == restored.resumption_key_len);
2100        if (original.resumption_key_len != 0) {
2101            TEST_ASSERT(original.resumption_key != NULL);
2102            TEST_ASSERT(restored.resumption_key != NULL);
2103            TEST_ASSERT(memcmp(original.resumption_key,
2104                               restored.resumption_key,
2105                               original.resumption_key_len) == 0);
2106        }
2107
2108#if defined(MBEDTLS_SSL_EARLY_DATA)
2109        TEST_ASSERT(
2110            original.max_early_data_size == restored.max_early_data_size);
2111#if defined(MBEDTLS_SSL_ALPN) && defined(MBEDTLS_SSL_SRV_C)
2112        if (endpoint_type == MBEDTLS_SSL_IS_SERVER) {
2113            TEST_ASSERT(original.ticket_alpn != NULL);
2114            TEST_ASSERT(restored.ticket_alpn != NULL);
2115            TEST_MEMORY_COMPARE(original.ticket_alpn, strlen(original.ticket_alpn),
2116                                restored.ticket_alpn, strlen(restored.ticket_alpn));
2117        }
2118#endif
2119#endif
2120
2121#if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
2122        if (endpoint_type == MBEDTLS_SSL_IS_CLIENT) {
2123#if defined(MBEDTLS_HAVE_TIME)
2124            TEST_ASSERT(original.ticket_reception_time == restored.ticket_reception_time);
2125#endif
2126            TEST_ASSERT(original.ticket_lifetime == restored.ticket_lifetime);
2127            TEST_ASSERT(original.ticket_len == restored.ticket_len);
2128            if (original.ticket_len != 0) {
2129                TEST_ASSERT(original.ticket != NULL);
2130                TEST_ASSERT(restored.ticket != NULL);
2131                TEST_ASSERT(memcmp(original.ticket,
2132                                   restored.ticket,
2133                                   original.ticket_len) == 0);
2134            }
2135
2136        }
2137#endif
2138    }
2139#endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
2140
2141#if defined(MBEDTLS_SSL_RECORD_SIZE_LIMIT)
2142    TEST_ASSERT(original.record_size_limit == restored.record_size_limit);
2143#endif
2144
2145exit:
2146    mbedtls_ssl_session_free(&original);
2147    mbedtls_ssl_session_free(&restored);
2148    mbedtls_free(buf);
2149    USE_PSA_DONE();
2150}
2151/* END_CASE */
2152
2153/* BEGIN_CASE */
2154void ssl_serialize_session_load_save(int ticket_len, char *crt_file,
2155                                     int endpoint_type, int tls_version)
2156{
2157    mbedtls_ssl_session session;
2158    unsigned char *buf1 = NULL, *buf2 = NULL;
2159    size_t len0, len1, len2;
2160
2161    /*
2162     * Test that a load-save pair is the identity
2163     */
2164    mbedtls_ssl_session_init(&session);
2165    USE_PSA_INIT();
2166
2167    /* Prepare a dummy session to work on */
2168    ((void) ticket_len);
2169    ((void) crt_file);
2170
2171    switch (tls_version) {
2172#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
2173        case MBEDTLS_SSL_VERSION_TLS1_3:
2174            TEST_ASSERT(mbedtls_test_ssl_tls13_populate_session(
2175                            &session, 0, endpoint_type) == 0);
2176            break;
2177#endif
2178
2179#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
2180        case MBEDTLS_SSL_VERSION_TLS1_2:
2181            TEST_ASSERT(mbedtls_test_ssl_tls12_populate_session(
2182                            &session, ticket_len, endpoint_type, crt_file) == 0);
2183            break;
2184#endif
2185        default:
2186            /* should never happen */
2187            TEST_ASSERT(0);
2188            break;
2189    }
2190
2191    /* Get desired buffer size for serializing */
2192    TEST_ASSERT(mbedtls_ssl_session_save(&session, NULL, 0, &len0)
2193                == MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL);
2194
2195    /* Allocate first buffer */
2196    buf1 = mbedtls_calloc(1, len0);
2197    TEST_ASSERT(buf1 != NULL);
2198
2199    /* Serialize to buffer and free live session */
2200    TEST_ASSERT(mbedtls_ssl_session_save(&session, buf1, len0, &len1)
2201                == 0);
2202    TEST_ASSERT(len0 == len1);
2203    mbedtls_ssl_session_free(&session);
2204
2205    /* Restore session from serialized data */
2206    TEST_ASSERT(mbedtls_ssl_session_load(&session, buf1, len1) == 0);
2207
2208    /* Allocate second buffer and serialize to it */
2209    buf2 = mbedtls_calloc(1, len0);
2210    TEST_ASSERT(buf2 != NULL);
2211    TEST_ASSERT(mbedtls_ssl_session_save(&session, buf2, len0, &len2)
2212                == 0);
2213
2214    /* Make sure both serialized versions are identical */
2215    TEST_ASSERT(len1 == len2);
2216    TEST_ASSERT(memcmp(buf1, buf2, len1) == 0);
2217
2218exit:
2219    mbedtls_ssl_session_free(&session);
2220    mbedtls_free(buf1);
2221    mbedtls_free(buf2);
2222    USE_PSA_DONE();
2223}
2224/* END_CASE */
2225
2226/* BEGIN_CASE */
2227void ssl_serialize_session_save_buf_size(int ticket_len, char *crt_file,
2228                                         int endpoint_type, int tls_version)
2229{
2230    mbedtls_ssl_session session;
2231    unsigned char *buf = NULL;
2232    size_t good_len, bad_len, test_len;
2233
2234    /*
2235     * Test that session_save() fails cleanly on small buffers
2236     */
2237    mbedtls_ssl_session_init(&session);
2238    USE_PSA_INIT();
2239
2240    /* Prepare dummy session and get serialized size */
2241    ((void) ticket_len);
2242    ((void) crt_file);
2243
2244    switch (tls_version) {
2245#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
2246        case MBEDTLS_SSL_VERSION_TLS1_3:
2247            TEST_ASSERT(mbedtls_test_ssl_tls13_populate_session(
2248                            &session, 0, endpoint_type) == 0);
2249            break;
2250#endif
2251#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
2252        case MBEDTLS_SSL_VERSION_TLS1_2:
2253            TEST_ASSERT(mbedtls_test_ssl_tls12_populate_session(
2254                            &session, ticket_len, endpoint_type, crt_file) == 0);
2255            break;
2256#endif
2257        default:
2258            /* should never happen */
2259            TEST_ASSERT(0);
2260            break;
2261    }
2262
2263    TEST_ASSERT(mbedtls_ssl_session_save(&session, NULL, 0, &good_len)
2264                == MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL);
2265
2266    /* Try all possible bad lengths */
2267    for (bad_len = 1; bad_len < good_len; bad_len++) {
2268        /* Allocate exact size so that asan/valgrind can detect any overwrite */
2269        mbedtls_free(buf);
2270        buf = NULL;
2271        TEST_CALLOC(buf, bad_len);
2272        TEST_ASSERT(mbedtls_ssl_session_save(&session, buf, bad_len,
2273                                             &test_len)
2274                    == MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL);
2275        TEST_ASSERT(test_len == good_len);
2276    }
2277
2278exit:
2279    mbedtls_ssl_session_free(&session);
2280    mbedtls_free(buf);
2281    USE_PSA_DONE();
2282}
2283/* END_CASE */
2284
2285/* BEGIN_CASE */
2286void ssl_serialize_session_load_buf_size(int ticket_len, char *crt_file,
2287                                         int endpoint_type, int tls_version)
2288{
2289    mbedtls_ssl_session session;
2290    unsigned char *good_buf = NULL, *bad_buf = NULL;
2291    size_t good_len, bad_len;
2292
2293    /*
2294     * Test that session_load() fails cleanly on small buffers
2295     */
2296    mbedtls_ssl_session_init(&session);
2297    USE_PSA_INIT();
2298
2299    /* Prepare serialized session data */
2300    ((void) ticket_len);
2301    ((void) crt_file);
2302
2303    switch (tls_version) {
2304#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
2305        case MBEDTLS_SSL_VERSION_TLS1_3:
2306            TEST_ASSERT(mbedtls_test_ssl_tls13_populate_session(
2307                            &session, 0, endpoint_type) == 0);
2308            break;
2309#endif
2310
2311#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
2312        case MBEDTLS_SSL_VERSION_TLS1_2:
2313            TEST_ASSERT(mbedtls_test_ssl_tls12_populate_session(
2314                            &session, ticket_len, endpoint_type, crt_file) == 0);
2315            break;
2316#endif
2317
2318        default:
2319            /* should never happen */
2320            TEST_ASSERT(0);
2321            break;
2322    }
2323
2324    TEST_ASSERT(mbedtls_ssl_session_save(&session, NULL, 0, &good_len)
2325                == MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL);
2326    TEST_CALLOC(good_buf, good_len);
2327    TEST_ASSERT(mbedtls_ssl_session_save(&session, good_buf, good_len,
2328                                         &good_len) == 0);
2329    mbedtls_ssl_session_free(&session);
2330
2331    /* Try all possible bad lengths */
2332    for (bad_len = 0; bad_len < good_len; bad_len++) {
2333        /* Allocate exact size so that asan/valgrind can detect any overread */
2334        mbedtls_free(bad_buf);
2335        bad_buf = NULL;
2336        TEST_CALLOC_NONNULL(bad_buf, bad_len);
2337        memcpy(bad_buf, good_buf, bad_len);
2338
2339        TEST_ASSERT(mbedtls_ssl_session_load(&session, bad_buf, bad_len)
2340                    == MBEDTLS_ERR_SSL_BAD_INPUT_DATA);
2341    }
2342
2343exit:
2344    mbedtls_ssl_session_free(&session);
2345    mbedtls_free(good_buf);
2346    mbedtls_free(bad_buf);
2347    USE_PSA_DONE();
2348}
2349/* END_CASE */
2350
2351/* BEGIN_CASE */
2352void ssl_session_serialize_version_check(int corrupt_major,
2353                                         int corrupt_minor,
2354                                         int corrupt_patch,
2355                                         int corrupt_config,
2356                                         int endpoint_type,
2357                                         int tls_version)
2358{
2359    unsigned char serialized_session[2048];
2360    size_t serialized_session_len;
2361    unsigned cur_byte;
2362    mbedtls_ssl_session session;
2363    uint8_t should_corrupt_byte[] = { corrupt_major  == 1,
2364                                      corrupt_minor  == 1,
2365                                      corrupt_patch  == 1,
2366                                      corrupt_config == 1,
2367                                      corrupt_config == 1 };
2368
2369    mbedtls_ssl_session_init(&session);
2370    USE_PSA_INIT();
2371
2372    switch (tls_version) {
2373#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
2374        case MBEDTLS_SSL_VERSION_TLS1_3:
2375            TEST_ASSERT(mbedtls_test_ssl_tls13_populate_session(
2376                            &session, 0, endpoint_type) == 0);
2377            break;
2378#endif
2379#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
2380        case MBEDTLS_SSL_VERSION_TLS1_2:
2381            TEST_ASSERT(mbedtls_test_ssl_tls12_populate_session(
2382                            &session, 0, endpoint_type, NULL) == 0);
2383
2384            break;
2385#endif
2386        default:
2387            /* should never happen */
2388            TEST_ASSERT(0);
2389            break;
2390    }
2391
2392    /* Infer length of serialized session. */
2393    TEST_ASSERT(mbedtls_ssl_session_save(&session,
2394                                         serialized_session,
2395                                         sizeof(serialized_session),
2396                                         &serialized_session_len) == 0);
2397
2398    mbedtls_ssl_session_free(&session);
2399
2400    /* Without any modification, we should be able to successfully
2401     * de-serialize the session - double-check that. */
2402    TEST_ASSERT(mbedtls_ssl_session_load(&session,
2403                                         serialized_session,
2404                                         serialized_session_len) == 0);
2405    mbedtls_ssl_session_free(&session);
2406
2407    /* Go through the bytes in the serialized session header and
2408     * corrupt them bit-by-bit. */
2409    for (cur_byte = 0; cur_byte < sizeof(should_corrupt_byte); cur_byte++) {
2410        int cur_bit;
2411        unsigned char *const byte = &serialized_session[cur_byte];
2412
2413        if (should_corrupt_byte[cur_byte] == 0) {
2414            continue;
2415        }
2416
2417        for (cur_bit = 0; cur_bit < CHAR_BIT; cur_bit++) {
2418            unsigned char const corrupted_bit = 0x1u << cur_bit;
2419            /* Modify a single bit in the serialized session. */
2420            *byte ^= corrupted_bit;
2421
2422            /* Attempt to deserialize */
2423            TEST_ASSERT(mbedtls_ssl_session_load(&session,
2424                                                 serialized_session,
2425                                                 serialized_session_len) ==
2426                        MBEDTLS_ERR_SSL_VERSION_MISMATCH);
2427
2428            /* Undo the change */
2429            *byte ^= corrupted_bit;
2430        }
2431    }
2432exit:
2433    USE_PSA_DONE();
2434}
2435/* END_CASE */
2436
2437/* BEGIN_CASE */
2438void ssl_session_id_accessors_check(int tls_version)
2439{
2440    mbedtls_ssl_session session;
2441    int ciphersuite_id;
2442    const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
2443
2444    mbedtls_ssl_session_init(&session);
2445    USE_PSA_INIT();
2446
2447    switch (tls_version) {
2448#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
2449        case MBEDTLS_SSL_VERSION_TLS1_3:
2450            ciphersuite_id = MBEDTLS_TLS1_3_AES_128_GCM_SHA256;
2451            TEST_ASSERT(mbedtls_test_ssl_tls13_populate_session(
2452                            &session, 0, MBEDTLS_SSL_IS_SERVER) == 0);
2453            break;
2454#endif
2455#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
2456        case MBEDTLS_SSL_VERSION_TLS1_2:
2457            ciphersuite_id = MBEDTLS_TLS_PSK_WITH_AES_128_GCM_SHA256;
2458            TEST_ASSERT(mbedtls_test_ssl_tls12_populate_session(
2459                            &session, 0, MBEDTLS_SSL_IS_SERVER, NULL) == 0);
2460
2461            break;
2462#endif
2463        default:
2464            /* should never happen */
2465            TEST_ASSERT(0);
2466            break;
2467    }
2468    TEST_ASSERT(*mbedtls_ssl_session_get_id(&session) == session.id);
2469    TEST_ASSERT(mbedtls_ssl_session_get_id_len(&session) == session.id_len);
2470    /* mbedtls_test_ssl_tls1x_populate_session sets a mock suite-id of 0xabcd */
2471    TEST_ASSERT(mbedtls_ssl_session_get_ciphersuite_id(&session) == 0xabcd);
2472
2473    /* Test setting a reference id for tls1.3 and tls1.2 */
2474    ciphersuite_info = mbedtls_ssl_ciphersuite_from_id(ciphersuite_id);
2475    if (ciphersuite_info != NULL) {
2476        TEST_ASSERT(mbedtls_ssl_ciphersuite_get_id(ciphersuite_info) == ciphersuite_id);
2477    }
2478
2479exit:
2480    mbedtls_ssl_session_free(&session);
2481    USE_PSA_DONE();
2482}
2483/* END_CASE */
2484
2485/* BEGIN_CASE depends_on:MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED:MBEDTLS_RSA_C:MBEDTLS_ECP_HAVE_SECP384R1:!MBEDTLS_SSL_PROTO_TLS1_3:MBEDTLS_PKCS1_V15:MBEDTLS_MD_CAN_SHA256 */
2486void mbedtls_endpoint_sanity(int endpoint_type)
2487{
2488    enum { BUFFSIZE = 1024 };
2489    mbedtls_test_ssl_endpoint ep;
2490    int ret = -1;
2491    mbedtls_test_handshake_test_options options;
2492    mbedtls_test_init_handshake_options(&options);
2493    options.pk_alg = MBEDTLS_PK_RSA;
2494
2495    MD_OR_USE_PSA_INIT();
2496
2497    ret = mbedtls_test_ssl_endpoint_init(NULL, endpoint_type, &options,
2498                                         NULL, NULL, NULL);
2499    TEST_ASSERT(MBEDTLS_ERR_SSL_BAD_INPUT_DATA == ret);
2500
2501    ret = mbedtls_test_ssl_endpoint_certificate_init(NULL, options.pk_alg,
2502                                                     0, 0, 0);
2503    TEST_ASSERT(MBEDTLS_ERR_SSL_BAD_INPUT_DATA == ret);
2504
2505    ret = mbedtls_test_ssl_endpoint_init(&ep, endpoint_type, &options,
2506                                         NULL, NULL, NULL);
2507    TEST_ASSERT(ret == 0);
2508
2509exit:
2510    mbedtls_test_ssl_endpoint_free(&ep, NULL);
2511    mbedtls_test_free_handshake_options(&options);
2512    MD_OR_USE_PSA_DONE();
2513}
2514/* END_CASE */
2515
2516/* BEGIN_CASE depends_on:MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED:MBEDTLS_RSA_C:MBEDTLS_ECP_HAVE_SECP384R1:MBEDTLS_PKCS1_V15:MBEDTLS_MD_CAN_SHA256:MBEDTLS_PK_HAVE_ECC_KEYS */
2517void move_handshake_to_state(int endpoint_type, int tls_version, int state, int need_pass)
2518{
2519    enum { BUFFSIZE = 1024 };
2520    mbedtls_test_ssl_endpoint base_ep, second_ep;
2521    int ret = -1;
2522    (void) tls_version;
2523
2524    mbedtls_test_handshake_test_options options;
2525    mbedtls_test_init_handshake_options(&options);
2526
2527    options.pk_alg = MBEDTLS_PK_RSA;
2528
2529    /*
2530     * If both TLS 1.2 and 1.3 are enabled and we want to do a TLS 1.2
2531     * handshake, force the TLS 1.2 version on endpoint under test.
2532     */
2533#if defined(MBEDTLS_SSL_PROTO_TLS1_3) && defined(MBEDTLS_SSL_PROTO_TLS1_2)
2534    if (MBEDTLS_SSL_VERSION_TLS1_2 == tls_version) {
2535        if (MBEDTLS_SSL_IS_CLIENT == endpoint_type) {
2536            options.client_min_version = MBEDTLS_SSL_VERSION_TLS1_2;
2537            options.client_max_version = MBEDTLS_SSL_VERSION_TLS1_2;
2538        } else {
2539            options.server_min_version = MBEDTLS_SSL_VERSION_TLS1_2;
2540            options.server_max_version = MBEDTLS_SSL_VERSION_TLS1_2;
2541        }
2542    }
2543#endif
2544
2545    MD_OR_USE_PSA_INIT();
2546    mbedtls_platform_zeroize(&base_ep, sizeof(base_ep));
2547    mbedtls_platform_zeroize(&second_ep, sizeof(second_ep));
2548
2549    ret = mbedtls_test_ssl_endpoint_init(&base_ep, endpoint_type, &options,
2550                                         NULL, NULL, NULL);
2551    TEST_ASSERT(ret == 0);
2552
2553    ret = mbedtls_test_ssl_endpoint_init(
2554        &second_ep,
2555        (endpoint_type == MBEDTLS_SSL_IS_SERVER) ?
2556        MBEDTLS_SSL_IS_CLIENT : MBEDTLS_SSL_IS_SERVER,
2557        &options, NULL, NULL, NULL);
2558
2559    TEST_ASSERT(ret == 0);
2560
2561    ret = mbedtls_test_mock_socket_connect(&(base_ep.socket),
2562                                           &(second_ep.socket),
2563                                           BUFFSIZE);
2564    TEST_ASSERT(ret == 0);
2565
2566    ret = mbedtls_test_move_handshake_to_state(&(base_ep.ssl),
2567                                               &(second_ep.ssl),
2568                                               state);
2569    if (need_pass) {
2570        TEST_ASSERT(ret == 0 ||
2571                    ret == MBEDTLS_ERR_SSL_WANT_READ ||
2572                    ret == MBEDTLS_ERR_SSL_WANT_WRITE);
2573        TEST_ASSERT(base_ep.ssl.state == state);
2574    } else {
2575        TEST_ASSERT(ret != 0 &&
2576                    ret != MBEDTLS_ERR_SSL_WANT_READ &&
2577                    ret != MBEDTLS_ERR_SSL_WANT_WRITE);
2578        TEST_ASSERT(base_ep.ssl.state != state);
2579    }
2580
2581exit:
2582    mbedtls_test_free_handshake_options(&options);
2583    mbedtls_test_ssl_endpoint_free(&base_ep, NULL);
2584    mbedtls_test_ssl_endpoint_free(&second_ep, NULL);
2585    MD_OR_USE_PSA_DONE();
2586}
2587/* END_CASE */
2588
2589/* BEGIN_CASE depends_on:MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED:MBEDTLS_PKCS1_V15:MBEDTLS_RSA_C:MBEDTLS_ECP_HAVE_SECP384R1:MBEDTLS_MD_CAN_SHA256:MBEDTLS_PK_HAVE_ECC_KEYS:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY */
2590void handshake_version(int dtls, int client_min_version, int client_max_version,
2591                       int server_min_version, int server_max_version,
2592                       int expected_negotiated_version)
2593{
2594    mbedtls_test_handshake_test_options options;
2595    mbedtls_test_init_handshake_options(&options);
2596
2597    options.client_min_version = client_min_version;
2598    options.client_max_version = client_max_version;
2599    options.server_min_version = server_min_version;
2600    options.server_max_version = server_max_version;
2601    options.expected_negotiated_version = expected_negotiated_version;
2602
2603    options.dtls = dtls;
2604    mbedtls_test_ssl_perform_handshake(&options);
2605
2606    /* The goto below is used to avoid an "unused label" warning.*/
2607    goto exit;
2608
2609exit:
2610    mbedtls_test_free_handshake_options(&options);
2611}
2612/* END_CASE */
2613
2614/* BEGIN_CASE depends_on:MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED:MBEDTLS_PKCS1_V15:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_MD_CAN_SHA256 */
2615void handshake_psk_cipher(char *cipher, int pk_alg, data_t *psk_str, int dtls)
2616{
2617    mbedtls_test_handshake_test_options options;
2618    mbedtls_test_init_handshake_options(&options);
2619
2620    options.cipher = cipher;
2621    options.dtls = dtls;
2622    options.psk_str = psk_str;
2623    options.pk_alg = pk_alg;
2624
2625    options.client_min_version = MBEDTLS_SSL_VERSION_TLS1_2;
2626    options.client_max_version = MBEDTLS_SSL_VERSION_TLS1_2;
2627    options.expected_negotiated_version = MBEDTLS_SSL_VERSION_TLS1_2;
2628
2629    mbedtls_test_ssl_perform_handshake(&options);
2630
2631    /* The goto below is used to avoid an "unused label" warning.*/
2632    goto exit;
2633
2634exit:
2635    mbedtls_test_free_handshake_options(&options);
2636}
2637/* END_CASE */
2638
2639/* BEGIN_CASE depends_on:MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED:MBEDTLS_PKCS1_V15:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_MD_CAN_SHA256 */
2640void handshake_cipher(char *cipher, int pk_alg, int dtls)
2641{
2642    test_handshake_psk_cipher(cipher, pk_alg, NULL, dtls);
2643
2644    /* The goto below is used to avoid an "unused label" warning.*/
2645    goto exit;
2646}
2647/* END_CASE */
2648
2649/* BEGIN_CASE depends_on:MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED:MBEDTLS_PKCS1_V15:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_MD_CAN_SHA256 */
2650void handshake_ciphersuite_select(char *cipher, int pk_alg, data_t *psk_str,
2651                                  int psa_alg, int psa_alg2, int psa_usage,
2652                                  int expected_handshake_result,
2653                                  int expected_ciphersuite)
2654{
2655    mbedtls_test_handshake_test_options options;
2656    mbedtls_test_init_handshake_options(&options);
2657
2658    options.cipher = cipher;
2659    options.psk_str = psk_str;
2660    options.pk_alg = pk_alg;
2661    options.opaque_alg = psa_alg;
2662    options.opaque_alg2 = psa_alg2;
2663    options.opaque_usage = psa_usage;
2664    options.expected_handshake_result = expected_handshake_result;
2665    options.expected_ciphersuite = expected_ciphersuite;
2666
2667    options.server_min_version = MBEDTLS_SSL_VERSION_TLS1_2;
2668    options.server_max_version = MBEDTLS_SSL_VERSION_TLS1_2;
2669    options.expected_negotiated_version = MBEDTLS_SSL_VERSION_TLS1_2;
2670
2671    mbedtls_test_ssl_perform_handshake(&options);
2672
2673    /* The goto below is used to avoid an "unused label" warning.*/
2674    goto exit;
2675
2676exit:
2677    mbedtls_test_free_handshake_options(&options);
2678}
2679/* END_CASE */
2680
2681/* BEGIN_CASE depends_on:MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED:MBEDTLS_PKCS1_V15:MBEDTLS_RSA_C:MBEDTLS_ECP_HAVE_SECP384R1:MBEDTLS_MD_CAN_SHA256 */
2682void app_data(int mfl, int cli_msg_len, int srv_msg_len,
2683              int expected_cli_fragments,
2684              int expected_srv_fragments, int dtls)
2685{
2686    mbedtls_test_handshake_test_options options;
2687    mbedtls_test_init_handshake_options(&options);
2688
2689    options.mfl = mfl;
2690    options.cli_msg_len = cli_msg_len;
2691    options.srv_msg_len = srv_msg_len;
2692    options.expected_cli_fragments = expected_cli_fragments;
2693    options.expected_srv_fragments = expected_srv_fragments;
2694    options.dtls = dtls;
2695
2696    options.client_min_version = MBEDTLS_SSL_VERSION_TLS1_2;
2697    options.client_max_version = MBEDTLS_SSL_VERSION_TLS1_2;
2698    options.expected_negotiated_version = MBEDTLS_SSL_VERSION_TLS1_2;
2699
2700    mbedtls_test_ssl_perform_handshake(&options);
2701
2702    /* The goto below is used to avoid an "unused label" warning.*/
2703    goto exit;
2704
2705exit:
2706    mbedtls_test_free_handshake_options(&options);
2707}
2708/* END_CASE */
2709
2710/* BEGIN_CASE depends_on:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED:MBEDTLS_PKCS1_V15:MBEDTLS_RSA_C:MBEDTLS_ECP_HAVE_SECP384R1:MBEDTLS_MD_CAN_SHA256:MBEDTLS_PK_HAVE_ECC_KEYS:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY */
2711void app_data_tls(int mfl, int cli_msg_len, int srv_msg_len,
2712                  int expected_cli_fragments,
2713                  int expected_srv_fragments)
2714{
2715    test_app_data(mfl, cli_msg_len, srv_msg_len, expected_cli_fragments,
2716                  expected_srv_fragments, 0);
2717    /* The goto below is used to avoid an "unused label" warning.*/
2718    goto exit;
2719}
2720/* END_CASE */
2721
2722/* BEGIN_CASE depends_on:MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED:!MBEDTLS_SSL_PROTO_TLS1_3:MBEDTLS_PKCS1_V15:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_RSA_C:MBEDTLS_ECP_HAVE_SECP384R1:MBEDTLS_SSL_PROTO_DTLS:MBEDTLS_MD_CAN_SHA256:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY */
2723void app_data_dtls(int mfl, int cli_msg_len, int srv_msg_len,
2724                   int expected_cli_fragments,
2725                   int expected_srv_fragments)
2726{
2727    test_app_data(mfl, cli_msg_len, srv_msg_len, expected_cli_fragments,
2728                  expected_srv_fragments, 1);
2729    /* The goto below is used to avoid an "unused label" warning.*/
2730    goto exit;
2731}
2732/* END_CASE */
2733
2734/* BEGIN_CASE depends_on:MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED:MBEDTLS_PKCS1_V15:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_RSA_C:MBEDTLS_ECP_HAVE_SECP384R1:MBEDTLS_SSL_PROTO_DTLS:MBEDTLS_SSL_RENEGOTIATION:MBEDTLS_SSL_CONTEXT_SERIALIZATION:MBEDTLS_MD_CAN_SHA256:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY */
2735void handshake_serialization()
2736{
2737    mbedtls_test_handshake_test_options options;
2738    mbedtls_test_init_handshake_options(&options);
2739
2740    options.serialize = 1;
2741    options.dtls = 1;
2742    options.expected_negotiated_version = MBEDTLS_SSL_VERSION_TLS1_2;
2743    mbedtls_test_ssl_perform_handshake(&options);
2744    /* The goto below is used to avoid an "unused label" warning.*/
2745    goto exit;
2746exit:
2747    mbedtls_test_free_handshake_options(&options);
2748}
2749/* END_CASE */
2750
2751/* BEGIN_CASE depends_on:MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED:!MBEDTLS_SSL_PROTO_TLS1_3:MBEDTLS_PKCS1_V15:MBEDTLS_RSA_C:MBEDTLS_SSL_HAVE_AES:MBEDTLS_ECP_HAVE_SECP384R1:MBEDTLS_DEBUG_C:MBEDTLS_SSL_MAX_FRAGMENT_LENGTH:MBEDTLS_SSL_HAVE_CBC:MBEDTLS_MD_CAN_SHA256:MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED */
2752void handshake_fragmentation(int mfl,
2753                             int expected_srv_hs_fragmentation,
2754                             int expected_cli_hs_fragmentation)
2755{
2756    mbedtls_test_handshake_test_options options;
2757    mbedtls_test_ssl_log_pattern srv_pattern, cli_pattern;
2758
2759    srv_pattern.pattern = cli_pattern.pattern = "found fragmented DTLS handshake";
2760    srv_pattern.counter = 0;
2761    cli_pattern.counter = 0;
2762
2763    mbedtls_test_init_handshake_options(&options);
2764    options.dtls = 1;
2765    options.expected_negotiated_version = MBEDTLS_SSL_VERSION_TLS1_2;
2766    options.mfl = mfl;
2767    /* Set cipher to one using CBC so that record splitting can be tested */
2768    options.cipher = "TLS-DHE-RSA-WITH-AES-256-CBC-SHA256";
2769    options.srv_auth_mode = MBEDTLS_SSL_VERIFY_REQUIRED;
2770    options.srv_log_obj = &srv_pattern;
2771    options.cli_log_obj = &cli_pattern;
2772    options.srv_log_fun = mbedtls_test_ssl_log_analyzer;
2773    options.cli_log_fun = mbedtls_test_ssl_log_analyzer;
2774
2775    mbedtls_test_ssl_perform_handshake(&options);
2776
2777    /* Test if the server received a fragmented handshake */
2778    if (expected_srv_hs_fragmentation) {
2779        TEST_ASSERT(srv_pattern.counter >= 1);
2780    }
2781    /* Test if the client received a fragmented handshake */
2782    if (expected_cli_hs_fragmentation) {
2783        TEST_ASSERT(cli_pattern.counter >= 1);
2784    }
2785
2786exit:
2787    mbedtls_test_free_handshake_options(&options);
2788}
2789/* END_CASE */
2790
2791/* BEGIN_CASE depends_on:MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED:!MBEDTLS_SSL_PROTO_TLS1_3:MBEDTLS_PKCS1_V15:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_RSA_C:MBEDTLS_ECP_HAVE_SECP384R1:MBEDTLS_SSL_PROTO_DTLS:MBEDTLS_SSL_RENEGOTIATION:MBEDTLS_MD_CAN_SHA256:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY */
2792void renegotiation(int legacy_renegotiation)
2793{
2794    mbedtls_test_handshake_test_options options;
2795    mbedtls_test_init_handshake_options(&options);
2796
2797    options.renegotiate = 1;
2798    options.legacy_renegotiation = legacy_renegotiation;
2799    options.dtls = 1;
2800    options.expected_negotiated_version = MBEDTLS_SSL_VERSION_TLS1_2;
2801
2802    mbedtls_test_ssl_perform_handshake(&options);
2803
2804    /* The goto below is used to avoid an "unused label" warning.*/
2805    goto exit;
2806exit:
2807    mbedtls_test_free_handshake_options(&options);
2808}
2809/* END_CASE */
2810
2811/* BEGIN_CASE depends_on:MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED:MBEDTLS_PKCS1_V15:MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_RSA_C:MBEDTLS_ECP_HAVE_SECP384R1:MBEDTLS_MD_CAN_SHA256 */
2812void resize_buffers(int mfl, int renegotiation, int legacy_renegotiation,
2813                    int serialize, int dtls, char *cipher)
2814{
2815    mbedtls_test_handshake_test_options options;
2816    mbedtls_test_init_handshake_options(&options);
2817
2818    options.mfl = mfl;
2819    options.cipher = cipher;
2820    options.renegotiate = renegotiation;
2821    options.legacy_renegotiation = legacy_renegotiation;
2822    options.serialize = serialize;
2823    options.dtls = dtls;
2824    if (dtls) {
2825        options.expected_negotiated_version = MBEDTLS_SSL_VERSION_TLS1_2;
2826    }
2827    options.resize_buffers = 1;
2828
2829    mbedtls_test_ssl_perform_handshake(&options);
2830
2831    /* The goto below is used to avoid an "unused label" warning.*/
2832    goto exit;
2833exit:
2834    mbedtls_test_free_handshake_options(&options);
2835}
2836/* END_CASE */
2837
2838/* BEGIN_CASE depends_on:MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED:!MBEDTLS_SSL_PROTO_TLS1_3:MBEDTLS_PKCS1_V15:MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH:MBEDTLS_SSL_CONTEXT_SERIALIZATION:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_RSA_C:MBEDTLS_ECP_HAVE_SECP384R1:MBEDTLS_SSL_PROTO_DTLS:MBEDTLS_MD_CAN_SHA256:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY */
2839void resize_buffers_serialize_mfl(int mfl)
2840{
2841    test_resize_buffers(mfl, 0, MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION, 1, 1,
2842                        (char *) "");
2843    /* The goto below is used to avoid an "unused label" warning.*/
2844    goto exit;
2845}
2846/* END_CASE */
2847
2848/* BEGIN_CASE depends_on:MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED:!MBEDTLS_SSL_PROTO_TLS1_3:MBEDTLS_PKCS1_V15:MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH:MBEDTLS_SSL_RENEGOTIATION:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_RSA_C:MBEDTLS_ECP_HAVE_SECP384R1:MBEDTLS_MD_CAN_SHA256:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY */
2849void resize_buffers_renegotiate_mfl(int mfl, int legacy_renegotiation,
2850                                    char *cipher)
2851{
2852    test_resize_buffers(mfl, 1, legacy_renegotiation, 0, 1, cipher);
2853    /* The goto below is used to avoid an "unused label" warning.*/
2854    goto exit;
2855}
2856/* END_CASE */
2857
2858/* BEGIN_CASE depends_on:MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED */
2859void test_multiple_psks()
2860{
2861    unsigned char psk0[10] = { 0 };
2862    unsigned char psk0_identity[] = { 'f', 'o', 'o' };
2863
2864    unsigned char psk1[10] = { 0 };
2865    unsigned char psk1_identity[] = { 'b', 'a', 'r' };
2866
2867    mbedtls_ssl_config conf;
2868
2869    mbedtls_ssl_config_init(&conf);
2870    MD_OR_USE_PSA_INIT();
2871
2872    TEST_ASSERT(mbedtls_ssl_conf_psk(&conf,
2873                                     psk0, sizeof(psk0),
2874                                     psk0_identity, sizeof(psk0_identity)) == 0);
2875    TEST_ASSERT(mbedtls_ssl_conf_psk(&conf,
2876                                     psk1, sizeof(psk1),
2877                                     psk1_identity, sizeof(psk1_identity)) ==
2878                MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE);
2879
2880exit:
2881    mbedtls_ssl_config_free(&conf);
2882    MD_OR_USE_PSA_DONE();
2883}
2884/* END_CASE */
2885
2886/* BEGIN_CASE depends_on:MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED:MBEDTLS_USE_PSA_CRYPTO */
2887void test_multiple_psks_opaque(int mode)
2888{
2889    /*
2890     * Mode 0: Raw PSK, then opaque PSK
2891     * Mode 1: Opaque PSK, then raw PSK
2892     * Mode 2: 2x opaque PSK
2893     */
2894
2895    unsigned char psk0_raw[10] = { 0 };
2896    unsigned char psk0_raw_identity[] = { 'f', 'o', 'o' };
2897
2898    mbedtls_svc_key_id_t psk0_opaque = mbedtls_svc_key_id_make(0x1, (psa_key_id_t) 1);
2899
2900    unsigned char psk0_opaque_identity[] = { 'f', 'o', 'o' };
2901
2902    unsigned char psk1_raw[10] = { 0 };
2903    unsigned char psk1_raw_identity[] = { 'b', 'a', 'r' };
2904
2905    mbedtls_svc_key_id_t psk1_opaque = mbedtls_svc_key_id_make(0x1, (psa_key_id_t) 2);
2906
2907    unsigned char psk1_opaque_identity[] = { 'b', 'a', 'r' };
2908
2909    mbedtls_ssl_config conf;
2910
2911    mbedtls_ssl_config_init(&conf);
2912    MD_OR_USE_PSA_INIT();
2913
2914    switch (mode) {
2915        case 0:
2916
2917            TEST_ASSERT(mbedtls_ssl_conf_psk(&conf,
2918                                             psk0_raw, sizeof(psk0_raw),
2919                                             psk0_raw_identity, sizeof(psk0_raw_identity))
2920                        == 0);
2921            TEST_ASSERT(mbedtls_ssl_conf_psk_opaque(&conf,
2922                                                    psk1_opaque,
2923                                                    psk1_opaque_identity,
2924                                                    sizeof(psk1_opaque_identity))
2925                        == MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE);
2926            break;
2927
2928        case 1:
2929
2930            TEST_ASSERT(mbedtls_ssl_conf_psk_opaque(&conf,
2931                                                    psk0_opaque,
2932                                                    psk0_opaque_identity,
2933                                                    sizeof(psk0_opaque_identity))
2934                        == 0);
2935            TEST_ASSERT(mbedtls_ssl_conf_psk(&conf,
2936                                             psk1_raw, sizeof(psk1_raw),
2937                                             psk1_raw_identity, sizeof(psk1_raw_identity))
2938                        == MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE);
2939
2940            break;
2941
2942        case 2:
2943
2944            TEST_ASSERT(mbedtls_ssl_conf_psk_opaque(&conf,
2945                                                    psk0_opaque,
2946                                                    psk0_opaque_identity,
2947                                                    sizeof(psk0_opaque_identity))
2948                        == 0);
2949            TEST_ASSERT(mbedtls_ssl_conf_psk_opaque(&conf,
2950                                                    psk1_opaque,
2951                                                    psk1_opaque_identity,
2952                                                    sizeof(psk1_opaque_identity))
2953                        == MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE);
2954
2955            break;
2956
2957        default:
2958            TEST_ASSERT(0);
2959            break;
2960    }
2961
2962exit:
2963    mbedtls_ssl_config_free(&conf);
2964    MD_OR_USE_PSA_DONE();
2965
2966}
2967/* END_CASE */
2968
2969/* BEGIN_CASE */
2970void conf_version(int endpoint, int transport,
2971                  int min_tls_version, int max_tls_version,
2972                  int expected_ssl_setup_result)
2973{
2974    mbedtls_ssl_config conf;
2975    mbedtls_ssl_context ssl;
2976
2977    mbedtls_ssl_config_init(&conf);
2978    mbedtls_ssl_init(&ssl);
2979    MD_OR_USE_PSA_INIT();
2980
2981    mbedtls_ssl_conf_endpoint(&conf, endpoint);
2982    mbedtls_ssl_conf_transport(&conf, transport);
2983    mbedtls_ssl_conf_min_tls_version(&conf, min_tls_version);
2984    mbedtls_ssl_conf_max_tls_version(&conf, max_tls_version);
2985    mbedtls_ssl_conf_rng(&conf, mbedtls_test_random, NULL);
2986
2987    TEST_ASSERT(mbedtls_ssl_setup(&ssl, &conf) == expected_ssl_setup_result);
2988    TEST_EQUAL(mbedtls_ssl_conf_get_endpoint(
2989                   mbedtls_ssl_context_get_config(&ssl)), endpoint);
2990
2991    mbedtls_ssl_free(&ssl);
2992    mbedtls_ssl_config_free(&conf);
2993
2994exit:
2995    MD_OR_USE_PSA_DONE();
2996}
2997/* END_CASE */
2998
2999/* BEGIN_CASE depends_on:MBEDTLS_ECP_C:!MBEDTLS_DEPRECATED_REMOVED:!MBEDTLS_DEPRECATED_WARNING:MBEDTLS_ECP_HAVE_SECP192R1:MBEDTLS_ECP_HAVE_SECP224R1:MBEDTLS_ECP_HAVE_SECP256R1 */
3000void conf_curve()
3001{
3002
3003    mbedtls_ecp_group_id curve_list[] = { MBEDTLS_ECP_DP_SECP192R1,
3004                                          MBEDTLS_ECP_DP_SECP224R1,
3005                                          MBEDTLS_ECP_DP_SECP256R1,
3006                                          MBEDTLS_ECP_DP_NONE };
3007    uint16_t iana_tls_group_list[] = { MBEDTLS_SSL_IANA_TLS_GROUP_SECP192R1,
3008                                       MBEDTLS_SSL_IANA_TLS_GROUP_SECP224R1,
3009                                       MBEDTLS_SSL_IANA_TLS_GROUP_SECP256R1,
3010                                       MBEDTLS_SSL_IANA_TLS_GROUP_NONE };
3011
3012    mbedtls_ssl_config conf;
3013    mbedtls_ssl_config_init(&conf);
3014#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
3015    mbedtls_ssl_conf_max_tls_version(&conf, MBEDTLS_SSL_VERSION_TLS1_2);
3016    mbedtls_ssl_conf_min_tls_version(&conf, MBEDTLS_SSL_VERSION_TLS1_2);
3017#else
3018    mbedtls_ssl_conf_max_tls_version(&conf, MBEDTLS_SSL_VERSION_TLS1_3);
3019    mbedtls_ssl_conf_min_tls_version(&conf, MBEDTLS_SSL_VERSION_TLS1_3);
3020#endif
3021    mbedtls_ssl_conf_curves(&conf, curve_list);
3022
3023    mbedtls_ssl_context ssl;
3024    mbedtls_ssl_init(&ssl);
3025    MD_OR_USE_PSA_INIT();
3026
3027    mbedtls_ssl_conf_rng(&conf, mbedtls_test_random, NULL);
3028
3029    TEST_ASSERT(mbedtls_ssl_setup(&ssl, &conf) == 0);
3030
3031    TEST_ASSERT(ssl.handshake != NULL && ssl.handshake->group_list != NULL);
3032    TEST_ASSERT(ssl.conf != NULL && ssl.conf->group_list == NULL);
3033
3034    TEST_EQUAL(ssl.handshake->
3035               group_list[ARRAY_LENGTH(iana_tls_group_list) - 1],
3036               MBEDTLS_SSL_IANA_TLS_GROUP_NONE);
3037
3038    for (size_t i = 0; i < ARRAY_LENGTH(iana_tls_group_list); i++) {
3039        TEST_EQUAL(iana_tls_group_list[i], ssl.handshake->group_list[i]);
3040    }
3041
3042exit:
3043    mbedtls_ssl_free(&ssl);
3044    mbedtls_ssl_config_free(&conf);
3045    MD_OR_USE_PSA_DONE();
3046}
3047/* END_CASE */
3048
3049/* BEGIN_CASE depends_on:MBEDTLS_DEPRECATED_REMOVED */
3050void conf_group()
3051{
3052    uint16_t iana_tls_group_list[] = { MBEDTLS_SSL_IANA_TLS_GROUP_SECP192R1,
3053                                       MBEDTLS_SSL_IANA_TLS_GROUP_SECP224R1,
3054                                       MBEDTLS_SSL_IANA_TLS_GROUP_SECP256R1,
3055                                       MBEDTLS_SSL_IANA_TLS_GROUP_NONE };
3056
3057    mbedtls_ssl_config conf;
3058    mbedtls_ssl_config_init(&conf);
3059
3060    mbedtls_ssl_conf_rng(&conf, mbedtls_test_random, NULL);
3061    mbedtls_ssl_conf_max_tls_version(&conf, MBEDTLS_SSL_VERSION_TLS1_2);
3062    mbedtls_ssl_conf_min_tls_version(&conf, MBEDTLS_SSL_VERSION_TLS1_2);
3063
3064    mbedtls_ssl_conf_groups(&conf, iana_tls_group_list);
3065
3066    mbedtls_ssl_context ssl;
3067    mbedtls_ssl_init(&ssl);
3068    MD_OR_USE_PSA_INIT();
3069
3070    TEST_ASSERT(mbedtls_ssl_setup(&ssl, &conf) == 0);
3071
3072    TEST_ASSERT(ssl.conf != NULL && ssl.conf->group_list != NULL);
3073
3074    TEST_EQUAL(ssl.conf->
3075               group_list[ARRAY_LENGTH(iana_tls_group_list) - 1],
3076               MBEDTLS_SSL_IANA_TLS_GROUP_NONE);
3077
3078    for (size_t i = 0; i < ARRAY_LENGTH(iana_tls_group_list); i++) {
3079        TEST_EQUAL(iana_tls_group_list[i], ssl.conf->group_list[i]);
3080    }
3081
3082exit:
3083    mbedtls_ssl_free(&ssl);
3084    mbedtls_ssl_config_free(&conf);
3085    MD_OR_USE_PSA_DONE();
3086}
3087/* END_CASE */
3088
3089/* BEGIN_CASE depends_on:MBEDTLS_SSL_SRV_C:MBEDTLS_SSL_CACHE_C:!MBEDTLS_SSL_PROTO_TLS1_3:MBEDTLS_DEBUG_C:MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED:MBEDTLS_RSA_C:MBEDTLS_ECP_HAVE_SECP384R1:MBEDTLS_PKCS1_V15:MBEDTLS_MD_CAN_SHA256 */
3090void force_bad_session_id_len()
3091{
3092    enum { BUFFSIZE = 1024 };
3093    mbedtls_test_handshake_test_options options;
3094    mbedtls_test_ssl_endpoint client, server;
3095    mbedtls_test_ssl_log_pattern srv_pattern, cli_pattern;
3096    mbedtls_test_message_socket_context server_context, client_context;
3097
3098    srv_pattern.pattern = cli_pattern.pattern = "cache did not store session";
3099    srv_pattern.counter = 0;
3100    mbedtls_test_init_handshake_options(&options);
3101
3102    options.srv_log_obj = &srv_pattern;
3103    options.srv_log_fun = mbedtls_test_ssl_log_analyzer;
3104
3105    mbedtls_platform_zeroize(&client, sizeof(client));
3106    mbedtls_platform_zeroize(&server, sizeof(server));
3107
3108    mbedtls_test_message_socket_init(&server_context);
3109    mbedtls_test_message_socket_init(&client_context);
3110    MD_OR_USE_PSA_INIT();
3111
3112    TEST_ASSERT(mbedtls_test_ssl_endpoint_init(&client, MBEDTLS_SSL_IS_CLIENT,
3113                                               &options, NULL, NULL,
3114                                               NULL) == 0);
3115
3116    TEST_ASSERT(mbedtls_test_ssl_endpoint_init(&server, MBEDTLS_SSL_IS_SERVER,
3117                                               &options, NULL, NULL, NULL) == 0);
3118
3119    mbedtls_debug_set_threshold(1);
3120    mbedtls_ssl_conf_dbg(&server.conf, options.srv_log_fun,
3121                         options.srv_log_obj);
3122
3123    TEST_ASSERT(mbedtls_test_mock_socket_connect(&(client.socket),
3124                                                 &(server.socket),
3125                                                 BUFFSIZE) == 0);
3126
3127    TEST_ASSERT(mbedtls_test_move_handshake_to_state(
3128                    &(client.ssl), &(server.ssl), MBEDTLS_SSL_HANDSHAKE_WRAPUP)
3129                ==  0);
3130    /* Force a bad session_id_len that will be read by the server in
3131     * mbedtls_ssl_cache_set. */
3132    server.ssl.session_negotiate->id_len = 33;
3133    if (options.cli_msg_len != 0 || options.srv_msg_len != 0) {
3134        /* Start data exchanging test */
3135        TEST_ASSERT(mbedtls_test_ssl_exchange_data(
3136                        &(client.ssl), options.cli_msg_len,
3137                        options.expected_cli_fragments,
3138                        &(server.ssl), options.srv_msg_len,
3139                        options.expected_srv_fragments)
3140                    == 0);
3141    }
3142
3143    /* Make sure that the cache did not store the session */
3144    TEST_EQUAL(srv_pattern.counter, 1);
3145exit:
3146    mbedtls_test_ssl_endpoint_free(&client, NULL);
3147    mbedtls_test_ssl_endpoint_free(&server, NULL);
3148    mbedtls_test_free_handshake_options(&options);
3149    mbedtls_debug_set_threshold(0);
3150    MD_OR_USE_PSA_DONE();
3151}
3152/* END_CASE */
3153
3154/* BEGIN_CASE depends_on:MBEDTLS_SSL_SRV_C:MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE:MBEDTLS_TEST_HOOKS */
3155void cookie_parsing(data_t *cookie, int exp_ret)
3156{
3157    mbedtls_ssl_context ssl;
3158    mbedtls_ssl_config conf;
3159    size_t len;
3160
3161    mbedtls_ssl_init(&ssl);
3162    mbedtls_ssl_config_init(&conf);
3163    USE_PSA_INIT();
3164
3165    TEST_EQUAL(mbedtls_ssl_config_defaults(&conf, MBEDTLS_SSL_IS_SERVER,
3166                                           MBEDTLS_SSL_TRANSPORT_DATAGRAM,
3167                                           MBEDTLS_SSL_PRESET_DEFAULT),
3168               0);
3169    mbedtls_ssl_conf_rng(&conf, mbedtls_test_random, NULL);
3170
3171    TEST_EQUAL(mbedtls_ssl_setup(&ssl, &conf), 0);
3172    TEST_EQUAL(mbedtls_ssl_check_dtls_clihlo_cookie(&ssl, ssl.cli_id,
3173                                                    ssl.cli_id_len,
3174                                                    cookie->x, cookie->len,
3175                                                    ssl.out_buf,
3176                                                    MBEDTLS_SSL_OUT_CONTENT_LEN,
3177                                                    &len),
3178               exp_ret);
3179
3180exit:
3181    mbedtls_ssl_free(&ssl);
3182    mbedtls_ssl_config_free(&conf);
3183    USE_PSA_DONE();
3184}
3185/* END_CASE */
3186
3187/* BEGIN_CASE depends_on:MBEDTLS_TIMING_C:MBEDTLS_HAVE_TIME */
3188void timing_final_delay_accessor()
3189{
3190    mbedtls_timing_delay_context    delay_context;
3191
3192    USE_PSA_INIT();
3193    mbedtls_timing_set_delay(&delay_context, 50, 100);
3194
3195    TEST_ASSERT(mbedtls_timing_get_final_delay(&delay_context) == 100);
3196
3197exit:
3198    USE_PSA_DONE();
3199}
3200/* END_CASE */
3201
3202/* BEGIN_CASE depends_on:MBEDTLS_SSL_DTLS_CONNECTION_ID */
3203void cid_sanity()
3204{
3205    mbedtls_ssl_context ssl;
3206    mbedtls_ssl_config conf;
3207
3208    unsigned char own_cid[MBEDTLS_SSL_CID_IN_LEN_MAX];
3209    unsigned char test_cid[MBEDTLS_SSL_CID_IN_LEN_MAX];
3210    int cid_enabled;
3211    size_t own_cid_len;
3212
3213    mbedtls_test_rnd_std_rand(NULL, own_cid, sizeof(own_cid));
3214
3215    mbedtls_ssl_init(&ssl);
3216    mbedtls_ssl_config_init(&conf);
3217    MD_OR_USE_PSA_INIT();
3218
3219    TEST_ASSERT(mbedtls_ssl_config_defaults(&conf,
3220                                            MBEDTLS_SSL_IS_CLIENT,
3221                                            MBEDTLS_SSL_TRANSPORT_STREAM,
3222                                            MBEDTLS_SSL_PRESET_DEFAULT)
3223                == 0);
3224    mbedtls_ssl_conf_rng(&conf, mbedtls_test_random, NULL);
3225
3226    TEST_ASSERT(mbedtls_ssl_setup(&ssl, &conf) == 0);
3227
3228    /* Can't use CID functions with stream transport. */
3229    TEST_ASSERT(mbedtls_ssl_set_cid(&ssl, MBEDTLS_SSL_CID_ENABLED, own_cid,
3230                                    sizeof(own_cid))
3231                == MBEDTLS_ERR_SSL_BAD_INPUT_DATA);
3232
3233    TEST_ASSERT(mbedtls_ssl_get_own_cid(&ssl, &cid_enabled, test_cid,
3234                                        &own_cid_len)
3235                == MBEDTLS_ERR_SSL_BAD_INPUT_DATA);
3236
3237    TEST_ASSERT(mbedtls_ssl_config_defaults(&conf,
3238                                            MBEDTLS_SSL_IS_CLIENT,
3239                                            MBEDTLS_SSL_TRANSPORT_DATAGRAM,
3240                                            MBEDTLS_SSL_PRESET_DEFAULT)
3241                == 0);
3242
3243    /* Attempt to set config cid size too big. */
3244    TEST_ASSERT(mbedtls_ssl_conf_cid(&conf, MBEDTLS_SSL_CID_IN_LEN_MAX + 1,
3245                                     MBEDTLS_SSL_UNEXPECTED_CID_IGNORE)
3246                == MBEDTLS_ERR_SSL_BAD_INPUT_DATA);
3247
3248    TEST_ASSERT(mbedtls_ssl_conf_cid(&conf, sizeof(own_cid),
3249                                     MBEDTLS_SSL_UNEXPECTED_CID_IGNORE)
3250                == 0);
3251
3252    /* Attempt to set CID length not matching config. */
3253    TEST_ASSERT(mbedtls_ssl_set_cid(&ssl, MBEDTLS_SSL_CID_ENABLED, own_cid,
3254                                    MBEDTLS_SSL_CID_IN_LEN_MAX - 1)
3255                == MBEDTLS_ERR_SSL_BAD_INPUT_DATA);
3256
3257    TEST_ASSERT(mbedtls_ssl_set_cid(&ssl, MBEDTLS_SSL_CID_ENABLED, own_cid,
3258                                    sizeof(own_cid))
3259                == 0);
3260
3261    /* Test we get back what we put in. */
3262    TEST_ASSERT(mbedtls_ssl_get_own_cid(&ssl, &cid_enabled, test_cid,
3263                                        &own_cid_len)
3264                == 0);
3265
3266    TEST_EQUAL(cid_enabled, MBEDTLS_SSL_CID_ENABLED);
3267    TEST_MEMORY_COMPARE(own_cid, own_cid_len, test_cid, own_cid_len);
3268
3269    /* Test disabling works. */
3270    TEST_ASSERT(mbedtls_ssl_set_cid(&ssl, MBEDTLS_SSL_CID_DISABLED, NULL,
3271                                    0)
3272                == 0);
3273
3274    TEST_ASSERT(mbedtls_ssl_get_own_cid(&ssl, &cid_enabled, test_cid,
3275                                        &own_cid_len)
3276                == 0);
3277
3278    TEST_EQUAL(cid_enabled, MBEDTLS_SSL_CID_DISABLED);
3279
3280exit:
3281    mbedtls_ssl_free(&ssl);
3282    mbedtls_ssl_config_free(&conf);
3283    MD_OR_USE_PSA_DONE();
3284}
3285/* END_CASE */
3286
3287/* BEGIN_CASE depends_on:MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED:MBEDTLS_USE_PSA_CRYPTO:MBEDTLS_PKCS1_V15:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_ECP_HAVE_SECP256R1:MBEDTLS_RSA_C:MBEDTLS_ECP_HAVE_SECP384R1:MBEDTLS_PK_CAN_ECDSA_SOME */
3288void raw_key_agreement_fail(int bad_server_ecdhe_key)
3289{
3290    enum { BUFFSIZE = 17000 };
3291    mbedtls_test_ssl_endpoint client, server;
3292    mbedtls_psa_stats_t stats;
3293    size_t free_slots_before = -1;
3294    mbedtls_test_handshake_test_options client_options, server_options;
3295    mbedtls_test_init_handshake_options(&client_options);
3296    mbedtls_test_init_handshake_options(&server_options);
3297
3298    uint16_t iana_tls_group_list[] = { MBEDTLS_SSL_IANA_TLS_GROUP_SECP256R1,
3299                                       MBEDTLS_SSL_IANA_TLS_GROUP_NONE };
3300    MD_OR_USE_PSA_INIT();
3301    mbedtls_platform_zeroize(&client, sizeof(client));
3302    mbedtls_platform_zeroize(&server, sizeof(server));
3303
3304    /* Client side, force SECP256R1 to make one key bitflip fail
3305     * the raw key agreement. Flipping the first byte makes the
3306     * required 0x04 identifier invalid. */
3307    client_options.pk_alg = MBEDTLS_PK_ECDSA;
3308    client_options.group_list = iana_tls_group_list;
3309    TEST_EQUAL(mbedtls_test_ssl_endpoint_init(&client, MBEDTLS_SSL_IS_CLIENT,
3310                                              &client_options, NULL, NULL,
3311                                              NULL), 0);
3312
3313    /* Server side */
3314    server_options.pk_alg = MBEDTLS_PK_ECDSA;
3315    server_options.server_min_version = MBEDTLS_SSL_VERSION_TLS1_2;
3316    server_options.server_max_version = MBEDTLS_SSL_VERSION_TLS1_2;
3317    TEST_EQUAL(mbedtls_test_ssl_endpoint_init(&server, MBEDTLS_SSL_IS_SERVER,
3318                                              &server_options, NULL, NULL,
3319                                              NULL), 0);
3320
3321    TEST_EQUAL(mbedtls_test_mock_socket_connect(&(client.socket),
3322                                                &(server.socket),
3323                                                BUFFSIZE), 0);
3324
3325    TEST_EQUAL(mbedtls_test_move_handshake_to_state(
3326                   &(client.ssl), &(server.ssl),
3327                   MBEDTLS_SSL_CLIENT_KEY_EXCHANGE), 0);
3328
3329    mbedtls_psa_get_stats(&stats);
3330    /* Save the number of slots in use up to this point.
3331     * With PSA, one can be used for the ECDH private key. */
3332    free_slots_before = stats.empty_slots;
3333
3334    if (bad_server_ecdhe_key) {
3335        /* Force a simulated bitflip in the server key. to make the
3336         * raw key agreement in ssl_write_client_key_exchange fail. */
3337        (client.ssl).handshake->xxdh_psa_peerkey[0] ^= 0x02;
3338    }
3339
3340    TEST_EQUAL(mbedtls_test_move_handshake_to_state(
3341                   &(client.ssl), &(server.ssl), MBEDTLS_SSL_HANDSHAKE_OVER),
3342               bad_server_ecdhe_key ? MBEDTLS_ERR_SSL_HW_ACCEL_FAILED : 0);
3343
3344    mbedtls_psa_get_stats(&stats);
3345
3346    /* Make sure that the key slot is already destroyed in case of failure,
3347     * without waiting to close the connection. */
3348    if (bad_server_ecdhe_key) {
3349        TEST_EQUAL(free_slots_before, stats.empty_slots);
3350    }
3351
3352exit:
3353    mbedtls_test_ssl_endpoint_free(&client, NULL);
3354    mbedtls_test_ssl_endpoint_free(&server, NULL);
3355    mbedtls_test_free_handshake_options(&client_options);
3356    mbedtls_test_free_handshake_options(&server_options);
3357
3358    MD_OR_USE_PSA_DONE();
3359}
3360/* END_CASE */
3361/* BEGIN_CASE depends_on:MBEDTLS_TEST_HOOKS:MBEDTLS_SSL_PROTO_TLS1_3:!MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_SSL_CLI_C:MBEDTLS_SSL_SRV_C:MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED:MBEDTLS_ECP_HAVE_SECP384R1 */
3362void tls13_server_certificate_msg_invalid_vector_len()
3363{
3364    int ret = -1;
3365    mbedtls_test_ssl_endpoint client_ep, server_ep;
3366    unsigned char *buf, *end;
3367    size_t buf_len;
3368    int step = 0;
3369    int expected_result;
3370    mbedtls_ssl_chk_buf_ptr_args expected_chk_buf_ptr_args;
3371    mbedtls_test_handshake_test_options client_options;
3372    mbedtls_test_handshake_test_options server_options;
3373
3374    /*
3375     * Test set-up
3376     */
3377    mbedtls_platform_zeroize(&client_ep, sizeof(client_ep));
3378    mbedtls_platform_zeroize(&server_ep, sizeof(server_ep));
3379
3380    mbedtls_test_init_handshake_options(&client_options);
3381    MD_OR_USE_PSA_INIT();
3382
3383    client_options.pk_alg = MBEDTLS_PK_ECDSA;
3384    ret = mbedtls_test_ssl_endpoint_init(&client_ep, MBEDTLS_SSL_IS_CLIENT,
3385                                         &client_options, NULL, NULL, NULL);
3386    TEST_EQUAL(ret, 0);
3387
3388    mbedtls_test_init_handshake_options(&server_options);
3389    server_options.pk_alg = MBEDTLS_PK_ECDSA;
3390    ret = mbedtls_test_ssl_endpoint_init(&server_ep, MBEDTLS_SSL_IS_SERVER,
3391                                         &server_options, NULL, NULL, NULL);
3392    TEST_EQUAL(ret, 0);
3393
3394    ret = mbedtls_test_mock_socket_connect(&(client_ep.socket),
3395                                           &(server_ep.socket), 1024);
3396    TEST_EQUAL(ret, 0);
3397
3398    while (1) {
3399        mbedtls_test_set_step(++step);
3400
3401        ret = mbedtls_test_move_handshake_to_state(
3402            &(server_ep.ssl), &(client_ep.ssl),
3403            MBEDTLS_SSL_CERTIFICATE_VERIFY);
3404        TEST_EQUAL(ret, 0);
3405
3406        ret = mbedtls_ssl_flush_output(&(server_ep.ssl));
3407        TEST_EQUAL(ret, 0);
3408
3409        ret = mbedtls_test_move_handshake_to_state(
3410            &(client_ep.ssl), &(server_ep.ssl),
3411            MBEDTLS_SSL_SERVER_CERTIFICATE);
3412        TEST_EQUAL(ret, 0);
3413
3414        ret = mbedtls_ssl_tls13_fetch_handshake_msg(&(client_ep.ssl),
3415                                                    MBEDTLS_SSL_HS_CERTIFICATE,
3416                                                    &buf, &buf_len);
3417        TEST_EQUAL(ret, 0);
3418
3419        end = buf + buf_len;
3420
3421        /*
3422         * Tweak server Certificate message and parse it.
3423         */
3424
3425        ret = mbedtls_test_tweak_tls13_certificate_msg_vector_len(
3426            buf, &end, step, &expected_result, &expected_chk_buf_ptr_args);
3427
3428        if (ret != 0) {
3429            break;
3430        }
3431
3432        ret = mbedtls_ssl_tls13_parse_certificate(&(client_ep.ssl), buf, end);
3433        TEST_EQUAL(ret, expected_result);
3434
3435        TEST_ASSERT(mbedtls_ssl_cmp_chk_buf_ptr_fail_args(
3436                        &expected_chk_buf_ptr_args) == 0);
3437
3438        mbedtls_ssl_reset_chk_buf_ptr_fail_args();
3439
3440        ret = mbedtls_ssl_session_reset(&(client_ep.ssl));
3441        TEST_EQUAL(ret, 0);
3442
3443        ret = mbedtls_ssl_session_reset(&(server_ep.ssl));
3444        TEST_EQUAL(ret, 0);
3445    }
3446
3447exit:
3448    mbedtls_ssl_reset_chk_buf_ptr_fail_args();
3449    mbedtls_test_ssl_endpoint_free(&client_ep, NULL);
3450    mbedtls_test_ssl_endpoint_free(&server_ep, NULL);
3451    mbedtls_test_free_handshake_options(&client_options);
3452    mbedtls_test_free_handshake_options(&server_options);
3453    MD_OR_USE_PSA_DONE();
3454}
3455/* END_CASE */
3456
3457/* BEGIN_CASE depends_on:MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
3458void ssl_ecjpake_set_password(int use_opaque_arg)
3459{
3460    mbedtls_ssl_context ssl;
3461    mbedtls_ssl_config conf;
3462#if defined(MBEDTLS_USE_PSA_CRYPTO)
3463    mbedtls_svc_key_id_t pwd_slot = MBEDTLS_SVC_KEY_ID_INIT;
3464#else   /* MBEDTLS_USE_PSA_CRYPTO */
3465    (void) use_opaque_arg;
3466#endif  /* MBEDTLS_USE_PSA_CRYPTO */
3467    unsigned char pwd_string[sizeof(ECJPAKE_TEST_PWD)] = "";
3468    size_t pwd_len = 0;
3469    int ret;
3470
3471    mbedtls_ssl_init(&ssl);
3472    MD_OR_USE_PSA_INIT();
3473
3474    /* test with uninitalized SSL context */
3475    ECJPAKE_TEST_SET_PASSWORD(MBEDTLS_ERR_SSL_BAD_INPUT_DATA);
3476
3477    mbedtls_ssl_config_init(&conf);
3478
3479    TEST_EQUAL(mbedtls_ssl_config_defaults(&conf,
3480                                           MBEDTLS_SSL_IS_CLIENT,
3481                                           MBEDTLS_SSL_TRANSPORT_STREAM,
3482                                           MBEDTLS_SSL_PRESET_DEFAULT), 0);
3483    mbedtls_ssl_conf_rng(&conf, mbedtls_test_random, NULL);
3484
3485    TEST_EQUAL(mbedtls_ssl_setup(&ssl, &conf), 0);
3486
3487    /* test with empty password or unitialized password key (depending on use_opaque_arg) */
3488    ECJPAKE_TEST_SET_PASSWORD(MBEDTLS_ERR_SSL_BAD_INPUT_DATA);
3489
3490    pwd_len = strlen(ECJPAKE_TEST_PWD);
3491    memcpy(pwd_string, ECJPAKE_TEST_PWD, pwd_len);
3492
3493#if defined(MBEDTLS_USE_PSA_CRYPTO)
3494    if (use_opaque_arg) {
3495        psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
3496        psa_key_attributes_t check_attributes = PSA_KEY_ATTRIBUTES_INIT;
3497
3498        /* First try with an invalid usage */
3499        psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_HASH);
3500        psa_set_key_algorithm(&attributes, PSA_ALG_JPAKE);
3501        psa_set_key_type(&attributes, PSA_KEY_TYPE_PASSWORD);
3502
3503        PSA_ASSERT(psa_import_key(&attributes, pwd_string,
3504                                  pwd_len, &pwd_slot));
3505
3506        ECJPAKE_TEST_SET_PASSWORD(MBEDTLS_ERR_SSL_HW_ACCEL_FAILED);
3507
3508        /* check that the opaque key is still valid after failure */
3509        TEST_EQUAL(psa_get_key_attributes(pwd_slot, &check_attributes),
3510                   PSA_SUCCESS);
3511
3512        psa_destroy_key(pwd_slot);
3513
3514        /* Then set the correct usage */
3515        psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_DERIVE);
3516
3517        PSA_ASSERT(psa_import_key(&attributes, pwd_string,
3518                                  pwd_len, &pwd_slot));
3519    }
3520#endif  /* MBEDTLS_USE_PSA_CRYPTO */
3521
3522    /* final check which should work without errors */
3523    ECJPAKE_TEST_SET_PASSWORD(0);
3524
3525#if defined(MBEDTLS_USE_PSA_CRYPTO)
3526    if (use_opaque_arg) {
3527        psa_destroy_key(pwd_slot);
3528    }
3529#endif  /* MBEDTLS_USE_PSA_CRYPTO */
3530    mbedtls_ssl_free(&ssl);
3531    mbedtls_ssl_config_free(&conf);
3532
3533    MD_OR_USE_PSA_DONE();
3534}
3535/* END_CASE */
3536
3537/* BEGIN_CASE */
3538void elliptic_curve_get_properties()
3539{
3540    psa_key_type_t psa_type = PSA_KEY_TYPE_NONE;
3541    size_t psa_bits;
3542
3543    MD_OR_USE_PSA_INIT();
3544
3545#if defined(MBEDTLS_ECP_HAVE_SECP521R1) || defined(PSA_WANT_ECC_SECP_R1_521)
3546    TEST_AVAILABLE_ECC(25, MBEDTLS_ECP_DP_SECP521R1, PSA_ECC_FAMILY_SECP_R1, 521);
3547#else
3548    TEST_UNAVAILABLE_ECC(25, MBEDTLS_ECP_DP_SECP521R1, PSA_ECC_FAMILY_SECP_R1, 521);
3549#endif
3550#if defined(MBEDTLS_ECP_HAVE_BP512R1) || defined(PSA_WANT_ECC_BRAINPOOL_P_R1_512)
3551    TEST_AVAILABLE_ECC(28, MBEDTLS_ECP_DP_BP512R1, PSA_ECC_FAMILY_BRAINPOOL_P_R1, 512);
3552#else
3553    TEST_UNAVAILABLE_ECC(28, MBEDTLS_ECP_DP_BP512R1, PSA_ECC_FAMILY_BRAINPOOL_P_R1, 512);
3554#endif
3555#if defined(MBEDTLS_ECP_HAVE_SECP384R1) || defined(PSA_WANT_ECC_SECP_R1_384)
3556    TEST_AVAILABLE_ECC(24, MBEDTLS_ECP_DP_SECP384R1, PSA_ECC_FAMILY_SECP_R1, 384);
3557#else
3558    TEST_UNAVAILABLE_ECC(24, MBEDTLS_ECP_DP_SECP384R1, PSA_ECC_FAMILY_SECP_R1, 384);
3559#endif
3560#if defined(MBEDTLS_ECP_HAVE_BP384R1) || defined(PSA_WANT_ECC_BRAINPOOL_P_R1_384)
3561    TEST_AVAILABLE_ECC(27, MBEDTLS_ECP_DP_BP384R1, PSA_ECC_FAMILY_BRAINPOOL_P_R1, 384);
3562#else
3563    TEST_UNAVAILABLE_ECC(27, MBEDTLS_ECP_DP_BP384R1, PSA_ECC_FAMILY_BRAINPOOL_P_R1, 384);
3564#endif
3565#if defined(MBEDTLS_ECP_HAVE_SECP256R1) || defined(PSA_WANT_ECC_SECP_R1_256)
3566    TEST_AVAILABLE_ECC(23, MBEDTLS_ECP_DP_SECP256R1, PSA_ECC_FAMILY_SECP_R1, 256);
3567#else
3568    TEST_UNAVAILABLE_ECC(23, MBEDTLS_ECP_DP_SECP256R1, PSA_ECC_FAMILY_SECP_R1, 256);
3569#endif
3570#if defined(MBEDTLS_ECP_HAVE_SECP256K1) || defined(PSA_WANT_ECC_SECP_K1_256)
3571    TEST_AVAILABLE_ECC(22, MBEDTLS_ECP_DP_SECP256K1, PSA_ECC_FAMILY_SECP_K1, 256);
3572#else
3573    TEST_UNAVAILABLE_ECC(22, MBEDTLS_ECP_DP_SECP256K1, PSA_ECC_FAMILY_SECP_K1, 256);
3574#endif
3575#if defined(MBEDTLS_ECP_HAVE_BP256R1) || defined(PSA_WANT_ECC_BRAINPOOL_P_R1_256)
3576    TEST_AVAILABLE_ECC(26, MBEDTLS_ECP_DP_BP256R1, PSA_ECC_FAMILY_BRAINPOOL_P_R1, 256);
3577#else
3578    TEST_UNAVAILABLE_ECC(26, MBEDTLS_ECP_DP_BP256R1, PSA_ECC_FAMILY_BRAINPOOL_P_R1, 256);
3579#endif
3580#if defined(MBEDTLS_ECP_HAVE_SECP224R1) || defined(PSA_WANT_ECC_SECP_R1_224)
3581    TEST_AVAILABLE_ECC(21, MBEDTLS_ECP_DP_SECP224R1, PSA_ECC_FAMILY_SECP_R1, 224);
3582#else
3583    TEST_UNAVAILABLE_ECC(21, MBEDTLS_ECP_DP_SECP224R1, PSA_ECC_FAMILY_SECP_R1, 224);
3584#endif
3585#if defined(MBEDTLS_ECP_HAVE_SECP224K1) || defined(PSA_WANT_ECC_SECP_K1_224)
3586    TEST_AVAILABLE_ECC(20, MBEDTLS_ECP_DP_SECP224K1, PSA_ECC_FAMILY_SECP_K1, 224);
3587#else
3588    TEST_UNAVAILABLE_ECC(20, MBEDTLS_ECP_DP_SECP224K1, PSA_ECC_FAMILY_SECP_K1, 224);
3589#endif
3590#if defined(MBEDTLS_ECP_HAVE_SECP192R1) || defined(PSA_WANT_ECC_SECP_R1_192)
3591    TEST_AVAILABLE_ECC(19, MBEDTLS_ECP_DP_SECP192R1, PSA_ECC_FAMILY_SECP_R1, 192);
3592#else
3593    TEST_UNAVAILABLE_ECC(19, MBEDTLS_ECP_DP_SECP192R1, PSA_ECC_FAMILY_SECP_R1, 192);
3594#endif
3595#if defined(MBEDTLS_ECP_HAVE_SECP192K1) || defined(PSA_WANT_ECC_SECP_K1_192)
3596    TEST_AVAILABLE_ECC(18, MBEDTLS_ECP_DP_SECP192K1, PSA_ECC_FAMILY_SECP_K1, 192);
3597#else
3598    TEST_UNAVAILABLE_ECC(18, MBEDTLS_ECP_DP_SECP192K1, PSA_ECC_FAMILY_SECP_K1, 192);
3599#endif
3600#if defined(MBEDTLS_ECP_HAVE_CURVE25519) || defined(PSA_WANT_ECC_MONTGOMERY_255)
3601    TEST_AVAILABLE_ECC(29, MBEDTLS_ECP_DP_CURVE25519, PSA_ECC_FAMILY_MONTGOMERY, 255);
3602#else
3603    TEST_UNAVAILABLE_ECC(29, MBEDTLS_ECP_DP_CURVE25519, PSA_ECC_FAMILY_MONTGOMERY, 255);
3604#endif
3605#if defined(MBEDTLS_ECP_HAVE_CURVE448) || defined(PSA_WANT_ECC_MONTGOMERY_448)
3606    TEST_AVAILABLE_ECC(30, MBEDTLS_ECP_DP_CURVE448, PSA_ECC_FAMILY_MONTGOMERY, 448);
3607#else
3608    TEST_UNAVAILABLE_ECC(30, MBEDTLS_ECP_DP_CURVE448, PSA_ECC_FAMILY_MONTGOMERY, 448);
3609#endif
3610    goto exit;
3611exit:
3612    MD_OR_USE_PSA_DONE();
3613}
3614/* END_CASE */
3615
3616/* BEGIN_CASE depends_on:MBEDTLS_SSL_PROTO_TLS1_3:MBEDTLS_SSL_CLI_C:MBEDTLS_SSL_SRV_C:MBEDTLS_TEST_AT_LEAST_ONE_TLS1_3_CIPHERSUITE:MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED:MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED:MBEDTLS_MD_CAN_SHA256:MBEDTLS_ECP_HAVE_SECP256R1:MBEDTLS_ECP_HAVE_SECP384R1:MBEDTLS_PK_CAN_ECDSA_VERIFY:MBEDTLS_SSL_SESSION_TICKETS */
3617void tls13_resume_session_with_ticket()
3618{
3619    int ret = -1;
3620    mbedtls_test_ssl_endpoint client_ep, server_ep;
3621    mbedtls_test_handshake_test_options client_options;
3622    mbedtls_test_handshake_test_options server_options;
3623    mbedtls_ssl_session saved_session;
3624
3625    mbedtls_platform_zeroize(&client_ep, sizeof(client_ep));
3626    mbedtls_platform_zeroize(&server_ep, sizeof(server_ep));
3627    mbedtls_test_init_handshake_options(&client_options);
3628    mbedtls_test_init_handshake_options(&server_options);
3629    mbedtls_ssl_session_init(&saved_session);
3630
3631    PSA_INIT();
3632
3633    /*
3634     * Run first handshake to get a ticket from the server.
3635     */
3636    client_options.pk_alg = MBEDTLS_PK_ECDSA;
3637    server_options.pk_alg = MBEDTLS_PK_ECDSA;
3638
3639    ret = mbedtls_test_get_tls13_ticket(&client_options, &server_options,
3640                                        &saved_session);
3641    TEST_EQUAL(ret, 0);
3642
3643    /*
3644     * Prepare for handshake with the ticket.
3645     */
3646    ret = mbedtls_test_ssl_endpoint_init(&client_ep, MBEDTLS_SSL_IS_CLIENT,
3647                                         &client_options, NULL, NULL, NULL);
3648    TEST_EQUAL(ret, 0);
3649
3650    ret = mbedtls_test_ssl_endpoint_init(&server_ep, MBEDTLS_SSL_IS_SERVER,
3651                                         &server_options, NULL, NULL, NULL);
3652    TEST_EQUAL(ret, 0);
3653
3654    mbedtls_ssl_conf_session_tickets_cb(&server_ep.conf,
3655                                        mbedtls_test_ticket_write,
3656                                        mbedtls_test_ticket_parse,
3657                                        NULL);
3658    TEST_EQUAL(ret, 0);
3659
3660    ret = mbedtls_test_mock_socket_connect(&(client_ep.socket),
3661                                           &(server_ep.socket), 1024);
3662    TEST_EQUAL(ret, 0);
3663
3664    ret = mbedtls_ssl_set_session(&(client_ep.ssl), &saved_session);
3665    TEST_EQUAL(ret, 0);
3666
3667    /*
3668     * Handshake with ticket.
3669     *
3670     * Run the handshake up to MBEDTLS_SSL_HANDSHAKE_WRAPUP and not
3671     * MBEDTLS_SSL_HANDSHAKE_OVER to preserve handshake data for the checks
3672     * below.
3673     */
3674    TEST_EQUAL(mbedtls_test_move_handshake_to_state(
3675                   &(server_ep.ssl), &(client_ep.ssl),
3676                   MBEDTLS_SSL_HANDSHAKE_WRAPUP), 0);
3677
3678    TEST_EQUAL(server_ep.ssl.handshake->resume, 1);
3679    TEST_EQUAL(server_ep.ssl.handshake->new_session_tickets_count, 1);
3680    TEST_EQUAL(server_ep.ssl.handshake->key_exchange_mode,
3681               MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL);
3682
3683exit:
3684    mbedtls_test_ssl_endpoint_free(&client_ep, NULL);
3685    mbedtls_test_ssl_endpoint_free(&server_ep, NULL);
3686    mbedtls_test_free_handshake_options(&client_options);
3687    mbedtls_test_free_handshake_options(&server_options);
3688    mbedtls_ssl_session_free(&saved_session);
3689    PSA_DONE();
3690}
3691/* END_CASE */
3692
3693/*
3694 * The !MBEDTLS_SSL_PROTO_TLS1_2 dependency of tls13_read_early_data() below is
3695 * a temporary workaround to not run the test in Windows-2013 where there is
3696 * an issue with mbedtls_vsnprintf().
3697 */
3698/* BEGIN_CASE depends_on:!MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_SSL_EARLY_DATA:MBEDTLS_SSL_CLI_C:MBEDTLS_SSL_SRV_C:MBEDTLS_DEBUG_C:MBEDTLS_TEST_AT_LEAST_ONE_TLS1_3_CIPHERSUITE:MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED:MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED:MBEDTLS_MD_CAN_SHA256:MBEDTLS_ECP_HAVE_SECP256R1:MBEDTLS_ECP_HAVE_SECP384R1:MBEDTLS_PK_CAN_ECDSA_VERIFY:MBEDTLS_SSL_SESSION_TICKETS */
3699void tls13_read_early_data(int scenario)
3700{
3701    int ret = -1;
3702    unsigned char buf[64];
3703    const char *early_data = "This is early data.";
3704    size_t early_data_len = strlen(early_data);
3705    mbedtls_test_ssl_endpoint client_ep, server_ep;
3706    mbedtls_test_handshake_test_options client_options;
3707    mbedtls_test_handshake_test_options server_options;
3708    mbedtls_ssl_session saved_session;
3709    mbedtls_test_ssl_log_pattern server_pattern = { NULL, 0 };
3710    uint16_t group_list[3] = {
3711        MBEDTLS_SSL_IANA_TLS_GROUP_SECP256R1,
3712        MBEDTLS_SSL_IANA_TLS_GROUP_SECP384R1,
3713        MBEDTLS_SSL_IANA_TLS_GROUP_NONE
3714    };
3715
3716    mbedtls_platform_zeroize(&client_ep, sizeof(client_ep));
3717    mbedtls_platform_zeroize(&server_ep, sizeof(server_ep));
3718    mbedtls_test_init_handshake_options(&client_options);
3719    mbedtls_test_init_handshake_options(&server_options);
3720    mbedtls_ssl_session_init(&saved_session);
3721
3722    PSA_INIT();
3723
3724    /*
3725     * Run first handshake to get a ticket from the server.
3726     */
3727
3728    client_options.pk_alg = MBEDTLS_PK_ECDSA;
3729    client_options.group_list = group_list;
3730    client_options.early_data = MBEDTLS_SSL_EARLY_DATA_ENABLED;
3731    server_options.pk_alg = MBEDTLS_PK_ECDSA;
3732    server_options.group_list = group_list;
3733    server_options.early_data = MBEDTLS_SSL_EARLY_DATA_ENABLED;
3734
3735#if defined(MBEDTLS_SSL_ALPN)
3736    switch (scenario) {
3737        case TEST_EARLY_DATA_SAME_ALPN:
3738        case TEST_EARLY_DATA_DIFF_ALPN:
3739        case TEST_EARLY_DATA_NO_LATER_ALPN:
3740            client_options.alpn_list[0] = "ALPNExample";
3741            client_options.alpn_list[1] = NULL;
3742            server_options.alpn_list[0] = "ALPNExample";
3743            server_options.alpn_list[1] = NULL;
3744            break;
3745    }
3746#endif
3747
3748    ret = mbedtls_test_get_tls13_ticket(&client_options, &server_options,
3749                                        &saved_session);
3750    TEST_EQUAL(ret, 0);
3751
3752    /*
3753     * Prepare for handshake with the ticket.
3754     */
3755    switch (scenario) {
3756        case TEST_EARLY_DATA_ACCEPTED:
3757            break;
3758
3759        case TEST_EARLY_DATA_NO_INDICATION_SENT:
3760            client_options.early_data = MBEDTLS_SSL_EARLY_DATA_DISABLED;
3761            break;
3762
3763        case TEST_EARLY_DATA_SERVER_REJECTS:
3764            mbedtls_debug_set_threshold(3);
3765            server_pattern.pattern =
3766                "EarlyData: deprotect and discard app data records.";
3767            server_options.early_data = MBEDTLS_SSL_EARLY_DATA_DISABLED;
3768            break;
3769
3770        case TEST_EARLY_DATA_HRR:
3771            mbedtls_debug_set_threshold(3);
3772            server_pattern.pattern =
3773                "EarlyData: Ignore application message before 2nd ClientHello";
3774            server_options.group_list = group_list + 1;
3775            break;
3776#if defined(MBEDTLS_SSL_ALPN)
3777        case TEST_EARLY_DATA_SAME_ALPN:
3778            client_options.alpn_list[0] = "ALPNExample";
3779            client_options.alpn_list[1] = NULL;
3780            server_options.alpn_list[0] = "ALPNExample";
3781            server_options.alpn_list[1] = NULL;
3782            break;
3783        case TEST_EARLY_DATA_DIFF_ALPN:
3784        case TEST_EARLY_DATA_NO_INITIAL_ALPN:
3785            client_options.alpn_list[0] = "ALPNExample2";
3786            client_options.alpn_list[1] = NULL;
3787            server_options.alpn_list[0] = "ALPNExample2";
3788            server_options.alpn_list[1] = NULL;
3789            mbedtls_debug_set_threshold(3);
3790            server_pattern.pattern =
3791                "EarlyData: rejected, the selected ALPN is different "
3792                "from the one associated with the pre-shared key.";
3793            break;
3794        case TEST_EARLY_DATA_NO_LATER_ALPN:
3795            client_options.alpn_list[0] = NULL;
3796            server_options.alpn_list[0] = NULL;
3797            mbedtls_debug_set_threshold(3);
3798            server_pattern.pattern =
3799                "EarlyData: rejected, the selected ALPN is different "
3800                "from the one associated with the pre-shared key.";
3801            break;
3802#endif
3803
3804        default:
3805            TEST_FAIL("Unknown scenario.");
3806    }
3807
3808    ret = mbedtls_test_ssl_endpoint_init(&client_ep, MBEDTLS_SSL_IS_CLIENT,
3809                                         &client_options, NULL, NULL, NULL);
3810    TEST_EQUAL(ret, 0);
3811
3812    server_options.srv_log_fun = mbedtls_test_ssl_log_analyzer;
3813    server_options.srv_log_obj = &server_pattern;
3814    ret = mbedtls_test_ssl_endpoint_init(&server_ep, MBEDTLS_SSL_IS_SERVER,
3815                                         &server_options, NULL, NULL, NULL);
3816    TEST_EQUAL(ret, 0);
3817
3818    mbedtls_ssl_conf_session_tickets_cb(&server_ep.conf,
3819                                        mbedtls_test_ticket_write,
3820                                        mbedtls_test_ticket_parse,
3821                                        NULL);
3822
3823    ret = mbedtls_test_mock_socket_connect(&(client_ep.socket),
3824                                           &(server_ep.socket), 1024);
3825    TEST_EQUAL(ret, 0);
3826
3827    ret = mbedtls_ssl_set_session(&(client_ep.ssl), &saved_session);
3828    TEST_EQUAL(ret, 0);
3829
3830    /*
3831     * Handshake with ticket and send early data.
3832     */
3833    TEST_EQUAL(mbedtls_test_move_handshake_to_state(
3834                   &(client_ep.ssl), &(server_ep.ssl),
3835                   MBEDTLS_SSL_SERVER_HELLO), 0);
3836
3837    ret = mbedtls_ssl_write_early_data(&(client_ep.ssl),
3838                                       (unsigned char *) early_data,
3839                                       early_data_len);
3840
3841    if (client_ep.ssl.early_data_state !=
3842        MBEDTLS_SSL_EARLY_DATA_STATE_NO_IND_SENT) {
3843        TEST_EQUAL(ret, early_data_len);
3844    } else {
3845        TEST_EQUAL(ret, MBEDTLS_ERR_SSL_CANNOT_WRITE_EARLY_DATA);
3846    }
3847
3848    ret = mbedtls_test_move_handshake_to_state(
3849        &(server_ep.ssl), &(client_ep.ssl),
3850        MBEDTLS_SSL_HANDSHAKE_WRAPUP);
3851
3852    switch (scenario) {
3853        case TEST_EARLY_DATA_ACCEPTED:
3854#if defined(MBEDTLS_SSL_ALPN)
3855        case TEST_EARLY_DATA_SAME_ALPN:
3856#endif
3857            TEST_EQUAL(ret, MBEDTLS_ERR_SSL_RECEIVED_EARLY_DATA);
3858            TEST_EQUAL(server_ep.ssl.handshake->early_data_accepted, 1);
3859            TEST_EQUAL(mbedtls_ssl_read_early_data(&(server_ep.ssl),
3860                                                   buf, sizeof(buf)), early_data_len);
3861            TEST_MEMORY_COMPARE(buf, early_data_len, early_data, early_data_len);
3862            break;
3863
3864        case TEST_EARLY_DATA_NO_INDICATION_SENT:
3865            TEST_EQUAL(ret, 0);
3866            TEST_EQUAL(server_ep.ssl.handshake->early_data_accepted, 0);
3867            break;
3868
3869        case TEST_EARLY_DATA_SERVER_REJECTS: /* Intentional fallthrough */
3870        case TEST_EARLY_DATA_HRR:
3871#if defined(MBEDTLS_SSL_ALPN)
3872        case TEST_EARLY_DATA_DIFF_ALPN:
3873        case TEST_EARLY_DATA_NO_INITIAL_ALPN:
3874        case TEST_EARLY_DATA_NO_LATER_ALPN:
3875#endif
3876            TEST_EQUAL(ret, 0);
3877            TEST_EQUAL(server_ep.ssl.handshake->early_data_accepted, 0);
3878            TEST_EQUAL(server_pattern.counter, 1);
3879            break;
3880
3881        default:
3882            TEST_FAIL("Unknown scenario.");
3883    }
3884
3885    TEST_EQUAL(mbedtls_test_move_handshake_to_state(
3886                   &(server_ep.ssl), &(client_ep.ssl),
3887                   MBEDTLS_SSL_HANDSHAKE_OVER), 0);
3888
3889exit:
3890    mbedtls_test_ssl_endpoint_free(&client_ep, NULL);
3891    mbedtls_test_ssl_endpoint_free(&server_ep, NULL);
3892    mbedtls_test_free_handshake_options(&client_options);
3893    mbedtls_test_free_handshake_options(&server_options);
3894    mbedtls_ssl_session_free(&saved_session);
3895    mbedtls_debug_set_threshold(0);
3896    PSA_DONE();
3897}
3898/* END_CASE */
3899
3900/* BEGIN_CASE depends_on:MBEDTLS_SSL_EARLY_DATA:MBEDTLS_SSL_CLI_C:MBEDTLS_SSL_SRV_C:MBEDTLS_TEST_AT_LEAST_ONE_TLS1_3_CIPHERSUITE:MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED:MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED:MBEDTLS_MD_CAN_SHA256:MBEDTLS_ECP_HAVE_SECP256R1:MBEDTLS_ECP_HAVE_SECP384R1:MBEDTLS_PK_CAN_ECDSA_VERIFY:MBEDTLS_SSL_SESSION_TICKETS */
3901void tls13_cli_early_data_state(int scenario)
3902{
3903    int ret = -1;
3904    mbedtls_test_ssl_endpoint client_ep, server_ep;
3905    mbedtls_test_handshake_test_options client_options;
3906    mbedtls_test_handshake_test_options server_options;
3907    mbedtls_ssl_session saved_session;
3908    uint16_t group_list[3] = {
3909        MBEDTLS_SSL_IANA_TLS_GROUP_SECP256R1,
3910        MBEDTLS_SSL_IANA_TLS_GROUP_SECP384R1,
3911        MBEDTLS_SSL_IANA_TLS_GROUP_NONE
3912    };
3913    uint8_t client_random[MBEDTLS_CLIENT_HELLO_RANDOM_LEN];
3914
3915    mbedtls_platform_zeroize(&client_ep, sizeof(client_ep));
3916    mbedtls_platform_zeroize(&server_ep, sizeof(server_ep));
3917    mbedtls_test_init_handshake_options(&client_options);
3918    mbedtls_test_init_handshake_options(&server_options);
3919    mbedtls_ssl_session_init(&saved_session);
3920
3921    PSA_INIT();
3922
3923    /*
3924     * Run first handshake to get a ticket from the server.
3925     */
3926    client_options.pk_alg = MBEDTLS_PK_ECDSA;
3927    client_options.early_data = MBEDTLS_SSL_EARLY_DATA_ENABLED;
3928    server_options.pk_alg = MBEDTLS_PK_ECDSA;
3929    server_options.early_data = MBEDTLS_SSL_EARLY_DATA_ENABLED;
3930    if (scenario == TEST_EARLY_DATA_HRR) {
3931        client_options.group_list = group_list;
3932        server_options.group_list = group_list;
3933    }
3934
3935    ret = mbedtls_test_get_tls13_ticket(&client_options, &server_options,
3936                                        &saved_session);
3937    TEST_EQUAL(ret, 0);
3938
3939    /*
3940     * Prepare for handshake with the ticket.
3941     */
3942    switch (scenario) {
3943        case TEST_EARLY_DATA_ACCEPTED:
3944            break;
3945
3946        case TEST_EARLY_DATA_NO_INDICATION_SENT:
3947            client_options.early_data = MBEDTLS_SSL_EARLY_DATA_DISABLED;
3948            break;
3949
3950        case TEST_EARLY_DATA_SERVER_REJECTS:
3951            server_options.early_data = MBEDTLS_SSL_EARLY_DATA_DISABLED;
3952            break;
3953
3954        case TEST_EARLY_DATA_HRR:
3955            server_options.group_list = group_list + 1;
3956            break;
3957
3958        default:
3959            TEST_FAIL("Unknown scenario.");
3960    }
3961
3962    ret = mbedtls_test_ssl_endpoint_init(&client_ep, MBEDTLS_SSL_IS_CLIENT,
3963                                         &client_options, NULL, NULL, NULL);
3964    TEST_EQUAL(ret, 0);
3965
3966    ret = mbedtls_test_ssl_endpoint_init(&server_ep, MBEDTLS_SSL_IS_SERVER,
3967                                         &server_options, NULL, NULL, NULL);
3968    TEST_EQUAL(ret, 0);
3969
3970    mbedtls_ssl_conf_session_tickets_cb(&server_ep.conf,
3971                                        mbedtls_test_ticket_write,
3972                                        mbedtls_test_ticket_parse,
3973                                        NULL);
3974
3975    ret = mbedtls_test_mock_socket_connect(&(client_ep.socket),
3976                                           &(server_ep.socket), 1024);
3977    TEST_EQUAL(ret, 0);
3978
3979    ret = mbedtls_ssl_set_session(&(client_ep.ssl), &saved_session);
3980    TEST_EQUAL(ret, 0);
3981
3982    /*
3983     * Go through the handshake sequence, state by state, checking the early
3984     * data status each time.
3985     */
3986    do {
3987        int state = client_ep.ssl.state;
3988
3989        /* Progress the handshake from at least one state */
3990        while (client_ep.ssl.state == state) {
3991            ret = mbedtls_ssl_handshake_step(&(client_ep.ssl));
3992            TEST_ASSERT((ret == 0) ||
3993                        (ret == MBEDTLS_ERR_SSL_WANT_READ) ||
3994                        (ret == MBEDTLS_ERR_SSL_WANT_WRITE));
3995            if (client_ep.ssl.state != state) {
3996                break;
3997            }
3998            ret = mbedtls_ssl_handshake_step(&(server_ep.ssl));
3999            TEST_ASSERT((ret == 0) ||
4000                        (ret == MBEDTLS_ERR_SSL_WANT_READ) ||
4001                        (ret == MBEDTLS_ERR_SSL_WANT_WRITE));
4002        }
4003
4004        if (client_ep.ssl.state != MBEDTLS_SSL_HANDSHAKE_OVER) {
4005            TEST_EQUAL(mbedtls_ssl_get_early_data_status(&(client_ep.ssl)),
4006                       MBEDTLS_ERR_SSL_BAD_INPUT_DATA);
4007        }
4008
4009        switch (client_ep.ssl.state) {
4010            case MBEDTLS_SSL_CLIENT_HELLO:
4011                switch (scenario) {
4012                    case TEST_EARLY_DATA_ACCEPTED: /* Intentional fallthrough */
4013                    case TEST_EARLY_DATA_NO_INDICATION_SENT: /* Intentional fallthrough */
4014                    case TEST_EARLY_DATA_SERVER_REJECTS:
4015                        TEST_EQUAL(client_ep.ssl.early_data_state,
4016                                   MBEDTLS_SSL_EARLY_DATA_STATE_IDLE);
4017                        break;
4018
4019                    case TEST_EARLY_DATA_HRR:
4020                        if (!client_ep.ssl.handshake->hello_retry_request_flag) {
4021                            TEST_EQUAL(client_ep.ssl.early_data_state,
4022                                       MBEDTLS_SSL_EARLY_DATA_STATE_IDLE);
4023                        } else {
4024                            TEST_EQUAL(client_ep.ssl.early_data_state,
4025                                       MBEDTLS_SSL_EARLY_DATA_STATE_REJECTED);
4026                        }
4027                        break;
4028
4029                    default:
4030                        TEST_FAIL("Unknown scenario.");
4031                }
4032                break;
4033
4034            case MBEDTLS_SSL_SERVER_HELLO:
4035                switch (scenario) {
4036                    case TEST_EARLY_DATA_ACCEPTED: /* Intentional fallthrough */
4037                    case TEST_EARLY_DATA_SERVER_REJECTS:
4038                        TEST_EQUAL(client_ep.ssl.early_data_state,
4039                                   MBEDTLS_SSL_EARLY_DATA_STATE_CAN_WRITE);
4040                        break;
4041
4042                    case TEST_EARLY_DATA_NO_INDICATION_SENT:
4043                        TEST_EQUAL(client_ep.ssl.early_data_state,
4044                                   MBEDTLS_SSL_EARLY_DATA_STATE_NO_IND_SENT);
4045                        break;
4046
4047                    case TEST_EARLY_DATA_HRR:
4048                        if (!client_ep.ssl.handshake->hello_retry_request_flag) {
4049                            TEST_EQUAL(client_ep.ssl.early_data_state,
4050                                       MBEDTLS_SSL_EARLY_DATA_STATE_CAN_WRITE);
4051                            memcpy(client_random,
4052                                   client_ep.ssl.handshake->randbytes,
4053                                   MBEDTLS_CLIENT_HELLO_RANDOM_LEN);
4054                        } else {
4055                            TEST_EQUAL(client_ep.ssl.early_data_state,
4056                                       MBEDTLS_SSL_EARLY_DATA_STATE_REJECTED);
4057                            TEST_MEMORY_COMPARE(client_random,
4058                                                MBEDTLS_CLIENT_HELLO_RANDOM_LEN,
4059                                                client_ep.ssl.handshake->randbytes,
4060                                                MBEDTLS_CLIENT_HELLO_RANDOM_LEN);
4061                        }
4062                        break;
4063
4064                    default:
4065                        TEST_FAIL("Unknown scenario.");
4066                }
4067                break;
4068
4069            case MBEDTLS_SSL_ENCRYPTED_EXTENSIONS:
4070                switch (scenario) {
4071                    case TEST_EARLY_DATA_ACCEPTED: /* Intentional fallthrough */
4072                    case TEST_EARLY_DATA_SERVER_REJECTS:
4073                        TEST_EQUAL(client_ep.ssl.early_data_state,
4074                                   MBEDTLS_SSL_EARLY_DATA_STATE_CAN_WRITE);
4075                        break;
4076
4077                    case TEST_EARLY_DATA_NO_INDICATION_SENT:
4078                        TEST_EQUAL(client_ep.ssl.early_data_state,
4079                                   MBEDTLS_SSL_EARLY_DATA_STATE_NO_IND_SENT);
4080                        break;
4081
4082                    case TEST_EARLY_DATA_HRR:
4083                        TEST_EQUAL(client_ep.ssl.early_data_state,
4084                                   MBEDTLS_SSL_EARLY_DATA_STATE_REJECTED);
4085                        break;
4086
4087                    default:
4088                        TEST_FAIL("Unknown scenario.");
4089                }
4090                break;
4091
4092            case MBEDTLS_SSL_SERVER_FINISHED:
4093                switch (scenario) {
4094                    case TEST_EARLY_DATA_ACCEPTED:
4095                        TEST_EQUAL(client_ep.ssl.early_data_state,
4096                                   MBEDTLS_SSL_EARLY_DATA_STATE_ACCEPTED);
4097                        break;
4098
4099                    case TEST_EARLY_DATA_NO_INDICATION_SENT:
4100                        TEST_EQUAL(client_ep.ssl.early_data_state,
4101                                   MBEDTLS_SSL_EARLY_DATA_STATE_NO_IND_SENT);
4102                        break;
4103
4104                    case TEST_EARLY_DATA_SERVER_REJECTS: /* Intentional fallthrough */
4105                    case TEST_EARLY_DATA_HRR:
4106                        TEST_EQUAL(client_ep.ssl.early_data_state,
4107                                   MBEDTLS_SSL_EARLY_DATA_STATE_REJECTED);
4108                        break;
4109
4110                    default:
4111                        TEST_FAIL("Unknown scenario.");
4112                }
4113                break;
4114
4115            case MBEDTLS_SSL_END_OF_EARLY_DATA:
4116                TEST_EQUAL(scenario, TEST_EARLY_DATA_ACCEPTED);
4117                TEST_EQUAL(client_ep.ssl.early_data_state,
4118                           MBEDTLS_SSL_EARLY_DATA_STATE_SERVER_FINISHED_RECEIVED);
4119                break;
4120
4121            case MBEDTLS_SSL_CLIENT_CERTIFICATE:
4122                switch (scenario) {
4123                    case TEST_EARLY_DATA_ACCEPTED:
4124                        TEST_EQUAL(client_ep.ssl.early_data_state,
4125                                   MBEDTLS_SSL_EARLY_DATA_STATE_SERVER_FINISHED_RECEIVED);
4126                        break;
4127
4128                    case TEST_EARLY_DATA_NO_INDICATION_SENT:
4129                        TEST_EQUAL(client_ep.ssl.early_data_state,
4130                                   MBEDTLS_SSL_EARLY_DATA_STATE_NO_IND_SENT);
4131                        break;
4132
4133                    case TEST_EARLY_DATA_SERVER_REJECTS: /* Intentional fallthrough */
4134                    case TEST_EARLY_DATA_HRR:
4135                        TEST_EQUAL(client_ep.ssl.early_data_state,
4136                                   MBEDTLS_SSL_EARLY_DATA_STATE_REJECTED);
4137                        break;
4138
4139                    default:
4140                        TEST_FAIL("Unknown scenario.");
4141                }
4142                break;
4143
4144            case MBEDTLS_SSL_CLIENT_FINISHED:
4145                switch (scenario) {
4146                    case TEST_EARLY_DATA_ACCEPTED:
4147                        TEST_EQUAL(client_ep.ssl.early_data_state,
4148                                   MBEDTLS_SSL_EARLY_DATA_STATE_SERVER_FINISHED_RECEIVED);
4149                        break;
4150
4151                    case TEST_EARLY_DATA_NO_INDICATION_SENT:
4152                        TEST_EQUAL(client_ep.ssl.early_data_state,
4153                                   MBEDTLS_SSL_EARLY_DATA_STATE_NO_IND_SENT);
4154                        break;
4155
4156                    case TEST_EARLY_DATA_SERVER_REJECTS: /* Intentional fallthrough */
4157                    case TEST_EARLY_DATA_HRR:
4158                        TEST_EQUAL(client_ep.ssl.early_data_state,
4159                                   MBEDTLS_SSL_EARLY_DATA_STATE_REJECTED);
4160                        break;
4161
4162                    default:
4163                        TEST_FAIL("Unknown scenario.");
4164                }
4165                break;
4166
4167#if defined(MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE)
4168            case MBEDTLS_SSL_CLIENT_CCS_AFTER_CLIENT_HELLO:
4169                switch (scenario) {
4170                    case TEST_EARLY_DATA_ACCEPTED: /* Intentional fallthrough */
4171                    case TEST_EARLY_DATA_SERVER_REJECTS: /* Intentional fallthrough */
4172                    case TEST_EARLY_DATA_HRR:
4173                        TEST_EQUAL(client_ep.ssl.early_data_state,
4174                                   MBEDTLS_SSL_EARLY_DATA_STATE_IND_SENT);
4175                        break;
4176
4177                    default:
4178                        TEST_FAIL("Unexpected or unknown scenario.");
4179                }
4180                break;
4181
4182            case MBEDTLS_SSL_CLIENT_CCS_BEFORE_2ND_CLIENT_HELLO:
4183                TEST_ASSERT(scenario == TEST_EARLY_DATA_HRR);
4184                TEST_EQUAL(client_ep.ssl.early_data_state,
4185                           MBEDTLS_SSL_EARLY_DATA_STATE_REJECTED);
4186                break;
4187
4188            case MBEDTLS_SSL_CLIENT_CCS_AFTER_SERVER_FINISHED:
4189                switch (scenario) {
4190                    case TEST_EARLY_DATA_NO_INDICATION_SENT:
4191                        TEST_EQUAL(client_ep.ssl.early_data_state,
4192                                   MBEDTLS_SSL_EARLY_DATA_STATE_NO_IND_SENT);
4193                        break;
4194
4195                    case TEST_EARLY_DATA_SERVER_REJECTS: /* Intentional fallthrough */
4196                    case TEST_EARLY_DATA_HRR:
4197                        TEST_EQUAL(client_ep.ssl.early_data_state,
4198                                   MBEDTLS_SSL_EARLY_DATA_STATE_REJECTED);
4199                        break;
4200
4201                    default:
4202                        TEST_FAIL("Unexpected or unknown scenario.");
4203                }
4204                break;
4205#endif /* MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE */
4206
4207            case MBEDTLS_SSL_FLUSH_BUFFERS: /* Intentional fallthrough */
4208            case MBEDTLS_SSL_HANDSHAKE_WRAPUP: /* Intentional fallthrough */
4209            case MBEDTLS_SSL_HANDSHAKE_OVER:
4210                switch (scenario) {
4211                    case TEST_EARLY_DATA_ACCEPTED:
4212                        TEST_EQUAL(client_ep.ssl.early_data_state,
4213                                   MBEDTLS_SSL_EARLY_DATA_STATE_SERVER_FINISHED_RECEIVED);
4214                        break;
4215
4216                    case TEST_EARLY_DATA_NO_INDICATION_SENT:
4217                        TEST_EQUAL(client_ep.ssl.early_data_state,
4218                                   MBEDTLS_SSL_EARLY_DATA_STATE_NO_IND_SENT);
4219                        break;
4220
4221                    case TEST_EARLY_DATA_SERVER_REJECTS: /* Intentional fallthrough */
4222                    case TEST_EARLY_DATA_HRR:
4223                        TEST_EQUAL(client_ep.ssl.early_data_state,
4224                                   MBEDTLS_SSL_EARLY_DATA_STATE_REJECTED);
4225                        break;
4226
4227                    default:
4228                        TEST_FAIL("Unknown scenario.");
4229                }
4230                break;
4231
4232            default:
4233                TEST_FAIL("Unexpected state.");
4234        }
4235    } while (client_ep.ssl.state != MBEDTLS_SSL_HANDSHAKE_OVER);
4236
4237    ret = mbedtls_ssl_get_early_data_status(&(client_ep.ssl));
4238    switch (scenario) {
4239        case TEST_EARLY_DATA_ACCEPTED:
4240            TEST_EQUAL(ret, MBEDTLS_SSL_EARLY_DATA_STATUS_ACCEPTED);
4241            break;
4242
4243        case TEST_EARLY_DATA_NO_INDICATION_SENT:
4244            TEST_EQUAL(ret, MBEDTLS_SSL_EARLY_DATA_STATUS_NOT_INDICATED);
4245            break;
4246
4247        case TEST_EARLY_DATA_SERVER_REJECTS: /* Intentional fallthrough */
4248        case TEST_EARLY_DATA_HRR:
4249            TEST_EQUAL(ret, MBEDTLS_SSL_EARLY_DATA_STATUS_REJECTED);
4250            break;
4251
4252        default:
4253            TEST_FAIL("Unknown scenario.");
4254    }
4255
4256    ret = mbedtls_ssl_get_early_data_status(&(server_ep.ssl));
4257    TEST_EQUAL(ret, MBEDTLS_ERR_SSL_BAD_INPUT_DATA);
4258
4259#if defined(MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE)
4260    TEST_EQUAL(client_ep.ssl.handshake->ccs_sent, 1);
4261#endif
4262
4263exit:
4264    mbedtls_test_ssl_endpoint_free(&client_ep, NULL);
4265    mbedtls_test_ssl_endpoint_free(&server_ep, NULL);
4266    mbedtls_test_free_handshake_options(&client_options);
4267    mbedtls_test_free_handshake_options(&server_options);
4268    mbedtls_ssl_session_free(&saved_session);
4269    PSA_DONE();
4270}
4271/* END_CASE */
4272
4273/* BEGIN_CASE depends_on:MBEDTLS_SSL_EARLY_DATA:MBEDTLS_SSL_CLI_C:MBEDTLS_SSL_SRV_C:MBEDTLS_TEST_AT_LEAST_ONE_TLS1_3_CIPHERSUITE:MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED:MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED:MBEDTLS_MD_CAN_SHA256:MBEDTLS_ECP_HAVE_SECP256R1:MBEDTLS_ECP_HAVE_SECP384R1:MBEDTLS_PK_CAN_ECDSA_VERIFY:MBEDTLS_SSL_SESSION_TICKETS */
4274void tls13_write_early_data(int scenario)
4275{
4276    int ret = -1;
4277    mbedtls_test_ssl_endpoint client_ep, server_ep;
4278    mbedtls_test_handshake_test_options client_options;
4279    mbedtls_test_handshake_test_options server_options;
4280    mbedtls_ssl_session saved_session;
4281    uint16_t group_list[3] = {
4282        MBEDTLS_SSL_IANA_TLS_GROUP_SECP256R1,
4283        MBEDTLS_SSL_IANA_TLS_GROUP_SECP384R1,
4284        MBEDTLS_SSL_IANA_TLS_GROUP_NONE
4285    };
4286    int beyond_first_hello = 0;
4287
4288    mbedtls_platform_zeroize(&client_ep, sizeof(client_ep));
4289    mbedtls_platform_zeroize(&server_ep, sizeof(server_ep));
4290    mbedtls_test_init_handshake_options(&client_options);
4291    mbedtls_test_init_handshake_options(&server_options);
4292    mbedtls_ssl_session_init(&saved_session);
4293
4294    PSA_INIT();
4295
4296    /*
4297     * Run first handshake to get a ticket from the server.
4298     */
4299    client_options.pk_alg = MBEDTLS_PK_ECDSA;
4300    client_options.early_data = MBEDTLS_SSL_EARLY_DATA_ENABLED;
4301    server_options.pk_alg = MBEDTLS_PK_ECDSA;
4302    server_options.early_data = MBEDTLS_SSL_EARLY_DATA_ENABLED;
4303    if (scenario == TEST_EARLY_DATA_HRR) {
4304        client_options.group_list = group_list;
4305        server_options.group_list = group_list;
4306    }
4307
4308    ret = mbedtls_test_get_tls13_ticket(&client_options, &server_options,
4309                                        &saved_session);
4310    TEST_EQUAL(ret, 0);
4311
4312    /*
4313     * Prepare for handshake with the ticket.
4314     */
4315    switch (scenario) {
4316        case TEST_EARLY_DATA_ACCEPTED:
4317            break;
4318
4319        case TEST_EARLY_DATA_NO_INDICATION_SENT:
4320            client_options.early_data = MBEDTLS_SSL_EARLY_DATA_DISABLED;
4321            break;
4322
4323        case TEST_EARLY_DATA_SERVER_REJECTS:
4324            server_options.early_data = MBEDTLS_SSL_EARLY_DATA_DISABLED;
4325            break;
4326
4327        case TEST_EARLY_DATA_HRR:
4328            /*
4329             * Remove server support for the group negotiated in
4330             * mbedtls_test_get_tls13_ticket() forcing a HelloRetryRequest.
4331             */
4332            server_options.group_list = group_list + 1;
4333            break;
4334
4335        default:
4336            TEST_FAIL("Unknown scenario.");
4337    }
4338
4339    ret = mbedtls_test_ssl_endpoint_init(&client_ep, MBEDTLS_SSL_IS_CLIENT,
4340                                         &client_options, NULL, NULL, NULL);
4341    TEST_EQUAL(ret, 0);
4342
4343    ret = mbedtls_test_ssl_endpoint_init(&server_ep, MBEDTLS_SSL_IS_SERVER,
4344                                         &server_options, NULL, NULL, NULL);
4345    TEST_EQUAL(ret, 0);
4346
4347    mbedtls_ssl_conf_session_tickets_cb(&server_ep.conf,
4348                                        mbedtls_test_ticket_write,
4349                                        mbedtls_test_ticket_parse,
4350                                        NULL);
4351
4352    ret = mbedtls_test_mock_socket_connect(&(client_ep.socket),
4353                                           &(server_ep.socket), 1024);
4354    TEST_EQUAL(ret, 0);
4355
4356    ret = mbedtls_ssl_set_session(&(client_ep.ssl), &saved_session);
4357    TEST_EQUAL(ret, 0);
4358
4359    /*
4360     * Run handshakes going one state further in the handshake sequence at each
4361     * loop up to the point where we reach the MBEDTLS_SSL_HANDSHAKE_OVER
4362     * state. For each reached handshake state, check the result of the call
4363     * to mbedtls_ssl_write_early_data(), make sure we can complete the
4364     * handshake successfully and then reset the connection to restart the
4365     * handshake from scratch.
4366     */
4367    do {
4368        int client_state = client_ep.ssl.state;
4369        int previous_client_state;
4370        const char *early_data_string = "This is early data.";
4371        const unsigned char *early_data = (const unsigned char *) early_data_string;
4372        size_t early_data_len = strlen(early_data_string);
4373        int write_early_data_ret, read_early_data_ret;
4374        unsigned char read_buf[64];
4375
4376        write_early_data_ret = mbedtls_ssl_write_early_data(&(client_ep.ssl),
4377                                                            early_data,
4378                                                            early_data_len);
4379
4380        if (scenario == TEST_EARLY_DATA_NO_INDICATION_SENT) {
4381            TEST_EQUAL(write_early_data_ret, MBEDTLS_ERR_SSL_CANNOT_WRITE_EARLY_DATA);
4382            TEST_EQUAL(client_ep.ssl.state, client_state);
4383            goto complete_handshake;
4384        }
4385
4386        switch (client_state) {
4387            case MBEDTLS_SSL_HELLO_REQUEST: /* Intentional fallthrough */
4388            case MBEDTLS_SSL_CLIENT_HELLO:
4389                switch (scenario) {
4390                    case TEST_EARLY_DATA_ACCEPTED: /* Intentional fallthrough */
4391                    case TEST_EARLY_DATA_SERVER_REJECTS:
4392                        TEST_EQUAL(write_early_data_ret, early_data_len);
4393                        TEST_EQUAL(client_ep.ssl.state, MBEDTLS_SSL_SERVER_HELLO);
4394                        break;
4395
4396                    case TEST_EARLY_DATA_HRR:
4397                        if (!client_ep.ssl.handshake->hello_retry_request_flag) {
4398                            TEST_EQUAL(write_early_data_ret, early_data_len);
4399                            TEST_EQUAL(client_ep.ssl.state, MBEDTLS_SSL_SERVER_HELLO);
4400                        } else {
4401                            beyond_first_hello = 1;
4402                            TEST_EQUAL(write_early_data_ret,
4403                                       MBEDTLS_ERR_SSL_CANNOT_WRITE_EARLY_DATA);
4404                            TEST_EQUAL(client_ep.ssl.state, MBEDTLS_SSL_CLIENT_HELLO);
4405                        }
4406                        break;
4407
4408                    default:
4409                        TEST_FAIL("Unknown scenario.");
4410                }
4411                break;
4412
4413            case MBEDTLS_SSL_SERVER_HELLO:
4414                switch (scenario) {
4415                    case TEST_EARLY_DATA_ACCEPTED: /* Intentional fallthrough */
4416                    case TEST_EARLY_DATA_SERVER_REJECTS:
4417                        TEST_EQUAL(write_early_data_ret, early_data_len);
4418                        TEST_EQUAL(client_ep.ssl.state, MBEDTLS_SSL_SERVER_HELLO);
4419                        break;
4420
4421                    case TEST_EARLY_DATA_HRR:
4422                        if (!client_ep.ssl.handshake->hello_retry_request_flag) {
4423                            TEST_EQUAL(write_early_data_ret, early_data_len);
4424                            TEST_EQUAL(client_ep.ssl.state, MBEDTLS_SSL_SERVER_HELLO);
4425                        } else {
4426                            TEST_EQUAL(write_early_data_ret,
4427                                       MBEDTLS_ERR_SSL_CANNOT_WRITE_EARLY_DATA);
4428                            TEST_EQUAL(client_ep.ssl.state, MBEDTLS_SSL_SERVER_HELLO);
4429                        }
4430                        break;
4431
4432                    default:
4433                        TEST_FAIL("Unknown scenario.");
4434                }
4435                break;
4436
4437            case MBEDTLS_SSL_ENCRYPTED_EXTENSIONS:
4438                switch (scenario) {
4439                    case TEST_EARLY_DATA_ACCEPTED: /* Intentional fallthrough */
4440                    case TEST_EARLY_DATA_SERVER_REJECTS:
4441                        TEST_EQUAL(write_early_data_ret, early_data_len);
4442                        TEST_EQUAL(client_ep.ssl.state, MBEDTLS_SSL_ENCRYPTED_EXTENSIONS);
4443                        break;
4444
4445                    case TEST_EARLY_DATA_HRR:
4446                        TEST_EQUAL(write_early_data_ret, MBEDTLS_ERR_SSL_CANNOT_WRITE_EARLY_DATA);
4447                        TEST_EQUAL(client_ep.ssl.state, MBEDTLS_SSL_ENCRYPTED_EXTENSIONS);
4448                        break;
4449
4450                    default:
4451                        TEST_FAIL("Unknown scenario.");
4452                }
4453                break;
4454
4455            case MBEDTLS_SSL_SERVER_FINISHED:
4456                switch (scenario) {
4457                    case TEST_EARLY_DATA_ACCEPTED:
4458                        TEST_EQUAL(write_early_data_ret, early_data_len);
4459                        TEST_EQUAL(client_ep.ssl.state, MBEDTLS_SSL_SERVER_FINISHED);
4460                        break;
4461
4462                    case TEST_EARLY_DATA_SERVER_REJECTS:
4463                        TEST_EQUAL(write_early_data_ret, MBEDTLS_ERR_SSL_CANNOT_WRITE_EARLY_DATA);
4464                        TEST_EQUAL(client_ep.ssl.state, MBEDTLS_SSL_SERVER_FINISHED);
4465                        break;
4466
4467                    case TEST_EARLY_DATA_HRR:
4468                        TEST_EQUAL(write_early_data_ret, MBEDTLS_ERR_SSL_CANNOT_WRITE_EARLY_DATA);
4469                        TEST_EQUAL(client_ep.ssl.state, MBEDTLS_SSL_SERVER_FINISHED);
4470                        break;
4471
4472                    default:
4473                        TEST_FAIL("Unknown scenario.");
4474                }
4475                break;
4476
4477            case MBEDTLS_SSL_END_OF_EARLY_DATA:
4478                TEST_EQUAL(scenario, TEST_EARLY_DATA_ACCEPTED);
4479                TEST_EQUAL(write_early_data_ret, MBEDTLS_ERR_SSL_CANNOT_WRITE_EARLY_DATA);
4480                TEST_EQUAL(client_ep.ssl.state, MBEDTLS_SSL_END_OF_EARLY_DATA);
4481                break;
4482
4483#if defined(MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE)
4484            case MBEDTLS_SSL_CLIENT_CCS_AFTER_CLIENT_HELLO:
4485                switch (scenario) {
4486                    case TEST_EARLY_DATA_ACCEPTED: /* Intentional fallthrough */
4487                    case TEST_EARLY_DATA_SERVER_REJECTS: /* Intentional fallthrough */
4488                    case TEST_EARLY_DATA_HRR:
4489                        TEST_EQUAL(write_early_data_ret, early_data_len);
4490                        TEST_EQUAL(client_ep.ssl.state, MBEDTLS_SSL_SERVER_HELLO);
4491                        break;
4492                    default:
4493                        TEST_FAIL("Unknown scenario.");
4494                }
4495                break;
4496
4497            case MBEDTLS_SSL_CLIENT_CCS_BEFORE_2ND_CLIENT_HELLO:
4498                TEST_EQUAL(scenario, TEST_EARLY_DATA_HRR);
4499                TEST_EQUAL(write_early_data_ret, MBEDTLS_ERR_SSL_CANNOT_WRITE_EARLY_DATA);
4500                TEST_EQUAL(client_ep.ssl.state, MBEDTLS_SSL_CLIENT_CCS_BEFORE_2ND_CLIENT_HELLO);
4501                break;
4502
4503            case MBEDTLS_SSL_CLIENT_CCS_AFTER_SERVER_FINISHED:
4504                switch (scenario) {
4505                    case TEST_EARLY_DATA_SERVER_REJECTS: /* Intentional fallthrough */
4506                    case TEST_EARLY_DATA_HRR:
4507                        TEST_EQUAL(write_early_data_ret,
4508                                   MBEDTLS_ERR_SSL_CANNOT_WRITE_EARLY_DATA);
4509                        TEST_EQUAL(client_ep.ssl.state,
4510                                   MBEDTLS_SSL_CLIENT_CCS_AFTER_SERVER_FINISHED);
4511                        break;
4512                    default:
4513                        TEST_FAIL("Unexpected or unknown scenario.");
4514                }
4515                break;
4516#endif /* MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE */
4517
4518            case MBEDTLS_SSL_CLIENT_CERTIFICATE: /* Intentional fallthrough */
4519            case MBEDTLS_SSL_CLIENT_FINISHED: /* Intentional fallthrough */
4520            case MBEDTLS_SSL_FLUSH_BUFFERS: /* Intentional fallthrough */
4521            case MBEDTLS_SSL_HANDSHAKE_WRAPUP: /* Intentional fallthrough */
4522            case MBEDTLS_SSL_HANDSHAKE_OVER:
4523                switch (scenario) {
4524                    case TEST_EARLY_DATA_ACCEPTED: /* Intentional fallthrough */
4525                    case TEST_EARLY_DATA_SERVER_REJECTS: /* Intentional fallthrough */
4526                    case TEST_EARLY_DATA_HRR:
4527                        TEST_EQUAL(write_early_data_ret, MBEDTLS_ERR_SSL_CANNOT_WRITE_EARLY_DATA);
4528                        TEST_EQUAL(client_ep.ssl.state, client_state);
4529                        break;
4530                    default:
4531                        TEST_FAIL("Unknown scenario.");
4532                }
4533                break;
4534
4535            default:
4536                TEST_FAIL("Unexpected state.");
4537        }
4538
4539complete_handshake:
4540        do {
4541            ret = mbedtls_test_move_handshake_to_state(
4542                &(server_ep.ssl), &(client_ep.ssl),
4543                MBEDTLS_SSL_HANDSHAKE_OVER);
4544
4545            if (ret == MBEDTLS_ERR_SSL_RECEIVED_EARLY_DATA) {
4546                read_early_data_ret = mbedtls_ssl_read_early_data(
4547                    &(server_ep.ssl), read_buf, sizeof(read_buf));
4548
4549                TEST_EQUAL(read_early_data_ret, early_data_len);
4550            }
4551        } while (ret == MBEDTLS_ERR_SSL_RECEIVED_EARLY_DATA);
4552
4553        TEST_EQUAL(ret, 0);
4554        TEST_EQUAL(mbedtls_test_move_handshake_to_state(
4555                       &(client_ep.ssl), &(server_ep.ssl),
4556                       MBEDTLS_SSL_HANDSHAKE_OVER), 0);
4557
4558        mbedtls_test_mock_socket_close(&(client_ep.socket));
4559        mbedtls_test_mock_socket_close(&(server_ep.socket));
4560
4561        ret = mbedtls_ssl_session_reset(&(client_ep.ssl));
4562        TEST_EQUAL(ret, 0);
4563
4564        ret = mbedtls_ssl_set_session(&(client_ep.ssl), &saved_session);
4565        TEST_EQUAL(ret, 0);
4566
4567        ret = mbedtls_ssl_session_reset(&(server_ep.ssl));
4568        TEST_EQUAL(ret, 0);
4569
4570        ret = mbedtls_test_mock_socket_connect(&(client_ep.socket),
4571                                               &(server_ep.socket), 1024);
4572        TEST_EQUAL(ret, 0);
4573
4574        previous_client_state = client_state;
4575        if (previous_client_state == MBEDTLS_SSL_HANDSHAKE_OVER) {
4576            break;
4577        }
4578
4579        /* In case of HRR scenario, once we have been through it, move over
4580         * the first ClientHello and ServerHello otherwise we just keep playing
4581         * this first part of the handshake with HRR.
4582         */
4583        if ((scenario == TEST_EARLY_DATA_HRR) && (beyond_first_hello)) {
4584            TEST_ASSERT(mbedtls_test_move_handshake_to_state(
4585                            &(client_ep.ssl), &(server_ep.ssl),
4586                            MBEDTLS_SSL_SERVER_HELLO) == 0);
4587            TEST_ASSERT(mbedtls_test_move_handshake_to_state(
4588                            &(client_ep.ssl), &(server_ep.ssl),
4589                            MBEDTLS_SSL_CLIENT_HELLO) == 0);
4590        }
4591
4592        TEST_EQUAL(mbedtls_test_move_handshake_to_state(
4593                       &(client_ep.ssl), &(server_ep.ssl),
4594                       previous_client_state), 0);
4595
4596        /* Progress the handshake from at least one state */
4597        while (client_ep.ssl.state == previous_client_state) {
4598            ret = mbedtls_ssl_handshake_step(&(client_ep.ssl));
4599            TEST_ASSERT((ret == 0) ||
4600                        (ret == MBEDTLS_ERR_SSL_WANT_READ) ||
4601                        (ret == MBEDTLS_ERR_SSL_WANT_WRITE));
4602            if (client_ep.ssl.state != previous_client_state) {
4603                break;
4604            }
4605            ret = mbedtls_ssl_handshake_step(&(server_ep.ssl));
4606            TEST_ASSERT((ret == 0) ||
4607                        (ret == MBEDTLS_ERR_SSL_WANT_READ) ||
4608                        (ret == MBEDTLS_ERR_SSL_WANT_WRITE));
4609        }
4610    } while (1);
4611
4612exit:
4613    mbedtls_test_ssl_endpoint_free(&client_ep, NULL);
4614    mbedtls_test_ssl_endpoint_free(&server_ep, NULL);
4615    mbedtls_test_free_handshake_options(&client_options);
4616    mbedtls_test_free_handshake_options(&server_options);
4617    mbedtls_ssl_session_free(&saved_session);
4618    PSA_DONE();
4619}
4620/* END_CASE */
4621
4622/* BEGIN_CASE depends_on:MBEDTLS_SSL_EARLY_DATA:MBEDTLS_SSL_CLI_C:MBEDTLS_SSL_SRV_C:MBEDTLS_DEBUG_C:MBEDTLS_TEST_AT_LEAST_ONE_TLS1_3_CIPHERSUITE:MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED:MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED:MBEDTLS_MD_CAN_SHA256:MBEDTLS_ECP_HAVE_SECP256R1:MBEDTLS_ECP_HAVE_SECP384R1:MBEDTLS_PK_CAN_ECDSA_VERIFY:MBEDTLS_SSL_SESSION_TICKETS */
4623void tls13_cli_max_early_data_size(int max_early_data_size_arg)
4624{
4625    int ret = -1;
4626    mbedtls_test_ssl_endpoint client_ep, server_ep;
4627    mbedtls_test_handshake_test_options client_options;
4628    mbedtls_test_handshake_test_options server_options;
4629    mbedtls_ssl_session saved_session;
4630    unsigned char *buf = NULL;
4631    uint32_t buf_size = 64;
4632    uint32_t max_early_data_size;
4633    uint32_t written_early_data_size = 0;
4634    uint32_t read_early_data_size = 0;
4635
4636    mbedtls_platform_zeroize(&client_ep, sizeof(client_ep));
4637    mbedtls_platform_zeroize(&server_ep, sizeof(server_ep));
4638    mbedtls_test_init_handshake_options(&client_options);
4639    mbedtls_test_init_handshake_options(&server_options);
4640    mbedtls_ssl_session_init(&saved_session);
4641
4642    PSA_INIT();
4643    TEST_CALLOC(buf, buf_size);
4644
4645    /*
4646     * Run first handshake to get a ticket from the server.
4647     */
4648
4649    client_options.pk_alg = MBEDTLS_PK_ECDSA;
4650    client_options.early_data = MBEDTLS_SSL_EARLY_DATA_ENABLED;
4651    server_options.pk_alg = MBEDTLS_PK_ECDSA;
4652    server_options.early_data = MBEDTLS_SSL_EARLY_DATA_ENABLED;
4653    server_options.max_early_data_size = max_early_data_size_arg;
4654
4655    ret = mbedtls_test_get_tls13_ticket(&client_options, &server_options,
4656                                        &saved_session);
4657    TEST_EQUAL(ret, 0);
4658
4659    /*
4660     * Prepare for handshake with the ticket.
4661     */
4662    ret = mbedtls_test_ssl_endpoint_init(&client_ep, MBEDTLS_SSL_IS_CLIENT,
4663                                         &client_options, NULL, NULL, NULL);
4664    TEST_EQUAL(ret, 0);
4665
4666    ret = mbedtls_test_ssl_endpoint_init(&server_ep, MBEDTLS_SSL_IS_SERVER,
4667                                         &server_options, NULL, NULL, NULL);
4668    TEST_EQUAL(ret, 0);
4669
4670    mbedtls_ssl_conf_session_tickets_cb(&server_ep.conf,
4671                                        mbedtls_test_ticket_write,
4672                                        mbedtls_test_ticket_parse,
4673                                        NULL);
4674
4675    max_early_data_size = saved_session.max_early_data_size;
4676    /*
4677     * (max_early_data_size + 1024) for the size of the socket buffers for the
4678     * server one to be able to contain the maximum number of early data bytes
4679     * plus the first flight of client messages. Needed because we cannot
4680     * initiate the handshake on server side before doing all the calls to
4681     * mbedtls_ssl_write_early_data() we want to test. See below for more
4682     * information.
4683     */
4684    ret = mbedtls_test_mock_socket_connect(&(client_ep.socket),
4685                                           &(server_ep.socket),
4686                                           max_early_data_size + 1024);
4687    TEST_EQUAL(ret, 0);
4688
4689    /* If our server is configured with max_early_data_size equal to zero, it
4690     * does not set the MBEDTLS_SSL_TLS1_3_TICKET_ALLOW_EARLY_DATA flag for
4691     * the tickets it creates. To be able to test early data with a ticket
4692     * allowing early data in its flags but with max_early_data_size equal to
4693     * zero (case supported by our client) tweak the ticket flags here.
4694     */
4695    if (max_early_data_size == 0) {
4696        saved_session.ticket_flags |= MBEDTLS_SSL_TLS1_3_TICKET_ALLOW_EARLY_DATA;
4697    }
4698
4699    ret = mbedtls_ssl_set_session(&(client_ep.ssl), &saved_session);
4700    TEST_EQUAL(ret, 0);
4701
4702    while (written_early_data_size < max_early_data_size) {
4703        uint32_t remaining = max_early_data_size - written_early_data_size;
4704
4705        for (size_t i = 0; i < buf_size; i++) {
4706            buf[i] = (unsigned char) (written_early_data_size + i);
4707        }
4708
4709        ret = mbedtls_ssl_write_early_data(&(client_ep.ssl),
4710                                           buf,
4711                                           buf_size);
4712
4713        if (buf_size <= remaining) {
4714            TEST_EQUAL(ret, buf_size);
4715        } else {
4716            TEST_EQUAL(ret, remaining);
4717        }
4718        written_early_data_size += buf_size;
4719    }
4720    TEST_EQUAL(client_ep.ssl.total_early_data_size, max_early_data_size);
4721
4722    ret = mbedtls_ssl_write_early_data(&(client_ep.ssl), buf, 1);
4723    TEST_EQUAL(ret, MBEDTLS_ERR_SSL_CANNOT_WRITE_EARLY_DATA);
4724    TEST_EQUAL(client_ep.ssl.total_early_data_size, max_early_data_size);
4725    TEST_EQUAL(client_ep.ssl.early_data_state,
4726               MBEDTLS_SSL_EARLY_DATA_STATE_CAN_WRITE);
4727
4728    /*
4729     * Now, check data on server side. It is not done in the previous loop as
4730     * in the first call to mbedtls_ssl_handshake(), the server ends up sending
4731     * its Finished message and then in the following call to
4732     * mbedtls_ssl_write_early_data() we go past the early data writing window
4733     * and we cannot test multiple calls to the API is this writing window.
4734     */
4735    while (read_early_data_size < max_early_data_size) {
4736        ret = mbedtls_ssl_handshake(&(server_ep.ssl));
4737        TEST_EQUAL(ret, MBEDTLS_ERR_SSL_RECEIVED_EARLY_DATA);
4738
4739        ret = mbedtls_ssl_read_early_data(&(server_ep.ssl),
4740                                          buf,
4741                                          buf_size);
4742        TEST_ASSERT(ret > 0);
4743
4744        for (size_t i = 0; i < (size_t) ret; i++) {
4745            TEST_EQUAL(buf[i], (unsigned char) (read_early_data_size + i));
4746        }
4747
4748        read_early_data_size += ret;
4749    }
4750    TEST_EQUAL(read_early_data_size, max_early_data_size);
4751
4752    ret = mbedtls_ssl_handshake(&(server_ep.ssl));
4753    TEST_EQUAL(ret, MBEDTLS_ERR_SSL_WANT_READ);
4754
4755    TEST_ASSERT(mbedtls_test_move_handshake_to_state(
4756                    &(client_ep.ssl), &(server_ep.ssl), MBEDTLS_SSL_HANDSHAKE_OVER)
4757                ==  0);
4758
4759exit:
4760    mbedtls_test_ssl_endpoint_free(&client_ep, NULL);
4761    mbedtls_test_ssl_endpoint_free(&server_ep, NULL);
4762    mbedtls_test_free_handshake_options(&client_options);
4763    mbedtls_test_free_handshake_options(&server_options);
4764    mbedtls_ssl_session_free(&saved_session);
4765    mbedtls_free(buf);
4766    PSA_DONE();
4767}
4768/* END_CASE */
4769
4770/*
4771 * The !MBEDTLS_SSL_PROTO_TLS1_2 dependency of tls13_early_data() below is
4772 * a temporary workaround to not run the test in Windows-2013 where there is
4773 * an issue with mbedtls_vsnprintf().
4774 */
4775/* BEGIN_CASE depends_on:!MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_SSL_EARLY_DATA:MBEDTLS_SSL_CLI_C:MBEDTLS_SSL_SRV_C:MBEDTLS_DEBUG_C:MBEDTLS_TEST_AT_LEAST_ONE_TLS1_3_CIPHERSUITE:MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED:MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED:MBEDTLS_MD_CAN_SHA256:MBEDTLS_ECP_HAVE_SECP256R1:MBEDTLS_ECP_HAVE_SECP384R1:MBEDTLS_PK_CAN_ECDSA_VERIFY:MBEDTLS_SSL_SESSION_TICKETS */
4776void tls13_srv_max_early_data_size(int scenario, int max_early_data_size_arg, int write_size_arg)
4777{
4778    int ret = -1;
4779    mbedtls_test_ssl_endpoint client_ep, server_ep;
4780    mbedtls_test_handshake_test_options client_options;
4781    mbedtls_test_handshake_test_options server_options;
4782    mbedtls_ssl_session saved_session;
4783    mbedtls_test_ssl_log_pattern server_pattern = { NULL, 0 };
4784    uint16_t group_list[3] = {
4785        MBEDTLS_SSL_IANA_TLS_GROUP_SECP256R1,
4786        MBEDTLS_SSL_IANA_TLS_GROUP_SECP384R1,
4787        MBEDTLS_SSL_IANA_TLS_GROUP_NONE
4788    };
4789    char pattern[128];
4790    unsigned char *buf_write = NULL;
4791    uint32_t write_size = (uint32_t) write_size_arg;
4792    unsigned char *buf_read = NULL;
4793    uint32_t read_size;
4794    uint32_t expanded_early_data_chunk_size = 0;
4795    uint32_t written_early_data_size = 0;
4796    uint32_t max_early_data_size;
4797
4798    mbedtls_platform_zeroize(&client_ep, sizeof(client_ep));
4799    mbedtls_platform_zeroize(&server_ep, sizeof(server_ep));
4800    mbedtls_test_init_handshake_options(&client_options);
4801    mbedtls_test_init_handshake_options(&server_options);
4802    mbedtls_ssl_session_init(&saved_session);
4803    PSA_INIT();
4804
4805    TEST_CALLOC(buf_write, write_size);
4806
4807    /*
4808     * Allocate a smaller buffer for early data reading to exercise the reading
4809     * of data in one record in multiple calls.
4810     */
4811    read_size = (write_size / 2) + 1;
4812    TEST_CALLOC(buf_read, read_size);
4813
4814    /*
4815     * Run first handshake to get a ticket from the server.
4816     */
4817
4818    client_options.pk_alg = MBEDTLS_PK_ECDSA;
4819    client_options.group_list = group_list;
4820    client_options.early_data = MBEDTLS_SSL_EARLY_DATA_ENABLED;
4821    server_options.pk_alg = MBEDTLS_PK_ECDSA;
4822    server_options.group_list = group_list;
4823    server_options.early_data = MBEDTLS_SSL_EARLY_DATA_ENABLED;
4824    server_options.max_early_data_size = max_early_data_size_arg;
4825
4826    ret = mbedtls_test_get_tls13_ticket(&client_options, &server_options,
4827                                        &saved_session);
4828    TEST_EQUAL(ret, 0);
4829
4830    /*
4831     * Prepare for handshake with the ticket.
4832     */
4833    server_options.srv_log_fun = mbedtls_test_ssl_log_analyzer;
4834    server_options.srv_log_obj = &server_pattern;
4835    server_pattern.pattern = pattern;
4836
4837    switch (scenario) {
4838        case TEST_EARLY_DATA_ACCEPTED:
4839            break;
4840
4841        case TEST_EARLY_DATA_SERVER_REJECTS:
4842            server_options.early_data = MBEDTLS_SSL_EARLY_DATA_DISABLED;
4843            ret = mbedtls_snprintf(pattern, sizeof(pattern),
4844                                   "EarlyData: deprotect and discard app data records.");
4845            TEST_ASSERT(ret < (int) sizeof(pattern));
4846            mbedtls_debug_set_threshold(3);
4847            break;
4848
4849        case TEST_EARLY_DATA_HRR:
4850            /*
4851             * Remove server support for the group negotiated in
4852             * mbedtls_test_get_tls13_ticket() forcing an HelloRetryRequest.
4853             */
4854            server_options.group_list = group_list + 1;
4855            ret = mbedtls_snprintf(
4856                pattern, sizeof(pattern),
4857                "EarlyData: Ignore application message before 2nd ClientHello");
4858            TEST_ASSERT(ret < (int) sizeof(pattern));
4859            mbedtls_debug_set_threshold(3);
4860            break;
4861
4862        default:
4863            TEST_FAIL("Unknown scenario.");
4864    }
4865
4866    ret = mbedtls_test_ssl_endpoint_init(&client_ep, MBEDTLS_SSL_IS_CLIENT,
4867                                         &client_options, NULL, NULL, NULL);
4868    TEST_EQUAL(ret, 0);
4869
4870    ret = mbedtls_test_ssl_endpoint_init(&server_ep, MBEDTLS_SSL_IS_SERVER,
4871                                         &server_options, NULL, NULL, NULL);
4872    TEST_EQUAL(ret, 0);
4873
4874    mbedtls_ssl_conf_session_tickets_cb(&server_ep.conf,
4875                                        mbedtls_test_ticket_write,
4876                                        mbedtls_test_ticket_parse,
4877                                        NULL);
4878
4879    ret = mbedtls_test_mock_socket_connect(&(client_ep.socket),
4880                                           &(server_ep.socket), 1024);
4881    TEST_EQUAL(ret, 0);
4882
4883    max_early_data_size = saved_session.max_early_data_size;
4884
4885    ret = mbedtls_ssl_set_session(&(client_ep.ssl), &saved_session);
4886    TEST_EQUAL(ret, 0);
4887
4888    /*
4889     * Start an handshake based on the ticket up to the point where early data
4890     * can be sent from client side. Then send in a loop as much early data as
4891     * possible without going over the maximum permitted size for the ticket.
4892     * Finally, do a last writting to go past that maximum permitted size and
4893     * check that we detect it.
4894     */
4895    TEST_EQUAL(mbedtls_test_move_handshake_to_state(
4896                   &(client_ep.ssl), &(server_ep.ssl),
4897                   MBEDTLS_SSL_SERVER_HELLO), 0);
4898
4899    TEST_ASSERT(client_ep.ssl.early_data_state !=
4900                MBEDTLS_SSL_EARLY_DATA_STATE_NO_IND_SENT);
4901
4902    ret = mbedtls_ssl_handshake(&(server_ep.ssl));
4903    TEST_EQUAL(ret, MBEDTLS_ERR_SSL_WANT_READ);
4904
4905    /*
4906     * Write and if possible read as much as possible chunks of write_size
4907     * bytes data without getting over the max_early_data_size limit.
4908     */
4909    do {
4910        uint32_t read_early_data_size = 0;
4911
4912        /*
4913         * The contents of the early data are not very important, write a
4914         * pattern that varies byte-by-byte and is different for every chunk of
4915         * early data.
4916         */
4917        if ((written_early_data_size + write_size) > max_early_data_size) {
4918            break;
4919        }
4920
4921        /*
4922         * If the server rejected early data, base the determination of when
4923         * to stop the loop on the expanded size (padding and encryption
4924         * expansion) of early data on server side and the number of early data
4925         * received so far by the server (multiple of the expanded size).
4926         */
4927        if ((expanded_early_data_chunk_size != 0) &&
4928            ((server_ep.ssl.total_early_data_size +
4929              expanded_early_data_chunk_size) > max_early_data_size)) {
4930            break;
4931        }
4932
4933        for (size_t i = 0; i < write_size; i++) {
4934            buf_write[i] = (unsigned char) (written_early_data_size + i);
4935        }
4936
4937        ret = write_early_data(&(client_ep.ssl), buf_write, write_size);
4938        TEST_EQUAL(ret, write_size);
4939        written_early_data_size += write_size;
4940
4941        switch (scenario) {
4942            case TEST_EARLY_DATA_ACCEPTED:
4943                while (read_early_data_size < write_size) {
4944                    ret = mbedtls_ssl_handshake(&(server_ep.ssl));
4945                    TEST_EQUAL(ret, MBEDTLS_ERR_SSL_RECEIVED_EARLY_DATA);
4946
4947                    ret = mbedtls_ssl_read_early_data(&(server_ep.ssl),
4948                                                      buf_read, read_size);
4949                    TEST_ASSERT(ret > 0);
4950
4951                    TEST_MEMORY_COMPARE(buf_read, ret,
4952                                        buf_write + read_early_data_size, ret);
4953                    read_early_data_size += ret;
4954
4955                    TEST_EQUAL(server_ep.ssl.total_early_data_size,
4956                               written_early_data_size);
4957                }
4958                break;
4959
4960            case TEST_EARLY_DATA_SERVER_REJECTS: /* Intentional fallthrough */
4961            case TEST_EARLY_DATA_HRR:
4962                ret = mbedtls_ssl_handshake(&(server_ep.ssl));
4963                /*
4964                 * In this write loop we try to always stay below the
4965                 * max_early_data_size limit but if max_early_data_size is very
4966                 * small we may exceed the max_early_data_size limit on the
4967                 * first write. In TEST_EARLY_DATA_SERVER_REJECTS/
4968                 * TEST_EARLY_DATA_HRR scenario, this is for sure the case if
4969                 * max_early_data_size is smaller than the smallest possible
4970                 * inner content/protected record. Take into account this
4971                 * possibility here but only for max_early_data_size values
4972                 * that are close to write_size. Below, '1' is for the inner
4973                 * type byte and '16' is to take into account some AEAD
4974                 * expansion (tag, ...).
4975                 */
4976                if (ret == MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE) {
4977                    if (scenario == TEST_EARLY_DATA_SERVER_REJECTS) {
4978                        TEST_LE_U(max_early_data_size,
4979                                  write_size + 1 +
4980                                  MBEDTLS_SSL_CID_TLS1_3_PADDING_GRANULARITY);
4981                    } else {
4982                        TEST_LE_U(max_early_data_size,
4983                                  write_size + 1 + 16 +
4984                                  MBEDTLS_SSL_CID_TLS1_3_PADDING_GRANULARITY);
4985                    }
4986                    goto exit;
4987                }
4988
4989                TEST_ASSERT(ret == MBEDTLS_ERR_SSL_WANT_READ);
4990
4991                TEST_EQUAL(server_pattern.counter, 1);
4992                server_pattern.counter = 0;
4993                if (expanded_early_data_chunk_size == 0) {
4994                    expanded_early_data_chunk_size = server_ep.ssl.total_early_data_size;
4995                }
4996                break;
4997        }
4998        TEST_LE_U(server_ep.ssl.total_early_data_size, max_early_data_size);
4999    } while (1);
5000
5001    mbedtls_debug_set_threshold(3);
5002    ret = write_early_data(&(client_ep.ssl), buf_write, write_size);
5003    TEST_EQUAL(ret, write_size);
5004
5005    ret = mbedtls_snprintf(pattern, sizeof(pattern),
5006                           "EarlyData: Too much early data received");
5007    TEST_ASSERT(ret < (int) sizeof(pattern));
5008
5009    ret = mbedtls_ssl_handshake(&(server_ep.ssl));
5010    TEST_EQUAL(ret, MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE);
5011    TEST_EQUAL(server_pattern.counter, 1);
5012
5013exit:
5014    mbedtls_test_ssl_endpoint_free(&client_ep, NULL);
5015    mbedtls_test_ssl_endpoint_free(&server_ep, NULL);
5016    mbedtls_test_free_handshake_options(&client_options);
5017    mbedtls_test_free_handshake_options(&server_options);
5018    mbedtls_ssl_session_free(&saved_session);
5019    mbedtls_free(buf_write);
5020    mbedtls_free(buf_read);
5021    mbedtls_debug_set_threshold(0);
5022    PSA_DONE();
5023}
5024/* END_CASE */
5025