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 <mbedtls/legacy_or_psa.h>
11#include "hash_info.h"
12
13#include <constant_time_internal.h>
14#include <test/constant_flow.h>
15
16/* END_HEADER */
17
18/* BEGIN_DEPENDENCIES
19 * depends_on:MBEDTLS_SSL_TLS_C
20 * END_DEPENDENCIES
21 */
22
23/* BEGIN_CASE */
24void test_callback_buffer_sanity()
25{
26    enum { MSGLEN = 10 };
27    mbedtls_test_ssl_buffer buf;
28    unsigned char input[MSGLEN];
29    unsigned char output[MSGLEN];
30
31    memset(input, 0, sizeof(input));
32
33    /* Make sure calling put and get on NULL buffer results in error. */
34    TEST_ASSERT(mbedtls_test_ssl_buffer_put(NULL, input, sizeof(input))
35                == -1);
36    TEST_ASSERT(mbedtls_test_ssl_buffer_get(NULL, output, sizeof(output))
37                == -1);
38    TEST_ASSERT(mbedtls_test_ssl_buffer_put(NULL, NULL, sizeof(input))
39                == -1);
40
41    TEST_ASSERT(mbedtls_test_ssl_buffer_put(NULL, NULL, 0) == -1);
42    TEST_ASSERT(mbedtls_test_ssl_buffer_get(NULL, NULL, 0) == -1);
43
44    /* Make sure calling put and get on a buffer that hasn't been set up results
45     * in error. */
46    mbedtls_test_ssl_buffer_init(&buf);
47
48    TEST_ASSERT(mbedtls_test_ssl_buffer_put(&buf, input, sizeof(input))
49                == -1);
50    TEST_ASSERT(mbedtls_test_ssl_buffer_get(&buf, output, sizeof(output))
51                == -1);
52    TEST_ASSERT(mbedtls_test_ssl_buffer_put(&buf, NULL, sizeof(input))
53                == -1);
54
55    TEST_ASSERT(mbedtls_test_ssl_buffer_put(&buf, NULL, 0) == -1);
56    TEST_ASSERT(mbedtls_test_ssl_buffer_get(&buf, NULL, 0) == -1);
57
58    /* Make sure calling put and get on NULL input only results in
59     * error if the length is not zero, and that a NULL output is valid for data
60     * dropping.
61     */
62
63    TEST_ASSERT(mbedtls_test_ssl_buffer_setup(&buf, sizeof(input)) == 0);
64
65    TEST_ASSERT(mbedtls_test_ssl_buffer_put(&buf, NULL, sizeof(input))
66                == -1);
67    TEST_ASSERT(mbedtls_test_ssl_buffer_get(&buf, NULL, sizeof(output))
68                == 0);
69    TEST_ASSERT(mbedtls_test_ssl_buffer_put(&buf, NULL, 0) == 0);
70    TEST_ASSERT(mbedtls_test_ssl_buffer_get(&buf, NULL, 0) == 0);
71
72    /* Make sure calling put several times in the row is safe */
73
74    TEST_ASSERT(mbedtls_test_ssl_buffer_put(&buf, input, sizeof(input))
75                == sizeof(input));
76    TEST_ASSERT(mbedtls_test_ssl_buffer_get(&buf, output, 2) == 2);
77    TEST_ASSERT(mbedtls_test_ssl_buffer_put(&buf, input, 1) == 1);
78    TEST_ASSERT(mbedtls_test_ssl_buffer_put(&buf, input, 2) == 1);
79    TEST_ASSERT(mbedtls_test_ssl_buffer_put(&buf, input, 2) == 0);
80
81
82exit:
83
84    mbedtls_test_ssl_buffer_free(&buf);
85}
86/* END_CASE */
87
88/*
89 * Test if the implementation of `mbedtls_test_ssl_buffer` related functions is
90 * correct and works as expected.
91 *
92 * That is
93 *  - If we try to put in \p put1 bytes then we can put in \p put1_ret bytes.
94 *  - Afterwards if we try to get \p get1 bytes then we can get \get1_ret bytes.
95 *  - Next, if we try to put in \p put1 bytes then we can put in \p put1_ret
96 *    bytes.
97 *  - Afterwards if we try to get \p get1 bytes then we can get \get1_ret bytes.
98 *  - All of the bytes we got match the bytes we put in in a FIFO manner.
99 */
100
101/* BEGIN_CASE */
102void test_callback_buffer(int size, int put1, int put1_ret,
103                          int get1, int get1_ret, int put2, int put2_ret,
104                          int get2, int get2_ret)
105{
106    enum { ROUNDS = 2 };
107    size_t put[ROUNDS];
108    int put_ret[ROUNDS];
109    size_t get[ROUNDS];
110    int get_ret[ROUNDS];
111    mbedtls_test_ssl_buffer buf;
112    unsigned char *input = NULL;
113    size_t input_len;
114    unsigned char *output = NULL;
115    size_t output_len;
116    size_t i, j, written, read;
117
118    mbedtls_test_ssl_buffer_init(&buf);
119    TEST_ASSERT(mbedtls_test_ssl_buffer_setup(&buf, size) == 0);
120
121    /* Check the sanity of input parameters and initialise local variables. That
122     * is, ensure that the amount of data is not negative and that we are not
123     * expecting more to put or get than we actually asked for. */
124    TEST_ASSERT(put1 >= 0);
125    put[0] = put1;
126    put_ret[0] = put1_ret;
127    TEST_ASSERT(put1_ret <= put1);
128    TEST_ASSERT(put2 >= 0);
129    put[1] = put2;
130    put_ret[1] = put2_ret;
131    TEST_ASSERT(put2_ret <= put2);
132
133    TEST_ASSERT(get1 >= 0);
134    get[0] = get1;
135    get_ret[0] = get1_ret;
136    TEST_ASSERT(get1_ret <= get1);
137    TEST_ASSERT(get2 >= 0);
138    get[1] = get2;
139    get_ret[1] = get2_ret;
140    TEST_ASSERT(get2_ret <= get2);
141
142    input_len = 0;
143    /* Calculate actual input and output lengths */
144    for (j = 0; j < ROUNDS; j++) {
145        if (put_ret[j] > 0) {
146            input_len += put_ret[j];
147        }
148    }
149    /* In order to always have a valid pointer we always allocate at least 1
150     * byte. */
151    if (input_len == 0) {
152        input_len = 1;
153    }
154    ASSERT_ALLOC(input, input_len);
155
156    output_len = 0;
157    for (j = 0; j < ROUNDS; j++) {
158        if (get_ret[j] > 0) {
159            output_len += get_ret[j];
160        }
161    }
162    TEST_ASSERT(output_len <= input_len);
163    /* In order to always have a valid pointer we always allocate at least 1
164     * byte. */
165    if (output_len == 0) {
166        output_len = 1;
167    }
168    ASSERT_ALLOC(output, output_len);
169
170    /* Fill up the buffer with structured data so that unwanted changes
171     * can be detected */
172    for (i = 0; i < input_len; i++) {
173        input[i] = i & 0xFF;
174    }
175
176    written = read = 0;
177    for (j = 0; j < ROUNDS; j++) {
178        TEST_ASSERT(put_ret[j] == mbedtls_test_ssl_buffer_put(&buf,
179                                                              input + written, put[j]));
180        written += put_ret[j];
181        TEST_ASSERT(get_ret[j] == mbedtls_test_ssl_buffer_get(&buf,
182                                                              output + read, get[j]));
183        read += get_ret[j];
184        TEST_ASSERT(read <= written);
185        if (get_ret[j] > 0) {
186            TEST_ASSERT(memcmp(output + read - get_ret[j],
187                               input + read - get_ret[j], get_ret[j])
188                        == 0);
189        }
190    }
191
192exit:
193
194    mbedtls_free(input);
195    mbedtls_free(output);
196    mbedtls_test_ssl_buffer_free(&buf);
197}
198/* END_CASE */
199
200/*
201 * Test if the implementation of `mbedtls_test_mock_socket` related
202 * I/O functions is correct and works as expected on unconnected sockets.
203 */
204
205/* BEGIN_CASE */
206void ssl_mock_sanity()
207{
208    enum { MSGLEN = 105 };
209    unsigned char message[MSGLEN] = { 0 };
210    unsigned char received[MSGLEN] = { 0 };
211    mbedtls_test_mock_socket socket;
212
213    mbedtls_mock_socket_init(&socket);
214    TEST_ASSERT(mbedtls_test_mock_tcp_send_b(&socket, message, MSGLEN) < 0);
215    mbedtls_test_mock_socket_close(&socket);
216    mbedtls_mock_socket_init(&socket);
217    TEST_ASSERT(mbedtls_test_mock_tcp_recv_b(&socket, received, MSGLEN) < 0);
218    mbedtls_test_mock_socket_close(&socket);
219
220    mbedtls_mock_socket_init(&socket);
221    TEST_ASSERT(mbedtls_test_mock_tcp_send_nb(&socket, message, MSGLEN) < 0);
222    mbedtls_test_mock_socket_close(&socket);
223    mbedtls_mock_socket_init(&socket);
224    TEST_ASSERT(mbedtls_test_mock_tcp_recv_nb(&socket, received, MSGLEN) < 0);
225    mbedtls_test_mock_socket_close(&socket);
226
227exit:
228
229    mbedtls_test_mock_socket_close(&socket);
230}
231/* END_CASE */
232
233/*
234 * Test if the implementation of `mbedtls_test_mock_socket` related functions
235 * can send a single message from the client to the server.
236 */
237
238/* BEGIN_CASE */
239void ssl_mock_tcp(int blocking)
240{
241    enum { MSGLEN = 105 };
242    enum { BUFLEN = MSGLEN / 5 };
243    unsigned char message[MSGLEN];
244    unsigned char received[MSGLEN];
245    mbedtls_test_mock_socket client;
246    mbedtls_test_mock_socket server;
247    size_t written, read;
248    int send_ret, recv_ret;
249    mbedtls_ssl_send_t *send;
250    mbedtls_ssl_recv_t *recv;
251    unsigned i;
252
253    if (blocking == 0) {
254        send = mbedtls_test_mock_tcp_send_nb;
255        recv = mbedtls_test_mock_tcp_recv_nb;
256    } else {
257        send = mbedtls_test_mock_tcp_send_b;
258        recv = mbedtls_test_mock_tcp_recv_b;
259    }
260
261    mbedtls_mock_socket_init(&client);
262    mbedtls_mock_socket_init(&server);
263
264    /* Fill up the buffer with structured data so that unwanted changes
265     * can be detected */
266    for (i = 0; i < MSGLEN; i++) {
267        message[i] = i & 0xFF;
268    }
269
270    /* Make sure that sending a message takes a few  iterations. */
271    TEST_ASSERT(0 == mbedtls_test_mock_socket_connect(&client, &server,
272                                                      BUFLEN));
273
274    /* Send the message to the server */
275    send_ret = recv_ret = 1;
276    written = read = 0;
277    while (send_ret != 0 || recv_ret != 0) {
278        send_ret = send(&client, message + written, MSGLEN - written);
279
280        TEST_ASSERT(send_ret >= 0);
281        TEST_ASSERT(send_ret <= BUFLEN);
282        written += send_ret;
283
284        /* If the buffer is full we can test blocking and non-blocking send */
285        if (send_ret == BUFLEN) {
286            int blocking_ret = send(&client, message, 1);
287            if (blocking) {
288                TEST_ASSERT(blocking_ret == 0);
289            } else {
290                TEST_ASSERT(blocking_ret == MBEDTLS_ERR_SSL_WANT_WRITE);
291            }
292        }
293
294        recv_ret = recv(&server, received + read, MSGLEN - read);
295
296        /* The result depends on whether any data was sent */
297        if (send_ret > 0) {
298            TEST_ASSERT(recv_ret > 0);
299            TEST_ASSERT(recv_ret <= BUFLEN);
300            read += recv_ret;
301        } else if (blocking) {
302            TEST_ASSERT(recv_ret == 0);
303        } else {
304            TEST_ASSERT(recv_ret == MBEDTLS_ERR_SSL_WANT_READ);
305            recv_ret = 0;
306        }
307
308        /* If the buffer is empty we can test blocking and non-blocking read */
309        if (recv_ret == BUFLEN) {
310            int blocking_ret = recv(&server, received, 1);
311            if (blocking) {
312                TEST_ASSERT(blocking_ret == 0);
313            } else {
314                TEST_ASSERT(blocking_ret == MBEDTLS_ERR_SSL_WANT_READ);
315            }
316        }
317    }
318    TEST_ASSERT(memcmp(message, received, MSGLEN) == 0);
319
320exit:
321
322    mbedtls_test_mock_socket_close(&client);
323    mbedtls_test_mock_socket_close(&server);
324}
325/* END_CASE */
326
327/*
328 * Test if the implementation of `mbedtls_test_mock_socket` related functions
329 * can send messages in both direction at the same time (with the I/O calls
330 * interleaving).
331 */
332
333/* BEGIN_CASE */
334void ssl_mock_tcp_interleaving(int blocking)
335{
336    enum { ROUNDS = 2 };
337    enum { MSGLEN = 105 };
338    enum { BUFLEN = MSGLEN / 5 };
339    unsigned char message[ROUNDS][MSGLEN];
340    unsigned char received[ROUNDS][MSGLEN];
341    mbedtls_test_mock_socket client;
342    mbedtls_test_mock_socket server;
343    size_t written[ROUNDS];
344    size_t read[ROUNDS];
345    int send_ret[ROUNDS];
346    int recv_ret[ROUNDS];
347    unsigned i, j, progress;
348    mbedtls_ssl_send_t *send;
349    mbedtls_ssl_recv_t *recv;
350
351    if (blocking == 0) {
352        send = mbedtls_test_mock_tcp_send_nb;
353        recv = mbedtls_test_mock_tcp_recv_nb;
354    } else {
355        send = mbedtls_test_mock_tcp_send_b;
356        recv = mbedtls_test_mock_tcp_recv_b;
357    }
358
359    mbedtls_mock_socket_init(&client);
360    mbedtls_mock_socket_init(&server);
361
362    /* Fill up the buffers with structured data so that unwanted changes
363     * can be detected */
364    for (i = 0; i < ROUNDS; i++) {
365        for (j = 0; j < MSGLEN; j++) {
366            message[i][j] = (i * MSGLEN + j) & 0xFF;
367        }
368    }
369
370    /* Make sure that sending a message takes a few  iterations. */
371    TEST_ASSERT(0 == mbedtls_test_mock_socket_connect(&client, &server,
372                                                      BUFLEN));
373
374    /* Send the message from both sides, interleaving. */
375    progress = 1;
376    for (i = 0; i < ROUNDS; i++) {
377        written[i] = 0;
378        read[i] = 0;
379    }
380    /* This loop does not stop as long as there was a successful write or read
381     * of at least one byte on either side. */
382    while (progress != 0) {
383        mbedtls_test_mock_socket *socket;
384
385        for (i = 0; i < ROUNDS; i++) {
386            /* First sending is from the client */
387            socket = (i % 2 == 0) ? (&client) : (&server);
388
389            send_ret[i] = send(socket, message[i] + written[i],
390                               MSGLEN - written[i]);
391            TEST_ASSERT(send_ret[i] >= 0);
392            TEST_ASSERT(send_ret[i] <= BUFLEN);
393            written[i] += send_ret[i];
394
395            /* If the buffer is full we can test blocking and non-blocking
396             * send */
397            if (send_ret[i] == BUFLEN) {
398                int blocking_ret = send(socket, message[i], 1);
399                if (blocking) {
400                    TEST_ASSERT(blocking_ret == 0);
401                } else {
402                    TEST_ASSERT(blocking_ret == MBEDTLS_ERR_SSL_WANT_WRITE);
403                }
404            }
405        }
406
407        for (i = 0; i < ROUNDS; i++) {
408            /* First receiving is from the server */
409            socket = (i % 2 == 0) ? (&server) : (&client);
410
411            recv_ret[i] = recv(socket, received[i] + read[i],
412                               MSGLEN - read[i]);
413
414            /* The result depends on whether any data was sent */
415            if (send_ret[i] > 0) {
416                TEST_ASSERT(recv_ret[i] > 0);
417                TEST_ASSERT(recv_ret[i] <= BUFLEN);
418                read[i] += recv_ret[i];
419            } else if (blocking) {
420                TEST_ASSERT(recv_ret[i] == 0);
421            } else {
422                TEST_ASSERT(recv_ret[i] == MBEDTLS_ERR_SSL_WANT_READ);
423                recv_ret[i] = 0;
424            }
425
426            /* If the buffer is empty we can test blocking and non-blocking
427             * read */
428            if (recv_ret[i] == BUFLEN) {
429                int blocking_ret = recv(socket, received[i], 1);
430                if (blocking) {
431                    TEST_ASSERT(blocking_ret == 0);
432                } else {
433                    TEST_ASSERT(blocking_ret == MBEDTLS_ERR_SSL_WANT_READ);
434                }
435            }
436        }
437
438        progress = 0;
439        for (i = 0; i < ROUNDS; i++) {
440            progress += send_ret[i] + recv_ret[i];
441        }
442    }
443
444    for (i = 0; i < ROUNDS; i++) {
445        TEST_ASSERT(memcmp(message[i], received[i], MSGLEN) == 0);
446    }
447
448exit:
449
450    mbedtls_test_mock_socket_close(&client);
451    mbedtls_test_mock_socket_close(&server);
452}
453/* END_CASE */
454
455/* BEGIN_CASE */
456void ssl_message_queue_sanity()
457{
458    mbedtls_test_ssl_message_queue queue;
459
460    /* Trying to push/pull to an empty queue */
461    TEST_ASSERT(mbedtls_test_ssl_message_queue_push_info(NULL, 1)
462                == MBEDTLS_TEST_ERROR_ARG_NULL);
463    TEST_ASSERT(mbedtls_test_ssl_message_queue_pop_info(NULL, 1)
464                == MBEDTLS_TEST_ERROR_ARG_NULL);
465
466    TEST_ASSERT(mbedtls_test_ssl_message_queue_setup(&queue, 3) == 0);
467    TEST_ASSERT(queue.capacity == 3);
468    TEST_ASSERT(queue.num == 0);
469
470exit:
471    mbedtls_test_ssl_message_queue_free(&queue);
472}
473/* END_CASE */
474
475/* BEGIN_CASE */
476void ssl_message_queue_basic()
477{
478    mbedtls_test_ssl_message_queue queue;
479
480    TEST_ASSERT(mbedtls_test_ssl_message_queue_setup(&queue, 3) == 0);
481
482    /* Sanity test - 3 pushes and 3 pops with sufficient space */
483    TEST_ASSERT(mbedtls_test_ssl_message_queue_push_info(&queue, 1) == 1);
484    TEST_ASSERT(queue.capacity == 3);
485    TEST_ASSERT(queue.num == 1);
486    TEST_ASSERT(mbedtls_test_ssl_message_queue_push_info(&queue, 1) == 1);
487    TEST_ASSERT(queue.capacity == 3);
488    TEST_ASSERT(queue.num == 2);
489    TEST_ASSERT(mbedtls_test_ssl_message_queue_push_info(&queue, 2) == 2);
490    TEST_ASSERT(queue.capacity == 3);
491    TEST_ASSERT(queue.num == 3);
492
493    TEST_ASSERT(mbedtls_test_ssl_message_queue_pop_info(&queue, 1) == 1);
494    TEST_ASSERT(mbedtls_test_ssl_message_queue_pop_info(&queue, 1) == 1);
495    TEST_ASSERT(mbedtls_test_ssl_message_queue_pop_info(&queue, 2) == 2);
496
497exit:
498    mbedtls_test_ssl_message_queue_free(&queue);
499}
500/* END_CASE */
501
502/* BEGIN_CASE */
503void ssl_message_queue_overflow_underflow()
504{
505    mbedtls_test_ssl_message_queue queue;
506
507    TEST_ASSERT(mbedtls_test_ssl_message_queue_setup(&queue, 3) == 0);
508
509    /* 4 pushes (last one with an error), 4 pops (last one with an error) */
510    TEST_ASSERT(mbedtls_test_ssl_message_queue_push_info(&queue, 1) == 1);
511    TEST_ASSERT(mbedtls_test_ssl_message_queue_push_info(&queue, 1) == 1);
512    TEST_ASSERT(mbedtls_test_ssl_message_queue_push_info(&queue, 2) == 2);
513    TEST_ASSERT(mbedtls_test_ssl_message_queue_push_info(&queue, 3)
514                == MBEDTLS_ERR_SSL_WANT_WRITE);
515
516    TEST_ASSERT(mbedtls_test_ssl_message_queue_pop_info(&queue, 1) == 1);
517    TEST_ASSERT(mbedtls_test_ssl_message_queue_pop_info(&queue, 1) == 1);
518    TEST_ASSERT(mbedtls_test_ssl_message_queue_pop_info(&queue, 2) == 2);
519
520    TEST_ASSERT(mbedtls_test_ssl_message_queue_pop_info(&queue, 1)
521                == MBEDTLS_ERR_SSL_WANT_READ);
522
523exit:
524    mbedtls_test_ssl_message_queue_free(&queue);
525}
526/* END_CASE */
527
528/* BEGIN_CASE */
529void ssl_message_queue_interleaved()
530{
531    mbedtls_test_ssl_message_queue queue;
532
533    TEST_ASSERT(mbedtls_test_ssl_message_queue_setup(&queue, 3) == 0);
534
535    /* Interleaved test - [2 pushes, 1 pop] twice, and then two pops
536     * (to wrap around the buffer) */
537    TEST_ASSERT(mbedtls_test_ssl_message_queue_push_info(&queue, 1) == 1);
538    TEST_ASSERT(mbedtls_test_ssl_message_queue_push_info(&queue, 1) == 1);
539
540    TEST_ASSERT(mbedtls_test_ssl_message_queue_pop_info(&queue, 1) == 1);
541
542    TEST_ASSERT(mbedtls_test_ssl_message_queue_push_info(&queue, 2) == 2);
543    TEST_ASSERT(mbedtls_test_ssl_message_queue_push_info(&queue, 3) == 3);
544
545    TEST_ASSERT(mbedtls_test_ssl_message_queue_pop_info(&queue, 1) == 1);
546    TEST_ASSERT(mbedtls_test_ssl_message_queue_pop_info(&queue, 2) == 2);
547
548    TEST_ASSERT(mbedtls_test_ssl_message_queue_push_info(&queue, 5) == 5);
549    TEST_ASSERT(mbedtls_test_ssl_message_queue_push_info(&queue, 8) == 8);
550
551    TEST_ASSERT(mbedtls_test_ssl_message_queue_pop_info(&queue, 3) == 3);
552
553    TEST_ASSERT(mbedtls_test_ssl_message_queue_pop_info(&queue, 5) == 5);
554
555    TEST_ASSERT(mbedtls_test_ssl_message_queue_pop_info(&queue, 8) == 8);
556
557exit:
558    mbedtls_test_ssl_message_queue_free(&queue);
559}
560/* END_CASE */
561
562/* BEGIN_CASE */
563void ssl_message_queue_insufficient_buffer()
564{
565    mbedtls_test_ssl_message_queue queue;
566    size_t message_len = 10;
567    size_t buffer_len = 5;
568
569    TEST_ASSERT(mbedtls_test_ssl_message_queue_setup(&queue, 1) == 0);
570
571    /* Popping without a sufficient buffer */
572    TEST_ASSERT(mbedtls_test_ssl_message_queue_push_info(&queue, message_len)
573                == (int) message_len);
574    TEST_ASSERT(mbedtls_test_ssl_message_queue_pop_info(&queue, buffer_len)
575                == (int) buffer_len);
576exit:
577    mbedtls_test_ssl_message_queue_free(&queue);
578}
579/* END_CASE */
580
581/* BEGIN_CASE */
582void ssl_message_mock_uninitialized()
583{
584    enum { MSGLEN = 10 };
585    unsigned char message[MSGLEN] = { 0 }, received[MSGLEN];
586    mbedtls_test_mock_socket client, server;
587    mbedtls_test_ssl_message_queue server_queue, client_queue;
588    mbedtls_test_message_socket_context server_context, client_context;
589    mbedtls_test_message_socket_init(&server_context);
590    mbedtls_test_message_socket_init(&client_context);
591
592    /* Send with a NULL context */
593    TEST_ASSERT(mbedtls_test_mock_tcp_send_msg(NULL, message, MSGLEN)
594                == MBEDTLS_TEST_ERROR_CONTEXT_ERROR);
595
596    TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(NULL, message, MSGLEN)
597                == MBEDTLS_TEST_ERROR_CONTEXT_ERROR);
598
599    TEST_ASSERT(mbedtls_test_message_socket_setup(&server_queue,
600                                                  &client_queue, 1,
601                                                  &server,
602                                                  &server_context) == 0);
603
604    TEST_ASSERT(mbedtls_test_message_socket_setup(&client_queue,
605                                                  &server_queue, 1,
606                                                  &client,
607                                                  &client_context) == 0);
608
609    TEST_ASSERT(mbedtls_test_mock_tcp_send_msg(&client_context, message,
610                                               MSGLEN)
611                == MBEDTLS_TEST_ERROR_SEND_FAILED);
612
613    TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&server_context, received,
614                                               MSGLEN)
615                == MBEDTLS_ERR_SSL_WANT_READ);
616
617    /* Push directly to a queue to later simulate a disconnected behavior */
618    TEST_ASSERT(mbedtls_test_ssl_message_queue_push_info(&server_queue,
619                                                         MSGLEN)
620                == MSGLEN);
621
622    /* Test if there's an error when trying to read from a disconnected
623     * socket */
624    TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&server_context, received,
625                                               MSGLEN)
626                == MBEDTLS_TEST_ERROR_RECV_FAILED);
627exit:
628    mbedtls_test_message_socket_close(&server_context);
629    mbedtls_test_message_socket_close(&client_context);
630}
631/* END_CASE */
632
633/* BEGIN_CASE */
634void ssl_message_mock_basic()
635{
636    enum { MSGLEN = 10 };
637    unsigned char message[MSGLEN], received[MSGLEN];
638    mbedtls_test_mock_socket client, server;
639    unsigned i;
640    mbedtls_test_ssl_message_queue server_queue, client_queue;
641    mbedtls_test_message_socket_context server_context, client_context;
642    mbedtls_test_message_socket_init(&server_context);
643    mbedtls_test_message_socket_init(&client_context);
644
645    TEST_ASSERT(mbedtls_test_message_socket_setup(&server_queue,
646                                                  &client_queue, 1,
647                                                  &server,
648                                                  &server_context) == 0);
649
650    TEST_ASSERT(mbedtls_test_message_socket_setup(&client_queue,
651                                                  &server_queue, 1,
652                                                  &client,
653                                                  &client_context) == 0);
654
655    /* Fill up the buffer with structured data so that unwanted changes
656     * can be detected */
657    for (i = 0; i < MSGLEN; i++) {
658        message[i] = i & 0xFF;
659    }
660    TEST_ASSERT(0 == mbedtls_test_mock_socket_connect(&client, &server,
661                                                      MSGLEN));
662
663    /* Send the message to the server */
664    TEST_ASSERT(mbedtls_test_mock_tcp_send_msg(&client_context, message,
665                                               MSGLEN) == MSGLEN);
666
667    /* Read from the server */
668    TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&server_context, received,
669                                               MSGLEN)
670                == MSGLEN);
671
672    TEST_ASSERT(memcmp(message, received, MSGLEN) == 0);
673    memset(received, 0, MSGLEN);
674
675    /* Send the message to the client */
676    TEST_ASSERT(mbedtls_test_mock_tcp_send_msg(&server_context, message,
677                                               MSGLEN)
678                == MSGLEN);
679
680    /* Read from the client */
681    TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&client_context, received,
682                                               MSGLEN)
683                == MSGLEN);
684    TEST_ASSERT(memcmp(message, received, MSGLEN) == 0);
685
686exit:
687    mbedtls_test_message_socket_close(&server_context);
688    mbedtls_test_message_socket_close(&client_context);
689}
690/* END_CASE */
691
692/* BEGIN_CASE */
693void ssl_message_mock_queue_overflow_underflow()
694{
695    enum { MSGLEN = 10 };
696    unsigned char message[MSGLEN], received[MSGLEN];
697    mbedtls_test_mock_socket client, server;
698    unsigned i;
699    mbedtls_test_ssl_message_queue server_queue, client_queue;
700    mbedtls_test_message_socket_context server_context, client_context;
701    mbedtls_test_message_socket_init(&server_context);
702    mbedtls_test_message_socket_init(&client_context);
703
704    TEST_ASSERT(mbedtls_test_message_socket_setup(&server_queue,
705                                                  &client_queue, 2,
706                                                  &server,
707                                                  &server_context) == 0);
708
709    TEST_ASSERT(mbedtls_test_message_socket_setup(&client_queue,
710                                                  &server_queue, 2,
711                                                  &client,
712                                                  &client_context) == 0);
713
714    /* Fill up the buffer with structured data so that unwanted changes
715     * can be detected */
716    for (i = 0; i < MSGLEN; i++) {
717        message[i] = i & 0xFF;
718    }
719    TEST_ASSERT(0 == mbedtls_test_mock_socket_connect(&client, &server,
720                                                      MSGLEN*2));
721
722    /* Send three message to the server, last one with an error */
723    TEST_ASSERT(mbedtls_test_mock_tcp_send_msg(&client_context, message,
724                                               MSGLEN - 1)
725                == MSGLEN - 1);
726
727    TEST_ASSERT(mbedtls_test_mock_tcp_send_msg(&client_context, message,
728                                               MSGLEN)
729                == MSGLEN);
730
731    TEST_ASSERT(mbedtls_test_mock_tcp_send_msg(&client_context, message,
732                                               MSGLEN)
733                == MBEDTLS_ERR_SSL_WANT_WRITE);
734
735    /* Read three messages from the server, last one with an error */
736    TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&server_context, received,
737                                               MSGLEN - 1)
738                == MSGLEN - 1);
739
740    TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&server_context, received,
741                                               MSGLEN)
742                == MSGLEN);
743
744    TEST_ASSERT(memcmp(message, received, MSGLEN) == 0);
745
746    TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&server_context, received,
747                                               MSGLEN)
748                == MBEDTLS_ERR_SSL_WANT_READ);
749
750exit:
751    mbedtls_test_message_socket_close(&server_context);
752    mbedtls_test_message_socket_close(&client_context);
753}
754/* END_CASE */
755
756/* BEGIN_CASE */
757void ssl_message_mock_socket_overflow()
758{
759    enum { MSGLEN = 10 };
760    unsigned char message[MSGLEN], received[MSGLEN];
761    mbedtls_test_mock_socket client, server;
762    unsigned i;
763    mbedtls_test_ssl_message_queue server_queue, client_queue;
764    mbedtls_test_message_socket_context server_context, client_context;
765    mbedtls_test_message_socket_init(&server_context);
766    mbedtls_test_message_socket_init(&client_context);
767
768    TEST_ASSERT(mbedtls_test_message_socket_setup(&server_queue,
769                                                  &client_queue, 2,
770                                                  &server,
771                                                  &server_context) == 0);
772
773    TEST_ASSERT(mbedtls_test_message_socket_setup(&client_queue,
774                                                  &server_queue, 2,
775                                                  &client,
776                                                  &client_context) == 0);
777
778    /* Fill up the buffer with structured data so that unwanted changes
779     * can be detected */
780    for (i = 0; i < MSGLEN; i++) {
781        message[i] = i & 0xFF;
782    }
783    TEST_ASSERT(0 == mbedtls_test_mock_socket_connect(&client, &server,
784                                                      MSGLEN));
785
786    /* Send two message to the server, second one with an error */
787    TEST_ASSERT(mbedtls_test_mock_tcp_send_msg(&client_context, message,
788                                               MSGLEN)
789                == MSGLEN);
790
791    TEST_ASSERT(mbedtls_test_mock_tcp_send_msg(&client_context, message,
792                                               MSGLEN)
793                == MBEDTLS_TEST_ERROR_SEND_FAILED);
794
795    /* Read the only message from the server */
796    TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&server_context, received,
797                                               MSGLEN)
798                == MSGLEN);
799
800    TEST_ASSERT(memcmp(message, received, MSGLEN) == 0);
801
802exit:
803    mbedtls_test_message_socket_close(&server_context);
804    mbedtls_test_message_socket_close(&client_context);
805}
806/* END_CASE */
807
808/* BEGIN_CASE */
809void ssl_message_mock_truncated()
810{
811    enum { MSGLEN = 10 };
812    unsigned char message[MSGLEN], received[MSGLEN];
813    mbedtls_test_mock_socket client, server;
814    unsigned i;
815    mbedtls_test_ssl_message_queue server_queue, client_queue;
816    mbedtls_test_message_socket_context server_context, client_context;
817    mbedtls_test_message_socket_init(&server_context);
818    mbedtls_test_message_socket_init(&client_context);
819
820    TEST_ASSERT(mbedtls_test_message_socket_setup(&server_queue,
821                                                  &client_queue, 2,
822                                                  &server,
823                                                  &server_context) == 0);
824
825    TEST_ASSERT(mbedtls_test_message_socket_setup(&client_queue,
826                                                  &server_queue, 2,
827                                                  &client,
828                                                  &client_context) == 0);
829
830    memset(received, 0, MSGLEN);
831    /* Fill up the buffer with structured data so that unwanted changes
832     * can be detected */
833    for (i = 0; i < MSGLEN; i++) {
834        message[i] = i & 0xFF;
835    }
836    TEST_ASSERT(0 == mbedtls_test_mock_socket_connect(&client, &server,
837                                                      2 * MSGLEN));
838
839    /* Send two messages to the server, the second one small enough to fit in the
840     * receiver's buffer. */
841    TEST_ASSERT(mbedtls_test_mock_tcp_send_msg(&client_context, message,
842                                               MSGLEN)
843                == MSGLEN);
844    TEST_ASSERT(mbedtls_test_mock_tcp_send_msg(&client_context, message,
845                                               MSGLEN / 2)
846                == MSGLEN / 2);
847    /* Read a truncated message from the server */
848    TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&server_context, received,
849                                               MSGLEN/2)
850                == MSGLEN/2);
851
852    /* Test that the first half of the message is valid, and second one isn't */
853    TEST_ASSERT(memcmp(message, received, MSGLEN/2) == 0);
854    TEST_ASSERT(memcmp(message + MSGLEN/2, received + MSGLEN/2, MSGLEN/2)
855                != 0);
856    memset(received, 0, MSGLEN);
857
858    /* Read a full message from the server */
859    TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&server_context, received,
860                                               MSGLEN/2)
861                == MSGLEN / 2);
862
863    /* Test that the first half of the message is valid */
864    TEST_ASSERT(memcmp(message, received, MSGLEN/2) == 0);
865
866exit:
867    mbedtls_test_message_socket_close(&server_context);
868    mbedtls_test_message_socket_close(&client_context);
869}
870/* END_CASE */
871
872/* BEGIN_CASE */
873void ssl_message_mock_socket_read_error()
874{
875    enum { MSGLEN = 10 };
876    unsigned char message[MSGLEN], received[MSGLEN];
877    mbedtls_test_mock_socket client, server;
878    unsigned i;
879    mbedtls_test_ssl_message_queue server_queue, client_queue;
880    mbedtls_test_message_socket_context server_context, client_context;
881    mbedtls_test_message_socket_init(&server_context);
882    mbedtls_test_message_socket_init(&client_context);
883
884    TEST_ASSERT(mbedtls_test_message_socket_setup(&server_queue,
885                                                  &client_queue, 1,
886                                                  &server,
887                                                  &server_context) == 0);
888
889    TEST_ASSERT(mbedtls_test_message_socket_setup(&client_queue,
890                                                  &server_queue, 1,
891                                                  &client,
892                                                  &client_context) == 0);
893
894    /* Fill up the buffer with structured data so that unwanted changes
895     * can be detected */
896    for (i = 0; i < MSGLEN; i++) {
897        message[i] = i & 0xFF;
898    }
899    TEST_ASSERT(0 == mbedtls_test_mock_socket_connect(&client, &server,
900                                                      MSGLEN));
901
902    TEST_ASSERT(mbedtls_test_mock_tcp_send_msg(&client_context, message,
903                                               MSGLEN)
904                == MSGLEN);
905
906    /* Force a read error by disconnecting the socket by hand */
907    server.status = 0;
908    TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&server_context, received,
909                                               MSGLEN)
910                == MBEDTLS_TEST_ERROR_RECV_FAILED);
911    /* Return to a valid state */
912    server.status = MBEDTLS_MOCK_SOCKET_CONNECTED;
913
914    memset(received, 0, sizeof(received));
915
916    /* Test that even though the server tried to read once disconnected, the
917     * continuity is preserved */
918    TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&server_context, received,
919                                               MSGLEN)
920                == MSGLEN);
921
922    TEST_ASSERT(memcmp(message, received, MSGLEN) == 0);
923
924exit:
925    mbedtls_test_message_socket_close(&server_context);
926    mbedtls_test_message_socket_close(&client_context);
927}
928/* END_CASE */
929
930/* BEGIN_CASE */
931void ssl_message_mock_interleaved_one_way()
932{
933    enum { MSGLEN = 10 };
934    unsigned char message[MSGLEN], received[MSGLEN];
935    mbedtls_test_mock_socket client, server;
936    unsigned i;
937    mbedtls_test_ssl_message_queue server_queue, client_queue;
938    mbedtls_test_message_socket_context server_context, client_context;
939    mbedtls_test_message_socket_init(&server_context);
940    mbedtls_test_message_socket_init(&client_context);
941
942    TEST_ASSERT(mbedtls_test_message_socket_setup(&server_queue,
943                                                  &client_queue, 3,
944                                                  &server,
945                                                  &server_context) == 0);
946
947    TEST_ASSERT(mbedtls_test_message_socket_setup(&client_queue,
948                                                  &server_queue, 3,
949                                                  &client,
950                                                  &client_context) == 0);
951
952    /* Fill up the buffer with structured data so that unwanted changes
953     * can be detected */
954    for (i = 0; i < MSGLEN; i++) {
955        message[i] = i & 0xFF;
956    }
957    TEST_ASSERT(0 == mbedtls_test_mock_socket_connect(&client, &server,
958                                                      MSGLEN*3));
959
960    /* Interleaved test - [2 sends, 1 read] twice, and then two reads
961     * (to wrap around the buffer) */
962    for (i = 0; i < 2; i++) {
963        TEST_ASSERT(mbedtls_test_mock_tcp_send_msg(&client_context, message,
964                                                   MSGLEN) == MSGLEN);
965
966        TEST_ASSERT(mbedtls_test_mock_tcp_send_msg(&client_context, message,
967                                                   MSGLEN) == MSGLEN);
968
969        TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&server_context, received,
970                                                   MSGLEN) == MSGLEN);
971        TEST_ASSERT(memcmp(message, received, MSGLEN) == 0);
972        memset(received, 0, sizeof(received));
973    }
974
975    for (i = 0; i < 2; i++) {
976        TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&server_context, received,
977                                                   MSGLEN) == MSGLEN);
978
979        TEST_ASSERT(memcmp(message, received, MSGLEN) == 0);
980    }
981    TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&server_context, received,
982                                               MSGLEN)
983                == MBEDTLS_ERR_SSL_WANT_READ);
984exit:
985    mbedtls_test_message_socket_close(&server_context);
986    mbedtls_test_message_socket_close(&client_context);
987}
988/* END_CASE */
989
990/* BEGIN_CASE */
991void ssl_message_mock_interleaved_two_ways()
992{
993    enum { MSGLEN = 10 };
994    unsigned char message[MSGLEN], received[MSGLEN];
995    mbedtls_test_mock_socket client, server;
996    unsigned i;
997    mbedtls_test_ssl_message_queue server_queue, client_queue;
998    mbedtls_test_message_socket_context server_context, client_context;
999    mbedtls_test_message_socket_init(&server_context);
1000    mbedtls_test_message_socket_init(&client_context);
1001
1002    TEST_ASSERT(mbedtls_test_message_socket_setup(&server_queue,
1003                                                  &client_queue, 3,
1004                                                  &server,
1005                                                  &server_context) == 0);
1006
1007    TEST_ASSERT(mbedtls_test_message_socket_setup(&client_queue,
1008                                                  &server_queue, 3,
1009                                                  &client,
1010                                                  &client_context) == 0);
1011
1012    /* Fill up the buffer with structured data so that unwanted changes
1013     * can be detected */
1014    for (i = 0; i < MSGLEN; i++) {
1015        message[i] = i & 0xFF;
1016    }
1017    TEST_ASSERT(0 == mbedtls_test_mock_socket_connect(&client, &server,
1018                                                      MSGLEN*3));
1019
1020    /* Interleaved test - [2 sends, 1 read] twice, both ways, and then two reads
1021     * (to wrap around the buffer) both ways. */
1022    for (i = 0; i < 2; i++) {
1023        TEST_ASSERT(mbedtls_test_mock_tcp_send_msg(&client_context, message,
1024                                                   MSGLEN) == MSGLEN);
1025
1026        TEST_ASSERT(mbedtls_test_mock_tcp_send_msg(&client_context, message,
1027                                                   MSGLEN) == MSGLEN);
1028
1029        TEST_ASSERT(mbedtls_test_mock_tcp_send_msg(&server_context, message,
1030                                                   MSGLEN) == MSGLEN);
1031
1032        TEST_ASSERT(mbedtls_test_mock_tcp_send_msg(&server_context, message,
1033                                                   MSGLEN) == MSGLEN);
1034
1035        TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&server_context, received,
1036                                                   MSGLEN) == MSGLEN);
1037
1038        TEST_ASSERT(memcmp(message, received, MSGLEN) == 0);
1039
1040        memset(received, 0, sizeof(received));
1041
1042        TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&client_context, received,
1043                                                   MSGLEN) == MSGLEN);
1044
1045        TEST_ASSERT(memcmp(message, received, MSGLEN) == 0);
1046
1047        memset(received, 0, sizeof(received));
1048    }
1049
1050    for (i = 0; i < 2; i++) {
1051        TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&server_context, received,
1052                                                   MSGLEN) == MSGLEN);
1053
1054        TEST_ASSERT(memcmp(message, received, MSGLEN) == 0);
1055        memset(received, 0, sizeof(received));
1056
1057        TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&client_context, received,
1058                                                   MSGLEN) == MSGLEN);
1059
1060        TEST_ASSERT(memcmp(message, received, MSGLEN) == 0);
1061        memset(received, 0, sizeof(received));
1062    }
1063
1064    TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&server_context, received,
1065                                               MSGLEN)
1066                == MBEDTLS_ERR_SSL_WANT_READ);
1067
1068    TEST_ASSERT(mbedtls_test_mock_tcp_recv_msg(&client_context, received,
1069                                               MSGLEN)
1070                == MBEDTLS_ERR_SSL_WANT_READ);
1071exit:
1072    mbedtls_test_message_socket_close(&server_context);
1073    mbedtls_test_message_socket_close(&client_context);
1074}
1075/* END_CASE */
1076
1077/* BEGIN_CASE depends_on:MBEDTLS_SSL_DTLS_ANTI_REPLAY */
1078void ssl_dtls_replay(data_t *prevs, data_t *new, int ret)
1079{
1080    uint32_t len = 0;
1081    mbedtls_ssl_context ssl;
1082    mbedtls_ssl_config conf;
1083
1084    mbedtls_ssl_init(&ssl);
1085    mbedtls_ssl_config_init(&conf);
1086
1087    TEST_ASSERT(mbedtls_ssl_config_defaults(&conf,
1088                                            MBEDTLS_SSL_IS_CLIENT,
1089                                            MBEDTLS_SSL_TRANSPORT_DATAGRAM,
1090                                            MBEDTLS_SSL_PRESET_DEFAULT) == 0);
1091    TEST_ASSERT(mbedtls_ssl_setup(&ssl, &conf) == 0);
1092
1093    /* Read previous record numbers */
1094    for (len = 0; len < prevs->len; len += 6) {
1095        memcpy(ssl.in_ctr + 2, prevs->x + len, 6);
1096        mbedtls_ssl_dtls_replay_update(&ssl);
1097    }
1098
1099    /* Check new number */
1100    memcpy(ssl.in_ctr + 2, new->x, 6);
1101    TEST_ASSERT(mbedtls_ssl_dtls_replay_check(&ssl) == ret);
1102
1103    mbedtls_ssl_free(&ssl);
1104    mbedtls_ssl_config_free(&conf);
1105}
1106/* END_CASE */
1107
1108/* BEGIN_CASE depends_on:MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
1109void ssl_set_hostname_twice(char *hostname0, char *hostname1)
1110{
1111    mbedtls_ssl_context ssl;
1112    mbedtls_ssl_init(&ssl);
1113
1114    TEST_ASSERT(mbedtls_ssl_set_hostname(&ssl, hostname0) == 0);
1115    TEST_ASSERT(mbedtls_ssl_set_hostname(&ssl, hostname1) == 0);
1116
1117    mbedtls_ssl_free(&ssl);
1118}
1119/* END_CASE */
1120
1121/* BEGIN_CASE */
1122void ssl_crypt_record(int cipher_type, int hash_id,
1123                      int etm, int tag_mode, int ver,
1124                      int cid0_len, int cid1_len)
1125{
1126    /*
1127     * Test several record encryptions and decryptions
1128     * with plenty of space before and after the data
1129     * within the record buffer.
1130     */
1131
1132    int ret;
1133    int num_records = 16;
1134    mbedtls_ssl_context ssl; /* ONLY for debugging */
1135
1136    mbedtls_ssl_transform t0, t1;
1137    unsigned char *buf = NULL;
1138    size_t const buflen = 512;
1139    mbedtls_record rec, rec_backup;
1140
1141    USE_PSA_INIT();
1142
1143    mbedtls_ssl_init(&ssl);
1144    mbedtls_ssl_transform_init(&t0);
1145    mbedtls_ssl_transform_init(&t1);
1146    ret = mbedtls_test_ssl_build_transforms(&t0, &t1, cipher_type, hash_id,
1147                                            etm, tag_mode, ver,
1148                                            (size_t) cid0_len,
1149                                            (size_t) cid1_len);
1150
1151    TEST_ASSERT(ret == 0);
1152
1153    TEST_ASSERT((buf = mbedtls_calloc(1, buflen)) != NULL);
1154
1155    while (num_records-- > 0) {
1156        mbedtls_ssl_transform *t_dec, *t_enc;
1157        /* Take turns in who's sending and who's receiving. */
1158        if (num_records % 3 == 0) {
1159            t_dec = &t0;
1160            t_enc = &t1;
1161        } else {
1162            t_dec = &t1;
1163            t_enc = &t0;
1164        }
1165
1166        /*
1167         * The record header affects the transformation in two ways:
1168         * 1) It determines the AEAD additional data
1169         * 2) The record counter sometimes determines the IV.
1170         *
1171         * Apart from that, the fields don't have influence.
1172         * In particular, it is currently not the responsibility
1173         * of ssl_encrypt/decrypt_buf to check if the transform
1174         * version matches the record version, or that the
1175         * type is sensible.
1176         */
1177
1178        memset(rec.ctr, num_records, sizeof(rec.ctr));
1179        rec.type    = 42;
1180        rec.ver[0]  = num_records;
1181        rec.ver[1]  = num_records;
1182#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
1183        rec.cid_len = 0;
1184#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1185
1186        rec.buf     = buf;
1187        rec.buf_len = buflen;
1188        rec.data_offset = 16;
1189        /* Make sure to vary the length to exercise different
1190         * paddings. */
1191        rec.data_len = 1 + num_records;
1192
1193        memset(rec.buf + rec.data_offset, 42, rec.data_len);
1194
1195        /* Make a copy for later comparison */
1196        rec_backup = rec;
1197
1198        /* Encrypt record */
1199        ret = mbedtls_ssl_encrypt_buf(&ssl, t_enc, &rec,
1200                                      mbedtls_test_rnd_std_rand, NULL);
1201        TEST_ASSERT(ret == 0 || ret == MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL);
1202        if (ret != 0) {
1203            continue;
1204        }
1205
1206#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
1207        if (rec.cid_len != 0) {
1208            /* DTLS 1.2 + CID hides the real content type and
1209             * uses a special CID content type in the protected
1210             * record. Double-check this. */
1211            TEST_ASSERT(rec.type == MBEDTLS_SSL_MSG_CID);
1212        }
1213#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1214
1215#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
1216        if (t_enc->tls_version == MBEDTLS_SSL_VERSION_TLS1_3) {
1217            /* TLS 1.3 hides the real content type and
1218             * always uses Application Data as the content type
1219             * for protected records. Double-check this. */
1220            TEST_ASSERT(rec.type == MBEDTLS_SSL_MSG_APPLICATION_DATA);
1221        }
1222#endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
1223
1224        /* Decrypt record with t_dec */
1225        ret = mbedtls_ssl_decrypt_buf(&ssl, t_dec, &rec);
1226        TEST_ASSERT(ret == 0);
1227
1228        /* Compare results */
1229        TEST_ASSERT(rec.type == rec_backup.type);
1230        TEST_ASSERT(memcmp(rec.ctr, rec_backup.ctr, 8) == 0);
1231        TEST_ASSERT(rec.ver[0] == rec_backup.ver[0]);
1232        TEST_ASSERT(rec.ver[1] == rec_backup.ver[1]);
1233        TEST_ASSERT(rec.data_len == rec_backup.data_len);
1234        TEST_ASSERT(rec.data_offset == rec_backup.data_offset);
1235        TEST_ASSERT(memcmp(rec.buf + rec.data_offset,
1236                           rec_backup.buf + rec_backup.data_offset,
1237                           rec.data_len) == 0);
1238    }
1239
1240exit:
1241
1242    /* Cleanup */
1243    mbedtls_ssl_free(&ssl);
1244    mbedtls_ssl_transform_free(&t0);
1245    mbedtls_ssl_transform_free(&t1);
1246
1247    mbedtls_free(buf);
1248    USE_PSA_DONE();
1249}
1250/* END_CASE */
1251
1252/* BEGIN_CASE */
1253void ssl_crypt_record_small(int cipher_type, int hash_id,
1254                            int etm, int tag_mode, int ver,
1255                            int cid0_len, int cid1_len)
1256{
1257    /*
1258     * Test pairs of encryption and decryption with an increasing
1259     * amount of space in the record buffer - in more detail:
1260     * 1) Try to encrypt with 0, 1, 2, ... bytes available
1261     *    in front of the plaintext, and expect the encryption
1262     *    to succeed starting from some offset. Always keep
1263     *    enough space in the end of the buffer.
1264     * 2) Try to encrypt with 0, 1, 2, ... bytes available
1265     *    at the end of the plaintext, and expect the encryption
1266     *    to succeed starting from some offset. Always keep
1267     *    enough space at the beginning of the buffer.
1268     * 3) Try to encrypt with 0, 1, 2, ... bytes available
1269     *    both at the front and end of the plaintext,
1270     *    and expect the encryption to succeed starting from
1271     *    some offset.
1272     *
1273     * If encryption succeeds, check that decryption succeeds
1274     * and yields the original record.
1275     */
1276
1277    mbedtls_ssl_context ssl; /* ONLY for debugging */
1278
1279    mbedtls_ssl_transform t0, t1;
1280    unsigned char *buf = NULL;
1281    size_t const buflen = 256;
1282    mbedtls_record rec, rec_backup;
1283
1284    int ret;
1285    int mode;              /* Mode 1, 2 or 3 as explained above     */
1286    size_t offset;         /* Available space at beginning/end/both */
1287    size_t threshold = 96; /* Maximum offset to test against        */
1288
1289    size_t default_pre_padding  = 64;  /* Pre-padding to use in mode 2  */
1290    size_t default_post_padding = 128; /* Post-padding to use in mode 1 */
1291
1292    int seen_success; /* Indicates if in the current mode we've
1293                       * already seen a successful test. */
1294
1295    USE_PSA_INIT();
1296
1297    mbedtls_ssl_init(&ssl);
1298    mbedtls_ssl_transform_init(&t0);
1299    mbedtls_ssl_transform_init(&t1);
1300    ret = mbedtls_test_ssl_build_transforms(&t0, &t1, cipher_type, hash_id,
1301                                            etm, tag_mode, ver,
1302                                            (size_t) cid0_len,
1303                                            (size_t) cid1_len);
1304
1305    TEST_ASSERT(ret == 0);
1306
1307    TEST_ASSERT((buf = mbedtls_calloc(1, buflen)) != NULL);
1308
1309    for (mode = 1; mode <= 3; mode++) {
1310        seen_success = 0;
1311        for (offset = 0; offset <= threshold; offset++) {
1312            mbedtls_ssl_transform *t_dec, *t_enc;
1313            t_dec = &t0;
1314            t_enc = &t1;
1315
1316            memset(rec.ctr, offset, sizeof(rec.ctr));
1317            rec.type    = 42;
1318            rec.ver[0]  = offset;
1319            rec.ver[1]  = offset;
1320            rec.buf     = buf;
1321            rec.buf_len = buflen;
1322#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
1323            rec.cid_len = 0;
1324#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1325
1326            switch (mode) {
1327                case 1: /* Space in the beginning */
1328                    rec.data_offset = offset;
1329                    rec.data_len = buflen - offset - default_post_padding;
1330                    break;
1331
1332                case 2: /* Space in the end */
1333                    rec.data_offset = default_pre_padding;
1334                    rec.data_len = buflen - default_pre_padding - offset;
1335                    break;
1336
1337                case 3: /* Space in the beginning and end */
1338                    rec.data_offset = offset;
1339                    rec.data_len = buflen - 2 * offset;
1340                    break;
1341
1342                default:
1343                    TEST_ASSERT(0);
1344                    break;
1345            }
1346
1347            memset(rec.buf + rec.data_offset, 42, rec.data_len);
1348
1349            /* Make a copy for later comparison */
1350            rec_backup = rec;
1351
1352            /* Encrypt record */
1353            ret = mbedtls_ssl_encrypt_buf(&ssl, t_enc, &rec,
1354                                          mbedtls_test_rnd_std_rand, NULL);
1355
1356            if ((mode == 1 || mode == 2) && seen_success) {
1357                TEST_ASSERT(ret == 0);
1358            } else {
1359                TEST_ASSERT(ret == 0 || ret == MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL);
1360                if (ret == 0) {
1361                    seen_success = 1;
1362                }
1363            }
1364
1365            if (ret != 0) {
1366                continue;
1367            }
1368
1369#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
1370            if (rec.cid_len != 0) {
1371                /* DTLS 1.2 + CID hides the real content type and
1372                 * uses a special CID content type in the protected
1373                 * record. Double-check this. */
1374                TEST_ASSERT(rec.type == MBEDTLS_SSL_MSG_CID);
1375            }
1376#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1377
1378#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
1379            if (t_enc->tls_version == MBEDTLS_SSL_VERSION_TLS1_3) {
1380                /* TLS 1.3 hides the real content type and
1381                 * always uses Application Data as the content type
1382                 * for protected records. Double-check this. */
1383                TEST_ASSERT(rec.type == MBEDTLS_SSL_MSG_APPLICATION_DATA);
1384            }
1385#endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
1386
1387            /* Decrypt record with t_dec */
1388            TEST_ASSERT(mbedtls_ssl_decrypt_buf(&ssl, t_dec, &rec) == 0);
1389
1390            /* Compare results */
1391            TEST_ASSERT(rec.type == rec_backup.type);
1392            TEST_ASSERT(memcmp(rec.ctr, rec_backup.ctr, 8) == 0);
1393            TEST_ASSERT(rec.ver[0] == rec_backup.ver[0]);
1394            TEST_ASSERT(rec.ver[1] == rec_backup.ver[1]);
1395            TEST_ASSERT(rec.data_len == rec_backup.data_len);
1396            TEST_ASSERT(rec.data_offset == rec_backup.data_offset);
1397            TEST_ASSERT(memcmp(rec.buf + rec.data_offset,
1398                               rec_backup.buf + rec_backup.data_offset,
1399                               rec.data_len) == 0);
1400        }
1401
1402        TEST_ASSERT(seen_success == 1);
1403    }
1404
1405exit:
1406
1407    /* Cleanup */
1408    mbedtls_ssl_free(&ssl);
1409    mbedtls_ssl_transform_free(&t0);
1410    mbedtls_ssl_transform_free(&t1);
1411
1412    mbedtls_free(buf);
1413    USE_PSA_DONE();
1414}
1415/* END_CASE */
1416
1417/* BEGIN_CASE depends_on:MBEDTLS_CIPHER_MODE_CBC:MBEDTLS_AES_C:MBEDTLS_SSL_PROTO_TLS1_2 */
1418void ssl_decrypt_non_etm_cbc(int cipher_type, int hash_id, int trunc_hmac,
1419                             int length_selector)
1420{
1421    /*
1422     * Test record decryption for CBC without EtM, focused on the verification
1423     * of padding and MAC.
1424     *
1425     * Actually depends on TLS 1.2 and either AES, ARIA or Camellia, but since
1426     * the test framework doesn't support alternation in dependency statements,
1427     * just depend on AES.
1428     *
1429     * The length_selector argument is interpreted as follows:
1430     * - if it's -1, the plaintext length is 0 and minimal padding is applied
1431     * - if it's -2, the plaintext length is 0 and maximal padding is applied
1432     * - otherwise it must be in [0, 255] and is padding_length from RFC 5246:
1433     *   it's the length of the rest of the padding, that is, excluding the
1434     *   byte that encodes the length. The minimal non-zero plaintext length
1435     *   that gives this padding_length is automatically selected.
1436     */
1437    mbedtls_ssl_context ssl; /* ONLY for debugging */
1438    mbedtls_ssl_transform t0, t1;
1439    mbedtls_record rec, rec_save;
1440    unsigned char *buf = NULL, *buf_save = NULL;
1441    size_t buflen, olen = 0;
1442    size_t plaintext_len, block_size, i;
1443    unsigned char padlen; /* excluding the padding_length byte */
1444    unsigned char add_data[13];
1445#if defined(MBEDTLS_USE_PSA_CRYPTO)
1446    psa_mac_operation_t operation = PSA_MAC_OPERATION_INIT;
1447    size_t sign_mac_length = 0;
1448    unsigned char mac[PSA_HASH_MAX_SIZE];
1449#else
1450    unsigned char mac[MBEDTLS_MD_MAX_SIZE];
1451#endif
1452    int exp_ret;
1453    int ret;
1454    const unsigned char pad_max_len = 255; /* Per the standard */
1455
1456    USE_PSA_INIT();
1457
1458    mbedtls_ssl_init(&ssl);
1459    mbedtls_ssl_transform_init(&t0);
1460    mbedtls_ssl_transform_init(&t1);
1461
1462    /* Set up transforms with dummy keys */
1463    ret = mbedtls_test_ssl_build_transforms(&t0, &t1, cipher_type, hash_id,
1464                                            0, trunc_hmac,
1465                                            MBEDTLS_SSL_VERSION_TLS1_2,
1466                                            0, 0);
1467
1468    TEST_ASSERT(ret == 0);
1469
1470    /* Determine padding/plaintext length */
1471    TEST_ASSERT(length_selector >= -2 && length_selector <= 255);
1472    block_size = t0.ivlen;
1473    if (length_selector < 0) {
1474        plaintext_len = 0;
1475
1476        /* Minimal padding
1477         * The +1 is for the padding_length byte, not counted in padlen. */
1478        padlen = block_size - (t0.maclen + 1) % block_size;
1479
1480        /* Maximal padding? */
1481        if (length_selector == -2) {
1482            padlen += block_size * ((pad_max_len - padlen) / block_size);
1483        }
1484    } else {
1485        padlen = length_selector;
1486
1487        /* Minimal non-zero plaintext_length giving desired padding.
1488         * The +1 is for the padding_length byte, not counted in padlen. */
1489        plaintext_len = block_size - (padlen + t0.maclen + 1) % block_size;
1490    }
1491
1492    /* Prepare a buffer for record data */
1493    buflen = block_size
1494             + plaintext_len
1495             + t0.maclen
1496             + padlen + 1;
1497    ASSERT_ALLOC(buf, buflen);
1498    ASSERT_ALLOC(buf_save, buflen);
1499
1500    /* Prepare a dummy record header */
1501    memset(rec.ctr, 0, sizeof(rec.ctr));
1502    rec.type    = MBEDTLS_SSL_MSG_APPLICATION_DATA;
1503    mbedtls_ssl_write_version(rec.ver, MBEDTLS_SSL_TRANSPORT_STREAM,
1504                              MBEDTLS_SSL_VERSION_TLS1_2);
1505#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
1506    rec.cid_len = 0;
1507#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1508
1509    /* Prepare dummy record content */
1510    rec.buf     = buf;
1511    rec.buf_len = buflen;
1512    rec.data_offset = block_size;
1513    rec.data_len = plaintext_len;
1514    memset(rec.buf + rec.data_offset, 42, rec.data_len);
1515
1516    /* Serialized version of record header for MAC purposes */
1517    memcpy(add_data, rec.ctr, 8);
1518    add_data[8] = rec.type;
1519    add_data[9] = rec.ver[0];
1520    add_data[10] = rec.ver[1];
1521    add_data[11] = (rec.data_len >> 8) & 0xff;
1522    add_data[12] = (rec.data_len >> 0) & 0xff;
1523
1524    /* Set dummy IV */
1525    memset(t0.iv_enc, 0x55, t0.ivlen);
1526    memcpy(rec.buf, t0.iv_enc, t0.ivlen);
1527
1528    /*
1529     * Prepare a pre-encryption record (with MAC and padding), and save it.
1530     */
1531
1532    /* MAC with additional data */
1533#if defined(MBEDTLS_USE_PSA_CRYPTO)
1534    TEST_EQUAL(PSA_SUCCESS, psa_mac_sign_setup(&operation,
1535                                               t0.psa_mac_enc,
1536                                               t0.psa_mac_alg));
1537    TEST_EQUAL(PSA_SUCCESS, psa_mac_update(&operation, add_data, 13));
1538    TEST_EQUAL(PSA_SUCCESS, psa_mac_update(&operation,
1539                                           rec.buf + rec.data_offset,
1540                                           rec.data_len));
1541    TEST_EQUAL(PSA_SUCCESS, psa_mac_sign_finish(&operation,
1542                                                mac, sizeof(mac),
1543                                                &sign_mac_length));
1544#else
1545    TEST_EQUAL(0, mbedtls_md_hmac_update(&t0.md_ctx_enc, add_data, 13));
1546    TEST_EQUAL(0, mbedtls_md_hmac_update(&t0.md_ctx_enc,
1547                                         rec.buf + rec.data_offset,
1548                                         rec.data_len));
1549    TEST_EQUAL(0, mbedtls_md_hmac_finish(&t0.md_ctx_enc, mac));
1550#endif
1551
1552    memcpy(rec.buf + rec.data_offset + rec.data_len, mac, t0.maclen);
1553    rec.data_len += t0.maclen;
1554
1555    /* Pad */
1556    memset(rec.buf + rec.data_offset + rec.data_len, padlen, padlen + 1);
1557    rec.data_len += padlen + 1;
1558
1559    /* Save correct pre-encryption record */
1560    rec_save = rec;
1561    rec_save.buf = buf_save;
1562    memcpy(buf_save, buf, buflen);
1563
1564    /*
1565     * Encrypt and decrypt the correct record, expecting success
1566     */
1567    TEST_EQUAL(0, mbedtls_test_psa_cipher_encrypt_helper(
1568                   &t0, t0.iv_enc, t0.ivlen, rec.buf + rec.data_offset,
1569                   rec.data_len, rec.buf + rec.data_offset, &olen));
1570    rec.data_offset -= t0.ivlen;
1571    rec.data_len    += t0.ivlen;
1572
1573    TEST_EQUAL(0, mbedtls_ssl_decrypt_buf(&ssl, &t1, &rec));
1574
1575    /*
1576     * Modify each byte of the pre-encryption record before encrypting and
1577     * decrypting it, expecting failure every time.
1578     */
1579    for (i = block_size; i < buflen; i++) {
1580        mbedtls_test_set_step(i);
1581
1582        /* Restore correct pre-encryption record */
1583        rec = rec_save;
1584        rec.buf = buf;
1585        memcpy(buf, buf_save, buflen);
1586
1587        /* Corrupt one byte of the data (could be plaintext, MAC or padding) */
1588        rec.buf[i] ^= 0x01;
1589
1590        /* Encrypt */
1591        TEST_EQUAL(0, mbedtls_test_psa_cipher_encrypt_helper(
1592                       &t0, t0.iv_enc, t0.ivlen, rec.buf + rec.data_offset,
1593                       rec.data_len, rec.buf + rec.data_offset, &olen));
1594        rec.data_offset -= t0.ivlen;
1595        rec.data_len    += t0.ivlen;
1596
1597        /* Decrypt and expect failure */
1598        TEST_EQUAL(MBEDTLS_ERR_SSL_INVALID_MAC,
1599                   mbedtls_ssl_decrypt_buf(&ssl, &t1, &rec));
1600    }
1601
1602    /*
1603     * Use larger values of the padding bytes - with small buffers, this tests
1604     * the case where the announced padlen would be larger than the buffer
1605     * (and before that, than the buffer minus the size of the MAC), to make
1606     * sure our padding checking code does not perform any out-of-bounds reads
1607     * in this case. (With larger buffers, ie when the plaintext is long or
1608     * maximal length padding is used, this is less relevant but still doesn't
1609     * hurt to test.)
1610     *
1611     * (Start the loop with correct padding, just to double-check that record
1612     * saving did work, and that we're overwriting the correct bytes.)
1613     */
1614    for (i = padlen; i <= pad_max_len; i++) {
1615        mbedtls_test_set_step(i);
1616
1617        /* Restore correct pre-encryption record */
1618        rec = rec_save;
1619        rec.buf = buf;
1620        memcpy(buf, buf_save, buflen);
1621
1622        /* Set padding bytes to new value */
1623        memset(buf + buflen - padlen - 1, i, padlen + 1);
1624
1625        /* Encrypt */
1626        TEST_EQUAL(0, mbedtls_test_psa_cipher_encrypt_helper(
1627                       &t0, t0.iv_enc, t0.ivlen, rec.buf + rec.data_offset,
1628                       rec.data_len, rec.buf + rec.data_offset, &olen));
1629        rec.data_offset -= t0.ivlen;
1630        rec.data_len    += t0.ivlen;
1631
1632        /* Decrypt and expect failure except the first time */
1633        exp_ret = (i == padlen) ? 0 : MBEDTLS_ERR_SSL_INVALID_MAC;
1634        TEST_EQUAL(exp_ret, mbedtls_ssl_decrypt_buf(&ssl, &t1, &rec));
1635    }
1636
1637exit:
1638    mbedtls_ssl_free(&ssl);
1639    mbedtls_ssl_transform_free(&t0);
1640    mbedtls_ssl_transform_free(&t1);
1641    mbedtls_free(buf);
1642    mbedtls_free(buf_save);
1643    USE_PSA_DONE();
1644}
1645/* END_CASE */
1646
1647/* BEGIN_CASE depends_on:MBEDTLS_SSL_PROTO_TLS1_3 */
1648void ssl_tls13_hkdf_expand_label(int hash_alg,
1649                                 data_t *secret,
1650                                 int label_idx,
1651                                 data_t *ctx,
1652                                 int desired_length,
1653                                 data_t *expected)
1654{
1655    unsigned char dst[100];
1656
1657    unsigned char const *lbl = NULL;
1658    size_t lbl_len;
1659#define MBEDTLS_SSL_TLS1_3_LABEL(name, string)                       \
1660    if (label_idx == (int) tls13_label_ ## name)                      \
1661    {                                                                  \
1662        lbl = mbedtls_ssl_tls13_labels.name;                           \
1663        lbl_len = sizeof(mbedtls_ssl_tls13_labels.name);             \
1664    }
1665    MBEDTLS_SSL_TLS1_3_LABEL_LIST
1666#undef MBEDTLS_SSL_TLS1_3_LABEL
1667    TEST_ASSERT(lbl != NULL);
1668
1669    /* Check sanity of test parameters. */
1670    TEST_ASSERT((size_t) desired_length <= sizeof(dst));
1671    TEST_ASSERT((size_t) desired_length == expected->len);
1672
1673    PSA_INIT();
1674
1675    TEST_ASSERT(mbedtls_ssl_tls13_hkdf_expand_label(
1676                    (psa_algorithm_t) hash_alg,
1677                    secret->x, secret->len,
1678                    lbl, lbl_len,
1679                    ctx->x, ctx->len,
1680                    dst, desired_length) == 0);
1681
1682    ASSERT_COMPARE(dst, (size_t) desired_length,
1683                   expected->x, (size_t) expected->len);
1684
1685    PSA_DONE();
1686}
1687/* END_CASE */
1688
1689/* BEGIN_CASE depends_on:MBEDTLS_SSL_PROTO_TLS1_3 */
1690void ssl_tls13_traffic_key_generation(int hash_alg,
1691                                      data_t *server_secret,
1692                                      data_t *client_secret,
1693                                      int desired_iv_len,
1694                                      int desired_key_len,
1695                                      data_t *expected_server_write_key,
1696                                      data_t *expected_server_write_iv,
1697                                      data_t *expected_client_write_key,
1698                                      data_t *expected_client_write_iv)
1699{
1700    mbedtls_ssl_key_set keys;
1701
1702    /* Check sanity of test parameters. */
1703    TEST_ASSERT(client_secret->len == server_secret->len);
1704    TEST_ASSERT(
1705        expected_client_write_iv->len == expected_server_write_iv->len &&
1706        expected_client_write_iv->len == (size_t) desired_iv_len);
1707    TEST_ASSERT(
1708        expected_client_write_key->len == expected_server_write_key->len &&
1709        expected_client_write_key->len == (size_t) desired_key_len);
1710
1711    PSA_INIT();
1712
1713    TEST_ASSERT(mbedtls_ssl_tls13_make_traffic_keys(
1714                    (psa_algorithm_t) hash_alg,
1715                    client_secret->x,
1716                    server_secret->x,
1717                    client_secret->len /* == server_secret->len */,
1718                    desired_key_len, desired_iv_len,
1719                    &keys) == 0);
1720
1721    ASSERT_COMPARE(keys.client_write_key,
1722                   keys.key_len,
1723                   expected_client_write_key->x,
1724                   (size_t) desired_key_len);
1725    ASSERT_COMPARE(keys.server_write_key,
1726                   keys.key_len,
1727                   expected_server_write_key->x,
1728                   (size_t) desired_key_len);
1729    ASSERT_COMPARE(keys.client_write_iv,
1730                   keys.iv_len,
1731                   expected_client_write_iv->x,
1732                   (size_t) desired_iv_len);
1733    ASSERT_COMPARE(keys.server_write_iv,
1734                   keys.iv_len,
1735                   expected_server_write_iv->x,
1736                   (size_t) desired_iv_len);
1737
1738    PSA_DONE();
1739}
1740/* END_CASE */
1741
1742/* BEGIN_CASE depends_on:MBEDTLS_SSL_PROTO_TLS1_3 */
1743void ssl_tls13_derive_secret(int hash_alg,
1744                             data_t *secret,
1745                             int label_idx,
1746                             data_t *ctx,
1747                             int desired_length,
1748                             int already_hashed,
1749                             data_t *expected)
1750{
1751    unsigned char dst[100];
1752
1753    unsigned char const *lbl = NULL;
1754    size_t lbl_len;
1755#define MBEDTLS_SSL_TLS1_3_LABEL(name, string)                       \
1756    if (label_idx == (int) tls13_label_ ## name)                      \
1757    {                                                                  \
1758        lbl = mbedtls_ssl_tls13_labels.name;                           \
1759        lbl_len = sizeof(mbedtls_ssl_tls13_labels.name);             \
1760    }
1761    MBEDTLS_SSL_TLS1_3_LABEL_LIST
1762#undef MBEDTLS_SSL_TLS1_3_LABEL
1763    TEST_ASSERT(lbl != NULL);
1764
1765    /* Check sanity of test parameters. */
1766    TEST_ASSERT((size_t) desired_length <= sizeof(dst));
1767    TEST_ASSERT((size_t) desired_length == expected->len);
1768
1769    PSA_INIT();
1770
1771    TEST_ASSERT(mbedtls_ssl_tls13_derive_secret(
1772                    (psa_algorithm_t) hash_alg,
1773                    secret->x, secret->len,
1774                    lbl, lbl_len,
1775                    ctx->x, ctx->len,
1776                    already_hashed,
1777                    dst, desired_length) == 0);
1778
1779    ASSERT_COMPARE(dst, desired_length,
1780                   expected->x, desired_length);
1781
1782    PSA_DONE();
1783}
1784/* END_CASE */
1785
1786/* BEGIN_CASE depends_on:MBEDTLS_SSL_PROTO_TLS1_3 */
1787void ssl_tls13_derive_early_secrets(int hash_alg,
1788                                    data_t *secret,
1789                                    data_t *transcript,
1790                                    data_t *traffic_expected,
1791                                    data_t *exporter_expected)
1792{
1793    mbedtls_ssl_tls13_early_secrets secrets;
1794
1795    /* Double-check that we've passed sane parameters. */
1796    psa_algorithm_t alg = (psa_algorithm_t) hash_alg;
1797    size_t const hash_len = PSA_HASH_LENGTH(alg);
1798    TEST_ASSERT(PSA_ALG_IS_HASH(alg)             &&
1799                secret->len == hash_len            &&
1800                transcript->len == hash_len        &&
1801                traffic_expected->len == hash_len  &&
1802                exporter_expected->len == hash_len);
1803
1804    PSA_INIT();
1805
1806    TEST_ASSERT(mbedtls_ssl_tls13_derive_early_secrets(
1807                    alg, secret->x, transcript->x, transcript->len,
1808                    &secrets) == 0);
1809
1810    ASSERT_COMPARE(secrets.client_early_traffic_secret, hash_len,
1811                   traffic_expected->x, traffic_expected->len);
1812    ASSERT_COMPARE(secrets.early_exporter_master_secret, hash_len,
1813                   exporter_expected->x, exporter_expected->len);
1814
1815    PSA_DONE();
1816}
1817/* END_CASE */
1818
1819/* BEGIN_CASE depends_on:MBEDTLS_SSL_PROTO_TLS1_3 */
1820void ssl_tls13_derive_handshake_secrets(int hash_alg,
1821                                        data_t *secret,
1822                                        data_t *transcript,
1823                                        data_t *client_expected,
1824                                        data_t *server_expected)
1825{
1826    mbedtls_ssl_tls13_handshake_secrets secrets;
1827
1828    /* Double-check that we've passed sane parameters. */
1829    psa_algorithm_t alg = (psa_algorithm_t) hash_alg;
1830    size_t const hash_len = PSA_HASH_LENGTH(alg);
1831    TEST_ASSERT(PSA_ALG_IS_HASH(alg)            &&
1832                secret->len == hash_len           &&
1833                transcript->len == hash_len       &&
1834                client_expected->len == hash_len  &&
1835                server_expected->len == hash_len);
1836
1837    PSA_INIT();
1838
1839    TEST_ASSERT(mbedtls_ssl_tls13_derive_handshake_secrets(
1840                    alg, secret->x, transcript->x, transcript->len,
1841                    &secrets) == 0);
1842
1843    ASSERT_COMPARE(secrets.client_handshake_traffic_secret, hash_len,
1844                   client_expected->x, client_expected->len);
1845    ASSERT_COMPARE(secrets.server_handshake_traffic_secret, hash_len,
1846                   server_expected->x, server_expected->len);
1847
1848    PSA_DONE();
1849}
1850/* END_CASE */
1851
1852/* BEGIN_CASE depends_on:MBEDTLS_SSL_PROTO_TLS1_3 */
1853void ssl_tls13_derive_application_secrets(int hash_alg,
1854                                          data_t *secret,
1855                                          data_t *transcript,
1856                                          data_t *client_expected,
1857                                          data_t *server_expected,
1858                                          data_t *exporter_expected)
1859{
1860    mbedtls_ssl_tls13_application_secrets secrets;
1861
1862    /* Double-check that we've passed sane parameters. */
1863    psa_algorithm_t alg = (psa_algorithm_t) hash_alg;
1864    size_t const hash_len = PSA_HASH_LENGTH(alg);
1865    TEST_ASSERT(PSA_ALG_IS_HASH(alg)            &&
1866                secret->len == hash_len           &&
1867                transcript->len == hash_len       &&
1868                client_expected->len == hash_len  &&
1869                server_expected->len == hash_len  &&
1870                exporter_expected->len == hash_len);
1871
1872    PSA_INIT();
1873
1874    TEST_ASSERT(mbedtls_ssl_tls13_derive_application_secrets(
1875                    alg, secret->x, transcript->x, transcript->len,
1876                    &secrets) == 0);
1877
1878    ASSERT_COMPARE(secrets.client_application_traffic_secret_N, hash_len,
1879                   client_expected->x, client_expected->len);
1880    ASSERT_COMPARE(secrets.server_application_traffic_secret_N, hash_len,
1881                   server_expected->x, server_expected->len);
1882    ASSERT_COMPARE(secrets.exporter_master_secret, hash_len,
1883                   exporter_expected->x, exporter_expected->len);
1884
1885    PSA_DONE();
1886}
1887/* END_CASE */
1888
1889/* BEGIN_CASE depends_on:MBEDTLS_SSL_PROTO_TLS1_3 */
1890void ssl_tls13_derive_resumption_secrets(int hash_alg,
1891                                         data_t *secret,
1892                                         data_t *transcript,
1893                                         data_t *resumption_expected)
1894{
1895    mbedtls_ssl_tls13_application_secrets secrets;
1896
1897    /* Double-check that we've passed sane parameters. */
1898    psa_algorithm_t alg = (psa_algorithm_t) hash_alg;
1899    size_t const hash_len = PSA_HASH_LENGTH(alg);
1900    TEST_ASSERT(PSA_ALG_IS_HASH(alg)              &&
1901                secret->len == hash_len             &&
1902                transcript->len == hash_len         &&
1903                resumption_expected->len == hash_len);
1904
1905    PSA_INIT();
1906
1907    TEST_ASSERT(mbedtls_ssl_tls13_derive_resumption_master_secret(
1908                    alg, secret->x, transcript->x, transcript->len,
1909                    &secrets) == 0);
1910
1911    ASSERT_COMPARE(secrets.resumption_master_secret, hash_len,
1912                   resumption_expected->x, resumption_expected->len);
1913
1914    PSA_DONE();
1915}
1916/* END_CASE */
1917
1918/* BEGIN_CASE depends_on:MBEDTLS_SSL_PROTO_TLS1_3 */
1919void ssl_tls13_create_psk_binder(int hash_alg,
1920                                 data_t *psk,
1921                                 int psk_type,
1922                                 data_t *transcript,
1923                                 data_t *binder_expected)
1924{
1925    unsigned char binder[MBEDTLS_HASH_MAX_SIZE];
1926
1927    /* Double-check that we've passed sane parameters. */
1928    psa_algorithm_t alg = (psa_algorithm_t) hash_alg;
1929    size_t const hash_len = PSA_HASH_LENGTH(alg);
1930    TEST_ASSERT(PSA_ALG_IS_HASH(alg)          &&
1931                transcript->len == hash_len     &&
1932                binder_expected->len == hash_len);
1933
1934    PSA_INIT();
1935
1936    TEST_ASSERT(mbedtls_ssl_tls13_create_psk_binder(
1937                    NULL,  /* SSL context for debugging only */
1938                    alg,
1939                    psk->x, psk->len,
1940                    psk_type,
1941                    transcript->x,
1942                    binder) == 0);
1943
1944    ASSERT_COMPARE(binder, hash_len,
1945                   binder_expected->x, binder_expected->len);
1946
1947    PSA_DONE();
1948}
1949/* END_CASE */
1950
1951/* BEGIN_CASE depends_on:MBEDTLS_SSL_PROTO_TLS1_3:MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA */
1952void ssl_tls13_record_protection(int ciphersuite,
1953                                 int endpoint,
1954                                 int ctr,
1955                                 int padding_used,
1956                                 data_t *server_write_key,
1957                                 data_t *server_write_iv,
1958                                 data_t *client_write_key,
1959                                 data_t *client_write_iv,
1960                                 data_t *plaintext,
1961                                 data_t *ciphertext)
1962{
1963    mbedtls_ssl_key_set keys;
1964    mbedtls_ssl_transform transform_send;
1965    mbedtls_ssl_transform transform_recv;
1966    mbedtls_record rec;
1967    unsigned char *buf = NULL;
1968    size_t buf_len;
1969    int other_endpoint;
1970
1971    USE_PSA_INIT();
1972
1973    TEST_ASSERT(endpoint == MBEDTLS_SSL_IS_CLIENT ||
1974                endpoint == MBEDTLS_SSL_IS_SERVER);
1975
1976    if (endpoint == MBEDTLS_SSL_IS_SERVER) {
1977        other_endpoint = MBEDTLS_SSL_IS_CLIENT;
1978    }
1979    if (endpoint == MBEDTLS_SSL_IS_CLIENT) {
1980        other_endpoint = MBEDTLS_SSL_IS_SERVER;
1981    }
1982
1983    TEST_ASSERT(server_write_key->len == client_write_key->len);
1984    TEST_ASSERT(server_write_iv->len  == client_write_iv->len);
1985
1986    memcpy(keys.client_write_key,
1987           client_write_key->x, client_write_key->len);
1988    memcpy(keys.client_write_iv,
1989           client_write_iv->x, client_write_iv->len);
1990    memcpy(keys.server_write_key,
1991           server_write_key->x, server_write_key->len);
1992    memcpy(keys.server_write_iv,
1993           server_write_iv->x, server_write_iv->len);
1994
1995    keys.key_len = server_write_key->len;
1996    keys.iv_len  = server_write_iv->len;
1997
1998    mbedtls_ssl_transform_init(&transform_recv);
1999    mbedtls_ssl_transform_init(&transform_send);
2000
2001    TEST_ASSERT(mbedtls_ssl_tls13_populate_transform(
2002                    &transform_send, endpoint,
2003                    ciphersuite, &keys, NULL) == 0);
2004    TEST_ASSERT(mbedtls_ssl_tls13_populate_transform(
2005                    &transform_recv, other_endpoint,
2006                    ciphersuite, &keys, NULL) == 0);
2007
2008    /* Make sure we have enough space in the buffer even if
2009     * we use more padding than the KAT. */
2010    buf_len = ciphertext->len + MBEDTLS_SSL_CID_TLS1_3_PADDING_GRANULARITY;
2011    ASSERT_ALLOC(buf, buf_len);
2012    rec.type   = MBEDTLS_SSL_MSG_APPLICATION_DATA;
2013
2014    /* TLS 1.3 uses the version identifier from TLS 1.2 on the wire. */
2015    mbedtls_ssl_write_version(rec.ver,
2016                              MBEDTLS_SSL_TRANSPORT_STREAM,
2017                              MBEDTLS_SSL_VERSION_TLS1_2);
2018
2019    /* Copy plaintext into record structure */
2020    rec.buf = buf;
2021    rec.buf_len = buf_len;
2022    rec.data_offset = 0;
2023    TEST_ASSERT(plaintext->len <= ciphertext->len);
2024    memcpy(rec.buf + rec.data_offset, plaintext->x, plaintext->len);
2025    rec.data_len = plaintext->len;
2026#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
2027    rec.cid_len = 0;
2028#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
2029
2030    memset(&rec.ctr[0], 0, 8);
2031    rec.ctr[7] = ctr;
2032
2033    TEST_ASSERT(mbedtls_ssl_encrypt_buf(NULL, &transform_send, &rec,
2034                                        NULL, NULL) == 0);
2035
2036    if (padding_used == MBEDTLS_SSL_CID_TLS1_3_PADDING_GRANULARITY) {
2037        ASSERT_COMPARE(rec.buf + rec.data_offset, rec.data_len,
2038                       ciphertext->x, ciphertext->len);
2039    }
2040
2041    TEST_ASSERT(mbedtls_ssl_decrypt_buf(NULL, &transform_recv, &rec) == 0);
2042    ASSERT_COMPARE(rec.buf + rec.data_offset, rec.data_len,
2043                   plaintext->x, plaintext->len);
2044
2045    mbedtls_free(buf);
2046    mbedtls_ssl_transform_free(&transform_send);
2047    mbedtls_ssl_transform_free(&transform_recv);
2048    USE_PSA_DONE();
2049}
2050/* END_CASE */
2051
2052/* BEGIN_CASE depends_on:MBEDTLS_SSL_PROTO_TLS1_3 */
2053void ssl_tls13_key_evolution(int hash_alg,
2054                             data_t *secret,
2055                             data_t *input,
2056                             data_t *expected)
2057{
2058    unsigned char secret_new[MBEDTLS_HASH_MAX_SIZE];
2059
2060    PSA_INIT();
2061
2062    TEST_ASSERT(mbedtls_ssl_tls13_evolve_secret(
2063                    (psa_algorithm_t) hash_alg,
2064                    secret->len ? secret->x : NULL,
2065                    input->len ? input->x : NULL, input->len,
2066                    secret_new) == 0);
2067
2068    ASSERT_COMPARE(secret_new, (size_t) expected->len,
2069                   expected->x, (size_t) expected->len);
2070
2071    PSA_DONE();
2072}
2073/* END_CASE */
2074
2075/* BEGIN_CASE depends_on:MBEDTLS_SSL_PROTO_TLS1_2 */
2076void ssl_tls_prf(int type, data_t *secret, data_t *random,
2077                 char *label, data_t *result_str, int exp_ret)
2078{
2079    unsigned char *output;
2080
2081    output = mbedtls_calloc(1, result_str->len);
2082    if (output == NULL) {
2083        goto exit;
2084    }
2085
2086    USE_PSA_INIT();
2087
2088    TEST_ASSERT(mbedtls_ssl_tls_prf(type, secret->x, secret->len,
2089                                    label, random->x, random->len,
2090                                    output, result_str->len) == exp_ret);
2091
2092    if (exp_ret == 0) {
2093        TEST_ASSERT(mbedtls_test_hexcmp(output, result_str->x,
2094                                        result_str->len, result_str->len) == 0);
2095    }
2096exit:
2097
2098    mbedtls_free(output);
2099    USE_PSA_DONE();
2100}
2101/* END_CASE */
2102
2103/* BEGIN_CASE */
2104void ssl_serialize_session_save_load(int ticket_len, char *crt_file,
2105                                     int endpoint_type, int tls_version)
2106{
2107    mbedtls_ssl_session original, restored;
2108    unsigned char *buf = NULL;
2109    size_t len;
2110
2111    /*
2112     * Test that a save-load pair is the identity
2113     */
2114
2115    mbedtls_ssl_session_init(&original);
2116    mbedtls_ssl_session_init(&restored);
2117
2118    /* Prepare a dummy session to work on */
2119    ((void) endpoint_type);
2120    ((void) tls_version);
2121#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
2122    if (tls_version == MBEDTLS_SSL_VERSION_TLS1_3) {
2123        TEST_ASSERT(mbedtls_test_ssl_tls13_populate_session(
2124                        &original, 0, endpoint_type) == 0);
2125    } else
2126#endif
2127    {
2128        TEST_ASSERT(mbedtls_test_ssl_tls12_populate_session(
2129                        &original, ticket_len, crt_file) == 0);
2130    }
2131
2132    /* Serialize it */
2133    TEST_ASSERT(mbedtls_ssl_session_save(&original, NULL, 0, &len)
2134                == MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL);
2135    TEST_ASSERT((buf = mbedtls_calloc(1, len)) != NULL);
2136    TEST_ASSERT(mbedtls_ssl_session_save(&original, buf, len, &len)
2137                == 0);
2138
2139    /* Restore session from serialized data */
2140    TEST_ASSERT(mbedtls_ssl_session_load(&restored, buf, len) == 0);
2141
2142    /*
2143     * Make sure both session structures are identical
2144     */
2145#if defined(MBEDTLS_HAVE_TIME)
2146    TEST_ASSERT(original.start == restored.start);
2147#endif
2148    TEST_ASSERT(original.tls_version == restored.tls_version);
2149    TEST_ASSERT(original.ciphersuite == restored.ciphersuite);
2150#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
2151    if (tls_version == MBEDTLS_SSL_VERSION_TLS1_2) {
2152        TEST_ASSERT(original.id_len == restored.id_len);
2153        TEST_ASSERT(memcmp(original.id,
2154                           restored.id, sizeof(original.id)) == 0);
2155        TEST_ASSERT(memcmp(original.master,
2156                           restored.master, sizeof(original.master)) == 0);
2157
2158#if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
2159#if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
2160        TEST_ASSERT((original.peer_cert == NULL) ==
2161                    (restored.peer_cert == NULL));
2162        if (original.peer_cert != NULL) {
2163            TEST_ASSERT(original.peer_cert->raw.len ==
2164                        restored.peer_cert->raw.len);
2165            TEST_ASSERT(memcmp(original.peer_cert->raw.p,
2166                               restored.peer_cert->raw.p,
2167                               original.peer_cert->raw.len) == 0);
2168        }
2169#else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2170        TEST_ASSERT(original.peer_cert_digest_type ==
2171                    restored.peer_cert_digest_type);
2172        TEST_ASSERT(original.peer_cert_digest_len ==
2173                    restored.peer_cert_digest_len);
2174        TEST_ASSERT((original.peer_cert_digest == NULL) ==
2175                    (restored.peer_cert_digest == NULL));
2176        if (original.peer_cert_digest != NULL) {
2177            TEST_ASSERT(memcmp(original.peer_cert_digest,
2178                               restored.peer_cert_digest,
2179                               original.peer_cert_digest_len) == 0);
2180        }
2181#endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2182#endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
2183        TEST_ASSERT(original.verify_result == restored.verify_result);
2184
2185#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
2186        TEST_ASSERT(original.mfl_code == restored.mfl_code);
2187#endif
2188
2189#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
2190        TEST_ASSERT(original.encrypt_then_mac == restored.encrypt_then_mac);
2191#endif
2192#if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
2193        TEST_ASSERT(original.ticket_len == restored.ticket_len);
2194        if (original.ticket_len != 0) {
2195            TEST_ASSERT(original.ticket != NULL);
2196            TEST_ASSERT(restored.ticket != NULL);
2197            TEST_ASSERT(memcmp(original.ticket,
2198                               restored.ticket, original.ticket_len) == 0);
2199        }
2200        TEST_ASSERT(original.ticket_lifetime == restored.ticket_lifetime);
2201#endif
2202    }
2203#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
2204
2205#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
2206    if (tls_version == MBEDTLS_SSL_VERSION_TLS1_3) {
2207        TEST_ASSERT(original.endpoint == restored.endpoint);
2208        TEST_ASSERT(original.ciphersuite == restored.ciphersuite);
2209        TEST_ASSERT(original.ticket_age_add == restored.ticket_age_add);
2210        TEST_ASSERT(original.ticket_flags == restored.ticket_flags);
2211        TEST_ASSERT(original.resumption_key_len == restored.resumption_key_len);
2212        if (original.resumption_key_len != 0) {
2213            TEST_ASSERT(original.resumption_key != NULL);
2214            TEST_ASSERT(restored.resumption_key != NULL);
2215            TEST_ASSERT(memcmp(original.resumption_key,
2216                               restored.resumption_key,
2217                               original.resumption_key_len) == 0);
2218        }
2219#if defined(MBEDTLS_HAVE_TIME) && defined(MBEDTLS_SSL_SRV_C)
2220        if (endpoint_type == MBEDTLS_SSL_IS_SERVER) {
2221            TEST_ASSERT(original.start == restored.start);
2222        }
2223#endif
2224#if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
2225        if (endpoint_type == MBEDTLS_SSL_IS_CLIENT) {
2226#if defined(MBEDTLS_HAVE_TIME)
2227            TEST_ASSERT(original.ticket_received == restored.ticket_received);
2228#endif
2229            TEST_ASSERT(original.ticket_lifetime == restored.ticket_lifetime);
2230            TEST_ASSERT(original.ticket_len == restored.ticket_len);
2231            if (original.ticket_len != 0) {
2232                TEST_ASSERT(original.ticket != NULL);
2233                TEST_ASSERT(restored.ticket != NULL);
2234                TEST_ASSERT(memcmp(original.ticket,
2235                                   restored.ticket,
2236                                   original.ticket_len) == 0);
2237            }
2238
2239        }
2240#endif
2241    }
2242#endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
2243
2244exit:
2245    mbedtls_ssl_session_free(&original);
2246    mbedtls_ssl_session_free(&restored);
2247    mbedtls_free(buf);
2248}
2249/* END_CASE */
2250
2251/* BEGIN_CASE */
2252void ssl_serialize_session_load_save(int ticket_len, char *crt_file,
2253                                     int endpoint_type, int tls_version)
2254{
2255    mbedtls_ssl_session session;
2256    unsigned char *buf1 = NULL, *buf2 = NULL;
2257    size_t len0, len1, len2;
2258
2259    /*
2260     * Test that a load-save pair is the identity
2261     */
2262
2263    mbedtls_ssl_session_init(&session);
2264
2265    /* Prepare a dummy session to work on */
2266    ((void) endpoint_type);
2267    ((void) tls_version);
2268#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
2269    if (tls_version == MBEDTLS_SSL_VERSION_TLS1_3) {
2270        TEST_ASSERT(mbedtls_test_ssl_tls13_populate_session(
2271                        &session, 0, endpoint_type) == 0);
2272    } else
2273#endif
2274    {
2275        TEST_ASSERT(mbedtls_test_ssl_tls12_populate_session(
2276                        &session, ticket_len, crt_file) == 0);
2277    }
2278
2279    /* Get desired buffer size for serializing */
2280    TEST_ASSERT(mbedtls_ssl_session_save(&session, NULL, 0, &len0)
2281                == MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL);
2282
2283    /* Allocate first buffer */
2284    buf1 = mbedtls_calloc(1, len0);
2285    TEST_ASSERT(buf1 != NULL);
2286
2287    /* Serialize to buffer and free live session */
2288    TEST_ASSERT(mbedtls_ssl_session_save(&session, buf1, len0, &len1)
2289                == 0);
2290    TEST_ASSERT(len0 == len1);
2291    mbedtls_ssl_session_free(&session);
2292
2293    /* Restore session from serialized data */
2294    TEST_ASSERT(mbedtls_ssl_session_load(&session, buf1, len1) == 0);
2295
2296    /* Allocate second buffer and serialize to it */
2297    buf2 = mbedtls_calloc(1, len0);
2298    TEST_ASSERT(buf2 != NULL);
2299    TEST_ASSERT(mbedtls_ssl_session_save(&session, buf2, len0, &len2)
2300                == 0);
2301
2302    /* Make sure both serialized versions are identical */
2303    TEST_ASSERT(len1 == len2);
2304    TEST_ASSERT(memcmp(buf1, buf2, len1) == 0);
2305
2306exit:
2307    mbedtls_ssl_session_free(&session);
2308    mbedtls_free(buf1);
2309    mbedtls_free(buf2);
2310}
2311/* END_CASE */
2312
2313/* BEGIN_CASE */
2314void ssl_serialize_session_save_buf_size(int ticket_len, char *crt_file,
2315                                         int endpoint_type, int tls_version)
2316{
2317    mbedtls_ssl_session session;
2318    unsigned char *buf = NULL;
2319    size_t good_len, bad_len, test_len;
2320
2321    /*
2322     * Test that session_save() fails cleanly on small buffers
2323     */
2324
2325    mbedtls_ssl_session_init(&session);
2326
2327    /* Prepare dummy session and get serialized size */
2328    ((void) endpoint_type);
2329    ((void) tls_version);
2330#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
2331    if (tls_version == MBEDTLS_SSL_VERSION_TLS1_3) {
2332        TEST_ASSERT(mbedtls_test_ssl_tls13_populate_session(
2333                        &session, 0, endpoint_type) == 0);
2334    } else
2335#endif
2336    {
2337        TEST_ASSERT(mbedtls_test_ssl_tls12_populate_session(
2338                        &session, ticket_len, crt_file) == 0);
2339    }
2340    TEST_ASSERT(mbedtls_ssl_session_save(&session, NULL, 0, &good_len)
2341                == MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL);
2342
2343    /* Try all possible bad lengths */
2344    for (bad_len = 1; bad_len < good_len; bad_len++) {
2345        /* Allocate exact size so that asan/valgrind can detect any overwrite */
2346        mbedtls_free(buf);
2347        TEST_ASSERT((buf = mbedtls_calloc(1, bad_len)) != NULL);
2348        TEST_ASSERT(mbedtls_ssl_session_save(&session, buf, bad_len,
2349                                             &test_len)
2350                    == MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL);
2351        TEST_ASSERT(test_len == good_len);
2352    }
2353
2354exit:
2355    mbedtls_ssl_session_free(&session);
2356    mbedtls_free(buf);
2357}
2358/* END_CASE */
2359
2360/* BEGIN_CASE */
2361void ssl_serialize_session_load_buf_size(int ticket_len, char *crt_file,
2362                                         int endpoint_type, int tls_version)
2363{
2364    mbedtls_ssl_session session;
2365    unsigned char *good_buf = NULL, *bad_buf = NULL;
2366    size_t good_len, bad_len;
2367
2368    /*
2369     * Test that session_load() fails cleanly on small buffers
2370     */
2371
2372    mbedtls_ssl_session_init(&session);
2373
2374    /* Prepare serialized session data */
2375    ((void) endpoint_type);
2376    ((void) tls_version);
2377#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
2378    if (tls_version == MBEDTLS_SSL_VERSION_TLS1_3) {
2379        TEST_ASSERT(mbedtls_test_ssl_tls13_populate_session(
2380                        &session, 0, endpoint_type) == 0);
2381    } else
2382#endif
2383    {
2384        TEST_ASSERT(mbedtls_test_ssl_tls12_populate_session(
2385                        &session, ticket_len, crt_file) == 0);
2386    }
2387    TEST_ASSERT(mbedtls_ssl_session_save(&session, NULL, 0, &good_len)
2388                == MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL);
2389    TEST_ASSERT((good_buf = mbedtls_calloc(1, good_len)) != NULL);
2390    TEST_ASSERT(mbedtls_ssl_session_save(&session, good_buf, good_len,
2391                                         &good_len) == 0);
2392    mbedtls_ssl_session_free(&session);
2393
2394    /* Try all possible bad lengths */
2395    for (bad_len = 0; bad_len < good_len; bad_len++) {
2396        /* Allocate exact size so that asan/valgrind can detect any overread */
2397        mbedtls_free(bad_buf);
2398        bad_buf = mbedtls_calloc(1, bad_len ? bad_len : 1);
2399        TEST_ASSERT(bad_buf != NULL);
2400        memcpy(bad_buf, good_buf, bad_len);
2401
2402        TEST_ASSERT(mbedtls_ssl_session_load(&session, bad_buf, bad_len)
2403                    == MBEDTLS_ERR_SSL_BAD_INPUT_DATA);
2404    }
2405
2406exit:
2407    mbedtls_ssl_session_free(&session);
2408    mbedtls_free(good_buf);
2409    mbedtls_free(bad_buf);
2410}
2411/* END_CASE */
2412
2413/* BEGIN_CASE */
2414void ssl_session_serialize_version_check(int corrupt_major,
2415                                         int corrupt_minor,
2416                                         int corrupt_patch,
2417                                         int corrupt_config,
2418                                         int endpoint_type,
2419                                         int tls_version)
2420{
2421    unsigned char serialized_session[2048];
2422    size_t serialized_session_len;
2423    unsigned cur_byte;
2424    mbedtls_ssl_session session;
2425    uint8_t should_corrupt_byte[] = { corrupt_major  == 1,
2426                                      corrupt_minor  == 1,
2427                                      corrupt_patch  == 1,
2428                                      corrupt_config == 1,
2429                                      corrupt_config == 1 };
2430
2431    mbedtls_ssl_session_init(&session);
2432    ((void) endpoint_type);
2433    ((void) tls_version);
2434#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
2435    if (tls_version == MBEDTLS_SSL_VERSION_TLS1_3) {
2436        TEST_ASSERT(mbedtls_test_ssl_tls13_populate_session(
2437                        &session, 0, endpoint_type) == 0);
2438    } else
2439#endif
2440    TEST_ASSERT(mbedtls_test_ssl_tls12_populate_session(
2441                    &session, 0, NULL) == 0);
2442
2443
2444    /* Infer length of serialized session. */
2445    TEST_ASSERT(mbedtls_ssl_session_save(&session,
2446                                         serialized_session,
2447                                         sizeof(serialized_session),
2448                                         &serialized_session_len) == 0);
2449
2450    mbedtls_ssl_session_free(&session);
2451
2452    /* Without any modification, we should be able to successfully
2453     * de-serialize the session - double-check that. */
2454    TEST_ASSERT(mbedtls_ssl_session_load(&session,
2455                                         serialized_session,
2456                                         serialized_session_len) == 0);
2457    mbedtls_ssl_session_free(&session);
2458
2459    /* Go through the bytes in the serialized session header and
2460     * corrupt them bit-by-bit. */
2461    for (cur_byte = 0; cur_byte < sizeof(should_corrupt_byte); cur_byte++) {
2462        int cur_bit;
2463        unsigned char * const byte = &serialized_session[cur_byte];
2464
2465        if (should_corrupt_byte[cur_byte] == 0) {
2466            continue;
2467        }
2468
2469        for (cur_bit = 0; cur_bit < CHAR_BIT; cur_bit++) {
2470            unsigned char const corrupted_bit = 0x1u << cur_bit;
2471            /* Modify a single bit in the serialized session. */
2472            *byte ^= corrupted_bit;
2473
2474            /* Attempt to deserialize */
2475            TEST_ASSERT(mbedtls_ssl_session_load(&session,
2476                                                 serialized_session,
2477                                                 serialized_session_len) ==
2478                        MBEDTLS_ERR_SSL_VERSION_MISMATCH);
2479
2480            /* Undo the change */
2481            *byte ^= corrupted_bit;
2482        }
2483    }
2484
2485}
2486/* END_CASE */
2487
2488/* BEGIN_CASE depends_on:MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED:MBEDTLS_RSA_C:MBEDTLS_ECP_DP_SECP384R1_ENABLED:!MBEDTLS_SSL_PROTO_TLS1_3:MBEDTLS_PKCS1_V15:MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA */
2489void mbedtls_endpoint_sanity(int endpoint_type)
2490{
2491    enum { BUFFSIZE = 1024 };
2492    mbedtls_test_ssl_endpoint ep;
2493    int ret = -1;
2494    mbedtls_test_handshake_test_options options;
2495    mbedtls_test_init_handshake_options(&options);
2496    options.pk_alg = MBEDTLS_PK_RSA;
2497
2498    ret = mbedtls_test_ssl_endpoint_init(NULL, endpoint_type, &options,
2499                                         NULL, NULL, NULL, NULL);
2500    TEST_ASSERT(MBEDTLS_ERR_SSL_BAD_INPUT_DATA == ret);
2501
2502    ret = mbedtls_test_ssl_endpoint_certificate_init(NULL, options.pk_alg,
2503                                                     0, 0, 0);
2504    TEST_ASSERT(MBEDTLS_ERR_SSL_BAD_INPUT_DATA == ret);
2505
2506    ret = mbedtls_test_ssl_endpoint_init(&ep, endpoint_type, &options,
2507                                         NULL, NULL, NULL, NULL);
2508    TEST_ASSERT(ret == 0);
2509
2510exit:
2511    mbedtls_test_ssl_endpoint_free(&ep, NULL);
2512    mbedtls_test_free_handshake_options(&options);
2513}
2514/* END_CASE */
2515
2516/* BEGIN_CASE depends_on:MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED:MBEDTLS_RSA_C:MBEDTLS_ECP_DP_SECP384R1_ENABLED:MBEDTLS_PKCS1_V15:MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA:MBEDTLS_ECP_C */
2517void move_handshake_to_state(int endpoint_type, int state, int need_pass)
2518{
2519    enum { BUFFSIZE = 1024 };
2520    mbedtls_test_ssl_endpoint base_ep, second_ep;
2521    int ret = -1;
2522    mbedtls_test_handshake_test_options options;
2523    mbedtls_test_init_handshake_options(&options);
2524    options.pk_alg = MBEDTLS_PK_RSA;
2525
2526    USE_PSA_INIT();
2527    mbedtls_platform_zeroize(&base_ep, sizeof(base_ep));
2528    mbedtls_platform_zeroize(&second_ep, sizeof(second_ep));
2529
2530    ret = mbedtls_test_ssl_endpoint_init(&base_ep, endpoint_type, &options,
2531                                         NULL, NULL, NULL, NULL);
2532    TEST_ASSERT(ret == 0);
2533
2534    ret = mbedtls_test_ssl_endpoint_init(
2535        &second_ep,
2536        (endpoint_type == MBEDTLS_SSL_IS_SERVER) ?
2537        MBEDTLS_SSL_IS_CLIENT : MBEDTLS_SSL_IS_SERVER,
2538        &options, NULL, NULL, NULL, NULL);
2539
2540    TEST_ASSERT(ret == 0);
2541
2542    ret = mbedtls_test_mock_socket_connect(&(base_ep.socket),
2543                                           &(second_ep.socket),
2544                                           BUFFSIZE);
2545    TEST_ASSERT(ret == 0);
2546
2547    ret = mbedtls_test_move_handshake_to_state(&(base_ep.ssl),
2548                                               &(second_ep.ssl),
2549                                               state);
2550    if (need_pass) {
2551        TEST_ASSERT(ret == 0 ||
2552                    ret == MBEDTLS_ERR_SSL_WANT_READ ||
2553                    ret == MBEDTLS_ERR_SSL_WANT_WRITE);
2554        TEST_ASSERT(base_ep.ssl.state == state);
2555    } else {
2556        TEST_ASSERT(ret != 0 &&
2557                    ret != MBEDTLS_ERR_SSL_WANT_READ &&
2558                    ret != MBEDTLS_ERR_SSL_WANT_WRITE);
2559        TEST_ASSERT(base_ep.ssl.state != state);
2560    }
2561
2562exit:
2563    mbedtls_test_free_handshake_options(&options);
2564    mbedtls_test_ssl_endpoint_free(&base_ep, NULL);
2565    mbedtls_test_ssl_endpoint_free(&second_ep, NULL);
2566    USE_PSA_DONE();
2567}
2568/* END_CASE */
2569
2570/* BEGIN_CASE depends_on:MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED:MBEDTLS_PKCS1_V15:MBEDTLS_RSA_C:MBEDTLS_ECP_DP_SECP384R1_ENABLED:MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA:MBEDTLS_ECP_C:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY */
2571void handshake_version(int dtls, int client_min_version, int client_max_version,
2572                       int server_min_version, int server_max_version,
2573                       int expected_negotiated_version)
2574{
2575    mbedtls_test_handshake_test_options options;
2576    mbedtls_test_init_handshake_options(&options);
2577
2578    options.client_min_version = client_min_version;
2579    options.client_max_version = client_max_version;
2580    options.server_min_version = server_min_version;
2581    options.server_max_version = server_max_version;
2582    options.expected_negotiated_version = expected_negotiated_version;
2583
2584    options.dtls = dtls;
2585    mbedtls_test_ssl_perform_handshake(&options);
2586
2587    /* The goto below is used to avoid an "unused label" warning.*/
2588    goto exit;
2589
2590exit:
2591    mbedtls_test_free_handshake_options(&options);
2592}
2593/* END_CASE */
2594
2595/* BEGIN_CASE depends_on:MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED:MBEDTLS_PKCS1_V15:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA */
2596void handshake_psk_cipher(char *cipher, int pk_alg, data_t *psk_str, int dtls)
2597{
2598    mbedtls_test_handshake_test_options options;
2599    mbedtls_test_init_handshake_options(&options);
2600
2601    options.cipher = cipher;
2602    options.dtls = dtls;
2603    options.psk_str = psk_str;
2604    options.pk_alg = pk_alg;
2605
2606    mbedtls_test_ssl_perform_handshake(&options);
2607
2608    /* The goto below is used to avoid an "unused label" warning.*/
2609    goto exit;
2610
2611exit:
2612    mbedtls_test_free_handshake_options(&options);
2613}
2614/* END_CASE */
2615
2616/* BEGIN_CASE depends_on:MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED:MBEDTLS_PKCS1_V15:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA */
2617void handshake_cipher(char *cipher, int pk_alg, int dtls)
2618{
2619    test_handshake_psk_cipher(cipher, pk_alg, NULL, dtls);
2620
2621    /* The goto below is used to avoid an "unused label" warning.*/
2622    goto exit;
2623}
2624/* END_CASE */
2625
2626/* BEGIN_CASE depends_on:MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED:MBEDTLS_PKCS1_V15:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA */
2627void handshake_ciphersuite_select(char *cipher, int pk_alg, data_t *psk_str,
2628                                  int psa_alg, int psa_alg2, int psa_usage,
2629                                  int expected_handshake_result,
2630                                  int expected_ciphersuite)
2631{
2632    mbedtls_test_handshake_test_options options;
2633    mbedtls_test_init_handshake_options(&options);
2634
2635    options.cipher = cipher;
2636    options.psk_str = psk_str;
2637    options.pk_alg = pk_alg;
2638    options.opaque_alg = psa_alg;
2639    options.opaque_alg2 = psa_alg2;
2640    options.opaque_usage = psa_usage;
2641    options.expected_handshake_result = expected_handshake_result;
2642    options.expected_ciphersuite = expected_ciphersuite;
2643    mbedtls_test_ssl_perform_handshake(&options);
2644
2645    /* The goto below is used to avoid an "unused label" warning.*/
2646    goto exit;
2647
2648exit:
2649    mbedtls_test_free_handshake_options(&options);
2650}
2651/* END_CASE */
2652
2653/* BEGIN_CASE depends_on:MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED:MBEDTLS_PKCS1_V15:MBEDTLS_RSA_C:MBEDTLS_ECP_DP_SECP384R1_ENABLED:MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA */
2654void app_data(int mfl, int cli_msg_len, int srv_msg_len,
2655              int expected_cli_fragments,
2656              int expected_srv_fragments, int dtls)
2657{
2658    mbedtls_test_handshake_test_options options;
2659    mbedtls_test_init_handshake_options(&options);
2660
2661    options.mfl = mfl;
2662    options.cli_msg_len = cli_msg_len;
2663    options.srv_msg_len = srv_msg_len;
2664    options.expected_cli_fragments = expected_cli_fragments;
2665    options.expected_srv_fragments = expected_srv_fragments;
2666    options.dtls = dtls;
2667#if !defined(MBEDTLS_SSL_PROTO_TLS1_2)
2668    options.expected_negotiated_version = MBEDTLS_SSL_VERSION_TLS1_3;
2669#endif
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_DP_SECP384R1_ENABLED:MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA:MBEDTLS_ECP_C:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY */
2682void app_data_tls(int mfl, int cli_msg_len, int srv_msg_len,
2683                  int expected_cli_fragments,
2684                  int expected_srv_fragments)
2685{
2686    test_app_data(mfl, cli_msg_len, srv_msg_len, expected_cli_fragments,
2687                  expected_srv_fragments, 0);
2688    /* The goto below is used to avoid an "unused label" warning.*/
2689    goto exit;
2690}
2691/* END_CASE */
2692
2693/* 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_DP_SECP384R1_ENABLED:MBEDTLS_SSL_PROTO_DTLS:MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY */
2694void app_data_dtls(int mfl, int cli_msg_len, int srv_msg_len,
2695                   int expected_cli_fragments,
2696                   int expected_srv_fragments)
2697{
2698    test_app_data(mfl, cli_msg_len, srv_msg_len, expected_cli_fragments,
2699                  expected_srv_fragments, 1);
2700    /* The goto below is used to avoid an "unused label" warning.*/
2701    goto exit;
2702}
2703/* END_CASE */
2704
2705/* 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_DP_SECP384R1_ENABLED:MBEDTLS_SSL_PROTO_DTLS:MBEDTLS_SSL_RENEGOTIATION:MBEDTLS_SSL_CONTEXT_SERIALIZATION:MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY */
2706void handshake_serialization()
2707{
2708    mbedtls_test_handshake_test_options options;
2709    mbedtls_test_init_handshake_options(&options);
2710
2711    options.serialize = 1;
2712    options.dtls = 1;
2713    mbedtls_test_ssl_perform_handshake(&options);
2714    /* The goto below is used to avoid an "unused label" warning.*/
2715    goto exit;
2716exit:
2717    mbedtls_test_free_handshake_options(&options);
2718}
2719/* END_CASE */
2720
2721/* BEGIN_CASE depends_on:MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED:!MBEDTLS_SSL_PROTO_TLS1_3:MBEDTLS_PKCS1_V15:MBEDTLS_RSA_C:MBEDTLS_ECP_DP_SECP384R1_ENABLED:MBEDTLS_DEBUG_C:MBEDTLS_SSL_MAX_FRAGMENT_LENGTH:MBEDTLS_CIPHER_MODE_CBC:MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA:MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED */
2722void handshake_fragmentation(int mfl,
2723                             int expected_srv_hs_fragmentation,
2724                             int expected_cli_hs_fragmentation)
2725{
2726    mbedtls_test_handshake_test_options options;
2727    mbedtls_test_ssl_log_pattern srv_pattern, cli_pattern;
2728
2729    srv_pattern.pattern = cli_pattern.pattern = "found fragmented DTLS handshake";
2730    srv_pattern.counter = 0;
2731    cli_pattern.counter = 0;
2732
2733    mbedtls_test_init_handshake_options(&options);
2734    options.dtls = 1;
2735    options.mfl = mfl;
2736    /* Set cipher to one using CBC so that record splitting can be tested */
2737    options.cipher = "TLS-DHE-RSA-WITH-AES-256-CBC-SHA256";
2738    options.srv_auth_mode = MBEDTLS_SSL_VERIFY_REQUIRED;
2739    options.srv_log_obj = &srv_pattern;
2740    options.cli_log_obj = &cli_pattern;
2741    options.srv_log_fun = mbedtls_test_ssl_log_analyzer;
2742    options.cli_log_fun = mbedtls_test_ssl_log_analyzer;
2743
2744    mbedtls_test_ssl_perform_handshake(&options);
2745
2746    /* Test if the server received a fragmented handshake */
2747    if (expected_srv_hs_fragmentation) {
2748        TEST_ASSERT(srv_pattern.counter >= 1);
2749    }
2750    /* Test if the client received a fragmented handshake */
2751    if (expected_cli_hs_fragmentation) {
2752        TEST_ASSERT(cli_pattern.counter >= 1);
2753    }
2754
2755exit:
2756    mbedtls_test_free_handshake_options(&options);
2757}
2758/* END_CASE */
2759
2760/* 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_DP_SECP384R1_ENABLED:MBEDTLS_SSL_PROTO_DTLS:MBEDTLS_SSL_RENEGOTIATION:MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY */
2761void renegotiation(int legacy_renegotiation)
2762{
2763    mbedtls_test_handshake_test_options options;
2764    mbedtls_test_init_handshake_options(&options);
2765
2766    options.renegotiate = 1;
2767    options.legacy_renegotiation = legacy_renegotiation;
2768    options.dtls = 1;
2769
2770    mbedtls_test_ssl_perform_handshake(&options);
2771
2772    /* The goto below is used to avoid an "unused label" warning.*/
2773    goto exit;
2774exit:
2775    mbedtls_test_free_handshake_options(&options);
2776}
2777/* END_CASE */
2778
2779/* 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_PROTO_TLS1_2:MBEDTLS_RSA_C:MBEDTLS_ECP_DP_SECP384R1_ENABLED:MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA */
2780void resize_buffers(int mfl, int renegotiation, int legacy_renegotiation,
2781                    int serialize, int dtls, char *cipher)
2782{
2783    mbedtls_test_handshake_test_options options;
2784    mbedtls_test_init_handshake_options(&options);
2785
2786    options.mfl = mfl;
2787    options.cipher = cipher;
2788    options.renegotiate = renegotiation;
2789    options.legacy_renegotiation = legacy_renegotiation;
2790    options.serialize = serialize;
2791    options.dtls = dtls;
2792    options.resize_buffers = 1;
2793
2794    mbedtls_test_ssl_perform_handshake(&options);
2795
2796    /* The goto below is used to avoid an "unused label" warning.*/
2797    goto exit;
2798exit:
2799    mbedtls_test_free_handshake_options(&options);
2800}
2801/* END_CASE */
2802
2803/* 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_DP_SECP384R1_ENABLED:MBEDTLS_SSL_PROTO_DTLS:MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY */
2804void resize_buffers_serialize_mfl(int mfl)
2805{
2806    test_resize_buffers(mfl, 0, MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION, 1, 1,
2807                        (char *) "");
2808
2809    /* The goto below is used to avoid an "unused label" warning.*/
2810    goto exit;
2811}
2812/* END_CASE */
2813
2814/* 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_DP_SECP384R1_ENABLED:MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY */
2815void resize_buffers_renegotiate_mfl(int mfl, int legacy_renegotiation,
2816                                    char *cipher)
2817{
2818    test_resize_buffers(mfl, 1, legacy_renegotiation, 0, 1, cipher);
2819
2820    /* The goto below is used to avoid an "unused label" warning.*/
2821    goto exit;
2822}
2823/* END_CASE */
2824
2825/* BEGIN_CASE depends_on:MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED */
2826void test_multiple_psks()
2827{
2828    unsigned char psk0[10] = { 0 };
2829    unsigned char psk0_identity[] = { 'f', 'o', 'o' };
2830
2831    unsigned char psk1[10] = { 0 };
2832    unsigned char psk1_identity[] = { 'b', 'a', 'r' };
2833
2834    mbedtls_ssl_config conf;
2835
2836    USE_PSA_INIT();
2837    mbedtls_ssl_config_init(&conf);
2838
2839    TEST_ASSERT(mbedtls_ssl_conf_psk(&conf,
2840                                     psk0, sizeof(psk0),
2841                                     psk0_identity, sizeof(psk0_identity)) == 0);
2842    TEST_ASSERT(mbedtls_ssl_conf_psk(&conf,
2843                                     psk1, sizeof(psk1),
2844                                     psk1_identity, sizeof(psk1_identity)) ==
2845                MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE);
2846
2847exit:
2848
2849    mbedtls_ssl_config_free(&conf);
2850
2851    USE_PSA_DONE();
2852}
2853/* END_CASE */
2854
2855/* BEGIN_CASE depends_on:MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED:MBEDTLS_USE_PSA_CRYPTO */
2856void test_multiple_psks_opaque(int mode)
2857{
2858    /*
2859     * Mode 0: Raw PSK, then opaque PSK
2860     * Mode 1: Opaque PSK, then raw PSK
2861     * Mode 2: 2x opaque PSK
2862     */
2863
2864    unsigned char psk0_raw[10] = { 0 };
2865    unsigned char psk0_raw_identity[] = { 'f', 'o', 'o' };
2866
2867    mbedtls_svc_key_id_t psk0_opaque = mbedtls_svc_key_id_make(0x1, (psa_key_id_t) 1);
2868
2869    unsigned char psk0_opaque_identity[] = { 'f', 'o', 'o' };
2870
2871    unsigned char psk1_raw[10] = { 0 };
2872    unsigned char psk1_raw_identity[] = { 'b', 'a', 'r' };
2873
2874    mbedtls_svc_key_id_t psk1_opaque = mbedtls_svc_key_id_make(0x1, (psa_key_id_t) 2);
2875
2876    unsigned char psk1_opaque_identity[] = { 'b', 'a', 'r' };
2877
2878    mbedtls_ssl_config conf;
2879
2880    USE_PSA_INIT();
2881    mbedtls_ssl_config_init(&conf);
2882
2883    switch (mode) {
2884        case 0:
2885
2886            TEST_ASSERT(mbedtls_ssl_conf_psk(&conf,
2887                                             psk0_raw, sizeof(psk0_raw),
2888                                             psk0_raw_identity, sizeof(psk0_raw_identity))
2889                        == 0);
2890            TEST_ASSERT(mbedtls_ssl_conf_psk_opaque(&conf,
2891                                                    psk1_opaque,
2892                                                    psk1_opaque_identity,
2893                                                    sizeof(psk1_opaque_identity))
2894                        == MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE);
2895            break;
2896
2897        case 1:
2898
2899            TEST_ASSERT(mbedtls_ssl_conf_psk_opaque(&conf,
2900                                                    psk0_opaque,
2901                                                    psk0_opaque_identity,
2902                                                    sizeof(psk0_opaque_identity))
2903                        == 0);
2904            TEST_ASSERT(mbedtls_ssl_conf_psk(&conf,
2905                                             psk1_raw, sizeof(psk1_raw),
2906                                             psk1_raw_identity, sizeof(psk1_raw_identity))
2907                        == MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE);
2908
2909            break;
2910
2911        case 2:
2912
2913            TEST_ASSERT(mbedtls_ssl_conf_psk_opaque(&conf,
2914                                                    psk0_opaque,
2915                                                    psk0_opaque_identity,
2916                                                    sizeof(psk0_opaque_identity))
2917                        == 0);
2918            TEST_ASSERT(mbedtls_ssl_conf_psk_opaque(&conf,
2919                                                    psk1_opaque,
2920                                                    psk1_opaque_identity,
2921                                                    sizeof(psk1_opaque_identity))
2922                        == MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE);
2923
2924            break;
2925
2926        default:
2927            TEST_ASSERT(0);
2928            break;
2929    }
2930
2931exit:
2932
2933    mbedtls_ssl_config_free(&conf);
2934    USE_PSA_DONE();
2935
2936}
2937/* END_CASE */
2938
2939/* BEGIN_CASE */
2940void conf_version(int endpoint, int transport,
2941                  int min_tls_version, int max_tls_version,
2942                  int expected_ssl_setup_result)
2943{
2944    mbedtls_ssl_config conf;
2945    mbedtls_ssl_context ssl;
2946
2947    mbedtls_ssl_config_init(&conf);
2948    mbedtls_ssl_init(&ssl);
2949
2950    mbedtls_ssl_conf_endpoint(&conf, endpoint);
2951    mbedtls_ssl_conf_transport(&conf, transport);
2952    mbedtls_ssl_conf_min_tls_version(&conf, min_tls_version);
2953    mbedtls_ssl_conf_max_tls_version(&conf, max_tls_version);
2954
2955    TEST_ASSERT(mbedtls_ssl_setup(&ssl, &conf) == expected_ssl_setup_result);
2956
2957    mbedtls_ssl_free(&ssl);
2958    mbedtls_ssl_config_free(&conf);
2959}
2960/* END_CASE */
2961
2962/* BEGIN_CASE depends_on:MBEDTLS_ECP_C:!MBEDTLS_DEPRECATED_REMOVED:!MBEDTLS_DEPRECATED_WARNING:MBEDTLS_ECP_DP_SECP192R1_ENABLED:MBEDTLS_ECP_DP_SECP224R1_ENABLED:MBEDTLS_ECP_DP_SECP256R1_ENABLED */
2963void conf_curve()
2964{
2965
2966    mbedtls_ecp_group_id curve_list[] = { MBEDTLS_ECP_DP_SECP192R1,
2967                                          MBEDTLS_ECP_DP_SECP224R1,
2968                                          MBEDTLS_ECP_DP_SECP256R1,
2969                                          MBEDTLS_ECP_DP_NONE };
2970    uint16_t iana_tls_group_list[] = { MBEDTLS_SSL_IANA_TLS_GROUP_SECP192R1,
2971                                       MBEDTLS_SSL_IANA_TLS_GROUP_SECP224R1,
2972                                       MBEDTLS_SSL_IANA_TLS_GROUP_SECP256R1,
2973                                       MBEDTLS_SSL_IANA_TLS_GROUP_NONE };
2974
2975    mbedtls_ssl_config conf;
2976    mbedtls_ssl_config_init(&conf);
2977#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
2978    mbedtls_ssl_conf_max_tls_version(&conf, MBEDTLS_SSL_VERSION_TLS1_2);
2979    mbedtls_ssl_conf_min_tls_version(&conf, MBEDTLS_SSL_VERSION_TLS1_2);
2980#else
2981    mbedtls_ssl_conf_max_tls_version(&conf, MBEDTLS_SSL_VERSION_TLS1_3);
2982    mbedtls_ssl_conf_min_tls_version(&conf, MBEDTLS_SSL_VERSION_TLS1_3);
2983#endif
2984    mbedtls_ssl_conf_curves(&conf, curve_list);
2985
2986    mbedtls_ssl_context ssl;
2987    mbedtls_ssl_init(&ssl);
2988    TEST_ASSERT(mbedtls_ssl_setup(&ssl, &conf) == 0);
2989
2990    TEST_ASSERT(ssl.handshake != NULL && ssl.handshake->group_list != NULL);
2991    TEST_ASSERT(ssl.conf != NULL && ssl.conf->group_list == NULL);
2992
2993    TEST_EQUAL(ssl.handshake->
2994               group_list[ARRAY_LENGTH(iana_tls_group_list) - 1],
2995               MBEDTLS_SSL_IANA_TLS_GROUP_NONE);
2996
2997    for (size_t i = 0; i < ARRAY_LENGTH(iana_tls_group_list); i++) {
2998        TEST_EQUAL(iana_tls_group_list[i], ssl.handshake->group_list[i]);
2999    }
3000
3001    mbedtls_ssl_free(&ssl);
3002    mbedtls_ssl_config_free(&conf);
3003}
3004/* END_CASE */
3005
3006/* BEGIN_CASE depends_on:MBEDTLS_DEPRECATED_REMOVED */
3007void conf_group()
3008{
3009    uint16_t iana_tls_group_list[] = { MBEDTLS_SSL_IANA_TLS_GROUP_SECP192R1,
3010                                       MBEDTLS_SSL_IANA_TLS_GROUP_SECP224R1,
3011                                       MBEDTLS_SSL_IANA_TLS_GROUP_SECP256R1,
3012                                       MBEDTLS_SSL_IANA_TLS_GROUP_NONE };
3013
3014    mbedtls_ssl_config conf;
3015    mbedtls_ssl_config_init(&conf);
3016
3017    mbedtls_ssl_conf_max_tls_version(&conf, MBEDTLS_SSL_VERSION_TLS1_2);
3018    mbedtls_ssl_conf_min_tls_version(&conf, MBEDTLS_SSL_VERSION_TLS1_2);
3019
3020    mbedtls_ssl_conf_groups(&conf, iana_tls_group_list);
3021
3022    mbedtls_ssl_context ssl;
3023    mbedtls_ssl_init(&ssl);
3024    TEST_ASSERT(mbedtls_ssl_setup(&ssl, &conf) == 0);
3025
3026    TEST_ASSERT(ssl.conf != NULL && ssl.conf->group_list != NULL);
3027
3028    TEST_EQUAL(ssl.conf->
3029               group_list[ARRAY_LENGTH(iana_tls_group_list) - 1],
3030               MBEDTLS_SSL_IANA_TLS_GROUP_NONE);
3031
3032    for (size_t i = 0; i < ARRAY_LENGTH(iana_tls_group_list); i++) {
3033        TEST_EQUAL(iana_tls_group_list[i], ssl.conf->group_list[i]);
3034    }
3035
3036    mbedtls_ssl_free(&ssl);
3037    mbedtls_ssl_config_free(&conf);
3038}
3039/* END_CASE */
3040
3041/* 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_DP_SECP384R1_ENABLED:MBEDTLS_PKCS1_V15:MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA */
3042void force_bad_session_id_len()
3043{
3044    enum { BUFFSIZE = 1024 };
3045    mbedtls_test_handshake_test_options options;
3046    mbedtls_test_ssl_endpoint client, server;
3047    mbedtls_test_ssl_log_pattern srv_pattern, cli_pattern;
3048    mbedtls_test_message_socket_context server_context, client_context;
3049
3050    srv_pattern.pattern = cli_pattern.pattern = "cache did not store session";
3051    srv_pattern.counter = 0;
3052    mbedtls_test_init_handshake_options(&options);
3053
3054    options.srv_log_obj = &srv_pattern;
3055    options.srv_log_fun = mbedtls_test_ssl_log_analyzer;
3056
3057    USE_PSA_INIT();
3058    mbedtls_platform_zeroize(&client, sizeof(client));
3059    mbedtls_platform_zeroize(&server, sizeof(server));
3060
3061    mbedtls_test_message_socket_init(&server_context);
3062    mbedtls_test_message_socket_init(&client_context);
3063
3064    TEST_ASSERT(mbedtls_test_ssl_endpoint_init(&client, MBEDTLS_SSL_IS_CLIENT,
3065                                               &options, NULL, NULL,
3066                                               NULL, NULL) == 0);
3067
3068    TEST_ASSERT(mbedtls_test_ssl_endpoint_init(&server, MBEDTLS_SSL_IS_SERVER,
3069                                               &options, NULL, NULL, NULL,
3070                                               NULL) == 0);
3071
3072    mbedtls_debug_set_threshold(1);
3073    mbedtls_ssl_conf_dbg(&server.conf, options.srv_log_fun,
3074                         options.srv_log_obj);
3075
3076    TEST_ASSERT(mbedtls_test_mock_socket_connect(&(client.socket),
3077                                                 &(server.socket),
3078                                                 BUFFSIZE) == 0);
3079
3080    TEST_ASSERT(mbedtls_test_move_handshake_to_state(
3081                    &(client.ssl), &(server.ssl), MBEDTLS_SSL_HANDSHAKE_WRAPUP)
3082                ==  0);
3083    /* Force a bad session_id_len that will be read by the server in
3084     * mbedtls_ssl_cache_set. */
3085    server.ssl.session_negotiate->id_len = 33;
3086    if (options.cli_msg_len != 0 || options.srv_msg_len != 0) {
3087        /* Start data exchanging test */
3088        TEST_ASSERT(mbedtls_exchange_data(&(client.ssl), options.cli_msg_len,
3089                                          options.expected_cli_fragments,
3090                                          &(server.ssl), options.srv_msg_len,
3091                                          options.expected_srv_fragments)
3092                    == 0);
3093    }
3094
3095    /* Make sure that the cache did not store the session */
3096    TEST_EQUAL(srv_pattern.counter, 1);
3097exit:
3098    mbedtls_test_ssl_endpoint_free(&client, NULL);
3099    mbedtls_test_ssl_endpoint_free(&server, NULL);
3100    mbedtls_test_free_handshake_options(&options);
3101    mbedtls_debug_set_threshold(0);
3102    USE_PSA_DONE();
3103}
3104/* END_CASE */
3105
3106/* BEGIN_CASE depends_on:MBEDTLS_SSL_SRV_C:MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE:MBEDTLS_TEST_HOOKS */
3107void cookie_parsing(data_t *cookie, int exp_ret)
3108{
3109    mbedtls_ssl_context ssl;
3110    mbedtls_ssl_config conf;
3111    size_t len;
3112
3113    mbedtls_ssl_init(&ssl);
3114    mbedtls_ssl_config_init(&conf);
3115    TEST_EQUAL(mbedtls_ssl_config_defaults(&conf, MBEDTLS_SSL_IS_SERVER,
3116                                           MBEDTLS_SSL_TRANSPORT_DATAGRAM,
3117                                           MBEDTLS_SSL_PRESET_DEFAULT),
3118               0);
3119
3120    TEST_EQUAL(mbedtls_ssl_setup(&ssl, &conf), 0);
3121    TEST_EQUAL(mbedtls_ssl_check_dtls_clihlo_cookie(&ssl, ssl.cli_id,
3122                                                    ssl.cli_id_len,
3123                                                    cookie->x, cookie->len,
3124                                                    ssl.out_buf,
3125                                                    MBEDTLS_SSL_OUT_CONTENT_LEN,
3126                                                    &len),
3127               exp_ret);
3128
3129    mbedtls_ssl_free(&ssl);
3130    mbedtls_ssl_config_free(&conf);
3131}
3132/* END_CASE */
3133
3134/* BEGIN_CASE depends_on:MBEDTLS_TIMING_C:MBEDTLS_HAVE_TIME */
3135void timing_final_delay_accessor()
3136{
3137    mbedtls_timing_delay_context    delay_context;
3138
3139    mbedtls_timing_set_delay(&delay_context, 50, 100);
3140
3141    TEST_ASSERT(mbedtls_timing_get_final_delay(&delay_context) == 100);
3142}
3143/* END_CASE */
3144
3145/* BEGIN_CASE depends_on:MBEDTLS_SSL_DTLS_CONNECTION_ID */
3146void cid_sanity()
3147{
3148    mbedtls_ssl_context ssl;
3149    mbedtls_ssl_config conf;
3150
3151    unsigned char own_cid[MBEDTLS_SSL_CID_IN_LEN_MAX];
3152    unsigned char test_cid[MBEDTLS_SSL_CID_IN_LEN_MAX];
3153    int cid_enabled;
3154    size_t own_cid_len;
3155
3156    mbedtls_test_rnd_std_rand(NULL, own_cid, sizeof(own_cid));
3157
3158    mbedtls_ssl_init(&ssl);
3159    mbedtls_ssl_config_init(&conf);
3160
3161    TEST_ASSERT(mbedtls_ssl_config_defaults(&conf,
3162                                            MBEDTLS_SSL_IS_CLIENT,
3163                                            MBEDTLS_SSL_TRANSPORT_STREAM,
3164                                            MBEDTLS_SSL_PRESET_DEFAULT)
3165                == 0);
3166
3167    TEST_ASSERT(mbedtls_ssl_setup(&ssl, &conf) == 0);
3168
3169    /* Can't use CID functions with stream transport. */
3170    TEST_ASSERT(mbedtls_ssl_set_cid(&ssl, MBEDTLS_SSL_CID_ENABLED, own_cid,
3171                                    sizeof(own_cid))
3172                == MBEDTLS_ERR_SSL_BAD_INPUT_DATA);
3173
3174    TEST_ASSERT(mbedtls_ssl_get_own_cid(&ssl, &cid_enabled, test_cid,
3175                                        &own_cid_len)
3176                == MBEDTLS_ERR_SSL_BAD_INPUT_DATA);
3177
3178    TEST_ASSERT(mbedtls_ssl_config_defaults(&conf,
3179                                            MBEDTLS_SSL_IS_CLIENT,
3180                                            MBEDTLS_SSL_TRANSPORT_DATAGRAM,
3181                                            MBEDTLS_SSL_PRESET_DEFAULT)
3182                == 0);
3183
3184    /* Attempt to set config cid size too big. */
3185    TEST_ASSERT(mbedtls_ssl_conf_cid(&conf, MBEDTLS_SSL_CID_IN_LEN_MAX + 1,
3186                                     MBEDTLS_SSL_UNEXPECTED_CID_IGNORE)
3187                == MBEDTLS_ERR_SSL_BAD_INPUT_DATA);
3188
3189    TEST_ASSERT(mbedtls_ssl_conf_cid(&conf, sizeof(own_cid),
3190                                     MBEDTLS_SSL_UNEXPECTED_CID_IGNORE)
3191                == 0);
3192
3193    /* Attempt to set CID length not matching config. */
3194    TEST_ASSERT(mbedtls_ssl_set_cid(&ssl, MBEDTLS_SSL_CID_ENABLED, own_cid,
3195                                    MBEDTLS_SSL_CID_IN_LEN_MAX - 1)
3196                == MBEDTLS_ERR_SSL_BAD_INPUT_DATA);
3197
3198    TEST_ASSERT(mbedtls_ssl_set_cid(&ssl, MBEDTLS_SSL_CID_ENABLED, own_cid,
3199                                    sizeof(own_cid))
3200                == 0);
3201
3202    /* Test we get back what we put in. */
3203    TEST_ASSERT(mbedtls_ssl_get_own_cid(&ssl, &cid_enabled, test_cid,
3204                                        &own_cid_len)
3205                == 0);
3206
3207    TEST_EQUAL(cid_enabled, MBEDTLS_SSL_CID_ENABLED);
3208    ASSERT_COMPARE(own_cid, own_cid_len, test_cid, own_cid_len);
3209
3210    /* Test disabling works. */
3211    TEST_ASSERT(mbedtls_ssl_set_cid(&ssl, MBEDTLS_SSL_CID_DISABLED, NULL,
3212                                    0)
3213                == 0);
3214
3215    TEST_ASSERT(mbedtls_ssl_get_own_cid(&ssl, &cid_enabled, test_cid,
3216                                        &own_cid_len)
3217                == 0);
3218
3219    TEST_EQUAL(cid_enabled, MBEDTLS_SSL_CID_DISABLED);
3220
3221    mbedtls_ssl_free(&ssl);
3222    mbedtls_ssl_config_free(&conf);
3223}
3224/* END_CASE */
3225
3226/* BEGIN_CASE depends_on:MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED:MBEDTLS_USE_PSA_CRYPTO:MBEDTLS_PKCS1_V15:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_ECP_DP_SECP256R1_ENABLED:MBEDTLS_RSA_C:MBEDTLS_ECP_DP_SECP384R1_ENABLED:MBEDTLS_PK_CAN_ECDSA_SOME */
3227void raw_key_agreement_fail(int bad_server_ecdhe_key)
3228{
3229    enum { BUFFSIZE = 17000 };
3230    mbedtls_test_ssl_endpoint client, server;
3231    mbedtls_psa_stats_t stats;
3232    size_t free_slots_before = -1;
3233    mbedtls_test_handshake_test_options options;
3234
3235    uint16_t iana_tls_group_list[] = { MBEDTLS_SSL_IANA_TLS_GROUP_SECP256R1,
3236                                       MBEDTLS_SSL_IANA_TLS_GROUP_NONE };
3237    USE_PSA_INIT();
3238    mbedtls_platform_zeroize(&client, sizeof(client));
3239    mbedtls_platform_zeroize(&server, sizeof(server));
3240
3241    mbedtls_test_init_handshake_options(&options);
3242    options.pk_alg = MBEDTLS_PK_ECDSA;
3243
3244    /* Client side, force SECP256R1 to make one key bitflip fail
3245     * the raw key agreement. Flipping the first byte makes the
3246     * required 0x04 identifier invalid. */
3247    TEST_EQUAL(mbedtls_test_ssl_endpoint_init(&client, MBEDTLS_SSL_IS_CLIENT,
3248                                              &options, NULL, NULL,
3249                                              NULL, iana_tls_group_list), 0);
3250
3251    /* Server side */
3252    TEST_EQUAL(mbedtls_test_ssl_endpoint_init(&server, MBEDTLS_SSL_IS_SERVER,
3253                                              &options, NULL, NULL,
3254                                              NULL, NULL), 0);
3255
3256    TEST_EQUAL(mbedtls_test_mock_socket_connect(&(client.socket),
3257                                                &(server.socket),
3258                                                BUFFSIZE), 0);
3259
3260    TEST_EQUAL(mbedtls_test_move_handshake_to_state(
3261                   &(client.ssl), &(server.ssl),
3262                   MBEDTLS_SSL_CLIENT_KEY_EXCHANGE), 0);
3263
3264    mbedtls_psa_get_stats(&stats);
3265    /* Save the number of slots in use up to this point.
3266     * With PSA, one can be used for the ECDH private key. */
3267    free_slots_before = stats.empty_slots;
3268
3269    if (bad_server_ecdhe_key) {
3270        /* Force a simulated bitflip in the server key. to make the
3271         * raw key agreement in ssl_write_client_key_exchange fail. */
3272        (client.ssl).handshake->ecdh_psa_peerkey[0] ^= 0x02;
3273    }
3274
3275    TEST_EQUAL(mbedtls_test_move_handshake_to_state(
3276                   &(client.ssl), &(server.ssl), MBEDTLS_SSL_HANDSHAKE_OVER),
3277               bad_server_ecdhe_key ? MBEDTLS_ERR_SSL_HW_ACCEL_FAILED : 0);
3278
3279    mbedtls_psa_get_stats(&stats);
3280
3281    /* Make sure that the key slot is already destroyed in case of failure,
3282     * without waiting to close the connection. */
3283    if (bad_server_ecdhe_key) {
3284        TEST_EQUAL(free_slots_before, stats.empty_slots);
3285    }
3286
3287exit:
3288    mbedtls_test_ssl_endpoint_free(&client, NULL);
3289    mbedtls_test_ssl_endpoint_free(&server, NULL);
3290    mbedtls_test_free_handshake_options(&options);
3291
3292    USE_PSA_DONE();
3293}
3294/* END_CASE */
3295/* 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_DP_SECP384R1_ENABLED */
3296void tls13_server_certificate_msg_invalid_vector_len()
3297{
3298    int ret = -1;
3299    mbedtls_test_ssl_endpoint client_ep, server_ep;
3300    unsigned char *buf, *end;
3301    size_t buf_len;
3302    int step = 0;
3303    int expected_result;
3304    mbedtls_ssl_chk_buf_ptr_args expected_chk_buf_ptr_args;
3305    mbedtls_test_handshake_test_options client_options;
3306    mbedtls_test_handshake_test_options server_options;
3307
3308    /*
3309     * Test set-up
3310     */
3311    USE_PSA_INIT();
3312    mbedtls_platform_zeroize(&client_ep, sizeof(client_ep));
3313    mbedtls_platform_zeroize(&server_ep, sizeof(server_ep));
3314
3315    mbedtls_test_init_handshake_options(&client_options);
3316    client_options.pk_alg = MBEDTLS_PK_ECDSA;
3317    ret = mbedtls_test_ssl_endpoint_init(&client_ep, MBEDTLS_SSL_IS_CLIENT,
3318                                         &client_options, NULL, NULL, NULL,
3319                                         NULL);
3320    TEST_EQUAL(ret, 0);
3321
3322    mbedtls_test_init_handshake_options(&server_options);
3323    server_options.pk_alg = MBEDTLS_PK_ECDSA;
3324    ret = mbedtls_test_ssl_endpoint_init(&server_ep, MBEDTLS_SSL_IS_SERVER,
3325                                         &server_options, NULL, NULL, NULL,
3326                                         NULL);
3327    TEST_EQUAL(ret, 0);
3328
3329    ret = mbedtls_test_mock_socket_connect(&(client_ep.socket),
3330                                           &(server_ep.socket), 1024);
3331    TEST_EQUAL(ret, 0);
3332
3333    while (1) {
3334        mbedtls_test_set_step(++step);
3335
3336        ret = mbedtls_test_move_handshake_to_state(
3337            &(server_ep.ssl), &(client_ep.ssl),
3338            MBEDTLS_SSL_CERTIFICATE_VERIFY);
3339        TEST_EQUAL(ret, 0);
3340
3341        ret = mbedtls_ssl_flush_output(&(server_ep.ssl));
3342        TEST_EQUAL(ret, 0);
3343
3344        ret = mbedtls_test_move_handshake_to_state(
3345            &(client_ep.ssl), &(server_ep.ssl),
3346            MBEDTLS_SSL_SERVER_CERTIFICATE);
3347        TEST_EQUAL(ret, 0);
3348
3349        ret = mbedtls_ssl_tls13_fetch_handshake_msg(&(client_ep.ssl),
3350                                                    MBEDTLS_SSL_HS_CERTIFICATE,
3351                                                    &buf, &buf_len);
3352        TEST_EQUAL(ret, 0);
3353
3354        end = buf + buf_len;
3355
3356        /*
3357         * Tweak server Certificate message and parse it.
3358         */
3359
3360        ret = tweak_tls13_certificate_msg_vector_len(
3361            buf, &end, step, &expected_result, &expected_chk_buf_ptr_args);
3362
3363        if (ret != 0) {
3364            break;
3365        }
3366
3367        ret = mbedtls_ssl_tls13_parse_certificate(&(client_ep.ssl), buf, end);
3368        TEST_EQUAL(ret, expected_result);
3369
3370        TEST_ASSERT(mbedtls_ssl_cmp_chk_buf_ptr_fail_args(
3371                        &expected_chk_buf_ptr_args) == 0);
3372
3373        mbedtls_ssl_reset_chk_buf_ptr_fail_args();
3374
3375        ret = mbedtls_ssl_session_reset(&(client_ep.ssl));
3376        TEST_EQUAL(ret, 0);
3377
3378        ret = mbedtls_ssl_session_reset(&(server_ep.ssl));
3379        TEST_EQUAL(ret, 0);
3380    }
3381
3382exit:
3383    mbedtls_ssl_reset_chk_buf_ptr_fail_args();
3384    mbedtls_test_ssl_endpoint_free(&client_ep, NULL);
3385    mbedtls_test_ssl_endpoint_free(&server_ep, NULL);
3386    mbedtls_test_free_handshake_options(&client_options);
3387    mbedtls_test_free_handshake_options(&server_options);
3388    USE_PSA_DONE();
3389}
3390/* END_CASE */
3391
3392/* BEGIN_CASE depends_on:MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
3393void ssl_ecjpake_set_password(int use_opaque_arg)
3394{
3395    mbedtls_ssl_context ssl;
3396    mbedtls_ssl_config conf;
3397#if defined(MBEDTLS_USE_PSA_CRYPTO)
3398    mbedtls_svc_key_id_t pwd_slot = MBEDTLS_SVC_KEY_ID_INIT;
3399#else   /* MBEDTLS_USE_PSA_CRYPTO */
3400    (void) use_opaque_arg;
3401#endif  /* MBEDTLS_USE_PSA_CRYPTO */
3402    unsigned char pwd_string[sizeof(ECJPAKE_TEST_PWD)] = "";
3403    size_t pwd_len = 0;
3404    int ret;
3405
3406    USE_PSA_INIT();
3407
3408    mbedtls_ssl_init(&ssl);
3409
3410    /* test with uninitalized SSL context */
3411    ECJPAKE_TEST_SET_PASSWORD(MBEDTLS_ERR_SSL_BAD_INPUT_DATA);
3412
3413    mbedtls_ssl_config_init(&conf);
3414
3415    TEST_EQUAL(mbedtls_ssl_config_defaults(&conf,
3416                                           MBEDTLS_SSL_IS_CLIENT,
3417                                           MBEDTLS_SSL_TRANSPORT_STREAM,
3418                                           MBEDTLS_SSL_PRESET_DEFAULT), 0);
3419
3420    TEST_EQUAL(mbedtls_ssl_setup(&ssl, &conf), 0);
3421
3422    /* test with empty password or unitialized password key (depending on use_opaque_arg) */
3423    ECJPAKE_TEST_SET_PASSWORD(MBEDTLS_ERR_SSL_BAD_INPUT_DATA);
3424
3425    pwd_len = strlen(ECJPAKE_TEST_PWD);
3426    memcpy(pwd_string, ECJPAKE_TEST_PWD, pwd_len);
3427
3428#if defined(MBEDTLS_USE_PSA_CRYPTO)
3429    if (use_opaque_arg) {
3430        psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
3431        psa_key_attributes_t check_attributes = PSA_KEY_ATTRIBUTES_INIT;
3432
3433        /* First try with an invalid usage */
3434        psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_HASH);
3435        psa_set_key_algorithm(&attributes, PSA_ALG_JPAKE);
3436        psa_set_key_type(&attributes, PSA_KEY_TYPE_PASSWORD);
3437
3438        PSA_ASSERT(psa_import_key(&attributes, pwd_string,
3439                                  pwd_len, &pwd_slot));
3440
3441        ECJPAKE_TEST_SET_PASSWORD(MBEDTLS_ERR_SSL_HW_ACCEL_FAILED);
3442
3443        /* check that the opaque key is still valid after failure */
3444        TEST_EQUAL(psa_get_key_attributes(pwd_slot, &check_attributes),
3445                   PSA_SUCCESS);
3446
3447        psa_destroy_key(pwd_slot);
3448
3449        /* Then set the correct usage */
3450        psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_DERIVE);
3451
3452        PSA_ASSERT(psa_import_key(&attributes, pwd_string,
3453                                  pwd_len, &pwd_slot));
3454    }
3455#endif  /* MBEDTLS_USE_PSA_CRYPTO */
3456
3457    /* final check which should work without errors */
3458    ECJPAKE_TEST_SET_PASSWORD(0);
3459
3460#if defined(MBEDTLS_USE_PSA_CRYPTO)
3461    if (use_opaque_arg) {
3462        psa_destroy_key(pwd_slot);
3463    }
3464#endif  /* MBEDTLS_USE_PSA_CRYPTO */
3465    mbedtls_ssl_free(&ssl);
3466    mbedtls_ssl_config_free(&conf);
3467
3468    USE_PSA_DONE();
3469}
3470/* END_CASE */
3471
3472/* BEGIN_CASE */
3473void elliptic_curve_get_properties()
3474{
3475    psa_ecc_family_t psa_family;
3476    size_t psa_bits;
3477
3478    USE_PSA_INIT();
3479
3480#if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED) || defined(PSA_WANT_ECC_SECP_R1_521)
3481    TEST_AVAILABLE_ECC(25, MBEDTLS_ECP_DP_SECP521R1, PSA_ECC_FAMILY_SECP_R1, 521);
3482#else
3483    TEST_UNAVAILABLE_ECC(25, MBEDTLS_ECP_DP_SECP521R1, PSA_ECC_FAMILY_SECP_R1, 521);
3484#endif
3485#if defined(MBEDTLS_ECP_DP_BP512R1_ENABLED) || defined(PSA_WANT_ECC_BRAINPOOL_P_R1_512)
3486    TEST_AVAILABLE_ECC(28, MBEDTLS_ECP_DP_BP512R1, PSA_ECC_FAMILY_BRAINPOOL_P_R1, 512);
3487#else
3488    TEST_UNAVAILABLE_ECC(28, MBEDTLS_ECP_DP_BP512R1, PSA_ECC_FAMILY_BRAINPOOL_P_R1, 512);
3489#endif
3490#if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) || defined(PSA_WANT_ECC_SECP_R1_384)
3491    TEST_AVAILABLE_ECC(24, MBEDTLS_ECP_DP_SECP384R1, PSA_ECC_FAMILY_SECP_R1, 384);
3492#else
3493    TEST_UNAVAILABLE_ECC(24, MBEDTLS_ECP_DP_SECP384R1, PSA_ECC_FAMILY_SECP_R1, 384);
3494#endif
3495#if defined(MBEDTLS_ECP_DP_BP384R1_ENABLED) || defined(PSA_WANT_ECC_BRAINPOOL_P_R1_384)
3496    TEST_AVAILABLE_ECC(27, MBEDTLS_ECP_DP_BP384R1, PSA_ECC_FAMILY_BRAINPOOL_P_R1, 384);
3497#else
3498    TEST_UNAVAILABLE_ECC(27, MBEDTLS_ECP_DP_BP384R1, PSA_ECC_FAMILY_BRAINPOOL_P_R1, 384);
3499#endif
3500#if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) || defined(PSA_WANT_ECC_SECP_R1_256)
3501    TEST_AVAILABLE_ECC(23, MBEDTLS_ECP_DP_SECP256R1, PSA_ECC_FAMILY_SECP_R1, 256);
3502#else
3503    TEST_UNAVAILABLE_ECC(23, MBEDTLS_ECP_DP_SECP256R1, PSA_ECC_FAMILY_SECP_R1, 256);
3504#endif
3505#if defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED) || defined(PSA_WANT_ECC_SECP_K1_256)
3506    TEST_AVAILABLE_ECC(22, MBEDTLS_ECP_DP_SECP256K1, PSA_ECC_FAMILY_SECP_K1, 256);
3507#else
3508    TEST_UNAVAILABLE_ECC(22, MBEDTLS_ECP_DP_SECP256K1, PSA_ECC_FAMILY_SECP_K1, 256);
3509#endif
3510#if defined(MBEDTLS_ECP_DP_BP256R1_ENABLED) || defined(PSA_WANT_ECC_BRAINPOOL_P_R1_256)
3511    TEST_AVAILABLE_ECC(26, MBEDTLS_ECP_DP_BP256R1, PSA_ECC_FAMILY_BRAINPOOL_P_R1, 256);
3512#else
3513    TEST_UNAVAILABLE_ECC(26, MBEDTLS_ECP_DP_BP256R1, PSA_ECC_FAMILY_BRAINPOOL_P_R1, 256);
3514#endif
3515#if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) || defined(PSA_WANT_ECC_SECP_R1_224)
3516    TEST_AVAILABLE_ECC(21, MBEDTLS_ECP_DP_SECP224R1, PSA_ECC_FAMILY_SECP_R1, 224);
3517#else
3518    TEST_UNAVAILABLE_ECC(21, MBEDTLS_ECP_DP_SECP224R1, PSA_ECC_FAMILY_SECP_R1, 224);
3519#endif
3520#if defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) || defined(PSA_WANT_ECC_SECP_K1_224)
3521    TEST_AVAILABLE_ECC(20, MBEDTLS_ECP_DP_SECP224K1, PSA_ECC_FAMILY_SECP_K1, 224);
3522#else
3523    TEST_UNAVAILABLE_ECC(20, MBEDTLS_ECP_DP_SECP224K1, PSA_ECC_FAMILY_SECP_K1, 224);
3524#endif
3525#if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) || defined(PSA_WANT_ECC_SECP_R1_192)
3526    TEST_AVAILABLE_ECC(19, MBEDTLS_ECP_DP_SECP192R1, PSA_ECC_FAMILY_SECP_R1, 192);
3527#else
3528    TEST_UNAVAILABLE_ECC(19, MBEDTLS_ECP_DP_SECP192R1, PSA_ECC_FAMILY_SECP_R1, 192);
3529#endif
3530#if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) || defined(PSA_WANT_ECC_SECP_K1_192)
3531    TEST_AVAILABLE_ECC(18, MBEDTLS_ECP_DP_SECP192K1, PSA_ECC_FAMILY_SECP_K1, 192);
3532#else
3533    TEST_UNAVAILABLE_ECC(18, MBEDTLS_ECP_DP_SECP192K1, PSA_ECC_FAMILY_SECP_K1, 192);
3534#endif
3535#if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) || defined(PSA_WANT_ECC_MONTGOMERY_255)
3536    TEST_AVAILABLE_ECC(29, MBEDTLS_ECP_DP_CURVE25519, PSA_ECC_FAMILY_MONTGOMERY, 255);
3537#else
3538    TEST_UNAVAILABLE_ECC(29, MBEDTLS_ECP_DP_CURVE25519, PSA_ECC_FAMILY_MONTGOMERY, 255);
3539#endif
3540#if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED) || defined(PSA_WANT_ECC_MONTGOMERY_448)
3541    TEST_AVAILABLE_ECC(30, MBEDTLS_ECP_DP_CURVE448, PSA_ECC_FAMILY_MONTGOMERY, 448);
3542#else
3543    TEST_UNAVAILABLE_ECC(30, MBEDTLS_ECP_DP_CURVE448, PSA_ECC_FAMILY_MONTGOMERY, 448);
3544#endif
3545
3546    USE_PSA_DONE();
3547}
3548/* END_CASE */
3549