1 /** \file ssl_helpers.c
2  *
3  * \brief Helper functions to set up a TLS connection.
4  */
5 
6 /*
7  *  Copyright The Mbed TLS Contributors
8  *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
9  */
10 
11 #include <test/ssl_helpers.h>
12 #include "md_psa.h"
13 
14 #if defined(MBEDTLS_SSL_TLS_C)
15 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
16 static int rng_seed = 0xBEEF;
rng_get(void * p_rng,unsigned char * output,size_t output_len)17 static int rng_get(void *p_rng, unsigned char *output, size_t output_len)
18 {
19     (void) p_rng;
20     for (size_t i = 0; i < output_len; i++) {
21         output[i] = rand();
22     }
23 
24     return 0;
25 }
26 #endif
27 
mbedtls_test_ssl_log_analyzer(void * ctx,int level,const char * file,int line,const char * str)28 void mbedtls_test_ssl_log_analyzer(void *ctx, int level,
29                                    const char *file, int line,
30                                    const char *str)
31 {
32     mbedtls_test_ssl_log_pattern *p = (mbedtls_test_ssl_log_pattern *) ctx;
33 
34     (void) level;
35     (void) line;
36     (void) file;
37 
38     if (NULL != p &&
39         NULL != p->pattern &&
40         NULL != strstr(str, p->pattern)) {
41         p->counter++;
42     }
43 }
44 
mbedtls_test_init_handshake_options(mbedtls_test_handshake_test_options * opts)45 void mbedtls_test_init_handshake_options(
46     mbedtls_test_handshake_test_options *opts)
47 {
48 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
49     srand(rng_seed);
50     rng_seed += 0xD0;
51 #endif
52     opts->cipher = "";
53     opts->client_min_version = MBEDTLS_SSL_VERSION_UNKNOWN;
54     opts->client_max_version = MBEDTLS_SSL_VERSION_UNKNOWN;
55     opts->server_min_version = MBEDTLS_SSL_VERSION_UNKNOWN;
56     opts->server_max_version = MBEDTLS_SSL_VERSION_UNKNOWN;
57     opts->expected_negotiated_version = MBEDTLS_SSL_VERSION_TLS1_3;
58     opts->expected_handshake_result = 0;
59     opts->expected_ciphersuite = 0;
60     opts->pk_alg = MBEDTLS_PK_RSA;
61     opts->opaque_alg = 0;
62     opts->opaque_alg2 = 0;
63     opts->opaque_usage = 0;
64     opts->psk_str = NULL;
65     opts->dtls = 0;
66     opts->srv_auth_mode = MBEDTLS_SSL_VERIFY_NONE;
67     opts->serialize = 0;
68     opts->mfl = MBEDTLS_SSL_MAX_FRAG_LEN_NONE;
69     opts->cli_msg_len = 100;
70     opts->srv_msg_len = 100;
71     opts->expected_cli_fragments = 1;
72     opts->expected_srv_fragments = 1;
73     opts->renegotiate = 0;
74     opts->legacy_renegotiation = MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION;
75     opts->srv_log_obj = NULL;
76     opts->srv_log_obj = NULL;
77     opts->srv_log_fun = NULL;
78     opts->cli_log_fun = NULL;
79     opts->resize_buffers = 1;
80 #if defined(MBEDTLS_SSL_CACHE_C)
81     opts->cache = NULL;
82     TEST_CALLOC(opts->cache, 1);
83     mbedtls_ssl_cache_init(opts->cache);
84 #if defined(MBEDTLS_HAVE_TIME)
85     TEST_EQUAL(mbedtls_ssl_cache_get_timeout(opts->cache),
86                MBEDTLS_SSL_CACHE_DEFAULT_TIMEOUT);
87 #endif
88 exit:
89     return;
90 #endif
91 }
92 
mbedtls_test_free_handshake_options(mbedtls_test_handshake_test_options * opts)93 void mbedtls_test_free_handshake_options(
94     mbedtls_test_handshake_test_options *opts)
95 {
96 #if defined(MBEDTLS_SSL_CACHE_C)
97     mbedtls_ssl_cache_free(opts->cache);
98     mbedtls_free(opts->cache);
99 #else
100     (void) opts;
101 #endif
102 }
103 
104 #if defined(MBEDTLS_TEST_HOOKS)
set_chk_buf_ptr_args(mbedtls_ssl_chk_buf_ptr_args * args,unsigned char * cur,unsigned char * end,size_t need)105 static void set_chk_buf_ptr_args(
106     mbedtls_ssl_chk_buf_ptr_args *args,
107     unsigned char *cur, unsigned char *end, size_t need)
108 {
109     args->cur = cur;
110     args->end = end;
111     args->need = need;
112 }
113 
reset_chk_buf_ptr_args(mbedtls_ssl_chk_buf_ptr_args * args)114 static void reset_chk_buf_ptr_args(mbedtls_ssl_chk_buf_ptr_args *args)
115 {
116     memset(args, 0, sizeof(*args));
117 }
118 #endif /* MBEDTLS_TEST_HOOKS */
119 
mbedtls_test_ssl_buffer_init(mbedtls_test_ssl_buffer * buf)120 void mbedtls_test_ssl_buffer_init(mbedtls_test_ssl_buffer *buf)
121 {
122     memset(buf, 0, sizeof(*buf));
123 }
124 
mbedtls_test_ssl_buffer_setup(mbedtls_test_ssl_buffer * buf,size_t capacity)125 int mbedtls_test_ssl_buffer_setup(mbedtls_test_ssl_buffer *buf,
126                                   size_t capacity)
127 {
128     buf->buffer = (unsigned char *) mbedtls_calloc(capacity,
129                                                    sizeof(unsigned char));
130     if (NULL == buf->buffer) {
131         return MBEDTLS_ERR_SSL_ALLOC_FAILED;
132     }
133     buf->capacity = capacity;
134 
135     return 0;
136 }
137 
mbedtls_test_ssl_buffer_free(mbedtls_test_ssl_buffer * buf)138 void mbedtls_test_ssl_buffer_free(mbedtls_test_ssl_buffer *buf)
139 {
140     if (buf->buffer != NULL) {
141         mbedtls_free(buf->buffer);
142     }
143 
144     memset(buf, 0, sizeof(*buf));
145 }
146 
mbedtls_test_ssl_buffer_put(mbedtls_test_ssl_buffer * buf,const unsigned char * input,size_t input_len)147 int mbedtls_test_ssl_buffer_put(mbedtls_test_ssl_buffer *buf,
148                                 const unsigned char *input, size_t input_len)
149 {
150     size_t overflow = 0;
151 
152     if ((buf == NULL) || (buf->buffer == NULL)) {
153         return -1;
154     }
155 
156     /* Reduce input_len to a number that fits in the buffer. */
157     if ((buf->content_length + input_len) > buf->capacity) {
158         input_len = buf->capacity - buf->content_length;
159     }
160 
161     if (input == NULL) {
162         return (input_len == 0) ? 0 : -1;
163     }
164 
165     /* Check if the buffer has not come full circle and free space is not in
166      * the middle */
167     if (buf->start + buf->content_length < buf->capacity) {
168 
169         /* Calculate the number of bytes that need to be placed at lower memory
170          * address */
171         if (buf->start + buf->content_length + input_len
172             > buf->capacity) {
173             overflow = (buf->start + buf->content_length + input_len)
174                        % buf->capacity;
175         }
176 
177         memcpy(buf->buffer + buf->start + buf->content_length, input,
178                input_len - overflow);
179         memcpy(buf->buffer, input + input_len - overflow, overflow);
180 
181     } else {
182         /* The buffer has come full circle and free space is in the middle */
183         memcpy(buf->buffer + buf->start + buf->content_length - buf->capacity,
184                input, input_len);
185     }
186 
187     buf->content_length += input_len;
188     return (input_len > INT_MAX) ? INT_MAX : (int) input_len;
189 }
190 
mbedtls_test_ssl_buffer_get(mbedtls_test_ssl_buffer * buf,unsigned char * output,size_t output_len)191 int mbedtls_test_ssl_buffer_get(mbedtls_test_ssl_buffer *buf,
192                                 unsigned char *output, size_t output_len)
193 {
194     size_t overflow = 0;
195 
196     if ((buf == NULL) || (buf->buffer == NULL)) {
197         return -1;
198     }
199 
200     if (output == NULL && output_len == 0) {
201         return 0;
202     }
203 
204     if (buf->content_length < output_len) {
205         output_len = buf->content_length;
206     }
207 
208     /* Calculate the number of bytes that need to be drawn from lower memory
209      * address */
210     if (buf->start + output_len > buf->capacity) {
211         overflow = (buf->start + output_len) % buf->capacity;
212     }
213 
214     if (output != NULL) {
215         memcpy(output, buf->buffer + buf->start, output_len - overflow);
216         memcpy(output + output_len - overflow, buf->buffer, overflow);
217     }
218 
219     buf->content_length -= output_len;
220     buf->start = (buf->start + output_len) % buf->capacity;
221 
222     return (output_len > INT_MAX) ? INT_MAX : (int) output_len;
223 }
224 
mbedtls_test_ssl_message_queue_setup(mbedtls_test_ssl_message_queue * queue,size_t capacity)225 int mbedtls_test_ssl_message_queue_setup(
226     mbedtls_test_ssl_message_queue *queue, size_t capacity)
227 {
228     queue->messages = (size_t *) mbedtls_calloc(capacity, sizeof(size_t));
229     if (NULL == queue->messages) {
230         return MBEDTLS_ERR_SSL_ALLOC_FAILED;
231     }
232 
233     queue->capacity = (capacity > INT_MAX) ? INT_MAX : (int) capacity;
234     queue->pos = 0;
235     queue->num = 0;
236 
237     return 0;
238 }
239 
mbedtls_test_ssl_message_queue_free(mbedtls_test_ssl_message_queue * queue)240 void mbedtls_test_ssl_message_queue_free(
241     mbedtls_test_ssl_message_queue *queue)
242 {
243     if (queue == NULL) {
244         return;
245     }
246 
247     if (queue->messages != NULL) {
248         mbedtls_free(queue->messages);
249     }
250 
251     memset(queue, 0, sizeof(*queue));
252 }
253 
mbedtls_test_ssl_message_queue_push_info(mbedtls_test_ssl_message_queue * queue,size_t len)254 int mbedtls_test_ssl_message_queue_push_info(
255     mbedtls_test_ssl_message_queue *queue, size_t len)
256 {
257     int place;
258     if (queue == NULL) {
259         return MBEDTLS_TEST_ERROR_ARG_NULL;
260     }
261 
262     if (queue->num >= queue->capacity) {
263         return MBEDTLS_ERR_SSL_WANT_WRITE;
264     }
265 
266     place = (queue->pos + queue->num) % queue->capacity;
267     queue->messages[place] = len;
268     queue->num++;
269     return (len > INT_MAX) ? INT_MAX : (int) len;
270 }
271 
mbedtls_test_ssl_message_queue_pop_info(mbedtls_test_ssl_message_queue * queue,size_t buf_len)272 int mbedtls_test_ssl_message_queue_pop_info(
273     mbedtls_test_ssl_message_queue *queue, size_t buf_len)
274 {
275     size_t message_length;
276     if (queue == NULL) {
277         return MBEDTLS_TEST_ERROR_ARG_NULL;
278     }
279     if (queue->num == 0) {
280         return MBEDTLS_ERR_SSL_WANT_READ;
281     }
282 
283     message_length = queue->messages[queue->pos];
284     queue->messages[queue->pos] = 0;
285     queue->num--;
286     queue->pos++;
287     queue->pos %= queue->capacity;
288     if (queue->pos < 0) {
289         queue->pos += queue->capacity;
290     }
291 
292     return (message_length > INT_MAX && buf_len > INT_MAX) ? INT_MAX :
293            (message_length > buf_len) ? (int) buf_len : (int) message_length;
294 }
295 
296 /*
297  * Take a peek on the info about the next message length from the queue.
298  * This will be the oldest inserted message length(fifo).
299  *
300  * \retval  MBEDTLS_TEST_ERROR_ARG_NULL, if the queue is null.
301  * \retval  MBEDTLS_ERR_SSL_WANT_READ, if the queue is empty.
302  * \retval  0, if the peek was successful.
303  * \retval  MBEDTLS_TEST_ERROR_MESSAGE_TRUNCATED, if the given buffer length is
304  *          too small to fit the message. In this case the \p msg_len will be
305  *          set to the full message length so that the
306  *          caller knows what portion of the message can be dropped.
307  */
test_ssl_message_queue_peek_info(mbedtls_test_ssl_message_queue * queue,size_t buf_len,size_t * msg_len)308 static int test_ssl_message_queue_peek_info(
309     mbedtls_test_ssl_message_queue *queue,
310     size_t buf_len, size_t *msg_len)
311 {
312     if (queue == NULL || msg_len == NULL) {
313         return MBEDTLS_TEST_ERROR_ARG_NULL;
314     }
315     if (queue->num == 0) {
316         return MBEDTLS_ERR_SSL_WANT_READ;
317     }
318 
319     *msg_len = queue->messages[queue->pos];
320     return (*msg_len > buf_len) ? MBEDTLS_TEST_ERROR_MESSAGE_TRUNCATED : 0;
321 }
322 
mbedtls_test_mock_socket_init(mbedtls_test_mock_socket * socket)323 void mbedtls_test_mock_socket_init(mbedtls_test_mock_socket *socket)
324 {
325     memset(socket, 0, sizeof(*socket));
326 }
327 
mbedtls_test_mock_socket_close(mbedtls_test_mock_socket * socket)328 void mbedtls_test_mock_socket_close(mbedtls_test_mock_socket *socket)
329 {
330     if (socket == NULL) {
331         return;
332     }
333 
334     if (socket->input != NULL) {
335         mbedtls_test_ssl_buffer_free(socket->input);
336         mbedtls_free(socket->input);
337     }
338 
339     if (socket->output != NULL) {
340         mbedtls_test_ssl_buffer_free(socket->output);
341         mbedtls_free(socket->output);
342     }
343 
344     if (socket->peer != NULL) {
345         memset(socket->peer, 0, sizeof(*socket->peer));
346     }
347 
348     memset(socket, 0, sizeof(*socket));
349 }
350 
mbedtls_test_mock_socket_connect(mbedtls_test_mock_socket * peer1,mbedtls_test_mock_socket * peer2,size_t bufsize)351 int mbedtls_test_mock_socket_connect(mbedtls_test_mock_socket *peer1,
352                                      mbedtls_test_mock_socket *peer2,
353                                      size_t bufsize)
354 {
355     int ret = -1;
356 
357     peer1->output =
358         (mbedtls_test_ssl_buffer *) mbedtls_calloc(
359             1, sizeof(mbedtls_test_ssl_buffer));
360     if (peer1->output == NULL) {
361         ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
362         goto exit;
363     }
364     mbedtls_test_ssl_buffer_init(peer1->output);
365     if (0 != (ret = mbedtls_test_ssl_buffer_setup(peer1->output, bufsize))) {
366         goto exit;
367     }
368 
369     peer2->output =
370         (mbedtls_test_ssl_buffer *) mbedtls_calloc(
371             1, sizeof(mbedtls_test_ssl_buffer));
372     if (peer2->output == NULL) {
373         ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
374         goto exit;
375     }
376     mbedtls_test_ssl_buffer_init(peer2->output);
377     if (0 != (ret = mbedtls_test_ssl_buffer_setup(peer2->output, bufsize))) {
378         goto exit;
379     }
380 
381     peer1->peer = peer2;
382     peer2->peer = peer1;
383     peer1->input = peer2->output;
384     peer2->input = peer1->output;
385 
386     peer1->status = peer2->status = MBEDTLS_MOCK_SOCKET_CONNECTED;
387     ret = 0;
388 
389 exit:
390 
391     if (ret != 0) {
392         mbedtls_test_mock_socket_close(peer1);
393         mbedtls_test_mock_socket_close(peer2);
394     }
395 
396     return ret;
397 }
398 
mbedtls_test_mock_tcp_send_b(void * ctx,const unsigned char * buf,size_t len)399 int mbedtls_test_mock_tcp_send_b(void *ctx,
400                                  const unsigned char *buf, size_t len)
401 {
402     mbedtls_test_mock_socket *socket = (mbedtls_test_mock_socket *) ctx;
403 
404     if (socket == NULL || socket->status != MBEDTLS_MOCK_SOCKET_CONNECTED) {
405         return -1;
406     }
407 
408     return mbedtls_test_ssl_buffer_put(socket->output, buf, len);
409 }
410 
mbedtls_test_mock_tcp_recv_b(void * ctx,unsigned char * buf,size_t len)411 int mbedtls_test_mock_tcp_recv_b(void *ctx, unsigned char *buf, size_t len)
412 {
413     mbedtls_test_mock_socket *socket = (mbedtls_test_mock_socket *) ctx;
414 
415     if (socket == NULL || socket->status != MBEDTLS_MOCK_SOCKET_CONNECTED) {
416         return -1;
417     }
418 
419     return mbedtls_test_ssl_buffer_get(socket->input, buf, len);
420 }
421 
mbedtls_test_mock_tcp_send_nb(void * ctx,const unsigned char * buf,size_t len)422 int mbedtls_test_mock_tcp_send_nb(void *ctx,
423                                   const unsigned char *buf, size_t len)
424 {
425     mbedtls_test_mock_socket *socket = (mbedtls_test_mock_socket *) ctx;
426 
427     if (socket == NULL || socket->status != MBEDTLS_MOCK_SOCKET_CONNECTED) {
428         return -1;
429     }
430 
431     if (socket->output->capacity == socket->output->content_length) {
432         return MBEDTLS_ERR_SSL_WANT_WRITE;
433     }
434 
435     return mbedtls_test_ssl_buffer_put(socket->output, buf, len);
436 }
437 
mbedtls_test_mock_tcp_recv_nb(void * ctx,unsigned char * buf,size_t len)438 int mbedtls_test_mock_tcp_recv_nb(void *ctx, unsigned char *buf, size_t len)
439 {
440     mbedtls_test_mock_socket *socket = (mbedtls_test_mock_socket *) ctx;
441 
442     if (socket == NULL || socket->status != MBEDTLS_MOCK_SOCKET_CONNECTED) {
443         return -1;
444     }
445 
446     if (socket->input->content_length == 0) {
447         return MBEDTLS_ERR_SSL_WANT_READ;
448     }
449 
450     return mbedtls_test_ssl_buffer_get(socket->input, buf, len);
451 }
452 
mbedtls_test_message_socket_init(mbedtls_test_message_socket_context * ctx)453 void mbedtls_test_message_socket_init(
454     mbedtls_test_message_socket_context *ctx)
455 {
456     ctx->queue_input = NULL;
457     ctx->queue_output = NULL;
458     ctx->socket = NULL;
459 }
460 
mbedtls_test_message_socket_setup(mbedtls_test_ssl_message_queue * queue_input,mbedtls_test_ssl_message_queue * queue_output,size_t queue_capacity,mbedtls_test_mock_socket * socket,mbedtls_test_message_socket_context * ctx)461 int mbedtls_test_message_socket_setup(
462     mbedtls_test_ssl_message_queue *queue_input,
463     mbedtls_test_ssl_message_queue *queue_output,
464     size_t queue_capacity,
465     mbedtls_test_mock_socket *socket,
466     mbedtls_test_message_socket_context *ctx)
467 {
468     int ret = mbedtls_test_ssl_message_queue_setup(queue_input, queue_capacity);
469     if (ret != 0) {
470         return ret;
471     }
472     ctx->queue_input = queue_input;
473     ctx->queue_output = queue_output;
474     ctx->socket = socket;
475     mbedtls_test_mock_socket_init(socket);
476 
477     return 0;
478 }
479 
mbedtls_test_message_socket_close(mbedtls_test_message_socket_context * ctx)480 void mbedtls_test_message_socket_close(
481     mbedtls_test_message_socket_context *ctx)
482 {
483     if (ctx == NULL) {
484         return;
485     }
486 
487     mbedtls_test_ssl_message_queue_free(ctx->queue_input);
488     mbedtls_test_mock_socket_close(ctx->socket);
489     memset(ctx, 0, sizeof(*ctx));
490 }
491 
mbedtls_test_mock_tcp_send_msg(void * ctx,const unsigned char * buf,size_t len)492 int mbedtls_test_mock_tcp_send_msg(void *ctx,
493                                    const unsigned char *buf, size_t len)
494 {
495     mbedtls_test_ssl_message_queue *queue;
496     mbedtls_test_mock_socket *socket;
497     mbedtls_test_message_socket_context *context =
498         (mbedtls_test_message_socket_context *) ctx;
499 
500     if (context == NULL || context->socket == NULL
501         || context->queue_output == NULL) {
502         return MBEDTLS_TEST_ERROR_CONTEXT_ERROR;
503     }
504 
505     queue = context->queue_output;
506     socket = context->socket;
507 
508     if (queue->num >= queue->capacity) {
509         return MBEDTLS_ERR_SSL_WANT_WRITE;
510     }
511 
512     if (mbedtls_test_mock_tcp_send_b(socket, buf, len) != (int) len) {
513         return MBEDTLS_TEST_ERROR_SEND_FAILED;
514     }
515 
516     return mbedtls_test_ssl_message_queue_push_info(queue, len);
517 }
518 
mbedtls_test_mock_tcp_recv_msg(void * ctx,unsigned char * buf,size_t buf_len)519 int mbedtls_test_mock_tcp_recv_msg(void *ctx,
520                                    unsigned char *buf, size_t buf_len)
521 {
522     mbedtls_test_ssl_message_queue *queue;
523     mbedtls_test_mock_socket *socket;
524     mbedtls_test_message_socket_context *context =
525         (mbedtls_test_message_socket_context *) ctx;
526     size_t drop_len = 0;
527     size_t msg_len;
528     int ret;
529 
530     if (context == NULL || context->socket == NULL
531         || context->queue_input == NULL) {
532         return MBEDTLS_TEST_ERROR_CONTEXT_ERROR;
533     }
534 
535     queue = context->queue_input;
536     socket = context->socket;
537 
538     /* Peek first, so that in case of a socket error the data remains in
539      * the queue. */
540     ret = test_ssl_message_queue_peek_info(queue, buf_len, &msg_len);
541     if (ret == MBEDTLS_TEST_ERROR_MESSAGE_TRUNCATED) {
542         /* Calculate how much to drop */
543         drop_len = msg_len - buf_len;
544 
545         /* Set the requested message len to be buffer length */
546         msg_len = buf_len;
547     } else if (ret != 0) {
548         return ret;
549     }
550 
551     if (mbedtls_test_mock_tcp_recv_b(socket, buf, msg_len) != (int) msg_len) {
552         return MBEDTLS_TEST_ERROR_RECV_FAILED;
553     }
554 
555     if (ret == MBEDTLS_TEST_ERROR_MESSAGE_TRUNCATED) {
556         /* Drop the remaining part of the message */
557         if (mbedtls_test_mock_tcp_recv_b(socket, NULL, drop_len) !=
558             (int) drop_len) {
559             /* Inconsistent state - part of the message was read,
560              * and a part couldn't. Not much we can do here, but it should not
561              * happen in test environment, unless forced manually. */
562         }
563     }
564     mbedtls_test_ssl_message_queue_pop_info(queue, buf_len);
565 
566     return (msg_len > INT_MAX) ? INT_MAX : (int) msg_len;
567 }
568 
569 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
570 
571 /*
572  * Deinitializes certificates from endpoint represented by \p ep.
573  */
test_ssl_endpoint_certificate_free(mbedtls_test_ssl_endpoint * ep)574 static void test_ssl_endpoint_certificate_free(mbedtls_test_ssl_endpoint *ep)
575 {
576     mbedtls_test_ssl_endpoint_certificate *cert = &(ep->cert);
577     if (cert != NULL) {
578         if (cert->ca_cert != NULL) {
579             mbedtls_x509_crt_free(cert->ca_cert);
580             mbedtls_free(cert->ca_cert);
581             cert->ca_cert = NULL;
582         }
583         if (cert->cert != NULL) {
584             mbedtls_x509_crt_free(cert->cert);
585             mbedtls_free(cert->cert);
586             cert->cert = NULL;
587         }
588         if (cert->pkey != NULL) {
589 #if defined(MBEDTLS_USE_PSA_CRYPTO)
590             if (mbedtls_pk_get_type(cert->pkey) == MBEDTLS_PK_OPAQUE) {
591                 psa_destroy_key(cert->pkey->priv_id);
592             }
593 #endif
594             mbedtls_pk_free(cert->pkey);
595             mbedtls_free(cert->pkey);
596             cert->pkey = NULL;
597         }
598     }
599 }
600 
mbedtls_test_ssl_endpoint_certificate_init(mbedtls_test_ssl_endpoint * ep,int pk_alg,int opaque_alg,int opaque_alg2,int opaque_usage)601 int mbedtls_test_ssl_endpoint_certificate_init(mbedtls_test_ssl_endpoint *ep,
602                                                int pk_alg,
603                                                int opaque_alg, int opaque_alg2,
604                                                int opaque_usage)
605 {
606     int i = 0;
607     int ret = -1;
608     mbedtls_test_ssl_endpoint_certificate *cert = NULL;
609 #if defined(MBEDTLS_USE_PSA_CRYPTO)
610     mbedtls_svc_key_id_t key_slot = MBEDTLS_SVC_KEY_ID_INIT;
611 #endif
612 
613     if (ep == NULL) {
614         return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
615     }
616 
617     cert = &(ep->cert);
618     TEST_CALLOC(cert->ca_cert, 1);
619     TEST_CALLOC(cert->cert, 1);
620     TEST_CALLOC(cert->pkey, 1);
621 
622     mbedtls_x509_crt_init(cert->ca_cert);
623     mbedtls_x509_crt_init(cert->cert);
624     mbedtls_pk_init(cert->pkey);
625 
626     /* Load the trusted CA */
627 
628     for (i = 0; mbedtls_test_cas_der[i] != NULL; i++) {
629         ret = mbedtls_x509_crt_parse_der(
630             cert->ca_cert,
631             (const unsigned char *) mbedtls_test_cas_der[i],
632             mbedtls_test_cas_der_len[i]);
633         TEST_ASSERT(ret == 0);
634     }
635 
636     /* Load own certificate and private key */
637 
638     if (ep->conf.endpoint == MBEDTLS_SSL_IS_SERVER) {
639         if (pk_alg == MBEDTLS_PK_RSA) {
640             ret = mbedtls_x509_crt_parse(
641                 cert->cert,
642                 (const unsigned char *) mbedtls_test_srv_crt_rsa_sha256_der,
643                 mbedtls_test_srv_crt_rsa_sha256_der_len);
644             TEST_ASSERT(ret == 0);
645 
646             ret = mbedtls_pk_parse_key(
647                 cert->pkey,
648                 (const unsigned char *) mbedtls_test_srv_key_rsa_der,
649                 mbedtls_test_srv_key_rsa_der_len, NULL, 0,
650                 mbedtls_test_rnd_std_rand, NULL);
651             TEST_ASSERT(ret == 0);
652         } else {
653             ret = mbedtls_x509_crt_parse(
654                 cert->cert,
655                 (const unsigned char *) mbedtls_test_srv_crt_ec_der,
656                 mbedtls_test_srv_crt_ec_der_len);
657             TEST_ASSERT(ret == 0);
658 
659             ret = mbedtls_pk_parse_key(
660                 cert->pkey,
661                 (const unsigned char *) mbedtls_test_srv_key_ec_der,
662                 mbedtls_test_srv_key_ec_der_len, NULL, 0,
663                 mbedtls_test_rnd_std_rand, NULL);
664             TEST_ASSERT(ret == 0);
665         }
666     } else {
667         if (pk_alg == MBEDTLS_PK_RSA) {
668             ret = mbedtls_x509_crt_parse(
669                 cert->cert,
670                 (const unsigned char *) mbedtls_test_cli_crt_rsa_der,
671                 mbedtls_test_cli_crt_rsa_der_len);
672             TEST_ASSERT(ret == 0);
673 
674             ret = mbedtls_pk_parse_key(
675                 cert->pkey,
676                 (const unsigned char *) mbedtls_test_cli_key_rsa_der,
677                 mbedtls_test_cli_key_rsa_der_len, NULL, 0,
678                 mbedtls_test_rnd_std_rand, NULL);
679             TEST_ASSERT(ret == 0);
680         } else {
681             ret = mbedtls_x509_crt_parse(
682                 cert->cert,
683                 (const unsigned char *) mbedtls_test_cli_crt_ec_der,
684                 mbedtls_test_cli_crt_ec_len);
685             TEST_ASSERT(ret == 0);
686 
687             ret = mbedtls_pk_parse_key(
688                 cert->pkey,
689                 (const unsigned char *) mbedtls_test_cli_key_ec_der,
690                 mbedtls_test_cli_key_ec_der_len, NULL, 0,
691                 mbedtls_test_rnd_std_rand, NULL);
692             TEST_ASSERT(ret == 0);
693         }
694     }
695 
696 #if defined(MBEDTLS_USE_PSA_CRYPTO)
697     if (opaque_alg != 0) {
698         TEST_EQUAL(mbedtls_pk_wrap_as_opaque(cert->pkey, &key_slot,
699                                              opaque_alg, opaque_usage,
700                                              opaque_alg2), 0);
701     }
702 #else
703     (void) opaque_alg;
704     (void) opaque_alg2;
705     (void) opaque_usage;
706 #endif
707 
708     mbedtls_ssl_conf_ca_chain(&(ep->conf), cert->ca_cert, NULL);
709 
710     ret = mbedtls_ssl_conf_own_cert(&(ep->conf), cert->cert,
711                                     cert->pkey);
712     TEST_ASSERT(ret == 0);
713     TEST_ASSERT(ep->conf.key_cert != NULL);
714 
715     ret = mbedtls_ssl_conf_own_cert(&(ep->conf), NULL, NULL);
716     TEST_ASSERT(ret == 0);
717     TEST_ASSERT(ep->conf.key_cert == NULL);
718 
719     ret = mbedtls_ssl_conf_own_cert(&(ep->conf), cert->cert,
720                                     cert->pkey);
721     TEST_ASSERT(ret == 0);
722 
723 exit:
724     if (ret != 0) {
725         test_ssl_endpoint_certificate_free(ep);
726     }
727 
728     return ret;
729 }
730 
mbedtls_test_ssl_endpoint_init(mbedtls_test_ssl_endpoint * ep,int endpoint_type,mbedtls_test_handshake_test_options * options,mbedtls_test_message_socket_context * dtls_context,mbedtls_test_ssl_message_queue * input_queue,mbedtls_test_ssl_message_queue * output_queue,uint16_t * group_list)731 int mbedtls_test_ssl_endpoint_init(
732     mbedtls_test_ssl_endpoint *ep, int endpoint_type,
733     mbedtls_test_handshake_test_options *options,
734     mbedtls_test_message_socket_context *dtls_context,
735     mbedtls_test_ssl_message_queue *input_queue,
736     mbedtls_test_ssl_message_queue *output_queue,
737     uint16_t *group_list)
738 {
739     int ret = -1;
740     uintptr_t user_data_n;
741 
742     if (dtls_context != NULL &&
743         (input_queue == NULL || output_queue == NULL)) {
744         return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
745 
746     }
747 
748     if (ep == NULL) {
749         return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
750     }
751 
752     memset(ep, 0, sizeof(*ep));
753 
754     ep->name = (endpoint_type == MBEDTLS_SSL_IS_SERVER) ? "Server" : "Client";
755 
756     mbedtls_ssl_init(&(ep->ssl));
757     mbedtls_ssl_config_init(&(ep->conf));
758     mbedtls_ssl_conf_rng(&(ep->conf), rng_get, NULL);
759 
760     TEST_ASSERT(mbedtls_ssl_conf_get_user_data_p(&ep->conf) == NULL);
761     TEST_EQUAL(mbedtls_ssl_conf_get_user_data_n(&ep->conf), 0);
762     TEST_ASSERT(mbedtls_ssl_get_user_data_p(&ep->ssl) == NULL);
763     TEST_EQUAL(mbedtls_ssl_get_user_data_n(&ep->ssl), 0);
764 
765     (void) mbedtls_test_rnd_std_rand(NULL,
766                                      (void *) &user_data_n,
767                                      sizeof(user_data_n));
768     mbedtls_ssl_conf_set_user_data_n(&ep->conf, user_data_n);
769     mbedtls_ssl_set_user_data_n(&ep->ssl, user_data_n);
770 
771     if (dtls_context != NULL) {
772         TEST_ASSERT(mbedtls_test_message_socket_setup(input_queue, output_queue,
773                                                       100, &(ep->socket),
774                                                       dtls_context) == 0);
775     } else {
776         mbedtls_test_mock_socket_init(&(ep->socket));
777     }
778 
779     /* Non-blocking callbacks without timeout */
780     if (dtls_context != NULL) {
781         mbedtls_ssl_set_bio(&(ep->ssl), dtls_context,
782                             mbedtls_test_mock_tcp_send_msg,
783                             mbedtls_test_mock_tcp_recv_msg,
784                             NULL);
785     } else {
786         mbedtls_ssl_set_bio(&(ep->ssl), &(ep->socket),
787                             mbedtls_test_mock_tcp_send_nb,
788                             mbedtls_test_mock_tcp_recv_nb,
789                             NULL);
790     }
791 
792     ret = mbedtls_ssl_config_defaults(&(ep->conf), endpoint_type,
793                                       (dtls_context != NULL) ?
794                                       MBEDTLS_SSL_TRANSPORT_DATAGRAM :
795                                       MBEDTLS_SSL_TRANSPORT_STREAM,
796                                       MBEDTLS_SSL_PRESET_DEFAULT);
797     TEST_ASSERT(ret == 0);
798 
799     if (MBEDTLS_SSL_IS_CLIENT == endpoint_type) {
800         if (options->client_min_version != MBEDTLS_SSL_VERSION_UNKNOWN) {
801             mbedtls_ssl_conf_min_tls_version(&(ep->conf),
802                                              options->client_min_version);
803         }
804 
805         if (options->client_max_version != MBEDTLS_SSL_VERSION_UNKNOWN) {
806             mbedtls_ssl_conf_max_tls_version(&(ep->conf),
807                                              options->client_max_version);
808         }
809     } else {
810         if (options->server_min_version != MBEDTLS_SSL_VERSION_UNKNOWN) {
811             mbedtls_ssl_conf_min_tls_version(&(ep->conf),
812                                              options->server_min_version);
813         }
814 
815         if (options->server_max_version != MBEDTLS_SSL_VERSION_UNKNOWN) {
816             mbedtls_ssl_conf_max_tls_version(&(ep->conf),
817                                              options->server_max_version);
818         }
819     }
820 
821     if (group_list != NULL) {
822         mbedtls_ssl_conf_groups(&(ep->conf), group_list);
823     }
824 
825     mbedtls_ssl_conf_authmode(&(ep->conf), MBEDTLS_SSL_VERIFY_REQUIRED);
826 
827 #if defined(MBEDTLS_SSL_CACHE_C) && defined(MBEDTLS_SSL_SRV_C)
828     if (endpoint_type == MBEDTLS_SSL_IS_SERVER && options->cache != NULL) {
829         mbedtls_ssl_conf_session_cache(&(ep->conf), options->cache,
830                                        mbedtls_ssl_cache_get,
831                                        mbedtls_ssl_cache_set);
832     }
833 #endif
834 
835     ret = mbedtls_ssl_setup(&(ep->ssl), &(ep->conf));
836     TEST_ASSERT(ret == 0);
837 
838 #if defined(MBEDTLS_SSL_PROTO_DTLS) && defined(MBEDTLS_SSL_SRV_C)
839     if (endpoint_type == MBEDTLS_SSL_IS_SERVER && dtls_context != NULL) {
840         mbedtls_ssl_conf_dtls_cookies(&(ep->conf), NULL, NULL, NULL);
841     }
842 #endif
843 
844     ret = mbedtls_test_ssl_endpoint_certificate_init(ep, options->pk_alg,
845                                                      options->opaque_alg,
846                                                      options->opaque_alg2,
847                                                      options->opaque_usage);
848     TEST_ASSERT(ret == 0);
849 
850     TEST_EQUAL(mbedtls_ssl_conf_get_user_data_n(&ep->conf), user_data_n);
851     mbedtls_ssl_conf_set_user_data_p(&ep->conf, ep);
852     TEST_EQUAL(mbedtls_ssl_get_user_data_n(&ep->ssl), user_data_n);
853     mbedtls_ssl_set_user_data_p(&ep->ssl, ep);
854 
855 exit:
856     return ret;
857 }
858 
mbedtls_test_ssl_endpoint_free(mbedtls_test_ssl_endpoint * ep,mbedtls_test_message_socket_context * context)859 void mbedtls_test_ssl_endpoint_free(
860     mbedtls_test_ssl_endpoint *ep,
861     mbedtls_test_message_socket_context *context)
862 {
863     test_ssl_endpoint_certificate_free(ep);
864 
865     mbedtls_ssl_free(&(ep->ssl));
866     mbedtls_ssl_config_free(&(ep->conf));
867 
868     if (context != NULL) {
869         mbedtls_test_message_socket_close(context);
870     } else {
871         mbedtls_test_mock_socket_close(&(ep->socket));
872     }
873 }
874 
mbedtls_test_move_handshake_to_state(mbedtls_ssl_context * ssl,mbedtls_ssl_context * second_ssl,int state)875 int mbedtls_test_move_handshake_to_state(mbedtls_ssl_context *ssl,
876                                          mbedtls_ssl_context *second_ssl,
877                                          int state)
878 {
879     enum { BUFFSIZE = 1024 };
880     int max_steps = 1000;
881     int ret = 0;
882 
883     if (ssl == NULL || second_ssl == NULL) {
884         return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
885     }
886 
887     /* Perform communication via connected sockets */
888     while ((ssl->state != state) && (--max_steps >= 0)) {
889         /* If /p second_ssl ends the handshake procedure before /p ssl then
890          * there is no need to call the next step */
891         if (!mbedtls_ssl_is_handshake_over(second_ssl)) {
892             ret = mbedtls_ssl_handshake_step(second_ssl);
893             if (ret != 0 && ret != MBEDTLS_ERR_SSL_WANT_READ &&
894                 ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
895                 return ret;
896             }
897         }
898 
899         /* We only care about the \p ssl state and returns, so we call it last,
900          * to leave the iteration as soon as the state is as expected. */
901         ret = mbedtls_ssl_handshake_step(ssl);
902         if (ret != 0 && ret != MBEDTLS_ERR_SSL_WANT_READ &&
903             ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
904             return ret;
905         }
906     }
907 
908     return (max_steps >= 0) ? ret : -1;
909 }
910 
911 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
912 
913 /*
914  * Write application data. Increase write counter if necessary.
915  */
mbedtls_ssl_write_fragment(mbedtls_ssl_context * ssl,unsigned char * buf,int buf_len,int * written,const int expected_fragments)916 int mbedtls_ssl_write_fragment(mbedtls_ssl_context *ssl,
917                                unsigned char *buf, int buf_len,
918                                int *written,
919                                const int expected_fragments)
920 {
921     int ret;
922     /* Verify that calling mbedtls_ssl_write with a NULL buffer and zero length is
923      * a valid no-op for TLS connections. */
924     if (ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
925         TEST_ASSERT(mbedtls_ssl_write(ssl, NULL, 0) == 0);
926     }
927 
928     ret = mbedtls_ssl_write(ssl, buf + *written, buf_len - *written);
929     if (ret > 0) {
930         *written += ret;
931     }
932 
933     if (expected_fragments == 0) {
934         /* Used for DTLS and the message size larger than MFL. In that case
935          * the message can not be fragmented and the library should return
936          * MBEDTLS_ERR_SSL_BAD_INPUT_DATA error. This error must be returned
937          * to prevent a dead loop inside mbedtls_test_ssl_exchange_data(). */
938         return ret;
939     } else if (expected_fragments == 1) {
940         /* Used for TLS/DTLS and the message size lower than MFL */
941         TEST_ASSERT(ret == buf_len ||
942                     ret == MBEDTLS_ERR_SSL_WANT_READ ||
943                     ret == MBEDTLS_ERR_SSL_WANT_WRITE);
944     } else {
945         /* Used for TLS and the message size larger than MFL */
946         TEST_ASSERT(expected_fragments > 1);
947         TEST_ASSERT((ret >= 0 && ret <= buf_len) ||
948                     ret == MBEDTLS_ERR_SSL_WANT_READ ||
949                     ret == MBEDTLS_ERR_SSL_WANT_WRITE);
950     }
951 
952     return 0;
953 
954 exit:
955     /* Some of the tests failed */
956     return -1;
957 }
958 
959 /*
960  * Read application data and increase read counter and fragments counter
961  * if necessary.
962  */
mbedtls_ssl_read_fragment(mbedtls_ssl_context * ssl,unsigned char * buf,int buf_len,int * read,int * fragments,const int expected_fragments)963 int mbedtls_ssl_read_fragment(mbedtls_ssl_context *ssl,
964                               unsigned char *buf, int buf_len,
965                               int *read, int *fragments,
966                               const int expected_fragments)
967 {
968     int ret;
969     /* Verify that calling mbedtls_ssl_write with a NULL buffer and zero length is
970      * a valid no-op for TLS connections. */
971     if (ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
972         TEST_ASSERT(mbedtls_ssl_read(ssl, NULL, 0) == 0);
973     }
974 
975     ret = mbedtls_ssl_read(ssl, buf + *read, buf_len - *read);
976     if (ret > 0) {
977         (*fragments)++;
978         *read += ret;
979     }
980 
981     if (expected_fragments == 0) {
982         TEST_ASSERT(ret == 0);
983     } else if (expected_fragments == 1) {
984         TEST_ASSERT(ret == buf_len ||
985                     ret == MBEDTLS_ERR_SSL_WANT_READ ||
986                     ret == MBEDTLS_ERR_SSL_WANT_WRITE);
987     } else {
988         TEST_ASSERT(expected_fragments > 1);
989         TEST_ASSERT((ret >= 0 && ret <= buf_len) ||
990                     ret == MBEDTLS_ERR_SSL_WANT_READ ||
991                     ret == MBEDTLS_ERR_SSL_WANT_WRITE);
992     }
993 
994     return 0;
995 
996 exit:
997     /* Some of the tests failed */
998     return -1;
999 }
1000 
1001 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
set_ciphersuite(mbedtls_ssl_config * conf,const char * cipher,int * forced_ciphersuite)1002 static void set_ciphersuite(mbedtls_ssl_config *conf, const char *cipher,
1003                             int *forced_ciphersuite)
1004 {
1005     const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
1006     forced_ciphersuite[0] = mbedtls_ssl_get_ciphersuite_id(cipher);
1007     forced_ciphersuite[1] = 0;
1008 
1009     ciphersuite_info =
1010         mbedtls_ssl_ciphersuite_from_id(forced_ciphersuite[0]);
1011 
1012     TEST_ASSERT(ciphersuite_info != NULL);
1013     TEST_ASSERT(ciphersuite_info->min_tls_version <= conf->max_tls_version);
1014     TEST_ASSERT(ciphersuite_info->max_tls_version >= conf->min_tls_version);
1015 
1016     if (conf->max_tls_version > ciphersuite_info->max_tls_version) {
1017         conf->max_tls_version = (mbedtls_ssl_protocol_version) ciphersuite_info->max_tls_version;
1018     }
1019     if (conf->min_tls_version < ciphersuite_info->min_tls_version) {
1020         conf->min_tls_version = (mbedtls_ssl_protocol_version) ciphersuite_info->min_tls_version;
1021     }
1022 
1023     mbedtls_ssl_conf_ciphersuites(conf, forced_ciphersuite);
1024 
1025 exit:
1026     return;
1027 }
1028 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
1029 
1030 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED) && \
1031     defined(MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED)  && \
1032     defined(MBEDTLS_SSL_SRV_C)
psk_dummy_callback(void * p_info,mbedtls_ssl_context * ssl,const unsigned char * name,size_t name_len)1033 static int psk_dummy_callback(void *p_info, mbedtls_ssl_context *ssl,
1034                               const unsigned char *name, size_t name_len)
1035 {
1036     (void) p_info;
1037     (void) ssl;
1038     (void) name;
1039     (void) name_len;
1040 
1041     return 0;
1042 }
1043 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED &&
1044           MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED  &&
1045           MBEDTLS_SSL_SRV_C */
1046 
1047 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
1048     defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_AES_C)
mbedtls_test_psa_cipher_encrypt_helper(mbedtls_ssl_transform * transform,const unsigned char * iv,size_t iv_len,const unsigned char * input,size_t ilen,unsigned char * output,size_t * olen)1049 int mbedtls_test_psa_cipher_encrypt_helper(mbedtls_ssl_transform *transform,
1050                                            const unsigned char *iv,
1051                                            size_t iv_len,
1052                                            const unsigned char *input,
1053                                            size_t ilen,
1054                                            unsigned char *output,
1055                                            size_t *olen)
1056 {
1057 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1058     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
1059     psa_cipher_operation_t cipher_op = PSA_CIPHER_OPERATION_INIT;
1060     size_t part_len;
1061 
1062     status = psa_cipher_encrypt_setup(&cipher_op,
1063                                       transform->psa_key_enc,
1064                                       transform->psa_alg);
1065 
1066     if (status != PSA_SUCCESS) {
1067         return PSA_TO_MBEDTLS_ERR(status);
1068     }
1069 
1070     status = psa_cipher_set_iv(&cipher_op, iv, iv_len);
1071 
1072     if (status != PSA_SUCCESS) {
1073         return PSA_TO_MBEDTLS_ERR(status);
1074     }
1075 
1076     status = psa_cipher_update(&cipher_op, input, ilen, output, ilen, olen);
1077 
1078     if (status != PSA_SUCCESS) {
1079         return PSA_TO_MBEDTLS_ERR(status);
1080     }
1081 
1082     status = psa_cipher_finish(&cipher_op, output + *olen, ilen - *olen,
1083                                &part_len);
1084 
1085     if (status != PSA_SUCCESS) {
1086         return PSA_TO_MBEDTLS_ERR(status);
1087     }
1088 
1089     *olen += part_len;
1090     return 0;
1091 #else
1092     return mbedtls_cipher_crypt(&transform->cipher_ctx_enc,
1093                                 iv, iv_len, input, ilen, output, olen);
1094 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1095 }
1096 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 && MBEDTLS_CIPHER_MODE_CBC &&
1097           MBEDTLS_AES_C */
1098 
mbedtls_test_ssl_build_transforms(mbedtls_ssl_transform * t_in,mbedtls_ssl_transform * t_out,int cipher_type,int hash_id,int etm,int tag_mode,mbedtls_ssl_protocol_version tls_version,size_t cid0_len,size_t cid1_len)1099 int mbedtls_test_ssl_build_transforms(mbedtls_ssl_transform *t_in,
1100                                       mbedtls_ssl_transform *t_out,
1101                                       int cipher_type, int hash_id,
1102                                       int etm, int tag_mode,
1103                                       mbedtls_ssl_protocol_version tls_version,
1104                                       size_t cid0_len,
1105                                       size_t cid1_len)
1106 {
1107     mbedtls_cipher_info_t const *cipher_info;
1108     int ret = 0;
1109 
1110 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1111     psa_key_type_t key_type;
1112     psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
1113     psa_algorithm_t alg;
1114     size_t key_bits;
1115     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
1116 #endif
1117 
1118     size_t keylen, maclen, ivlen;
1119     unsigned char *key0 = NULL, *key1 = NULL;
1120     unsigned char *md0 = NULL, *md1 = NULL;
1121     unsigned char iv_enc[16], iv_dec[16];
1122 
1123 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
1124     unsigned char cid0[SSL_CID_LEN_MIN];
1125     unsigned char cid1[SSL_CID_LEN_MIN];
1126 
1127     mbedtls_test_rnd_std_rand(NULL, cid0, sizeof(cid0));
1128     mbedtls_test_rnd_std_rand(NULL, cid1, sizeof(cid1));
1129 #else
1130     ((void) cid0_len);
1131     ((void) cid1_len);
1132 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1133 
1134     maclen = 0;
1135 
1136     /* Pick cipher */
1137     cipher_info = mbedtls_cipher_info_from_type((mbedtls_cipher_type_t) cipher_type);
1138     CHK(cipher_info != NULL);
1139     CHK(mbedtls_cipher_info_get_iv_size(cipher_info) <= 16);
1140     CHK(mbedtls_cipher_info_get_key_bitlen(cipher_info) % 8 == 0);
1141 
1142     /* Pick keys */
1143     keylen = mbedtls_cipher_info_get_key_bitlen(cipher_info) / 8;
1144     /* Allocate `keylen + 1` bytes to ensure that we get
1145      * a non-NULL pointers from `mbedtls_calloc` even if
1146      * `keylen == 0` in the case of the NULL cipher. */
1147     CHK((key0 = mbedtls_calloc(1, keylen + 1)) != NULL);
1148     CHK((key1 = mbedtls_calloc(1, keylen + 1)) != NULL);
1149     memset(key0, 0x1, keylen);
1150     memset(key1, 0x2, keylen);
1151 
1152 #if !defined(MBEDTLS_USE_PSA_CRYPTO)
1153     /* Setup cipher contexts */
1154     CHK(mbedtls_cipher_setup(&t_in->cipher_ctx_enc,  cipher_info) == 0);
1155     CHK(mbedtls_cipher_setup(&t_in->cipher_ctx_dec,  cipher_info) == 0);
1156     CHK(mbedtls_cipher_setup(&t_out->cipher_ctx_enc, cipher_info) == 0);
1157     CHK(mbedtls_cipher_setup(&t_out->cipher_ctx_dec, cipher_info) == 0);
1158 
1159 #if defined(MBEDTLS_CIPHER_MODE_CBC)
1160     if (cipher_info->mode == MBEDTLS_MODE_CBC) {
1161         CHK(mbedtls_cipher_set_padding_mode(&t_in->cipher_ctx_enc,
1162                                             MBEDTLS_PADDING_NONE) == 0);
1163         CHK(mbedtls_cipher_set_padding_mode(&t_in->cipher_ctx_dec,
1164                                             MBEDTLS_PADDING_NONE) == 0);
1165         CHK(mbedtls_cipher_set_padding_mode(&t_out->cipher_ctx_enc,
1166                                             MBEDTLS_PADDING_NONE) == 0);
1167         CHK(mbedtls_cipher_set_padding_mode(&t_out->cipher_ctx_dec,
1168                                             MBEDTLS_PADDING_NONE) == 0);
1169     }
1170 #endif /* MBEDTLS_CIPHER_MODE_CBC */
1171 
1172     CHK(mbedtls_cipher_setkey(&t_in->cipher_ctx_enc, key0,
1173                               (keylen << 3 > INT_MAX) ? INT_MAX : (int) keylen << 3,
1174                               MBEDTLS_ENCRYPT)
1175         == 0);
1176     CHK(mbedtls_cipher_setkey(&t_in->cipher_ctx_dec, key1,
1177                               (keylen << 3 > INT_MAX) ? INT_MAX : (int) keylen << 3,
1178                               MBEDTLS_DECRYPT)
1179         == 0);
1180     CHK(mbedtls_cipher_setkey(&t_out->cipher_ctx_enc, key1,
1181                               (keylen << 3 > INT_MAX) ? INT_MAX : (int) keylen << 3,
1182                               MBEDTLS_ENCRYPT)
1183         == 0);
1184     CHK(mbedtls_cipher_setkey(&t_out->cipher_ctx_dec, key0,
1185                               (keylen << 3 > INT_MAX) ? INT_MAX : (int) keylen << 3,
1186                               MBEDTLS_DECRYPT)
1187         == 0);
1188 #endif
1189 
1190     /* Setup MAC contexts */
1191 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_MAC)
1192     if (cipher_info->mode == MBEDTLS_MODE_CBC ||
1193         cipher_info->mode == MBEDTLS_MODE_STREAM) {
1194 #if !defined(MBEDTLS_USE_PSA_CRYPTO)
1195         mbedtls_md_info_t const *md_info = mbedtls_md_info_from_type((mbedtls_md_type_t) hash_id);
1196         CHK(md_info != NULL);
1197 #endif
1198         maclen = mbedtls_md_get_size_from_type((mbedtls_md_type_t) hash_id);
1199         CHK(maclen != 0);
1200         /* Pick hash keys */
1201         CHK((md0 = mbedtls_calloc(1, maclen)) != NULL);
1202         CHK((md1 = mbedtls_calloc(1, maclen)) != NULL);
1203         memset(md0, 0x5, maclen);
1204         memset(md1, 0x6, maclen);
1205 
1206 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1207         alg = mbedtls_md_psa_alg_from_type(hash_id);
1208 
1209         CHK(alg != 0);
1210 
1211         t_out->psa_mac_alg = PSA_ALG_HMAC(alg);
1212         t_in->psa_mac_alg = PSA_ALG_HMAC(alg);
1213         t_in->psa_mac_enc = MBEDTLS_SVC_KEY_ID_INIT;
1214         t_out->psa_mac_enc = MBEDTLS_SVC_KEY_ID_INIT;
1215         t_in->psa_mac_dec = MBEDTLS_SVC_KEY_ID_INIT;
1216         t_out->psa_mac_dec = MBEDTLS_SVC_KEY_ID_INIT;
1217 
1218         psa_reset_key_attributes(&attributes);
1219         psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_MESSAGE);
1220         psa_set_key_algorithm(&attributes, PSA_ALG_HMAC(alg));
1221         psa_set_key_type(&attributes, PSA_KEY_TYPE_HMAC);
1222 
1223         CHK(psa_import_key(&attributes,
1224                            md0, maclen,
1225                            &t_in->psa_mac_enc) == PSA_SUCCESS);
1226 
1227         CHK(psa_import_key(&attributes,
1228                            md1, maclen,
1229                            &t_out->psa_mac_enc) == PSA_SUCCESS);
1230 
1231         if (cipher_info->mode == MBEDTLS_MODE_STREAM ||
1232             etm == MBEDTLS_SSL_ETM_DISABLED) {
1233             /* mbedtls_ct_hmac() requires the key to be exportable */
1234             psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_EXPORT |
1235                                     PSA_KEY_USAGE_VERIFY_HASH);
1236         } else {
1237             psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_VERIFY_HASH);
1238         }
1239 
1240         CHK(psa_import_key(&attributes,
1241                            md1, maclen,
1242                            &t_in->psa_mac_dec) == PSA_SUCCESS);
1243 
1244         CHK(psa_import_key(&attributes,
1245                            md0, maclen,
1246                            &t_out->psa_mac_dec) == PSA_SUCCESS);
1247 #else
1248         CHK(mbedtls_md_setup(&t_out->md_ctx_enc, md_info, 1) == 0);
1249         CHK(mbedtls_md_setup(&t_out->md_ctx_dec, md_info, 1) == 0);
1250         CHK(mbedtls_md_setup(&t_in->md_ctx_enc,  md_info, 1) == 0);
1251         CHK(mbedtls_md_setup(&t_in->md_ctx_dec,  md_info, 1) == 0);
1252 
1253         CHK(mbedtls_md_hmac_starts(&t_in->md_ctx_enc,
1254                                    md0, maclen) == 0);
1255         CHK(mbedtls_md_hmac_starts(&t_in->md_ctx_dec,
1256                                    md1, maclen) == 0);
1257         CHK(mbedtls_md_hmac_starts(&t_out->md_ctx_enc,
1258                                    md1, maclen) == 0);
1259         CHK(mbedtls_md_hmac_starts(&t_out->md_ctx_dec,
1260                                    md0, maclen) == 0);
1261 #endif
1262     }
1263 #else
1264     ((void) hash_id);
1265 #endif /* MBEDTLS_SSL_SOME_SUITES_USE_MAC */
1266 
1267 
1268     /* Pick IV's (regardless of whether they
1269      * are being used by the transform). */
1270     ivlen = mbedtls_cipher_info_get_iv_size(cipher_info);
1271     memset(iv_enc, 0x3, sizeof(iv_enc));
1272     memset(iv_dec, 0x4, sizeof(iv_dec));
1273 
1274     /*
1275      * Setup transforms
1276      */
1277 
1278 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) && \
1279     defined(MBEDTLS_SSL_SOME_SUITES_USE_MAC)
1280     t_out->encrypt_then_mac = etm;
1281     t_in->encrypt_then_mac = etm;
1282 #else
1283     ((void) etm);
1284 #endif
1285 
1286     t_out->tls_version = tls_version;
1287     t_in->tls_version = tls_version;
1288     t_out->ivlen = ivlen;
1289     t_in->ivlen = ivlen;
1290 
1291     switch (cipher_info->mode) {
1292         case MBEDTLS_MODE_GCM:
1293         case MBEDTLS_MODE_CCM:
1294 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
1295             if (tls_version == MBEDTLS_SSL_VERSION_TLS1_3) {
1296                 t_out->fixed_ivlen = 12;
1297                 t_in->fixed_ivlen  = 12;
1298             } else
1299 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
1300             {
1301                 t_out->fixed_ivlen = 4;
1302                 t_in->fixed_ivlen = 4;
1303             }
1304             t_out->maclen = 0;
1305             t_in->maclen = 0;
1306             switch (tag_mode) {
1307                 case 0: /* Full tag */
1308                     t_out->taglen = 16;
1309                     t_in->taglen = 16;
1310                     break;
1311                 case 1: /* Partial tag */
1312                     t_out->taglen = 8;
1313                     t_in->taglen = 8;
1314                     break;
1315                 default:
1316                     ret = 1;
1317                     goto cleanup;
1318             }
1319             break;
1320 
1321         case MBEDTLS_MODE_CHACHAPOLY:
1322             t_out->fixed_ivlen = 12;
1323             t_in->fixed_ivlen = 12;
1324             t_out->maclen = 0;
1325             t_in->maclen = 0;
1326             switch (tag_mode) {
1327                 case 0: /* Full tag */
1328                     t_out->taglen = 16;
1329                     t_in->taglen = 16;
1330                     break;
1331                 case 1: /* Partial tag */
1332                     t_out->taglen = 8;
1333                     t_in->taglen = 8;
1334                     break;
1335                 default:
1336                     ret = 1;
1337                     goto cleanup;
1338             }
1339             break;
1340 
1341         case MBEDTLS_MODE_STREAM:
1342         case MBEDTLS_MODE_CBC:
1343             t_out->fixed_ivlen = 0; /* redundant, must be 0 */
1344             t_in->fixed_ivlen = 0;  /* redundant, must be 0 */
1345             t_out->taglen = 0;
1346             t_in->taglen = 0;
1347             switch (tag_mode) {
1348                 case 0: /* Full tag */
1349                     t_out->maclen = maclen;
1350                     t_in->maclen = maclen;
1351                     break;
1352                 default:
1353                     ret = 1;
1354                     goto cleanup;
1355             }
1356             break;
1357         default:
1358             ret = 1;
1359             goto cleanup;
1360             break;
1361     }
1362 
1363     /* Setup IV's */
1364 
1365     memcpy(&t_in->iv_dec, iv_dec, sizeof(iv_dec));
1366     memcpy(&t_in->iv_enc, iv_enc, sizeof(iv_enc));
1367     memcpy(&t_out->iv_dec, iv_enc, sizeof(iv_enc));
1368     memcpy(&t_out->iv_enc, iv_dec, sizeof(iv_dec));
1369 
1370 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
1371     /* Add CID */
1372     memcpy(&t_in->in_cid,  cid0, cid0_len);
1373     memcpy(&t_in->out_cid, cid1, cid1_len);
1374     t_in->in_cid_len = (uint8_t) cid0_len;
1375     t_in->out_cid_len = (uint8_t) cid1_len;
1376     memcpy(&t_out->in_cid,  cid1, cid1_len);
1377     memcpy(&t_out->out_cid, cid0, cid0_len);
1378     t_out->in_cid_len = (uint8_t) cid1_len;
1379     t_out->out_cid_len = (uint8_t) cid0_len;
1380 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1381 
1382 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1383     status = mbedtls_ssl_cipher_to_psa(cipher_type,
1384                                        t_in->taglen,
1385                                        &alg,
1386                                        &key_type,
1387                                        &key_bits);
1388 
1389     if (status != PSA_SUCCESS) {
1390         ret = PSA_TO_MBEDTLS_ERR(status);
1391         goto cleanup;
1392     }
1393 
1394     t_in->psa_alg = alg;
1395     t_out->psa_alg = alg;
1396 
1397     if (alg != MBEDTLS_SSL_NULL_CIPHER) {
1398         psa_reset_key_attributes(&attributes);
1399         psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_ENCRYPT);
1400         psa_set_key_algorithm(&attributes, alg);
1401         psa_set_key_type(&attributes, key_type);
1402 
1403         status = psa_import_key(&attributes,
1404                                 key0,
1405                                 PSA_BITS_TO_BYTES(key_bits),
1406                                 &t_in->psa_key_enc);
1407 
1408         if (status != PSA_SUCCESS) {
1409             ret = PSA_TO_MBEDTLS_ERR(status);
1410             goto cleanup;
1411         }
1412 
1413         status = psa_import_key(&attributes,
1414                                 key1,
1415                                 PSA_BITS_TO_BYTES(key_bits),
1416                                 &t_out->psa_key_enc);
1417 
1418         if (status != PSA_SUCCESS) {
1419             ret = PSA_TO_MBEDTLS_ERR(status);
1420             goto cleanup;
1421         }
1422 
1423         psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_DECRYPT);
1424 
1425         status = psa_import_key(&attributes,
1426                                 key1,
1427                                 PSA_BITS_TO_BYTES(key_bits),
1428                                 &t_in->psa_key_dec);
1429 
1430         if (status != PSA_SUCCESS) {
1431             ret = PSA_TO_MBEDTLS_ERR(status);
1432             goto cleanup;
1433         }
1434 
1435         status = psa_import_key(&attributes,
1436                                 key0,
1437                                 PSA_BITS_TO_BYTES(key_bits),
1438                                 &t_out->psa_key_dec);
1439 
1440         if (status != PSA_SUCCESS) {
1441             ret = PSA_TO_MBEDTLS_ERR(status);
1442             goto cleanup;
1443         }
1444     }
1445 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1446 
1447 cleanup:
1448 
1449     mbedtls_free(key0);
1450     mbedtls_free(key1);
1451 
1452     mbedtls_free(md0);
1453     mbedtls_free(md1);
1454 
1455     return ret;
1456 }
1457 
1458 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_MAC)
mbedtls_test_ssl_prepare_record_mac(mbedtls_record * record,mbedtls_ssl_transform * transform_out)1459 int mbedtls_test_ssl_prepare_record_mac(mbedtls_record *record,
1460                                         mbedtls_ssl_transform *transform_out)
1461 {
1462 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1463     psa_mac_operation_t operation = PSA_MAC_OPERATION_INIT;
1464 #endif
1465 
1466     /* Serialized version of record header for MAC purposes */
1467     unsigned char add_data[13];
1468     memcpy(add_data, record->ctr, 8);
1469     add_data[8] = record->type;
1470     add_data[9] = record->ver[0];
1471     add_data[10] = record->ver[1];
1472     add_data[11] = (record->data_len >> 8) & 0xff;
1473     add_data[12] = (record->data_len >> 0) & 0xff;
1474 
1475     /* MAC with additional data */
1476 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1477     size_t sign_mac_length = 0;
1478     TEST_EQUAL(PSA_SUCCESS, psa_mac_sign_setup(&operation,
1479                                                transform_out->psa_mac_enc,
1480                                                transform_out->psa_mac_alg));
1481     TEST_EQUAL(PSA_SUCCESS, psa_mac_update(&operation, add_data, 13));
1482     TEST_EQUAL(PSA_SUCCESS, psa_mac_update(&operation,
1483                                            record->buf + record->data_offset,
1484                                            record->data_len));
1485     /* Use a temporary buffer for the MAC, because with the truncated HMAC
1486      * extension, there might not be enough room in the record for the
1487      * full-length MAC. */
1488     unsigned char mac[PSA_HASH_MAX_SIZE];
1489     TEST_EQUAL(PSA_SUCCESS, psa_mac_sign_finish(&operation,
1490                                                 mac, sizeof(mac),
1491                                                 &sign_mac_length));
1492 #else
1493     TEST_EQUAL(0, mbedtls_md_hmac_update(&transform_out->md_ctx_enc, add_data, 13));
1494     TEST_EQUAL(0, mbedtls_md_hmac_update(&transform_out->md_ctx_enc,
1495                                          record->buf + record->data_offset,
1496                                          record->data_len));
1497     /* Use a temporary buffer for the MAC, because with the truncated HMAC
1498      * extension, there might not be enough room in the record for the
1499      * full-length MAC. */
1500     unsigned char mac[MBEDTLS_MD_MAX_SIZE];
1501     TEST_EQUAL(0, mbedtls_md_hmac_finish(&transform_out->md_ctx_enc, mac));
1502 #endif
1503     memcpy(record->buf + record->data_offset + record->data_len, mac, transform_out->maclen);
1504     record->data_len += transform_out->maclen;
1505 
1506     return 0;
1507 
1508 exit:
1509 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1510     psa_mac_abort(&operation);
1511 #endif
1512     return -1;
1513 }
1514 #endif /* MBEDTLS_SSL_SOME_SUITES_USE_MAC */
1515 
mbedtls_test_ssl_tls12_populate_session(mbedtls_ssl_session * session,int ticket_len,const char * crt_file)1516 int mbedtls_test_ssl_tls12_populate_session(mbedtls_ssl_session *session,
1517                                             int ticket_len,
1518                                             const char *crt_file)
1519 {
1520 #if defined(MBEDTLS_HAVE_TIME)
1521     session->start = mbedtls_time(NULL) - 42;
1522 #endif
1523     session->tls_version = MBEDTLS_SSL_VERSION_TLS1_2;
1524     session->ciphersuite = 0xabcd;
1525     session->id_len = sizeof(session->id);
1526     memset(session->id, 66, session->id_len);
1527     memset(session->master, 17, sizeof(session->master));
1528 
1529 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED) && defined(MBEDTLS_FS_IO)
1530     if (crt_file != NULL && strlen(crt_file) != 0) {
1531         mbedtls_x509_crt tmp_crt;
1532         int ret;
1533 
1534         mbedtls_x509_crt_init(&tmp_crt);
1535         ret = mbedtls_x509_crt_parse_file(&tmp_crt, crt_file);
1536         if (ret != 0) {
1537             return ret;
1538         }
1539 
1540 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
1541         /* Move temporary CRT. */
1542         session->peer_cert = mbedtls_calloc(1, sizeof(*session->peer_cert));
1543         if (session->peer_cert == NULL) {
1544             return -1;
1545         }
1546         *session->peer_cert = tmp_crt;
1547         memset(&tmp_crt, 0, sizeof(tmp_crt));
1548 #else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
1549         /* Calculate digest of temporary CRT. */
1550         session->peer_cert_digest =
1551             mbedtls_calloc(1, MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_LEN);
1552         if (session->peer_cert_digest == NULL) {
1553             return -1;
1554         }
1555 
1556 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1557         psa_algorithm_t psa_alg = mbedtls_md_psa_alg_from_type(
1558             MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_TYPE);
1559         size_t hash_size = 0;
1560         psa_status_t status = psa_hash_compute(
1561             psa_alg, tmp_crt.raw.p,
1562             tmp_crt.raw.len,
1563             session->peer_cert_digest,
1564             MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_LEN,
1565             &hash_size);
1566         ret = PSA_TO_MBEDTLS_ERR(status);
1567 #else
1568         ret = mbedtls_md(mbedtls_md_info_from_type(
1569                              MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_TYPE),
1570                          tmp_crt.raw.p, tmp_crt.raw.len,
1571                          session->peer_cert_digest);
1572 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1573         if (ret != 0) {
1574             return ret;
1575         }
1576         session->peer_cert_digest_type =
1577             MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_TYPE;
1578         session->peer_cert_digest_len =
1579             MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_LEN;
1580 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
1581 
1582         mbedtls_x509_crt_free(&tmp_crt);
1583     }
1584 #else /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED && MBEDTLS_FS_IO */
1585     (void) crt_file;
1586 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED && MBEDTLS_FS_IO */
1587     session->verify_result = 0xdeadbeef;
1588 
1589 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
1590     if (ticket_len != 0) {
1591         session->ticket = mbedtls_calloc(1, ticket_len);
1592         if (session->ticket == NULL) {
1593             return -1;
1594         }
1595         memset(session->ticket, 33, ticket_len);
1596     }
1597     session->ticket_len = ticket_len;
1598     session->ticket_lifetime = 86401;
1599 #else
1600     (void) ticket_len;
1601 #endif
1602 
1603 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
1604     session->mfl_code = 1;
1605 #endif
1606 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
1607     session->encrypt_then_mac = 1;
1608 #endif
1609 
1610     return 0;
1611 }
1612 
1613 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
mbedtls_test_ssl_tls13_populate_session(mbedtls_ssl_session * session,int ticket_len,int endpoint_type)1614 int mbedtls_test_ssl_tls13_populate_session(mbedtls_ssl_session *session,
1615                                             int ticket_len,
1616                                             int endpoint_type)
1617 {
1618     ((void) ticket_len);
1619     session->tls_version = MBEDTLS_SSL_VERSION_TLS1_3;
1620     session->endpoint = endpoint_type == MBEDTLS_SSL_IS_CLIENT ?
1621                         MBEDTLS_SSL_IS_CLIENT : MBEDTLS_SSL_IS_SERVER;
1622     session->ciphersuite = 0xabcd;
1623     session->ticket_age_add = 0x87654321;
1624     session->ticket_flags = 0x7;
1625 
1626     session->resumption_key_len = 32;
1627     memset(session->resumption_key, 0x99, sizeof(session->resumption_key));
1628 
1629 #if defined(MBEDTLS_HAVE_TIME)
1630     if (session->endpoint == MBEDTLS_SSL_IS_SERVER) {
1631         session->start = mbedtls_time(NULL) - 42;
1632     }
1633 #endif
1634 
1635 #if defined(MBEDTLS_SSL_CLI_C)
1636     if (session->endpoint == MBEDTLS_SSL_IS_CLIENT) {
1637 #if defined(MBEDTLS_HAVE_TIME)
1638         session->ticket_received = mbedtls_time(NULL) - 40;
1639 #endif
1640         session->ticket_lifetime = 0xfedcba98;
1641 
1642         session->ticket_len = ticket_len;
1643         if (ticket_len != 0) {
1644             session->ticket = mbedtls_calloc(1, ticket_len);
1645             if (session->ticket == NULL) {
1646                 return -1;
1647             }
1648             memset(session->ticket, 33, ticket_len);
1649         }
1650     }
1651 #endif /* MBEDTLS_SSL_CLI_C */
1652 
1653     return 0;
1654 }
1655 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
1656 
mbedtls_test_ssl_exchange_data(mbedtls_ssl_context * ssl_1,int msg_len_1,const int expected_fragments_1,mbedtls_ssl_context * ssl_2,int msg_len_2,const int expected_fragments_2)1657 int mbedtls_test_ssl_exchange_data(
1658     mbedtls_ssl_context *ssl_1,
1659     int msg_len_1, const int expected_fragments_1,
1660     mbedtls_ssl_context *ssl_2,
1661     int msg_len_2, const int expected_fragments_2)
1662 {
1663     unsigned char *msg_buf_1 = malloc(msg_len_1);
1664     unsigned char *msg_buf_2 = malloc(msg_len_2);
1665     unsigned char *in_buf_1  = malloc(msg_len_2);
1666     unsigned char *in_buf_2  = malloc(msg_len_1);
1667     int msg_type, ret = -1;
1668 
1669     /* Perform this test with two message types. At first use a message
1670      * consisting of only 0x00 for the client and only 0xFF for the server.
1671      * At the second time use message with generated data */
1672     for (msg_type = 0; msg_type < 2; msg_type++) {
1673         int written_1 = 0;
1674         int written_2 = 0;
1675         int read_1 = 0;
1676         int read_2 = 0;
1677         int fragments_1 = 0;
1678         int fragments_2 = 0;
1679 
1680         if (msg_type == 0) {
1681             memset(msg_buf_1, 0x00, msg_len_1);
1682             memset(msg_buf_2, 0xff, msg_len_2);
1683         } else {
1684             int i, j = 0;
1685             for (i = 0; i < msg_len_1; i++) {
1686                 msg_buf_1[i] = j++ & 0xFF;
1687             }
1688             for (i = 0; i < msg_len_2; i++) {
1689                 msg_buf_2[i] = (j -= 5) & 0xFF;
1690             }
1691         }
1692 
1693         while (read_1 < msg_len_2 || read_2 < msg_len_1) {
1694             /* ssl_1 sending */
1695             if (msg_len_1 > written_1) {
1696                 ret = mbedtls_ssl_write_fragment(ssl_1, msg_buf_1,
1697                                                  msg_len_1, &written_1,
1698                                                  expected_fragments_1);
1699                 if (expected_fragments_1 == 0) {
1700                     /* This error is expected when the message is too large and
1701                      * cannot be fragmented */
1702                     TEST_ASSERT(ret == MBEDTLS_ERR_SSL_BAD_INPUT_DATA);
1703                     msg_len_1 = 0;
1704                 } else {
1705                     TEST_ASSERT(ret == 0);
1706                 }
1707             }
1708 
1709             /* ssl_2 sending */
1710             if (msg_len_2 > written_2) {
1711                 ret = mbedtls_ssl_write_fragment(ssl_2, msg_buf_2,
1712                                                  msg_len_2, &written_2,
1713                                                  expected_fragments_2);
1714                 if (expected_fragments_2 == 0) {
1715                     /* This error is expected when the message is too large and
1716                      * cannot be fragmented */
1717                     TEST_ASSERT(ret == MBEDTLS_ERR_SSL_BAD_INPUT_DATA);
1718                     msg_len_2 = 0;
1719                 } else {
1720                     TEST_ASSERT(ret == 0);
1721                 }
1722             }
1723 
1724             /* ssl_1 reading */
1725             if (read_1 < msg_len_2) {
1726                 ret = mbedtls_ssl_read_fragment(ssl_1, in_buf_1,
1727                                                 msg_len_2, &read_1,
1728                                                 &fragments_2,
1729                                                 expected_fragments_2);
1730                 TEST_ASSERT(ret == 0);
1731             }
1732 
1733             /* ssl_2 reading */
1734             if (read_2 < msg_len_1) {
1735                 ret = mbedtls_ssl_read_fragment(ssl_2, in_buf_2,
1736                                                 msg_len_1, &read_2,
1737                                                 &fragments_1,
1738                                                 expected_fragments_1);
1739                 TEST_ASSERT(ret == 0);
1740             }
1741         }
1742 
1743         ret = -1;
1744         TEST_ASSERT(0 == memcmp(msg_buf_1, in_buf_2, msg_len_1));
1745         TEST_ASSERT(0 == memcmp(msg_buf_2, in_buf_1, msg_len_2));
1746         TEST_ASSERT(fragments_1 == expected_fragments_1);
1747         TEST_ASSERT(fragments_2 == expected_fragments_2);
1748     }
1749 
1750     ret = 0;
1751 
1752 exit:
1753     free(msg_buf_1);
1754     free(in_buf_1);
1755     free(msg_buf_2);
1756     free(in_buf_2);
1757 
1758     return ret;
1759 }
1760 
1761 /*
1762  * Perform data exchanging between \p ssl_1 and \p ssl_2. Both of endpoints
1763  * must be initialized and connected beforehand.
1764  *
1765  * \retval  0 on success, otherwise error code.
1766  */
1767 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED) && \
1768     (defined(MBEDTLS_SSL_RENEGOTIATION)              || \
1769     defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH))
exchange_data(mbedtls_ssl_context * ssl_1,mbedtls_ssl_context * ssl_2)1770 static int exchange_data(mbedtls_ssl_context *ssl_1,
1771                          mbedtls_ssl_context *ssl_2)
1772 {
1773     return mbedtls_test_ssl_exchange_data(ssl_1, 256, 1,
1774                                           ssl_2, 256, 1);
1775 }
1776 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED &&
1777           (MBEDTLS_SSL_RENEGOTIATION              ||
1778           MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) */
1779 
1780 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
check_ssl_version(mbedtls_ssl_protocol_version expected_negotiated_version,const mbedtls_ssl_context * ssl)1781 static int check_ssl_version(
1782     mbedtls_ssl_protocol_version expected_negotiated_version,
1783     const mbedtls_ssl_context *ssl)
1784 {
1785     const char *version_string = mbedtls_ssl_get_version(ssl);
1786     mbedtls_ssl_protocol_version version_number =
1787         mbedtls_ssl_get_version_number(ssl);
1788 
1789     TEST_EQUAL(ssl->tls_version, expected_negotiated_version);
1790 
1791     if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
1792         TEST_EQUAL(version_string[0], 'D');
1793         ++version_string;
1794     }
1795 
1796     switch (expected_negotiated_version) {
1797         case MBEDTLS_SSL_VERSION_TLS1_2:
1798             TEST_EQUAL(version_number, MBEDTLS_SSL_VERSION_TLS1_2);
1799             TEST_ASSERT(strcmp(version_string, "TLSv1.2") == 0);
1800             break;
1801 
1802         case MBEDTLS_SSL_VERSION_TLS1_3:
1803             TEST_EQUAL(version_number, MBEDTLS_SSL_VERSION_TLS1_3);
1804             TEST_ASSERT(strcmp(version_string, "TLSv1.3") == 0);
1805             break;
1806 
1807         default:
1808             TEST_FAIL(
1809                 "Version check not implemented for this protocol version");
1810     }
1811 
1812     return 1;
1813 
1814 exit:
1815     return 0;
1816 }
1817 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
1818 
1819 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
mbedtls_test_ssl_perform_handshake(mbedtls_test_handshake_test_options * options)1820 void mbedtls_test_ssl_perform_handshake(
1821     mbedtls_test_handshake_test_options *options)
1822 {
1823     /* forced_ciphersuite needs to last until the end of the handshake */
1824     int forced_ciphersuite[2];
1825     enum { BUFFSIZE = 17000 };
1826     mbedtls_test_ssl_endpoint client, server;
1827 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED)
1828     const char *psk_identity = "foo";
1829 #endif
1830 #if defined(MBEDTLS_TIMING_C)
1831     mbedtls_timing_delay_context timer_client, timer_server;
1832 #endif
1833 #if defined(MBEDTLS_SSL_CONTEXT_SERIALIZATION)
1834     unsigned char *context_buf = NULL;
1835     size_t context_buf_len;
1836 #endif
1837 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1838     int ret = -1;
1839 #endif
1840     int expected_handshake_result = options->expected_handshake_result;
1841 
1842     MD_OR_USE_PSA_INIT();
1843     mbedtls_platform_zeroize(&client, sizeof(client));
1844     mbedtls_platform_zeroize(&server, sizeof(server));
1845     mbedtls_test_ssl_message_queue server_queue, client_queue;
1846     mbedtls_test_message_socket_context server_context, client_context;
1847     mbedtls_test_message_socket_init(&server_context);
1848     mbedtls_test_message_socket_init(&client_context);
1849 
1850     /* Client side */
1851     if (options->dtls != 0) {
1852         TEST_ASSERT(mbedtls_test_ssl_endpoint_init(&client,
1853                                                    MBEDTLS_SSL_IS_CLIENT,
1854                                                    options, &client_context,
1855                                                    &client_queue,
1856                                                    &server_queue, NULL) == 0);
1857 #if defined(MBEDTLS_TIMING_C)
1858         mbedtls_ssl_set_timer_cb(&client.ssl, &timer_client,
1859                                  mbedtls_timing_set_delay,
1860                                  mbedtls_timing_get_delay);
1861 #endif
1862     } else {
1863         TEST_ASSERT(mbedtls_test_ssl_endpoint_init(&client,
1864                                                    MBEDTLS_SSL_IS_CLIENT,
1865                                                    options, NULL, NULL,
1866                                                    NULL, NULL) == 0);
1867     }
1868 
1869     if (strlen(options->cipher) > 0) {
1870         set_ciphersuite(&client.conf, options->cipher, forced_ciphersuite);
1871     }
1872 
1873 #if defined(MBEDTLS_DEBUG_C)
1874     if (options->cli_log_fun) {
1875         mbedtls_debug_set_threshold(4);
1876         mbedtls_ssl_conf_dbg(&client.conf, options->cli_log_fun,
1877                              options->cli_log_obj);
1878     }
1879 #endif
1880 
1881     /* Server side */
1882     if (options->dtls != 0) {
1883         TEST_ASSERT(mbedtls_test_ssl_endpoint_init(&server,
1884                                                    MBEDTLS_SSL_IS_SERVER,
1885                                                    options, &server_context,
1886                                                    &server_queue,
1887                                                    &client_queue, NULL) == 0);
1888 #if defined(MBEDTLS_TIMING_C)
1889         mbedtls_ssl_set_timer_cb(&server.ssl, &timer_server,
1890                                  mbedtls_timing_set_delay,
1891                                  mbedtls_timing_get_delay);
1892 #endif
1893     } else {
1894         TEST_ASSERT(mbedtls_test_ssl_endpoint_init(&server,
1895                                                    MBEDTLS_SSL_IS_SERVER,
1896                                                    options, NULL, NULL, NULL,
1897                                                    NULL) == 0);
1898     }
1899 
1900     mbedtls_ssl_conf_authmode(&server.conf, options->srv_auth_mode);
1901 
1902 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
1903     TEST_ASSERT(mbedtls_ssl_conf_max_frag_len(&(server.conf),
1904                                               (unsigned char) options->mfl)
1905                 == 0);
1906     TEST_ASSERT(mbedtls_ssl_conf_max_frag_len(&(client.conf),
1907                                               (unsigned char) options->mfl)
1908                 == 0);
1909 #else
1910     TEST_ASSERT(MBEDTLS_SSL_MAX_FRAG_LEN_NONE == options->mfl);
1911 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
1912 
1913 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED)
1914     if (options->psk_str != NULL && options->psk_str->len > 0) {
1915         TEST_ASSERT(mbedtls_ssl_conf_psk(
1916                         &client.conf, options->psk_str->x,
1917                         options->psk_str->len,
1918                         (const unsigned char *) psk_identity,
1919                         strlen(psk_identity)) == 0);
1920 
1921         TEST_ASSERT(mbedtls_ssl_conf_psk(
1922                         &server.conf, options->psk_str->x,
1923                         options->psk_str->len,
1924                         (const unsigned char *) psk_identity,
1925                         strlen(psk_identity)) == 0);
1926 #if defined(MBEDTLS_SSL_SRV_C)
1927         mbedtls_ssl_conf_psk_cb(&server.conf, psk_dummy_callback, NULL);
1928 #endif
1929     }
1930 #endif
1931 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1932     if (options->renegotiate) {
1933         mbedtls_ssl_conf_renegotiation(&(server.conf),
1934                                        MBEDTLS_SSL_RENEGOTIATION_ENABLED);
1935         mbedtls_ssl_conf_renegotiation(&(client.conf),
1936                                        MBEDTLS_SSL_RENEGOTIATION_ENABLED);
1937 
1938         mbedtls_ssl_conf_legacy_renegotiation(&(server.conf),
1939                                               options->legacy_renegotiation);
1940         mbedtls_ssl_conf_legacy_renegotiation(&(client.conf),
1941                                               options->legacy_renegotiation);
1942     }
1943 #endif /* MBEDTLS_SSL_RENEGOTIATION */
1944 
1945 #if defined(MBEDTLS_DEBUG_C)
1946     if (options->srv_log_fun) {
1947         mbedtls_debug_set_threshold(4);
1948         mbedtls_ssl_conf_dbg(&server.conf, options->srv_log_fun,
1949                              options->srv_log_obj);
1950     }
1951 #endif
1952 
1953     TEST_ASSERT(mbedtls_test_mock_socket_connect(&(client.socket),
1954                                                  &(server.socket),
1955                                                  BUFFSIZE) == 0);
1956 
1957 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
1958     if (options->resize_buffers != 0) {
1959         /* Ensure that the buffer sizes are appropriate before resizes */
1960         TEST_ASSERT(client.ssl.out_buf_len == MBEDTLS_SSL_OUT_BUFFER_LEN);
1961         TEST_ASSERT(client.ssl.in_buf_len == MBEDTLS_SSL_IN_BUFFER_LEN);
1962         TEST_ASSERT(server.ssl.out_buf_len == MBEDTLS_SSL_OUT_BUFFER_LEN);
1963         TEST_ASSERT(server.ssl.in_buf_len == MBEDTLS_SSL_IN_BUFFER_LEN);
1964     }
1965 #endif
1966 
1967     if (options->expected_negotiated_version == MBEDTLS_SSL_VERSION_UNKNOWN) {
1968         expected_handshake_result = MBEDTLS_ERR_SSL_BAD_PROTOCOL_VERSION;
1969     }
1970 
1971     TEST_ASSERT(mbedtls_test_move_handshake_to_state(&(client.ssl),
1972                                                      &(server.ssl),
1973                                                      MBEDTLS_SSL_HANDSHAKE_OVER)
1974                 ==  expected_handshake_result);
1975 
1976     if (expected_handshake_result != 0) {
1977         /* Connection will have failed by this point, skip to cleanup */
1978         goto exit;
1979     }
1980 
1981     TEST_ASSERT(mbedtls_ssl_is_handshake_over(&client.ssl) == 1);
1982 
1983     /* Make sure server state is moved to HANDSHAKE_OVER also. */
1984     TEST_EQUAL(mbedtls_test_move_handshake_to_state(&(server.ssl),
1985                                                     &(client.ssl),
1986                                                     MBEDTLS_SSL_HANDSHAKE_OVER),
1987                0);
1988 
1989     TEST_ASSERT(mbedtls_ssl_is_handshake_over(&server.ssl) == 1);
1990     /* Check that both sides have negotiated the expected version. */
1991     mbedtls_test_set_step(0);
1992     if (!check_ssl_version(options->expected_negotiated_version,
1993                            &client.ssl)) {
1994         goto exit;
1995     }
1996 
1997     mbedtls_test_set_step(1);
1998     if (!check_ssl_version(options->expected_negotiated_version,
1999                            &server.ssl)) {
2000         goto exit;
2001     }
2002 
2003     if (options->expected_ciphersuite != 0) {
2004         TEST_EQUAL(server.ssl.session->ciphersuite,
2005                    options->expected_ciphersuite);
2006     }
2007 
2008 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
2009     if (options->resize_buffers != 0) {
2010         /* A server, when using DTLS, might delay a buffer resize to happen
2011          * after it receives a message, so we force it. */
2012         TEST_ASSERT(exchange_data(&(client.ssl), &(server.ssl)) == 0);
2013 
2014         TEST_ASSERT(client.ssl.out_buf_len ==
2015                     mbedtls_ssl_get_output_buflen(&client.ssl));
2016         TEST_ASSERT(client.ssl.in_buf_len ==
2017                     mbedtls_ssl_get_input_buflen(&client.ssl));
2018         TEST_ASSERT(server.ssl.out_buf_len ==
2019                     mbedtls_ssl_get_output_buflen(&server.ssl));
2020         TEST_ASSERT(server.ssl.in_buf_len ==
2021                     mbedtls_ssl_get_input_buflen(&server.ssl));
2022     }
2023 #endif
2024 
2025     if (options->cli_msg_len != 0 || options->srv_msg_len != 0) {
2026         /* Start data exchanging test */
2027         TEST_ASSERT(mbedtls_test_ssl_exchange_data(
2028                         &(client.ssl), options->cli_msg_len,
2029                         options->expected_cli_fragments,
2030                         &(server.ssl), options->srv_msg_len,
2031                         options->expected_srv_fragments)
2032                     == 0);
2033     }
2034 #if defined(MBEDTLS_SSL_CONTEXT_SERIALIZATION)
2035     if (options->serialize == 1) {
2036         TEST_ASSERT(options->dtls == 1);
2037 
2038         TEST_ASSERT(mbedtls_ssl_context_save(&(server.ssl), NULL,
2039                                              0, &context_buf_len)
2040                     == MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL);
2041 
2042         context_buf = mbedtls_calloc(1, context_buf_len);
2043         TEST_ASSERT(context_buf != NULL);
2044 
2045         TEST_ASSERT(mbedtls_ssl_context_save(&(server.ssl), context_buf,
2046                                              context_buf_len,
2047                                              &context_buf_len)
2048                     == 0);
2049 
2050         mbedtls_ssl_free(&(server.ssl));
2051         mbedtls_ssl_init(&(server.ssl));
2052 
2053         TEST_ASSERT(mbedtls_ssl_setup(&(server.ssl), &(server.conf)) == 0);
2054 
2055         mbedtls_ssl_set_bio(&(server.ssl), &server_context,
2056                             mbedtls_test_mock_tcp_send_msg,
2057                             mbedtls_test_mock_tcp_recv_msg,
2058                             NULL);
2059 
2060         mbedtls_ssl_set_user_data_p(&server.ssl, &server);
2061 
2062 #if defined(MBEDTLS_TIMING_C)
2063         mbedtls_ssl_set_timer_cb(&server.ssl, &timer_server,
2064                                  mbedtls_timing_set_delay,
2065                                  mbedtls_timing_get_delay);
2066 #endif
2067 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
2068         if (options->resize_buffers != 0) {
2069             /* Ensure that the buffer sizes are appropriate before resizes */
2070             TEST_ASSERT(server.ssl.out_buf_len == MBEDTLS_SSL_OUT_BUFFER_LEN);
2071             TEST_ASSERT(server.ssl.in_buf_len == MBEDTLS_SSL_IN_BUFFER_LEN);
2072         }
2073 #endif
2074         TEST_ASSERT(mbedtls_ssl_context_load(&(server.ssl), context_buf,
2075                                              context_buf_len) == 0);
2076 
2077 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
2078         /* Validate buffer sizes after context deserialization */
2079         if (options->resize_buffers != 0) {
2080             TEST_ASSERT(server.ssl.out_buf_len ==
2081                         mbedtls_ssl_get_output_buflen(&server.ssl));
2082             TEST_ASSERT(server.ssl.in_buf_len ==
2083                         mbedtls_ssl_get_input_buflen(&server.ssl));
2084         }
2085 #endif
2086         /* Retest writing/reading */
2087         if (options->cli_msg_len != 0 || options->srv_msg_len != 0) {
2088             TEST_ASSERT(mbedtls_test_ssl_exchange_data(
2089                             &(client.ssl), options->cli_msg_len,
2090                             options->expected_cli_fragments,
2091                             &(server.ssl), options->srv_msg_len,
2092                             options->expected_srv_fragments)
2093                         == 0);
2094         }
2095     }
2096 #endif /* MBEDTLS_SSL_CONTEXT_SERIALIZATION */
2097 
2098 #if defined(MBEDTLS_SSL_RENEGOTIATION)
2099     if (options->renegotiate) {
2100         /* Start test with renegotiation */
2101         TEST_ASSERT(server.ssl.renego_status ==
2102                     MBEDTLS_SSL_INITIAL_HANDSHAKE);
2103         TEST_ASSERT(client.ssl.renego_status ==
2104                     MBEDTLS_SSL_INITIAL_HANDSHAKE);
2105 
2106         /* After calling this function for the server, it only sends a handshake
2107          * request. All renegotiation should happen during data exchanging */
2108         TEST_ASSERT(mbedtls_ssl_renegotiate(&(server.ssl)) == 0);
2109         TEST_ASSERT(server.ssl.renego_status ==
2110                     MBEDTLS_SSL_RENEGOTIATION_PENDING);
2111         TEST_ASSERT(client.ssl.renego_status ==
2112                     MBEDTLS_SSL_INITIAL_HANDSHAKE);
2113 
2114         TEST_ASSERT(exchange_data(&(client.ssl), &(server.ssl)) == 0);
2115         TEST_ASSERT(server.ssl.renego_status ==
2116                     MBEDTLS_SSL_RENEGOTIATION_DONE);
2117         TEST_ASSERT(client.ssl.renego_status ==
2118                     MBEDTLS_SSL_RENEGOTIATION_DONE);
2119 
2120         /* After calling mbedtls_ssl_renegotiate for the client,
2121          * all renegotiation should happen inside this function.
2122          * However in this test, we cannot perform simultaneous communication
2123          * between client and server so this function will return waiting error
2124          * on the socket. All rest of renegotiation should happen
2125          * during data exchanging */
2126         ret = mbedtls_ssl_renegotiate(&(client.ssl));
2127 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
2128         if (options->resize_buffers != 0) {
2129             /* Ensure that the buffer sizes are appropriate before resizes */
2130             TEST_ASSERT(client.ssl.out_buf_len == MBEDTLS_SSL_OUT_BUFFER_LEN);
2131             TEST_ASSERT(client.ssl.in_buf_len == MBEDTLS_SSL_IN_BUFFER_LEN);
2132         }
2133 #endif
2134         TEST_ASSERT(ret == 0 ||
2135                     ret == MBEDTLS_ERR_SSL_WANT_READ ||
2136                     ret == MBEDTLS_ERR_SSL_WANT_WRITE);
2137         TEST_ASSERT(server.ssl.renego_status ==
2138                     MBEDTLS_SSL_RENEGOTIATION_DONE);
2139         TEST_ASSERT(client.ssl.renego_status ==
2140                     MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS);
2141 
2142         TEST_ASSERT(exchange_data(&(client.ssl), &(server.ssl)) == 0);
2143         TEST_ASSERT(server.ssl.renego_status ==
2144                     MBEDTLS_SSL_RENEGOTIATION_DONE);
2145         TEST_ASSERT(client.ssl.renego_status ==
2146                     MBEDTLS_SSL_RENEGOTIATION_DONE);
2147 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
2148         /* Validate buffer sizes after renegotiation */
2149         if (options->resize_buffers != 0) {
2150             TEST_ASSERT(client.ssl.out_buf_len ==
2151                         mbedtls_ssl_get_output_buflen(&client.ssl));
2152             TEST_ASSERT(client.ssl.in_buf_len ==
2153                         mbedtls_ssl_get_input_buflen(&client.ssl));
2154             TEST_ASSERT(server.ssl.out_buf_len ==
2155                         mbedtls_ssl_get_output_buflen(&server.ssl));
2156             TEST_ASSERT(server.ssl.in_buf_len ==
2157                         mbedtls_ssl_get_input_buflen(&server.ssl));
2158         }
2159 #endif /* MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH */
2160     }
2161 #endif /* MBEDTLS_SSL_RENEGOTIATION */
2162 
2163     TEST_ASSERT(mbedtls_ssl_conf_get_user_data_p(&client.conf) == &client);
2164     TEST_ASSERT(mbedtls_ssl_get_user_data_p(&client.ssl) == &client);
2165     TEST_ASSERT(mbedtls_ssl_conf_get_user_data_p(&server.conf) == &server);
2166     TEST_ASSERT(mbedtls_ssl_get_user_data_p(&server.ssl) == &server);
2167 
2168 exit:
2169     mbedtls_test_ssl_endpoint_free(&client,
2170                                    options->dtls != 0 ? &client_context : NULL);
2171     mbedtls_test_ssl_endpoint_free(&server,
2172                                    options->dtls != 0 ? &server_context : NULL);
2173 #if defined(MBEDTLS_DEBUG_C)
2174     if (options->cli_log_fun || options->srv_log_fun) {
2175         mbedtls_debug_set_threshold(0);
2176     }
2177 #endif
2178 #if defined(MBEDTLS_SSL_CONTEXT_SERIALIZATION)
2179     if (context_buf != NULL) {
2180         mbedtls_free(context_buf);
2181     }
2182 #endif
2183     MD_OR_USE_PSA_DONE();
2184 }
2185 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
2186 
2187 #if defined(MBEDTLS_TEST_HOOKS)
mbedtls_test_tweak_tls13_certificate_msg_vector_len(unsigned char * buf,unsigned char ** end,int tweak,int * expected_result,mbedtls_ssl_chk_buf_ptr_args * args)2188 int mbedtls_test_tweak_tls13_certificate_msg_vector_len(
2189     unsigned char *buf, unsigned char **end, int tweak,
2190     int *expected_result, mbedtls_ssl_chk_buf_ptr_args *args)
2191 {
2192 /*
2193  * The definition of the tweaks assume that the certificate list contains only
2194  * one certificate.
2195  */
2196 
2197 /*
2198  * struct {
2199  *     opaque cert_data<1..2^24-1>;
2200  *     Extension extensions<0..2^16-1>;
2201  * } CertificateEntry;
2202  *
2203  * struct {
2204  *     opaque certificate_request_context<0..2^8-1>;
2205  *     CertificateEntry certificate_list<0..2^24-1>;
2206  * } Certificate;
2207  */
2208     unsigned char *p_certificate_request_context_len = buf;
2209     size_t certificate_request_context_len = buf[0];
2210 
2211     unsigned char *p_certificate_list_len =
2212         buf + 1 + certificate_request_context_len;
2213     unsigned char *certificate_list = p_certificate_list_len + 3;
2214     size_t certificate_list_len =
2215         MBEDTLS_GET_UINT24_BE(p_certificate_list_len, 0);
2216 
2217     unsigned char *p_cert_data_len = certificate_list;
2218     unsigned char *cert_data = p_cert_data_len + 3;
2219     size_t cert_data_len = MBEDTLS_GET_UINT24_BE(p_cert_data_len, 0);
2220 
2221     unsigned char *p_extensions_len = cert_data + cert_data_len;
2222     unsigned char *extensions = p_extensions_len + 2;
2223     size_t extensions_len = MBEDTLS_GET_UINT16_BE(p_extensions_len, 0);
2224 
2225     *expected_result = MBEDTLS_ERR_SSL_DECODE_ERROR;
2226 
2227     switch (tweak) {
2228         case 1:
2229             /* Failure when checking if the certificate request context length
2230              * and certificate list length can be read
2231              */
2232             *end = buf + 3;
2233             set_chk_buf_ptr_args(args, buf, *end, 4);
2234             break;
2235 
2236         case 2:
2237             /* Invalid certificate request context length.
2238              */
2239             *p_certificate_request_context_len =
2240                 (unsigned char) certificate_request_context_len + 1;
2241             reset_chk_buf_ptr_args(args);
2242             break;
2243 
2244         case 3:
2245             /* Failure when checking if certificate_list data can be read. */
2246             MBEDTLS_PUT_UINT24_BE(certificate_list_len + 1,
2247                                   p_certificate_list_len, 0);
2248             set_chk_buf_ptr_args(args, certificate_list, *end,
2249                                  certificate_list_len + 1);
2250             break;
2251 
2252         case 4:
2253             /* Failure when checking if the cert_data length can be read. */
2254             MBEDTLS_PUT_UINT24_BE(2, p_certificate_list_len, 0);
2255             set_chk_buf_ptr_args(args, p_cert_data_len, certificate_list + 2, 3);
2256             break;
2257 
2258         case 5:
2259             /* Failure when checking if cert_data data can be read. */
2260             MBEDTLS_PUT_UINT24_BE(certificate_list_len - 3 + 1,
2261                                   p_cert_data_len, 0);
2262             set_chk_buf_ptr_args(args, cert_data,
2263                                  certificate_list + certificate_list_len,
2264                                  certificate_list_len - 3 + 1);
2265             break;
2266 
2267         case 6:
2268             /* Failure when checking if the extensions length can be read. */
2269             MBEDTLS_PUT_UINT24_BE(certificate_list_len - extensions_len - 1,
2270                                   p_certificate_list_len, 0);
2271             set_chk_buf_ptr_args(
2272                 args, p_extensions_len,
2273                 certificate_list + certificate_list_len - extensions_len - 1, 2);
2274             break;
2275 
2276         case 7:
2277             /* Failure when checking if extensions data can be read. */
2278             MBEDTLS_PUT_UINT16_BE(extensions_len + 1, p_extensions_len, 0);
2279 
2280             set_chk_buf_ptr_args(
2281                 args, extensions,
2282                 certificate_list + certificate_list_len, extensions_len + 1);
2283             break;
2284 
2285         default:
2286             return -1;
2287     }
2288 
2289     return 0;
2290 }
2291 #endif /* MBEDTLS_TEST_HOOKS */
2292 #endif /* MBEDTLS_SSL_TLS_C */
2293