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